viborm 1.3.3 → 1.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (234) hide show
  1. package/dist/{adapter-internals-AGgQRu5t.mjs → adapter-internals-Cy2QEBnH.mjs} +1 -1
  2. package/dist/{adapter-internals-AGgQRu5t.mjs.map → adapter-internals-Cy2QEBnH.mjs.map} +1 -1
  3. package/dist/{adapter-namespace-CWLEmon2.mjs → adapter-namespace-NnXlXR8c.mjs} +2 -2
  4. package/dist/{adapter-namespace-CWLEmon2.mjs.map → adapter-namespace-NnXlXR8c.mjs.map} +1 -1
  5. package/dist/adapter-result-parser-D6lluSMi.mjs +2 -0
  6. package/dist/adapter-result-parser-D6lluSMi.mjs.map +1 -0
  7. package/dist/adapters.d.mts +1 -1
  8. package/dist/adapters.mjs +1 -1
  9. package/dist/{array-literal-BKdLfNzM.mjs → array-literal-BsbbSLw3.mjs} +1 -1
  10. package/dist/{array-literal-BKdLfNzM.mjs.map → array-literal-BsbbSLw3.mjs.map} +1 -1
  11. package/dist/{batch-refs-DGJPz8-G.mjs → batch-refs-BYCu1JnQ.mjs} +1 -1
  12. package/dist/{batch-refs-DGJPz8-G.mjs.map → batch-refs-BYCu1JnQ.mjs.map} +1 -1
  13. package/dist/bind-parameter-capacity-D6p9HrbB.mjs +2 -0
  14. package/dist/bind-parameter-capacity-D6p9HrbB.mjs.map +1 -0
  15. package/dist/builder-BxCr9ANq.mjs +2 -0
  16. package/dist/builder-BxCr9ANq.mjs.map +1 -0
  17. package/dist/bun-sql.d.mts +3 -1
  18. package/dist/bun-sql.mjs +1 -1
  19. package/dist/bun-sql.mjs.map +1 -1
  20. package/dist/bun-sqlite.d.mts +1 -1
  21. package/dist/bun-sqlite.mjs +1 -1
  22. package/dist/cache/cloudflare-kv.d.mts +1 -1
  23. package/dist/cache/cloudflare-kv.mjs +1 -1
  24. package/dist/cache/memory.d.mts +1 -1
  25. package/dist/cache/memory.mjs +1 -1
  26. package/dist/cache.d.mts +1 -1
  27. package/dist/cache.mjs +1 -1
  28. package/dist/{canonical-json-BReb5nFO.mjs → canonical-json-acY4dQNQ.mjs} +2 -2
  29. package/dist/canonical-json-acY4dQNQ.mjs.map +1 -0
  30. package/dist/chain-C4EUyLzF.mjs +2 -0
  31. package/dist/chain-C4EUyLzF.mjs.map +1 -0
  32. package/dist/cli.mjs +1 -1
  33. package/dist/{client-DR0vYetv.d.mts → client-3FqgR4eS.d.mts} +3 -1
  34. package/dist/client-DUulrWw5.mjs +2 -0
  35. package/dist/client-DUulrWw5.mjs.map +1 -0
  36. package/dist/{client-DjtWangN.mjs → client-sAey5P-I.mjs} +16 -16
  37. package/dist/client-sAey5P-I.mjs.map +1 -0
  38. package/dist/client.d.mts +1 -1
  39. package/dist/client.mjs +1 -1
  40. package/dist/{clock-YTLtjLFS.mjs → clock-CJotKAxc.mjs} +1 -1
  41. package/dist/{clock-YTLtjLFS.mjs.map → clock-CJotKAxc.mjs.map} +1 -1
  42. package/dist/config.d.mts +1 -1
  43. package/dist/config.mjs +1 -1
  44. package/dist/current-C2fZL9Ln.mjs +2 -0
  45. package/dist/current-C2fZL9Ln.mjs.map +1 -0
  46. package/dist/d1.d.mts +1 -1
  47. package/dist/d1.mjs +1 -1
  48. package/dist/d1.mjs.map +1 -1
  49. package/dist/{datetime-physical-codec-qKxFtI3B.mjs → datetime-physical-codec-CFoeuitT.mjs} +2 -2
  50. package/dist/{datetime-physical-codec-qKxFtI3B.mjs.map → datetime-physical-codec-CFoeuitT.mjs.map} +1 -1
  51. package/dist/{driver-BvP7eW0A.mjs → driver-BqD-3_jO.mjs} +2 -2
  52. package/dist/{driver-BvP7eW0A.mjs.map → driver-BqD-3_jO.mjs.map} +1 -1
  53. package/dist/driver-DseQwbsu.mjs +2 -0
  54. package/dist/driver-DseQwbsu.mjs.map +1 -0
  55. package/dist/driver.d.mts +1 -1
  56. package/dist/driver.mjs +1 -1
  57. package/dist/error-mapping-6op318w6.mjs.map +1 -1
  58. package/dist/every-CEQMQEdt.mjs +2 -0
  59. package/dist/{every-WUr3mlvg.mjs.map → every-CEQMQEdt.mjs.map} +1 -1
  60. package/dist/execution-context-asSCmyas.mjs +2 -0
  61. package/dist/execution-context-asSCmyas.mjs.map +1 -0
  62. package/dist/{fs-estate-azK36i9V.mjs → fs-estate-N_F2YqYa.mjs} +2 -2
  63. package/dist/{fs-estate-azK36i9V.mjs.map → fs-estate-N_F2YqYa.mjs.map} +1 -1
  64. package/dist/{geo-area-codec-BmMmWgU_.mjs → geo-area-codec-4W5b7whM.mjs} +2 -2
  65. package/dist/{geo-area-codec-BmMmWgU_.mjs.map → geo-area-codec-4W5b7whM.mjs.map} +1 -1
  66. package/dist/geo-point-codec-pAWYj5ZZ.mjs +2 -0
  67. package/dist/geo-point-codec-pAWYj5ZZ.mjs.map +1 -0
  68. package/dist/{hydration-BflrXEIQ.mjs → hydration-Az2rjp5a.mjs} +2 -2
  69. package/dist/{hydration-BflrXEIQ.mjs.map → hydration-Az2rjp5a.mjs.map} +1 -1
  70. package/dist/{identifier-conversion-Bs7A2GGU.mjs → identifier-conversion-ufaCNi9E.mjs} +2 -2
  71. package/dist/{identifier-conversion-Bs7A2GGU.mjs.map → identifier-conversion-ufaCNi9E.mjs.map} +1 -1
  72. package/dist/identity-CmRos0Yf.mjs +2 -0
  73. package/dist/identity-CmRos0Yf.mjs.map +1 -0
  74. package/dist/{index-B_jh2oaQ.d.mts → index-oVv9RLt5.d.mts} +1315 -1057
  75. package/dist/index.d.mts +1 -1
  76. package/dist/index.mjs +1 -1
  77. package/dist/instrumentation.d.mts +1 -1
  78. package/dist/instrumentation.mjs +1 -1
  79. package/dist/instrumentation.mjs.map +1 -1
  80. package/dist/{invariant-D57gi_yW.mjs → invariant-D_fIjY_z.mjs} +1 -1
  81. package/dist/{invariant-D57gi_yW.mjs.map → invariant-D_fIjY_z.mjs.map} +1 -1
  82. package/dist/{json-number-DvmiNx0n.mjs → json-number-CGXpPu4D.mjs} +1 -1
  83. package/dist/{json-number-DvmiNx0n.mjs.map → json-number-CGXpPu4D.mjs.map} +1 -1
  84. package/dist/{key-B89Z4vxn.mjs → key-CyLRw0ne.mjs} +2 -2
  85. package/dist/{key-B89Z4vxn.mjs.map → key-CyLRw0ne.mjs.map} +1 -1
  86. package/dist/{libsql-C8dn4id0.mjs → libsql-DPrXWc_J.mjs} +2 -2
  87. package/dist/{libsql-C8dn4id0.mjs.map → libsql-DPrXWc_J.mjs.map} +1 -1
  88. package/dist/libsql.d.mts +1 -1
  89. package/dist/libsql.mjs +1 -1
  90. package/dist/libsql.mjs.map +1 -1
  91. package/dist/{memory-B7CcHS6I.mjs → memory-DiTWROVS.mjs} +2 -2
  92. package/dist/{memory-B7CcHS6I.mjs.map → memory-DiTWROVS.mjs.map} +1 -1
  93. package/dist/migrations/mysql.d.mts +4 -4
  94. package/dist/migrations/mysql.mjs +1 -1
  95. package/dist/migrations/postgres.d.mts +4 -4
  96. package/dist/migrations/postgres.mjs +1 -1
  97. package/dist/migrations/sqlite.d.mts +4 -4
  98. package/dist/migrations/sqlite.mjs +1 -1
  99. package/dist/migrations/storage/durable-object.mjs +1 -1
  100. package/dist/migrations/storage/fs.mjs +1 -1
  101. package/dist/migrations/storage/r2.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-adapter-B1U35CJn.mjs +2 -0
  107. package/dist/{mysql-adapter-ABpgFB2N.mjs.map → mysql-adapter-B1U35CJn.mjs.map} +1 -1
  108. package/dist/{mysql-mUmhH9Cf.mjs → mysql-fJlFIW7m.mjs} +2 -2
  109. package/dist/{mysql-mUmhH9Cf.mjs.map → mysql-fJlFIW7m.mjs.map} +1 -1
  110. package/dist/mysql2.d.mts +1 -1
  111. package/dist/mysql2.mjs +1 -1
  112. package/dist/mysql2.mjs.map +1 -1
  113. package/dist/neon-http.d.mts +3 -1
  114. package/dist/neon-http.mjs +1 -1
  115. package/dist/neon-http.mjs.map +1 -1
  116. package/dist/normalized-result-BF7gr4_b.mjs +2 -0
  117. package/dist/normalized-result-BF7gr4_b.mjs.map +1 -0
  118. package/dist/{object-store-Ds9NKRU6.d.mts → object-store-C56-FLkl.d.mts} +3 -3
  119. package/dist/{object-store-CZADAv4c.mjs → object-store-WjVilDvN.mjs} +2 -2
  120. package/dist/{object-store-CZADAv4c.mjs.map → object-store-WjVilDvN.mjs.map} +1 -1
  121. package/dist/permissions.d.mts +1 -1
  122. package/dist/permissions.mjs +1 -1
  123. package/dist/pg.d.mts +26 -1
  124. package/dist/pg.mjs +1 -1
  125. package/dist/pg.mjs.map +1 -1
  126. package/dist/pglite.d.mts +3 -1
  127. package/dist/pglite.mjs +1 -1
  128. package/dist/pglite.mjs.map +1 -1
  129. package/dist/{physical-uJfmo4-Z.mjs → physical-C4D-979R.mjs} +2 -2
  130. package/dist/{physical-uJfmo4-Z.mjs.map → physical-C4D-979R.mjs.map} +1 -1
  131. package/dist/{pinned-session-C79aDzOg.mjs → pinned-session-FYOFV_gB.mjs} +2 -2
  132. package/dist/{pinned-session-C79aDzOg.mjs.map → pinned-session-FYOFV_gB.mjs.map} +1 -1
  133. package/dist/planetscale.d.mts +1 -1
  134. package/dist/planetscale.mjs +1 -1
  135. package/dist/planetscale.mjs.map +1 -1
  136. package/dist/{planner-DHZG9Vy7.d.mts → planner-C3KX6S85.d.mts} +1 -1
  137. package/dist/{postgres-BACQ_wqF.mjs → postgres-DD92WdFu.mjs} +2 -2
  138. package/dist/{postgres-BACQ_wqF.mjs.map → postgres-DD92WdFu.mjs.map} +1 -1
  139. package/dist/postgres-adapter-B7hzWhky.mjs +2 -0
  140. package/dist/postgres-adapter-B7hzWhky.mjs.map +1 -0
  141. package/dist/postgres-adapter-CJmoxTW7.mjs +2 -0
  142. package/dist/{postgres-adapter-DaMvNOkx.mjs.map → postgres-adapter-CJmoxTW7.mjs.map} +1 -1
  143. package/dist/postgres-result-BCUQf8b_.mjs +2 -0
  144. package/dist/{postgres-result-D403cLyA.mjs.map → postgres-result-BCUQf8b_.mjs.map} +1 -1
  145. package/dist/postgres.d.mts +3 -1
  146. package/dist/postgres.mjs +1 -1
  147. package/dist/postgres.mjs.map +1 -1
  148. package/dist/{provider-limits-DSv2tYFr.mjs → provider-limits-D0ECF7_Q.mjs} +2 -2
  149. package/dist/{provider-limits-DSv2tYFr.mjs.map → provider-limits-D0ECF7_Q.mjs.map} +1 -1
  150. package/dist/relation-bound-BrZLsSke.mjs +2 -0
  151. package/dist/relation-bound-BrZLsSke.mjs.map +1 -0
  152. package/dist/{result-parsing-8wEK3GY1.mjs → result-parsing-CQf_eCl8.mjs} +1 -1
  153. package/dist/{result-parsing-8wEK3GY1.mjs.map → result-parsing-CQf_eCl8.mjs.map} +1 -1
  154. package/dist/result-shape-ic2j3Tze.mjs +2 -0
  155. package/dist/result-shape-ic2j3Tze.mjs.map +1 -0
  156. package/dist/{rows-v1VuwOTa.mjs → rows-YyvK9MDz.mjs} +2 -2
  157. package/dist/{rows-v1VuwOTa.mjs.map → rows-YyvK9MDz.mjs.map} +1 -1
  158. package/dist/{scalar-Cm7nMFmO.mjs → scalar-Dyns7kc7.mjs} +2 -2
  159. package/dist/{scalar-Cm7nMFmO.mjs.map → scalar-Dyns7kc7.mjs.map} +1 -1
  160. package/dist/schema/json.d.mts +1 -1
  161. package/dist/schema/json.mjs +1 -1
  162. package/dist/{schema-D3-ScVH6.mjs → schema-CUm_yh6L.mjs} +2 -2
  163. package/dist/{schema-D3-ScVH6.mjs.map → schema-CUm_yh6L.mjs.map} +1 -1
  164. package/dist/{schema-introspection-TdJrSaKd.mjs → schema-introspection-LpRNeSG2.mjs} +2 -2
  165. package/dist/{schema-introspection-TdJrSaKd.mjs.map → schema-introspection-LpRNeSG2.mjs.map} +1 -1
  166. package/dist/schema.d.mts +1 -1
  167. package/dist/schema.mjs +1 -1
  168. package/dist/select-assembly-BjT_fDbu.mjs +2 -0
  169. package/dist/select-assembly-BjT_fDbu.mjs.map +1 -0
  170. package/dist/{settle-etgtP1WM.mjs → settle-C4w1GfTU.mjs} +2 -2
  171. package/dist/{settle-etgtP1WM.mjs.map → settle-C4w1GfTU.mjs.map} +1 -1
  172. package/dist/{sha256-CEYo7k7R.mjs → sha256-_Nu4s32f.mjs} +1 -1
  173. package/dist/{sha256-CEYo7k7R.mjs.map → sha256-_Nu4s32f.mjs.map} +1 -1
  174. package/dist/soft-delete.d.mts +3 -3
  175. package/dist/{sql-statement-tokens-BW7Q-rF-.mjs → sql-statement-tokens-4J5l5Lyt.mjs} +1 -1
  176. package/dist/{sql-statement-tokens-BW7Q-rF-.mjs.map → sql-statement-tokens-4J5l5Lyt.mjs.map} +1 -1
  177. package/dist/sqlite-adapter-B3dRr5fl.mjs +2 -0
  178. package/dist/sqlite-adapter-B3dRr5fl.mjs.map +1 -0
  179. package/dist/{sqlite-utils-BvSlEs5W.mjs → sqlite-utils-C5_KQPZn.mjs} +2 -2
  180. package/dist/{sqlite-utils-BvSlEs5W.mjs.map → sqlite-utils-C5_KQPZn.mjs.map} +1 -1
  181. package/dist/sqlite3.d.mts +1 -1
  182. package/dist/sqlite3.mjs +1 -1
  183. package/dist/sqlite3.mjs.map +1 -1
  184. package/dist/{standard-sql-CYdZ_KXH.mjs → standard-sql-DmKF8msN.mjs} +2 -2
  185. package/dist/{standard-sql-CYdZ_KXH.mjs.map → standard-sql-DmKF8msN.mjs.map} +1 -1
  186. package/dist/{to-many-Btc9X5Ga.mjs → to-many-DxQuOBuq.mjs} +2 -2
  187. package/dist/{to-many-Btc9X5Ga.mjs.map → to-many-DxQuOBuq.mjs.map} +1 -1
  188. package/dist/transaction-operation-CU1zlxiG.mjs.map +1 -1
  189. package/dist/{utils-Qr8ug94X.mjs → utils-CQ2nQwwO.mjs} +2 -2
  190. package/dist/{utils-Qr8ug94X.mjs.map → utils-CQ2nQwwO.mjs.map} +1 -1
  191. package/dist/{v-514RME2X.mjs → v-BcroBusN.mjs} +2 -2
  192. package/dist/{v-514RME2X.mjs.map → v-BcroBusN.mjs.map} +1 -1
  193. package/dist/{validation-CPnrLcjW.mjs → validation-CjWRiLWU.mjs} +2 -2
  194. package/dist/{validation-CPnrLcjW.mjs.map → validation-CjWRiLWU.mjs.map} +1 -1
  195. package/dist/validation.d.mts +1 -1
  196. package/dist/validation.mjs +1 -1
  197. package/dist/{validator-CQOw7G3q.mjs → validator-yrGnrsAo.mjs} +2 -2
  198. package/dist/{validator-CQOw7G3q.mjs.map → validator-yrGnrsAo.mjs.map} +1 -1
  199. package/dist/version-B9azgPiR.mjs +2 -0
  200. package/dist/{version-0RVYpih5.mjs.map → version-B9azgPiR.mjs.map} +1 -1
  201. package/package.json +16 -16
  202. package/dist/bind-parameter-capacity-DiwRmZ1h.mjs +0 -2
  203. package/dist/bind-parameter-capacity-DiwRmZ1h.mjs.map +0 -1
  204. package/dist/builder-D6Ug-zjM.mjs +0 -2
  205. package/dist/builder-D6Ug-zjM.mjs.map +0 -1
  206. package/dist/canonical-json-BReb5nFO.mjs.map +0 -1
  207. package/dist/chain-B5IbqLGi.mjs +0 -2
  208. package/dist/chain-B5IbqLGi.mjs.map +0 -1
  209. package/dist/client-BmcHzDBa.mjs +0 -2
  210. package/dist/client-BmcHzDBa.mjs.map +0 -1
  211. package/dist/client-DjtWangN.mjs.map +0 -1
  212. package/dist/current-oXcxSCBQ.mjs +0 -2
  213. package/dist/current-oXcxSCBQ.mjs.map +0 -1
  214. package/dist/driver-Bzc0GCQ4.mjs +0 -2
  215. package/dist/driver-Bzc0GCQ4.mjs.map +0 -1
  216. package/dist/every-WUr3mlvg.mjs +0 -2
  217. package/dist/execution-context-rJXTRVrJ.mjs +0 -2
  218. package/dist/execution-context-rJXTRVrJ.mjs.map +0 -1
  219. package/dist/geo-point-codec-D95uXgDF.mjs +0 -2
  220. package/dist/geo-point-codec-D95uXgDF.mjs.map +0 -1
  221. package/dist/identity-Bj2EN6Ss.mjs +0 -2
  222. package/dist/identity-Bj2EN6Ss.mjs.map +0 -1
  223. package/dist/mysql-adapter-ABpgFB2N.mjs +0 -2
  224. package/dist/postgres-adapter-Ci07rgh_.mjs +0 -2
  225. package/dist/postgres-adapter-Ci07rgh_.mjs.map +0 -1
  226. package/dist/postgres-adapter-DaMvNOkx.mjs +0 -2
  227. package/dist/postgres-result-D403cLyA.mjs +0 -2
  228. package/dist/result-shape-BKydBCsR.mjs +0 -2
  229. package/dist/result-shape-BKydBCsR.mjs.map +0 -1
  230. package/dist/select-assembly-uZfvbYjz.mjs +0 -2
  231. package/dist/select-assembly-uZfvbYjz.mjs.map +0 -1
  232. package/dist/sqlite-adapter-DPc9T6Lh.mjs +0 -2
  233. package/dist/sqlite-adapter-DPc9T6Lh.mjs.map +0 -1
  234. package/dist/version-0RVYpih5.mjs +0 -2
@@ -1 +1 @@
1
- {"version":3,"file":"rows-v1VuwOTa.mjs","names":["requiredOn","#keys","#model","#where","previous","models","admitted","#pending","#settle","#settleAll"],"sources":["../src/cache/capability.ts","../src/query-engine/routed-operations.ts","../src/extensions/controls.ts","../src/query-engine/raptor3/shared/row-scope.ts","../src/extensions/admission.ts","../src/extensions/rows.ts"],"sourcesContent":["// The part of the official cache the core client reads on every operation:\n// whether a chain carries the cache, and a handle on the cache runtime. The\n// runtime itself (cache driver, cache flow, result codecs) is installed by\n// `cache()` from `viborm/cache`, so an application that never creates the\n// extension does not load it. A chain can only carry the capability after\n// `cache()` ran, which is what makes `officialCacheRuntime()` total wherever\n// the core asks for it.\n\nimport type { ResolvedExtensionChain } from \"@extensions/chain\";\nimport type { StandardSchemaV1 } from \"@standard-schema/spec\";\nimport type {\n GenericQueryHandler,\n OfficialGenericQueryHandler,\n} from \"@extensions/query\";\nimport { isFunction } from \"@validation/value-guards\";\nimport type { CacheDriver, WaitUntilFn } from \"./driver\";\nimport type { OfficialCacheRuntime } from \"./runtime\";\nimport type { CacheInvalidationOptions } from \"./schema\";\n\nexport const OFFICIAL_CACHE_NAME = \"viborm.cache\";\n\n/** The exact official query contribution. It is recognized by identity. */\nexport type OfficialCacheQueryContribution = OfficialGenericQueryHandler & {\n bind(thisArg: unknown): GenericQueryHandler;\n};\n\n/**\n * A mutation's `cache` argument is the cache's declared control (ruling 7):\n * core removes and admits it before request handlers run, through the cache's\n * own parser, so a malformed value is still a `CacheConfigurationError`.\n */\nexport type OfficialCacheControls = {\n readonly cache: {\n readonly schema: StandardSchemaV1<CacheInvalidationOptions>;\n readonly on: \"writes\";\n };\n};\n\n/** The official value accepted by the dedicated `$extends` overload. */\nexport type OfficialCacheExtension = {\n readonly name: typeof OFFICIAL_CACHE_NAME;\n readonly query: OfficialCacheQueryContribution;\n readonly controls: OfficialCacheControls;\n};\n\n/**\n * The cache's one declaration. The chain places it for any definition carrying\n * the cache's query, whatever `controls` that definition spells: the query is\n * the cache's identity, so its control cannot be forged or left out. It lives\n * here, in the part core always loads, and admits through the runtime: a chain\n * carries the cache only after `cache()` installed that runtime.\n */\nexport const officialCacheControls: OfficialCacheControls = Object.freeze({\n cache: Object.freeze({\n schema: Object.freeze({\n \"~standard\": Object.freeze({\n version: 1,\n vendor: \"viborm\",\n validate: (value: unknown) =>\n Object.freeze({\n value: officialCacheRuntime().admitMutationCacheOptions(value),\n }),\n }),\n }),\n on: \"writes\",\n }),\n});\n\n/**\n * What `cache()` knows before it meets a client: no scope, because the scope\n * partitions on facts (dialect, SQL namespace) that only a concrete driver\n * carries. One definition may be appended to several clients.\n */\nexport interface OfficialCacheDefinitionCapability {\n readonly driver: CacheDriver;\n readonly version: string | number | undefined;\n readonly waitUntil: WaitUntilFn | undefined;\n}\n\n/** The definition once bound to one client's driver, gaining its scope. */\nexport interface OfficialCacheCapability\n extends OfficialCacheDefinitionCapability {\n readonly scope: object;\n}\n\n/**\n * The two driver facts the scope derives from. Structural, so the cache holds\n * no driver reference and no import edge back into `src/drivers`.\n */\nexport interface OfficialCacheBindTarget {\n readonly dialect: string;\n readonly adapter: { readonly namespace?: string | undefined };\n}\n\nconst capabilitiesByQuery = new WeakMap<\n CallableFunction,\n OfficialCacheDefinitionCapability\n>();\nconst definitionsByChain = new WeakMap<\n ResolvedExtensionChain,\n OfficialCacheDefinitionCapability\n>();\nconst capabilitiesByChain = new WeakMap<\n ResolvedExtensionChain,\n OfficialCacheCapability\n>();\nlet runtime: OfficialCacheRuntime | undefined;\n\n/** Recognize `query` as the official cache's contribution. `cache()` only. */\nexport function registerOfficialCacheQuery(\n query: CallableFunction,\n capability: OfficialCacheDefinitionCapability,\n installed: OfficialCacheRuntime\n): void {\n runtime = installed;\n capabilitiesByQuery.set(query, capability);\n}\n\n/** Make the cache runtime reachable; `viborm/cache` does this as it loads. */\nexport function installOfficialCacheRuntime(\n installed: OfficialCacheRuntime\n): void {\n runtime = installed;\n}\n\n/** The cache runtime; reachable only where a chain carries the cache. */\nexport function officialCacheRuntime(): OfficialCacheRuntime {\n if (runtime === undefined)\n throw new Error(\n \"The official cache runtime is not loaded: import cache() from viborm/cache.\"\n );\n return runtime;\n}\n\nexport function getOfficialCacheQueryCapability(\n query: unknown\n): OfficialCacheDefinitionCapability | undefined {\n return isFunction(query) ? capabilitiesByQuery.get(query) : undefined;\n}\n\n/**\n * The definition carried by this chain, scope or no scope. Generic\n * extension-chain code sees only this: admission, duplicate refusal, and\n * propagation are all decisions about the DEFINITION, and none of them may\n * depend on whether a client has bound it yet.\n */\nexport function getOfficialCacheChainDefinition(\n chain: ResolvedExtensionChain | undefined\n): OfficialCacheDefinitionCapability | undefined {\n return chain === undefined ? undefined : definitionsByChain.get(chain);\n}\n\n/** The bound capability: present only after a client composition root bound it. */\nexport function getOfficialCacheChainCapability(\n chain: ResolvedExtensionChain | undefined\n): OfficialCacheCapability | undefined {\n return chain === undefined ? undefined : capabilitiesByChain.get(chain);\n}\n\nexport function registerOfficialCacheChain(\n chain: ResolvedExtensionChain,\n capability: OfficialCacheDefinitionCapability\n): void {\n definitionsByChain.set(chain, capability);\n}\n\n/** Publish the capability the runtime bound for one chain. */\nexport function setOfficialCacheChainCapability(\n chain: ResolvedExtensionChain,\n capability: OfficialCacheCapability\n): void {\n capabilitiesByChain.set(chain, capability);\n}\n\n/**\n * Bind one resolved chain's cache definition to the concrete client driver,\n * deriving the scope that partitions its storage.\n *\n * Called by the client composition root — the one place that holds both the\n * resolved chain and the driver — and only for a chain that carries the\n * official cache, so an ordinary extension costs nothing here.\n */\nexport function bindOfficialCacheChain(\n chain: ResolvedExtensionChain,\n target: OfficialCacheBindTarget\n): void {\n if (definitionsByChain.get(chain) === undefined) return;\n officialCacheRuntime().bindChain(chain, target);\n}\n\n/** Whether an operation runs under the official cache's managed execution. */\nexport function isCacheManagedExecution(\n options: { readonly skipSpan?: boolean } | undefined\n): boolean {\n return options?.skipSpan === true;\n}\n","import type { Operations } from \"@client/types\";\n\n/**\n * The client operation vocabulary, retained at the C-01 cutover.\n *\n * These four names are the only part of the deleted shipped routing module that\n * owners OUTSIDE the engine consume: the client (`isWriteOperation`), the\n * official cache (`isWriteOperation`), the extension surface\n * (`ROUTED_OPERATIONS`) and the query-interception seam (`isReadOperation`).\n * The text below is the deleted `write-engine/routing.ts` definitions verbatim,\n * so no operation changes classification at the cutover.\n */\n\nconst READ_OPERATIONS: ReadonlySet<string> = new Set([\n \"findMany\",\n \"findUnique\",\n \"findFirst\",\n \"findUniqueOrThrow\",\n \"findFirstOrThrow\",\n \"count\",\n \"aggregate\",\n \"groupBy\",\n \"exist\",\n]);\n\n/** Whether a public operation routes through the engine's read owner. */\nexport function isReadOperation(operation: string): boolean {\n return READ_OPERATIONS.has(operation);\n}\n\n/**\n * The operation names the engine owns a construction path for. Every client\n * operation family is here; a name outside it (there is none on the client path)\n * resolves to `undefined`.\n */\nexport const ROUTED_OPERATIONS: ReadonlySet<string> = new Set([\n ...READ_OPERATIONS,\n \"create\",\n \"update\",\n \"delete\",\n \"upsert\",\n \"createMany\",\n \"updateMany\",\n \"deleteMany\",\n]);\n\n/** Whether a public operation routes through the engine's write owner. */\nexport function isWriteOperation(operation: string): boolean {\n return ROUTED_OPERATIONS.has(operation) && !isReadOperation(operation);\n}\n\n/**\n * The verb an `…OrThrow` operation shares its whole envelope with: its schema,\n * its admission and its result. Every other verb is its own base.\n */\nexport function baseOperation(\n operation: Operations\n): Exclude<Operations, \"findUniqueOrThrow\" | \"findFirstOrThrow\"> {\n if (operation === \"findUniqueOrThrow\") return \"findUnique\";\n if (operation === \"findFirstOrThrow\") return \"findFirst\";\n return operation;\n}\n","import { isCanonicalKeyData } from \"@cache/key\";\nimport type {\n CacheableOperations,\n MutationOperations,\n Operations,\n} from \"@client/types\";\nimport {\n ClientInitializationError,\n QueryError,\n ValidationError,\n VibORMError,\n} from \"@errors\";\nimport {\n isReadOperation,\n isWriteOperation,\n ROUTED_OPERATIONS,\n} from \"@query-engine/routed-operations\";\nimport type { Operation } from \"@query-engine/types\";\nimport type { StandardSchemaV1 } from \"@standard-schema/spec\";\nimport { isFunction, isRecord } from \"@validation/value-guards\";\nimport { errorCause } from \"../errors/diagnostic-safety\";\nimport type { ControlLiteral, RuntimeExtensionDefinition } from \"./definition\";\n\n// =============================================================================\n// DEFINITION MEMBERS: plain data, checked by TypeScript only\n// =============================================================================\n\n/** The operations a declared control is accepted on. */\nexport type ControlPlacement =\n | \"reads\"\n | \"writes\"\n | \"all\"\n | readonly Operations[];\n\n/**\n * One argument an extension declares. Its values are a closed list or a\n * Standard Schema; `on` names the operations that accept it (every operation\n * when absent). With `required`, a call on one of those operations that does\n * not pass it is refused, on the models the extension names in `rows`,\n * `data` or `deletion` only; an extension that names no model asks for it on\n * every model. With `bound`, it is accepted only from a binding (the client\n * scope's `$bind`), never from a call's arguments: its placement reads no\n * argument, so a call that passes it is refused as passing an unknown key.\n * With `uncacheable`, a read that holds a value of it is never served from\n * the cache: `$withCache` on that read is refused before any statement. A\n * value held in a variable keeps its literal type only with `as const`, as a\n * held enum clause does.\n */\nexport type ControlDeclaration = (\n | { readonly oneOf: readonly (string | number | boolean)[] }\n | { readonly schema: StandardSchemaV1 }\n) & {\n readonly on?: ControlPlacement;\n readonly required?: boolean;\n readonly bound?: boolean;\n readonly uncacheable?: boolean;\n};\n\nexport type ControlsContribution = {\n readonly [name: string]: ControlDeclaration;\n};\n\n/** Constant scalar `where` or `data` fields of one model. */\ntype ScalarFields = { readonly [field: string]: unknown };\n\n/**\n * Which rows an operation sees. `control` names the call argument that picks\n * a mode; every model entry declares the same mode names, `default` among\n * them. `root` filters the call's own candidates, `related` rows reached\n * through a relation; each is a model's `where`, admitted once when the\n * extension is applied, or the name of one of its `verbs` predicates. Where a\n * filter takes a value, `{ control: \"<name>\", path?: \"a.b\" }` takes the value\n * the call passed for that control (or a field of it), `{ now: true }` the\n * call's instant, and `{ $if: … }` tests a call value. An absent value\n * (`null` included) matches nothing where its control is required, and drops\n * its filter where it is not.\n *\n * `verbs` judges, per model, what a call may do to the rows it sees: a mode\n * only narrows them (R8). A model's entry may be a function returning it:\n * it is called when a call of the chain first needs that model, and its\n * entry admitted then, so a refusal of it fails that call instead of\n * `$extends`. A function returning deeply frozen plain data is called once\n * per schema; one returning anything else, once per client.\n */\nexport type RowsContribution = {\n readonly control: string;\n readonly default: string;\n readonly models: {\n readonly [model: string]: {\n readonly [mode: string]: {\n readonly root?: ScalarFields | string;\n readonly related?: ScalarFields | string;\n };\n };\n };\n readonly verbs?: {\n readonly [model: string]: RowsVerbs | (() => RowsVerbs);\n };\n};\n\n/**\n * One model's named predicates, each a `where` admitted once, and the verbs\n * that take them. `read` ANDs with every mode's `root` and `related`; a write\n * takes its verb's beside them: a delete `delete`'s, an update, for each\n * field its data writes, that field's `writes` entry, else `update`'s, and\n * `update`'s when its data writes only stamps. A join row's change is a write\n * of the relation on both rows it links; a row only addressed to reach its\n * children is read. A verb left out matches nothing.\n *\n * The row a write produces is judged too, as a value, against the rows as\n * they stand before the write, inside the statement that writes it (R4): a\n * created row at `place` (a model naming none is not judged on create); an\n * updated row at the predicates that judged its old row, and, for each field\n * its data writes, at that field's `moves` entry, and where it writes the\n * key of an `acyclic` relation (a to-one relation of the model to itself),\n * outside its own subtree. `acyclic` may be a function returning that list:\n * it is called the first time an update writes the key of one of the\n * model's self relations. A refused row is written by no statement.\n *\n * `evidence` declares a projection key (`evidence.as`) a `select` or\n * `include` may name at every depth, on reads and on the rows a write\n * returns: per row, whether each of `names` holds there beside `read`, or,\n * `ordered`, the last of them that holds (`null` on a row `read` does not\n * hold). `reads` gates a field on a predicate: the row carries it only where\n * `read` and that predicate hold, a `select` naming it fails on a row\n * without them, and every operand a call writes over it (`where`, `orderBy`,\n * aggregates, `distinct`, unique lookups, relation filters) reads it as\n * absent there. A key or foreign-key field is never gated.\n */\nexport type RowsVerbs = {\n readonly predicates: { readonly [name: string]: ScalarFields };\n readonly read?: string;\n readonly update?: string;\n readonly delete?: string;\n readonly writes?: { readonly [field: string]: string };\n readonly place?: string;\n readonly moves?: { readonly [field: string]: string };\n readonly acyclic?: readonly string[] | (() => readonly string[]);\n readonly evidence?: {\n readonly as: string;\n readonly names: readonly string[];\n readonly ordered?: boolean;\n };\n readonly reads?: { readonly [field: string]: string };\n};\n\n/**\n * What a delete does on the models named here: an update that stamps `at`\n * with the call's time and writes `assign`, unless the call's controls match\n * `removeWhen`.\n */\nexport type DeletionContribution = {\n readonly removeWhen?: {\n readonly [control: string]: string | number | boolean;\n };\n readonly models: {\n readonly [model: string]: {\n readonly at?: string;\n readonly assign?: ScalarFields;\n };\n };\n};\n\n/**\n * Fields an extension writes on the models named here: `create` on every\n * create of the model, `update` on every update of it, a soft delete's\n * included. A value is a constant, `{ control: \"<name>\", path?: \"a.b\" }` for\n * the value the call passed for that control or a field of it (a call that\n * passed none writes nothing there), `{ now: true }` for the call's instant,\n * or, on `update`, one of the field's update operators (`{ increment: 1 }`). A field is written only where the caller left it\n * out: a call that writes it itself, or writes the relation whose foreign key\n * holds it, keeps its own value there. A create may leave out such a field\n * even where the schema requires it: the call's data is checked with it\n * counted as given. When the model names here are known to the types\n * (written out, or kept by a `const` type parameter, not a plain\n * `string[]`), the extended client's types agree, nested creates included:\n * the field is optional on a create. When two extensions name a field, the\n * later one writes it, and a value the caller writes wins over both.\n */\nexport type DataContribution = {\n readonly models: {\n readonly [model: string]: {\n readonly create?: ScalarFields;\n readonly update?: ScalarFields;\n };\n };\n};\n\n// =============================================================================\n// CONTROL STATE: what a chain's controls add to each (model, operation)\n// =============================================================================\n\n/** Operations that select candidates: where a rows control is accepted. */\ntype CandidateOperations = Exclude<Operations, \"create\" | \"createMany\">;\n\n/** One declared control as the delegates see it. */\nexport interface PlacedControl<\n Value = unknown,\n Models = PropertyKey,\n Placed = Operations,\n> {\n readonly value: Value;\n readonly models: Models;\n readonly operations: Placed;\n}\n\nexport type NoControls = Record<never, never>;\n\ntype ControlValue<Declaration> = Declaration extends {\n readonly oneOf: readonly (infer Value)[];\n}\n ? Value\n : Declaration extends { readonly schema: StandardSchemaV1<infer Input> }\n ? Input\n : never;\n\ntype PlacementOperations<On> = On extends \"reads\"\n ? CacheableOperations\n : On extends \"writes\"\n ? MutationOperations\n : On extends readonly (infer Operation)[]\n ? Operation\n : Operations;\n\n/**\n * `deletion` places the control `removeWhen` names: on the deletes of the\n * models it manages, whatever the declaration's `on` says.\n */\ntype PlaceControl<Name, Declaration, Deletion> = Deletion extends {\n readonly removeWhen: infer RemoveWhen;\n readonly models: infer Managed;\n}\n ? Name extends keyof RemoveWhen\n ? PlacedControl<\n ControlValue<Declaration>,\n keyof Managed,\n \"delete\" | \"deleteMany\"\n >\n : PlaceFreeControl<Declaration>\n : PlaceFreeControl<Declaration>;\n\ntype PlaceFreeControl<Declaration> = PlacedControl<\n ControlValue<Declaration>,\n PropertyKey,\n PlacementOperations<\n Declaration extends { readonly on: infer On } ? On : \"all\"\n >\n>;\n\ntype DeclaredControls<Definition> = Definition extends {\n readonly controls: infer Controls extends ControlsContribution;\n}\n ? {\n readonly [Name in keyof Controls as Controls[Name] extends {\n readonly bound: true;\n }\n ? never\n : Name]: PlaceControl<\n Name,\n Controls[Name],\n Definition extends { readonly deletion: infer Deletion }\n ? Deletion\n : unknown\n >;\n }\n : NoControls;\n\n/** Every model entry declares the same mode names: those are the values. */\ntype RowsModes<Rows extends RowsContribution> =\n | Rows[\"default\"]\n | {\n [Model in keyof Rows[\"models\"]]: keyof Rows[\"models\"][Model];\n }[keyof Rows[\"models\"]];\n\n/** The rows control: every candidate-selecting operation of every model. */\ntype RowsControl<Definition> = Definition extends {\n readonly rows: infer Rows extends RowsContribution;\n}\n ? {\n readonly [Name in Rows[\"control\"]]: PlacedControl<\n RowsModes<Rows>,\n PropertyKey,\n CandidateOperations\n >;\n }\n : NoControls;\n\n/**\n * The models one definition's `rows` can hide from a relation read: its\n * `models` and `verbs` keys. A to-one relation that targets one of them reads `null` when\n * its target is hidden, so the result types widen it (`result-types.ts`).\n */\nexport type RowsModels<Definition> = Definition extends {\n readonly rows: infer Rows extends RowsContribution;\n}\n ? Extract<\n | keyof Rows[\"models\"]\n | (Rows extends { readonly verbs: infer Verbs } ? keyof Verbs : never),\n string\n >\n : never;\n\n/** The controls one definition places, keyed by control name. */\nexport type DefinitionControls<Definition> = DeclaredControls<Definition> &\n RowsControl<Definition>;\n\n/** The optional control arguments one (model, operation) accepts. */\nexport type OperationControls<Controls, ModelName, Operation> = {\n readonly [Name in keyof Controls as Controls[Name] extends PlacedControl<\n unknown,\n infer Models,\n infer Placed\n >\n ? ModelName extends Models\n ? Operation extends Placed\n ? Name\n : never\n : never\n : never]?: Controls[Name] extends PlacedControl<infer Value>\n ? Value\n : never;\n};\n\n// =============================================================================\n// DATA STATE: the fields a chain's `data` writes, per model\n// =============================================================================\n\n/**\n * The fields one `data` entry writes on its models' creates: there they may\n * be left out even where the schema requires them. An update's fields need\n * nothing, as every field of an update is optional already.\n */\nexport interface StampedFields<Models = PropertyKey, Fields = PropertyKey> {\n readonly models: Models;\n readonly fields: Fields;\n}\n\ntype CreateStamps<Model, Entry> = \"create\" extends keyof Entry\n ? Entry extends { readonly create?: infer Fields }\n ? StampedFields<Model, keyof NonNullable<Fields>>\n : never\n : never;\n\n/**\n * What one definition's `data` writes on creates: one member per model. A\n * definition whose model names are lost (`{ [model: string]: ... }`, as a\n * recipe called with a plain `string[]` builds) writes nothing the types can\n * name: its required fields stay required in the payloads.\n */\nexport type DefinitionData<Definition> = Definition extends {\n readonly data: { readonly models: infer Models };\n}\n ? string extends keyof Models\n ? never\n : {\n [Model in keyof Models]: CreateStamps<Model, Models[Model]>;\n }[keyof Models]\n : never;\n\n/** The fields a chain writes on every create of one model. */\nexport type StampedFieldNames<Data, ModelName> =\n Data extends StampedFields<infer Models, infer Fields extends PropertyKey>\n ? ModelName extends Models\n ? Fields\n : never\n : never;\n\n// =============================================================================\n// PLACEMENT: where each declared control is accepted\n// =============================================================================\n\n/** Where a control goes when its declaration names a placement. */\nconst PLACEMENTS: Readonly<\n Record<\"reads\" | \"writes\" | \"all\", ReadonlySet<string>>\n> = {\n reads: new Set([...ROUTED_OPERATIONS].filter(isReadOperation)),\n writes: new Set([...ROUTED_OPERATIONS].filter(isWriteOperation)),\n all: ROUTED_OPERATIONS,\n};\n\n/** Every operation that selects candidates: where a `rows` control goes. */\nconst CANDIDATE_OPERATIONS: ReadonlySet<string> = new Set(\n [...ROUTED_OPERATIONS].filter(\n (operation) => operation !== \"create\" && operation !== \"createMany\"\n )\n);\n\n/** Where a `deletion.removeWhen` control goes, on the models it manages. */\nconst DELETE_OPERATIONS: ReadonlySet<string> = new Set([\n \"delete\",\n \"deleteMany\",\n]);\n\n/** One control of a chain: its owner, its placement and how a value is admitted. */\nexport interface ResolvedControl {\n readonly name: string;\n readonly extension: string;\n readonly declaration: ControlDeclaration;\n /** The operations that accept it. */\n readonly operations: ReadonlySet<string>;\n /** The models that accept it; every model when absent. */\n readonly models?: ReadonlySet<string>;\n /**\n * Where a call that does not pass it is refused: on every model that\n * accepts it (`true`), on these models only, or nowhere when absent.\n */\n readonly required?: true | ReadonlySet<string>;\n /** What an absent argument admits: the `rows` control's default mode. */\n readonly fallback?: ControlLiteral;\n /** Accepted only from a binding, never read from the arguments. */\n readonly bound?: true;\n /** A read holding a value of it is not served from the cache. */\n readonly uncacheable?: true;\n}\n\n/**\n * Give every control of one definition its placement. A control\n * `deletion.removeWhen` names goes on the deletes of the models `deletion`\n * manages; the `rows` control on every candidate-selecting operation of every\n * model, its values the mode names; every other control where its own `on`\n * says (every operation without one), on every model. A `required` control\n * is asked for only on the models the definition names in `rows`, `data` or\n * `deletion`, and on every model when it names none.\n */\nexport function placeControls(\n definition: RuntimeExtensionDefinition\n): readonly ResolvedControl[] {\n const placed: ResolvedControl[] = [];\n const { name: extension, controls, rows, deletion, data } = definition;\n const removeWhen = deletion?.removeWhen ?? {};\n const managed = new Set(Object.keys(deletion?.models ?? {}));\n const named = new Set([\n ...managed,\n ...Object.keys(rows?.models ?? {}),\n ...Object.keys(rows?.verbs ?? {}),\n ...Object.keys(data?.models ?? {}),\n ]);\n const requiredOn = named.size === 0 ? true : named;\n for (const [name, declaration] of Object.entries(controls ?? {})) {\n const removes = Object.hasOwn(removeWhen, name);\n placed.push({\n name,\n extension,\n declaration,\n operations: removes ? DELETE_OPERATIONS : placementOf(declaration.on),\n models: removes ? managed : undefined,\n required: declaration.required === true ? requiredOn : undefined,\n ...(declaration.bound === true && { bound: true }),\n ...(declaration.uncacheable === true && { uncacheable: true }),\n });\n }\n if (rows !== undefined) {\n placed.push({\n name: rows.control,\n extension,\n declaration: Object.freeze({ oneOf: Object.freeze(rowsModes(rows)) }),\n operations: CANDIDATE_OPERATIONS,\n fallback: rows.default,\n });\n }\n return placed;\n}\n\nfunction placementOf(on: ControlDeclaration[\"on\"]): ReadonlySet<string> {\n if (on === undefined) return ROUTED_OPERATIONS;\n return typeof on === \"string\" ? PLACEMENTS[on] : new Set<string>(on);\n}\n\n/**\n * The `rows` control's values: the mode names, which every model entry\n * declares alike, or the default alone when no model is named.\n */\nexport function rowsModes(rows: RowsContribution): readonly string[] {\n const [modes] = Object.values(rows.models);\n return modes === undefined ? [rows.default] : Object.keys(modes);\n}\n\n// =============================================================================\n// ADMISSION: one call's controls, removed and validated once\n// =============================================================================\n\n/**\n * The controls one call admitted, by name. A `rows` control is resolved to its\n * mode, so an absent one reads as its default; an absent plain control is not\n * here.\n */\nexport type AdmittedControls = Readonly<Record<string, unknown>>;\n\nexport interface ControlAdmission {\n /** The arguments without their controls; the input itself when none was given. */\n readonly args: Record<string, unknown>;\n /** `undefined` when the call admitted no value. */\n readonly controls: AdmittedControls | undefined;\n}\n\n/** The admitted values {@link snapshotControlValue} copied: the stable ones. */\nconst snapshots = new WeakSet<object>();\n\n/**\n * An admitted value as the call holds it from here on. Plain data is copied\n * once and frozen, so every reader of the call's controls (the rows its\n * filters bind, the key its cached read is stored under, its handlers) reads\n * the same value whatever the caller later does to its own. A value already\n * fixed all the way down is kept by identity. A value a copy would change\n * (a non-enumerable or symbol property, which `structuredClone` drops; a\n * getter, whose answer only calling it shows), one that resists inspection,\n * one with no canonical spelling, or one that cannot be copied (a Proxy), is\n * kept as given, as are bytes (an indexed write survives `freeze`); a copy\n * that still holds a `Date` is kept but not stable (`setTime` survives it). In\n * those cases the call binds the value for itself alone and its read is not\n * cached.\n */\nexport function snapshotControlValue(value: unknown): unknown {\n if (typeof value !== \"object\" || value === null) return value;\n if (!isCanonicalKeyData(value)) return value;\n let capture: ReturnType<typeof captureOf>;\n try {\n capture = captureOf(value, new WeakSet());\n } catch {\n // A Proxy may answer the canonical check and refuse a later reflection.\n return value;\n }\n if (capture === \"opaque\") return value;\n if (capture === \"fixed\") {\n snapshots.add(value);\n return value;\n }\n let copy: object;\n try {\n copy = structuredClone(value);\n } catch {\n return value;\n }\n if (freezeCopy(copy)) snapshots.add(copy);\n return copy;\n}\n\n/**\n * How an admitted value can be held: `fixed` when nothing reachable from it\n * can change (frozen own data properties only, no `Date`), `copy` when a\n * copy reproduces it (enumerable string-keyed data properties), `opaque`\n * when a copy might not (a non-enumerable or symbol property, or a getter,\n * never called here) or would not fix it (bytes).\n */\nfunction captureOf(\n value: object,\n seen: WeakSet<object>\n): \"fixed\" | \"copy\" | \"opaque\" {\n // Bytes are never stable (an indexed write survives `freeze`), and their\n // own properties are one per byte: kept as given, unread.\n if (ArrayBuffer.isView(value)) return \"opaque\";\n if (seen.has(value)) return \"fixed\";\n seen.add(value);\n let capture: \"fixed\" | \"copy\" =\n value instanceof Date || !Object.isFrozen(value) ? \"copy\" : \"fixed\";\n const array = Array.isArray(value);\n for (const key of Reflect.ownKeys(value)) {\n if (array && key === \"length\") continue;\n const descriptor = Object.getOwnPropertyDescriptor(value, key)!;\n if (\n typeof key === \"symbol\" ||\n !descriptor.enumerable ||\n !(\"value\" in descriptor)\n )\n return \"opaque\";\n const entry: unknown = descriptor.value;\n if (typeof entry !== \"object\" || entry === null) continue;\n const inner = captureOf(entry, seen);\n if (inner === \"opaque\") return \"opaque\";\n if (inner === \"copy\") capture = \"copy\";\n }\n return capture;\n}\n\n/** Freeze a private copy; answer whether nothing in it can still change. */\nfunction freezeCopy(value: object): boolean {\n if (value instanceof Date) return false;\n let fixed = true;\n for (const entry of Object.values(value))\n if (typeof entry === \"object\" && entry !== null && !freezeCopy(entry))\n fixed = false;\n Object.freeze(value);\n return fixed;\n}\n\n/**\n * Whether a control value is the one admission fixed: a primitive, or plain\n * data {@link snapshotControlValue} copied. Only such a value may key anything that\n * outlives the call (a bound-facts memo, a cache entry).\n */\nexport function isStableControlValue(value: unknown): boolean {\n return typeof value !== \"object\" || value === null || snapshots.has(value);\n}\n\n/**\n * Remove every control placed on this operation from its arguments and admit\n * each once, before any request handler runs. A key naming a control placed\n * elsewhere, or a bound-only one, stays in the arguments, where core\n * validation refuses it as an unknown key. A control the call did not pass\n * takes the value its view binds, if any; without one it is refused here on\n * the models its placement requires it on.\n */\nexport function admitControls(\n model: string,\n operation: Operation,\n input: Record<string, unknown>,\n placed: readonly ResolvedControl[],\n bound?: AdmittedControls\n): ControlAdmission {\n // Arguments that are not an object hold no control: core validation refuses\n // them as it does on a client without controls.\n if (typeof input !== \"object\" || input === null) {\n return { args: input, controls: undefined };\n }\n let keys: PropertyKey[];\n try {\n keys = Reflect.ownKeys(input);\n } catch (cause) {\n throw controlFailure(\n `The arguments of ${model}.${operation} could not be inspected for controls`,\n model,\n operation,\n cause\n );\n }\n const admitted: [string, unknown][] = [];\n let given: Set<PropertyKey> | undefined;\n for (const control of placed) {\n const { name, required } = control;\n let raw: unknown;\n if (control.bound !== true && keys.includes(name)) {\n (given ??= new Set()).add(name);\n raw = readControl(input, control, model, operation);\n }\n // A bound value was admitted and fixed once, when its view was bound.\n const value =\n raw === undefined\n ? (bound?.[name] ?? control.fallback)\n : snapshotControlValue(admitControl(control, raw, model, operation));\n if (value !== undefined) admitted.push([name, value]);\n else if (required === true || required?.has(model)) {\n throw invalidControl(control, model, operation, [\"is required\"]);\n }\n }\n return {\n args:\n given === undefined\n ? input\n : withoutControls(input, keys, given, model, operation),\n controls:\n admitted.length === 0\n ? undefined\n : Object.freeze(Object.fromEntries(admitted)),\n };\n}\n\n/**\n * The values a view binds after one extension binds its own controls: each\n * admitted once and fixed, over the values the view already binds, a value\n * replacing an earlier one.\n */\nexport function bindControls(\n controls: readonly ResolvedControl[],\n extension: string,\n values: Readonly<Record<string, unknown>>,\n previous: AdmittedControls | undefined\n): AdmittedControls {\n const next: Record<string, unknown> = { ...previous };\n for (const [name, raw] of Object.entries(values)) {\n const control = controls.find(\n (candidate) =>\n candidate.name === name && candidate.extension === extension\n );\n if (control === undefined) {\n throw new ClientInitializationError(\n `Extension \"${extension}\" binds control \"${name}\", which it does not declare.`,\n { meta: { extension } }\n );\n }\n next[name] = snapshotControlValue(admitControl(control, raw));\n }\n return Object.freeze(next);\n}\n\n/** One extension's own admitted controls, as its handlers see them. */\nexport function controlsOwnedBy(\n admitted: AdmittedControls | undefined,\n names: readonly string[]\n): AdmittedControls {\n const owned: [string, unknown][] = [];\n for (const name of names) {\n if (admitted !== undefined && Object.hasOwn(admitted, name)) {\n owned.push([name, admitted[name]]);\n }\n }\n return Object.freeze(Object.fromEntries(owned));\n}\n\nfunction readControl(\n input: Record<string, unknown>,\n control: ResolvedControl,\n model: string,\n operation: Operation\n): unknown {\n try {\n return Reflect.get(input, control.name);\n } catch (cause) {\n throw controlFailure(\n `Extension \"${control.extension}\" control \"${control.name}\" of ${model}.${operation} could not be read`,\n model,\n operation,\n cause\n );\n }\n}\n\n/** The caller's arguments minus the controls, every other descriptor kept. */\nfunction withoutControls(\n input: Record<string, unknown>,\n keys: readonly PropertyKey[],\n controls: ReadonlySet<PropertyKey>,\n model: string,\n operation: Operation\n): Record<string, unknown> {\n const args: Record<string, unknown> = {};\n try {\n for (const key of keys) {\n if (controls.has(key)) continue;\n const descriptor = Object.getOwnPropertyDescriptor(input, key);\n if (descriptor) Object.defineProperty(args, key, descriptor);\n }\n } catch (cause) {\n throw controlFailure(\n `The arguments of ${model}.${operation} could not be inspected for controls`,\n model,\n operation,\n cause\n );\n }\n return args;\n}\n\n/** One value admitted for a call's (model, operation), or, without them, a binding. */\nfunction admitControl(\n control: ResolvedControl,\n value: unknown,\n model?: string,\n operation?: Operation\n): unknown {\n const { declaration } = control;\n if (\"oneOf\" in declaration) {\n if (declaration.oneOf.some((allowed) => allowed === value)) return value;\n throw invalidControl(control, model, operation, [\n `must be one of ${declaration.oneOf.map((allowed) => JSON.stringify(allowed)).join(\", \")}`,\n ]);\n }\n let result: unknown;\n try {\n result = declaration.schema[\"~standard\"].validate(value);\n } catch (cause) {\n // A validator may own its typed failure; anything else is a failure of\n // extension code, as a throwing request transform is.\n if (isVibORMFailure(cause)) throw cause;\n throw validatorFailure(control, model, operation, \"threw\", cause);\n }\n let shape: \"promise\" | \"malformed\" | \"issues\" | \"value\" = \"malformed\";\n let issues: readonly unknown[] = [];\n let admitted: unknown;\n try {\n if (isRecord(result)) {\n const then = \"then\" in result ? result.then : undefined;\n if (isFunction(then)) {\n shape = \"promise\";\n // The refused promise is still live; without a handler its rejection\n // would surface as an unhandled rejection (D-37).\n Reflect.apply(then, result, [undefined, () => undefined]);\n } else {\n const listed = result.issues;\n if (listed !== undefined) {\n if (Array.isArray(listed)) {\n shape = \"issues\";\n issues = listed;\n }\n } else if (\"value\" in result) {\n shape = \"value\";\n admitted = result.value;\n }\n }\n }\n } catch (cause) {\n throw validatorFailure(\n control,\n model,\n operation,\n \"returned an unreadable result\",\n cause\n );\n }\n switch (shape) {\n case \"value\":\n return admitted;\n case \"issues\":\n throw invalidControl(control, model, operation, issueMessages(issues));\n case \"promise\":\n throw validatorFailure(\n control,\n model,\n operation,\n \"returned a promise\",\n new TypeError(\"Control validators must return synchronously\")\n );\n default:\n throw validatorFailure(\n control,\n model,\n operation,\n \"returned a malformed result\",\n new TypeError(\"A Standard Schema result has a value or an issue list\")\n );\n }\n}\n\n/** Each issue's message; an issue that cannot be read still refuses. */\nfunction issueMessages(issues: readonly unknown[]): string[] {\n const messages: string[] = [];\n try {\n for (const issue of issues) {\n const message = isRecord(issue) ? issue.message : undefined;\n messages.push(typeof message === \"string\" ? message : \"is invalid\");\n }\n } catch {\n return [\"is invalid\"];\n }\n return messages.length === 0 ? [\"is invalid\"] : messages;\n}\n\n/** Contained: `instanceof` on a hostile thrown proxy is itself a throw site. */\nfunction isVibORMFailure(value: unknown): value is VibORMError {\n try {\n return value instanceof VibORMError;\n } catch {\n return false;\n }\n}\n\n/**\n * The refusal of a cached read that holds a value of an `uncacheable`\n * control, or `undefined` when it holds none: such a read is an observation\n * the control's owner does not accept (the cache would serve it after the\n * facts it was judged on changed).\n */\nexport function uncacheableRead(\n controls: readonly ResolvedControl[],\n admitted: AdmittedControls | undefined,\n model: string,\n operation: Operation\n): ValidationError | undefined {\n const held = controls.find(\n (control) =>\n control.uncacheable === true && admitted?.[control.name] !== undefined\n );\n return (\n held &&\n invalidControl(held, model, operation, [\n \"is not cacheable: a read that holds it is not served from the cache\",\n ])\n );\n}\n\nfunction invalidControl(\n control: ResolvedControl,\n model: string | undefined,\n operation: Operation | undefined,\n messages: readonly string[]\n): ValidationError {\n return new ValidationError(\n operation === undefined\n ? { kind: \"schema-builder\", builder: \"$bind\", path: control.name }\n : { kind: \"operation\", operation, model },\n messages.map((message) => ({\n path: control.name,\n message: `Control \"${control.name}\" ${message}`,\n })),\n { meta: { model, extension: control.extension } }\n );\n}\n\nfunction validatorFailure(\n control: ResolvedControl,\n model: string | undefined,\n operation: Operation | undefined,\n failure: string,\n cause: unknown\n): QueryError {\n return controlFailure(\n `Extension \"${control.extension}\" control \"${control.name}\" validator for ${operation === undefined ? \"$bind\" : `${model}.${operation}`} ${failure}`,\n model,\n operation,\n cause\n );\n}\n\nfunction controlFailure(\n message: string,\n model: string | undefined,\n operation: Operation | undefined,\n cause: unknown\n): QueryError {\n return new QueryError(`${message}.`, {\n cause: errorCause(cause),\n meta: { model, operation },\n });\n}\n","import { parseProviding } from \"@validation/primitives/object\";\nimport type { PreparedDomain } from \"./query\";\nimport type { Input } from \"./schema\";\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 `rows` member's place in the chain, so a\n * layer stating nothing for the model leaves a hole.\n */\nexport type ModelDomain = ReadonlyMap<string, 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 * Per model (its TS name), indexed by layer as {@link ModelDomain} is, the\n * predicates of the model's verbs. A model absent here judges a write by\n * its purpose's predicates alone.\n */\n readonly verbs?: ReadonlyMap<string, readonly (ModelVerbs | undefined)[]>;\n /**\n * Whether some model's verbs may declare a projection key or a read-gated\n * field: when not, no model is asked for them. The maps may be resolved a\n * model at a time, so they are never walked to find out.\n */\n readonly projects?: boolean;\n}\n\n/**\n * One layer's predicates for one model's verbs, as admission left them: `read`\n * ANDs with the layer's predicate at every purpose, a write's verb with its\n * candidates beside them (R2). 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): a created row at `place`, absent where the layer\n * does not judge creates; an updated row at the predicates that judged its\n * old row and, per field it writes, that field's `moves` predicate.\n */\nexport interface ModelVerbs {\n readonly read: Input;\n readonly update: Input;\n readonly delete: Input;\n readonly writes: ReadonlyMap<string, Input>;\n readonly place?: Input;\n readonly moves: ReadonlyMap<string, Input>;\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 acyclic: readonly string[] | LazyRelations;\n /** The projection key the layer declares on the model (K5). */\n readonly evidence?: ModelEvidence;\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, Input>;\n}\n\n/**\n * A projection key and what it reports per row, each name with its admitted\n * predicate in declared order: whether each holds beside `read`, or, when\n * `ordered`, the last that does.\n */\nexport interface ModelEvidence {\n readonly as: string;\n readonly names: readonly (readonly [string, Input])[];\n readonly ordered: boolean;\n}\n\n/**\n * The verb a write lookup takes 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 RowJudgement {\n readonly verb: \"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 * 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 control 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 control 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 controls outside the engine:\n * the engine never sees a mode or an extension's name, and a control'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 * control are the call's own.\n */\nexport interface CallRows {\n /** The domain the call's own controls select. */\n readonly domain: RowDomain;\n /**\n * The domain an absent control selects: what a tombstoning delete takes,\n * and every other layer a layer's own traversals read (R5).\n */\n readonly defaults: RowDomain;\n /**\n * Per managed model, what its deletes write; absent when the call deletes\n * physically (its controls match the declaration's `removeWhen`).\n */\n readonly tombstones?: ReadonlyMap<string, Tombstone>;\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}\n\n/** A call's admitted controls, and how an absent value resolves (R6). */\nexport interface CallValues {\n readonly controls: Readonly<Record<string, unknown>>;\n /** An absent value of `control` on `model` matches nothing; else it drops. */\n readonly required: (control: string, model: string) => boolean;\n}\n\n/**\n * A value a domain predicate reads from its call, prepared once and read at\n * lowering: a control's value, or a field of it along `path`; with no\n * control, the call's one instant. `null` is absent: a parameter never lowers\n * to `IS NULL`. Its own fields are its spelling (`{ control, path }` or\n * `{ now: true }`), which no literal of a declaration can be, so a cache key\n * over declarations tells the two apart.\n */\nexport class Parameter {\n readonly control?: string;\n readonly path?: string;\n readonly now?: true;\n readonly #keys: readonly string[];\n constructor(control?: string, path?: string) {\n if (control === undefined) this.now = true;\n else this.control = control;\n if (path !== undefined) this.path = path;\n this.#keys = path === undefined ? [] : path.split(\".\");\n Object.freeze(this);\n }\n /** The call's value, `undefined` when absent. */\n read(values: CallValues | undefined, instant: () => Date): unknown {\n if (this.control === undefined) return instant();\n let value = values?.controls[this.control];\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(values: CallValues | undefined, instant: () => Date): 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 cache key 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 cache 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 /** The default domain, prepared once per engine view. */\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","import type { Schema } from \"@client/types\";\nimport { ClientInitializationError } from \"@errors\";\nimport {\n Condition,\n type ConditionTest,\n Existence,\n type LazyRelations,\n OuterColumn,\n Parameter,\n} from \"@query-engine/raptor3/shared/row-scope\";\nimport type { Input } from \"@query-engine/raptor3/shared/schema\";\nimport type { ModelState } from \"@schema/model\";\nimport { isPlainRecord } from \"@schema/relation/terminal\";\nimport { createSchemaRegistry } from \"@validation/builder\";\nimport { validateSchema } from \"@validation/primitives/helpers\";\nimport {\n type AdmittedFilters,\n admittingDomainPredicate,\n type DomainMarkers,\n} from \"@validation/primitives/parameter\";\nimport type { SchemaRegistryLookup } from \"@validation/types\";\nimport type { RowsContribution, RowsVerbs } from \"./controls\";\n\n/**\n * Each domain predicate admitted once, when its extension is applied, through\n * its model's `where` schema: a misspelt key fails here, never at the first\n * read, and the engine prepares what a caller's `where` would be (K1(a)).\n */\n\n/**\n * The where schemas of a schema no client prepared (a definition read on its\n * own), built once; a client hands admission its own.\n */\nconst registries = new WeakMap<Schema, SchemaRegistryLookup<Schema>>();\n\nfunction standaloneRegistry(schema: Schema): SchemaRegistryLookup<Schema> {\n let registry = registries.get(schema);\n if (registry === undefined) {\n registry = createSchemaRegistry(schema);\n registries.set(schema, registry);\n }\n return registry;\n}\n\n/** Successful admission can be reused only for immutable data and native schemas.\n * Registry identity carries the resolved relation topology; model entries also\n * guard schema maps edited between applications. No call/driver facts live here.\n */\nconst admittedRows = new WeakMap<\n SchemaRegistryLookup<Schema>,\n WeakMap<\n RowsContribution,\n {\n schema: Schema;\n entries: [string, Schema[string]][];\n admitted: RowsContribution;\n }\n >\n>();\n/**\n * A lazy `verbs` entry's admission, per registry, entry and model, for one\n * that returned immutable data: one function may serve several models.\n */\nconst admittedLazily = new WeakMap<\n SchemaRegistryLookup<Schema>,\n WeakMap<\n () => RowsVerbs,\n Map<\n string,\n {\n schema: Schema;\n entries: [string, Schema[string]][];\n admitted: RowsVerbs;\n }\n >\n >\n>();\nconst immutableData = new WeakSet<object>();\nconst immutableAdmitted = new WeakSet<object>();\n/** The functions admission puts in place of a lazy entry and its names. */\nconst resolvers = new WeakSet<object>();\nconst isResolver = (value: object) => resolvers.has(value);\nconst resolver = <T>(resolve: () => T): (() => T) => {\n resolvers.add(resolve);\n return resolve;\n};\n/**\n * Deeply frozen plain data: records, arrays and admitted nodes. With\n * `functions`, a function it accepts is a leaf known by identity.\n */\nexport function isImmutableRowData(\n value: unknown,\n open = new Set<object>(),\n functions?: (value: object) => boolean\n): boolean {\n if (typeof value === \"function\") return functions?.(value) === true;\n if (value === null || typeof value !== \"object\")\n return typeof value !== \"symbol\";\n const known = functions ? immutableAdmitted : immutableData;\n if (known.has(value) || immutableData.has(value)) return true;\n if (!Object.isFrozen(value) || open.has(value)) return false;\n const prototype = Object.getPrototypeOf(value);\n if (\n Array.isArray(value)\n ? prototype !== Array.prototype ||\n !Array.from({ length: value.length }, (_, index) =>\n Object.hasOwn(value, index)\n ).every(Boolean)\n : prototype !== Object.prototype &&\n prototype !== null &&\n prototype !== Parameter.prototype &&\n prototype !== Condition.prototype &&\n prototype !== Existence.prototype &&\n prototype !== OuterColumn.prototype\n )\n return false;\n open.add(value);\n const safe = Reflect.ownKeys(value).every((key) => {\n const descriptor = Object.getOwnPropertyDescriptor(value, key);\n return (\n typeof key === \"string\" &&\n descriptor &&\n \"value\" in descriptor &&\n isImmutableRowData(descriptor.value, open, functions)\n );\n });\n open.delete(value);\n if (safe) known.add(value);\n return safe;\n}\n\n/** Rows admission produced and nobody can change: their facts may be memoised. */\nexport const isAdmittedRows = (rows: object) =>\n isImmutableRowData(rows, new Set(), isResolver);\n\n/** Frozen own data properties of a record, each passing `item`. */\nconst frozenRecord = (\n value: unknown,\n item: (key: string, value: unknown) => boolean\n): boolean =>\n isPlainRecord(value) &&\n Object.isFrozen(value) &&\n Reflect.ownKeys(value).every((key) => {\n const descriptor = Object.getOwnPropertyDescriptor(value, key);\n return (\n typeof key === \"string\" &&\n descriptor !== undefined &&\n \"value\" in descriptor &&\n item(key, descriptor.value)\n );\n });\n\n/** A `verbs` entry's data immutable; its `acyclic` may be a function. */\nconst isImmutableEntry = (entry: unknown) =>\n frozenRecord(\n entry,\n (key, value) =>\n (key === \"acyclic\" && typeof value === \"function\") ||\n isImmutableRowData(value)\n );\n\n/**\n * Immutable `rows` as declared: plain data, but for a `verbs` entry that is\n * a function (and an entry's function `acyclic`), known by identity.\n */\nconst isImmutableRows = (rows: unknown) =>\n frozenRecord(rows, (key, value) =>\n key === \"verbs\"\n ? frozenRecord(\n value,\n (_, entry) => typeof entry === \"function\" || isImmutableEntry(entry)\n )\n : isImmutableRowData(value)\n );\n\n/** Native admission of immutable input owns every newly produced container. */\nfunction freezeAdmitted(value: unknown, seen = new Set<object>()): void {\n if (value === null || typeof value !== \"object\" || seen.has(value)) return;\n seen.add(value);\n for (const child of Object.values(value)) freezeAdmitted(child, seen);\n Object.freeze(value);\n}\n\n/** A model's `rows.verbs` entry, key by key. */\nconst VERBS_KEYS: Record<keyof RowsVerbs, true> = {\n predicates: true,\n read: true,\n update: true,\n delete: true,\n writes: true,\n place: true,\n moves: true,\n acyclic: true,\n evidence: true,\n reads: true,\n};\n\n/**\n * A declared projection key's spelling: `$` and an identifier. No model\n * member and no engine carrier is spelled so, so a key never hides either,\n * whatever the schema later adds.\n */\nconst PROJECTION_KEY = /^\\$[a-zA-Z_][a-zA-Z0-9_]*$/;\n\n/**\n * A model's key, unique and foreign-key fields: what identity and every join\n * read, and what a unique constraint answers for on a write, so none of them\n * is ever read-gated.\n */\nfunction keyFields(state: ModelState): ReadonlySet<string> {\n return new Set([\n ...Object.entries(state.scalars)\n .filter(([, scalar]) => scalar[\"~\"].state.isId === true)\n .map(([field]) => field),\n // A write of a guessed value fails on the constraint exactly when some\n // row holds it: a gate on a unique field would be confirmed by it.\n ...Object.keys(state.uniques),\n ...[\n ...Object.values(state.compoundId ?? {}),\n ...Object.values(state.compoundUniques ?? {}),\n ].flatMap(({ entries }) => Object.keys(entries)),\n ...Object.values(state.relations).flatMap(\n (relation) => relation[\"~\"].state.foreignKey?.fields ?? []\n ),\n ]);\n}\n\n/** A condition's tests, the filter vocabulary's own words (OD-12). */\nconst TESTS = [\"exists\", \"equals\", \"in\", \"has\", \"hasSome\"] as const;\n\n/** `{ control, path? }`: a control's value, or a field of it. */\nexport function isReference(\n value: unknown\n): value is { readonly control: string; readonly path?: string } {\n return (\n isPlainRecord(value) &&\n typeof value.control === \"string\" &&\n Object.keys(value).every((key) => key === \"control\" || key === \"path\") &&\n (value.path === undefined || typeof value.path === \"string\")\n );\n}\n\n/** `{ $row, up }`: a column of an enclosing row (resolved where it is compared). */\nexport const isOuterColumn = (\n value: unknown\n): value is { readonly $row: string; readonly up: number } =>\n isPlainRecord(value) &&\n Object.keys(value).length === 2 &&\n typeof value.$row === \"string\" &&\n Number.isSafeInteger(value.up) &&\n (value.up as number) >= 0;\n\n/** `{ now: true }`: the call's one instant. */\nexport const isInstant = (value: unknown): boolean =>\n isPlainRecord(value) && value.now === true && Object.keys(value).length === 1;\n\nconst REFUSED_CONDITION = `a condition names one control and exactly one of ${TESTS.join(\", \")}`;\n\n/** `$if`'s `{ control, path?, <one test> }` as a condition, or the refusal. */\nfunction conditionOf(spec: unknown): Condition | string {\n if (!isPlainRecord(spec)) return REFUSED_CONDITION;\n const { control, path, ...tests } = spec;\n const [test, ...others] = Object.keys(tests);\n const operand = tests[test!];\n if (\n typeof control !== \"string\" ||\n (path !== undefined && typeof path !== \"string\") ||\n !TESTS.includes(test as (typeof TESTS)[number]) ||\n others.length > 0 ||\n (test === \"exists\" && typeof operand !== \"boolean\") ||\n ((test === \"in\" || test === \"hasSome\") && !Array.isArray(operand))\n )\n return REFUSED_CONDITION;\n return new Condition(\n new Parameter(control, path),\n Object.freeze({ [test!]: operand }) as unknown as ConditionTest\n );\n}\n\n/** The nodes a predicate's markers stand for, as its `where` meets them. */\nconst MARKERS: DomainMarkers = {\n value: (value) => {\n if (isReference(value)) return new Parameter(value.control, value.path);\n if (isOuterColumn(value)) return new OuterColumn(value.$row, value.up);\n return isInstant(value) ? new Parameter() : undefined;\n },\n condition: conditionOf,\n};\n\n/**\n * The path at which `value` contains itself, `undefined` where it does not.\n * Only an object inside its own descendants is refused: a predicate may share\n * sub-objects freely.\n */\nfunction cyclePath(\n value: unknown,\n acyclic: WeakSet<object>,\n ancestors = new Set<object>(),\n path: string[] = []\n): string | undefined {\n if (typeof value !== \"object\" || value === null || acyclic.has(value))\n return undefined;\n // The root has no ancestor: a path is never empty here.\n if (ancestors.has(value)) return path.join(\".\");\n ancestors.add(value);\n for (const [key, item] of Object.entries(value)) {\n path.push(key);\n const found = cyclePath(item, acyclic, ancestors, path);\n if (found !== undefined) return found;\n path.pop();\n }\n ancestors.delete(value);\n // Every descendant was walked: no cycle passes through this object.\n acyclic.add(value);\n return undefined;\n}\n\n/**\n * One definition's `rows` with every predicate admitted, each named predicate\n * once and a mode naming one given its admitted object: refusals are\n * `ClientInitializationError`s naming the extension, the model, the\n * predicate's place in `rows` and the path inside it.\n */\nexport function admitRows(\n rows: RowsContribution,\n schema: Schema,\n extension: string,\n registry: SchemaRegistryLookup<Schema> = standaloneRegistry(schema)\n): RowsContribution {\n const native = Object.values(schema).every((model) => {\n const state: ModelState = model[\"~\"].state;\n return Object.values(state.scalars).every(\n (scalar) => scalar[\"~\"].state.schema === undefined\n );\n });\n const reusable = native && isImmutableRows(rows);\n const entries = reusable ? Object.entries(schema) : undefined;\n /** A cached admission still holds where the schema map is the one it read. */\n const holds = (previous: {\n schema: Schema;\n entries: [string, Schema[string]][];\n }) => {\n const current = Object.entries(schema);\n return (\n previous.schema === schema &&\n current.length === previous.entries.length &&\n current.every(\n ([name, model], index) =>\n name === previous.entries[index]![0] &&\n model === previous.entries[index]![1]\n )\n );\n };\n const previous = reusable ? admittedRows.get(registry)?.get(rows) : undefined;\n if (previous && holds(previous)) return previous.admitted;\n const refuse = (\n name: string,\n place: string,\n at: string,\n reason: string\n ): never => {\n throw new ClientInitializationError(\n `Extension \"${extension}\" rows.${place} at \"${at}\": ${reason}.`,\n { meta: { extension, model: name } }\n );\n };\n // Shared sub-predicates are walked and parsed once per admission, a lazy\n // entry's included.\n const acyclic = new WeakSet<object>();\n const filters: AdmittedFilters = new WeakMap();\n /**\n * `$exists`: one model of the schema and its `where`, admitted with that\n * model's own schema (its markers and depth rules included).\n */\n const markers: DomainMarkers = {\n ...MARKERS,\n exists: (spec) => {\n const models = isPlainRecord(spec) ? Object.keys(spec) : [];\n const [model] = models;\n if (\n models.length !== 1 ||\n !Object.hasOwn(schema, model!) ||\n !isPlainRecord((spec as Record<string, unknown>)[model!])\n )\n return {\n message:\n \"names exactly one model of the schema and the `where` its rows must match\",\n path: [],\n };\n const result = validateSchema(\n registry.getModelSchemas(schema[model!]!).core.where,\n (spec as Record<string, unknown>)[model!]\n );\n if (result.issues) {\n const [issue] = result.issues;\n return {\n message: issue!.message,\n path: [model!, ...(issue!.path ?? [])],\n };\n }\n return new Existence(model!, result.value as Input);\n },\n };\n const admit = (\n name: string,\n place: string,\n predicate: unknown\n ): Record<string, unknown> => {\n const cycle = cyclePath(predicate, acyclic);\n if (cycle !== undefined) refuse(name, place, cycle, \"contains itself\");\n const where = registry.getModelSchemas(schema[name]!).core.where;\n const result = admittingDomainPredicate(\n markers,\n () => validateSchema(where, predicate),\n filters\n );\n if (!result.issues) return result.value as Record<string, unknown>;\n const [issue] = result.issues;\n return refuse(\n name,\n place,\n issue!.path?.map(String).join(\".\") || \"root\",\n issue!.message\n );\n };\n /** The self relations of `name` holding its key: what `acyclic` may name. */\n const selfKeys = (name: string): readonly string[] => {\n const { state } = schema[name]![\"~\"];\n return Object.keys(state.relations).filter((relation) => {\n const held = state.relations[relation]![\"~\"];\n return (\n held.state.foreignKey !== undefined &&\n held.settleTarget() === schema[name]\n );\n });\n };\n const admitAcyclic = (\n name: string,\n place: string,\n relations: readonly string[]\n ): readonly string[] => {\n const allowed = selfKeys(name);\n for (const relation of relations)\n if (!allowed.includes(relation))\n refuse(\n name,\n place,\n `acyclic.${relation}`,\n \"names no to-one relation of the model to itself holding its key\"\n );\n return relations;\n };\n /** One model's `verbs` entry, every predicate admitted and every name checked. */\n const admitVerbs = (name: string, entry: RowsVerbs): RowsVerbs => {\n const place = `verbs.${name}`;\n if (!isPlainRecord(entry))\n refuse(name, place, \"root\", \"is not an object or a function\");\n // Policies may be data built at runtime: a misspelt `writes` would leave\n // its field judged at `update`, which widens the write.\n for (const key of Object.keys(entry))\n if (!Object.hasOwn(VERBS_KEYS, key))\n refuse(\n name,\n place,\n key,\n `is not one of ${Object.keys(VERBS_KEYS).join(\", \")}`\n );\n const { state } = schema[name]![\"~\"];\n const predicates = Object.fromEntries(\n Object.entries(entry.predicates).map(([key, predicate]) => [\n key,\n admit(name, `${place}.predicates.${key}`, predicate),\n ])\n );\n const known = (at: string, predicate: string | undefined) => {\n if (predicate !== undefined && !Object.hasOwn(predicates, predicate))\n refuse(name, place, at, `names unknown predicate \"${predicate}\"`);\n };\n known(\"read\", entry.read);\n known(\"update\", entry.update);\n known(\"delete\", entry.delete);\n known(\"place\", entry.place);\n for (const key of [\"writes\", \"moves\"] as const)\n for (const [field, predicate] of Object.entries(entry[key] ?? {})) {\n if (\n !(\n Object.hasOwn(state.scalars, field) ||\n Object.hasOwn(state.relations, field)\n )\n )\n refuse(name, place, `${key}.${field}`, \"names an unknown field\");\n known(`${key}.${field}`, predicate);\n }\n let cycles: readonly string[] | LazyRelations | undefined;\n const declared = entry.acyclic;\n if (typeof declared === \"function\") {\n let resolved: readonly string[] | undefined;\n cycles = Object.freeze({\n candidates: Object.freeze(selfKeys(name)),\n resolve: () =>\n (resolved ??= Object.freeze([\n ...admitAcyclic(name, place, declared()),\n ])),\n });\n } else if (declared !== undefined)\n cycles = admitAcyclic(name, place, declared);\n const { evidence } = entry;\n if (evidence !== undefined) {\n if (!PROJECTION_KEY.test(evidence.as))\n refuse(name, place, \"evidence.as\", \"is not `$` and an identifier\");\n for (const [index, predicate] of evidence.names.entries())\n known(`evidence.names.${index}`, predicate);\n }\n const keys = entry.reads === undefined ? undefined : keyFields(state);\n for (const [field, predicate] of Object.entries(entry.reads ?? {})) {\n if (!Object.hasOwn(state.scalars, field))\n refuse(name, place, `reads.${field}`, \"names no scalar of the model\");\n // Masked in a caller's operands while identity and joins read it raw,\n // a key would answer through a relation what a filter hides.\n if (keys!.has(field))\n refuse(\n name,\n place,\n `reads.${field}`,\n \"names a key, a unique or a foreign key field\"\n );\n known(`reads.${field}`, predicate);\n }\n return Object.freeze({\n ...entry,\n predicates: Object.freeze(predicates),\n ...(cycles !== undefined && {\n acyclic: cycles as RowsVerbs[\"acyclic\"],\n }),\n });\n };\n /**\n * A lazy entry, admitted the first time it is resolved: once per schema\n * registry when it returns immutable data, else once per admission.\n */\n const lazily = (name: string, entry: () => RowsVerbs): (() => RowsVerbs) => {\n let admitted: RowsVerbs | undefined;\n return resolver(() => {\n if (admitted !== undefined) return admitted;\n const cached = native\n ? admittedLazily.get(registry)?.get(entry)?.get(name)\n : undefined;\n if (cached && holds(cached)) return (admitted = cached.admitted);\n const declared = entry();\n const result = admitVerbs(name, declared);\n if (native && isImmutableEntry(declared)) {\n freezeAdmitted(result);\n let cache = admittedLazily.get(registry);\n if (!cache) {\n cache = new WeakMap();\n admittedLazily.set(registry, cache);\n }\n let models = cache.get(entry);\n if (!models) {\n models = new Map();\n cache.set(entry, models);\n }\n models.set(name, {\n schema,\n entries: Object.entries(schema),\n admitted: result,\n });\n }\n admitted = result;\n return result;\n });\n };\n const verbs: Record<string, RowsVerbs | (() => RowsVerbs)> = {};\n for (const [name, entry] of Object.entries(rows.verbs ?? {})) {\n if (!Object.hasOwn(schema, name))\n refuse(name, `verbs.${name}`, \"root\", \"names an unknown model\");\n verbs[name] =\n typeof entry === \"function\"\n ? lazily(name, entry)\n : admitVerbs(name, entry);\n }\n const models: Record<string, Record<string, object>> = {};\n for (const [name, modes] of Object.entries(rows.models)) {\n const admitted = new Map<string, object>();\n const own = verbs[name];\n for (const [mode, purposes] of Object.entries(modes)) {\n const out: Record<string, unknown> = {};\n for (const purpose of [\"root\", \"related\"] as const) {\n const predicate = purposes[purpose];\n if (predicate === undefined) continue;\n const place = `${name}.${mode}.${purpose}`;\n if (typeof predicate !== \"string\")\n out[purpose] = admit(name, place, predicate);\n else if (typeof own === \"function\")\n // A lazy entry's predicate, named when its model is first needed.\n out[purpose] = resolver(() =>\n Object.hasOwn(own().predicates, predicate)\n ? own().predicates[predicate]\n : refuse(\n name,\n place,\n \"root\",\n `names unknown predicate \"${predicate}\"`\n )\n );\n else if (Object.hasOwn(own?.predicates ?? {}, predicate))\n out[purpose] = own!.predicates[predicate];\n else\n refuse(name, place, \"root\", `names unknown predicate \"${predicate}\"`);\n }\n admitted.set(mode, Object.freeze(out));\n }\n models[name] = Object.freeze(Object.fromEntries(admitted));\n }\n const admitted = Object.freeze({\n ...rows,\n models: Object.freeze(models),\n ...(rows.verbs && { verbs: Object.freeze(verbs) }),\n }) as RowsContribution;\n if (entries) freezeAdmitted(admitted);\n if (entries && isAdmittedRows(admitted)) {\n let cache = admittedRows.get(registry);\n if (!cache) {\n cache = new WeakMap();\n admittedRows.set(registry, cache);\n }\n cache.set(rows, { schema, entries, admitted });\n }\n return admitted;\n}\n","import { ClientInitializationError } from \"@errors\";\nimport {\n type CallRows,\n Condition,\n Existence,\n type LazyRelations,\n type ModelDomain,\n type ModelStamps,\n type ModelVerbs,\n Parameter,\n type RowDomain,\n} from \"@query-engine/raptor3/shared/row-scope\";\nimport type { Input } from \"@query-engine/raptor3/shared/schema\";\nimport { isPlainRecord } from \"@schema/relation/terminal\";\nimport { isImmutableRowData, isInstant, isReference } from \"./admission\";\nimport type { ResolvedControls, ResolvedDeletion } from \"./chain\";\nimport {\n type AdmittedControls,\n type RowsContribution,\n type RowsVerbs,\n rowsModes,\n} from \"./controls\";\nimport type { RuntimeExtensionDefinition } from \"./definition\";\n\ntype Predicates = RowsContribution[\"models\"][string][string];\n\n/** One `rows` member: its control, and where each of its modes sits. */\ninterface BoundRowsMember {\n readonly control: string;\n readonly names: readonly string[];\n readonly modes: ReadonlyMap<unknown, number>;\n readonly fallback: number;\n /** How far one step of this member's mode moves the combination index. */\n readonly stride: number;\n}\n\n/**\n * A chain's row facts, resolved once when an extension is applied: one\n * {@link CallRows} per combination of its `rows` members' modes, with and\n * without the tombstones, each with the chain's `data` stamps, so a call only\n * looks its facts up. The predicates hold the values they read as\n * parameters, prepared once for every call: a call whose combination reads\n * one carries its values beside the shared domains. When a stamp names a\n * control, the call's values are put in its stamps for that call alone.\n */\nexport interface RowsBinding {\n readonly members: readonly BoundRowsMember[];\n readonly deletion: Readonly<Record<string, ResolvedDeletion>>;\n /** Indexed by mode combination: the call writes tombstones. */\n readonly tombstoning: readonly CallRows[];\n /** Indexed by mode combination: the call deletes physically. */\n readonly physical: readonly CallRows[];\n /**\n * Indexed by mode combination: its domain or the default one reads a call\n * value, so its calls carry their values.\n */\n readonly parametric: readonly boolean[];\n /** A stamp names a control: each call puts its values in the stamps. */\n readonly bindsStamps: boolean;\n /** Whether a call must pass a control to touch a model directly. */\n readonly required: RequiredOn;\n}\n\ntype RequiredOn = (control: string, model: string) => boolean;\n\nconst NEVER_REQUIRED: RequiredOn = () => false;\n\nconst NO_DELETION: Readonly<Record<string, ResolvedDeletion>> = Object.freeze(\n Object.create(null)\n);\n\nconst NO_CONTROLS: AdmittedControls = Object.freeze({});\n\n/** A named control the call did not pass. */\nconst ABSENT = Symbol(\"absent\");\n\n/**\n * Every control a definition's values name, at any depth: an admitted\n * predicate's parameters and conditions, and a stamp's references.\n */\nfunction collectReferences(\n value: unknown,\n names: Set<string>,\n // Predicates share sub-predicates freely: each is read once.\n seen = new Set<object>()\n): void {\n if (value instanceof Existence) {\n collectReferences(value.where, names, seen);\n return;\n }\n const parameter = value instanceof Condition ? value.parameter : value;\n if (parameter instanceof Parameter) {\n if (parameter.control !== undefined) names.add(parameter.control);\n } else if (isReference(value)) names.add(value.control);\n else if (Array.isArray(value) || isPlainRecord(value)) {\n if (seen.has(value)) return;\n seen.add(value);\n for (const item of Object.values(value))\n collectReferences(item, names, seen);\n }\n}\n\n// Admission-owned immutable predicates have the same references in every chain.\n// Declarations and the receiving chain's controls are still checked each time.\nconst rowReferences = new WeakMap<RowsContribution, readonly string[]>();\nfunction referencesOfRows(rows: RowsContribution): readonly string[] {\n const cached = rowReferences.get(rows);\n if (cached) return cached;\n const references = new Set<string>();\n const seen = new Set<object>();\n for (const modes of Object.values(rows.models))\n for (const mode of Object.values(modes)) {\n collectReferences(mode.root, references, seen);\n collectReferences(mode.related, references, seen);\n }\n // A lazy entry's references are checked when it is resolved.\n for (const entry of Object.values(rows.verbs ?? {}))\n if (typeof entry !== \"function\")\n collectReferences(entry.predicates, references, seen);\n const names = [...references];\n if (isImmutableRowData(rows)) rowReferences.set(rows, names);\n return names;\n}\n\n/** The controls a stamp's fields name: its own keys are fields, never values. */\nfunction collectStampReferences(\n stamp: Input | undefined,\n names: Set<string>\n): void {\n for (const value of Object.values(stamp ?? {}))\n collectReferences(value, names);\n}\n\n/**\n * The controls a definition names but does not declare; the chain admits\n * those an earlier extension declares.\n */\nexport function undeclaredControlReferencesOf(\n definition: RuntimeExtensionDefinition\n): readonly string[] {\n const declared = new Set(Object.keys(definition.controls ?? {}));\n if (definition.rows) declared.add(definition.rows.control);\n const references = new Set(\n definition.rows ? referencesOfRows(definition.rows) : []\n );\n for (const entry of Object.values(definition.data?.models ?? {})) {\n collectStampReferences(entry.create, references);\n collectStampReferences(entry.update, references);\n }\n for (const name of Object.keys(definition.deletion?.removeWhen ?? {}))\n references.add(name);\n return [...references].filter((name) => !declared.has(name));\n}\n\n/** Whether a domain's predicates read a call value (admission's nodes). */\nfunction readsCall(value: unknown): boolean {\n if (value instanceof Parameter || value instanceof Condition) return true;\n if (value instanceof Existence) return readsCall(value.where);\n if (Array.isArray(value)) return value.some(readsCall);\n return isPlainRecord(value) && Object.values(value).some(readsCall);\n}\n\n/** A stamp's value with the call's put in: itself when it names none. */\nfunction stampValue(\n value: unknown,\n controls: AdmittedControls | undefined\n): unknown {\n if (isReference(value)) {\n let given = controls?.[value.control];\n const { path } = value;\n for (const key of path === undefined ? [] : path.split(\".\")) {\n given =\n isPlainRecord(given) && Object.hasOwn(given, key)\n ? given[key]\n : undefined;\n }\n return given === undefined ? ABSENT : given;\n }\n if (Array.isArray(value)) {\n const items = value.map((item) => stampValue(item, controls));\n if (items.includes(ABSENT)) return ABSENT;\n return items.every((item, index) => item === value[index]) ? value : items;\n }\n if (!isPlainRecord(value)) return value;\n let copy: Record<string, unknown> | undefined;\n for (const [key, item] of Object.entries(value)) {\n const bound = stampValue(item, controls);\n if (bound === ABSENT) return ABSENT;\n if (bound !== item) (copy ??= { ...value })[key] = bound;\n }\n return copy ?? value;\n}\n\n/**\n * A stamp bound: a field whose value names a control the call did not pass is\n * not written. The same object when no field names a control.\n */\nfunction boundStamp(\n stamp: Input | undefined,\n controls: AdmittedControls | undefined\n): Input | undefined {\n if (stamp === undefined) return undefined;\n const values: Record<string, unknown> = {};\n let changed = false;\n for (const [field, value] of Object.entries(stamp)) {\n const bound = stampValue(value, controls);\n changed ||= bound !== value;\n if (bound !== ABSENT) values[field] = bound;\n }\n return changed ? Object.freeze(values) : stamp;\n}\n\n/** Each model's stamps bound; an entry naming no control is kept as is. */\nfunction boundStamps(\n stamps: ReadonlyMap<string, ModelStamps>,\n controls: AdmittedControls | undefined\n): ReadonlyMap<string, ModelStamps> {\n const bound = new Map<string, ModelStamps>();\n for (const [model, entry] of stamps) {\n const create = boundStamp(entry.create, controls);\n const update = boundStamp(entry.update, controls);\n bound.set(\n model,\n create === entry.create && update === entry.update\n ? entry\n : Object.freeze({ create, update })\n );\n }\n return bound;\n}\n\n/** The call's one instant, where a stamp's field writes `{ now: true }`. */\nconst NOW = new Parameter();\n\n/** A stamp with each `{ now: true }` field as {@link NOW}: itself without one. */\nfunction withInstants(stamp: Input | undefined): Input | undefined {\n let copy: Record<string, unknown> | undefined;\n for (const [field, value] of Object.entries(stamp ?? {}))\n if (isInstant(value)) (copy ??= { ...stamp })[field] = NOW;\n return copy === undefined ? stamp : Object.freeze(copy);\n}\n\n/** The chain's `required` declarations as one test, by control and model. */\nfunction requiredOn(controls: ResolvedControls | undefined): RequiredOn {\n const required = new Map<string, true | ReadonlySet<string>>();\n for (const control of controls?.all ?? []) {\n if (control.required !== undefined)\n required.set(control.name, control.required);\n }\n if (required.size === 0) return NEVER_REQUIRED;\n return (control, model) => {\n const on = required.get(control);\n return on === true || on?.has(model) === true;\n };\n}\n\n/**\n * A map whose entries are built the first time they are read: a `rows`\n * member's lazy `verbs` entry is resolved only for a model a call reaches.\n * `has` answers without building; walking the map builds every entry. A\n * build that throws is kept, so the next read throws again: an entry is\n * never read as absent because its build failed.\n */\nclass LazyMap<K, V> extends Map<K, V> {\n readonly #pending: Map<K, () => V>;\n constructor(built: Iterable<readonly [K, V]>, pending: Map<K, () => V>) {\n super(built);\n this.#pending = pending;\n }\n #settle(key: K): void {\n const build = this.#pending.get(key);\n if (build === undefined) return;\n const value = build();\n this.#pending.delete(key);\n super.set(key, value);\n }\n #settleAll(): void {\n for (const key of [...this.#pending.keys()]) this.#settle(key);\n }\n override get(key: K): V | undefined {\n this.#settle(key);\n return super.get(key);\n }\n override has(key: K): boolean {\n return this.#pending.has(key) || super.has(key);\n }\n override get size(): number {\n this.#settleAll();\n return super.size;\n }\n override keys(): MapIterator<K> {\n this.#settleAll();\n return super.keys();\n }\n override values(): MapIterator<V> {\n this.#settleAll();\n return super.values();\n }\n override entries(): MapIterator<[K, V]> {\n this.#settleAll();\n return super.entries();\n }\n override [Symbol.iterator](): MapIterator<[K, V]> {\n return this.entries();\n }\n override forEach(\n callback: (value: V, key: K, map: Map<K, V>) => void,\n thisArg?: unknown\n ): void {\n this.#settleAll();\n super.forEach(callback, thisArg);\n }\n}\n\n/** A map of `built` entries, and of `pending` ones built when first read. */\nfunction lazyMap<K, V>(\n built: Map<K, V>,\n pending: Map<K, () => V>\n): ReadonlyMap<K, V> {\n return pending.size === 0 ? built : new LazyMap(built, pending);\n}\n\n/** What admission leaves in place of a lazy entry's predicate: its resolver. */\ntype Lazy<T> = () => T;\n\n/**\n * One purpose's predicates per model, for one mode of every member, each at\n * its member's place in the chain: the layer the engine reads it as. A mode\n * that named a predicate holds its admitted object; one that named a lazy\n * entry's predicate, its resolver, called when the model is first read.\n */\nfunction modelDomain(\n rows: readonly RowsContribution[],\n modes: readonly string[],\n purpose: keyof Predicates\n): ModelDomain {\n const declared = new Map<string, (Input | Lazy<Input>)[]>();\n for (const [layer, member] of rows.entries()) {\n for (const [model, entry] of Object.entries(member.models)) {\n const where = entry[modes[layer]!]?.[purpose];\n if (where === undefined) continue;\n const list = declared.get(model) ?? [];\n list[layer] = where as Input | Lazy<Input>;\n declared.set(model, list);\n }\n }\n const built = new Map<string, Input[]>();\n const pending = new Map<string, () => Input[]>();\n for (const [model, list] of declared) {\n if (list.some((where) => typeof where === \"function\"))\n pending.set(model, () => {\n const resolved: Input[] = [];\n for (const [layer, where] of list.entries())\n if (where !== undefined)\n resolved[layer] =\n typeof where === \"function\" ? (where as Lazy<Input>)() : where;\n return resolved;\n });\n else built.set(model, list as Input[]);\n }\n return lazyMap(built, pending);\n}\n\n/** `{ OR: [] }`, false: what a verb a model's `verbs` leaves out takes. */\nconst NOTHING: Input = Object.freeze({ OR: Object.freeze([]) });\n\n/** A `writes` or `moves` entry, its names resolved. */\nconst fieldsOf = (\n entry: { readonly [field: string]: string } | undefined,\n named: (name: string) => Input\n): ReadonlyMap<string, Input> =>\n new Map(\n Object.entries(entry ?? {}).map(([field, name]) => [field, named(name)])\n );\n\n/** One layer's admitted entry as the engine reads it. */\nfunction layerVerbs(entry: RowsVerbs): ModelVerbs {\n const named = (name: string | undefined): Input =>\n name === undefined ? NOTHING : entry.predicates[name]!;\n // Admission leaves a lazy `acyclic` as its candidates and resolver.\n const acyclic = entry.acyclic as\n | readonly string[]\n | LazyRelations\n | undefined;\n return Object.freeze({\n read: named(entry.read),\n update: named(entry.update),\n delete: named(entry.delete),\n writes: fieldsOf(entry.writes, named),\n ...(entry.place !== undefined && { place: named(entry.place) }),\n moves: fieldsOf(entry.moves, named),\n acyclic: Array.isArray(acyclic)\n ? Object.freeze([...acyclic])\n : ((acyclic as LazyRelations | undefined) ?? NO_RELATIONS),\n ...(entry.evidence && {\n evidence: Object.freeze({\n as: entry.evidence.as,\n names: Object.freeze(\n entry.evidence.names.map((name) =>\n Object.freeze([name, named(name)] as const)\n )\n ),\n ordered: entry.evidence.ordered === true,\n }),\n }),\n reads: fieldsOf(entry.reads, named),\n });\n}\nconst NO_RELATIONS: readonly string[] = Object.freeze([]);\n\n/**\n * Every member's verbs per model, each at its member's layer, their names\n * resolved to the admitted predicates: the same for every mode combination.\n * A model one member declares lazily is resolved when it is first read.\n */\nfunction modelVerbs(\n rows: readonly RowsContribution[]\n): ReadonlyMap<string, readonly (ModelVerbs | undefined)[]> | undefined {\n const declared = new Map<string, (RowsVerbs | Lazy<RowsVerbs>)[]>();\n for (const [layer, member] of rows.entries())\n for (const [model, entry] of Object.entries(member.verbs ?? {})) {\n const list = declared.get(model) ?? [];\n list[layer] = entry;\n declared.set(model, list);\n }\n const layers = (model: string, list: readonly (RowsVerbs | undefined)[]) => {\n const keys = new Set<string>();\n const verbs: (ModelVerbs | undefined)[] = [];\n for (const [layer, entry] of list.entries()) {\n if (entry === undefined) continue;\n // One projection key, one layer: a second would hide the first.\n const key = entry.evidence?.as;\n if (key !== undefined && keys.has(key))\n throw new ClientInitializationError(\n `rows.verbs.${model}.evidence.as \"${key}\" is declared by two extensions of the chain.`,\n { meta: { model } }\n );\n if (key !== undefined) keys.add(key);\n verbs[layer] = layerVerbs(entry);\n }\n return verbs;\n };\n const built = new Map<string, readonly (ModelVerbs | undefined)[]>();\n const pending = new Map<string, () => readonly (ModelVerbs | undefined)[]>();\n for (const [model, list] of declared) {\n if (list.some((entry) => typeof entry === \"function\"))\n pending.set(model, () =>\n layers(\n model,\n Array.from(list, (entry) =>\n typeof entry === \"function\" ? entry() : entry\n )\n )\n );\n else built.set(model, layers(model, list as RowsVerbs[]));\n }\n if (declared.size === 0) return undefined;\n return lazyMap(built, pending);\n}\n\n/** Whether a member names a lazy entry: its contents are not known yet. */\nexport const isLazy = (member: RowsContribution) =>\n Object.values(member.verbs ?? {}).some(\n (entry) => typeof entry === \"function\"\n );\n\n/**\n * `rows` whose lazy entries check, when resolved, that every control their\n * predicates name is one the chain declared where the extension was\n * applied (`declared`), as an eager entry is checked by `$extends`. The same\n * object when it names no lazy entry.\n */\nexport function checkingLazyReferences(\n rows: RowsContribution,\n declared: (control: string) => boolean,\n refuse: (control: string) => never\n): RowsContribution {\n if (!isLazy(rows)) return rows;\n const checked = new Map<string, Lazy<RowsVerbs>>();\n const verbs = Object.fromEntries(\n Object.entries(rows.verbs!).map(([model, entry]) => {\n if (typeof entry !== \"function\") return [model, entry];\n let resolved: RowsVerbs | undefined;\n const check = () => {\n if (resolved !== undefined) return resolved;\n const admitted = entry();\n for (const control of verbsReferences(admitted))\n if (!declared(control)) refuse(control);\n resolved = admitted;\n return admitted;\n };\n checked.set(model, check);\n return [model, check];\n })\n );\n // A mode naming a lazy predicate reaches it through the checked entry.\n const models = Object.fromEntries(\n Object.entries(rows.models).map(([model, modes]) => {\n const check = checked.get(model);\n if (check === undefined) return [model, modes];\n return [\n model,\n Object.fromEntries(\n Object.entries(modes).map(([mode, purposes]) => [\n mode,\n Object.fromEntries(\n Object.entries(purposes).map(([purpose, where]) => [\n purpose,\n typeof where === \"function\"\n ? () => {\n check();\n return (where as Lazy<Input>)();\n }\n : where,\n ])\n ),\n ])\n ),\n ];\n })\n );\n const checking = Object.freeze({\n ...rows,\n models,\n verbs: Object.freeze(verbs),\n });\n origins.set(checking, rows);\n return checking;\n}\n/** The admitted rows a chain's checking copy stands for: the same content. */\nconst origins = new WeakMap<RowsContribution, RowsContribution>();\nexport const admittedRowsOf = (rows: RowsContribution) =>\n origins.get(rows) ?? rows;\n\n// An admitted entry's references, read once: it is immutable once admitted.\nconst entryReferences = new WeakMap<RowsVerbs, readonly string[]>();\nfunction verbsReferences(entry: RowsVerbs): readonly string[] {\n const known = entryReferences.get(entry);\n if (known) return known;\n const names = new Set<string>();\n collectReferences(entry.predicates, names);\n const list = [...names];\n if (Object.isFrozen(entry)) entryReferences.set(entry, list);\n return list;\n}\n\nexport function bindRows(\n rows: readonly RowsContribution[] | undefined,\n deletion: Readonly<Record<string, ResolvedDeletion>> | undefined,\n data?: Readonly<Record<string, ModelStamps>>,\n controls?: ResolvedControls\n): RowsBinding {\n const declared = rows ?? [];\n let stride = 1;\n const members = declared.map((member): BoundRowsMember => {\n const modes = rowsModes(member);\n const bound = {\n control: member.control,\n names: modes,\n modes: new Map<unknown, number>(\n modes.map((mode, index) => [mode, index])\n ),\n fallback: modes.indexOf(member.default),\n stride,\n };\n stride *= modes.length;\n return bound;\n });\n const domains: RowDomain[] = [];\n const verbs = modelVerbs(declared);\n // Whether a model may project: a lazy entry may, until it is read.\n const projects = declared.some((member) =>\n Object.values(member.verbs ?? {}).some(\n (entry) =>\n typeof entry === \"function\" ||\n entry.evidence !== undefined ||\n Object.keys(entry.reads ?? {}).length > 0\n )\n );\n for (let combination = 0; combination < stride; combination++) {\n const modes = members.map(\n (member) =>\n member.names[\n Math.floor(combination / member.stride) % member.names.length\n ]!\n );\n domains.push(\n Object.freeze({\n root: modelDomain(declared, modes, \"root\"),\n related: modelDomain(declared, modes, \"related\"),\n ...(verbs && { verbs, projects }),\n })\n );\n }\n const defaults =\n domains[\n members.reduce(\n (index, member) => index + member.fallback * member.stride,\n 0\n )\n ]!;\n const tombstones =\n deletion === undefined ? undefined : new Map(Object.entries(deletion));\n const stamps =\n data === undefined\n ? undefined\n : new Map(\n Object.entries(data).map(([model, entry]) => {\n const create = withInstants(entry.create);\n const update = withInstants(entry.update);\n return [\n model,\n create === entry.create && update === entry.update\n ? entry\n : Object.freeze({ create, update }),\n ] as const;\n })\n );\n const stampReferences = new Set<string>();\n for (const entry of stamps?.values() ?? []) {\n collectStampReferences(entry.create, stampReferences);\n collectStampReferences(entry.update, stampReferences);\n }\n const physical = domains.map((domain) =>\n Object.freeze({ domain, defaults, ...(stamps && { stamps }) })\n );\n // A lazy entry's predicates are not known yet: its calls carry their values.\n const lazy = declared.some(isLazy);\n const verbsRead =\n lazy ||\n declared.some((member) =>\n Object.values(member.verbs ?? {}).some(\n (entry) => typeof entry !== \"function\" && readsCall(entry.predicates)\n )\n );\n const reads = (domain: RowDomain) =>\n verbsRead ||\n [domain.root, domain.related].some((models) =>\n [...models.values()].some(readsCall)\n );\n return Object.freeze({\n members,\n deletion: deletion ?? NO_DELETION,\n physical,\n tombstoning:\n tombstones === undefined\n ? physical\n : physical.map((facts) => Object.freeze({ ...facts, tombstones })),\n parametric: domains.map((domain) => reads(domain) || reads(defaults)),\n bindsStamps: stampReferences.size > 0,\n required: requiredOn(controls),\n });\n}\n\n/**\n * One call's row facts, from the controls it admitted: the modes its `rows`\n * controls chose (an absent one reads as its default), and whether it deletes\n * physically — its model's `deletion` entry names a `removeWhen` the call's\n * controls match. That control is placed only on the deletes of the models\n * the entry manages, so no other call can match it. When its predicates read\n * a call value, the call carries its controls; when a stamp names a control,\n * the call's values are put in.\n */\nexport function callRows(\n binding: RowsBinding,\n model: string,\n controls: AdmittedControls | undefined\n): CallRows {\n let combination = 0;\n for (const member of binding.members) {\n combination +=\n member.stride *\n (member.modes.get(controls?.[member.control]) ?? member.fallback);\n }\n const removeWhen = binding.deletion[model]?.removeWhen;\n const physical =\n removeWhen !== undefined &&\n Object.entries(removeWhen).every(\n ([control, value]) => controls?.[control] === value\n );\n const facts = (physical ? binding.physical : binding.tombstoning)[\n combination\n ]!;\n const parametric = binding.parametric[combination]!;\n if (!(parametric || binding.bindsStamps)) return facts;\n return Object.freeze({\n ...facts,\n ...(parametric && {\n values: Object.freeze({\n controls: controls ?? NO_CONTROLS,\n required: binding.required,\n }),\n }),\n ...(binding.bindsStamps && {\n stamps: boundStamps(facts.stamps!, controls),\n }),\n });\n}\n"],"mappings":"oYAmBA,MAAa,EAAsB,eAiCtB,EAA+C,OAAO,OAAO,CACxE,MAAO,OAAO,OAAO,CACnB,OAAQ,OAAO,OAAO,CACpB,YAAa,OAAO,OAAO,CACzB,QAAS,EACT,OAAQ,SACR,SAAW,GACT,OAAO,OAAO,CACZ,MAAO,sBAAsB,CAAC,0BAA0B,EAAM,CAC/D,CAAC,CACL,CAAC,CACH,CAAC,CACF,GAAI,SACL,CAAC,CACH,CAAC,CA4BI,EAAsB,IAAI,QAI1B,EAAqB,IAAI,QAIzB,EAAsB,IAAI,QAIhC,IAAI,EAGJ,SAAgB,2BACd,EACA,EACA,EACM,CACN,EAAU,EACV,EAAoB,IA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OAAO,CACpB,SAAU,GAAY,EACtB,SAAU,EAAQ,SACnB,CAAC,CACH,CACD,GAAI,EAAQ,aAAe,CACzB,OAAQ,YAAY,EAAM,OAAS,EAAS,CAC7C,CACF,CAAC,CAZ+C"}
1
+ {"version":3,"file":"rows-YyvK9MDz.mjs","names":["requiredOn","#keys","#model","#where","previous","models","admitted","#pending","#settle","#settleAll"],"sources":["../src/cache/capability.ts","../src/query-engine/routed-operations.ts","../src/extensions/controls.ts","../src/query-engine/raptor3/shared/row-scope.ts","../src/extensions/admission.ts","../src/extensions/rows.ts"],"sourcesContent":["// The part of the official cache the core client reads on every operation:\n// whether a chain carries the cache, and a handle on the cache runtime. The\n// runtime itself (cache driver, cache flow, result codecs) is installed by\n// `cache()` from `viborm/cache`, so an application that never creates the\n// extension does not load it. A chain can only carry the capability after\n// `cache()` ran, which is what makes `officialCacheRuntime()` total wherever\n// the core asks for it.\n\nimport type { ResolvedExtensionChain } from \"@extensions/chain\";\nimport type { StandardSchemaV1 } from \"@standard-schema/spec\";\nimport type {\n GenericQueryHandler,\n OfficialGenericQueryHandler,\n} from \"@extensions/query\";\nimport { isFunction } from \"@validation/value-guards\";\nimport type { CacheDriver, WaitUntilFn } from \"./driver\";\nimport type { OfficialCacheRuntime } from \"./runtime\";\nimport type { CacheInvalidationOptions } from \"./schema\";\n\nexport const OFFICIAL_CACHE_NAME = \"viborm.cache\";\n\n/** The exact official query contribution. It is recognized by identity. */\nexport type OfficialCacheQueryContribution = OfficialGenericQueryHandler & {\n bind(thisArg: unknown): GenericQueryHandler;\n};\n\n/**\n * A mutation's `cache` argument is the cache's declared control (ruling 7):\n * core removes and admits it before request handlers run, through the cache's\n * own parser, so a malformed value is still a `CacheConfigurationError`.\n */\nexport type OfficialCacheControls = {\n readonly cache: {\n readonly schema: StandardSchemaV1<CacheInvalidationOptions>;\n readonly on: \"writes\";\n };\n};\n\n/** The official value accepted by the dedicated `$extends` overload. */\nexport type OfficialCacheExtension = {\n readonly name: typeof OFFICIAL_CACHE_NAME;\n readonly query: OfficialCacheQueryContribution;\n readonly controls: OfficialCacheControls;\n};\n\n/**\n * The cache's one declaration. The chain places it for any definition carrying\n * the cache's query, whatever `controls` that definition spells: the query is\n * the cache's identity, so its control cannot be forged or left out. It lives\n * here, in the part core always loads, and admits through the runtime: a chain\n * carries the cache only after `cache()` installed that runtime.\n */\nexport const officialCacheControls: OfficialCacheControls = Object.freeze({\n cache: Object.freeze({\n schema: Object.freeze({\n \"~standard\": Object.freeze({\n version: 1,\n vendor: \"viborm\",\n validate: (value: unknown) =>\n Object.freeze({\n value: officialCacheRuntime().admitMutationCacheOptions(value),\n }),\n }),\n }),\n on: \"writes\",\n }),\n});\n\n/**\n * What `cache()` knows before it meets a client: no scope, because the scope\n * partitions on facts (dialect, SQL namespace) that only a concrete driver\n * carries. One definition may be appended to several clients.\n */\nexport interface OfficialCacheDefinitionCapability {\n readonly driver: CacheDriver;\n readonly version: string | number | undefined;\n readonly waitUntil: WaitUntilFn | undefined;\n}\n\n/** The definition once bound to one client's driver, gaining its scope. */\nexport interface OfficialCacheCapability\n extends OfficialCacheDefinitionCapability {\n readonly scope: object;\n}\n\n/**\n * The two driver facts the scope derives from. Structural, so the cache holds\n * no driver reference and no import edge back into `src/drivers`.\n */\nexport interface OfficialCacheBindTarget {\n readonly dialect: string;\n readonly adapter: { readonly namespace?: string | undefined };\n}\n\nconst capabilitiesByQuery = new WeakMap<\n CallableFunction,\n OfficialCacheDefinitionCapability\n>();\nconst definitionsByChain = new WeakMap<\n ResolvedExtensionChain,\n OfficialCacheDefinitionCapability\n>();\nconst capabilitiesByChain = new WeakMap<\n ResolvedExtensionChain,\n OfficialCacheCapability\n>();\nlet runtime: OfficialCacheRuntime | undefined;\n\n/** Recognize `query` as the official cache's contribution. `cache()` only. */\nexport function registerOfficialCacheQuery(\n query: CallableFunction,\n capability: OfficialCacheDefinitionCapability,\n installed: OfficialCacheRuntime\n): void {\n runtime = installed;\n capabilitiesByQuery.set(query, capability);\n}\n\n/** Make the cache runtime reachable; `viborm/cache` does this as it loads. */\nexport function installOfficialCacheRuntime(\n installed: OfficialCacheRuntime\n): void {\n runtime = installed;\n}\n\n/** The cache runtime; reachable only where a chain carries the cache. */\nexport function officialCacheRuntime(): OfficialCacheRuntime {\n if (runtime === undefined)\n throw new Error(\n \"The official cache runtime is not loaded: import cache() from viborm/cache.\"\n );\n return runtime;\n}\n\nexport function getOfficialCacheQueryCapability(\n query: unknown\n): OfficialCacheDefinitionCapability | undefined {\n return isFunction(query) ? capabilitiesByQuery.get(query) : undefined;\n}\n\n/**\n * The definition carried by this chain, scope or no scope. Generic\n * extension-chain code sees only this: admission, duplicate refusal, and\n * propagation are all decisions about the DEFINITION, and none of them may\n * depend on whether a client has bound it yet.\n */\nexport function getOfficialCacheChainDefinition(\n chain: ResolvedExtensionChain | undefined\n): OfficialCacheDefinitionCapability | undefined {\n return chain === undefined ? undefined : definitionsByChain.get(chain);\n}\n\n/** The bound capability: present only after a client composition root bound it. */\nexport function getOfficialCacheChainCapability(\n chain: ResolvedExtensionChain | undefined\n): OfficialCacheCapability | undefined {\n return chain === undefined ? undefined : capabilitiesByChain.get(chain);\n}\n\nexport function registerOfficialCacheChain(\n chain: ResolvedExtensionChain,\n capability: OfficialCacheDefinitionCapability\n): void {\n definitionsByChain.set(chain, capability);\n}\n\n/** Publish the capability the runtime bound for one chain. */\nexport function setOfficialCacheChainCapability(\n chain: ResolvedExtensionChain,\n capability: OfficialCacheCapability\n): void {\n capabilitiesByChain.set(chain, capability);\n}\n\n/**\n * Bind one resolved chain's cache definition to the concrete client driver,\n * deriving the scope that partitions its storage.\n *\n * Called by the client composition root — the one place that holds both the\n * resolved chain and the driver — and only for a chain that carries the\n * official cache, so an ordinary extension costs nothing here.\n */\nexport function bindOfficialCacheChain(\n chain: ResolvedExtensionChain,\n target: OfficialCacheBindTarget\n): void {\n if (definitionsByChain.get(chain) === undefined) return;\n officialCacheRuntime().bindChain(chain, target);\n}\n\n/** Whether an operation runs under the official cache's managed execution. */\nexport function isCacheManagedExecution(\n options: { readonly skipSpan?: boolean } | undefined\n): boolean {\n return options?.skipSpan === true;\n}\n","import type { Operations } from \"@client/types\";\n\n/**\n * The client operation vocabulary, retained at the C-01 cutover.\n *\n * These four names are the only part of the deleted shipped routing module that\n * owners OUTSIDE the engine consume: the client (`isWriteOperation`), the\n * official cache (`isWriteOperation`), the extension surface\n * (`ROUTED_OPERATIONS`) and the query-interception seam (`isReadOperation`).\n * The text below is the deleted `write-engine/routing.ts` definitions verbatim,\n * so no operation changes classification at the cutover.\n */\n\nconst READ_OPERATIONS: ReadonlySet<string> = new Set([\n \"findMany\",\n \"findUnique\",\n \"findFirst\",\n \"findUniqueOrThrow\",\n \"findFirstOrThrow\",\n \"count\",\n \"aggregate\",\n \"groupBy\",\n \"exist\",\n]);\n\n/** Whether a public operation routes through the engine's read owner. */\nexport function isReadOperation(operation: string): boolean {\n return READ_OPERATIONS.has(operation);\n}\n\n/**\n * The operation names the engine owns a construction path for. Every client\n * operation family is here; a name outside it (there is none on the client path)\n * resolves to `undefined`.\n */\nexport const ROUTED_OPERATIONS: ReadonlySet<string> = new Set([\n ...READ_OPERATIONS,\n \"create\",\n \"update\",\n \"delete\",\n \"upsert\",\n \"createMany\",\n \"updateMany\",\n \"deleteMany\",\n]);\n\n/** Whether a public operation routes through the engine's write owner. */\nexport function isWriteOperation(operation: string): boolean {\n return ROUTED_OPERATIONS.has(operation) && !isReadOperation(operation);\n}\n\n/**\n * The verb an `…OrThrow` operation shares its whole envelope with: its schema,\n * its admission and its result. Every other verb is its own base.\n */\nexport function baseOperation(\n operation: Operations\n): Exclude<Operations, \"findUniqueOrThrow\" | \"findFirstOrThrow\"> {\n if (operation === \"findUniqueOrThrow\") return \"findUnique\";\n if (operation === \"findFirstOrThrow\") return \"findFirst\";\n return operation;\n}\n","import { isCanonicalKeyData } from \"@cache/key\";\nimport type {\n CacheableOperations,\n MutationOperations,\n Operations,\n} from \"@client/types\";\nimport {\n ClientInitializationError,\n QueryError,\n ValidationError,\n VibORMError,\n} from \"@errors\";\nimport {\n isReadOperation,\n isWriteOperation,\n ROUTED_OPERATIONS,\n} from \"@query-engine/routed-operations\";\nimport type { Operation } from \"@query-engine/types\";\nimport type { StandardSchemaV1 } from \"@standard-schema/spec\";\nimport { isFunction, isRecord } from \"@validation/value-guards\";\nimport { errorCause } from \"../errors/diagnostic-safety\";\nimport type { ControlLiteral, RuntimeExtensionDefinition } from \"./definition\";\n\n// =============================================================================\n// DEFINITION MEMBERS: plain data, checked by TypeScript only\n// =============================================================================\n\n/** The operations a declared control is accepted on. */\nexport type ControlPlacement =\n | \"reads\"\n | \"writes\"\n | \"all\"\n | readonly Operations[];\n\n/**\n * One argument an extension declares. Its values are a closed list or a\n * Standard Schema; `on` names the operations that accept it (every operation\n * when absent). With `required`, a call on one of those operations that does\n * not pass it is refused, on the models the extension names in `rows`,\n * `data` or `deletion` only; an extension that names no model asks for it on\n * every model. With `bound`, it is accepted only from a binding (the client\n * scope's `$bind`), never from a call's arguments: its placement reads no\n * argument, so a call that passes it is refused as passing an unknown key.\n * With `uncacheable`, a read that holds a value of it is never served from\n * the cache: `$withCache` on that read is refused before any statement. A\n * value held in a variable keeps its literal type only with `as const`, as a\n * held enum clause does.\n */\nexport type ControlDeclaration = (\n | { readonly oneOf: readonly (string | number | boolean)[] }\n | { readonly schema: StandardSchemaV1 }\n) & {\n readonly on?: ControlPlacement;\n readonly required?: boolean;\n readonly bound?: boolean;\n readonly uncacheable?: boolean;\n};\n\nexport type ControlsContribution = {\n readonly [name: string]: ControlDeclaration;\n};\n\n/** Constant scalar `where` or `data` fields of one model. */\ntype ScalarFields = { readonly [field: string]: unknown };\n\n/**\n * Which rows an operation sees. `control` names the call argument that picks\n * a mode; every model entry declares the same mode names, `default` among\n * them. `root` filters the call's own candidates, `related` rows reached\n * through a relation; each is a model's `where`, admitted once when the\n * extension is applied, or the name of one of its `verbs` predicates. Where a\n * filter takes a value, `{ control: \"<name>\", path?: \"a.b\" }` takes the value\n * the call passed for that control (or a field of it), `{ now: true }` the\n * call's instant, and `{ $if: … }` tests a call value. An absent value\n * (`null` included) matches nothing where its control is required, and drops\n * its filter where it is not.\n *\n * `verbs` judges, per model, what a call may do to the rows it sees: a mode\n * only narrows them (R8). A model's entry may be a function returning it:\n * it is called when a call of the chain first needs that model, and its\n * entry admitted then, so a refusal of it fails that call instead of\n * `$extends`. A function returning deeply frozen plain data is called once\n * per schema; one returning anything else, once per client.\n */\nexport type RowsContribution = {\n readonly control: string;\n readonly default: string;\n readonly models: {\n readonly [model: string]: {\n readonly [mode: string]: {\n readonly root?: ScalarFields | string;\n readonly related?: ScalarFields | string;\n };\n };\n };\n readonly verbs?: {\n readonly [model: string]: RowsVerbs | (() => RowsVerbs);\n };\n};\n\n/**\n * One model's named predicates, each a `where` admitted once, and the verbs\n * that take them. `read` ANDs with every mode's `root` and `related`; a write\n * takes its verb's beside them: a delete `delete`'s, an update, for each\n * field its data writes, that field's `writes` entry, else `update`'s, and\n * `update`'s when its data writes only stamps. A join row's change is a write\n * of the relation on both rows it links; a row only addressed to reach its\n * children is read. A verb left out matches nothing.\n *\n * The row a write produces is judged too, as a value, against the rows as\n * they stand before the write, inside the statement that writes it (R4): a\n * created row at `place` (a model naming none is not judged on create); an\n * updated row at the predicates that judged its old row, and, for each field\n * its data writes, at that field's `moves` entry, and where it writes the\n * key of an `acyclic` relation (a to-one relation of the model to itself),\n * outside its own subtree. `acyclic` may be a function returning that list:\n * it is called the first time an update writes the key of one of the\n * model's self relations. A refused row is written by no statement.\n *\n * `evidence` declares a projection key (`evidence.as`) a `select` or\n * `include` may name at every depth, on reads and on the rows a write\n * returns: per row, whether each of `names` holds there beside `read`, or,\n * `ordered`, the last of them that holds (`null` on a row `read` does not\n * hold). `reads` gates a field on a predicate: the row carries it only where\n * `read` and that predicate hold, a `select` naming it fails on a row\n * without them, and every operand a call writes over it (`where`, `orderBy`,\n * aggregates, `distinct`, unique lookups, relation filters) reads it as\n * absent there. A key or foreign-key field is never gated.\n */\nexport type RowsVerbs = {\n readonly predicates: { readonly [name: string]: ScalarFields };\n readonly read?: string;\n readonly update?: string;\n readonly delete?: string;\n readonly writes?: { readonly [field: string]: string };\n readonly place?: string;\n readonly moves?: { readonly [field: string]: string };\n readonly acyclic?: readonly string[] | (() => readonly string[]);\n readonly evidence?: {\n readonly as: string;\n readonly names: readonly string[];\n readonly ordered?: boolean;\n };\n readonly reads?: { readonly [field: string]: string };\n};\n\n/**\n * What a delete does on the models named here: an update that stamps `at`\n * with the call's time and writes `assign`, unless the call's controls match\n * `removeWhen`.\n */\nexport type DeletionContribution = {\n readonly removeWhen?: {\n readonly [control: string]: string | number | boolean;\n };\n readonly models: {\n readonly [model: string]: {\n readonly at?: string;\n readonly assign?: ScalarFields;\n };\n };\n};\n\n/**\n * Fields an extension writes on the models named here: `create` on every\n * create of the model, `update` on every update of it, a soft delete's\n * included. A value is a constant, `{ control: \"<name>\", path?: \"a.b\" }` for\n * the value the call passed for that control or a field of it (a call that\n * passed none writes nothing there), `{ now: true }` for the call's instant,\n * or, on `update`, one of the field's update operators (`{ increment: 1 }`). A field is written only where the caller left it\n * out: a call that writes it itself, or writes the relation whose foreign key\n * holds it, keeps its own value there. A create may leave out such a field\n * even where the schema requires it: the call's data is checked with it\n * counted as given. When the model names here are known to the types\n * (written out, or kept by a `const` type parameter, not a plain\n * `string[]`), the extended client's types agree, nested creates included:\n * the field is optional on a create. When two extensions name a field, the\n * later one writes it, and a value the caller writes wins over both.\n */\nexport type DataContribution = {\n readonly models: {\n readonly [model: string]: {\n readonly create?: ScalarFields;\n readonly update?: ScalarFields;\n };\n };\n};\n\n// =============================================================================\n// CONTROL STATE: what a chain's controls add to each (model, operation)\n// =============================================================================\n\n/** Operations that select candidates: where a rows control is accepted. */\ntype CandidateOperations = Exclude<Operations, \"create\" | \"createMany\">;\n\n/** One declared control as the delegates see it. */\nexport interface PlacedControl<\n Value = unknown,\n Models = PropertyKey,\n Placed = Operations,\n> {\n readonly value: Value;\n readonly models: Models;\n readonly operations: Placed;\n}\n\nexport type NoControls = Record<never, never>;\n\ntype ControlValue<Declaration> = Declaration extends {\n readonly oneOf: readonly (infer Value)[];\n}\n ? Value\n : Declaration extends { readonly schema: StandardSchemaV1<infer Input> }\n ? Input\n : never;\n\ntype PlacementOperations<On> = On extends \"reads\"\n ? CacheableOperations\n : On extends \"writes\"\n ? MutationOperations\n : On extends readonly (infer Operation)[]\n ? Operation\n : Operations;\n\n/**\n * `deletion` places the control `removeWhen` names: on the deletes of the\n * models it manages, whatever the declaration's `on` says.\n */\ntype PlaceControl<Name, Declaration, Deletion> = Deletion extends {\n readonly removeWhen: infer RemoveWhen;\n readonly models: infer Managed;\n}\n ? Name extends keyof RemoveWhen\n ? PlacedControl<\n ControlValue<Declaration>,\n keyof Managed,\n \"delete\" | \"deleteMany\"\n >\n : PlaceFreeControl<Declaration>\n : PlaceFreeControl<Declaration>;\n\ntype PlaceFreeControl<Declaration> = PlacedControl<\n ControlValue<Declaration>,\n PropertyKey,\n PlacementOperations<\n Declaration extends { readonly on: infer On } ? On : \"all\"\n >\n>;\n\ntype DeclaredControls<Definition> = Definition extends {\n readonly controls: infer Controls extends ControlsContribution;\n}\n ? {\n readonly [Name in keyof Controls as Controls[Name] extends {\n readonly bound: true;\n }\n ? never\n : Name]: PlaceControl<\n Name,\n Controls[Name],\n Definition extends { readonly deletion: infer Deletion }\n ? Deletion\n : unknown\n >;\n }\n : NoControls;\n\n/** Every model entry declares the same mode names: those are the values. */\ntype RowsModes<Rows extends RowsContribution> =\n | Rows[\"default\"]\n | {\n [Model in keyof Rows[\"models\"]]: keyof Rows[\"models\"][Model];\n }[keyof Rows[\"models\"]];\n\n/** The rows control: every candidate-selecting operation of every model. */\ntype RowsControl<Definition> = Definition extends {\n readonly rows: infer Rows extends RowsContribution;\n}\n ? {\n readonly [Name in Rows[\"control\"]]: PlacedControl<\n RowsModes<Rows>,\n PropertyKey,\n CandidateOperations\n >;\n }\n : NoControls;\n\n/**\n * The models one definition's `rows` can hide from a relation read: its\n * `models` and `verbs` keys. A to-one relation that targets one of them reads `null` when\n * its target is hidden, so the result types widen it (`result-types.ts`).\n */\nexport type RowsModels<Definition> = Definition extends {\n readonly rows: infer Rows extends RowsContribution;\n}\n ? Extract<\n | keyof Rows[\"models\"]\n | (Rows extends { readonly verbs: infer Verbs } ? keyof Verbs : never),\n string\n >\n : never;\n\n/** The controls one definition places, keyed by control name. */\nexport type DefinitionControls<Definition> = DeclaredControls<Definition> &\n RowsControl<Definition>;\n\n/** The optional control arguments one (model, operation) accepts. */\nexport type OperationControls<Controls, ModelName, Operation> = {\n readonly [Name in keyof Controls as Controls[Name] extends PlacedControl<\n unknown,\n infer Models,\n infer Placed\n >\n ? ModelName extends Models\n ? Operation extends Placed\n ? Name\n : never\n : never\n : never]?: Controls[Name] extends PlacedControl<infer Value>\n ? Value\n : never;\n};\n\n// =============================================================================\n// DATA STATE: the fields a chain's `data` writes, per model\n// =============================================================================\n\n/**\n * The fields one `data` entry writes on its models' creates: there they may\n * be left out even where the schema requires them. An update's fields need\n * nothing, as every field of an update is optional already.\n */\nexport interface StampedFields<Models = PropertyKey, Fields = PropertyKey> {\n readonly models: Models;\n readonly fields: Fields;\n}\n\ntype CreateStamps<Model, Entry> = \"create\" extends keyof Entry\n ? Entry extends { readonly create?: infer Fields }\n ? StampedFields<Model, keyof NonNullable<Fields>>\n : never\n : never;\n\n/**\n * What one definition's `data` writes on creates: one member per model. A\n * definition whose model names are lost (`{ [model: string]: ... }`, as a\n * recipe called with a plain `string[]` builds) writes nothing the types can\n * name: its required fields stay required in the payloads.\n */\nexport type DefinitionData<Definition> = Definition extends {\n readonly data: { readonly models: infer Models };\n}\n ? string extends keyof Models\n ? never\n : {\n [Model in keyof Models]: CreateStamps<Model, Models[Model]>;\n }[keyof Models]\n : never;\n\n/** The fields a chain writes on every create of one model. */\nexport type StampedFieldNames<Data, ModelName> =\n Data extends StampedFields<infer Models, infer Fields extends PropertyKey>\n ? ModelName extends Models\n ? Fields\n : never\n : never;\n\n// =============================================================================\n// PLACEMENT: where each declared control is accepted\n// =============================================================================\n\n/** Where a control goes when its declaration names a placement. */\nconst PLACEMENTS: Readonly<\n Record<\"reads\" | \"writes\" | \"all\", ReadonlySet<string>>\n> = {\n reads: new Set([...ROUTED_OPERATIONS].filter(isReadOperation)),\n writes: new Set([...ROUTED_OPERATIONS].filter(isWriteOperation)),\n all: ROUTED_OPERATIONS,\n};\n\n/** Every operation that selects candidates: where a `rows` control goes. */\nconst CANDIDATE_OPERATIONS: ReadonlySet<string> = new Set(\n [...ROUTED_OPERATIONS].filter(\n (operation) => operation !== \"create\" && operation !== \"createMany\"\n )\n);\n\n/** Where a `deletion.removeWhen` control goes, on the models it manages. */\nconst DELETE_OPERATIONS: ReadonlySet<string> = new Set([\n \"delete\",\n \"deleteMany\",\n]);\n\n/** One control of a chain: its owner, its placement and how a value is admitted. */\nexport interface ResolvedControl {\n readonly name: string;\n readonly extension: string;\n readonly declaration: ControlDeclaration;\n /** The operations that accept it. */\n readonly operations: ReadonlySet<string>;\n /** The models that accept it; every model when absent. */\n readonly models?: ReadonlySet<string>;\n /**\n * Where a call that does not pass it is refused: on every model that\n * accepts it (`true`), on these models only, or nowhere when absent.\n */\n readonly required?: true | ReadonlySet<string>;\n /** What an absent argument admits: the `rows` control's default mode. */\n readonly fallback?: ControlLiteral;\n /** Accepted only from a binding, never read from the arguments. */\n readonly bound?: true;\n /** A read holding a value of it is not served from the cache. */\n readonly uncacheable?: true;\n}\n\n/**\n * Give every control of one definition its placement. A control\n * `deletion.removeWhen` names goes on the deletes of the models `deletion`\n * manages; the `rows` control on every candidate-selecting operation of every\n * model, its values the mode names; every other control where its own `on`\n * says (every operation without one), on every model. A `required` control\n * is asked for only on the models the definition names in `rows`, `data` or\n * `deletion`, and on every model when it names none.\n */\nexport function placeControls(\n definition: RuntimeExtensionDefinition\n): readonly ResolvedControl[] {\n const placed: ResolvedControl[] = [];\n const { name: extension, controls, rows, deletion, data } = definition;\n const removeWhen = deletion?.removeWhen ?? {};\n const managed = new Set(Object.keys(deletion?.models ?? {}));\n const named = new Set([\n ...managed,\n ...Object.keys(rows?.models ?? {}),\n ...Object.keys(rows?.verbs ?? {}),\n ...Object.keys(data?.models ?? {}),\n ]);\n const requiredOn = named.size === 0 ? true : named;\n for (const [name, declaration] of Object.entries(controls ?? {})) {\n const removes = Object.hasOwn(removeWhen, name);\n placed.push({\n name,\n extension,\n declaration,\n operations: removes ? DELETE_OPERATIONS : placementOf(declaration.on),\n models: removes ? managed : undefined,\n required: declaration.required === true ? requiredOn : undefined,\n ...(declaration.bound === true && { bound: true }),\n ...(declaration.uncacheable === true && { uncacheable: true }),\n });\n }\n if (rows !== undefined) {\n placed.push({\n name: rows.control,\n extension,\n declaration: Object.freeze({ oneOf: Object.freeze(rowsModes(rows)) }),\n operations: CANDIDATE_OPERATIONS,\n fallback: rows.default,\n });\n }\n return placed;\n}\n\nfunction placementOf(on: ControlDeclaration[\"on\"]): ReadonlySet<string> {\n if (on === undefined) return ROUTED_OPERATIONS;\n return typeof on === \"string\" ? PLACEMENTS[on] : new Set<string>(on);\n}\n\n/**\n * The `rows` control's values: the mode names, which every model entry\n * declares alike, or the default alone when no model is named.\n */\nexport function rowsModes(rows: RowsContribution): readonly string[] {\n const [modes] = Object.values(rows.models);\n return modes === undefined ? [rows.default] : Object.keys(modes);\n}\n\n// =============================================================================\n// ADMISSION: one call's controls, removed and validated once\n// =============================================================================\n\n/**\n * The controls one call admitted, by name. A `rows` control is resolved to its\n * mode, so an absent one reads as its default; an absent plain control is not\n * here.\n */\nexport type AdmittedControls = Readonly<Record<string, unknown>>;\n\nexport interface ControlAdmission {\n /** The arguments without their controls; the input itself when none was given. */\n readonly args: Record<string, unknown>;\n /** `undefined` when the call admitted no value. */\n readonly controls: AdmittedControls | undefined;\n}\n\n/** The admitted values {@link snapshotControlValue} copied: the stable ones. */\nconst snapshots = new WeakSet<object>();\n\n/**\n * An admitted value as the call holds it from here on. Plain data is copied\n * once and frozen, so every reader of the call's controls (the rows its\n * filters bind, the key its cached read is stored under, its handlers) reads\n * the same value whatever the caller later does to its own. A value already\n * fixed all the way down is kept by identity. A value a copy would change\n * (a non-enumerable or symbol property, which `structuredClone` drops; a\n * getter, whose answer only calling it shows), one that resists inspection,\n * one with no canonical spelling, or one that cannot be copied (a Proxy), is\n * kept as given, as are bytes (an indexed write survives `freeze`); a copy\n * that still holds a `Date` is kept but not stable (`setTime` survives it). In\n * those cases the call binds the value for itself alone and its read is not\n * cached.\n */\nexport function snapshotControlValue(value: unknown): unknown {\n if (typeof value !== \"object\" || value === null) return value;\n if (!isCanonicalKeyData(value)) return value;\n let capture: ReturnType<typeof captureOf>;\n try {\n capture = captureOf(value, new WeakSet());\n } catch {\n // A Proxy may answer the canonical check and refuse a later reflection.\n return value;\n }\n if (capture === \"opaque\") return value;\n if (capture === \"fixed\") {\n snapshots.add(value);\n return value;\n }\n let copy: object;\n try {\n copy = structuredClone(value);\n } catch {\n return value;\n }\n if (freezeCopy(copy)) snapshots.add(copy);\n return copy;\n}\n\n/**\n * How an admitted value can be held: `fixed` when nothing reachable from it\n * can change (frozen own data properties only, no `Date`), `copy` when a\n * copy reproduces it (enumerable string-keyed data properties), `opaque`\n * when a copy might not (a non-enumerable or symbol property, or a getter,\n * never called here) or would not fix it (bytes).\n */\nfunction captureOf(\n value: object,\n seen: WeakSet<object>\n): \"fixed\" | \"copy\" | \"opaque\" {\n // Bytes are never stable (an indexed write survives `freeze`), and their\n // own properties are one per byte: kept as given, unread.\n if (ArrayBuffer.isView(value)) return \"opaque\";\n if (seen.has(value)) return \"fixed\";\n seen.add(value);\n let capture: \"fixed\" | \"copy\" =\n value instanceof Date || !Object.isFrozen(value) ? \"copy\" : \"fixed\";\n const array = Array.isArray(value);\n for (const key of Reflect.ownKeys(value)) {\n if (array && key === \"length\") continue;\n const descriptor = Object.getOwnPropertyDescriptor(value, key)!;\n if (\n typeof key === \"symbol\" ||\n !descriptor.enumerable ||\n !(\"value\" in descriptor)\n )\n return \"opaque\";\n const entry: unknown = descriptor.value;\n if (typeof entry !== \"object\" || entry === null) continue;\n const inner = captureOf(entry, seen);\n if (inner === \"opaque\") return \"opaque\";\n if (inner === \"copy\") capture = \"copy\";\n }\n return capture;\n}\n\n/** Freeze a private copy; answer whether nothing in it can still change. */\nfunction freezeCopy(value: object): boolean {\n if (value instanceof Date) return false;\n let fixed = true;\n for (const entry of Object.values(value))\n if (typeof entry === \"object\" && entry !== null && !freezeCopy(entry))\n fixed = false;\n Object.freeze(value);\n return fixed;\n}\n\n/**\n * Whether a control value is the one admission fixed: a primitive, or plain\n * data {@link snapshotControlValue} copied. Only such a value may key anything that\n * outlives the call (a bound-facts memo, a cache entry).\n */\nexport function isStableControlValue(value: unknown): boolean {\n return typeof value !== \"object\" || value === null || snapshots.has(value);\n}\n\n/**\n * Remove every control placed on this operation from its arguments and admit\n * each once, before any request handler runs. A key naming a control placed\n * elsewhere, or a bound-only one, stays in the arguments, where core\n * validation refuses it as an unknown key. A control the call did not pass\n * takes the value its view binds, if any; without one it is refused here on\n * the models its placement requires it on.\n */\nexport function admitControls(\n model: string,\n operation: Operation,\n input: Record<string, unknown>,\n placed: readonly ResolvedControl[],\n bound?: AdmittedControls\n): ControlAdmission {\n // Arguments that are not an object hold no control: core validation refuses\n // them as it does on a client without controls.\n if (typeof input !== \"object\" || input === null) {\n return { args: input, controls: undefined };\n }\n let keys: PropertyKey[];\n try {\n keys = Reflect.ownKeys(input);\n } catch (cause) {\n throw controlFailure(\n `The arguments of ${model}.${operation} could not be inspected for controls`,\n model,\n operation,\n cause\n );\n }\n const admitted: [string, unknown][] = [];\n let given: Set<PropertyKey> | undefined;\n for (const control of placed) {\n const { name, required } = control;\n let raw: unknown;\n if (control.bound !== true && keys.includes(name)) {\n (given ??= new Set()).add(name);\n raw = readControl(input, control, model, operation);\n }\n // A bound value was admitted and fixed once, when its view was bound.\n const value =\n raw === undefined\n ? (bound?.[name] ?? control.fallback)\n : snapshotControlValue(admitControl(control, raw, model, operation));\n if (value !== undefined) admitted.push([name, value]);\n else if (required === true || required?.has(model)) {\n throw invalidControl(control, model, operation, [\"is required\"]);\n }\n }\n return {\n args:\n given === undefined\n ? input\n : withoutControls(input, keys, given, model, operation),\n controls:\n admitted.length === 0\n ? undefined\n : Object.freeze(Object.fromEntries(admitted)),\n };\n}\n\n/**\n * The values a view binds after one extension binds its own controls: each\n * admitted once and fixed, over the values the view already binds, a value\n * replacing an earlier one.\n */\nexport function bindControls(\n controls: readonly ResolvedControl[],\n extension: string,\n values: Readonly<Record<string, unknown>>,\n previous: AdmittedControls | undefined\n): AdmittedControls {\n const next: Record<string, unknown> = { ...previous };\n for (const [name, raw] of Object.entries(values)) {\n const control = controls.find(\n (candidate) =>\n candidate.name === name && candidate.extension === extension\n );\n if (control === undefined) {\n throw new ClientInitializationError(\n `Extension \"${extension}\" binds control \"${name}\", which it does not declare.`,\n { meta: { extension } }\n );\n }\n next[name] = snapshotControlValue(admitControl(control, raw));\n }\n return Object.freeze(next);\n}\n\n/** One extension's own admitted controls, as its handlers see them. */\nexport function controlsOwnedBy(\n admitted: AdmittedControls | undefined,\n names: readonly string[]\n): AdmittedControls {\n const owned: [string, unknown][] = [];\n for (const name of names) {\n if (admitted !== undefined && Object.hasOwn(admitted, name)) {\n owned.push([name, admitted[name]]);\n }\n }\n return Object.freeze(Object.fromEntries(owned));\n}\n\nfunction readControl(\n input: Record<string, unknown>,\n control: ResolvedControl,\n model: string,\n operation: Operation\n): unknown {\n try {\n return Reflect.get(input, control.name);\n } catch (cause) {\n throw controlFailure(\n `Extension \"${control.extension}\" control \"${control.name}\" of ${model}.${operation} could not be read`,\n model,\n operation,\n cause\n );\n }\n}\n\n/** The caller's arguments minus the controls, every other descriptor kept. */\nfunction withoutControls(\n input: Record<string, unknown>,\n keys: readonly PropertyKey[],\n controls: ReadonlySet<PropertyKey>,\n model: string,\n operation: Operation\n): Record<string, unknown> {\n const args: Record<string, unknown> = {};\n try {\n for (const key of keys) {\n if (controls.has(key)) continue;\n const descriptor = Object.getOwnPropertyDescriptor(input, key);\n if (descriptor) Object.defineProperty(args, key, descriptor);\n }\n } catch (cause) {\n throw controlFailure(\n `The arguments of ${model}.${operation} could not be inspected for controls`,\n model,\n operation,\n cause\n );\n }\n return args;\n}\n\n/** One value admitted for a call's (model, operation), or, without them, a binding. */\nfunction admitControl(\n control: ResolvedControl,\n value: unknown,\n model?: string,\n operation?: Operation\n): unknown {\n const { declaration } = control;\n if (\"oneOf\" in declaration) {\n if (declaration.oneOf.some((allowed) => allowed === value)) return value;\n throw invalidControl(control, model, operation, [\n `must be one of ${declaration.oneOf.map((allowed) => JSON.stringify(allowed)).join(\", \")}`,\n ]);\n }\n let result: unknown;\n try {\n result = declaration.schema[\"~standard\"].validate(value);\n } catch (cause) {\n // A validator may own its typed failure; anything else is a failure of\n // extension code, as a throwing request transform is.\n if (isVibORMFailure(cause)) throw cause;\n throw validatorFailure(control, model, operation, \"threw\", cause);\n }\n let shape: \"promise\" | \"malformed\" | \"issues\" | \"value\" = \"malformed\";\n let issues: readonly unknown[] = [];\n let admitted: unknown;\n try {\n if (isRecord(result)) {\n const then = \"then\" in result ? result.then : undefined;\n if (isFunction(then)) {\n shape = \"promise\";\n // The refused promise is still live; without a handler its rejection\n // would surface as an unhandled rejection (D-37).\n Reflect.apply(then, result, [undefined, () => undefined]);\n } else {\n const listed = result.issues;\n if (listed !== undefined) {\n if (Array.isArray(listed)) {\n shape = \"issues\";\n issues = listed;\n }\n } else if (\"value\" in result) {\n shape = \"value\";\n admitted = result.value;\n }\n }\n }\n } catch (cause) {\n throw validatorFailure(\n control,\n model,\n operation,\n \"returned an unreadable result\",\n cause\n );\n }\n switch (shape) {\n case \"value\":\n return admitted;\n case \"issues\":\n throw invalidControl(control, model, operation, issueMessages(issues));\n case \"promise\":\n throw validatorFailure(\n control,\n model,\n operation,\n \"returned a promise\",\n new TypeError(\"Control validators must return synchronously\")\n );\n default:\n throw validatorFailure(\n control,\n model,\n operation,\n \"returned a malformed result\",\n new TypeError(\"A Standard Schema result has a value or an issue list\")\n );\n }\n}\n\n/** Each issue's message; an issue that cannot be read still refuses. */\nfunction issueMessages(issues: readonly unknown[]): string[] {\n const messages: string[] = [];\n try {\n for (const issue of issues) {\n const message = isRecord(issue) ? issue.message : undefined;\n messages.push(typeof message === \"string\" ? message : \"is invalid\");\n }\n } catch {\n return [\"is invalid\"];\n }\n return messages.length === 0 ? [\"is invalid\"] : messages;\n}\n\n/** Contained: `instanceof` on a hostile thrown proxy is itself a throw site. */\nfunction isVibORMFailure(value: unknown): value is VibORMError {\n try {\n return value instanceof VibORMError;\n } catch {\n return false;\n }\n}\n\n/**\n * The refusal of a cached read that holds a value of an `uncacheable`\n * control, or `undefined` when it holds none: such a read is an observation\n * the control's owner does not accept (the cache would serve it after the\n * facts it was judged on changed).\n */\nexport function uncacheableRead(\n controls: readonly ResolvedControl[],\n admitted: AdmittedControls | undefined,\n model: string,\n operation: Operation\n): ValidationError | undefined {\n const held = controls.find(\n (control) =>\n control.uncacheable === true && admitted?.[control.name] !== undefined\n );\n return (\n held &&\n invalidControl(held, model, operation, [\n \"is not cacheable: a read that holds it is not served from the cache\",\n ])\n );\n}\n\nfunction invalidControl(\n control: ResolvedControl,\n model: string | undefined,\n operation: Operation | undefined,\n messages: readonly string[]\n): ValidationError {\n return new ValidationError(\n operation === undefined\n ? { kind: \"schema-builder\", builder: \"$bind\", path: control.name }\n : { kind: \"operation\", operation, model },\n messages.map((message) => ({\n path: control.name,\n message: `Control \"${control.name}\" ${message}`,\n })),\n { meta: { model, extension: control.extension } }\n );\n}\n\nfunction validatorFailure(\n control: ResolvedControl,\n model: string | undefined,\n operation: Operation | undefined,\n failure: string,\n cause: unknown\n): QueryError {\n return controlFailure(\n `Extension \"${control.extension}\" control \"${control.name}\" validator for ${operation === undefined ? \"$bind\" : `${model}.${operation}`} ${failure}`,\n model,\n operation,\n cause\n );\n}\n\nfunction controlFailure(\n message: string,\n model: string | undefined,\n operation: Operation | undefined,\n cause: unknown\n): QueryError {\n return new QueryError(`${message}.`, {\n cause: errorCause(cause),\n meta: { model, operation },\n });\n}\n","import { parseProviding } from \"@validation/primitives/object\";\nimport type { PreparedDomain } from \"./query\";\nimport type { Input } from \"./schema\";\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 `rows` member's place in the chain, so a\n * layer stating nothing for the model leaves a hole.\n */\nexport type ModelDomain = ReadonlyMap<string, 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 * Per model (its TS name), indexed by layer as {@link ModelDomain} is, the\n * predicates of the model's verbs. A model absent here judges a write by\n * its purpose's predicates alone.\n */\n readonly verbs?: ReadonlyMap<string, readonly (ModelVerbs | undefined)[]>;\n /**\n * Whether some model's verbs may declare a projection key or a read-gated\n * field: when not, no model is asked for them. The maps may be resolved a\n * model at a time, so they are never walked to find out.\n */\n readonly projects?: boolean;\n}\n\n/**\n * One layer's predicates for one model's verbs, as admission left them: `read`\n * ANDs with the layer's predicate at every purpose, a write's verb with its\n * candidates beside them (R2). 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): a created row at `place`, absent where the layer\n * does not judge creates; an updated row at the predicates that judged its\n * old row and, per field it writes, that field's `moves` predicate.\n */\nexport interface ModelVerbs {\n readonly read: Input;\n readonly update: Input;\n readonly delete: Input;\n readonly writes: ReadonlyMap<string, Input>;\n readonly place?: Input;\n readonly moves: ReadonlyMap<string, Input>;\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 acyclic: readonly string[] | LazyRelations;\n /** The projection key the layer declares on the model (K5). */\n readonly evidence?: ModelEvidence;\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, Input>;\n}\n\n/**\n * A projection key and what it reports per row, each name with its admitted\n * predicate in declared order: whether each holds beside `read`, or, when\n * `ordered`, the last that does.\n */\nexport interface ModelEvidence {\n readonly as: string;\n readonly names: readonly (readonly [string, Input])[];\n readonly ordered: boolean;\n}\n\n/**\n * The verb a write lookup takes 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 RowJudgement {\n readonly verb: \"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 * 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 control 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 control 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 controls outside the engine:\n * the engine never sees a mode or an extension's name, and a control'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 * control are the call's own.\n */\nexport interface CallRows {\n /** The domain the call's own controls select. */\n readonly domain: RowDomain;\n /**\n * The domain an absent control selects: what a tombstoning delete takes,\n * and every other layer a layer's own traversals read (R5).\n */\n readonly defaults: RowDomain;\n /**\n * Per managed model, what its deletes write; absent when the call deletes\n * physically (its controls match the declaration's `removeWhen`).\n */\n readonly tombstones?: ReadonlyMap<string, Tombstone>;\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}\n\n/** A call's admitted controls, and how an absent value resolves (R6). */\nexport interface CallValues {\n readonly controls: Readonly<Record<string, unknown>>;\n /** An absent value of `control` on `model` matches nothing; else it drops. */\n readonly required: (control: string, model: string) => boolean;\n}\n\n/**\n * A value a domain predicate reads from its call, prepared once and read at\n * lowering: a control's value, or a field of it along `path`; with no\n * control, the call's one instant. `null` is absent: a parameter never lowers\n * to `IS NULL`. Its own fields are its spelling (`{ control, path }` or\n * `{ now: true }`), which no literal of a declaration can be, so a cache key\n * over declarations tells the two apart.\n */\nexport class Parameter {\n readonly control?: string;\n readonly path?: string;\n readonly now?: true;\n readonly #keys: readonly string[];\n constructor(control?: string, path?: string) {\n if (control === undefined) this.now = true;\n else this.control = control;\n if (path !== undefined) this.path = path;\n this.#keys = path === undefined ? [] : path.split(\".\");\n Object.freeze(this);\n }\n /** The call's value, `undefined` when absent. */\n read(values: CallValues | undefined, instant: () => Date): unknown {\n if (this.control === undefined) return instant();\n let value = values?.controls[this.control];\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(values: CallValues | undefined, instant: () => Date): 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 cache key 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 cache 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 /** The default domain, prepared once per engine view. */\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","import type { Schema } from \"@client/types\";\nimport { ClientInitializationError } from \"@errors\";\nimport {\n Condition,\n type ConditionTest,\n Existence,\n type LazyRelations,\n OuterColumn,\n Parameter,\n} from \"@query-engine/raptor3/shared/row-scope\";\nimport type { Input } from \"@query-engine/raptor3/shared/schema\";\nimport type { ModelState } from \"@schema/model\";\nimport { isPlainRecord } from \"@schema/relation/terminal\";\nimport { createSchemaRegistry } from \"@validation/builder\";\nimport { validateSchema } from \"@validation/primitives/helpers\";\nimport {\n type AdmittedFilters,\n admittingDomainPredicate,\n type DomainMarkers,\n} from \"@validation/primitives/parameter\";\nimport type { SchemaRegistryLookup } from \"@validation/types\";\nimport type { RowsContribution, RowsVerbs } from \"./controls\";\n\n/**\n * Each domain predicate admitted once, when its extension is applied, through\n * its model's `where` schema: a misspelt key fails here, never at the first\n * read, and the engine prepares what a caller's `where` would be (K1(a)).\n */\n\n/**\n * The where schemas of a schema no client prepared (a definition read on its\n * own), built once; a client hands admission its own.\n */\nconst registries = new WeakMap<Schema, SchemaRegistryLookup<Schema>>();\n\nfunction standaloneRegistry(schema: Schema): SchemaRegistryLookup<Schema> {\n let registry = registries.get(schema);\n if (registry === undefined) {\n registry = createSchemaRegistry(schema);\n registries.set(schema, registry);\n }\n return registry;\n}\n\n/** Successful admission can be reused only for immutable data and native schemas.\n * Registry identity carries the resolved relation topology; model entries also\n * guard schema maps edited between applications. No call/driver facts live here.\n */\nconst admittedRows = new WeakMap<\n SchemaRegistryLookup<Schema>,\n WeakMap<\n RowsContribution,\n {\n schema: Schema;\n entries: [string, Schema[string]][];\n admitted: RowsContribution;\n }\n >\n>();\n/**\n * A lazy `verbs` entry's admission, per registry, entry and model, for one\n * that returned immutable data: one function may serve several models.\n */\nconst admittedLazily = new WeakMap<\n SchemaRegistryLookup<Schema>,\n WeakMap<\n () => RowsVerbs,\n Map<\n string,\n {\n schema: Schema;\n entries: [string, Schema[string]][];\n admitted: RowsVerbs;\n }\n >\n >\n>();\nconst immutableData = new WeakSet<object>();\nconst immutableAdmitted = new WeakSet<object>();\n/** The functions admission puts in place of a lazy entry and its names. */\nconst resolvers = new WeakSet<object>();\nconst isResolver = (value: object) => resolvers.has(value);\nconst resolver = <T>(resolve: () => T): (() => T) => {\n resolvers.add(resolve);\n return resolve;\n};\n/**\n * Deeply frozen plain data: records, arrays and admitted nodes. With\n * `functions`, a function it accepts is a leaf known by identity.\n */\nexport function isImmutableRowData(\n value: unknown,\n open = new Set<object>(),\n functions?: (value: object) => boolean\n): boolean {\n if (typeof value === \"function\") return functions?.(value) === true;\n if (value === null || typeof value !== \"object\")\n return typeof value !== \"symbol\";\n const known = functions ? immutableAdmitted : immutableData;\n if (known.has(value) || immutableData.has(value)) return true;\n if (!Object.isFrozen(value) || open.has(value)) return false;\n const prototype = Object.getPrototypeOf(value);\n if (\n Array.isArray(value)\n ? prototype !== Array.prototype ||\n !Array.from({ length: value.length }, (_, index) =>\n Object.hasOwn(value, index)\n ).every(Boolean)\n : prototype !== Object.prototype &&\n prototype !== null &&\n prototype !== Parameter.prototype &&\n prototype !== Condition.prototype &&\n prototype !== Existence.prototype &&\n prototype !== OuterColumn.prototype\n )\n return false;\n open.add(value);\n const safe = Reflect.ownKeys(value).every((key) => {\n const descriptor = Object.getOwnPropertyDescriptor(value, key);\n return (\n typeof key === \"string\" &&\n descriptor &&\n \"value\" in descriptor &&\n isImmutableRowData(descriptor.value, open, functions)\n );\n });\n open.delete(value);\n if (safe) known.add(value);\n return safe;\n}\n\n/** Rows admission produced and nobody can change: their facts may be memoised. */\nexport const isAdmittedRows = (rows: object) =>\n isImmutableRowData(rows, new Set(), isResolver);\n\n/** Frozen own data properties of a record, each passing `item`. */\nconst frozenRecord = (\n value: unknown,\n item: (key: string, value: unknown) => boolean\n): boolean =>\n isPlainRecord(value) &&\n Object.isFrozen(value) &&\n Reflect.ownKeys(value).every((key) => {\n const descriptor = Object.getOwnPropertyDescriptor(value, key);\n return (\n typeof key === \"string\" &&\n descriptor !== undefined &&\n \"value\" in descriptor &&\n item(key, descriptor.value)\n );\n });\n\n/** A `verbs` entry's data immutable; its `acyclic` may be a function. */\nconst isImmutableEntry = (entry: unknown) =>\n frozenRecord(\n entry,\n (key, value) =>\n (key === \"acyclic\" && typeof value === \"function\") ||\n isImmutableRowData(value)\n );\n\n/**\n * Immutable `rows` as declared: plain data, but for a `verbs` entry that is\n * a function (and an entry's function `acyclic`), known by identity.\n */\nconst isImmutableRows = (rows: unknown) =>\n frozenRecord(rows, (key, value) =>\n key === \"verbs\"\n ? frozenRecord(\n value,\n (_, entry) => typeof entry === \"function\" || isImmutableEntry(entry)\n )\n : isImmutableRowData(value)\n );\n\n/** Native admission of immutable input owns every newly produced container. */\nfunction freezeAdmitted(value: unknown, seen = new Set<object>()): void {\n if (value === null || typeof value !== \"object\" || seen.has(value)) return;\n seen.add(value);\n for (const child of Object.values(value)) freezeAdmitted(child, seen);\n Object.freeze(value);\n}\n\n/** A model's `rows.verbs` entry, key by key. */\nconst VERBS_KEYS: Record<keyof RowsVerbs, true> = {\n predicates: true,\n read: true,\n update: true,\n delete: true,\n writes: true,\n place: true,\n moves: true,\n acyclic: true,\n evidence: true,\n reads: true,\n};\n\n/**\n * A declared projection key's spelling: `$` and an identifier. No model\n * member and no engine carrier is spelled so, so a key never hides either,\n * whatever the schema later adds.\n */\nconst PROJECTION_KEY = /^\\$[a-zA-Z_][a-zA-Z0-9_]*$/;\n\n/**\n * A model's key, unique and foreign-key fields: what identity and every join\n * read, and what a unique constraint answers for on a write, so none of them\n * is ever read-gated.\n */\nfunction keyFields(state: ModelState): ReadonlySet<string> {\n return new Set([\n ...Object.entries(state.scalars)\n .filter(([, scalar]) => scalar[\"~\"].state.isId === true)\n .map(([field]) => field),\n // A write of a guessed value fails on the constraint exactly when some\n // row holds it: a gate on a unique field would be confirmed by it.\n ...Object.keys(state.uniques),\n ...[\n ...Object.values(state.compoundId ?? {}),\n ...Object.values(state.compoundUniques ?? {}),\n ].flatMap(({ entries }) => Object.keys(entries)),\n ...Object.values(state.relations).flatMap(\n (relation) => relation[\"~\"].state.foreignKey?.fields ?? []\n ),\n ]);\n}\n\n/** A condition's tests, the filter vocabulary's own words (OD-12). */\nconst TESTS = [\"exists\", \"equals\", \"in\", \"has\", \"hasSome\"] as const;\n\n/** `{ control, path? }`: a control's value, or a field of it. */\nexport function isReference(\n value: unknown\n): value is { readonly control: string; readonly path?: string } {\n return (\n isPlainRecord(value) &&\n typeof value.control === \"string\" &&\n Object.keys(value).every((key) => key === \"control\" || key === \"path\") &&\n (value.path === undefined || typeof value.path === \"string\")\n );\n}\n\n/** `{ $row, up }`: a column of an enclosing row (resolved where it is compared). */\nexport const isOuterColumn = (\n value: unknown\n): value is { readonly $row: string; readonly up: number } =>\n isPlainRecord(value) &&\n Object.keys(value).length === 2 &&\n typeof value.$row === \"string\" &&\n Number.isSafeInteger(value.up) &&\n (value.up as number) >= 0;\n\n/** `{ now: true }`: the call's one instant. */\nexport const isInstant = (value: unknown): boolean =>\n isPlainRecord(value) && value.now === true && Object.keys(value).length === 1;\n\nconst REFUSED_CONDITION = `a condition names one control and exactly one of ${TESTS.join(\", \")}`;\n\n/** `$if`'s `{ control, path?, <one test> }` as a condition, or the refusal. */\nfunction conditionOf(spec: unknown): Condition | string {\n if (!isPlainRecord(spec)) return REFUSED_CONDITION;\n const { control, path, ...tests } = spec;\n const [test, ...others] = Object.keys(tests);\n const operand = tests[test!];\n if (\n typeof control !== \"string\" ||\n (path !== undefined && typeof path !== \"string\") ||\n !TESTS.includes(test as (typeof TESTS)[number]) ||\n others.length > 0 ||\n (test === \"exists\" && typeof operand !== \"boolean\") ||\n ((test === \"in\" || test === \"hasSome\") && !Array.isArray(operand))\n )\n return REFUSED_CONDITION;\n return new Condition(\n new Parameter(control, path),\n Object.freeze({ [test!]: operand }) as unknown as ConditionTest\n );\n}\n\n/** The nodes a predicate's markers stand for, as its `where` meets them. */\nconst MARKERS: DomainMarkers = {\n value: (value) => {\n if (isReference(value)) return new Parameter(value.control, value.path);\n if (isOuterColumn(value)) return new OuterColumn(value.$row, value.up);\n return isInstant(value) ? new Parameter() : undefined;\n },\n condition: conditionOf,\n};\n\n/**\n * The path at which `value` contains itself, `undefined` where it does not.\n * Only an object inside its own descendants is refused: a predicate may share\n * sub-objects freely.\n */\nfunction cyclePath(\n value: unknown,\n acyclic: WeakSet<object>,\n ancestors = new Set<object>(),\n path: string[] = []\n): string | undefined {\n if (typeof value !== \"object\" || value === null || acyclic.has(value))\n return undefined;\n // The root has no ancestor: a path is never empty here.\n if (ancestors.has(value)) return path.join(\".\");\n ancestors.add(value);\n for (const [key, item] of Object.entries(value)) {\n path.push(key);\n const found = cyclePath(item, acyclic, ancestors, path);\n if (found !== undefined) return found;\n path.pop();\n }\n ancestors.delete(value);\n // Every descendant was walked: no cycle passes through this object.\n acyclic.add(value);\n return undefined;\n}\n\n/**\n * One definition's `rows` with every predicate admitted, each named predicate\n * once and a mode naming one given its admitted object: refusals are\n * `ClientInitializationError`s naming the extension, the model, the\n * predicate's place in `rows` and the path inside it.\n */\nexport function admitRows(\n rows: RowsContribution,\n schema: Schema,\n extension: string,\n registry: SchemaRegistryLookup<Schema> = standaloneRegistry(schema)\n): RowsContribution {\n const native = Object.values(schema).every((model) => {\n const state: ModelState = model[\"~\"].state;\n return Object.values(state.scalars).every(\n (scalar) => scalar[\"~\"].state.schema === undefined\n );\n });\n const reusable = native && isImmutableRows(rows);\n const entries = reusable ? Object.entries(schema) : undefined;\n /** A cached admission still holds where the schema map is the one it read. */\n const holds = (previous: {\n schema: Schema;\n entries: [string, Schema[string]][];\n }) => {\n const current = Object.entries(schema);\n return (\n previous.schema === schema &&\n current.length === previous.entries.length &&\n current.every(\n ([name, model], index) =>\n name === previous.entries[index]![0] &&\n model === previous.entries[index]![1]\n )\n );\n };\n const previous = reusable ? admittedRows.get(registry)?.get(rows) : undefined;\n if (previous && holds(previous)) return previous.admitted;\n const refuse = (\n name: string,\n place: string,\n at: string,\n reason: string\n ): never => {\n throw new ClientInitializationError(\n `Extension \"${extension}\" rows.${place} at \"${at}\": ${reason}.`,\n { meta: { extension, model: name } }\n );\n };\n // Shared sub-predicates are walked and parsed once per admission, a lazy\n // entry's included.\n const acyclic = new WeakSet<object>();\n const filters: AdmittedFilters = new WeakMap();\n /**\n * `$exists`: one model of the schema and its `where`, admitted with that\n * model's own schema (its markers and depth rules included).\n */\n const markers: DomainMarkers = {\n ...MARKERS,\n exists: (spec) => {\n const models = isPlainRecord(spec) ? Object.keys(spec) : [];\n const [model] = models;\n if (\n models.length !== 1 ||\n !Object.hasOwn(schema, model!) ||\n !isPlainRecord((spec as Record<string, unknown>)[model!])\n )\n return {\n message:\n \"names exactly one model of the schema and the `where` its rows must match\",\n path: [],\n };\n const result = validateSchema(\n registry.getModelSchemas(schema[model!]!).core.where,\n (spec as Record<string, unknown>)[model!]\n );\n if (result.issues) {\n const [issue] = result.issues;\n return {\n message: issue!.message,\n path: [model!, ...(issue!.path ?? [])],\n };\n }\n return new Existence(model!, result.value as Input);\n },\n };\n const admit = (\n name: string,\n place: string,\n predicate: unknown\n ): Record<string, unknown> => {\n const cycle = cyclePath(predicate, acyclic);\n if (cycle !== undefined) refuse(name, place, cycle, \"contains itself\");\n const where = registry.getModelSchemas(schema[name]!).core.where;\n const result = admittingDomainPredicate(\n markers,\n () => validateSchema(where, predicate),\n filters\n );\n if (!result.issues) return result.value as Record<string, unknown>;\n const [issue] = result.issues;\n return refuse(\n name,\n place,\n issue!.path?.map(String).join(\".\") || \"root\",\n issue!.message\n );\n };\n /** The self relations of `name` holding its key: what `acyclic` may name. */\n const selfKeys = (name: string): readonly string[] => {\n const { state } = schema[name]![\"~\"];\n return Object.keys(state.relations).filter((relation) => {\n const held = state.relations[relation]![\"~\"];\n return (\n held.state.foreignKey !== undefined &&\n held.settleTarget() === schema[name]\n );\n });\n };\n const admitAcyclic = (\n name: string,\n place: string,\n relations: readonly string[]\n ): readonly string[] => {\n const allowed = selfKeys(name);\n for (const relation of relations)\n if (!allowed.includes(relation))\n refuse(\n name,\n place,\n `acyclic.${relation}`,\n \"names no to-one relation of the model to itself holding its key\"\n );\n return relations;\n };\n /** One model's `verbs` entry, every predicate admitted and every name checked. */\n const admitVerbs = (name: string, entry: RowsVerbs): RowsVerbs => {\n const place = `verbs.${name}`;\n if (!isPlainRecord(entry))\n refuse(name, place, \"root\", \"is not an object or a function\");\n // Policies may be data built at runtime: a misspelt `writes` would leave\n // its field judged at `update`, which widens the write.\n for (const key of Object.keys(entry))\n if (!Object.hasOwn(VERBS_KEYS, key))\n refuse(\n name,\n place,\n key,\n `is not one of ${Object.keys(VERBS_KEYS).join(\", \")}`\n );\n const { state } = schema[name]![\"~\"];\n const predicates = Object.fromEntries(\n Object.entries(entry.predicates).map(([key, predicate]) => [\n key,\n admit(name, `${place}.predicates.${key}`, predicate),\n ])\n );\n const known = (at: string, predicate: string | undefined) => {\n if (predicate !== undefined && !Object.hasOwn(predicates, predicate))\n refuse(name, place, at, `names unknown predicate \"${predicate}\"`);\n };\n known(\"read\", entry.read);\n known(\"update\", entry.update);\n known(\"delete\", entry.delete);\n known(\"place\", entry.place);\n for (const key of [\"writes\", \"moves\"] as const)\n for (const [field, predicate] of Object.entries(entry[key] ?? {})) {\n if (\n !(\n Object.hasOwn(state.scalars, field) ||\n Object.hasOwn(state.relations, field)\n )\n )\n refuse(name, place, `${key}.${field}`, \"names an unknown field\");\n known(`${key}.${field}`, predicate);\n }\n let cycles: readonly string[] | LazyRelations | undefined;\n const declared = entry.acyclic;\n if (typeof declared === \"function\") {\n let resolved: readonly string[] | undefined;\n cycles = Object.freeze({\n candidates: Object.freeze(selfKeys(name)),\n resolve: () =>\n (resolved ??= Object.freeze([\n ...admitAcyclic(name, place, declared()),\n ])),\n });\n } else if (declared !== undefined)\n cycles = admitAcyclic(name, place, declared);\n const { evidence } = entry;\n if (evidence !== undefined) {\n if (!PROJECTION_KEY.test(evidence.as))\n refuse(name, place, \"evidence.as\", \"is not `$` and an identifier\");\n for (const [index, predicate] of evidence.names.entries())\n known(`evidence.names.${index}`, predicate);\n }\n const keys = entry.reads === undefined ? undefined : keyFields(state);\n for (const [field, predicate] of Object.entries(entry.reads ?? {})) {\n if (!Object.hasOwn(state.scalars, field))\n refuse(name, place, `reads.${field}`, \"names no scalar of the model\");\n // Masked in a caller's operands while identity and joins read it raw,\n // a key would answer through a relation what a filter hides.\n if (keys!.has(field))\n refuse(\n name,\n place,\n `reads.${field}`,\n \"names a key, a unique or a foreign key field\"\n );\n known(`reads.${field}`, predicate);\n }\n return Object.freeze({\n ...entry,\n predicates: Object.freeze(predicates),\n ...(cycles !== undefined && {\n acyclic: cycles as RowsVerbs[\"acyclic\"],\n }),\n });\n };\n /**\n * A lazy entry, admitted the first time it is resolved: once per schema\n * registry when it returns immutable data, else once per admission.\n */\n const lazily = (name: string, entry: () => RowsVerbs): (() => RowsVerbs) => {\n let admitted: RowsVerbs | undefined;\n return resolver(() => {\n if (admitted !== undefined) return admitted;\n const cached = native\n ? admittedLazily.get(registry)?.get(entry)?.get(name)\n : undefined;\n if (cached && holds(cached)) return (admitted = cached.admitted);\n const declared = entry();\n const result = admitVerbs(name, declared);\n if (native && isImmutableEntry(declared)) {\n freezeAdmitted(result);\n let cache = admittedLazily.get(registry);\n if (!cache) {\n cache = new WeakMap();\n admittedLazily.set(registry, cache);\n }\n let models = cache.get(entry);\n if (!models) {\n models = new Map();\n cache.set(entry, models);\n }\n models.set(name, {\n schema,\n entries: Object.entries(schema),\n admitted: result,\n });\n }\n admitted = result;\n return result;\n });\n };\n const verbs: Record<string, RowsVerbs | (() => RowsVerbs)> = {};\n for (const [name, entry] of Object.entries(rows.verbs ?? {})) {\n if (!Object.hasOwn(schema, name))\n refuse(name, `verbs.${name}`, \"root\", \"names an unknown model\");\n verbs[name] =\n typeof entry === \"function\"\n ? lazily(name, entry)\n : admitVerbs(name, entry);\n }\n const models: Record<string, Record<string, object>> = {};\n for (const [name, modes] of Object.entries(rows.models)) {\n const admitted = new Map<string, object>();\n const own = verbs[name];\n for (const [mode, purposes] of Object.entries(modes)) {\n const out: Record<string, unknown> = {};\n for (const purpose of [\"root\", \"related\"] as const) {\n const predicate = purposes[purpose];\n if (predicate === undefined) continue;\n const place = `${name}.${mode}.${purpose}`;\n if (typeof predicate !== \"string\")\n out[purpose] = admit(name, place, predicate);\n else if (typeof own === \"function\")\n // A lazy entry's predicate, named when its model is first needed.\n out[purpose] = resolver(() =>\n Object.hasOwn(own().predicates, predicate)\n ? own().predicates[predicate]\n : refuse(\n name,\n place,\n \"root\",\n `names unknown predicate \"${predicate}\"`\n )\n );\n else if (Object.hasOwn(own?.predicates ?? {}, predicate))\n out[purpose] = own!.predicates[predicate];\n else\n refuse(name, place, \"root\", `names unknown predicate \"${predicate}\"`);\n }\n admitted.set(mode, Object.freeze(out));\n }\n models[name] = Object.freeze(Object.fromEntries(admitted));\n }\n const admitted = Object.freeze({\n ...rows,\n models: Object.freeze(models),\n ...(rows.verbs && { verbs: Object.freeze(verbs) }),\n }) as RowsContribution;\n if (entries) freezeAdmitted(admitted);\n if (entries && isAdmittedRows(admitted)) {\n let cache = admittedRows.get(registry);\n if (!cache) {\n cache = new WeakMap();\n admittedRows.set(registry, cache);\n }\n cache.set(rows, { schema, entries, admitted });\n }\n return admitted;\n}\n","import { ClientInitializationError } from \"@errors\";\nimport {\n type CallRows,\n Condition,\n Existence,\n type LazyRelations,\n type ModelDomain,\n type ModelStamps,\n type ModelVerbs,\n Parameter,\n type RowDomain,\n} from \"@query-engine/raptor3/shared/row-scope\";\nimport type { Input } from \"@query-engine/raptor3/shared/schema\";\nimport { isPlainRecord } from \"@schema/relation/terminal\";\nimport { isImmutableRowData, isInstant, isReference } from \"./admission\";\nimport type { ResolvedControls, ResolvedDeletion } from \"./chain\";\nimport {\n type AdmittedControls,\n type RowsContribution,\n type RowsVerbs,\n rowsModes,\n} from \"./controls\";\nimport type { RuntimeExtensionDefinition } from \"./definition\";\n\ntype Predicates = RowsContribution[\"models\"][string][string];\n\n/** One `rows` member: its control, and where each of its modes sits. */\ninterface BoundRowsMember {\n readonly control: string;\n readonly names: readonly string[];\n readonly modes: ReadonlyMap<unknown, number>;\n readonly fallback: number;\n /** How far one step of this member's mode moves the combination index. */\n readonly stride: number;\n}\n\n/**\n * A chain's row facts, resolved once when an extension is applied: one\n * {@link CallRows} per combination of its `rows` members' modes, with and\n * without the tombstones, each with the chain's `data` stamps, so a call only\n * looks its facts up. The predicates hold the values they read as\n * parameters, prepared once for every call: a call whose combination reads\n * one carries its values beside the shared domains. When a stamp names a\n * control, the call's values are put in its stamps for that call alone.\n */\nexport interface RowsBinding {\n readonly members: readonly BoundRowsMember[];\n readonly deletion: Readonly<Record<string, ResolvedDeletion>>;\n /** Indexed by mode combination: the call writes tombstones. */\n readonly tombstoning: readonly CallRows[];\n /** Indexed by mode combination: the call deletes physically. */\n readonly physical: readonly CallRows[];\n /**\n * Indexed by mode combination: its domain or the default one reads a call\n * value, so its calls carry their values.\n */\n readonly parametric: readonly boolean[];\n /** A stamp names a control: each call puts its values in the stamps. */\n readonly bindsStamps: boolean;\n /** Whether a call must pass a control to touch a model directly. */\n readonly required: RequiredOn;\n}\n\ntype RequiredOn = (control: string, model: string) => boolean;\n\nconst NEVER_REQUIRED: RequiredOn = () => false;\n\nconst NO_DELETION: Readonly<Record<string, ResolvedDeletion>> = Object.freeze(\n Object.create(null)\n);\n\nconst NO_CONTROLS: AdmittedControls = Object.freeze({});\n\n/** A named control the call did not pass. */\nconst ABSENT = Symbol(\"absent\");\n\n/**\n * Every control a definition's values name, at any depth: an admitted\n * predicate's parameters and conditions, and a stamp's references.\n */\nfunction collectReferences(\n value: unknown,\n names: Set<string>,\n // Predicates share sub-predicates freely: each is read once.\n seen = new Set<object>()\n): void {\n if (value instanceof Existence) {\n collectReferences(value.where, names, seen);\n return;\n }\n const parameter = value instanceof Condition ? value.parameter : value;\n if (parameter instanceof Parameter) {\n if (parameter.control !== undefined) names.add(parameter.control);\n } else if (isReference(value)) names.add(value.control);\n else if (Array.isArray(value) || isPlainRecord(value)) {\n if (seen.has(value)) return;\n seen.add(value);\n for (const item of Object.values(value))\n collectReferences(item, names, seen);\n }\n}\n\n// Admission-owned immutable predicates have the same references in every chain.\n// Declarations and the receiving chain's controls are still checked each time.\nconst rowReferences = new WeakMap<RowsContribution, readonly string[]>();\nfunction referencesOfRows(rows: RowsContribution): readonly string[] {\n const cached = rowReferences.get(rows);\n if (cached) return cached;\n const references = new Set<string>();\n const seen = new Set<object>();\n for (const modes of Object.values(rows.models))\n for (const mode of Object.values(modes)) {\n collectReferences(mode.root, references, seen);\n collectReferences(mode.related, references, seen);\n }\n // A lazy entry's references are checked when it is resolved.\n for (const entry of Object.values(rows.verbs ?? {}))\n if (typeof entry !== \"function\")\n collectReferences(entry.predicates, references, seen);\n const names = [...references];\n if (isImmutableRowData(rows)) rowReferences.set(rows, names);\n return names;\n}\n\n/** The controls a stamp's fields name: its own keys are fields, never values. */\nfunction collectStampReferences(\n stamp: Input | undefined,\n names: Set<string>\n): void {\n for (const value of Object.values(stamp ?? {}))\n collectReferences(value, names);\n}\n\n/**\n * The controls a definition names but does not declare; the chain admits\n * those an earlier extension declares.\n */\nexport function undeclaredControlReferencesOf(\n definition: RuntimeExtensionDefinition\n): readonly string[] {\n const declared = new Set(Object.keys(definition.controls ?? {}));\n if (definition.rows) declared.add(definition.rows.control);\n const references = new Set(\n definition.rows ? referencesOfRows(definition.rows) : []\n );\n for (const entry of Object.values(definition.data?.models ?? {})) {\n collectStampReferences(entry.create, references);\n collectStampReferences(entry.update, references);\n }\n for (const name of Object.keys(definition.deletion?.removeWhen ?? {}))\n references.add(name);\n return [...references].filter((name) => !declared.has(name));\n}\n\n/** Whether a domain's predicates read a call value (admission's nodes). */\nfunction readsCall(value: unknown): boolean {\n if (value instanceof Parameter || value instanceof Condition) return true;\n if (value instanceof Existence) return readsCall(value.where);\n if (Array.isArray(value)) return value.some(readsCall);\n return isPlainRecord(value) && Object.values(value).some(readsCall);\n}\n\n/** A stamp's value with the call's put in: itself when it names none. */\nfunction stampValue(\n value: unknown,\n controls: AdmittedControls | undefined\n): unknown {\n if (isReference(value)) {\n let given = controls?.[value.control];\n const { path } = value;\n for (const key of path === undefined ? [] : path.split(\".\")) {\n given =\n isPlainRecord(given) && Object.hasOwn(given, key)\n ? given[key]\n : undefined;\n }\n return given === undefined ? ABSENT : given;\n }\n if (Array.isArray(value)) {\n const items = value.map((item) => stampValue(item, controls));\n if (items.includes(ABSENT)) return ABSENT;\n return items.every((item, index) => item === value[index]) ? value : items;\n }\n if (!isPlainRecord(value)) return value;\n let copy: Record<string, unknown> | undefined;\n for (const [key, item] of Object.entries(value)) {\n const bound = stampValue(item, controls);\n if (bound === ABSENT) return ABSENT;\n if (bound !== item) (copy ??= { ...value })[key] = bound;\n }\n return copy ?? value;\n}\n\n/**\n * A stamp bound: a field whose value names a control the call did not pass is\n * not written. The same object when no field names a control.\n */\nfunction boundStamp(\n stamp: Input | undefined,\n controls: AdmittedControls | undefined\n): Input | undefined {\n if (stamp === undefined) return undefined;\n const values: Record<string, unknown> = {};\n let changed = false;\n for (const [field, value] of Object.entries(stamp)) {\n const bound = stampValue(value, controls);\n changed ||= bound !== value;\n if (bound !== ABSENT) values[field] = bound;\n }\n return changed ? Object.freeze(values) : stamp;\n}\n\n/** Each model's stamps bound; an entry naming no control is kept as is. */\nfunction boundStamps(\n stamps: ReadonlyMap<string, ModelStamps>,\n controls: AdmittedControls | undefined\n): ReadonlyMap<string, ModelStamps> {\n const bound = new Map<string, ModelStamps>();\n for (const [model, entry] of stamps) {\n const create = boundStamp(entry.create, controls);\n const update = boundStamp(entry.update, controls);\n bound.set(\n model,\n create === entry.create && update === entry.update\n ? entry\n : Object.freeze({ create, update })\n );\n }\n return bound;\n}\n\n/** The call's one instant, where a stamp's field writes `{ now: true }`. */\nconst NOW = new Parameter();\n\n/** A stamp with each `{ now: true }` field as {@link NOW}: itself without one. */\nfunction withInstants(stamp: Input | undefined): Input | undefined {\n let copy: Record<string, unknown> | undefined;\n for (const [field, value] of Object.entries(stamp ?? {}))\n if (isInstant(value)) (copy ??= { ...stamp })[field] = NOW;\n return copy === undefined ? stamp : Object.freeze(copy);\n}\n\n/** The chain's `required` declarations as one test, by control and model. */\nfunction requiredOn(controls: ResolvedControls | undefined): RequiredOn {\n const required = new Map<string, true | ReadonlySet<string>>();\n for (const control of controls?.all ?? []) {\n if (control.required !== undefined)\n required.set(control.name, control.required);\n }\n if (required.size === 0) return NEVER_REQUIRED;\n return (control, model) => {\n const on = required.get(control);\n return on === true || on?.has(model) === true;\n };\n}\n\n/**\n * A map whose entries are built the first time they are read: a `rows`\n * member's lazy `verbs` entry is resolved only for a model a call reaches.\n * `has` answers without building; walking the map builds every entry. A\n * build that throws is kept, so the next read throws again: an entry is\n * never read as absent because its build failed.\n */\nclass LazyMap<K, V> extends Map<K, V> {\n readonly #pending: Map<K, () => V>;\n constructor(built: Iterable<readonly [K, V]>, pending: Map<K, () => V>) {\n super(built);\n this.#pending = pending;\n }\n #settle(key: K): void {\n const build = this.#pending.get(key);\n if (build === undefined) return;\n const value = build();\n this.#pending.delete(key);\n super.set(key, value);\n }\n #settleAll(): void {\n for (const key of [...this.#pending.keys()]) this.#settle(key);\n }\n override get(key: K): V | undefined {\n this.#settle(key);\n return super.get(key);\n }\n override has(key: K): boolean {\n return this.#pending.has(key) || super.has(key);\n }\n override get size(): number {\n this.#settleAll();\n return super.size;\n }\n override keys(): MapIterator<K> {\n this.#settleAll();\n return super.keys();\n }\n override values(): MapIterator<V> {\n this.#settleAll();\n return super.values();\n }\n override entries(): MapIterator<[K, V]> {\n this.#settleAll();\n return super.entries();\n }\n override [Symbol.iterator](): MapIterator<[K, V]> {\n return this.entries();\n }\n override forEach(\n callback: (value: V, key: K, map: Map<K, V>) => void,\n thisArg?: unknown\n ): void {\n this.#settleAll();\n super.forEach(callback, thisArg);\n }\n}\n\n/** A map of `built` entries, and of `pending` ones built when first read. */\nfunction lazyMap<K, V>(\n built: Map<K, V>,\n pending: Map<K, () => V>\n): ReadonlyMap<K, V> {\n return pending.size === 0 ? built : new LazyMap(built, pending);\n}\n\n/** What admission leaves in place of a lazy entry's predicate: its resolver. */\ntype Lazy<T> = () => T;\n\n/**\n * One purpose's predicates per model, for one mode of every member, each at\n * its member's place in the chain: the layer the engine reads it as. A mode\n * that named a predicate holds its admitted object; one that named a lazy\n * entry's predicate, its resolver, called when the model is first read.\n */\nfunction modelDomain(\n rows: readonly RowsContribution[],\n modes: readonly string[],\n purpose: keyof Predicates\n): ModelDomain {\n const declared = new Map<string, (Input | Lazy<Input>)[]>();\n for (const [layer, member] of rows.entries()) {\n for (const [model, entry] of Object.entries(member.models)) {\n const where = entry[modes[layer]!]?.[purpose];\n if (where === undefined) continue;\n const list = declared.get(model) ?? [];\n list[layer] = where as Input | Lazy<Input>;\n declared.set(model, list);\n }\n }\n const built = new Map<string, Input[]>();\n const pending = new Map<string, () => Input[]>();\n for (const [model, list] of declared) {\n if (list.some((where) => typeof where === \"function\"))\n pending.set(model, () => {\n const resolved: Input[] = [];\n for (const [layer, where] of list.entries())\n if (where !== undefined)\n resolved[layer] =\n typeof where === \"function\" ? (where as Lazy<Input>)() : where;\n return resolved;\n });\n else built.set(model, list as Input[]);\n }\n return lazyMap(built, pending);\n}\n\n/** `{ OR: [] }`, false: what a verb a model's `verbs` leaves out takes. */\nconst NOTHING: Input = Object.freeze({ OR: Object.freeze([]) });\n\n/** A `writes` or `moves` entry, its names resolved. */\nconst fieldsOf = (\n entry: { readonly [field: string]: string } | undefined,\n named: (name: string) => Input\n): ReadonlyMap<string, Input> =>\n new Map(\n Object.entries(entry ?? {}).map(([field, name]) => [field, named(name)])\n );\n\n/** One layer's admitted entry as the engine reads it. */\nfunction layerVerbs(entry: RowsVerbs): ModelVerbs {\n const named = (name: string | undefined): Input =>\n name === undefined ? NOTHING : entry.predicates[name]!;\n // Admission leaves a lazy `acyclic` as its candidates and resolver.\n const acyclic = entry.acyclic as\n | readonly string[]\n | LazyRelations\n | undefined;\n return Object.freeze({\n read: named(entry.read),\n update: named(entry.update),\n delete: named(entry.delete),\n writes: fieldsOf(entry.writes, named),\n ...(entry.place !== undefined && { place: named(entry.place) }),\n moves: fieldsOf(entry.moves, named),\n acyclic: Array.isArray(acyclic)\n ? Object.freeze([...acyclic])\n : ((acyclic as LazyRelations | undefined) ?? NO_RELATIONS),\n ...(entry.evidence && {\n evidence: Object.freeze({\n as: entry.evidence.as,\n names: Object.freeze(\n entry.evidence.names.map((name) =>\n Object.freeze([name, named(name)] as const)\n )\n ),\n ordered: entry.evidence.ordered === true,\n }),\n }),\n reads: fieldsOf(entry.reads, named),\n });\n}\nconst NO_RELATIONS: readonly string[] = Object.freeze([]);\n\n/**\n * Every member's verbs per model, each at its member's layer, their names\n * resolved to the admitted predicates: the same for every mode combination.\n * A model one member declares lazily is resolved when it is first read.\n */\nfunction modelVerbs(\n rows: readonly RowsContribution[]\n): ReadonlyMap<string, readonly (ModelVerbs | undefined)[]> | undefined {\n const declared = new Map<string, (RowsVerbs | Lazy<RowsVerbs>)[]>();\n for (const [layer, member] of rows.entries())\n for (const [model, entry] of Object.entries(member.verbs ?? {})) {\n const list = declared.get(model) ?? [];\n list[layer] = entry;\n declared.set(model, list);\n }\n const layers = (model: string, list: readonly (RowsVerbs | undefined)[]) => {\n const keys = new Set<string>();\n const verbs: (ModelVerbs | undefined)[] = [];\n for (const [layer, entry] of list.entries()) {\n if (entry === undefined) continue;\n // One projection key, one layer: a second would hide the first.\n const key = entry.evidence?.as;\n if (key !== undefined && keys.has(key))\n throw new ClientInitializationError(\n `rows.verbs.${model}.evidence.as \"${key}\" is declared by two extensions of the chain.`,\n { meta: { model } }\n );\n if (key !== undefined) keys.add(key);\n verbs[layer] = layerVerbs(entry);\n }\n return verbs;\n };\n const built = new Map<string, readonly (ModelVerbs | undefined)[]>();\n const pending = new Map<string, () => readonly (ModelVerbs | undefined)[]>();\n for (const [model, list] of declared) {\n if (list.some((entry) => typeof entry === \"function\"))\n pending.set(model, () =>\n layers(\n model,\n Array.from(list, (entry) =>\n typeof entry === \"function\" ? entry() : entry\n )\n )\n );\n else built.set(model, layers(model, list as RowsVerbs[]));\n }\n if (declared.size === 0) return undefined;\n return lazyMap(built, pending);\n}\n\n/** Whether a member names a lazy entry: its contents are not known yet. */\nexport const isLazy = (member: RowsContribution) =>\n Object.values(member.verbs ?? {}).some(\n (entry) => typeof entry === \"function\"\n );\n\n/**\n * `rows` whose lazy entries check, when resolved, that every control their\n * predicates name is one the chain declared where the extension was\n * applied (`declared`), as an eager entry is checked by `$extends`. The same\n * object when it names no lazy entry.\n */\nexport function checkingLazyReferences(\n rows: RowsContribution,\n declared: (control: string) => boolean,\n refuse: (control: string) => never\n): RowsContribution {\n if (!isLazy(rows)) return rows;\n const checked = new Map<string, Lazy<RowsVerbs>>();\n const verbs = Object.fromEntries(\n Object.entries(rows.verbs!).map(([model, entry]) => {\n if (typeof entry !== \"function\") return [model, entry];\n let resolved: RowsVerbs | undefined;\n const check = () => {\n if (resolved !== undefined) return resolved;\n const admitted = entry();\n for (const control of verbsReferences(admitted))\n if (!declared(control)) refuse(control);\n resolved = admitted;\n return admitted;\n };\n checked.set(model, check);\n return [model, check];\n })\n );\n // A mode naming a lazy predicate reaches it through the checked entry.\n const models = Object.fromEntries(\n Object.entries(rows.models).map(([model, modes]) => {\n const check = checked.get(model);\n if (check === undefined) return [model, modes];\n return [\n model,\n Object.fromEntries(\n Object.entries(modes).map(([mode, purposes]) => [\n mode,\n Object.fromEntries(\n Object.entries(purposes).map(([purpose, where]) => [\n purpose,\n typeof where === \"function\"\n ? () => {\n check();\n return (where as Lazy<Input>)();\n }\n : where,\n ])\n ),\n ])\n ),\n ];\n })\n );\n const checking = Object.freeze({\n ...rows,\n models,\n verbs: Object.freeze(verbs),\n });\n origins.set(checking, rows);\n return checking;\n}\n/** The admitted rows a chain's checking copy stands for: the same content. */\nconst origins = new WeakMap<RowsContribution, RowsContribution>();\nexport const admittedRowsOf = (rows: RowsContribution) =>\n origins.get(rows) ?? rows;\n\n// An admitted entry's references, read once: it is immutable once admitted.\nconst entryReferences = new WeakMap<RowsVerbs, readonly string[]>();\nfunction verbsReferences(entry: RowsVerbs): readonly string[] {\n const known = entryReferences.get(entry);\n if (known) return known;\n const names = new Set<string>();\n collectReferences(entry.predicates, names);\n const list = [...names];\n if (Object.isFrozen(entry)) entryReferences.set(entry, list);\n return list;\n}\n\nexport function bindRows(\n rows: readonly RowsContribution[] | undefined,\n deletion: Readonly<Record<string, ResolvedDeletion>> | undefined,\n data?: Readonly<Record<string, ModelStamps>>,\n controls?: ResolvedControls\n): RowsBinding {\n const declared = rows ?? [];\n let stride = 1;\n const members = declared.map((member): BoundRowsMember => {\n const modes = rowsModes(member);\n const bound = {\n control: member.control,\n names: modes,\n modes: new Map<unknown, number>(\n modes.map((mode, index) => [mode, index])\n ),\n fallback: modes.indexOf(member.default),\n stride,\n };\n stride *= modes.length;\n return bound;\n });\n const domains: RowDomain[] = [];\n const verbs = modelVerbs(declared);\n // Whether a model may project: a lazy entry may, until it is read.\n const projects = declared.some((member) =>\n Object.values(member.verbs ?? {}).some(\n (entry) =>\n typeof entry === \"function\" ||\n entry.evidence !== undefined ||\n Object.keys(entry.reads ?? {}).length > 0\n )\n );\n for (let combination = 0; combination < stride; combination++) {\n const modes = members.map(\n (member) =>\n member.names[\n Math.floor(combination / member.stride) % member.names.length\n ]!\n );\n domains.push(\n Object.freeze({\n root: modelDomain(declared, modes, \"root\"),\n related: modelDomain(declared, modes, \"related\"),\n ...(verbs && { verbs, projects }),\n })\n );\n }\n const defaults =\n domains[\n members.reduce(\n (index, member) => index + member.fallback * member.stride,\n 0\n )\n ]!;\n const tombstones =\n deletion === undefined ? undefined : new Map(Object.entries(deletion));\n const stamps =\n data === undefined\n ? undefined\n : new Map(\n Object.entries(data).map(([model, entry]) => {\n const create = withInstants(entry.create);\n const update = withInstants(entry.update);\n return [\n model,\n create === entry.create && update === entry.update\n ? entry\n : Object.freeze({ create, update }),\n ] as const;\n })\n );\n const stampReferences = new Set<string>();\n for (const entry of stamps?.values() ?? []) {\n collectStampReferences(entry.create, stampReferences);\n collectStampReferences(entry.update, stampReferences);\n }\n const physical = domains.map((domain) =>\n Object.freeze({ domain, defaults, ...(stamps && { stamps }) })\n );\n // A lazy entry's predicates are not known yet: its calls carry their values.\n const lazy = declared.some(isLazy);\n const verbsRead =\n lazy ||\n declared.some((member) =>\n Object.values(member.verbs ?? {}).some(\n (entry) => typeof entry !== \"function\" && readsCall(entry.predicates)\n )\n );\n const reads = (domain: RowDomain) =>\n verbsRead ||\n [domain.root, domain.related].some((models) =>\n [...models.values()].some(readsCall)\n );\n return Object.freeze({\n members,\n deletion: deletion ?? NO_DELETION,\n physical,\n tombstoning:\n tombstones === undefined\n ? physical\n : physical.map((facts) => Object.freeze({ ...facts, tombstones })),\n parametric: domains.map((domain) => reads(domain) || reads(defaults)),\n bindsStamps: stampReferences.size > 0,\n required: requiredOn(controls),\n });\n}\n\n/**\n * One call's row facts, from the controls it admitted: the modes its `rows`\n * controls chose (an absent one reads as its default), and whether it deletes\n * physically — its model's `deletion` entry names a `removeWhen` the call's\n * controls match. That control is placed only on the deletes of the models\n * the entry manages, so no other call can match it. When its predicates read\n * a call value, the call carries its controls; when a stamp names a control,\n * the call's values are put in.\n */\nexport function callRows(\n binding: RowsBinding,\n model: string,\n controls: AdmittedControls | undefined\n): CallRows {\n let combination = 0;\n for (const member of binding.members) {\n combination +=\n member.stride *\n (member.modes.get(controls?.[member.control]) ?? member.fallback);\n }\n const removeWhen = binding.deletion[model]?.removeWhen;\n const physical =\n removeWhen !== undefined &&\n Object.entries(removeWhen).every(\n ([control, value]) => controls?.[control] === value\n );\n const facts = (physical ? binding.physical : binding.tombstoning)[\n combination\n ]!;\n const parametric = binding.parametric[combination]!;\n if (!(parametric || binding.bindsStamps)) return facts;\n return Object.freeze({\n ...facts,\n ...(parametric && {\n values: Object.freeze({\n controls: controls ?? NO_CONTROLS,\n required: binding.required,\n }),\n }),\n ...(binding.bindsStamps && {\n stamps: boundStamps(facts.stamps!, controls),\n }),\n });\n}\n"],"mappings":"oYAmBA,MAAa,EAAsB,eAiCtB,EAA+C,OAAO,OAAO,CACxE,MAAO,OAAO,OAAO,CACnB,OAAQ,OAAO,OAAO,CACpB,YAAa,OAAO,OAAO,CACzB,QAAS,EACT,OAAQ,SACR,SAAW,GACT,OAAO,OAAO,CACZ,MAAO,sBAAsB,CAAC,0BAA0B,EAAM,CAC/D,CAAC,CACL,CAAC,CACH,CAAC,CACF,GAAI,SACL,CAAC,CACH,CAAC,CA4BI,EAAsB,IAAI,QAI1B,EAAqB,IAAI,QAIzB,EAAsB,IAAI,QAIhC,IAAI,EAGJ,SAAgB,2BACd,EACA,EACA,EACM,CACN,EAAU,EACV,EAAoB,IAAI,EAAO,EAAW,CAI5C,SAAgB,4BACd,EACM,CACN,EAAU,EAIZ,SAAgB,sBAA6C,CAC3D,GAAI,IAAY,IAAA,GACd,MAAU,MACR,8EACD,CACH,OAAO,EAGT,SAAgB,gCACd,EAC+C,CAC/C,OAAO,EAAW,EAAM,CAAG,EAAoB,IAAI,EAAM,CAAG,IAAA,GAS9D,SAAgB,gCACd,EAC+C,CAC/C,OAAO,IAAU,IAAA,GAAY,IAAA,GAAY,EAAmB,IAAI,EAAM,CAIxE,SAAgB,gCACd,EACqC,CACrC,OAAO,IAAU,IAAA,GAAY,IAAA,GAAY,EAAoB,IAAI,EA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