viborm 1.14.2 → 1.15.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 (272) hide show
  1. package/dist/{adapter-namespace-DaRiTIIf.mjs → adapter-namespace-DD-BQ2Wk.mjs} +2 -2
  2. package/dist/{adapter-namespace-DaRiTIIf.mjs.map → adapter-namespace-DD-BQ2Wk.mjs.map} +1 -1
  3. package/dist/adapters.d.mts +15 -3
  4. package/dist/adapters.mjs +1 -1
  5. package/dist/{args-764KdWMr.mjs → args-BvA37zBZ.mjs} +2 -2
  6. package/dist/{args-764KdWMr.mjs.map → args-BvA37zBZ.mjs.map} +1 -1
  7. package/dist/{batch-refs-C-gx7A4-.mjs → batch-refs-BmEpMmjI.mjs} +2 -2
  8. package/dist/{batch-refs-C-gx7A4-.mjs.map → batch-refs-BmEpMmjI.mjs.map} +1 -1
  9. package/dist/bun-sql.d.mts +1 -1
  10. package/dist/bun-sql.mjs +1 -1
  11. package/dist/bun-sqlite.d.mts +1 -1
  12. package/dist/bun-sqlite.mjs +1 -1
  13. package/dist/cache/cloudflare-kv.d.mts +1 -1
  14. package/dist/cache/cloudflare-kv.mjs +1 -1
  15. package/dist/cache/memory.d.mts +1 -1
  16. package/dist/cache/memory.mjs +1 -1
  17. package/dist/cache.d.mts +2 -2
  18. package/dist/cache.mjs +1 -1
  19. package/dist/{call-Cz8XUmrl.mjs → call-BWFI7-vU.mjs} +2 -2
  20. package/dist/{call-Cz8XUmrl.mjs.map → call-BWFI7-vU.mjs.map} +1 -1
  21. package/dist/cli.mjs +2 -2
  22. package/dist/cli.mjs.map +1 -1
  23. package/dist/client-CVCC-D1j.mjs +2 -0
  24. package/dist/client-CVCC-D1j.mjs.map +1 -0
  25. package/dist/{client-CRxfhw2y.d.mts → client-DZ39sYy2.d.mts} +2 -2
  26. package/dist/{client-y7TV0PRZ.mjs → client-DtPTegtA.mjs} +2 -2
  27. package/dist/{client-y7TV0PRZ.mjs.map → client-DtPTegtA.mjs.map} +1 -1
  28. package/dist/client.d.mts +3 -3
  29. package/dist/client.mjs +1 -1
  30. package/dist/config.d.mts +1 -1
  31. package/dist/config.mjs +1 -1
  32. package/dist/{confine-DqFBTUw6.mjs → confine-BGGv2du0.mjs} +2 -2
  33. package/dist/{confine-DqFBTUw6.mjs.map → confine-BGGv2du0.mjs.map} +1 -1
  34. package/dist/{coordination-6qZHx_kl.mjs → coordination-BY6Np3xV.mjs} +2 -2
  35. package/dist/{coordination-6qZHx_kl.mjs.map → coordination-BY6Np3xV.mjs.map} +1 -1
  36. package/dist/d1.d.mts +1 -1
  37. package/dist/d1.mjs +1 -1
  38. package/dist/{database-adapter-BGqvjeEy.d.mts → database-adapter-D62c-uC6.d.mts} +604 -473
  39. package/dist/{datetime-physical-codec-Dj-APo9f.mjs → datetime-physical-codec-BS2T81sD.mjs} +2 -2
  40. package/dist/{datetime-physical-codec-Dj-APo9f.mjs.map → datetime-physical-codec-BS2T81sD.mjs.map} +1 -1
  41. package/dist/{defaults-DwOHWI_M.mjs → defaults-CrtGVdEC.mjs} +2 -2
  42. package/dist/{defaults-DwOHWI_M.mjs.map → defaults-CrtGVdEC.mjs.map} +1 -1
  43. package/dist/{document-BVTQ-cF-.d.mts → document-o5Bd5ZoJ.d.mts} +1 -1
  44. package/dist/{driver-BBEmaJZy.d.mts → driver-0cdCF_KD.d.mts} +1 -1
  45. package/dist/{driver-BGVcgnIX.mjs → driver-D1grnHEr.mjs} +2 -2
  46. package/dist/{driver-BGVcgnIX.mjs.map → driver-D1grnHEr.mjs.map} +1 -1
  47. package/dist/{driver-BIXhOH2_.mjs → driver-Df88hu4U.mjs} +2 -2
  48. package/dist/{driver-BIXhOH2_.mjs.map → driver-Df88hu4U.mjs.map} +1 -1
  49. package/dist/driver.d.mts +1 -1
  50. package/dist/driver.mjs +1 -1
  51. package/dist/durable-object.d.mts +1 -1
  52. package/dist/durable-object.mjs +1 -1
  53. package/dist/error-mapping-DIRlrmDK.mjs +2 -0
  54. package/dist/error-mapping-DIRlrmDK.mjs.map +1 -0
  55. package/dist/every-BHEmfLOW.mjs +2 -0
  56. package/dist/{every-tOgQmaIE.mjs.map → every-BHEmfLOW.mjs.map} +1 -1
  57. package/dist/execution-context-VMQm-9CH.mjs +2 -0
  58. package/dist/execution-context-VMQm-9CH.mjs.map +1 -0
  59. package/dist/{exports-COCJ8f2f.d.mts → exports-Bzvtum3F.d.mts} +1 -1
  60. package/dist/geo-area-codec-BDvW7IH-.mjs +2 -0
  61. package/dist/{geo-area-codec-mHrM3b9A.mjs.map → geo-area-codec-BDvW7IH-.mjs.map} +1 -1
  62. package/dist/{hydration-A3zffFWP.mjs → hydration-D7U8HACL.mjs} +2 -2
  63. package/dist/{hydration-A3zffFWP.mjs.map → hydration-D7U8HACL.mjs.map} +1 -1
  64. package/dist/{identifier-conversion-DHYPTgzr.mjs → identifier-conversion-Ci_iaJ0b.mjs} +2 -2
  65. package/dist/{identifier-conversion-DHYPTgzr.mjs.map → identifier-conversion-Ci_iaJ0b.mjs.map} +1 -1
  66. package/dist/identifiers-BTCfD5ic.mjs +2 -0
  67. package/dist/identifiers-BTCfD5ic.mjs.map +1 -0
  68. package/dist/index.d.mts +2 -2
  69. package/dist/index.mjs +1 -1
  70. package/dist/instrumentation.d.mts +1 -1
  71. package/dist/instrumentation.mjs +1 -1
  72. package/dist/{introspect-Bm6xnXcG.mjs → introspect-C4T5gt9O.mjs} +2 -2
  73. package/dist/{introspect-Bm6xnXcG.mjs.map → introspect-C4T5gt9O.mjs.map} +1 -1
  74. package/dist/{json-DgMc8-GU.mjs → json-CHdgejCt.mjs} +2 -2
  75. package/dist/{json-DgMc8-GU.mjs.map → json-CHdgejCt.mjs.map} +1 -1
  76. package/dist/judge-words-DpwxOfre.mjs +2 -0
  77. package/dist/judge-words-DpwxOfre.mjs.map +1 -0
  78. package/dist/{key-hxFFCKed.mjs → key-B3xgpu0M.mjs} +2 -2
  79. package/dist/{key-hxFFCKed.mjs.map → key-B3xgpu0M.mjs.map} +1 -1
  80. package/dist/{keys-BQxM4c_a.mjs → keys-1Z6WKrnE.mjs} +1 -1
  81. package/dist/{keys-BQxM4c_a.mjs.map → keys-1Z6WKrnE.mjs.map} +1 -1
  82. package/dist/{libsql-DuGR904j.mjs → libsql-DJRsCDT_.mjs} +2 -2
  83. package/dist/{libsql-DuGR904j.mjs.map → libsql-DJRsCDT_.mjs.map} +1 -1
  84. package/dist/libsql.d.mts +1 -1
  85. package/dist/libsql.mjs +1 -1
  86. package/dist/{memory-G4cSuc6A.mjs → memory-gjKMy3Ql.mjs} +2 -2
  87. package/dist/{memory-G4cSuc6A.mjs.map → memory-gjKMy3Ql.mjs.map} +1 -1
  88. package/dist/methods-part-DoTrY6b9.mjs +2 -0
  89. package/dist/methods-part-DoTrY6b9.mjs.map +1 -0
  90. package/dist/migrations/mysql.d.mts +4 -4
  91. package/dist/migrations/mysql.mjs +1 -1
  92. package/dist/migrations/postgres.d.mts +4 -4
  93. package/dist/migrations/postgres.mjs +1 -1
  94. package/dist/migrations/snowflake.d.mts +4 -4
  95. package/dist/migrations/snowflake.mjs +1 -1
  96. package/dist/migrations/sqlite.d.mts +4 -4
  97. package/dist/migrations/sqlite.mjs +1 -1
  98. package/dist/migrations/storage/durable-object.mjs +1 -1
  99. package/dist/migrations/storage/r2.mjs +1 -1
  100. package/dist/migrations/surrealdb.d.mts +4 -4
  101. package/dist/migrations/surrealdb.mjs +1 -1
  102. package/dist/migrations/tenant.d.mts +2 -2
  103. package/dist/migrations/tenant.mjs +1 -1
  104. package/dist/migrations.d.mts +4 -4
  105. package/dist/migrations.mjs +1 -1
  106. package/dist/{mysql-BNXWfTOo.mjs → mysql-BH0Z3PlH.mjs} +2 -2
  107. package/dist/{mysql-BNXWfTOo.mjs.map → mysql-BH0Z3PlH.mjs.map} +1 -1
  108. package/dist/mysql-adapter-B06Ve3ds.mjs +2 -0
  109. package/dist/mysql-adapter-B06Ve3ds.mjs.map +1 -0
  110. package/dist/mysql2.d.mts +1 -1
  111. package/dist/mysql2.mjs +1 -1
  112. package/dist/named-statements-Bdz2GD5R.d.mts +13 -0
  113. package/dist/named-statements-CMj1QEyw.mjs +2 -0
  114. package/dist/named-statements-CMj1QEyw.mjs.map +1 -0
  115. package/dist/{native-types-DgjMUikz.mjs → native-types-DspZ0Z5E.mjs} +2 -2
  116. package/dist/{native-types-DgjMUikz.mjs.map → native-types-DspZ0Z5E.mjs.map} +1 -1
  117. package/dist/neon-http.d.mts +1 -1
  118. package/dist/neon-http.mjs +1 -1
  119. package/dist/{object-store-B_YMoW8u.d.mts → object-store-D5x-Yf7w.d.mts} +3 -3
  120. package/dist/{object-store-DS0F0yZX.mjs → object-store-WIE0DGGG.mjs} +1 -1
  121. package/dist/{object-store-DS0F0yZX.mjs.map → object-store-WIE0DGGG.mjs.map} +1 -1
  122. package/dist/{on-ylYaKuRu.mjs → on-DvrfHGje.mjs} +2 -2
  123. package/dist/{on-ylYaKuRu.mjs.map → on-DvrfHGje.mjs.map} +1 -1
  124. package/dist/on.d.mts +1 -1
  125. package/dist/on.mjs +1 -1
  126. package/dist/ordering/keys.mjs +1 -1
  127. package/dist/ordering.d.mts +1 -1
  128. package/dist/ordering.mjs +1 -1
  129. package/dist/pending-operation-Dq4rv-Ml.mjs +2 -0
  130. package/dist/pending-operation-Dq4rv-Ml.mjs.map +1 -0
  131. package/dist/permissions.d.mts +1 -1
  132. package/dist/permissions.mjs +1 -1
  133. package/dist/pg.d.mts +27 -1
  134. package/dist/pg.mjs +1 -1
  135. package/dist/pg.mjs.map +1 -1
  136. package/dist/pglite.d.mts +1 -1
  137. package/dist/pglite.mjs +1 -1
  138. package/dist/{physical-CeE2nYmI.mjs → physical-wboFLAg9.mjs} +2 -2
  139. package/dist/{physical-CeE2nYmI.mjs.map → physical-wboFLAg9.mjs.map} +1 -1
  140. package/dist/planetscale.d.mts +1 -1
  141. package/dist/planetscale.mjs +1 -1
  142. package/dist/{planner-DHjdvjwk.d.mts → planner-Ckoxeruk.d.mts} +1 -1
  143. package/dist/{postgres-CDdh5dSP.mjs → postgres-DQ_pO0hi.mjs} +2 -2
  144. package/dist/{postgres-CDdh5dSP.mjs.map → postgres-DQ_pO0hi.mjs.map} +1 -1
  145. package/dist/{postgres-adapter-axapXX8d.mjs → postgres-adapter-Byp7Zpop.mjs} +2 -2
  146. package/dist/{postgres-adapter-axapXX8d.mjs.map → postgres-adapter-Byp7Zpop.mjs.map} +1 -1
  147. package/dist/postgres-adapter-Ia4u0-Ht.mjs +2 -0
  148. package/dist/postgres-adapter-Ia4u0-Ht.mjs.map +1 -0
  149. package/dist/postgres-result-CiS5OWp1.mjs +2 -0
  150. package/dist/postgres-result-CiS5OWp1.mjs.map +1 -0
  151. package/dist/postgres.d.mts +17 -1
  152. package/dist/postgres.mjs +1 -1
  153. package/dist/postgres.mjs.map +1 -1
  154. package/dist/{provider-limits-Ccsb8PTb.mjs → provider-limits-CCOa4d1E.mjs} +2 -2
  155. package/dist/{provider-limits-Ccsb8PTb.mjs.map → provider-limits-CCOa4d1E.mjs.map} +1 -1
  156. package/dist/{provider-parameter-snapshot-BikrgKqI.mjs → provider-parameter-snapshot-C0ehKSAA.mjs} +2 -2
  157. package/dist/{provider-parameter-snapshot-BikrgKqI.mjs.map → provider-parameter-snapshot-C0ehKSAA.mjs.map} +1 -1
  158. package/dist/query-Cdy8E2jM.mjs +2 -0
  159. package/dist/query-Cdy8E2jM.mjs.map +1 -0
  160. package/dist/{query-inspection-BoG-yAln.mjs → query-inspection-C-T2ttRx.mjs} +2 -2
  161. package/dist/{query-inspection-BoG-yAln.mjs.map → query-inspection-C-T2ttRx.mjs.map} +1 -1
  162. package/dist/{raw-Dyq6Y6UX.mjs → raw-uaVIxHcE.mjs} +2 -2
  163. package/dist/{raw-Dyq6Y6UX.mjs.map → raw-uaVIxHcE.mjs.map} +1 -1
  164. package/dist/{relation-bound-ku_cMdye.mjs → relation-bound-BaU-LuuI.mjs} +1 -1
  165. package/dist/{relation-bound-ku_cMdye.mjs.map → relation-bound-BaU-LuuI.mjs.map} +1 -1
  166. package/dist/{rule-words-ZIGm7cDm.mjs → rule-words-C4lXzgW2.mjs} +2 -2
  167. package/dist/{rule-words-ZIGm7cDm.mjs.map → rule-words-C4lXzgW2.mjs.map} +1 -1
  168. package/dist/scalar-B9WizsvR.mjs +4 -0
  169. package/dist/scalar-B9WizsvR.mjs.map +1 -0
  170. package/dist/schema/introspect.d.mts +2 -2
  171. package/dist/schema/introspect.mjs +1 -1
  172. package/dist/schema/json.d.mts +2 -2
  173. package/dist/schema/json.mjs +1 -1
  174. package/dist/{schema-BYA-_bpk.mjs → schema-MB-pPNTO.mjs} +2 -2
  175. package/dist/schema-MB-pPNTO.mjs.map +1 -0
  176. package/dist/{schema-CFIaebgi.mjs → schema-TthAXPVP.mjs} +2 -2
  177. package/dist/{schema-CFIaebgi.mjs.map → schema-TthAXPVP.mjs.map} +1 -1
  178. package/dist/schema-introspection-wMVZowIF.mjs +6 -0
  179. package/dist/schema-introspection-wMVZowIF.mjs.map +1 -0
  180. package/dist/schema.d.mts +1 -1
  181. package/dist/schema.mjs +1 -1
  182. package/dist/select-assembly-SuVxJjps.mjs +2 -0
  183. package/dist/select-assembly-SuVxJjps.mjs.map +1 -0
  184. package/dist/{serializer-rBq3v1xr.mjs → serializer-B2kk7NAR.mjs} +5 -5
  185. package/dist/{serializer-rBq3v1xr.mjs.map → serializer-B2kk7NAR.mjs.map} +1 -1
  186. package/dist/{settled-BjyuA76m.mjs → settled-Dkk5w1vE.mjs} +2 -2
  187. package/dist/{settled-BjyuA76m.mjs.map → settled-Dkk5w1vE.mjs.map} +1 -1
  188. package/dist/{snowflake-UOCC820W.mjs → snowflake-6sBLJi34.mjs} +2 -2
  189. package/dist/{snowflake-UOCC820W.mjs.map → snowflake-6sBLJi34.mjs.map} +1 -1
  190. package/dist/snowflake.d.mts +2 -2
  191. package/dist/snowflake.mjs +1 -1
  192. package/dist/snowflake.mjs.map +1 -1
  193. package/dist/soft-delete.d.mts +1 -1
  194. package/dist/soft-delete.mjs +1 -1
  195. package/dist/{spans-XDUFeTzC.mjs → spans-BE-EjlZK.mjs} +1 -1
  196. package/dist/{spans-XDUFeTzC.mjs.map → spans-BE-EjlZK.mjs.map} +1 -1
  197. package/dist/sql-BGjAsoBE.mjs +2 -0
  198. package/dist/sql-BGjAsoBE.mjs.map +1 -0
  199. package/dist/{sql-Dl6nykFV.mjs → sql-CFxGrk3K.mjs} +2 -2
  200. package/dist/{sql-Dl6nykFV.mjs.map → sql-CFxGrk3K.mjs.map} +1 -1
  201. package/dist/{sql-BVZ8QefY.d.mts → sql-CXtSIPzy.d.mts} +11 -5
  202. package/dist/sql.d.mts +1 -1
  203. package/dist/sql.mjs +1 -1
  204. package/dist/{sqlite-adapter-Ad0d-m2t.mjs → sqlite-adapter-fIbNDvwO.mjs} +2 -2
  205. package/dist/{sqlite-adapter-Ad0d-m2t.mjs.map → sqlite-adapter-fIbNDvwO.mjs.map} +1 -1
  206. package/dist/{sqlite-utils-BRvbmlQ1.mjs → sqlite-utils-DcQct689.mjs} +2 -2
  207. package/dist/{sqlite-utils-BRvbmlQ1.mjs.map → sqlite-utils-DcQct689.mjs.map} +1 -1
  208. package/dist/sqlite3.d.mts +1 -1
  209. package/dist/sqlite3.mjs +1 -1
  210. package/dist/{standard-sql-qLcQyCtK.mjs → standard-sql-Bsf5nrla.mjs} +3 -3
  211. package/dist/standard-sql-Bsf5nrla.mjs.map +1 -0
  212. package/dist/surrealdb.d.mts +2 -2
  213. package/dist/surrealdb.mjs +1 -1
  214. package/dist/surrealdb.mjs.map +1 -1
  215. package/dist/{surrealql-C1dp1sWw.mjs → surrealql-DY7sgVnJ.mjs} +2 -2
  216. package/dist/{surrealql-C1dp1sWw.mjs.map → surrealql-DY7sgVnJ.mjs.map} +1 -1
  217. package/dist/{to-many-BybuKQM1.mjs → to-many-DiP6cOSQ.mjs} +2 -2
  218. package/dist/{to-many-BybuKQM1.mjs.map → to-many-DiP6cOSQ.mjs.map} +1 -1
  219. package/dist/{unit-BhHbZyuJ.mjs → unit-CSaAB0su.mjs} +2 -2
  220. package/dist/{unit-BhHbZyuJ.mjs.map → unit-CSaAB0su.mjs.map} +1 -1
  221. package/dist/{unit-words-CT0yeqfZ.mjs → unit-words-BGMVZ1MX.mjs} +2 -2
  222. package/dist/{unit-words-CT0yeqfZ.mjs.map → unit-words-BGMVZ1MX.mjs.map} +1 -1
  223. package/dist/{utils-CpAojrCj.mjs → utils-BLlgSQIo.mjs} +2 -2
  224. package/dist/{utils-CpAojrCj.mjs.map → utils-BLlgSQIo.mjs.map} +1 -1
  225. package/dist/validation-D0LG854o.mjs +2 -0
  226. package/dist/validation-D0LG854o.mjs.map +1 -0
  227. package/dist/validation.d.mts +1 -1
  228. package/dist/validation.mjs +1 -1
  229. package/dist/{validator-CZLW7aR3.mjs → validator-CDYlO9HV.mjs} +2 -2
  230. package/dist/{validator-CZLW7aR3.mjs.map → validator-CDYlO9HV.mjs.map} +1 -1
  231. package/dist/{values-B4aj1i1f.mjs → values-Byqn5wAh.mjs} +2 -2
  232. package/dist/{values-B4aj1i1f.mjs.map → values-Byqn5wAh.mjs.map} +1 -1
  233. package/dist/version-B_ZLWzLW.mjs +2 -0
  234. package/dist/{version-CXGIA82S.mjs.map → version-B_ZLWzLW.mjs.map} +1 -1
  235. package/package.json +35 -35
  236. package/dist/client-DRpX3-vw.mjs +0 -2
  237. package/dist/client-DRpX3-vw.mjs.map +0 -1
  238. package/dist/error-mapping-B1-IWkCQ.mjs +0 -2
  239. package/dist/error-mapping-B1-IWkCQ.mjs.map +0 -1
  240. package/dist/every-tOgQmaIE.mjs +0 -2
  241. package/dist/execution-context-BXpcbyPe.mjs +0 -2
  242. package/dist/execution-context-BXpcbyPe.mjs.map +0 -1
  243. package/dist/geo-area-codec-mHrM3b9A.mjs +0 -2
  244. package/dist/identifiers-s00pGES8.mjs +0 -2
  245. package/dist/identifiers-s00pGES8.mjs.map +0 -1
  246. package/dist/judge-words-CzUyXtJ6.mjs +0 -2
  247. package/dist/judge-words-CzUyXtJ6.mjs.map +0 -1
  248. package/dist/methods-part-ZY0f2AV_.mjs +0 -2
  249. package/dist/methods-part-ZY0f2AV_.mjs.map +0 -1
  250. package/dist/mysql-adapter-C69j1sKh.mjs +0 -2
  251. package/dist/mysql-adapter-C69j1sKh.mjs.map +0 -1
  252. package/dist/pending-operation-C_eOFOBE.mjs +0 -2
  253. package/dist/pending-operation-C_eOFOBE.mjs.map +0 -1
  254. package/dist/postgres-adapter-Dlr3ZWd7.mjs +0 -2
  255. package/dist/postgres-adapter-Dlr3ZWd7.mjs.map +0 -1
  256. package/dist/postgres-result-DF6DmW3r.mjs +0 -2
  257. package/dist/postgres-result-DF6DmW3r.mjs.map +0 -1
  258. package/dist/query-BZVHfA0s.mjs +0 -2
  259. package/dist/query-BZVHfA0s.mjs.map +0 -1
  260. package/dist/scalar-BHCh7aUz.mjs +0 -4
  261. package/dist/scalar-BHCh7aUz.mjs.map +0 -1
  262. package/dist/schema-BYA-_bpk.mjs.map +0 -1
  263. package/dist/schema-introspection-D0f8cti4.mjs +0 -6
  264. package/dist/schema-introspection-D0f8cti4.mjs.map +0 -1
  265. package/dist/select-assembly-DVI7d3tf.mjs +0 -2
  266. package/dist/select-assembly-DVI7d3tf.mjs.map +0 -1
  267. package/dist/sql-3o4DOKm9.mjs +0 -2
  268. package/dist/sql-3o4DOKm9.mjs.map +0 -1
  269. package/dist/standard-sql-qLcQyCtK.mjs.map +0 -1
  270. package/dist/validation-CYaJ8ndO.mjs +0 -2
  271. package/dist/validation-CYaJ8ndO.mjs.map +0 -1
  272. package/dist/version-CXGIA82S.mjs +0 -2
@@ -1 +0,0 @@
1
- {"version":3,"file":"query-BZVHfA0s.mjs","names":["#keys","#model","#where","AGGREGATE_NAMES","relations","entries","own","own","sql","own","#views","#call","#drops","#instantOf","#leaf","#rooted","#prepareWhere","#scopes","#prepareScalarPredicate","#capturedSet","#prepareExists","#prepareSlotPredicate","#prepareOperatorFilter","#prepareOperand","#prepareOuterOperand","#prepareFieldOperand","entries","#relationPredicate","#relationScope","#prepareCounts","#distanceLeaf","#prepareRelationProjection","#collectionShape","#relationShape","#projectCounts","#projectDistance","#projectVariants","#prepareLinkRow","arms","#compileCollection","#compileScalarValue","#enterJsonContainer","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 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 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 { QueryEngineError } from \"../types\";\n\n/** Normalize groupBy fields and reject duplicate output columns. */\nexport function getGroupByFields(value: unknown): string[] {\n const fields = Array.isArray(value)\n ? value.filter((field): field is string => typeof field === \"string\")\n : typeof value === \"string\"\n ? [value]\n : [];\n const uniqueFields = new Set(fields);\n if (uniqueFields.size !== fields.length) {\n throw new QueryEngineError(\n \"GroupBy operation does not allow duplicate fields in 'by'\"\n );\n }\n return fields;\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_COUNTS_RESULT_KEY,\n} from \"../result-aliases\";\nimport {\n type ExpectedAggregateResultShape,\n type ExpectedPolymorphicResultShape,\n type ExpectedPolymorphicVariantShape,\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 =\n \"Distance select supports only one _distance field 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 // 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 createShape(\n rawKeys,\n relations,\n new Map(),\n relationCounts,\n polymorphic,\n distanceScalar\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 groupedFields = getGroupByFields(getOwnValue(args, \"by\"));\n return buildAggregateShape(args, groupedFields);\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(\n `Decimal field '${field}' has no declared precision and scale, so it has no exact value to bind.`\n );\n return state.decimal;\n}\n\n/** One bound decimal, canonical, or the binder's refusal. */\nexport function canonicalDecimal(value: unknown, field: string): string {\n const canonical = canonicalizeDecimal(value);\n if (canonical === undefined)\n engineFault(\n `Decimal field '${field}' received a value that is not an exact decimal.`\n );\n return canonical;\n}\n\n/** The members of a bound decimal list, in the provider's list spelling. */\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(\n `Decimal list '${field}' received a member that is not an exact decimal.`\n );\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 text\";\n const stored =\n column.representation === \"text\"\n ? \"as its own text\"\n : column.representation === \"uuid\"\n ? \"as a uuid payload\"\n : \"as payload bytes\";\n return `${describeIdDomain(column.domain)}, stored ${stored}`;\n}\n\n/**\n * The comparability of two columns a FIELD REFERENCE puts side by side, or\n * the refusal's sentence when one public value would not have one physical\n * spelling in both.\n *\n * Admission cannot ask it: the interned filter schemas are model-blind and\n * see two strings. Two text columns compare whatever their domains — each\n * holds the whole public string — and two compact columns compare only inside\n * one domain in one storage.\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 (\n `'${ownField}' is ${describeStorage(own)} and '${otherField}' is ` +\n `${describeStorage(other)}. Two columns compare only when one value has the ` +\n \"same physical spelling in both.\"\n );\n}\n","import { assembleAdapterSelect } from \"@adapters/adapter-internals\";\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 { Sql, sql } from \"@sql\";\nimport { projectableScalarNames } 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 { SqlSlot } from \"../../../sql/slot\";\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 EngineSchema,\n entries,\n type Input,\n memo,\n type QueryViews,\n type ReadOperation,\n} from \"./schema\";\nimport {\n bindMembership,\n type Membership,\n type PhysicalField,\n physicalField,\n} from \"./storage\";\nimport {\n engineFault,\n listed,\n nameOf,\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};\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;\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/** 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 | {\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 /**\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 */\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 while (arm.kind === \"and\" && arm.predicates.length === 1)\n arm = arm.predicates[0]!;\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\" }>;\n/** One row a predicate being lowered reads ({@link Queries}' `#frames`). */\nexport interface LoweringFrame {\n readonly alias: string | undefined;\n escaped: boolean;\n joins?: Sql[] | undefined;\n}\n/**\n * The quantifiers one connective merges over the same relation: `EXISTS` is\n * two-valued and `EXISTS (… WHERE A) OR EXISTS (… WHERE B)` holds exactly\n * where some member makes `A` or `B` TRUE, which is `EXISTS (… WHERE (A OR\n * B))`, whatever `A` and `B` answer for a member (NULL included), for an\n * empty set (both false) and for a NULL key (no member). So `some A OR some\n * B` is `some (A OR B)`, `is` likewise, and, negated, `none A AND none B` is\n * `none (A OR B)`, `isNot` likewise. `every` and a body-less `is`/`isNot`\n * (the presence test) are not here.\n */\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 while (arm.kind === \"and\" && arm.predicates.length === 1)\n arm = arm.predicates[0]!;\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 === undefined\n ? right.closure === undefined\n : right.closure !== undefined &&\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 readonly at: number;\n readonly head: RelationPredicate;\n readonly bodies: PreparedPredicate[];\n /** A merged walk's seeds are every arm's: few only where each is. */\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.bodies.push(arm.predicate);\n group.selective &&= arm.closure?.selective === true;\n continue;\n }\n groups.push({\n at: merged.length,\n head: arm,\n bodies: [arm.predicate],\n selective: 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 (value === null || typeof value !== \"object\") return undefined;\n const { lt, lte } = value as { lt?: unknown; lte?: unknown };\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/**\n * A membership the parent claims whose row is gone.\n *\n * The statement answers a claimed arm with a document and an unclaimed one\n * with `null`, so an EMPTY document is the claim without the row. The test is\n * the arm's own selected keys — a shape that requests fields and receives none\n * — and never a private carrier column (Arnaud's D-19).\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 (typeof document !== \"object\" || document === null) return false;\n return (\n Object.keys(document).length === 0 && Object.keys(arm.fields).length > 0\n );\n}\n/**\n * A structured value — a document, a collection, a variant slot, a recursive\n * carrier, or a vector or point scalar — as the provider handed it: a driver\n * that does not parse JSON itself hands back the value's TEXT, which is parsed\n * here once, and any other value is already the parsed structure.\n */\nexport function providerJson(value: unknown): unknown {\n return typeof value === \"string\" ? JSON.parse(value) : value;\n}\n/**\n * The ONE reading of a provider DOCUMENT, whatever carries it: a root row, a\n * relation, `_count` or aggregate carrier, a collection row, a variant slot,\n * its integrity entry and each of its arms, a recursive node row, the\n * recursive carrier and each of its node and edge entries. A document is an\n * object that is not an array, and its members are then read by {@link own}.\n * `null` is answered as itself, because only the placement knows whether its\n * shape permits it; anything else is no document (`undefined`), which the\n * placement refuses in its own registered sentence. The one placement that\n * may be ABSENT is the integrity entry, which a slot without junction\n * memberships does not carry; a present one is refused like any other.\n */\nexport function providerDocument(value: unknown): Input | null | undefined {\n if (value === null) return null;\n return typeof value === \"object\" && !Array.isArray(value)\n ? (value as Input)\n : undefined;\n}\n/**\n * One member of a provider document, read with OWN-key semantics. An omitted\n * field is absent, whatever `Object.prototype` happens to carry under that\n * name.\n */\nexport function own(source: Record<string, unknown>, key: string): unknown {\n return Object.hasOwn(source, key) ? source[key] : undefined;\n}\n/**\n * The ONE cursor-eligibility sentence, raised from the order walker for a key\n * whose lowering would consult a provider capability, and from\n * {@link Queries.page} for every other non-scalar key.\n */\nexport const CURSOR_ORDER_REFUSAL =\n \"Cursor pagination supports direct scalar sort directions only; relation and vector-distance orderBy are not supported.\";\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; `field` marks a direct scalar a cursor can use. */\nexport interface OrderTerm {\n readonly expression: Sql;\n readonly descending: boolean;\n /**\n * The placement the caller spelled. Unspelled is not a placement: the bare\n * direction names the provider's own default, and only a windowed read —\n * whose cursor predicate must read the same total order — states one.\n */\n readonly nulls?: \"first\" | \"last\";\n /**\n * Set when `nulls` belongs to the expression instead of to the caller: a\n * reversed window flips the caller's placement and leaves this one alone,\n * because the shipped engine reverses the input `sort` only\n * (`operations/find-pagination.ts:131-151`) and `buildDistanceOrder` then\n * re-emits `nullsLast(distance, …)` (`builders/sort-order-builder.ts:36-45`).\n */\n readonly expressionNulls?: true;\n readonly nullable: boolean;\n readonly field?: string;\n}\n/**\n * One page's to-one order joins: the LEFT JOIN each relation path takes, in\n * the order their ON clauses need, keyed by the parent alias and the field so\n * every term on one path reads one joined row.\n */\nexport interface OrderJoins {\n readonly aliases: Map<string, string>;\n readonly joins: Sql[];\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: string): 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 '${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}' would return more than ${this.limit} occurrences of recursive relation '${this.relation}' under one row, its output budget; raise recurse.maxOccurrences, lower recurse.depth or filter the 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 root: \"__rq_root\",\n nodes: \"__rq_nodes\",\n edges: \"__rq_edges\",\n key: \"__rq_key\",\n row: \"__rq_row\",\n parent: \"__rq_parent\",\n child: \"__rq_child\",\n depth: \"__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\",\n \"isNot\",\n \"some\",\n \"every\",\n \"none\",\n]);\nconst FILTER_OPERATORS: ReadonlySet<string> = new Set([\n \"equals\",\n \"not\",\n \"in\",\n \"notIn\",\n \"lt\",\n \"lte\",\n \"gt\",\n \"gte\",\n \"contains\",\n \"startsWith\",\n \"endsWith\",\n \"mode\",\n \"has\",\n \"hasEvery\",\n \"hasSome\",\n \"isEmpty\",\n \"path\",\n \"string_contains\",\n \"string_starts_with\",\n \"string_ends_with\",\n \"array_contains\",\n \"array_starts_with\",\n \"array_ends_with\",\n \"within\",\n \"distance\",\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 (!isOperatorRecord(value)) return false;\n if (state?.type !== \"json\" && state?.type !== \"point\") return true;\n return Object.keys(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\n/** A plain admitted record, as opposed to one whole value of an object domain. */\nfunction isOperatorRecord(value: object): boolean {\n const prototype = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null;\n}\n\n/**\n * The ONE answer to \"does this admitted scalar payload name a whole value?\",\n * boxed so `undefined` can mean \"it names an operator instead\".\n *\n * An admitted operator record owns its keys; a `Uint8Array`, `Decimal` or\n * `Date` inherits methods with the same names and is one whole value in EVERY\n * domain, as is a `Sql` fragment. Both consumers read this one answer —\n * {@link Queries.updateValue}'s payload interpreter, which needs to know when\n * the payload is NOT whole, and `commands/assignments.ts`'s symbolic final\n * field, which only needs the value — so the two can never disagree about what\n * `set` names.\n */\nexport function wholeValue(\n value: unknown\n): { readonly value: unknown } | undefined {\n if (value instanceof Sql || value === null || typeof value !== \"object\")\n return { value };\n if (!isOperatorRecord(value)) return { value };\n return Object.hasOwn(value, \"set\")\n ? { value: (value as Input).set }\n : undefined;\n}\n\n/**\n * The ONE interpreter of an admitted scalar update payload.\n *\n * It answers WHICH operator the caller spelled and WHAT its operand is, and\n * nothing about SQL. Two lowerings consume that one answer — the provider's\n * own `SET` assignment ({@link Queries.updateAssignment}) and the same\n * operator named over an already-known value ({@link Queries.updateValue}) —\n * so an operator can never be admitted in one spelling and refused in the\n * other.\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 (Object.hasOwn(operation, operator))\n return { kind: \"arithmetic\", operator, by: operation[operator] };\n for (const operator of LIST_UPDATES)\n if (Object.hasOwn(operation, operator)) {\n const members = operation[operator];\n return {\n kind: \"list\",\n operator,\n members: Array.isArray(members) ? members : [members],\n };\n }\n // The shipped engine's own last word on an admitted payload that names no\n // operator (`builders/set-builder.ts:217-219`), identity included: the one\n // reachable shape is an empty record, and it is refused here, before any\n // statement of the update is built.\n engineFault(`Unknown update operation: ${Object.keys(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 scalar the\n * default projection's one owner (`projectableScalarNames`) keeps.\n */\nfunction defaultSelection(model: AnyModel): Record<string, true> {\n const selection: Record<string, true> = {};\n for (const field of projectableScalarNames(model)) selection[field] = true;\n return selection;\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 = Object.keys(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\n/**\n * One relation filter body a statement lowers ({@link Queries.relationExists}):\n * its key set's name and query, and each place it was lowered at, with the\n * two texts that place settles to.\n */\nexport interface SharedBody {\n readonly name: string;\n readonly query: Sql;\n /**\n * Read once per outer row through its key columns (a relation body), not\n * once per statement (an `$exists` body): where it reads no other shared\n * body, the adapter keeps such a member inlined where a repeated member\n * would otherwise be materialized.\n */\n readonly correlated: boolean;\n /**\n * A walk's reaching set ({@link Queries.sharedWalk}): two terms, computed\n * once by every database, so it states no form.\n */\n readonly recursive?: true;\n /**\n * A walk some place states selective ({@link NormalizedRecurrence}): the\n * same walk is the same rows wherever it is read.\n */\n selective?: true;\n readonly slots: {\n readonly slot: SqlSlot;\n readonly inline: Sql;\n readonly use: Sql;\n /** No columns for an `$exists`, which reads no row's. */\n readonly test: SetTest;\n /** A walk's: the relation body it is lowered in, if any. */\n readonly within?: Enclosing;\n }[];\n}\n/**\n * The relation body a walk is lowered in, once the statement knows whether\n * that body is shared (`body`): a selective walk read only inside sets\n * computed over their whole tables is computed as a set too\n * ({@link sharingBodies}).\n */\nexport interface Enclosing {\n body?: SharedBody;\n}\n/**\n * The row columns a placed body's use compares with its key set's `k`\n * columns, in their order, and whether the test holds where they are in the\n * set (`EXISTS`) or where they are not (`NOT EXISTS`).\n */\ninterface SetTest {\n readonly alias: string;\n readonly columns: readonly string[];\n readonly holds: boolean;\n}\n/**\n * A statement's relation bodies, by {@link sharedKey}, in lowering order,\n * and the slots after each alias's `FROM` item where it may join the key\n * sets it is tested against ({@link Queries.sharingBodies}).\n */\nexport interface SharedBodies {\n readonly byKey: Map<string, SharedBody>;\n readonly order: SharedBody[];\n readonly attach: Map<string, SqlSlot[]>;\n /**\n * The statement's root read, where it joins its key sets: its alias, and\n * its projection and `WHERE`, each place of which reads what it joins.\n */\n root?: { readonly alias: string; readonly scope: Sql };\n}\n/** One place a shared body was lowered at ({@link SharedBody}). */\nexport type PlacedBody = SharedBody[\"slots\"][number];\n/** The places one alias tests key sets on the same columns, and the sets. */\nexport interface TestedColumns {\n readonly test: SetTest;\n readonly bodies: SharedBody[];\n readonly placed: [SharedBody, PlacedBody][];\n}\n/**\n * Key sets one member flags for the groups that join it, and the relations\n * joining it saves ({@link Queries.flagging}).\n */\nexport interface FlagPlan {\n readonly sets: readonly SharedBody[];\n readonly groups: readonly TestedColumns[];\n readonly saves: number;\n}\n/** The flag members a statement joins, of those that save relations. */\nexport type FlagChoice = (plans: readonly FlagPlan[]) => readonly FlagPlan[];\n/** A `WITH` member of key sets' flags ({@link Queries.flagging}). */\nexport interface FlagMember {\n readonly name: string;\n readonly query: Sql;\n readonly inlined: boolean;\n}\n/** How a relation filter tests its subquery, and whether that is `EXISTS`. */\nexport interface Quantified {\n readonly of: (query: Sql) => Sql;\n readonly holds: boolean;\n}\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 (Array.isArray(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\",\n \"enum\",\n \"boolean\",\n \"int\",\n \"bigint\",\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[] = [];\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 sharesBodies: 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.queryViews(adapter);\n this.result = result;\n this.domain = domain;\n this.#call = call;\n this.sharesBodies =\n adapter.capabilities.sharesRelationBodies === true &&\n !resemblesAlias(adapter.namespace ?? \"\") &&\n !hasAliasLikeNames(schema);\n }\n /**\n * The order the call's extensions give `model`'s reads when the caller\n * states none (the `order` capability), else `undefined`.\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 /**\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 private fieldReader(type: string): FieldReader {\n const adapter = this.adapter.result;\n const adapterLeg = (input: unknown): unknown =>\n adapter.parseField(input, type, (transformed?: unknown) =>\n transformed === undefined ? input : transformed\n );\n const driverParse = this.result?.parseField;\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 scalar decoding failed\");\n }\n };\n }\n /**\n * ONE operation's raw result, through the same provider chain at the RESULT\n * boundary that {@link fieldReader} walks at the row-value boundary: the\n * driver first (it owns what its own TRANSPORT answers for a verb), then the\n * adapter (it owns what its DIALECT answers for one), then the engine's\n * decoder, which is the caller of this function and the one authority on what\n * a `count`/`exist` answer means: it asks for `_count` and reads `_count`\n * back. Neither provider leg says anything today: Arnaud's D-35 deleted the\n * SQLite drivers' count/exists arm and his D-40 the two adapter legs (MySQL's\n * count-column normalisation, PostgreSQL's bigint conversion), all three\n * measured answering `undefined` on every live operation of both routes.\n *\n * The other half of D-17 (Arnaud's D-28): `DriverResultParser.parseResult` is\n * a public driver contract — a driver may wrap the raw result of an operation\n * ONCE, before decoding — and it reached nothing after the result engine was\n * retired. Asked here, it is asked once per OPERATION, never per statement\n * and never per member, and the same way for live and prepared execution\n * (rule 7).\n */\n decodeResult(\n raw: Input[],\n operation: Operation,\n decode: (rows: Input[]) => Input[]\n ): Input[] {\n const adapterDecode = (input: unknown): unknown =>\n this.adapter.result.parseResult(\n input,\n operation,\n (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, (input: unknown) => adapterDecode(input))\n : adapterDecode(raw)\n ) as Input[];\n }\n columnName(model: AnyModel, field: string): string {\n return this.physical(model, field).name;\n }\n /** The declared native form of a column; a list's members live in its container. */\n protected nativeType(scalar: Scalar): NativeTypeDeclaration | undefined {\n return scalar[\"~\"].state.array === true\n ? undefined\n : scalar[\"~\"].nativeType;\n }\n /**\n * One field's decoded leaf, resolved once per (adapter, model, field).\n *\n * The answer is the field's declared scalar, its nullability and the\n * adapter's representation of it — schema and dialect only — so rebuilding a\n * fresh object (and a fresh enum `Set`) on every projection of every\n * operation was pure repetition (rule 1). Nothing consumes a leaf by\n * identity: the decoder, the result codec and the shape readers all read its\n * fields.\n */\n protected scalarShape(model: AnyModel, field: string): Leaf {\n let leaves = this.#views.leaves.get(model);\n if (leaves === undefined) {\n leaves = new Map();\n this.#views.leaves.set(model, leaves);\n }\n let shape = leaves.get(field);\n if (shape === undefined) {\n const physical = this.physical(model, field);\n shape = this.#leaf(\n physical.scalar,\n physical.nullable,\n identifierColumn(\n this.adapter,\n this.schema.index,\n model,\n field,\n physical\n )\n );\n leaves.set(field, shape);\n }\n return shape;\n }\n #leaf(\n scalar: Scalar,\n nullable: boolean,\n id: IdentifierColumn | undefined\n ): Leaf {\n const state = scalar[\"~\"].state;\n return {\n kind: \"scalar\",\n type: state.type,\n nullable,\n scalar,\n list: state.array === true ? true : undefined,\n decimal: state.type === \"decimal\" ? state.decimal : undefined,\n dateTime:\n state.type === \"datetime\"\n ? (this.adapter.result.dateTimeRepresentation?.(\n this.nativeType(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,\n };\n }\n /**\n * Whether {@link updateValue} names this payload over a known prior value:\n * the answer a counter `upsert` folds on (engine-08). Read before the\n * divide-by-zero refusal, which belongs to an assignment that runs.\n */\n namesUpdate(model: AnyModel, field: string, value: unknown): boolean {\n return this.named(model, field, readUpdate(value));\n }\n /**\n * A list operator, and an exact decimal's `multiply` or `divide`, have no\n * expression form: the provider's assignment decides the stored result.\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.physical(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 = Object.keys(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 {\n readonly model: AnyModel;\n readonly facts: SelectorFacts | undefined;\n readonly sealed?: string;\n }[] = [];\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 Object.entries(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 /** One captured set's rows, as the disjunction of their own identities. */\n #capturedSet(\n model: AnyModel,\n identities: readonly Input[],\n facts: SelectorFacts,\n taken = true\n ): PreparedPredicate {\n const keys = getModelKeyCatalog(model).rowKey?.fields;\n const field = keys?.length === 1 ? keys[0] : undefined;\n if (\n field &&\n identities.length > 0 &&\n identities.every(\n (identity) =>\n Object.keys(identity).length === 1 && Object.hasOwn(identity, field)\n )\n )\n return this.#prepareScalarPredicate(\n model,\n field,\n { in: identities.map((identity) => identity[field]) },\n facts\n );\n // A set pins no equality, and the rows left out (`taken` false) none\n // either: only one row taken holds what names it.\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 combinator(\n model: AnyModel,\n key: string\n ): 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 /**\n * The one logical-combinator owner, shared by `where` and `having`. An arm\n * that builds no condition is absent: it contributes nothing to `AND`,\n * nothing to `NOT` and nothing to `OR`, and only `OR` turns \"no surviving\n * arm\" into a condition — the vacuous FALSE.\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 Object.entries(where).map(([field, operand]) => {\n if (this.combinator(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.schema.schema[existence.model]!;\n const nestedFacts = facts && apart(facts);\n // One body below the row that holds it, joined to nothing: a\n // `{ $row, up }` inside it may read that row (or one above), and then it\n // is correlated; else it is the same wherever the statement holds it.\n const scopes = this.#scopes;\n this.#scopes = [...scopes, { model, facts: 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 /** One prepared scalar: the field and its memoised physical view. */\n protected scalar(model: AnyModel, field: string): PreparedScalar {\n return {\n model,\n field,\n physical: this.physical(model, field),\n };\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.scalar(model, field);\n if (facts) {\n facts.fields.add(field);\n const filter =\n value !== null &&\n typeof value === \"object\" &&\n !(value instanceof Sql) &&\n !(value instanceof Parameter) &&\n !isFieldRef(value)\n ? (value as Input)\n : undefined;\n const hasEquality =\n filter === undefined ||\n (Object.keys(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 // A call's value (K2) is an equality whose value preparation does not\n // know: it pins nothing, and leaves the selector a conjunction of\n // equalities, so its literal ones still prove a write disjoint (N1).\n }\n return this.prepareOperations(\n key ? { kind: \"column\", scalar, key: true } : { kind: \"column\", scalar },\n value,\n false,\n positive\n );\n }\n /**\n * One operator vocabulary over one target. A column, a JSON value inside it\n * and an aggregate over it are the same grammar, so `where` and `having`\n * cannot admit different operators or bind an operand two ways.\n */\n protected prepareOperations(\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 value === null ||\n value instanceof Sql ||\n isFieldRef(value) ||\n typeof value !== \"object\" ||\n jsonNullKindOf(value) !== undefined ||\n (state?.array === true && Array.isArray(value)) ||\n !addressesOperators(state, value as Input);\n if (shorthand)\n return this.prepareOperation(\n target,\n \"equals\",\n value,\n insensitive,\n positive\n );\n return this.#prepareOperatorFilter(target, value, insensitive, positive);\n }\n /** An operator object (`{ gt: 1, not: … }`), out of line from the shorthand. */\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 // D-22. A JSON filter's own `mode` wins in BOTH directions — a declared\n // `default` really does restore exact matching on that arm — while a\n // scalar filter's `mode` may only UPGRADE to insensitive. That asymmetry\n // is the shipped pair of rules (`json-filter-builder.ts:31-45` against\n // `where-builder.ts`), and it is a fact about the TARGET KIND, resolved\n // here in the one operand owner rather than by a second walker.\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\" && Array.isArray(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 Object.keys(filter)) {\n if (name === \"mode\" || name === \"path\") continue;\n const operand = filter[name];\n if (name === \"equals\") {\n predicates.push(\n this.prepareOperations(scoped, operand, folded, positive)\n );\n } else if (name === \"not\") {\n predicates.push({\n kind: \"not\",\n predicate: this.prepareOperations(scoped, operand, folded, !positive),\n });\n } else {\n predicates.push(\n this.prepareOperation(scoped, name, operand, folded, positive)\n );\n }\n }\n return conjunction(predicates);\n }\n /** One admitted operator, with its operand resolved once. */\n private prepareOperation(\n target: PreparedTarget,\n operator: string,\n value: unknown,\n insensitive: boolean,\n positive = true\n ): PreparedPredicate {\n const owner = target.scalar;\n switch (operator) {\n case \"in\":\n case \"notIn\":\n return {\n kind: \"operation\",\n operator,\n target,\n operands:\n value instanceof Parameter\n ? [\n {\n kind: \"parameter\" as const,\n parameter: value,\n spread: true as const,\n },\n ]\n : (value as unknown[]).map((member) =>\n owner\n ? this.#prepareOperand(owner, member)\n : { kind: \"value\" as const, value: member }\n ),\n insensitive,\n };\n case \"equals\":\n case \"lt\":\n case \"lte\":\n case \"gt\":\n case \"gte\":\n case \"contains\":\n case \"startsWith\":\n case \"endsWith\":\n return {\n kind: \"operation\",\n operator,\n target,\n operand: owner\n ? this.#prepareOperand(owner, value)\n : ({ kind: \"value\", value } satisfies PreparedOperand),\n value,\n insensitive,\n };\n default:\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\n ? { probe: true as const }\n : {}),\n };\n }\n }\n /**\n * One admitted filter member, resolved to the value it binds or the column it\n * names. A plain box per member: what is prepared is read-only by its type,\n * and nothing freezes it (a freeze per member of one `id: { in: ids₁₀₀ }`\n * measured 1.98–2.20 µs against 0.25–0.28 µs,\n * `g4/perf2/receipts/micro-in-list.json`).\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(\n `Field reference '${formatFieldRef(value)}' is not supported in a JSON filter operand.`\n );\n return this.#prepareFieldOperand(owner, value);\n }\n if (!(value instanceof Sql)) return { kind: \"value\", value };\n // Peeked, not flattened: the fragment keeps the nodes it is composed of\n // (a `RowsOf` its lowering settles).\n const flat = Sql.peek(value);\n const operands = flat.values.map((member) => {\n if (isFieldRef(member)) return this.#prepareFieldOperand(owner, member);\n // A token is executable only in a flat interpolation slot. An object\n // parameter stays data; never turn a hidden token into provider data.\n const pending = [member];\n const seen = new WeakSet<object>();\n for (const nested of pending) {\n if (isFieldRef(nested))\n unsupported(\n \"An SQL filter field reference must be a direct interpolation, not nested inside a parameter object.\"\n );\n if (nested instanceof OuterColumn)\n unsupported(\n \"An enclosing row's column ({ $row, up }) is compared directly, never inside an SQL filter.\"\n );\n if (nested === null || typeof nested !== \"object\" || seen.has(nested))\n continue;\n seen.add(nested);\n for (const descriptor of Object.values(\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 /** A field-reference operand, out of line: most operands are values. */\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 if (payload.model !== scope)\n unsupported(\n `Field reference '${formatFieldRef(value)}' cannot be used while filtering '${scope}': a field reference may only compare columns of the same model.`\n );\n if (payload.list)\n unsupported(\n `Field reference '${formatFieldRef(value)}' is a list field and cannot be used as a scalar SQL operand.`\n );\n const referenced = scalarsOf(model)[payload.field];\n if (!referenced)\n unsupported(\n `Field reference '${formatFieldRef(value)}' does not name a scalar field of '${scope}'.`\n );\n const own = exactDecimalDomain(owner.physical.state);\n const other = exactDecimalDomain(referenced[\"~\"].state);\n if (own && other && !sameDecimalDomain(own, other))\n unsupported(\n `Field reference '${payload.field}' cannot be compared with '${owner.field}' on '${scope}': '${owner.field}' is decimal(${own.precision},${own.scale}) and '${payload.field}' is decimal(${other.precision},${other.scale}). Two decimals compare exactly only when they declare the same precision and scale.`\n );\n const storage = incomparableIdentifiers(\n this.scalarShape(model, owner.field).id,\n this.scalarShape(model, payload.field).id,\n owner.field,\n payload.field\n );\n if (storage !== undefined)\n unsupported(\n `Field reference '${payload.field}' cannot be compared with '${owner.field}' on '${scope}': ${storage}`\n );\n return {\n kind: \"field\",\n scalar: this.scalar(model, payload.field),\n };\n }\n /**\n * `{ $row, up }`: the column of the row `up` relation bodies above, which\n * that row's scope reads, compared like a field reference. Refused when it\n * leaves the predicate (or an `$exists` body), crosses a recursive or\n * polymorphic relation, or names what a comparison cannot read.\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} reaches past the predicate it is written in: it is ${Math.max(scopes.length - 1, 0)} relation bodies deep.`\n );\n for (let index = at + 1; index < scopes.length; index++)\n if (scopes[index]!.sealed !== undefined)\n unsupported(\n `${spelled} crosses a ${scopes[index]!.sealed} relation: an enclosing row is read only through plain relations.`\n );\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)\n unsupported(`${spelled} does not name a scalar field of '${name}'.`);\n const other = referenced[\"~\"].state;\n const kinds = new Set([own.type, other.type]);\n if (\n own.array === true ||\n other.array === true ||\n own.type === \"json\" ||\n !(\n own.type === other.type ||\n (kinds.size === 2 && kinds.has(\"string\") && kinds.has(\"enum\"))\n )\n )\n unsupported(\n `${spelled} names '${name}.${value.$row}' (${other.array === true ? `${other.type}[]` : other.type}), which cannot be compared with '${owner.field}' (${own.array === true ? `${own.type}[]` : own.type}).`\n );\n const ownDomain = exactDecimalDomain(own);\n const otherDomain = exactDecimalDomain(other);\n if (ownDomain && otherDomain && !sameDecimalDomain(ownDomain, otherDomain))\n unsupported(\n `${spelled} names a decimal(${otherDomain.precision},${otherDomain.scale}) and '${owner.field}' is decimal(${ownDomain.precision},${ownDomain.scale}): two decimals compare exactly only when they declare the same precision and scale.`\n );\n const storage = incomparableIdentifiers(\n this.scalarShape(owner.model, owner.field).id,\n this.scalarShape(model, value.$row).id,\n owner.field,\n value.$row\n );\n if (storage !== undefined) unsupported(`${spelled}: ${storage}`);\n // The row that holds the column reads it: a write to it reorders.\n facts?.fields.add(value.$row);\n return {\n kind: \"field\",\n scalar: this.scalar(model, value.$row),\n ...(value.up > 0 && { up: value.up }),\n };\n }\n /** One relation slot: ordinary quantifiers, to-one shorthand, or tagged arms. */\n #prepareSlotPredicate(\n model: AnyModel,\n name: string,\n operand: unknown,\n facts: SelectorFacts | undefined,\n positive = true\n ): PreparedPredicate {\n const resolved = this.schema.index.get(model)!.get(name)!;\n const entries = operand as Input;\n if (\n resolved.member ||\n (resolved.edge.kind !== \"variantRowCarrier\" &&\n resolved.edge.kind !== \"variantJunctionCarrier\")\n ) {\n const edge = bindMembership(this.schema, model, name);\n // A spelled `recurse` IS the closure form (the validation dispatcher's\n // one rule), admitted densely: its unspelled arms are `undefined` holes.\n // The assertion names the admitted shape, as `Arguments.recurse` does.\n const recurrence = entries.recurse as NormalizedRecurrence | undefined;\n const closure: Closure | undefined =\n recurrence === undefined\n ? undefined\n : {\n depth: recurrence.depth,\n self: entries.self === true,\n ...(recurrence.selective && { selective: true as const }),\n };\n const arms: [string, unknown][] = closure\n ? Object.entries(entries).filter(\n ([key, value]) => QUANTIFIERS.has(key) && value !== undefined\n )\n : Object.keys(entries).every((key) => QUANTIFIERS.has(key))\n ? Object.entries(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 = resolved.edge.members;\n const many = resolved.edge.kind === \"variantJunctionCarrier\";\n const variantEdge = (variant: unknown) =>\n bindMembership(this.schema, model, name, variant as string);\n if (\n resolved.edge.kind === \"variantRowCarrier\" &&\n entries.type === undefined\n ) {\n const absent = \"is\" in entries;\n // Presence names the stored pair, independently of target-row existence.\n const fields = [\n resolved.edge.storage.typeColumn.name,\n resolved.edge.storage.idColumn.name,\n ];\n return conjunction(\n fields.map((field) =>\n this.#prepareScalarPredicate(\n model,\n field,\n absent ? null : { not: null },\n facts\n )\n )\n );\n }\n const arms: [string | undefined, Input][] = many\n ? Object.entries(entries).map(([quantifier, tagged]) => [\n quantifier,\n tagged as Input,\n ])\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 as Input) : (tagged.is as Input | undefined),\n facts,\n inexact,\n positive,\n undefined,\n \"polymorphic\"\n );\n if (quantifier !== undefined) {\n const quantified = {\n kind: \"relation\" as const,\n edge,\n quantifier,\n predicate:\n negated && inner\n ? { kind: \"not\" as const, predicate: inner }\n : inner,\n };\n // `some` and `none` address the tagged arm and nothing else.\n // `every` is a statement about the WHOLE collection — \"every member\n // is an arm-`T` member satisfying P\" — so a member of any OTHER arm\n // falsifies it. That is the one tagged quantifier that must also\n // state the arms it did not name; the shipped engine answers a\n // board holding two posts and one tag `false` for\n // `every: { type: \"post\", … }`, and this is why.\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 // A tagged to-one arm: `{ type }` asks only that the slot holds that\n // variant; `is`/`isNot` keep the ordinary to-one quantifier meaning.\n return {\n kind: \"relation\",\n edge,\n quantifier: \"some\",\n predicate:\n negated && inner ? { kind: \"not\", predicate: inner } : inner,\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.prepareSelector(\n (edge as Extract<Membership, { kind: \"junction\" }>).declared!.model,\n linkWhere,\n false,\n false\n ).predicate,\n linkFields: Object.keys(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 = [\n ...scopes,\n { model: edge.target, facts: nestedFacts, ...(sealed && { sealed }) },\n ];\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 told(\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.scalarShape(model, field);\n return leaf.list || leaf.id || !SPELLED_ONCE.has(leaf.type)\n ? undefined\n : false;\n }\n /** A field of a model as it is stored. */\n physical(model: AnyModel, field: string): PhysicalField {\n return this.schema.physicalField(model, field);\n }\n /**\n * The model's key order: a bare scalar id, else the row key's fields in\n * declaration order. A windowed read's tie-break, and the order a limited\n * write takes its rows in ({@link capped}, {@link through}).\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)\n engineFault(\n \"Paginated scalar ordering requires a primary model identifier.\"\n );\n const fields = new Set<string>(rowKey.fields);\n return Object.keys(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 /**\n * A widened `_sum` the provider's own `SUM` would overflow travels as two\n * parts no realistic row count overflows, joined before the field's decoder\n * reads it (engine-10): a number on every dialect, an int64 — an int, a\n * bigint or SQLite's decimal coefficient — where the adapter states\n * `integerSum`.\n */\n protected splitSum(leaf: Leaf): SplitSum | undefined {\n if (!leaf.widened) return undefined;\n const { numberSum, integerSum } = this.adapter.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 /** What a read-back owes its write: every row it names, or the write's refusal. */\n protected seriesExpectation(\n model: AnyModel,\n count: number,\n operation: \"createMany\" | \"updateMany\"\n ): NonNullable<Query[\"expectedRows\"]> {\n return {\n count,\n missing:\n operation === \"createMany\"\n ? new QueryEngineError(\n \"createMany with 'select' could not read back one of the created rows at the primary key it reported. A later row in the same call moved that row's primary key; use the '{ count }' form, or write those rows in separate calls.\"\n )\n : new TransactionError(\n \"updateMany with 'select' could not read back one of the updated rows at its final primary key.\",\n {\n meta: {\n model: nameOf(model) ?? \"unknown\",\n operation: \"updateMany\",\n },\n }\n ),\n };\n }\n /** The `_count` member of a projection, out of line: most reads have none. */\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 // An empty count SELECTION contributes no field at all: the shipped\n // engine pushed the `_count` pair only `if (relationCountPairs.length\n // > 0)` (`select-builder.ts:418`), so `_count: true` on a model with\n // no to-many relation publishes no `_count` key rather than `{}`.\n if (counts.length === 0) return;\n fields[name] = {\n kind: \"object\",\n // A count carrier is a document the statement always builds: a\n // provider that answers `null` here has not answered the question,\n // and an object shape that carried no nullability let that `null`\n // reach a caller whose type says `{ children: number }`.\n nullable: false,\n fields: Object.fromEntries(\n counts.map((count) => [count.relation, COUNT_LEAF])\n ),\n };\n prepared.push({ kind: \"counts\", name, counts });\n }\n /** A selected `_distance`, out of line: most reads select none. */\n #projectDistance(\n model: AnyModel,\n name: string,\n distance: unknown,\n distanceSelected: boolean,\n fields: Record<string, Shape | Leaf>,\n prepared: PreparedProjectionField[]\n ): void {\n if (distanceSelected) engineFault(DISTANCE_SELECTED_TWICE);\n // The output key `_distance` is the distance's alone: schema\n // validation refuses a member of that name (F010).\n prepared.push({\n kind: \"distance\",\n name: DISTANCE_FIELD,\n field: name,\n specification: distance as Input,\n });\n fields[DISTANCE_FIELD] = this.#distanceLeaf(model, name, distance as Input);\n }\n /** A polymorphic slot's projection, out of line: most reads have none. */\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 // The caller dispatched on a variant carrier; the closure below loses that.\n const edge = resolved.edge as ResolvedVariantEdge;\n const many = edge.kind === \"variantJunctionCarrier\";\n // A junction-carried slot's arm is a collection of its rows; a row\n // carrier's arm is the target's document.\n const collections: Record<string, CollectionShape> = {};\n const documents: Record<string, Shape> = {};\n const preparedArms: ({\n readonly variant: string;\n } & PreparedRelationProjection)[] = [];\n // The integrity probe's subjects: every configured member of a\n // junction-carried slot, each of which binds a junction membership (an\n // invariant of this one construction site, not a refusal: N4). A ROW\n // carrier states its own claim on the parent row, which the arm document\n // already answers (D-19).\n const memberships = many\n ? edge.members.map((member) => ({\n variant: member.variant,\n edge: bindMembership(\n this.schema,\n model,\n name,\n member.variant\n ) as Extract<Membership, { kind: \"junction\" }>,\n }))\n : [];\n // Which arms are read, and with which node, is `selectedArm`'s one\n // rule, shared with the schema-only result shape.\n for (const member of edge.members) {\n const arm = selectedArm(selection, many, member.variant);\n if (arm === undefined) continue;\n const nested = this.#prepareRelationProjection(\n bindMembership(this.schema, model, name, member.variant),\n arm,\n `${path}${many ? \"variants.\" : \"\"}${member.variant}.`\n );\n if (many) collections[member.variant] = this.#collectionShape(nested);\n else documents[member.variant] = this.#relationShape(nested);\n preparedArms.push({ variant: member.variant, ...nested });\n }\n fields[name] = many\n ? {\n kind: \"variants\",\n relation: name,\n many,\n arms: collections,\n }\n : {\n kind: \"variants\",\n relation: name,\n many,\n arms: documents,\n };\n prepared.push({\n kind: \"variants\",\n name,\n many,\n arms: preparedArms,\n memberships,\n });\n }\n /**\n * One immutable alias-free projection description and decoder shape.\n *\n * An operation that names NEITHER `select` NOR `include` asks for the model's\n * DEFAULT projection, which is a fact of the model and the dialect and of\n * nothing else, so it is resolved once per (adapter, model) and shared\n * ({@link QueryViews}). Every other operation prepares per operation exactly\n * as before, reusing only the per-field leaves.\n */\n /**\n * `internal` names a projection the engine reads for itself (a stored row,\n * an identity): it carries no declared key and no gate, whatever the domain\n * declares (K5); every projection a caller's result reads is not internal.\n */\n prepareProjection(\n model: AnyModel,\n args: Partial<Arguments>,\n internal = false,\n path = \"\"\n ): PreparedProjection {\n // What the domain's declared keys and read gates add (K5).\n const added = internal\n ? undefined\n : this.domain?.project?.preparing(model, args.select, path);\n const shared = args.select === undefined && 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 // `omit` is desugared into `select` at admission; an explicit selection and\n // an include can therefore both be present and both belong to the result.\n let selected = args.select ?? defaultSelection(model);\n if (args.include !== undefined) selected = { ...selected, ...args.include };\n const prepared: PreparedProjectionField[] = [];\n const fields: Record<string, Shape | Leaf> = {};\n let distanceSelected = false;\n for (const name of Object.keys(selected)) {\n const selection = selected[name];\n if (!selection) continue;\n // `_count` is the relation-count key and nothing else: schema\n // validation refuses a member of that name (F010).\n if (name === \"_count\") {\n this.#projectCounts(model, name, selection, fields, prepared);\n continue;\n }\n if (!model[\"~\"].state.relations[name]) {\n const distance =\n selection === true ? undefined : (selection as Input)._distance;\n if (distance !== undefined) {\n this.#projectDistance(\n model,\n name,\n distance,\n distanceSelected,\n fields,\n prepared\n );\n distanceSelected = true;\n continue;\n }\n }\n if (added?.key(name, selection, fields, prepared)) continue;\n if (!model[\"~\"].state.relations[name]) {\n prepared.push({ kind: \"scalar\", name });\n fields[name] = this.scalarShape(model, name);\n added?.field(name, prepared);\n continue;\n }\n const resolved = this.schema.index.get(model)!.get(name)!;\n if (\n !resolved.member &&\n (resolved.edge.kind === \"variantRowCarrier\" ||\n resolved.edge.kind === \"variantJunctionCarrier\")\n ) {\n this.#projectVariants(\n model,\n name,\n resolved,\n selection,\n fields,\n prepared,\n `${path}${args.include?.[name] === undefined ? \"select\" : \"include\"}.${name}.`\n );\n continue;\n }\n const nested = this.#prepareRelationProjection(\n bindMembership(this.schema, model, name),\n selection,\n `${path}${args.include?.[name] === undefined ? \"select\" : \"include\"}.${name}.`\n );\n fields[name] = this.#relationShape(nested);\n prepared.push({ kind: \"relation\", name, ...nested });\n }\n // An empty projection is the model's own default — every scalar omitted —\n // and the row still exists, so it carries the sentinel column. A written\n // `select` that projects nothing never arrives: admission refuses it at\n // its path (`requireSelectedField`, validation/model/core/select.ts).\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 /**\n * A to-many node's decoded shape. A negative `take` runs the reversed window\n * exactly as at the root, so the carried array is restored to the caller's\n * logical order by the one decoder that reads this shape.\n */\n #relationShape(nested: PreparedRelationProjection): Shape {\n if (nested.recurrence) {\n const resolved = this.schema.index\n .get(nested.edge.source)!\n .get(nested.edge.name)!;\n return {\n kind: \"recursive\",\n relation: nested.edge.name,\n many: nested.edge.many,\n optional: slotMayBeEmpty(resolved),\n recurrence: nested.recurrence,\n row: nested.projection.shape,\n identity: this.schema\n .keys(nested.edge.target)\n .map((field) => this.scalarShape(nested.edge.target, field)),\n };\n }\n if (!nested.edge.many) return nested.projection.shape;\n return this.#collectionShape(nested);\n }\n /** A to-many relation's rows, in the window its `take` requested. */\n #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 /** A missing point/vector or a zero-norm cosine distance has no number. */\n #distanceLeaf(model: AnyModel, field: string, distance: Input): Leaf {\n const physical = this.physical(model, field);\n return {\n kind: \"scalar\",\n type: \"number\",\n nullable:\n physical.nullable ||\n (physical.state.type === \"vector\" && distance.metric === \"cosine\"),\n };\n }\n /**\n * A node's `$through`, and its arguments without it: the key is the slot's,\n * not a field of the target its projection reads. Admission mounted it only\n * on a slot a declared model holds, so no other slot has anything to take.\n *\n * It RETURNS the junction model's columns, so it is a read of that model,\n * unlike the hop beside it. Whatever a direct read of them would hide on\n * this client refuses the key, before any statement: a row its rules hide\n * or a field a gate masks has no faithful answer in a value the hop already\n * reached (the target row is there; the link it came through is not to be\n * told). `defaultOmit` is presentation, and is settled at the client.\n */\n #prepareLinkRow(edge: Membership, nested: Partial<Arguments>) {\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 { nested: rest };\n const model = edge.declared.model;\n const named = Object.entries((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 nested: rest,\n linkRow: {\n model,\n fields: named,\n shape: {\n kind: \"object\" as const,\n fields: Object.fromEntries(\n named.map((field) => [field, this.scalarShape(model, field)])\n ),\n },\n },\n };\n }\n #prepareRelationProjection(\n edge: Membership,\n selection: unknown,\n path = \"\"\n ): PreparedRelationProjection {\n const { nested: 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 Object.keys(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.prepareSelector(\n (edge as Extract<Membership, { kind: \"junction\" }>).declared!.model,\n linkWhere,\n false,\n false\n ),\n arguments: {\n selector: nested.where\n ? this.prepareSelector(edge.target, nested.where, false, false)\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 /**\n * Admission desugars `_count: true` into `{ select: { relation: … } }`, so\n * the projection owner reads one shape; an entry may filter its target.\n */\n #prepareCounts(\n model: AnyModel,\n selection: unknown\n ): readonly PreparedCount[] {\n const requested = (selection as Input).select as Input;\n const counts: PreparedCount[] = [];\n for (const [relation, configuration] of Object.entries(requested)) {\n if (!configuration) continue;\n const { edges, variants } = this.countedMemberships(model, relation);\n const where =\n configuration === true ? undefined : (configuration as Input).where;\n if (where === undefined) {\n counts.push({ relation, edges });\n continue;\n }\n const filter = where as Input;\n if (!variants) {\n counts.push({\n relation,\n edges,\n selector: this.prepareSelector(\n edges[0]!.target,\n filter,\n false,\n false\n ),\n });\n continue;\n }\n // A TAGGED count filter selects an arm; it is not a scalar predicate\n // over one of them. `type` names the arm — admission makes it mandatory\n // for a polymorphic collection — and `is`/`isNot` are prepared against\n // THAT arm's target, whose columns are the only ones they can address.\n const tag = filter.type;\n const arm = edges.find((edge) => edge.scope.member?.variant === tag);\n if (!arm)\n engineFault(\n `Unknown polymorphic target '${String(tag)}' for relation '${relation}'.`\n );\n const negated = filter.isNot !== undefined;\n const inner = negated ? filter.isNot : filter.is;\n counts.push({\n relation,\n edges: [arm],\n selector:\n inner === undefined\n ? undefined\n : this.prepareSelector(arm.target, inner as Input, false, false),\n ...(negated ? { negated: true as const } : {}),\n });\n }\n return counts;\n }\n /**\n * Every membership one relation SLOT counts.\n *\n * An ordinary relation is one edge. A variant carrier is not: it has no single\n * membership — each arm has its own target and its own correlation — so the\n * slot's population is the union of its arms, and its size is their sum. This\n * is the one place that fact is stated; the `_count` projection and `_count`\n * ordering both read it here.\n */\n countedMemberships(\n model: AnyModel,\n relation: string\n ): {\n readonly edges: readonly Membership[];\n /**\n * Whether those memberships are a carrier's ARMS. The same owner answers\n * it, because it is the same classification: a tagged `_count` filter\n * selects one arm and an ordinary `where` filters one target, and reading\n * \"is this a carrier?\" a second time is how the two got confused.\n */\n readonly variants: boolean;\n } {\n const resolved = this.schema.index.get(model)!.get(relation)!;\n const carrier =\n resolved.member === undefined &&\n (resolved.edge.kind === \"variantRowCarrier\" ||\n resolved.edge.kind === \"variantJunctionCarrier\")\n ? resolved.edge\n : undefined;\n return {\n edges: carrier\n ? carrier.members.map((member) =>\n bindMembership(this.schema, model, relation, member.variant)\n )\n : [bindMembership(this.schema, model, relation)],\n variants: carrier !== undefined,\n };\n }\n /**\n * ONE statement's row-count contract, on the rows that statement answered.\n *\n * It is the one fact a terminal WINDOW owns rather than the operation:\n * {@link Queries.selectSeries} stamps every bind-budget window with its own\n * identity count and its own registered refusal, so a terminal split into\n * windows is decided here, per window, while the window is still known. A\n * total taken over the concatenation would compare a whole terminal with one\n * window's count and could not raise that window's refusal at all\n * (`OperationContext.publishedTerminal`, Arnaud's D-28).\n */\n assertExpectedRows(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(\n \"createMany returned a different number of rows than expected.\"\n );\n }\n /** A write's own read, decoded as the stored row it is (an internal read). */\n decodeQuery(query: Query, rows: Input[]): Input[] {\n this.assertExpectedRows(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 // An empty batch — a filter that matched nothing — reads nothing, so it\n // compiles nothing.\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 private decodeRecursiveCarrier(\n shape: Extract<Shape, { kind: \"recursive\" }>,\n value: unknown,\n readRow: Reader,\n readIdentity: readonly Reader[]\n ): unknown {\n const carrier = providerDocument(providerJson(value));\n if (!carrier)\n refuseResult(\"recursive carrier\", \"the carrier is not an object\");\n const root = own(carrier, RECURSIVE_CARRIER.root);\n const rawNodes = own(carrier, RECURSIVE_CARRIER.nodes);\n const rawEdges = own(carrier, RECURSIVE_CARRIER.edges);\n if (\n !(\n Array.isArray(root) &&\n Array.isArray(rawNodes) &&\n Array.isArray(rawEdges)\n )\n )\n refuseResult(\n \"recursive carrier\",\n \"the carrier's root, nodes or edges member is not an array\"\n );\n\n const identity = (tuple: unknown): string => {\n if (!Array.isArray(tuple) || tuple.length !== shape.identity.length)\n refuseResult(\n \"recursive identity\",\n \"an identity is not a tuple of the key's width\"\n );\n // A counted walk: `entries()` allocated an iterator and a pair per\n // member on every identity — root, node key and both edge endpoints.\n let index = 0;\n for (const read of readIdentity) {\n read(tuple[index]);\n index += 1;\n }\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 = providerDocument(rawNode);\n if (!node)\n refuseResult(\"recursive node\", \"a node entry is not an object\");\n const key = identity(own(node, RECURSIVE_CARRIER.key));\n if (nodes.has(key))\n refuseResult(\n \"duplicate recursive node\",\n \"two nodes carry the same identity\"\n );\n nodes.set(key, own(node, RECURSIVE_CARRIER.row));\n }\n\n type Edge = { readonly child: string; readonly depth?: number };\n const edges = new Map<string, Edge[]>();\n const facts = new Set<string>();\n for (const rawEdge of rawEdges) {\n const edge = providerDocument(rawEdge);\n if (!edge)\n refuseResult(\"recursive edge\", \"an edge entry is not an object\");\n const parent = identity(own(edge, RECURSIVE_CARRIER.parent));\n const child = identity(own(edge, RECURSIVE_CARRIER.child));\n if (!nodes.has(child))\n refuseResult(\n \"recursive edge endpoint\",\n \"an edge's child is not a carried node\"\n );\n const rawDepth = own(edge, RECURSIVE_CARRIER.depth);\n let depth: number | undefined;\n if (shape.recurrence.depth === false) {\n if (rawDepth !== undefined)\n refuseResult(\n \"exhaustive recursive depth\",\n \"an exhaustive carrier states an edge depth\"\n );\n } else {\n if (\n typeof rawDepth !== \"number\" ||\n !Number.isSafeInteger(rawDepth) ||\n rawDepth < 1 ||\n rawDepth > shape.recurrence.depth\n )\n refuseResult(\n \"recursive depth\",\n \"an edge depth is not an integer from 1 to the cutoff\"\n );\n depth = rawDepth;\n }\n const fact = JSON.stringify([parent, child, depth ?? null]);\n if (facts.has(fact))\n refuseResult(\n \"duplicate recursive edge\",\n \"an edge fact is carried twice\"\n );\n facts.add(fact);\n const siblings = edges.get(parent);\n const entry = {\n child,\n ...(depth === undefined ? {} : { depth }),\n };\n if (siblings) siblings.push(entry);\n else edges.set(parent, [entry]);\n }\n\n /**\n * One parent, one answer, taken once over the COMPLETE edge index: the\n * distinct successors it offers, in transported sibling order. Their count\n * is also where singular cardinality is answerable at all, so the parent's\n * endpoint, its cardinality and its successors are decided here — over\n * every transported fact — instead of being rediscovered at each\n * occurrence that happens to unfold this parent.\n */\n const successors = new Map<string, readonly string[]>();\n for (const [parent, entries] of edges) {\n if (parent !== rootKey && !nodes.has(parent))\n refuseResult(\n \"recursive edge endpoint\",\n \"an edge's parent is neither the root nor a carried node\"\n );\n const unique = [...new Set(entries.map((entry) => entry.child))];\n if (!shape.many && unique.length > 1)\n refuseResult(\n \"recursive singular relation\",\n \"a singular parent has several successors\"\n );\n successors.set(parent, unique);\n }\n /**\n * ONE walk over the transported facts, before any of them is unfolded.\n *\n * The root is reached at level 0, and a bounded edge is reachable only one\n * level below its own recorded `__rq_depth` — the only meaning that number\n * has, and the reason the provider transports it. An identity reached by\n * several distinct paths keeps EVERY level it was reached at, so a diamond\n * and a re-entered junction node stay legal; an exhaustive carrier records\n * no level, collapses to the identity alone, and so still terminates on a\n * legal cyclic graph.\n *\n * Three facts fall out of that one walk. A BOUNDED edge no level can\n * consume is a depth attributed to a hop it was not discovered at. A\n * bounded hop below the cutoff whose children at the next level are not\n * the parent's one answer is a hop the provider did not discover: the\n * statement discovers a parent's children at EVERY level it reaches that\n * parent (a filter prunes each hop the same way, and prevention is this\n * decoder's, not the statement's), so unfolding the one answer there would\n * invent an occurrence the carrier never transported. An identity no\n * consumed edge reaches is a node outside this answer. Only a stated depth\n * can be misattributed or missing, so only a bounded carrier is asked the\n * first two questions: on an exhaustive one an unconsumed edge means its\n * parent was never reached, which is the third question's answer.\n */\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…of` re-reads the length each step, so the levels pushed below are\n // walked too, exactly as the indexed loop did.\n for (const [parent, level] of pending) {\n const children = new Set<string>();\n for (const entry of edges.get(parent) ?? []) {\n if (entry.depth !== undefined && entry.depth !== level + 1) continue;\n consumed.add(entry);\n reached.add(entry.child);\n children.add(entry.child);\n const at =\n entry.depth === undefined\n ? entry.child\n : `${entry.depth} ${entry.child}`;\n if (levels.has(at)) continue;\n levels.add(at);\n pending.push([entry.child, level + 1]);\n }\n if (\n shape.recurrence.depth !== false &&\n carriesRepeatedKey(shape.recurrence.depth, level) &&\n children.size !== (successors.get(parent)?.length ?? 0)\n )\n refuseResult(\n \"recursive depth\",\n \"a hop below the cutoff omits some of its parent's children\"\n );\n }\n if (shape.recurrence.depth !== false && consumed.size !== facts.size)\n refuseResult(\n \"recursive depth\",\n \"an edge is not reachable at its recorded depth\"\n );\n if (reached.size !== nodes.size)\n refuseResult(\n \"unreachable recursive node\",\n \"a carried node is not reachable from the root\"\n );\n\n /** A numeric cutoff reached: this occurrence omits the repeated slot. */\n const cutoff = (depth: number) =>\n !carriesRepeatedKey(shape.recurrence.depth, depth);\n /** One slot's successors, collapsed by its cardinality and emptiness. */\n // A singular slot here may be empty: CM002 refuses a required self\n // foreign key.\n const collapse = (rows: Input[]): unknown => {\n if (rows.length > 0) return shape.many ? rows : rows[0]!;\n return shape.many ? [] : null;\n };\n type Frame = {\n readonly key: string;\n readonly depth: number;\n readonly row: Input;\n readonly childKeys: readonly string[];\n readonly childRows: Input[];\n next: number;\n };\n /**\n * ONE active path, seeded by the outer row and kept by enter and leave.\n *\n * Copying the ancestry prefix into every descended occurrence held those\n * identities once per hop and made a chain quadratic in its own depth;\n * the stack already holds them.\n */\n const active = new Set<string>([rootKey]);\n const stack: Frame[] = [];\n /**\n * The one admission EVERY followed edge passes, the first hop included —\n * which is what seeding the path with the root makes possible: a graph\n * edge straight back to the outer row is a revisit like any other, and an\n * FK one is the same refusal at the first hop as at the hundredth.\n */\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 relation '${shape.relation}' contains 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)\n refuseResult(\"recursive row\", \"a node's row is null\");\n const depth = from + 1;\n stack.push({\n key,\n depth,\n row: decoded as Input,\n childKeys: cutoff(depth) ? [] : (successors.get(key) ?? []),\n childRows: [],\n next: 0,\n });\n };\n const rootRows: Input[] = [];\n for (const child of successors.get(rootKey) ?? []) {\n follow(0, child);\n for (\n let current = stack.at(-1);\n current !== undefined;\n current = stack.at(-1)\n ) {\n if (current.next < current.childKeys.length) {\n follow(current.depth, current.childKeys[current.next++]!);\n continue;\n }\n active.delete(current.key);\n stack.pop();\n if (!cutoff(current.depth))\n current.row[shape.relation] = collapse(current.childRows);\n const parent = stack.at(-1);\n if (parent) parent.childRows.push(current.row);\n else rootRows.push(current.row);\n }\n }\n return collapse(rootRows);\n }\n /**\n * The ONE decoder of the projection language, compiled for one decoded\n * batch — a result window, a RETURNING answer, an internal read — and\n * dropped with it. Every invariant decision of a placement is taken here,\n * once: an object's member list and each member's placement, a variant\n * slot's arms, a collection's and a recursive carrier's row reader, a list\n * leaf's container reader ({@link compileList}), and — for a PHYSICAL\n * scalar slot only — this execution's provider continuation\n * ({@link fieldReader}). The returned reader then does only what depends on\n * the provider's value, through the preselected scalar codec\n * ({@link compileScalar}) and the one carrier validator\n * ({@link decodeRecursiveCarrier}).\n *\n * `carried` is a fact of the PLACEMENT, never of the shape: a to-one\n * relation's shape is its target's shared default projection, read as the\n * root row of one statement and inside a JSON document of another. Only a\n * scalar member of a physical row crosses the provider chain; a JSON window\n * already decoded everything under it.\n *\n * The reader holds a driver's parser, so it lives no longer than the batch\n * it was compiled for and is never stored on the prepared shape, which\n * `EngineSchema` shares across executions and driver bindings. A domain's\n * gated document reads its gates with it.\n */\n compileReader(\n shape: Shape | Leaf,\n internal: boolean,\n carried: boolean,\n columns?: readonly string[]\n ): Reader {\n if (shape.kind === \"scalar\") {\n const provider = carried ? undefined : this.fieldReader(shape.type);\n const list = shape.list ? this.compileList(shape, internal) : undefined;\n return this.compileScalar(shape, internal, provider, list);\n }\n if (shape.kind === \"recursive\") {\n const readRow = this.compileReader(shape.row, internal, true);\n // An identity is validated as the stored key it is (an INTERNAL read),\n // never published.\n const readIdentity = shape.identity.map((leaf) =>\n this.compileReader(leaf, true, true)\n );\n return (value) =>\n this.decodeRecursiveCarrier(shape, value, readRow, readIdentity);\n }\n if (shape.kind === \"variants\") {\n const slot = (value: unknown): Input => {\n // The slot is a provider document the statement always builds, read\n // by the one document rule: a NULL or non-object slot is a malformed\n // result, refused at the slot before any arm is asked (Arnaud,\n // 2026-09-25).\n const variants = providerDocument(providerJson(value));\n if (!variants)\n refuseResult(\"polymorphic slot\", \"the slot is not an object\");\n // The integrity probe first, and before any arm: a membership whose\n // row is gone is a fact about the SLOT, so `only` — which selects what\n // is read — cannot make it unobservable (Arnaud's D-26). One refusal,\n // from the decoder arm that already owns the sentence. Its entry is a\n // document of the slot, read by the same rule: a slot with no\n // junction membership carries none, and a PRESENT entry that is no\n // document is the slot's malformed result — never \"no memberships\".\n const evidence = own(variants, POLYMORPHIC_COLLECTION_ORPHANS_KEY);\n if (evidence === undefined) return variants;\n const orphans = providerDocument(evidence);\n if (!orphans)\n refuseResult(\n \"polymorphic slot\",\n \"the integrity entry is not an object\"\n );\n for (const [type, count] of Object.entries(orphans))\n if (Number(count) > 0) {\n if (type === \"$storage\")\n engineFault(\n `Polymorphic relation '${shape.relation}' has an unknown discriminator or incomplete stored pair.`\n );\n engineFault(\n `Polymorphic relation '${shape.relation}' references a missing '${type}' record.`\n );\n }\n return variants;\n };\n // Its arms, compiled once, in `shape.arms` order. A junction-carried\n // slot's arm is a collection, so its reader answers the arm's rows.\n if (shape.many) {\n const arms = Object.keys(shape.arms).map((type) => ({\n type,\n read: this.#compileCollection(shape.arms[type]!, internal),\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 = Object.keys(shape.arms).map((type) => {\n const arm = shape.arms[type]!;\n return { type, arm, read: this.compileReader(arm, internal, true) };\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))\n engineFault(\n `Polymorphic relation '${shape.relation}' references a missing '${type}' record.`\n );\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 // The document's MEMBER LIST is a fact of the PREPARED PROJECTION, stated\n // once by {@link prepareProjection} on the shape; a row carries\n // only the values for it. It is read here, once per batch — the shape's\n // OWN keys, exactly as {@link own} reads the provider's — and never again\n // per row: materialising it per row as pairs (`Object.entries` read back\n // by `Object.fromEntries`) made this decoder allocate 2.5x the shipped\n // engine's bytes per row (`g4/release/p1/note.md`).\n const fields = Object.keys(shape.fields);\n const readers = fields.map((field) => {\n const nested = shape.fields[field]!;\n return this.compileReader(\n nested,\n internal,\n carried || nested.kind !== \"scalar\"\n );\n });\n // An internal read is the engine's own: it reads every member it asked\n // for, its gates unread (K5).\n if (shape.gates && !internal)\n return this.domain!.project!.gatedDocument(\n this,\n carried,\n shape,\n fields,\n readers,\n columns\n );\n if (columns) {\n // Native aliases locate cells once; a statement transform may reorder\n // columns. Last occurrence matches the keyed transport's duplicate names.\n const positions = fields.map((field) => columns.lastIndexOf(field));\n return (value) => {\n if (!Array.isArray(value))\n refuseResult(\"row\", \"a positional row is not an array\");\n const document: Input = {};\n for (let index = 0; index < fields.length; index++) {\n const position = positions[index]!;\n document[fields[index]!] = readers[index]!(\n position < 0 ? undefined : value[position]\n );\n }\n return document;\n };\n }\n return (value) => {\n const source = providerDocument(providerJson(value));\n if (source === null) {\n if (shape.nullable === false)\n refuseResult(\"row\", \"a document the statement always builds is null\");\n return null;\n }\n if (source === undefined)\n refuseResult(\"row\", \"a requested document is not a provider row\");\n // OWN-key semantics ({@link own}): a plain member read on a\n // `JSON.parse` result finds `Object.prototype`'s own members, so a\n // field named `toString` the provider OMITTED would inherit a function\n // instead of failing closed. Nested evidence documents also contain\n // user-named predicates, not just schema identifiers. Their `__proto__`\n // member must be an own data property, never the inherited setter.\n const document: Input = {};\n for (let index = 0; index < fields.length; index++) {\n const field = fields[index]!;\n const decoded = readers[index]!(own(source, field));\n if (field === \"__proto__\")\n Object.defineProperty(document, field, {\n value: decoded,\n enumerable: true,\n configurable: true,\n writable: true,\n });\n else document[field] = decoded;\n }\n return document;\n };\n }\n /**\n * A collection's reader, compiled by {@link compileReader} for a to-many\n * relation and for each arm of a junction-carried variant slot: its rows\n * are carried documents, restored to the requested order.\n */\n #compileCollection(\n shape: CollectionShape,\n internal: boolean\n ): (value: unknown) => unknown[] {\n const readRow = this.compileReader(shape.row, internal, true);\n return (value) => {\n const decoded = providerJson(value);\n if (!Array.isArray(decoded))\n refuseResult(\n \"collection\",\n \"a requested relation is not a provider array\"\n );\n const rows = decoded.map(readRow);\n return shape.reversed ? rows.reverse() : rows;\n };\n }\n /**\n * One strict scalar decode per leaf, through the existing codec owners. A\n * value outside the column's declared domain is a malformed provider row,\n * never a value to coerce. `provider` is the physical value's continuation;\n * a CARRIED value — one a JSON document already holds — has none. `list` is\n * a list leaf's compiled container reader, and a list MEMBER's leaf is no\n * list.\n */\n private compileScalar(\n leaf: Leaf,\n internal: boolean,\n provider?: FieldReader,\n list?: Reader\n ): Reader {\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 ? \"a required list is null\" : \"a required scalar is null\"\n );\n }\n if (raw === undefined) refuseResult(leaf.type, \"the value is absent\");\n return readValue(provider === undefined ? raw : provider(raw));\n };\n const join = this.splitSum(leaf)?.join;\n return join ? (parts) => read(join(parts)) : read;\n }\n /** Bind the declared scalar codec once, preserving its provider-value checks. */\n #compileScalarValue(leaf: Leaf, internal: boolean): Reader {\n const invalid = (why: string) => new InvalidScalarResult(leaf.type, why);\n const identifier = leaf.id;\n if (identifier !== undefined) {\n return (value) => {\n const decoded = decodeIdentifier(identifier, value);\n if (decoded === undefined)\n throw invalid(\n \"the value is not in this column's declared identifier domain\"\n );\n return internal && identifier.representation === \"text\"\n ? value\n : decoded;\n };\n }\n switch (leaf.type) {\n case \"string\":\n return decodeString;\n case \"boolean\":\n return decodeBoolean;\n case \"int\":\n return leaf.widened ? (sum) => decodeInt(sum, true) : decodeInt;\n case \"bigint\":\n return decodeBigint;\n case \"number\":\n // A number sum is already decoded by `joinNumberSum`.\n return leaf.widened ? (sum) => sum : decodeNumber;\n case \"decimal\":\n return (value) => {\n const decoded = decodeDecimalScalar(\n value,\n leaf.decimal!,\n leaf.widened === true,\n internal,\n this.adapter.result\n );\n if (decoded === undefined)\n throw invalid(\n leaf.widened\n ? \"the sum is not an exact decimal at this column's scale\"\n : \"the value is not an exact decimal in this column's declared domain\"\n );\n return decoded;\n };\n case \"datetime\":\n return (value) => {\n if (leaf.dateTime !== undefined && leaf.dateTime !== \"text\") {\n const decoded = decodePhysicalDateTime(value, leaf.dateTime);\n if (decoded === undefined)\n throw invalid(\n \"the value is not this column's declared physical timestamp\"\n );\n return decoded;\n }\n if (value instanceof Date) {\n if (isDateTimeInstant(value.getTime()))\n return new Date(value.getTime());\n throw invalid(\"the Date is outside the public DateTime domain\");\n }\n const parsed =\n typeof value === \"string\"\n ? decodeProviderTimestamp(value)\n : undefined;\n if (!parsed)\n throw invalid(\n \"the value is not a valid provider timestamp in the public DateTime domain\"\n );\n // A TEXT-stored instant's PHYSICAL value is the spelling itself\n // (`encodePhysicalDateTime(iso, \"text\")` is the identity), and this\n // column admits more than one spelling of one instant, so an INTERNAL\n // read keeps the bytes the row holds and a public one materializes the\n // `Date` — the same split the decimal arm above takes through\n // `decodeDecimalScalar`. That is what makes a captured identity\n // address its own row: `Queries.scalarValue` binds this string back\n // unchanged, while a `Date` would be re-spelled by the admission\n // boundary and match a row only where the payload's spelling was that\n // one (FC-02B, which repaired N5 §6's residual).\n return internal ? value : parsed;\n };\n case \"date\":\n return (value) => {\n if (value instanceof Date) {\n const epoch = value.getTime();\n if (\n isDateTimeInstant(epoch) &&\n value.getUTCHours() === 0 &&\n value.getUTCMinutes() === 0 &&\n value.getUTCSeconds() === 0 &&\n value.getUTCMilliseconds() === 0\n )\n return new Date(epoch);\n throw invalid(\"the Date is invalid or not UTC midnight\");\n }\n const match =\n typeof value === \"string\" ? DATE_TEXT.exec(value) : null;\n const parsed = match\n ? decodeProviderTimestamp(\n `${match[1]}-${match[2]}-${match[3]}T00:00:00.000Z${match[4] ? \" BC\" : \"\"}`\n )\n : undefined;\n if (!parsed)\n throw invalid(\"the value is not a valid ISO calendar date\");\n return parsed;\n };\n case \"time\":\n return decodeTime;\n case \"enum\":\n return (value) => {\n if (typeof value === \"string\" && leaf.enumValues?.has(value) === true)\n return value;\n throw invalid(\"the value is not a declared enum member\");\n };\n case \"json\":\n return (value) => this.jsonValue(value);\n case \"blob\":\n return decodeBlob;\n case \"vector\":\n return (value) => {\n const decoded = providerJson(value);\n if (\n !Array.isArray(decoded) ||\n decoded.some(\n (member) => typeof member !== \"number\" || !Number.isFinite(member)\n )\n )\n throw invalid(\"the value is not an array of finite numbers\");\n if (leaf.dimension !== undefined && decoded.length !== leaf.dimension)\n throw invalid(\n `the value does not have the configured dimension ${leaf.dimension}`\n );\n return [...decoded];\n };\n case \"point\":\n return (value) => {\n const decoded = providerJson(value);\n const point = validateGeoPoint(decoded);\n if (point.issues)\n throw invalid(\n point.issues[0]?.message ??\n \"the value is not a canonical GeoPoint\"\n );\n return point.value;\n };\n default:\n return () => {\n throw invalid(\"the scalar type is unsupported\");\n };\n }\n }\n /**\n * A list leaf's container reader, compiled with its placement by\n * {@link compileReader}: the decimal whole-list codec or one container, then\n * each member through the element's own codec. The member's non-null leaf\n * is derived here, once per list placement of a decoded batch, never per\n * returned list. The reader runs after the NULL and absence checks and the\n * provider continuation, and each member is a carried value.\n */\n private compileList(leaf: Leaf, internal: boolean): Reader {\n if (leaf.type === \"decimal\")\n return (value) => {\n const members = decodeDecimalList(\n value,\n leaf.decimal!,\n internal,\n this.adapter.result\n );\n if (members === undefined)\n refuseResult(\n leaf.type,\n \"the value is not an exact decimal list in this column's declared domain\"\n );\n return members;\n };\n const member: Leaf = {\n ...leaf,\n list: undefined,\n nullable: false,\n };\n const readMember = this.compileScalar(member, internal);\n const arrayText =\n this.adapter.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 (!Array.isArray(items))\n refuseResult(leaf.type, \"a list scalar did not return an array\");\n return items.map((item, index) => {\n if (!Object.hasOwn(items, index))\n refuseResult(leaf.type, \"a list scalar returned a sparse array\");\n return readMember(item);\n });\n };\n }\n /**\n * The JSON value domain, normalized once.\n *\n * A provider's JSON is not JavaScript's: SQLite declares a `json` column\n * with NUMERIC affinity, so the bound text `\"42\"` comes back as `42n` and a\n * caller who wrote `42` must read `42` — and a non-finite number, a sparse\n * array or an exotic prototype is a malformed provider value rather than\n * something to publish. (The shipped `scalar-structured-parser.ts:144-200`.)\n *\n * A JavaScript value can also contain ITSELF, which provider text never can:\n * a recursive read's node row arrives as an object, not as text this decoder\n * parsed. That is the same fact as every other one here — the value is not\n * in the JSON domain — so this boundary answers it instead of recursing into\n * a `RangeError`. `enclosing` is the containers this value is being\n * normalized INSIDE, entered before a container's members and left after\n * them, so a document that merely REPEATS one object still normalizes it\n * twice and only a container reached from within itself is refused.\n */\n private jsonValue(value: unknown, enclosing?: object[]): unknown {\n if (\n value === null ||\n typeof value === \"string\" ||\n typeof value === \"boolean\"\n )\n return value;\n if (typeof value === \"number\") {\n if (Number.isFinite(value)) return value;\n refuseResult(\"json\", \"a JSON number is not finite\");\n }\n if (typeof value === \"bigint\") {\n const parsed = Number(value);\n if (Number.isFinite(parsed)) return parsed;\n refuseResult(\n \"json\",\n \"a JSON integer is outside the finite Number domain\"\n );\n }\n if (Array.isArray(value)) {\n const path = this.#enterJsonContainer(value, enclosing);\n const members = new Array<unknown>(value.length);\n for (let index = 0; index < value.length; index += 1) {\n if (!Object.hasOwn(value, index))\n refuseResult(\"json\", \"a JSON array is sparse\");\n members[index] = this.jsonValue(value[index], path);\n }\n path.pop();\n return members;\n }\n if (isPlainJsonRecord(value)) {\n const path = this.#enterJsonContainer(value, enclosing);\n const members: Record<string, unknown> = {};\n for (const key of Object.keys(value)) {\n const member = this.jsonValue(value[key], path);\n // Defined where `Object.prototype` holds the key: assigning\n // `__proto__` would set the prototype, and an inherited property\n // a hardened (frozen) prototype holds would refuse the assignment.\n if (key in Object.prototype)\n Object.defineProperty(members, key, {\n configurable: true,\n enumerable: true,\n value: member,\n writable: true,\n });\n else members[key] = member;\n }\n path.pop();\n return members;\n }\n refuseResult(\"json\", \"the value is outside the JSON value domain\");\n }\n /**\n * The one entry into a JSON container: the containers already being\n * normalized around it, plus this one. A container that is already open is\n * inside itself, which no JSON document is. The path is a stack, as deep\n * as the document's nesting, so a scan of it is cheaper than a set.\n */\n #enterJsonContainer(\n container: object,\n enclosing: object[] | undefined\n ): object[] {\n const path = enclosing ?? [];\n if (path.includes(container))\n refuseResult(\"json\", \"a JSON value contains itself\");\n path.push(container);\n return path;\n }\n}\n\n/** A document, not a class instance: the shipped JSON record test. */\nfunction isPlainJsonRecord(value: unknown): value is Record<string, unknown> {\n if (typeof value !== \"object\" || value === null) return false;\n const prototype = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null;\n}\n\nconst INTEGER_TEXT = /^(?:0|-?[1-9]\\d*)$/;\nconst DATE_TEXT = /^(\\d{4})-(\\d{2})-(\\d{2})(?: (BC))?$/;\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\", \"the value is 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\", \"the value is not true, false, zero, or one\");\n}\n\n/** `sum`: an int `_sum` past 2^53 reads as the nearest double (a lossy sum). */\nfunction decodeInt(value: unknown, sum = false): unknown {\n const parsed =\n typeof value === \"bigint\"\n ? Number(value)\n : typeof value === \"string\" && INTEGER_TEXT.test(value)\n ? Number(value)\n : value;\n if (typeof parsed !== \"number\")\n refuseResult(\"int\", \"the value is not a canonical integer\");\n if (!(sum ? Number.isInteger(parsed) : Number.isSafeInteger(parsed)))\n refuseResult(\"int\", \"the integer is outside the safe 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\", \"the value is not a canonical integer\");\n}\n\nfunction decodeNumber(value: unknown): number {\n const parsed =\n typeof value === \"string\" && value.trim() !== \"\" ? Number(value) : value;\n if (typeof parsed !== \"number\" || !Number.isFinite(parsed))\n refuseResult(\"number\", \"the value is not a canonical finite number\");\n return parsed;\n}\n\n/** A widened `_sum`'s SQL and the join its reader reads. */\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\n/** The divisor `aggregates.numberSum` scales its high part by. */\nconst NUMBER_SUM_SCALE = 2 ** 64;\n\n/**\n * A number `_sum` from its two `numberSum` parts: `high * 2^64 + low`, which\n * is the summed double, `±Infinity` past the double range. Each part is null\n * when none of its members is present, so both are for an empty window.\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\n/** The factor `aggregates.integerSum` splits its high part at. */\nconst INTEGER_SUM_SCALE = 2n ** 32n;\n\n/**\n * An int64 `_sum` from its two `integerSum` parts, `high * 2^32 + low`, as\n * the integer text the bigint and decimal-coefficient decoders read. Both\n * parts sum the same members, so both are null for an empty window.\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 (!Array.isArray(value) || value.length !== 2)\n refuseResult(type, \"the sum is not its two parts\");\n return [value[0], value[1]];\n}\n\nfunction decodeTime(value: unknown): string {\n if (typeof value !== \"string\")\n refuseResult(\"time\", \"the value is not a valid provider 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\", \"the value is not a valid provider time\");\n if (Number(match[4] ?? 0) > 23 || Number(match[5] ?? 0) > 59)\n refuseResult(\"time\", \"the timezone suffix is invalid\");\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\", \"the normalized precision exceeds milliseconds\");\n return time;\n}\n\n/**\n * Every driver's binary spelling, normalized to one fresh Uint8Array by the one\n * binary-shape owner (`validation/primitives/binary-shapes.ts`); the refusal's\n * wording is this boundary's.\n */\nfunction decodeBlob(value: unknown): Uint8Array {\n const { bytes } = normalizeBinaryValue(value);\n if (bytes) return bytes;\n refuseResult(\"blob\", \"the value is not a binary value\");\n}\n\n/** One dimension of a provider's own array output text: `{a,\"b,c\",NULL}`. */\nfunction providerArrayMembers(text: string): unknown[] {\n if (!(text.startsWith(\"{\") && text.endsWith(\"}\")))\n refuseResult(\"enum\", \"a list scalar did not return 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":"g9BAqOA,MAAa,cACX,EACA,IAEA,GACG,EAAO,IAAU,EAAO,IAAI,EAAM,EAAE,SAAS,KAAW,IAAA,GACzD,EACD,CAuDH,IAAa,UAAb,KAAuB,CACrB,IACA,KACA,IACA,GACA,YAAY,EAAc,EAAe,CACnC,IAAQ,IAAA,GAAW,KAAK,IAAM,GAC7B,KAAK,IAAM,EACZ,IAAS,IAAA,KAAW,KAAK,KAAO,GACpC,MAAA,EAAa,IAAS,IAAA,GAAY,EAAE,CAAG,EAAK,MAAM,IAAI,CACtD,OAAO,OAAO,KAAK,CAMrB,KACE,EACA,EACS,CACT,GAAI,KAAK,MAAQ,IAAA,GAAW,OAAO,GAAU,CAC7C,IAAI,EAAQ,GAAQ,KAAK,KAAK,KAC9B,IAAK,IAAM,KAAO,MAAA,EAAY,CAC5B,GAAsB,OAAO,GAAU,WAAnC,EAA6C,OACjD,EAAQ,OAAO,OAAO,EAAO,EAAI,CAAI,EAAgB,GAAO,IAAA,GAE9D,OAAO,GAAS,IAAA,KAaP,UAAb,KAAuB,CACrB,UACA,KACA,YAAY,EAAsB,EAAqB,CACrD,KAAK,UAAY,EACjB,KAAK,KAAO,EACZ,OAAO,OAAO,KAAK,CAErB,MACE,EACA,EACS,CACT,IAAM,EAAQ,KAAK,UAAU,KAAK,EAAQ,EAAQ,CAC5C,EAAO,KAAK,KAOlB,MANI,WAAY,EAAc,IAAU,IAAA,KAAe,EAAK,OACxD,IAAU,IAAA,GAAkB,GAC5B,WAAY,EAAa,OAAO,GAAG,EAAO,EAAK,OAAO,CACtD,OAAQ,EAAa,EAAK,GAAG,SAAS,EAAM,CAC3C,MAAM,QAAQ,EAAM,CACrB,QAAS,EAAa,EAAM,SAAS,EAAK,IAAI,CAC3C,EAAK,QAAQ,KAAM,GAAW,EAAM,SAAS,EAAO,CAAC,CAF1B,K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