viborm 1.4.0 → 1.4.2

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 (164) hide show
  1. package/dist/{adapter-namespace-BLejG8FA.mjs → adapter-namespace-NnXlXR8c.mjs} +2 -2
  2. package/dist/{adapter-namespace-BLejG8FA.mjs.map → adapter-namespace-NnXlXR8c.mjs.map} +1 -1
  3. package/dist/adapters.d.mts +1 -1
  4. package/dist/adapters.mjs +1 -1
  5. package/dist/builder-BxCr9ANq.mjs +2 -0
  6. package/dist/builder-BxCr9ANq.mjs.map +1 -0
  7. package/dist/bun-sql.d.mts +1 -1
  8. package/dist/bun-sql.mjs +1 -1
  9. package/dist/bun-sqlite.d.mts +1 -1
  10. package/dist/bun-sqlite.mjs +1 -1
  11. package/dist/cache/cloudflare-kv.d.mts +1 -1
  12. package/dist/cache/cloudflare-kv.mjs +1 -1
  13. package/dist/cache/memory.d.mts +1 -1
  14. package/dist/cache/memory.mjs +1 -1
  15. package/dist/cache.d.mts +1 -1
  16. package/dist/cache.mjs +1 -1
  17. package/dist/{chain-D5J9hIw-.mjs → chain-C4EUyLzF.mjs} +2 -2
  18. package/dist/{chain-D5J9hIw-.mjs.map → chain-C4EUyLzF.mjs.map} +1 -1
  19. package/dist/cli.mjs +1 -1
  20. package/dist/{client-BzgBm_86.d.mts → client-D-XiaClb.d.mts} +1 -1
  21. package/dist/client-DACEO6tS.mjs +2 -0
  22. package/dist/client-DACEO6tS.mjs.map +1 -0
  23. package/dist/{client-aU3YhZ6G.mjs → client-sAey5P-I.mjs} +2 -2
  24. package/dist/{client-aU3YhZ6G.mjs.map → client-sAey5P-I.mjs.map} +1 -1
  25. package/dist/client.d.mts +1 -1
  26. package/dist/client.mjs +1 -1
  27. package/dist/config.d.mts +1 -1
  28. package/dist/config.mjs +1 -1
  29. package/dist/current-C2fZL9Ln.mjs +2 -0
  30. package/dist/current-C2fZL9Ln.mjs.map +1 -0
  31. package/dist/d1.d.mts +1 -1
  32. package/dist/d1.mjs +1 -1
  33. package/dist/d1.mjs.map +1 -1
  34. package/dist/{datetime-physical-codec-lX7IJBlz.mjs → datetime-physical-codec-CFoeuitT.mjs} +2 -2
  35. package/dist/{datetime-physical-codec-lX7IJBlz.mjs.map → datetime-physical-codec-CFoeuitT.mjs.map} +1 -1
  36. package/dist/{driver-u2qJicrE.mjs → driver-BqD-3_jO.mjs} +2 -2
  37. package/dist/{driver-u2qJicrE.mjs.map → driver-BqD-3_jO.mjs.map} +1 -1
  38. package/dist/driver-DseQwbsu.mjs +2 -0
  39. package/dist/driver-DseQwbsu.mjs.map +1 -0
  40. package/dist/driver.d.mts +1 -1
  41. package/dist/driver.mjs +1 -1
  42. package/dist/every-CEQMQEdt.mjs +2 -0
  43. package/dist/{every-CzF00eDV.mjs.map → every-CEQMQEdt.mjs.map} +1 -1
  44. package/dist/execution-context-asSCmyas.mjs +2 -0
  45. package/dist/execution-context-asSCmyas.mjs.map +1 -0
  46. package/dist/{geo-area-codec-BmMmWgU_.mjs → geo-area-codec-4W5b7whM.mjs} +2 -2
  47. package/dist/{geo-area-codec-BmMmWgU_.mjs.map → geo-area-codec-4W5b7whM.mjs.map} +1 -1
  48. package/dist/geo-point-codec-pAWYj5ZZ.mjs +2 -0
  49. package/dist/geo-point-codec-pAWYj5ZZ.mjs.map +1 -0
  50. package/dist/{hydration-BflrXEIQ.mjs → hydration-Az2rjp5a.mjs} +2 -2
  51. package/dist/{hydration-BflrXEIQ.mjs.map → hydration-Az2rjp5a.mjs.map} +1 -1
  52. package/dist/{identifier-conversion-Dc0Rf4Gi.mjs → identifier-conversion-ufaCNi9E.mjs} +2 -2
  53. package/dist/{identifier-conversion-Dc0Rf4Gi.mjs.map → identifier-conversion-ufaCNi9E.mjs.map} +1 -1
  54. package/dist/{index-B4IWFJfv.d.mts → index-Ci8b13Lm.d.mts} +52 -6
  55. package/dist/index.d.mts +1 -1
  56. package/dist/index.mjs +1 -1
  57. package/dist/instrumentation.d.mts +1 -1
  58. package/dist/instrumentation.mjs +1 -1
  59. package/dist/instrumentation.mjs.map +1 -1
  60. package/dist/{key-B89Z4vxn.mjs → key-CyLRw0ne.mjs} +2 -2
  61. package/dist/{key-B89Z4vxn.mjs.map → key-CyLRw0ne.mjs.map} +1 -1
  62. package/dist/{libsql-CrDXsfpL.mjs → libsql-DPrXWc_J.mjs} +2 -2
  63. package/dist/{libsql-CrDXsfpL.mjs.map → libsql-DPrXWc_J.mjs.map} +1 -1
  64. package/dist/libsql.d.mts +1 -1
  65. package/dist/libsql.mjs +1 -1
  66. package/dist/libsql.mjs.map +1 -1
  67. package/dist/{memory-TXO4KgBy.mjs → memory-DiTWROVS.mjs} +2 -2
  68. package/dist/{memory-TXO4KgBy.mjs.map → memory-DiTWROVS.mjs.map} +1 -1
  69. package/dist/migrations/mysql.d.mts +4 -4
  70. package/dist/migrations/mysql.mjs +1 -1
  71. package/dist/migrations/postgres.d.mts +4 -4
  72. package/dist/migrations/postgres.mjs +1 -1
  73. package/dist/migrations/sqlite.d.mts +4 -4
  74. package/dist/migrations/sqlite.mjs +1 -1
  75. package/dist/migrations/tenant.d.mts +2 -2
  76. package/dist/migrations/tenant.mjs +1 -1
  77. package/dist/migrations.d.mts +4 -4
  78. package/dist/migrations.mjs +1 -1
  79. package/dist/{mysql-adapter-C5CMIYRS.mjs → mysql-adapter-B1U35CJn.mjs} +2 -2
  80. package/dist/{mysql-adapter-C5CMIYRS.mjs.map → mysql-adapter-B1U35CJn.mjs.map} +1 -1
  81. package/dist/{mysql-C2vOPcuA.mjs → mysql-fJlFIW7m.mjs} +2 -2
  82. package/dist/{mysql-C2vOPcuA.mjs.map → mysql-fJlFIW7m.mjs.map} +1 -1
  83. package/dist/mysql2.d.mts +1 -1
  84. package/dist/mysql2.mjs +1 -1
  85. package/dist/neon-http.d.mts +1 -1
  86. package/dist/neon-http.mjs +1 -1
  87. package/dist/{object-store-uRqi0URP.d.mts → object-store-H7fJwgPR.d.mts} +3 -3
  88. package/dist/permissions.d.mts +1 -1
  89. package/dist/permissions.mjs +1 -1
  90. package/dist/pg.d.mts +1 -1
  91. package/dist/pg.mjs +1 -1
  92. package/dist/pg.mjs.map +1 -1
  93. package/dist/pglite.d.mts +1 -1
  94. package/dist/pglite.mjs +1 -1
  95. package/dist/{physical-uJfmo4-Z.mjs → physical-C4D-979R.mjs} +2 -2
  96. package/dist/{physical-uJfmo4-Z.mjs.map → physical-C4D-979R.mjs.map} +1 -1
  97. package/dist/planetscale.d.mts +1 -1
  98. package/dist/planetscale.mjs +1 -1
  99. package/dist/planetscale.mjs.map +1 -1
  100. package/dist/{planner-SzkGh-3T.d.mts → planner-CUcPdJwD.d.mts} +1 -1
  101. package/dist/{postgres-BSmy1PYR.mjs → postgres-DD92WdFu.mjs} +2 -2
  102. package/dist/{postgres-BSmy1PYR.mjs.map → postgres-DD92WdFu.mjs.map} +1 -1
  103. package/dist/{postgres-adapter-BAqRfWl1.mjs → postgres-adapter-B7hzWhky.mjs} +2 -2
  104. package/dist/{postgres-adapter-BAqRfWl1.mjs.map → postgres-adapter-B7hzWhky.mjs.map} +1 -1
  105. package/dist/{postgres-adapter-B1RyJlWL.mjs → postgres-adapter-CJmoxTW7.mjs} +2 -2
  106. package/dist/{postgres-adapter-B1RyJlWL.mjs.map → postgres-adapter-CJmoxTW7.mjs.map} +1 -1
  107. package/dist/postgres.d.mts +1 -1
  108. package/dist/postgres.mjs +1 -1
  109. package/dist/postgres.mjs.map +1 -1
  110. package/dist/{provider-limits-V09frtmK.mjs → provider-limits-D0ECF7_Q.mjs} +2 -2
  111. package/dist/{provider-limits-V09frtmK.mjs.map → provider-limits-D0ECF7_Q.mjs.map} +1 -1
  112. package/dist/result-shape-ic2j3Tze.mjs +2 -0
  113. package/dist/result-shape-ic2j3Tze.mjs.map +1 -0
  114. package/dist/{rows-BiaiswSV.mjs → rows-YyvK9MDz.mjs} +2 -2
  115. package/dist/{rows-BiaiswSV.mjs.map → rows-YyvK9MDz.mjs.map} +1 -1
  116. package/dist/{scalar-Cm7nMFmO.mjs → scalar-Dyns7kc7.mjs} +2 -2
  117. package/dist/{scalar-Cm7nMFmO.mjs.map → scalar-Dyns7kc7.mjs.map} +1 -1
  118. package/dist/schema/json.d.mts +1 -1
  119. package/dist/schema/json.mjs +1 -1
  120. package/dist/{schema-tGtziyCJ.mjs → schema-CUm_yh6L.mjs} +2 -2
  121. package/dist/{schema-tGtziyCJ.mjs.map → schema-CUm_yh6L.mjs.map} +1 -1
  122. package/dist/{schema-introspection-C1-XrQP4.mjs → schema-introspection-LpRNeSG2.mjs} +2 -2
  123. package/dist/{schema-introspection-C1-XrQP4.mjs.map → schema-introspection-LpRNeSG2.mjs.map} +1 -1
  124. package/dist/schema.d.mts +1 -1
  125. package/dist/schema.mjs +1 -1
  126. package/dist/soft-delete.d.mts +1 -1
  127. package/dist/{sqlite-adapter-CoDeF2h2.mjs → sqlite-adapter-CLWY4B8w.mjs} +2 -2
  128. package/dist/sqlite-adapter-CLWY4B8w.mjs.map +1 -0
  129. package/dist/{sqlite-utils-C0TyzOys.mjs → sqlite-utils-C5_KQPZn.mjs} +2 -2
  130. package/dist/{sqlite-utils-C0TyzOys.mjs.map → sqlite-utils-C5_KQPZn.mjs.map} +1 -1
  131. package/dist/sqlite3.d.mts +1 -1
  132. package/dist/sqlite3.mjs +1 -1
  133. package/dist/{to-many-Btc9X5Ga.mjs → to-many-DxQuOBuq.mjs} +2 -2
  134. package/dist/{to-many-Btc9X5Ga.mjs.map → to-many-DxQuOBuq.mjs.map} +1 -1
  135. package/dist/{utils-DkAxKcDD.mjs → utils-CQ2nQwwO.mjs} +2 -2
  136. package/dist/{utils-DkAxKcDD.mjs.map → utils-CQ2nQwwO.mjs.map} +1 -1
  137. package/dist/{v-514RME2X.mjs → v-BcroBusN.mjs} +2 -2
  138. package/dist/{v-514RME2X.mjs.map → v-BcroBusN.mjs.map} +1 -1
  139. package/dist/{validation-C7Z6wTJa.mjs → validation-CjWRiLWU.mjs} +2 -2
  140. package/dist/{validation-C7Z6wTJa.mjs.map → validation-CjWRiLWU.mjs.map} +1 -1
  141. package/dist/validation.d.mts +1 -1
  142. package/dist/validation.mjs +1 -1
  143. package/dist/{validator-CQOw7G3q.mjs → validator-yrGnrsAo.mjs} +2 -2
  144. package/dist/{validator-CQOw7G3q.mjs.map → validator-yrGnrsAo.mjs.map} +1 -1
  145. package/dist/version-DLtcW9kn.mjs +2 -0
  146. package/dist/{version-n393hhwM.mjs.map → version-DLtcW9kn.mjs.map} +1 -1
  147. package/package.json +15 -15
  148. package/dist/builder-BS8EW4BQ.mjs +0 -2
  149. package/dist/builder-BS8EW4BQ.mjs.map +0 -1
  150. package/dist/client-Bhl2mWam.mjs +0 -2
  151. package/dist/client-Bhl2mWam.mjs.map +0 -1
  152. package/dist/current-oXcxSCBQ.mjs +0 -2
  153. package/dist/current-oXcxSCBQ.mjs.map +0 -1
  154. package/dist/driver-CQQbCQh9.mjs +0 -2
  155. package/dist/driver-CQQbCQh9.mjs.map +0 -1
  156. package/dist/every-CzF00eDV.mjs +0 -2
  157. package/dist/execution-context-rJXTRVrJ.mjs +0 -2
  158. package/dist/execution-context-rJXTRVrJ.mjs.map +0 -1
  159. package/dist/geo-point-codec-D95uXgDF.mjs +0 -2
  160. package/dist/geo-point-codec-D95uXgDF.mjs.map +0 -1
  161. package/dist/result-shape-Fi1-Fvri.mjs +0 -2
  162. package/dist/result-shape-Fi1-Fvri.mjs.map +0 -1
  163. package/dist/sqlite-adapter-CoDeF2h2.mjs.map +0 -1
  164. package/dist/version-n393hhwM.mjs +0 -2
@@ -1,2 +0,0 @@
1
- import{n as e}from"./chunk-BuuaeEvq.mjs";import{i as t,o as n}from"./value-guards-CK9guf2Z.mjs";import{C as r,N as i,_ as a,h as o,j as s,r as c,x as l}from"./rows-BiaiswSV.mjs";import{f as u,i as d,r as f}from"./chain-D5J9hIw-.mjs";import{S as p,t as m}from"./base-D3m1S7Uc.mjs";import{a as h,h as g,r as _}from"./error-mapping-6op318w6.mjs";import{d as v,f as y,p as b,y as x}from"./validation-gwZYm3Yn.mjs";import{t as S}from"./transaction-4dfqals6.mjs";import{t as C}from"./sql-BvHwL73I.mjs";import{p as w}from"./validator-CQOw7G3q.mjs";import{o as T,s as E}from"./builder-BS8EW4BQ.mjs";import{t as D}from"./types-C5Oxz9yp.mjs";import{i as O,t as k}from"./observation-Co72iCd1.mjs";import{a as A,o as j,r as M}from"./execution-context-rJXTRVrJ.mjs";import{n as N}from"./transaction-operation-CU1zlxiG.mjs";import{t as P}from"./adapter-result-parser-D6lluSMi.mjs";import{n as F}from"./bind-parameter-capacity-D6p9HrbB.mjs";import{t as I}from"./result-parsing-CQf_eCl8.mjs";const L=new WeakMap,R=new WeakMap;function executePreparedQuery(e,t,n,r,i,a,o){return(e===void 0||t===void 0||t.length===0)&&o===void 0?n():!r&&o===void 0&&e!==void 0&&t!==void 0&&t.length>0?runCompiledQueryInterceptors(e,t,n,discardReadWriteOutcomeRegistration,a?.readCommitCertainty,a?.reportAdmissionFailure):executeInterceptedQuery(e,t,n,r,i,a,o)}function discardReadWriteOutcomeRegistration(){}async function executeInterceptedQuery(e,t,n,r,i,a,o){let s=o===void 0?[]:[o];o!==void 0&&i?.stage(o);let captureWriteOutcome=e=>{s.push(e),i?.stage(e)},c=0,l,u=!1,publish=async e=>{if(i){if(s.length===0||u)return;u=!0,i.confirm(s);return}c+=1,l=e,s.length!==0&&await publishWriteOutcomes(s,{certainty:e})},d=Object.freeze({committed:()=>publish(`committed`),mayHaveCommitted:()=>publish(`may-have-committed`)}),executeChild=async()=>{try{let e=await n(d);return r&&(i!==void 0||c===0)&&await publish(`committed`),e}catch(e){throw i&&!u&&i.discard(s),e}};try{return e===void 0||t===void 0||t.length===0?await executeChild():await runCompiledQueryInterceptors(e,t,executeChild,captureWriteOutcome,()=>l??a?.readCommitCertainty?.(),a?.reportAdmissionFailure)}catch(e){throw i&&!u&&i.discard(s),e}}function runCompiledQueryInterceptors(e,t,n,r,i,a){return t===void 0||t.length===0?n():runInterceptorAt(e,t,0,n,r,i,a)}function runInterceptorAt(e,t,n,r,i,a,o){let s=t[n];return s===void 0?r():runOneInterceptor(e,s,()=>runInterceptorAt(e,t,n+1,r,i,a,o),i,a,o)}async function runOneInterceptor(e,n,r,i,a,o){let s=!0,c,l=!1,u=!0,d,recordProtocolFailure=t=>{if(d)return d;let r=interceptorError(n.extension,e,t);return d=r,o?.(r),r},proceed=()=>{if(!s)throw recordProtocolFailure(`called proceed more than once`);if(l)throw recordProtocolFailure(`called proceed after its handler settled`);u=!1,s=!1;let e=startChild(r);return c=settle(e),e},onWriteOutcome=e=>{if(!t(e))throw recordProtocolFailure(`registered a non-function write-outcome listener`);if(!u||l)throw recordProtocolFailure(`registered a write-outcome listener after proceed`);i(Object.freeze({extension:n.extension,listener:e}))},f=exposeHandlerContext(e,proceed,onWriteOutcome,n.controls),p;try{p=Promise.resolve(Reflect.apply(n.handler,void 0,[f]))}catch(e){p=Promise.reject(e)}let m=await settle(p);l=!0,u=!1;let h=m.status===`fulfilled`?m:{...m,failure:d!==void 0&&m.reason===d?d:interceptorFailure(n.extension,e,m.reason,a?.())};if(c!==void 0&&h.status===`rejected`&&h.reason!==d&&o?.(h.failure),c===void 0){if(d)throw d;if(h.status===`rejected`)throw h.failure;if(requiresProceed(e))throw interceptorError(n.extension,e,`completed without proceed`);return h.value}let g=await c;if(g.status===`rejected`){let e=selectExtensionFailures(d,h,g);throw e?retainSuppressedFailures(g.reason,e):g.reason}let _=selectExtensionFailures(d,h,g);return _&&throwExtensionFailures(_),h.value}function selectExtensionFailures(e,t,n){if(e&&n.status===`rejected`&&n.reason===e)return;if(t.status!==`rejected`||e!==void 0&&t.reason===e||n.status===`rejected`&&t.reason===n.reason)return e?[e]:void 0;let r=t.failure;return e?[e,r]:[r]}function exposeHandlerContext(e,t,n,r){return Object.freeze({mode:e.mode,kind:e.kind,model:e.model,operation:e.operation,get input(){return e.input},...e.kind===`model`&&r!==void 0?{controls:a(e.controls,r)}:{},proceed:t,onWriteOutcome:n})}function startChild(e){try{return Promise.resolve(e())}catch(e){return Promise.reject(e)}}async function settle(e){try{return{status:`fulfilled`,value:await e}}catch(e){return{status:`rejected`,reason:e}}}function requiresProceed(e){return e.mode===`array`||e.kind!==`model`||!r(e.operation)}function interceptorFailure(e,t,n,r){return p(n)?n:interceptorError(e,t,`failed`,Error(`Query interceptor rejected with a non-Error value`),r)}function interceptorError(e,t,n,r,i){let a=`Extension "${e}" query handler for ${describeOperation(t)} ${n}.`,o={method:`query`,model:t.model,operation:String(t.operation),...i===void 0?{}:{commitCertainty:i}};return r?new b(a,{cause:r,meta:o}):new b(a,{meta:o})}function describeOperation(e){return e.kind===`model`?`${e.model}.${e.operation}`:e.operation}function throwExtensionFailures(e){let t=e[0];throw e.length===1?t:AggregateError(e,`Query interceptor protocol and handler both failed.`,{cause:t})}function retainSuppressedFailures(e,t){let n=AggregateError([e,...t],`Query execution and extension post-work both failed.`,{cause:e});return L.set(n,e),n}function decomposeQueryCoordinationFailure(e){if(!(e instanceof AggregateError)||!L.has(e))return;let t=L.get(e);if(!(e.cause!==t||e.errors[0]!==t))return Object.freeze({child:t,postWork:Object.freeze(e.errors.slice(1))})}var TransactionWriteOutcomes=class{#e=[];stage(e){for(let t of this.#e)if(t.registration===e)return;this.#e.push({registration:e,state:`pending`})}confirm(e){this.#t(e,`confirmed`)}discard(e){this.#t(e,`discarded`)}discardAll(){for(let e of this.#e)e.state=`discarded`}promoteTo(e){for(let t of this.#e)t.state===`confirmed`&&e.#e.push({...t}),t.state=`discarded`}publishCommitted(){return this.publish(`committed`)}async publish(e){let t=[];for(let e of this.#e)e.state===`confirmed`&&t.push(e.registration),e.state=`discarded`;await publishWriteOutcomes(t,{certainty:e})}#t(e,t){for(let n of this.#e)n.state===`pending`&&e.includes(n.registration)&&(n.state=t)}};async function publishWriteOutcomes(e,t){let n;for(let r of e)try{await r.listener(t)}catch(e){let i=p(e)?e:void 0,a=r.failurePolicy===`boundary-owned`&&i!==void 0?i:new b(`Extension "${r.extension}" write-outcome listener failed after ${t.certainty}.`,{cause:i??Error(`Write-outcome listener rejected with a non-Error value`),meta:{method:`onWriteOutcome`,commitCertainty:t.certainty}});(n??=[]).push(a)}if(n===void 0)return;let[r]=n;if(n.length===1)throw r;let i=AggregateError(n,`Multiple extension write-outcome listeners failed.`,{cause:r});throw R.set(i,n),i}function decomposeWriteOutcomePublicationFailure(e){return e instanceof AggregateError?R.get(e)??[e]:[e]}function createOperationExecutionContext(e,t,n){let r=k(n)?.diagnostics?.includeCallsite===!0?Error(`VibORM operation created here`).stack:void 0;return M({model:e,operation:t},createCorrelationId,n,r)}function createPendingOperationContext(e,t,n,r,i){return Object.freeze({clientId:n,scopeId:r,attribution:createOperationExecutionContext(e,t,i)})}function withOperationErrorContext(e,t){let n=A(e);if(n===void 0)return t();let r=k(j(e))?.diagnostics,annotate=t=>{throw t instanceof m?h(t,{forceContext:!1,driverName:typeof t.meta.driver==`string`?t.meta.driver:`unknown`,model:e.model,operation:e.operation,correlationId:e.correlationId,callsite:n,diagnostics:r}):t};try{return t().catch(annotate)}catch(e){return Promise.reject().catch(()=>annotate(e))}}function createPendingOperationInstrumentationFacts(e,t,n,r,i,a,o){return createOperationInstrumentationFacts(e,t,n,r,i,a,o)}function createRawOperationInstrumentationFacts(e,t,n){return createOperationInstrumentationFacts(e,t,void 0,n,n,void 0,!1)}function createOperationInstrumentationFacts(e,t,n,r,a,o,s){let c=k(j(t));if(c?.observesLifecycle===!0)return()=>Object.freeze({kind:`operation`,context:t,identity:u(e),model:n,requestedOperation:r,operation:a,collection:o,complete(e){let n=s?i().readCacheExecutionOutcomes(t):void 0,{failure:r}=e,a=e.status===`failure`&&c.wants(`error-log`)&&isUnloggedError(r)?r:void 0,o=e.status===`failure`&&r instanceof Error&&c.wants(`operation`)?r:void 0;if(!(n===void 0&&a===void 0&&o===void 0))return Object.freeze({kind:`operation`,endedAt:Date.now(),...n===void 0?{}:{readCacheOutcomes:n},...(a??o)===void 0?{}:{failure:a??o},...a===void 0?{skipLog:!0}:{}})}})}async function observeTransactionBatchPhase(e,t,n){let r=k(j(e))?.diagnostics;try{return await n()}catch(n){throw _(n,{driverName:t.driverName,dialect:t.dialect,model:e.model,operation:e.operation,correlationId:e.correlationId,callsite:A(e),diagnostics:r,forceContext:!0})}}function createCorrelationId(){return typeof globalThis.crypto?.randomUUID==`function`?globalThis.crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`}function isUnloggedError(e){return e instanceof Error&&!g(e)}function captureExecution(e){try{return e()}catch(e){return Promise.reject(e)}}var PendingExecution=class{#e=null;#t=null;#n=!1;#r;#i;constructor(e,t){this.#r=e,this.#i=t}executeDefault(e){if(this.#t!==null&&this.#t!==`default`)throw v.alreadyExecutedWithDriver(this.#r,this.#i);return this.#e||=(this.#t=`default`,captureExecution(e)),this.#e}executeWith(e,t){if(this.#n)throw v.alreadyExecutedWithDriver(this.#r,this.#i);if(this.#t===`default`)throw v.alreadyExecutedDefault(this.#r,this.#i);if(this.#t!==null&&this.#t!==e)throw v.differentDriverConflict(this.#r,this.#i);return this.#e||=(this.#t=e,captureExecution(t)),this.#e}reserveWith(e){if(this.#t===`default`)throw v.alreadyExecutedDefault(this.#r,this.#i);if(this.#t!==null)throw this.#t===e?v.alreadyExecutedWithDriver(this.#r,this.#i):v.differentDriverConflict(this.#r,this.#i);this.#t=e,this.#n=!0}executeReserved(e){return this.#e||=captureExecution(e),this.#e}};const z=Object.freeze({accessor:opaqueInspectionValue(`accessor`),function:opaqueInspectionValue(`function`),unsupported:opaqueInspectionValue(`unsupported`)}),B=Object.getOwnPropertyDescriptor(C.prototype,`strings`)?.get,V=Object.getOwnPropertyDescriptor(C.prototype,`values`)?.get;function opaqueInspectionValue(e){let t=Object.create(null);return t.opaque=e,Object.freeze(t)}function snapshotQueryInput(e){return snapshotOwn(e,new Map,!1)}function snapshotOwn(e,t,n){let r=n?[]:Object.create(null);t.set(e,r);let i;try{i=Reflect.ownKeys(e)}catch{return t.set(e,z.unsupported),z.unsupported}for(let a of i){let i;try{i=Object.getOwnPropertyDescriptor(e,a)}catch{return t.set(e,z.unsupported),z.unsupported}if(i!==void 0){if(n&&a===`length`){Object.defineProperty(r,a,i);continue}i.enumerable&&Object.defineProperty(r,a,{configurable:!1,enumerable:!0,value:`value`in i?snapshotValue(i.value,t):z.accessor,writable:!1})}}return Object.freeze(r)}function snapshotValue(e,t){if(typeof e==`function`)return z.function;if(typeof e!=`object`||!e)return e;if(t.has(e))return t.get(e);try{if(Array.isArray(e))return snapshotOwn(e,t,!0);let r=Object.getPrototypeOf(e);if(r===C.prototype&&e instanceof C)return snapshotSql(e,t);if(r===Date.prototype&&e instanceof Date){let n=Object.freeze(new Date(Date.prototype.getTime.call(e)));return t.set(e,n),n}if(e instanceof Uint8Array){let n=new Uint8Array(e);return t.set(e,n),n}if(r===ArrayBuffer.prototype&&e instanceof ArrayBuffer){let n=e.slice(0);return t.set(e,n),n}if(r===Map.prototype&&e instanceof Map){let n=new Map;return t.set(e,n),Map.prototype.forEach.call(e,(e,r)=>{n.set(snapshotValue(r,t),snapshotValue(e,t))}),n}if(r===Set.prototype&&e instanceof Set){let n=new Set;return t.set(e,n),Set.prototype.forEach.call(e,e=>{n.add(snapshotValue(e,t))}),n}if(ArrayBuffer.isView(e)){let n=structuredClone(e);return t.set(e,n),n}if((r===Object.prototype||r===null)&&n(e))return snapshotOwn(e,t,!1)}catch{}return t.set(e,z.unsupported),z.unsupported}function snapshotSql(e,t){if(!(B&&V))throw TypeError(`Sql inspection getters are unavailable`);let n=Reflect.apply(B,e,[]),r=Reflect.apply(V,e,[]),i=Array(n.length);for(let e=0;e<n.length;e+=1){let t=Object.getOwnPropertyDescriptor(n,e);if(!(t&&`value`in t&&typeof t.value==`string`))throw TypeError(`Sql inspection strings are not plain data values`);i[e]=t.value}let a=Array(r.length),o=new C(i,a);t.set(e,o);for(let e=0;e<r.length;e+=1){let n=Object.getOwnPropertyDescriptor(r,e);a[e]=n&&`value`in n?snapshotValue(n.value,t):z.accessor}o.toStatement(`?`),o.toStatement(`$n`),o.toStatement(`:n`);for(let e of Reflect.ownKeys(o)){let t=Reflect.get(o,e);typeof t==`object`&&t&&Object.freeze(t)}return Object.freeze(o),o}function compileBindBudgetChunks(e,t,n){if(e===0)return[];let r=n(0,e);if(t===void 0||r.values.length<=t||e===1)return[{start:0,end:e,statement:r}];let i=[],a=0;for(;a<e;){let r=a+1,o=Math.min(e,a+1),s;for(;;){let i=n(a,o);if(i.values.length>t||(s={start:a,end:o,statement:i},o===e))break;r=o+1,o=Math.min(e,a+(o-a)*2)}if(s?.end!==e)for(--o;r<=o;){let e=r+Math.floor((o-r)/2),i=n(a,e);i.values.length<=t?(s={start:a,end:e,statement:i},r=e+1):o=e-1}let c=s??{start:a,end:a+1,statement:n(a,a+1)};i.push(c),a=c.end}return i}const H=Symbol(`run alone`),U={string:e=>typeof e==`string`,int:e=>typeof e==`number`&&Number.isSafeInteger(e),bigint:e=>typeof e==`bigint`};let W;const G=(()=>{let e=globalThis.process,t=e?.nextTick;return typeof t==`function`?n=>t.call(e,n):queueMicrotask})();function batchFindUnique(e){if(!engineBatches(e.engine))return;let t;try{t=e.routed.preparedArgs}catch{return}let n=keyOf(e.model,t.where);if(n===void 0)return;let{where:r,...i}=e.args,a=signatureOf(i);if(a===void 0)return;let o,s=new Promise(e=>{o=e}),c={values:n.values,signature:signatureOf(n.values),orThrow:e.requested!==`findUnique`,decide:o};return enqueue(e,`${n.selector}\u0000${a}`,n,c),s.then(t=>t===H?e.run():t.value)}function engineBatches(e){let{driver:t}=e;return t===e.route.driver&&(e.extensionChain?.statement.length??0)===0&&t.result?.parseResult===void 0&&t.adapter.result.parseResult===P}function keyOf(e,t){if(!n(t))return;let r=Object.keys(t);if(r.length!==1)return;let i=r[0],a=w(e,i);if(a===void 0)return;let o=t[i],s;if(a.name===void 0)s=[o];else{if(!n(o)||Object.keys(o).length!==a.fields.length)return;s=a.fields.map(e=>o[e])}let{scalars:c,omit:l}=e[`~`].state,u=!1;for(let[e,t]of a.fields.entries()){let n=c[t]?.[`~`].state;if(!(n&&!n.array&&U[n.type])?.(s[e])||l?.[t]===!0)return;n.type===`string`&&(u=!0)}return{selector:i,fields:a.fields,values:s,textKey:u}}function enqueue(e,t,n,r){W===void 0&&(W=new Map,G(flush));let i=W.get(e.engine);i===void 0&&W.set(e.engine,i=new Map);let a=`${e.model[`~`].names.ts}\u0000${t}`,o=i.get(a);o===void 0&&i.set(a,o=[]);let s=o.find(t=>sameControls(t.leader.controls,e.controls));s===void 0&&(s={leader:e,fields:n.fields,textKey:n.textKey,members:[]},o.push(s)),s.members.push(r)}function sameControls(e,t){if(e===t)return!0;if(e===void 0||t===void 0)return!1;let n=Object.keys(e);return n.length===Object.keys(t).length&&n.every(n=>Object.hasOwn(t,n)&&e[n]===t[n])}function flush(){let e=W;W=void 0;for(let t of e.values())for(let e of t.values())for(let t of e)runBatch(t)}function runBatch(e){let{members:t}=e,runAlone=e=>{for(let t of e)t.decide(H)};if(t.length===1){runAlone(t);return}try{let n=new Map;for(let e of t){let t=n.get(e.signature);t?t.push(e):n.set(e.signature,[e])}let r=planBatch(e,[...n.values()]),{engine:i,context:a}=e.leader;for(let t of r.chunks){let o=t.signatures.flatMap(e=>n.get(e));t.read.execute({committedWriteSegment:void 0,context:a,driverOverride:void 0,engineDriver:i.driver,isWrite:!1,writeMayBeVisible:void 0}).then(i=>{try{dispatch(e,t,n,r.injected,i)}catch{runAlone(o)}},()=>runAlone(o))}}catch{runAlone(t)}}function planBatch(e,t){let{leader:n,fields:r}=e,i=projectionWithKey(n,r),a=n.rows(),o=new Map,read=(e,s)=>{let c=`${e}:${s}`,l=o.get(c);if(l===void 0){let u=t.slice(e,s).map(e=>e[0].values);l=n.engine.route.operation(n.model,`findMany`,{...i.args,where:mergedWhere(r,u)},a),o.set(c,l)}return l},s=t.map(e=>e[0].signature),c=F(n.engine.driver.maxBindParametersPerStatement);return{chunks:(c===void 0?[{start:0,end:t.length}]:compileBindBudgetChunks(t.length,c,(e,t)=>read(e,t).buildStatement())).map(({start:e,end:t})=>({signatures:s.slice(e,t),read:read(e,t)})),injected:i.injected}}function mergedWhere(e,t){return e.length===1?{[e[0]]:{in:t.map(e=>e[0])}}:{OR:t.map(t=>Object.fromEntries(e.map((e,n)=>[e,t[n]])))}}function projectionWithKey(e,t){let{where:r,...i}=e.args,a=e.routed.preparedArgs.select,o=[];if(!n(a))return{args:i,injected:o};for(let e of t)a[e]!==!0&&(n(i.select)&&(i.select={...i.select,[e]:!0}),n(i.omit)&&(i.omit={...i.omit,[e]:!1}),o.push(e));return{args:i,injected:o}}function dispatch(e,t,n,r,i){let a=new Map;for(let t of i){let n=signatureOf(e.fields.map(e=>t[e]));for(let e of r)delete t[e];a.has(n)||a.set(n,t)}for(let r of t.signatures){let t=a.get(r);for(let[i,a]of n.get(r).entries())t===void 0?a.orThrow||e.textKey?a.decide(H):a.decide({value:null}):a.decide({value:i===0?t:copyResult(t)})}}function signatureOf(e){switch(typeof e){case`undefined`:return`u`;case`boolean`:case`number`:return String(e);case`string`:return JSON.stringify(e);case`bigint`:return`${e}n`;case`object`:break;default:return}if(e===null)return`null`;if(Array.isArray(e)){let t=[];for(let n of e){let e=signatureOf(n);if(e===void 0)return;t.push(e)}return`[${t.join(`,`)}]`}if(e instanceof Date)return`D${e.getTime()}`;let t=Object.getPrototypeOf(e);if(t!==Object.prototype&&t!==null)return;let n=[];for(let[t,r]of Object.entries(e)){let e=signatureOf(r);if(e===void 0)return;n.push(`${JSON.stringify(t)}:${e}`)}return`{${n.join(`,`)}}`}function copyResult(e,t=new Map){if(typeof e!=`object`||!e)return e;let n=t.get(e);if(n!==void 0)return n;if(e instanceof Date)return new Date(e.getTime());if(e instanceof Uint8Array)return Uint8Array.prototype.slice.call(e);if(Array.isArray(e)){let n=[];t.set(e,n);for(let r of e)n.push(copyResult(r,t));return n}let r=Object.getPrototypeOf(e);if(r!==Object.prototype&&r!==null)return e;let i=Object.create(r);t.set(e,i);for(let[n,r]of Object.entries(e))Object.defineProperty(i,n,{value:copyResult(r,t),enumerable:!0,writable:!0,configurable:!0});return i}const K=Symbol.for(`viborm.pendingOperation`);let attachPendingCacheExecutionFriend,readPendingCacheResultFriend;function combineWriteNotifications(e,t){return e===void 0?t:t===void 0||t===e?e:async()=>{let n=!1,r;try{await e()}catch(e){n=!0,r=e}try{await t()}catch(e){throw n?x(r,e,`Write publication callbacks both failed.`):e}if(n)throw r}}const q=Object.freeze({});let createPendingOperationFriend,J;var Y=class PendingOperation{[Symbol.toStringTag]=`Promise`;[K]=!0;#e;#t;#n;#r;#i;#a;#o;#s;#c;#l;#u;#d;#f=!1;#p;#m;#h;#g;#_;#v=!1;static{createPendingOperationFriend=(e,t,n,r,i,a,o)=>new PendingOperation(q,e,t,n,r,i,void 0,void 0,a===void 0?void 0:{prepare:a,status:`pending`},void 0,o),attachPendingCacheExecutionFriend=(e,t)=>e.#L(t),readPendingCacheResultFriend=e=>({get args(){return e.cacheKeyArgs()},get controls(){return e.#y(),e.#l?.controls},get codec(){return e.#E()},executionContext:e.#e.attribution}),J=Object.freeze({clientId:e=>e.#e.clientId,scopeId:e=>e.#e.scopeId,model:e=>e.#i,operation:e=>e.#a,context:e=>e.#e.attribution,requiresInterception:e=>{let t=String(e.#o.originalOperation),n=d(e.#t.extensionChain,`request`,e.#i,t),r=n!==void 0&&n.length>0&&(e.#t.extensionChain?.observe.length??0)>0,i=d(e.#t.extensionChain,`query`,e.#i,t);return r||i!==void 0&&i.length>0||e.#u!==void 0},prepareAdmission:(e,t=`input`)=>{e.#w(),t===`plan`&&e.#C()},stagePackageWriteOutcomes:(e,t)=>{let n=e.#b();n!==void 0&&t.stage(n)},startInterception:(e,t,n,i)=>{let a=String(e.#o.originalOperation),o=d(e.#t.extensionChain,`query`,e.#i,a),s=e.#w(),c=e.#b();return(o===void 0||o.length===0)&&c===void 0?t():executePreparedQuery(o===void 0||o.length===0?void 0:e.#T(`array`,s),o,t,!r(a),n,i,c)},executeCore:(e,t,n)=>e.#s.executeReserved(()=>e.#P(t,n?.committed,n?.mayHaveCommitted)),isWrite:e=>!r(String(e.#o.originalOperation)),hasObservation:e=>(e.#t.extensionChain?.observe.length??0)>0,observe:(e,t,n)=>{let r=e.#t.extensionChain?.observe;return r===void 0||r.length===0?t():O(r,String(e.#o.originalOperation),e.#i,t,n,e.#k())},reserveWith:(e,t)=>{e.#s.reserveWith(t)},executeWith:(e,t)=>{let n=e.#t.extensionChain?.observe;return n===void 0||n.length===0?e.#s.executeWith(t,()=>e.#P(t)):e.#s.executeWith(t,()=>O(n,String(e.#o.originalOperation),e.#i,()=>e.#P(t),()=>e.#m===void 0?void 0:{commitCertainty:e.#m},e.#k()))},finishResult:(e,t)=>e.#o.finishResult?e.#o.finishResult(t):t,prepare:e=>e.#C()?.queries[0],prepareBatch:e=>e.#x().prepareBatch(e.#e.attribution),parseResult:(e,t)=>{let n=e.#C();if(!n)throw new y(`Operation '${e.#a}' on model '${e.#i}' publishes no single driver result to parse.`);return n.parseResult([t])},observeBatchPhase:(e,t,n)=>observeTransactionBatchPhase(e.#e.attribution,t,n)}),N(PendingOperation.prototype,e=>#e in e,J),Object.freeze(PendingOperation.prototype)}constructor(e,t,n,r,i,a,o,s,c,l,u){if(e!==q)throw new S;this.#t=t,this.#n=n,this.#r=i,this.#c=s,this.#l=c,this.#u=u,this.#p=l,this.#h=t.route;let d=r.endsWith(`OrThrow`);this.#a=d?r.slice(0,-7):r,this.#i=n[`~`].names.ts??`unknown`,this.#s=new PendingExecution(this.#i,this.#a),this.#o=Object.freeze({...a,throwIfNotFound:d||a?.throwIfNotFound,originalOperation:a?.originalOperation??r}),this.#e=o??createPendingOperationContext(this.#i,this.#a,t.clientId,t.scopeId,t.extensionChain),Object.freeze(this)}#y(){let e=this.#l;if(e===void 0)return this.#r;if(e.status===`success`&&e.args)return e.args;if(e.status===`failure`)throw e.error;try{let t=f(this.#t.extensionChain,this.#i,String(this.#o.originalOperation)),n=t.length===0?void 0:o(this.#i,this.#a,this.#r,t,this.#t.bound),r=e.prepare(n?.args??this.#r,n?.controls);return e.args=r,e.controls=n?.controls,e.status=`success`,r}catch(t){throw e.error=t,e.status=`failure`,t}}#b(){return this.#f?this.#d:(this.#d=this.#u?.(this.#e.attribution,this.#l?.controls),this.#f=!0,this.#d)}#x(){let e=this.#p?.routed;if(e)return e;if(this.#g)return this.#g;if(!l.has(this.#a))throw new y(`Unknown operation '${this.#a}' on model '${this.#i}'. Known operations: ${[...l].sort().join(`, `)}.`);let t=this.#y(),n=this.#h.operation(this.#n,String(this.#o.originalOperation),t,this.#S());return this.#g=n,this.#p&&(this.#p.routed=n),n}#S(){let e=this.#t.extensionChain?.callRows;return e&&c(e,this.#i,this.#l?.controls)}#C(){if(this.#v)return this.#_;let e=this.#x().prepareSingle(this.#e.attribution);return this.#_=e?.queries.length===1?e:void 0,this.#v=!0,this.#_}#w(){return this.#x().preparedArgs}#T(e,t){let n=this.#l?.controls,r;return Object.freeze({mode:e,kind:`model`,model:this.#i,operation:String(this.#o.originalOperation),get input(){return r??=snapshotQueryInput(t),r},...n===void 0?{}:{controls:n}})}#E(){return this.#x().cacheResultCodec()}#D(){return this.#s.executeDefault(()=>{let e=this.#t.extensionChain?.observe;return e===void 0||e.length===0?this.#O(this.#A()):O(e,String(this.#o.originalOperation),this.#i,()=>this.#O(this.#A()),()=>this.#m===void 0?void 0:{commitCertainty:this.#m},this.#k())})}#O(e){let t=this.#o.finishResult;return t?e.then(e=>t(e)):e}#k(){return createPendingOperationInstrumentationFacts(this.#t.driver,this.#e.attribution,this.#i,String(this.#o.originalOperation),String(this.#a),this.#n[`~`].names.sql??this.#i,s(this.#o))}#A(e,t,n){return withOperationErrorContext(this.#e.attribution,()=>this.#j(e,t,n))}#j(e,t,n){let r=this.#N(`committed`),i=this.#N(`may-have-committed`),a=String(this.#o.originalOperation),o=d(this.#t.extensionChain,`query`,this.#i,a);return(o===void 0||o.length===0)&&this.#u===void 0?this.#P(e,combineWriteNotifications(t,r),combineWriteNotifications(n,i)):this.#M(o,a,r,i,e,t,n)}#M(e,t,n,i,a,o,s){let c;try{c=this.#w()}catch(e){return Promise.reject(e)}let l=this.#b();return(e===void 0||e.length===0)&&l===void 0?this.#P(a,combineWriteNotifications(o,n),combineWriteNotifications(s,i)):executePreparedQuery(e===void 0||e.length===0?void 0:this.#T(this.#t.transactionWriteOutcomes?`transaction`:`direct`,c),e,e=>this.#P(a,combineWriteNotifications(o,combineWriteNotifications(e?.committed,n)),combineWriteNotifications(s,combineWriteNotifications(e?.mayHaveCommitted,i))),!r(t),this.#t.transactionWriteOutcomes,void 0,l)}#N(e){if(!(this.#t.transactionWriteOutcomes!==void 0||(this.#t.extensionChain?.observe.length??0)===0))return async()=>{(e===`committed`||this.#m===void 0)&&(this.#m=e)}}#P(e,t,n){return this.#c?this.#c(e,t,n):this.#F(e,t,n)}#F(e,t,n){let i;try{i=this.#x()}catch(e){return Promise.reject(e)}let run=()=>i.execute({committedWriteSegment:t,context:this.#e.attribution,driverOverride:e,engineDriver:this.#t.driver,isWrite:!r(String(this.#o.originalOperation)),writeMayBeVisible:n});if(this.#a===`findUnique`&&e===void 0){let e=batchFindUnique({engine:this.#t,model:this.#n,requested:String(this.#o.originalOperation),args:this.#y(),controls:this.#l?.controls,rows:()=>this.#S(),routed:i,context:this.#e.attribution,run});if(e!==void 0)return e}return run()}getArgs(){return this.#r}cacheKeyArgs(){let e=this.#I();if(!e)throw new y(`Operation '${this.#a}' on model '${this.#i}' exposes no validated payload to key a cache entry on.`);return e}#I(){if(r(this.#a))return this.#x().preparedArgs}buildStatement(){return this.#x().buildStatement()}#L(e){let t=this.#p??={routed:this.#g},deferredExecution=(t,n,r)=>e((e,i,a)=>this.#P(e??t,combineWriteNotifications(i,n),combineWriteNotifications(a,r)),t);return new PendingOperation(q,this.#t,this.#n,this.#a,this.#r,this.#o,this.#e,deferredExecution,this.#l,t,this.#u)}then(e,t){return this.#D().then(e,t)}catch(e){return this.#D().catch(e)}finally(e){return this.#D().finally(e)}};function createPendingOperation(e,t,n,r,i,a,o){return createPendingOperationFriend(e,t,n,r,i,a,o)}function attachPendingCacheExecution(e,t){return attachPendingCacheExecutionFriend(e,t)}function readPendingCacheResult(e){return readPendingCacheResultFriend(e)}function isPendingOperation(e){return typeof e==`object`&&!!e&&K in e&&e[K]===!0}const X=`0viborm_distance`,Z=`0viborm_relation_counts`,Q=`0viborm_empty_row`,gateResultKey=e=>`0viborm_gate:${e}`,ee=`0viborm_cursor_`,te=`0viborm_orphans`;function getAggregateResultKey(e){return`0viborm_aggregate:${e.slice(1)}`}function getAggregateResultName(e){switch(e){case`0viborm_aggregate:count`:return`_count`;case`0viborm_aggregate:avg`:return`_avg`;case`0viborm_aggregate:sum`:return`_sum`;case`0viborm_aggregate:min`:return`_min`;case`0viborm_aggregate:max`:return`_max`;default:return}}function getGroupByFields(e){let t=Array.isArray(e)?e.filter(e=>typeof e==`string`):typeof e==`string`?[e]:[];if(new Set(t).size!==t.length)throw new y(`GroupBy operation does not allow duplicate fields in 'by'`);return t}const ne=new Set([`findFirst`,`findMany`,`findUnique`,`create`,`createManyAndReturn`,`update`,`updateManyAndReturn`,`delete`,`deleteManyAndReturn`,`upsert`]),$=`Distance select supports only one _distance field per select.`;function selectedArm(e,t,r){let i=n(e)?e:void 0;if(!t)return getOwnValue(i,r)??!0;let a=getOwnValue(i,`only`);if(Array.isArray(a)&&!a.includes(r))return;let o=getOwnValue(i,`variants`);return(n(o)?getOwnValue(o,r):void 0)??!0}const re=[`_count`,`_avg`,`_sum`,`_min`,`_max`];function getOwnValue(e,t){return e&&Object.hasOwn(e,t)?e[t]:void 0}function createShape(e,t=new Map,n=new Map,r=new Set,i=new Map,a){if(new Set(e).size!==e.length)throw new y(`The requested result shape contains colliding output columns.`);return{carrier:`rows`,rawKeys:e,...a?{distanceScalar:a}:{},relations:t,polymorphic:i,aggregates:n,relationCounts:r}}function selectedEntries(e){return n(e)?Object.entries(e).filter(([,e])=>e!==!1&&e!==void 0):[]}function getNestedSelection(e){if(!n(e))return{};let t={},r=getOwnValue(e,`select`),i=getOwnValue(e,`include`);return n(r)&&(t.select=r),n(i)&&(t.include=i),t}function buildModelShape(e,t,r){let i=[],a=new Map,o=new Map,s=e[`~`].state.scalars,c=e[`~`].state.relations,l=getOwnValue(t,`select`),u=getOwnValue(t,`include`),d=n(l)?l:void 0,f=n(u)?u:void 0,p=!1,m;if(d)for(let[e,t]of Object.entries(d)){let r=getOwnValue(s,e);if(r){if(t===!0){i.push(e);continue}if(n(t)&&Object.hasOwn(t,`_distance`)){if(p)throw new y($);p=!0,m=r,i.push(X)}}}else for(let t of E(e))i.push(t);addSelectedRelations(e,c,d,i,a,r),addSelectedPolymorphicRelations(e,d,i,o,r),addSelectedRelations(e,c,f,i,a,r),addSelectedPolymorphicRelations(e,f,i,o,r);let h=[getOwnValue(d,`_count`),getOwnValue(f,`_count`)],g=new Set;for(let e of h){if(!n(e))continue;let t=getOwnValue(e,`select`);if(n(t))for(let[e]of selectedEntries(t)){let t=getOwnValue(c,e);if(!t)continue;let n=t[`~`].state;D(n)&&n.cardinality!==`many`||g.add(e)}}return g.size>0&&i.push(Z),i.length===0&&i.push(Q),createShape(i,a,new Map,g,o,m)}function admittedRecurrence(e){if(n(e))return getOwnValue(e,`recurse`)}function addSelectedRelations(e,t,n,r,i,a){for(let[o,s]of selectedEntries(n)){let n=getOwnValue(t,o);if(!n||D(n[`~`].state))continue;let c=n[`~`].settleTarget();r.push(o);let l=buildModelShape(c,getNestedSelection(s),a),u=a.get(e)?.get(o),d=admittedRecurrence(s);i.set(o,{model:c,shape:l,cardinality:n[`~`].state.cardinality,optional:u!==void 0&&T(u),...d?{recurrence:d}:{}})}}function addSelectedPolymorphicRelations(e,t,n,r,i){let a=e[`~`].state.relations;for(let[o,s]of selectedEntries(t)){let t=getOwnValue(a,o);if(!t)continue;let c=t[`~`].state;if(!D(c))continue;let l=c.cardinality===`many`,u=new Map;for(let e of Object.keys(c.target.entries)){let n=selectedArm(s,l,e);if(n===void 0)continue;let r=t[`~`].settleTarget(e);u.set(e,{model:r,shape:buildModelShape(r,getNestedSelection(n),i)})}n.push(o);let d=i.get(e)?.get(o);r.set(o,{cardinality:c.cardinality,optional:d!==void 0&&T(d),variants:u})}}function buildAggregateShape(e,t=[]){let n=[...t],r=new Set(t),i=new Map;for(let t of re){let a=getOwnValue(e,t);if(a===void 0||a===!1)continue;let o;if(!(t===`_count`&&a===!0)){let e=selectedEntries(a);if(e.length===0)continue;o=new Set(e.map(([e])=>e))}if(r.has(t))throw new y(`GroupBy cannot return both grouped scalar '${t}' and aggregate '${t}' in one result.`);let s=getAggregateResultKey(t);n.push(s),r.add(t),i.set(s,{...o?{fields:o}:{}})}return createShape(n,new Map,i)}function buildCountShape(e){let t=selectedEntries(getOwnValue(e,`select`)).map(([e])=>e);return{...createShape(t.length===0?[I]:t),carrier:`count`}}function buildExpectedResultShape(e,t,n,r){if(t===`count`)return buildCountShape(n);if(t===`exist`)return{...createShape([I]),carrier:`existence`};if(t===`aggregate`)return buildAggregateShape(n);if(t===`groupBy`)return buildAggregateShape(n,getGroupByFields(getOwnValue(n,`by`)));if(ne.has(t))return buildModelShape(e,n,r)}export{TransactionWriteOutcomes as C,executePreparedQuery as E,withOperationErrorContext as S,decomposeWriteOutcomePublicationFailure as T,snapshotQueryInput as _,X as a,createRawOperationInstrumentationFacts as b,Z as c,Y as d,attachPendingCacheExecution as f,compileBindBudgetChunks as g,readPendingCacheResult as h,ee as i,gateResultKey as l,isPendingOperation as m,buildExpectedResultShape as n,Q as o,createPendingOperation as p,selectedArm as r,te as s,$ as t,getAggregateResultName as u,PendingExecution as v,decomposeQueryCoordinationFailure as w,observeTransactionBatchPhase as x,createOperationExecutionContext as y};
2
- //# sourceMappingURL=result-shape-Fi1-Fvri.mjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"result-shape-Fi1-Fvri.mjs","names":["extensionFailures","#staged","#setState","#model","#operation","#executedWith","#promise","#reservedForBatch","copy","#context","#engine","#model","#args","#modelName","#operation","#options","#execution","#deferredExecution","#inputPreparation","#prepareWriteOutcomeRegistration","#route","#wrapExecution","#resolveArgs","#cacheResultCodec","#preparedInput","#resolveSinglePackage","#resolveWriteOutcomeRegistration","#queryContext","#runCoreExecution","#readInstrumentationFacts","#observationCommitCertainty","#resolveRouted","#operationResolution","#writeOutcomeRegistrationResolved","#writeOutcomeRegistration","#routedInstance","#callRows","#singlePackageResolved","#singlePackage","#finished","#runExecution","#runAttributedExecution","#observationNotification","#runExtendedExecution","#run","#cacheKeyPayload","#getPromise"],"sources":["../src/extensions/query.ts","../src/query-engine/execution-context.ts","../src/query-engine/pending-execution.ts","../src/query-engine/query-inspection.ts","../src/query-engine/bind-budget.ts","../src/query-engine/find-unique-batch.ts","../src/query-engine/pending-operation.ts","../src/query-engine/result-aliases.ts","../src/query-engine/result/groupby-fields.ts","../src/query-engine/result/result-shape.ts"],"sourcesContent":["import type { ClientSchema } from \"@client/schema-links\";\nimport { QueryError } from \"@errors\";\nimport { isReadOperation } from \"@query-engine/routed-operations\";\nimport { isFunction } from \"@validation/value-guards\";\nimport { isError } from \"../errors/diagnostic-safety\";\nimport type { ResolvedOperationHandler } from \"./chain\";\nimport { type AdmittedControls, controlsOwnedBy } from \"./controls\";\n\n/** Frozen runtime contribution after hostile definition normalization. */\ntype RuntimeQueryFunction = (...args: never[]) => unknown;\nexport type RuntimeQueryContribution =\n | RuntimeQueryFunction\n | Readonly<Record<string, Readonly<Record<string, RuntimeQueryFunction>>>>;\n\nexport type QueryInterceptionMode = \"direct\" | \"transaction\" | \"array\";\n\nexport type RawQueryKind =\n | \"queryRaw\"\n | \"executeRaw\"\n | \"queryRawUnsafe\"\n | \"executeRawUnsafe\";\n\nexport type RawQueryOperation = `$${RawQueryKind}`;\n\ninterface PreparedQueryContextBase<Input extends object> {\n readonly mode: QueryInterceptionMode;\n readonly input: Readonly<Input>;\n}\n\nexport interface PreparedModelQueryContext<Input extends object>\n extends PreparedQueryContextBase<Input> {\n readonly kind: \"model\";\n readonly model: string;\n readonly operation: string;\n /**\n * The call's admitted controls. A handler sees only its own extension's,\n * and only when that extension declares any.\n */\n readonly controls?: AdmittedControls;\n}\n\nexport interface PreparedRawQueryContext<Input extends object>\n extends PreparedQueryContextBase<Input> {\n readonly kind: RawQueryKind;\n readonly model: undefined;\n readonly operation: RawQueryOperation;\n}\n\n/** The prepared logical-operation facts safe for query interceptors to inspect. */\nexport type PreparedQueryContext<\n Input extends object = Record<string, unknown>,\n> = PreparedModelQueryContext<Input> | PreparedRawQueryContext<Input>;\n\nexport type WriteOutcome = Readonly<{\n certainty: \"committed\" | \"may-have-committed\";\n}>;\n\nexport type WriteOutcomeListener = (\n outcome: WriteOutcome\n) => unknown | Promise<unknown>;\n\nexport type GenericQueryKind = \"model\" | RawQueryKind;\n\ntype GenericQueryContextBase<Result> = {\n readonly mode: QueryInterceptionMode;\n readonly input: Readonly<Record<string, unknown>>;\n readonly proceed: () => Promise<Result>;\n readonly onWriteOutcome: (listener: WriteOutcomeListener) => void;\n};\n\ntype GenericModelQueryContext<Result> = GenericQueryContextBase<Result> & {\n readonly kind: \"model\";\n readonly model: string;\n readonly operation: Operations;\n /** The call's controls this handler's extension declares, and only those. */\n readonly controls?: AdmittedControls;\n};\n\ntype GenericRawQueryContext<Result> = GenericQueryContextBase<Result> &\n {\n [Kind in RawQueryKind]: {\n readonly kind: Kind;\n readonly model: undefined;\n readonly operation: `$${Kind}`;\n };\n }[RawQueryKind];\n\nexport type GenericQueryContext<Result> =\n | GenericModelQueryContext<Result>\n | GenericRawQueryContext<Result>;\n\ntype GenericQueryHandlerCall = <Result>(\n context: GenericQueryContext<Result>\n) => Promise<Result>;\n\ndeclare const officialQueryHandlerIdentity: unique symbol;\n\n/** Public ordinary query handler; official identities cannot be erased into it. */\nexport type GenericQueryHandler = GenericQueryHandlerCall & {\n readonly [officialQueryHandlerIdentity]?: never;\n};\n\n/** Internal nominal call shape used by official query-based capabilities. */\nexport type OfficialGenericQueryHandler = GenericQueryHandlerCall & {\n readonly [officialQueryHandlerIdentity]: true;\n};\n\n/**\n * Per-model query handlers. Their results read the result context of the\n * chain they are applied to: `Hidden` names the models its `rows` can hide\n * (`rows` cannot follow a model-mapped handler, so a later extension adds\n * none). A `rows` entry in the handler's OWN definition is not seen, as no\n * definition types against its own contributions: declare it one step\n * earlier.\n */\nexport type QueryHandlerMap<\n C extends VibORMConfig,\n Hidden extends string = never,\n> = {\n readonly [ModelName in keyof ClientSchema<C>]?: {\n readonly [OperationName in Operations]?: <\n Arg extends Exclude<\n OperationPayload<OperationName, ClientSchema<C>[ModelName]>,\n undefined\n >,\n >(context: {\n readonly mode: QueryInterceptionMode;\n readonly kind: \"model\";\n readonly model: ModelName;\n readonly operation: OperationName;\n readonly input: Readonly<Arg>;\n /** The call's controls this handler's extension declares, and only those. */\n readonly controls?: AdmittedControls;\n readonly proceed: () => Promise<\n ContextualOperationResult<\n C,\n ModelName,\n OperationName,\n Arg,\n ClientRowsContext<C, Hidden>\n >\n >;\n readonly onWriteOutcome: (listener: WriteOutcomeListener) => void;\n }) => Promise<\n ContextualOperationResult<\n C,\n ModelName,\n OperationName,\n Arg,\n ClientRowsContext<C, Hidden>\n >\n >;\n };\n};\n\nexport interface WriteOutcomeRegistration {\n readonly extension: string;\n readonly listener: WriteOutcomeListener;\n /** Package-owned listeners may already translate failures at their boundary. */\n readonly failurePolicy?: \"boundary-owned\";\n}\n\nexport type WriteOutcomeRegistrationCapture = (\n registration: WriteOutcomeRegistration\n) => void;\n\nexport interface WriteOutcomeNotifications {\n readonly committed: () => Promise<void>;\n readonly mayHaveCommitted: () => Promise<void>;\n}\n\ninterface QueryInterceptorCapabilities<Result> {\n readonly proceed: () => Promise<Result>;\n readonly onWriteOutcome: (listener: WriteOutcomeListener) => void;\n}\n\nexport type QueryInterceptorContext<\n Result,\n Input extends object = Record<string, unknown>,\n> = Readonly<\n PreparedQueryContext<Input> & QueryInterceptorCapabilities<Result>\n>;\n\nconst queryCoordinationFailures = new WeakMap<AggregateError, unknown>();\nconst publicationFailures = new WeakMap<AggregateError, readonly Error[]>();\n\ntype ReadCommitCertainty = () => WriteOutcome[\"certainty\"] | undefined;\n\n/** Private coordination hooks used only while array members await admission. */\nexport interface QueryInterceptorExecutionControl {\n readonly reportAdmissionFailure?: (failure: unknown) => void;\n readonly readCommitCertainty?: ReadCommitCertainty;\n}\n\n/**\n * Execute one prepared operation through its exact precompiled query chain.\n *\n * The absent-chain arm calls the child directly and allocates no context,\n * registration list, notification callback, or runner promise.\n */\nexport function executePreparedQuery<Result, Input extends object>(\n context: PreparedQueryContext<Input> | undefined,\n interceptors: readonly ResolvedOperationHandler[] | undefined,\n child: (notifications?: WriteOutcomeNotifications) => Promise<Result>,\n isWrite: boolean,\n transactionWriteOutcomes?: TransactionWriteOutcomes,\n control?: QueryInterceptorExecutionControl,\n preRegisteredWriteOutcome?: WriteOutcomeRegistration\n): Promise<Result> {\n if (\n (context === undefined ||\n interceptors === undefined ||\n interceptors.length === 0) &&\n preRegisteredWriteOutcome === undefined\n ) {\n return child();\n }\n if (\n !isWrite &&\n preRegisteredWriteOutcome === undefined &&\n context !== undefined &&\n interceptors !== undefined &&\n interceptors.length > 0\n ) {\n return runCompiledQueryInterceptors(\n context,\n interceptors,\n child,\n discardReadWriteOutcomeRegistration,\n control?.readCommitCertainty,\n control?.reportAdmissionFailure\n );\n }\n return executeInterceptedQuery(\n context,\n interceptors,\n child,\n isWrite,\n transactionWriteOutcomes,\n control,\n preRegisteredWriteOutcome\n );\n}\n\nfunction discardReadWriteOutcomeRegistration(): void {\n return;\n}\n\nasync function executeInterceptedQuery<Result, Input extends object>(\n context: PreparedQueryContext<Input> | undefined,\n interceptors: readonly ResolvedOperationHandler[] | undefined,\n child: (notifications?: WriteOutcomeNotifications) => Promise<Result>,\n isWrite: boolean,\n transactionWriteOutcomes: TransactionWriteOutcomes | undefined,\n control: QueryInterceptorExecutionControl | undefined,\n preRegisteredWriteOutcome: WriteOutcomeRegistration | undefined\n): Promise<Result> {\n const registrations: WriteOutcomeRegistration[] =\n preRegisteredWriteOutcome === undefined ? [] : [preRegisteredWriteOutcome];\n if (preRegisteredWriteOutcome !== undefined) {\n transactionWriteOutcomes?.stage(preRegisteredWriteOutcome);\n }\n const captureWriteOutcome = (\n registration: WriteOutcomeRegistration\n ): void => {\n registrations.push(registration);\n transactionWriteOutcomes?.stage(registration);\n };\n let publishedDirectUnits = 0;\n let directCommitCertainty: WriteOutcome[\"certainty\"] | undefined;\n let transactionConfirmed = false;\n const publish = async (\n certainty: WriteOutcome[\"certainty\"]\n ): Promise<void> => {\n if (transactionWriteOutcomes) {\n if (registrations.length === 0) return;\n if (transactionConfirmed) return;\n transactionConfirmed = true;\n transactionWriteOutcomes.confirm(registrations);\n return;\n }\n publishedDirectUnits += 1;\n directCommitCertainty = certainty;\n if (registrations.length === 0) return;\n await publishWriteOutcomes(registrations, { certainty });\n };\n const notifications: WriteOutcomeNotifications = Object.freeze({\n committed: () => publish(\"committed\"),\n mayHaveCommitted: () => publish(\"may-have-committed\"),\n });\n const executeChild = async (): Promise<Result> => {\n try {\n const value = await child(notifications);\n if (\n isWrite &&\n (transactionWriteOutcomes !== undefined || publishedDirectUnits === 0)\n ) {\n await publish(\"committed\");\n }\n return value;\n } catch (error) {\n if (transactionWriteOutcomes && !transactionConfirmed) {\n transactionWriteOutcomes.discard(registrations);\n }\n throw error;\n }\n };\n\n try {\n const value =\n context === undefined ||\n interceptors === undefined ||\n interceptors.length === 0\n ? await executeChild()\n : await runCompiledQueryInterceptors(\n context,\n interceptors,\n executeChild,\n captureWriteOutcome,\n () => directCommitCertainty ?? control?.readCommitCertainty?.(),\n control?.reportAdmissionFailure\n );\n return value;\n } catch (error) {\n if (transactionWriteOutcomes && !transactionConfirmed) {\n transactionWriteOutcomes.discard(registrations);\n }\n throw error;\n }\n}\n\ntype Settled<Value> =\n | { readonly status: \"fulfilled\"; readonly value: Value }\n | { readonly status: \"rejected\"; readonly reason: unknown };\n\ntype HandlerOutcome<Value> =\n | { readonly status: \"fulfilled\"; readonly value: Value }\n | {\n readonly status: \"rejected\";\n readonly reason: unknown;\n readonly failure: Error;\n };\n\ntype ExtensionFailures = readonly [Error] | readonly [Error, Error] | undefined;\n\n/**\n * Run one already-compiled interceptor chain around one prepared child.\n *\n * The undefined/empty branch deliberately returns the child's promise directly:\n * unextended operations allocate no runner promise, context, closure, or list.\n */\nexport function runCompiledQueryInterceptors<Result, Input extends object>(\n context: PreparedQueryContext<Input>,\n interceptors: readonly ResolvedOperationHandler[] | undefined,\n child: () => Promise<Result>,\n captureWriteOutcome: WriteOutcomeRegistrationCapture,\n readCommitCertainty?: ReadCommitCertainty,\n reportAdmissionFailure?: (failure: unknown) => void\n): Promise<Result> {\n if (interceptors === undefined || interceptors.length === 0) return child();\n return runInterceptorAt(\n context,\n interceptors,\n 0,\n child,\n captureWriteOutcome,\n readCommitCertainty,\n reportAdmissionFailure\n );\n}\n\nfunction runInterceptorAt<Result, Input extends object>(\n context: PreparedQueryContext<Input>,\n interceptors: readonly ResolvedOperationHandler[],\n index: number,\n child: () => Promise<Result>,\n captureWriteOutcome: WriteOutcomeRegistrationCapture,\n readCommitCertainty: ReadCommitCertainty | undefined,\n reportAdmissionFailure: ((failure: unknown) => void) | undefined\n): Promise<Result> {\n const interceptor = interceptors[index];\n if (interceptor === undefined) return child();\n\n return runOneInterceptor(\n context,\n interceptor,\n () =>\n runInterceptorAt(\n context,\n interceptors,\n index + 1,\n child,\n captureWriteOutcome,\n readCommitCertainty,\n reportAdmissionFailure\n ),\n captureWriteOutcome,\n readCommitCertainty,\n reportAdmissionFailure\n );\n}\n\nasync function runOneInterceptor<Result, Input extends object>(\n prepared: PreparedQueryContext<Input>,\n interceptor: ResolvedOperationHandler,\n child: () => Promise<Result>,\n captureWriteOutcome: WriteOutcomeRegistrationCapture,\n readCommitCertainty: ReadCommitCertainty | undefined,\n reportAdmissionFailure: ((failure: unknown) => void) | undefined\n): Promise<Result> {\n let continuationOpen = true;\n let childOutcomePromise: Promise<Settled<Result>> | undefined;\n let handlerSettled = false;\n let registrationOpen = true;\n let protocolFailure: QueryError | undefined;\n\n const recordProtocolFailure = (failure: string): QueryError => {\n if (protocolFailure) return protocolFailure;\n const error = interceptorError(interceptor.extension, prepared, failure);\n protocolFailure = error;\n reportAdmissionFailure?.(error);\n return error;\n };\n\n const proceed = (): Promise<Result> => {\n if (!continuationOpen) {\n throw recordProtocolFailure(\"called proceed more than once\");\n }\n if (handlerSettled) {\n throw recordProtocolFailure(\"called proceed after its handler settled\");\n }\n\n registrationOpen = false;\n continuationOpen = false;\n const promise = startChild(child);\n childOutcomePromise = settle(promise);\n return promise;\n };\n\n const onWriteOutcome = (listener: WriteOutcomeListener): void => {\n if (!isFunction(listener)) {\n throw recordProtocolFailure(\n \"registered a non-function write-outcome listener\"\n );\n }\n if (!registrationOpen || handlerSettled) {\n throw recordProtocolFailure(\n \"registered a write-outcome listener after proceed\"\n );\n }\n captureWriteOutcome(\n Object.freeze({ extension: interceptor.extension, listener })\n );\n };\n\n const handlerContext = exposeHandlerContext(\n prepared,\n proceed,\n onWriteOutcome,\n interceptor.controls\n );\n let handlerValue: Promise<Result>;\n try {\n handlerValue = Promise.resolve<Result>(\n Reflect.apply(interceptor.handler, undefined, [handlerContext])\n );\n } catch (reason) {\n handlerValue = Promise.reject(reason);\n }\n\n const settledHandler = await settle(handlerValue);\n handlerSettled = true;\n registrationOpen = false;\n const handlerOutcome: HandlerOutcome<Result> =\n settledHandler.status === \"fulfilled\"\n ? settledHandler\n : {\n ...settledHandler,\n failure:\n protocolFailure !== undefined &&\n settledHandler.reason === protocolFailure\n ? protocolFailure\n : interceptorFailure(\n interceptor.extension,\n prepared,\n settledHandler.reason,\n readCommitCertainty?.()\n ),\n };\n\n if (\n childOutcomePromise !== undefined &&\n handlerOutcome.status === \"rejected\" &&\n handlerOutcome.reason !== protocolFailure\n ) {\n reportAdmissionFailure?.(handlerOutcome.failure);\n }\n\n if (childOutcomePromise === undefined) {\n if (protocolFailure) throw protocolFailure;\n if (handlerOutcome.status === \"rejected\") {\n throw handlerOutcome.failure;\n }\n if (requiresProceed(prepared)) {\n throw interceptorError(\n interceptor.extension,\n prepared,\n \"completed without proceed\"\n );\n }\n return handlerOutcome.value;\n }\n\n const childOutcome = await childOutcomePromise;\n if (childOutcome.status === \"rejected\") {\n const extensionFailures = selectExtensionFailures(\n protocolFailure,\n handlerOutcome,\n childOutcome\n );\n if (extensionFailures) {\n throw retainSuppressedFailures(childOutcome.reason, extensionFailures);\n }\n throw childOutcome.reason;\n }\n const extensionFailures = selectExtensionFailures(\n protocolFailure,\n handlerOutcome,\n childOutcome\n );\n if (extensionFailures) throwExtensionFailures(extensionFailures);\n // With the child fulfilled, a rejected handler always selects a failure.\n return (handlerOutcome as Extract<HandlerOutcome<Result>, { value: Result }>)\n .value;\n}\n\nfunction selectExtensionFailures(\n protocolFailure: QueryError | undefined,\n handlerOutcome: HandlerOutcome<unknown>,\n childOutcome: Settled<unknown>\n): ExtensionFailures {\n if (\n protocolFailure &&\n childOutcome.status === \"rejected\" &&\n childOutcome.reason === protocolFailure\n ) {\n return undefined;\n }\n if (handlerOutcome.status !== \"rejected\") {\n return protocolFailure ? [protocolFailure] : undefined;\n }\n if (\n (protocolFailure !== undefined &&\n handlerOutcome.reason === protocolFailure) ||\n (childOutcome.status === \"rejected\" &&\n handlerOutcome.reason === childOutcome.reason)\n ) {\n return protocolFailure ? [protocolFailure] : undefined;\n }\n const handlerFailure = handlerOutcome.failure;\n return protocolFailure ? [protocolFailure, handlerFailure] : [handlerFailure];\n}\n\nfunction exposeHandlerContext<Result, Input extends object>(\n context: PreparedQueryContext<Input>,\n proceed: () => Promise<Result>,\n onWriteOutcome: (listener: WriteOutcomeListener) => void,\n ownControls: readonly string[] | undefined\n): QueryInterceptorContext<Result, Input> {\n // `kind`, `model` and `operation` are copied from one prepared context, so\n // they stay one of its arms; TypeScript cannot correlate the copies.\n // `input` is read through: the prepared context snapshots it at the first\n // read, which a handler that never inspects it does not pay for.\n return Object.freeze({\n mode: context.mode,\n kind: context.kind,\n model: context.model,\n operation: context.operation,\n get input() {\n return context.input;\n },\n ...(context.kind === \"model\" && ownControls !== undefined\n ? { controls: controlsOwnedBy(context.controls, ownControls) }\n : {}),\n proceed,\n onWriteOutcome,\n }) as QueryInterceptorContext<Result, Input>;\n}\n\nfunction startChild<Result>(child: () => Promise<Result>): Promise<Result> {\n try {\n return Promise.resolve(child());\n } catch (reason) {\n return Promise.reject(reason);\n }\n}\n\nasync function settle<Value>(promise: Promise<Value>): Promise<Settled<Value>> {\n try {\n return { status: \"fulfilled\", value: await promise };\n } catch (reason) {\n return { status: \"rejected\", reason };\n }\n}\n\nfunction requiresProceed(context: PreparedQueryContext<object>): boolean {\n return (\n context.mode === \"array\" ||\n context.kind !== \"model\" ||\n !isReadOperation(context.operation)\n );\n}\n\nfunction interceptorFailure<Input extends object>(\n extension: string,\n context: PreparedQueryContext<Input>,\n reason: unknown,\n commitCertainty?: WriteOutcome[\"certainty\"]\n): Error {\n if (isError(reason)) return reason;\n return interceptorError(\n extension,\n context,\n \"failed\",\n new Error(\"Query interceptor rejected with a non-Error value\"),\n commitCertainty\n );\n}\n\nfunction interceptorError<Input extends object>(\n extension: string,\n context: PreparedQueryContext<Input>,\n failure: string,\n cause?: Error,\n commitCertainty?: WriteOutcome[\"certainty\"]\n): QueryError {\n const message = `Extension \"${extension}\" query handler for ${describeOperation(context)} ${failure}.`;\n const meta = {\n method: \"query\",\n model: context.model,\n operation: String(context.operation),\n ...(commitCertainty === undefined ? {} : { commitCertainty }),\n };\n return cause\n ? new QueryError(message, { cause, meta })\n : new QueryError(message, { meta });\n}\n\nfunction describeOperation(context: PreparedQueryContext<object>): string {\n return context.kind === \"model\"\n ? `${context.model}.${context.operation}`\n : context.operation;\n}\n\nfunction throwExtensionFailures(\n failures: NonNullable<ExtensionFailures>\n): never {\n const primary = failures[0];\n if (failures.length === 1) throw primary;\n throw new AggregateError(\n failures,\n \"Query interceptor protocol and handler both failed.\",\n { cause: primary }\n );\n}\n\nfunction retainSuppressedFailures(\n childFailure: unknown,\n extensionFailures: NonNullable<ExtensionFailures>\n): AggregateError {\n const failure = new AggregateError(\n [childFailure, ...extensionFailures],\n \"Query execution and extension post-work both failed.\",\n { cause: childFailure }\n );\n queryCoordinationFailures.set(failure, childFailure);\n return failure;\n}\n\n/** Decompose only this runner's own child-plus-post-work coordination error. */\nexport function decomposeQueryCoordinationFailure(failure: unknown):\n | Readonly<{\n child: unknown;\n postWork: readonly unknown[];\n }>\n | undefined {\n if (!(failure instanceof AggregateError)) return undefined;\n if (!queryCoordinationFailures.has(failure)) return undefined;\n const child = queryCoordinationFailures.get(failure);\n if (failure.cause !== child || failure.errors[0] !== child) {\n return undefined;\n }\n return Object.freeze({\n child,\n postWork: Object.freeze(failure.errors.slice(1)),\n });\n}\n\ntype StagedWriteOutcome = {\n readonly registration: WriteOutcomeRegistration;\n state: \"pending\" | \"confirmed\" | \"discarded\";\n};\n\n/** Transaction-local staging for extension write-outcome registrations. */\nexport class TransactionWriteOutcomes {\n readonly #staged: StagedWriteOutcome[] = [];\n\n stage(registration: WriteOutcomeRegistration): void {\n for (const staged of this.#staged) {\n if (staged.registration === registration) return;\n }\n this.#staged.push({ registration, state: \"pending\" });\n }\n\n confirm(registrations: readonly WriteOutcomeRegistration[]): void {\n this.#setState(registrations, \"confirmed\");\n }\n\n discard(registrations: readonly WriteOutcomeRegistration[]): void {\n this.#setState(registrations, \"discarded\");\n }\n\n discardAll(): void {\n for (const staged of this.#staged) staged.state = \"discarded\";\n }\n\n promoteTo(parent: TransactionWriteOutcomes): void {\n for (const staged of this.#staged) {\n if (staged.state === \"confirmed\") {\n parent.#staged.push({ ...staged });\n }\n staged.state = \"discarded\";\n }\n }\n\n publishCommitted(): Promise<void> {\n return this.publish(\"committed\");\n }\n\n async publish(certainty: WriteOutcome[\"certainty\"]): Promise<void> {\n const registrations: WriteOutcomeRegistration[] = [];\n for (const staged of this.#staged) {\n if (staged.state === \"confirmed\") {\n registrations.push(staged.registration);\n }\n staged.state = \"discarded\";\n }\n await publishWriteOutcomes(registrations, { certainty });\n }\n\n #setState(\n registrations: readonly WriteOutcomeRegistration[],\n state: \"confirmed\" | \"discarded\"\n ): void {\n for (const staged of this.#staged) {\n if (\n staged.state === \"pending\" &&\n registrations.includes(staged.registration)\n ) {\n staged.state = state;\n }\n }\n }\n}\n\n/** Deliver every registered listener in registration order. */\nexport async function publishWriteOutcomes(\n registrations: readonly WriteOutcomeRegistration[],\n outcome: WriteOutcome\n): Promise<void> {\n let failures: Error[] | undefined;\n for (const registration of registrations) {\n try {\n await registration.listener(outcome);\n } catch (reason) {\n const cause = isError(reason) ? reason : undefined;\n const failure =\n registration.failurePolicy === \"boundary-owned\" && cause !== undefined\n ? cause\n : new QueryError(\n `Extension \"${registration.extension}\" write-outcome listener failed after ${outcome.certainty}.`,\n {\n cause:\n cause ??\n new Error(\n \"Write-outcome listener rejected with a non-Error value\"\n ),\n meta: {\n method: \"onWriteOutcome\",\n commitCertainty: outcome.certainty,\n },\n }\n );\n (failures ??= []).push(failure);\n }\n }\n if (failures === undefined) return;\n const [primary] = failures;\n if (failures.length === 1) throw primary;\n const aggregate = new AggregateError(\n failures,\n \"Multiple extension write-outcome listeners failed.\",\n { cause: primary }\n );\n publicationFailures.set(aggregate, failures);\n throw aggregate;\n}\n\n/** Decompose only the aggregate created by this publication owner. */\nexport function decomposeWriteOutcomePublicationFailure(\n failure: unknown\n): readonly unknown[] {\n if (!(failure instanceof AggregateError)) return [failure];\n return publicationFailures.get(failure) ?? [failure];\n}\n\nimport type { VibORMConfig } from \"@client/client\";\nimport type {\n ClientRowsContext,\n ContextualOperationResult,\n OperationPayload,\n Operations,\n} from \"@client/types\";\n","import { officialCacheRuntime } from \"@cache/capability\";\nimport { attachExecutionContext } from \"@drivers/driver-error-context\";\nimport { readDriverIdentity } from \"@drivers/driver-identity\";\nimport { normalizeDriverError } from \"@drivers/error-mapping\";\nimport {\n createExecutionContext,\n getExecutionCallsite,\n getExecutionExtensionChain,\n} from \"@drivers/execution-context\";\nimport type { AnyDriver, QueryExecutionContext } from \"@drivers/exports\";\nimport { VibORMError } from \"@errors\";\nimport type { ResolvedExtensionChain } from \"@extensions/chain\";\nimport { getOfficialInstrumentationChainCapability } from \"@extensions/observation\";\nimport type { OfficialLifecycleFactsReader } from \"@extensions/official-facts\";\nimport { isErrorLogged } from \"../errors/logged-errors\";\nimport type { Operation } from \"./types\";\n\n/** Immutable ownership and attribution captured when an operation is created. */\nexport interface OperationExecutionContext {\n readonly clientId: symbol;\n readonly scopeId: symbol;\n readonly attribution: QueryExecutionContext;\n}\n\nexport function createOperationExecutionContext(\n model: string,\n operation: Operation | string,\n extensionChain?: ResolvedExtensionChain\n): QueryExecutionContext {\n const disclosure =\n getOfficialInstrumentationChainCapability(extensionChain)?.diagnostics;\n // Capture before asynchronous request/plan/provider work, and allocate no stack by default.\n const origin =\n disclosure?.includeCallsite === true\n ? new Error(\"VibORM operation created here\").stack\n : undefined;\n return createExecutionContext(\n { model, operation },\n createCorrelationId,\n extensionChain,\n origin\n );\n}\n\nexport function createPendingOperationContext(\n model: string,\n operation: Operation,\n clientId: symbol,\n scopeId: symbol,\n extensionChain?: ResolvedExtensionChain\n): OperationExecutionContext {\n return Object.freeze({\n clientId,\n scopeId,\n attribution: createOperationExecutionContext(\n model,\n operation,\n extensionChain\n ),\n });\n}\n\n/** Preserve an ORM failure's deferred origin without wrapping errors returned by user extensions. */\nexport function withOperationErrorContext<T>(\n context: QueryExecutionContext,\n execute: () => Promise<T>\n): Promise<T> {\n const callsite = getExecutionCallsite(context);\n if (callsite === undefined) return execute();\n const diagnostics = getOfficialInstrumentationChainCapability(\n getExecutionExtensionChain(context)\n )?.diagnostics;\n const annotate = (error: unknown): never => {\n throw error instanceof VibORMError\n ? attachExecutionContext(error, {\n forceContext: false,\n driverName:\n typeof error.meta.driver === \"string\"\n ? error.meta.driver\n : \"unknown\",\n model: context.model,\n operation: context.operation,\n correlationId: context.correlationId,\n callsite,\n diagnostics,\n })\n : error;\n };\n try {\n return execute().catch(annotate);\n } catch (error) {\n return Promise.reject().catch(() => annotate(error));\n }\n}\n\n/** Build the private official-operation facts only for an official chain. */\nexport function createPendingOperationInstrumentationFacts(\n driver: AnyDriver,\n context: QueryExecutionContext,\n model: string,\n requestedOperation: string,\n operation: string,\n collection: string,\n cacheManaged: boolean\n): OfficialLifecycleFactsReader | undefined {\n return createOperationInstrumentationFacts(\n driver,\n context,\n model,\n requestedOperation,\n operation,\n collection,\n cacheManaged\n );\n}\n\n/** Build the corresponding private facts for a raw logical operation. */\nexport function createRawOperationInstrumentationFacts(\n driver: AnyDriver,\n context: QueryExecutionContext,\n operation: string\n): OfficialLifecycleFactsReader | undefined {\n return createOperationInstrumentationFacts(\n driver,\n context,\n undefined,\n operation,\n operation,\n undefined,\n false\n );\n}\n\nfunction createOperationInstrumentationFacts(\n driver: AnyDriver,\n context: QueryExecutionContext,\n model: string | undefined,\n requestedOperation: string,\n operation: string,\n collection: string | undefined,\n cacheManaged: boolean\n): OfficialLifecycleFactsReader | undefined {\n const official = getOfficialInstrumentationChainCapability(\n getExecutionExtensionChain(context)\n );\n if (official?.observesLifecycle !== true) return undefined;\n\n return () =>\n Object.freeze({\n kind: \"operation\" as const,\n context,\n identity: readDriverIdentity(driver),\n model,\n requestedOperation,\n operation,\n collection,\n complete(outcome) {\n const readCacheOutcomes = cacheManaged\n ? officialCacheRuntime().readCacheExecutionOutcomes(context)\n : undefined;\n // Core selects the failure: one error, one error log.\n const { failure } = outcome;\n const logged =\n outcome.status === \"failure\" &&\n official.wants(\"error-log\") &&\n isUnloggedError(failure)\n ? failure\n : undefined;\n const failureForTrace =\n outcome.status === \"failure\" &&\n failure instanceof Error &&\n official.wants(\"operation\")\n ? failure\n : undefined;\n if (\n readCacheOutcomes === undefined &&\n logged === undefined &&\n failureForTrace === undefined\n ) {\n return undefined;\n }\n return Object.freeze({\n kind: \"operation\" as const,\n endedAt: Date.now(),\n ...(readCacheOutcomes === undefined ? {} : { readCacheOutcomes }),\n ...((logged ?? failureForTrace) === undefined\n ? {}\n : { failure: logged ?? failureForTrace }),\n ...(logged === undefined ? { skipLog: true as const } : {}),\n });\n },\n });\n}\n\n/** Observe native-batch preparation and parsing as one logical operation. */\nexport async function observeTransactionBatchPhase<R>(\n executionContext: QueryExecutionContext,\n driver: AnyDriver,\n execute: () => R | Promise<R>\n): Promise<R> {\n const diagnostics = getOfficialInstrumentationChainCapability(\n getExecutionExtensionChain(executionContext)\n )?.diagnostics;\n try {\n return await execute();\n } catch (error) {\n throw normalizeDriverError(error, {\n driverName: driver.driverName,\n dialect: driver.dialect,\n model: executionContext.model,\n operation: executionContext.operation,\n correlationId: executionContext.correlationId,\n callsite: getExecutionCallsite(executionContext),\n diagnostics,\n forceContext: true,\n });\n }\n}\n\nexport function createCorrelationId(): string {\n if (typeof globalThis.crypto?.randomUUID === \"function\") {\n return globalThis.crypto.randomUUID();\n }\n return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;\n}\n\n/** Whether the exact failure has not already been presented downstream. */\nfunction isUnloggedError(error: unknown): error is Error {\n return error instanceof Error && !isErrorLogged(error);\n}\n","import type { AnyDriver } from \"@drivers/exports\";\nimport { PendingOperationError } from \"@errors\";\n\nfunction captureExecution<T>(run: () => Promise<T>): Promise<T> {\n try {\n return run();\n } catch (error) {\n return Promise.reject(error);\n }\n}\n\n/** One deferred operation's mutually exclusive default/transaction execution. */\nexport class PendingExecution<T> {\n #promise: Promise<T> | null = null;\n #executedWith: AnyDriver | \"default\" | null = null;\n #reservedForBatch = false;\n readonly #model: string;\n readonly #operation: string;\n\n constructor(model: string, operation: string) {\n this.#model = model;\n this.#operation = operation;\n }\n\n executeDefault(run: () => Promise<T>): Promise<T> {\n if (this.#executedWith !== null && this.#executedWith !== \"default\") {\n throw PendingOperationError.alreadyExecutedWithDriver(\n this.#model,\n this.#operation\n );\n }\n\n if (!this.#promise) {\n this.#executedWith = \"default\";\n this.#promise = captureExecution(run);\n }\n return this.#promise;\n }\n\n executeWith(driver: AnyDriver, run: () => Promise<T>): Promise<T> {\n if (this.#reservedForBatch) {\n throw PendingOperationError.alreadyExecutedWithDriver(\n this.#model,\n this.#operation\n );\n }\n if (this.#executedWith === \"default\") {\n throw PendingOperationError.alreadyExecutedDefault(\n this.#model,\n this.#operation\n );\n }\n if (this.#executedWith !== null && this.#executedWith !== driver) {\n throw PendingOperationError.differentDriverConflict(\n this.#model,\n this.#operation\n );\n }\n\n if (!this.#promise) {\n this.#executedWith = driver;\n this.#promise = captureExecution(run);\n }\n return this.#promise;\n }\n\n reserveWith(driver: AnyDriver): void {\n if (this.#executedWith === \"default\") {\n throw PendingOperationError.alreadyExecutedDefault(\n this.#model,\n this.#operation\n );\n }\n if (this.#executedWith !== null) {\n if (this.#executedWith !== driver) {\n throw PendingOperationError.differentDriverConflict(\n this.#model,\n this.#operation\n );\n }\n throw PendingOperationError.alreadyExecutedWithDriver(\n this.#model,\n this.#operation\n );\n }\n this.#executedWith = driver;\n this.#reservedForBatch = true;\n }\n\n /** Run the core child once after the array coordinator reserved this operation. */\n executeReserved(run: () => Promise<T>): Promise<T> {\n if (!this.#promise) this.#promise = captureExecution(run);\n return this.#promise;\n }\n}\n","import { Sql } from \"@sql\";\nimport { isRecord } from \"@validation/value-guards\";\n\ntype OpaqueInspectionKind = \"accessor\" | \"function\" | \"unsupported\";\n\nconst opaqueInspectionValues = Object.freeze({\n accessor: opaqueInspectionValue(\"accessor\"),\n function: opaqueInspectionValue(\"function\"),\n unsupported: opaqueInspectionValue(\"unsupported\"),\n});\n\nconst sqlStringsGetter = Object.getOwnPropertyDescriptor(\n Sql.prototype,\n \"strings\"\n)?.get;\nconst sqlValuesGetter = Object.getOwnPropertyDescriptor(\n Sql.prototype,\n \"values\"\n)?.get;\n\nfunction opaqueInspectionValue(\n kind: OpaqueInspectionKind\n): Readonly<Record<string, unknown>> {\n const value: Record<string, unknown> = Object.create(null);\n value.opaque = kind;\n return Object.freeze(value);\n}\n\n/** Copy the prepared payload without exposing caller authority or core state. */\nexport function snapshotQueryInput(\n input: Record<string, unknown>\n): Readonly<Record<string, unknown>> {\n return snapshotOwn(input, new Map(), false);\n}\n\n/**\n * One plain record or array, copied own key by own key: each enumerable data\n * member is snapshotted, an accessor is disclosed as opaque, and an array keeps\n * its `length` descriptor — array exotic-object invariants guarantee it is the\n * non-configurable data descriptor of one valid uint32 length, and a proxy that\n * lies there is rejected by `getOwnPropertyDescriptor` before this point.\n */\nfunction snapshotOwn(\n input: object,\n seen: Map<object, unknown>,\n array: boolean\n): Readonly<Record<string, unknown>> {\n const snapshot: Record<string, unknown> = array ? [] : Object.create(null);\n seen.set(input, snapshot);\n let keys: readonly PropertyKey[];\n try {\n keys = Reflect.ownKeys(input);\n } catch {\n seen.set(input, opaqueInspectionValues.unsupported);\n return opaqueInspectionValues.unsupported;\n }\n for (const key of keys) {\n let descriptor: PropertyDescriptor | undefined;\n try {\n descriptor = Object.getOwnPropertyDescriptor(input, key);\n } catch {\n seen.set(input, opaqueInspectionValues.unsupported);\n return opaqueInspectionValues.unsupported;\n }\n if (descriptor === undefined) continue;\n if (array && key === \"length\") {\n Object.defineProperty(snapshot, key, descriptor);\n continue;\n }\n if (!descriptor.enumerable) continue;\n Object.defineProperty(snapshot, key, {\n configurable: false,\n enumerable: true,\n value:\n \"value\" in descriptor\n ? snapshotValue(descriptor.value, seen)\n : opaqueInspectionValues.accessor,\n writable: false,\n });\n }\n return Object.freeze(snapshot);\n}\n\nfunction snapshotValue(value: unknown, seen: Map<object, unknown>): unknown {\n if (typeof value === \"function\") return opaqueInspectionValues.function;\n if (value === null || typeof value !== \"object\") return value;\n if (seen.has(value)) return seen.get(value);\n try {\n if (Array.isArray(value)) return snapshotOwn(value, seen, true);\n const prototype = Object.getPrototypeOf(value);\n if (prototype === Sql.prototype && value instanceof Sql) {\n return snapshotSql(value, seen);\n }\n if (prototype === Date.prototype && value instanceof Date) {\n const snapshot = Object.freeze(\n new Date(Date.prototype.getTime.call(value))\n );\n seen.set(value, snapshot);\n return snapshot;\n }\n if (value instanceof Uint8Array) {\n const snapshot = new Uint8Array(value);\n seen.set(value, snapshot);\n return snapshot;\n }\n if (prototype === ArrayBuffer.prototype && value instanceof ArrayBuffer) {\n const snapshot = value.slice(0);\n seen.set(value, snapshot);\n return snapshot;\n }\n if (prototype === Map.prototype && value instanceof Map) {\n const snapshot = new Map<unknown, unknown>();\n seen.set(value, snapshot);\n Map.prototype.forEach.call(value, (member: unknown, key: unknown) => {\n snapshot.set(snapshotValue(key, seen), snapshotValue(member, seen));\n });\n return snapshot;\n }\n if (prototype === Set.prototype && value instanceof Set) {\n const snapshot = new Set<unknown>();\n seen.set(value, snapshot);\n Set.prototype.forEach.call(value, (member: unknown) => {\n snapshot.add(snapshotValue(member, seen));\n });\n return snapshot;\n }\n if (ArrayBuffer.isView(value)) {\n const snapshot = structuredClone(value);\n seen.set(value, snapshot);\n return snapshot;\n }\n if (\n (prototype === Object.prototype || prototype === null) &&\n isRecord(value)\n ) {\n return snapshotOwn(value, seen, false);\n }\n } catch {\n // A hostile proxy or malformed built-in is disclosed only as an opaque fact.\n }\n seen.set(value, opaqueInspectionValues.unsupported);\n return opaqueInspectionValues.unsupported;\n}\n\nfunction snapshotSql(value: Sql, seen: Map<object, unknown>): Sql {\n if (!(sqlStringsGetter && sqlValuesGetter)) {\n throw new TypeError(\"Sql inspection getters are unavailable\");\n }\n const sourceStrings = Reflect.apply(sqlStringsGetter, value, []);\n const sourceValues = Reflect.apply(sqlValuesGetter, value, []);\n const strings = new Array<string>(sourceStrings.length);\n for (let index = 0; index < sourceStrings.length; index += 1) {\n const descriptor = Object.getOwnPropertyDescriptor(sourceStrings, index);\n if (\n !(\n descriptor &&\n \"value\" in descriptor &&\n typeof descriptor.value === \"string\"\n )\n ) {\n throw new TypeError(\"Sql inspection strings are not plain data values\");\n }\n strings[index] = descriptor.value;\n }\n const detachedValues = new Array<unknown>(sourceValues.length);\n const snapshot = new Sql(strings, detachedValues);\n seen.set(value, snapshot);\n for (let index = 0; index < sourceValues.length; index += 1) {\n const descriptor = Object.getOwnPropertyDescriptor(sourceValues, index);\n detachedValues[index] =\n descriptor && \"value\" in descriptor\n ? snapshotValue(descriptor.value, seen)\n : opaqueInspectionValues.accessor;\n }\n\n snapshot.toStatement(\"?\");\n snapshot.toStatement(\"$n\");\n snapshot.toStatement(\":n\");\n for (const key of Reflect.ownKeys(snapshot)) {\n const member = Reflect.get(snapshot, key);\n if (member !== null && typeof member === \"object\") Object.freeze(member);\n }\n Object.freeze(snapshot);\n return snapshot;\n}\n","import type { Sql } from \"@sql\";\n\nexport { normalizedBindParameterLimit } from \"@drivers/bind-parameter-capacity\";\n\nexport interface CompiledBindBudgetChunk {\n /** Inclusive semantic-item offset. */\n readonly start: number;\n /** Exclusive semantic-item offset. */\n readonly end: number;\n readonly statement: Sql;\n}\n\n/**\n * Compile the largest contiguous semantic-item ranges that fit a verified bind\n * budget. The compiled SQL is the meter; callers do not estimate binds from\n * item count or shape. `compile` must be monotonic for a growing prefix, as\n * INSERT value tuples and exact-key predicate lists are.\n *\n * Unknown capacity preserves the original one-statement shape. One item that\n * exceeds a known budget stays indivisible so the executor's final capacity\n * check can refuse it before I/O.\n */\nexport function compileBindBudgetChunks(\n itemCount: number,\n maxBindParametersPerStatement: number | undefined,\n compile: (start: number, end: number) => Sql\n): CompiledBindBudgetChunk[] {\n if (itemCount === 0) return [];\n const whole = compile(0, itemCount);\n if (\n maxBindParametersPerStatement === undefined ||\n whole.values.length <= maxBindParametersPerStatement ||\n itemCount === 1\n ) {\n return [{ start: 0, end: itemCount, statement: whole }];\n }\n\n const chunks: CompiledBindBudgetChunk[] = [];\n let start = 0;\n while (start < itemCount) {\n let lower = start + 1;\n let upper = Math.min(itemCount, start + 1);\n let largest: CompiledBindBudgetChunk | undefined;\n // Probe geometrically from this window, never from the entire remaining\n // suffix. Oversized compilation stays proportional to a window's size.\n while (true) {\n const statement = compile(start, upper);\n if (statement.values.length > maxBindParametersPerStatement) break;\n largest = { start, end: upper, statement };\n if (upper === itemCount) break;\n lower = upper + 1;\n upper = Math.min(itemCount, start + (upper - start) * 2);\n }\n if (largest?.end !== itemCount) {\n upper -= 1;\n while (lower <= upper) {\n const end = lower + Math.floor((upper - lower) / 2);\n const statement = compile(start, end);\n if (statement.values.length <= maxBindParametersPerStatement) {\n largest = { start, end, statement };\n lower = end + 1;\n } else upper = end - 1;\n }\n }\n const chunk = largest ?? {\n start,\n end: start + 1,\n statement: compile(start, start + 1),\n };\n chunks.push(chunk);\n start = chunk.end;\n }\n return chunks;\n}\n","/**\n * `findUnique` batching: Prisma's dataloader, at the operation dispatch layer.\n *\n * Calls issued in the same tick that would each cost one round trip are\n * answered by ONE `findMany` over the keys they name, and each caller gets its\n * own row back. The merge happens below every per-call lifecycle step — request\n * transforms, controls, default omit, admission, query interceptors, the\n * official cache and observers all still see each call as its own operation —\n * and above the route, which runs the merged read like any other read.\n *\n * Two calls share a batch only when nothing that decides their rows differs:\n * the same engine (so the same client view, extension chain and bound\n * controls), outside every transaction, the same model, the same unique key\n * spelled the same way, the same projection (`select`/`include`/`omit`, nested\n * arguments included, compared structurally) and the same admitted controls.\n * The `where` must be the key alone: a value per member, nothing else.\n *\n * A row reaches a caller only when its decoded key is EXACTLY the caller's\n * admitted key. Whatever cannot be decided that way runs as the caller's own\n * unbatched operation, so a batch can cost a statement but never change an\n * answer:\n * - a string key without an exact match (a case-insensitive or padding\n * collation can make the database find a row JavaScript does not match);\n * - a missing row for `findUniqueOrThrow` (its own error comes from its owner);\n * - a merged read that fails, for every caller of that read.\n * Only string, integer and bigint key members are batched. An integer or\n * bigint member's decoded value is its bound value, so a row JavaScript does\n * not match is a row the database did not return either: a missing integer\n * key answers `null` from the batch.\n */\n\nimport { passThroughParseResult } from \"@adapters/adapter-result-parser\";\nimport { normalizedBindParameterLimit } from \"@drivers/bind-parameter-capacity\";\nimport type { QueryExecutionContext } from \"@drivers/exports\";\nimport type { AdmittedControls } from \"@extensions/controls\";\nimport type { AnyModel } from \"@schema/model\";\nimport { findAddressableKey } from \"@schema/model/keys\";\nimport { isRecord } from \"@validation/value-guards\";\nimport { compileBindBudgetChunks } from \"./bind-budget\";\nimport type { QueryEngine } from \"./query-engine\";\nimport type { RoutedCandidateOperation } from \"./raptor3/route/client-route\";\nimport type { CallRows } from \"./raptor3/shared/row-scope\";\n\n/** One `findUnique` call, as its pending operation knows it at dispatch. */\nexport interface FindUniqueCall {\n readonly engine: QueryEngine;\n readonly model: AnyModel;\n /** `findUnique` or `findUniqueOrThrow`. */\n readonly requested: string;\n /** The client-prepared input: controls removed, request transforms applied. */\n readonly args: Record<string, unknown>;\n readonly controls: AdmittedControls | undefined;\n /** The call's own row domain, resolved for the batch that runs it. */\n readonly rows: () => CallRows | undefined;\n readonly routed: RoutedCandidateOperation;\n readonly context: QueryExecutionContext;\n /** The call's own, unbatched execution. */\n readonly run: () => Promise<unknown>;\n}\n\n/** What a batch decided for one caller. */\ntype Decision = { readonly value: unknown } | typeof RUN_ALONE;\nconst RUN_ALONE = Symbol(\"run alone\");\n\ninterface Member {\n readonly values: readonly unknown[];\n readonly signature: string;\n readonly orThrow: boolean;\n readonly decide: (decision: Decision) => void;\n}\n\ninterface Batch {\n readonly leader: FindUniqueCall;\n readonly fields: readonly string[];\n readonly textKey: boolean;\n readonly members: Member[];\n}\n\n/** Key members whose decoded value is the bound value, by scalar type. */\nconst EXACT_KEY_VALUES: Readonly<Record<string, (value: unknown) => boolean>> =\n {\n string: (value) => typeof value === \"string\",\n int: (value) => typeof value === \"number\" && Number.isSafeInteger(value),\n bigint: (value) => typeof value === \"bigint\",\n };\n\nlet pending: Map<QueryEngine, Map<string, Batch[]>> | undefined;\n\n/**\n * After the current synchronous run AND the microtasks it queued, so resolvers\n * that each await once before calling still share a batch. Where there is no\n * `process.nextTick`, the end of the current synchronous run.\n */\nconst defer: (callback: () => void) => void = (() => {\n const host = (\n globalThis as {\n process?: { nextTick?: (callback: () => void) => void };\n }\n ).process;\n const nextTick = host?.nextTick;\n return typeof nextTick === \"function\"\n ? (callback) => nextTick.call(host, callback)\n : queueMicrotask;\n})();\n\n/**\n * Join a batch, or answer `undefined` when this call does not batch and must\n * run as it always has.\n */\nexport function batchFindUnique(\n call: FindUniqueCall\n): Promise<unknown> | undefined {\n if (!engineBatches(call.engine)) return undefined;\n let admitted: Record<string, unknown>;\n try {\n admitted = call.routed.preparedArgs;\n } catch {\n // The call's own execution admits again and rejects with the same error.\n return undefined;\n }\n const key = keyOf(call.model, admitted.where);\n if (key === undefined) return undefined;\n const { where: _where, ...projection } = call.args;\n const shape = signatureOf(projection);\n if (shape === undefined) return undefined;\n\n let decide!: (decision: Decision) => void;\n const decision = new Promise<Decision>((resolve) => {\n decide = resolve;\n });\n const member: Member = {\n values: key.values,\n signature: signatureOf(key.values)!,\n orThrow: call.requested !== \"findUnique\",\n decide,\n };\n enqueue(call, `${key.selector}\\u0000${shape}`, key, member);\n // The decision is reached in the caller's own continuation, so a call that\n // runs alone runs in its own async context.\n return decision.then((settled) =>\n settled === RUN_ALONE ? call.run() : settled.value\n );\n}\n\n/**\n * The engine runs outside every transaction scope, and nothing below the\n * operation is keyed on the statement or the operation name: a statement\n * transform sees `findUnique`, and a result middleware is handed the operation\n * name, so either would observe the merged `findMany`.\n */\nfunction engineBatches(engine: QueryEngine): boolean {\n const { driver } = engine;\n return (\n driver === engine.route.driver &&\n (engine.extensionChain?.statement.length ?? 0) === 0 &&\n driver.result?.parseResult === undefined &&\n driver.adapter.result.parseResult === passThroughParseResult\n );\n}\n\ninterface BatchKey {\n readonly selector: string;\n readonly fields: readonly string[];\n readonly values: readonly unknown[];\n readonly textKey: boolean;\n}\n\n/** The admitted `where` as one addressable key and nothing else, or nothing. */\nfunction keyOf(model: AnyModel, where: unknown): BatchKey | undefined {\n if (!isRecord(where)) return undefined;\n const selectors = Object.keys(where);\n if (selectors.length !== 1) return undefined;\n const selector = selectors[0]!;\n const key = findAddressableKey(model, selector);\n if (key === undefined) return undefined;\n const value = where[selector];\n let values: unknown[];\n if (key.name === undefined) values = [value];\n else {\n if (!isRecord(value) || Object.keys(value).length !== key.fields.length)\n return undefined;\n values = key.fields.map((field) => value[field]);\n }\n // A member the model hides from every result cannot be read back to\n // dispatch a row, and no call may select it.\n const { scalars, omit } = model[\"~\"].state;\n let textKey = false;\n for (const [index, field] of key.fields.entries()) {\n const state = scalars[field]?.[\"~\"].state;\n const exact = state && !state.array && EXACT_KEY_VALUES[state.type];\n if (!exact?.(values[index]) || omit?.[field] === true) return undefined;\n if (state.type === \"string\") textKey = true;\n }\n return { selector, fields: key.fields, values, textKey };\n}\n\nfunction enqueue(\n call: FindUniqueCall,\n shape: string,\n key: BatchKey,\n member: Member\n): void {\n if (pending === undefined) {\n pending = new Map();\n defer(flush);\n }\n let byShape = pending.get(call.engine);\n if (byShape === undefined) pending.set(call.engine, (byShape = new Map()));\n const signature = `${call.model[\"~\"].names.ts}\\u0000${shape}`;\n let batches = byShape.get(signature);\n if (batches === undefined) byShape.set(signature, (batches = []));\n let batch = batches.find((candidate) =>\n sameControls(candidate.leader.controls, call.controls)\n );\n if (batch === undefined) {\n batch = {\n leader: call,\n fields: key.fields,\n textKey: key.textKey,\n members: [],\n };\n batches.push(batch);\n }\n batch.members.push(member);\n}\n\n/** Admitted controls decide the row domain: the same values, the same rows. */\nfunction sameControls(\n first: AdmittedControls | undefined,\n second: AdmittedControls | undefined\n): boolean {\n if (first === second) return true;\n if (first === undefined || second === undefined) return false;\n const names = Object.keys(first);\n return (\n names.length === Object.keys(second).length &&\n names.every(\n (name) => Object.hasOwn(second, name) && first[name] === second[name]\n )\n );\n}\n\nfunction flush(): void {\n const batches = pending;\n pending = undefined;\n for (const byShape of batches!.values())\n for (const list of byShape.values())\n for (const batch of list) runBatch(batch);\n}\n\ninterface Chunk {\n readonly signatures: readonly string[];\n readonly read: RoutedCandidateOperation;\n}\n\n/**\n * Run one batch. Whatever goes wrong before a caller's row is decided sends\n * that caller back to its own execution; a caller is decided once, so a later\n * decision never replaces an earlier one.\n */\nfunction runBatch(batch: Batch): void {\n const { members } = batch;\n const runAlone = (callers: readonly Member[]) => {\n for (const member of callers) member.decide(RUN_ALONE);\n };\n if (members.length === 1) {\n runAlone(members);\n return;\n }\n try {\n const bySignature = new Map<string, Member[]>();\n for (const member of members) {\n const same = bySignature.get(member.signature);\n if (same) same.push(member);\n else bySignature.set(member.signature, [member]);\n }\n const plan = planBatch(batch, [...bySignature.values()]);\n const { engine, context } = batch.leader;\n for (const chunk of plan.chunks) {\n const callers = chunk.signatures.flatMap((key) => bySignature.get(key)!);\n chunk.read\n .execute<Record<string, unknown>[]>({\n committedWriteSegment: undefined,\n context,\n driverOverride: undefined,\n engineDriver: engine.driver,\n isWrite: false,\n writeMayBeVisible: undefined,\n })\n .then(\n (rows) => {\n try {\n dispatch(batch, chunk, bySignature, plan.injected, rows);\n } catch {\n runAlone(callers);\n }\n },\n () => runAlone(callers)\n );\n }\n } catch {\n runAlone(members);\n }\n}\n\n/**\n * The merged reads, split where the driver's bind budget requires, through the\n * one chunking owner: the compiled statement is the meter.\n */\nfunction planBatch(\n batch: Batch,\n keys: readonly (readonly Member[])[]\n): { chunks: Chunk[]; injected: readonly string[] } {\n const { leader, fields } = batch;\n const projected = projectionWithKey(leader, fields);\n const rows = leader.rows();\n const reads = new Map<string, RoutedCandidateOperation>();\n const read = (start: number, end: number): RoutedCandidateOperation => {\n const id = `${start}:${end}`;\n let operation = reads.get(id);\n if (operation === undefined) {\n const values = keys.slice(start, end).map((same) => same[0]!.values);\n operation = leader.engine.route.operation(\n leader.model,\n \"findMany\",\n { ...projected.args, where: mergedWhere(fields, values) },\n rows\n );\n reads.set(id, operation);\n }\n return operation;\n };\n const signatures = keys.map((same) => same[0]!.signature);\n const limit = normalizedBindParameterLimit(\n leader.engine.driver.maxBindParametersPerStatement\n );\n const ranges =\n limit === undefined\n ? [{ start: 0, end: keys.length }]\n : compileBindBudgetChunks(\n keys.length,\n limit,\n (start, end) => read(start, end).buildStatement()!\n );\n return {\n chunks: ranges.map(({ start, end }) => ({\n signatures: signatures.slice(start, end),\n read: read(start, end),\n })),\n injected: projected.injected,\n };\n}\n\n/** One key member: `IN`; a compound key: one equality group per key. */\nfunction mergedWhere(\n fields: readonly string[],\n values: readonly (readonly unknown[])[]\n): Record<string, unknown> {\n if (fields.length === 1)\n return { [fields[0]!]: { in: values.map((value) => value[0]) } };\n return {\n OR: values.map((value) =>\n Object.fromEntries(fields.map((field, index) => [field, value[index]]))\n ),\n };\n}\n\n/**\n * The leader's projection with every key member read, so each row can be\n * dispatched; a member the caller does not read is removed again before the\n * row is handed over. A member can be missing because it is not selected or\n * because it is omitted (an omit wins over a select), so both are lifted.\n */\nfunction projectionWithKey(\n leader: FindUniqueCall,\n fields: readonly string[]\n): { args: Record<string, unknown>; injected: string[] } {\n const { where: _where, ...args } = leader.args;\n const selected = leader.routed.preparedArgs.select;\n const injected: string[] = [];\n if (!isRecord(selected)) return { args, injected };\n for (const field of fields) {\n if (selected[field] === true) continue;\n if (isRecord(args.select)) args.select = { ...args.select, [field]: true };\n if (isRecord(args.omit)) args.omit = { ...args.omit, [field]: false };\n injected.push(field);\n }\n return { args, injected };\n}\n\nfunction dispatch(\n batch: Batch,\n chunk: Chunk,\n bySignature: ReadonlyMap<string, readonly Member[]>,\n injected: readonly string[],\n rows: readonly Record<string, unknown>[]\n): void {\n const found = new Map<string | undefined, Record<string, unknown>>();\n for (const row of rows) {\n const signature = signatureOf(batch.fields.map((field) => row[field]));\n for (const field of injected) delete row[field];\n if (!found.has(signature)) found.set(signature, row);\n }\n for (const signature of chunk.signatures) {\n const row = found.get(signature);\n for (const [index, member] of bySignature.get(signature)!.entries()) {\n if (row !== undefined)\n member.decide({ value: index === 0 ? row : copyResult(row) });\n else if (member.orThrow || batch.textKey) member.decide(RUN_ALONE);\n else member.decide({ value: null });\n }\n }\n}\n\n/**\n * A structural signature of plain argument data: equal signatures, equal\n * arguments. Anything else (a function, a fragment, a class instance) has\n * none, and the call does not batch.\n */\nfunction signatureOf(value: unknown): string | undefined {\n switch (typeof value) {\n case \"undefined\":\n return \"u\";\n case \"boolean\":\n case \"number\":\n return String(value);\n case \"string\":\n return JSON.stringify(value);\n case \"bigint\":\n return `${value}n`;\n case \"object\":\n break;\n default:\n return undefined;\n }\n if (value === null) return \"null\";\n if (Array.isArray(value)) {\n const items: string[] = [];\n for (const item of value) {\n const signature = signatureOf(item);\n if (signature === undefined) return undefined;\n items.push(signature);\n }\n return `[${items.join(\",\")}]`;\n }\n if (value instanceof Date) return `D${value.getTime()}`;\n const prototype = Object.getPrototypeOf(value);\n if (prototype !== Object.prototype && prototype !== null) return undefined;\n const entries: string[] = [];\n for (const [name, entry] of Object.entries(value)) {\n const signature = signatureOf(entry);\n if (signature === undefined) return undefined;\n entries.push(`${JSON.stringify(name)}:${signature}`);\n }\n return `{${entries.join(\",\")}}`;\n}\n\n/**\n * A second caller of the same key gets its own result, as it would have\n * unbatched: plain objects, arrays, dates and byte arrays are copied, keeping\n * the shape of what is shared inside the result (a node reached twice is one\n * copy); an immutable value (a Decimal) is shared. Members are defined, never\n * assigned, so a JSON key named `__proto__` stays an own member.\n */\nfunction copyResult(\n value: unknown,\n copies = new Map<object, unknown>()\n): unknown {\n if (typeof value !== \"object\" || value === null) return value;\n const known = copies.get(value);\n if (known !== undefined) return known;\n if (value instanceof Date) return new Date(value.getTime());\n if (value instanceof Uint8Array)\n return Uint8Array.prototype.slice.call(value);\n if (Array.isArray(value)) {\n const copy: unknown[] = [];\n copies.set(value, copy);\n for (const item of value) copy.push(copyResult(item, copies));\n return copy;\n }\n const prototype = Object.getPrototypeOf(value);\n if (prototype !== Object.prototype && prototype !== null) return value;\n const copy = Object.create(prototype) as object;\n copies.set(value, copy);\n for (const [name, entry] of Object.entries(value))\n Object.defineProperty(copy, name, {\n value: copyResult(entry, copies),\n enumerable: true,\n writable: true,\n configurable: true,\n });\n return copy;\n}\n","/**\n * Deferred operation lifecycle owned by the query engine.\n * Validation, SQL construction, and execution remain lazy until a lifecycle\n * method is called. Every operation is served by the single (V2) engine.\n */\n\nimport { isCacheManagedExecution } from \"@cache/capability\";\nimport type { AnyDriver, QueryExecutionContext } from \"@drivers/exports\";\nimport {\n InvalidTransactionInputError,\n retainWriteOutcomeFailure,\n} from \"@errors\";\nimport {\n lookupPlacedControls,\n lookupResolvedExtensionHandlers,\n} from \"@extensions/chain\";\nimport { type AdmittedControls, admitControls } from \"@extensions/controls\";\nimport { observeOperation } from \"@extensions/observation\";\nimport {\n executePreparedQuery,\n type PreparedModelQueryContext,\n type QueryInterceptionMode,\n type WriteOutcomeRegistration,\n} from \"@extensions/query\";\nimport { callRows } from \"@extensions/rows\";\nimport type { AnyModel } from \"@schema/model\";\nimport type { Sql } from \"@sql\";\nimport type { CacheResultCodec } from \"./cache-flow\";\nimport {\n createPendingOperationContext,\n createPendingOperationInstrumentationFacts,\n type OperationExecutionContext,\n observeTransactionBatchPhase,\n withOperationErrorContext,\n} from \"./execution-context\";\nimport { batchFindUnique } from \"./find-unique-batch\";\nimport { PendingExecution } from \"./pending-execution\";\nimport type { QueryEngine } from \"./query-engine\";\nimport { snapshotQueryInput } from \"./query-inspection\";\nimport type {\n ClientOperationRoute,\n RoutedCandidateOperation,\n} from \"./raptor3/route/client-route\";\nimport { isReadOperation, ROUTED_OPERATIONS } from \"./routed-operations\";\nimport {\n registerTransactionOperationOwner,\n type TransactionOperation,\n type TransactionOperationOwner,\n} from \"./transaction-operation\";\nimport {\n type Operation,\n type PreparedBatchOperation,\n type PrepareOptions,\n QueryEngineError,\n} from \"./types\";\n\nexport const PENDING_OPERATION_SYMBOL = Symbol.for(\"viborm.pendingOperation\");\n\n/** Publish a durably committed write segment to the cache and observers. */\nexport type CommittedWriteSegmentNotification = () => Promise<void>;\n/** Conservatively invalidate after dispatch when provider acknowledgement is ambiguous. */\nexport type WriteMayBeVisibleNotification = () => Promise<void>;\n\ntype PendingCacheExecution<T> = (\n execute: (\n driver?: AnyDriver,\n committedWriteSegment?: CommittedWriteSegmentNotification,\n writeMayBeVisible?: WriteMayBeVisibleNotification\n ) => Promise<T>,\n driverOverride: AnyDriver | undefined\n) => Promise<T>;\n\ntype AttachPendingCacheExecution = <T>(\n operation: PendingOperation<T>,\n wrapper: PendingCacheExecution<T>\n) => PendingOperation<T>;\n\ninterface PendingCacheResultAccess {\n readonly args: Record<string, unknown>;\n /** The controls the read admitted: part of what its cache entry is keyed on. */\n readonly controls: AdmittedControls | undefined;\n readonly codec: CacheResultCodec;\n readonly executionContext: QueryExecutionContext;\n}\n\ntype ReadPendingCacheResult = (\n operation: PendingOperation<unknown>\n) => PendingCacheResultAccess;\n\nlet attachPendingCacheExecutionFriend: AttachPendingCacheExecution;\nlet readPendingCacheResultFriend: ReadPendingCacheResult;\n\ntype DeferredExecution<T> = (\n driverOverride?: AnyDriver,\n committedWriteSegment?: CommittedWriteSegmentNotification,\n writeMayBeVisible?: WriteMayBeVisibleNotification\n) => Promise<T>;\n\nfunction combineWriteNotifications(\n first: (() => Promise<void>) | undefined,\n second: (() => Promise<void>) | undefined\n): (() => Promise<void>) | undefined {\n if (first === undefined) return second;\n if (second === undefined || second === first) return first;\n return async () => {\n let firstFailed = false;\n let firstFailure: unknown;\n try {\n await first();\n } catch (error) {\n firstFailed = true;\n firstFailure = error;\n }\n try {\n await second();\n } catch (error) {\n if (firstFailed) {\n throw retainWriteOutcomeFailure(\n firstFailure,\n error,\n \"Write publication callbacks both failed.\"\n );\n }\n throw error;\n }\n if (firstFailed) throw firstFailure;\n };\n}\n\n/**\n * Client-owned work that must finish before operation construction starts. It\n * receives the arguments without their controls, and the controls admitted\n * from them.\n */\nexport type PrepareOperationInput = (\n args: Record<string, unknown>,\n controls: AdmittedControls | undefined\n) => Record<string, unknown>;\n\n/** Package-owned write listener prepared only after the operation input is trusted. */\nexport type PrepareWriteOutcomeRegistration = (\n context: QueryExecutionContext,\n controls: AdmittedControls | undefined\n) => WriteOutcomeRegistration | undefined;\n\ninterface OperationInputPreparation {\n readonly prepare: PrepareOperationInput;\n status: \"pending\" | \"success\" | \"failure\";\n args?: Record<string, unknown>;\n /** The operation's one admission record, settled with its arguments. */\n controls?: AdmittedControls;\n error?: unknown;\n}\n\ninterface OperationResolution {\n routed?: RoutedCandidateOperation;\n}\n\ntype ResolvedPrepareOptions = Readonly<\n PrepareOptions & { readonly originalOperation: string }\n>;\n\nconst OR_THROW_SUFFIX = \"OrThrow\";\nconst pendingOperationConstruction = Object.freeze({});\n\ntype CreatePendingOperation = <T>(\n engine: QueryEngine,\n model: AnyModel,\n operation: Operation | `${Operation}OrThrow`,\n args: Record<string, unknown>,\n options?: PrepareOptions,\n prepareInput?: PrepareOperationInput,\n prepareWriteOutcomeRegistration?: PrepareWriteOutcomeRegistration\n) => PendingOperation<T>;\n\nlet createPendingOperationFriend: CreatePendingOperation;\n\nlet pendingOperationTransactionOwner: TransactionOperationOwner<\n PendingOperation<unknown>\n>;\n\n/** One user operation, from lazy creation through execution and parsing. */\nexport class PendingOperation<T>\n implements Promise<T>, TransactionOperation<T>\n{\n readonly [Symbol.toStringTag] = \"Promise\";\n readonly [PENDING_OPERATION_SYMBOL] = true;\n readonly #context: OperationExecutionContext;\n readonly #engine: QueryEngine;\n readonly #model: AnyModel;\n readonly #args: Record<string, unknown>;\n readonly #modelName: string;\n readonly #operation: Operation;\n readonly #options: ResolvedPrepareOptions;\n\n readonly #execution: PendingExecution<T>;\n readonly #deferredExecution: DeferredExecution<T> | undefined;\n readonly #inputPreparation: OperationInputPreparation | undefined;\n readonly #prepareWriteOutcomeRegistration:\n | PrepareWriteOutcomeRegistration\n | undefined;\n #writeOutcomeRegistration: WriteOutcomeRegistration | undefined;\n #writeOutcomeRegistrationResolved = false;\n #operationResolution: OperationResolution | undefined;\n #observationCommitCertainty: \"committed\" | \"may-have-committed\" | undefined;\n\n // The ONE operation owner (C-01). Every client lineage builds it in\n // `VibORM`'s constructor and `bind()` forwards it, so an operation that was\n // created from a client has one.\n readonly #route: ClientOperationRoute;\n #routedInstance: RoutedCandidateOperation | undefined;\n #singlePackage: PreparedBatchOperation<unknown> | undefined;\n #singlePackageResolved = false;\n\n static {\n createPendingOperationFriend = <T>(\n engine: QueryEngine,\n model: AnyModel,\n operation: Operation | `${Operation}OrThrow`,\n args: Record<string, unknown>,\n options?: PrepareOptions,\n prepareInput?: PrepareOperationInput,\n prepareWriteOutcomeRegistration?: PrepareWriteOutcomeRegistration\n ) =>\n new PendingOperation<T>(\n pendingOperationConstruction,\n engine,\n model,\n operation,\n args,\n options,\n undefined,\n undefined,\n prepareInput === undefined\n ? undefined\n : { prepare: prepareInput, status: \"pending\" },\n undefined,\n prepareWriteOutcomeRegistration\n );\n attachPendingCacheExecutionFriend = (operation, wrapper) =>\n operation.#wrapExecution(wrapper);\n // Each part is computed when read: a read the cache bypasses asks only\n // for its controls, admitted once with its arguments.\n readPendingCacheResultFriend = (operation) => ({\n get args() {\n return operation.cacheKeyArgs();\n },\n get controls() {\n operation.#resolveArgs();\n return operation.#inputPreparation?.controls;\n },\n get codec() {\n return operation.#cacheResultCodec();\n },\n executionContext: operation.#context.attribution,\n });\n pendingOperationTransactionOwner = Object.freeze({\n clientId: (operation) => operation.#context.clientId,\n scopeId: (operation) => operation.#context.scopeId,\n model: (operation) => operation.#modelName,\n operation: (operation) => operation.#operation,\n context: (operation) => operation.#context.attribution,\n requiresInterception: (operation) => {\n const requestedOperation = String(operation.#options.originalOperation);\n const requestHandlers = lookupResolvedExtensionHandlers(\n operation.#engine.extensionChain,\n \"request\",\n operation.#modelName,\n requestedOperation\n );\n const hasRequestHandlers =\n requestHandlers !== undefined && requestHandlers.length > 0;\n const requestNeedsObservedCoordination =\n hasRequestHandlers &&\n (operation.#engine.extensionChain?.observe.length ?? 0) > 0;\n const queryHandlers = lookupResolvedExtensionHandlers(\n operation.#engine.extensionChain,\n \"query\",\n operation.#modelName,\n requestedOperation\n );\n return (\n requestNeedsObservedCoordination ||\n (queryHandlers !== undefined && queryHandlers.length > 0) ||\n operation.#prepareWriteOutcomeRegistration !== undefined\n );\n },\n prepareAdmission: (operation, phase = \"input\") => {\n operation.#preparedInput();\n if (phase === \"plan\") operation.#resolveSinglePackage();\n },\n stagePackageWriteOutcomes: (operation, outcomes) => {\n const registration = operation.#resolveWriteOutcomeRegistration();\n if (registration !== undefined) outcomes.stage(registration);\n },\n startInterception: (operation, child, outcomes, control) => {\n const requestedOperation = String(operation.#options.originalOperation);\n const handlers = lookupResolvedExtensionHandlers(\n operation.#engine.extensionChain,\n \"query\",\n operation.#modelName,\n requestedOperation\n );\n const preparedInput = operation.#preparedInput();\n const writeOutcomeRegistration =\n operation.#resolveWriteOutcomeRegistration();\n if (\n (handlers === undefined || handlers.length === 0) &&\n writeOutcomeRegistration === undefined\n ) {\n return child();\n }\n const queryContext =\n handlers === undefined || handlers.length === 0\n ? undefined\n : operation.#queryContext(\"array\", preparedInput);\n return executePreparedQuery<unknown, Record<string, unknown>>(\n queryContext,\n handlers,\n child,\n !isReadOperation(requestedOperation),\n outcomes,\n control,\n writeOutcomeRegistration\n );\n },\n executeCore: (operation, driver, notifications) =>\n operation.#execution.executeReserved(() =>\n operation.#runCoreExecution(\n driver,\n notifications?.committed,\n notifications?.mayHaveCommitted\n )\n ),\n isWrite: (operation) =>\n !isReadOperation(String(operation.#options.originalOperation)),\n hasObservation: (operation) =>\n (operation.#engine.extensionChain?.observe.length ?? 0) > 0,\n observe: (operation, child, readCompletionFacts) => {\n const observers = operation.#engine.extensionChain?.observe;\n if (observers === undefined || observers.length === 0) return child();\n return observeOperation(\n observers,\n String(operation.#options.originalOperation),\n operation.#modelName,\n child,\n readCompletionFacts,\n operation.#readInstrumentationFacts()\n );\n },\n reserveWith: (operation, driver) => {\n operation.#execution.reserveWith(driver);\n },\n executeWith: (operation, driver) => {\n const observers = operation.#engine.extensionChain?.observe;\n if (observers === undefined || observers.length === 0) {\n return operation.#execution.executeWith(driver, () =>\n operation.#runCoreExecution(driver)\n );\n }\n return operation.#execution.executeWith(driver, () =>\n observeOperation(\n observers,\n String(operation.#options.originalOperation),\n operation.#modelName,\n () => operation.#runCoreExecution(driver),\n () =>\n operation.#observationCommitCertainty === undefined\n ? undefined\n : {\n commitCertainty: operation.#observationCommitCertainty,\n },\n operation.#readInstrumentationFacts()\n )\n );\n },\n // One preparation answers both arms: the package this operation prepares\n // to synchronously publishes the one query and the parser for its one\n // result. A verb that needs the asynchronous fold publishes no single\n // query, and the array owner asks it for the package instead.\n finishResult: (operation, value) =>\n operation.#options.finishResult\n ? operation.#options.finishResult(value)\n : value,\n prepare: (operation) => operation.#resolveSinglePackage()?.queries[0],\n prepareBatch: (operation) =>\n operation.#resolveRouted().prepareBatch(operation.#context.attribution),\n parseResult: (operation, raw) => {\n const single = operation.#resolveSinglePackage();\n if (!single) {\n throw new QueryEngineError(\n `Operation '${operation.#operation}' on model '${operation.#modelName}' publishes no single driver result to parse.`\n );\n }\n return single.parseResult([raw]);\n },\n observeBatchPhase: (operation, driver, execute) =>\n observeTransactionBatchPhase(\n operation.#context.attribution,\n driver,\n execute\n ),\n } satisfies TransactionOperationOwner<PendingOperation<unknown>>);\n registerTransactionOperationOwner(\n PendingOperation.prototype,\n (value): value is PendingOperation<unknown> => #context in value,\n pendingOperationTransactionOwner\n );\n Object.freeze(PendingOperation.prototype);\n }\n\n private constructor(\n construction: typeof pendingOperationConstruction,\n engine: QueryEngine,\n model: AnyModel,\n requestedOperation: Operation | `${Operation}OrThrow`,\n args: Record<string, unknown>,\n options?: PrepareOptions,\n context?: OperationExecutionContext,\n deferredExecution?: DeferredExecution<T>,\n inputPreparation?: OperationInputPreparation,\n operationResolution?: OperationResolution,\n prepareWriteOutcomeRegistration?: PrepareWriteOutcomeRegistration\n ) {\n if (construction !== pendingOperationConstruction) {\n throw new InvalidTransactionInputError();\n }\n this.#engine = engine;\n this.#model = model;\n this.#args = args;\n this.#deferredExecution = deferredExecution;\n this.#inputPreparation = inputPreparation;\n this.#prepareWriteOutcomeRegistration = prepareWriteOutcomeRegistration;\n this.#operationResolution = operationResolution;\n // Every client lineage installs the route in `VibORM`'s constructor and\n // `bind()` forwards it (C-01); an engine built outside that lineage owns no\n // operation path at all.\n this.#route = engine.route as ClientOperationRoute;\n const isOrThrow = requestedOperation.endsWith(OR_THROW_SUFFIX);\n this.#operation = isOrThrow\n ? (requestedOperation.slice(0, -OR_THROW_SUFFIX.length) as Operation)\n : (requestedOperation as Operation);\n this.#modelName = model[\"~\"].names.ts ?? \"unknown\";\n this.#execution = new PendingExecution<T>(this.#modelName, this.#operation);\n this.#options = Object.freeze({\n ...options,\n throwIfNotFound: isOrThrow || options?.throwIfNotFound,\n originalOperation: options?.originalOperation ?? requestedOperation,\n });\n this.#context =\n context ??\n createPendingOperationContext(\n this.#modelName,\n this.#operation,\n engine.clientId,\n engine.scopeId,\n engine.extensionChain\n );\n Object.freeze(this);\n }\n\n /**\n * Resolve client request preparation once, caching both values and throws.\n * The operation's controls leave its arguments and are admitted first, so\n * the record is settled with the arguments and no request handler sees one.\n */\n #resolveArgs(): Record<string, unknown> {\n const preparation = this.#inputPreparation;\n if (preparation === undefined) return this.#args;\n if (preparation.status === \"success\" && preparation.args) {\n return preparation.args;\n }\n if (preparation.status === \"failure\") throw preparation.error;\n\n try {\n const placed = lookupPlacedControls(\n this.#engine.extensionChain,\n this.#modelName,\n String(this.#options.originalOperation)\n );\n const admission =\n placed.length === 0\n ? undefined\n : admitControls(\n this.#modelName,\n this.#operation,\n this.#args,\n placed,\n this.#engine.bound\n );\n const args = preparation.prepare(\n admission?.args ?? this.#args,\n admission?.controls\n );\n preparation.args = args;\n preparation.controls = admission?.controls;\n preparation.status = \"success\";\n return args;\n } catch (error) {\n preparation.error = error;\n preparation.status = \"failure\";\n throw error;\n }\n }\n\n /** Resolve one exact package-owned listener for every lifecycle entry point. */\n #resolveWriteOutcomeRegistration(): WriteOutcomeRegistration | undefined {\n if (this.#writeOutcomeRegistrationResolved) {\n return this.#writeOutcomeRegistration;\n }\n this.#writeOutcomeRegistration = this.#prepareWriteOutcomeRegistration?.(\n this.#context.attribution,\n this.#inputPreparation?.controls\n );\n this.#writeOutcomeRegistrationResolved = true;\n return this.#writeOutcomeRegistration;\n }\n\n /**\n * Construct (once) the route's view of this operation. It shares the\n * cache wrapper's resolution object, so a wrapped copy and its source name\n * one operation, exactly as the shipped construction above does.\n */\n #resolveRouted(): RoutedCandidateOperation {\n const shared = this.#operationResolution?.routed;\n if (shared) return shared;\n if (this.#routedInstance) return this.#routedInstance;\n // The model proxy answers every property with a callable child, so a\n // misspelled or REMOVED operation name (`createManyAndReturn`,\n // `updateManyAndReturn` — see the implicit-returning surface) reaches here\n // instead of failing as \"undefined is not a function\". Name it as what it\n // is, from the one vocabulary owner, before the route is asked for a verb\n // it has no construction path for.\n if (!ROUTED_OPERATIONS.has(this.#operation)) {\n throw new QueryEngineError(\n `Unknown operation '${this.#operation}' on model '${this.#modelName}'. Known operations: ${[...ROUTED_OPERATIONS].sort().join(\", \")}.`\n );\n }\n const args = this.#resolveArgs();\n const routed = this.#route.operation(\n this.#model,\n String(this.#options.originalOperation),\n args,\n this.#callRows()\n );\n this.#routedInstance = routed;\n if (this.#operationResolution) {\n this.#operationResolution.routed = routed;\n }\n return routed;\n }\n\n /** The row facts this call's admitted controls resolve to, if any. */\n #callRows() {\n const binding = this.#engine.extensionChain?.callRows;\n return (\n binding &&\n callRows(binding, this.#modelName, this.#inputPreparation?.controls)\n );\n }\n\n /**\n * The ONE prepared package this operation compiles to when it compiles to\n * exactly one driver query — every read. The route prepares it once and both\n * array-owner arms read it: the query `prepare()` publishes and the parser\n * `parseResult()` applies come from that single preparation, so a member's\n * statement and its decoder cannot describe different queries.\n */\n #resolveSinglePackage(): PreparedBatchOperation<unknown> | undefined {\n if (this.#singlePackageResolved) return this.#singlePackage;\n const prepared = this.#resolveRouted().prepareSingle(\n this.#context.attribution\n );\n this.#singlePackage = prepared?.queries.length === 1 ? prepared : undefined;\n this.#singlePackageResolved = true;\n return this.#singlePackage;\n }\n\n /**\n * The payload this operation runs: the prepared operation's ONE admission.\n * Resolving it settles request preparation and admits the operation.\n */\n #preparedInput(): Record<string, unknown> {\n return this.#resolveRouted().preparedArgs;\n }\n\n /**\n * The prepared facts one query handler chain inspects. Its `input` is\n * snapshotted at the first read, once for the whole chain: the prepared\n * payload is the admission's own and nothing writes it after admission, so\n * a later snapshot says what an eager one would, and a chain that never\n * reads it never copies it.\n */\n #queryContext(\n mode: QueryInterceptionMode,\n preparedInput: Record<string, unknown>\n ): PreparedModelQueryContext<Record<string, unknown>> {\n const controls = this.#inputPreparation?.controls;\n let input: Readonly<Record<string, unknown>> | undefined;\n return Object.freeze({\n mode,\n kind: \"model\" as const,\n model: this.#modelName,\n operation: String(this.#options.originalOperation),\n get input() {\n input ??= snapshotQueryInput(preparedInput);\n return input;\n },\n ...(controls === undefined ? {} : { controls }),\n });\n }\n\n /** The detached cache representation of this read, from its result owner. */\n #cacheResultCodec(): CacheResultCodec {\n return this.#resolveRouted().cacheResultCodec();\n }\n\n #getPromise(): Promise<T> {\n return this.#execution.executeDefault(() => {\n const observers = this.#engine.extensionChain?.observe;\n if (observers === undefined || observers.length === 0) {\n return this.#finished(this.#runExecution());\n }\n return observeOperation(\n observers,\n String(this.#options.originalOperation),\n this.#modelName,\n () => this.#finished(this.#runExecution()),\n () =>\n this.#observationCommitCertainty === undefined\n ? undefined\n : { commitCertainty: this.#observationCommitCertainty },\n this.#readInstrumentationFacts()\n );\n });\n }\n\n /** The value its caller receives: the client's last step applied, if any. */\n #finished(value: Promise<T>): Promise<T> {\n const finish = this.#options.finishResult;\n return finish ? value.then((result) => finish(result) as T) : value;\n }\n\n #readInstrumentationFacts() {\n return createPendingOperationInstrumentationFacts(\n this.#engine.driver,\n this.#context.attribution,\n this.#modelName,\n String(this.#options.originalOperation),\n String(this.#operation),\n this.#model[\"~\"].names.sql ?? this.#modelName,\n isCacheManagedExecution(this.#options)\n );\n }\n\n #runExecution(\n driverOverride?: AnyDriver,\n committedWriteSegment?: CommittedWriteSegmentNotification,\n writeMayBeVisible?: WriteMayBeVisibleNotification\n ): Promise<T> {\n return withOperationErrorContext(this.#context.attribution, () =>\n this.#runAttributedExecution(\n driverOverride,\n committedWriteSegment,\n writeMayBeVisible\n )\n );\n }\n\n #runAttributedExecution(\n driverOverride?: AnyDriver,\n committedWriteSegment?: CommittedWriteSegmentNotification,\n writeMayBeVisible?: WriteMayBeVisibleNotification\n ): Promise<T> {\n const observerCommitted = this.#observationNotification(\"committed\");\n const observerMayHaveCommitted =\n this.#observationNotification(\"may-have-committed\");\n const requestedOperation = String(this.#options.originalOperation);\n const handlers = lookupResolvedExtensionHandlers(\n this.#engine.extensionChain,\n \"query\",\n this.#modelName,\n requestedOperation\n );\n if (\n (handlers === undefined || handlers.length === 0) &&\n this.#prepareWriteOutcomeRegistration === undefined\n ) {\n return this.#runCoreExecution(\n driverOverride,\n combineWriteNotifications(committedWriteSegment, observerCommitted),\n combineWriteNotifications(writeMayBeVisible, observerMayHaveCommitted)\n );\n }\n return this.#runExtendedExecution(\n handlers,\n requestedOperation,\n observerCommitted,\n observerMayHaveCommitted,\n driverOverride,\n committedWriteSegment,\n writeMayBeVisible\n );\n }\n\n /** Query extensions and write-outcome registration, out of line. */\n #runExtendedExecution(\n handlers: ReturnType<typeof lookupResolvedExtensionHandlers>,\n requestedOperation: string,\n observerCommitted: (() => Promise<void>) | undefined,\n observerMayHaveCommitted: (() => Promise<void>) | undefined,\n driverOverride?: AnyDriver,\n committedWriteSegment?: CommittedWriteSegmentNotification,\n writeMayBeVisible?: WriteMayBeVisibleNotification\n ): Promise<T> {\n let preparedInput: Record<string, unknown>;\n try {\n preparedInput = this.#preparedInput();\n } catch (error) {\n return Promise.reject(error);\n }\n const writeOutcomeRegistration = this.#resolveWriteOutcomeRegistration();\n if (\n (handlers === undefined || handlers.length === 0) &&\n writeOutcomeRegistration === undefined\n ) {\n return this.#runCoreExecution(\n driverOverride,\n combineWriteNotifications(committedWriteSegment, observerCommitted),\n combineWriteNotifications(writeMayBeVisible, observerMayHaveCommitted)\n );\n }\n const context =\n handlers === undefined || handlers.length === 0\n ? undefined\n : this.#queryContext(\n this.#engine.transactionWriteOutcomes ? \"transaction\" : \"direct\",\n preparedInput\n );\n return executePreparedQuery<T, Record<string, unknown>>(\n context,\n handlers,\n (notifications) =>\n this.#runCoreExecution(\n driverOverride,\n combineWriteNotifications(\n committedWriteSegment,\n combineWriteNotifications(\n notifications?.committed,\n observerCommitted\n )\n ),\n combineWriteNotifications(\n writeMayBeVisible,\n combineWriteNotifications(\n notifications?.mayHaveCommitted,\n observerMayHaveCommitted\n )\n )\n ),\n !isReadOperation(requestedOperation),\n this.#engine.transactionWriteOutcomes,\n undefined,\n writeOutcomeRegistration\n );\n }\n\n #observationNotification(\n certainty: \"committed\" | \"may-have-committed\"\n ): (() => Promise<void>) | undefined {\n if (\n this.#engine.transactionWriteOutcomes !== undefined ||\n (this.#engine.extensionChain?.observe.length ?? 0) === 0\n ) {\n return undefined;\n }\n return async () => {\n if (\n certainty === \"committed\" ||\n this.#observationCommitCertainty === undefined\n ) {\n this.#observationCommitCertainty = certainty;\n }\n };\n }\n\n #runCoreExecution(\n driverOverride?: AnyDriver,\n committedWriteSegment?: CommittedWriteSegmentNotification,\n writeMayBeVisible?: WriteMayBeVisibleNotification\n ): Promise<T> {\n if (this.#deferredExecution) {\n return this.#deferredExecution(\n driverOverride,\n committedWriteSegment,\n writeMayBeVisible\n );\n }\n return this.#run(driverOverride, committedWriteSegment, writeMayBeVisible);\n }\n\n /**\n * Run this operation through the route. The driver an existing transaction or\n * array owner supplied stays exactly the driver it supplied; this owner opens\n * and closes no scope of its own, and retries nothing here. The engine's four\n * bounded recoveries live inside the route (`raptor3/AGENTS.md`, \"Which\n * recovery REPLAYS and which RE-PLANS\"); one of them reads `meta.raceable`\n * off the failure to decide whether a premise may be answered by a second\n * attempt.\n */\n #run(\n driverOverride?: AnyDriver,\n committedWriteSegment?: CommittedWriteSegmentNotification,\n writeMayBeVisible?: WriteMayBeVisibleNotification\n ): Promise<T> {\n let routed: RoutedCandidateOperation;\n try {\n routed = this.#resolveRouted();\n } catch (error) {\n return Promise.reject(error);\n }\n const run = () =>\n routed.execute<T>({\n committedWriteSegment,\n context: this.#context.attribution,\n driverOverride,\n engineDriver: this.#engine.driver,\n isWrite: !isReadOperation(String(this.#options.originalOperation)),\n writeMayBeVisible,\n });\n // Below every per-call lifecycle step, outside any borrowed scope: a\n // `findUnique` may share one read with the calls of the same tick.\n if (this.#operation === \"findUnique\" && driverOverride === undefined) {\n const batched = batchFindUnique({\n engine: this.#engine,\n model: this.#model,\n requested: String(this.#options.originalOperation),\n args: this.#resolveArgs(),\n controls: this.#inputPreparation?.controls,\n rows: () => this.#callRows(),\n routed,\n context: this.#context.attribution,\n run,\n });\n if (batched !== undefined) return batched as Promise<T>;\n }\n return run();\n }\n\n getArgs(): Record<string, unknown> {\n return this.#args;\n }\n\n /**\n * The payload a cache entry is keyed on: the VALIDATED one, never the\n * caller's.\n *\n * A raw payload may carry an operand callback, and a function has no stable\n * serialization — keying on it would either throw or, worse, key two\n * equivalent calls differently. Validation is what turns the callback into the\n * field reference or fragment it returned, so keying waits for it. That makes\n * a cached read resolve its operation (validate, build SQL) before it can look\n * in the cache, where it previously did so only on a miss; the price buys a\n * key that describes the query that will actually run.\n *\n * Fails loudly rather than falling back to the raw payload: only the read\n * families are cacheable. Routed writes also carry their canonical validated\n * payload for request and query inspection, but this cache-only seam never\n * publishes it; scalar and record-series writes share the same refusal.\n */\n cacheKeyArgs(): Record<string, unknown> {\n const validated = this.#cacheKeyPayload();\n if (!validated) {\n throw new QueryEngineError(\n `Operation '${this.#operation}' on model '${this.#modelName}' exposes no validated payload to key a cache entry on.`\n );\n }\n return validated;\n }\n\n /** The read payload a cache entry is keyed on, from its admitting owner. */\n #cacheKeyPayload(): Record<string, unknown> | undefined {\n if (!isReadOperation(this.#operation)) return undefined;\n return this.#resolveRouted().preparedArgs;\n }\n\n /**\n * The one SQL statement this operation compiles to, or `undefined` when it\n * does not compile to exactly one (backs {@link QueryEngine.build}).\n *\n * Every read compiles to one statement and publishes it, from the prepared\n * read the execution itself runs — there is no second lowering here. A write\n * answers `undefined`: the engine's only write fold is the asynchronous\n * `prepareBatch()`, which publishes driver-prepared queries rather than an\n * `Sql`, and this accessor is synchronous.\n */\n buildStatement(): Sql | undefined {\n return this.#resolveRouted().buildStatement();\n }\n\n #wrapExecution(wrapper: PendingCacheExecution<T>): PendingOperation<T> {\n const operationResolution =\n this.#operationResolution ??\n (this.#operationResolution = { routed: this.#routedInstance });\n const deferredExecution: DeferredExecution<T> = (\n driverOverride,\n outerCommittedWriteSegment,\n outerWriteMayBeVisible\n ) =>\n wrapper(\n (driver, committedWriteSegment, writeMayBeVisible) =>\n this.#runCoreExecution(\n driver ?? driverOverride,\n combineWriteNotifications(\n committedWriteSegment,\n outerCommittedWriteSegment\n ),\n combineWriteNotifications(writeMayBeVisible, outerWriteMayBeVisible)\n ),\n driverOverride\n );\n return new PendingOperation(\n pendingOperationConstruction,\n this.#engine,\n this.#model,\n this.#operation,\n this.#args,\n this.#options,\n this.#context,\n deferredExecution,\n this.#inputPreparation,\n operationResolution,\n this.#prepareWriteOutcomeRegistration\n );\n }\n\n then<TResult1 = T, TResult2 = never>(\n onfulfilled?: ((value: T) => TResult1 | PromiseLike<TResult1>) | null,\n onrejected?: ((reason: unknown) => TResult2 | PromiseLike<TResult2>) | null\n ): Promise<TResult1 | TResult2> {\n return this.#getPromise().then(onfulfilled, onrejected);\n }\n\n catch<TResult = never>(\n onrejected?: ((reason: unknown) => TResult | PromiseLike<TResult>) | null\n ): Promise<T | TResult> {\n return this.#getPromise().catch(onrejected);\n }\n\n finally(onfinally?: (() => void) | null): Promise<T> {\n return this.#getPromise().finally(onfinally);\n }\n}\n\n/** Create one genuine operation without exposing its construction identity. */\nexport function createPendingOperation<T>(\n engine: QueryEngine,\n model: AnyModel,\n operation: Operation | `${Operation}OrThrow`,\n args: Record<string, unknown>,\n options?: PrepareOptions,\n prepareInput?: PrepareOperationInput,\n prepareWriteOutcomeRegistration?: PrepareWriteOutcomeRegistration\n): PendingOperation<T> {\n return createPendingOperationFriend(\n engine,\n model,\n operation,\n args,\n options,\n prepareInput,\n prepareWriteOutcomeRegistration\n );\n}\n\n/** Place the official cache child inside arbitrary query interception. */\nexport function attachPendingCacheExecution<T>(\n operation: PendingOperation<T>,\n wrapper: PendingCacheExecution<T>\n): PendingOperation<T> {\n return attachPendingCacheExecutionFriend(operation, wrapper);\n}\n\n/** Internal cache reader; resolves the operation-owned canonical payload once. */\nexport function readPendingCacheResult(\n operation: PendingOperation<unknown>\n): PendingCacheResultAccess {\n return readPendingCacheResultFriend(operation);\n}\n\nexport function isPendingOperation<T = unknown>(\n value: unknown\n): value is PendingOperation<T> {\n return (\n value !== null &&\n typeof value === \"object\" &&\n PENDING_OPERATION_SYMBOL in value &&\n (value as Record<symbol, unknown>)[PENDING_OPERATION_SYMBOL] === true\n );\n}\n\nexport type UnwrapPendingOperation<T> =\n T extends PendingOperation<infer U> ? U : T;\n\nexport type UnwrapPendingOperations<\n T extends readonly PendingOperation<unknown>[],\n> = {\n [K in keyof T]: UnwrapPendingOperation<T[K]>;\n};\n","/**\n * SQL-only aliases that cannot collide with validated model identifiers.\n * A leading digit survives every supported provider while schema identifiers\n * must start with a letter or underscore.\n */\nexport const DISTANCE_RESULT_KEY = \"0viborm_distance\" as const;\nexport const RELATION_COUNTS_RESULT_KEY = \"0viborm_relation_counts\" as const;\nexport const EMPTY_ROW_RESULT_KEY = \"0viborm_empty_row\" as const;\n/** The `index`-th read gate of one projected row (K5), never published. */\nexport const gateResultKey = (index: number): string => `0viborm_gate:${index}`;\n/**\n * The cursor predicate's derived-table carrier, one per requested sort key.\n *\n * A nullable sort column's cursor predicate reads the cursor row's own values\n * out of a derived table, and those values need names that cannot collide with\n * a model identifier — which is this file's whole subject. It lives here, and\n * not as a literal in the engine, so a witness can assert the carrier without\n * pinning a spelling the engine is free to choose (Arnaud's D-21).\n */\nexport const CURSOR_CARRIER_PREFIX = \"0viborm_cursor_\" as const;\n/** Private envelope tag for one direct polymorphic result carrier. */\nexport const POLYMORPHIC_RESULT_STATE_KEY = \"__viborm_state\" as const;\nexport const POLYMORPHIC_RESULT_STATE_LINKED = \"linked\" as const;\nexport const POLYMORPHIC_RESULT_STATE_INVALID = \"invalid\" as const;\n/** The direct polymorphic COLLECTION carrier: one document per relation column. */\nexport const POLYMORPHIC_RESULT_STATE_COLLECTION = \"collection\" as const;\n/**\n * The collection carrier's PRIVATE arm container.\n *\n * Arms live one level down, under this key, precisely so a user variant named\n * `only`, `variants` or `__viborm_state` cannot collide with a carrier key —\n * the same hostility the public grammar owes.\n */\nexport const POLYMORPHIC_COLLECTION_ARMS_KEY = \"arms\" as const;\nexport const POLYMORPHIC_COLLECTION_MEMBERSHIP_KEY = \"membership\" as const;\n/**\n * The variant slot's INTEGRITY carrier: one count per configured member of the\n * memberships whose target row is gone (Arnaud's D-26).\n *\n * It rides the slot's own document beside the arms, so it takes this file's\n * leading-digit spelling rather than a bare word: the deleted engine could\n * afford `orphans` because it nested every arm one level down under\n * `arms`, and this engine keeps the arms at the document's top level, where a\n * bare carrier name would be reachable by a variant of the same name. A\n * validated identifier cannot start with a digit, so this one cannot collide.\n */\nexport const POLYMORPHIC_COLLECTION_ORPHANS_KEY = \"0viborm_orphans\" as const;\nexport const POLYMORPHIC_COLLECTION_ROWS_KEY = \"rows\" as const;\n\nexport type AggregateResultName = \"_count\" | \"_avg\" | \"_sum\" | \"_min\" | \"_max\";\n\nexport function getAggregateResultKey(name: AggregateResultName): string {\n return `0viborm_aggregate:${name.slice(1)}`;\n}\n\nexport function getAggregateResultName(\n key: string\n): AggregateResultName | undefined {\n switch (key) {\n case \"0viborm_aggregate:count\":\n return \"_count\";\n case \"0viborm_aggregate:avg\":\n return \"_avg\";\n case \"0viborm_aggregate:sum\":\n return \"_sum\";\n case \"0viborm_aggregate:min\":\n return \"_min\";\n case \"0viborm_aggregate:max\":\n return \"_max\";\n default:\n return undefined;\n }\n}\n","import { QueryEngineError } from \"../types\";\n\n/** Normalize groupBy fields and reject duplicate output columns. */\nexport function getGroupByFields(value: unknown): string[] {\n const fields = Array.isArray(value)\n ? value.filter((field): field is string => typeof field === \"string\")\n : typeof value === \"string\"\n ? [value]\n : [];\n const uniqueFields = new Set(fields);\n if (uniqueFields.size !== fields.length) {\n throw new QueryEngineError(\n \"GroupBy operation does not allow duplicate fields in 'by'\"\n );\n }\n return fields;\n}\n","import { COUNT_RESULT_KEY } from \"@adapters/shared/result-parsing\";\nimport type { Model } from \"@schema/model\";\nimport {\n type AnyRelation,\n isVariantRelationState,\n slotMayBeEmpty,\n} from \"@schema/relation\";\nimport type { Scalar } from \"@schema/scalars\";\nimport type { ResolvedRelationIndex } from \"@schema/validation/relation-resolution\";\nimport { projectableScalarNames } from \"@validation/model/core/projection\";\nimport type { NormalizedRecurrence } from \"@validation/relations/recurrence\";\nimport { isRecord } from \"@validation/value-guards\";\nimport {\n type AggregateResultName,\n DISTANCE_RESULT_KEY,\n EMPTY_ROW_RESULT_KEY,\n getAggregateResultKey,\n RELATION_COUNTS_RESULT_KEY,\n} from \"../result-aliases\";\nimport {\n type ExpectedAggregateResultShape,\n type ExpectedPolymorphicResultShape,\n type ExpectedPolymorphicVariantShape,\n type ExpectedRelationResultShape,\n type ExpectedResultShape,\n type Operation,\n QueryEngineError,\n} from \"../types\";\nimport { getGroupByFields } from \"./groupby-fields\";\n\nconst MODEL_ROW_OPERATIONS = new Set<Operation>([\n \"findFirst\",\n \"findMany\",\n \"findUnique\",\n \"create\",\n \"createManyAndReturn\",\n \"update\",\n \"updateManyAndReturn\",\n \"delete\",\n \"deleteManyAndReturn\",\n \"upsert\",\n]);\n\n/**\n * The registered refusal for a second `_distance` in one select, stated once\n * for both result views: this schema-only shape and Raptor 3's prepared\n * projection (`raptor3/shared/query.ts`) raise it.\n */\nexport const DISTANCE_SELECTED_TWICE =\n \"Distance select supports only one _distance field per select.\";\n\n/**\n * The node one arm of a variant slot is read with, or `undefined` when the\n * selection leaves that arm out of the result. One rule for both result views:\n * this schema-only shape and Raptor 3's prepared projection\n * (`raptor3/shared/query.ts`).\n *\n * Only a collection's `only` narrows the arms; admission deduplicates it and\n * refuses a `variants` key outside it. A singular slot has no such key: its row\n * belongs to exactly one arm, so every arm is read and an arm the selection\n * leaves unnamed is read at its model's default projection (`true`), which\n * keeps the result union exhaustive\n * (docs/content/docs/schema/relations/polymorphic.mdx). An admitted arm is\n * `true` or a relation node; admission has no `false` arm.\n */\nexport function selectedArm(\n selection: unknown,\n many: boolean,\n variant: string\n): unknown {\n const configuration = isRecord(selection) ? selection : undefined;\n if (!many) return getOwnValue(configuration, variant) ?? true;\n const only = getOwnValue(configuration, \"only\");\n if (Array.isArray(only) && !only.includes(variant)) return undefined;\n const arms = getOwnValue(configuration, \"variants\");\n return (isRecord(arms) ? getOwnValue(arms, variant) : undefined) ?? true;\n}\n\nconst AGGREGATE_NAMES: readonly AggregateResultName[] = [\n \"_count\",\n \"_avg\",\n \"_sum\",\n \"_min\",\n \"_max\",\n];\n\nfunction getOwnValue<T>(\n record: Readonly<Record<string, T>> | undefined,\n key: string\n): T | undefined {\n return record && Object.hasOwn(record, key) ? record[key] : undefined;\n}\n\nfunction createShape(\n rawKeys: string[],\n relations = new Map<string, ExpectedRelationResultShape>(),\n aggregates = new Map<string, ExpectedAggregateResultShape>(),\n relationCounts = new Set<string>(),\n polymorphic = new Map<string, ExpectedPolymorphicResultShape>(),\n distanceScalar?: Scalar\n): ExpectedResultShape {\n if (new Set(rawKeys).size !== rawKeys.length) {\n throw new QueryEngineError(\n \"The requested result shape contains colliding output columns.\"\n );\n }\n return {\n carrier: \"rows\",\n rawKeys,\n ...(distanceScalar ? { distanceScalar } : {}),\n relations,\n polymorphic,\n aggregates,\n relationCounts,\n };\n}\n\nfunction selectedEntries(value: unknown): [string, unknown][] {\n if (!isRecord(value)) return [];\n return Object.entries(value).filter(\n ([, selected]) => selected !== false && selected !== undefined\n );\n}\n\nfunction getNestedSelection(value: unknown): Record<string, unknown> {\n if (!isRecord(value)) return {};\n const nested: Record<string, unknown> = {};\n const select = getOwnValue(value, \"select\");\n const include = getOwnValue(value, \"include\");\n if (isRecord(select)) nested.select = select;\n if (isRecord(include)) nested.include = include;\n return nested;\n}\n\nfunction buildModelShape(\n model: Model<any>,\n args: Record<string, unknown>,\n index: ResolvedRelationIndex\n): ExpectedResultShape {\n const rawKeys: string[] = [];\n const relations = new Map<string, ExpectedRelationResultShape>();\n const polymorphic = new Map<string, ExpectedPolymorphicResultShape>();\n const scalars: Record<string, Scalar> = model[\"~\"].state.scalars;\n const modelRelations = model[\"~\"].state.relations;\n const selectValue = getOwnValue(args, \"select\");\n const includeValue = getOwnValue(args, \"include\");\n const select = isRecord(selectValue) ? selectValue : undefined;\n const include = isRecord(includeValue) ? includeValue : undefined;\n let hasDistance = false;\n let distanceScalar: Scalar | undefined;\n\n if (select) {\n for (const [fieldName, value] of Object.entries(select)) {\n const scalar: Scalar | undefined = getOwnValue(scalars, fieldName);\n if (!scalar) continue;\n if (value === true) {\n rawKeys.push(fieldName);\n continue;\n }\n if (isRecord(value) && Object.hasOwn(value, \"_distance\")) {\n if (hasDistance) {\n throw new QueryEngineError(DISTANCE_SELECTED_TWICE);\n }\n hasDistance = true;\n distanceScalar = scalar;\n rawKeys.push(DISTANCE_RESULT_KEY);\n }\n }\n } else {\n for (const fieldName of projectableScalarNames(model)) {\n rawKeys.push(fieldName);\n }\n }\n\n addSelectedRelations(\n model,\n modelRelations,\n select,\n rawKeys,\n relations,\n index\n );\n addSelectedPolymorphicRelations(model, select, rawKeys, polymorphic, index);\n\n addSelectedRelations(\n model,\n modelRelations,\n include,\n rawKeys,\n relations,\n index\n );\n addSelectedPolymorphicRelations(model, include, rawKeys, polymorphic, index);\n const relationCountSelections = [\n getOwnValue(select, \"_count\"),\n getOwnValue(include, \"_count\"),\n ];\n const relationCounts = new Set<string>();\n for (const countSelection of relationCountSelections) {\n if (!isRecord(countSelection)) continue;\n const countSelect = getOwnValue(countSelection, \"select\");\n if (!isRecord(countSelect)) continue;\n for (const [relationName] of selectedEntries(countSelect)) {\n const relation: AnyRelation | undefined = getOwnValue(\n modelRelations,\n relationName\n );\n if (!relation) continue;\n // ONE map, one rule: a variant COLLECTION joins the count surface\n // (plan §7.4); a variant SINGULAR slot has no collection to count, and\n // its `countFilter` family is a named refusal for the same reason.\n const state = relation[\"~\"].state;\n if (isVariantRelationState(state) && state.cardinality !== \"many\") {\n continue;\n }\n relationCounts.add(relationName);\n }\n }\n\n if (relationCounts.size > 0) {\n rawKeys.push(RELATION_COUNTS_RESULT_KEY);\n }\n\n // A written `select` that keeps nothing never arrives: admission refuses it.\n if (rawKeys.length === 0) rawKeys.push(EMPTY_ROW_RESULT_KEY);\n\n return createShape(\n rawKeys,\n relations,\n new Map(),\n relationCounts,\n polymorphic,\n distanceScalar\n );\n}\n\n/**\n * The recurrence admission normalized onto this relation node. Admission\n * (`validation/relations/recurrence.ts`) is its only producer, so the admitted\n * value is read, never re-parsed; a node without `recurse` answers `undefined`.\n */\nfunction admittedRecurrence(value: unknown): NormalizedRecurrence | undefined {\n if (!isRecord(value)) return undefined;\n return getOwnValue(value, \"recurse\") as NormalizedRecurrence | undefined;\n}\n\nfunction addSelectedRelations(\n model: Model<any>,\n modelRelations: Model<any>[\"~\"][\"state\"][\"relations\"],\n selection: Record<string, unknown> | undefined,\n rawKeys: string[],\n relations: Map<string, ExpectedRelationResultShape>,\n index: ResolvedRelationIndex\n): void {\n for (const [relationName, value] of selectedEntries(selection)) {\n const relation: AnyRelation | undefined = getOwnValue(\n modelRelations,\n relationName\n );\n // ONE relation map, split here by TARGET KIND: a variant slot produces a\n // tagged carrier, which the polymorphic pass below shapes instead.\n if (!relation || isVariantRelationState(relation[\"~\"].state)) continue;\n const targetModel = relation[\"~\"].settleTarget() as Model<any>;\n rawKeys.push(relationName);\n const shape = buildModelShape(\n targetModel,\n getNestedSelection(value),\n index\n );\n const resolved = index.get(model)?.get(relationName);\n const recurrence = admittedRecurrence(value);\n relations.set(relationName, {\n model: targetModel,\n shape,\n cardinality: relation[\"~\"].state.cardinality,\n optional: resolved !== undefined && slotMayBeEmpty(resolved),\n ...(recurrence ? { recurrence } : {}),\n });\n }\n}\n\n/**\n * The expected shape of one polymorphic projection. It records exactly the arms\n * {@link selectedArm} reads, each with the node it reads it with.\n */\nfunction addSelectedPolymorphicRelations(\n model: Model<any>,\n selection: Record<string, unknown> | undefined,\n rawKeys: string[],\n polymorphic: Map<string, ExpectedPolymorphicResultShape>,\n index: ResolvedRelationIndex\n): void {\n const modelRelations = model[\"~\"].state.relations;\n for (const [relationName, value] of selectedEntries(selection)) {\n const relation: AnyRelation | undefined = getOwnValue(\n modelRelations,\n relationName\n );\n if (!relation) continue;\n const state = relation[\"~\"].state;\n if (!isVariantRelationState(state)) continue;\n\n const many = state.cardinality === \"many\";\n const variants = new Map<string, ExpectedPolymorphicVariantShape>();\n for (const publicType of Object.keys(state.target.entries)) {\n const arm = selectedArm(value, many, publicType);\n if (arm === undefined) continue;\n const targetModel = relation[\"~\"].settleTarget(publicType) as Model<any>;\n variants.set(publicType, {\n model: targetModel,\n shape: buildModelShape(targetModel, getNestedSelection(arm), index),\n });\n }\n\n rawKeys.push(relationName);\n const resolved = index.get(model)?.get(relationName);\n polymorphic.set(relationName, {\n // CARDINALITY is the declaration's own fact — the slot the factory was\n // spelled with. EMPTINESS is not: it is the resolved edge's answer, which\n // for a row carrier IS the nullability of its private `(type, id)` pair\n // (§8.4).\n cardinality: state.cardinality,\n optional: resolved !== undefined && slotMayBeEmpty(resolved),\n variants,\n });\n }\n}\n\nfunction buildAggregateShape(\n args: Record<string, unknown>,\n groupedFields: readonly string[] = []\n): ExpectedResultShape {\n const rawKeys = [...groupedFields];\n const selectedOutputKeys = new Set(groupedFields);\n const aggregates = new Map<string, ExpectedAggregateResultShape>();\n\n for (const aggregateName of AGGREGATE_NAMES) {\n const spec = getOwnValue(args, aggregateName);\n if (spec === undefined || spec === false) continue;\n\n let fields: ReadonlySet<string> | undefined;\n if (!(aggregateName === \"_count\" && spec === true)) {\n const entries = selectedEntries(spec);\n if (entries.length === 0) continue;\n fields = new Set(entries.map(([fieldName]) => fieldName));\n }\n\n if (selectedOutputKeys.has(aggregateName)) {\n throw new QueryEngineError(\n `GroupBy cannot return both grouped scalar '${aggregateName}' and aggregate '${aggregateName}' in one result.`\n );\n }\n\n const rawKey = getAggregateResultKey(aggregateName);\n rawKeys.push(rawKey);\n selectedOutputKeys.add(aggregateName);\n aggregates.set(rawKey, {\n ...(fields ? { fields } : {}),\n });\n }\n\n return createShape(rawKeys, new Map(), aggregates);\n}\n\nfunction buildCountShape(args: Record<string, unknown>): ExpectedResultShape {\n const fields = selectedEntries(getOwnValue(args, \"select\")).map(\n ([fieldName]) => fieldName\n );\n return {\n ...createShape(fields.length === 0 ? [COUNT_RESULT_KEY] : fields),\n carrier: \"count\",\n };\n}\n\nexport function buildExpectedResultShape(\n model: Model<any>,\n operation: Operation,\n args: Record<string, unknown>,\n relations: ResolvedRelationIndex\n): ExpectedResultShape | undefined {\n if (operation === \"count\") return buildCountShape(args);\n if (operation === \"exist\") {\n return {\n ...createShape([COUNT_RESULT_KEY]),\n carrier: \"existence\",\n };\n }\n if (operation === \"aggregate\") return buildAggregateShape(args);\n if (operation === \"groupBy\") {\n const groupedFields = getGroupByFields(getOwnValue(args, \"by\"));\n return buildAggregateShape(args, groupedFields);\n }\n if (MODEL_ROW_OPERATIONS.has(operation)) {\n return buildModelShape(model, args, relations);\n }\n return undefined;\n}\n"],"mappings":"g9BAuLA,MAAM,EAA4B,IAAI,QAChC,EAAsB,IAAI,QAgBhC,SAAgB,qBACd,EACA,EACA,EACA,EACA,EACA,EACA,EACiB,CAyBjB,OAvBG,IAAY,IAAA,IACX,IAAiB,IAAA,IACjB,EAAa,S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ACA,EACiC,CACjC,GAAI,IAAc,QAAS,OAAO,gBAAgB,EAAK,CACvD,GAAI,IAAc,QAChB,MAAO,CACL,GAAG,YAAY,CAAC,EAAiB,CAAC,CAClC,QAAS,YACV,CAEH,GAAI,IAAc,YAAa,OAAO,oBAAoB,EAAK,CAC/D,GAAI,IAAc,UAEhB,OAAO,oBAAoB,EADL,iBAAiB,YAAY,EAAM,KAAK,CAAC,CAChB,CAEjD,GAAI,GAAqB,IAAI,EAAU,CACrC,OAAO,gBAAgB,EAAO,EAAM,EAAU"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"sqlite-adapter-CoDeF2h2.mjs","names":["sql","#createBatchRefs","#assemble"],"sources":["../src/adapters/databases/sqlite/sqlite-adapter.ts"],"sourcesContent":["import { UnsupportedOperationError, unsupportedVector } from \"@errors\";\nimport { sqliteDateTimePhysicalForm } from \"@schema/scalars/datetime/physical\";\nimport type { NativeTypeDeclaration } from \"@schema/scalars/native-types\";\nimport { idStorageOf } from \"@schema/scalars/string/id-domain\";\nimport { Sql, sql } from \"@sql\";\nimport { encodePhysicalDateTime } from \"@validation/primitives/datetime-physical-codec\";\nimport {\n type DecimalDescriptor,\n encodePhysicalDecimal,\n} from \"@validation/primitives/decimal-codec\";\nimport type { IdRepresentation } from \"@validation/primitives/id-codec\";\nimport { createIdentifierQuoter } from \"../../../sql/identifiers\";\nimport type {\n ArithmeticTarget,\n BatchReferenceSqlAdapter,\n} from \"../../adapter-core-types\";\nimport { installAdapterInternals } from \"../../adapter-internals\";\nimport type { QueryParts } from \"../../adapter-query-parts\";\nimport {\n type AdapterResultParser,\n passThroughParseResult,\n} from \"../../adapter-result-parser\";\nimport { sqliteConstraintIdentities } from \"../../constraint-identity\";\nimport {\n type DatabaseAdapter,\n type GeoPointSql,\n installGeoPointSql,\n} from \"../../database-adapter\";\nimport {\n BATCH_REFS_TABLE,\n createOnConflictBatchRefs,\n} from \"../../shared/batch-refs\";\nimport {\n type ExactIntegerArithmetic,\n halfEvenQuotient,\n scaleFactorSql,\n signedNumerator,\n} from \"../../shared/decimal-arithmetic\";\nimport { createGeoPointCoordinatePredicates } from \"../../shared/geo-point\";\nimport {\n assembleDistinctOnEmulation,\n assembleSelectQuery,\n} from \"../../shared/select-assembly\";\nimport {\n createAggregateFunctions,\n createCastExpression,\n createCommonExpressions,\n createComparisonOperators,\n createCoreJoins,\n createCteBuilders,\n createDirectionOrderBy,\n createExistenceOperators,\n createIdentifiers,\n createInsertStatement,\n createLogicalOperators,\n createMembershipOperators,\n createMutationCommands,\n createNullOperators,\n createNumericSetOperations,\n createOnConflictBuilders,\n createRangeOperators,\n createRawSql,\n createRelationFilters,\n createSetOperations,\n createStandardClauses,\n createStandardLiterals,\n createSubqueries,\n decimalCoefficientPrecision,\n escapeGlobLiteral,\n rowValues,\n stringifyJson,\n} from \"../../shared/standard-sql\";\nimport { SQLITE_BINARY64_FORMAT } from \"./storage/json-number\";\n\nconst quoteIdent = createIdentifierQuoter('\"');\n\n/**\n * Every SQLite decimal expression is signed-int64 integer arithmetic on the\n * stored unscaled coefficient, so `/` IS truncating integer division and `%`\n * carries the dividend's sign. Neither is true once an operand becomes REAL or\n * TEXT, which is why every operand below arrives as an INTEGER column, an\n * integer literal, or a `CAST(... AS INTEGER)` bind.\n */\nconst SQLITE_INTEGERS: ExactIntegerArithmetic = {\n quotient: (n: Sql, d: Sql): Sql => sql`(${n} / ${d})`,\n remainder: (n: Sql, d: Sql): Sql => sql`(${n} % ${d})`,\n};\n\nconst SQLITE_INT64_NEGATIVE_MAGNITUDE = \"9223372036854775808\";\nconst SQLITE_INT64_MAX = \"9223372036854775807\";\n\n/** Admit the exact TEXT-to-INTEGER cast domain, including its 19-digit edges. */\nfunction sqliteIntegerPrecision(coefficient: string): number | undefined {\n const precision = decimalCoefficientPrecision(coefficient);\n if (precision < 19) return precision;\n if (precision > 19) return undefined;\n const isAdmitted = coefficient.startsWith(\"-\")\n ? coefficient.slice(1) <= SQLITE_INT64_NEGATIVE_MAGNITUDE\n : coefficient <= SQLITE_INT64_MAX;\n return isAdmitted ? precision : undefined;\n}\n\n/**\n * The widest intermediate the guarded arms will evaluate: 10^18.\n *\n * SQLite does not raise on an integer multiply that overflows — it converts the\n * expression to REAL, which is the one representation an exact decimal must\n * never touch. So the arms are GUARDED: the guard compares magnitudes by\n * DIVISION (`|x| <= LIMIT / |y|`, exact for integers) instead of computing the\n * product it is protecting, and a `CASE` evaluates only the branch it selects.\n *\n * 10^18 is not arbitrary, and it is not independent. `precision + scale <= 18`\n * is SQLite's declared field limit (plan 3.1), ENFORCED once when the schema is\n * bound (`schema/scalars/decimal/provider-limits.ts`), so every mathematically\n * in-range result has `|x * y| <= 10^(p+s) <= 10^18`: the guard never rejects\n * an answer that fits the field, and int64 keeps a factor of nine in reserve\n * for the `+/- 1` step and the `d - |r|` tie test.\n *\n * THE COUPLING IS LOAD-BEARING, in both directions. This constant is flat where\n * the per-descriptor bound would be `B = scale === 0 ? M : M*F + F/2 - 1`, and\n * that is only equivalent because no descriptor past `p + s = 18` can reach it:\n * a product in `(B, 10^18]` is admitted here and then refused by the range\n * CHECK instead of by the sentinel — the same loud, atomic failure by the other\n * mechanism. Remove the bind limit and the flat guard stops being a bound on\n * the FIELD at all, which is exactly what {@link overflowCoefficient} depends\n * on below.\n */\nconst SQLITE_INTERMEDIATE_LIMIT = sql.raw(\"1000000000000000000\");\n\n/**\n * The coefficient an unsafe or out-of-domain arithmetic result becomes: 10^p,\n * the smallest integer OUTSIDE a `precision: p` field's declared range.\n *\n * The DDL's range check refuses it, so the statement fails atomically and\n * nothing is written — which is the contract for an overflow that is only\n * knowable mid-statement.\n *\n * THE CLAMP DEPENDS ON THE BIND LIMIT, and is only correct because of it. At 19\n * digits and beyond, `10^p` is a REAL to SQLite's own parser, so the sentinel\n * would stop being an integer the CHECK can refuse — and `min(p, 18)` would put\n * it INSIDE the range of a `precision >= 19` column, which is a silently\n * written wrong value rather than a failure. No such column exists: plan 3.1's\n * `precision <= 18 && precision + scale <= 18` is proven once at schema bind\n * (`schema/scalars/decimal/provider-limits.ts`), before any I/O, so\n * `min(p, 18)` is `p` for every descriptor that ever reaches here. The clamp is\n * what an unreachable arm does when it is reached anyway, not a policy — and it\n * is why the bind limit is load-bearing rather than ergonomic.\n */\nconst overflowCoefficient = (descriptor: DecimalDescriptor): Sql =>\n sql.raw(`1${\"0\".repeat(Math.min(descriptor.precision, 18))}`);\n\n/**\n * `column = <exact coefficient arithmetic>`, or the constraint-breaking\n * coefficient when the intermediate would leave int64.\n *\n * A NULL column is safe by definition and takes the guarded arm, where every\n * operator is null-strict and the assignment stays NULL.\n */\nconst guardedCoefficientAssignment = (\n column: Sql,\n safe: Sql,\n value: Sql,\n descriptor: DecimalDescriptor\n): Sql =>\n sql`${column} = CASE WHEN ${column} IS NULL OR ${safe} THEN ${value} ELSE ${overflowCoefficient(descriptor)} END`;\n\nconst JSON_ARRAY_INDEX_SEGMENT = /^\\d+$/;\nconst JSON_UNADDRESSABLE_LABEL = /[\"\\\\]/;\n\n// Each path segment binds as its own single-leg JSONPath ('$[N]' for\n// array indices, '$.\"seg\"' otherwise) chained with -> , so segments can\n// never splice extra legs into the path. SQLite's path grammar has no\n// escape syntax inside quoted labels, so the portable query contract rejects\n// keys containing \" or \\ before adapter execution. This throw is defensive.\nconst jsonPathLeg = (segment: string): string => {\n if (JSON_ARRAY_INDEX_SEGMENT.test(segment)) {\n return `$[${segment}]`;\n }\n if (JSON_UNADDRESSABLE_LABEL.test(segment)) {\n throw new Error(\n 'SQLite JSON path segments containing \" or \\\\ must be rejected by the portable query contract.'\n );\n }\n return `$.\"${segment}\"`;\n};\n\n/** Chain one bound `-> '$leg'` per path segment ('$' alone = document root). */\nconst jsonExtract = (column: Sql, path: string[]): Sql => {\n let expr = sql`${column} -> '$'`;\n for (const segment of path) {\n expr = sql`${expr} -> ${jsonPathLeg(segment)}`;\n }\n return expr;\n};\n\n/** Same chain, but the final leg uses `->>` so strings come back unquoted. */\nconst jsonExtractText = (column: Sql, path: string[]): Sql => {\n if (path.length === 0) {\n return sql`${column} ->> '$'`;\n }\n const legs = path.map(jsonPathLeg);\n const last = legs.pop()!;\n let expr: Sql = column;\n for (const leg of legs) {\n expr = sql`${expr} -> ${leg}`;\n }\n return sql`${expr} ->> ${last}`;\n};\n\n/**\n * Concatenate two JSON array texts by string surgery: strip `left`'s closing\n * bracket and `right`'s opening bracket. SQLite has no JSON array-concat\n * function, and json_insert('$[#]') can only append one element per pair.\n * Both sides must be canonical JSON (json() output or JSON.stringify).\n */\nconst jsonArrayConcat = (left: Sql, right: Sql): Sql =>\n sql`(CASE WHEN ${left} = '[]' THEN ${right} WHEN ${right} = '[]' THEN ${left} ELSE substr(${left}, 1, length(${left}) - 1) || ',' || substr(${right}, 2) END)`;\n\n/** The one JSON list container every SQLite list value crosses as. */\nconst sqliteJsonListValue = (values: unknown[]): Sql =>\n sql`${stringifyJson(values)}`;\n\n/** A bare operand, and a decimal operand: its coefficient read as INTEGER. */\nconst PARAMETER = [\"\", \"\"];\nconst COEFFICIENT = [\"CAST(\", \" AS INTEGER)\"];\nconst LONE_SURROGATE = /\\p{Cs}/u;\nconst PARENTHESIZED_LIST = createStandardLiterals().list;\n/**\n * The longest list kept parenthesized. Without `sqlite_stat1` SQLite sizes an\n * `IN (SELECT …)` at 25 rows and a list at its length, so up to 25 members the\n * list is planned no worse: a key list beside another indexed equality still\n * seeks the key. It is also a quarter of D1's 100-value bind budget.\n */\nconst PLANNED_LIST = 25;\n\n/**\n * One member as JSON text that `json_each` reads back as the value its own\n * parameter binds, or `undefined`. A non-integer number is not one: SQLite\n * reparses JSON text with an error in the last place for some doubles; nor is\n * a string with a lone surrogate, which a driver binds as U+FFFD.\n */\nfunction jsonMember(value: unknown): string | undefined {\n if (typeof value === \"string\")\n return LONE_SURROGATE.test(value) ? undefined : JSON.stringify(value);\n if (value instanceof Uint8Array)\n return `\"${Array.from(value, (byte) => byte.toString(16).padStart(2, \"0\")).join(\"\")}\"`;\n return typeof value === \"bigint\" ||\n typeof value === \"boolean\" ||\n Number.isSafeInteger(value)\n ? String(value)\n : undefined;\n}\n\n/**\n * engine-09: a list longer than {@link PLANNED_LIST} whose members are each one\n * parameter under one spelling — bare, or a decimal's coefficient cast — as\n * ONE parameter, a JSON array `json_each` reads back and spells per element as\n * each member was, so `IN` and `NOT IN` keep their answers, NULLs included.\n * Blobs travel as hex, read through `unhex` (SQLite 3.41). Any other list\n * keeps a parameter per member.\n */\nfunction sqliteList(members: Sql[]): Sql {\n if (members.length <= PLANNED_LIST) return PARENTHESIZED_LIST(members);\n const [first] = members;\n const spelling =\n first?.strings[0] === COEFFICIENT[0] ? COEFFICIENT : PARAMETER;\n const elements: string[] = [];\n let blobs = 0;\n for (const member of members) {\n const [head, tail, extra] = member.strings;\n const value = member.values[0];\n const element = jsonMember(value);\n if (\n element === undefined ||\n head !== spelling[0] ||\n tail !== spelling[1] ||\n extra !== undefined\n )\n return PARENTHESIZED_LIST(members);\n if (value instanceof Uint8Array) blobs++;\n elements.push(element);\n }\n // Blobs beside other values: nothing one spelling reads.\n if (blobs !== 0 && blobs !== members.length)\n return PARENTHESIZED_LIST(members);\n const read = new Sql(spelling, [\n sql.raw(blobs === 0 ? \"value\" : \"unhex(value)\"),\n ]);\n return sql`(SELECT ${read} FROM json_each(${`[${elements.join(\",\")}]`}))`;\n}\n\n/** Facts a SQLite driver states about its transport. */\nexport interface SQLiteAdapterOptions {\n /**\n * Whether the transport admits temporary objects (`CREATE TEMP TABLE`).\n * better-sqlite3, libSQL and bun:sqlite do; Cloudflare D1's authorizer\n * rejects them with `SQLITE_AUTH`, and rejects the whole batch with them.\n * Defaults to `true`.\n */\n readonly temporaryObjects?: boolean;\n /**\n * Whether the transport compiles deep expression trees. SQLite counts a\n * subquery's `WHERE` in the height of the expression that holds it, and sums\n * those heights again while it resolves names, so k nested relation filters\n * cost about k² of `SQLITE_MAX_EXPR_DEPTH`: SQLite's default (1000) admits\n * that; Cloudflare D1 compiles with 100 and refuses \"Expression tree is too\n * large\". Where it does not, each relation filter reads its rows from a\n * derived table, whose `WHERE` neither count reaches through the expression:\n * about four per level, the same plan (SQLite flattens it), one statement.\n * A conjunction of many members nests as a balanced tree where it does not,\n * as the engine already nests a disjunction: SQLite parses `a AND b AND …`\n * one level per member. A level's row domain, where the filter goes on\n * below it, is isolated the same way (`subqueries.isolated`), so a policy\n * costs its height once and not at every level (measured on D1: a\n * three-arm read policy 10 per level, failing at 9 levels; isolated, 5 per\n * level, 94 at the 15 levels admission takes).\n * Defaults to `true`.\n */\n readonly deepExpressions?: boolean;\n /**\n * Whether a statement states each relation filter body it repeats once\n * (`capabilities.sharesRelationBodies`), for a\n * transport that bounds statement text (Cloudflare D1: 100 KB). Defaults\n * to `false`.\n */\n readonly sharedRelationBodies?: boolean;\n /**\n * The most terms one compound `SELECT` may chain\n * (`capabilities.compoundSelectTerms`): Cloudflare D1 compiles SQLite with\n * 5 and refuses a sixth (\"too many terms in compound SELECT\"). Defaults to\n * SQLite's own bound, which the engine never reaches.\n */\n readonly compoundSelectTerms?: number;\n /**\n * Where bodies are shared, the relations a statement may reference before\n * its repeated walks become reaching sets and its rows join the key sets\n * they test (`capabilities.relationsPerStatement`). Absent: unbounded.\n */\n readonly relationsPerStatement?: number;\n}\n\n/**\n * The dialect's stateless SQL builders, built once per module. Each adapter\n * takes its own shallow copy of every group, so a driver that overrides one\n * hook (`driver.adapter.result.parseField = …`) changes only its own adapter,\n * as before, while a driver per request no longer rebuilds every closure.\n */\nconst SQLITE_LITERALS = {\n ...createStandardLiterals(),\n\n value: (value: unknown): Sql => {\n if (\n typeof value === \"bigint\" &&\n sqliteIntegerPrecision(String(value)) === undefined\n )\n throw new UnsupportedOperationError(\n \"SQLite bigint values must fit signed 64-bit integers.\"\n );\n return sql`${value}`;\n },\n\n // SQLite uses 1/0 for booleans\n true: (): Sql => sql.raw(\"1\"),\n\n false: (): Sql => sql.raw(\"0\"),\n\n // SQLite requires JSON values to be stringified\n json: (v: unknown): Sql => sql`${JSON.stringify(v)}`,\n\n // SQLite has no temporal type, so the field's declaration is what the column\n // physically holds and the operand has to be the same kind of value: an ISO\n // string bound against an epoch-millisecond INTEGER matches no row and,\n // written, stores text the typed read then refuses. A TEXT-declared or\n // undeclared field keeps the ISO spelling byte for byte. The string is a\n // validated ISO timestamp — the ISO boundary owns that — and every\n // four-digit public instant round-trips through the Julian-day double.\n dateTime: (iso: string, nativeType?: NativeTypeDeclaration): Sql =>\n sql`${encodePhysicalDateTime(iso, sqliteDateTimePhysicalForm(nativeType))}`,\n\n // SQLite has no exact decimal type, so a decimal column stores the UNSCALED\n // INTEGER COEFFICIENT and an operand becomes that same coefficient. Integer\n // comparison is then exact numeric comparison, and ordering, aggregation\n // and arithmetic are exact for the same reason.\n //\n // The digits bind as TEXT and `CAST(... AS INTEGER)` reads them, rather than\n // riding a JavaScript number (which rounds above 2^53) or a bigint (which\n // D1 will not bind). SQLite's TEXT-to-INTEGER cast is a decimal integer\n // parse, not a float one.\n decimal: (canonical: string, descriptor: DecimalDescriptor): Sql =>\n new Sql(COEFFICIENT, [\n encodePhysicalDecimal(canonical, descriptor, \"coefficient\"),\n ]),\n\n // Every compact domain is a `BLOB` here and takes the payload's bytes as\n // the ordinary binary parameter a blob scalar already binds; a text-stored\n // domain takes the public string unchanged.\n id: (physical: string | Uint8Array, _representation: IdRepresentation): Sql =>\n sql`${physical}`,\n\n list: sqliteList,\n};\n\nconst SQLITE_OPERATORS = {\n ...createComparisonOperators(),\n\n // Explicit ESCAPE '\\' pairs with wildcard escaping in the where-builder\n like: (column: Sql, pattern: Sql): Sql =>\n sql`${column} LIKE ${pattern} ESCAPE '\\\\'`,\n notLike: (column: Sql, pattern: Sql): Sql =>\n sql`${column} NOT LIKE ${pattern} ESCAPE '\\\\'`,\n ilike: (column: Sql, pattern: Sql): Sql =>\n sql`lower(${column}) LIKE lower(${pattern}) ESCAPE '\\\\'`,\n notIlike: (column: Sql, pattern: Sql): Sql =>\n sql`lower(${column}) NOT LIKE lower(${pattern}) ESCAPE '\\\\'`,\n containsText: (column: Sql, value: Sql): Sql =>\n sql`instr(${column}, ${value}) > 0`,\n startsWithText: (column: Sql, value: Sql): Sql =>\n sql`substr(${column}, 1, length(${value})) COLLATE BINARY = ${value}`,\n endsWithText: (column: Sql, value: Sql): Sql =>\n sql`substr(${column}, length(${column}) - length(${value}) + 1) COLLATE BINARY = ${value}`,\n // GLOB, not LIKE — and this is the one place the \"portable escaped LIKE\"\n // premise of Decision 7.3 does not survive contact with SQLite. Both of\n // SQLite's LIKE-optimization preconditions fail here: an ESCAPE clause\n // disqualifies the optimization outright, and with `case_sensitive_like`\n // off (the default, and connection-global, so not ours to flip) the\n // optimization additionally wants a NOCASE-collated index, while `push()`\n // only ever creates BINARY ones. Measured on better-sqlite3, 20k rows,\n // plain index: `col LIKE ? ESCAPE '\\'` is a SCAN — exactly what the\n // `substr` spelling above already costs — AND it answers case-insensitively,\n // which would break the case-sensitivity contract this operator holds.\n //\n // GLOB has neither problem. It compares bytes, so it is case- and\n // accent-sensitive by construction (that is what `COLLATE BINARY` buys\n // above, so nothing is lost by dropping it), and it ranges on the ordinary\n // BINARY index: the same probe plans this as a covering index SEARCH over\n // 111 rows against a 20000-row SCAN. Its wildcards are `*`/`?`/`[`, and it\n // has no ESCAPE clause, so `escapeGlobLiteral` quotes them as classes.\n startsWithPrefix: (column: Sql, value: string): Sql =>\n sql`${column} GLOB ${`${escapeGlobLiteral(value)}*`}`,\n\n // `COLLATE BINARY` names a COLLATION, not a function of the column, and\n // SQLite's ordinary index is a BINARY index — so the case-sensitive\n // spelling is already the index-usable one and there is nothing to add.\n // Byte-identical to what shipped before §10.2.\n exactTextEq: (column: Sql, value: Sql): Sql =>\n sql`${column} COLLATE BINARY = ${value}`,\n exactTextIn: (column: Sql, values: Sql): Sql =>\n sql`${column} COLLATE BINARY IN ${values}`,\n\n ...createMembershipOperators(),\n\n ...createNullOperators(),\n\n ...createRangeOperators(),\n\n // Logical (vacuous cases use SQLite's 1/0 booleans)\n ...createLogicalOperators(SQLITE_LITERALS.true, SQLITE_LITERALS.false),\n\n ...createExistenceOperators(),\n};\n\nconst SQLITE_EXPRESSIONS = {\n ...createCommonExpressions(),\n\n // SQLite lower() intentionally provides the portable ASCII-only contract.\n asciiCaseFold: (expr: Sql): Sql => sql`lower(${expr})`,\n caseSensitiveText: (expr: Sql): Sql => sql`${expr} COLLATE BINARY`,\n\n concat: (...parts: Sql[]): Sql => {\n if (parts.length === 0) return sql.raw(\"''\");\n if (parts.length === 1) return parts[0]!;\n return sql`(${sql.join(parts, \" || \")})`;\n },\n\n // SQLite has no GREATEST/LEAST; multi-arg MAX/MIN are the scalar forms\n greatest: (...exprs: Sql[]): Sql => sql`MAX(${sql.join(exprs, \", \")})`,\n least: (...exprs: Sql[]): Sql => sql`MIN(${sql.join(exprs, \", \")})`,\n\n // The expression form of `set.divide`'s integer arm, and for the same\n // reason: SQLite drivers bind JS numbers as REAL, so `x / ?` would run real\n // division. Casting the divisor to INTEGER makes it native INT/INT\n // division, truncating toward zero.\n integerDivide: (left: Sql, right: Sql): Sql =>\n sql`(${left} / CAST(${right} AS INTEGER))`,\n\n // A deferred SQLite decimal is already a captured coefficient. The\n // descriptor still travels through the common contract so no caller can\n // select this physical cast without naming the destination domain.\n decimalCast: (expr: Sql, _descriptor: DecimalDescriptor): Sql =>\n sql`CAST(${expr} AS INTEGER)`,\n\n idCast: (expr: Sql, representation: IdRepresentation): Sql =>\n representation === \"bytes\"\n ? sql`unhex(${expr})`\n : sql`CAST(${expr} AS TEXT)`,\n\n // SQLite type mappings\n cast: createCastExpression({\n text: \"TEXT\",\n integer: \"INTEGER\",\n bigint: \"INTEGER\",\n boolean: \"INTEGER\",\n numeric: \"NUMERIC\",\n }),\n\n blobToHex: (expr: Sql): Sql => sql`lower(hex(${expr}))`,\n};\n\nconst SQLITE_AGGREGATES = {\n ...createAggregateFunctions(\"9e999\"),\n\n // The average of a coefficient column IS the half-even integer quotient of\n // its exact sum by its non-null count: dividing both the sum and the count\n // of `logical x 10^s` values leaves `average x 10^s`, so no scale factor\n // appears at all. `COUNT(column)` is zero exactly when `SUM` is NULL, so\n // the null-strict operators answer NULL for an empty or all-null group and\n // the zero divisor is never reached with a value.\n decimalAvg: (column: Sql, _descriptor: DecimalDescriptor): Sql =>\n halfEvenQuotient(\n SQLITE_INTEGERS,\n sql`SUM(${column})`,\n sql`COUNT(${column})`\n ),\n\n // A SQLite decimal aggregate is an int64 `SUM` over coefficients. Exact\n // operand admission follows the signed range rather than digit count: some\n // 19-digit values fit, while the next value past either endpoint would make\n // `CAST(... AS INTEGER)` saturate. The sum itself is `integerSum`'s, exact\n // past that range.\n decimalSumOperandPrecision: sqliteIntegerPrecision,\n\n // `>>` is arithmetic, so an int64 member is exactly `(x >> 32) * 2^32` plus\n // its second part. That part stays REAL for a non-integer member, which the\n // reader refuses as it refused the plain `SUM`.\n // `low` sums non-negative 32-bit remainders: carrying its high bits into\n // `high` leaves a pair that sorts exactly as the total. `value` is that\n // total inside int64 and its nearest double outside, below -2^63 at most\n // `-2^63 - 2048`: SQLite compares an integer with a double exactly, so it\n // is exact against every int64 operand (a decimal coefficient's whole\n // domain), and a number operand past int64 is told apart from every total\n // but those that round to it.\n integerSum: (column: Sql) => {\n const high = sql`SUM(${column} >> 32)`;\n const low = sql`SUM(${column} - ((${column} >> 32) << 32))`;\n const carried = sql`(${high} + (${low} >> 32))`;\n const rest = sql`(${low} & 4294967295)`;\n const double = sql`${carried} * 4294967296.0 + ${rest}`;\n return {\n parts: [high, low] as const,\n value: sql`CASE WHEN ${carried} > 2147483647 THEN ${double} WHEN ${carried} >= -2147483648 THEN ${carried} * 4294967296 + ${rest} ELSE MIN(${double}, -9223372036854777856.0) END`,\n order: [carried, rest],\n };\n },\n};\n\n// Compare every node, including empty containers. Array indices remain part\n// of the path; object property insertion order does not. JSON numbers share\n// one domain, while booleans, strings and JSON null retain their distinct type.\nfunction sqliteJsonEquals(left: Sql, right: Sql): Sql {\n const nodes = (value: Sql) =>\n sql`SELECT fullkey, CASE WHEN type IN ('integer', 'real') THEN 'number' ELSE type END, atom FROM json_tree(${value})`;\n return sql`(CASE WHEN ${left} IS NULL OR ${right} IS NULL THEN NULL ELSE NOT EXISTS (${nodes(left)} EXCEPT ${nodes(right)}) AND NOT EXISTS (${nodes(right)} EXCEPT ${nodes(left)}) END)`;\n}\n\nconst sqliteJsonObject = (pairs: [string, Sql][]): Sql => {\n if (pairs.length === 0) return sql.raw(\"json_object()\");\n const args = pairs.flatMap(([key, value]) => [sql`${key}`, value]);\n return sql`json_object(${sql.join(args, \", \")})`;\n};\n\nconst SQLITE_JSON = {\n equals: sqliteJsonEquals,\n number: (expression: Sql): Sql =>\n sql`CASE WHEN ${expression} IS NULL THEN NULL ELSE printf(${sql.raw(`'${SQLITE_BINARY64_FORMAT}'`)}, ${expression}) END`,\n boolean: (condition: Sql): Sql =>\n sql`json(CASE WHEN ${condition} THEN 'true' ELSE 'false' END)`,\n // SQLite drops the JSON subtype across scalar-subquery boundaries. Restore it\n // before embedding the value in json_object/json_array, or an object becomes a\n // quoted JSON string inside the outer document.\n document: (expression: Sql): Sql => sql`json(${expression})`,\n\n object: sqliteJsonObject,\n\n array: (items: Sql[]): Sql => {\n if (items.length === 0) return sql.raw(\"json_array()\");\n return sql`json_array(${sql.join(items, \", \")})`;\n },\n\n emptyArray: (): Sql => sql.raw(\"json_array()\"),\n\n // `expr` carries the JSON subtype (a json_object call, or a subquery\n // column restored through `document`), so it is aggregated as JSON, not\n // quoted as a string. Over no rows json_group_array is `[]`, never NULL.\n agg: (expr: Sql): Sql => sql`json_group_array(${expr})`,\n\n objectFromColumns: sqliteJsonObject,\n\n // `->` returns the value as canonical JSON text ('\"str\"', '2', 'null'),\n // the same format json.value binds, so extracted values compare with\n // plain equality (json_extract would return native SQL values instead)\n extract: jsonExtract,\n\n // `->>` returns text with strings unquoted, for LIKE matching\n extractText: jsonExtractText,\n\n // json_type reads the chained `->` result (canonical JSON text), so it\n // sees 'integer'/'real' only for real JSON numbers; every other shape —\n // and an absent path, where `->` is NULL — falls through to NULL\n numberAtPath: (column: Sql, path: string[]): Sql =>\n sql`(CASE WHEN json_type(${jsonExtract(column, path)}) IN ('integer', 'real') THEN CAST(${jsonExtractText(column, path)} AS REAL) END)`,\n\n // COLLATE BINARY is SQLite's default for these columns; naming it keeps\n // the code-point ordering contract explicit alongside PG's COLLATE \"C\"\n stringAtPath: (column: Sql, path: string[]): Sql =>\n sql`((CASE WHEN json_type(${jsonExtract(column, path)}) = 'text' THEN ${jsonExtractText(column, path)} END) COLLATE BINARY)`,\n\n contains: (target: Sql, value: Sql): Sql =>\n sql`(json_type(${target}) = 'array' AND NOT EXISTS (SELECT 1 FROM json_each(${value}) AS required WHERE NOT EXISTS (SELECT 1 FROM json_each(${target}) AS candidate WHERE ${sqliteJsonEquals(sql`${target} -> candidate.fullkey`, sql`${value} -> required.fullkey`)})))`,\n\n lastElement: (target: Sql): Sql => sql`${target} -> '$[#-1]'`,\n\n value: (v: unknown): Sql => sql`${stringifyJson(v)}`,\n};\n\nconst SQLITE_ARRAYS = {\n // SQLite uses JSON arrays\n literal: (items: Sql[]): Sql => {\n if (items.length === 0) return sql.raw(\"json_array()\");\n return sql`json_array(${sql.join(items, \", \")})`;\n },\n\n value: sqliteJsonListValue,\n\n // Deliberately the same container, by identity: SQLite stores an enum LIST\n // as JSON like every other list, so its members are ordinary JSON strings\n // and there is no element type to spell. The `TEXT CHECK(col IN ...)`\n // describes one member.\n enumValue: sqliteJsonListValue,\n\n // Check if value exists in JSON array using json_each\n has: (column: Sql, value: Sql): Sql =>\n sql`EXISTS (SELECT 1 FROM json_each(${column}) WHERE value = ${value})`,\n\n hasEvery: (column: Sql, values: Sql): Sql =>\n sql`(SELECT COUNT(*) FROM json_each(${values}) WHERE value IN (SELECT value FROM json_each(${column}))) = json_array_length(${values})`,\n\n hasSome: (column: Sql, values: Sql): Sql =>\n sql`EXISTS (SELECT 1 FROM json_each(${column}) AS a, json_each(${values}) AS b WHERE a.value = b.value)`,\n\n isEmpty: (column: Sql): Sql =>\n sql`(json_array_length(${column}) = 0 OR ${column} IS NULL)`,\n\n // The column already stores the container as TEXT (its declared type is\n // TEXT, not JSON, precisely so the descriptor's CHECK can hold it). The\n // cast is what stops a JSON carrier from embedding it as a document and a\n // driver from handing back anything but the stored bytes.\n exactNumericProjection: (column: Sql): Sql => sql`CAST(${column} AS TEXT)`,\n\n length: (column: Sql): Sql => sql`json_array_length(${column})`,\n\n get: (column: Sql, index: Sql): Sql =>\n sql`json_extract(${column}, '$[' || ${index} || ']')`,\n\n push: (column: Sql, value: Sql): Sql =>\n sql`json_insert(${column}, '$[#]', ${value})`,\n\n set: (column: Sql, index: Sql, value: Sql): Sql =>\n sql`json_set(${column}, '$[' || ${index} || ']', ${value})`,\n};\n\nconst SQLITE_ORDER_BY = {\n ...createDirectionOrderBy(),\n nullsFirst: (column: Sql, direction: \"asc\" | \"desc\"): Sql =>\n direction === \"desc\"\n ? sql`${column} DESC NULLS FIRST`\n : sql`${column} ASC NULLS FIRST`,\n nullsLast: (column: Sql, direction: \"asc\" | \"desc\"): Sql =>\n direction === \"desc\"\n ? sql`${column} DESC NULLS LAST`\n : sql`${column} ASC NULLS LAST`,\n};\n\nconst SQLITE_SET = {\n ...createNumericSetOperations(),\n\n // `x * y / 10^s` in coefficient space, rounded half to even. The guard is\n // the multiply's own: `x * y` is the only intermediate here that can leave\n // int64, and it does so exactly when the result cannot fit the field.\n multiply: (column: Sql, by: Sql, target?: ArithmeticTarget): Sql => {\n const descriptor = target?.decimal;\n if (!descriptor) return sql`${column} = ${column} * ${by}`;\n return guardedCoefficientAssignment(\n column,\n sql`${by} = 0 OR ABS(${column}) <= ${SQLITE_INTERMEDIATE_LIMIT} / ABS(${by})`,\n halfEvenQuotient(\n SQLITE_INTEGERS,\n sql`(${column} * ${by})`,\n scaleFactorSql(descriptor.scale)\n ),\n descriptor\n );\n },\n\n // `x * 10^s / y` in coefficient space, rounded half to even; the divisor's\n // sign moves onto the numerator so the rule always sees a positive divisor.\n // `y` is never zero — division by canonical zero is refused before I/O.\n //\n // SQLite drivers bind JS numbers as REAL, so `col / ?` runs real division\n // and would persist a fractional value into an INTEGER column. Casting the\n // divisor to INTEGER makes it native INT/INT division (truncating toward\n // zero, matching Postgres) for integer columns; real columns keep real\n // division since the column itself carries REAL affinity.\n divide: (column: Sql, by: Sql, target?: ArithmeticTarget): Sql => {\n const descriptor = target?.decimal;\n if (descriptor) {\n const factor = scaleFactorSql(descriptor.scale);\n return guardedCoefficientAssignment(\n column,\n sql`ABS(${column}) <= ${SQLITE_INTERMEDIATE_LIMIT} / ${factor}`,\n halfEvenQuotient(\n SQLITE_INTEGERS,\n signedNumerator(sql`(${column} * ${factor})`, by),\n sql`ABS(${by})`\n ),\n descriptor\n );\n }\n return target?.integer\n ? sql`${column} = ${column} / CAST(${by} AS INTEGER)`\n : sql`${column} = ${column} / ${by}`;\n },\n\n push: (column: Sql, values: Sql): Sql =>\n sql`${column} = ${jsonArrayConcat(\n sql`json(COALESCE(${column}, '[]'))`,\n values\n )}`,\n\n unshift: (column: Sql, values: Sql): Sql =>\n sql`${column} = ${jsonArrayConcat(\n values,\n sql`json(COALESCE(${column}, '[]'))`\n )}`,\n};\n\nconst SQLITE_MUTATIONS = {\n skipDuplicatesStrategy: \"sql\" as const,\n insert: createInsertStatement(quoteIdent),\n insertDefault: (table: Sql): Sql => sql`INSERT INTO ${table} DEFAULT VALUES`,\n\n ...createMutationCommands(),\n\n // SQLite 3.35+ supports RETURNING\n returning: (columns: Sql): Sql => sql`RETURNING ${columns}`,\n\n // SQLite uses same ON CONFLICT syntax as PostgreSQL (3.24+/3.35+)\n ...createOnConflictBuilders(),\n};\n\nconst SQLITE_ASSERTIONS = {\n exists: (query: Sql): Sql =>\n sql`SELECT CASE WHEN EXISTS (${query}) THEN 1 ELSE json_extract('x', '$') END AS \"__viborm_assert__\"`,\n notExists: (query: Sql): Sql =>\n sql`SELECT CASE WHEN NOT EXISTS (${query}) THEN 1 ELSE json_extract('x', '$') END AS \"__viborm_assert__\"`,\n // The refusal names its sentinel (`bad JSON path: '__viborm_refused__'`).\n holds: (condition: Sql, from?: Sql): Sql =>\n sql`SELECT CASE WHEN ${condition} THEN 1 ELSE json_extract('{}', '__viborm_refused__') END AS \"__viborm_judged__\"${from ? sql` FROM ${from}` : sql``}`,\n};\n\nconst SQLITE_JOINS = {\n ...createCoreJoins(),\n\n // SQLite doesn't support RIGHT JOIN (before 3.39, and driver support varies).\n // Never silently downgrade: emitting LEFT JOIN without swapping operands\n // returns wrong rows. The query engine never calls this today.\n right: (_table: Sql, _condition: Sql): Sql => {\n throw new Error(\n \"SQLite does not support RIGHT JOIN. Restructure the query with joins.left and swapped operands.\"\n );\n },\n\n // SQLite doesn't support FULL OUTER JOIN (before 3.39, and driver support varies).\n full: (_table: Sql, _condition: Sql): Sql => {\n throw new Error(\n \"SQLite does not support FULL OUTER JOIN. Check adapter.capabilities.supportsFullOuterJoin before calling.\"\n );\n },\n\n // SQLite does NOT support LATERAL joins\n // These methods should never be called - query engine should check capability first\n lateral: (_subquery: Sql, _alias: string): Sql => {\n throw new Error(\n \"SQLite does not support LATERAL joins. Check adapter.capabilities.supportsLateralJoins before calling.\"\n );\n },\n\n lateralLeft: (_subquery: Sql, _alias: string): Sql => {\n throw new Error(\n \"SQLite does not support LATERAL joins. Check adapter.capabilities.supportsLateralJoins before calling.\"\n );\n },\n};\n\nconst SQLITE_CAPABILITIES = {\n supportsReturning: true, // SQLite 3.35+\n // FALSE IN FACT, and it read `true` until the Phase 8 fold gave the flag its\n // first reader (query-performance-plan Phase 10.1). SQLite's `WITH` grammar\n // admits a SELECT and nothing else: measured on SQLite 3.51.2, each of\n // `WITH x AS (UPDATE …/INSERT …/DELETE … RETURNING …) SELECT * FROM x` is a\n // parse error (`near \"UPDATE\": syntax error`). Kept as a capability rather\n // than deleted because Phase 8's `WITH u AS (UPDATE … RETURNING *) SELECT …`\n // fold reads it to decide whether it may emit at all.\n supportsCteWithMutations: false,\n supportsFullOuterJoin: false,\n supportsLateralJoins: false, // SQLite does not support LATERAL joins\n supportsVector: false,\n supportsUpsertWhere: true, // SQLite supports WHERE in ON CONFLICT (3.24+)\n supportsTargetedUpsert: true, // ON CONFLICT (cols) arbitrates on those cols\n supportsMutationTargetInSubquery: true,\n // UPDATE/DELETE ... LIMIT needs SQLITE_ENABLE_UPDATE_DELETE_LIMIT, which is\n // off in the builds this project targets (better-sqlite3, libSQL, D1).\n supportsMutationRowLimit: false,\n supportsRowLocks: false,\n joinsJunctionFilters: true,\n};\n\nconst SQLITE_RESULT: AdapterResultParser = {\n // SQLite has no exact decimal type: a decimal column IS its unscaled\n // integer coefficient, and every projection casts it to text before a\n // driver turns an int64 into a double. The result boundary cannot tell the\n // two vocabularies apart by inspection, so the promise is declared here.\n decimalRepresentation: \"coefficient\",\n\n // A decimal LIST is TEXT holding a JSON array of those same coefficients,\n // stated separately because the two facts are separate: a dialect can spell\n // its scalar decimals exactly and still have no exact decimal inside JSON.\n decimalListRepresentation: \"coefficient\",\n\n // The same reading the `dateTime` literal above lowers through, so a column\n // is read back in the vocabulary it was written in.\n dateTimeRepresentation: sqliteDateTimePhysicalForm,\n\n // Derived from the ONE storage owner, so the column the migration creates\n // and the value this reads back cannot be two decisions.\n idRepresentation: (domain, nativeType) =>\n idStorageOf(domain, nativeType, \"sqlite\")?.representation ?? \"text\",\n\n parseResult: passThroughParseResult,\n\n parseRelation: (\n _value: unknown,\n next: (value?: unknown) => unknown\n ): unknown => next(),\n\n parseField: (\n _value: unknown,\n _scalarType: string,\n next: (value?: unknown) => unknown\n ): unknown => next(),\n};\n\nconst SQLITE_IDENTIFIERS = createIdentifiers(quoteIdent);\n\nconst SQLITE_CLAUSES = createStandardClauses();\n\nconst SQLITE_FILTERS = createRelationFilters();\n\nconst SQLITE_SUBQUERIES = createSubqueries(quoteIdent);\n\n// A member is written once and inlined at every use: one a nested body reads\n// is compiled again inside each use of that body, so it is materialized.\nconst SQLITE_CTE = createCteBuilders(quoteIdent, {\n materializing: sql.raw(\"MATERIALIZED\"),\n});\n\n/**\n * A multi-row `VALUES` is the one compound SQLite does not count against\n * `SQLITE_MAX_COMPOUND_SELECT` (500 terms; measured on 3.53.2: 500 `UNION\n * ALL SELECT` arms refused, 10,922 `VALUES` rows read), so the produced rows\n * follow their typed head as one: the head's columns still type every row,\n * as an arm's did (affinity and collation measured equal).\n */\nconst SQLITE_SET_OPERATIONS = createSetOperations(\n quoteIdent,\n (typed, rows, alias) =>\n sql`(${typed.head} UNION ALL VALUES ${sql.join(rows.map(rowValues), \", \")}) AS ${sql.raw(quoteIdent(alias))}`\n);\n\nconst SQLITE_RAW = createRawSql();\n\n/**\n * `and` nesting its members as a balanced tree, about log2(n) levels for n\n * members, where `and` itself nests one level per member.\n */\nfunction balancedConjunction(\n and: (...conditions: Sql[]) => Sql\n): (...conditions: Sql[]) => Sql {\n const balanced = (...conditions: Sql[]): Sql => {\n if (conditions.length <= 2) return and(...conditions);\n const middle = Math.floor(conditions.length / 2);\n return and(\n balanced(...conditions.slice(0, middle)),\n balanced(...conditions.slice(middle))\n );\n };\n return balanced;\n}\n\nexport class SQLiteAdapter implements DatabaseAdapter {\n constructor({\n temporaryObjects = true,\n deepExpressions = true,\n sharedRelationBodies = false,\n compoundSelectTerms,\n relationsPerStatement,\n }: SQLiteAdapterOptions = {}) {\n installGeoPointSql(this, this.geoPoint);\n if (!deepExpressions) {\n this.subqueries.existsCheck = (from, where) =>\n sql`SELECT 1 FROM (${SQLITE_SUBQUERIES.existsCheck(from, where)})`;\n // A derived table's `WHERE` is resolved on its own branch: a level's\n // row domain costs its height there, once, not at every level below.\n this.subqueries.isolated = (condition) =>\n sql`EXISTS (SELECT 1 FROM (SELECT 1 WHERE ${condition}))`;\n this.operators.and = balancedConjunction(SQLITE_OPERATORS.and);\n this.capabilities.boundsExpressionDepth = true;\n }\n if (sharedRelationBodies) this.capabilities.sharesRelationBodies = true;\n if (compoundSelectTerms !== undefined)\n this.capabilities.compoundSelectTerms = compoundSelectTerms;\n if (relationsPerStatement !== undefined)\n this.capabilities.relationsPerStatement = relationsPerStatement;\n // Only batches read the reference-table SQL, so it is built on first use.\n let batchRefs: BatchReferenceSqlAdapter | undefined;\n const createBatchRefs = () => this.#createBatchRefs(temporaryObjects);\n installAdapterInternals(this, {\n get batchRefs() {\n batchRefs ??= createBatchRefs();\n return batchRefs;\n },\n constraints: sqliteConstraintIdentities,\n select: this.#assemble.select,\n });\n }\n\n raw = SQLITE_RAW;\n\n identifiers = { ...SQLITE_IDENTIFIERS };\n\n literals = { ...SQLITE_LITERALS };\n\n operators = { ...SQLITE_OPERATORS };\n\n expressions = { ...SQLITE_EXPRESSIONS };\n\n aggregates = { ...SQLITE_AGGREGATES };\n\n // SQLite 3.38+ JSON functions\n json = { ...SQLITE_JSON };\n\n arrays = { ...SQLITE_ARRAYS };\n\n // SQLite parses NULLS FIRST/LAST natively since 3.30 (2019-10-04), which is\n // below this adapter's documented 3.35+ floor. The `(col IS NULL)` emulation\n // this replaces was an extra leading sort key, and an index can never supply\n // a sort key that is an expression: on a 100,000-row table with an index over\n // the sort columns, the emulated spelling planned `SCAN t | USE TEMP B-TREE\n // FOR ORDER BY` at 3.356 ms per page and the native one plans `SCAN t USING\n // INDEX` at 0.005 ms. MySQL keeps the emulation — it has no native syntax at\n // any version.\n orderBy = { ...SQLITE_ORDER_BY };\n\n clauses = { ...SQLITE_CLAUSES };\n\n set = { ...SQLITE_SET };\n\n filters = { ...SQLITE_FILTERS };\n\n subqueries = { ...SQLITE_SUBQUERIES };\n\n // SQLite has no bare OFFSET; LIMIT -1 means \"no limit\"\n noLimitValue = sql.raw(\"-1\");\n\n readonly #assemble = {\n select: (parts: QueryParts): Sql => {\n // SQLite doesn't support DISTINCT ON natively\n // Simulate using ROW_NUMBER() OVER (PARTITION BY ... ORDER BY ...)\n if (parts.distinct) {\n return assembleDistinctOnEmulation(\n parts,\n parts.distinct,\n this.identifiers.escape,\n this.noLimitValue\n );\n }\n\n // SQLite uses database-level locking, so FOR UPDATE is a no-op\n // (ignoring parts.forUpdate intentionally)\n return assembleSelectQuery(sql`SELECT ${parts.columns}`, parts, {\n forUpdate: \"omit\",\n noLimitValue: this.noLimitValue,\n });\n },\n };\n\n cte = { ...SQLITE_CTE };\n\n mutations = { ...SQLITE_MUTATIONS };\n\n assertions = { ...SQLITE_ASSERTIONS };\n\n joins = { ...SQLITE_JOINS };\n\n setOperations = { ...SQLITE_SET_OPERATIONS };\n\n capabilities: DatabaseAdapter[\"capabilities\"] = { ...SQLITE_CAPABILITIES };\n\n lastInsertId = (): Sql => sql.raw(\"last_insert_rowid()\");\n\n // The scratch is a TEMP table wherever the transport admits one, so it never\n // enters the user's database file. Where it does not (D1), it is an ordinary\n // table in `main`: created once, kept, and EMPTY between batches — every\n // batch deletes the rows it stored, keyed by its own batch id, inside that\n // same batch, and a batch that fails rolls its rows back with it. The table\n // itself persists; SQLite migration introspection leaves it out of the\n // snapshot (`src/migrations/drivers/sqlite/introspect.ts`).\n #createBatchRefs(temporaryObjects: boolean): BatchReferenceSqlAdapter {\n const table = sql.raw(quoteIdent(BATCH_REFS_TABLE));\n const create = sql.raw(\n temporaryObjects\n ? \"CREATE TEMP TABLE IF NOT EXISTS\"\n : \"CREATE TABLE IF NOT EXISTS\"\n );\n return createOnConflictBatchRefs({\n table,\n batchIdColumn: sql.raw('\"batch_id\"'),\n keyColumn: sql.raw('\"ref_key\"'),\n valueColumn: sql.raw('\"ref_value\"'),\n createTable: sql`${create} ${table} (\"batch_id\" TEXT NOT NULL, \"ref_key\" TEXT NOT NULL, \"ref_value\" TEXT, PRIMARY KEY (\"batch_id\", \"ref_key\"))`,\n castValue: (valueSql) => sql`CAST((${valueSql}) AS TEXT)`,\n lastInsertId: () => this.lastInsertId(),\n });\n }\n\n vector = unsupportedVector;\n\n readonly geoPoint: GeoPointSql = (() => {\n const longitude = (point: Sql): Sql =>\n this.json.numberAtPath(point, [\"longitude\"]);\n const latitude = (point: Sql): Sql =>\n this.json.numberAtPath(point, [\"latitude\"]);\n return {\n value: (pointLongitude, pointLatitude) =>\n sql`json_object('longitude', ${this.json.document(this.json.number(pointLongitude))}, 'latitude', ${this.json.document(this.json.number(pointLatitude))})`,\n longitude,\n latitude,\n ...createGeoPointCoordinatePredicates(\n longitude,\n latitude,\n this.operators\n ),\n };\n })();\n\n result: AdapterResultParser = { ...SQLITE_RESULT };\n}\n"],"mappings":"u1BA0EA,MAAM,EAAa,EAAuB,IAAI,CASxC,EAA0C,CAC9C,UAAW,EAAQ,IAAgB,CAAG,IAAI,EAAE,KAAK,EAAE,GACnD,WAAY,EAAQ,IAAgB,CAAG,IAAI,EAAE,KAAK,EAAE,GACrD,CAMD,SAAS,uBAAuB,EAAyC,CACvE,IAAM,EAAY,GAA4B,EAAY,CAC1D,GAAI,EAAY,GAAI,OAAO,EACvB,OAAY,IAIhB,OAHmB,EAAY,WAAW,IAAI,CAC1C,EAAY,MAAM,EAAE,EAAI,sBACxB,GAAe,uBACC,EAAY,IAAA,GA4BlC,MAAM,EAA4BA,EAAI,IAAI,sBAAsB,CAqB1D,oBAAuB,GAC3BA,EAAI,IAAI,IAAI,IAAI,OAAO,KAAK,IAAI,EAAW,UAAW,GAAG,CAAC,GAAG,CASzD,8BACJ,EACA,EACA,EACA,IAEA,CAAG,GAAG,EAAO,eAAe,EAAO,cAAc,EAAK,QAAQ,EAAM,QAAQ,oBAAoB,EAAW,CAAC,MAExG,EAA2B,QAC3B,EAA2B,QAO3B,YAAe,GAA4B,CAC/C,GAAI,EAAyB,KAAK,EAAQ,CACxC,MAAO,KAAK,EAAQ,GAEtB,GAAI,EAAyB,KAAK,EAAQ,CACxC,MAAU,MACR,gGACD,CAEH,MAAO,MAAM,EAAQ,IAIjB,aAAe,EAAa,IAAwB,CACxD,IAAI,EAAO,CAAG,GAAG,EAAO,SACxB,IAAK,IAAM,KAAW,EACpB,EAAO,CAAG,GAAG,EAAK,MAAM,YAAY,EAAQ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