viborm 1.16.0 → 1.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (403) hide show
  1. package/dist/adapter-internals-Dz2nNEF5.mjs +2 -0
  2. package/dist/adapter-internals-Dz2nNEF5.mjs.map +1 -0
  3. package/dist/adapter-namespace-C1SUkH2U.mjs +2 -0
  4. package/dist/{adapter-namespace-DwFnfpED.mjs.map → adapter-namespace-C1SUkH2U.mjs.map} +1 -1
  5. package/dist/adapters.d.mts +50 -94
  6. package/dist/adapters.mjs +1 -1
  7. package/dist/{args-7WgBFd_f.mjs → args-DsGRkPRw.mjs} +2 -2
  8. package/dist/{args-7WgBFd_f.mjs.map → args-DsGRkPRw.mjs.map} +1 -1
  9. package/dist/{array-literal-BOzj0E2u.mjs → array-literal-U6SeastY.mjs} +1 -1
  10. package/dist/{array-literal-BOzj0E2u.mjs.map → array-literal-U6SeastY.mjs.map} +1 -1
  11. package/dist/auto-names-GpcDfhaw.mjs +2 -0
  12. package/dist/auto-names-GpcDfhaw.mjs.map +1 -0
  13. package/dist/batch-refs-BuICt2tu.mjs +2 -0
  14. package/dist/{batch-refs-Bd8HvwUc.mjs.map → batch-refs-BuICt2tu.mjs.map} +1 -1
  15. package/dist/better-auth.d.mts +1 -1
  16. package/dist/better-auth.mjs +2 -2
  17. package/dist/bun-sql.d.mts +1 -1
  18. package/dist/bun-sql.mjs +1 -1
  19. package/dist/bun-sqlite.d.mts +1 -1
  20. package/dist/bun-sqlite.mjs +1 -1
  21. package/dist/cache/cloudflare-kv.d.mts +1 -1
  22. package/dist/cache/cloudflare-kv.mjs +1 -1
  23. package/dist/cache/memory.d.mts +1 -1
  24. package/dist/cache/memory.mjs +1 -1
  25. package/dist/cache.d.mts +2 -2
  26. package/dist/cache.mjs +1 -1
  27. package/dist/call-D2E7dPCd.mjs +2 -0
  28. package/dist/{call-0bd_B9Vp.mjs.map → call-D2E7dPCd.mjs.map} +1 -1
  29. package/dist/cli.mjs +6 -6
  30. package/dist/cli.mjs.map +1 -1
  31. package/dist/client-Cq_VcF43.d.mts +183 -0
  32. package/dist/client-DkNRAOuH.mjs +2 -0
  33. package/dist/client-DkNRAOuH.mjs.map +1 -0
  34. package/dist/{planner-C-zjj19U.d.mts → client-driver-DuQy6lsN.d.mts} +3 -3
  35. package/dist/client-rIiFOn1W.mjs +9 -0
  36. package/dist/client-rIiFOn1W.mjs.map +1 -0
  37. package/dist/client.d.mts +2 -2
  38. package/dist/client.mjs +1 -1
  39. package/dist/config.d.mts +2 -2
  40. package/dist/config.mjs +1 -1
  41. package/dist/{confine-CyI9IwjC.mjs → confine-FIfjlAHp.mjs} +2 -2
  42. package/dist/{confine-CyI9IwjC.mjs.map → confine-FIfjlAHp.mjs.map} +1 -1
  43. package/dist/{object-store-C4qmW7xf.d.mts → conformance-C1JveA8y.d.mts} +5 -60
  44. package/dist/conformance-C4JYA0JG.mjs +2 -0
  45. package/dist/conformance-C4JYA0JG.mjs.map +1 -0
  46. package/dist/contract-BBone8RD.mjs +2 -0
  47. package/dist/contract-BBone8RD.mjs.map +1 -0
  48. package/dist/coordination-BxMskOgi.mjs +1 -1
  49. package/dist/d1.d.mts +1 -1
  50. package/dist/d1.mjs +1 -1
  51. package/dist/{database-adapter-BMjJiBFm.d.mts → database-adapter-cW0nmWM6.d.mts} +1 -1
  52. package/dist/datetime-physical-codec-Ci0dyOot.mjs +2 -0
  53. package/dist/datetime-physical-codec-Ci0dyOot.mjs.map +1 -0
  54. package/dist/datetime-values-D_G6m5_o.mjs +2 -0
  55. package/dist/datetime-values-D_G6m5_o.mjs.map +1 -0
  56. package/dist/decimal-D4DRlT2y.mjs +2 -0
  57. package/dist/decimal-D4DRlT2y.mjs.map +1 -0
  58. package/dist/{defaults-DAPb-tJ4.mjs → defaults-BrXUK350.mjs} +2 -2
  59. package/dist/{defaults-DAPb-tJ4.mjs.map → defaults-BrXUK350.mjs.map} +1 -1
  60. package/dist/{document-CHaVF7Vn.d.mts → document-B8ClXlb7.d.mts} +1 -1
  61. package/dist/{driver-kiIQS_Fd.mjs → driver-BOsmU3kz.mjs} +2 -2
  62. package/dist/{driver-kiIQS_Fd.mjs.map → driver-BOsmU3kz.mjs.map} +1 -1
  63. package/dist/{driver-BvTixv-m.d.mts → driver-KgGMnfz8.d.mts} +1 -1
  64. package/dist/{driver-lShUkDmf.mjs → driver-PkP_1p80.mjs} +2 -2
  65. package/dist/{driver-lShUkDmf.mjs.map → driver-PkP_1p80.mjs.map} +1 -1
  66. package/dist/{driver-diagnostics-aQ54bArn.mjs → driver-diagnostics-sSpge6kv.mjs} +1 -1
  67. package/dist/{driver-diagnostics-aQ54bArn.mjs.map → driver-diagnostics-sSpge6kv.mjs.map} +1 -1
  68. package/dist/driver.d.mts +1 -1
  69. package/dist/driver.mjs +1 -1
  70. package/dist/durable-object.d.mts +1 -1
  71. package/dist/durable-object.mjs +2 -2
  72. package/dist/error-mapping-B9rSvgG9.mjs +1 -1
  73. package/dist/every-tAZuZ50K.mjs +2 -0
  74. package/dist/{every-JpbiHdMb.mjs.map → every-tAZuZ50K.mjs.map} +1 -1
  75. package/dist/execution-context-couU2tgh.mjs +1 -1
  76. package/dist/{exports-DYnTfvQo.d.mts → exports-reE3GioL.d.mts} +1 -1
  77. package/dist/extension-Bf4vO5mp.mjs +2 -0
  78. package/dist/extension-Bf4vO5mp.mjs.map +1 -0
  79. package/dist/facts-Bjnzv3j-.mjs +2 -0
  80. package/dist/facts-Bjnzv3j-.mjs.map +1 -0
  81. package/dist/{fs-estate-n-QpsFqb.mjs → fs-estate-C3ahNKmi.mjs} +2 -2
  82. package/dist/{fs-estate-n-QpsFqb.mjs.map → fs-estate-C3ahNKmi.mjs.map} +1 -1
  83. package/dist/geo-area-codec-CBdiCOzj.mjs +2 -0
  84. package/dist/{geo-area-codec-Bti2PA2i.mjs.map → geo-area-codec-CBdiCOzj.mjs.map} +1 -1
  85. package/dist/geo-point-DCV0eO1p.mjs +2 -0
  86. package/dist/geo-point-DCV0eO1p.mjs.map +1 -0
  87. package/dist/id-domain-Cj6MnMxg.mjs +2 -0
  88. package/dist/{id-domain-Cg65TLZ-.mjs.map → id-domain-Cj6MnMxg.mjs.map} +1 -1
  89. package/dist/identifier-BdLx66pi.mjs +2 -0
  90. package/dist/identifier-BdLx66pi.mjs.map +1 -0
  91. package/dist/identifier-conversion-CMKVatU4.mjs +3 -0
  92. package/dist/identifier-conversion-CMKVatU4.mjs.map +1 -0
  93. package/dist/{identifiers-BxOf57qy.mjs → identifiers-BAZ_S6Lk.mjs} +1 -1
  94. package/dist/{identifiers-BxOf57qy.mjs.map → identifiers-BAZ_S6Lk.mjs.map} +1 -1
  95. package/dist/{identity-CJlRQA-m.mjs → identity-nPArhpsD.mjs} +2 -2
  96. package/dist/{identity-CJlRQA-m.mjs.map → identity-nPArhpsD.mjs.map} +1 -1
  97. package/dist/index.d.mts +2 -2
  98. package/dist/index.mjs +1 -1
  99. package/dist/index.mjs.map +1 -1
  100. package/dist/instrumentation.d.mts +1 -1
  101. package/dist/instrumentation.mjs +1 -1
  102. package/dist/introspect-dyBpdr2L.mjs +2 -0
  103. package/dist/{introspect-q3Rf_Xv8.mjs.map → introspect-dyBpdr2L.mjs.map} +1 -1
  104. package/dist/json-DvvrTWUw.mjs +2 -0
  105. package/dist/{json-CsAdz9pg.mjs.map → json-DvvrTWUw.mjs.map} +1 -1
  106. package/dist/{json-number-C09rsm1g.mjs → json-number-Guh-5rff.mjs} +1 -1
  107. package/dist/{json-number-C09rsm1g.mjs.map → json-number-Guh-5rff.mjs.map} +1 -1
  108. package/dist/{json-parameter-D7hDrVKw.mjs → json-parameter-DtHhEfyE.mjs} +1 -1
  109. package/dist/{json-parameter-D7hDrVKw.mjs.map → json-parameter-DtHhEfyE.mjs.map} +1 -1
  110. package/dist/judge-words-CqNdnbou.mjs +2 -0
  111. package/dist/judge-words-CqNdnbou.mjs.map +1 -0
  112. package/dist/{key-BDH6oTyC.mjs → key-v4k7Cqb6.mjs} +2 -2
  113. package/dist/{key-BDH6oTyC.mjs.map → key-v4k7Cqb6.mjs.map} +1 -1
  114. package/dist/{keys-CIal55WQ.mjs → keys-BLWaO_YM.mjs} +1 -1
  115. package/dist/{keys-CIal55WQ.mjs.map → keys-BLWaO_YM.mjs.map} +1 -1
  116. package/dist/keys-o4Pl6Vsg.mjs +2 -0
  117. package/dist/{keys-DZdKAd4n.mjs.map → keys-o4Pl6Vsg.mjs.map} +1 -1
  118. package/dist/libsql-C0iMZifz.mjs +3 -0
  119. package/dist/libsql-C0iMZifz.mjs.map +1 -0
  120. package/dist/libsql.d.mts +1 -1
  121. package/dist/libsql.mjs +1 -1
  122. package/dist/light-reLULeHN.mjs +2 -0
  123. package/dist/{light-D2wNSbzY.mjs.map → light-reLULeHN.mjs.map} +1 -1
  124. package/dist/memory-DtTuFo-h.mjs +2 -0
  125. package/dist/memory-DtTuFo-h.mjs.map +1 -0
  126. package/dist/methods-part-Dsi0DBNU.mjs +2 -0
  127. package/dist/{methods-part-BaNx3o7b.mjs.map → methods-part-Dsi0DBNU.mjs.map} +1 -1
  128. package/dist/migrations/mysql/runtime.d.mts +7 -0
  129. package/dist/migrations/mysql/runtime.mjs +2 -0
  130. package/dist/migrations/mysql/runtime.mjs.map +1 -0
  131. package/dist/migrations/mysql.d.mts +7 -5
  132. package/dist/migrations/mysql.mjs +1 -1
  133. package/dist/migrations/mysql.mjs.map +1 -1
  134. package/dist/migrations/postgres/runtime.d.mts +7 -0
  135. package/dist/migrations/postgres/runtime.mjs +2 -0
  136. package/dist/migrations/postgres/runtime.mjs.map +1 -0
  137. package/dist/migrations/postgres.d.mts +7 -5
  138. package/dist/migrations/postgres.mjs +1 -1
  139. package/dist/migrations/postgres.mjs.map +1 -1
  140. package/dist/migrations/snowflake.d.mts +7 -5
  141. package/dist/migrations/snowflake.mjs +1 -1
  142. package/dist/migrations/snowflake.mjs.map +1 -1
  143. package/dist/migrations/sqlite/runtime.d.mts +7 -0
  144. package/dist/migrations/sqlite/runtime.mjs +2 -0
  145. package/dist/migrations/sqlite/runtime.mjs.map +1 -0
  146. package/dist/migrations/sqlite.d.mts +7 -5
  147. package/dist/migrations/sqlite.mjs +1 -1
  148. package/dist/migrations/sqlite.mjs.map +1 -1
  149. package/dist/migrations/storage/durable-object.d.mts +1 -1
  150. package/dist/migrations/storage/durable-object.mjs +1 -1
  151. package/dist/migrations/storage/fs.d.mts +1 -1
  152. package/dist/migrations/storage/fs.mjs +1 -1
  153. package/dist/migrations/storage/r2.d.mts +1 -1
  154. package/dist/migrations/storage/r2.mjs +1 -1
  155. package/dist/migrations/surrealdb.d.mts +7 -5
  156. package/dist/migrations/surrealdb.mjs +1 -1
  157. package/dist/migrations/surrealdb.mjs.map +1 -1
  158. package/dist/migrations/tenant.d.mts +4 -3
  159. package/dist/migrations/tenant.mjs +1 -1
  160. package/dist/migrations/tenant.mjs.map +1 -1
  161. package/dist/migrations.d.mts +7 -5
  162. package/dist/migrations.mjs +1 -1
  163. package/dist/migrations.mjs.map +1 -1
  164. package/dist/model-ByktcCGW.mjs +2 -0
  165. package/dist/model-ByktcCGW.mjs.map +1 -0
  166. package/dist/mysql-DPYi1p_g.mjs +4 -0
  167. package/dist/mysql-DPYi1p_g.mjs.map +1 -0
  168. package/dist/mysql-adapter-6gVm5PHp.mjs +2 -0
  169. package/dist/{mysql-adapter-BFWYPoM0.mjs.map → mysql-adapter-6gVm5PHp.mjs.map} +1 -1
  170. package/dist/mysql2.d.mts +1 -1
  171. package/dist/mysql2.mjs +1 -1
  172. package/dist/{named-statements-CkOOD__I.mjs → named-statements-CswIc5m1.mjs} +2 -2
  173. package/dist/{named-statements-CkOOD__I.mjs.map → named-statements-CswIc5m1.mjs.map} +1 -1
  174. package/dist/native-types-BUkcVedc.mjs +2 -0
  175. package/dist/native-types-BUkcVedc.mjs.map +1 -0
  176. package/dist/neon-http.d.mts +1 -1
  177. package/dist/neon-http.mjs +1 -1
  178. package/dist/normalized-result-D7nVkF36.mjs +1 -1
  179. package/dist/{object-store-Chq1PMYz.mjs → object-store-DnrLNxz_.mjs} +2 -2
  180. package/dist/{object-store-Chq1PMYz.mjs.map → object-store-DnrLNxz_.mjs.map} +1 -1
  181. package/dist/object-store-j4kgh61D.d.mts +59 -0
  182. package/dist/{on-ZkOVmE4-.mjs → on-nOenqmgP.mjs} +2 -2
  183. package/dist/{on-ZkOVmE4-.mjs.map → on-nOenqmgP.mjs.map} +1 -1
  184. package/dist/on.d.mts +1 -1
  185. package/dist/on.mjs +1 -1
  186. package/dist/ordering/keys.mjs +1 -1
  187. package/dist/ordering.d.mts +1 -1
  188. package/dist/ordering.mjs +2 -2
  189. package/dist/pending-operation-B5o-zhES.mjs +2 -0
  190. package/dist/{pending-operation-D4gUKMxD.mjs.map → pending-operation-B5o-zhES.mjs.map} +1 -1
  191. package/dist/permissions.d.mts +1 -1
  192. package/dist/permissions.mjs +1 -1
  193. package/dist/pg.d.mts +2 -2
  194. package/dist/pg.mjs +1 -1
  195. package/dist/pglite.d.mts +1 -1
  196. package/dist/pglite.mjs +1 -1
  197. package/dist/{physical-DO4PEYcc.mjs → physical-BheMRPY0.mjs} +2 -2
  198. package/dist/{physical-DO4PEYcc.mjs.map → physical-BheMRPY0.mjs.map} +1 -1
  199. package/dist/{pinned-session-Y7-2pRBJ.mjs → pinned-session-eNyd0dkT.mjs} +2 -2
  200. package/dist/{pinned-session-Y7-2pRBJ.mjs.map → pinned-session-eNyd0dkT.mjs.map} +1 -1
  201. package/dist/planetscale.d.mts +1 -1
  202. package/dist/planetscale.mjs +1 -1
  203. package/dist/postgres-CEGFOi8D.mjs +27 -0
  204. package/dist/postgres-CEGFOi8D.mjs.map +1 -0
  205. package/dist/postgres-adapter-B-im38AE.mjs +2 -0
  206. package/dist/postgres-adapter-B-im38AE.mjs.map +1 -0
  207. package/dist/{postgres-adapter-BpLizOaK.mjs → postgres-adapter-OoqoBdhb.mjs} +2 -2
  208. package/dist/{postgres-adapter-BpLizOaK.mjs.map → postgres-adapter-OoqoBdhb.mjs.map} +1 -1
  209. package/dist/{postgres-result-133boRW-.mjs → postgres-result-D-bqmofR.mjs} +1 -1
  210. package/dist/{postgres-result-133boRW-.mjs.map → postgres-result-D-bqmofR.mjs.map} +1 -1
  211. package/dist/postgres.d.mts +2 -2
  212. package/dist/postgres.mjs +1 -1
  213. package/dist/provider-limits-DvcCUw7l.mjs +2 -0
  214. package/dist/provider-limits-DvcCUw7l.mjs.map +1 -0
  215. package/dist/{provider-parameter-snapshot-cyTUDutH.mjs → provider-parameter-snapshot-DnJ6Av9y.mjs} +2 -2
  216. package/dist/{provider-parameter-snapshot-cyTUDutH.mjs.map → provider-parameter-snapshot-DnJ6Av9y.mjs.map} +1 -1
  217. package/dist/push-fingerprint-CegYVFFp.mjs +18 -0
  218. package/dist/push-fingerprint-CegYVFFp.mjs.map +1 -0
  219. package/dist/{quantized-BKBs0joq.mjs → quantized-DLD2cd6q.mjs} +1 -1
  220. package/dist/{quantized-BKBs0joq.mjs.map → quantized-DLD2cd6q.mjs.map} +1 -1
  221. package/dist/query-DSEMPA7r.mjs +2 -0
  222. package/dist/query-DSEMPA7r.mjs.map +1 -0
  223. package/dist/query-backend-CzwVfrQ6.mjs +2 -0
  224. package/dist/{query-backend-TisPjCPF.mjs.map → query-backend-CzwVfrQ6.mjs.map} +1 -1
  225. package/dist/{query-inspection-DwYBKSDG.mjs → query-inspection-CvtTL5Fs.mjs} +2 -2
  226. package/dist/{query-inspection-DwYBKSDG.mjs.map → query-inspection-CvtTL5Fs.mjs.map} +1 -1
  227. package/dist/raw-B8cNef_V.mjs +2 -0
  228. package/dist/{raw-DqEb71JZ.mjs.map → raw-B8cNef_V.mjs.map} +1 -1
  229. package/dist/{relation-bound-CSNKLyDy.mjs → relation-bound-DHP5cpTE.mjs} +1 -1
  230. package/dist/{relation-bound-CSNKLyDy.mjs.map → relation-bound-DHP5cpTE.mjs.map} +1 -1
  231. package/dist/{result-parsing-BbffueEX.mjs → result-parsing-DfwBAXY2.mjs} +1 -1
  232. package/dist/{result-parsing-BbffueEX.mjs.map → result-parsing-DfwBAXY2.mjs.map} +1 -1
  233. package/dist/{rows-of-Bgl9GVtK.mjs → rows-of-UeSasWGq.mjs} +2 -2
  234. package/dist/{rows-of-Bgl9GVtK.mjs.map → rows-of-UeSasWGq.mjs.map} +1 -1
  235. package/dist/rule-words-ojG0-vSf.mjs +2 -0
  236. package/dist/{rule-words-DMbQuvD2.mjs.map → rule-words-ojG0-vSf.mjs.map} +1 -1
  237. package/dist/runtime-BAqlANG_.mjs +10 -0
  238. package/dist/runtime-BAqlANG_.mjs.map +1 -0
  239. package/dist/runtime-D0oaIS1E.mjs +2 -0
  240. package/dist/runtime-D0oaIS1E.mjs.map +1 -0
  241. package/dist/runtime-Dfkv59_p.mjs +15 -0
  242. package/dist/runtime-Dfkv59_p.mjs.map +1 -0
  243. package/dist/runtime-client-CvGGOOFd.d.mts +38 -0
  244. package/dist/runtime-client-xeiXA_1m.mjs +2 -0
  245. package/dist/runtime-client-xeiXA_1m.mjs.map +1 -0
  246. package/dist/scalar-BTYxpiP_.mjs +4 -0
  247. package/dist/scalar-BTYxpiP_.mjs.map +1 -0
  248. package/dist/schema/introspect.d.mts +2 -2
  249. package/dist/schema/introspect.mjs +1 -1
  250. package/dist/schema/json.d.mts +2 -2
  251. package/dist/schema/json.mjs +1 -1
  252. package/dist/schema-BzkBJTF-.mjs +2 -0
  253. package/dist/{schema-DDkAUfOb.mjs.map → schema-BzkBJTF-.mjs.map} +1 -1
  254. package/dist/schema-D7MyYTjA.mjs +2 -0
  255. package/dist/{schema-DqR_Kcje.mjs.map → schema-D7MyYTjA.mjs.map} +1 -1
  256. package/dist/{schema-introspection-Bbo4DN_d.mjs → schema-introspection-b4xPGPfu.mjs} +4 -4
  257. package/dist/{schema-introspection-Bbo4DN_d.mjs.map → schema-introspection-b4xPGPfu.mjs.map} +1 -1
  258. package/dist/schema.d.mts +1 -1
  259. package/dist/schema.mjs +1 -1
  260. package/dist/{select-assembly-CEpNu-Gw.mjs → select-assembly-B01JtBRm.mjs} +2 -2
  261. package/dist/{select-assembly-CEpNu-Gw.mjs.map → select-assembly-B01JtBRm.mjs.map} +1 -1
  262. package/dist/serializer-CIhcZMxs.mjs +7 -0
  263. package/dist/serializer-CIhcZMxs.mjs.map +1 -0
  264. package/dist/{settle-Pui-1tfJ.mjs → settle-CIbvnLED.mjs} +1 -1
  265. package/dist/{settle-Pui-1tfJ.mjs.map → settle-CIbvnLED.mjs.map} +1 -1
  266. package/dist/{settled-DYYPcaBX.mjs → settled-Clanz_kI.mjs} +2 -2
  267. package/dist/{settled-DYYPcaBX.mjs.map → settled-Clanz_kI.mjs.map} +1 -1
  268. package/dist/snowflake-C1dqbche.mjs +2 -0
  269. package/dist/{snowflake-BfF8xwfP.mjs.map → snowflake-C1dqbche.mjs.map} +1 -1
  270. package/dist/snowflake.d.mts +2 -2
  271. package/dist/snowflake.mjs +2 -2
  272. package/dist/snowflake.mjs.map +1 -1
  273. package/dist/soft-delete.d.mts +1 -1
  274. package/dist/soft-delete.mjs +1 -1
  275. package/dist/{spans-DwDXMvyd.mjs → spans-CVl3RKUR.mjs} +1 -1
  276. package/dist/{spans-DwDXMvyd.mjs.map → spans-CVl3RKUR.mjs.map} +1 -1
  277. package/dist/sql-AHN2niBz.mjs +2 -0
  278. package/dist/{sql-Bu63iAfT.mjs.map → sql-AHN2niBz.mjs.map} +1 -1
  279. package/dist/sql-control-Cdp0_Mwy.mjs +2 -0
  280. package/dist/sql-control-Cdp0_Mwy.mjs.map +1 -0
  281. package/dist/{sql-statement-tokens-Z5Ta4iDB.mjs → sql-statement-tokens-BdVJnUQY.mjs} +2 -2
  282. package/dist/{sql-statement-tokens-Z5Ta4iDB.mjs.map → sql-statement-tokens-BdVJnUQY.mjs.map} +1 -1
  283. package/dist/sql-tegqTqGq.mjs +1 -1
  284. package/dist/sql.d.mts +1 -1
  285. package/dist/sqlite-adapter-B7r7w3CS.mjs +2 -0
  286. package/dist/sqlite-adapter-B7r7w3CS.mjs.map +1 -0
  287. package/dist/{sqlite-statement-classifier-JBHiQO6Q.mjs → sqlite-statement-classifier-CBmKy8Ta.mjs} +2 -2
  288. package/dist/{sqlite-statement-classifier-JBHiQO6Q.mjs.map → sqlite-statement-classifier-CBmKy8Ta.mjs.map} +1 -1
  289. package/dist/sqlite-storage-audit-D8nA9ylL.mjs +2 -0
  290. package/dist/sqlite-storage-audit-D8nA9ylL.mjs.map +1 -0
  291. package/dist/{sqlite-utils-Bfmtkt1b.mjs → sqlite-utils-BAUMCrok.mjs} +2 -2
  292. package/dist/{sqlite-utils-Bfmtkt1b.mjs.map → sqlite-utils-BAUMCrok.mjs.map} +1 -1
  293. package/dist/sqlite3.d.mts +1 -1
  294. package/dist/sqlite3.mjs +1 -1
  295. package/dist/{standard-sql-Bl2OHGfi.mjs → standard-sql-tpcKlArE.mjs} +2 -2
  296. package/dist/{standard-sql-Bl2OHGfi.mjs.map → standard-sql-tpcKlArE.mjs.map} +1 -1
  297. package/dist/surrealdb.d.mts +2 -2
  298. package/dist/surrealdb.mjs +1 -1
  299. package/dist/surrealdb.mjs.map +1 -1
  300. package/dist/surrealql-AyDLKSEQ.mjs +2 -0
  301. package/dist/surrealql-AyDLKSEQ.mjs.map +1 -0
  302. package/dist/time-step-BIdl2Iy7.mjs +2 -0
  303. package/dist/time-step-BIdl2Iy7.mjs.map +1 -0
  304. package/dist/transaction-operation-CaWzo7gE.mjs +1 -1
  305. package/dist/type-mapping-BYre7JQ1.mjs +3 -0
  306. package/dist/type-mapping-BYre7JQ1.mjs.map +1 -0
  307. package/dist/{types-Dy33vBdd.mjs → types-M-IdB4Mo.mjs} +1 -1
  308. package/dist/{types-Dy33vBdd.mjs.map → types-M-IdB4Mo.mjs.map} +1 -1
  309. package/dist/{unit-DUPX5Sdd.mjs → unit-Dnp2HIWg.mjs} +2 -2
  310. package/dist/{unit-DUPX5Sdd.mjs.map → unit-Dnp2HIWg.mjs.map} +1 -1
  311. package/dist/{unit-words-BXpLpyr2.mjs → unit-words-DjVhRXAQ.mjs} +2 -2
  312. package/dist/{unit-words-BXpLpyr2.mjs.map → unit-words-DjVhRXAQ.mjs.map} +1 -1
  313. package/dist/{utils-BHkJsduV.mjs → utils-BB_4NZQC.mjs} +2 -2
  314. package/dist/{utils-BHkJsduV.mjs.map → utils-BB_4NZQC.mjs.map} +1 -1
  315. package/dist/utils-DYrxwV_M.mjs +2 -0
  316. package/dist/utils-DYrxwV_M.mjs.map +1 -0
  317. package/dist/{v1-parse-shared-cJ-uD14P.mjs → v1-parse-shared-CNiFHAJF.mjs} +1 -1
  318. package/dist/{v1-parse-shared-cJ-uD14P.mjs.map → v1-parse-shared-CNiFHAJF.mjs.map} +1 -1
  319. package/dist/validation-CEnhYqhl.mjs +2 -0
  320. package/dist/{validation-BHjx13zG.mjs.map → validation-CEnhYqhl.mjs.map} +1 -1
  321. package/dist/validation.d.mts +1 -1
  322. package/dist/validation.mjs +1 -1
  323. package/dist/validator-CISkL46K.mjs +2 -0
  324. package/dist/validator-CISkL46K.mjs.map +1 -0
  325. package/dist/{values-Ch2cTlss.mjs → values-D0k60ei0.mjs} +2 -2
  326. package/dist/{values-Ch2cTlss.mjs.map → values-D0k60ei0.mjs.map} +1 -1
  327. package/dist/{client-Dlz3-2JC.d.mts → verify-v1-CJFrJ4lx.d.mts} +10 -183
  328. package/dist/version-nEOMCWfV.mjs +2 -0
  329. package/dist/{version-0BDwfy7C.mjs.map → version-nEOMCWfV.mjs.map} +1 -1
  330. package/dist/view-CmLQ0I6x.mjs +2 -0
  331. package/dist/{view-CHgjF2BO.mjs.map → view-CmLQ0I6x.mjs.map} +1 -1
  332. package/dist/write-sinks-BhwgQn_5.mjs +2 -0
  333. package/dist/{write-sinks-Bei5vFHP.mjs.map → write-sinks-BhwgQn_5.mjs.map} +1 -1
  334. package/package.json +27 -2
  335. package/dist/adapter-namespace-DwFnfpED.mjs +0 -2
  336. package/dist/batch-refs-Bd8HvwUc.mjs +0 -2
  337. package/dist/call-0bd_B9Vp.mjs +0 -2
  338. package/dist/client-D7sWgUt2.mjs +0 -2
  339. package/dist/client-D7sWgUt2.mjs.map +0 -1
  340. package/dist/client-DEfFqv4S.mjs +0 -9
  341. package/dist/client-DEfFqv4S.mjs.map +0 -1
  342. package/dist/datetime-physical-codec-DAF7WJpy.mjs +0 -2
  343. package/dist/datetime-physical-codec-DAF7WJpy.mjs.map +0 -1
  344. package/dist/every-JpbiHdMb.mjs +0 -2
  345. package/dist/extension-Dh1ddrlA.mjs +0 -2
  346. package/dist/extension-Dh1ddrlA.mjs.map +0 -1
  347. package/dist/geo-area-codec-Bti2PA2i.mjs +0 -2
  348. package/dist/id-domain-Cg65TLZ-.mjs +0 -2
  349. package/dist/identifier-conversion-BTDxDwDB.mjs +0 -2
  350. package/dist/identifier-conversion-BTDxDwDB.mjs.map +0 -1
  351. package/dist/introspect-q3Rf_Xv8.mjs +0 -2
  352. package/dist/json-CsAdz9pg.mjs +0 -2
  353. package/dist/judge-words-k5GCc4cV.mjs +0 -2
  354. package/dist/judge-words-k5GCc4cV.mjs.map +0 -1
  355. package/dist/keys-DZdKAd4n.mjs +0 -2
  356. package/dist/libsql-DEZ0uhK2.mjs +0 -3
  357. package/dist/libsql-DEZ0uhK2.mjs.map +0 -1
  358. package/dist/light-D2wNSbzY.mjs +0 -2
  359. package/dist/memory-BaGWNdvk.mjs +0 -2
  360. package/dist/memory-BaGWNdvk.mjs.map +0 -1
  361. package/dist/methods-part-BaNx3o7b.mjs +0 -2
  362. package/dist/model-Dtd37Sky.mjs +0 -2
  363. package/dist/model-Dtd37Sky.mjs.map +0 -1
  364. package/dist/mysql-BFPF8xyv.mjs +0 -9
  365. package/dist/mysql-BFPF8xyv.mjs.map +0 -1
  366. package/dist/mysql-adapter-BFWYPoM0.mjs +0 -2
  367. package/dist/native-types-1ewJXVks.mjs +0 -2
  368. package/dist/native-types-1ewJXVks.mjs.map +0 -1
  369. package/dist/pending-operation-D4gUKMxD.mjs +0 -2
  370. package/dist/postgres-DQQE2ys_.mjs +0 -34
  371. package/dist/postgres-DQQE2ys_.mjs.map +0 -1
  372. package/dist/postgres-adapter-psTVfuw7.mjs +0 -2
  373. package/dist/postgres-adapter-psTVfuw7.mjs.map +0 -1
  374. package/dist/provider-limits-Bcsz0EJv.mjs +0 -2
  375. package/dist/provider-limits-Bcsz0EJv.mjs.map +0 -1
  376. package/dist/query-BTb6iakn.mjs +0 -2
  377. package/dist/query-BTb6iakn.mjs.map +0 -1
  378. package/dist/query-backend-TisPjCPF.mjs +0 -2
  379. package/dist/raw-DqEb71JZ.mjs +0 -2
  380. package/dist/rule-words-DMbQuvD2.mjs +0 -2
  381. package/dist/scalar-Dm9brvAU.mjs +0 -4
  382. package/dist/scalar-Dm9brvAU.mjs.map +0 -1
  383. package/dist/schema-DDkAUfOb.mjs +0 -2
  384. package/dist/schema-DqR_Kcje.mjs +0 -2
  385. package/dist/serializer-ettLu5xG.mjs +0 -33
  386. package/dist/serializer-ettLu5xG.mjs.map +0 -1
  387. package/dist/snowflake-BfF8xwfP.mjs +0 -2
  388. package/dist/sql-Bu63iAfT.mjs +0 -2
  389. package/dist/sqlite-adapter-Cb-SJw2f.mjs +0 -2
  390. package/dist/sqlite-adapter-Cb-SJw2f.mjs.map +0 -1
  391. package/dist/surrealql-DY74AUeD.mjs +0 -2
  392. package/dist/surrealql-DY74AUeD.mjs.map +0 -1
  393. package/dist/time-step-DJaIhpAz.mjs +0 -2
  394. package/dist/time-step-DJaIhpAz.mjs.map +0 -1
  395. package/dist/validation-BHjx13zG.mjs +0 -2
  396. package/dist/validator-DMzH5Tz0.mjs +0 -2
  397. package/dist/validator-DMzH5Tz0.mjs.map +0 -1
  398. package/dist/version-0BDwfy7C.mjs +0 -2
  399. package/dist/view-CHgjF2BO.mjs +0 -2
  400. package/dist/write-sinks-Bei5vFHP.mjs +0 -2
  401. /package/dist/{contract-CxJn0_cV.d.mts → contract-CAoFgKSO.d.mts} +0 -0
  402. /package/dist/{named-statements-NF7Iycjk.d.mts → named-statements-CT4Gbd6t.d.mts} +0 -0
  403. /package/dist/{sql-C4_sFNDm.d.mts → sql-C-SBCGCx.d.mts} +0 -0
@@ -1 +0,0 @@
1
- {"version":3,"file":"query-BTb6iakn.mjs","names":["#keys","#model","#where","AGGREGATE_NAMES","record","relations","entries","own","own","sql","own","#views","#call","#s","#a","#ph","#drops","#instantOf","#rooted","#prepareWhere","#scopes","#prepareScalarPredicate","#capturedSet","#prepareExists","#prepareSlotPredicate","#sc","#prepareOperation","#prepareOperatorFilter","#prepareOperand","#prepareOuterOperand","#prepareFieldOperand","#lf","#checkComparable","#slot","entries","#bm","#relationPredicate","#relationScope","#ps","#prepareCounts","#prepareRelationProjection","#relationShape","#documentShape","#projectCounts","#projectAggregates","#projectVariants","#defaultRelation","#prepareLinkRow","#cr","#compileLeaf","arms","#compileCollection","#compileScalarValue","#fieldReader","#compileList","#compileScalar","member"],"sources":["../src/query-engine/raptor3/shared/row-scope.ts","../src/query-engine/result-aliases.ts","../src/query-engine/result/groupby-fields.ts","../src/query-engine/result/result-shape.ts","../src/query-engine/raptor3/shared/decimal.ts","../src/query-engine/raptor3/shared/identifier.ts","../src/query-engine/raptor3/shared/query.ts"],"sourcesContent":["import type { Judge } from \"@extensions/judge\";\nimport type { Projection } from \"@extensions/projection\";\nimport type { AnyModel } from \"@schema/model\";\nimport { parseProviding } from \"@validation/primitives/object\";\nimport type { PreparedGuardFailure } from \"../../types\";\nimport type { Writer } from \"../write/statements\";\nimport type {\n PreparedDomain,\n PreparedPredicate,\n PreparedSelector,\n Queries,\n Query,\n} from \"./query\";\nimport type { EngineSchema, Input } from \"./schema\";\nimport type { Membership } from \"./storage\";\n\n/**\n * What each model (by its TS name) holds, asked a model at a time: what\n * answers may build a model's entry the first time it is asked, so an entry\n * declared lazily is resolved only for a model a call reaches.\n */\nexport interface ByModel<T> {\n get(model: string): T | undefined;\n}\n\n/**\n * `where` inputs per model (its TS name), as admission left them: a value the\n * call supplies is a {@link Parameter}, a test of one a {@link Condition}. They\n * AND with each other; a model with none is not narrowed. Each list is\n * indexed by layer, the declaring `rule` part's place in the chain, so a\n * layer stating nothing for the model leaves a hole.\n */\nexport type ModelDomain = ByModel<readonly Input[]>;\n\n/** Relations named on demand, among the ones that could be named. */\nexport interface LazyRelations {\n readonly candidates: readonly string[];\n resolve(): readonly string[];\n}\n\n/**\n * The rows an operation may take, by purpose: its own candidates (`root`) and\n * rows it reaches through a relation (`related`).\n */\nexport interface RowDomain {\n readonly root: ModelDomain;\n readonly related: ModelDomain;\n /**\n * What makes a layer's node of a predicate that reads its call (an\n * argument, the instant, a test of an argument): brought by the words\n * that read it. Absent, a layer is what it states.\n */\n readonly layered?: (\n layer: number,\n model: string,\n predicate: PreparedPredicate\n ) => PreparedPredicate;\n /**\n * The same domain read where every argument with a default takes it\n * ({@link CallValues.defaults}): what `CallScope.defaults` prepares.\n * Absent where no argument a predicate reads has a default.\n */\n readonly defaults?: RowDomain;\n /** What a layer's own whole-table sets hold (`rows.confine`), in every mode. */\n readonly confine?: ModelDomain;\n /**\n * Per model (its TS name), indexed by layer as {@link ModelDomain} is, the\n * rule entries of the model. A model absent here judges a write by\n * its purpose's predicates alone.\n */\n readonly rules?: ByModel<readonly (JudgedEntry | undefined)[]> & {\n has(model: string): boolean;\n };\n /**\n * What judges the rows a write produces, made once per prepared domain:\n * stated where some model's entry judges them, by what reads the entries.\n */\n readonly judge?: (domain: PreparedDomain) => Judge;\n /**\n * What a read may carry beside the rows (projection keys) and what it\n * hides of them (read-gated fields), made once per prepared domain: stated\n * where some model's entry may declare either, by what reads the entries.\n */\n readonly project?: (domain: PreparedDomain) => Projection;\n /**\n * What an `excluded` layer states its own whole-table sets of a model hold\n * (`confine`), made once per prepared domain: stated where some member\n * confines one, by what reads the entries.\n */\n readonly bound?: (\n domain: PreparedDomain\n ) => (\n model: AnyModel,\n excluded: readonly number[]\n ) => PreparedSelector | undefined;\n /**\n * Per model (its TS name), the order its reads take when the caller gives\n * none (`orderBy` input, as admitted): a root `findMany`/`findFirst`, a\n * to-many relation read at any depth, and a paged aggregate's window.\n */\n readonly order?: ReadonlyMap<string, readonly Input[]>;\n}\n\n/**\n * One layer's entry for one model beyond its filters, its predicates `P`:\n * as written (`unknown`), then as admission left them (`Input`). `read`\n * (an entry given lazily's `read.where`) ANDs with the layer's predicate at\n * every purpose, a write's own key (`update`, `delete`) with its candidates\n * beside them (R2); a key left out restricts nothing. An update takes, per field its data writes,\n * that field's predicate, else `update`'s. The row a write produces is\n * judged as a value (R4) where a check said so: a created row at `place`;\n * an updated row at the predicates that judged its old row, `check`, and per\n * field it writes, that field's `moves` predicate.\n */\nexport interface JudgedEntry<P = Input> {\n readonly read?: P;\n /**\n * What a row a write returns holds for the layer's projection key and\n * read-gated fields to show, where it is not `read` (an eager entry's\n * read filter is the layer's own).\n */\n readonly shown?: P;\n readonly update?: P;\n readonly delete?: P;\n readonly writes?: ReadonlyMap<string, P>;\n readonly place?: P;\n /** What the row an update leaves holds, where it writes a field this reads. */\n readonly check?: P;\n readonly moves?: ReadonlyMap<string, P>;\n /**\n * Self relations, each held by this model's key, whose links stay\n * acyclic: an update writing one is refused where its new target is the\n * row itself or a row below it. Lazy: the list is resolved only for an\n * update writing the key of one of `candidates`.\n */\n readonly cycles?: LazyRelations;\n /** The projection key the layer declares on the model (K5). */\n readonly as?: string;\n /** What it reports per row: each name with its predicate, in declared order. */\n readonly facts?: ReadonlyMap<string, P>;\n /**\n * Per read-gated field, the predicate a row holds, beside `read`, where it\n * carries the field (K5).\n */\n readonly reads?: ReadonlyMap<string, P>;\n /** A check was written on the entry: the rows its writes produce are judged. */\n readonly judge?: (domain: PreparedDomain) => Judge;\n}\n\n/**\n * What a write lookup is judged at beside its purpose (R3): `delete`, or `update`\n * with the fields the occurrence's data writes, none when it writes only\n * stamps and generated values.\n */\nexport interface WriteJudgement {\n readonly kind: \"update\" | \"delete\";\n readonly writes: readonly string[];\n /**\n * The caller writes a field the model's tombstone manages (sets or clears\n * a marker by hand, a restore): the row is also judged at `delete`, as the\n * tombstone the extension writes is.\n */\n readonly marks?: true;\n}\n\n/**\n * Which rows a candidate lookup takes: the call's own (`root`) or rows reached\n * through a relation (`related`). A lookup that names no purpose is a premise\n * or physical: it takes exactly the selector it is handed.\n */\nexport type RowPurpose = \"root\" | \"related\";\n\n/** What a delete of one model writes instead of removing the row. */\nexport interface Tombstone {\n /** The DateTime field that receives the call's one instant. */\n readonly at?: string;\n /** Constant scalar data, written beside it. */\n readonly assign: Input;\n}\n\n/**\n * What the models that keep the rows they delete write instead, by model,\n * and what a kept row meets where the database would have refused its\n * removal: said by what declares the keeping.\n */\nexport interface Tombstones extends ReadonlyMap<string, Tombstone> {\n /** What a row of `model` takes instead of going; none where its model removes its rows. */\n marks(writer: Writer, model: AnyModel): Input | undefined;\n /** Among the rows that still reference a kept row, the one a call reaches it through restricts nothing. */\n referenced(\n schema: EngineSchema,\n edge: Membership | undefined,\n of?: Input\n ): true | { readonly slot: string; readonly identity: Input };\n /** What a kept row is refused with where a row still references it. */\n restriction(\n schema: EngineSchema,\n model: AnyModel\n ): PreparedGuardFailure | undefined;\n /** Every row of `selector` locked, answered as one row. */\n lock(queries: Queries, selector: PreparedSelector): Query;\n /** The rows of `model` a visible member still references, one member excepted by identity. */\n selector(\n queries: Queries,\n model: AnyModel,\n visible: PreparedDomain | undefined,\n except?: { readonly slot: string; readonly identity: Input }\n ): PreparedSelector;\n}\n\n/**\n * A model's stamps: what the call's extensions write on every create, and on\n * every update, tombstones too. Each is scalar `data` input, as declared with\n * the call's argument values put in: constants and, on an update, the field's\n * update operators.\n */\nexport interface ModelStamps {\n readonly create?: Input;\n readonly update?: Input;\n}\n\n/**\n * Parse the caller's data where validation knows what the call's create\n * stamps write ({@link parseProviding}, by the model's TS name): a required\n * field a stamp writes may be left out, as the stamp writes it after\n * admission. A field whose argument the call left out is not written, so it\n * is still asked for. `parse` is synchronous; a call without stamps never\n * comes here.\n */\nexport const parseStamped = <T>(\n stamps: ReadonlyMap<string, ModelStamps>,\n parse: () => T\n): T =>\n parseProviding(\n (model, field) => stamps.get(model)?.create?.[field] !== undefined,\n parse\n );\n\n/**\n * One root call's row facts, resolved from its arguments outside the engine:\n * the engine never sees a mode or an extension's name, and an argument's only\n * as the key a parameter reads its value under ({@link CallValues}). Its domains\n * are shared by every call that resolves to the same ones; stamps that name a\n * argument are the call's own.\n */\nexport interface CallRows {\n /**\n * The rows the call may take: its predicates read the call's values, or,\n * prepared as the default domain, each argument with a default at its\n * default ({@link CallScope.defaults}).\n */\n readonly domain: RowDomain;\n /**\n * Per managed model, what its deletes write; absent when the call deletes\n * physically (what its `keep` reads of the call says so).\n */\n readonly tombstones?: Tombstones;\n /** Per model (its TS name), the fields its creates and updates write. */\n readonly stamps?: ReadonlyMap<string, ModelStamps>;\n /** What the domains' parameters read; absent when no predicate names one. */\n readonly values?: CallValues;\n /** These facts as the engine reads them through one query owner: what states them says how. */\n readonly prepare: (queries: Queries, instant: () => Date) => CallScope;\n}\n\n/** A call's admitted arguments, and how an absent value resolves (R6). */\nexport interface CallValues {\n readonly args: Readonly<Record<string, unknown>>;\n /** An absent value of `arg` on `model` matches nothing; else it drops. */\n readonly required: (arg: string, model: string) => boolean;\n /**\n * The read view under `domain` for a call carrying these values: one per\n * domain where the same object serves every call that passes them and no\n * predicate reads the instant, else the call's own.\n */\n readonly view?: (domain: PreparedDomain, call: CallScope) => Queries;\n /**\n * The values where every argument with a default takes it, where this\n * call's differ: what the default domain reads (`CallScope.defaults`).\n */\n readonly defaults?: CallValues;\n}\n\n/**\n * A value a domain predicate reads from its call, prepared once and read at\n * lowering: an argument's value, or a field of it along `path`; with no\n * argument, the call's one instant. `null` is absent: a parameter never lowers\n * to `IS NULL`. Its own fields are its spelling (`{ argument, path }` or\n * `{ now: true }`), which no literal of a declaration can be, so a key\n * over declarations tells the two apart.\n */\nexport class Parameter {\n readonly arg?: string;\n readonly path?: string;\n readonly now?: true;\n readonly #keys: readonly string[];\n constructor(arg?: string, path?: string) {\n if (arg === undefined) this.now = true;\n else this.arg = arg;\n if (path !== undefined) this.path = path;\n this.#keys = path === undefined ? [] : path.split(\".\");\n Object.freeze(this);\n }\n /**\n * The call's value, `undefined` when absent. Only a parameter without an\n * argument reads `instant`, and every caller that may hold one passes it.\n */\n read(\n values: Pick<CallValues, \"args\"> | undefined,\n instant?: () => Date\n ): unknown {\n if (this.arg === undefined) return instant!();\n let value = values?.args[this.arg];\n for (const key of this.#keys) {\n if (value === null || typeof value !== \"object\") return undefined;\n value = Object.hasOwn(value, key) ? (value as Input)[key] : undefined;\n }\n return value ?? undefined;\n }\n}\n\n/** What a {@link Condition} asks of its value, in the filter vocabulary. */\nexport type ConditionTest =\n | { readonly exists: boolean }\n | { readonly equals: unknown }\n | { readonly in: readonly unknown[] }\n | { readonly has: unknown }\n | { readonly hasSome: readonly unknown[] };\n\n/** A test of a call value that reads no column: folded per call. */\nexport class Condition {\n readonly parameter: Parameter;\n readonly test: ConditionTest;\n constructor(parameter: Parameter, test: ConditionTest) {\n this.parameter = parameter;\n this.test = test;\n Object.freeze(this);\n }\n holds(\n values: Pick<CallValues, \"args\"> | undefined,\n instant?: () => Date\n ): boolean {\n const value = this.parameter.read(values, instant);\n const test = this.test;\n if (\"exists\" in test) return (value !== undefined) === test.exists;\n if (value === undefined) return false;\n if (\"equals\" in test) return Object.is(value, test.equals);\n if (\"in\" in test) return test.in.includes(value);\n if (!Array.isArray(value)) return false;\n if (\"has\" in test) return value.includes(test.has);\n return test.hasSome.some((member) => value.includes(member));\n }\n}\n\n/**\n * `{ $row: \"<field>\", up: <n> }` in a domain predicate's value position: that\n * column of the row `up` relation bodies above the one the value is compared\n * in (`0`, the same row; an `$exists` body counts as one). Never past the\n * predicate it is written in, nor across a recursive or polymorphic\n * relation. Its own fields are its spelling, so a key over it reads it as\n * plain data.\n */\nexport class OuterColumn {\n readonly $row: string;\n readonly up: number;\n constructor(field: string, up: number) {\n this.$row = field;\n this.up = up;\n Object.freeze(this);\n }\n}\n\n/**\n * `{ $exists: { <model>: <where> } }` in a domain predicate: whether some row\n * of `model` the call may see matches `where`. It reads no column of the row\n * it judges (an uncorrelated `EXISTS`), so a statement can evaluate it once.\n * Its own field is its spelling, with the model by name, so a key over\n * declarations reads it as plain data.\n */\nexport class Existence {\n readonly $exists: Readonly<Record<string, Input>>;\n readonly #model: string;\n readonly #where: Input;\n constructor(model: string, where: Input) {\n this.#model = model;\n this.#where = where;\n this.$exists = Object.freeze({ [model]: where });\n Object.freeze(this);\n }\n /** The model whose rows it looks for (its TS name). */\n get model(): string {\n return this.#model;\n }\n /** What one of them must match, admitted with that model's `where`. */\n get where(): Input {\n return this.#where;\n }\n}\n\n/** The row facts one prepared call carries, and its one instant. */\nexport interface CallScope {\n readonly rows: CallRows;\n /** The call's domain, prepared once per engine view. */\n readonly domain: PreparedDomain;\n /**\n * The domain read where every argument with a default takes it: what a\n * tombstoning delete takes, and every other layer a layer's own\n * traversals read (R5). The call's own where its values are the defaults.\n */\n readonly defaults: PreparedDomain;\n /**\n * The call's one instant (a tombstone's, and `{ now: true }`'s): sampled at\n * its first use and kept for the prepared call's lifetime, so every\n * occurrence of every attempt shares it.\n */\n instant(): Date;\n}\n","/**\n * SQL-only aliases that cannot collide with validated model identifiers.\n * A leading digit survives every supported provider while schema identifiers\n * must start with a letter or underscore.\n */\nexport const DISTANCE_RESULT_KEY = \"0viborm_distance\" as const;\nexport const RELATION_COUNTS_RESULT_KEY = \"0viborm_relation_counts\" as const;\nexport const RELATION_AGGREGATES_RESULT_KEY =\n \"0viborm_relation_aggregates\" as const;\nexport const EMPTY_ROW_RESULT_KEY = \"0viborm_empty_row\" as const;\n/** The `index`-th read gate of one projected row (K5), never published. */\nexport const gateResultKey = (index: number): string => `0viborm_gate:${index}`;\n/**\n * The `index`-th time-step period of a grouped read's window: the column it\n * is computed once in, grouped and ordered by there, published under the\n * grouped field's own name.\n */\nexport const periodColumnKey = (index: number): string =>\n `0viborm_period:${index}`;\n/**\n * The cursor predicate's derived-table carrier, one per requested sort key.\n *\n * A nullable sort column's cursor predicate reads the cursor row's own values\n * out of a derived table, and those values need names that cannot collide with\n * a model identifier — which is this file's whole subject. It lives here, and\n * not as a literal in the engine, so a witness can assert the carrier without\n * pinning a spelling the engine is free to choose (Arnaud's D-21).\n */\nexport const CURSOR_CARRIER_PREFIX = \"0viborm_cursor_\" as const;\n/**\n * The variant slot's INTEGRITY carrier: one count per configured member of the\n * memberships whose target row is gone (Arnaud's D-26).\n *\n * It rides the slot's own document beside the arms, so it takes this file's\n * leading-digit spelling rather than a bare word: the deleted engine could\n * afford `orphans` because it nested every arm one level down under\n * `arms`, and this engine keeps the arms at the document's top level, where a\n * bare carrier name would be reachable by a variant of the same name. A\n * validated identifier cannot start with a digit, so this one cannot collide.\n */\nexport const POLYMORPHIC_COLLECTION_ORPHANS_KEY = \"0viborm_orphans\" as const;\n\nexport type AggregateResultName = \"_count\" | \"_avg\" | \"_sum\" | \"_min\" | \"_max\";\n\nexport function getAggregateResultKey(name: AggregateResultName): string {\n return `0viborm_aggregate:${name.slice(1)}`;\n}\n\nexport function getAggregateResultName(\n key: string\n): AggregateResultName | undefined {\n switch (key) {\n case \"0viborm_aggregate:count\":\n return \"_count\";\n case \"0viborm_aggregate:avg\":\n return \"_avg\";\n case \"0viborm_aggregate:sum\":\n return \"_sum\";\n case \"0viborm_aggregate:min\":\n return \"_min\";\n case \"0viborm_aggregate:max\":\n return \"_max\";\n default:\n return undefined;\n }\n}\n","import { groupedColumn } from \"@validation/model/args/time-step\";\n\n/**\n * The grouped fields of an admitted `by` (a list, duplicates already\n * refused), and those grouped by a time step among them.\n */\nexport function getGroupByFields(by: unknown): {\n readonly fields: string[];\n readonly periods: ReadonlySet<string>;\n} {\n const columns = Array.isArray(by) ? by.map(groupedColumn) : [];\n return {\n fields: columns.map(({ field }) => field),\n periods: new Set(\n columns.filter(({ step }) => step !== undefined).map(({ field }) => field)\n ),\n };\n}\n","import { COUNT_RESULT_KEY } from \"@adapters/shared/result-parsing\";\nimport type { Model } from \"@schema/model\";\nimport {\n type AnyRelation,\n isVariantRelationState,\n slotMayBeEmpty,\n} from \"@schema/relation\";\nimport type { Scalar } from \"@schema/scalars\";\nimport type { ResolvedRelationIndex } from \"@schema/validation/relation-resolution\";\nimport { projectableScalarNames } from \"@validation/model/core/projection\";\nimport type { NormalizedRecurrence } from \"@validation/relations/recurrence\";\nimport { isRecord } from \"@validation/value-guards\";\nimport {\n type AggregateResultName,\n DISTANCE_RESULT_KEY,\n EMPTY_ROW_RESULT_KEY,\n getAggregateResultKey,\n RELATION_AGGREGATES_RESULT_KEY,\n RELATION_COUNTS_RESULT_KEY,\n} from \"../result-aliases\";\nimport {\n type ExpectedAggregateResultShape,\n type ExpectedPolymorphicResultShape,\n type ExpectedPolymorphicVariantShape,\n type ExpectedRelationAggregateShape,\n type ExpectedRelationResultShape,\n type ExpectedResultShape,\n type Operation,\n QueryEngineError,\n} from \"../types\";\nimport { getGroupByFields } from \"./groupby-fields\";\n\nconst MODEL_ROW_OPERATIONS = new Set<Operation>([\n \"findFirst\",\n \"findMany\",\n \"findUnique\",\n \"create\",\n \"createManyAndReturn\",\n \"update\",\n \"updateManyAndReturn\",\n \"delete\",\n \"deleteManyAndReturn\",\n \"upsert\",\n]);\n\n/**\n * The registered refusal for a second `_distance` in one select, stated once\n * for both result views: this schema-only shape and Raptor 3's prepared\n * projection (`raptor3/shared/query.ts`) raise it.\n */\nexport const DISTANCE_SELECTED_TWICE = \"Only one _distance per select.\";\n\n/**\n * The node one arm of a variant slot is read with, or `undefined` when the\n * selection leaves that arm out of the result. One rule for both result views:\n * this schema-only shape and Raptor 3's prepared projection\n * (`raptor3/shared/query.ts`).\n *\n * Only a collection's `only` narrows the arms; admission deduplicates it and\n * refuses a `variants` key outside it. A singular slot has no such key: its row\n * belongs to exactly one arm, so every arm is read and an arm the selection\n * leaves unnamed is read at its model's default projection (`true`), which\n * keeps the result union exhaustive\n * (docs/content/docs/schema/relations/polymorphic.mdx). An admitted arm is\n * `true` or a relation node; admission has no `false` arm.\n */\nexport function selectedArm(\n selection: unknown,\n many: boolean,\n variant: string\n): unknown {\n const configuration = isRecord(selection) ? selection : undefined;\n if (!many) return getOwnValue(configuration, variant) ?? true;\n const only = getOwnValue(configuration, \"only\");\n if (Array.isArray(only) && !only.includes(variant)) return undefined;\n const arms = getOwnValue(configuration, \"variants\");\n return (isRecord(arms) ? getOwnValue(arms, variant) : undefined) ?? true;\n}\n\nconst AGGREGATE_NAMES: readonly AggregateResultName[] = [\n \"_count\",\n \"_avg\",\n \"_sum\",\n \"_min\",\n \"_max\",\n];\n\nfunction getOwnValue<T>(\n record: Readonly<Record<string, T>> | undefined,\n key: string\n): T | undefined {\n return record && Object.hasOwn(record, key) ? record[key] : undefined;\n}\n\nfunction createShape(\n rawKeys: string[],\n relations = new Map<string, ExpectedRelationResultShape>(),\n aggregates = new Map<string, ExpectedAggregateResultShape>(),\n relationCounts = new Set<string>(),\n polymorphic = new Map<string, ExpectedPolymorphicResultShape>(),\n distanceScalar?: Scalar\n): ExpectedResultShape {\n if (new Set(rawKeys).size !== rawKeys.length) {\n throw new QueryEngineError(\n \"The requested result shape contains colliding output columns.\"\n );\n }\n return {\n carrier: \"rows\",\n rawKeys,\n ...(distanceScalar ? { distanceScalar } : {}),\n relations,\n polymorphic,\n aggregates,\n relationCounts,\n };\n}\n\nfunction selectedEntries(value: unknown): [string, unknown][] {\n if (!isRecord(value)) return [];\n return Object.entries(value).filter(\n ([, selected]) => selected !== false && selected !== undefined\n );\n}\n\nfunction getNestedSelection(value: unknown): Record<string, unknown> {\n if (!isRecord(value)) return {};\n const nested: Record<string, unknown> = {};\n const select = getOwnValue(value, \"select\");\n const include = getOwnValue(value, \"include\");\n if (isRecord(select)) nested.select = select;\n if (isRecord(include)) nested.include = include;\n return nested;\n}\n\nfunction buildModelShape(\n model: Model<any>,\n args: Record<string, unknown>,\n index: ResolvedRelationIndex\n): ExpectedResultShape {\n const rawKeys: string[] = [];\n const relations = new Map<string, ExpectedRelationResultShape>();\n const polymorphic = new Map<string, ExpectedPolymorphicResultShape>();\n const scalars: Record<string, Scalar> = model[\"~\"].state.scalars;\n const modelRelations = model[\"~\"].state.relations;\n const selectValue = getOwnValue(args, \"select\");\n const includeValue = getOwnValue(args, \"include\");\n const select = isRecord(selectValue) ? selectValue : undefined;\n const include = isRecord(includeValue) ? includeValue : undefined;\n let hasDistance = false;\n let distanceScalar: Scalar | undefined;\n\n if (select) {\n for (const [fieldName, value] of Object.entries(select)) {\n const scalar: Scalar | undefined = getOwnValue(scalars, fieldName);\n if (!scalar) continue;\n if (value === true) {\n rawKeys.push(fieldName);\n continue;\n }\n if (isRecord(value) && Object.hasOwn(value, \"_distance\")) {\n if (hasDistance) {\n throw new QueryEngineError(DISTANCE_SELECTED_TWICE);\n }\n hasDistance = true;\n distanceScalar = scalar;\n rawKeys.push(DISTANCE_RESULT_KEY);\n }\n }\n } else {\n for (const fieldName of projectableScalarNames(model)) {\n rawKeys.push(fieldName);\n }\n }\n\n addSelectedRelations(\n model,\n modelRelations,\n select,\n rawKeys,\n relations,\n index\n );\n addSelectedPolymorphicRelations(model, select, rawKeys, polymorphic, index);\n\n addSelectedRelations(\n model,\n modelRelations,\n include,\n rawKeys,\n relations,\n index\n );\n addSelectedPolymorphicRelations(model, include, rawKeys, polymorphic, index);\n const relationCountSelections = [\n getOwnValue(select, \"_count\"),\n getOwnValue(include, \"_count\"),\n ];\n const relationCounts = new Set<string>();\n for (const countSelection of relationCountSelections) {\n if (!isRecord(countSelection)) continue;\n const countSelect = getOwnValue(countSelection, \"select\");\n if (!isRecord(countSelect)) continue;\n for (const [relationName] of selectedEntries(countSelect)) {\n const relation: AnyRelation | undefined = getOwnValue(\n modelRelations,\n relationName\n );\n if (!relation) continue;\n // ONE map, one rule: a variant COLLECTION joins the count surface\n // (plan §7.4); a variant SINGULAR slot has no collection to count, and\n // its `countFilter` family is a named refusal for the same reason.\n const state = relation[\"~\"].state;\n if (isVariantRelationState(state) && state.cardinality !== \"many\") {\n continue;\n }\n relationCounts.add(relationName);\n }\n }\n\n if (relationCounts.size > 0) {\n rawKeys.push(RELATION_COUNTS_RESULT_KEY);\n }\n\n // Admission admits an `_aggregate` entry on an ordinary to-many relation only.\n const relationAggregates = new Map<string, ExpectedRelationAggregateShape>();\n for (const selection of [\n getOwnValue(select, \"_aggregate\"),\n getOwnValue(include, \"_aggregate\"),\n ]) {\n for (const [relationName, entry] of selectedEntries(selection)) {\n const relation: AnyRelation | undefined = getOwnValue(\n modelRelations,\n relationName\n );\n if (!(relation && isRecord(entry))) continue;\n relationAggregates.set(relationName, {\n model: relation[\"~\"].settleTarget() as Model<any>,\n shape: buildAggregateShape(entry),\n });\n }\n }\n if (relationAggregates.size > 0) rawKeys.push(RELATION_AGGREGATES_RESULT_KEY);\n\n // A written `select` that keeps nothing never arrives: admission refuses it.\n if (rawKeys.length === 0) rawKeys.push(EMPTY_ROW_RESULT_KEY);\n\n return {\n ...createShape(\n rawKeys,\n relations,\n new Map(),\n relationCounts,\n polymorphic,\n distanceScalar\n ),\n ...(relationAggregates.size > 0 ? { relationAggregates } : {}),\n };\n}\n\n/**\n * The recurrence admission normalized onto this relation node. Admission\n * (`validation/relations/recurrence.ts`) is its only producer, so the admitted\n * value is read, never re-parsed; a node without `recurse` answers `undefined`.\n */\nfunction admittedRecurrence(value: unknown): NormalizedRecurrence | undefined {\n if (!isRecord(value)) return undefined;\n return getOwnValue(value, \"recurse\") as NormalizedRecurrence | undefined;\n}\n\nfunction addSelectedRelations(\n model: Model<any>,\n modelRelations: Model<any>[\"~\"][\"state\"][\"relations\"],\n selection: Record<string, unknown> | undefined,\n rawKeys: string[],\n relations: Map<string, ExpectedRelationResultShape>,\n index: ResolvedRelationIndex\n): void {\n for (const [relationName, value] of selectedEntries(selection)) {\n const relation: AnyRelation | undefined = getOwnValue(\n modelRelations,\n relationName\n );\n // ONE relation map, split here by TARGET KIND: a variant slot produces a\n // tagged carrier, which the polymorphic pass below shapes instead.\n if (!relation || isVariantRelationState(relation[\"~\"].state)) continue;\n const targetModel = relation[\"~\"].settleTarget() as Model<any>;\n rawKeys.push(relationName);\n const shape = buildModelShape(\n targetModel,\n getNestedSelection(value),\n index\n );\n const resolved = index.get(model)?.get(relationName);\n const recurrence = admittedRecurrence(value);\n relations.set(relationName, {\n model: targetModel,\n shape,\n cardinality: relation[\"~\"].state.cardinality,\n optional: resolved !== undefined && slotMayBeEmpty(resolved),\n ...(recurrence ? { recurrence } : {}),\n });\n }\n}\n\n/**\n * The expected shape of one polymorphic projection. It records exactly the arms\n * {@link selectedArm} reads, each with the node it reads it with.\n */\nfunction addSelectedPolymorphicRelations(\n model: Model<any>,\n selection: Record<string, unknown> | undefined,\n rawKeys: string[],\n polymorphic: Map<string, ExpectedPolymorphicResultShape>,\n index: ResolvedRelationIndex\n): void {\n const modelRelations = model[\"~\"].state.relations;\n for (const [relationName, value] of selectedEntries(selection)) {\n const relation: AnyRelation | undefined = getOwnValue(\n modelRelations,\n relationName\n );\n if (!relation) continue;\n const state = relation[\"~\"].state;\n if (!isVariantRelationState(state)) continue;\n\n const many = state.cardinality === \"many\";\n const variants = new Map<string, ExpectedPolymorphicVariantShape>();\n for (const publicType of Object.keys(state.target.entries)) {\n const arm = selectedArm(value, many, publicType);\n if (arm === undefined) continue;\n const targetModel = relation[\"~\"].settleTarget(publicType) as Model<any>;\n variants.set(publicType, {\n model: targetModel,\n shape: buildModelShape(targetModel, getNestedSelection(arm), index),\n });\n }\n\n rawKeys.push(relationName);\n const resolved = index.get(model)?.get(relationName);\n polymorphic.set(relationName, {\n // CARDINALITY is the declaration's own fact — the slot the factory was\n // spelled with. EMPTINESS is not: it is the resolved edge's answer, which\n // for a row carrier IS the nullability of its private `(type, id)` pair\n // (§8.4).\n cardinality: state.cardinality,\n optional: resolved !== undefined && slotMayBeEmpty(resolved),\n variants,\n });\n }\n}\n\nfunction buildAggregateShape(\n args: Record<string, unknown>,\n groupedFields: readonly string[] = []\n): ExpectedResultShape {\n const rawKeys = [...groupedFields];\n const selectedOutputKeys = new Set(groupedFields);\n const aggregates = new Map<string, ExpectedAggregateResultShape>();\n\n for (const aggregateName of AGGREGATE_NAMES) {\n const spec = getOwnValue(args, aggregateName);\n if (spec === undefined || spec === false) continue;\n\n let fields: ReadonlySet<string> | undefined;\n if (!(aggregateName === \"_count\" && spec === true)) {\n const entries = selectedEntries(spec);\n if (entries.length === 0) continue;\n fields = new Set(entries.map(([fieldName]) => fieldName));\n }\n\n if (selectedOutputKeys.has(aggregateName)) {\n throw new QueryEngineError(\n `GroupBy cannot return both grouped scalar '${aggregateName}' and aggregate '${aggregateName}' in one result.`\n );\n }\n\n const rawKey = getAggregateResultKey(aggregateName);\n rawKeys.push(rawKey);\n selectedOutputKeys.add(aggregateName);\n aggregates.set(rawKey, {\n ...(fields ? { fields } : {}),\n });\n }\n\n return createShape(rawKeys, new Map(), aggregates);\n}\n\nfunction buildCountShape(args: Record<string, unknown>): ExpectedResultShape {\n const fields = selectedEntries(getOwnValue(args, \"select\")).map(\n ([fieldName]) => fieldName\n );\n return {\n ...createShape(fields.length === 0 ? [COUNT_RESULT_KEY] : fields),\n carrier: \"count\",\n };\n}\n\nexport function buildExpectedResultShape(\n model: Model<any>,\n operation: Operation,\n args: Record<string, unknown>,\n relations: ResolvedRelationIndex\n): ExpectedResultShape | undefined {\n if (operation === \"count\") return buildCountShape(args);\n if (operation === \"exist\") {\n return {\n ...createShape([COUNT_RESULT_KEY]),\n carrier: \"existence\",\n };\n }\n if (operation === \"aggregate\") return buildAggregateShape(args);\n if (operation === \"groupBy\") {\n const { fields, periods } = getGroupByFields(getOwnValue(args, \"by\"));\n return { ...buildAggregateShape(args, fields), periods };\n }\n if (MODEL_ROW_OPERATIONS.has(operation)) {\n return buildModelShape(model, args, relations);\n }\n return undefined;\n}\n","/**\n * The engine's decimal seam: every place Raptor 3 hands a value to the\n * central decimal codec, in one decimal-named module.\n *\n * The codec owns what an exact decimal is. This module owns what the engine\n * adds when it asks: which codec entry a traversal takes (a bound literal, a\n * list member, a widened `_sum`, an internal or a public result), the\n * provider's representation with its one default, and the engine's sentence\n * for a value the codec refuses. The query owner reaches the codec only\n * through here, so the census that reads every decimal module in full reads\n * this one, and the owner's integer, date and JSON readers stay outside a\n * decimal region — the shape the retired engine kept with its\n * `decimal-result-decode` and `decimal-field` modules.\n */\nimport type { DatabaseAdapter } from \"@adapters/database-adapter\";\nimport type { ScalarState } from \"@schema/scalars/common\";\nimport {\n canonicalizeDecimal,\n type DecimalDescriptor,\n decodePhysicalDecimal,\n decodePhysicalDecimalList,\n decodePhysicalWidenedSum,\n encodePhysicalDecimalListMembers,\n logicalToCoefficient,\n materializePhysicalDecimal,\n materializePhysicalWidenedSum,\n sameDecimalDescriptor,\n toDecimal,\n} from \"@validation/primitives/decimal-codec\";\nimport { engineFault } from \"./terms\";\n\nexport type { DecimalDescriptor } from \"@validation/primitives/decimal-codec\";\n\n/** The provider's result contract, where its decimal spellings are declared. */\ntype ResultContract = DatabaseAdapter[\"result\"];\n\n/**\n * The declared domain of an exact decimal COLUMN, or `undefined` when the state\n * is not one. A list answers `undefined`: its members live in a container and\n * the scalar comparison this domain governs is not one a list has.\n */\nexport function exactDecimalDomain(\n state: ScalarState\n): DecimalDescriptor | undefined {\n return state.type === \"decimal\" && state.array !== true\n ? state.decimal\n : undefined;\n}\n\n/** The declared domain a decimal field must carry before a value can bind. */\nexport function requireDecimal(\n state: ScalarState,\n field: string\n): DecimalDescriptor {\n if (!state.decimal)\n engineFault(`Decimal '${field}' has no declared precision/scale.`);\n return state.decimal;\n}\n\nexport function canonicalDecimal(value: unknown, field: string): string {\n const canonical = canonicalizeDecimal(value);\n if (canonical === undefined)\n engineFault(`Decimal '${field}' value is not an exact decimal.`);\n return canonical;\n}\n\nexport function decimalMembers(\n state: ScalarState,\n values: readonly unknown[],\n field: string,\n result: ResultContract\n): string[] {\n const members = encodePhysicalDecimalListMembers(\n values,\n requireDecimal(state, field),\n result.decimalListRepresentation ?? \"text\"\n );\n if (members === undefined)\n engineFault(`Decimal list '${field}' member is not an exact decimal.`);\n return members;\n}\n\n/** Whether an arithmetic operand is the exact zero no provider may divide by. */\nexport function dividesByZero(by: unknown): boolean {\n return canonicalizeDecimal(by) === \"0\";\n}\n\n/** Two exact decimal columns compare only in one declared domain. */\nexport function sameDecimalDomain(\n own: DecimalDescriptor,\n other: DecimalDescriptor\n): boolean {\n return sameDecimalDescriptor(own, other);\n}\n\n/**\n * A `having` `_sum` operand: its canonical form and its coefficient at the\n * domain's scale, or `undefined` when the value is not an exact decimal.\n */\nexport function decimalSumOperand(\n value: unknown,\n domain: DecimalDescriptor\n): { readonly canonical: string; readonly coefficient: string } | undefined {\n const canonical = canonicalizeDecimal(value);\n if (canonical === undefined) return undefined;\n return {\n canonical,\n coefficient: logicalToCoefficient(canonical, domain.scale),\n };\n}\n\n/**\n * One decimal result cell: a widened `_sum` keeps the field scale and drops\n * its precision; an internal read keeps the codec's form, a public one\n * materializes the Decimal. `undefined` is the codec's refusal.\n */\nexport function decodeDecimalScalar(\n value: unknown,\n descriptor: DecimalDescriptor,\n widened: boolean,\n internal: boolean,\n result: ResultContract\n): unknown {\n const representation = result.decimalRepresentation ?? \"text\";\n if (widened)\n return internal\n ? decodePhysicalWidenedSum(value, descriptor, representation)\n : materializePhysicalWidenedSum(value, descriptor, representation);\n return internal\n ? decodePhysicalDecimal(value, descriptor, representation)\n : materializePhysicalDecimal(value, descriptor, representation);\n}\n\n/** One decimal list result cell; `undefined` is the codec's refusal. */\nexport function decodeDecimalList(\n value: unknown,\n descriptor: DecimalDescriptor,\n internal: boolean,\n result: ResultContract\n): unknown[] | undefined {\n const members = decodePhysicalDecimalList(\n value,\n descriptor,\n result.decimalListRepresentation ?? \"text\"\n );\n if (members === undefined) return undefined;\n return internal ? members : members.map((member) => toDecimal(member));\n}\n","/**\n * The engine's identifier seam: every place Raptor 3 hands a value to the\n * identifier codec, in one identifier-named module — the sibling of\n * `decimal.ts`, and for the same reason.\n *\n * Two facts, asked together because no seam needs one without the other. The\n * DOMAIN — declared by a named format, or derived by L5 from the key a foreign\n * key references — says which strings a column holds and what their canonical\n * spelling is (`idDomainOf`). The REPRESENTATION says what the column\n * physically holds for one, and it is the ADAPTER's answer\n * (`result.idRepresentation`, derived from the one storage owner\n * `idStorageOf`): `bytea` on PostgreSQL and `BINARY(16)` on MySQL are the same\n * ULID, and the engine is not allowed to know which dialect it is building for.\n *\n * This module knows no format's bytes and spells no SQL of its own: the codec\n * (`validation/primitives/id-codec.ts`) owns the bytes, and every expression\n * below is an adapter member. A field with no domain answers `undefined` from\n * {@link identifierColumn}, and every path stays the one it was.\n */\nimport type { DatabaseAdapter, EngineFacts } from \"@adapters/database-adapter\";\nimport type { AnyModel } from \"@schema/model\";\nimport { idDomainOf } from \"@schema/validation/id-domains\";\nimport type { ResolvedRelationIndex } from \"@schema/validation/relation-resolution\";\nimport type { Sql } from \"@sql\";\nimport {\n decodePhysicalId,\n describeIdDomain,\n encodePhysicalId,\n type IdDomain,\n type IdRepresentation,\n sameIdDomain,\n} from \"@validation/primitives/id-codec\";\nimport type { PhysicalField } from \"./storage\";\nimport { scalarsOf } from \"./terms\";\n\n/** One identifier column: what it admits, and what it physically holds. */\nexport interface IdentifierColumn {\n readonly domain: IdDomain;\n readonly representation: IdRepresentation;\n}\n\n/**\n * The domain and representation of one stored column, or `undefined` when it\n * holds no identifier domain.\n *\n * A declared scalar is its own key. A PRIVATE column — a polymorphic row\n * carrier's id column — holds no field of its own: it holds some model key's\n * values, and that key's domain may be DERIVED (the one-to-one child whose\n * primary key is its parent foreign key), and derivation is keyed by (model,\n * field), never by a scalar instance two models may share. So the private\n * column NAMES the key it stands in for (`PhysicalField.reference`) and is\n * resolved through the same lookup, against that key; the type discriminator\n * names none. A junction side needs no such name: every binding of it already\n * goes through the referenced key (`Queries.junctionWhere`).\n */\nexport function identifierColumn(\n adapter: EngineFacts,\n index: ResolvedRelationIndex,\n model: AnyModel,\n field: string,\n physical: PhysicalField\n): IdentifierColumn | undefined {\n const key =\n scalarsOf(model)[field] === undefined\n ? physical.reference\n : { model, field };\n if (key === undefined) return undefined;\n const domain = idDomainOf(key.model, key.field, index);\n if (domain === undefined) return undefined;\n const representation =\n adapter.result.idRepresentation?.(\n domain,\n scalarsOf(key.model)[key.field]?.[\"~\"].nativeType\n ) ?? \"text\";\n return { domain, representation };\n}\n\n/**\n * Whether the column holds something other than the public string itself —\n * payload bytes, or a PostgreSQL `uuid`. A text-stored domain is NOT compact:\n * it binds, projects, collates and aggregates exactly as any string column.\n */\nexport function isCompact(\n column: IdentifierColumn | undefined\n): column is IdentifierColumn {\n return column !== undefined && column.representation !== \"text\";\n}\n\n/**\n * The physical value ONE compact identifier binds as.\n *\n * INVARIANT, not a refusal (N4): every value that reaches a binding of an\n * identifier column crossed the field's validation schema, which admitted and\n * canonicalized it into the domain — a payload, a `{ set }`, a filter operand,\n * a cursor, a unique selector, a connect key — or is a captured row key, which\n * the decoder returned as the canonical public string. A `Sql` operand never\n * reaches here: it is the caller's physical fragment.\n */\nexport function encodeIdentifier(\n column: IdentifierColumn,\n value: unknown\n): string | Uint8Array {\n return encodePhysicalId(\n value as string,\n column.domain,\n column.representation\n )!;\n}\n\n/** The public string one physical identifier value stands for, or `undefined`. */\nexport function decodeIdentifier(\n column: IdentifierColumn,\n value: unknown\n): string | undefined {\n return decodePhysicalId(value, column.domain, column.representation);\n}\n\n/**\n * One compact identifier expression, spelled for TRANSPORT: lowercase hex for\n * a byte column, the column itself otherwise.\n *\n * A byte column travels as hex in a flat select exactly as inside a JSON\n * carrier. JSON cannot hold binary at all, so the carrier has no choice;\n * making the flat read take the same spelling keeps ONE physical promise per\n * column — the decoder reads the same text whether the row came back from a\n * top-level select or three levels inside an `include`, and the drivers' many\n * binary shapes stop being a variable.\n *\n * `nullable` is a fact about the EXPRESSION, not only about the column: a\n * `MIN()` over no rows is null however the column is declared. The guard is a\n * measured requirement, not symmetry: SQLite's `hex(NULL)` is the EMPTY\n * STRING, so without it a null identifier reads as a zero-byte one.\n */\nexport function transportedIdentifier(\n adapter: DatabaseAdapter,\n column: IdentifierColumn | undefined,\n expression: Sql,\n nullable: boolean\n): Sql {\n if (column?.representation !== \"bytes\") return expression;\n const hex = adapter.expressions.blobToHex(expression);\n return nullable\n ? adapter.expressions.caseWhen(\n [\n {\n when: adapter.operators.isNull(expression),\n then: adapter.literals.null(),\n },\n ],\n hex\n )\n : hex;\n}\n\n/**\n * What `MIN`/`MAX` run OVER for one compact identifier: its transported TEXT.\n *\n * Two facts force it, either alone decisive: PostgreSQL has no `min(uuid)`\n * and no `max(bytea)`, and JSON — the aggregate carrier — cannot hold binary.\n * The answer is the same: every compact format's canonical text is\n * fixed-width and lowercase, so its text order IS its byte order. The null\n * guard travels INSIDE the aggregate, where SQLite's `hex(NULL)` would\n * otherwise be the empty string that wins every `MIN`.\n */\nexport function aggregatedIdentifier(\n adapter: DatabaseAdapter,\n column: IdentifierColumn | undefined,\n expression: Sql\n): Sql {\n if (column?.representation === \"uuid\")\n return adapter.expressions.cast(expression, \"text\");\n return transportedIdentifier(adapter, column, expression, true);\n}\n\n/** One phrase naming a column's identifier storage, for the refusal below. */\nfunction describeStorage(column: IdentifierColumn | undefined): string {\n if (column === undefined) return \"plain string\";\n return `${describeIdDomain(column.domain)} (${column.representation})`;\n}\n\nexport function incomparableIdentifiers(\n own: IdentifierColumn | undefined,\n other: IdentifierColumn | undefined,\n ownField: string,\n otherField: string\n): string | undefined {\n const representation = own?.representation ?? \"text\";\n if (representation === (other?.representation ?? \"text\")) {\n if (representation === \"text\") return undefined;\n if (sameIdDomain(own?.domain, other?.domain)) return undefined;\n }\n return `'${ownField}' (${describeStorage(own)}) incompatible with '${otherField}' (${describeStorage(other)}).`;\n}\n","import { assembleAdapterSelect } from \"@adapters/adapter-internals\";\nimport { passThroughParseField } from \"@adapters/adapter-result-parser\";\nimport type { DatabaseAdapter, EngineFacts } from \"@adapters/database-adapter\";\nimport type { DriverResultParser } from \"@drivers/exports\";\nimport type { Dialect } from \"@drivers/types\";\nimport {\n QueryEngineError,\n TransactionError,\n UnsupportedOperationError,\n VibORMError,\n} from \"@errors\";\nimport type { PreparedDomain } from \"@extensions/row-domain\";\nimport {\n DISTANCE_SELECTED_TWICE,\n selectedArm,\n} from \"@query-engine/result/result-shape\";\nimport {\n EMPTY_ROW_RESULT_KEY,\n POLYMORPHIC_COLLECTION_ORPHANS_KEY,\n} from \"@query-engine/result-aliases\";\nimport { fieldRefPayload, formatFieldRef, isFieldRef } from \"@schema/field-ref\";\nimport { jsonNullKindOf } from \"@schema/json-null\";\nimport {\n type AnyModel,\n findAddressableKey,\n getModelKeyCatalog,\n type OrderedModelKey,\n} from \"@schema/model\";\nimport { slotMayBeEmpty } from \"@schema/relation/clearability\";\nimport type { Scalar } from \"@schema/scalars/base\";\nimport type { ScalarState } from \"@schema/scalars/common\";\nimport type { NativeTypeDeclaration } from \"@schema/scalars/native-types\";\nimport type {\n ResolvedSlot,\n ResolvedVariantEdge,\n} from \"@schema/validation/relation-resolution\";\nimport { type ViewFacts, viewFacts } from \"@schema/view/facts\";\nimport { Sql, sql } from \"@sql\";\nimport { defaultProjectionNames } from \"@validation/model/core/projection\";\nimport { normalizeBinaryValue } from \"@validation/primitives/binary-shapes\";\nimport {\n type DateTimePhysicalForm,\n decodePhysicalDateTime,\n decodeProviderTimestamp,\n} from \"@validation/primitives/datetime-physical-codec\";\nimport {\n isDateTimeClock,\n isDateTimeInstant,\n} from \"@validation/primitives/datetime-values\";\nimport { validateGeoPoint } from \"@validation/primitives/geo-point-codec\";\nimport {\n carriesRepeatedKey,\n DEFAULT_MAX_OCCURRENCES,\n type NormalizedRecurrence,\n} from \"@validation/relations/recurrence\";\nimport type { Operation } from \"../../types\";\nimport {\n type DecimalDescriptor,\n decodeDecimalList,\n decodeDecimalScalar,\n exactDecimalDomain,\n sameDecimalDomain,\n} from \"./decimal\";\nimport {\n decodeIdentifier,\n type IdentifierColumn,\n identifierColumn,\n incomparableIdentifiers,\n} from \"./identifier\";\nimport type { ModelSql } from \"./insert-value\";\nimport {\n type CallScope,\n type CallValues,\n Condition,\n Existence,\n OuterColumn,\n Parameter,\n type RowPurpose,\n type WriteJudgement,\n} from \"./row-scope\";\nimport {\n type Arguments,\n type DefaultRelation,\n type EngineSchema,\n entries,\n type Input,\n memo,\n type QueryViews,\n type ReadOperation,\n record,\n} from \"./schema\";\nimport { type Membership, type PhysicalField, physicalField } from \"./storage\";\nimport {\n engineFault,\n fromEntries,\n hasOwn,\n isArr,\n isObj,\n isPlain,\n listed,\n nameOf,\n objEntries,\n objKeys,\n objValues,\n pushTo,\n same,\n scalarsOf,\n tableOf,\n unsupported,\n} from \"./terms\";\n\n/** `Object.freeze`, named once for what an extension states and shares. */\nexport const freeze = Object.freeze;\n\nexport type Leaf = {\n kind: \"scalar\";\n type: string;\n nullable: boolean;\n /**\n * The DECLARING scalar, for consumers that compile a value codec from it.\n *\n * The fields beside it are a projection of this object's state, which SQL\n * lowering and row decoding read; a codec owner such as\n * a result value codec is addressed by the object itself and must\n * never re-dispatch on `type`, which would be a second scalar-meaning\n * authority (g4/unit03/note.md FU.6 B-1c). Absent on the leaves no declared\n * scalar produces — `_count`, `exist`, a non-decimal `_avg`, `_distance` —\n * whose meaning is the aggregate's, not a column's.\n */\n scalar?: Scalar;\n /** A list column: the container decodes once, then each member as `type`. */\n list?: boolean;\n decimal?: DecimalDescriptor;\n /**\n * A `_sum` answering outside the field's domain: a decimal keeps the field\n * scale and drops its precision, a bigint may leave the int64 range, a\n * number may be `±Infinity`, and an int past 2^53 is the nearest double, as\n * a number sum is; `splitSum` states which travel as two parts.\n */\n widened?: boolean;\n /** The declared physical timestamp spelling of this column. */\n dateTime?: DateTimePhysicalForm;\n /**\n * The column's identifier domain and what it physically holds, resolved\n * once per (adapter, model, field) — a foreign key's DERIVED domain and a\n * private carrier column's referenced key included (`identifier.ts`).\n */\n id?: IdentifierColumn;\n enumValues?: ReadonlySet<string>;\n dimension?: number;\n /**\n * A time-step period (`groupBy`'s `{ column: step }`): the adapter's\n * `YYYY-MM-DD AD|BC` text of its first day, published as an ISO day. A\n * period may begin outside the DateTime domain (the week of 0000-01-01, the\n * year a zone moves 9999-12-31 into), so it is read as a calendar day, not\n * through the instant codec.\n */\n period?: true;\n};\nexport type ProjectionShape =\n | {\n kind: \"object\";\n /**\n * `false` where the statement ALWAYS builds this document and says so —\n * a relation `_count` carrier. A provider `null` there is a malformed\n * row, not an absent relation. Left unset (nullable) everywhere a row\n * may genuinely be absent: a to-one relation, a variant arm. An\n * aggregate carrier (`_count`/`_sum`/`_avg`/`_min`/`_max` of\n * `aggregate`/`groupBy`) is always built too but is left unset, so a\n * provider `null` there publishes `null`: a compatibility answer\n * `tests/raptor3/result-decoder.test.ts` pins, not a stated contract.\n */\n nullable?: boolean;\n fields: Record<string, ProjectionShape | Leaf>;\n /**\n * Read-gated members (K5): each is present only where its gate, one of\n * `gates`, reads true; where it reads false the member is left out, or,\n * when the caller named it, the read fails at `refused`.\n */\n gated?: Readonly<Record<string, GatedMember>>;\n /** The boolean members the row carries for `gated`, never published. */\n gates?: readonly string[];\n }\n | CollectionShape\n | {\n kind: \"variants\";\n /** The public slot, for the refusal that names it. */\n relation: string;\n many: false;\n arms: Record<string, ProjectionShape>;\n }\n | {\n kind: \"variants\";\n relation: string;\n /** A junction-carried slot: each arm is a collection of its rows. */\n many: true;\n arms: Record<string, CollectionShape>;\n }\n | {\n kind: \"recursive\";\n relation: string;\n many: boolean;\n optional: boolean;\n recurrence: NormalizedRecurrence;\n row: ProjectionShape;\n identity: readonly Leaf[];\n };\nexport type Shape = ProjectionShape;\n/** One read-gated member of a document: its gate, and the path a caller named it at. */\nexport interface GatedMember {\n readonly gate: string;\n readonly refused?: string;\n}\n/** A to-many relation's rows. */\ntype CollectionShape = {\n kind: \"collection\";\n /** A negative `take` runs a reversed window; the decoder restores it. */\n reversed?: boolean;\n row: ProjectionShape;\n};\n/**\n * A physical value's provider continuation ({@link Queries.fieldReader}),\n * bound to one execution's driver and adapter.\n */\ntype FieldReader = (value: unknown) => unknown;\n/**\n * One placement of the projection language, compiled for one decoded batch\n * ({@link Queries.compileReader}): it reads the provider's value there and\n * answers the public one.\n */\nexport type Reader = (value: unknown) => unknown;\n/**\n * A scalar placement's compiled reader, and the `typeof` of the values it\n * answers unchanged when it has one.\n */\ninterface CompiledLeaf {\n readonly read: Reader;\n readonly unchanged: string | undefined;\n}\ntype RelationProjectionArguments = Pick<\n Partial<Arguments>,\n \"orderBy\" | \"take\" | \"skip\" | \"cursor\" | \"distinct\"\n> & {\n readonly selector?: Pick<PreparedSelector, \"model\" | \"predicate\">;\n};\n/** The link row columns one relation node reads: `$through`. */\ninterface PreparedLinkRow {\n readonly model: AnyModel;\n readonly fields: readonly string[];\n readonly shape: Extract<ProjectionShape, { kind: \"object\" }>;\n}\nexport interface PreparedRelationProjection {\n readonly edge: Membership;\n readonly linkRow?: PreparedLinkRow;\n /** A nested `where`'s `$through`, tested on the link this page joins. */\n readonly linkWhere?: Pick<PreparedSelector, \"model\" | \"predicate\">;\n readonly arguments: RelationProjectionArguments;\n readonly projection: PreparedProjection;\n readonly recurrence?: NormalizedRecurrence;\n}\n/**\n * One aggregate selection, as `aggregate`, `groupBy` and a relation's\n * `_aggregate` admit it ({@link Queries.aggregateSelection}): the decoder\n * shape of each selected aggregate, and the members it was built from, in that\n * shape's own key order. A lowering builds each carrier from `members`.\n */\nexport interface PreparedAggregates {\n readonly shape: Record<string, Shape | Leaf>;\n /** Each aggregate, in {@link AGGREGATES} order: `undefined` for `_count: true`'s row count. */\n readonly members: readonly {\n readonly name: Aggregate;\n readonly fields: readonly string[] | undefined;\n }[];\n}\n/** One `_aggregate` entry: a relation's rows, the filter that narrows them, what is aggregated. */\nexport interface PreparedRelationAggregate {\n readonly relation: string;\n readonly edge: Membership;\n readonly selector?: Pick<PreparedSelector, \"model\" | \"predicate\">;\n readonly selection: PreparedAggregates;\n}\n/** One counted slot: its memberships, and the filter that narrows them. */\nexport type PreparedCount = {\n readonly relation: string;\n /** Every membership the slot counts: one edge, or every variant arm. */\n readonly edges: readonly Membership[];\n readonly selector?: Pick<PreparedSelector, \"model\" | \"predicate\">;\n /** A tagged `isNot` counts the arm's members the selector does NOT match. */\n readonly negated?: true;\n};\nexport type PreparedProjectionField =\n | { readonly kind: \"scalar\"; readonly name: string }\n /** A view's JSON column, read as it is stored: the document a read carries. */\n | { readonly kind: \"document\"; readonly name: string }\n | {\n /**\n * The sentinel column of an EMPTY default projection. A model whose\n * every scalar is omitted still has rows, and `SELECT FROM …` is a\n * syntax error, so one constant column carries the row's existence. It\n * is not in the decoder's shape, so the caller reads `{}`.\n */\n readonly kind: \"sentinel\";\n readonly name: string;\n }\n | {\n readonly kind: \"counts\";\n readonly name: string;\n readonly counts: readonly PreparedCount[];\n }\n | {\n readonly kind: \"aggregates\";\n readonly name: string;\n readonly aggregates: readonly PreparedRelationAggregate[];\n }\n | {\n /**\n * A declared projection key (K5): per row, whether each named\n * predicate holds beside the layer's `read`.\n */\n readonly kind: \"evidence\";\n readonly name: string;\n readonly evidence: DeclaredEvidence;\n readonly names: readonly (readonly [string, Input])[];\n }\n | {\n /** A read-gated member's gate (K5): a boolean the decoder reads. */\n readonly kind: \"gate\";\n readonly name: string;\n readonly gate: FieldGate;\n }\n | {\n readonly kind: \"distance\";\n readonly name: string;\n readonly field: string;\n readonly specification: Input;\n }\n | ({\n readonly kind: \"relation\";\n readonly name: string;\n } & PreparedRelationProjection)\n | {\n readonly kind: \"variants\";\n readonly name: string;\n readonly many: boolean;\n readonly arms: readonly ({\n readonly variant: string;\n } & PreparedRelationProjection)[];\n /**\n * Every CONFIGURED member of a junction-carried slot, selected or not:\n * the subjects of the integrity probe (Arnaud's D-26). `only` selects\n * what is READ, never what is TRUE, so this list is not the arms'.\n */\n readonly memberships: readonly {\n readonly variant: string;\n readonly edge: Extract<Membership, { kind: \"junction\" }>;\n }[];\n };\nexport interface PreparedProjection {\n readonly model: AnyModel;\n readonly fields: readonly PreparedProjectionField[];\n readonly shape: Extract<ProjectionShape, { kind: \"object\" }>;\n}\n\n/**\n * May this prepared projection ride a mutation's `RETURNING`?\n *\n * The projection owner answers, because the answer is a property of how each\n * field LOWERS: a scalar is a column of the mutated row, while a relation\n * carrier, a variant slot and a `_count` all read OTHER rows through a\n * correlated subquery, which no `RETURNING` carries. A physical owner asking\n * \"does this name a relation?\" was the same question answered a second time.\n *\n * This is the RELOCATION of that one kind-test into the module that owns the\n * kinds — not a new per-field fact and not a wider rule. A `_distance` is an\n * expression over the mutated row's own columns and could ride a `RETURNING`,\n * but no provider in the qualified set declares the distance tier, so nothing\n * can witness that arm; it stays outside the gate until one can.\n */\nexport function returningSafeProjection(\n projection: PreparedProjection\n): boolean {\n return projection.fields.every(\n (field) => field.kind === \"scalar\" || field.kind === \"sentinel\"\n );\n}\n/**\n * May decoding this projection REFUSE a row its statement already answered?\n * A read-gated member (`GatedFieldRefusal`), a recursive relation (its output\n * budget, a rejected cycle) and a variant slot (its integrity probe) each\n * raise while decoding, after the statement. A write that answers its\n * projection in its own statement (`OperationContext.answersInStatement`)\n * could not roll back under such a refusal, so this owner says which do. A\n * malformed provider result is not counted: it is no refusal of the row.\n */\nexport function refusesWhileDecoding(projection: PreparedProjection): boolean {\n return projection.fields.some(\n (field) =>\n field.kind === \"gate\" ||\n field.kind === \"variants\" ||\n (field.kind === \"relation\" &&\n (field.recurrence !== undefined ||\n refusesWhileDecoding(field.projection)))\n );\n}\nexport interface Query {\n sql: Sql;\n shape: Shape;\n expectedRows?: {\n readonly count: number;\n readonly missing: Error;\n };\n}\n/** What a {@link Queries.select} takes beyond its arguments. */\nexport interface SelectControls {\n forUpdate?: boolean;\n identity?: Input;\n projection?: PreparedProjection;\n selector?: Pick<PreparedSelector, \"model\" | \"predicate\">;\n /** Rows this selector does not take, NULL read as not taken. */\n unless?: Pick<PreparedSelector, \"model\" | \"predicate\">;\n /** The rows the read takes: its selector and cursor anchor under it. */\n purpose?: RowPurpose;\n /**\n * The relation the root row is read FROM in place of the model's table: a\n * `WITH` member of the same statement carrying the table's columns (a\n * write's `RETURNING *`, `OperationContext`'s projection over its own write).\n */\n source?: string;\n}\n/**\n * What writes a read in a database's language. {@link Queries} is the SQL one;\n * a driver supplies another through `driver.backend`. It takes the admitted\n * arguments and answers one statement with its shape, and decoding stays shared.\n */\nexport interface ReadBackend {\n read(model: AnyModel, operation: ReadOperation, args: Arguments): Read;\n}\n/** One statement plus the operation's own cardinality and public shape. */\nexport interface Read {\n readonly query: Query;\n /**\n * Does this verb publish ONE value rather than the row set? Stated here, by\n * the owner that decides the cardinality, so no consumer re-derives it.\n */\n readonly single: boolean;\n /**\n * The PUBLIC value's own shape — which is not always the row shape\n * `query.shape` decodes: `count` publishes a number and `exist` a boolean\n * over a row of `{_count}`, and `findMany`/`groupBy` publish the set of rows.\n */\n readonly value: ProjectionShape | Leaf;\n result(rows: Input[]): unknown;\n}\n/**\n * What a write asks of a selector before it trusts what it knows of a row:\n * the row's own fields the selector reads, the values every row it takes\n * holds, and the relations it reads other rows through.\n */\nexport interface SelectorFacts {\n fields: Set<string>;\n /**\n * The literal equalities the selector's own conjunction states: what every\n * row it takes holds. An equality under an `OR` or a `NOT`, or inside a\n * relation's body, is none.\n */\n equals: Map<string, unknown>;\n /**\n * The admitted unique selector's DISCRIMINATOR pins: the literal equality of\n * every `key: true` prepared column, which is exactly what the shipped\n * `partitionWhereUnique` files under `entries`\n * (`write-engine/shared.ts:154-166`). An extended `where`'s filter half and\n * every entry of a selector admitted as a filter are absent by\n * construction: they are `equals` and not a pin.\n */\n keys: Map<string, unknown>;\n exact: boolean;\n /** The models, and the junction tables, whose rows the selector reads besides its own row. */\n reads: Set<AnyModel | string>;\n}\n/** Expressions compared as one: a row value, or the expression itself alone. */\nexport function rowValue(items: Sql[]): Sql {\n return items.length === 1 ? items[0]! : sql`(${listed(items)})`;\n}\n/** Every column of `query`, read through a derived table named `alias`. */\nexport function throughDerived(\n adapter: DatabaseAdapter,\n query: Sql,\n alias: string\n): Sql {\n return assembleAdapterSelect(adapter, {\n columns: sql.raw(\"*\"),\n from: adapter.subqueries.correlate(query, alias),\n });\n}\nexport function newSelectorFacts(exact = true): SelectorFacts {\n return {\n fields: new Set(),\n equals: new Map(),\n keys: new Map(),\n exact,\n reads: new Set(),\n };\n}\n/**\n * The facts of what `facts`' selector holds apart: an arm of an `OR` or a\n * `NOT` (`own`: it reads the same row's fields), a relation's body. It reads\n * what the selector reads and pins nothing of the selector's row.\n */\nconst apart = (facts: SelectorFacts, own = false): SelectorFacts => ({\n ...newSelectorFacts(false),\n reads: facts.reads,\n ...(own && { fields: facts.fields }),\n});\nexport type PreparedScalar = {\n readonly model: AnyModel;\n readonly field: string;\n readonly physical: PhysicalField;\n};\nexport type PreparedOperand =\n | { readonly kind: \"value\"; readonly value: unknown }\n | {\n readonly kind: \"field\";\n readonly scalar: PreparedScalar;\n /** An enclosing row's column: how many relation bodies above (`$row`). */\n readonly up?: number;\n }\n /**\n * A call value of a domain predicate, read at lowering; `spread` when it is\n * a whole `in`/`notIn` list, one value operand per member once read.\n */\n | {\n readonly kind: \"parameter\";\n readonly parameter: Parameter;\n readonly spread?: true;\n }\n | {\n readonly kind: \"sql\";\n readonly strings: readonly string[];\n readonly operands: readonly Extract<\n PreparedOperand,\n { kind: \"value\" | \"field\" }\n >[];\n };\n/** An operand as lowering reads it: every parameter's value read. */\nexport type BoundOperand = Exclude<PreparedOperand, { kind: \"parameter\" }>;\n/**\n * What a prepared operator compares. A physical column, a JSON value addressed\n * inside one, and an aggregate over a column are three targets of the SAME\n * operator vocabulary — `where` and `having` never interpret operators twice.\n */\n/** A scalar column's declared state, as the lowering reads it. */\nexport type ScalarStateOf = PreparedScalar[\"physical\"][\"scalar\"][\"~\"][\"state\"];\nexport type PreparedTarget =\n | {\n readonly kind: \"column\";\n readonly scalar: PreparedScalar;\n readonly path?: readonly string[];\n /**\n * The column is addressed as a member of a unique `where`'s DISCRIMINATOR\n * rather than as a filter, so the comparison is the CONSTRAINT's, not the\n * engine's text contract: it names the row the provider's own unique\n * index holds under this value.\n *\n * A byte-exact conjunct here would ask a stricter question than the index\n * that answers it — on a case-insensitive collation a probe could report\n * a key free and the very next INSERT be rejected for duplicating it —\n * so the shipped engine spells exactly this half with the dialect's plain\n * equality (`buildUniqueEquality`, `builders/where-unique-builder.ts:213`)\n * and leaves the extended `where`'s filter half to `buildWhere`.\n */\n readonly key?: true;\n }\n | {\n readonly kind: \"aggregate\";\n readonly aggregate: Aggregate;\n readonly scalar?: PreparedScalar;\n };\n/**\n * A recursive relation filter's range ({@link PreparedPredicate}), and\n * whether its author stated it selective ({@link NormalizedRecurrence}).\n */\nexport type Closure = {\n readonly depth: number | false;\n readonly self: boolean;\n readonly selective?: true;\n};\n/** A row read through columns a walk or a key set carries, by field. */\nexport type CarriedRow = (field: string) => Sql;\nexport type PreparedPredicate =\n | {\n readonly kind: \"and\" | \"or\";\n readonly predicates: readonly PreparedPredicate[];\n }\n | { readonly kind: \"not\"; readonly predicate: PreparedPredicate }\n | { readonly kind: \"always\"; readonly value: boolean }\n /** A test of a call value that reads no column. */\n | { readonly kind: \"condition\"; readonly condition: Condition }\n | {\n /**\n * Whether some row of `model` the call may see holds `predicate` (any\n * row without one): reads no column of the row it judges, so it is\n * the same everywhere in a statement (`$exists`).\n */\n readonly kind: \"exists\";\n readonly model: AnyModel;\n readonly predicate?: PreparedPredicate;\n }\n | {\n /**\n * One layer's domain predicate for `model`, the unit R6 judges: what\n * made it says what it is for a call (`resolve`: `undefined` where the\n * call drops it), over the row read under `alias` where one is given.\n * While it lowers, its relation reads take every other layer at its\n * default and never this one (R5).\n */\n readonly kind: \"layer\";\n readonly layer: number;\n readonly model: string;\n readonly predicate: PreparedPredicate;\n readonly resolve: (\n queries: Queries,\n alias?: string\n ) => PreparedPredicate | undefined;\n }\n | {\n readonly kind: \"operation\";\n readonly operator: string;\n readonly target: PreparedTarget;\n readonly operand?: PreparedOperand;\n readonly operands?: readonly PreparedOperand[];\n readonly value?: unknown;\n readonly insensitive?: boolean;\n /**\n * Set on a bounded GeoPoint `distance` filter in POSITIVE polarity: the\n * comparison implies the bounding box of its smallest finite upper\n * bound, so the box is a conjunct the provider can answer from the\n * spatial index. Under a negation the box would be part of what is\n * negated, which is why polarity is a preparation fact and not a\n * lowering guess.\n */\n readonly probe?: true;\n }\n | {\n readonly kind: \"relation\";\n readonly edge: Membership;\n readonly quantifier: string;\n readonly predicate?: PreparedPredicate;\n /**\n * The relation is correlated by membership alone: the predicate states\n * which members count itself, so the lowering `Queries`' domain never\n * joins it (a premise that names its own visibility).\n */\n readonly unscoped?: true;\n /**\n * The quantifier ranges over the edge's CLOSURE from the parent row: the\n * rows 1..`depth` hops away (every hop when `depth` is false), and the\n * parent itself when `self` holds. The cycle policy is deliberately not\n * carried: a set does not depend on the paths that reach it.\n */\n readonly closure?: Closure;\n /**\n * `$through`: what the link row joining each target must hold, tested\n * with the target's own conditions on that one link. A model's scalars\n * only, so it reads no other row and no bound ever narrows it.\n */\n readonly link?: PreparedPredicate;\n readonly linkFields?: readonly string[];\n }\n | {\n /** The first `limit` rows of `selector` in key order ({@link Queries.window}). */\n readonly kind: \"window\";\n readonly selector: PreparedSelector;\n readonly limit: number;\n };\nexport type OperationPredicate = Extract<\n PreparedPredicate,\n { kind: \"operation\" }\n>;\n/** An operation as lowering reads it ({@link Queries.lowerOperation}). */\nexport type BoundOperation = Omit<\n OperationPredicate,\n \"operand\" | \"operands\"\n> & {\n readonly operand?: BoundOperand;\n readonly operands?: readonly BoundOperand[];\n};\n/**\n * A conjunction of nothing states nothing; every other prepared predicate is a\n * condition. This is the one reading of \"this arm built no condition\" that the\n * shipped builders express by answering `undefined`\n * (`builders/where-builder.ts:217-308`, `operations/groupby-having.ts:77-173`).\n */\nexport function states(predicate: PreparedPredicate): boolean {\n if (predicate.kind === \"layer\") return states(predicate.predicate);\n return predicate.kind !== \"and\" || predicate.predicates.some(states);\n}\n/**\n * An `OR` whose every arm is one value equality on the same plain column, as\n * that column's `in` (platform-15): the same three-valued answer, so a long\n * chain binds as the one list `in` binds instead of one arm per expression\n * level. A JSON, list, point or vector column compares by its own rules, a\n * folded or referenced operand is not a member, and `null` is `IS NULL`.\n */\nconst unwrap = (arm: PreparedPredicate): PreparedPredicate => {\n let current = arm;\n while (current.kind === \"and\" && current.predicates.length === 1)\n current = current.predicates[0]!;\n return current;\n};\nfunction sameColumnIn(\n arms: readonly PreparedPredicate[]\n): PreparedPredicate | undefined {\n const operands: PreparedOperand[] = [];\n let target: Extract<PreparedTarget, { kind: \"column\" }> | undefined;\n for (let arm of arms) {\n arm = unwrap(arm);\n const operand = arm.kind === \"operation\" ? arm.operand : undefined;\n if (\n arm.kind !== \"operation\" ||\n arm.operator !== \"equals\" ||\n arm.insensitive ||\n arm.target.kind !== \"column\" ||\n arm.target.path ||\n operand?.kind !== \"value\" ||\n operand.value === null ||\n operand.value instanceof Sql ||\n (target &&\n (arm.target.scalar.model !== target.scalar.model ||\n arm.target.scalar.field !== target.scalar.field ||\n arm.target.key !== target.key))\n )\n return;\n target ??= arm.target;\n operands.push(operand);\n }\n const state = target?.scalar.physical.state;\n if (\n !target ||\n state?.array === true ||\n state?.type === \"json\" ||\n state?.type === \"point\" ||\n state?.type === \"vector\"\n )\n return;\n return {\n kind: \"operation\",\n operator: \"in\",\n target,\n operands,\n insensitive: false,\n };\n}\ntype RelationPredicate = Extract<PreparedPredicate, { kind: \"relation\" }>;\nconst MERGED_QUANTIFIERS = {\n or: new Set([\"some\", \"is\"]),\n and: new Set([\"none\", \"isNot\"]),\n} as const;\n/** The arms of a `kind` connective, through nested ones and one-member `and`s. */\nfunction connectiveArms(\n kind: \"and\" | \"or\",\n arms: readonly PreparedPredicate[],\n into: PreparedPredicate[]\n): PreparedPredicate[] {\n for (let arm of arms) {\n arm = unwrap(arm);\n if (arm.kind === kind) connectiveArms(kind, arm.predicates, into);\n else into.push(arm);\n }\n return into;\n}\n/** Do two quantifiers range over the same rows: edge, quantifier, scope, walk? */\nfunction sameRange(left: RelationPredicate, right: RelationPredicate): boolean {\n return (\n // A body is merged over one range; a link condition belongs to its own.\n left.link === undefined &&\n right.link === undefined &&\n left.edge === right.edge &&\n left.quantifier === right.quantifier &&\n left.unscoped === right.unscoped &&\n left.closure?.depth === right.closure?.depth &&\n left.closure?.self === right.closure?.self\n );\n}\n/**\n * The arms of a `kind` connective with every group of quantifiers over the\n * same range ({@link MERGED_QUANTIFIERS}) merged into the first of them, its\n * body the disjunction of theirs in their order; `undefined` where no two\n * merge, so a connective with nothing to merge keeps its own structure. The\n * merged relation states one subquery (and one recursive walk) where each\n * arm stated its own: an acceptance rule's three ancestor walks per\n * document level become two.\n */\nexport function mergeQuantifiers(\n kind: \"and\" | \"or\",\n arms: readonly PreparedPredicate[]\n): PreparedPredicate[] | undefined {\n const quantifiers: ReadonlySet<string> = MERGED_QUANTIFIERS[kind];\n let candidates = 0;\n for (const arm of arms) candidates += quantifiedArms(arm, kind, quantifiers);\n if (candidates < 2) return;\n const merged: PreparedPredicate[] = [];\n const groups: [\n at: number,\n head: RelationPredicate,\n bodies: PreparedPredicate[],\n selective: boolean,\n ][] = [];\n for (const arm of connectiveArms(kind, arms, [])) {\n if (\n arm.kind === \"relation\" &&\n arm.predicate !== undefined &&\n quantifiers.has(arm.quantifier)\n ) {\n const group = groups.find(([, head]) => sameRange(head, arm));\n if (group) {\n group[2].push(arm.predicate);\n group[3] &&= arm.closure?.selective === true;\n continue;\n }\n groups.push([\n merged.length,\n arm,\n [arm.predicate],\n arm.closure?.selective === true,\n ]);\n }\n merged.push(arm);\n }\n let changed = false;\n for (const [at, head, bodies, selective] of groups) {\n if (bodies.length === 1) continue;\n changed = true;\n const { closure } = head;\n merged[at] = {\n ...head,\n predicate: disjunction(bodies),\n ...(closure?.selective &&\n !selective && {\n closure: { depth: closure.depth, self: closure.self },\n }),\n };\n }\n return changed ? merged : undefined;\n}\n/** How many arms of a `kind` connective `arm` holds that may merge. */\nfunction quantifiedArms(\n arm: PreparedPredicate,\n kind: \"and\" | \"or\",\n quantifiers: ReadonlySet<string>\n): number {\n if (arm.kind === \"relation\")\n return arm.predicate !== undefined && quantifiers.has(arm.quantifier)\n ? 1\n : 0;\n if (arm.kind !== kind && !(arm.kind === \"and\" && arm.predicates.length === 1))\n return 0;\n let count = 0;\n for (const member of arm.predicates)\n count += quantifiedArms(member, kind, quantifiers);\n return count;\n}\n/** `predicates` AND-ed, as they stand. */\nexport const conjunction = (\n predicates: readonly PreparedPredicate[]\n): PreparedPredicate => ({ kind: \"and\", predicates });\n/**\n * `arms` OR-ed: one column's `in` ({@link sameColumnIn}), the quantifiers\n * over one relation merged ({@link mergeQuantifiers}), or the `or` itself.\n */\nfunction disjunction(arms: readonly PreparedPredicate[]): PreparedPredicate {\n const sameColumn = sameColumnIn(arms);\n if (sameColumn) return sameColumn;\n const merged = mergeQuantifiers(\"or\", arms);\n if (merged === undefined) return { kind: \"or\", predicates: arms };\n return merged.length === 1 ? merged[0]! : { kind: \"or\", predicates: merged };\n}\n/** Does the predicate read another row: a relation subquery anywhere in it? */\nexport function readsRelation(predicate: PreparedPredicate): boolean {\n switch (predicate.kind) {\n case \"relation\":\n case \"exists\":\n return true;\n case \"and\":\n case \"or\":\n return predicate.predicates.some(readsRelation);\n case \"not\":\n case \"layer\":\n return readsRelation(predicate.predicate);\n default:\n return false;\n }\n}\n/**\n * The smallest FINITE upper bound a distance filter states, or `undefined`\n * when it states none. A bound of zero or less bounds nothing worth probing:\n * the box degenerates to the point itself.\n */\nexport function distanceUpperBound(value: unknown): number | undefined {\n if (!isObj(value)) return undefined;\n const { lt, lte } = value;\n const bounds = [lt, lte].filter(\n (bound): bound is number => typeof bound === \"number\" && bound > 0\n );\n return bounds.length === 0 ? undefined : Math.min(...bounds);\n}\n\nfunction orphanedArm(carrier: unknown, arm: ProjectionShape): boolean {\n if (arm.kind !== \"object\" || carrier === null || carrier === undefined)\n return false;\n const document = providerJson(carrier);\n if (!isObj(document)) return false;\n return objKeys(document).length === 0 && objKeys(arm.fields).length > 0;\n}\n\nexport function providerJson(value: unknown): unknown {\n return typeof value === \"string\" ? JSON.parse(value) : value;\n}\n\nexport function providerDocument(value: unknown): Input | null | undefined {\n if (value === null) return null;\n return typeof value === \"object\" && !isArr(value)\n ? (value as Input)\n : undefined;\n}\n\nexport function providerMembers(\n value: unknown,\n size: number\n): unknown[] | null | undefined {\n const members = providerJson(value);\n if (members === null) return null;\n return isArr(members) && members.length === size ? members : undefined;\n}\n\nexport function own(source: Record<string, unknown>, key: string): unknown {\n return hasOwn(source, key) ? source[key] : undefined;\n}\n\nexport const CURSOR_ORDER_REFUSAL = \"Cursor requires scalar orderBy.\";\n/** A disjunction of nothing is FALSE; it is the one predicate that says so. */\nexport const VACUOUS_FALSE: PreparedPredicate = {\n kind: \"always\",\n value: false,\n};\n/** One normalized sort key; `f` marks a direct scalar a cursor can use. */\nexport interface OrderTerm {\n /** expression */\n readonly e: Sql;\n /** descending */\n readonly d: boolean;\n /** nulls placement */\n readonly n: \"first\" | \"last\";\n /** expressionNulls */\n readonly x?: true;\n /** nullable */\n readonly b: boolean;\n /** field */\n readonly f?: string;\n}\nexport interface PreparedSelector {\n readonly model: AnyModel;\n readonly facts: SelectorFacts;\n readonly uniqueKey?: OrderedModelKey;\n readonly uniqueValues?: ReadonlyMap<string, unknown>;\n readonly predicate?: PreparedPredicate;\n /**\n * A row domain narrowed this selector ({@link Queries.candidates}): it\n * states more than its unique key, so a consumer that would trust the key\n * alone to name the row must not.\n */\n readonly scoped?: true;\n}\n/** The decoder identifies the invalid value; its operation owns public errors. */\nexport class InvalidScalarResult extends TypeError {\n readonly scalarType: string;\n readonly reason: string;\n constructor(scalarType: string, reason: string) {\n super(`Invalid provider ${scalarType === \"int\" ? \"integer\" : scalarType}`);\n this.scalarType = scalarType;\n this.reason = reason;\n }\n}\n\n/** Refuses a value a provider returned: it is not of the kind the read asked for. */\nfunction refuseResult(scalarType: string, reason = \"invalid\"): never {\n throw new InvalidScalarResult(scalarType, reason);\n}\n\n/**\n * A recursive projection decoded more occurrences under one outer row than\n * its budget (`recurse.maxOccurrences`). The decoder knows the slot; as for\n * {@link InvalidScalarResult}, its operation owns the public error.\n */\nexport class RecursiveOutputOverBudget extends RangeError {\n readonly relation: string;\n readonly limit: number;\n constructor(relation: string, limit: number) {\n super(`Recursive '${relation}' exceeds ${limit} occurrences`);\n this.relation = relation;\n this.limit = limit;\n }\n /** The result-size refusal of `operation`, which ran the projection. */\n refusal(operation: Operation, model: string): UnsupportedOperationError {\n return new UnsupportedOperationError(\n `'${operation}' exceeded maxOccurrences (${this.limit}) on '${this.relation}'.`,\n {\n meta: {\n model,\n operation,\n relation: this.relation,\n feature: \"recursive output budget\",\n },\n }\n );\n }\n}\n\n/**\n * An error raised while a result is read that states its own refusal: as for\n * {@link InvalidScalarResult}, its operation owns the public error.\n */\nexport interface ResultRefusal {\n refusal(operation: Operation, model: string): Error;\n}\n\n/** The public output name of a `_distance` projection, stated once. */\nconst DISTANCE_FIELD = \"_distance\";\n/**\n * The private recursive carrier's member names, stated once: the one wire\n * vocabulary the recursive lowering writes and `decodeRecursiveCarrier` reads.\n */\nexport const RECURSIVE_CARRIER = {\n r: \"__rq_root\",\n n: \"__rq_nodes\",\n e: \"__rq_edges\",\n k: \"__rq_key\",\n w: \"__rq_row\",\n p: \"__rq_parent\",\n c: \"__rq_child\",\n d: \"__rq_depth\",\n};\nexport const AGGREGATES = [\"_count\", \"_avg\", \"_sum\", \"_min\", \"_max\"] as const;\n/**\n * The aggregate vocabulary as a TYPE, so the lowering switch over it is\n * exhaustive by construction rather than by a sentence (N4, plan §4).\n * {@link isAggregate} is the ONE narrowing of a payload key into it — the same\n * set admission enumerates (`validation/model/args/aggregate.ts`), never a\n * second one.\n */\nexport type Aggregate = (typeof AGGREGATES)[number];\nconst AGGREGATE_NAMES: ReadonlySet<string> = new Set(AGGREGATES);\nexport function isAggregate(name: string): name is Aggregate {\n return AGGREGATE_NAMES.has(name);\n}\nexport const BOOLEAN_LEAF: Leaf = {\n kind: \"scalar\",\n type: \"boolean\",\n nullable: false,\n};\nexport const COUNT_LEAF: Leaf = {\n kind: \"scalar\",\n type: \"int\",\n nullable: false,\n};\nconst QUANTIFIERS: ReadonlySet<string> = new Set(\n \"is isNot some every none\".split(\" \")\n);\nconst FILTER_OPERATORS: ReadonlySet<string> = new Set(\n \"equals not in notIn lt lte gt gte contains startsWith endsWith mode has hasEvery hasSome isEmpty path string_contains string_starts_with string_ends_with array_contains array_starts_with array_ends_with within distance\".split(\n \" \"\n )\n);\n\nconst SINGLE_OPS: ReadonlySet<string> = new Set(\n \"equals lt lte gt gte contains startsWith endsWith\".split(\" \")\n);\n\n/**\n * Whether an admitted object addresses operators rather than being one whole\n * value. Only the two scalars whose own values ARE objects can be ambiguous.\n */\nfunction addressesOperators(\n state: ScalarState | undefined,\n value: Input\n): boolean {\n if (!isPlain(value)) return false;\n if (state?.type !== \"json\" && state?.type !== \"point\") return true;\n return objKeys(value).some((key) => FILTER_OPERATORS.has(key));\n}\n\nconst ARITHMETIC_UPDATES = [\n \"increment\",\n \"decrement\",\n \"multiply\",\n \"divide\",\n] as const;\nconst LIST_UPDATES = [\"push\", \"unshift\"] as const;\n\n/** One admitted scalar update payload, interpreted once and lowered twice. */\nexport type PreparedUpdate =\n | { readonly kind: \"value\"; readonly value: unknown }\n | {\n readonly kind: \"arithmetic\";\n readonly operator: (typeof ARITHMETIC_UPDATES)[number];\n readonly by: unknown;\n }\n | {\n readonly kind: \"list\";\n readonly operator: (typeof LIST_UPDATES)[number];\n readonly members: readonly unknown[];\n };\n\nexport function wholeValue(\n value: unknown\n): { readonly value: unknown } | undefined {\n if (value instanceof Sql || !isPlain(value)) return { value };\n return hasOwn(value, \"set\") ? { value: value.set } : undefined;\n}\n\nexport function readUpdate(value: unknown): PreparedUpdate {\n const whole = wholeValue(value);\n if (whole) return { kind: \"value\", value: whole.value };\n const operation = value as Input;\n for (const operator of ARITHMETIC_UPDATES)\n if (hasOwn(operation, operator))\n return { kind: \"arithmetic\", operator, by: operation[operator] };\n for (const operator of LIST_UPDATES)\n if (hasOwn(operation, operator)) {\n const members = operation[operator];\n return {\n kind: \"list\",\n operator,\n members: isArr(members) ? members : [members],\n };\n }\n engineFault(`Unknown update op: ${objKeys(operation).join(\", \")}`);\n}\n\n/** Query scopes and output shapes share no record-identity requirement. */\n/**\n * A temporal operand's WIRE form: what the ADMISSION boundary makes of it.\n *\n * A payload's instant crossed `validation/primitives/iso.ts` before it reached\n * this engine — `Date` in, ISO spelling out — and a value the engine DECODED\n * is the `Date` of that same instant, which is bound BACK whenever an\n * identity, a membership or a premise is built from a row the engine read: a\n * `dateTime` or `date` key captured on a transport without RETURNING answers\n * `UPDATE … WHERE (\"id\" = ? OR \"id\" = ?)`, and no driver binds a `Date`\n * (\"SQLite3 can only bind numbers, strings, bigints, buffers, and null\"). So a\n * captured instant crosses the same boundary the payload did, which spells a\n * `Date` as `Date.prototype.toISOString` produces it (`iso.ts:75`).\n *\n * That spelling addresses the row wherever the column's stored form is\n * INSTANT-valued — SQLite INTEGER/REAL, the PostgreSQL and MySQL timestamp\n * types — and wherever the payload's own spelling was that one. A TEXT-stored\n * `dateTime` admits MORE than one spelling of one instant: the same boundary\n * admits a valid ISO STRING unchanged (`ok(value)`, `iso.ts:94`) and the\n * SQLite adapter keeps that string byte for byte\n * (`sqlite-adapter.ts:288-296`), so a key written `2020-03-01T10:00:00Z` or\n * with a `+02:00` offset is stored as those bytes and `…:00.000Z` names no\n * row of its own. Nothing here re-spells it: a capture of such a column never\n * decodes to a `Date` at all, because the row decoder keeps the PROVIDER's\n * spelling for an INTERNAL read and materializes the `Date` only for a public\n * one ({@link Queries.decodeScalar}, the split the decimal arm beside it\n * already takes). A string reaches this function only to pass through, so the\n * captured identity binds the stored bytes and the spelling still has exactly\n * one owner (FC-02B, which repaired `g4/release/n5/note.md` §6's residual).\n * Every other value passes through untouched. The other captured domains bind\n * as they are — measured: `bigint`, `decimal` and `time` are already\n * provider-bindable, and `blob`, `json`, `point` and `vector` can be neither a\n * key nor a unique, so no identity carries one.\n */\nexport function admittedTemporal(\n value: unknown,\n admit: (value: unknown) => { value: string } | { issues: unknown }\n): unknown {\n if (!(value instanceof Date)) return value;\n const admitted = admit(value);\n return \"value\" in admitted ? admitted.value : value;\n}\n\n/**\n * The selection a query that writes no `select` asks for: every name the\n * default projection's one owner (`defaultProjectionNames`) keeps.\n */\nfunction defaultSelection(model: AnyModel): Record<string, true> {\n const selection: Record<string, true> = {};\n for (const field of defaultProjectionNames(model)) selection[field] = true;\n return selection;\n}\n\n/**\n * A relation member's prepared field, its members written out: a literal\n * that spreads after members of its own (`{ kind, name, ...nested }`) takes\n * V8's generic property copy, which was 1.6 % of a three-level read's client\n * CPU (2026-11-16). It names every member of\n * {@link PreparedRelationProjection}.\n */\nfunction relationField(\n name: string,\n nested: PreparedRelationProjection\n): PreparedProjectionField {\n return {\n kind: \"relation\",\n name,\n edge: nested.edge,\n linkRow: nested.linkRow,\n linkWhere: nested.linkWhere,\n arguments: nested.arguments,\n projection: nested.projection,\n recurrence: nested.recurrence,\n };\n}\n\n/**\n * Does `select` name exactly the default selection: every name of the default\n * projection, `true`, in its order? It then prepares what no `select`\n * prepares. An inherited enumerable key fails the count, and takes the\n * general path.\n */\nfunction namesDefault(model: AnyModel, select: Input): boolean {\n const names = defaultProjectionNames(model);\n let at = 0;\n for (const name in select) {\n if (select[name] !== true || names[at] !== name) return false;\n at++;\n }\n return at === names.length;\n}\n\n/**\n * Is a relation member's admitted node its target's default read: `true`, or\n * a node holding nothing but a `select` that names the default selection?\n */\nfunction namesDefaultNode(edge: Membership, selection: unknown): boolean {\n if (selection === true) return true;\n const node = record(selection);\n for (const key in node) if (key !== \"select\") return false;\n return (\n node.select === undefined || namesDefault(edge.target, record(node.select))\n );\n}\n\nexport function rowSet(query: Query): ProjectionShape {\n return { kind: \"collection\", row: query.shape };\n}\n\nexport function firstRow(rows: Input[]): Input | null {\n return rows[0] ?? null;\n}\n\n/**\n * The vector distance an index may serve approximately (`approximate: true`),\n * where a read lets it: a root `findMany`/`findFirst` whose FIRST order term is\n * that distance, nearest first, reading the first `take > 0` rows with no\n * cursor, skip or distinct. An index answers exactly that question and nothing\n * else, so everywhere else — a nested window, an aggregate, a count — the flag\n * names nothing and the read is exact. Every backend reads this one answer.\n */\nexport function approximateOrder(\n operation: ReadOperation,\n args: Partial<Arguments>\n):\n | { readonly field: string; readonly distance: Input; readonly take: number }\n | undefined {\n let take: number | undefined;\n if (operation === \"findMany\") take = args.take;\n else if (operation === \"findFirst\") take = args.take ?? 1;\n if (\n !(take !== undefined && take > 0) ||\n args.cursor !== undefined ||\n args.skip ||\n args.distinct?.length\n )\n return undefined;\n const first = entries(args.orderBy)[0] ?? {};\n const field = objKeys(first).find((key) => first[key] !== undefined);\n if (field === undefined) return undefined;\n const distance = (first[field] as Input)._distance as Input;\n return distance?.approximate === true && distance.sort !== \"desc\"\n ? { field, distance, take }\n : undefined;\n}\n\nexport function aggregateRow(rows: Input[]): Input {\n return rows[0] ?? {};\n}\n\nexport function rowIdentity(rows: Input[]): Input[] {\n return rows;\n}\n\nexport function reversedRows(rows: Input[]): Input[] {\n return rows.reverse();\n}\n\n/** A filter read's controls: it takes the root domain's rows. */\nexport const ROOT_CANDIDATES = { purpose: \"root\" as const };\n/** `\"`, `_` or `` ` ``: a character an alias token sits between. */\nconst aliasEdge = (code: number) => code === 34 || code === 95 || code === 96;\n/**\n * `text` with each alias the per-statement counter minted renumbered in\n * order of first appearance (`renumbered` carries the order across a body's\n * runs). An alias token is `q<digits>` inside an identifier: quoted `\"q1\"`\n * (PostgreSQL, SQLite) or `` `q1` `` (MySQL), or within a derived name\n * (`__q1_recursive`), so between two of {@link aliasEdge}'s characters. A\n * scan, not a regular expression: keying is most of what sharing costs.\n */\nfunction renumberAliases(\n text: string,\n renumbered: Map<string, number>\n): string {\n let out = \"\";\n let from = 0;\n let at = text.indexOf(\"q\");\n while (at !== -1) {\n let next = at + 1;\n if (aliasEdge(text.charCodeAt(at - 1))) {\n let end = next;\n let code = text.charCodeAt(end);\n while (code >= 48 && code <= 57) code = text.charCodeAt(++end);\n if (end > next && aliasEdge(code)) {\n const minted = text.slice(next, end);\n let local = renumbered.get(minted);\n if (local === undefined) {\n local = renumbered.size;\n renumbered.set(minted, local);\n }\n out += `${text.slice(from, next)}${local}`;\n from = end;\n }\n next = end;\n }\n at = text.indexOf(\"q\", next);\n }\n return from === 0 ? text : out + text.slice(from);\n}\n/**\n * A caller's `Sql` operand as lowered, parenthesized ({@link Queries.value}):\n * text the engine did not write, so nothing in it is an alias of the\n * engine's, whatever it spells ({@link sharedKey}).\n */\nclass CallerText extends Sql {}\nconst isCallerText = (fragment: Sql): boolean => fragment instanceof CallerText;\nexport const callerText = (fragment: Sql): Sql =>\n new CallerText([\"(\", \")\"], [fragment]);\nconst valueIds = new WeakMap<object, number>();\nlet nextValueId = 0;\n/** A bound value as a key: a primitive by value, a `Date` by its instant, a list by its members, anything else by identity. */\nfunction valueKey(value: unknown): string {\n if (value instanceof Date) return `d${value.getTime()}`;\n if (isArr(value)) return `a${JSON.stringify(value.map(valueKey))}`;\n if (\n value === null ||\n (typeof value !== \"object\" && typeof value !== \"function\")\n )\n return `${typeof value}:${String(value)}`;\n return `o${memo(valueIds, value, () => nextValueId++)}`;\n}\n/**\n * Two bodies are one where their texts are equal once their aliases are\n * renumbered in order of appearance, and their values are equal: the same\n * rows of the same table under the same conditions. A body holding another\n * reads it provisionally, by its key set's name, which equal bodies share.\n * Only the engine's own text holds its aliases: a caller's `Sql` operand\n * ({@link CallerText}) is compared as written, so `'_q1_'` and `'_q2_'` stay\n * two bodies (ENG-4, review 2). Its runs are found on the fragment tree,\n * which no lowering flattens before its statement settles ({@link SqlSlot}).\n */\n/** The places a statement reads a shared member unaliased, `FROM \"<name>\"`. */\nconst memberReads = new WeakSet<Sql>();\n/** `name`'s member read unaliased, as a `FROM` item ({@link relations}). */\nexport function memberRead(a: DatabaseAdapter, name: string): Sql {\n const read = sql`${a.identifiers.escape(name)}`;\n memberReads.add(read);\n return read;\n}\n/**\n * How many relations `statement` references as PlanetScale's Neki counts\n * them (it refuses over 256): each `FROM` item, a table, a reference to a\n * `WITH` member or a derived table, wherever it is, a member's own counted\n * once, used or not. Every item the engine writes is either aliased by the\n * statement's counter, `\"q<n>\"` where it is defined (followed by anything\n * but the `.` of a column it qualifies), or one of its {@link memberReads}.\n * A caller's `Sql` operand is not counted. `visit` sees every fragment\n * read.\n */\nexport function relations(\n statement: Sql,\n visit?: (fragment: Sql) => void\n): number {\n let count = 0;\n const { runs } = Sql.peekRuns(statement, (fragment) => {\n if (memberReads.has(fragment)) count++;\n visit?.(fragment);\n return isCallerText(fragment);\n });\n let text = \"\";\n for (const run of runs) text += run.opaque ? \" \" : run.text;\n let at = text.indexOf(\"q\");\n while (at !== -1) {\n const quote = text.charCodeAt(at - 1);\n let end = at + 1;\n while (text.charCodeAt(end) >= 48 && text.charCodeAt(end) <= 57) end++;\n if (\n (quote === 34 || quote === 96) &&\n end > at + 1 &&\n text.charCodeAt(end) === quote &&\n text.charCodeAt(end + 1) !== 46\n )\n count++;\n at = text.indexOf(\"q\", end);\n }\n return count;\n}\nexport function sharedKey(query: Sql): string {\n const { runs, values } = Sql.peekRuns(query, isCallerText);\n const renumbered = new Map<string, number>();\n // SQL text and bound strings may contain any delimiter: each part is\n // length-prefixed (a caller's run marked `!`), after the count of runs,\n // so the tuple boundaries, array members included, survive in the key.\n let key = `${runs.length}|`;\n for (const { text, opaque } of runs) {\n const part = opaque ? text : renumberAliases(text, renumbered);\n key += `${opaque ? \"!\" : \"\"}${part.length}:${part}`;\n }\n for (const value of values) {\n const part = valueKey(value);\n key += `${part.length}:${part}`;\n }\n return key;\n}\n\n/**\n * Textual alias renumbering cannot distinguish a physical name from an\n * alias. Such schemas keep their relation bodies inline: an optimization\n * must never rename a column, table, junction or namespace in its identity.\n * An alias is `q<n>` between quotes or underscores\n * ({@link renumberAliases}), so only a name that is one, or holds one at an\n * end or between underscores, resembles it; `seq1` or `freq2` do not. A name\n * holds no quote (`isValidSchemaIdentifier`).\n */\nconst aliasLikeSchemas = new WeakMap<EngineSchema, boolean>();\nconst ALIAS_LIKE_NAME = /(?:^|_)q\\d+(?:_|$)/;\nconst resemblesAlias = (name: string) => ALIAS_LIKE_NAME.test(name);\nfunction hasAliasLikeNames(schema: EngineSchema): boolean {\n // Physical names are immutable for the schema lifetime, shared by every\n // bound view. Scan them once, not for each operation's Queries.\n return memo(aliasLikeSchemas, schema, () => {\n for (const [model, slots] of schema.index) {\n if (resemblesAlias(tableOf(model))) return true;\n for (const field of schema.storedFields(model))\n if (resemblesAlias(physicalField(schema, model, field).name))\n return true;\n for (const { edge } of slots.values()) {\n const junctions =\n edge.kind === \"junction\"\n ? [edge.topology]\n : edge.kind === \"variantJunctionCarrier\"\n ? edge.members.map((member) => member.topology)\n : [];\n for (const junction of junctions) {\n if (resemblesAlias(junction.table)) return true;\n for (const side of [junction.source, junction.target])\n if (\n side.members.some((member) =>\n resemblesAlias(member.junctionField)\n )\n )\n return true;\n }\n }\n }\n return false;\n });\n}\n/** The scalar types a value of which has one spelling: two texts that differ are two values. */\nconst SPELLED_ONCE: ReadonlySet<string> = new Set(\n \"string enum boolean int bigint\".split(\" \")\n);\n/** No layer is lowering. */\nexport const NO_LAYERS: readonly number[] = [];\n/** A projection that carries no gate member (K5). */\nexport const NO_GATES: readonly string[] = [];\nexport const isParameterOperand = (operand: PreparedOperand): boolean =>\n operand.kind === \"parameter\";\n\n/** One layer's projection key on a model (K5), with the layer's `read`. */\nexport interface DeclaredEvidence {\n readonly layer: number;\n readonly read: Input;\n readonly names: readonly (readonly [string, Input])[];\n}\n/**\n * What a read-gated field's row must hold, per layer gating it: the layer's\n * `read` and the field's predicate there.\n */\nexport type FieldGate = readonly (readonly [number, Input, Input])[];\n/** A model's projection keys and read-gated fields under one domain (K5). */\nexport interface ProjectedFacts {\n readonly keys: ReadonlyMap<string, DeclaredEvidence>;\n readonly gates: ReadonlyMap<string, FieldGate>;\n}\n\nexport const NO_RELATIONS: readonly string[] = [];\nfunction variantCarrier(\n resolved: ResolvedSlot\n): ResolvedVariantEdge | undefined {\n return resolved.member === undefined &&\n (resolved.edge.kind === \"variantRowCarrier\" ||\n resolved.edge.kind === \"variantJunctionCarrier\")\n ? resolved.edge\n : undefined;\n}\n\n/** A relation node or body without its `$through`, which belongs to the link. */\nfunction withoutLinkKey(map: Input): Input {\n const { $through: _taken, ...rest } = map;\n return rest;\n}\n\n/** Generated boolean sets must not inherit a provider's linear expression depth. */\nexport function balancedOr<T>(\n items: readonly T[],\n join: (items: readonly T[]) => T\n): T {\n const build = (start: number, end: number): T => {\n if (end - start < 2) return end === start ? join([]) : items[start]!;\n const middle = start + Math.floor((end - start) / 2);\n return join([build(start, middle), build(middle, end)]);\n };\n return build(0, items.length);\n}\n\n/** A produced row a judgement reads: its alias, which written fields are null, and what folds them in. */\nexport interface KnownRow {\n readonly alias: string;\n readonly nulls: ReadonlyMap<string, boolean>;\n readonly fold: (\n predicate: PreparedPredicate,\n nulls: ReadonlyMap<string, boolean>\n ) => PreparedPredicate;\n}\n\nexport abstract class Queries {\n readonly schema: EngineSchema;\n readonly adapter: EngineFacts;\n readonly #views: QueryViews;\n /**\n * The DRIVER's own representation rules (D-17). Scalar meaning is owned by\n * the existing codecs, but \"what shape does THIS transport hand back?\" is\n * owned by the driver and the adapter — SQLite stores `json` as TEXT and\n * booleans as 0/1, MySQL hands back naive wall-clock datetimes — and that\n * chain is declared, implemented by every adapter and driver, and was\n * reached by nothing. The decoder asks it once per row value, at the row\n * boundary, and never for a value a JSON window already decoded.\n */\n protected readonly result: DriverResultParser | undefined;\n /**\n * The row domain this `Queries` reads under: every to-many relation it\n * correlates, and every root read or lookup that names a purpose. Absent on\n * every path of a client without rules.\n */\n readonly domain: PreparedDomain | undefined;\n /**\n * The produced row a judgement is lowering over, where one is: declared\n * here for what a layer folds over it (`overKnown`), held by `SqlQueries`.\n */\n declare known?: KnownRow;\n /** The call whose values the domain's parameters read. */\n readonly #call: CallScope | undefined;\n /**\n * The layers whose predicates are lowering here, outermost first: inside\n * one, a relation read takes every other layer at its default (R5). On this\n * `Queries`, so the statement keeps its one alias counter.\n */\n protected excluded: number[] | undefined;\n protected readonly shBodies: boolean;\n constructor(\n schema: EngineSchema,\n adapter: EngineFacts,\n result?: DriverResultParser,\n domain?: PreparedDomain,\n call?: CallScope\n ) {\n this.schema = schema;\n this.adapter = adapter;\n this.#views = schema.qViews(adapter);\n this.result = result;\n this.domain = domain;\n this.#call = call;\n this.shBodies =\n adapter.capabilities.sharesRelationBodies === true &&\n !resemblesAlias(adapter.namespace ?? \"\") &&\n !hasAliasLikeNames(schema);\n }\n get #s() {\n return this.schema;\n }\n get #a() {\n return this.adapter;\n }\n #slot(model: AnyModel, name: string): ResolvedSlot {\n return this.#s.index.get(model)!.get(name)!;\n }\n #bm(model: AnyModel, name: string, variant?: string): Membership {\n return this.#s.membership(model, name, variant);\n }\n #ps(model: AnyModel, where: Input) {\n return this.prepareSelector(model, where, false, false);\n }\n #ph(model: AnyModel, field: string): PhysicalField {\n return this.#s.physicalField(model, field);\n }\n #lf(model: AnyModel, field: string): Leaf {\n return this.leaf(model, field);\n }\n #sc(model: AnyModel, field: string): PreparedScalar {\n return { model, field, physical: this.#ph(model, field) };\n }\n protected defaultOrder(model: AnyModel): Arguments[\"orderBy\"] {\n return this.domain?.rows.order?.get(nameOf(model)) as\n | Arguments[\"orderBy\"]\n | undefined;\n }\n abstract under(domain: PreparedDomain, call?: CallScope): Queries;\n decs(driver: {\n readonly adapter: EngineFacts;\n readonly result?: DriverResultParser;\n }): boolean {\n return driver.adapter === this.adapter && driver.result === this.result;\n }\n /**\n * The domain predicate a lowering-time read takes for `model`: the call's\n * own outside every layer, under `judgement` for a write; inside one, the\n * defaults' without the layers lowering, which a layer's traversal only\n * reads.\n */\n protected scope(\n model: AnyModel,\n purpose: RowPurpose,\n judgement?: WriteJudgement\n ): PreparedSelector | undefined {\n const excluded = this.excluded;\n return excluded === undefined || excluded.length === 0\n ? this.domain?.selector(model, purpose, NO_LAYERS, judgement)\n : this.domain?.defaults.selector(model, purpose, excluded);\n }\n /**\n * The domain predicate a read lowering here takes for `model` and\n * `purpose`; `undefined` where it states none, or the call drops all it\n * states (R6), so the statement is the one without a domain.\n */\n domainOf(\n model: AnyModel,\n purpose: RowPurpose,\n judgement?: WriteJudgement\n ): PreparedSelector | undefined {\n const scope = this.scope(model, purpose, judgement);\n return scope && !this.#drops(scope.predicate) ? scope : undefined;\n }\n get values(): CallValues | undefined {\n return this.#call?.rows.values;\n }\n #instantOf: (() => Date) | undefined;\n /**\n * The call's one instant: a domain that reads it lowers for its call. Made\n * when first read, so a `Queries` whose domain reads no value makes none.\n */\n get instant(): () => Date {\n return (this.#instantOf ??= () => this.#call!.instant());\n }\n /**\n * The ONE provider continuation for a physical value of `type`, bound to\n * THIS execution's driver and adapter: the driver first (it owns the\n * transport's own spellings), then the adapter (it owns the dialect's), then\n * the engine's strict codec, which is the caller of the reader this returns.\n *\n * The driver's `next(value, type)` hands the adapter its value only: the\n * adapter is always asked about the leaf's own `type`. The adapter's `next()`\n * — or `next(undefined)` — answers the value the ADAPTER was handed, which is\n * the driver's transformed one, and either leg may answer without calling\n * `next` at all.\n *\n * A provider that raises the library's own error has already said what went\n * wrong, and that error reaches the caller intact; only a FOREIGN throw is\n * reported as a malformed scalar.\n *\n * The reader holds a driver's parser, so it belongs to the execution that\n * built this `Queries`, never to a shared leaf or projection: a borrowed\n * transaction may bind a different driver to the same prepared shape.\n */\n #fieldReader(type: string): FieldReader | undefined {\n const adapter = this.#a.result;\n const driverParse = this.result?.parseField;\n if (driverParse === undefined) {\n const descriptor = Object.getOwnPropertyDescriptor(adapter, \"parseField\");\n const isPassthrough =\n descriptor !== undefined\n ? descriptor.get === undefined &&\n descriptor.value === passThroughParseField\n : adapter.parseField === passThroughParseField;\n if (isPassthrough) return undefined;\n }\n const adapterLeg = (input: unknown): unknown =>\n adapter.parseField(input, type, (transformed?: unknown) =>\n transformed === undefined ? input : transformed\n );\n return (value) => {\n try {\n return driverParse\n ? driverParse(value, type, adapterLeg)\n : adapterLeg(value);\n } catch (error) {\n if (\n error instanceof InvalidScalarResult ||\n error instanceof VibORMError\n )\n throw error;\n refuseResult(type, \"provider decode failed\");\n }\n };\n }\n decodeResult(\n raw: Input[],\n operation: Operation,\n decode: (rows: Input[]) => Input[]\n ): Input[] {\n const adapterDecode = (input: unknown): unknown =>\n this.#a.result.parseResult(input, operation, (transformed?: unknown) =>\n decode((transformed === undefined ? input : transformed) as Input[])\n );\n const driverParse = this.result?.parseResult;\n return (\n driverParse\n ? driverParse(raw, operation, adapterDecode)\n : adapterDecode(raw)\n ) as Input[];\n }\n columnName(model: AnyModel, field: string): string {\n return this.#ph(model, field).name;\n }\n protected natType(scalar: Scalar): NativeTypeDeclaration | undefined {\n return scalar[\"~\"].state.array ? undefined : scalar[\"~\"].nativeType;\n }\n protected leaf(model: AnyModel, field: string): Leaf {\n const leaves = memo(this.#views.leaves, model, () => new Map());\n return memo(leaves, field, () => {\n const physical = this.#ph(model, field);\n const { scalar, nullable } = physical;\n const state = scalar[\"~\"].state;\n return {\n kind: \"scalar\",\n type: state.type,\n nullable,\n scalar,\n list: state.array ? true : undefined,\n decimal: state.type === \"decimal\" ? state.decimal : undefined,\n dateTime:\n state.type === \"datetime\"\n ? (this.#a.result.dateTimeRepresentation?.(this.natType(scalar)) ??\n \"text\")\n : undefined,\n enumValues:\n state.type === \"enum\" && \"enumValues\" in scalar\n ? new Set(scalar.enumValues as readonly string[])\n : undefined,\n dimension: state.dimension,\n id: identifierColumn(this.#a, this.#s.index, model, field, physical),\n };\n });\n }\n namesUpdate(model: AnyModel, field: string, value: unknown): boolean {\n return this.named(model, field, readUpdate(value));\n }\n protected named(\n model: AnyModel,\n field: string,\n update: PreparedUpdate\n ): update is Exclude<PreparedUpdate, { kind: \"list\" }> {\n if (update.kind !== \"arithmetic\") return update.kind === \"value\";\n return !(\n (update.operator === \"multiply\" || update.operator === \"divide\") &&\n exactDecimalDomain(this.#ph(model, field).state) !== undefined\n );\n }\n /** `model`'s names and values as this lowering spells them, for a fragment written by hand. */\n abstract spelling(model: AnyModel, dialect: Dialect): ModelSql;\n abstract updateAssignment(\n model: AnyModel,\n field: string,\n value: unknown\n ): Sql;\n /**\n * One prepared selector. `unique` states that the caller admitted this\n * `where` as a UNIQUE selector (a `whereUnique` input): its top-level\n * addressable-key entries are the row's discriminator and compare through the\n * constraint, while every other entry — an extended `where`'s filters, its\n * `AND`/`OR`/`NOT` arms and its relation predicates — stays a filter. The\n * same `{ id: … }` object is a discriminator under `findUnique` and a filter\n * under `findFirst`, so the fact belongs to the admitted operation and cannot\n * be recovered from the object's shape.\n * SQL-only consumers omit dependency summaries through `includeFacts`; the\n * unique constraint comparison remains independent of that collection.\n */\n prepareSelector(\n model: AnyModel,\n where?: Input,\n unique?: boolean\n ): PreparedSelector;\n prepareSelector(\n model: AnyModel,\n where: Input | undefined,\n unique: boolean,\n includeFacts: false\n ): Pick<PreparedSelector, \"model\" | \"predicate\">;\n prepareSelector(\n model: AnyModel,\n where?: Input,\n unique = false,\n includeFacts = true\n ): Pick<PreparedSelector, \"model\" | \"predicate\"> | PreparedSelector {\n if (!includeFacts)\n return {\n model,\n predicate: where\n ? this.#rooted(model, undefined, () =>\n this.#prepareWhere(model, where, undefined, unique)\n )\n : undefined,\n };\n const facts = newSelectorFacts();\n const keys = objKeys(where ?? {});\n const uniqueKey =\n keys.length === 1 ? findAddressableKey(model, keys[0]!) : undefined;\n const selected = uniqueKey\n ? uniqueKey.name\n ? (where![uniqueKey.name] as Input)\n : where!\n : undefined;\n return {\n model,\n facts,\n uniqueKey,\n uniqueValues: selected\n ? new Map(uniqueKey!.fields.map((field) => [field, selected[field]]))\n : undefined,\n predicate: where\n ? this.#rooted(model, facts, () =>\n this.#prepareWhere(model, where, facts, unique)\n )\n : undefined,\n };\n }\n /**\n * The rows a predicate being prepared reads, from its root to the relation\n * body it is in: what a `{ $row, up }` names. `sealed` says why a reference\n * may not cross that body.\n */\n #scopes: readonly [AnyModel, SelectorFacts | undefined, string?][] = [];\n #rooted<T>(\n model: AnyModel,\n facts: SelectorFacts | undefined,\n prepare: () => T\n ): T {\n const scopes = this.#scopes;\n this.#scopes = [[model, facts]];\n try {\n return prepare();\n } finally {\n this.#scopes = scopes;\n }\n }\n /** One row's identity as prepared meaning: its key fields' equalities. */\n identityPredicate(\n model: AnyModel,\n identity: Input,\n facts: SelectorFacts\n ): PreparedPredicate {\n return conjunction(\n objEntries(identity).map(([field, value]) =>\n this.#prepareScalarPredicate(model, field, value, facts)\n )\n );\n }\n /**\n * The complement of a CAPTURED identity set — \"this row is not one of the\n * rows the engine read\" — as prepared meaning.\n *\n * A captured set is identities the engine itself read, so its complement is\n * composed here from {@link identityPredicate}'s equalities under the one\n * combinator owner ({@link combine}), and never spelled as a public\n * `{ NOT: { OR: … } }` payload: N4 lets a model DECLARE a scalar or relation\n * named `NOT`, `OR` or `AND`, and such a payload is then read as that field\n * ({@link combinator}) — the public name wins, as validation admitted it. An\n * internal premise that borrowed public syntax could not survive that, which\n * is why the meaning is stated and only the SQL is spelled.\n *\n * An empty set excludes nothing: it states no condition, so a caller that\n * conjoins it through {@link andSelectors} keeps exactly its own selector —\n * the truth both consumers already carried, one by omitting the bag and the\n * other through the vacuous `NOT` of an empty `OR`.\n */\n excludeIdentities(\n model: AnyModel,\n identities: readonly Input[]\n ): PreparedSelector {\n const facts = newSelectorFacts();\n const captured = this.#capturedSet(model, identities, facts, false);\n return {\n model,\n facts,\n predicate:\n identities.length === 0 ? undefined : this.combine(\"NOT\", [captured]),\n };\n }\n /**\n * The captured identity set ITSELF — \"this row is one of the rows the engine\n * read\" — and the positive counterpart of {@link excludeIdentities}.\n *\n * D-65 gives the consuming UPDATE/DELETE of a captured ROOT set both facts:\n * the rows the capture named, and the selector it captured them by. This\n * states the first, from the same identities' own equalities under the same\n * combinator owner, so the effect addresses the captured rows with no public\n * payload to collide with a declared `OR` (N4).\n *\n * An empty set names NO row — the vacuous FALSE {@link combine} already\n * states — which is why each caller answers an empty capture before any\n * statement is built.\n */\n includeIdentities(\n model: AnyModel,\n identities: readonly Input[]\n ): PreparedSelector {\n const facts = newSelectorFacts();\n return {\n model,\n facts,\n predicate: this.#capturedSet(model, identities, facts),\n };\n }\n #capturedSet(\n model: AnyModel,\n identities: readonly Input[],\n facts: SelectorFacts,\n taken = true\n ): PreparedPredicate {\n const keys = this.#s.keys(model);\n const field = keys.length === 1 ? keys[0] : undefined;\n if (\n field &&\n identities.length > 0 &&\n identities.every(\n (identity) => objKeys(identity).length === 1 && hasOwn(identity, field)\n )\n )\n return this.#prepareScalarPredicate(\n model,\n field,\n { in: identities.map((identity) => identity[field]) },\n facts\n );\n const held = taken && identities.length === 1 ? facts : apart(facts, true);\n const captured = identities.map((identity) =>\n this.identityPredicate(model, identity, held)\n );\n if (captured.length > 0) facts.exact = false;\n return balancedOr(captured, (arms) => this.combine(\"OR\", arms));\n }\n andSelectors(\n model: AnyModel,\n selectors: readonly PreparedSelector[]\n ): PreparedSelector {\n const facts = newSelectorFacts();\n const predicates: PreparedPredicate[] = [];\n for (const selector of selectors) {\n for (const field of selector.facts.fields) facts.fields.add(field);\n for (const [field, value] of selector.facts.equals)\n facts.equals.set(field, value);\n for (const [field, value] of selector.facts.keys)\n facts.keys.set(field, value);\n facts.exact &&= selector.facts.exact;\n for (const read of selector.facts.reads) facts.reads.add(read);\n if (selector.predicate) predicates.push(selector.predicate);\n }\n return {\n model,\n facts,\n predicate: predicates.length === 0 ? undefined : conjunction(predicates),\n };\n }\n /**\n * The key-preserving conjunction: `selector` AND `domain`'s predicate for\n * `purpose`, keeping the selector's unique key, so the consumers that read\n * the key to recover (race convergence, a hidden conflict's rethrow) behave\n * as without a domain; `scoped` tells the ones that trust the key alone to\n * name the row (the RETURNING confirmation fast path, the targeted\n * `ON CONFLICT` fold) that it no longer does. A write's `judgement` adds\n * its verb's predicates. The selector itself where the domain states\n * nothing for its model.\n */\n candidates(\n selector: PreparedSelector,\n purpose: RowPurpose,\n domain: PreparedDomain | undefined = this.domain,\n judgement?: WriteJudgement\n ): PreparedSelector {\n const scope = domain?.selector(\n selector.model,\n purpose,\n NO_LAYERS,\n judgement\n );\n if (scope === undefined) return selector;\n return {\n ...this.andSelectors(selector.model, [selector, scope]),\n uniqueKey: selector.uniqueKey,\n uniqueValues: selector.uniqueValues,\n scoped: true,\n };\n }\n abstract lowerSelector(\n selector: Pick<PreparedSelector, \"model\" | \"predicate\">,\n alias?: string\n ): Sql | undefined;\n /** Whether the call drops every layer `predicate` is made of (R6). */\n #drops(predicate: PreparedPredicate | undefined): boolean {\n if (predicate?.kind === \"layer\")\n return predicate.resolve(this) === undefined;\n return (\n predicate?.kind === \"and\" &&\n predicate.predicates.length > 0 &&\n predicate.predicates.every((member) => this.#drops(member))\n );\n }\n abstract locatedValue(\n model: AnyModel,\n field: string,\n selector: PreparedSelector\n ): Sql;\n /**\n * The first `limit` rows of `selector` in key order, as prepared meaning: a\n * limited window two statements of one atomic unit both name — a premise\n * about the window, then the effect over it — and agree on by construction,\n * because a total order leaves the same data one answer. Its rows are rows\n * of `selector`, so the selector's facts hold for them.\n */\n window(selector: PreparedSelector, limit: number): PreparedSelector {\n return {\n model: selector.model,\n facts: selector.facts,\n predicate: { kind: \"window\", selector, limit },\n };\n }\n /**\n * A combinator, unless the model declares a field by that name: validation\n * extends its three combinator entries with the model's own fields, so a\n * scalar or relation literally named `AND` wins the key there\n * (`validation/model/core/where.ts`, `validation/model/args/aggregate.ts`\n * for `having`), and\n * the engine reads the admitted payload the same way (N4).\n */\n protected comb(model: AnyModel, key: string): key is \"AND\" | \"OR\" | \"NOT\" {\n return (\n (key === \"AND\" || key === \"OR\" || key === \"NOT\") &&\n !scalarsOf(model)[key] &&\n !model[\"~\"].state.relations[key]\n );\n }\n combine(\n key: \"AND\" | \"OR\" | \"NOT\",\n arms: readonly PreparedPredicate[]\n ): PreparedPredicate {\n const stated = arms.filter(states);\n if (key === \"OR\")\n return stated.length === 0 ? VACUOUS_FALSE : disjunction(stated);\n const predicates: readonly PreparedPredicate[] =\n key === \"AND\"\n ? (mergeQuantifiers(\"and\", stated) ?? stated)\n : stated.map((predicate) => ({ kind: \"not\" as const, predicate }));\n return conjunction(predicates);\n }\n #prepareWhere(\n model: AnyModel,\n where: Input,\n facts: SelectorFacts | undefined,\n unique = false,\n positive = true\n ): PreparedPredicate {\n if (where instanceof Condition) {\n if (facts) facts.exact = false;\n return { kind: \"condition\", condition: where };\n }\n if (where instanceof Existence) return this.#prepareExists(where, facts);\n return conjunction(\n objEntries(where).map(([field, operand]) => {\n if (this.comb(model, field)) {\n const held = facts && field !== \"AND\" ? apart(facts, true) : facts;\n if (held !== facts) facts!.exact = false;\n return this.combine(\n field,\n entries(operand).map((clause) =>\n this.#prepareWhere(\n model,\n clause,\n held,\n false,\n field === \"NOT\" ? !positive : positive\n )\n )\n );\n }\n if (model[\"~\"].state.relations[field])\n return this.#prepareSlotPredicate(\n model,\n field,\n operand,\n facts,\n positive\n );\n // An ordinary scalar predicate is not a unique discriminator. Only\n // unique selectors and possible compound names need the key catalog.\n const key =\n unique || scalarsOf(model)[field] === undefined\n ? findAddressableKey(model, field)\n : undefined;\n if (key?.name)\n return conjunction(\n key.fields.map((member) =>\n this.#prepareScalarPredicate(\n model,\n member,\n (operand as Input)[member],\n facts,\n unique,\n positive\n )\n )\n );\n return this.#prepareScalarPredicate(\n model,\n field,\n operand,\n facts,\n unique && key !== undefined,\n positive\n );\n })\n );\n }\n /**\n * `$exists`: the target's rows, read by the statement wherever it sits, so\n * a write to them orders before it (a read of the target with no path).\n */\n #prepareExists(\n existence: Existence,\n facts: SelectorFacts | undefined\n ): PreparedPredicate {\n const model = this.#s.schema[existence.model]!;\n const nestedFacts = facts && apart(facts);\n const scopes = this.#scopes;\n this.#scopes = [...scopes, [model, nestedFacts]];\n let predicate: PreparedPredicate;\n try {\n predicate = this.#prepareWhere(model, existence.where, nestedFacts);\n } finally {\n this.#scopes = scopes;\n }\n if (facts) {\n facts.exact = false;\n facts.reads.add(model);\n }\n return {\n kind: \"exists\",\n model,\n ...(states(predicate) && { predicate }),\n };\n }\n protected scalar(model: AnyModel, field: string): PreparedScalar {\n return this.#sc(model, field);\n }\n #prepareScalarPredicate(\n model: AnyModel,\n field: string,\n value: unknown,\n facts: SelectorFacts | undefined,\n key = false,\n positive = true\n ): PreparedPredicate {\n const scalar = this.#sc(model, field);\n if (facts) {\n facts.fields.add(field);\n const filter =\n isObj(value) &&\n !(value instanceof Sql) &&\n !(value instanceof Parameter) &&\n !isFieldRef(value)\n ? value\n : undefined;\n const hasEquality =\n filter === undefined ||\n (objKeys(filter).length === 1 && \"equals\" in filter);\n const equality = filter && hasEquality ? filter.equals : value;\n if (\n hasEquality &&\n (equality === null ||\n (typeof equality !== \"object\" && !(equality instanceof Sql)))\n ) {\n facts.equals.set(field, equality);\n if (key) facts.keys.set(field, equality);\n } else if (!(hasEquality && equality instanceof Parameter))\n facts.exact = false;\n }\n return this.prepOps(\n key ? { kind: \"column\", scalar, key: true } : { kind: \"column\", scalar },\n value,\n false,\n positive\n );\n }\n protected prepOps(\n target: PreparedTarget,\n value: unknown,\n insensitive = false,\n positive = true\n ): PreparedPredicate {\n const state = target.scalar?.physical.state;\n const shorthand =\n !isObj(value) ||\n value instanceof Sql ||\n isFieldRef(value) ||\n jsonNullKindOf(value) !== undefined ||\n (state?.array && isArr(value)) ||\n !addressesOperators(state, value);\n return shorthand\n ? this.#prepareOperation(target, \"equals\", value, insensitive, positive)\n : this.#prepareOperatorFilter(target, value, insensitive, positive);\n }\n #prepareOperatorFilter(\n target: PreparedTarget,\n value: unknown,\n insensitive: boolean,\n positive: boolean\n ): PreparedPredicate {\n const state = target.scalar?.physical.state;\n const filter = value as Input;\n const declared = filter.mode;\n const folded =\n state?.type === \"json\" && declared !== undefined\n ? declared === \"insensitive\"\n : insensitive || declared === \"insensitive\";\n const scoped: PreparedTarget =\n state?.type === \"json\" && isArr(filter.path)\n ? {\n ...(target as Extract<PreparedTarget, { kind: \"column\" }>),\n path: [...(filter.path as string[])],\n }\n : target;\n const predicates: PreparedPredicate[] = [];\n for (const name of objKeys(filter)) {\n if (name === \"mode\" || name === \"path\") continue;\n const operand = filter[name];\n predicates.push(\n name === \"equals\"\n ? this.prepOps(scoped, operand, folded, positive)\n : name === \"not\"\n ? {\n kind: \"not\",\n predicate: this.prepOps(scoped, operand, folded, !positive),\n }\n : this.#prepareOperation(scoped, name, operand, folded, positive)\n );\n }\n return conjunction(predicates);\n }\n #prepareOperation(\n target: PreparedTarget,\n operator: string,\n value: unknown,\n insensitive: boolean,\n positive = true\n ): PreparedPredicate {\n const owner = target.scalar;\n const opOf = (v: unknown): PreparedOperand =>\n owner ? this.#prepareOperand(owner, v) : { kind: \"value\", value: v };\n if (operator === \"in\" || operator === \"notIn\")\n return {\n kind: \"operation\",\n operator,\n target,\n operands:\n value instanceof Parameter\n ? [{ kind: \"parameter\", parameter: value, spread: true }]\n : (value as unknown[]).map(opOf),\n insensitive,\n };\n if (SINGLE_OPS.has(operator))\n return {\n kind: \"operation\",\n operator,\n target,\n operand: opOf(value),\n value,\n insensitive,\n };\n return {\n kind: \"operation\",\n operator,\n target,\n value,\n insensitive,\n ...(operator === \"distance\" &&\n positive &&\n owner?.physical.state.type === \"point\" &&\n distanceUpperBound(value) !== undefined && { probe: true }),\n };\n }\n #prepareOperand(owner: PreparedScalar, value: unknown): PreparedOperand {\n if (value instanceof Parameter)\n return { kind: \"parameter\", parameter: value };\n if (value instanceof OuterColumn)\n return this.#prepareOuterOperand(owner, value);\n if (isFieldRef(value)) {\n if (owner.physical.state.type === \"json\")\n unsupported(`Field ref '${formatFieldRef(value)}' invalid in JSON.`);\n return this.#prepareFieldOperand(owner, value);\n }\n if (!(value instanceof Sql)) return { kind: \"value\", value };\n const flat = Sql.peek(value);\n const operands = flat.values.map((member) => {\n if (isFieldRef(member)) return this.#prepareFieldOperand(owner, member);\n const pending = [member];\n const seen = new WeakSet<object>();\n for (const nested of pending) {\n if (isFieldRef(nested)) unsupported(\"Field ref must be top-level.\");\n if (nested instanceof OuterColumn)\n unsupported(\"{ $row, up } cannot nest in SQL.\");\n if (!isObj(nested) || seen.has(nested)) continue;\n seen.add(nested);\n for (const descriptor of objValues(\n Object.getOwnPropertyDescriptors(nested)\n ))\n if (\"value\" in descriptor) pending.push(descriptor.value);\n }\n return { kind: \"value\", value: member } as const;\n });\n return operands.some((member) => member.kind === \"field\")\n ? { kind: \"sql\", strings: [...flat.strings], operands }\n : { kind: \"value\", value };\n }\n #checkComparable(\n label: string,\n owner: PreparedScalar,\n targetModel: AnyModel,\n targetField: string,\n targetState: ScalarState\n ): void {\n const own = exactDecimalDomain(owner.physical.state);\n const other = exactDecimalDomain(targetState);\n if (own && other && !sameDecimalDomain(own, other))\n unsupported(\n `${label} decimal(${other.precision},${other.scale}) != '${owner.field}' decimal(${own.precision},${own.scale}).`\n );\n const storage = incomparableIdentifiers(\n this.#lf(owner.model, owner.field).id,\n this.#lf(targetModel, targetField).id,\n owner.field,\n targetField\n );\n if (storage !== undefined)\n unsupported(`${label} incompatible with '${owner.field}': ${storage}`);\n }\n #prepareFieldOperand(\n owner: PreparedScalar,\n value: Parameters<typeof fieldRefPayload>[0]\n ): Extract<PreparedOperand, { kind: \"field\" }> {\n const { model } = owner;\n const payload = fieldRefPayload(value);\n const scope = nameOf(model) ?? \"unknown\";\n const ref = `Field ref '${formatFieldRef(value)}'`;\n if (payload.model !== scope) unsupported(`${ref} must target '${scope}'.`);\n if (payload.list) unsupported(`${ref} is a list field.`);\n const referenced = scalarsOf(model)[payload.field];\n if (!referenced) unsupported(`${ref} is not a scalar of '${scope}'.`);\n this.#checkComparable(\n `Field ref '${payload.field}' on '${scope}'`,\n owner,\n model,\n payload.field,\n referenced[\"~\"].state\n );\n return { kind: \"field\", scalar: this.#sc(model, payload.field) };\n }\n #prepareOuterOperand(\n owner: PreparedScalar,\n value: OuterColumn\n ): Extract<PreparedOperand, { kind: \"field\" }> {\n const spelled = `{ $row: ${JSON.stringify(value.$row)}, up: ${value.up} }`;\n const scopes = this.#scopes;\n const at = scopes.length - 1 - value.up;\n if (at < 0)\n unsupported(\n `${spelled} exceeds ${Math.max(scopes.length - 1, 0)} enclosing relation(s).`\n );\n for (let index = at + 1; index < scopes.length; index++)\n if (scopes[index]![2] !== undefined)\n unsupported(`${spelled} crosses ${scopes[index]![2]} relation.`);\n const [model, facts] = scopes[at]!;\n const name = nameOf(model) ?? \"unknown\";\n const referenced = scalarsOf(model)[value.$row];\n const own = owner.physical.state;\n if (!referenced) unsupported(`${spelled} is not a scalar of '${name}'.`);\n const other = referenced[\"~\"].state;\n const fmt = (s: ScalarState) => (s.array ? `${s.type}[]` : s.type);\n if (\n own.array ||\n other.array ||\n own.type === \"json\" ||\n !(\n own.type === other.type ||\n (own.type === \"string\" && other.type === \"enum\") ||\n (own.type === \"enum\" && other.type === \"string\")\n )\n )\n unsupported(\n `${spelled} (${fmt(other)}) incompatible with '${owner.field}' (${fmt(own)}).`\n );\n this.#checkComparable(spelled, owner, model, value.$row, other);\n facts?.fields.add(value.$row);\n return {\n kind: \"field\",\n scalar: this.#sc(model, value.$row),\n ...(value.up > 0 && { up: value.up }),\n };\n }\n #prepareSlotPredicate(\n model: AnyModel,\n name: string,\n operand: unknown,\n facts: SelectorFacts | undefined,\n positive = true\n ): PreparedPredicate {\n const resolved = this.#slot(model, name);\n const entries = operand as Input;\n const carrier = variantCarrier(resolved);\n if (!carrier) {\n const edge = this.#bm(model, name);\n const recurrence = entries.recurse as NormalizedRecurrence | undefined;\n const closure: Closure | undefined = recurrence && {\n depth: recurrence.depth,\n self: entries.self === true,\n ...(recurrence.selective && { selective: true }),\n };\n const arms: [string, unknown][] = closure\n ? objEntries(entries).filter(\n ([key, value]) => QUANTIFIERS.has(key) && value !== undefined\n )\n : objKeys(entries).every((key) => QUANTIFIERS.has(key))\n ? objEntries(entries)\n : [[\"is\", entries]];\n return conjunction(\n arms.map(([quantifier, value]) =>\n this.#relationPredicate(\n edge,\n quantifier,\n value,\n facts,\n positive,\n closure\n )\n )\n );\n }\n const members = carrier.members;\n const many = carrier.kind === \"variantJunctionCarrier\";\n const variantEdge = (variant: unknown) =>\n this.#bm(model, name, variant as string);\n if (!many && entries.type === undefined) {\n const cond = \"is\" in entries ? null : { not: null };\n return conjunction(\n [carrier.storage.typeColumn.name, carrier.storage.idColumn.name].map(\n (field) => this.#prepareScalarPredicate(model, field, cond, facts)\n )\n );\n }\n const arms: [string | undefined, Input][] = many\n ? (objEntries(entries) as [string, Input][])\n : [[undefined, entries]];\n return conjunction(\n arms.map(([quantifier, tagged]) => {\n const edge = variantEdge(tagged.type);\n const negated = tagged.isNot !== undefined;\n const inexact =\n negated || quantifier === \"none\" || quantifier === \"every\";\n const inner = this.#relationScope(\n edge,\n (negated ? tagged.isNot : tagged.is) as Input | undefined,\n facts,\n inexact,\n positive,\n undefined,\n \"polymorphic\"\n );\n const quantified: PreparedPredicate = {\n kind: \"relation\",\n edge,\n quantifier: quantifier ?? \"some\",\n predicate:\n negated && inner ? { kind: \"not\", predicate: inner } : inner,\n };\n if (quantifier !== \"every\") return quantified;\n return conjunction([\n ...(inner ? [quantified] : []),\n ...members\n .filter((member) => member.variant !== tagged.type)\n .map((member) =>\n this.#relationPredicate(\n variantEdge(member.variant),\n \"none\",\n undefined,\n facts,\n positive\n )\n ),\n ]);\n })\n );\n }\n #relationPredicate(\n edge: Membership,\n quantifier: string,\n value: unknown,\n facts: SelectorFacts | undefined,\n positive = true,\n closure?: Closure\n ): PreparedPredicate {\n const body =\n value === null || value === undefined ? undefined : (value as Input);\n const linkWhere =\n edge.kind === \"junction\" && edge.declared\n ? (body?.$through as Input | undefined)\n : undefined;\n const link = linkWhere && {\n link: this.#ps(\n (edge as Extract<Membership, { kind: \"junction\" }>).declared!.model,\n linkWhere\n ).predicate,\n linkFields: objKeys(linkWhere),\n };\n return {\n kind: \"relation\",\n edge,\n quantifier,\n ...link,\n predicate: this.#relationScope(\n edge,\n link ? withoutLinkKey(body!) : body,\n facts,\n quantifier === \"none\" ||\n quantifier === \"every\" ||\n quantifier === \"isNot\",\n positive,\n closure\n ),\n ...(closure && { closure }),\n };\n }\n /**\n * One relation's body, and the read of other rows it is. `inexact` is also\n * this arm's POLARITY: `none`, `isNot` and `every` consume their nested\n * predicate under a negation — `every` emits `NOT(nested)` inside its\n * `NOT EXISTS` — so a conjunct added there is a conjunct of what is\n * negated. One fact, read twice, instead of a second flag that could\n * disagree with it.\n */\n #relationScope(\n edge: Membership,\n where: Input | undefined,\n facts: SelectorFacts | undefined,\n inexact: boolean,\n positive = true,\n closure?: Closure,\n sealed: string | undefined = closure && \"recursive\"\n ): PreparedPredicate | undefined {\n if (facts) {\n // What other rows hold is not stated by what its own row holds.\n facts.exact = false;\n facts.reads.add(edge.target);\n if (edge.kind === \"junction\") facts.reads.add(edge.table);\n }\n if (!where) return;\n const scopes = this.#scopes;\n const nestedFacts = facts && apart(facts);\n this.#scopes = [...scopes, [edge.target, nestedFacts, sealed]];\n try {\n return this.#prepareWhere(\n edge.target,\n where,\n nestedFacts,\n false,\n positive && !inexact\n );\n } finally {\n this.#scopes = scopes;\n }\n }\n /**\n * Whether a row that holds `held` of `field` holds the value `asked`:\n * `undefined` where the two are spelled apart and may still be one value to\n * the database (an instant, a decimal, a number, a document, an\n * identifier), which then answers.\n */\n tld(\n model: AnyModel,\n field: string,\n held: unknown,\n asked: unknown\n ): boolean | undefined {\n if (same(held, asked)) return true;\n const leaf = this.#lf(model, field);\n return leaf.list || leaf.id || !SPELLED_ONCE.has(leaf.type)\n ? undefined\n : false;\n }\n physical(model: AnyModel, field: string): PhysicalField {\n return this.#ph(model, field);\n }\n keyOrder(model: AnyModel): readonly string[] {\n const catalog = getModelKeyCatalog(model);\n const bare = catalog.addressableKeys.find(\n (key) => key.kind === \"primary\" && key.name === undefined\n );\n if (bare) return bare.fields;\n const rowKey = catalog.rowKey;\n if (!rowKey) engineFault(\"Paginated orderBy requires PK.\");\n const fields = new Set<string>(rowKey.fields);\n return objKeys(scalarsOf(model)).filter((field) => fields.has(field));\n }\n abstract select(\n model: AnyModel,\n args: Partial<Arguments>,\n membership?: { edge: Membership; parent: Input },\n controls?: SelectControls\n ): Query;\n abstract read(\n model: AnyModel,\n operation: ReadOperation,\n args: Arguments\n ): Read;\n protected spSum(leaf: Leaf): SplitSum | undefined {\n if (!leaf.widened) return undefined;\n const { numberSum, integerSum } = this.#a.aggregates;\n if (leaf.type === \"number\")\n return numberSum && { sql: numberSum, join: joinNumberSum };\n return (\n integerSum && {\n sql: integerSum,\n join: (parts) => joinIntegerSum(parts, leaf.type),\n }\n );\n }\n abstract selectSeries(\n prepared: PreparedProjection,\n identities: Input[],\n operation?: \"createMany\" | \"updateMany\"\n ): Query;\n protected seriesExpectation(\n model: AnyModel,\n count: number,\n operation: \"createMany\" | \"updateMany\"\n ): NonNullable<Query[\"expectedRows\"]> {\n const msg = `${operation} with 'select' could not read back a row at its primary key.`;\n return {\n count,\n missing:\n operation === \"createMany\"\n ? new QueryEngineError(msg)\n : new TransactionError(msg, {\n meta: { model: nameOf(model) ?? \"unknown\", operation },\n }),\n };\n }\n #projectCounts(\n model: AnyModel,\n name: string,\n selection: unknown,\n fields: Record<string, Shape | Leaf>,\n prepared: PreparedProjectionField[]\n ): void {\n const counts = this.#prepareCounts(model, selection);\n if (counts.length === 0) return;\n fields[name] = {\n kind: \"object\",\n nullable: false,\n fields: fromEntries(counts.map((count) => [count.relation, COUNT_LEAF])),\n };\n prepared.push({ kind: \"counts\", name, counts });\n }\n #projectAggregates(\n model: AnyModel,\n name: string,\n selection: Input,\n fields: Record<string, Shape | Leaf>,\n prepared: PreparedProjectionField[]\n ): void {\n const aggregates: PreparedRelationAggregate[] = [];\n const shapes: Record<string, Shape> = {};\n for (const relation of objKeys(selection)) {\n const entry = selection[relation] as Input;\n const edge = this.#bm(model, relation);\n const aggregated = this.aggSel(edge.target, entry);\n shapes[relation] = {\n kind: \"object\",\n nullable: false,\n fields: aggregated.shape,\n };\n aggregates.push({\n relation,\n edge,\n selector:\n entry.where === undefined\n ? undefined\n : this.#ps(edge.target, entry.where as Input),\n selection: aggregated,\n });\n }\n fields[name] = { kind: \"object\", nullable: false, fields: shapes };\n prepared.push({ kind: \"aggregates\", name, aggregates });\n }\n aggSel(model: AnyModel, args: Input): PreparedAggregates {\n const shape: Record<string, Shape | Leaf> = {};\n const members: PreparedAggregates[\"members\"][number][] = [];\n for (const name of AGGREGATES) {\n const selection = args[name];\n if (!selection) continue;\n if (name === \"_count\" && selection === true) {\n shape._count = COUNT_LEAF;\n members.push({ name, fields: undefined });\n continue;\n }\n const selected = objKeys(selection as Input).filter(\n (field) => (selection as Input)[field]\n );\n if (selected.length === 0) continue;\n const leaves: Record<string, Leaf> = {};\n for (const field of selected)\n leaves[field] = this.aggregateLeaf(model, name, field);\n shape[name] = { kind: \"object\", fields: leaves };\n members.push({ name, fields: selected });\n }\n return { shape, members };\n }\n aggregateLeaf(model: AnyModel, aggregate: Aggregate, field: string): Leaf {\n if (aggregate === \"_count\") return COUNT_LEAF;\n const leaf = this.#lf(model, field);\n return aggregate === \"_avg\" && leaf.type !== \"decimal\"\n ? { kind: \"scalar\", type: \"number\", nullable: true }\n : {\n ...leaf,\n nullable: true,\n widened: aggregate === \"_sum\" ? true : undefined,\n };\n }\n #projectVariants(\n model: AnyModel,\n name: string,\n resolved: ResolvedSlot,\n selection: unknown,\n fields: Record<string, Shape | Leaf>,\n prepared: PreparedProjectionField[],\n path: string\n ): void {\n const edge = resolved.edge as ResolvedVariantEdge;\n const many = edge.kind === \"variantJunctionCarrier\";\n const collections: Record<string, CollectionShape> = {};\n const documents: Record<string, Shape> = {};\n const preparedArms: ({\n readonly variant: string;\n } & PreparedRelationProjection)[] = [];\n const memberships = many\n ? edge.members.map(({ variant }) => ({\n variant,\n edge: this.#bm(model, name, variant) as Extract<\n Membership,\n { kind: \"junction\" }\n >,\n }))\n : [];\n for (const { variant } of edge.members) {\n const arm = selectedArm(selection, many, variant);\n if (arm === undefined) continue;\n const nested = this.#prepareRelationProjection(\n this.#bm(model, name, variant),\n arm,\n `${path}${many ? \"variants.\" : \"\"}${variant}.`\n );\n if (many) collections[variant] = collectionShape(nested);\n else documents[variant] = this.#relationShape(nested);\n preparedArms.push({ variant, ...nested });\n }\n fields[name] = many\n ? { kind: \"variants\", relation: name, many, arms: collections }\n : { kind: \"variants\", relation: name, many, arms: documents };\n prepared.push({\n kind: \"variants\",\n name,\n many,\n arms: preparedArms,\n memberships,\n });\n }\n prepareProjection(\n model: AnyModel,\n args: Partial<Arguments>,\n internal = false,\n path = \"\"\n ): PreparedProjection {\n const added = internal\n ? undefined\n : this.domain?.project?.preparing(model, args.select, path);\n const scalars =\n args.select === undefined ||\n (added === undefined && namesDefault(model, args.select));\n const shared = scalars && args.include === undefined;\n const defaults = added?.defaults ?? this.#views.defaultProjections;\n if (shared) {\n const resolved = defaults.get(model);\n if (resolved !== undefined) return resolved;\n }\n let selected: Input;\n let prepared: PreparedProjectionField[];\n let fields: Record<string, Shape | Leaf>;\n if (scalars && args.include !== undefined && added === undefined) {\n const base = this.prepareProjection(model, {}, true);\n prepared = base.fields[0]?.kind === \"sentinel\" ? [] : base.fields.slice();\n fields = { ...base.shape.fields };\n selected = args.include;\n } else {\n selected = args.select ?? defaultSelection(model);\n if (args.include !== undefined)\n selected = { ...selected, ...args.include, ...selected };\n prepared = [];\n fields = {};\n }\n let distanceSelected = false;\n const view = viewFacts(model);\n const rels = model[\"~\"].state.relations;\n for (const name of objKeys(selected)) {\n const selection = selected[name];\n if (!selection) continue;\n if (view?.documents.includes(name)) {\n prepared.push({ kind: \"document\", name });\n fields[name] = this.#documentShape(model, view, name);\n continue;\n }\n if (name === \"_count\") {\n this.#projectCounts(model, name, selection, fields, prepared);\n continue;\n }\n if (name === \"_aggregate\") {\n this.#projectAggregates(\n model,\n name,\n selection as Input,\n fields,\n prepared\n );\n continue;\n }\n const isRel = Boolean(rels[name]);\n if (!isRel) {\n const distance =\n selection === true ? undefined : (selection as Input)._distance;\n if (distance !== undefined) {\n if (distanceSelected) engineFault(DISTANCE_SELECTED_TWICE);\n const spec = distance as Input;\n prepared.push({\n kind: \"distance\",\n name: DISTANCE_FIELD,\n field: name,\n specification: spec,\n });\n const physical = this.#ph(model, name);\n fields[DISTANCE_FIELD] = {\n kind: \"scalar\",\n type: \"number\",\n nullable:\n physical.nullable ||\n (physical.state.type === \"vector\" && spec.metric === \"cosine\"),\n };\n distanceSelected = true;\n continue;\n }\n }\n if (added?.key(name, selection, fields, prepared)) continue;\n if (!isRel) {\n prepared.push({ kind: \"scalar\", name });\n fields[name] = this.#lf(model, name);\n added?.field(name, prepared);\n continue;\n }\n const resolved = this.#slot(model, name);\n const childPath = `${path}${args.include?.[name] === undefined ? \"select\" : \"include\"}.${name}.`;\n if (variantCarrier(resolved)) {\n this.#projectVariants(\n model,\n name,\n resolved,\n selection,\n fields,\n prepared,\n childPath\n );\n continue;\n }\n const edge = this.#bm(model, name);\n if (this.domain === undefined && namesDefaultNode(edge, selection)) {\n const relation = this.#defaultRelation(edge);\n fields[name] = relation.shape;\n prepared.push(relation.field);\n continue;\n }\n const nested = this.#prepareRelationProjection(\n edge,\n selection,\n childPath\n );\n fields[name] = this.#relationShape(nested);\n prepared.push(relationField(name, nested));\n }\n if (prepared.length === 0)\n prepared.push({ kind: \"sentinel\", name: EMPTY_ROW_RESULT_KEY });\n const projection: PreparedProjection = {\n model,\n fields: prepared,\n shape: { kind: \"object\", fields, ...added?.shape() },\n };\n if (shared) defaults.set(model, projection);\n return projection;\n }\n #documentShape(view: AnyModel, facts: ViewFacts, name: string): Shape | Leaf {\n const shapes = memo(\n this.#views.documents,\n view,\n () =>\n (this.domain?.queries ?? this).prepareProjection(\n facts.source,\n this.#s.admit(facts.source, \"findMany\", facts.query)\n ).shape.fields\n );\n return shapes[name]!;\n }\n #defaultRelation(edge: Membership): DefaultRelation {\n const relations = memo(\n this.#views.defaultRelations,\n edge.source,\n () => new Map<string, DefaultRelation>()\n );\n return memo(relations, edge.name, () => {\n const nested = this.#prepareRelationProjection(edge, true);\n return {\n field: relationField(edge.name, nested),\n shape: this.#relationShape(nested),\n };\n });\n }\n #relationShape(nested: PreparedRelationProjection): Shape {\n const { edge, recurrence } = nested;\n if (recurrence)\n return {\n kind: \"recursive\",\n relation: edge.name,\n many: edge.many,\n optional: slotMayBeEmpty(this.#slot(edge.source, edge.name)),\n recurrence,\n row: nested.projection.shape,\n identity: this.#s\n .keys(edge.target)\n .map((field) => this.#lf(edge.target, field)),\n };\n return edge.many ? collectionShape(nested) : nested.projection.shape;\n }\n #prepareLinkRow(\n edge: Membership,\n nested: Partial<Arguments>\n ): [Partial<Arguments>, PreparedLinkRow?] {\n if (edge.kind !== \"junction\" || !edge.declared) return [nested];\n const { select, include } = nested as {\n select?: Record<string, unknown>;\n include?: Record<string, unknown>;\n };\n const asked = select?.$through ?? include?.$through;\n if (select?.$through === undefined && include?.$through === undefined)\n return [nested];\n const rest = {\n ...nested,\n ...(select && { select: withoutLinkKey(select as Input) }),\n ...(include && { include: withoutLinkKey(include as Input) }),\n };\n if (!asked) return [rest];\n const model = edge.declared.model;\n const named = objEntries((asked as Input).select as Input)\n .filter(([, wanted]) => wanted === true)\n .map(([field]) => field);\n this.domain?.refuseHiddenLinkRow(this, edge, named, \"read\");\n return [\n rest,\n {\n model,\n fields: named,\n shape: {\n kind: \"object\",\n fields: fromEntries(\n named.map((field) => [field, this.#lf(model, field)])\n ),\n },\n },\n ];\n }\n #prepareRelationProjection(\n edge: Membership,\n selection: unknown,\n path = \"\"\n ): PreparedRelationProjection {\n const [taken, linkRow] = this.#prepareLinkRow(\n edge,\n selection === true ? {} : (selection as Input as Partial<Arguments>)\n );\n const linkWhere =\n edge.kind === \"junction\" && edge.declared\n ? (taken.where?.$through as Input | undefined)\n : undefined;\n if (linkWhere)\n this.domain?.refuseHiddenLinkRow(\n this,\n edge,\n objKeys(linkWhere),\n \"filter\"\n );\n const nested = linkWhere\n ? { ...taken, where: withoutLinkKey(taken.where as Input) }\n : taken;\n return {\n edge,\n linkRow,\n linkWhere:\n linkWhere &&\n this.#ps(\n (edge as Extract<Membership, { kind: \"junction\" }>).declared!.model,\n linkWhere\n ),\n arguments: {\n selector: nested.where\n ? this.#ps(edge.target, nested.where)\n : undefined,\n orderBy:\n nested.orderBy ??\n (edge.many ? this.defaultOrder(edge.target) : undefined),\n take: nested.take,\n skip: nested.skip,\n cursor: nested.cursor,\n distinct: nested.distinct,\n },\n projection: this.prepareProjection(edge.target, nested, false, path),\n recurrence: nested.recurse,\n };\n }\n #prepareCounts(\n model: AnyModel,\n selection: unknown\n ): readonly PreparedCount[] {\n const counts: PreparedCount[] = [];\n for (const [relation, configuration] of objEntries(\n (selection as Input).select as Input\n )) {\n if (!configuration) continue;\n const { edges, variants } = this.countedMemberships(model, relation);\n const where =\n configuration === true\n ? undefined\n : ((configuration as Input).where as Input | undefined);\n if (where === undefined) {\n counts.push({ relation, edges });\n continue;\n }\n if (!variants) {\n counts.push({\n relation,\n edges,\n selector: this.#ps(edges[0]!.target, where),\n });\n continue;\n }\n const arm = edges.find(\n (edge) => edge.scope.member?.variant === where.type\n );\n if (!arm)\n engineFault(\n `Unknown polymorphic target '${String(where.type)}' on '${relation}'.`\n );\n const negated = where.isNot !== undefined;\n const inner = negated ? where.isNot : where.is;\n counts.push({\n relation,\n edges: [arm],\n selector:\n inner === undefined\n ? undefined\n : this.#ps(arm.target, inner as Input),\n ...(negated && { negated: true }),\n });\n }\n return counts;\n }\n countedMemberships(\n model: AnyModel,\n relation: string\n ): {\n readonly edges: readonly Membership[];\n readonly variants: boolean;\n } {\n const carrier = variantCarrier(this.#slot(model, relation));\n return {\n edges: carrier\n ? carrier.members.map(({ variant }) =>\n this.#bm(model, relation, variant)\n )\n : [this.#bm(model, relation)],\n variants: carrier !== undefined,\n };\n }\n chkRows(query: Query, rows: number): void {\n if (query.expectedRows && rows < query.expectedRows.count)\n throw query.expectedRows.missing;\n if (query.expectedRows && rows > query.expectedRows.count)\n engineFault(\"createMany row count mismatch.\");\n }\n decodeQuery(query: Query, rows: Input[]): Input[] {\n this.chkRows(query, rows.length);\n return this.decodeProjection(query.shape, rows, true);\n }\n decodeProjection(\n shape: ProjectionShape,\n rows: Input[] | unknown[][],\n internal = false,\n columns?: readonly string[]\n ): Input[] {\n if (rows.length === 0) return [];\n const read = this.compileReader(shape, internal, false, columns);\n return rows.map((row) => read(row) as Input);\n }\n compileReader(\n shape: Shape | Leaf,\n internal: boolean,\n carried: boolean,\n columns?: readonly string[]\n ): Reader {\n return this.#cr(shape, internal, carried, columns);\n }\n #cr(\n shape: Shape | Leaf,\n internal: boolean,\n carried: boolean,\n columns?: readonly string[]\n ): Reader {\n if (shape.kind === \"scalar\")\n return this.#compileLeaf(shape, internal, carried).read;\n if (shape.kind === \"recursive\") {\n const readRow = this.#cr(shape.row, internal, true);\n const readIdentity = shape.identity.map((leaf) =>\n this.#cr(leaf, true, true)\n );\n return (value) =>\n decodeRecursiveCarrier(shape, value, readRow, readIdentity);\n }\n if (shape.kind === \"variants\") {\n const missingRecord = (type: string): never =>\n engineFault(\n `Polymorphic '${shape.relation}' missing '${type}' record.`\n );\n const slot = (value: unknown): Input => {\n const variants = providerDocument(providerJson(value));\n if (!variants) refuseResult(\"polymorphic slot\", \"not an object\");\n const evidence = own(variants, POLYMORPHIC_COLLECTION_ORPHANS_KEY);\n if (evidence !== undefined) {\n const orphans = providerDocument(evidence);\n if (!orphans) refuseResult(\"polymorphic slot\");\n for (const [type, count] of objEntries(orphans))\n if (Number(count) > 0)\n if (type === \"$storage\")\n engineFault(`Polymorphic '${shape.relation}' invalid row.`);\n else missingRecord(type);\n }\n return variants;\n };\n if (shape.many) {\n const arms = objKeys(shape.arms).map(\n (type) =>\n [\n type,\n this.#compileCollection(shape.arms[type]!, internal),\n ] as const\n );\n return (value) => {\n const variants = slot(value);\n const values: unknown[] = [];\n for (const [type, read] of arms)\n for (const data of read(own(variants, type)))\n values.push({ type, data });\n return values;\n };\n }\n const arms = objKeys(shape.arms).map((type) => {\n const arm = shape.arms[type]!;\n return [type, arm, this.#cr(arm, internal, true)] as const;\n });\n return (value) => {\n const variants = slot(value);\n for (const [type, arm, read] of arms) {\n const carrier = own(variants, type);\n if (orphanedArm(carrier, arm)) missingRecord(type);\n const data = read(carrier);\n if (data !== null) return { type, data };\n }\n return null;\n };\n }\n if (shape.kind === \"collection\")\n return this.#compileCollection(shape, internal);\n const fields = objKeys(shape.fields);\n const readers: Reader[] = [];\n const unchanged: (string | undefined)[] = [];\n for (const field of fields) {\n const nested = shape.fields[field]!;\n if (nested.kind === \"scalar\") {\n const leaf = this.#compileLeaf(nested, internal, carried);\n readers.push(leaf.read);\n unchanged.push(leaf.unchanged);\n } else {\n readers.push(this.#cr(nested, internal, true));\n unchanged.push(undefined);\n }\n }\n const members =\n carried && this.#a.capabilities.carriesDocumentsAsArrays === true;\n if (shape.gates && !internal)\n return this.domain!.project!.gatedDocument(\n this,\n carried,\n shape,\n fields,\n readers,\n columns,\n members\n );\n const inherited = fields.map((field) => field in Object.prototype);\n if (members) {\n const size = fields.length + (shape.gates?.length ?? 0);\n return (value) => {\n const source = providerMembers(value, size);\n if (!source) return refuseInvalidDocument(source, shape.nullable);\n const plain = Object.getPrototypeOf(source) === Array.prototype;\n const document: Input = {};\n for (let index = 0; index < fields.length; index++) {\n const field = fields[index]!;\n const raw =\n plain || hasOwn(source, index) ? source[index] : undefined;\n const tag = unchanged[index];\n const decoded =\n typeof raw === tag ||\n (typeof raw === \"number\" &&\n (tag === \"int\"\n ? Number.isSafeInteger(raw)\n : tag === \"num\" && Number.isFinite(raw)))\n ? raw\n : readers[index]!(raw);\n if (inherited[index]) defineOwn(document, field, decoded);\n else document[field] = decoded;\n }\n return document;\n };\n }\n if (columns) {\n const positions = fields.map((field) => columns.lastIndexOf(field));\n return (value) => {\n if (!isArr(value)) refuseResult(\"row\");\n const document: Input = {};\n for (let index = 0; index < fields.length; index++) {\n const position = positions[index]!;\n const raw =\n position >= 0 && hasOwn(value, position)\n ? value[position]\n : undefined;\n const field = fields[index]!;\n const tag = unchanged[index];\n const decoded =\n typeof raw === tag ||\n (typeof raw === \"number\" &&\n (tag === \"int\"\n ? Number.isSafeInteger(raw)\n : tag === \"num\" && Number.isFinite(raw)))\n ? raw\n : readers[index]!(raw);\n if (inherited[index]) defineOwn(document, field, decoded);\n else document[field] = decoded;\n }\n return document;\n };\n }\n return (value) => {\n const source = providerDocument(providerJson(value));\n if (!source) return refuseInvalidDocument(source, shape.nullable);\n const plain = isPlain(source);\n const document: Input = {};\n let index = 0;\n if (plain)\n for (const key in source) {\n if (key !== fields[index] || inherited[index]) break;\n const raw = source[key];\n const tag = unchanged[index];\n document[key] =\n typeof raw === tag ||\n (typeof raw === \"number\" &&\n (tag === \"int\"\n ? Number.isSafeInteger(raw)\n : tag === \"num\" && Number.isFinite(raw)))\n ? raw\n : readers[index]!(raw);\n index++;\n }\n for (; index < fields.length; index++) {\n const field = fields[index]!;\n const decoded = readers[index]!(\n plain && !inherited[index] ? source[field] : own(source, field)\n );\n if (inherited[index]) defineOwn(document, field, decoded);\n else document[field] = decoded;\n }\n return document;\n };\n }\n #compileCollection(\n shape: CollectionShape,\n internal: boolean\n ): (value: unknown) => unknown[] {\n const readRow = this.#cr(shape.row, internal, true);\n return (value) => {\n const decoded = providerJson(value);\n if (!isArr(decoded)) refuseResult(\"collection\", \"not an array\");\n const rows = decoded.map(readRow);\n return shape.reversed ? rows.reverse() : rows;\n };\n }\n #compileScalar(\n leaf: Leaf,\n internal: boolean,\n provider?: FieldReader,\n list?: Reader\n ): CompiledLeaf {\n const readValue = list ?? this.#compileScalarValue(leaf, internal);\n const nullable = leaf.nullable;\n const allowsJsonNull = leaf.type === \"json\" && leaf.list !== true;\n const read: Reader = (raw) => {\n if (raw === null) {\n if (nullable) return null;\n if (!allowsJsonNull)\n refuseResult(\n leaf.type,\n leaf.list ? \"required list is null\" : \"required scalar is null\"\n );\n }\n if (raw === undefined) refuseResult(leaf.type, \"absent\");\n return readValue(provider === undefined ? raw : provider(raw));\n };\n const join = this.spSum(leaf)?.join;\n if (join)\n return { read: (parts) => read(join(parts)), unchanged: undefined };\n return {\n read,\n unchanged: provider ? undefined : UNCHANGED_BY.get(readValue),\n };\n }\n #compileLeaf(leaf: Leaf, internal: boolean, carried: boolean): CompiledLeaf {\n const provider = carried ? undefined : this.#fieldReader(leaf.type);\n const list = leaf.list ? this.#compileList(leaf, internal) : undefined;\n return this.#compileScalar(leaf, internal, provider, list);\n }\n #compileScalarValue(leaf: Leaf, internal: boolean): Reader {\n const type = leaf.type;\n function bad(detail?: string): never {\n refuseResult(type, detail);\n }\n const identifier = leaf.id;\n if (identifier)\n return (value) => {\n const decoded =\n decodeIdentifier(identifier, value) ?? bad(\"invalid identifier\");\n return internal && identifier.representation === \"text\"\n ? value\n : decoded;\n };\n const direct = SCALAR_DECODERS[type];\n if (direct) return direct;\n switch (type) {\n case \"int\":\n return leaf.widened ? (sum) => decodeInt(sum, true) : decodeInt;\n case \"number\":\n return leaf.widened ? (sum) => sum : decodeNumber;\n case \"decimal\":\n return (value) =>\n decodeDecimalScalar(\n value,\n leaf.decimal!,\n leaf.widened === true,\n internal,\n this.#a.result\n ) ?? bad(\"invalid decimal\");\n case \"datetime\":\n return (value) => {\n if (leaf.dateTime && leaf.dateTime !== \"text\")\n return decodePhysicalDateTime(value, leaf.dateTime) ?? bad();\n if (value instanceof Date)\n return isDateTimeInstant(value.getTime())\n ? new Date(value.getTime())\n : bad();\n const parsed =\n (typeof value === \"string\"\n ? decodeProviderTimestamp(value)\n : undefined) ?? bad();\n return internal ? value : parsed;\n };\n case \"date\":\n if (leaf.period) return decodePeriod;\n return (value) => {\n if (value instanceof Date) {\n const epoch = value.getTime();\n return isDateTimeInstant(epoch) && epoch % 864e5 === 0\n ? new Date(epoch)\n : bad();\n }\n const match =\n typeof value === \"string\" ? DATE_TEXT.exec(value) : null;\n return (\n (match &&\n decodeProviderTimestamp(\n `${match[1]}-${match[2]}-${match[3]}T00:00:00.000Z${match[4] ? \" BC\" : \"\"}`\n )) ||\n bad()\n );\n };\n case \"enum\":\n return (value) =>\n typeof value === \"string\" && leaf.enumValues?.has(value)\n ? value\n : bad();\n case \"vector\":\n return (value) => {\n const decoded = providerJson(value);\n if (\n !isArr(decoded) ||\n decoded.some((member) => !Number.isFinite(member)) ||\n (leaf.dimension !== undefined && decoded.length !== leaf.dimension)\n )\n bad();\n return [...decoded];\n };\n case \"point\":\n return (value) => {\n const point = validateGeoPoint(providerJson(value));\n if (point.issues) bad(point.issues[0]?.message);\n return point.value;\n };\n default:\n return () => bad();\n }\n }\n #compileList(leaf: Leaf, internal: boolean): Reader {\n if (leaf.type === \"decimal\")\n return (value) =>\n decodeDecimalList(value, leaf.decimal!, internal, this.#a.result) ??\n refuseResult(leaf.type);\n const readMember = this.#compileScalar(\n { ...leaf, list: undefined, nullable: false },\n internal\n ).read;\n const arrayText = this.#a.result.enumListRepresentation === \"arrayText\";\n return (value) => {\n const items: unknown =\n typeof value !== \"string\"\n ? value\n : arrayText && value.startsWith(\"{\")\n ? providerArrayMembers(value)\n : JSON.parse(value);\n if (!isArr(items)) refuseResult(leaf.type, \"not an array\");\n return items.map((item, index) => {\n if (!hasOwn(items, index)) refuseResult(leaf.type, \"sparse array\");\n return readMember(item);\n });\n };\n }\n}\n\nfunction decodeJson(value: unknown): unknown {\n if (value === null || typeof value === \"string\" || typeof value === \"boolean\")\n return value;\n if (typeof value === \"number\")\n return Number.isFinite(value)\n ? value\n : refuseResult(\"json\", \"non-finite number\");\n return jsonValue(value, []);\n}\n\nfunction jsonValue(value: unknown, seen: object[]): unknown {\n if (value === null || typeof value === \"string\" || typeof value === \"boolean\")\n return value;\n if (typeof value === \"number\")\n return Number.isFinite(value)\n ? value\n : refuseResult(\"json\", \"non-finite number\");\n if (typeof value === \"bigint\") {\n const parsed = Number(value);\n return Number.isFinite(parsed) ? parsed : refuseResult(\"json\");\n }\n if (isArr(value)) {\n if (seen.includes(value)) refuseResult(\"json\", \"cyclic JSON\");\n seen.push(value);\n const members = new Array<unknown>(value.length);\n for (let index = 0; index < value.length; index += 1) {\n if (!hasOwn(value, index)) refuseResult(\"json\", \"sparse array\");\n members[index] = jsonValue(value[index], seen);\n }\n seen.pop();\n return members;\n }\n if (isPlain(value)) {\n if (seen.includes(value)) refuseResult(\"json\", \"cyclic JSON\");\n seen.push(value);\n const members: Record<string, unknown> = {};\n for (const key in value) {\n if (!hasOwn(value, key)) continue;\n const member = jsonValue(value[key], seen);\n if (key in Object.prototype) defineOwn(members, key, member);\n else members[key] = member;\n }\n seen.pop();\n return members;\n }\n refuseResult(\"json\");\n}\n\nfunction collectionShape(nested: PreparedRelationProjection): CollectionShape {\n const take = nested.arguments.take;\n return {\n kind: \"collection\",\n reversed: take !== undefined && take < 0 ? true : undefined,\n row: nested.linkRow\n ? {\n ...nested.projection.shape,\n fields: {\n ...nested.projection.shape.fields,\n $through: nested.linkRow.shape,\n },\n }\n : nested.projection.shape,\n };\n}\n\nfunction decodeRecursiveCarrier(\n shape: Extract<Shape, { kind: \"recursive\" }>,\n value: unknown,\n readRow: Reader,\n readIdentity: readonly Reader[]\n): unknown {\n function bad(what: string, detail?: string): never {\n refuseResult(`recursive ${what}`, detail);\n }\n const doc = (v: unknown, t: string): Input => {\n const d = providerDocument(v);\n if (!d) bad(t, \"not an object\");\n return d;\n };\n const carrier = doc(providerJson(value), \"carrier\");\n const C = RECURSIVE_CARRIER;\n const root = own(carrier, C.r);\n const rawNodes = own(carrier, C.n);\n const rawEdges = own(carrier, C.e);\n if (!(isArr(root) && isArr(rawNodes) && isArr(rawEdges))) bad(\"carrier\");\n\n const identity = (tuple: unknown): string => {\n if (!isArr(tuple) || tuple.length !== shape.identity.length)\n bad(\"identity\");\n let index = 0;\n for (const read of readIdentity) read(tuple[index++]);\n return JSON.stringify(tuple);\n };\n const rootKey = identity(root);\n const nodes = new Map<string, unknown>();\n for (const rawNode of rawNodes) {\n const node = doc(rawNode, \"node\");\n const key = identity(own(node, C.k));\n if (nodes.has(key)) bad(\"node\", \"duplicate node\");\n nodes.set(key, own(node, C.w));\n }\n\n type Edge = readonly [child: string, depth?: number];\n const edges = new Map<string, Edge[]>();\n const facts = new Set<string>();\n const maxDepth = shape.recurrence.depth;\n for (const rawEdge of rawEdges) {\n const edge = doc(rawEdge, \"edge\");\n const parent = identity(own(edge, C.p));\n const child = identity(own(edge, C.c));\n if (!nodes.has(child)) bad(\"edge endpoint\");\n const rawDepth = own(edge, C.d);\n let depth: number | undefined;\n if (maxDepth === false) {\n if (rawDepth !== undefined) bad(\"depth\");\n } else {\n if (\n !Number.isSafeInteger(rawDepth) ||\n (rawDepth as number) < 1 ||\n (rawDepth as number) > maxDepth\n )\n bad(\"depth\");\n depth = rawDepth as number;\n }\n const fact = `${parent}\\0${child}\\0${depth ?? \"\"}`;\n if (facts.has(fact)) bad(\"edge\", \"duplicate edge\");\n facts.add(fact);\n pushTo(edges, parent, depth === undefined ? [child] : [child, depth]);\n }\n\n const successors = new Map<string, readonly string[]>();\n for (const [parent, entries] of edges) {\n if (parent !== rootKey && !nodes.has(parent)) bad(\"edge endpoint\");\n const unique = [...new Set(entries.map((entry) => entry[0]))];\n if (!shape.many && unique.length > 1) bad(\"singular relation\");\n successors.set(parent, unique);\n }\n\n const cutoff = (depth: number) => !carriesRepeatedKey(maxDepth, depth);\n const consumed = new Set<Edge>();\n const reached = new Set<string>();\n const levels = new Set<string>();\n const pending: (readonly [string, number])[] = [[rootKey, 0]];\n for (const [parent, level] of pending) {\n const children = new Set<string>();\n for (const entry of edges.get(parent) ?? []) {\n const [child, depth] = entry;\n if (depth !== undefined && depth !== level + 1) continue;\n consumed.add(entry);\n reached.add(child);\n children.add(child);\n const at = depth === undefined ? child : `${depth} ${child}`;\n if (levels.has(at)) continue;\n levels.add(at);\n pending.push([child, level + 1]);\n }\n if (\n maxDepth !== false &&\n !cutoff(level) &&\n children.size !== (successors.get(parent)?.length ?? 0)\n )\n bad(\"depth\");\n }\n if (maxDepth !== false && consumed.size !== facts.size) bad(\"depth\");\n if (reached.size !== nodes.size) bad(\"unreachable node\");\n\n const collapse = (rows: Input[]): unknown =>\n shape.many ? rows : (rows[0] ?? null);\n type Frame = [string, number, Input, readonly string[], Input[], number];\n const active = new Set<string>([rootKey]);\n const stack: Frame[] = [];\n let occurrences = 0;\n const budget = shape.recurrence.maxOccurrences ?? DEFAULT_MAX_OCCURRENCES;\n const follow = (from: number, key: string): void => {\n if (active.has(key)) {\n if (shape.recurrence.cycles === \"reject\")\n throw new UnsupportedOperationError(\n `Recursive '${shape.relation}' has a cycle.`,\n {\n meta: {\n relation: shape.relation,\n feature: \"cyclic recursive traversal\",\n },\n }\n );\n if (shape.recurrence.cycles === \"prevent\") return;\n }\n if (++occurrences > budget)\n throw new RecursiveOutputOverBudget(shape.relation, budget);\n active.add(key);\n const decoded = readRow(nodes.get(key));\n if (decoded === null) bad(\"row\");\n const d = from + 1;\n stack.push([\n key,\n d,\n decoded as Input,\n cutoff(d) ? [] : (successors.get(key) ?? []),\n [],\n 0,\n ]);\n };\n const rootRows: Input[] = [];\n for (const child of successors.get(rootKey) ?? []) {\n follow(0, child);\n while (stack.length) {\n const cur = stack.at(-1)!;\n if (cur[5] < cur[3].length) {\n follow(cur[1], cur[3][cur[5]++]!);\n continue;\n }\n active.delete(cur[0]);\n stack.pop();\n if (!cutoff(cur[1])) cur[2][shape.relation] = collapse(cur[4]);\n (stack.at(-1)?.[4] ?? rootRows).push(cur[2]);\n }\n }\n return collapse(rootRows);\n}\n\nfunction defineOwn(\n target: Record<string, unknown>,\n key: string,\n value: unknown\n): void {\n Object.defineProperty(target, key, {\n configurable: true,\n enumerable: true,\n value,\n writable: true,\n });\n}\n\nfunction refuseInvalidDocument(\n source: null | undefined,\n nullable: boolean | undefined\n): null {\n if (source === null) {\n if (nullable === false) refuseResult(\"row\", \"null document\");\n return null;\n }\n refuseResult(\"row\", \"not a row\");\n}\n\nconst INTEGER_TEXT = /^(?:0|-?[1-9]\\d*)$/;\nconst DATE_TEXT = /^(\\d{4})-(\\d{2})-(\\d{2})(?: (BC))?$/;\nconst PERIOD_TEXT = /^(\\d{4,})(-\\d{2}-\\d{2}) (AD|BC)$/;\nconst decodePeriod: Reader = (value) => {\n const match = typeof value === \"string\" ? PERIOD_TEXT.exec(value) : null;\n if (!match) refuseResult(\"date\");\n if (match[3] === \"AD\") return match[1]! + match[2]!;\n const year = 1 - Number(match[1]);\n return `${year < 0 ? \"-\" : \"\"}${String(Math.abs(year)).padStart(4, \"0\")}${match[2]}`;\n};\nconst TIME_TEXT =\n /^(\\d{2}):(\\d{2}):(\\d{2})(?:\\.\\d{1,6})?(?:Z|[+-](\\d{2})(?::?(\\d{2}))?)?$/;\nconst TIME_ZONE_SUFFIX = /(?:Z|[+-]\\d{2}(?::?\\d{2})?)$/;\nconst TRAILING_FRACTION_ZEROS = /\\.?0+$/;\n\nfunction decodeString(value: unknown): unknown {\n if (typeof value === \"string\") return value;\n refuseResult(\"string\", \"not a string\");\n}\n\nfunction decodeBoolean(value: unknown): unknown {\n if (typeof value === \"boolean\") return value;\n if (value === 0 || value === 0n) return false;\n if (value === 1 || value === 1n) return true;\n refuseResult(\"boolean\", \"not a boolean\");\n}\n\nconst UNCHANGED_BY = new Map<Reader, string>([\n [decodeString, \"string\"],\n [decodeBoolean, \"boolean\"],\n [decodeInt, \"int\"],\n [decodeNumber, \"num\"],\n]);\n\nfunction decodeInt(value: unknown, sum = false): unknown {\n if (typeof value === \"number\") {\n if (sum ? Number.isInteger(value) : Number.isSafeInteger(value))\n return value;\n refuseResult(\"int\", \"outside safe integer range\");\n }\n const parsed =\n typeof value === \"bigint\"\n ? Number(value)\n : typeof value === \"string\" && INTEGER_TEXT.test(value)\n ? Number(value)\n : undefined;\n if (parsed === undefined) refuseResult(\"int\", \"not an integer\");\n if (!(sum ? Number.isInteger(parsed) : Number.isSafeInteger(parsed)))\n refuseResult(\"int\", \"outside safe integer range\");\n return parsed;\n}\n\nfunction decodeBigint(value: unknown): bigint {\n if (typeof value === \"bigint\") return value;\n if (typeof value === \"number\" && Number.isSafeInteger(value))\n return BigInt(value);\n if (typeof value === \"string\" && INTEGER_TEXT.test(value))\n return BigInt(value);\n refuseResult(\"bigint\", \"not an integer\");\n}\n\nfunction decodeNumber(value: unknown): number {\n if (typeof value === \"number\") {\n if (Number.isFinite(value)) return value;\n refuseResult(\"number\", \"not a finite number\");\n }\n const parsed =\n typeof value === \"string\" && value.trim() !== \"\"\n ? Number(value)\n : Number.NaN;\n if (!Number.isFinite(parsed)) refuseResult(\"number\", \"not a finite number\");\n return parsed;\n}\n\nexport type SplitSumSql = ReturnType<\n DatabaseAdapter[\"aggregates\"][\"numberSum\"]\n>;\ninterface SplitSum {\n readonly sql: (expr: Sql) => SplitSumSql;\n readonly join: (parts: unknown) => unknown;\n}\n\nconst NUMBER_SUM_SCALE = 2 ** 64;\n\nfunction joinNumberSum(value: unknown): number | null {\n const [first, second] = sumParts(value, \"number\");\n const high = first === null ? null : decodeNumber(first);\n const low = second === null ? null : decodeNumber(second);\n if (high === null) return low;\n return high * NUMBER_SUM_SCALE + (low ?? 0);\n}\n\nconst INTEGER_SUM_SCALE = 2n ** 32n;\n\nfunction joinIntegerSum(value: unknown, type: string): string | null {\n const [high, low] = sumParts(value, type);\n if (high === null) return null;\n return String(decodeBigint(high) * INTEGER_SUM_SCALE + decodeBigint(low));\n}\n\nfunction sumParts(value: unknown, type: string): [unknown, unknown] {\n if (!isArr(value) || value.length !== 2) refuseResult(type);\n return [value[0], value[1]];\n}\n\nfunction decodeTime(value: unknown): string {\n if (typeof value !== \"string\") refuseResult(\"time\", \"invalid time\");\n const match = TIME_TEXT.exec(value);\n if (\n !(\n match &&\n isDateTimeClock(Number(match[1]), Number(match[2]), Number(match[3]))\n )\n )\n refuseResult(\"time\", \"invalid time\");\n if (Number(match[4] ?? 0) > 23 || Number(match[5] ?? 0) > 59)\n refuseResult(\"time\", \"invalid timezone\");\n let time = value.replace(TIME_ZONE_SUFFIX, \"\");\n if (time.includes(\".\")) time = time.replace(TRAILING_FRACTION_ZEROS, \"\");\n const fraction = time.split(\".\")[1];\n if (fraction && fraction.length > 3)\n refuseResult(\"time\", \"precision exceeds ms\");\n return time;\n}\n\nfunction decodeBlob(value: unknown): Uint8Array {\n if (value instanceof Uint8Array) {\n const out = new Uint8Array(value.byteLength);\n out.set(value);\n return out;\n }\n return normalizeBinaryValue(value).bytes ?? refuseResult(\"blob\");\n}\n\nconst SCALAR_DECODERS: Record<string, Reader> = {\n string: decodeString,\n boolean: decodeBoolean,\n bigint: decodeBigint,\n time: decodeTime,\n blob: decodeBlob,\n json: decodeJson,\n};\n\nfunction providerArrayMembers(text: string): unknown[] {\n if (!(text.startsWith(\"{\") && text.endsWith(\"}\")))\n refuseResult(\"enum\", \"not an array\");\n const body = text.slice(1, -1);\n if (body.length === 0) return [];\n const members: unknown[] = [];\n let index = 0;\n while (index <= body.length) {\n if (body[index] === '\"') {\n let member = \"\";\n index += 1;\n while (index < body.length && body[index] !== '\"') {\n member += body[index] === \"\\\\\" ? body[++index] : body[index];\n index += 1;\n }\n members.push(member);\n index += 2;\n continue;\n }\n const next = body.indexOf(\",\", index);\n const end = next === -1 ? body.length : next;\n const member = body.slice(index, end);\n members.push(member === \"NULL\" ? null : member);\n index = end + 1;\n if (next === -1) break;\n }\n return members;\n}\n\nexport type { PreparedDomain } from \"@extensions/row-domain\";\n"],"mappings":"4iCAqOA,MAAa,IACX,EACA,IAEA,GACG,EAAO,IAAU,EAAO,IAAI,EAAM,EAAE,SAAS,KAAW,IAAA,GACzD,EACD,CAuDH,IAAa,EAAb,KAAuB,CACrB,IACA,KACA,IACA,GACA,YAAY,EAAc,EAAe,CACnC,IAAQ,IAAA,GAAW,KAAK,IAAM,GAC7B,KAAK,IAAM,EACZ,IAAS,IAAA,K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