viborm 1.1.0 → 1.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (293) hide show
  1. package/dist/{adapter-namespace-DMhEF6my.mjs → adapter-namespace-DqkJQdrD.mjs} +2 -2
  2. package/dist/{adapter-namespace-DMhEF6my.mjs.map → adapter-namespace-DqkJQdrD.mjs.map} +1 -1
  3. package/dist/adapters.d.mts +1 -1
  4. package/dist/adapters.mjs +1 -1
  5. package/dist/{array-literal-DcEm5tt_.mjs → array-literal-BsbbSLw3.mjs} +1 -1
  6. package/dist/{array-literal-DcEm5tt_.mjs.map → array-literal-BsbbSLw3.mjs.map} +1 -1
  7. package/dist/base-AdXAoy6l.mjs +2 -0
  8. package/dist/base-AdXAoy6l.mjs.map +1 -0
  9. package/dist/batch-refs-4L8ECdPU.mjs +2 -0
  10. package/dist/batch-refs-4L8ECdPU.mjs.map +1 -0
  11. package/dist/bind-parameter-capacity-CjPgqnmx.mjs +2 -0
  12. package/dist/{bind-parameter-capacity-DzMcIB95.mjs.map → bind-parameter-capacity-CjPgqnmx.mjs.map} +1 -1
  13. package/dist/builder-Ycvq3ETg.mjs +2 -0
  14. package/dist/builder-Ycvq3ETg.mjs.map +1 -0
  15. package/dist/bun-sql.d.mts +19 -2
  16. package/dist/bun-sql.mjs +1 -1
  17. package/dist/bun-sql.mjs.map +1 -1
  18. package/dist/bun-sqlite.d.mts +9 -8
  19. package/dist/bun-sqlite.mjs +1 -1
  20. package/dist/bun-sqlite.mjs.map +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/memory.mjs.map +1 -1
  26. package/dist/cache-BO57X0TT.mjs +2 -0
  27. package/dist/cache-BO57X0TT.mjs.map +1 -0
  28. package/dist/cache.d.mts +1 -1
  29. package/dist/cache.mjs +1 -1
  30. package/dist/cache.mjs.map +1 -1
  31. package/dist/canonical-json-rfC2Dg0X.mjs +2 -0
  32. package/dist/canonical-json-rfC2Dg0X.mjs.map +1 -0
  33. package/dist/chain-Dh0FV72b.mjs +2 -0
  34. package/dist/chain-Dh0FV72b.mjs.map +1 -0
  35. package/dist/cli.mjs +5 -6
  36. package/dist/cli.mjs.map +1 -1
  37. package/dist/client-BLiBmykn.mjs +2 -0
  38. package/dist/client-BLiBmykn.mjs.map +1 -0
  39. package/dist/client-CCgfcp5A.mjs +52 -0
  40. package/dist/client-CCgfcp5A.mjs.map +1 -0
  41. package/dist/client-XQSEkF90.d.mts +610 -0
  42. package/dist/client.d.mts +1 -1
  43. package/dist/client.mjs +1 -1
  44. package/dist/{clock-W8H2Khng.mjs → clock-CK41KO7t.mjs} +1 -1
  45. package/dist/{clock-W8H2Khng.mjs.map → clock-CK41KO7t.mjs.map} +1 -1
  46. package/dist/config.d.mts +3 -3
  47. package/dist/config.mjs +1 -1
  48. package/dist/controls-DXgIn4zh.mjs +2 -0
  49. package/dist/controls-DXgIn4zh.mjs.map +1 -0
  50. package/dist/d1.d.mts +1 -1
  51. package/dist/d1.mjs +1 -1
  52. package/dist/d1.mjs.map +1 -1
  53. package/dist/datetime-physical-codec-oIhiYZEP.mjs +2 -0
  54. package/dist/{datetime-physical-codec-BK93pJGW.mjs.map → datetime-physical-codec-oIhiYZEP.mjs.map} +1 -1
  55. package/dist/driver-B19QlFqn.mjs +2 -0
  56. package/dist/{driver-ZIbkciaz.mjs.map → driver-B19QlFqn.mjs.map} +1 -1
  57. package/dist/driver-BlnKXPFF.mjs +2 -0
  58. package/dist/driver-BlnKXPFF.mjs.map +1 -0
  59. package/dist/driver.d.mts +2 -2
  60. package/dist/driver.mjs +1 -1
  61. package/dist/error-mapping-CnPCv1dm.mjs +2 -0
  62. package/dist/error-mapping-CnPCv1dm.mjs.map +1 -0
  63. package/dist/every-4KE0p2Gw.mjs +2 -0
  64. package/dist/every-4KE0p2Gw.mjs.map +1 -0
  65. package/dist/{execution-context-Bm_qTp1i.mjs → execution-context-BKR3bgES.mjs} +1 -1
  66. package/dist/{execution-context-Bm_qTp1i.mjs.map → execution-context-BKR3bgES.mjs.map} +1 -1
  67. package/dist/fs-estate-CAhDg7nY.mjs +2 -0
  68. package/dist/fs-estate-CAhDg7nY.mjs.map +1 -0
  69. package/dist/{geo-area-codec-B4DRInvA.mjs → geo-area-codec-1SY9im7O.mjs} +2 -2
  70. package/dist/{geo-area-codec-B4DRInvA.mjs.map → geo-area-codec-1SY9im7O.mjs.map} +1 -1
  71. package/dist/geo-point-codec-lhxH42SK.mjs +2 -0
  72. package/dist/geo-point-codec-lhxH42SK.mjs.map +1 -0
  73. package/dist/{hydration-D6JICBQG.mjs → hydration-CAxOL4aI.mjs} +2 -2
  74. package/dist/{hydration-D6JICBQG.mjs.map → hydration-CAxOL4aI.mjs.map} +1 -1
  75. package/dist/identifier-conversion-GgbwHc2G.mjs +2 -0
  76. package/dist/identifier-conversion-GgbwHc2G.mjs.map +1 -0
  77. package/dist/{identifier-EsWKVHXi.mjs → identifier-hQCs8M1n.mjs} +2 -2
  78. package/dist/{identifier-EsWKVHXi.mjs.map → identifier-hQCs8M1n.mjs.map} +1 -1
  79. package/dist/identity-CLFhCTZx.mjs +2 -0
  80. package/dist/identity-CLFhCTZx.mjs.map +1 -0
  81. package/dist/{index-BbcE-gyl.d.mts → index-Likdf5qP.d.mts} +638 -351
  82. package/dist/index.d.mts +2 -2
  83. package/dist/index.mjs +1 -1
  84. package/dist/index.mjs.map +1 -1
  85. package/dist/instrumentation.d.mts +1 -1
  86. package/dist/instrumentation.mjs +1 -1
  87. package/dist/instrumentation.mjs.map +1 -1
  88. package/dist/{invariant-DCsftyml.mjs → invariant-BnLYqsHO.mjs} +1 -1
  89. package/dist/{invariant-DCsftyml.mjs.map → invariant-BnLYqsHO.mjs.map} +1 -1
  90. package/dist/{json-number-TpD-pfqt.mjs → json-number-CGXpPu4D.mjs} +1 -1
  91. package/dist/{json-number-TpD-pfqt.mjs.map → json-number-CGXpPu4D.mjs.map} +1 -1
  92. package/dist/key-BeoOwGr3.mjs +2 -0
  93. package/dist/key-BeoOwGr3.mjs.map +1 -0
  94. package/dist/libsql-Bu_IdFU1.mjs +11 -0
  95. package/dist/libsql-Bu_IdFU1.mjs.map +1 -0
  96. package/dist/libsql.d.mts +1 -1
  97. package/dist/libsql.mjs +1 -1
  98. package/dist/libsql.mjs.map +1 -1
  99. package/dist/memory-D4yxtCPK.mjs +2 -0
  100. package/dist/memory-D4yxtCPK.mjs.map +1 -0
  101. package/dist/migrations/mysql.d.mts +6 -0
  102. package/dist/migrations/mysql.mjs +2 -0
  103. package/dist/migrations/mysql.mjs.map +1 -0
  104. package/dist/migrations/postgres.d.mts +6 -0
  105. package/dist/migrations/postgres.mjs +2 -0
  106. package/dist/migrations/postgres.mjs.map +1 -0
  107. package/dist/migrations/sqlite.d.mts +6 -0
  108. package/dist/migrations/sqlite.mjs +2 -0
  109. package/dist/migrations/sqlite.mjs.map +1 -0
  110. package/dist/migrations/storage/durable-object.d.mts +17 -0
  111. package/dist/migrations/storage/durable-object.mjs +2 -0
  112. package/dist/migrations/storage/durable-object.mjs.map +1 -0
  113. package/dist/migrations/storage/fs.d.mts +6 -1
  114. package/dist/migrations/storage/fs.mjs +1 -1
  115. package/dist/migrations/storage/r2.d.mts +14 -0
  116. package/dist/migrations/storage/r2.mjs +2 -0
  117. package/dist/migrations/storage/r2.mjs.map +1 -0
  118. package/dist/migrations/tenant.d.mts +92 -0
  119. package/dist/migrations/tenant.mjs +2 -0
  120. package/dist/migrations/tenant.mjs.map +1 -0
  121. package/dist/{migrations-BWZSBMZh.mjs → migrations-DTObIjAm.mjs} +2 -2
  122. package/dist/migrations-DTObIjAm.mjs.map +1 -0
  123. package/dist/migrations.d.mts +6 -561
  124. package/dist/migrations.mjs +1 -1
  125. package/dist/migrations.mjs.map +1 -1
  126. package/dist/mysql-CibPaHSp.mjs +99 -0
  127. package/dist/mysql-CibPaHSp.mjs.map +1 -0
  128. package/dist/mysql-adapter-DkJPfoGf.mjs +2 -0
  129. package/dist/mysql-adapter-DkJPfoGf.mjs.map +1 -0
  130. package/dist/mysql2.d.mts +1 -3
  131. package/dist/mysql2.mjs +1 -1
  132. package/dist/mysql2.mjs.map +1 -1
  133. package/dist/neon-http.d.mts +1 -1
  134. package/dist/neon-http.mjs +1 -1
  135. package/dist/neon-http.mjs.map +1 -1
  136. package/dist/object-store-CbjhsBQ3.d.mts +156 -0
  137. package/dist/object-store-DQR6bTBY.mjs +2 -0
  138. package/dist/object-store-DQR6bTBY.mjs.map +1 -0
  139. package/dist/observation-DUSm7oXK.mjs +2 -0
  140. package/dist/observation-DUSm7oXK.mjs.map +1 -0
  141. package/dist/pg.d.mts +37 -12
  142. package/dist/pg.mjs +1 -1
  143. package/dist/pg.mjs.map +1 -1
  144. package/dist/pglite.d.mts +2 -1
  145. package/dist/pglite.mjs +1 -1
  146. package/dist/pglite.mjs.map +1 -1
  147. package/dist/physical-6V_LNU3L.mjs +2 -0
  148. package/dist/{physical-BkelResN.mjs.map → physical-6V_LNU3L.mjs.map} +1 -1
  149. package/dist/pinned-session-CLxj5M5e.mjs +2 -0
  150. package/dist/pinned-session-CLxj5M5e.mjs.map +1 -0
  151. package/dist/planetscale.d.mts +1 -1
  152. package/dist/planetscale.mjs +1 -1
  153. package/dist/planetscale.mjs.map +1 -1
  154. package/dist/{planner-Bbw8W81b.d.mts → planner-CwFUkNHP.d.mts} +57 -3
  155. package/dist/postgres-adapter-B3SQvcV1.mjs +2 -0
  156. package/dist/postgres-adapter-B3SQvcV1.mjs.map +1 -0
  157. package/dist/postgres-adapter-CQD2oGuD.mjs +2 -0
  158. package/dist/postgres-adapter-CQD2oGuD.mjs.map +1 -0
  159. package/dist/postgres-oqNW9xqo.mjs +415 -0
  160. package/dist/postgres-oqNW9xqo.mjs.map +1 -0
  161. package/dist/{postgres-result-Dc_iW3Hb.mjs → postgres-result-7F0DllQe.mjs} +2 -2
  162. package/dist/{postgres-result-Dc_iW3Hb.mjs.map → postgres-result-7F0DllQe.mjs.map} +1 -1
  163. package/dist/postgres.d.mts +11 -1
  164. package/dist/postgres.mjs +1 -1
  165. package/dist/postgres.mjs.map +1 -1
  166. package/dist/{provider-limits-DXj_pOT0.mjs → provider-limits-BHATED_m.mjs} +2 -2
  167. package/dist/{provider-limits-DXj_pOT0.mjs.map → provider-limits-BHATED_m.mjs.map} +1 -1
  168. package/dist/registration-preflight-DEjv050M.mjs +4 -0
  169. package/dist/registration-preflight-DEjv050M.mjs.map +1 -0
  170. package/dist/result-shape-CTNdNSW3.mjs +2 -0
  171. package/dist/result-shape-CTNdNSW3.mjs.map +1 -0
  172. package/dist/scalar-U0wD5bKy.mjs +2 -0
  173. package/dist/{scalar-BTktMqvO.mjs.map → scalar-U0wD5bKy.mjs.map} +1 -1
  174. package/dist/schema/json.d.mts +1 -1
  175. package/dist/schema/json.mjs +1 -1
  176. package/dist/schema/json.mjs.map +1 -1
  177. package/dist/schema-Cjem1-0f.mjs +2 -0
  178. package/dist/{schema-BFNcMdO6.mjs.map → schema-Cjem1-0f.mjs.map} +1 -1
  179. package/dist/schema-introspection-DEYGC2qg.mjs +6 -0
  180. package/dist/schema-introspection-DEYGC2qg.mjs.map +1 -0
  181. package/dist/schema.d.mts +1 -1
  182. package/dist/schema.mjs +1 -1
  183. package/dist/{select-assembly-BgqlrePH.mjs → select-assembly-f1UGoblh.mjs} +2 -2
  184. package/dist/select-assembly-f1UGoblh.mjs.map +1 -0
  185. package/dist/settle-B9Vg1FnP.mjs +2 -0
  186. package/dist/settle-B9Vg1FnP.mjs.map +1 -0
  187. package/dist/soft-delete.d.mts +1 -1
  188. package/dist/{sql--69HUgel.mjs → sql-Bp7jicEX.mjs} +1 -1
  189. package/dist/{sql--69HUgel.mjs.map → sql-Bp7jicEX.mjs.map} +1 -1
  190. package/dist/{sql-statement-tokens-CykxFmOJ.mjs → sql-statement-tokens-BBcoGmJb.mjs} +1 -1
  191. package/dist/{sql-statement-tokens-CykxFmOJ.mjs.map → sql-statement-tokens-BBcoGmJb.mjs.map} +1 -1
  192. package/dist/sql.d.mts +1 -1
  193. package/dist/sql.mjs +1 -1
  194. package/dist/sqlite-adapter-CW_3l6ea.mjs +2 -0
  195. package/dist/sqlite-adapter-CW_3l6ea.mjs.map +1 -0
  196. package/dist/sqlite-utils-DlgokMJN.mjs +2 -0
  197. package/dist/sqlite-utils-DlgokMJN.mjs.map +1 -0
  198. package/dist/sqlite3.d.mts +2 -8
  199. package/dist/sqlite3.mjs +1 -1
  200. package/dist/sqlite3.mjs.map +1 -1
  201. package/dist/standard-sql-Bk4RZPqJ.mjs +6 -0
  202. package/dist/standard-sql-Bk4RZPqJ.mjs.map +1 -0
  203. package/dist/{suppressed-failure-BPxfHTMc.mjs → suppressed-failure-BwULh-8h.mjs} +1 -1
  204. package/dist/{suppressed-failure-BPxfHTMc.mjs.map → suppressed-failure-BwULh-8h.mjs.map} +1 -1
  205. package/dist/{terminal-BbRi0CNZ.mjs → terminal-C8cq1WWX.mjs} +2 -2
  206. package/dist/{terminal-BbRi0CNZ.mjs.map → terminal-C8cq1WWX.mjs.map} +1 -1
  207. package/dist/{transaction-oskVwmsf.mjs → transaction-Bnl6ULTw.mjs} +2 -2
  208. package/dist/transaction-Bnl6ULTw.mjs.map +1 -0
  209. package/dist/{transaction-operation-BC7aua5V.mjs → transaction-operation-CKK3l_9x.mjs} +2 -2
  210. package/dist/{transaction-operation-BC7aua5V.mjs.map → transaction-operation-CKK3l_9x.mjs.map} +1 -1
  211. package/dist/{utils-CRFUUfNn.mjs → utils-CZNaOZR7.mjs} +4 -3
  212. package/dist/utils-CZNaOZR7.mjs.map +1 -0
  213. package/dist/v-D5Z06FKN.mjs +2 -0
  214. package/dist/v-D5Z06FKN.mjs.map +1 -0
  215. package/dist/validation-Dk9Q_-C7.mjs +2 -0
  216. package/dist/validation-Dk9Q_-C7.mjs.map +1 -0
  217. package/dist/validation-PF9-_nKd.mjs +2 -0
  218. package/dist/{validation-tgjL_9n8.mjs.map → validation-PF9-_nKd.mjs.map} +1 -1
  219. package/dist/validation.d.mts +1 -1
  220. package/dist/validation.mjs +1 -1
  221. package/dist/validator-X9-bwtRo.mjs +2 -0
  222. package/dist/{validator-DMlEScV3.mjs.map → validator-X9-bwtRo.mjs.map} +1 -1
  223. package/dist/value-guards-CK9guf2Z.mjs +2 -0
  224. package/dist/value-guards-CK9guf2Z.mjs.map +1 -0
  225. package/dist/version-B4VuToLC.mjs +2 -0
  226. package/dist/{version-De1l_ZMF.mjs.map → version-B4VuToLC.mjs.map} +1 -1
  227. package/package.json +76 -33
  228. package/dist/base-vfur-DaU.mjs +0 -2
  229. package/dist/base-vfur-DaU.mjs.map +0 -1
  230. package/dist/batch-refs-Op1fx9Bo.mjs +0 -6
  231. package/dist/batch-refs-Op1fx9Bo.mjs.map +0 -1
  232. package/dist/bind-parameter-capacity-DzMcIB95.mjs +0 -2
  233. package/dist/builder-DkWfNHEV.mjs +0 -2
  234. package/dist/builder-DkWfNHEV.mjs.map +0 -1
  235. package/dist/chain-uIFlkkXS.mjs +0 -2
  236. package/dist/chain-uIFlkkXS.mjs.map +0 -1
  237. package/dist/client-C8gXvWIA.mjs +0 -2
  238. package/dist/client-C8gXvWIA.mjs.map +0 -1
  239. package/dist/client-z9mcpRtA.mjs +0 -435
  240. package/dist/client-z9mcpRtA.mjs.map +0 -1
  241. package/dist/controls-BhxRnPYS.mjs +0 -2
  242. package/dist/controls-BhxRnPYS.mjs.map +0 -1
  243. package/dist/datetime-physical-codec-BK93pJGW.mjs +0 -2
  244. package/dist/driver-CHclfK3q.mjs +0 -2
  245. package/dist/driver-CHclfK3q.mjs.map +0 -1
  246. package/dist/driver-ZIbkciaz.mjs +0 -2
  247. package/dist/driver-options-DVxWlZ0s.mjs +0 -2
  248. package/dist/driver-options-DVxWlZ0s.mjs.map +0 -1
  249. package/dist/error-mapping-LKqxnw-b.mjs +0 -2
  250. package/dist/error-mapping-LKqxnw-b.mjs.map +0 -1
  251. package/dist/fs-estate-3Bu_K9mk.d.mts +0 -7
  252. package/dist/fs-estate-BLqNdigQ.mjs +0 -2
  253. package/dist/fs-estate-BLqNdigQ.mjs.map +0 -1
  254. package/dist/geo-point-codec-DUTTtlav.mjs +0 -2
  255. package/dist/geo-point-codec-DUTTtlav.mjs.map +0 -1
  256. package/dist/key-DKaqPb8w.mjs +0 -2
  257. package/dist/key-DKaqPb8w.mjs.map +0 -1
  258. package/dist/migrations-BWZSBMZh.mjs.map +0 -1
  259. package/dist/mysql-adapter-DtZdwqzc.mjs +0 -2
  260. package/dist/mysql-adapter-DtZdwqzc.mjs.map +0 -1
  261. package/dist/observation-CLp8ylmL.mjs +0 -2
  262. package/dist/observation-CLp8ylmL.mjs.map +0 -1
  263. package/dist/physical-BkelResN.mjs +0 -2
  264. package/dist/pinned-session-CNANv7bv.mjs +0 -2
  265. package/dist/pinned-session-CNANv7bv.mjs.map +0 -1
  266. package/dist/postgres-adapter-ButxrmEa.mjs +0 -2
  267. package/dist/postgres-adapter-ButxrmEa.mjs.map +0 -1
  268. package/dist/registration-preflight-BrA3EWvq.mjs +0 -4
  269. package/dist/registration-preflight-BrA3EWvq.mjs.map +0 -1
  270. package/dist/result-shape-CKLOBSKl.mjs +0 -2
  271. package/dist/result-shape-CKLOBSKl.mjs.map +0 -1
  272. package/dist/scalar-BTktMqvO.mjs +0 -2
  273. package/dist/schema-BFNcMdO6.mjs +0 -2
  274. package/dist/schema-introspection-C7P7lwIs.mjs +0 -6
  275. package/dist/schema-introspection-C7P7lwIs.mjs.map +0 -1
  276. package/dist/select-assembly-BgqlrePH.mjs.map +0 -1
  277. package/dist/sqlite-adapter-1krz0OXw.mjs +0 -2
  278. package/dist/sqlite-adapter-1krz0OXw.mjs.map +0 -1
  279. package/dist/sqlite-utils-D26BFuJJ.mjs +0 -2
  280. package/dist/sqlite-utils-D26BFuJJ.mjs.map +0 -1
  281. package/dist/transaction-oskVwmsf.mjs.map +0 -1
  282. package/dist/transactions-gjmrWN5W.mjs +0 -2
  283. package/dist/transactions-gjmrWN5W.mjs.map +0 -1
  284. package/dist/utils-CRFUUfNn.mjs.map +0 -1
  285. package/dist/v-B2WwtcRz.mjs +0 -2
  286. package/dist/v-B2WwtcRz.mjs.map +0 -1
  287. package/dist/validation-Du6j0Q38.mjs +0 -2
  288. package/dist/validation-Du6j0Q38.mjs.map +0 -1
  289. package/dist/validation-tgjL_9n8.mjs +0 -2
  290. package/dist/validator-DMlEScV3.mjs +0 -2
  291. package/dist/version-De1l_ZMF.mjs +0 -2
  292. /package/dist/{contract-BHUOUAZ-.d.mts → contract-CIIqgFyb.d.mts} +0 -0
  293. /package/dist/{sql--yhoVvRM.d.mts → sql-BvfwUKIh.d.mts} +0 -0
@@ -0,0 +1,2 @@
1
+ import{n as e}from"./chunk-BuuaeEvq.mjs";import{n as t}from"./base-AdXAoy6l.mjs";import{t as n}from"./migrations-DTObIjAm.mjs";import{n as r}from"./canonical-json-rfC2Dg0X.mjs";import{a as i}from"./identity-CLFhCTZx.mjs";function refuseWorkersKvWritable(){throw new n(`Workers KV cannot be a V1 estate writer: listing is eventually consistent and puts are not conditional`,t.MIGRATION_UNSUPPORTED_PROVIDER)}var ObjectStoreEstateStorage=class{store;constructor(e){this.store=e}async readEstate(){return this.store.get(`estate.json`)}async listStates(){return this.listHex(`states/`,`.json`)}async listSnapshots(){return this.listHex(`snapshots/`,`.json`)}async listSql(){return this.listHex(`sql/`,`.sql`)}async readState(e){return this.store.get(`states/${e}.json`)}async readSnapshot(e){return this.store.get(`snapshots/${e}.json`)}async readSql(e){return this.store.get(`sql/${e}.sql`)}async publishEstate(e){return this.publish(`estate.json`,e)}async publishSnapshot(e,t){return this.publish(`snapshots/${e}.json`,t)}async publishSql(e,t){return this.publish(`sql/${e}.sql`,t)}async publishState(e,r){if(!i(e))throw new n(`State id is not a SHA-256 digest`,t.MIGRATION_INVALID_ESTATE);return this.publish(`states/${e}.json`,r)}async publish(e,i){if(await this.store.putIfAbsent(e,i)===`created`)return{outcome:`created`};let a=await this.store.get(e);if(!(a&&r(a,i)))throw new n(`Object-store key ${e} already holds different bytes`,t.MIGRATION_CORRUPTION);return{outcome:`identical`}}async listHex(e,t){let n=await this.store.list(e),r=[];for(let a of n){let n=a.slice(e.length);if(!n.endsWith(t))continue;let o=n.slice(0,-t.length);i(o)&&r.push(o)}return r.sort()}},MemoryConditionalObjectStore=class{objects=new Map;async putIfAbsent(e,t){return this.objects.has(e)?`exists`:(this.objects.set(e,t.slice()),`created`)}async get(e){let t=this.objects.get(e);return t?t.slice():null}async list(e){return[...this.objects.keys()].filter(t=>t.startsWith(e)).sort()}};export{ObjectStoreEstateStorage as n,refuseWorkersKvWritable as r,MemoryConditionalObjectStore as t};
2
+ //# sourceMappingURL=object-store-DQR6bTBY.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"object-store-DQR6bTBY.mjs","names":[],"sources":["../src/migrations/storage/object-store.ts"],"sourcesContent":["/**\n * Strong object-store publication contract.\n * A writable driver that cannot do conditional create is not a V1 estate owner.\n * Workers KV is refused here: it has no compare-and-swap publication.\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 function refuseWorkersKvWritable(): never {\n throw new MigrationError(\n \"Workers KV cannot be a V1 estate writer: listing is eventually consistent and puts are not conditional\",\n VibORMErrorCode.MIGRATION_UNSUPPORTED_PROVIDER\n );\n}\n\nexport interface ObjectStoreConditionalPut {\n putIfAbsent(key: string, bytes: Uint8Array): Promise<\"created\" | \"exists\">;\n get(key: string): Promise<Uint8Array | null>;\n list(prefix: string): Promise<readonly string[]>;\n}\n\n/**\n * Estate writer over a strongly consistent object store with if-none-match\n * publication. Manifests become visible only after referenced bytes exist.\n */\nexport class ObjectStoreEstateStorage implements MigrationStorageWriter {\n private readonly store: ObjectStoreConditionalPut;\n\n constructor(store: ObjectStoreConditionalPut) {\n this.store = store;\n }\n\n async readEstate(): Promise<Uint8Array | null> {\n return this.store.get(\"estate.json\");\n }\n\n async listStates(): Promise<readonly Sha256[]> {\n return this.listHex(\"states/\", \".json\");\n }\n\n async listSnapshots(): Promise<readonly Sha256[]> {\n return this.listHex(\"snapshots/\", \".json\");\n }\n\n async listSql(): Promise<readonly Sha256[]> {\n return this.listHex(\"sql/\", \".sql\");\n }\n\n async readState(id: Sha256): Promise<Uint8Array | null> {\n return this.store.get(`states/${id}.json`);\n }\n\n async readSnapshot(hash: Sha256): Promise<Uint8Array | null> {\n return this.store.get(`snapshots/${hash}.json`);\n }\n\n async readSql(hash: Sha256): Promise<Uint8Array | null> {\n return this.store.get(`sql/${hash}.sql`);\n }\n\n async publishEstate(bytes: Uint8Array): Promise<PublishResult> {\n return this.publish(\"estate.json\", bytes);\n }\n\n async publishSnapshot(\n hash: Sha256,\n bytes: Uint8Array\n ): Promise<PublishResult> {\n return this.publish(`snapshots/${hash}.json`, bytes);\n }\n\n async publishSql(hash: Sha256, bytes: Uint8Array): Promise<PublishResult> {\n return this.publish(`sql/${hash}.sql`, bytes);\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 this.publish(`states/${id}.json`, bytes);\n }\n\n private async publish(\n key: string,\n bytes: Uint8Array\n ): Promise<PublishResult> {\n const result = await this.store.putIfAbsent(key, bytes);\n if (result === \"created\") return { outcome: \"created\" };\n const existing = await this.store.get(key);\n if (!(existing && bytesEqual(existing, bytes))) {\n throw new MigrationError(\n `Object-store key ${key} already holds different bytes`,\n VibORMErrorCode.MIGRATION_CORRUPTION\n );\n }\n return { outcome: \"identical\" };\n }\n\n private async listHex(prefix: string, suffix: string): Promise<Sha256[]> {\n const keys = await this.store.list(prefix);\n const hashes: Sha256[] = [];\n for (const key of keys) {\n const name = key.slice(prefix.length);\n if (!name.endsWith(suffix)) continue;\n const hex = name.slice(0, -suffix.length);\n if (isSha256(hex)) hashes.push(hex);\n }\n return hashes.sort();\n }\n}\n\n/** In-memory strong object store for the conformance fixture. */\nexport class MemoryConditionalObjectStore implements ObjectStoreConditionalPut {\n private readonly objects = new Map<string, Uint8Array>();\n\n async putIfAbsent(\n key: string,\n bytes: Uint8Array\n ): Promise<\"created\" | \"exists\"> {\n if (this.objects.has(key)) return \"exists\";\n this.objects.set(key, bytes.slice());\n return \"created\";\n }\n\n async get(key: string): Promise<Uint8Array | null> {\n const bytes = this.objects.get(key);\n return bytes ? bytes.slice() : null;\n }\n\n async list(prefix: string): Promise<readonly string[]> {\n return [...this.objects.keys()]\n .filter((key) => key.startsWith(prefix))\n .sort();\n }\n}\n"],"mappings":"6NAWA,SAAgB,yBAAiC,CAC/C,MAAM,IAAI,EACR,yGACA,EAAgB,+BACjB,CAaH,IAAa,yBAAb,KAAwE,CACtE,MAEA,YAAY,EAAkC,CAC5C,KAAK,MAAQ,EAGf,MAAM,YAAyC,CAC7C,OAAO,KAAK,MAAM,IAAI,cAAc,CAGtC,MAAM,YAAyC,CAC7C,OAAO,KAAK,QAAQ,UAAW,QAAQ,CAGzC,MAAM,eAA4C,CAChD,OAAO,KAAK,QAAQ,aAAc,QAAQ,CAG5C,MAAM,SAAsC,CAC1C,OAAO,KAAK,QAAQ,OAAQ,OAAO,CAGrC,MAAM,UAAU,EAAwC,CACtD,OAAO,KAAK,MAAM,IAAI,UAAU,EAAG,OAAO,CAG5C,MAAM,aAAa,EAA0C,CAC3D,OAAO,KAAK,MAAM,IAAI,aAAa,EAAK,OAAO,CAGjD,MAAM,QAAQ,EAA0C,CACtD,OAAO,KAAK,MAAM,IAAI,OAAO,EAAK,MAAM,CAG1C,MAAM,cAAc,EAA2C,CAC7D,OAAO,KAAK,QAAQ,cAAe,EAAM,CAG3C,MAAM,gBACJ,EAC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A4C,CACrD,MAAO,CAAC,GAAG,KAAK,QAAQ,MAAM,CAAC,CAC5B,OAAQ,GAAQ,EAAI,WAAW,EAAO,CAAC,CACvC,MAAM"}
@@ -0,0 +1,2 @@
1
+ import{n as e}from"./chunk-BuuaeEvq.mjs";import{i as t}from"./value-guards-CK9guf2Z.mjs";import{S as n,g as r}from"./base-AdXAoy6l.mjs";const i=new WeakMap,a=new WeakMap,o=new WeakMap,settleObserverReturn=()=>void 0;function getOfficialInstrumentationChainCapability(e){return e===void 0?void 0:o.get(e)}function registerOfficialInstrumentationChain(e,t){o.set(e,t)}function registerTrustedProtectedObserver(e,t,n){i.set(e,{capability:t,observer:n})}function getTrustedProtectedObserverCapability(e){return t(e)?i.get(e)?.capability:void 0}function selectTrustedObservers(e){let t=e?.find(({handler:e})=>i.has(e));return t===void 0?void 0:[t]}function prewarmProtectedObservers(e){if(!(e===void 0||e.length===0))for(let t of e){let e=i.get(t.handler);if(e===void 0)continue;let n=prewarmTrustedObserver(e.capability);if(n!==void 0)return n}}function readProtectedLifecycleFacts(e){return a.get(e)?.facts}function readProtectedLifecycleCompletionFacts(e){return a.get(e)?.completion}function runProtectedObservers(e,t,n,r,o){if(t===void 0||t.length===0)return n();let s=Date.now(),c=freezeLifecycleUnit(e),l=-1,u;for(let[e,n]of t.entries()){let t=i.get(n.handler);if(t!==void 0){l=e,u=t;break}}let d,f,p,m=u===void 0?void 0:new Promise(e=>{p=e}),h,g=u===void 0,_,v=!1,resolveOuterWhenReady=()=>{g&&h!==void 0&&p?.(h)},settleCompletion=(e,t)=>{let n=Math.max(0,Date.now()-s),i;try{i=r?.()?.commitCertainty}catch{i=void 0}let o=createCompletion(e,n,i,t);h=o;let l=a.get(c);if(l!==void 0)try{l.completion=l.facts.complete({status:e,durationMs:n,...e===`failure`?{failure:t}:{}})}catch{l.completion=void 0}d?.(o),resolveOuterWhenReady()},observeApplicationCompletion=()=>{v||f===void 0||_===void 0||(v=!0,_.then(()=>settleCompletion(`success`),e=>settleCompletion(`failure`,e)))},readCompletionPromise=()=>(f===void 0&&(f=new Promise(e=>{d=e})),observeApplicationCompletion(),f),startChild=()=>{let e;try{e=n()}catch(t){e=Promise.reject(t)}return _=e,observeApplicationCompletion(),e},startObserver=e=>{let n=t[e];if(n===void 0)return startChild();let r=i.get(n.handler);if(r!==void 0){if(o!==void 0)try{let e=o();e!==void 0&&a.set(c,{facts:e})}catch{}let t,n,i=new Promise((e,r)=>{t=e,n=r}),s=!1,startNext=()=>(s||(s=!0,startObserver(e+1).then(e=>t(e),e=>n(e))),readCompletionPromise()),l;try{l=r.observer(c,startNext)}catch{return startNext(),g=!0,resolveOuterWhenReady(),i}return Promise.resolve(l).then(()=>{s||startNext(),g=!0,resolveOuterWhenReady()},()=>{s||startNext(),g=!0,resolveOuterWhenReady()}),i}let s,startNextApplication=()=>(s===void 0&&(s=startObserver(e+1)),s),proceed=()=>(startNextApplication(),m!==void 0&&e<l?m:readCompletionPromise()),u;try{u=Reflect.apply(n.handler,void 0,[c,proceed])}catch{u=void 0}let d=startNextApplication();return consumeObserverReturn(u),d},y=o===void 0||u===void 0?void 0:prewarmTrustedObserver(u.capability);if(y===void 0)return startObserver(0);let b,x,S=new Promise((e,t)=>{b=e,x=t}),startAfterPrewarm=()=>{startObserver(0).then(e=>b(e),e=>x(e))};return y.then(startAfterPrewarm),S}function observeOperation(e,t,n,r,i,a){return runProtectedObservers({kind:`operation`,operation:t,...n===void 0?{}:{model:n}},e,r,i,a)}function observeStatement(e,t,n,r,i,a){return runProtectedObservers({kind:`statement`,...t===void 0?{}:{operation:t},...n===void 0||n===`$raw`?{}:{model:n}},e,r,i,a)}function observeDriverLifecycle(e,t,n,r,i,a){return runProtectedObservers({kind:e,...n===void 0?{}:{operation:n}},t,r,i,a)}function prewarmTrustedObserver(e){let t=e.prewarm;if(t===void 0)return;let n;try{n=t()}catch{return}if(n!==void 0)return Promise.resolve(n).then(()=>void 0,()=>void 0)}function freezeLifecycleUnit(e){return Object.freeze(e)}function consumeObserverReturn(e){if(!(e===null||typeof e!=`object`&&typeof e!=`function`))try{let n=Reflect.get(e,`then`);if(!t(n))return;Reflect.apply(n,e,[settleObserverReturn,settleObserverReturn])}catch{}}function createCompletion(e,t,n,r){let i=e===`failure`?summarizeFailure(r):void 0;return Object.freeze({status:e,durationMs:t,...i===void 0?{}:{error:i},...n===void 0?{}:{commitCertainty:n}})}function summarizeFailure(e){let t=r(n(e)?e:Error(`Application rejected with a non-Error value`)),i=Object.getOwnPropertyDescriptor(t,`code`)?.value;return Object.freeze({name:t.name,message:t.message,...typeof i==`string`?{code:i}:{}})}export{observeStatement as a,readProtectedLifecycleFacts as c,runProtectedObservers as d,selectTrustedObservers as f,observeOperation as i,registerOfficialInstrumentationChain as l,getTrustedProtectedObserverCapability as n,prewarmProtectedObservers as o,observeDriverLifecycle as r,readProtectedLifecycleCompletionFacts as s,getOfficialInstrumentationChainCapability as t,registerTrustedProtectedObserver as u};
2
+ //# sourceMappingURL=observation-DUSm7oXK.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"observation-DUSm7oXK.mjs","names":["resolveApplication","rejectApplication","applicationBridge"],"sources":["../src/extensions/observation.ts"],"sourcesContent":["import { sanitizeErrorForLogging } from \"@errors\";\nimport { isFunction } from \"@validation/value-guards\";\nimport { isError } from \"../errors/diagnostic-safety\";\nimport type { ResolvedExtensionChain, ResolvedExtensionHandler } from \"./chain\";\nimport type {\n OfficialLifecycleCompletionFacts,\n OfficialLifecycleFacts,\n OfficialLifecycleFactsReader,\n OfficialObservationCapability,\n} from \"./official-facts\";\n\n/** The exact public facts carried by each protected lifecycle boundary. */\nexport type LifecycleUnit =\n | Readonly<{\n kind: \"operation\";\n operation: string;\n model?: string;\n }>\n | Readonly<{\n kind: \"statement\";\n operation?: string;\n model?: string;\n }>\n | Readonly<{\n kind: \"batch\";\n operation: string;\n }>\n | Readonly<{\n kind: \"transaction\";\n operation?: string;\n }>\n | Readonly<{\n kind: \"savepoint\";\n operation?: string;\n }>\n | Readonly<{\n kind: \"connection\";\n operation?: string;\n }>\n | Readonly<{\n kind: \"cache\";\n operation: \"get\" | \"set\" | \"revalidate\" | \"invalidate\";\n }>;\n\nexport type LifecycleUnitKind = LifecycleUnit[\"kind\"];\n\nexport type CommitCertainty = \"committed\" | \"may-have-committed\";\n\nexport interface ObservationErrorSummary {\n readonly name: string;\n readonly message: string;\n readonly code?: string;\n}\n\nexport interface ObservationCompletion {\n readonly status: \"success\" | \"failure\";\n readonly durationMs: number;\n readonly error?: ObservationErrorSummary;\n readonly commitCertainty?: CommitCertainty;\n}\n\nexport interface ObservationCompletionFacts {\n readonly commitCertainty?: CommitCertainty;\n}\n\nexport type ObservationCompletionFactsReader = () =>\n | ObservationCompletionFacts\n | undefined;\n\nexport type ObservationUnit = LifecycleUnit;\n\nexport type ObserveHandler = (\n unit: ObservationUnit,\n proceed: () => Promise<ObservationCompletion>\n) => unknown;\n\ntype TrustedProtectedObserver = (\n unit: LifecycleUnit,\n proceed: () => Promise<ObservationCompletion>\n) => unknown;\n\ninterface TrustedProtectedObserverRegistration {\n readonly capability: OfficialObservationCapability;\n readonly observer: TrustedProtectedObserver;\n}\n\ninterface ProtectedLifecycleFactsState {\n readonly facts: OfficialLifecycleFacts;\n completion?: OfficialLifecycleCompletionFacts;\n}\n\nconst trustedObservers = new WeakMap<\n CallableFunction,\n TrustedProtectedObserverRegistration\n>();\nconst lifecycleFacts = new WeakMap<\n LifecycleUnit,\n ProtectedLifecycleFactsState\n>();\nconst officialCapabilitiesByChain = new WeakMap<\n ResolvedExtensionChain,\n OfficialObservationCapability\n>();\nconst settleObserverReturn = (): undefined => undefined;\n\n/** The one official capability registered for this exact chain, if any. */\nexport function getOfficialInstrumentationChainCapability(\n chain: ResolvedExtensionChain | undefined\n): OfficialObservationCapability | undefined {\n return chain === undefined\n ? undefined\n : officialCapabilitiesByChain.get(chain);\n}\n\n/** Bind the admitted official capability to one exact resolved chain. */\nexport function registerOfficialInstrumentationChain(\n chain: ResolvedExtensionChain,\n capability: OfficialObservationCapability\n): void {\n officialCapabilitiesByChain.set(chain, capability);\n}\n\n/** Register one package-owned observer identity without publishing a marker. */\nexport function registerTrustedProtectedObserver(\n handler: CallableFunction,\n capability: OfficialObservationCapability,\n observer: TrustedProtectedObserver\n): void {\n trustedObservers.set(handler, { capability, observer });\n}\n\n/** Recognize the exact package-owned handler identity and nothing else. */\nexport function getTrustedProtectedObserverCapability(\n handler: unknown\n): OfficialObservationCapability | undefined {\n return isFunction(handler)\n ? trustedObservers.get(handler)?.capability\n : undefined;\n}\n\n/**\n * The exact chain's one trusted observer, alone, or `undefined`. Dispatch\n * through it reaches no ordinary observer: cache backend delete/clear, which\n * have no public unit, run through the one runner this way.\n */\nexport function selectTrustedObservers(\n observers: readonly ResolvedExtensionHandler[] | undefined\n): readonly ResolvedExtensionHandler[] | undefined {\n const trusted = observers?.find(({ handler }) =>\n trustedObservers.has(handler)\n );\n return trusted === undefined ? undefined : [trusted];\n}\n\n/** Resolve the one trusted readiness once before a coordinated array starts. */\nexport function prewarmProtectedObservers(\n observers: readonly ResolvedExtensionHandler[] | undefined\n): void | Promise<void> {\n if (observers === undefined || observers.length === 0) return;\n for (const observer of observers) {\n const registration = trustedObservers.get(observer.handler);\n if (registration === undefined) continue;\n const readiness = prewarmTrustedObserver(registration.capability);\n if (readiness !== undefined) return readiness;\n }\n}\n\n/** Read facts only for the exact frozen unit created by this runner. */\nexport function readProtectedLifecycleFacts(\n unit: LifecycleUnit\n): OfficialLifecycleFacts | undefined {\n return lifecycleFacts.get(unit)?.facts;\n}\n\n/** Read completion facts projected by core after the child settled. */\nexport function readProtectedLifecycleCompletionFacts(\n unit: LifecycleUnit\n): OfficialLifecycleCompletionFacts | undefined {\n return lifecycleFacts.get(unit)?.completion;\n}\n\n/**\n * Runs completion-only observers without giving their onion authority over the\n * application promise.\n */\nexport function runProtectedObservers<Result>(\n unit: LifecycleUnit,\n observers: readonly ResolvedExtensionHandler[] | undefined,\n child: () => Promise<Result>,\n readCompletionFacts?: ObservationCompletionFactsReader,\n readInstrumentationFacts?: OfficialLifecycleFactsReader\n): Promise<Result> {\n if (observers === undefined || observers.length === 0) return child();\n\n const startedAt = Date.now();\n const immutableUnit = freezeLifecycleUnit(unit);\n let trustedIndex = -1;\n let trustedRegistration: TrustedProtectedObserverRegistration | undefined;\n for (const [index, observer] of observers.entries()) {\n const registration = trustedObservers.get(observer.handler);\n if (registration !== undefined) {\n trustedIndex = index;\n trustedRegistration = registration;\n break;\n }\n }\n let resolveCompletion:\n | ((completion: ObservationCompletion) => void)\n | undefined;\n let completionPromise: Promise<ObservationCompletion> | undefined;\n let resolveOuterCompletion:\n | ((completion: ObservationCompletion) => void)\n | undefined;\n const outerCompletionPromise =\n trustedRegistration === undefined\n ? undefined\n : new Promise<ObservationCompletion>((resolve) => {\n resolveOuterCompletion = resolve;\n });\n let settledCompletion: ObservationCompletion | undefined;\n let trustedSetupSettled = trustedRegistration === undefined;\n let applicationPromise: Promise<Result> | undefined;\n let observesApplicationCompletion = false;\n\n const resolveOuterWhenReady = (): void => {\n if (trustedSetupSettled && settledCompletion !== undefined) {\n resolveOuterCompletion?.(settledCompletion);\n }\n };\n\n const settleCompletion = (\n status: ObservationCompletion[\"status\"],\n failure?: unknown\n ): void => {\n const durationMs = Math.max(0, Date.now() - startedAt);\n let commitCertainty: CommitCertainty | undefined;\n try {\n commitCertainty = readCompletionFacts?.()?.commitCertainty;\n } catch {\n commitCertainty = undefined;\n }\n const completion = createCompletion(\n status,\n durationMs,\n commitCertainty,\n failure\n );\n settledCompletion = completion;\n const factsState = lifecycleFacts.get(immutableUnit);\n if (factsState !== undefined) {\n try {\n factsState.completion = factsState.facts.complete({\n status,\n durationMs,\n ...(status === \"failure\" ? { failure } : {}),\n });\n } catch {\n factsState.completion = undefined;\n }\n }\n resolveCompletion?.(completion);\n resolveOuterWhenReady();\n };\n\n const observeApplicationCompletion = (): void => {\n if (\n observesApplicationCompletion ||\n completionPromise === undefined ||\n applicationPromise === undefined\n ) {\n return;\n }\n observesApplicationCompletion = true;\n applicationPromise.then(\n () => settleCompletion(\"success\"),\n (failure: unknown) => settleCompletion(\"failure\", failure)\n );\n };\n\n const readCompletionPromise = (): Promise<ObservationCompletion> => {\n if (completionPromise === undefined) {\n completionPromise = new Promise<ObservationCompletion>((resolve) => {\n resolveCompletion = resolve;\n });\n }\n observeApplicationCompletion();\n return completionPromise;\n };\n\n const startChild = (): Promise<Result> => {\n let started: Promise<Result>;\n try {\n started = child();\n } catch (failure) {\n started = Promise.reject(failure);\n }\n applicationPromise = started;\n observeApplicationCompletion();\n return started;\n };\n\n const startObserver = (index: number): Promise<Result> => {\n const observer = observers[index];\n if (observer === undefined) return startChild();\n\n const trustedObserver = trustedObservers.get(observer.handler);\n if (trustedObserver !== undefined) {\n if (readInstrumentationFacts !== undefined) {\n try {\n const facts = readInstrumentationFacts();\n if (facts !== undefined) lifecycleFacts.set(immutableUnit, { facts });\n } catch {\n // Instrumentation fact production cannot stop the application.\n }\n }\n // Promise executors run synchronously; TypeScript does not model that guarantee.\n let resolveApplication!: (value: Result | PromiseLike<Result>) => void;\n let rejectApplication!: (reason?: unknown) => void;\n const applicationBridge = new Promise<Result>((resolve, reject) => {\n resolveApplication = resolve;\n rejectApplication = reject;\n });\n let proceeded = false;\n const startNext = (): Promise<ObservationCompletion> => {\n if (!proceeded) {\n proceeded = true;\n startObserver(index + 1).then(\n (value) => resolveApplication(value),\n (failure: unknown) => rejectApplication(failure)\n );\n }\n return readCompletionPromise();\n };\n let setup: unknown;\n try {\n setup = trustedObserver.observer(immutableUnit, startNext);\n } catch {\n startNext();\n trustedSetupSettled = true;\n resolveOuterWhenReady();\n return applicationBridge;\n }\n Promise.resolve(setup).then(\n () => {\n if (!proceeded) startNext();\n trustedSetupSettled = true;\n resolveOuterWhenReady();\n },\n () => {\n if (!proceeded) startNext();\n trustedSetupSettled = true;\n resolveOuterWhenReady();\n }\n );\n return applicationBridge;\n }\n\n let nextApplicationPromise: Promise<Result> | undefined;\n const startNextApplication = (): Promise<Result> => {\n if (nextApplicationPromise === undefined) {\n nextApplicationPromise = startObserver(index + 1);\n }\n return nextApplicationPromise;\n };\n const proceed = (): Promise<ObservationCompletion> => {\n startNextApplication();\n return outerCompletionPromise !== undefined && index < trustedIndex\n ? outerCompletionPromise\n : readCompletionPromise();\n };\n\n let returned: unknown;\n try {\n returned = Reflect.apply(observer.handler, undefined, [\n immutableUnit,\n proceed,\n ]);\n } catch {\n returned = undefined;\n }\n const nextApplication = startNextApplication();\n consumeObserverReturn(returned);\n return nextApplication;\n };\n\n const readiness =\n readInstrumentationFacts === undefined || trustedRegistration === undefined\n ? undefined\n : prewarmTrustedObserver(trustedRegistration.capability);\n if (readiness === undefined) return startObserver(0);\n\n // Promise executors run synchronously; TypeScript does not model that guarantee.\n let resolveApplication!: (value: Result | PromiseLike<Result>) => void;\n let rejectApplication!: (reason?: unknown) => void;\n const applicationBridge = new Promise<Result>((resolve, reject) => {\n resolveApplication = resolve;\n rejectApplication = reject;\n });\n const startAfterPrewarm = (): void => {\n startObserver(0).then(\n (value) => resolveApplication(value),\n (failure: unknown) => rejectApplication(failure)\n );\n };\n readiness.then(startAfterPrewarm);\n return applicationBridge;\n}\n\n/** Observe one logical operation without duplicating its completion protocol. */\nexport function observeOperation<Result>(\n observers: readonly ResolvedExtensionHandler[],\n operation: string,\n model: string | undefined,\n child: () => Promise<Result>,\n readCompletionFacts?: ObservationCompletionFactsReader,\n readInstrumentationFacts?: OfficialLifecycleFactsReader\n): Promise<Result> {\n return runProtectedObservers(\n {\n kind: \"operation\",\n operation,\n ...(model === undefined ? {} : { model }),\n },\n observers,\n child,\n readCompletionFacts,\n readInstrumentationFacts\n );\n}\n\n/** Observe one driver-owned physical statement boundary. */\nexport function observeStatement<Result>(\n observers: readonly ResolvedExtensionHandler[],\n operation: string | undefined,\n model: string | undefined,\n child: () => Promise<Result>,\n readCompletionFacts?: ObservationCompletionFactsReader,\n readInstrumentationFacts?: OfficialLifecycleFactsReader\n): Promise<Result> {\n return runProtectedObservers(\n {\n kind: \"statement\",\n ...(operation === undefined ? {} : { operation }),\n ...(model === undefined || model === \"$raw\" ? {} : { model }),\n },\n observers,\n child,\n readCompletionFacts,\n readInstrumentationFacts\n );\n}\n\n/** Observe one driver-owned connection, transaction, or savepoint boundary. */\nexport function observeDriverLifecycle<Result>(\n kind: Extract<LifecycleUnitKind, \"connection\" | \"savepoint\" | \"transaction\">,\n observers: readonly ResolvedExtensionHandler[],\n operation: string | undefined,\n child: () => Promise<Result>,\n readCompletionFacts?: ObservationCompletionFactsReader,\n readInstrumentationFacts?: OfficialLifecycleFactsReader\n): Promise<Result> {\n return runProtectedObservers(\n {\n kind,\n ...(operation === undefined ? {} : { operation }),\n },\n observers,\n child,\n readCompletionFacts,\n readInstrumentationFacts\n );\n}\n\nfunction prewarmTrustedObserver(\n capability: OfficialObservationCapability\n): void | Promise<void> {\n const prewarm = capability.prewarm;\n if (prewarm === undefined) return;\n let readiness: void | Promise<void>;\n try {\n readiness = prewarm();\n } catch {\n return;\n }\n if (readiness === undefined) return;\n return Promise.resolve(readiness).then(\n () => undefined,\n () => undefined\n );\n}\n\nfunction freezeLifecycleUnit(unit: LifecycleUnit): LifecycleUnit {\n return Object.freeze(unit);\n}\n\nfunction consumeObserverReturn(returned: unknown): void {\n if (\n returned === null ||\n (typeof returned !== \"object\" && typeof returned !== \"function\")\n ) {\n return;\n }\n try {\n const then = Reflect.get(returned, \"then\");\n if (!isFunction(then)) return;\n Reflect.apply(then, returned, [settleObserverReturn, settleObserverReturn]);\n } catch {\n // Observer returns cannot affect the application.\n }\n}\n\nfunction createCompletion(\n status: ObservationCompletion[\"status\"],\n durationMs: number,\n commitCertainty: CommitCertainty | undefined,\n failure: unknown\n): ObservationCompletion {\n const error = status === \"failure\" ? summarizeFailure(failure) : undefined;\n return Object.freeze({\n status,\n durationMs,\n ...(error === undefined ? {} : { error }),\n ...(commitCertainty === undefined ? {} : { commitCertainty }),\n });\n}\n\nfunction summarizeFailure(failure: unknown): ObservationErrorSummary {\n const normalized = isError(failure)\n ? failure\n : new Error(\"Application rejected with a non-Error value\");\n const sanitized = sanitizeErrorForLogging(normalized);\n const code = Object.getOwnPropertyDescriptor(sanitized, \"code\")?.value;\n return Object.freeze({\n name: sanitized.name,\n message: sanitized.message,\n ...(typeof code === \"string\" ? { code } : {}),\n });\n}\n"],"mappings":"wIA2FA,MAAM,EAAmB,IAAI,QAIvB,EAAiB,IAAI,QAIrB,EAA8B,IAAI,QAIlC,yBAAwC,IAAA,GAG9C,SAAgB,0CACd,EAC2C,CAC3C,OAAO,IAAU,IAAA,GACb,IAAA,GACA,EAA4B,IAAI,EAAM,CAI5C,SAAgB,qCACd,EACA,EACM,CACN,EAA4B,IAAI,EAAO,EAAW,CAIpD,SAAgB,iCACd,EACA,EACA,EACM,CACN,EAAiB,IAAI,EAAS,CAAE,aAAY,WAAU,CAAC,CAIzD,SAAgB,sCACd,EAC2C,CAC3C,OAAO,EAAW,EAAQ,CACtB,EAAiB,IAAI,EAAQ,EAAE,WAC/B,IAAA,GAQN,SAAgB,uBACd,EACiD,CACjD,IAAM,EAAU,GAAW,MAAM,CAAE,aACjC,EAAiB,IAAI,EAAQ,CAC9B,CACD,OAAO,IAAY,IAAA,GAAY,IAAA,GAAY,CAAC,EAAQ,CAItD,SAAgB,0BACd,EACsB,CAClB,SAAc,IAAA,IAAa,EAAU,SAAW,GACpD,IAAK,IAAM,KAAY,EAAW,CAChC,IAAM,EAAe,EAAiB,IAAI,EAAS,QAAQ,CAC3D,GAAI,IAAiB,IAAA,GAAW,SAChC,IAAM,EAAY,uBAAuB,EAAa,WAAW,CACjE,GAAI,IAAc,IAAA,GAAW,OAAO,GAKxC,SAAgB,4BACd,EACoC,CACpC,OAAO,EAAe,IAAI,EAAK,EAAE,MAInC,SAAgB,sCACd,EAC8C,CAC9C,OAAO,EAAe,IAAI,EAAK,EAAE,WAOnC,SAAgB,sBACd,EACA,EACA,EACA,EACA,EACi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ACZ,OAAO,GAAa,UAAY,OAAO,GAAa,YAIvD,GAAI,CACF,IAAM,EAAO,QAAQ,IAAI,EAAU,OAAO,CAC1C,GAAI,CAAC,EAAW,EAAK,CAAE,OACvB,QAAQ,MAAM,EAAM,EAAU,CAAC,qBAAsB,qBAAqB,CAAC,MACrE,GAKV,SAAS,iBACP,EACA,EACA,EACA,EACuB,CACvB,IAAM,EAAQ,IAAW,UAAY,iBAAiB,EAAQ,CAAG,IAAA,GACjE,OAAO,OAAO,OAAO,CACnB,SACA,aACA,GAAI,IAAU,IAAA,GAAY,EAAE,CAAG,CAAE,QAAO,CACxC,GAAI,IAAoB,IAAA,GAAY,EAAE,CAAG,CAAE,kBAAiB,CAC7D,CAAC,CAGJ,SAAS,iBAAiB,EAA2C,CAInE,IAAM,EAAY,EAHC,EAAQ,EAAQ,CAC/B,EACI,MAAM,8CAA8C,CACP,CAC/C,EAAO,OAAO,yBAAyB,EAAW,OAAO,EAAE,MACjE,OAAO,OAAO,OAAO,CACnB,KAAM,EAAU,KAChB,QAAS,EAAU,QACnB,GAAI,OAAO,GAAS,SAAW,CAAE,OAAM,CAAG,EAAE,CAC7C,CAAC"}
package/dist/pg.d.mts CHANGED
@@ -1,19 +1,42 @@
1
- import { D as Schema, Dn as QueryExecutionContext, Ft as NoExtraDriverConfigKeys, Ht as TransactionOptionSupport, It as VibORMClient, L as LinkedClientConfig, On as QueryResult, Vt as DriverTransactionOptions, d as PinnedSessionReservation, jt as DriverConfig, s as DatabaseAdapter, u as Driver } from "./index-BbcE-gyl.mjs";
1
+ import { A as Schema, B as LinkedClientConfig, Dn as TransactionOptionSupport, En as DriverTransactionOptions, Mn as QueryResult, Pt as DriverConfig, Rt as NoExtraDriverConfigKeys, d as MigrationSessionAttestation, jn as QueryExecutionContext, m as PinnedSessionReservation, s as DatabaseAdapter, u as Driver, zt as VibORMClient } from "./index-Likdf5qP.mjs";
2
2
  import { Pool, PoolClient, PoolConfig, PoolConfig as PgOptions } from "pg";
3
3
 
4
4
  //#region src/drivers/pg/index.d.ts
5
5
 
6
+ interface PgErrorEvents {
7
+ on(event: "error", listener: (error: Error) => void): unknown;
8
+ off(event: "error", listener: (error: Error) => void): unknown;
9
+ }
10
+ /** The part of a node-postgres `PoolClient` this driver uses. */
11
+ interface PgPoolClient extends Pick<PoolClient, "query" | "release">, PgErrorEvents {}
12
+ /**
13
+ * The part of a node-postgres `Pool` this driver uses, so any pool with that
14
+ * shape is accepted. A Neon WebSocket `Pool` (`@neondatabase/serverless`) is
15
+ * node-postgres's pool over a WebSocket and runs here unchanged, but its
16
+ * bundled copy of the pg declarations lags `@types/pg`: in 8.23 a
17
+ * `PoolClient` is a whole `Client`, and the full `Pool` type refused Neon's.
18
+ */
19
+ interface PgPool extends Pick<Pool, "query" | "end">, PgErrorEvents {
20
+ connect(): Promise<PgPoolClient>;
21
+ }
6
22
  interface PgDriverOptions {
7
- pool?: Pool;
23
+ pool?: PgPool;
8
24
  options?: PoolConfig;
9
25
  pgvector?: boolean;
10
26
  postgis?: boolean;
11
27
  databaseUrl?: string;
12
28
  /** The PostgreSQL schema this driver's persistent objects live in. Defaults to `public`. */
13
29
  namespace?: string;
30
+ /**
31
+ * Your claim, at your risk, that every connection this pool opens is one
32
+ * server session for its whole life. It lifts migrations' refusal of
33
+ * Cloudflare Hyperdrive and Neon `-pooler` hosts; application queries never
34
+ * need it.
35
+ */
36
+ migrationSessionAttestation?: MigrationSessionAttestation;
14
37
  }
15
38
  type PgClientConfig<C extends DriverConfig> = PgDriverOptions & C;
16
- declare class PgDriver extends Driver<Pool, PoolClient> {
39
+ declare class PgDriver extends Driver<PgPool, PgPoolClient> {
17
40
  readonly adapter: DatabaseAdapter;
18
41
  readonly maxBindParametersPerStatement: number | undefined;
19
42
  /**
@@ -29,11 +52,10 @@ declare class PgDriver extends Driver<Pool, PoolClient> {
29
52
  *
30
53
  * A copy of THIS record, not of what it points at: a nested `ssl` object or
31
54
  * stream is the caller's to own, and the keys that decide where a pool
32
- * connects — host, port, user, database, connectionString — all live here.
55
+ * connects — host, port, user, database, connectionString — all live here,
56
+ * with the caller's `databaseUrl` merged in (see `connectionRecord`).
33
57
  */
34
58
  private readonly connectionOptions;
35
- /** The caller's `databaseUrl`, read once, for the same reason. */
36
- private readonly connectionString;
37
59
  /**
38
60
  * The listener and latest idle failure for each pool this driver created.
39
61
  *
@@ -44,6 +66,8 @@ declare class PgDriver extends Driver<Pool, PoolClient> {
44
66
  */
45
67
  private readonly ownedPoolErrors;
46
68
  constructor(options?: PgDriverOptions);
69
+ /** Every host or URL this driver's pool connects through, for migration admission. */
70
+ protected migrationSessionEndpoints(): readonly unknown[];
47
71
  /**
48
72
  * The pool this driver connects through.
49
73
  *
@@ -59,7 +83,7 @@ declare class PgDriver extends Driver<Pool, PoolClient> {
59
83
  * for a caller who never asked it to — and for the other consumers of a pool
60
84
  * two estates share. This driver listens only on the pool it made.
61
85
  */
62
- protected initClient(): Promise<Pool>;
86
+ protected initClient(): Promise<PgPool>;
63
87
  private readBackgroundPoolFailure;
64
88
  /** Clear exactly the failure observed before an operation started. */
65
89
  private clearBackgroundPoolFailure;
@@ -92,23 +116,24 @@ declare class PgDriver extends Driver<Pool, PoolClient> {
92
116
  * caller's record says now: every pool this driver made is ended, and the one
93
117
  * it was handed never is.
94
118
  */
95
- protected closeClient(pool: Pool): Promise<void>;
96
- protected execute<T>(client: Pool | PoolClient, sql: string, params: unknown[], context?: QueryExecutionContext): Promise<QueryResult<T>>;
97
- protected executeRaw<T>(client: Pool | PoolClient, sql: string, params: unknown[] | undefined, context?: QueryExecutionContext): Promise<QueryResult<T>>;
119
+ protected closeClient(pool: PgPool): Promise<void>;
120
+ protected execute<T>(client: PgPool | PgPoolClient, sql: string, params: unknown[], context?: QueryExecutionContext): Promise<QueryResult<T>>;
121
+ protected executeRaw<T>(client: PgPool | PgPoolClient, sql: string, params: unknown[] | undefined, context?: QueryExecutionContext): Promise<QueryResult<T>>;
122
+ private executeQuery;
98
123
  /**
99
124
  * PostgreSQL takes the isolation level as the first statement inside the
100
125
  * transaction, and node-postgres hands out a pooled client we can wait for
101
126
  * with a bound (and release if we stop waiting).
102
127
  */
103
128
  protected transactionOptionSupport(): TransactionOptionSupport;
104
- protected transaction<T>(client: Pool | PoolClient, fn: (tx: PoolClient) => Promise<T>, context?: QueryExecutionContext, options?: DriverTransactionOptions): Promise<T>;
129
+ protected transaction<T>(client: PgPool | PgPoolClient, fn: (tx: PgPoolClient) => Promise<T>, context?: QueryExecutionContext, options?: DriverTransactionOptions): Promise<T>;
105
130
  protected transactionCleanupFailed(_error: Error): void;
106
131
  /**
107
132
  * One `PoolClient` from `pool.connect()` — plan §3.5's pinned producer for
108
133
  * `pg`. `release(true)` destroys the connection instead of returning it, so a
109
134
  * session whose advisory-lock state is unknown never re-enters the pool.
110
135
  */
111
- protected pinnedSession(): Promise<PinnedSessionReservation<Pool | PoolClient>>;
136
+ protected pinnedSession(): Promise<PinnedSessionReservation<PgPool | PgPoolClient>>;
112
137
  }
113
138
  declare function createClient<S extends Schema, C extends DriverConfig<S>>(config: PgClientConfig<C> & DriverConfig<S> & NoExtraDriverConfigKeys<C, PgDriverOptions, S>): VibORMClient<{ [P in keyof LinkedClientConfig<C & {
114
139
  driver: PgDriver;
package/dist/pg.mjs CHANGED
@@ -1,2 +1,2 @@
1
- import{n as e}from"./chunk-BuuaeEvq.mjs";import{y as t}from"./validation-Du6j0Q38.mjs";import{n,r}from"./error-mapping-LKqxnw-b.mjs";import{n as i}from"./transaction-oskVwmsf.mjs";import{n as a}from"./suppressed-failure-BPxfHTMc.mjs";import{r as o,s}from"./transactions-gjmrWN5W.mjs";import{s as c}from"./execution-context-Bm_qTp1i.mjs";import{n as l}from"./client-C8gXvWIA.mjs";import{i as u,t as d}from"./driver-options-DVxWlZ0s.mjs";import{r as f,t as p}from"./driver-CHclfK3q.mjs";import{t as m}from"./postgres-adapter-ButxrmEa.mjs";import{t as h}from"./postgres-result-Dc_iW3Hb.mjs";import{Pool as g,types as _}from"pg";const identityParser=e=>e,v={getTypeParser:(e,t)=>[1082,1114,1184,1115,1182,1185].includes(e)&&t!==`binary`?identityParser:_.getTypeParser(e,t)};function createOwnedPoolErrorState(){let e=0,t={retain(n){e+=1,t.backgroundFailure={error:n,generation:e,isAvailable:!0}}};return t}function holdClientErrors(e){let t,retain=e=>{t??=e};return e.on(`error`,retain),{failure:()=>t,stop:()=>{e.off(`error`,retain)}}}var PgDriver=class extends p{maxBindParametersPerStatement=65535;suppliedPool;connectionOptions;connectionString;ownedPoolErrors=new WeakMap;constructor(e={}){super(`postgresql`,`pg`);let n=u(e);this.suppliedPool=e.pool,this.connectionOptions={...e.options},this.connectionString=e.databaseUrl,this.suppliedPool&&(this.client=this.suppliedPool);let r=new m(n,e.postgis===!0);r.capabilities.supportsVector=e.pgvector===!0,e.pgvector||(r.vector=t),d(this,`adapter`,r)}initClient(){if(this.suppliedPool!==void 0)return Promise.resolve(this.suppliedPool);let e={types:v,...this.connectionOptions};this.connectionString!==void 0&&(e.connectionString??=this.connectionString);let t=new g(e),n=createOwnedPoolErrorState();return this.ownedPoolErrors.set(t,n),t.on(`error`,n.retain),Promise.resolve(t)}readBackgroundPoolFailure(e){return this.ownedPoolErrors.get(e)?.backgroundFailure}clearBackgroundPoolFailure(e,t){if(t===void 0||!t.isAvailable)return!1;t.isAvailable=!1;let n=this.ownedPoolErrors.get(e);return n?.backgroundFailure?.generation===t.generation&&(n.backgroundFailure=void 0),!0}consumeBackgroundPoolFailure(e,t){if(this.clearBackgroundPoolFailure(e,t))return t?.error}throwPoolQueryFailure(e,t,n,i,o,s){let c=this.consumeBackgroundPoolFailure(e,t);throw c===void 0?n:a(r(n,{driverName:this.driverName,dialect:this.dialect,model:s?.model,operation:s?.operation,correlationId:s?.correlationId,query:i,params:this.getDiagnosticParameters(o??[],s),diagnostics:this.getErrorDisclosure(s),forceContext:!0}),c)}async acquirePooledClient(e,t={},r){let i=this.readBackgroundPoolFailure(e),o=!1;try{return await f(async()=>{try{let t=await e.connect();return this.clearBackgroundPoolFailure(e,i),t}finally{o=!0}},e=>e.release(),r,{driverName:this.driverName,form:`callback`})}catch(r){if(!o)throw r;let s=this.consumeBackgroundPoolFailure(e,i);throw s===void 0?r:a(n(r,{driverName:this.driverName,model:t.model,operation:t.operation,correlationId:t.correlationId,diagnostics:this.getErrorDisclosure(t)},`Database connection failed after the pool reported a background failure`),s)}}async closeClient(e){if(e===this.suppliedPool)return;let t=this.ownedPoolErrors.get(e);try{await e.end()}catch(r){let i=this.consumeBackgroundPoolFailure(e,t?.backgroundFailure);throw i===void 0?r:a(n(r,{driverName:this.driverName},`Database disconnection failed`),i)}t!==void 0&&(e.off(`error`,t.retain),t.backgroundFailure=void 0,this.ownedPoolErrors.delete(e))}async execute(e,t,n,r){let i=r?.operation??`execute`,a=this.readBackgroundPoolFailure(e),o=await e.query({text:t,values:n,types:v}).catch(i=>this.throwPoolQueryFailure(e,a,i,t,n,r));return this.clearBackgroundPoolFailure(e,a),{rows:o.rows,rowCount:h(o.rowCount,o.command,o.rows,{provider:`pg`,operation:i})}}async executeRaw(e,t,n,r){let i=r?.operation??`executeRaw`,a=this.readBackgroundPoolFailure(e),o=await e.query({text:t,values:n,types:v}).catch(i=>this.throwPoolQueryFailure(e,a,i,t,n,r));return this.clearBackgroundPoolFailure(e,a),{rows:o.rows,rowCount:h(o.rowCount,o.command,o.rows,{provider:`pg`,operation:i})}}transactionOptionSupport(){return{isolationLevel:`post-begin`,timeout:!0,maxWait:`acquisition`}}async transaction(e,t,n,r){if(`release`in e)throw o(this.driverName);let l=e,u=await this.acquirePooledClient(l,n,r?.maxWaitMs),d=holdClientErrors(u),withClientFailure=e=>{let t=d.failure();return t===void 0||t===e?e:a(e,t)},f,queryOrDiscard=async e=>{try{await u.query(e)}catch(e){throw f??=e instanceof Error?e:!0,withClientFailure(e)}};return s({begin:()=>queryOrDiscard(`BEGIN`),callback:async()=>{try{return await t(u)}catch(e){throw withClientFailure(e)}},commit:()=>{let e=d.failure();if(e!==void 0)throw e;return queryOrDiscard(`COMMIT`)},rollback:()=>d.failure()===void 0?queryOrDiscard(`ROLLBACK`):void 0,phases:c(n),close:()=>{try{let e=f??d.failure();if(e){u.release(e);return}u.release()}catch(e){throw super.transactionCleanupFailed(new i(`Driver "pg" could not release an unsafe transaction connection.`,{meta:{driver:`pg`,method:`$transaction`}})),e}finally{d.stop()}}})}transactionCleanupFailed(e){}async pinnedSession(){let e=await this.getClient({operation:`pinnedSession`});if(`release`in e)throw o(this.driverName);let t=await this.acquirePooledClient(e,{operation:`pinnedSession`}),n=holdClientErrors(t);return{session:t,release:e=>{try{t.release(n.failure()??(e?!0:void 0))}finally{n.stop()}return Promise.resolve()}}}};function createClient(e){let{pool:t,options:n={},pgvector:r,postgis:i,databaseUrl:a}=e,o=u(e),s={options:a===void 0?n:{...n,connectionString:a}};return t&&(s.pool=t),r!==void 0&&(s.pgvector=r),i!==void 0&&(s.postgis=i),o!==void 0&&(s.namespace=o),l(e,new PgDriver(s))}export{PgDriver,createClient};
1
+ import{n as e}from"./chunk-BuuaeEvq.mjs";import{l as t,n,p as r,r as i}from"./error-mapping-CnPCv1dm.mjs";import{r as a}from"./validation-Dk9Q_-C7.mjs";import{n as o}from"./transaction-Bnl6ULTw.mjs";import{n as s}from"./suppressed-failure-BwULh-8h.mjs";import{s as c}from"./execution-context-BKR3bgES.mjs";import{n as l}from"./client-BLiBmykn.mjs";import{c as u,d,f,i as p,o as m,s as h,t as g,u as _}from"./driver-BlnKXPFF.mjs";import{t as v}from"./postgres-result-7F0DllQe.mjs";import{t as y}from"./postgres-adapter-CQD2oGuD.mjs";import{Pool as b,types as x}from"pg";const identityParser=e=>e,S={getTypeParser:(e,t)=>[1082,1114,1184,1115,1182,1185].includes(e)&&t!==`binary`?identityParser:x.getTypeParser(e,t)};function createOwnedPoolErrorState(){let e=0,t={retain(n){e+=1,t.backgroundFailure={error:n,generation:e,isAvailable:!0}}};return t}function holdClientErrors(e){let t,retain=e=>{t??=e};return e.on(`error`,retain),{failure:()=>t,stop:()=>{e.off(`error`,retain)}}}const C=new Set([`user`,`password`,`host`,`port`]),w=[`sslmode`,`sslcert`,`sslkey`,`sslrootcert`];function connectionRecord(e,t){let n=e.connectionString??t;if(!n)return e;if(typeof e.password==`function`)throw new a('Driver "pg" cannot keep a password callback beside a connection URL: node-postgres reads the password from the URL. Pass `host`, `user` and `database` in `options` instead.',{meta:{driver:`pg`,operation:`configuration`}});let r=f(n),i;try{i=new URL(r)}catch{i=void 0}let o=Object.entries(e).filter(([e,t])=>t!==void 0&&(C.has(e)||e===`database`||e===`ssl`||e!==`connectionString`&&i?.searchParams.has(e)));if(o.length===0)return{...e,connectionString:r};if(i===void 0)throw new a(`Driver "pg" could not read its connection URL to apply the connection options beside it.`,{meta:{driver:`pg`,operation:`configuration`}});for(let[e,t]of o)if(i.searchParams.delete(e),e===`ssl`)for(let e of w)i.searchParams.delete(e);else e===`database`?i.pathname=`/${String(t)}`:C.has(e)&&(typeof t==`string`||typeof t==`number`)&&i.searchParams.set(e,String(t));return{...e,connectionString:i.href}}const T={pool:!0,options:!0,pgvector:!0,postgis:!0,databaseUrl:!0,namespace:!0,migrationSessionAttestation:!0};var PgDriver=class extends g{maxBindParametersPerStatement=65535;suppliedPool;connectionOptions;ownedPoolErrors=new WeakMap;constructor(e={}){super(`postgresql`,`pg`);let t=d(e);this.suppliedPool=e.pool;let n={...e.options};h(`pg`,e,!!(this.suppliedPool||n.host||n.connectionString)),this.connectionOptions=connectionRecord(n,e.databaseUrl),this.suppliedPool&&(this.client=this.suppliedPool),y(this,t,e),m(this,`migrationSessionAttestation`,_(e))}migrationSessionEndpoints(){let e=this.suppliedPool?Reflect.get(this.suppliedPool,`options`):void 0,t=typeof e==`object`&&e?e:{};return[this.connectionOptions.host,this.connectionOptions.connectionString,Reflect.get(t,`host`),Reflect.get(t,`connectionString`)]}initClient(){if(this.suppliedPool!==void 0)return Promise.resolve(this.suppliedPool);let e=new b({types:S,...this.connectionOptions}),t=createOwnedPoolErrorState();return this.ownedPoolErrors.set(e,t),e.on(`error`,t.retain),Promise.resolve(e)}readBackgroundPoolFailure(e){return this.ownedPoolErrors.get(e)?.backgroundFailure}clearBackgroundPoolFailure(e,t){if(t===void 0||!t.isAvailable)return!1;t.isAvailable=!1;let n=this.ownedPoolErrors.get(e);return n?.backgroundFailure?.generation===t.generation&&(n.backgroundFailure=void 0),!0}consumeBackgroundPoolFailure(e,t){if(this.clearBackgroundPoolFailure(e,t))return t?.error}throwPoolQueryFailure(e,t,n,r,a,o){let c=this.consumeBackgroundPoolFailure(e,t);throw c===void 0?n:s(i(n,{driverName:this.driverName,dialect:this.dialect,model:o?.model,operation:o?.operation,correlationId:o?.correlationId,query:r,params:this.getDiagnosticParameters(a??[],o),diagnostics:this.getErrorDisclosure(o),forceContext:!0}),c)}async acquirePooledClient(e,t={},r){let i=this.readBackgroundPoolFailure(e),a=!1;try{return await p(async()=>{try{let t=await e.connect();return this.clearBackgroundPoolFailure(e,i),t}finally{a=!0}},e=>e.release(),r,{driverName:this.driverName,form:`callback`})}catch(r){if(!a)throw r;let o=this.consumeBackgroundPoolFailure(e,i);throw o===void 0?r:s(n(r,{driverName:this.driverName,model:t.model,operation:t.operation,correlationId:t.correlationId,diagnostics:this.getErrorDisclosure(t)},`Database connection failed after the pool reported a background failure`),o)}}async closeClient(e){if(e===this.suppliedPool)return;let t=this.ownedPoolErrors.get(e);try{await e.end()}catch(r){let i=this.consumeBackgroundPoolFailure(e,t?.backgroundFailure);throw i===void 0?r:s(n(r,{driverName:this.driverName},`Database disconnection failed`),i)}t!==void 0&&(e.off(`error`,t.retain),t.backgroundFailure=void 0,this.ownedPoolErrors.delete(e))}async execute(e,t,n,r){return this.executeQuery(e,t,n,r,`execute`)}async executeRaw(e,t,n,r){return this.executeQuery(e,t,n,r,`executeRaw`)}async executeQuery(e,t,n,r,i){let a=r?.operation??i,o=this.readBackgroundPoolFailure(e),s=await e.query({text:t,values:n,types:S}).catch(i=>this.throwPoolQueryFailure(e,o,i,t,n,r));return this.clearBackgroundPoolFailure(e,o),{rows:s.rows,rowCount:v(s.rowCount,s.command,s.rows,{provider:`pg`,operation:a})}}transactionOptionSupport(){return{isolationLevel:`post-begin`,timeout:!0,maxWait:`acquisition`}}async transaction(e,n,i,a){if(`release`in e)throw t(this.driverName);let l=await this.acquirePooledClient(e,i,a?.maxWaitMs),u=holdClientErrors(l),withClientFailure=e=>{let t=u.failure();return t===void 0||t===e?e:s(e,t)},d,queryOrDiscard=async e=>{try{await l.query(e)}catch(e){throw d??=e instanceof Error?e:!0,withClientFailure(e)}};return r({begin:()=>queryOrDiscard(`BEGIN`),callback:async()=>{try{return await n(l)}catch(e){throw withClientFailure(e)}},commit:()=>{let e=u.failure();if(e!==void 0)throw e;return queryOrDiscard(`COMMIT`)},rollback:()=>u.failure()===void 0?queryOrDiscard(`ROLLBACK`):void 0,phases:c(i),close:()=>{try{let e=d??u.failure();if(e){l.release(e);return}l.release()}catch(e){throw super.transactionCleanupFailed(new o(`Driver "pg" could not release an unsafe transaction connection.`,{meta:{driver:`pg`,method:`$transaction`}})),e}finally{u.stop()}}})}transactionCleanupFailed(e){}async pinnedSession(){let e=await this.getClient({operation:`pinnedSession`});if(`release`in e)throw t(this.driverName);let n=await this.acquirePooledClient(e,{operation:`pinnedSession`}),r=holdClientErrors(n);return{session:n,lost:r.failure,release:e=>{try{n.release(r.failure()??(e?!0:void 0))}finally{r.stop()}return Promise.resolve()}}}};function createClient(e){u(e,`pg`,T);let{pool:t,options:n={},pgvector:r,postgis:i,databaseUrl:a}=e;return l(e,new PgDriver({namespace:d(e),migrationSessionAttestation:_(e),pool:t||void 0,options:n,...Object.hasOwn(e,`databaseUrl`)?{databaseUrl:a}:{},pgvector:r,postgis:i}))}export{PgDriver,createClient};
2
2
  //# sourceMappingURL=pg.mjs.map
package/dist/pg.mjs.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"pg.mjs","names":["pgTypes"],"sources":["../src/drivers/pg/index.ts"],"sourcesContent":["/**\n * PostgreSQL Driver (node-postgres)\n *\n * Driver implementation for pg (node-postgres) with connection pooling.\n *\n * No statement pipelining. node-postgres has no pipeline mode: a `Client` holds\n * one query active at a time and drains the rest from an internal queue, so the\n * statements of a transaction always cost one round trip each no matter how\n * they are issued. Nothing here can change that, and nothing here tries to —\n * see the Phase 9 disposition in `docs/architecture/query-performance-plan.md`,\n * which measured the same limit on the postgres.js driver for different\n * reasons.\n */\n\nimport type { DatabaseAdapter } from \"@adapters/database-adapter\";\nimport { PostgresAdapter } from \"@adapters/databases/postgres/postgres-adapter\";\nimport {\n createClientFromDriverConfig,\n type DriverConfig,\n type LinkedClientConfig,\n type NoExtraDriverConfigKeys,\n type VibORMClient,\n} from \"@client/client\";\nimport type { Schema } from \"@client/types\";\nimport { TransactionError, unsupportedVector } from \"@errors\";\nimport { Pool, type PoolClient, type PoolConfig, types as pgTypes } from \"pg\";\nimport { Driver, type QueryExecutionContext } from \"../driver\";\nimport {\n normalizeDriverConnectionError,\n normalizeDriverError,\n} from \"../error-mapping\";\nimport { getExecutionTransactionPhases } from \"../execution-context\";\nimport {\n acquireWithMaxWait,\n type DriverTransactionOptions,\n defineImmutableDriverFact,\n nestedTransactionDispatchError,\n normalizePostgresRowCount,\n type PinnedSessionReservation,\n resolveNamespaceOption,\n runTransactionLifecycle,\n type TransactionOptionSupport,\n withSuppressedFailure,\n} from \"../shared\";\nimport type { QueryResult } from \"../types\";\n\n// DATE (1082) and TIMESTAMP WITHOUT TIME ZONE (1114): pg's default parsers\n// build process-local Dates, shifting the stored value by the process\n// timezone. Return the raw strings instead — the shared result parser builds\n// UTC Dates from them, matching every other driver.\nconst DATE_OID = 1082;\nconst TIMESTAMP_OID = 1114;\nconst identityParser = (value: string) => value;\nconst utcSafeTypes: PoolConfig[\"types\"] = {\n getTypeParser: (oid: number, format?: string) => {\n if (\n [DATE_OID, TIMESTAMP_OID, 1184, 1115, 1182, 1185].includes(oid) &&\n format !== \"binary\"\n ) {\n return identityParser;\n }\n return pgTypes.getTypeParser(oid as never, format as never);\n },\n};\n\ninterface BackgroundPoolFailure {\n readonly error: Error;\n readonly generation: number;\n isAvailable: boolean;\n}\n\ninterface OwnedPoolErrorState {\n backgroundFailure?: BackgroundPoolFailure;\n readonly retain: (error: Error) => void;\n}\n\nfunction createOwnedPoolErrorState(): OwnedPoolErrorState {\n let generation = 0;\n const state: OwnedPoolErrorState = {\n retain(error) {\n generation += 1;\n state.backgroundFailure = { error, generation, isAvailable: true };\n },\n };\n return state;\n}\n\n/**\n * The `error` channel of one checked-out client, owned for as long as VibORM\n * holds that client.\n *\n * pg-pool removes its idle listener on checkout and puts it back on release,\n * so a connection that drops in between (a restart, a failover, a terminated\n * backend) would otherwise emit an unhandled `error` and end the process. The\n * first failure is kept: its holder refuses to commit after it and releases the\n * client with it, so the pool destroys that connection instead of reusing it.\n *\n * This holds for a supplied pool too. Its `error` event stays the caller's, but\n * a checked-out client is the holder's to answer for until it is released.\n */\ninterface HeldClientErrors {\n readonly failure: () => Error | undefined;\n readonly stop: () => void;\n}\n\nfunction holdClientErrors(client: PoolClient): HeldClientErrors {\n let failure: Error | undefined;\n const retain = (error: Error) => {\n failure ??= error;\n };\n client.on(\"error\", retain);\n return {\n failure: () => failure,\n stop: () => {\n client.off(\"error\", retain);\n },\n };\n}\n\n// ============================================================\n// EXPORTED OPTIONS\n// ============================================================\n\nexport type { PoolConfig as PgOptions } from \"pg\";\n\nexport interface PgDriverOptions {\n pool?: Pool;\n options?: PoolConfig;\n pgvector?: boolean;\n postgis?: boolean;\n databaseUrl?: string;\n /** The PostgreSQL schema this driver's persistent objects live in. Defaults to `public`. */\n namespace?: string;\n}\n\nexport type PgClientConfig<C extends DriverConfig> = PgDriverOptions & C;\n\n// ============================================================\n// DRIVER IMPLEMENTATION\n// ============================================================\n\nexport class PgDriver extends Driver<Pool, PoolClient> {\n declare readonly adapter: DatabaseAdapter;\n readonly maxBindParametersPerStatement: number | undefined = 65_535;\n\n /**\n * The EXACT pool the caller supplied, or absent when this driver makes its\n * own. Identity, settled here, is the whole ownership answer: the caller's\n * options object is theirs to change, and a `pool` key deleted after\n * construction used to make `$disconnect()` end a transport VibORM was handed\n * and may be sharing with the caller's own code.\n */\n private readonly suppliedPool: Pool | undefined;\n /**\n * The caller's connection record, copied once.\n *\n * A copy of THIS record, not of what it points at: a nested `ssl` object or\n * stream is the caller's to own, and the keys that decide where a pool\n * connects — host, port, user, database, connectionString — all live here.\n */\n private readonly connectionOptions: PoolConfig;\n /** The caller's `databaseUrl`, read once, for the same reason. */\n private readonly connectionString: string | undefined;\n /**\n * The listener and latest idle failure for each pool this driver created.\n *\n * Pool identity matters after a failed `end()`: the base lifecycle\n * quarantines that exact pool for a later disconnect retry, while this state\n * keeps its error listener and retained evidence attached to the same\n * transport until a proven successful end.\n */\n private readonly ownedPoolErrors = new WeakMap<object, OwnedPoolErrorState>();\n\n constructor(options: PgDriverOptions = {}) {\n super(\"postgresql\", \"pg\");\n const namespace = resolveNamespaceOption(options);\n this.suppliedPool = options.pool;\n this.connectionOptions = { ...options.options };\n this.connectionString = options.databaseUrl;\n\n if (this.suppliedPool) {\n this.client = this.suppliedPool;\n }\n\n const adapter = new PostgresAdapter(namespace, options.postgis === true);\n adapter.capabilities.supportsVector = options.pgvector === true;\n if (!options.pgvector) adapter.vector = unsupportedVector;\n defineImmutableDriverFact(this, \"adapter\", adapter);\n }\n\n /**\n * The pool this driver connects through.\n *\n * A caller's pool is RETURNED rather than replaced: reconnecting after a\n * `$disconnect()` used to build a second pool behind their back — a transport\n * they never asked for, pointed at whatever their options record said by\n * then, and then never closed, because the ownership question was still\n * answered \"supplied\".\n *\n * It is also returned UNSUBSCRIBED. A supplied pool is borrowed transport and\n * its events belong to its owner: an 'error' listener added here is the very\n * thing that stops Node from throwing, so VibORM would be silencing a crash\n * for a caller who never asked it to — and for the other consumers of a pool\n * two estates share. This driver listens only on the pool it made.\n */\n protected initClient(): Promise<Pool> {\n if (this.suppliedPool !== undefined) {\n return Promise.resolve(this.suppliedPool);\n }\n const options: PoolConfig = {\n types: utcSafeTypes,\n ...this.connectionOptions,\n };\n if (this.connectionString !== undefined) {\n options.connectionString ??= this.connectionString;\n }\n const pool = new Pool(options);\n const errorState = createOwnedPoolErrorState();\n this.ownedPoolErrors.set(pool, errorState);\n pool.on(\"error\", errorState.retain);\n return Promise.resolve(pool);\n }\n\n private readBackgroundPoolFailure(\n pool: Pool | PoolClient\n ): BackgroundPoolFailure | undefined {\n return this.ownedPoolErrors.get(pool)?.backgroundFailure;\n }\n\n /** Clear exactly the failure observed before an operation started. */\n private clearBackgroundPoolFailure(\n pool: Pool | PoolClient,\n observed: BackgroundPoolFailure | undefined\n ): boolean {\n if (observed === undefined || !observed.isAvailable) return false;\n observed.isAvailable = false;\n const state = this.ownedPoolErrors.get(pool);\n if (state?.backgroundFailure?.generation === observed.generation) {\n state.backgroundFailure = undefined;\n }\n return true;\n }\n\n /** Claim one retained failure for one failed acquisition, at most once. */\n private consumeBackgroundPoolFailure(\n pool: Pool | PoolClient,\n observed: BackgroundPoolFailure | undefined\n ): Error | undefined {\n if (!this.clearBackgroundPoolFailure(pool, observed)) return undefined;\n return observed?.error;\n }\n\n /** Surface one pool-owned idle failure beside one pool query failure. */\n private throwPoolQueryFailure(\n pool: Pool | PoolClient,\n observed: BackgroundPoolFailure | undefined,\n error: unknown,\n sql: string,\n params: unknown[] | undefined,\n context: QueryExecutionContext | undefined\n ): never {\n const background = this.consumeBackgroundPoolFailure(pool, observed);\n if (background === undefined) throw error;\n const queryFailure = normalizeDriverError(error, {\n driverName: this.driverName,\n dialect: this.dialect,\n model: context?.model,\n operation: context?.operation,\n correlationId: context?.correlationId,\n query: sql,\n params: this.getDiagnosticParameters(params ?? [], context),\n diagnostics: this.getErrorDisclosure(context),\n forceContext: true,\n });\n throw withSuppressedFailure(queryFailure, background);\n }\n\n /**\n * One pooled connection, and — when there is none to be had — the current\n * acquisition failure as primary, with the pool's last background failure\n * retained beside it.\n *\n * The acquisition rejection is the failure of the requested action, so it\n * stays primary. The background report arrived outside every request and is\n * retained through the shared suppressed-failure record. Reported once and\n * released, so the next failure speaks for itself rather than inheriting an\n * explanation that has already been given. An acquisition that fails with\n * nothing retained is left exactly as it was.\n */\n private async acquirePooledClient(\n pool: Pool,\n context: QueryExecutionContext = {},\n maxWaitMs?: number\n ): Promise<PoolClient> {\n const observed = this.readBackgroundPoolFailure(pool);\n let acquisitionSettled = false;\n try {\n const client = await acquireWithMaxWait(\n async () => {\n try {\n const acquired = await pool.connect();\n // This runs even when maxWait has already rejected the caller: a\n // late success healed the pre-start failure before the abandoned\n // client goes straight back to the pool.\n this.clearBackgroundPoolFailure(pool, observed);\n return acquired;\n } finally {\n acquisitionSettled = true;\n }\n },\n (acquired) => acquired.release(),\n maxWaitMs,\n { driverName: this.driverName, form: \"callback\" }\n );\n return client;\n } catch (error) {\n // A maxWait winner abandons the acquisition. Its eventual rejection is\n // observed by acquireWithMaxWait, but it must not consume evidence into\n // a promise whose result no caller will ever inspect.\n if (!acquisitionSettled) throw error;\n const background = this.consumeBackgroundPoolFailure(pool, observed);\n if (background === undefined) throw error;\n const acquisitionFailure = normalizeDriverConnectionError(\n error,\n {\n driverName: this.driverName,\n model: context.model,\n operation: context.operation,\n correlationId: context.correlationId,\n diagnostics: this.getErrorDisclosure(context),\n },\n \"Database connection failed after the pool reported a background failure\"\n );\n throw withSuppressedFailure(acquisitionFailure, background);\n }\n }\n\n /**\n * A supplied pool belongs to the caller, who may be sharing it with other\n * clients — two schema-scoped estates over one pool is the documented shape\n * — and §5.3's rule is that VibORM never changes a caller's connection\n * state. `$disconnect()` used to end it regardless, so disconnecting one\n * client tore down every other consumer of that pool.\n *\n * The test is on the pool's IDENTITY against what construction captured, so\n * it answers for the pool actually being closed rather than for whatever the\n * caller's record says now: every pool this driver made is ended, and the one\n * it was handed never is.\n */\n protected async closeClient(pool: Pool): Promise<void> {\n if (pool === this.suppliedPool) {\n return;\n }\n const errorState = this.ownedPoolErrors.get(pool);\n try {\n await pool.end();\n } catch (error) {\n const background = this.consumeBackgroundPoolFailure(\n pool,\n errorState?.backgroundFailure\n );\n if (background === undefined) throw error;\n const disconnectFailure = normalizeDriverConnectionError(\n error,\n { driverName: this.driverName },\n \"Database disconnection failed\"\n );\n throw withSuppressedFailure(disconnectFailure, background);\n }\n // AFTER a proven end, not before it: `end()` disposes idle clients whose\n // own listeners can still re-emit on the pool. If end rejects, the still\n // live pool keeps containment; its pre-start evidence travels on the public\n // disconnect failure, exactly once.\n if (errorState !== undefined) {\n pool.off(\"error\", errorState.retain);\n errorState.backgroundFailure = undefined;\n this.ownedPoolErrors.delete(pool);\n }\n }\n\n protected async execute<T>(\n client: Pool | PoolClient,\n sql: string,\n params: unknown[],\n context?: QueryExecutionContext\n ): Promise<QueryResult<T>> {\n const operation = context?.operation ?? \"execute\";\n const observed = this.readBackgroundPoolFailure(client);\n const result = await client\n .query({ text: sql, values: params, types: utcSafeTypes })\n .catch((error: unknown) =>\n this.throwPoolQueryFailure(\n client,\n observed,\n error,\n sql,\n params,\n context\n )\n );\n // `Pool.query` includes an acquisition. Its success proves transport\n // recovery, but only for evidence that predates this exact operation.\n this.clearBackgroundPoolFailure(client, observed);\n return {\n rows: result.rows,\n rowCount: normalizePostgresRowCount(\n result.rowCount,\n result.command,\n result.rows,\n { provider: \"pg\", operation }\n ),\n };\n }\n\n protected async executeRaw<T>(\n client: Pool | PoolClient,\n sql: string,\n params: unknown[] | undefined,\n context?: QueryExecutionContext\n ): Promise<QueryResult<T>> {\n const operation = context?.operation ?? \"executeRaw\";\n const observed = this.readBackgroundPoolFailure(client);\n const result = await client\n .query({ text: sql, values: params, types: utcSafeTypes })\n .catch((error: unknown) =>\n this.throwPoolQueryFailure(\n client,\n observed,\n error,\n sql,\n params,\n context\n )\n );\n this.clearBackgroundPoolFailure(client, observed);\n return {\n rows: result.rows,\n rowCount: normalizePostgresRowCount(\n result.rowCount,\n result.command,\n result.rows,\n { provider: \"pg\", operation }\n ),\n };\n }\n\n /**\n * PostgreSQL takes the isolation level as the first statement inside the\n * transaction, and node-postgres hands out a pooled client we can wait for\n * with a bound (and release if we stop waiting).\n */\n protected override transactionOptionSupport(): TransactionOptionSupport {\n return {\n isolationLevel: \"post-begin\",\n timeout: true,\n maxWait: \"acquisition\",\n };\n }\n\n protected async transaction<T>(\n client: Pool | PoolClient,\n fn: (tx: PoolClient) => Promise<T>,\n context?: QueryExecutionContext,\n options?: DriverTransactionOptions\n ): Promise<T> {\n if (\"release\" in client) {\n throw nestedTransactionDispatchError(this.driverName);\n }\n\n // Start a new transaction\n const pool = client as Pool;\n const poolClient = await this.acquirePooledClient(\n pool,\n context,\n options?.maxWaitMs\n );\n const clientErrors = holdClientErrors(poolClient);\n // A step's own failure stays primary; a different client failure travels\n // beside it through the shared evidence owner instead of being lost.\n const withClientFailure = (error: unknown): unknown => {\n const failure = clientErrors.failure();\n return failure === undefined || failure === error\n ? error\n : withSuppressedFailure(error, failure);\n };\n let releaseError: Error | boolean | undefined;\n const queryOrDiscard = async (statement: string) => {\n try {\n await poolClient.query(statement);\n } catch (error) {\n releaseError ??= error instanceof Error ? error : true;\n throw withClientFailure(error);\n }\n };\n return runTransactionLifecycle({\n begin: () => queryOrDiscard(\"BEGIN\"),\n callback: async () => {\n try {\n return await fn(poolClient);\n } catch (error) {\n throw withClientFailure(error);\n }\n },\n commit: () => {\n // A callback that settles after its connection failed must not commit:\n // whatever it awaited meanwhile never reached the database.\n const failure = clientErrors.failure();\n if (failure !== undefined) throw failure;\n return queryOrDiscard(\"COMMIT\");\n },\n // The server ends a transaction with its session; a ROLLBACK sent on a\n // client that is no longer queryable would only add a second failure.\n rollback: () =>\n clientErrors.failure() === undefined\n ? queryOrDiscard(\"ROLLBACK\")\n : undefined,\n phases: getExecutionTransactionPhases(context),\n close: () => {\n try {\n const discard = releaseError ?? clientErrors.failure();\n if (discard) {\n poolClient.release(discard);\n return;\n }\n poolClient.release();\n } catch (error) {\n super.transactionCleanupFailed(\n new TransactionError(\n 'Driver \"pg\" could not release an unsafe transaction connection.',\n { meta: { driver: \"pg\", method: \"$transaction\" } }\n )\n );\n throw error;\n } finally {\n clientErrors.stop();\n }\n },\n });\n }\n\n protected override transactionCleanupFailed(_error: Error): void {\n // The failed PoolClient was discarded with release(error); the pool stays usable.\n }\n\n /**\n * One `PoolClient` from `pool.connect()` — plan §3.5's pinned producer for\n * `pg`. `release(true)` destroys the connection instead of returning it, so a\n * session whose advisory-lock state is unknown never re-enters the pool.\n */\n protected override async pinnedSession(): Promise<\n PinnedSessionReservation<Pool | PoolClient>\n > {\n const client = await this.getClient({ operation: \"pinnedSession\" });\n if (\"release\" in client) {\n throw nestedTransactionDispatchError(this.driverName);\n }\n const poolClient = await this.acquirePooledClient(client, {\n operation: \"pinnedSession\",\n });\n const clientErrors = holdClientErrors(poolClient);\n return {\n session: poolClient,\n release: (discard) => {\n try {\n poolClient.release(\n clientErrors.failure() ?? (discard ? true : undefined)\n );\n } finally {\n clientErrors.stop();\n }\n return Promise.resolve();\n },\n };\n }\n}\n\n// ============================================================\n// CONVENIENCE FUNCTION\n// ============================================================\n\nexport function createClient<S extends Schema, C extends DriverConfig<S>>(\n config: PgClientConfig<C> &\n DriverConfig<S> &\n NoExtraDriverConfigKeys<C, PgDriverOptions, S>\n): VibORMClient<{\n [P in keyof LinkedClientConfig<C & { driver: PgDriver }>]: LinkedClientConfig<\n C & { driver: PgDriver }\n >[P];\n}> {\n const { pool, options = {}, pgvector, postgis, databaseUrl } = config;\n const namespace = resolveNamespaceOption(config);\n\n // The caller's `options` record is theirs: the connection string goes on a\n // copy this wrapper owns.\n const driverOptions: PgDriverOptions = {\n options:\n databaseUrl === undefined\n ? options\n : { ...options, connectionString: databaseUrl },\n };\n if (pool) driverOptions.pool = pool;\n if (pgvector !== undefined) driverOptions.pgvector = pgvector;\n if (postgis !== undefined) driverOptions.postgis = postgis;\n if (namespace !== undefined) driverOptions.namespace = namespace;\n\n const driver = new PgDriver(driverOptions);\n\n return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O,CAOd,MANA,MAAM,yBACJ,IAAI,EACF,kEACA,CAAE,KAAM,CAAE,OAAQ,KAAM,OAAQ,eAAgB,CAAE,CACnD,CACF,CACK,SACE,CACR,EAAa,MAAM,GAGxB,CAAC,CAGJ,yBAA4C,EAAqB,EASjE,MAAyB,eAEvB,CACA,IAAM,EAAS,MAAM,KAAK,UAAU,CAAE,UAAW,gBAAiB,CAAC,CACnE,GAAI,YAAa,EACf,MAAM,EAA+B,KAAK,WAAW,CAEvD,IAAM,EAAa,MAAM,KAAK,oBAAoB,EAAQ,CACxD,UAAW,gBACZ,CAAC,CACI,EAAe,iBAAiB,EAAW,CACjD,MAAO,CACL,QAAS,EACT,QAAU,GAAY,CACpB,GAAI,CACF,EAAW,QACT,EAAa,SAAS,GAAK,EAAU,GAAO,IAAA,IAC7C,QACO,CACR,EAAa,MAAM,CAErB,OAAO,QAAQ,SAAS,EAE3B,GAQL,SAAgB,aACd,EAOC,CACD,GAAM,CAAE,OAAM,UAAU,EAAE,CAAE,WAAU,UAAS,eAAgB,EACzD,EAAY,EAAuB,EAAO,CAI1C,EAAiC,CACrC,QACE,IAAgB,IAAA,GACZ,EACA,CAAE,GAAG,EAAS,iBAAkB,EAAa,CACpD,CAQD,OAPI,IAAM,EAAc,KAAO,GAC3B,IAAa,IAAA,KAAW,EAAc,SAAW,GACjD,IAAY,IAAA,KAAW,EAAc,QAAU,GAC/C,IAAc,IAAA,KAAW,EAAc,UAAY,GAIhD,EAA6C,EAFrC,IAAI,SAAS,EAAc,CAEyB"}
1
+ {"version":3,"file":"pg.mjs","names":["pgTypes"],"sources":["../src/drivers/pg/index.ts"],"sourcesContent":["/**\n * PostgreSQL Driver (node-postgres)\n *\n * Driver implementation for pg (node-postgres) with connection pooling.\n *\n * No statement pipelining. node-postgres has no pipeline mode: a `Client` holds\n * one query active at a time and drains the rest from an internal queue, so the\n * statements of a transaction always cost one round trip each no matter how\n * they are issued. Nothing here can change that, and nothing here tries to —\n * see the Phase 9 disposition in `docs/architecture/query-performance-plan.md`,\n * which measured the same limit on the postgres.js driver for different\n * reasons.\n */\n\nimport type { DatabaseAdapter } from \"@adapters/database-adapter\";\nimport {\n createClientFromDriverConfig,\n type DriverConfig,\n type LinkedClientConfig,\n type NoExtraDriverConfigKeys,\n type VibORMClient,\n} from \"@client/client\";\nimport type { Schema } from \"@client/types\";\nimport { ClientInitializationError, TransactionError } from \"@errors\";\nimport { Pool, type PoolClient, type PoolConfig, types as pgTypes } from \"pg\";\nimport {\n Driver,\n type MigrationSessionAttestation,\n type QueryExecutionContext,\n} from \"../driver\";\nimport {\n normalizeDriverConnectionError,\n normalizeDriverError,\n} from \"../error-mapping\";\nimport { getExecutionTransactionPhases } from \"../execution-context\";\nimport {\n acquireWithMaxWait,\n type DriverTransactionOptions,\n defineImmutableDriverFact,\n nestedTransactionDispatchError,\n normalizePostgresRowCount,\n type PinnedSessionReservation,\n resolveMigrationSessionAttestationOption,\n resolveNamespaceOption,\n runTransactionLifecycle,\n type TransactionOptionSupport,\n withSuppressedFailure,\n} from \"../shared\";\nimport {\n refuseEmptyDatabaseUrl,\n refuseUnknownDriverConfigKeys,\n systemRootAsVerifyFull,\n} from \"../shared/driver-options\";\nimport { installPostgresAdapter } from \"../shared/postgres-adapter\";\nimport type { QueryResult } from \"../types\";\n\n// DATE (1082) and TIMESTAMP WITHOUT TIME ZONE (1114): pg's default parsers\n// build process-local Dates, shifting the stored value by the process\n// timezone. Return the raw strings instead — the shared result parser builds\n// UTC Dates from them, matching every other driver.\nconst DATE_OID = 1082;\nconst TIMESTAMP_OID = 1114;\nconst identityParser = (value: string) => value;\nconst utcSafeTypes: PoolConfig[\"types\"] = {\n getTypeParser: (oid: number, format?: string) => {\n if (\n [DATE_OID, TIMESTAMP_OID, 1184, 1115, 1182, 1185].includes(oid) &&\n format !== \"binary\"\n ) {\n return identityParser;\n }\n return pgTypes.getTypeParser(oid as never, format as never);\n },\n};\n\ninterface BackgroundPoolFailure {\n readonly error: Error;\n readonly generation: number;\n isAvailable: boolean;\n}\n\ninterface OwnedPoolErrorState {\n backgroundFailure?: BackgroundPoolFailure;\n readonly retain: (error: Error) => void;\n}\n\nfunction createOwnedPoolErrorState(): OwnedPoolErrorState {\n let generation = 0;\n const state: OwnedPoolErrorState = {\n retain(error) {\n generation += 1;\n state.backgroundFailure = { error, generation, isAvailable: true };\n },\n };\n return state;\n}\n\n/**\n * The `error` channel of one checked-out client, owned for as long as VibORM\n * holds that client.\n *\n * pg-pool removes its idle listener on checkout and puts it back on release,\n * so a connection that drops in between (a restart, a failover, a terminated\n * backend) would otherwise emit an unhandled `error` and end the process. The\n * first failure is kept: its holder refuses to commit after it and releases the\n * client with it, so the pool destroys that connection instead of reusing it.\n *\n * This holds for a supplied pool too. Its `error` event stays the caller's, but\n * a checked-out client is the holder's to answer for until it is released.\n */\ninterface HeldClientErrors {\n readonly failure: () => Error | undefined;\n readonly stop: () => void;\n}\n\nfunction holdClientErrors(client: PgPoolClient): HeldClientErrors {\n let failure: Error | undefined;\n const retain = (error: Error) => {\n failure ??= error;\n };\n client.on(\"error\", retain);\n return {\n failure: () => failure,\n stop: () => {\n client.off(\"error\", retain);\n },\n };\n}\n\n/** The keys node-postgres's URL parser reads from the query before the authority. */\nconst URL_QUERY_KEYS = new Set([\"user\", \"password\", \"host\", \"port\"]);\n/** The query parameters node-postgres derives `ssl` from. */\nconst URL_SSL_KEYS = [\"sslmode\", \"sslcert\", \"sslkey\", \"sslrootcert\"];\n\n/**\n * The pool's connection record: the caller's options, with `databaseUrl` as\n * the connection string unless `options.connectionString` names one, and each\n * connection option they set written into that URL so that it wins.\n *\n * node-postgres parses the connection string over the options beside it and\n * fills the connection keys the URL lacks with empty values, so a per-tenant\n * URL without a password lost `options.password` from a secret, and the URL's\n * port replaced `options.port`. Its parser prefers `user`, `password`, `host`\n * and `port` from the query and reads the database from the path, so an\n * explicit key is written there; any other option the query also names is\n * dropped from it, and an explicit `ssl` drops the parameters that derive one.\n * A password callback cannot be written into a URL, and node-postgres would\n * replace it with the URL's password, so one beside a URL is refused.\n */\nfunction connectionRecord(\n options: PoolConfig,\n databaseUrl: string | undefined\n): PoolConfig {\n const given = options.connectionString ?? databaseUrl;\n if (!given) return options;\n if (typeof options.password === \"function\") {\n throw new ClientInitializationError(\n 'Driver \"pg\" cannot keep a password callback beside a connection URL: node-postgres reads the password from the URL. Pass `host`, `user` and `database` in `options` instead.',\n { meta: { driver: \"pg\", operation: \"configuration\" } }\n );\n }\n const connectionString = systemRootAsVerifyFull(given);\n let url: URL | undefined;\n try {\n url = new URL(connectionString);\n } catch {\n url = undefined;\n }\n const entries: [string, unknown][] = Object.entries(options);\n const overrides = entries.filter(\n ([key, value]) =>\n value !== undefined &&\n (URL_QUERY_KEYS.has(key) ||\n key === \"database\" ||\n key === \"ssl\" ||\n (key !== \"connectionString\" && url?.searchParams.has(key)))\n );\n if (overrides.length === 0) return { ...options, connectionString };\n if (url === undefined) {\n throw new ClientInitializationError(\n 'Driver \"pg\" could not read its connection URL to apply the connection options beside it.',\n { meta: { driver: \"pg\", operation: \"configuration\" } }\n );\n }\n for (const [key, value] of overrides) {\n url.searchParams.delete(key);\n if (key === \"ssl\") {\n for (const sslKey of URL_SSL_KEYS) url.searchParams.delete(sslKey);\n } else if (key === \"database\") {\n url.pathname = `/${String(value)}`;\n } else if (\n URL_QUERY_KEYS.has(key) &&\n (typeof value === \"string\" || typeof value === \"number\")\n ) {\n url.searchParams.set(key, String(value));\n }\n }\n return { ...options, connectionString: url.href };\n}\n\n// ============================================================\n// EXPORTED OPTIONS\n// ============================================================\n\nexport type { PoolConfig as PgOptions } from \"pg\";\n\ninterface PgErrorEvents {\n on(event: \"error\", listener: (error: Error) => void): unknown;\n off(event: \"error\", listener: (error: Error) => void): unknown;\n}\n\n/** The part of a node-postgres `PoolClient` this driver uses. */\ninterface PgPoolClient\n extends Pick<PoolClient, \"query\" | \"release\">,\n PgErrorEvents {}\n\n/**\n * The part of a node-postgres `Pool` this driver uses, so any pool with that\n * shape is accepted. A Neon WebSocket `Pool` (`@neondatabase/serverless`) is\n * node-postgres's pool over a WebSocket and runs here unchanged, but its\n * bundled copy of the pg declarations lags `@types/pg`: in 8.23 a\n * `PoolClient` is a whole `Client`, and the full `Pool` type refused Neon's.\n */\ninterface PgPool extends Pick<Pool, \"query\" | \"end\">, PgErrorEvents {\n connect(): Promise<PgPoolClient>;\n}\n\nexport interface PgDriverOptions {\n pool?: PgPool;\n options?: PoolConfig;\n pgvector?: boolean;\n postgis?: boolean;\n databaseUrl?: string;\n /** The PostgreSQL schema this driver's persistent objects live in. Defaults to `public`. */\n namespace?: string;\n /**\n * Your claim, at your risk, that every connection this pool opens is one\n * server session for its whole life. It lifts migrations' refusal of\n * Cloudflare Hyperdrive and Neon `-pooler` hosts; application queries never\n * need it.\n */\n migrationSessionAttestation?: MigrationSessionAttestation;\n}\n\nexport type PgClientConfig<C extends DriverConfig> = PgDriverOptions & C;\n\nconst PG_CONFIG_KEYS: Record<keyof PgDriverOptions, true> = {\n pool: true,\n options: true,\n pgvector: true,\n postgis: true,\n databaseUrl: true,\n namespace: true,\n migrationSessionAttestation: true,\n};\n\n// ============================================================\n// DRIVER IMPLEMENTATION\n// ============================================================\n\nexport class PgDriver extends Driver<PgPool, PgPoolClient> {\n declare readonly adapter: DatabaseAdapter;\n readonly maxBindParametersPerStatement: number | undefined = 65_535;\n\n /**\n * The EXACT pool the caller supplied, or absent when this driver makes its\n * own. Identity, settled here, is the whole ownership answer: the caller's\n * options object is theirs to change, and a `pool` key deleted after\n * construction used to make `$disconnect()` end a transport VibORM was handed\n * and may be sharing with the caller's own code.\n */\n private readonly suppliedPool: PgPool | undefined;\n /**\n * The caller's connection record, copied once.\n *\n * A copy of THIS record, not of what it points at: a nested `ssl` object or\n * stream is the caller's to own, and the keys that decide where a pool\n * connects — host, port, user, database, connectionString — all live here,\n * with the caller's `databaseUrl` merged in (see `connectionRecord`).\n */\n private readonly connectionOptions: PoolConfig;\n /**\n * The listener and latest idle failure for each pool this driver created.\n *\n * Pool identity matters after a failed `end()`: the base lifecycle\n * quarantines that exact pool for a later disconnect retry, while this state\n * keeps its error listener and retained evidence attached to the same\n * transport until a proven successful end.\n */\n private readonly ownedPoolErrors = new WeakMap<object, OwnedPoolErrorState>();\n\n constructor(options: PgDriverOptions = {}) {\n super(\"postgresql\", \"pg\");\n const namespace = resolveNamespaceOption(options);\n this.suppliedPool = options.pool;\n const connection = { ...options.options };\n refuseEmptyDatabaseUrl(\n \"pg\",\n options,\n Boolean(\n this.suppliedPool || connection.host || connection.connectionString\n )\n );\n this.connectionOptions = connectionRecord(connection, options.databaseUrl);\n\n if (this.suppliedPool) {\n this.client = this.suppliedPool;\n }\n\n installPostgresAdapter(this, namespace, options);\n defineImmutableDriverFact(\n this,\n \"migrationSessionAttestation\",\n resolveMigrationSessionAttestationOption(options)\n );\n }\n\n /** Every host or URL this driver's pool connects through, for migration admission. */\n protected override migrationSessionEndpoints(): readonly unknown[] {\n const supplied: unknown = this.suppliedPool\n ? Reflect.get(this.suppliedPool, \"options\")\n : undefined;\n const pool =\n typeof supplied === \"object\" && supplied !== null ? supplied : {};\n return [\n this.connectionOptions.host,\n this.connectionOptions.connectionString,\n Reflect.get(pool, \"host\"),\n Reflect.get(pool, \"connectionString\"),\n ];\n }\n\n /**\n * The pool this driver connects through.\n *\n * A caller's pool is RETURNED rather than replaced: reconnecting after a\n * `$disconnect()` used to build a second pool behind their back — a transport\n * they never asked for, pointed at whatever their options record said by\n * then, and then never closed, because the ownership question was still\n * answered \"supplied\".\n *\n * It is also returned UNSUBSCRIBED. A supplied pool is borrowed transport and\n * its events belong to its owner: an 'error' listener added here is the very\n * thing that stops Node from throwing, so VibORM would be silencing a crash\n * for a caller who never asked it to — and for the other consumers of a pool\n * two estates share. This driver listens only on the pool it made.\n */\n protected initClient(): Promise<PgPool> {\n if (this.suppliedPool !== undefined) {\n return Promise.resolve(this.suppliedPool);\n }\n const pool = new Pool({ types: utcSafeTypes, ...this.connectionOptions });\n const errorState = createOwnedPoolErrorState();\n this.ownedPoolErrors.set(pool, errorState);\n pool.on(\"error\", errorState.retain);\n return Promise.resolve(pool);\n }\n\n private readBackgroundPoolFailure(\n pool: PgPool | PgPoolClient\n ): BackgroundPoolFailure | undefined {\n return this.ownedPoolErrors.get(pool)?.backgroundFailure;\n }\n\n /** Clear exactly the failure observed before an operation started. */\n private clearBackgroundPoolFailure(\n pool: PgPool | PgPoolClient,\n observed: BackgroundPoolFailure | undefined\n ): boolean {\n if (observed === undefined || !observed.isAvailable) return false;\n observed.isAvailable = false;\n const state = this.ownedPoolErrors.get(pool);\n if (state?.backgroundFailure?.generation === observed.generation) {\n state.backgroundFailure = undefined;\n }\n return true;\n }\n\n /** Claim one retained failure for one failed acquisition, at most once. */\n private consumeBackgroundPoolFailure(\n pool: PgPool | PgPoolClient,\n observed: BackgroundPoolFailure | undefined\n ): Error | undefined {\n if (!this.clearBackgroundPoolFailure(pool, observed)) return undefined;\n return observed?.error;\n }\n\n /** Surface one pool-owned idle failure beside one pool query failure. */\n private throwPoolQueryFailure(\n pool: PgPool | PgPoolClient,\n observed: BackgroundPoolFailure | undefined,\n error: unknown,\n sql: string,\n params: unknown[] | undefined,\n context: QueryExecutionContext | undefined\n ): never {\n const background = this.consumeBackgroundPoolFailure(pool, observed);\n if (background === undefined) throw error;\n const queryFailure = normalizeDriverError(error, {\n driverName: this.driverName,\n dialect: this.dialect,\n model: context?.model,\n operation: context?.operation,\n correlationId: context?.correlationId,\n query: sql,\n params: this.getDiagnosticParameters(params ?? [], context),\n diagnostics: this.getErrorDisclosure(context),\n forceContext: true,\n });\n throw withSuppressedFailure(queryFailure, background);\n }\n\n /**\n * One pooled connection, and — when there is none to be had — the current\n * acquisition failure as primary, with the pool's last background failure\n * retained beside it.\n *\n * The acquisition rejection is the failure of the requested action, so it\n * stays primary. The background report arrived outside every request and is\n * retained through the shared suppressed-failure record. Reported once and\n * released, so the next failure speaks for itself rather than inheriting an\n * explanation that has already been given. An acquisition that fails with\n * nothing retained is left exactly as it was.\n */\n private async acquirePooledClient(\n pool: PgPool,\n context: QueryExecutionContext = {},\n maxWaitMs?: number\n ): Promise<PgPoolClient> {\n const observed = this.readBackgroundPoolFailure(pool);\n let acquisitionSettled = false;\n try {\n const client = await acquireWithMaxWait(\n async () => {\n try {\n const acquired = await pool.connect();\n // This runs even when maxWait has already rejected the caller: a\n // late success healed the pre-start failure before the abandoned\n // client goes straight back to the pool.\n this.clearBackgroundPoolFailure(pool, observed);\n return acquired;\n } finally {\n acquisitionSettled = true;\n }\n },\n (acquired) => acquired.release(),\n maxWaitMs,\n { driverName: this.driverName, form: \"callback\" }\n );\n return client;\n } catch (error) {\n // A maxWait winner abandons the acquisition. Its eventual rejection is\n // observed by acquireWithMaxWait, but it must not consume evidence into\n // a promise whose result no caller will ever inspect.\n if (!acquisitionSettled) throw error;\n const background = this.consumeBackgroundPoolFailure(pool, observed);\n if (background === undefined) throw error;\n const acquisitionFailure = normalizeDriverConnectionError(\n error,\n {\n driverName: this.driverName,\n model: context.model,\n operation: context.operation,\n correlationId: context.correlationId,\n diagnostics: this.getErrorDisclosure(context),\n },\n \"Database connection failed after the pool reported a background failure\"\n );\n throw withSuppressedFailure(acquisitionFailure, background);\n }\n }\n\n /**\n * A supplied pool belongs to the caller, who may be sharing it with other\n * clients — two schema-scoped estates over one pool is the documented shape\n * — and §5.3's rule is that VibORM never changes a caller's connection\n * state. `$disconnect()` used to end it regardless, so disconnecting one\n * client tore down every other consumer of that pool.\n *\n * The test is on the pool's IDENTITY against what construction captured, so\n * it answers for the pool actually being closed rather than for whatever the\n * caller's record says now: every pool this driver made is ended, and the one\n * it was handed never is.\n */\n protected async closeClient(pool: PgPool): Promise<void> {\n if (pool === this.suppliedPool) {\n return;\n }\n const errorState = this.ownedPoolErrors.get(pool);\n try {\n await pool.end();\n } catch (error) {\n const background = this.consumeBackgroundPoolFailure(\n pool,\n errorState?.backgroundFailure\n );\n if (background === undefined) throw error;\n const disconnectFailure = normalizeDriverConnectionError(\n error,\n { driverName: this.driverName },\n \"Database disconnection failed\"\n );\n throw withSuppressedFailure(disconnectFailure, background);\n }\n // AFTER a proven end, not before it: `end()` disposes idle clients whose\n // own listeners can still re-emit on the pool. If end rejects, the still\n // live pool keeps containment; its pre-start evidence travels on the public\n // disconnect failure, exactly once.\n if (errorState !== undefined) {\n pool.off(\"error\", errorState.retain);\n errorState.backgroundFailure = undefined;\n this.ownedPoolErrors.delete(pool);\n }\n }\n\n protected async execute<T>(\n client: PgPool | PgPoolClient,\n sql: string,\n params: unknown[],\n context?: QueryExecutionContext\n ): Promise<QueryResult<T>> {\n return this.executeQuery(client, sql, params, context, \"execute\");\n }\n\n protected async executeRaw<T>(\n client: PgPool | PgPoolClient,\n sql: string,\n params: unknown[] | undefined,\n context?: QueryExecutionContext\n ): Promise<QueryResult<T>> {\n return this.executeQuery(client, sql, params, context, \"executeRaw\");\n }\n\n private async executeQuery<T>(\n client: PgPool | PgPoolClient,\n sql: string,\n params: unknown[] | undefined,\n context: QueryExecutionContext | undefined,\n fallbackOperation: \"execute\" | \"executeRaw\"\n ): Promise<QueryResult<T>> {\n const operation = context?.operation ?? fallbackOperation;\n const observed = this.readBackgroundPoolFailure(client);\n const result = await client\n .query({ text: sql, values: params, types: utcSafeTypes })\n .catch((error: unknown) =>\n this.throwPoolQueryFailure(\n client,\n observed,\n error,\n sql,\n params,\n context\n )\n );\n // `Pool.query` includes an acquisition. Its success proves transport\n // recovery, but only for evidence that predates this exact operation.\n this.clearBackgroundPoolFailure(client, observed);\n return {\n rows: result.rows,\n rowCount: normalizePostgresRowCount(\n result.rowCount,\n result.command,\n result.rows,\n { provider: \"pg\", operation }\n ),\n };\n }\n\n /**\n * PostgreSQL takes the isolation level as the first statement inside the\n * transaction, and node-postgres hands out a pooled client we can wait for\n * with a bound (and release if we stop waiting).\n */\n protected override transactionOptionSupport(): TransactionOptionSupport {\n return {\n isolationLevel: \"post-begin\",\n timeout: true,\n maxWait: \"acquisition\",\n };\n }\n\n protected async transaction<T>(\n client: PgPool | PgPoolClient,\n fn: (tx: PgPoolClient) => Promise<T>,\n context?: QueryExecutionContext,\n options?: DriverTransactionOptions\n ): Promise<T> {\n if (\"release\" in client) {\n throw nestedTransactionDispatchError(this.driverName);\n }\n\n // Start a new transaction\n const poolClient = await this.acquirePooledClient(\n client,\n context,\n options?.maxWaitMs\n );\n const clientErrors = holdClientErrors(poolClient);\n // A step's own failure stays primary; a different client failure travels\n // beside it through the shared evidence owner instead of being lost.\n const withClientFailure = (error: unknown): unknown => {\n const failure = clientErrors.failure();\n return failure === undefined || failure === error\n ? error\n : withSuppressedFailure(error, failure);\n };\n let releaseError: Error | boolean | undefined;\n const queryOrDiscard = async (statement: string) => {\n try {\n await poolClient.query(statement);\n } catch (error) {\n releaseError ??= error instanceof Error ? error : true;\n throw withClientFailure(error);\n }\n };\n return runTransactionLifecycle({\n begin: () => queryOrDiscard(\"BEGIN\"),\n callback: async () => {\n try {\n return await fn(poolClient);\n } catch (error) {\n throw withClientFailure(error);\n }\n },\n commit: () => {\n // A callback that settles after its connection failed must not commit:\n // whatever it awaited meanwhile never reached the database.\n const failure = clientErrors.failure();\n if (failure !== undefined) throw failure;\n return queryOrDiscard(\"COMMIT\");\n },\n // The server ends a transaction with its session; a ROLLBACK sent on a\n // client that is no longer queryable would only add a second failure.\n rollback: () =>\n clientErrors.failure() === undefined\n ? queryOrDiscard(\"ROLLBACK\")\n : undefined,\n phases: getExecutionTransactionPhases(context),\n close: () => {\n try {\n const discard = releaseError ?? clientErrors.failure();\n if (discard) {\n poolClient.release(discard);\n return;\n }\n poolClient.release();\n } catch (error) {\n super.transactionCleanupFailed(\n new TransactionError(\n 'Driver \"pg\" could not release an unsafe transaction connection.',\n { meta: { driver: \"pg\", method: \"$transaction\" } }\n )\n );\n throw error;\n } finally {\n clientErrors.stop();\n }\n },\n });\n }\n\n protected override transactionCleanupFailed(_error: Error): void {\n // The failed PoolClient was discarded with release(error); the pool stays usable.\n }\n\n /**\n * One `PoolClient` from `pool.connect()` — plan §3.5's pinned producer for\n * `pg`. `release(true)` destroys the connection instead of returning it, so a\n * session whose advisory-lock state is unknown never re-enters the pool.\n */\n protected override async pinnedSession(): Promise<\n PinnedSessionReservation<PgPool | PgPoolClient>\n > {\n const client = await this.getClient({ operation: \"pinnedSession\" });\n if (\"release\" in client) {\n throw nestedTransactionDispatchError(this.driverName);\n }\n const poolClient = await this.acquirePooledClient(client, {\n operation: \"pinnedSession\",\n });\n const clientErrors = holdClientErrors(poolClient);\n return {\n session: poolClient,\n // The client's own `error` event is how pg reports a socket that died\n // between or under statements; the pinned session then sends nothing\n // more on it (plan S2). Release destroys it either way.\n lost: clientErrors.failure,\n release: (discard) => {\n try {\n poolClient.release(\n clientErrors.failure() ?? (discard ? true : undefined)\n );\n } finally {\n clientErrors.stop();\n }\n return Promise.resolve();\n },\n };\n }\n}\n\n// ============================================================\n// CONVENIENCE FUNCTION\n// ============================================================\n\nexport function createClient<S extends Schema, C extends DriverConfig<S>>(\n config: PgClientConfig<C> &\n DriverConfig<S> &\n NoExtraDriverConfigKeys<C, PgDriverOptions, S>\n): VibORMClient<{\n [P in keyof LinkedClientConfig<C & { driver: PgDriver }>]: LinkedClientConfig<\n C & { driver: PgDriver }\n >[P];\n}> {\n refuseUnknownDriverConfigKeys(config, \"pg\", PG_CONFIG_KEYS);\n const { pool, options = {}, pgvector, postgis, databaseUrl } = config;\n const driver = new PgDriver({\n // Namespace, then attestation: the order a refusal reports in.\n namespace: resolveNamespaceOption(config),\n migrationSessionAttestation:\n resolveMigrationSessionAttestationOption(config),\n // Only a supplied pool counts: a falsy one leaves the driver to build its own.\n pool: pool || undefined,\n options,\n // Present even when undefined: the driver refuses an empty one (parity-18).\n ...(Object.hasOwn(config, \"databaseUrl\") ? { databaseUrl } : {}),\n pgvector,\n postgis,\n });\n\n return createClientFromDriverConfig<S, C, PgDriver>(config, driver);\n}\n"],"mappings":"yjBA4DA,MAEM,eAAkB,GAAkB,EACpC,EAAoC,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ACE,CACR,EAAa,MAAM,GAGxB,CAAC,CAGJ,yBAA4C,EAAqB,EASjE,MAAyB,eAEvB,CACA,IAAM,EAAS,MAAM,KAAK,UAAU,CAAE,UAAW,gBAAiB,CAAC,CACnE,GAAI,YAAa,EACf,MAAM,EAA+B,KAAK,WAAW,CAEvD,IAAM,EAAa,MAAM,KAAK,oBAAoB,EAAQ,CACxD,UAAW,gBACZ,CAAC,CACI,EAAe,iBAAiB,EAAW,CACjD,MAAO,CACL,QAAS,EAIT,KAAM,EAAa,QACnB,QAAU,GAAY,CACpB,GAAI,CACF,EAAW,QACT,EAAa,SAAS,GAAK,EAAU,GAAO,IAAA,IAC7C,QACO,CACR,EAAa,MAAM,CAErB,OAAO,QAAQ,SAAS,EAE3B,GAQL,SAAgB,aACd,EAOC,CACD,EAA8B,EAAQ,KAAM,EAAe,CAC3D,GAAM,CAAE,OAAM,UAAU,EAAE,CAAE,WAAU,UAAS,eAAgB,EAe/D,OAAO,EAA6C,EAdrC,IAAI,SAAS,CAE1B,UAAW,EAAuB,EAAO,CACzC,4BACE,EAAyC,EAAO,CAElD,KAAM,GAAQ,IAAA,GACd,UAEA,GAAI,OAAO,OAAO,EAAQ,cAAc,CAAG,CAAE,cAAa,CAAG,EAAE,CAC/D,WACA,UACD,CAAC,CAEiE"}
package/dist/pglite.d.mts CHANGED
@@ -1,4 +1,4 @@
1
- import { D as Schema, Dn as QueryExecutionContext, Ft as NoExtraDriverConfigKeys, Ht as TransactionOptionSupport, It as VibORMClient, L as LinkedClientConfig, On as QueryResult, d as PinnedSessionReservation, jt as DriverConfig, s as DatabaseAdapter, u as Driver } from "./index-BbcE-gyl.mjs";
1
+ import { A as Schema, B as LinkedClientConfig, Dn as TransactionOptionSupport, Mn as QueryResult, Pt as DriverConfig, Rt as NoExtraDriverConfigKeys, jn as QueryExecutionContext, m as PinnedSessionReservation, s as DatabaseAdapter, u as Driver, zt as VibORMClient } from "./index-Likdf5qP.mjs";
2
2
  import { PGlite, PGliteOptions, PGliteOptions as PGliteOptions$1, Transaction } from "@electric-sql/pglite";
3
3
 
4
4
  //#region src/drivers/pglite/index.d.ts
@@ -49,6 +49,7 @@ declare class PGliteDriver extends Driver<PGlite, Transaction> {
49
49
  protected closeClient(client: PGlite): Promise<void>;
50
50
  protected execute<T>(client: PGlite | Transaction, sql: string, params: unknown[], context?: QueryExecutionContext): Promise<QueryResult<T>>;
51
51
  protected executeRaw<T>(client: PGlite | Transaction, sql: string, params: unknown[] | undefined, context?: QueryExecutionContext): Promise<QueryResult<T>>;
52
+ private executeQuery;
52
53
  /**
53
54
  * PGlite is a full PostgreSQL, so the isolation level is a real post-BEGIN
54
55
  * statement. It is also single-connection, so top-level transactions queue —
package/dist/pglite.mjs CHANGED
@@ -1,2 +1,2 @@
1
- import{n as e}from"./chunk-BuuaeEvq.mjs";import{y as t}from"./validation-Du6j0Q38.mjs";import{c as n}from"./bind-parameter-capacity-DzMcIB95.mjs";import{a as r,r as i}from"./transactions-gjmrWN5W.mjs";import{s as a}from"./execution-context-Bm_qTp1i.mjs";import{n as o}from"./client-C8gXvWIA.mjs";import{i as s,t as c}from"./driver-options-DVxWlZ0s.mjs";import{i as l,t as u}from"./pinned-session-CNANv7bv.mjs";import{n as d,t as f}from"./driver-CHclfK3q.mjs";import{t as p}from"./postgres-adapter-ButxrmEa.mjs";import{PGlite as m}from"@electric-sql/pglite";const h=Object.fromEntries([1082,1114,1184,1115,1182,1185].map(e=>[e,e=>e]));var PGliteDriver=class extends f{maxBindParametersPerStatement=32767;serializeTransactions=!0;driverOptions;suppliedClient;constructor(e={}){super(`postgresql`,`pglite`);let n=s(e);this.driverOptions=e,this.suppliedClient=e.client,this.suppliedClient&&(this.client=this.suppliedClient,Object.defineProperty(this,`connectionQueue`,{value:d(this.suppliedClient)}));let r=new p(n,e.postgis===!0);r.capabilities.supportsVector=e.pgvector===!0,e.pgvector||(r.vector=t),c(this,`adapter`,r)}async initClient(){if(this.suppliedClient!==void 0)return this.suppliedClient;let e=this.driverOptions.dataDir,t=this.driverOptions.options??{},n={...t,parsers:{1114:e=>e,...t.parsers}};return e?await m.create(e,n):await m.create(n)}async closeClient(e){e!==this.suppliedClient&&await e.close()}async execute(e,t,r,i){let a=i?.operation??`execute`,o=await e.query(t,r,{parsers:h}),s=n(o.affectedRows,{provider:`pglite`,operation:a});return{rows:o.rows,rowCount:o.rows.length>0?o.rows.length:s}}async executeRaw(e,t,r,i){let a=i?.operation??`executeRaw`,o=await e.query(t,r,{parsers:h}),s=n(o.affectedRows,{provider:`pglite`,operation:a});return{rows:o.rows,rowCount:o.rows.length>0?o.rows.length:s}}transactionOptionSupport(){return{isolationLevel:`post-begin`,timeout:!0,maxWait:`queue`}}transaction(e,t,n){if(!(e instanceof m))throw i(this.driverName);return r({run:t=>e.transaction(t),callback:t,phases:a(n),close:async()=>void 0})}async physicalPinnedSession(){return await this.getClient({operation:`pinnedSession`})}async pinnedSession(){let e=await this.getClient({operation:`pinnedSession`});if(!(e instanceof m))throw i(this.driverName);return{session:e,release:async t=>{if(t)try{await e.query(`SELECT pg_advisory_unlock_all()`)}catch(t){throw u(e),l(this.driverName,`No driver will pin a further migration session on that client. The client itself was NOT closed: it is the caller's database, not a pooled connection VibORM may discard.`,t)}}}}};function createClient(e){let{client:t,dataDir:n,options:r,pgvector:i,postgis:a}=e;return o(e,new PGliteDriver({client:t,dataDir:n,options:r,pgvector:i,postgis:a,namespace:s(e)}))}export{PGliteDriver,createClient};
1
+ import{n as e}from"./chunk-BuuaeEvq.mjs";import{c as t}from"./bind-parameter-capacity-CjPgqnmx.mjs";import{d as n,l as r}from"./error-mapping-CnPCv1dm.mjs";import{s as i}from"./execution-context-BKR3bgES.mjs";import{n as a}from"./client-BLiBmykn.mjs";import{a as o,n as s}from"./pinned-session-CLxj5M5e.mjs";import{c,d as l,r as u,t as d}from"./driver-BlnKXPFF.mjs";import{t as f}from"./postgres-adapter-CQD2oGuD.mjs";import{PGlite as p}from"@electric-sql/pglite";const m=Object.fromEntries([1082,1114,1184,1115,1182,1185].map(e=>[e,e=>e])),h={client:!0,dataDir:!0,options:!0,pgvector:!0,postgis:!0,namespace:!0};function isPGliteDatabase(e){return`transaction`in e}var PGliteDriver=class extends d{maxBindParametersPerStatement=32767;serializeTransactions=!0;driverOptions;suppliedClient;constructor(e={}){super(`postgresql`,`pglite`);let t=l(e);this.driverOptions=e,this.suppliedClient=e.client,this.suppliedClient&&(this.client=this.suppliedClient,Object.defineProperty(this,`connectionQueue`,{value:u(this.suppliedClient)})),f(this,t,e)}async initClient(){if(this.suppliedClient!==void 0)return this.suppliedClient;let e=this.driverOptions.dataDir,t=this.driverOptions.options??{},n={...t,parsers:{1114:e=>e,...t.parsers}};return e?await p.create(e,n):await p.create(n)}async closeClient(e){e!==this.suppliedClient&&await e.close()}async execute(e,t,n,r){return this.executeQuery(e,t,n,r,`execute`)}async executeRaw(e,t,n,r){return this.executeQuery(e,t,n,r,`executeRaw`)}async executeQuery(e,n,r,i,a){let o=i?.operation??a,s=await e.query(n,r,{parsers:m}),c=t(s.affectedRows,{provider:`pglite`,operation:o});return{rows:s.rows,rowCount:s.rows.length>0?s.rows.length:c}}transactionOptionSupport(){return{isolationLevel:`post-begin`,timeout:!0,maxWait:`queue`}}transaction(e,t,a){if(!isPGliteDatabase(e))throw r(this.driverName);return n({run:t=>e.transaction(t),callback:t,phases:i(a),close:async()=>void 0})}async physicalPinnedSession(){return await this.getClient({operation:`pinnedSession`})}async pinnedSession(){let e=await this.getClient({operation:`pinnedSession`});if(!isPGliteDatabase(e))throw r(this.driverName);return{session:e,release:async t=>{if(t)try{await e.query(`SELECT pg_advisory_unlock_all()`)}catch(t){throw s(e),o(this.driverName,`No driver will pin a further migration session on that client. The client itself was NOT closed: it is the caller's database, not a pooled connection VibORM may discard.`,t)}}}}};function createClient(e){c(e,`pglite`,h);let{client:t,dataDir:n,options:r,pgvector:i,postgis:o}=e;return a(e,new PGliteDriver({client:t,dataDir:n,options:r,pgvector:i,postgis:o,namespace:l(e)}))}export{PGliteDriver,createClient};
2
2
  //# sourceMappingURL=pglite.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"pglite.mjs","names":[],"sources":["../src/drivers/pglite/index.ts"],"sourcesContent":["import { physicalConnectionQueue } from \"../connection-scope\";\n/**\n * PGlite Driver\n *\n * Driver implementation for PGlite (PostgreSQL in WebAssembly).\n * Supports optional pgvector and PostGIS extensions.\n */\n\nimport type { DatabaseAdapter } from \"@adapters/database-adapter\";\nimport { PostgresAdapter } from \"@adapters/databases/postgres/postgres-adapter\";\nimport {\n createClientFromDriverConfig,\n type DriverConfig,\n type LinkedClientConfig,\n type NoExtraDriverConfigKeys,\n type VibORMClient,\n} from \"@client/client\";\nimport type { Schema } from \"@client/types\";\nimport {\n PGlite,\n type PGliteOptions,\n type Transaction,\n} from \"@electric-sql/pglite\";\nimport { unsupportedVector } from \"@errors\";\nimport { Driver, type QueryExecutionContext } from \"../driver\";\nimport { getExecutionTransactionPhases } from \"../execution-context\";\nimport { normalizeProviderRowCount } from \"../normalized-result\";\nimport {\n defineImmutableDriverFact,\n nestedTransactionDispatchError,\n resolveNamespaceOption,\n runProviderManagedTransaction,\n type TransactionOptionSupport,\n} from \"../shared\";\nimport {\n condemnPhysicalSession,\n type PinnedSessionReservation,\n unprovenLockStateError,\n} from \"../shared/pinned-session\";\nimport type { QueryResult } from \"../types\";\n\nconst temporalParsers = Object.fromEntries(\n [1082, 1114, 1184, 1115, 1182, 1185].map((oid) => [\n oid,\n (value: string) => value,\n ])\n);\n\n// ============================================================\n// EXPORTED OPTIONS\n// ============================================================\n\nexport type { PGliteOptions } from \"@electric-sql/pglite\";\n\nexport interface PGliteDriverOptions {\n client?: PGlite;\n dataDir?: string;\n options?: PGliteOptions;\n pgvector?: boolean;\n postgis?: boolean;\n /** The PostgreSQL schema this driver's persistent objects live in. Defaults to `public`. */\n namespace?: string;\n}\n\nexport type PGliteConfig<C extends DriverConfig> = PGliteDriverOptions & C;\n\n// === ======================================================\n// DRIVER IMPLEMENTATION\n// ============================================================\n\nexport class PGliteDriver extends Driver<PGlite, Transaction> {\n declare readonly adapter: DatabaseAdapter;\n readonly maxBindParametersPerStatement: number | undefined = 32_767;\n protected override readonly serializeTransactions = true;\n\n private readonly driverOptions: PGliteDriverOptions;\n /**\n * The EXACT database the caller supplied, or absent when this driver makes\n * its own. Identity, settled here from ONE read, is the whole ownership\n * answer: the caller's options object is theirs to change, and a `client`\n * getter answering differently on a second read used to leave this driver\n * holding the caller's database while believing it had made its own.\n */\n private readonly suppliedClient: PGlite | undefined;\n\n constructor(options: PGliteDriverOptions = {}) {\n super(\"postgresql\", \"pglite\");\n const namespace = resolveNamespaceOption(options);\n this.driverOptions = options;\n this.suppliedClient = options.client;\n\n if (this.suppliedClient) {\n this.client = this.suppliedClient;\n Object.defineProperty(this, \"connectionQueue\", {\n value: physicalConnectionQueue(this.suppliedClient),\n });\n }\n\n const adapter = new PostgresAdapter(namespace, options.postgis === true);\n adapter.capabilities.supportsVector = options.pgvector === true;\n if (!options.pgvector) adapter.vector = unsupportedVector;\n defineImmutableDriverFact(this, \"adapter\", adapter);\n }\n\n /**\n * The database this driver runs on.\n *\n * A caller's database is RETURNED rather than replaced: reconnecting after a\n * `$disconnect()` used to build a second, EMPTY in-memory PGlite behind their\n * back — a database they never asked for, holding none of their data, while\n * the one they handed over stayed open and unused.\n */\n protected async initClient(): Promise<PGlite> {\n if (this.suppliedClient !== undefined) {\n return this.suppliedClient;\n }\n const dataDir = this.driverOptions.dataDir;\n const userOptions = this.driverOptions.options ?? {};\n const options: PGliteOptions = {\n ...userOptions,\n parsers: {\n // TIMESTAMP WITHOUT TIME ZONE: PGlite builds process-local Dates,\n // shifting the stored UTC wall clock. Keep the raw string — the\n // shared result parser builds a UTC Date, matching other drivers.\n 1114: (value: string) => value,\n ...userOptions.parsers,\n },\n };\n\n // PGlite.create accepts dataDir as first argument or in options\n return dataDir\n ? await PGlite.create(dataDir, options)\n : await PGlite.create(options);\n }\n\n /**\n * A supplied database belongs to the caller, who may be running two\n * schema-scoped estates over it — the documented shape — and closing it here\n * would take the sibling's data down with this one's `$disconnect()`, on an\n * in-memory database for good.\n *\n * The test is on the client's IDENTITY against what construction captured, so\n * it answers for the database actually being closed rather than for whatever\n * the caller's record says now.\n */\n protected async closeClient(client: PGlite): Promise<void> {\n if (client === this.suppliedClient) {\n return;\n }\n await client.close();\n }\n\n protected async execute<T>(\n client: PGlite | Transaction,\n sql: string,\n params: unknown[],\n context?: QueryExecutionContext\n ): Promise<QueryResult<T>> {\n const operation = context?.operation ?? \"execute\";\n const result = await client.query<T>(sql, params, {\n parsers: temporalParsers,\n });\n const affectedRows = normalizeProviderRowCount(result.affectedRows, {\n provider: \"pglite\",\n operation,\n });\n return {\n rows: result.rows,\n rowCount: result.rows.length > 0 ? result.rows.length : affectedRows,\n };\n }\n\n protected async executeRaw<T>(\n client: PGlite | Transaction,\n sql: string,\n params: unknown[] | undefined,\n context?: QueryExecutionContext\n ): Promise<QueryResult<T>> {\n const operation = context?.operation ?? \"executeRaw\";\n const result = await client.query<T>(sql, params, {\n parsers: temporalParsers,\n });\n const affectedRows = normalizeProviderRowCount(result.affectedRows, {\n provider: \"pglite\",\n operation,\n });\n return {\n rows: result.rows,\n rowCount: result.rows.length > 0 ? result.rows.length : affectedRows,\n };\n }\n\n /**\n * PGlite is a full PostgreSQL, so the isolation level is a real post-BEGIN\n * statement. It is also single-connection, so top-level transactions queue —\n * and that queue wait is exactly what `maxWait` bounds.\n */\n protected override transactionOptionSupport(): TransactionOptionSupport {\n return {\n isolationLevel: \"post-begin\",\n timeout: true,\n maxWait: \"queue\",\n };\n }\n\n protected transaction<T>(\n client: PGlite | Transaction,\n fn: (tx: Transaction) => Promise<T>,\n context?: QueryExecutionContext\n ): Promise<T> {\n if (!(client instanceof PGlite)) {\n throw nestedTransactionDispatchError(this.driverName);\n }\n return runProviderManagedTransaction({\n run: (callback) => client.transaction(callback),\n callback: fn,\n phases: getExecutionTransactionPhases(context),\n // The provider transaction primitive already rolls back/discards its\n // failed session. A transaction does not own this shared pool/database.\n close: async () => undefined,\n });\n }\n\n /**\n * The PGlite instance itself — the physical session a pinned command runs on.\n *\n * A caller may hand ONE PGlite to several drivers (two schema-scoped estates\n * over one database is the documented shape), and each of those drivers owns\n * its own connection queue. The client is what they all agree on, so it is\n * what serializes their pinned commands; without it the second command\n * re-acquires the reentrant session advisory lock the first is holding and\n * runs inside the first command's session.\n */\n protected override async physicalPinnedSession(): Promise<object> {\n return await this.getClient({ operation: \"pinnedSession\" });\n }\n\n /**\n * PGlite's single client, under the queue it already owns — plan §3.5's\n * pinned producer here. There is nothing to reserve and nothing to return:\n * one connection IS the session, which is exactly what a session lock needs.\n *\n * A condemned session can be neither destroyed nor abandoned: closing this\n * client closes the DATABASE, which for an in-memory one takes the caller's\n * data with it and for a supplied one is not VibORM's to do at all. So the\n * session is reset with `pg_advisory_unlock_all()`, and when that reset FAILS\n * the CLIENT is condemned instead — the subject of an unknown lock state is\n * the session, so the condemnation is recorded on it and refuses the next\n * pinned command through every driver over it. Ordinary queries keep working\n * — the data was never in doubt. Swallowing that reset failure was the\n * alternative, and it left the next migration command running inside a\n * session that may still hold the lock, on the one transport where the lock\n * is reentrant and would not stop it.\n */\n protected override async pinnedSession(): Promise<\n PinnedSessionReservation<PGlite | Transaction>\n > {\n const client = await this.getClient({ operation: \"pinnedSession\" });\n if (!(client instanceof PGlite)) {\n throw nestedTransactionDispatchError(this.driverName);\n }\n return {\n session: client,\n release: async (discard) => {\n if (!discard) {\n return;\n }\n try {\n await client.query(\"SELECT pg_advisory_unlock_all()\");\n } catch (resetFailure) {\n condemnPhysicalSession(client);\n throw unprovenLockStateError(\n this.driverName,\n \"No driver will pin a further migration session on that client. The client itself was NOT closed: it is the caller's database, not a pooled connection VibORM may discard.\",\n resetFailure\n );\n }\n },\n };\n }\n}\n\n// ============================================================\n// CONVENIENCE FUNCTION\n// ============================================================\n\nexport function createClient<S extends Schema, C extends DriverConfig<S>>(\n config: PGliteConfig<C> &\n DriverConfig<S> &\n NoExtraDriverConfigKeys<C, PGliteDriverOptions, S>\n): VibORMClient<{\n [P in keyof LinkedClientConfig<\n C & { driver: PGliteDriver }\n >]: LinkedClientConfig<C & { driver: PGliteDriver }>[P];\n}> {\n const { client, dataDir, options, pgvector, postgis } = config;\n const namespace = resolveNamespaceOption(config);\n\n const driver = new PGliteDriver({\n client,\n dataDir,\n options,\n pgvector,\n postgis,\n namespace,\n });\n\n return createClientFromDriverConfig<S, C, PGliteDriver>(config, driver);\n}\n"],"mappings":"6iBAyCA,MAAM,EAAkB,OAAO,YAC7B,CAAC,KAAM,KAAM,KAAM,KAAM,KAAM,KAAK,CAAC,IAAK,GAAQ,CAChD,EACC,GAAkB,EACpB,CAAC,CACH,CAwBD,IAAa,aAAb,cAAkC,CAA4B,CAE5D,8BAA6D,MAC7D,sBAAoD,GAEpD,cAQA,eAEA,YAAY,EAA+B,EAAE,CAAE,CAC7C,MAAM,aAAc,SAAS,CAC7B,IAAM,EAAY,EAAuB,EAAQ,CACjD,KAAK,cAAgB,EACrB,KAAK,eAAiB,EAAQ,OAE1B,KAAK,iBACP,KAAK,OAAS,KAAK,eACnB,OAAO,eAAe,KAAM,kBAAmB,CAC7C,MAAO,EAAwB,KAAK,eAAe,CACpD,CAAC,EAGJ,IAAM,EAAU,IAAI,EAAgB,EAAW,EAAQ,UAAY,GAAK,CACxE,EAAQ,aAAa,eAAiB,EAAQ,WAAa,GACtD,EAAQ,WAAU,EAAQ,OAAS,GACxC,EAA0B,KAAM,UAAW,EAAQ,CAWrD,MAAgB,YAA8B,CAC5C,GAAI,KAAK,iBAAmB,IAAA,GAC1B,OAAO,KAAK,eAEd,IAAM,EAAU,KAAK,cAAc,QAC7B,EAAc,KAAK,cAAc,SAAW,EAAE,CAC9C,EAAyB,CAC7B,GAAG,EACH,QAAS,CAIP,KAAO,GAAkB,EACzB,GAAG,EAAY,QAChB,CACF,CAGD,OAAO,EACH,MAAM,EAAO,OAAO,EAAS,EAA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CACF,MAAM,EAAO,MAAM,kCAAkC,OAC9C,EAAc,CAErB,MADA,EAAuB,EAAO,CACxB,EACJ,KAAK,WACL,4KACA,EACD,GAGN,GAQL,SAAgB,aACd,EAOC,CACD,GAAM,CAAE,SAAQ,UAAS,UAAS,WAAU,WAAY,EAYxD,OAAO,EAAiD,EATzC,IAAI,aAAa,CAC9B,SACA,UACA,UACA,WACA,UACA,UARgB,EAAuB,EAAO,CAS/C,CAAC,CAEqE"}
1
+ {"version":3,"file":"pglite.mjs","names":[],"sources":["../src/drivers/pglite/index.ts"],"sourcesContent":["import { physicalConnectionQueue } from \"../connection-scope\";\n/**\n * PGlite Driver\n *\n * Driver implementation for PGlite (PostgreSQL in WebAssembly).\n * Supports optional pgvector and PostGIS extensions.\n */\n\nimport type { DatabaseAdapter } from \"@adapters/database-adapter\";\nimport {\n createClientFromDriverConfig,\n type DriverConfig,\n type LinkedClientConfig,\n type NoExtraDriverConfigKeys,\n type VibORMClient,\n} from \"@client/client\";\nimport type { Schema } from \"@client/types\";\nimport {\n PGlite,\n type PGliteOptions,\n type Transaction,\n} from \"@electric-sql/pglite\";\nimport { Driver, type QueryExecutionContext } from \"../driver\";\nimport { getExecutionTransactionPhases } from \"../execution-context\";\nimport { normalizeProviderRowCount } from \"../normalized-result\";\nimport {\n nestedTransactionDispatchError,\n resolveNamespaceOption,\n runProviderManagedTransaction,\n type TransactionOptionSupport,\n} from \"../shared\";\nimport { refuseUnknownDriverConfigKeys } from \"../shared/driver-options\";\nimport {\n condemnPhysicalSession,\n type PinnedSessionReservation,\n unprovenLockStateError,\n} from \"../shared/pinned-session\";\nimport { installPostgresAdapter } from \"../shared/postgres-adapter\";\nimport type { QueryResult } from \"../types\";\n\nconst temporalParsers = Object.fromEntries(\n [1082, 1114, 1184, 1115, 1182, 1185].map((oid) => [\n oid,\n (value: string) => value,\n ])\n);\n\n// ============================================================\n// EXPORTED OPTIONS\n// ============================================================\n\nexport type { PGliteOptions } from \"@electric-sql/pglite\";\n\nexport interface PGliteDriverOptions {\n client?: PGlite;\n dataDir?: string;\n options?: PGliteOptions;\n pgvector?: boolean;\n postgis?: boolean;\n /** The PostgreSQL schema this driver's persistent objects live in. Defaults to `public`. */\n namespace?: string;\n}\n\nexport type PGliteConfig<C extends DriverConfig> = PGliteDriverOptions & C;\n\nconst PGLITE_CONFIG_KEYS: Record<keyof PGliteDriverOptions, true> = {\n client: true,\n dataDir: true,\n options: true,\n pgvector: true,\n postgis: true,\n namespace: true,\n};\n\n/**\n * The database, as opposed to a transaction handle, which has no `transaction`\n * method. Not `instanceof PGlite`: a PGlite built by another copy of\n * `@electric-sql/pglite` (its CommonJS build beside the ESM one, or a second\n * installed version) has another class, and every transaction and pinned\n * command on it used to fail as \"nested provider state\".\n */\nfunction isPGliteDatabase(client: PGlite | Transaction): client is PGlite {\n return \"transaction\" in client;\n}\n\n// === ======================================================\n// DRIVER IMPLEMENTATION\n// ============================================================\n\nexport class PGliteDriver extends Driver<PGlite, Transaction> {\n declare readonly adapter: DatabaseAdapter;\n readonly maxBindParametersPerStatement: number | undefined = 32_767;\n protected override readonly serializeTransactions = true;\n\n private readonly driverOptions: PGliteDriverOptions;\n /**\n * The EXACT database the caller supplied, or absent when this driver makes\n * its own. Identity, settled here from ONE read, is the whole ownership\n * answer: the caller's options object is theirs to change, and a `client`\n * getter answering differently on a second read used to leave this driver\n * holding the caller's database while believing it had made its own.\n */\n private readonly suppliedClient: PGlite | undefined;\n\n constructor(options: PGliteDriverOptions = {}) {\n super(\"postgresql\", \"pglite\");\n const namespace = resolveNamespaceOption(options);\n this.driverOptions = options;\n this.suppliedClient = options.client;\n\n if (this.suppliedClient) {\n this.client = this.suppliedClient;\n Object.defineProperty(this, \"connectionQueue\", {\n value: physicalConnectionQueue(this.suppliedClient),\n });\n }\n\n installPostgresAdapter(this, namespace, options);\n }\n\n /**\n * The database this driver runs on.\n *\n * A caller's database is RETURNED rather than replaced: reconnecting after a\n * `$disconnect()` used to build a second, EMPTY in-memory PGlite behind their\n * back — a database they never asked for, holding none of their data, while\n * the one they handed over stayed open and unused.\n */\n protected async initClient(): Promise<PGlite> {\n if (this.suppliedClient !== undefined) {\n return this.suppliedClient;\n }\n const dataDir = this.driverOptions.dataDir;\n const userOptions = this.driverOptions.options ?? {};\n const options: PGliteOptions = {\n ...userOptions,\n parsers: {\n // TIMESTAMP WITHOUT TIME ZONE: PGlite builds process-local Dates,\n // shifting the stored UTC wall clock. Keep the raw string — the\n // shared result parser builds a UTC Date, matching other drivers.\n 1114: (value: string) => value,\n ...userOptions.parsers,\n },\n };\n\n // PGlite.create accepts dataDir as first argument or in options\n return dataDir\n ? await PGlite.create(dataDir, options)\n : await PGlite.create(options);\n }\n\n /**\n * A supplied database belongs to the caller, who may be running two\n * schema-scoped estates over it — the documented shape — and closing it here\n * would take the sibling's data down with this one's `$disconnect()`, on an\n * in-memory database for good.\n *\n * The test is on the client's IDENTITY against what construction captured, so\n * it answers for the database actually being closed rather than for whatever\n * the caller's record says now.\n */\n protected async closeClient(client: PGlite): Promise<void> {\n if (client === this.suppliedClient) {\n return;\n }\n await client.close();\n }\n\n protected async execute<T>(\n client: PGlite | Transaction,\n sql: string,\n params: unknown[],\n context?: QueryExecutionContext\n ): Promise<QueryResult<T>> {\n return this.executeQuery(client, sql, params, context, \"execute\");\n }\n\n protected async executeRaw<T>(\n client: PGlite | Transaction,\n sql: string,\n params: unknown[] | undefined,\n context?: QueryExecutionContext\n ): Promise<QueryResult<T>> {\n return this.executeQuery(client, sql, params, context, \"executeRaw\");\n }\n\n private async executeQuery<T>(\n client: PGlite | Transaction,\n sql: string,\n params: unknown[] | undefined,\n context: QueryExecutionContext | undefined,\n fallbackOperation: \"execute\" | \"executeRaw\"\n ): Promise<QueryResult<T>> {\n const operation = context?.operation ?? fallbackOperation;\n const result = await client.query<T>(sql, params, {\n parsers: temporalParsers,\n });\n const affectedRows = normalizeProviderRowCount(result.affectedRows, {\n provider: \"pglite\",\n operation,\n });\n return {\n rows: result.rows,\n rowCount: result.rows.length > 0 ? result.rows.length : affectedRows,\n };\n }\n\n /**\n * PGlite is a full PostgreSQL, so the isolation level is a real post-BEGIN\n * statement. It is also single-connection, so top-level transactions queue —\n * and that queue wait is exactly what `maxWait` bounds.\n */\n protected override transactionOptionSupport(): TransactionOptionSupport {\n return {\n isolationLevel: \"post-begin\",\n timeout: true,\n maxWait: \"queue\",\n };\n }\n\n protected transaction<T>(\n client: PGlite | Transaction,\n fn: (tx: Transaction) => Promise<T>,\n context?: QueryExecutionContext\n ): Promise<T> {\n if (!isPGliteDatabase(client)) {\n throw nestedTransactionDispatchError(this.driverName);\n }\n return runProviderManagedTransaction({\n run: (callback) => client.transaction(callback),\n callback: fn,\n phases: getExecutionTransactionPhases(context),\n // The provider transaction primitive already rolls back/discards its\n // failed session. A transaction does not own this shared pool/database.\n close: async () => undefined,\n });\n }\n\n /**\n * The PGlite instance itself — the physical session a pinned command runs on.\n *\n * A caller may hand ONE PGlite to several drivers (two schema-scoped estates\n * over one database is the documented shape), and each of those drivers owns\n * its own connection queue. The client is what they all agree on, so it is\n * what serializes their pinned commands; without it the second command\n * re-acquires the reentrant session advisory lock the first is holding and\n * runs inside the first command's session.\n */\n protected override async physicalPinnedSession(): Promise<object> {\n return await this.getClient({ operation: \"pinnedSession\" });\n }\n\n /**\n * PGlite's single client, under the queue it already owns — plan §3.5's\n * pinned producer here. There is nothing to reserve and nothing to return:\n * one connection IS the session, which is exactly what a session lock needs.\n *\n * A condemned session can be neither destroyed nor abandoned: closing this\n * client closes the DATABASE, which for an in-memory one takes the caller's\n * data with it and for a supplied one is not VibORM's to do at all. So the\n * session is reset with `pg_advisory_unlock_all()`, and when that reset FAILS\n * the CLIENT is condemned instead — the subject of an unknown lock state is\n * the session, so the condemnation is recorded on it and refuses the next\n * pinned command through every driver over it. Ordinary queries keep working\n * — the data was never in doubt. Swallowing that reset failure was the\n * alternative, and it left the next migration command running inside a\n * session that may still hold the lock, on the one transport where the lock\n * is reentrant and would not stop it.\n */\n protected override async pinnedSession(): Promise<\n PinnedSessionReservation<PGlite | Transaction>\n > {\n const client = await this.getClient({ operation: \"pinnedSession\" });\n if (!isPGliteDatabase(client)) {\n throw nestedTransactionDispatchError(this.driverName);\n }\n return {\n session: client,\n release: async (discard) => {\n if (!discard) {\n return;\n }\n try {\n await client.query(\"SELECT pg_advisory_unlock_all()\");\n } catch (resetFailure) {\n condemnPhysicalSession(client);\n throw unprovenLockStateError(\n this.driverName,\n \"No driver will pin a further migration session on that client. The client itself was NOT closed: it is the caller's database, not a pooled connection VibORM may discard.\",\n resetFailure\n );\n }\n },\n };\n }\n}\n\n// ============================================================\n// CONVENIENCE FUNCTION\n// ============================================================\n\nexport function createClient<S extends Schema, C extends DriverConfig<S>>(\n config: PGliteConfig<C> &\n DriverConfig<S> &\n NoExtraDriverConfigKeys<C, PGliteDriverOptions, S>\n): VibORMClient<{\n [P in keyof LinkedClientConfig<\n C & { driver: PGliteDriver }\n >]: LinkedClientConfig<C & { driver: PGliteDriver }>[P];\n}> {\n refuseUnknownDriverConfigKeys(config, \"pglite\", PGLITE_CONFIG_KEYS);\n const { client, dataDir, options, pgvector, postgis } = config;\n const namespace = resolveNamespaceOption(config);\n\n const driver = new PGliteDriver({\n client,\n dataDir,\n options,\n pgvector,\n postgis,\n namespace,\n });\n\n return createClientFromDriverConfig<S, C, PGliteDriver>(config, driver);\n}\n"],"mappings":"gdAwCA,MAAM,EAAkB,OAAO,YAC7B,CAAC,KAAM,KAAM,KAAM,KAAM,KAAM,KAAK,CAAC,IAAK,GAAQ,CAChD,EACC,GAAkB,EACpB,CAAC,CACH,CAoBK,EAA8D,CAClE,OAAQ,GACR,QAAS,GACT,QAAS,GACT,SAAU,GACV,QAAS,GACT,UAAW,GACZ,CASD,SAAS,iBAAiB,EAAgD,CACxE,MAAO,gBAAiB,EAO1B,IAAa,aAAb,cAAkC,CAA4B,CAE5D,8BAA6D,MAC7D,sBAAoD,GAEpD,cAQA,eAEA,YAAY,EAA+B,EAAE,C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EAAO,CAC3B,MAAM,EAA+B,KAAK,WAAW,CAEvD,OAAO,EAA8B,CACnC,IAAM,GAAa,EAAO,YAAY,EAAS,CAC/C,SAAU,EACV,OAAQ,EAA8B,EAAQ,CAG9C,MAAO,SAAY,IAAA,GACpB,CAAC,CAaJ,MAAyB,uBAAyC,CAChE,OAAO,MAAM,KAAK,UAAU,CAAE,UAAW,gBAAiB,CAAC,CAoB7D,MAAyB,eAEvB,CACA,IAAM,EAAS,MAAM,KAAK,UAAU,CAAE,UAAW,gBAAiB,CAAC,CACnE,GAAI,CAAC,iBAAiB,EAAO,CAC3B,MAAM,EAA+B,KAAK,WAAW,CAEvD,MAAO,CACL,QAAS,EACT,QAAS,KAAO,IAAY,CACrB,KAGL,GAAI,CACF,MAAM,EAAO,MAAM,kCAAkC,OAC9C,EAAc,CAErB,MADA,EAAuB,EAAO,CACxB,EACJ,KAAK,WACL,4KACA,EACD,GAGN,GAQL,SAAgB,aACd,EAOC,CACD,EAA8B,EAAQ,SAAU,EAAmB,CACnE,GAAM,CAAE,SAAQ,UAAS,UAAS,WAAU,WAAY,EAYxD,OAAO,EAAiD,EATzC,IAAI,aAAa,CAC9B,SACA,UACA,UACA,WACA,UACA,UARgB,EAAuB,EAAO,CAS/C,CAAC,CAEqE"}
@@ -0,0 +1,2 @@
1
+ import{n as e}from"./chunk-BuuaeEvq.mjs";import{at as t,rt as n}from"./geo-point-codec-lhxH42SK.mjs";import{i as r,o as i,r as a,t as o}from"./native-types-veeTk36s.mjs";const s=new WeakMap;function idDomainOfState(e){return e?.array===!0?void 0:idMemberDomainOfState(e)}function idMemberDomainOfState(e){if(e===void 0||e.type!==`string`)return;let n=s.get(e);if(n)return n;let r=e.autoGenerate;if(r===void 0||!t(r.kind)||r.implicit===!0)return;let i={format:r.kind,prefix:r.prefix,length:r.length};return s.set(e,i),i}const c=/^(?:text|citext|varchar\(\d+\))$/,l=/^(?:TINYTEXT|TEXT|MEDIUMTEXT|LONGTEXT|VARCHAR\(\d+\)|CHAR\(\d+\))$/,u=/^TEXT$/,d=/^(?:BINARY|VARBINARY)\((\d+)\)$/;function defaultIdStorage(e,t){let i=n(e);if(i===void 0)switch(t){case`pg`:return{representation:`text`,columnType:a.STRING.TEXT.type};case`mysql`:return{representation:`text`,columnType:`TEXT`};default:return{representation:`text`,columnType:r.STRING.TEXT.type}}switch(t){case`pg`:return e===`uuid`||e===`uuidv7`?{representation:`uuid`,columnType:a.STRING.UUID.type}:{representation:`bytes`,columnType:a.BLOB.BYTEA.type};case`mysql`:return{representation:`bytes`,columnType:o.BLOB.BINARY(i).type};default:return{representation:`bytes`,columnType:r.BLOB.BLOB.type}}}function isTextColumnType(e,t){switch(t){case`pg`:return c.test(e);case`mysql`:return l.test(e);default:return u.test(e)}}function binaryRepresentation(e,t,i){let s=n(t);if(s===void 0)return;if(i===`pg`)return e===a.BLOB.BYTEA.type?`bytes`:e===a.STRING.UUID.type&&(t===`uuid`||t===`uuidv7`)?`uuid`:void 0;if(i===`sqlite`)return e===r.BLOB.BLOB.type?`bytes`:void 0;if(e===o.BLOB.BLOB.type)return`bytes`;let c=d.exec(e);return c&&Number(c[1])===s?`bytes`:void 0}function idStorageOf(e,t,n){let r=i(t,n);if(r===void 0)return defaultIdStorage(e.format,n);let a=r.type;if(isTextColumnType(a,n))return{representation:`text`,columnType:a};let o=binaryRepresentation(a,e.format,n);return o===void 0?void 0:{representation:o,columnType:a}}function describeIdNativeTypes(e,t){let r=n(e),i=t===`pg`?`text, citext, varchar(n)`:t===`mysql`?`TEXT, TINYTEXT, MEDIUMTEXT, LONGTEXT, VARCHAR(n), CHAR(n)`:`TEXT`;return r===void 0?i:`${t===`pg`?e===`uuid`||e===`uuidv7`?`uuid, bytea`:`bytea`:t===`mysql`?`BINARY(${r}), VARBINARY(${r}), BLOB`:`BLOB`}, ${i}`}function sqliteDateTimePhysicalForm(e){let t=i(e,`sqlite`);return t===void 0?`text`:t.type===`INTEGER`?`epochMillis`:t.type===`REAL`?`julianDay`:`text`}export{idStorageOf as a,idMemberDomainOfState as i,describeIdNativeTypes as n,idDomainOfState as r,sqliteDateTimePhysicalForm as t};
2
+ //# sourceMappingURL=physical-6V_LNU3L.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"physical-BkelResN.mjs","names":[],"sources":["../src/schema/scalars/string/id-domain.ts","../src/schema/scalars/datetime/physical.ts"],"sourcesContent":["/**\n * Where a DECLARED identifier domain is read from, and how it becomes a column.\n *\n * There is no second declaration: `ScalarState.autoGenerate` — the same record\n * `.uuid()`, `.ulid()`, `.ksuid()`, `.nanoid()` and `.cuid()` already write —\n * IS the domain. This module only projects it into the shape the codec takes,\n * and answers the one storage question the projection cannot: which physical\n * representation and which column spelling this domain has on a given dialect,\n * with a native type override taken into account.\n *\n * Storage lives HERE rather than in the codec because it is the only part of\n * the identifier language that speaks a dialect's vocabulary. The codec below\n * it stays pure — it takes a representation, never a provider — so the\n * validation schemas, which run long before any adapter exists, can use it.\n */\n\nimport {\n type IdDomain,\n type IdFormat,\n type IdRepresentation,\n idByteLength,\n isIdFormat,\n} from \"@validation/primitives/id-codec\";\nimport type { AutoGenerate, ScalarState } from \"../common\";\nimport {\n MYSQL,\n type NativeDialect,\n type NativeTypeDeclaration,\n nativeTypeFor,\n PG,\n SQLITE,\n} from \"../native-types\";\n\n// =============================================================================\n// THE DECLARED DOMAIN\n// =============================================================================\n\nconst DOMAINS = new WeakMap<ScalarState, IdDomain>();\n\n/**\n * The identifier domain a scalar state declares, or `undefined`.\n *\n * Only a NAMED format declares one. `.id()` installs a ULID generator without\n * naming a format (see {@link AutoGenerate.implicit}), so a `.id()` key has no\n * domain: nothing admits its values and nothing narrows its storage.\n *\n * A LIST answers `undefined` deliberately, exactly as the decimal descriptor\n * lookup does: physical parameter encoding, projection, decode and DDL must\n * not bind a whole container as one compact identifier. List admission reads\n * the same declaration through idMemberDomainOfState instead.\n *\n * The projection is memoized per state so the hot write path compares and\n * encodes against one object instead of allocating a domain per value.\n */\nexport function idDomainOfState(\n state: ScalarState | undefined\n): IdDomain | undefined {\n return state?.array === true ? undefined : idMemberDomainOfState(state);\n}\n\n/** The named member domain, also used by lists with plain string storage. */\nexport function idMemberDomainOfState(\n state: ScalarState | undefined\n): IdDomain | undefined {\n if (state === undefined || state.type !== \"string\") return undefined;\n const existing = DOMAINS.get(state);\n if (existing) return existing;\n const generate = state.autoGenerate;\n if (generate === undefined || !isIdFormat(generate.kind)) return undefined;\n // A format the caller did not NAME is not a domain the caller asserted:\n // `.id()` declares a key and carries a generator for convenience, and its\n // values stay whatever a string column holds. `.ulid().id()` names the\n // format and gets the domain, the admission and the compact column.\n if (generate.implicit === true) return undefined;\n const domain: IdDomain = {\n format: generate.kind,\n prefix: generate.prefix,\n length: generate.length,\n };\n DOMAINS.set(state, domain);\n return domain;\n}\n\n// =============================================================================\n// PHYSICAL STORAGE\n// =============================================================================\n\n/** The three dialects a column spelling is asked for. */\nexport type IdDialect = NativeDialect;\n\n/** What one domain is physically, on one dialect. */\nexport interface IdStorage {\n readonly representation: IdRepresentation;\n /** The column type this dialect spells it with. */\n readonly columnType: string;\n}\n\n// `char(n)` is absent deliberately. PostgreSQL BLANK-PADS `character(n)` to its\n// full width, so a 36-character uuid in a `char(40)` column reads back with four\n// trailing spaces and no value of the domain is ever returned — the column is\n// unusable from the moment it is created, for every n wider than the format's\n// own public spelling. MySQL's `CHAR(n)` pads on the way in and STRIPS on the\n// way out, so it keeps its place in that dialect's list.\nconst PG_TEXT_FAMILY = /^(?:text|citext|varchar\\(\\d+\\))$/;\nconst MYSQL_TEXT_FAMILY =\n /^(?:TINYTEXT|TEXT|MEDIUMTEXT|LONGTEXT|VARCHAR\\(\\d+\\)|CHAR\\(\\d+\\))$/;\nconst SQLITE_TEXT_FAMILY = /^TEXT$/;\nconst MYSQL_SIZED_BINARY = /^(?:BINARY|VARBINARY)\\((\\d+)\\)$/;\n\n/** The default column spelling and representation, before any override. */\nfunction defaultIdStorage(format: IdFormat, dialect: IdDialect): IdStorage {\n const width = idByteLength(format);\n if (width === undefined) {\n // `nanoid` and `cuid` keep the text column the dialect already gave them.\n switch (dialect) {\n case \"pg\":\n return { representation: \"text\", columnType: PG.STRING.TEXT.type };\n case \"mysql\":\n return { representation: \"text\", columnType: \"TEXT\" };\n default:\n return {\n representation: \"text\",\n columnType: SQLITE.STRING.TEXT.type,\n };\n }\n }\n switch (dialect) {\n case \"pg\":\n // A UUID gets PostgreSQL's own 16-byte type, which the wire spells as\n // canonical text. A ULID is never spelled `uuid`: its bytes are not a\n // UUID's and a database that formatted them as one would publish a\n // version nibble the value does not have.\n return format === \"uuid\" || format === \"uuidv7\"\n ? { representation: \"uuid\", columnType: PG.STRING.UUID.type }\n : { representation: \"bytes\", columnType: PG.BLOB.BYTEA.type };\n case \"mysql\":\n return {\n representation: \"bytes\",\n columnType: MYSQL.BLOB.BINARY(width).type,\n };\n default:\n return { representation: \"bytes\", columnType: SQLITE.BLOB.BLOB.type };\n }\n}\n\n/** Whether this dialect spells `type` as one of its text column types. */\nfunction isTextColumnType(type: string, dialect: IdDialect): boolean {\n switch (dialect) {\n case \"pg\":\n return PG_TEXT_FAMILY.test(type);\n case \"mysql\":\n return MYSQL_TEXT_FAMILY.test(type);\n default:\n return SQLITE_TEXT_FAMILY.test(type);\n }\n}\n\n/**\n * The representation a BINARY-family override names for this format, or\n * `undefined` when the override is not a binary column this domain fits.\n *\n * A sized MySQL column must be the format's exact width: `BINARY(16)` holds a\n * KSUID's first sixteen bytes and pads a ULID that was never short, and both\n * are silent corruptions rather than storage choices. `bytea` and `BLOB` carry\n * no declared width, so the codec's exact-width encoding is the only promise\n * they need.\n */\nfunction binaryRepresentation(\n type: string,\n format: IdFormat,\n dialect: IdDialect\n): IdRepresentation | undefined {\n const width = idByteLength(format);\n if (width === undefined) return undefined;\n if (dialect === \"pg\") {\n if (type === PG.BLOB.BYTEA.type) return \"bytes\";\n return type === PG.STRING.UUID.type &&\n (format === \"uuid\" || format === \"uuidv7\")\n ? \"uuid\"\n : undefined;\n }\n if (dialect === \"sqlite\") {\n return type === SQLITE.BLOB.BLOB.type ? \"bytes\" : undefined;\n }\n if (type === MYSQL.BLOB.BLOB.type) return \"bytes\";\n const sized = MYSQL_SIZED_BINARY.exec(type);\n return sized && Number(sized[1]) === width ? \"bytes\" : undefined;\n}\n\n/**\n * The column spelling and representation of one domain on one dialect.\n *\n * The ONE owner of that decision: the migration type mapping, the parameter\n * encoding, the read projection and the result decode all derive from this, so\n * a column cannot be created as one thing and written as another.\n *\n * The declaration is resolved for THIS dialect (`nativeTypeFor`): a tagged\n * native type for another dialect, or a map without this dialect's entry, is\n * not this dialect's column and is ignored exactly as every other scalar's\n * mapping ignores it. An override that IS this\n * dialect's and that this domain cannot live in returns `undefined` — the\n * schema boundary refuses it by name long before a query is built, and this\n * answering `undefined` rather than guessing is what keeps that refusal the\n * only place the question is decided.\n */\nexport function idStorageOf(\n domain: IdDomain,\n declaration: NativeTypeDeclaration | undefined,\n dialect: IdDialect\n): IdStorage | undefined {\n const nativeType = nativeTypeFor(declaration, dialect);\n if (nativeType === undefined) {\n return defaultIdStorage(domain.format, dialect);\n }\n const type = nativeType.type;\n if (isTextColumnType(type, dialect)) {\n // The opt-out for a column that already holds text: the domain is still\n // admitted and normalized, only its storage stays as it was.\n return { representation: \"text\", columnType: type };\n }\n const representation = binaryRepresentation(type, domain.format, dialect);\n return representation === undefined\n ? undefined\n : { representation, columnType: type };\n}\n\n/** The overrides this domain accepts on this dialect, for a refusal message. */\nexport function describeIdNativeTypes(\n format: IdFormat,\n dialect: IdDialect\n): string {\n const width = idByteLength(format);\n const text =\n dialect === \"pg\"\n ? \"text, citext, varchar(n)\"\n : dialect === \"mysql\"\n ? \"TEXT, TINYTEXT, MEDIUMTEXT, LONGTEXT, VARCHAR(n), CHAR(n)\"\n : \"TEXT\";\n if (width === undefined) return text;\n const binary =\n dialect === \"pg\"\n ? format === \"uuid\" || format === \"uuidv7\"\n ? \"uuid, bytea\"\n : \"bytea\"\n : dialect === \"mysql\"\n ? `BINARY(${width}), VARBINARY(${width}), BLOB`\n : \"BLOB\";\n return `${binary}, ${text}`;\n}\n","import type { DateTimePhysicalForm } from \"@validation/primitives/datetime-physical-codec\";\nimport { type NativeTypeDeclaration, nativeTypeFor } from \"../native-types\";\n\n/**\n * The physical vocabulary SQLite assigns to one DateTime native declaration.\n *\n * A missing declaration, a declaration that selects nothing on SQLite, and\n * explicit TEXT all use SQLite's default timestamp text. INTEGER is epoch milliseconds and\n * REAL is a Julian day. Schema validation, query lowering, result parsing, and\n * migration defaults consume this same interpretation.\n */\nexport function sqliteDateTimePhysicalForm(\n declaration: NativeTypeDeclaration | undefined\n): DateTimePhysicalForm {\n const nativeType = nativeTypeFor(declaration, \"sqlite\");\n if (nativeType === undefined) return \"text\";\n if (nativeType.type === \"INTEGER\") return \"epochMillis\";\n return nativeType.type === \"REAL\" ? \"julianDay\" : \"text\";\n}\n"],"mappings":"wKAqCA,MAAM,EAAU,IAAI,QAiBpB,SAAgB,gBACd,EACsB,CACtB,OAAO,GAAO,QAAU,GAAO,IAAA,GAAY,sBAAsB,EAAM,CAIzE,SAAgB,sBACd,EACsB,CACtB,GAAI,IAAU,IAAA,IAAa,EAAM,OAAS,SAAU,OACpD,IAAM,EAAW,EAAQ,IAAI,EAAM,CACnC,GAAI,EAAU,OAAO,EACrB,IAAM,EAAW,EAAM,aAMvB,GALI,IAAa,IAAA,IAAa,CAAC,EAAW,EAAS,KAAK,EAKpD,EAAS,WAAa,GAAM,OAChC,IAAM,EAAmB,CACvB,OAAQ,EAAS,KACjB,OAAQ,EAAS,OACjB,OAAQ,EAAS,OAClB,CAED,OADA,EAAQ,IAAI,EAAO,EAAO,CACnB,EAuBT,MAAM,EAAiB,mCACjB,EACJ,qEACI,EAAqB,SACrB,EAAqB,kCAG3B,SAAS,iBAAiB,EAAkB,EAA+B,CACzE,IAAM,EAAQ,EAAa,EAAO,CAClC,GAAI,IAAU,IAAA,GAEZ,OAAQ,EAAR,CACE,IAAK,KACH,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O,iBAAiB,EAAO,OAAQ,EAAQ,CAEjD,IAAM,EAAO,EAAW,KACxB,GAAI,iBAAiB,EAAM,EAAQ,CAGjC,MAAO,CAAE,eAAgB,OAAQ,WAAY,EAAM,CAErD,IAAM,EAAiB,qBAAqB,EAAM,EAAO,OAAQ,EAAQ,CACzE,OAAO,IAAmB,IAAA,GACtB,IAAA,GACA,CAAE,iBAAgB,WAAY,EAAM,CAI1C,SAAgB,sBACd,EACA,EACQ,CACR,IAAM,EAAQ,EAAa,EAAO,CAC5B,EACJ,IAAY,KACR,2BACA,IAAY,QACV,4DACA,OAUR,OATI,IAAU,IAAA,GAAkB,EASzB,GAPL,IAAY,KACR,IAAW,QAAU,IAAW,SAC9B,cACA,QACF,IAAY,QACV,UAAU,EAAM,eAAe,EAAM,SACrC,OACS,IAAI,IC5OvB,SAAgB,2BACd,EACsB,CACtB,IAAM,EAAa,EAAc,EAAa,SAAS,CAGvD,OAFI,IAAe,IAAA,GAAkB,OACjC,EAAW,OAAS,UAAkB,cACnC,EAAW,OAAS,OAAS,YAAc"}
1
+ {"version":3,"file":"physical-6V_LNU3L.mjs","names":[],"sources":["../src/schema/scalars/string/id-domain.ts","../src/schema/scalars/datetime/physical.ts"],"sourcesContent":["/**\n * Where a DECLARED identifier domain is read from, and how it becomes a column.\n *\n * There is no second declaration: `ScalarState.autoGenerate` — the same record\n * `.uuid()`, `.ulid()`, `.ksuid()`, `.nanoid()` and `.cuid()` already write —\n * IS the domain. This module only projects it into the shape the codec takes,\n * and answers the one storage question the projection cannot: which physical\n * representation and which column spelling this domain has on a given dialect,\n * with a native type override taken into account.\n *\n * Storage lives HERE rather than in the codec because it is the only part of\n * the identifier language that speaks a dialect's vocabulary. The codec below\n * it stays pure — it takes a representation, never a provider — so the\n * validation schemas, which run long before any adapter exists, can use it.\n */\n\nimport {\n type IdDomain,\n type IdFormat,\n type IdRepresentation,\n idByteLength,\n isIdFormat,\n} from \"@validation/primitives/id-codec\";\nimport type { AutoGenerate, ScalarState } from \"../common\";\nimport {\n MYSQL,\n type NativeDialect,\n type NativeTypeDeclaration,\n nativeTypeFor,\n PG,\n SQLITE,\n} from \"../native-types\";\n\n// =============================================================================\n// THE DECLARED DOMAIN\n// =============================================================================\n\nconst DOMAINS = new WeakMap<ScalarState, IdDomain>();\n\n/**\n * The identifier domain a scalar state declares, or `undefined`.\n *\n * Only a NAMED format declares one. `.id()` installs a ULID generator without\n * naming a format (see {@link AutoGenerate.implicit}), so a `.id()` key has no\n * domain: nothing admits its values and nothing narrows its storage.\n *\n * A LIST answers `undefined` deliberately, exactly as the decimal descriptor\n * lookup does: physical parameter encoding, projection, decode and DDL must\n * not bind a whole container as one compact identifier. List admission reads\n * the same declaration through idMemberDomainOfState instead.\n *\n * The projection is memoized per state so the hot write path compares and\n * encodes against one object instead of allocating a domain per value.\n */\nexport function idDomainOfState(\n state: ScalarState | undefined\n): IdDomain | undefined {\n return state?.array === true ? undefined : idMemberDomainOfState(state);\n}\n\n/** The named member domain, also used by lists with plain string storage. */\nexport function idMemberDomainOfState(\n state: ScalarState | undefined\n): IdDomain | undefined {\n if (state === undefined || state.type !== \"string\") return undefined;\n const existing = DOMAINS.get(state);\n if (existing) return existing;\n const generate = state.autoGenerate;\n if (generate === undefined || !isIdFormat(generate.kind)) return undefined;\n // A format the caller did not NAME is not a domain the caller asserted:\n // `.id()` declares a key and carries a generator for convenience, and its\n // values stay whatever a string column holds. `.ulid().id()` names the\n // format and gets the domain, the admission and the compact column.\n if (generate.implicit === true) return undefined;\n const domain: IdDomain = {\n format: generate.kind,\n prefix: generate.prefix,\n length: generate.length,\n };\n DOMAINS.set(state, domain);\n return domain;\n}\n\n// =============================================================================\n// PHYSICAL STORAGE\n// =============================================================================\n\n/** The three dialects a column spelling is asked for. */\nexport type IdDialect = NativeDialect;\n\n/** What one domain is physically, on one dialect. */\nexport interface IdStorage {\n readonly representation: IdRepresentation;\n /** The column type this dialect spells it with. */\n readonly columnType: string;\n}\n\n// `char(n)` is absent deliberately. PostgreSQL BLANK-PADS `character(n)` to its\n// full width, so a 36-character uuid in a `char(40)` column reads back with four\n// trailing spaces and no value of the domain is ever returned — the column is\n// unusable from the moment it is created, for every n wider than the format's\n// own public spelling. MySQL's `CHAR(n)` pads on the way in and STRIPS on the\n// way out, so it keeps its place in that dialect's list.\nconst PG_TEXT_FAMILY = /^(?:text|citext|varchar\\(\\d+\\))$/;\nconst MYSQL_TEXT_FAMILY =\n /^(?:TINYTEXT|TEXT|MEDIUMTEXT|LONGTEXT|VARCHAR\\(\\d+\\)|CHAR\\(\\d+\\))$/;\nconst SQLITE_TEXT_FAMILY = /^TEXT$/;\nconst MYSQL_SIZED_BINARY = /^(?:BINARY|VARBINARY)\\((\\d+)\\)$/;\n\n/** The default column spelling and representation, before any override. */\nfunction defaultIdStorage(format: IdFormat, dialect: IdDialect): IdStorage {\n const width = idByteLength(format);\n if (width === undefined) {\n // `nanoid` and `cuid` keep the text column the dialect already gave them.\n switch (dialect) {\n case \"pg\":\n return { representation: \"text\", columnType: PG.STRING.TEXT.type };\n case \"mysql\":\n return { representation: \"text\", columnType: \"TEXT\" };\n default:\n return {\n representation: \"text\",\n columnType: SQLITE.STRING.TEXT.type,\n };\n }\n }\n switch (dialect) {\n case \"pg\":\n // A UUID gets PostgreSQL's own 16-byte type, which the wire spells as\n // canonical text. A ULID is never spelled `uuid`: its bytes are not a\n // UUID's and a database that formatted them as one would publish a\n // version nibble the value does not have.\n return format === \"uuid\" || format === \"uuidv7\"\n ? { representation: \"uuid\", columnType: PG.STRING.UUID.type }\n : { representation: \"bytes\", columnType: PG.BLOB.BYTEA.type };\n case \"mysql\":\n return {\n representation: \"bytes\",\n columnType: MYSQL.BLOB.BINARY(width).type,\n };\n default:\n return { representation: \"bytes\", columnType: SQLITE.BLOB.BLOB.type };\n }\n}\n\n/** Whether this dialect spells `type` as one of its text column types. */\nfunction isTextColumnType(type: string, dialect: IdDialect): boolean {\n switch (dialect) {\n case \"pg\":\n return PG_TEXT_FAMILY.test(type);\n case \"mysql\":\n return MYSQL_TEXT_FAMILY.test(type);\n default:\n return SQLITE_TEXT_FAMILY.test(type);\n }\n}\n\n/**\n * The representation a BINARY-family override names for this format, or\n * `undefined` when the override is not a binary column this domain fits.\n *\n * A sized MySQL column must be the format's exact width: `BINARY(16)` holds a\n * KSUID's first sixteen bytes and pads a ULID that was never short, and both\n * are silent corruptions rather than storage choices. `bytea` and `BLOB` carry\n * no declared width, so the codec's exact-width encoding is the only promise\n * they need.\n */\nfunction binaryRepresentation(\n type: string,\n format: IdFormat,\n dialect: IdDialect\n): IdRepresentation | undefined {\n const width = idByteLength(format);\n if (width === undefined) return undefined;\n if (dialect === \"pg\") {\n if (type === PG.BLOB.BYTEA.type) return \"bytes\";\n return type === PG.STRING.UUID.type &&\n (format === \"uuid\" || format === \"uuidv7\")\n ? \"uuid\"\n : undefined;\n }\n if (dialect === \"sqlite\") {\n return type === SQLITE.BLOB.BLOB.type ? \"bytes\" : undefined;\n }\n if (type === MYSQL.BLOB.BLOB.type) return \"bytes\";\n const sized = MYSQL_SIZED_BINARY.exec(type);\n return sized && Number(sized[1]) === width ? \"bytes\" : undefined;\n}\n\n/**\n * The column spelling and representation of one domain on one dialect.\n *\n * The ONE owner of that decision: the migration type mapping, the parameter\n * encoding, the read projection and the result decode all derive from this, so\n * a column cannot be created as one thing and written as another.\n *\n * The declaration is resolved for THIS dialect (`nativeTypeFor`): a tagged\n * native type for another dialect, or a map without this dialect's entry, is\n * not this dialect's column and is ignored exactly as every other scalar's\n * mapping ignores it. An override that IS this\n * dialect's and that this domain cannot live in returns `undefined` — the\n * schema boundary refuses it by name long before a query is built, and this\n * answering `undefined` rather than guessing is what keeps that refusal the\n * only place the question is decided.\n */\nexport function idStorageOf(\n domain: IdDomain,\n declaration: NativeTypeDeclaration | undefined,\n dialect: IdDialect\n): IdStorage | undefined {\n const nativeType = nativeTypeFor(declaration, dialect);\n if (nativeType === undefined) {\n return defaultIdStorage(domain.format, dialect);\n }\n const type = nativeType.type;\n if (isTextColumnType(type, dialect)) {\n // The opt-out for a column that already holds text: the domain is still\n // admitted and normalized, only its storage stays as it was.\n return { representation: \"text\", columnType: type };\n }\n const representation = binaryRepresentation(type, domain.format, dialect);\n return representation === undefined\n ? undefined\n : { representation, columnType: type };\n}\n\n/** The overrides this domain accepts on this dialect, for a refusal message. */\nexport function describeIdNativeTypes(\n format: IdFormat,\n dialect: IdDialect\n): string {\n const width = idByteLength(format);\n const text =\n dialect === \"pg\"\n ? \"text, citext, varchar(n)\"\n : dialect === \"mysql\"\n ? \"TEXT, TINYTEXT, MEDIUMTEXT, LONGTEXT, VARCHAR(n), CHAR(n)\"\n : \"TEXT\";\n if (width === undefined) return text;\n const binary =\n dialect === \"pg\"\n ? format === \"uuid\" || format === \"uuidv7\"\n ? \"uuid, bytea\"\n : \"bytea\"\n : dialect === \"mysql\"\n ? `BINARY(${width}), VARBINARY(${width}), BLOB`\n : \"BLOB\";\n return `${binary}, ${text}`;\n}\n","import type { DateTimePhysicalForm } from \"@validation/primitives/datetime-physical-codec\";\nimport { type NativeTypeDeclaration, nativeTypeFor } from \"../native-types\";\n\n/**\n * The physical vocabulary SQLite assigns to one DateTime native declaration.\n *\n * A missing declaration, a declaration that selects nothing on SQLite, and\n * explicit TEXT all use SQLite's default timestamp text. INTEGER is epoch milliseconds and\n * REAL is a Julian day. Schema validation, query lowering, result parsing, and\n * migration defaults consume this same interpretation.\n */\nexport function sqliteDateTimePhysicalForm(\n declaration: NativeTypeDeclaration | undefined\n): DateTimePhysicalForm {\n const nativeType = nativeTypeFor(declaration, \"sqlite\");\n if (nativeType === undefined) return \"text\";\n if (nativeType.type === \"INTEGER\") return \"epochMillis\";\n return nativeType.type === \"REAL\" ? \"julianDay\" : \"text\";\n}\n"],"mappings":"0KAqCA,MAAM,EAAU,IAAI,QAiBpB,SAAgB,gBACd,EACsB,CACtB,OAAO,GAAO,QAAU,GAAO,IAAA,GAAY,sBAAsB,EAAM,CAIzE,SAAgB,sBACd,EAC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