viborm 1.2.3 → 1.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +6 -1
- package/dist/{adapter-internals-n3Mf3css.mjs → adapter-internals-AGgQRu5t.mjs} +1 -1
- package/dist/{adapter-internals-n3Mf3css.mjs.map → adapter-internals-AGgQRu5t.mjs.map} +1 -1
- package/dist/adapter-namespace-BpMbLKpL.mjs +2 -0
- package/dist/{adapter-namespace-DqkJQdrD.mjs.map → adapter-namespace-BpMbLKpL.mjs.map} +1 -1
- package/dist/adapters.d.mts +1 -1
- package/dist/adapters.mjs +1 -1
- package/dist/{array-literal-BsbbSLw3.mjs → array-literal-BKdLfNzM.mjs} +1 -1
- package/dist/{array-literal-BsbbSLw3.mjs.map → array-literal-BKdLfNzM.mjs.map} +1 -1
- package/dist/{base-AdXAoy6l.mjs → base-D3m1S7Uc.mjs} +2 -2
- package/dist/{base-AdXAoy6l.mjs.map → base-D3m1S7Uc.mjs.map} +1 -1
- package/dist/{batch-refs-4L8ECdPU.mjs → batch-refs-B4zn-FAu.mjs} +2 -2
- package/dist/{batch-refs-4L8ECdPU.mjs.map → batch-refs-B4zn-FAu.mjs.map} +1 -1
- package/dist/{bind-parameter-capacity-CjPgqnmx.mjs → bind-parameter-capacity-qfEejeOX.mjs} +2 -2
- package/dist/{bind-parameter-capacity-CjPgqnmx.mjs.map → bind-parameter-capacity-qfEejeOX.mjs.map} +1 -1
- package/dist/builder-Df24l2Bd.mjs +2 -0
- package/dist/builder-Df24l2Bd.mjs.map +1 -0
- package/dist/bun-sql.d.mts +3 -1
- package/dist/bun-sql.mjs +1 -1
- package/dist/bun-sql.mjs.map +1 -1
- package/dist/bun-sqlite.d.mts +1 -1
- package/dist/bun-sqlite.mjs +1 -1
- package/dist/cache/cloudflare-kv.d.mts +1 -1
- package/dist/cache/cloudflare-kv.mjs +1 -1
- package/dist/cache/memory.d.mts +1 -1
- package/dist/cache/memory.mjs +1 -1
- package/dist/{cache-BO57X0TT.mjs → cache-CIPRF-pz.mjs} +2 -2
- package/dist/{cache-BO57X0TT.mjs.map → cache-CIPRF-pz.mjs.map} +1 -1
- package/dist/cache.d.mts +1 -1
- package/dist/cache.mjs +1 -1
- package/dist/cache.mjs.map +1 -1
- package/dist/{canonical-json-rfC2Dg0X.mjs → canonical-json-BReb5nFO.mjs} +2 -2
- package/dist/{canonical-json-rfC2Dg0X.mjs.map → canonical-json-BReb5nFO.mjs.map} +1 -1
- package/dist/chain-C7c1YTXD.mjs +2 -0
- package/dist/chain-C7c1YTXD.mjs.map +1 -0
- package/dist/cli.mjs +2 -2
- package/dist/cli.mjs.map +1 -1
- package/dist/{client-GoDZgqdq.d.mts → client-70MrTq1E.d.mts} +3 -3
- package/dist/client-DM1UHfYG.mjs +49 -0
- package/dist/client-DM1UHfYG.mjs.map +1 -0
- package/dist/client-_WKrPNmm.mjs +2 -0
- package/dist/client-_WKrPNmm.mjs.map +1 -0
- package/dist/client.d.mts +2 -2
- package/dist/client.mjs +1 -1
- package/dist/{clock-CK41KO7t.mjs → clock-C24RcpwO.mjs} +1 -1
- package/dist/{clock-CK41KO7t.mjs.map → clock-C24RcpwO.mjs.map} +1 -1
- package/dist/config.d.mts +2 -2
- package/dist/config.mjs +1 -1
- package/dist/controls-Da-efekX.mjs +2 -0
- package/dist/controls-Da-efekX.mjs.map +1 -0
- package/dist/{current-DyzK6OCh.mjs → current-oXcxSCBQ.mjs} +1 -1
- package/dist/{current-DyzK6OCh.mjs.map → current-oXcxSCBQ.mjs.map} +1 -1
- package/dist/d1.d.mts +1 -1
- package/dist/d1.mjs +1 -1
- package/dist/d1.mjs.map +1 -1
- package/dist/{datetime-physical-codec-oIhiYZEP.mjs → datetime-physical-codec-BEqQbIP_.mjs} +2 -2
- package/dist/{datetime-physical-codec-oIhiYZEP.mjs.map → datetime-physical-codec-BEqQbIP_.mjs.map} +1 -1
- package/dist/driver-B9fIori_.mjs +2 -0
- package/dist/driver-B9fIori_.mjs.map +1 -0
- package/dist/{driver-B19QlFqn.mjs → driver-CPD0Xxw2.mjs} +2 -2
- package/dist/{driver-B19QlFqn.mjs.map → driver-CPD0Xxw2.mjs.map} +1 -1
- package/dist/driver.d.mts +1 -1
- package/dist/driver.mjs +1 -1
- package/dist/error-mapping-C9WgitPi.mjs +2 -0
- package/dist/error-mapping-C9WgitPi.mjs.map +1 -0
- package/dist/every-1pKZteeB.mjs +2 -0
- package/dist/{every-DCY4HV0X.mjs.map → every-1pKZteeB.mjs.map} +1 -1
- package/dist/{execution-context-BKR3bgES.mjs → execution-context-rJXTRVrJ.mjs} +1 -1
- package/dist/{execution-context-BKR3bgES.mjs.map → execution-context-rJXTRVrJ.mjs.map} +1 -1
- package/dist/{fs-estate-CAhDg7nY.mjs → fs-estate-i8Zlr1OQ.mjs} +2 -2
- package/dist/{fs-estate-CAhDg7nY.mjs.map → fs-estate-i8Zlr1OQ.mjs.map} +1 -1
- package/dist/{geo-area-codec-1SY9im7O.mjs → geo-area-codec-CbkmFArQ.mjs} +2 -2
- package/dist/{geo-area-codec-1SY9im7O.mjs.map → geo-area-codec-CbkmFArQ.mjs.map} +1 -1
- package/dist/geo-point-codec-DyEHMdJg.mjs +2 -0
- package/dist/geo-point-codec-DyEHMdJg.mjs.map +1 -0
- package/dist/hydration-DsyHNSDS.mjs +2 -0
- package/dist/{hydration-CAxOL4aI.mjs.map → hydration-DsyHNSDS.mjs.map} +1 -1
- package/dist/identifier-conversion-DaZ9yNpv.mjs +2 -0
- package/dist/{identifier-conversion-GgbwHc2G.mjs.map → identifier-conversion-DaZ9yNpv.mjs.map} +1 -1
- package/dist/{identity-CLFhCTZx.mjs → identity-oQvIe7u8.mjs} +2 -2
- package/dist/{identity-CLFhCTZx.mjs.map → identity-oQvIe7u8.mjs.map} +1 -1
- package/dist/{index-BaK35ze2.d.mts → index-VsM29vYN.d.mts} +5269 -4918
- package/dist/index.d.mts +3 -3
- package/dist/index.mjs +1 -1
- package/dist/index.mjs.map +1 -1
- package/dist/instrumentation.d.mts +1 -1
- package/dist/instrumentation.mjs +1 -1
- package/dist/{invariant-BnLYqsHO.mjs → invariant-D57gi_yW.mjs} +1 -1
- package/dist/{invariant-BnLYqsHO.mjs.map → invariant-D57gi_yW.mjs.map} +1 -1
- package/dist/{json-number-CGXpPu4D.mjs → json-number-DvmiNx0n.mjs} +1 -1
- package/dist/{json-number-CGXpPu4D.mjs.map → json-number-DvmiNx0n.mjs.map} +1 -1
- package/dist/key-D_kagnFv.mjs +2 -0
- package/dist/{key-BeoOwGr3.mjs.map → key-D_kagnFv.mjs.map} +1 -1
- package/dist/{libsql-x0RPVRDS.mjs → libsql-DFAoHXrI.mjs} +3 -3
- package/dist/{libsql-x0RPVRDS.mjs.map → libsql-DFAoHXrI.mjs.map} +1 -1
- package/dist/libsql.d.mts +1 -1
- package/dist/libsql.mjs +1 -1
- package/dist/{memory-gv5jLGYm.mjs → memory-GTWgeDNY.mjs} +2 -2
- package/dist/{memory-gv5jLGYm.mjs.map → memory-GTWgeDNY.mjs.map} +1 -1
- package/dist/migrations/mysql.d.mts +5 -5
- package/dist/migrations/mysql.mjs +1 -1
- package/dist/migrations/postgres.d.mts +5 -5
- package/dist/migrations/postgres.mjs +1 -1
- package/dist/migrations/sqlite.d.mts +5 -5
- package/dist/migrations/sqlite.mjs +1 -1
- package/dist/migrations/storage/durable-object.d.mts +1 -1
- package/dist/migrations/storage/durable-object.mjs +1 -1
- package/dist/migrations/storage/fs.d.mts +1 -1
- package/dist/migrations/storage/fs.mjs +1 -1
- package/dist/migrations/storage/r2.d.mts +1 -1
- package/dist/migrations/storage/r2.mjs +1 -1
- package/dist/migrations/tenant.d.mts +3 -3
- package/dist/migrations/tenant.mjs +1 -1
- package/dist/{migrations-DTObIjAm.mjs → migrations-Bn1SatyB.mjs} +2 -2
- package/dist/{migrations-DTObIjAm.mjs.map → migrations-Bn1SatyB.mjs.map} +1 -1
- package/dist/migrations.d.mts +5 -5
- package/dist/migrations.mjs +1 -1
- package/dist/mysql-adapter-C6c5govr.mjs +2 -0
- package/dist/{mysql-adapter-DkJPfoGf.mjs.map → mysql-adapter-C6c5govr.mjs.map} +1 -1
- package/dist/{mysql-B5cqxG99.mjs → mysql-xChEivOe.mjs} +6 -6
- package/dist/{mysql-B5cqxG99.mjs.map → mysql-xChEivOe.mjs.map} +1 -1
- package/dist/mysql2.d.mts +1 -1
- package/dist/mysql2.mjs +1 -1
- package/dist/{native-types-veeTk36s.mjs → native-types-asNCr26n.mjs} +1 -1
- package/dist/{native-types-veeTk36s.mjs.map → native-types-asNCr26n.mjs.map} +1 -1
- package/dist/neon-http.d.mts +3 -1
- package/dist/neon-http.mjs +1 -1
- package/dist/neon-http.mjs.map +1 -1
- package/dist/{object-store-DQR6bTBY.mjs → object-store-ChYHlOMD.mjs} +2 -2
- package/dist/{object-store-DQR6bTBY.mjs.map → object-store-ChYHlOMD.mjs.map} +1 -1
- package/dist/{object-store-Cj8Cnnba.d.mts → object-store-D9mvOHP4.d.mts} +4 -4
- package/dist/{observation-DUSm7oXK.mjs → observation-Co72iCd1.mjs} +2 -2
- package/dist/{observation-DUSm7oXK.mjs.map → observation-Co72iCd1.mjs.map} +1 -1
- package/dist/permissions.d.mts +424 -0
- package/dist/permissions.mjs +2 -0
- package/dist/permissions.mjs.map +1 -0
- package/dist/pg.d.mts +9 -1
- package/dist/pg.mjs +1 -1
- package/dist/pg.mjs.map +1 -1
- package/dist/pglite.d.mts +3 -1
- package/dist/pglite.mjs +1 -1
- package/dist/pglite.mjs.map +1 -1
- package/dist/{physical-6V_LNU3L.mjs → physical-CAOaNM4R.mjs} +2 -2
- package/dist/{physical-6V_LNU3L.mjs.map → physical-CAOaNM4R.mjs.map} +1 -1
- package/dist/{pinned-session-CLxj5M5e.mjs → pinned-session-BTplL3iZ.mjs} +2 -2
- package/dist/{pinned-session-CLxj5M5e.mjs.map → pinned-session-BTplL3iZ.mjs.map} +1 -1
- package/dist/planetscale.d.mts +1 -1
- package/dist/planetscale.mjs +1 -1
- package/dist/{planner-DH-K2gSq.d.mts → planner-C1NzLBge.d.mts} +1 -1
- package/dist/{postgres-DrXDok0O.mjs → postgres-BqAxDWTQ.mjs} +4 -4
- package/dist/{postgres-DrXDok0O.mjs.map → postgres-BqAxDWTQ.mjs.map} +1 -1
- package/dist/postgres-adapter-CGthb5yh.mjs +2 -0
- package/dist/postgres-adapter-CGthb5yh.mjs.map +1 -0
- package/dist/postgres-adapter-CxEit2-v.mjs +2 -0
- package/dist/postgres-adapter-CxEit2-v.mjs.map +1 -0
- package/dist/{postgres-result-7F0DllQe.mjs → postgres-result-KyBKBNJr.mjs} +2 -2
- package/dist/{postgres-result-7F0DllQe.mjs.map → postgres-result-KyBKBNJr.mjs.map} +1 -1
- package/dist/postgres.d.mts +3 -1
- package/dist/postgres.mjs +1 -1
- package/dist/postgres.mjs.map +1 -1
- package/dist/{provider-limits-BHATED_m.mjs → provider-limits-Da00ilvv.mjs} +2 -2
- package/dist/{provider-limits-BHATED_m.mjs.map → provider-limits-Da00ilvv.mjs.map} +1 -1
- package/dist/{result-parsing-DRXC89ek.mjs → result-parsing-8wEK3GY1.mjs} +1 -1
- package/dist/{result-parsing-DRXC89ek.mjs.map → result-parsing-8wEK3GY1.mjs.map} +1 -1
- package/dist/result-shape-CDgX_vzn.mjs +2 -0
- package/dist/result-shape-CDgX_vzn.mjs.map +1 -0
- package/dist/scalar-S8yMvdmx.mjs +4 -0
- package/dist/scalar-S8yMvdmx.mjs.map +1 -0
- package/dist/schema/json.d.mts +1 -1
- package/dist/schema/json.mjs +1 -1
- package/dist/schema/json.mjs.map +1 -1
- package/dist/schema-9N9jQlVL.mjs +2 -0
- package/dist/{schema-Cjem1-0f.mjs.map → schema-9N9jQlVL.mjs.map} +1 -1
- package/dist/{schema-introspection-DEYGC2qg.mjs → schema-introspection-CyXKReK1.mjs} +4 -4
- package/dist/{schema-introspection-DEYGC2qg.mjs.map → schema-introspection-CyXKReK1.mjs.map} +1 -1
- package/dist/schema.d.mts +1 -1
- package/dist/schema.mjs +1 -1
- package/dist/{select-assembly-f1UGoblh.mjs → select-assembly-CkGe2ABs.mjs} +2 -2
- package/dist/{select-assembly-f1UGoblh.mjs.map → select-assembly-CkGe2ABs.mjs.map} +1 -1
- package/dist/{settle-B9Vg1FnP.mjs → settle-CS_k6Ztm.mjs} +2 -2
- package/dist/{settle-B9Vg1FnP.mjs.map → settle-CS_k6Ztm.mjs.map} +1 -1
- package/dist/soft-delete.d.mts +27 -96
- package/dist/soft-delete.mjs +1 -1
- package/dist/soft-delete.mjs.map +1 -1
- package/dist/sql-Bhxq9arK.mjs +2 -0
- package/dist/sql-Bhxq9arK.mjs.map +1 -0
- package/dist/{sql-BvfwUKIh.d.mts → sql-EsoN_7Et.d.mts} +24 -0
- package/dist/{sql-statement-tokens-BBcoGmJb.mjs → sql-statement-tokens-CFi1y3bK.mjs} +1 -1
- package/dist/{sql-statement-tokens-BBcoGmJb.mjs.map → sql-statement-tokens-CFi1y3bK.mjs.map} +1 -1
- package/dist/sql.d.mts +1 -1
- package/dist/sql.mjs +1 -1
- package/dist/sqlite-adapter-BXAJy3mI.mjs +2 -0
- package/dist/sqlite-adapter-BXAJy3mI.mjs.map +1 -0
- package/dist/{sqlite-utils-DlgokMJN.mjs → sqlite-utils-D_cypcyW.mjs} +2 -2
- package/dist/{sqlite-utils-DlgokMJN.mjs.map → sqlite-utils-D_cypcyW.mjs.map} +1 -1
- package/dist/sqlite3.d.mts +3 -1
- package/dist/sqlite3.mjs +1 -1
- package/dist/sqlite3.mjs.map +1 -1
- package/dist/{standard-sql-Bk4RZPqJ.mjs → standard-sql-CoGqv-iX.mjs} +3 -3
- package/dist/standard-sql-CoGqv-iX.mjs.map +1 -0
- package/dist/{suppressed-failure-BwULh-8h.mjs → suppressed-failure-Bdo2aK81.mjs} +1 -1
- package/dist/{suppressed-failure-BwULh-8h.mjs.map → suppressed-failure-Bdo2aK81.mjs.map} +1 -1
- package/dist/to-many-C1PuFIpf.mjs +2 -0
- package/dist/to-many-C1PuFIpf.mjs.map +1 -0
- package/dist/{transaction-Bnl6ULTw.mjs → transaction-4dfqals6.mjs} +2 -2
- package/dist/{transaction-Bnl6ULTw.mjs.map → transaction-4dfqals6.mjs.map} +1 -1
- package/dist/{transaction-operation-CKK3l_9x.mjs → transaction-operation-CU1zlxiG.mjs} +2 -2
- package/dist/{transaction-operation-CKK3l_9x.mjs.map → transaction-operation-CU1zlxiG.mjs.map} +1 -1
- package/dist/{types-C4v6iAmY.mjs → types-C5Oxz9yp.mjs} +1 -1
- package/dist/{types-C4v6iAmY.mjs.map → types-C5Oxz9yp.mjs.map} +1 -1
- package/dist/{utils-CZNaOZR7.mjs → utils-CtFUE8UN.mjs} +4 -4
- package/dist/{utils-CZNaOZR7.mjs.map → utils-CtFUE8UN.mjs.map} +1 -1
- package/dist/v-CYTUI0H5.mjs +2 -0
- package/dist/v-CYTUI0H5.mjs.map +1 -0
- package/dist/validation-BQtO6srU.mjs +2 -0
- package/dist/{validation-PF9-_nKd.mjs.map → validation-BQtO6srU.mjs.map} +1 -1
- package/dist/validation-BamBwne9.mjs +2 -0
- package/dist/validation-BamBwne9.mjs.map +1 -0
- package/dist/validation.d.mts +1 -1
- package/dist/validation.mjs +1 -1
- package/dist/validator-DgffZq9C.mjs +2 -0
- package/dist/validator-DgffZq9C.mjs.map +1 -0
- package/dist/version-CXuJzC-q.mjs +2 -0
- package/dist/{version-Bemp-64P.mjs.map → version-CXuJzC-q.mjs.map} +1 -1
- package/package.json +35 -9
- package/dist/adapter-namespace-DqkJQdrD.mjs +0 -2
- package/dist/builder-Ycvq3ETg.mjs +0 -2
- package/dist/builder-Ycvq3ETg.mjs.map +0 -1
- package/dist/chain-Dh0FV72b.mjs +0 -2
- package/dist/chain-Dh0FV72b.mjs.map +0 -1
- package/dist/client-B1p6Le_h.mjs +0 -49
- package/dist/client-B1p6Le_h.mjs.map +0 -1
- package/dist/client-BLiBmykn.mjs +0 -2
- package/dist/client-BLiBmykn.mjs.map +0 -1
- package/dist/controls-DXgIn4zh.mjs +0 -2
- package/dist/controls-DXgIn4zh.mjs.map +0 -1
- package/dist/driver-BlnKXPFF.mjs +0 -2
- package/dist/driver-BlnKXPFF.mjs.map +0 -1
- package/dist/error-mapping-CnPCv1dm.mjs +0 -2
- package/dist/error-mapping-CnPCv1dm.mjs.map +0 -1
- package/dist/every-DCY4HV0X.mjs +0 -2
- package/dist/geo-point-codec-lhxH42SK.mjs +0 -2
- package/dist/geo-point-codec-lhxH42SK.mjs.map +0 -1
- package/dist/hydration-CAxOL4aI.mjs +0 -2
- package/dist/identifier-conversion-GgbwHc2G.mjs +0 -2
- package/dist/identifier-hQCs8M1n.mjs +0 -2
- package/dist/identifier-hQCs8M1n.mjs.map +0 -1
- package/dist/key-BeoOwGr3.mjs +0 -2
- package/dist/mysql-adapter-DkJPfoGf.mjs +0 -2
- package/dist/postgres-adapter-B3SQvcV1.mjs +0 -2
- package/dist/postgres-adapter-B3SQvcV1.mjs.map +0 -1
- package/dist/postgres-adapter-CQD2oGuD.mjs +0 -2
- package/dist/postgres-adapter-CQD2oGuD.mjs.map +0 -1
- package/dist/registration-preflight-DEjv050M.mjs +0 -4
- package/dist/registration-preflight-DEjv050M.mjs.map +0 -1
- package/dist/result-shape-CTNdNSW3.mjs +0 -2
- package/dist/result-shape-CTNdNSW3.mjs.map +0 -1
- package/dist/scalar-U0wD5bKy.mjs +0 -2
- package/dist/scalar-U0wD5bKy.mjs.map +0 -1
- package/dist/schema-Cjem1-0f.mjs +0 -2
- package/dist/sql-Bp7jicEX.mjs +0 -2
- package/dist/sql-Bp7jicEX.mjs.map +0 -1
- package/dist/sqlite-adapter-CW_3l6ea.mjs +0 -2
- package/dist/sqlite-adapter-CW_3l6ea.mjs.map +0 -1
- package/dist/standard-sql-Bk4RZPqJ.mjs.map +0 -1
- package/dist/terminal-C8cq1WWX.mjs +0 -2
- package/dist/terminal-C8cq1WWX.mjs.map +0 -1
- package/dist/v-D5Z06FKN.mjs +0 -2
- package/dist/v-D5Z06FKN.mjs.map +0 -1
- package/dist/validation-Dk9Q_-C7.mjs +0 -2
- package/dist/validation-Dk9Q_-C7.mjs.map +0 -1
- package/dist/validation-PF9-_nKd.mjs +0 -2
- package/dist/validator-X9-bwtRo.mjs +0 -2
- package/dist/validator-X9-bwtRo.mjs.map +0 -1
- package/dist/version-Bemp-64P.mjs +0 -2
- /package/dist/{contract-CIIqgFyb.d.mts → contract-Dw0FR78e.d.mts} +0 -0
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"result-shape-CTNdNSW3.mjs","names":["extensionFailures","#staged","#setState","#model","#operation","#executedWith","#promise","#reservedForBatch","#context","#engine","#model","#args","#modelName","#operation","#options","#execution","#deferredExecution","#inputPreparation","#prepareWriteOutcomeRegistration","#route","#wrapExecution","#cacheResultCodec","#preparedInput","#resolveSinglePackage","#resolveWriteOutcomeRegistration","#queryContext","#runCoreExecution","#readInstrumentationFacts","#observationCommitCertainty","#resolveRouted","#operationResolution","#writeOutcomeRegistrationResolved","#writeOutcomeRegistration","#routedInstance","#resolveArgs","#singlePackageResolved","#singlePackage","#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/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 return Object.freeze({\n mode: context.mode,\n kind: context.kind,\n model: context.model,\n operation: context.operation,\n input: context.input,\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","/**\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 { 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 readPendingCacheResultFriend = (operation) => ({\n args: operation.cacheKeyArgs(),\n controls: operation.#inputPreparation?.controls,\n codec: operation.#cacheResultCodec(),\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 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(this.#modelName, this.#operation, this.#args, placed);\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 binding = this.#engine.extensionChain?.callRows;\n const routed = this.#route.operation(\n this.#model,\n String(this.#options.originalOperation),\n args,\n binding &&\n callRows(binding, this.#modelName, this.#inputPreparation?.controls)\n );\n this.#routedInstance = routed;\n if (this.#operationResolution) {\n this.#operationResolution.routed = routed;\n }\n return routed;\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 /** The prepared facts one query handler chain inspects. */\n #queryContext(\n mode: QueryInterceptionMode,\n preparedInput: Record<string, unknown>\n ): PreparedModelQueryContext<Record<string, unknown>> {\n const controls = this.#inputPreparation?.controls;\n return Object.freeze({\n mode,\n kind: \"model\",\n model: this.#modelName,\n operation: String(this.#options.originalOperation),\n input: snapshotQueryInput(preparedInput),\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.#runExecution();\n }\n return observeOperation(\n observers,\n String(this.#options.originalOperation),\n this.#modelName,\n () => this.#runExecution(),\n () =>\n this.#observationCommitCertainty === undefined\n ? undefined\n : { commitCertainty: this.#observationCommitCertainty },\n this.#readInstrumentationFacts()\n );\n });\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 return 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 }\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/**\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":"8yBAuLA,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,SAAW,IAC1B,IAA8B,IAAA,GAEvB,GAAO,CAGd,CAAC,GACD,IAA8B,IAAA,IAC9B,IAAY,IAAA,IACZ,IAAiB,IAAA,IACjB,EAAa,OAAS,EAEf,6BACL,EACA,EACA,EACA,oCACA,GAAS,oBACT,GAAS,uBACV,CAEI,wBACL,EACA,EACA,EACA,EACA,EACA,EACA,EACD,CAGH,SAAS,qCAA4C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AAY,EAAS,IAAI,IAAO,EAAW,CAGpD,SAAS,gBAAgB,EAAoD,CAC3E,IAAM,EAAS,gBAAgB,YAAY,EAAM,SAAS,CAAC,CAAC,KACzD,CAAC,KAAe,EAClB,CACD,MAAO,CACL,GAAG,YAAY,EAAO,SAAW,EAAI,CAAC,EAAiB,CAAG,EAAO,CACjE,QAAS,QACV,CAGH,SAAgB,yBACd,EACA,EACA,EACA,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,EAAqB,IAAI,EAAU,CACrC,OAAO,gBAAgB,EAAO,EAAM,EAAU"}
|
package/dist/scalar-U0wD5bKy.mjs
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{n as e}from"./chunk-BuuaeEvq.mjs";import{o as t}from"./value-guards-CK9guf2Z.mjs";import{t as n}from"./validation-Dk9Q_-C7.mjs";import{_ as r,d as i,l as a,m as o,o as s,s as c,t as l}from"./terminal-C8cq1WWX.mjs";import{T as u,d,l as f,o as p,r as m,s as h,u as g,w as _}from"./registration-preflight-DEjv050M.mjs";import{J as v}from"./geo-point-codec-lhxH42SK.mjs";import{n as y}from"./v-D5Z06FKN.mjs";import{t as b}from"./current-DyzK6OCh.mjs";var x=class ModelToMany{#e;#t;constructor(e){this.#e=Object.freeze(e),this.#t=Object.freeze({state:this.#e,settleTarget:l(()=>this.#e.target.getter)})}name(e){return new ModelToMany({...this.#e,name:a(`s.toMany`,e)})}through(e){return this.#n({...this.#e.junction,table:c(`through`,e)})}source(e){return this.#n({...this.#e.junction,source:c(`source`,e)})}target(e){return this.#n({...this.#e.junction,target:c(`target`,e)})}onDelete(e){return this.#n({...this.#e.junction,onDelete:s(`onDelete`,e)})}onUpdate(e){return this.#n({...this.#e.junction,onUpdate:s(`onUpdate`,e)})}#n(e){return new ModelToMany({...this.#e,junction:Object.freeze(e)})}get"~"(){return this.#t}};function toMany(e,t){return typeof e==`function`?(arguments.length>1&&i(`s.toMany`,`options`,`A model-target relation takes exactly one argument`),new x({kind:`relation`,cardinality:`many`,target:{kind:`model`,getter:e}})):u({kind:`relation`,cardinality:`many`,target:{kind:`variants`,entries:_(`s.toMany`,e,t)}})}const S=y.bigint();var C=class BigIntScalar{state;_nativeType;constructor(e,t){this.state=e,this._nativeType=t}nullable(){return new BigIntScalar(d(this,{nullable:!0,hasDefault:!0,default:f(this.state),optional:!0,base:y.bigint({nullable:!0,array:this.state.array,schema:this.state.schema})}),this._nativeType)}array(){return new BigIntScalar(d(this,{array:!0,base:y.bigint({nullable:this.state.nullable,array:!0,schema:this.state.schema})}),this._nativeType)}id(){return new BigIntScalar(d(this,{isId:!0,isUnique:!0}),this._nativeType)}unique(){return new BigIntScalar(d(this,{isUnique:!0}),this._nativeType)}default(e){return new BigIntScalar(d(this,{hasDefault:!0,default:e,optional:!0}),this._nativeType)}schema(e){return new BigIntScalar(d(this,{schema:e,base:y.bigint({nullable:this.state.nullable,array:this.state.array,schema:e})}),this._nativeType)}map(e){return new BigIntScalar(d(this,{columnName:e}),this._nativeType)}increment(){return new BigIntScalar(d(this,{hasDefault:!0,autoGenerate:{kind:`increment`},default:void 0,disallowZero:!0,optional:!0}),this._nativeType)}get"~"(){return{state:this.state,nativeType:this._nativeType}}};const bigInt=e=>new C(p(`bigint`,S),m(`s.bigInt`,e)),w=y.blob();var T=class BlobScalar{state;_nativeType;constructor(e,t){this.state=e,this._nativeType=t}nullable(){return new BlobScalar(d(this,{nullable:!0,hasDefault:!0,default:f(this.state),optional:!0,base:y.blob({nullable:!0})}),this._nativeType)}default(e){return new BlobScalar(d(this,{hasDefault:!0,default:e,optional:!0}),this._nativeType)}map(e){return new BlobScalar(d(this,{columnName:e}),this._nativeType)}array(){throw Error(`Blob scalars don't support array modifier`)}id(){throw Error(`Blob scalars cannot be used as IDs`)}unique(){throw Error(`Blob scalars cannot be unique`)}get"~"(){return{state:this.state,nativeType:this._nativeType}}};const blob=e=>new T(p(`blob`,w),m(`s.blob`,e)),E=y.boolean();var D=class BooleanScalar{state;_nativeType;constructor(e,t){this.state=e,this._nativeType=t}nullable(){return new BooleanScalar(d(this,{nullable:!0,hasDefault:!0,default:f(this.state),optional:!0,base:y.boolean({nullable:!0,array:this.state.array})}),this._nativeType)}array(){return new BooleanScalar(d(this,{array:!0,base:y.boolean({nullable:this.state.nullable,array:!0})}),this._nativeType)}default(e){return new BooleanScalar(d(this,{hasDefault:!0,default:e,optional:!0}),this._nativeType)}map(e){return new BooleanScalar(d(this,{columnName:e}),this._nativeType)}_internal;get"~"(){return this._internal??={state:this.state,nativeType:this._nativeType}}};const boolean=e=>new D(p(`boolean`,E),m(`s.boolean`,e)),O=h(()=>b(`date`)),k=h(()=>b(`date`)),A=y.isoDate();var j=class DateScalar{state;_nativeType;constructor(e,t){this.state=e,this._nativeType=t}nullable(){return new DateScalar(d(this,{nullable:!0,hasDefault:!0,default:f(this.state),optional:!0,base:y.isoDate({nullable:!0,array:this.state.array,schema:this.state.schema})}),this._nativeType)}array(){return(this.state.autoGenerate?.kind===`now`||this.state.autoGenerate?.kind===`updatedAt`)&&g(`s.date`),new DateScalar(d(this,{array:!0,base:y.isoDate({nullable:this.state.nullable,array:!0,schema:this.state.schema})}),this._nativeType)}id(){return new DateScalar(d(this,{isId:!0,isUnique:!0}),this._nativeType)}unique(){return new DateScalar(d(this,{isUnique:!0}),this._nativeType)}schema(e){return new DateScalar(d(this,{schema:e,base:y.isoDate({nullable:this.state.nullable,array:this.state.array,schema:e})}),this._nativeType)}default(e){return new DateScalar(d(this,{hasDefault:!0,default:e,optional:!0}),this._nativeType)}map(e){return new DateScalar(d(this,{columnName:e}),this._nativeType)}now(){return this.state.array&&g(`s.date`),new DateScalar(d(this,{hasDefault:!0,autoGenerate:{kind:`now`},default:O,optional:!0}),this._nativeType)}updatedAt(){return this.state.array&&g(`s.date`),new DateScalar(d(this,{hasDefault:!0,autoGenerate:{kind:`updatedAt`},default:k,optional:!0}),this._nativeType)}get"~"(){return{state:this.state,nativeType:this._nativeType}}};const date=e=>new j(p(`date`,A),m(`s.date`,e)),M=h(()=>b(`datetime`)),N=h(()=>b(`datetime`)),P=y.isoTimestamp();var F=class DateTimeScalar{state;_nativeType;constructor(e,t){this.state=e,this._nativeType=t}nullable(){return new DateTimeScalar(d(this,{nullable:!0,hasDefault:!0,default:f(this.state),optional:!0,base:y.isoTimestamp({nullable:!0,array:this.state.array,schema:this.state.schema})}),this._nativeType)}array(){return(this.state.autoGenerate?.kind===`now`||this.state.autoGenerate?.kind===`updatedAt`)&&g(`s.dateTime`),new DateTimeScalar(d(this,{array:!0,base:y.isoTimestamp({nullable:this.state.nullable,array:!0,schema:this.state.schema})}),this._nativeType)}id(){return new DateTimeScalar(d(this,{isId:!0,isUnique:!0}),this._nativeType)}unique(){return new DateTimeScalar(d(this,{isUnique:!0}),this._nativeType)}schema(e){return new DateTimeScalar(d(this,{schema:e,base:y.isoTimestamp({nullable:this.state.nullable,array:this.state.array,schema:e})}),this._nativeType)}default(e){return new DateTimeScalar(d(this,{hasDefault:!0,default:e,optional:!0}),this._nativeType)}map(e){return new DateTimeScalar(d(this,{columnName:e}),this._nativeType)}now(){return this.state.array&&g(`s.dateTime`),new DateTimeScalar(d(this,{hasDefault:!0,autoGenerate:{kind:`now`},default:M,optional:!0}),this._nativeType)}updatedAt(){return this.state.array&&g(`s.dateTime`),new DateTimeScalar(d(this,{hasDefault:!0,autoGenerate:{kind:`updatedAt`},default:N,optional:!0}),this._nativeType)}withoutTimezone(){return new DateTimeScalar(d(this,{withTimezone:!1}),this._nativeType)}get"~"(){return{state:this.state,nativeType:this._nativeType}}};const dateTime=e=>new F({...p(`datetime`,P),withTimezone:!0},m(`s.dateTime`,e)),I=h(()=>b(`time`)),L=h(()=>b(`time`)),R=y.isoTime();var z=class TimeScalar{state;_nativeType;constructor(e,t){this.state=e,this._nativeType=t}nullable(){return new TimeScalar(d(this,{nullable:!0,hasDefault:!0,default:f(this.state),optional:!0,base:y.isoTime({nullable:!0,array:this.state.array,schema:this.state.schema})}),this._nativeType)}array(){return(this.state.autoGenerate?.kind===`now`||this.state.autoGenerate?.kind===`updatedAt`)&&g(`s.time`),new TimeScalar(d(this,{array:!0,base:y.isoTime({nullable:this.state.nullable,array:!0,schema:this.state.schema})}),this._nativeType)}id(){return new TimeScalar(d(this,{isId:!0,isUnique:!0}),this._nativeType)}unique(){return new TimeScalar(d(this,{isUnique:!0}),this._nativeType)}schema(e){return new TimeScalar(d(this,{schema:e,base:y.isoTime({nullable:this.state.nullable,array:this.state.array,schema:e})}),this._nativeType)}default(e){return new TimeScalar(d(this,{hasDefault:!0,default:e,optional:!0}),this._nativeType)}map(e){return new TimeScalar(d(this,{columnName:e}),this._nativeType)}now(){return this.state.array&&g(`s.time`),new TimeScalar(d(this,{hasDefault:!0,autoGenerate:{kind:`now`},default:I,optional:!0}),this._nativeType)}updatedAt(){return this.state.array&&g(`s.time`),new TimeScalar(d(this,{hasDefault:!0,autoGenerate:{kind:`updatedAt`},default:L,optional:!0}),this._nativeType)}withoutTimezone(){return new TimeScalar(d(this,{withTimezone:!1}),this._nativeType)}get"~"(){return{state:this.state,nativeType:this._nativeType}}};const time=e=>new z({...p(`time`,R),withTimezone:!1},m(`s.time`,e));function refuse(e,t){throw new n({kind:`schema-builder`,builder:`s.decimal`,path:e},[{path:e,message:t}])}function readDecimalDescriptor(e){let n=t(e)?e.precision:void 0,r=t(e)?e.scale:void 0;return typeof n==`number`&&Number.isSafeInteger(n)&&n>=1||refuse(`descriptor.precision`,`'precision' must be an integer between 1 and the maximum safe integer`),typeof r==`number`&&Number.isSafeInteger(r)&&r>=0&&r<=n&&!Object.is(r,-0)||refuse(`descriptor.scale`,`'scale' must be an integer between 0 and precision`),Object.freeze({precision:n,scale:r})}function refuseDecimalListKey(e){let t=`a fixed-decimal list cannot be an ID, a unique field, an index member, a foreign-key member, or a relation identity member`;refuse(e,e===`array`?`A decimal key cannot become a list: ${t}`:`A decimal list cannot be declared '.${e}()': ${t}`)}function normalizeDecimalDefault(e,t){if(typeof e==`function`)return e;let n=v(t,e);return n.issues!==void 0&&refuse(`default`,`The decimal default did not satisfy its field schema`),n.value}var B=class DecimalScalar{state;constructor(e){this.state=e}get descriptor(){return this.state.decimal}nullable(){return new DecimalScalar(d(this,{nullable:!0,hasDefault:!0,default:f(this.state),optional:!0,base:y.decimal({nullable:!0,array:this.state.array,decimal:this.descriptor,schema:this.state.schema})}))}array(){(this.state.isId||this.state.isUnique)&&refuseDecimalListKey(`array`);let e=y.decimal({nullable:this.state.nullable,array:!0,decimal:this.descriptor,schema:this.state.schema}),t=d(this,{array:!0,base:e});return this.state.hasDefault&&typeof this.state.default!=`function`&&Object.defineProperty(t,`default`,{value:normalizeDecimalDefault(this.state.default,e),configurable:!0,enumerable:!0,writable:!0}),new DecimalScalar(t)}id(){return this.state.array&&refuseDecimalListKey(`id`),new DecimalScalar(d(this,{isId:!0,isUnique:!0}))}unique(){return this.state.array&&refuseDecimalListKey(`unique`),new DecimalScalar(d(this,{isUnique:!0}))}default(e){return withValidatedDecimalDefault(this,normalizeDecimalDefault(e,this.state.base))}schema(e){let t=y.decimal({nullable:this.state.nullable,array:this.state.array,decimal:this.descriptor,schema:e}),n=d(this,{schema:e,base:t});return this.state.hasDefault&&typeof this.state.default!=`function`&&Object.defineProperty(n,`default`,{value:normalizeDecimalDefault(this.state.default,t),configurable:!0,enumerable:!0,writable:!0}),new DecimalScalar(n)}map(e){return new DecimalScalar(d(this,{columnName:e}))}get"~"(){return{state:this.state}}};function withValidatedDecimalDefault(e,t){return new B(d(e,{hasDefault:!0,default:t,optional:!0}))}const buildDecimalScalar=e=>{let t=readDecimalDescriptor(e);return new B({...p(`decimal`,y.decimal({decimal:t})),decimal:t})},decimal=e=>buildDecimalScalar(e);var V=class EnumScalar{state;_nativeType;constructor(e,t){this.state=e,this._nativeType=t}get enumValues(){return`values`in this.state.base?this.state.base.values:[]}nullable(){return new EnumScalar(d(this,{nullable:!0,hasDefault:!0,default:f(this.state),optional:!0,base:y.enum(this.enumValues,{nullable:!0,array:this.state.array})}),this._nativeType)}array(){return new EnumScalar(d(this,{array:!0,base:y.enum(this.enumValues,{nullable:this.state.nullable,array:!0})}),this._nativeType)}default(e){return new EnumScalar(d(this,{hasDefault:!0,default:e,optional:!0}),this._nativeType)}map(e){return new EnumScalar(d(this,{columnName:e}),this._nativeType)}name(e){return new EnumScalar(d(this,{enumName:e}),this._nativeType)}get"~"(){return{state:this.state,nativeType:this._nativeType}}};const enumScalar=(e,t)=>new V(p(`enum`,y.enum(e)),m(`s.enum`,t)),H=y.integer();var U=class IntScalar{state;_nativeType;constructor(e,t){this.state=e,this._nativeType=t}nullable(){return new IntScalar(d(this,{nullable:!0,hasDefault:!0,default:f(this.state),optional:!0,base:y.integer({nullable:!0,array:this.state.array,schema:this.state.schema})}),this._nativeType)}array(){return new IntScalar(d(this,{array:!0,base:y.integer({nullable:this.state.nullable,array:!0,schema:this.state.schema})}),this._nativeType)}id(){return new IntScalar(d(this,{isId:!0,isUnique:!0}),this._nativeType)}unique(){return new IntScalar(d(this,{isUnique:!0}),this._nativeType)}default(e){return new IntScalar(d(this,{hasDefault:!0,default:e,optional:!0}),this._nativeType)}schema(e){return new IntScalar(d(this,{schema:e,base:y.integer({nullable:this.state.nullable,array:this.state.array,schema:e})}),this._nativeType)}map(e){return new IntScalar(d(this,{columnName:e}),this._nativeType)}increment(){return new IntScalar(d(this,{hasDefault:!0,autoGenerate:{kind:`increment`},default:void 0,disallowZero:!0,optional:!0}),this._nativeType)}_internal;get"~"(){return this._internal??={state:this.state,nativeType:this._nativeType}}};const int=e=>new U(p(`int`,H),m(`s.int`,e)),W=y.json();var G=class JsonScalar{state;_nativeType;constructor(e,t){this.state=e,this._nativeType=t}nullable(){return new JsonScalar(d(this,{nullable:!0,hasDefault:!0,default:f(this.state),optional:!0,base:y.json({nullable:!0,schema:this.state.schema})}),this._nativeType)}default(e){let t=r(e);if(t===`AnyNull`||t===`DbNull`&&!this.state.nullable)throw new n({kind:`schema-builder`,builder:`s.json`,path:`default`},[{path:`default`,message:`JSON default must name a null this column can store`}]);let i=e===null&&!this.state.nullable?o:e;return new JsonScalar(d(this,{hasDefault:!0,default:i,optional:!0}),this._nativeType)}schema(e){return new JsonScalar(d(this,{schema:e,base:y.json({nullable:this.state.nullable,schema:e})}),this._nativeType)}map(e){return new JsonScalar(d(this,{columnName:e}),this._nativeType)}get"~"(){return{state:this.state,nativeType:this._nativeType}}};const json=e=>new G(p(`json`,W),m(`s.json`,e)),K=y.number();var q=class NumberScalar{state;_nativeType;constructor(e,t){this.state=e,this._nativeType=t}nullable(){return new NumberScalar(d(this,{nullable:!0,hasDefault:!0,default:f(this.state),optional:!0,base:y.number({nullable:!0,array:this.state.array,schema:this.state.schema})}),this._nativeType)}array(){return new NumberScalar(d(this,{array:!0,base:y.number({nullable:this.state.nullable,array:!0,schema:this.state.schema})}),this._nativeType)}id(){return new NumberScalar(d(this,{isId:!0,isUnique:!0}),this._nativeType)}unique(){return new NumberScalar(d(this,{isUnique:!0}),this._nativeType)}default(e){return new NumberScalar(d(this,{hasDefault:!0,default:e,optional:!0}),this._nativeType)}schema(e){return new NumberScalar(d(this,{schema:e,base:y.number({nullable:this.state.nullable,array:this.state.array,schema:e})}),this._nativeType)}map(e){return new NumberScalar(d(this,{columnName:e}),this._nativeType)}get"~"(){return{state:this.state,nativeType:this._nativeType}}};const number=e=>new q(p(`number`,K),m(`s.number`,e)),J=y.point();var Y=class PointScalar{state;constructor(e){this.state=e}nullable(){return new PointScalar(d(this,{nullable:!0,hasDefault:!0,default:f(this.state),optional:!0,base:y.point({nullable:!0})}))}default(e){return new PointScalar(d(this,{hasDefault:!0,default:normalizePointDefault(e,this.state.base),optional:!0}))}map(e){return new PointScalar(d(this,{columnName:e}))}get"~"(){return{state:this.state}}};function normalizePointDefault(e,t){if(typeof e==`function`)return e;let r=v(t,e);if(!r.issues)return r.value;throw new n({kind:`schema-builder`,builder:`s.point`,path:`default`},r.issues.map(e=>({path:e.path?.join(`.`)??`default`,message:e.message})))}function point(...e){if(e.length!==0)throw new n({kind:`schema-builder`,builder:`s.point`,path:`arguments`},[{path:`arguments`,message:`s.point() takes no native type or options`}]);return new Y(p(`point`,J))}const X=y.vector();var Z=class VectorScalar{state;_nativeType;constructor(e,t){this.state=e,this._nativeType=t}nullable(){return new VectorScalar(d(this,{nullable:!0,hasDefault:!0,default:f(this.state),optional:!0,base:y.vector(this.state.dimension,{nullable:!0})}),this._nativeType)}default(e){return new VectorScalar(d(this,{hasDefault:!0,default:e,optional:!0}),this._nativeType)}map(e){return new VectorScalar(d(this,{columnName:e}),this._nativeType)}dimension(e){if(!Number.isSafeInteger(e)||e<=0)throw new n({kind:`schema-builder`,builder:`s.vector`,path:`dimension`},[{path:`dimension`,message:`Vector dimension must be a positive safe integer`}]);return new VectorScalar(d(this,{dimension:e,base:y.vector(e,{nullable:this.state.nullable})}),this._nativeType)}get"~"(){return{state:this.state,nativeType:this._nativeType}}};const vector=e=>new Z(p(`vector`,X),m(`s.vector`,e));export{toMany as _,int as a,buildDecimalScalar as c,time as d,dateTime as f,bigInt as g,blob as h,json as i,decimal as l,boolean as m,point as n,enumScalar as o,date as p,number as r,B as s,vector as t,withValidatedDecimalDefault as u};
|
|
2
|
-
//# sourceMappingURL=scalar-U0wD5bKy.mjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"scalar-U0wD5bKy.mjs","names":["#state","#internal","#withJunction","v","v","v","defaultNow","defaultUpdatedAt","v","defaultNow","defaultUpdatedAt","v","v","v","v","v","v","v","v","v"],"sources":["../src/schema/relation/to-many.ts","../src/schema/scalars/bigint/scalar.ts","../src/schema/scalars/blob/scalar.ts","../src/schema/scalars/boolean/scalar.ts","../src/schema/scalars/datetime/date-scalar.ts","../src/schema/scalars/datetime/scalar.ts","../src/schema/scalars/datetime/time-scalar.ts","../src/schema/scalars/decimal/descriptor.ts","../src/schema/scalars/decimal/scalar.ts","../src/schema/scalars/enum/scalar.ts","../src/schema/scalars/int/scalar.ts","../src/schema/scalars/json/scalar.ts","../src/schema/scalars/number/scalar.ts","../src/schema/scalars/point/scalar.ts","../src/schema/scalars/vector/scalar.ts"],"sourcesContent":["// `s.toMany` — the other of the two relation factories.\n//\n// The factory states the SLOT CARDINALITY (many) and its argument states the\n// TARGET DOMAIN. A model-target collection is junction-capable and an empty\n// collection is `[]`, so there is no `.optional()` here and no `.unique()`\n// anywhere: the paired slot cardinality owns remote uniqueness.\n\nimport {\n type ExactVariantOptions,\n type NormalizedManyEntries,\n normalizeVariantEntries,\n type VariantGetterMap,\n type VariantMapGuard,\n type VariantOptions,\n type VariantToManyRelation,\n variantToManyTerminal,\n} from \"./polymorphic\";\nimport {\n createTargetSettlement,\n normalizeJunctionActions,\n normalizeJunctionToken,\n normalizeRelationName,\n refuseRelationInput,\n} from \"./terminal\";\nimport type {\n AnyRelation,\n Getter,\n GetterOnly,\n JunctionReferentialAction,\n JunctionSideActions,\n ModelToManyState,\n OrdinaryJunctionOverrides,\n RelationInternal,\n Replace,\n} from \"./types\";\n\n// =============================================================================\n// TERMINAL CAPABILITY SURFACE\n// =============================================================================\n\n/** A junction action: the symmetric shorthand, or one action per side. */\nexport type JunctionActionDeclaration =\n | JunctionReferentialAction\n | JunctionSideActions;\n\n/** Every key any map member of `Action` declares; a bare action declares none. */\ntype DeclaredMapKeys<Action> = Action extends JunctionReferentialAction\n ? never\n : keyof Action;\n\n/**\n * `{ source, target }` is exact: a key beside the two sides is refused\n * structurally, so a map held in a variable cannot carry one past\n * excess-property checking either. The keys are gathered across a union\n * before the check, so one clean member cannot vouch for another that carries\n * an extra key.\n */\nexport type ExactJunctionActions<Action> = Record<\n Exclude<DeclaredMapKeys<Action>, keyof JunctionSideActions>,\n never\n>;\n\n/**\n * A model-target collection slot.\n *\n * The junction overrides are independent, meaningful facts rather than stages of\n * one all-or-nothing value, so any subset may override its canonical default.\n * Exactly one endpoint owns all supplied overrides; the other endpoint supplies\n * none and consumes the mirrored resolved view. Whether these overrides belong\n * on the resolved physical owner is one full-schema topology rule, not a second\n * type-level guess — which is why they are offered before the inverse graph\n * exists and why the state does not carry them as a public type parameter.\n */\nexport type ModelToManyRelation<State> = {\n readonly \"~\": RelationInternal<State>;\n name<const Name extends string>(\n name: Name\n ): ModelToManyRelation<Replace<State, { readonly name: Name }>>;\n through(table: string): ModelToManyRelation<State>;\n source(token: string): ModelToManyRelation<State>;\n target(token: string): ModelToManyRelation<State>;\n onDelete<const Action extends JunctionActionDeclaration>(\n action: Action & ExactJunctionActions<Action>\n ): ModelToManyRelation<State>;\n onUpdate<const Action extends JunctionActionDeclaration>(\n action: Action & ExactJunctionActions<Action>\n ): ModelToManyRelation<State>;\n};\n\n// =============================================================================\n// PRIVATE TERMINAL\n// =============================================================================\n\nclass ModelToMany {\n readonly #state: ModelToManyState;\n readonly #internal: RelationInternal<ModelToManyState>;\n\n constructor(state: ModelToManyState) {\n this.#state = Object.freeze(state);\n this.#internal = Object.freeze({\n state: this.#state,\n settleTarget: createTargetSettlement(() => this.#state.target.getter),\n });\n }\n\n name(name: string): ModelToMany {\n return new ModelToMany({\n ...this.#state,\n name: normalizeRelationName(\"s.toMany\", name),\n });\n }\n\n through(table: string): ModelToMany {\n return this.#withJunction({\n ...this.#state.junction,\n table: normalizeJunctionToken(\"through\", table),\n });\n }\n\n source(token: string): ModelToMany {\n return this.#withJunction({\n ...this.#state.junction,\n source: normalizeJunctionToken(\"source\", token),\n });\n }\n\n target(token: string): ModelToMany {\n return this.#withJunction({\n ...this.#state.junction,\n target: normalizeJunctionToken(\"target\", token),\n });\n }\n\n onDelete(action: JunctionActionDeclaration): ModelToMany {\n return this.#withJunction({\n ...this.#state.junction,\n onDelete: normalizeJunctionActions(\"onDelete\", action),\n });\n }\n\n onUpdate(action: JunctionActionDeclaration): ModelToMany {\n return this.#withJunction({\n ...this.#state.junction,\n onUpdate: normalizeJunctionActions(\"onUpdate\", action),\n });\n }\n\n #withJunction(junction: OrdinaryJunctionOverrides): ModelToMany {\n return new ModelToMany({\n ...this.#state,\n junction: Object.freeze(junction),\n });\n }\n\n get \"~\"(): RelationInternal<ModelToManyState> {\n return this.#internal;\n }\n}\n\n// =============================================================================\n// FACTORY\n// =============================================================================\n\n/**\n * Declare a slot that holds a COLLECTION.\n *\n * The map overload is declared first so a variant map is never swallowed by the\n * broad getter overload. Dispatch examines only the argument representation and\n * never invokes a getter.\n */\nexport function toMany<\n const Entries extends VariantGetterMap,\n const Options extends VariantOptions<Entries> | undefined = undefined,\n>(\n variants: Entries & VariantMapGuard<Entries>,\n options?: Options & ExactVariantOptions<Options, Entries>\n): VariantToManyRelation<{\n readonly kind: \"relation\";\n readonly cardinality: \"many\";\n readonly target: {\n readonly kind: \"variants\";\n readonly entries: NormalizedManyEntries<Entries>;\n };\n}>;\nexport function toMany<const G>(getter: G & GetterOnly<G>): G extends Getter\n ? ModelToManyRelation<{\n readonly kind: \"relation\";\n readonly cardinality: \"many\";\n readonly target: { readonly kind: \"model\"; readonly getter: G };\n }>\n : never;\nexport function toMany(target: unknown, options?: unknown): AnyRelation {\n if (typeof target === \"function\") {\n // biome-ignore lint/complexity/noArguments: distinguishes omission from explicit undefined without changing the factory's public arity\n if (arguments.length > 1) {\n refuseRelationInput(\n \"s.toMany\",\n \"options\",\n \"A model-target relation takes exactly one argument\"\n );\n }\n return new ModelToMany({\n kind: \"relation\",\n cardinality: \"many\",\n target: { kind: \"model\", getter: target },\n });\n }\n return variantToManyTerminal({\n kind: \"relation\",\n cardinality: \"many\",\n target: {\n kind: \"variants\",\n entries: normalizeVariantEntries(\"s.toMany\", target, options),\n },\n });\n}\n","// BigInt Scalar\n// Standalone scalar class with State generic pattern\n\nimport type { StandardSchemaV1 } from \"@standard-schema/spec\";\nimport v from \"@validation/primitives/v\";\nimport {\n createDefaultState,\n type DefaultValueInput,\n nullableDefault,\n type ScalarState,\n updateState,\n} from \"../common\";\nimport { admitNativeType } from \"../native-catalog\";\nimport type {\n ExactNativeTypeMap,\n NativeDialect,\n NativeTypeArgument,\n NativeTypeDeclaration,\n} from \"../native-types\";\n\nconst bigIntBase = v.bigint();\n\nexport class BigIntScalar<State extends ScalarState<\"bigint\">> {\n private readonly state: State;\n private readonly _nativeType?: NativeTypeDeclaration | undefined;\n\n constructor(state: State, _nativeType?: NativeTypeDeclaration) {\n this.state = state;\n this._nativeType = _nativeType;\n }\n\n nullable() {\n return new BigIntScalar(\n updateState(this, {\n nullable: true,\n hasDefault: true,\n default: nullableDefault(this.state),\n optional: true,\n base: v.bigint<{\n nullable: true;\n array: State[\"array\"];\n schema: State[\"schema\"];\n }>({\n nullable: true,\n array: this.state.array,\n schema: this.state.schema,\n }),\n }),\n this._nativeType\n );\n }\n\n array() {\n return new BigIntScalar(\n updateState(this, {\n array: true,\n base: v.bigint<{\n nullable: State[\"nullable\"];\n array: true;\n schema: State[\"schema\"];\n }>({\n nullable: this.state.nullable,\n array: true,\n schema: this.state.schema,\n }),\n }),\n this._nativeType\n );\n }\n\n id() {\n return new BigIntScalar(\n updateState(this, { isId: true, isUnique: true }),\n this._nativeType\n );\n }\n\n unique() {\n return new BigIntScalar(\n updateState(this, { isUnique: true }),\n this._nativeType\n );\n }\n\n default<V extends DefaultValueInput<State>>(value: V) {\n return new BigIntScalar(\n updateState(this, { hasDefault: true, default: value, optional: true }),\n this._nativeType\n );\n }\n\n schema<S extends StandardSchemaV1<bigint>>(schema: S) {\n return new BigIntScalar(\n updateState(this, {\n schema,\n base: v.bigint<{\n nullable: State[\"nullable\"];\n array: State[\"array\"];\n schema: S;\n }>({\n nullable: this.state.nullable,\n array: this.state.array,\n schema,\n }),\n }),\n this._nativeType\n );\n }\n\n map(columnName: string) {\n return new BigIntScalar(\n updateState(this, { columnName }),\n this._nativeType\n );\n }\n\n increment() {\n return new BigIntScalar(\n updateState(this, {\n hasDefault: true,\n autoGenerate: { kind: \"increment\" },\n default: undefined,\n disallowZero: true,\n optional: true,\n }),\n this._nativeType\n );\n }\n\n get [\"~\"]() {\n return {\n state: this.state,\n nativeType: this._nativeType,\n };\n }\n}\n\nexport const bigInt = <\n Db extends NativeDialect = never,\n const Given extends ExactNativeTypeMap<Given> = never,\n>(\n nativeType?: NativeTypeArgument<Db, Given>\n) =>\n new BigIntScalar(\n createDefaultState(\"bigint\", bigIntBase),\n admitNativeType(\"s.bigInt\", nativeType)\n );\n","// Blob Scalar\n// Standalone scalar class with State generic pattern\n\nimport v from \"@validation/primitives/v\";\nimport {\n createDefaultState,\n type DefaultValueInput,\n nullableDefault,\n type ScalarState,\n updateState,\n} from \"../common\";\nimport { admitNativeType } from \"../native-catalog\";\nimport type {\n ExactNativeTypeMap,\n NativeDialect,\n NativeTypeArgument,\n NativeTypeDeclaration,\n} from \"../native-types\";\n\nconst blobBase = v.blob();\n\nexport class BlobScalar<State extends ScalarState<\"blob\">> {\n private readonly state: State;\n private readonly _nativeType?: NativeTypeDeclaration | undefined;\n\n constructor(state: State, _nativeType?: NativeTypeDeclaration) {\n this.state = state;\n this._nativeType = _nativeType;\n }\n\n nullable() {\n return new BlobScalar(\n updateState(this, {\n nullable: true,\n hasDefault: true,\n default: nullableDefault(this.state),\n optional: true,\n base: v.blob<{\n nullable: true;\n }>({\n nullable: true,\n }),\n }),\n this._nativeType\n );\n }\n\n default<V extends DefaultValueInput<State>>(value: V) {\n return new BlobScalar(\n updateState(this, {\n hasDefault: true,\n default: value,\n optional: true,\n }),\n this._nativeType\n );\n }\n\n /**\n * Maps this scalar to a custom column name in the database\n */\n map(columnName: string) {\n return new BlobScalar(updateState(this, { columnName }), this._nativeType);\n }\n\n // Blob scalars don't support array(), id(), or unique()\n array(): never {\n throw new Error(\"Blob scalars don't support array modifier\");\n }\n\n id(): never {\n throw new Error(\"Blob scalars cannot be used as IDs\");\n }\n\n unique(): never {\n throw new Error(\"Blob scalars cannot be unique\");\n }\n\n get [\"~\"]() {\n return {\n state: this.state,\n nativeType: this._nativeType,\n };\n }\n}\n\nexport const blob = <\n Db extends NativeDialect = never,\n const Given extends ExactNativeTypeMap<Given> = never,\n>(\n nativeType?: NativeTypeArgument<Db, Given>\n) =>\n new BlobScalar(\n createDefaultState(\"blob\", blobBase),\n admitNativeType(\"s.blob\", nativeType)\n );\n","// Boolean Scalar\n// Standalone scalar class with State generic pattern\n\nimport v from \"@validation/primitives/v\";\nimport {\n createDefaultState,\n type DefaultValueInput,\n nullableDefault,\n type ScalarState,\n updateState,\n} from \"../common\";\nimport { admitNativeType } from \"../native-catalog\";\nimport type {\n ExactNativeTypeMap,\n NativeDialect,\n NativeTypeArgument,\n NativeTypeDeclaration,\n} from \"../native-types\";\n\nconst booleanBase = v.boolean();\n\nexport class BooleanScalar<State extends ScalarState<\"boolean\">> {\n private readonly state: State;\n private readonly _nativeType?: NativeTypeDeclaration | undefined;\n\n constructor(state: State, _nativeType?: NativeTypeDeclaration) {\n this.state = state;\n this._nativeType = _nativeType;\n }\n\n nullable() {\n return new BooleanScalar(\n updateState(this, {\n nullable: true,\n hasDefault: true,\n default: nullableDefault(this.state),\n optional: true,\n base: v.boolean<{\n nullable: true;\n array: State[\"array\"];\n }>({\n nullable: true,\n array: this.state.array,\n }),\n }),\n this._nativeType\n );\n }\n\n array() {\n return new BooleanScalar(\n updateState(this, {\n array: true,\n base: v.boolean<{\n nullable: State[\"nullable\"];\n array: true;\n }>({\n nullable: this.state.nullable,\n array: true,\n }),\n }),\n this._nativeType\n );\n }\n\n default<V extends DefaultValueInput<State>>(value: V) {\n return new BooleanScalar(\n updateState(this, {\n hasDefault: true,\n default: value,\n optional: true,\n }),\n this._nativeType\n );\n }\n\n /**\n * Maps this scalar to a custom column name in the database\n */\n map(columnName: string) {\n return new BooleanScalar(\n updateState(this, { columnName }),\n this._nativeType\n );\n }\n\n private _internal?: {\n state: State;\n nativeType: NativeTypeDeclaration | undefined;\n };\n\n get [\"~\"]() {\n return (this._internal ??= {\n state: this.state,\n nativeType: this._nativeType,\n });\n }\n}\n\nexport const boolean = <\n Db extends NativeDialect = never,\n const Given extends ExactNativeTypeMap<Given> = never,\n>(\n nativeType?: NativeTypeArgument<Db, Given>\n) =>\n new BooleanScalar(\n createDefaultState(\"boolean\", booleanBase),\n admitNativeType(\"s.boolean\", nativeType)\n );\n","// Date Scalar\n// Standalone scalar class with State generic pattern\n\nimport type { StandardSchemaV1 } from \"@standard-schema/spec\";\nimport v from \"@validation/primitives/v\";\nimport {\n createDefaultState,\n type DefaultValueInput,\n generatorDefault,\n nullableDefault,\n refuseListGenerator,\n type ScalarState,\n updateState,\n} from \"../common\";\nimport { admitNativeType } from \"../native-catalog\";\nimport type {\n ExactNativeTypeMap,\n NativeDialect,\n NativeTypeArgument,\n NativeTypeDeclaration,\n} from \"../native-types\";\nimport { currentTemporalValue } from \"./current\";\n\nconst defaultNow = generatorDefault(() => currentTemporalValue(\"date\"));\nconst defaultUpdatedAt = generatorDefault(() => currentTemporalValue(\"date\"));\nconst dateBase = v.isoDate();\n\nexport class DateScalar<State extends ScalarState<\"date\">> {\n private readonly state: State;\n private readonly _nativeType?: NativeTypeDeclaration | undefined;\n\n constructor(state: State, _nativeType?: NativeTypeDeclaration) {\n this.state = state;\n this._nativeType = _nativeType;\n }\n\n nullable() {\n return new DateScalar(\n updateState(this, {\n nullable: true,\n hasDefault: true,\n default: nullableDefault(this.state),\n optional: true,\n base: v.isoDate<{\n nullable: true;\n array: State[\"array\"];\n schema: State[\"schema\"];\n }>({\n nullable: true,\n array: this.state.array,\n schema: this.state.schema,\n }),\n }),\n this._nativeType\n );\n }\n\n array() {\n if (\n this.state.autoGenerate?.kind === \"now\" ||\n this.state.autoGenerate?.kind === \"updatedAt\"\n )\n refuseListGenerator(\"s.date\");\n return new DateScalar(\n updateState(this, {\n array: true,\n base: v.isoDate<{\n nullable: State[\"nullable\"];\n array: true;\n schema: State[\"schema\"];\n }>({\n nullable: this.state.nullable,\n array: true,\n schema: this.state.schema,\n }),\n }),\n this._nativeType\n );\n }\n\n id() {\n return new DateScalar(\n updateState(this, { isId: true, isUnique: true }),\n this._nativeType\n );\n }\n\n unique() {\n return new DateScalar(\n updateState(this, { isUnique: true }),\n this._nativeType\n );\n }\n\n schema<S extends StandardSchemaV1<string>>(schema: S) {\n return new DateScalar(\n updateState(this, {\n schema,\n base: v.isoDate<{\n nullable: State[\"nullable\"];\n array: State[\"array\"];\n schema: S;\n }>({\n nullable: this.state.nullable,\n array: this.state.array,\n schema,\n }),\n }),\n this._nativeType\n );\n }\n\n default<V extends DefaultValueInput<State>>(value: V) {\n return new DateScalar(\n updateState(this, {\n hasDefault: true,\n default: value,\n optional: true,\n }),\n this._nativeType\n );\n }\n\n /**\n * Maps this scalar to a custom column name in the database\n */\n map(columnName: string) {\n return new DateScalar(updateState(this, { columnName }), this._nativeType);\n }\n\n now() {\n if (this.state.array) refuseListGenerator(\"s.date\");\n return new DateScalar(\n updateState(this, {\n hasDefault: true,\n autoGenerate: { kind: \"now\" },\n default: defaultNow,\n optional: true,\n }),\n this._nativeType\n );\n }\n\n updatedAt() {\n if (this.state.array) refuseListGenerator(\"s.date\");\n return new DateScalar(\n updateState(this, {\n hasDefault: true,\n autoGenerate: { kind: \"updatedAt\" },\n default: defaultUpdatedAt,\n optional: true,\n }),\n this._nativeType\n );\n }\n\n get [\"~\"]() {\n return {\n state: this.state,\n nativeType: this._nativeType,\n };\n }\n}\n\nexport const date = <\n Db extends NativeDialect = never,\n const Given extends ExactNativeTypeMap<Given> = never,\n>(\n nativeType?: NativeTypeArgument<Db, Given>\n) =>\n new DateScalar(\n createDefaultState(\"date\", dateBase),\n admitNativeType(\"s.date\", nativeType)\n );\n","// DateTime Scalar\n// Standalone scalar class with State generic pattern\n\nimport type { StandardSchemaV1 } from \"@standard-schema/spec\";\nimport v from \"@validation/primitives/v\";\nimport {\n createDefaultState,\n type DefaultValueInput,\n generatorDefault,\n nullableDefault,\n refuseListGenerator,\n type ScalarState,\n updateState,\n} from \"../common\";\nimport { admitNativeType } from \"../native-catalog\";\nimport type {\n ExactNativeTypeMap,\n NativeDialect,\n NativeTypeArgument,\n NativeTypeDeclaration,\n} from \"../native-types\";\nimport { currentTemporalValue } from \"./current\";\n\nconst defaultNow = generatorDefault(() => currentTemporalValue(\"datetime\"));\nconst defaultUpdatedAt = generatorDefault(() =>\n currentTemporalValue(\"datetime\")\n);\nconst datetimeBase = v.isoTimestamp();\n\nexport class DateTimeScalar<State extends ScalarState<\"datetime\">> {\n private readonly state: State;\n private readonly _nativeType?: NativeTypeDeclaration | undefined;\n constructor(state: State, _nativeType?: NativeTypeDeclaration) {\n this.state = state;\n this._nativeType = _nativeType;\n }\n\n nullable() {\n return new DateTimeScalar(\n updateState(this, {\n nullable: true,\n hasDefault: true,\n default: nullableDefault(this.state),\n optional: true,\n base: v.isoTimestamp<{\n nullable: true;\n array: State[\"array\"];\n schema: State[\"schema\"];\n }>({\n nullable: true,\n array: this.state.array,\n schema: this.state.schema,\n }),\n }),\n this._nativeType\n );\n }\n\n array() {\n if (\n this.state.autoGenerate?.kind === \"now\" ||\n this.state.autoGenerate?.kind === \"updatedAt\"\n )\n refuseListGenerator(\"s.dateTime\");\n return new DateTimeScalar(\n updateState(this, {\n array: true,\n base: v.isoTimestamp<{\n nullable: State[\"nullable\"];\n array: true;\n schema: State[\"schema\"];\n }>({\n nullable: this.state.nullable,\n array: true,\n schema: this.state.schema,\n }),\n }),\n this._nativeType\n );\n }\n\n id() {\n return new DateTimeScalar(\n updateState(this, { isId: true, isUnique: true }),\n this._nativeType\n );\n }\n\n unique() {\n return new DateTimeScalar(\n updateState(this, { isUnique: true }),\n this._nativeType\n );\n }\n\n schema<S extends StandardSchemaV1<string>>(schema: S) {\n return new DateTimeScalar(\n updateState(this, {\n schema,\n base: v.isoTimestamp<{\n nullable: State[\"nullable\"];\n array: State[\"array\"];\n schema: S;\n }>({\n nullable: this.state.nullable,\n array: this.state.array,\n schema,\n }),\n }),\n this._nativeType\n );\n }\n\n default<V extends DefaultValueInput<State>>(value: V) {\n return new DateTimeScalar(\n updateState(this, {\n hasDefault: true,\n default: value,\n optional: true,\n }),\n this._nativeType\n );\n }\n\n map(columnName: string) {\n return new DateTimeScalar(\n updateState(this, { columnName }),\n this._nativeType\n );\n }\n\n now() {\n if (this.state.array) refuseListGenerator(\"s.dateTime\");\n return new DateTimeScalar(\n updateState(this, {\n hasDefault: true,\n autoGenerate: { kind: \"now\" },\n default: defaultNow,\n optional: true,\n }),\n this._nativeType\n );\n }\n\n updatedAt() {\n if (this.state.array) refuseListGenerator(\"s.dateTime\");\n return new DateTimeScalar(\n updateState(this, {\n hasDefault: true,\n autoGenerate: { kind: \"updatedAt\" },\n default: defaultUpdatedAt,\n optional: true,\n }),\n this._nativeType\n );\n }\n\n withoutTimezone() {\n return new DateTimeScalar(\n updateState(this, { withTimezone: false }),\n this._nativeType\n );\n }\n\n get [\"~\"]() {\n return {\n state: this.state,\n nativeType: this._nativeType,\n };\n }\n}\n\nexport const dateTime = <\n Db extends NativeDialect = never,\n const Given extends ExactNativeTypeMap<Given> = never,\n>(\n nativeType?: NativeTypeArgument<Db, Given>\n) =>\n new DateTimeScalar(\n { ...createDefaultState(\"datetime\", datetimeBase), withTimezone: true },\n admitNativeType(\"s.dateTime\", nativeType)\n );\n","// Time Scalar\n// Standalone scalar class with State generic pattern\n\nimport type { StandardSchemaV1 } from \"@standard-schema/spec\";\nimport v from \"@validation/primitives/v\";\nimport {\n createDefaultState,\n type DefaultValueInput,\n generatorDefault,\n nullableDefault,\n refuseListGenerator,\n type ScalarState,\n updateState,\n} from \"../common\";\nimport { admitNativeType } from \"../native-catalog\";\nimport type {\n ExactNativeTypeMap,\n NativeDialect,\n NativeTypeArgument,\n NativeTypeDeclaration,\n} from \"../native-types\";\nimport { currentTemporalValue } from \"./current\";\n\nconst defaultNow = generatorDefault(() => currentTemporalValue(\"time\"));\nconst defaultUpdatedAt = generatorDefault(() => currentTemporalValue(\"time\"));\nconst timeBase = v.isoTime();\n\nexport class TimeScalar<State extends ScalarState<\"time\">> {\n private readonly state: State;\n private readonly _nativeType?: NativeTypeDeclaration | undefined;\n\n constructor(state: State, _nativeType?: NativeTypeDeclaration) {\n this.state = state;\n this._nativeType = _nativeType;\n }\n\n nullable() {\n return new TimeScalar(\n updateState(this, {\n nullable: true,\n hasDefault: true,\n default: nullableDefault(this.state),\n optional: true,\n base: v.isoTime<{\n nullable: true;\n array: State[\"array\"];\n schema: State[\"schema\"];\n }>({\n nullable: true,\n array: this.state.array,\n schema: this.state.schema,\n }),\n }),\n this._nativeType\n );\n }\n\n array() {\n if (\n this.state.autoGenerate?.kind === \"now\" ||\n this.state.autoGenerate?.kind === \"updatedAt\"\n )\n refuseListGenerator(\"s.time\");\n return new TimeScalar(\n updateState(this, {\n array: true,\n base: v.isoTime<{\n nullable: State[\"nullable\"];\n array: true;\n schema: State[\"schema\"];\n }>({\n nullable: this.state.nullable,\n array: true,\n schema: this.state.schema,\n }),\n }),\n this._nativeType\n );\n }\n\n id() {\n return new TimeScalar(\n updateState(this, { isId: true, isUnique: true }),\n this._nativeType\n );\n }\n\n unique() {\n return new TimeScalar(\n updateState(this, { isUnique: true }),\n this._nativeType\n );\n }\n\n schema<S extends StandardSchemaV1<string>>(schema: S) {\n return new TimeScalar(\n updateState(this, {\n schema,\n base: v.isoTime<{\n nullable: State[\"nullable\"];\n array: State[\"array\"];\n schema: S;\n }>({\n nullable: this.state.nullable,\n array: this.state.array,\n schema,\n }),\n }),\n this._nativeType\n );\n }\n\n default<V extends DefaultValueInput<State>>(value: V) {\n return new TimeScalar(\n updateState(this, {\n hasDefault: true,\n default: value,\n optional: true,\n }),\n this._nativeType\n );\n }\n\n /**\n * Maps this scalar to a custom column name in the database\n */\n map(columnName: string) {\n return new TimeScalar(updateState(this, { columnName }), this._nativeType);\n }\n\n now() {\n if (this.state.array) refuseListGenerator(\"s.time\");\n return new TimeScalar(\n updateState(this, {\n hasDefault: true,\n autoGenerate: { kind: \"now\" },\n default: defaultNow,\n optional: true,\n }),\n this._nativeType\n );\n }\n\n updatedAt() {\n if (this.state.array) refuseListGenerator(\"s.time\");\n return new TimeScalar(\n updateState(this, {\n hasDefault: true,\n autoGenerate: { kind: \"updatedAt\" },\n default: defaultUpdatedAt,\n optional: true,\n }),\n this._nativeType\n );\n }\n\n /**\n * Stores time without timezone information (the default).\n * Use an explicit native type for an existing TIMETZ column.\n *\n * Use this when:\n * - You want to store local times (e.g., \"store opens at 9:00 AM\")\n * - The time should not be converted based on timezone\n */\n withoutTimezone() {\n return new TimeScalar(\n updateState(this, { withTimezone: false }),\n this._nativeType\n );\n }\n\n get [\"~\"]() {\n return {\n state: this.state,\n nativeType: this._nativeType,\n };\n }\n}\n\nexport const time = <\n Db extends NativeDialect = never,\n const Given extends ExactNativeTypeMap<Given> = never,\n>(\n nativeType?: NativeTypeArgument<Db, Given>\n) =>\n new TimeScalar(\n { ...createDefaultState(\"time\", timeBase), withTimezone: false },\n admitNativeType(\"s.time\", nativeType)\n );\n","/**\n * The definition boundary for `s.decimal({ precision, scale })`.\n *\n * A scale cannot be inferred from storage, a value, a driver, or an operation:\n * SQLite ignores the numbers in `DECIMAL(10,5)` and may put a fractional value\n * in a binary64 double. So the domain is DECLARED once, here, and every later\n * consumer — validation, DDL, binding, decoding, comparison, arithmetic,\n * migration — reads that one frozen fact off the resolved scalar.\n *\n * The descriptor is the developer's own argument, or two numbers a schema\n * document carried verbatim; neither is a hostile object, so it is read like\n * any other argument — no read-once snapshot, no key enumeration. What this\n * module owns is whether the two numbers name a domain at all.\n */\n\nimport { ValidationError } from \"@errors\";\nimport type { StandardSchemaV1 } from \"@standard-schema/spec\";\nimport type { DecimalDescriptor } from \"@validation/primitives/decimal-codec\";\nimport { validateSchema } from \"@validation/primitives/helpers\";\nimport { isRecord } from \"@validation/value-guards\";\n\n/** The one construction-time refusal of a decimal declaration. */\nfunction refuse(path: string, message: string): never {\n throw new ValidationError(\n { kind: \"schema-builder\", builder: \"s.decimal\", path },\n [{ path, message }]\n );\n}\n\n/**\n * The frozen fixed-decimal domain the two numbers name: `precision` an integer\n * from 1 to the maximum safe integer, `scale` an integer from 0 to `precision`,\n * so \"at most `precision` total digits and at most `scale` fractional digits\"\n * is a domain with values in it.\n *\n * Its unique coverage is the schema document and an untyped JavaScript caller:\n * `read.ts` hands the numbers over as they were written, so `10.5`, `1e300` and\n * `-0` (which `JSON.parse` keeps and `JSON.stringify` loses) reach this check\n * and nothing earlier. The argument is `unknown` because the document seam\n * passes it untyped; it is read as an ordinary object, not a hostile one.\n * Whether a given PROVIDER can store the domain is a different question with a\n * different owner: the adapter answers it once when the schema is bound.\n */\nexport function readDecimalDescriptor(source: unknown): DecimalDescriptor {\n const precision = isRecord(source) ? source.precision : undefined;\n const scale = isRecord(source) ? source.scale : undefined;\n if (\n !(\n typeof precision === \"number\" &&\n Number.isSafeInteger(precision) &&\n precision >= 1\n )\n ) {\n refuse(\n \"descriptor.precision\",\n \"'precision' must be an integer between 1 and the maximum safe integer\"\n );\n }\n if (\n !(\n typeof scale === \"number\" &&\n Number.isSafeInteger(scale) &&\n scale >= 0 &&\n scale <= precision &&\n !Object.is(scale, -0)\n )\n ) {\n refuse(\n \"descriptor.scale\",\n \"'scale' must be an integer between 0 and precision\"\n );\n }\n return Object.freeze({ precision, scale });\n}\n\n/**\n * A fixed-decimal LIST is not a key, and this is where a chain that tries to\n * make one into a key stops (plan 2.1).\n *\n * Both directions are refused because the chain has two of them:\n * `.array().id()` names a list and then a key, `.id().array()` names a key and\n * then a list, and only refusing the one that comes second would leave the\n * other spelling admitted. The exclusion is the DECLARATION's, not the\n * database's: a decimal list is stored as one container value on two of three\n * providers, so a key over it would be a key over a JSON document whose\n * identity is its spelling rather than its members — and there is no member\n * arrangement that could make it addressable.\n *\n * The whole-schema rule F007 (\"an ID cannot be an array\") is untouched and\n * still owns every OTHER scalar type. This refuses earlier, at the call that\n * writes the illegal chain, and it also owns `.unique()`, which no rule in the\n * repository refuses on a list of any type.\n */\nexport function refuseDecimalListKey(\n position: \"id\" | \"unique\" | \"array\"\n): never {\n const explanation =\n \"a fixed-decimal list cannot be an ID, a unique field, an index member, a foreign-key member, or a relation identity member\";\n refuse(\n position,\n position === \"array\"\n ? `A decimal key cannot become a list: ${explanation}`\n : `A decimal list cannot be declared '.${position}()': ${explanation}`\n );\n}\n\n/**\n * A literal default, normalized through the field's complete current schema at\n * DEFINITION time, so model metadata holds the canonical logical value the DDL\n * renderer, the schema-document serializer and the create schema's trusted\n * default all read. A value outside the declared domain fails at the call that\n * wrote it, not at the first write.\n *\n * A function default keeps its closure, exactly as every other scalar's does:\n * a closure has no canonical spelling to retain, and the create schema runs the\n * field codec on each value it returns.\n */\nexport function normalizeDecimalDefault(\n value: unknown,\n schema: StandardSchemaV1<unknown, unknown>\n): unknown {\n if (typeof value === \"function\") return value;\n const result = validateSchema(schema, value);\n if (result.issues !== undefined) {\n refuse(\"default\", \"The decimal default did not satisfy its field schema\");\n }\n return result.value;\n}\n","import type { StandardSchemaV1 } from \"@standard-schema/spec\";\nimport type { DecimalDescriptor } from \"@validation/primitives/decimal-codec\";\nimport type { Decimal } from \"@validation/primitives/decimal-value\";\nimport v from \"@validation/primitives/v\";\nimport {\n createDefaultState,\n type DefaultValueInput,\n nullableDefault,\n type ScalarState,\n updateState,\n} from \"../common\";\nimport {\n normalizeDecimalDefault,\n readDecimalDescriptor,\n refuseDecimalListKey,\n} from \"./descriptor\";\n\n/**\n * The shared L1 descriptor supplies the two required keys. This intersection\n * makes that surface exact for held objects too, without declaring a second L2\n * precision/scale bag.\n */\ntype KeysOfUnion<Given> = Given extends unknown ? keyof Given : never;\n\ntype ExactDomain<Given> = Given &\n Record<Exclude<KeysOfUnion<Given>, keyof DecimalDescriptor>, never>;\n\n/**\n * The type-level half of plan 2.1's list exclusion.\n *\n * A key position is refused by making the RECEIVER unassignable, which is what\n * lets the diagnostic carry the reason: TypeScript reports the missing property\n * by name, so `s.decimal({...}).array().id()` reads as \"a fixed-decimal list\n * cannot be a key\" rather than as an arity or an argument error. The scalar's\n * own type is intersected in, so inside the method body `this` is the scalar it\n * has always been and no assertion is needed to reach its state.\n *\n * `unknown` on the legal side is inert: intersecting it changes nothing, so a\n * non-list decimal keeps exactly the chain it had, and a scalar whose arity is\n * still the unresolved `boolean` is admitted — only a declared list is refused.\n */\ninterface DecimalListKeyRefusal {\n readonly \"a fixed-decimal list cannot be a key\": never;\n}\n\ntype NotAList<State extends ScalarState<\"decimal\">> =\n State[\"array\"] extends true ? DecimalListKeyRefusal : unknown;\n\ntype NotAKey<State extends ScalarState<\"decimal\">> = State[\"isId\"] extends true\n ? DecimalListKeyRefusal\n : State[\"isUnique\"] extends true\n ? DecimalListKeyRefusal\n : unknown;\n\ntype DecimalScalarState<State extends ScalarState<\"decimal\">> = State & {\n readonly decimal: DecimalDescriptor;\n};\n\nexport class DecimalScalar<State extends ScalarState<\"decimal\">> {\n private readonly state: DecimalScalarState<State>;\n\n constructor(state: DecimalScalarState<State>) {\n this.state = state;\n }\n\n /** The frozen domain, carried by reference so identity survives a chain. */\n private get descriptor(): DecimalDescriptor {\n return this.state.decimal;\n }\n\n nullable() {\n return new DecimalScalar(\n updateState(this, {\n nullable: true,\n hasDefault: true,\n default: nullableDefault(this.state),\n optional: true,\n // The custom schema travels with the rebuilt base. `create` reads\n // `state.schema` directly, but `set`, `equals` and the field's own\n // value schema all read `state.base` — dropping it here would make one\n // field refine on create and not on update.\n base: v.decimal<{\n nullable: true;\n array: State[\"array\"];\n decimal: DecimalDescriptor;\n schema: State[\"schema\"];\n }>({\n nullable: true,\n array: this.state.array,\n decimal: this.descriptor,\n schema: this.state.schema,\n }),\n })\n );\n }\n\n array(this: DecimalScalar<State> & NotAKey<State>) {\n if (this.state.isId || this.state.isUnique) refuseDecimalListKey(\"array\");\n const base = v.decimal<{\n nullable: State[\"nullable\"];\n array: true;\n decimal: DecimalDescriptor;\n schema: State[\"schema\"];\n }>({\n nullable: this.state.nullable,\n array: true,\n decimal: this.descriptor,\n schema: this.state.schema,\n });\n const state = updateState(this, { array: true, base });\n if (this.state.hasDefault && typeof this.state.default !== \"function\") {\n Object.defineProperty(state, \"default\", {\n value: normalizeDecimalDefault(this.state.default, base),\n configurable: true,\n enumerable: true,\n writable: true,\n });\n }\n return new DecimalScalar(state);\n }\n\n id(this: DecimalScalar<State> & NotAList<State>) {\n if (this.state.array) refuseDecimalListKey(\"id\");\n return new DecimalScalar(updateState(this, { isId: true, isUnique: true }));\n }\n\n unique(this: DecimalScalar<State> & NotAList<State>) {\n if (this.state.array) refuseDecimalListKey(\"unique\");\n return new DecimalScalar(updateState(this, { isUnique: true }));\n }\n\n /**\n * A literal default is normalized through the field codec HERE, at\n * definition time, so model metadata retains the canonical logical value and\n * a schema document round-trips to the same declaration. A value outside the\n * declared domain fails at the call that wrote it, not at the first write.\n */\n default<V extends DefaultValueInput<State>>(value: V) {\n return withValidatedDecimalDefault(\n this,\n normalizeDecimalDefault(value, this.state.base)\n );\n }\n\n /**\n * Refine or brand the exact value. The schema observes a `Decimal` — the\n * public value type — and the declared domain validates whatever it returns\n * LAST, so a custom schema can narrow the domain but never escape it, and it\n * cannot change the value family the field reads back as.\n */\n schema<S extends StandardSchemaV1<Decimal>>(schema: S) {\n const base = v.decimal<{\n nullable: State[\"nullable\"];\n array: State[\"array\"];\n decimal: DecimalDescriptor;\n schema: S;\n }>({\n nullable: this.state.nullable,\n array: this.state.array,\n decimal: this.descriptor,\n schema,\n });\n const state = updateState(this, { schema, base });\n if (this.state.hasDefault && typeof this.state.default !== \"function\") {\n Object.defineProperty(state, \"default\", {\n value: normalizeDecimalDefault(this.state.default, base),\n configurable: true,\n enumerable: true,\n writable: true,\n });\n }\n return new DecimalScalar(state);\n }\n\n map(columnName: string) {\n return new DecimalScalar(updateState(this, { columnName }));\n }\n\n get [\"~\"](): {\n state: DecimalScalarState<State>;\n nativeType?: undefined;\n } {\n // A fixed decimal has no native-type override: PostgreSQL's `NUMERIC(p,s)`,\n // MySQL's `DECIMAL(p,s)` and SQLite's checked scaled `INTEGER` are all\n // DERIVED from the declared domain, and a second spelling beside it would\n // be a second answer to what the column is. The absence is DECLARED so the\n // scalar union keeps one internal shape for every reader.\n return { state: this.state };\n }\n}\n\n/**\n * Store the canonical verdict of the field's current base schema.\n *\n * This is an internal schema-document seam, deliberately absent from the\n * public decimal barrel. The document interpreter already has to validate a\n * decoded default to own its J008 diagnostic; feeding that verdict back\n * through `.default()` would run the same field codec a second time.\n */\nexport function withValidatedDecimalDefault<\n State extends ScalarState<\"decimal\">,\n>(scalar: DecimalScalar<State>, value: unknown) {\n return new DecimalScalar(\n updateState(scalar, {\n hasDefault: true,\n default: value,\n optional: true,\n })\n );\n}\n\n/**\n * The one public decimal factory.\n *\n * `precision` is the maximum total digit count and `scale` the maximum\n * fractional digit count; values are multiples of `10^-scale`, and an input\n * that does not fit is refused rather than silently rounded. There is no\n * zero-argument form, no native-type override, and no second \"fixed decimal\"\n * factory: portable exact decimal arithmetic needs these two numbers, and\n * SQLite cannot supply them from storage, so they are declared once here.\n */\nexport const buildDecimalScalar = (descriptor: unknown) => {\n const domain = readDecimalDescriptor(descriptor);\n return new DecimalScalar({\n ...createDefaultState(\n \"decimal\",\n v.decimal<{ decimal: DecimalDescriptor }>({ decimal: domain })\n ),\n decimal: domain,\n });\n};\n\n/** The exact public argument surface over the untyped construction seam. */\nexport const decimal = <const D>(\n descriptor: D & NoInfer<DecimalDescriptor & ExactDomain<D>>\n) => buildDecimalScalar(descriptor);\n","// Enum Scalar\n// Standalone scalar class with State generic pattern\n\nimport type { EnumValues } from \"@validation/primitives/enum\";\nimport v from \"@validation/primitives/v\";\nimport {\n createDefaultState,\n type DefaultValueInput,\n nullableDefault,\n type ScalarState,\n updateState,\n} from \"../common\";\nimport { admitNativeType } from \"../native-catalog\";\nimport type {\n ExactNativeTypeMap,\n NativeDialect,\n NativeTypeArgument,\n NativeTypeDeclaration,\n} from \"../native-types\";\n\nexport class EnumScalar<State extends ScalarState<\"enum\">> {\n private readonly state: State;\n private readonly _nativeType?: NativeTypeDeclaration | undefined;\n constructor(state: State, _nativeType?: NativeTypeDeclaration) {\n this.state = state;\n this._nativeType = _nativeType;\n }\n\n get enumValues() {\n return (\n \"values\" in this.state.base ? this.state.base.values : []\n ) as EnumValues<State[\"base\"]>;\n }\n\n nullable() {\n return new EnumScalar(\n updateState(this, {\n nullable: true,\n hasDefault: true,\n default: nullableDefault(this.state),\n optional: true,\n base: v.enum<\n typeof this.enumValues,\n {\n nullable: true;\n array: State[\"array\"];\n }\n >(this.enumValues, {\n nullable: true,\n array: this.state.array,\n }),\n }),\n this._nativeType\n );\n }\n\n array() {\n return new EnumScalar(\n updateState(this, {\n array: true,\n base: v.enum<\n typeof this.enumValues,\n {\n nullable: State[\"nullable\"];\n array: true;\n }\n >(this.enumValues, {\n nullable: this.state.nullable,\n array: true,\n }),\n }),\n this._nativeType\n );\n }\n\n default<V extends DefaultValueInput<State>>(value: V) {\n return new EnumScalar(\n updateState(this, {\n hasDefault: true,\n default: value,\n optional: true,\n }),\n this._nativeType\n );\n }\n\n map(columnName: string) {\n return new EnumScalar(updateState(this, { columnName }), this._nativeType);\n }\n\n /**\n * Set a custom name for the enum type in the database.\n * This allows reusing the same enum across multiple tables.\n *\n * @example\n * ```ts\n * const Status = s.enum([\"PENDING\", \"ACTIVE\"]).name(\"status\");\n *\n * const user = s.model({ status: Status });\n * const order = s.model({ status: Status }); // Same \"status\" enum type\n * ```\n */\n name(enumName: string) {\n return new EnumScalar(updateState(this, { enumName }), this._nativeType);\n }\n\n get [\"~\"]() {\n return {\n state: this.state,\n nativeType: this._nativeType,\n };\n }\n}\n\nexport const enumScalar = <\n // A readonly tuple is admitted; see `enum_` for the mutable arm.\n const T extends string[] | readonly string[],\n Db extends NativeDialect = never,\n const Given extends ExactNativeTypeMap<Given> = never,\n>(\n values: T,\n nativeType?: NativeTypeArgument<Db, Given>\n) => {\n return new EnumScalar(\n createDefaultState(\"enum\", v.enum(values)),\n admitNativeType(\"s.enum\", nativeType)\n );\n};\n","import type { StandardSchemaV1 } from \"@standard-schema/spec\";\nimport v from \"@validation/primitives/v\";\nimport {\n createDefaultState,\n type DefaultValueInput,\n nullableDefault,\n type ScalarState,\n updateState,\n} from \"../common\";\nimport { admitNativeType } from \"../native-catalog\";\nimport type {\n ExactNativeTypeMap,\n NativeDialect,\n NativeTypeArgument,\n NativeTypeDeclaration,\n} from \"../native-types\";\n\nconst intBase = v.integer();\n\nexport class IntScalar<State extends ScalarState<\"int\">> {\n private readonly state: State;\n private readonly _nativeType?: NativeTypeDeclaration | undefined;\n\n constructor(state: State, _nativeType?: NativeTypeDeclaration) {\n this.state = state;\n this._nativeType = _nativeType;\n }\n\n nullable() {\n return new IntScalar(\n updateState(this, {\n nullable: true,\n hasDefault: true,\n default: nullableDefault(this.state),\n optional: true,\n base: v.integer<{\n nullable: true;\n array: State[\"array\"];\n schema: State[\"schema\"];\n }>({\n nullable: true,\n array: this.state.array,\n schema: this.state.schema,\n }),\n }),\n this._nativeType\n );\n }\n\n array() {\n return new IntScalar(\n updateState(this, {\n array: true,\n base: v.integer<{\n nullable: State[\"nullable\"];\n array: true;\n schema: State[\"schema\"];\n }>({\n nullable: this.state.nullable,\n array: true,\n schema: this.state.schema,\n }),\n }),\n this._nativeType\n );\n }\n\n id() {\n return new IntScalar(\n updateState(this, { isId: true, isUnique: true }),\n this._nativeType\n );\n }\n\n unique() {\n return new IntScalar(\n updateState(this, { isUnique: true }),\n this._nativeType\n );\n }\n\n default<V extends DefaultValueInput<State>>(value: V) {\n return new IntScalar(\n updateState(this, {\n hasDefault: true,\n default: value,\n optional: true,\n }),\n this._nativeType\n );\n }\n\n schema<S extends StandardSchemaV1<number>>(schema: S) {\n return new IntScalar(\n updateState(this, {\n schema,\n base: v.integer<{\n nullable: State[\"nullable\"];\n array: State[\"array\"];\n schema: S;\n }>({\n nullable: this.state.nullable,\n array: this.state.array,\n schema,\n }),\n }),\n this._nativeType\n );\n }\n\n map(columnName: string) {\n return new IntScalar(updateState(this, { columnName }), this._nativeType);\n }\n\n increment() {\n return new IntScalar(\n updateState(this, {\n hasDefault: true,\n autoGenerate: { kind: \"increment\" },\n default: undefined,\n disallowZero: true,\n optional: true,\n }),\n this._nativeType\n );\n }\n\n private _internal?: {\n state: State;\n nativeType: NativeTypeDeclaration | undefined;\n };\n\n get [\"~\"]() {\n return (this._internal ??= {\n state: this.state,\n nativeType: this._nativeType,\n });\n }\n}\n\nexport const int = <\n Db extends NativeDialect = never,\n const Given extends ExactNativeTypeMap<Given> = never,\n>(\n nativeType?: NativeTypeArgument<Db, Given>\n) =>\n new IntScalar(\n createDefaultState(\"int\", intBase),\n admitNativeType(\"s.int\", nativeType)\n );\n","import { ValidationError } from \"@errors\";\nimport {\n JsonNull,\n type JsonNullSentinel,\n jsonNullKindOf,\n} from \"@schema/json-null\";\nimport type { StandardSchemaV1 } from \"@standard-schema/spec\";\nimport type { JsonValue } from \"@validation\";\nimport type { JsonInput } from \"@validation/primitives/json\";\nimport v from \"@validation/primitives/v\";\nimport {\n createDefaultState,\n type DefaultValue,\n type DefaultValueInput,\n nullableDefault,\n type ScalarState,\n updateState,\n} from \"../common\";\nimport { admitNativeType } from \"../native-catalog\";\nimport type {\n ExactNativeTypeMap,\n NativeDialect,\n NativeTypeArgument,\n NativeTypeDeclaration,\n} from \"../native-types\";\n\nconst jsonBase = v.json();\n\nexport class JsonScalar<\n State extends ScalarState<\"json\"> = ScalarState<\"json\">,\n> {\n private readonly state: State;\n private readonly _nativeType?: NativeTypeDeclaration | undefined;\n constructor(state: State, _nativeType?: NativeTypeDeclaration) {\n this.state = state;\n this._nativeType = _nativeType;\n }\n\n nullable() {\n return new JsonScalar(\n updateState(this, {\n nullable: true,\n hasDefault: true,\n default: nullableDefault(this.state),\n optional: true,\n base: v.json<{\n nullable: true;\n schema: State[\"schema\"];\n }>({\n nullable: true,\n schema: this.state.schema,\n }),\n }),\n this._nativeType\n );\n }\n\n default<\n V extends\n | DefaultValueInput<State>\n | DefaultValue<\n JsonNullSentinel<\n State[\"nullable\"] extends true ? \"JsonNull\" | \"DbNull\" : \"JsonNull\"\n >\n >,\n >(value: V) {\n const kind = jsonNullKindOf(value);\n if (kind === \"AnyNull\" || (kind === \"DbNull\" && !this.state.nullable)) {\n throw new ValidationError(\n { kind: \"schema-builder\", builder: \"s.json\", path: \"default\" },\n [\n {\n path: \"default\",\n message: \"JSON default must name a null this column can store\",\n },\n ]\n );\n }\n const defaultValue =\n value === null && !this.state.nullable ? JsonNull : value;\n return new JsonScalar(\n updateState(this, {\n hasDefault: true,\n default: defaultValue,\n optional: true,\n }),\n this._nativeType\n );\n }\n\n schema<S extends StandardSchemaV1<JsonInput, JsonValue>>(schema: S) {\n return new JsonScalar(\n updateState(this, {\n schema,\n base: v.json<{\n nullable: State[\"nullable\"];\n schema: S;\n }>({\n nullable: this.state.nullable,\n schema,\n }),\n }),\n this._nativeType\n );\n }\n\n map(columnName: string) {\n return new JsonScalar(updateState(this, { columnName }), this._nativeType);\n }\n\n get [\"~\"]() {\n return {\n state: this.state,\n nativeType: this._nativeType,\n };\n }\n}\n\nexport const json = <\n Db extends NativeDialect = never,\n const Given extends ExactNativeTypeMap<Given> = never,\n>(\n nativeType?: NativeTypeArgument<Db, Given>\n) =>\n new JsonScalar(\n createDefaultState(\"json\", jsonBase),\n admitNativeType(\"s.json\", nativeType)\n );\n","import type { StandardSchemaV1 } from \"@standard-schema/spec\";\nimport v from \"@validation/primitives/v\";\nimport {\n createDefaultState,\n type DefaultValueInput,\n nullableDefault,\n type ScalarState,\n updateState,\n} from \"../common\";\nimport { admitNativeType } from \"../native-catalog\";\nimport type {\n ExactNativeTypeMap,\n NativeDialect,\n NativeTypeArgument,\n NativeTypeDeclaration,\n} from \"../native-types\";\n\nconst numberBase = v.number();\n\nexport class NumberScalar<State extends ScalarState<\"number\">> {\n private readonly state: State;\n private readonly _nativeType?: NativeTypeDeclaration | undefined;\n\n constructor(state: State, _nativeType?: NativeTypeDeclaration) {\n this.state = state;\n this._nativeType = _nativeType;\n }\n\n nullable() {\n return new NumberScalar(\n updateState(this, {\n nullable: true,\n hasDefault: true,\n default: nullableDefault(this.state),\n optional: true,\n base: v.number<{\n nullable: true;\n array: State[\"array\"];\n schema: State[\"schema\"];\n }>({\n nullable: true,\n array: this.state.array,\n schema: this.state.schema,\n }),\n }),\n this._nativeType\n );\n }\n\n array() {\n return new NumberScalar(\n updateState(this, {\n array: true,\n base: v.number<{\n nullable: State[\"nullable\"];\n array: true;\n schema: State[\"schema\"];\n }>({\n nullable: this.state.nullable,\n array: true,\n schema: this.state.schema,\n }),\n }),\n this._nativeType\n );\n }\n\n id() {\n return new NumberScalar(\n updateState(this, { isId: true, isUnique: true }),\n this._nativeType\n );\n }\n\n unique() {\n return new NumberScalar(\n updateState(this, { isUnique: true }),\n this._nativeType\n );\n }\n\n default<V extends DefaultValueInput<State>>(value: V) {\n return new NumberScalar(\n updateState(this, {\n hasDefault: true,\n default: value,\n optional: true,\n }),\n this._nativeType\n );\n }\n\n schema<S extends StandardSchemaV1<number>>(schema: S) {\n return new NumberScalar(\n updateState(this, {\n schema,\n base: v.number<{\n nullable: State[\"nullable\"];\n array: State[\"array\"];\n schema: S;\n }>({\n nullable: this.state.nullable,\n array: this.state.array,\n schema,\n }),\n }),\n this._nativeType\n );\n }\n\n map(columnName: string) {\n return new NumberScalar(\n updateState(this, { columnName }),\n this._nativeType\n );\n }\n\n get [\"~\"]() {\n return {\n state: this.state,\n nativeType: this._nativeType,\n };\n }\n}\n\nexport const number = <\n Db extends NativeDialect = never,\n const Given extends ExactNativeTypeMap<Given> = never,\n>(\n nativeType?: NativeTypeArgument<Db, Given>\n) =>\n new NumberScalar(\n createDefaultState(\"number\", numberBase),\n admitNativeType(\"s.number\", nativeType)\n );\n","import { ValidationError } from \"@errors\";\nimport { validateSchema } from \"@validation/primitives/helpers\";\nimport v from \"@validation/primitives/v\";\nimport {\n createDefaultState,\n type DefaultValueInput,\n nullableDefault,\n type ScalarState,\n updateState,\n} from \"../common\";\n\nconst pointBase = v.point();\n\nexport class PointScalar<State extends ScalarState<\"point\">> {\n private readonly state: State;\n constructor(state: State) {\n this.state = state;\n }\n\n nullable() {\n return new PointScalar(\n updateState(this, {\n nullable: true,\n hasDefault: true,\n default: nullableDefault(this.state),\n optional: true,\n base: v.point<{\n nullable: true;\n }>({\n nullable: true,\n }),\n })\n );\n }\n\n default<V extends DefaultValueInput<State>>(value: V) {\n return new PointScalar(\n updateState(this, {\n hasDefault: true,\n default: normalizePointDefault(value, this.state.base),\n optional: true,\n })\n );\n }\n\n map(columnName: string) {\n return new PointScalar(updateState(this, { columnName }));\n }\n\n get [\"~\"](): { state: State; nativeType?: undefined } {\n return { state: this.state };\n }\n}\n\nfunction normalizePointDefault(value: unknown, schema: StateSchema): unknown {\n if (typeof value === \"function\") return value;\n const result = validateSchema(schema, value);\n if (!result.issues) return result.value;\n throw new ValidationError(\n { kind: \"schema-builder\", builder: \"s.point\", path: \"default\" },\n result.issues.map((issue) => ({\n path: issue.path?.join(\".\") ?? \"default\",\n message: issue.message,\n }))\n );\n}\n\ntype StateSchema = ScalarState<\"point\">[\"base\"];\n\n/** The one public GeoPoint scalar factory; EPSG:4326 is not configurable. */\nexport function point(...args: []) {\n if (args.length !== 0) {\n throw new ValidationError(\n { kind: \"schema-builder\", builder: \"s.point\", path: \"arguments\" },\n [\n {\n path: \"arguments\",\n message: \"s.point() takes no native type or options\",\n },\n ]\n );\n }\n return new PointScalar(createDefaultState(\"point\", pointBase));\n}\n","// Vector Scalar\n// Standalone scalar class with State generic pattern\n\nimport { ValidationError } from \"@errors\";\nimport v from \"@validation/primitives/v\";\nimport {\n createDefaultState,\n type DefaultValueInput,\n nullableDefault,\n type ScalarState,\n updateState,\n} from \"../common\";\nimport { admitNativeType } from \"../native-catalog\";\nimport type {\n ExactNativeTypeMap,\n NativeDialect,\n NativeTypeArgument,\n NativeTypeDeclaration,\n} from \"../native-types\";\n\nconst vectorBase = v.vector();\n\nexport class VectorScalar<State extends ScalarState<\"vector\">> {\n private readonly state: State;\n private readonly _nativeType?: NativeTypeDeclaration | undefined;\n\n constructor(state: State, _nativeType?: NativeTypeDeclaration) {\n this.state = state;\n this._nativeType = _nativeType;\n }\n\n nullable() {\n return new VectorScalar(\n updateState(this, {\n nullable: true,\n hasDefault: true,\n default: nullableDefault(this.state),\n optional: true,\n base: v.vector<{\n nullable: true;\n }>(this.state.dimension, {\n nullable: true,\n }),\n }),\n this._nativeType\n );\n }\n\n default<V extends DefaultValueInput<State>>(value: V) {\n return new VectorScalar(\n updateState(this, {\n hasDefault: true,\n default: value,\n optional: true,\n }),\n this._nativeType\n );\n }\n\n /**\n * Maps this scalar to a custom column name in the database\n */\n map(columnName: string) {\n return new VectorScalar(\n updateState(this, { columnName }),\n this._nativeType\n );\n }\n\n dimension(dim: number) {\n if (!Number.isSafeInteger(dim) || dim <= 0) {\n throw new ValidationError(\n { kind: \"schema-builder\", builder: \"s.vector\", path: \"dimension\" },\n [\n {\n path: \"dimension\",\n message: \"Vector dimension must be a positive safe integer\",\n },\n ]\n );\n }\n return new VectorScalar(\n updateState(this, {\n dimension: dim,\n base: v.vector(dim, { nullable: this.state.nullable }),\n }),\n this._nativeType\n );\n }\n\n get [\"~\"]() {\n return {\n state: this.state,\n nativeType: this._nativeType,\n };\n }\n}\n\nexport const vector = <\n Db extends NativeDialect = never,\n const Given extends ExactNativeTypeMap<Given> = never,\n>(\n nativeType?: NativeTypeArgument<Db, Given>\n) =>\n new VectorScalar(\n createDefaultState(\"vector\", vectorBase),\n admitNativeType(\"s.vector\", nativeType)\n );\n"],"mappings":"scA6FA,IAAM,EAAN,MAAM,WAAY,CAChB,GACA,GAEA,YAAY,EAAyB,CACnC,MAAA,EAAc,OAAO,OAAO,EAAM,CAClC,MAAA,EAAiB,OAAO,OAAO,CAC7B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AY,EAAW,CACxC"}
|
package/dist/schema-Cjem1-0f.mjs
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{C as e,n as t,y as n}from"./registration-preflight-DEjv050M.mjs";import{_ as r,a as i,d as a,f as o,g as s,h as c,i as l,l as u,m as d,n as f,o as p,p as m,r as h,t as g}from"./scalar-U0wD5bKy.mjs";const _={model:n,string:t,boolean:d,int:i,number:h,decimal:u,bigInt:s,dateTime:o,date:m,time:a,json:l,blob:c,enum:p,point:f,vector:g,toOne:e,toMany:r};export{_ as t};
|
|
2
|
-
//# sourceMappingURL=schema-Cjem1-0f.mjs.map
|
package/dist/sql-Bp7jicEX.mjs
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{n as e}from"./chunk-BuuaeEvq.mjs";var t=class Sql{rawStrings;rawValues;projection;statements;constructor(e,t){if(e.length-1!==t.length)throw e.length===0?TypeError(`Expected at least 1 string`):TypeError(`Expected ${e.length} strings to have ${e.length-1} values`);this.rawStrings=e,this.rawValues=t}get values(){return this.flatten().values}get strings(){return this.flatten().strings}flatten(){if(this.projection!==void 0)return this.projection;let e=[],t=[],n=``,walk=(r,i)=>{n+=r[0];for(let a=0;a<i.length;a++){let o=i[a];o instanceof Sql?walk(o.rawStrings,o.rawValues):(t.push(o),e.push(n),n=``),n+=r[a+1]}};walk(this.rawStrings,this.rawValues),e.push(n);let r={strings:e,values:t};return this.rawStrings=e,this.rawValues=t,this.projection=r,r}toStatement(e=`?`){let t=this.statements?.[e];if(t!==void 0)return t;let n=this.strings,r=n.length;if(r===1){let e=n[0];return this.statements={$n:e,":n":e,"?":e},e}let i;if(e===`?`)i=n.join(`?`);else{let t=e===`$n`?`$`:`:`,a=Array(r*2-1);a[0]=n[0];for(let e=1;e<r;e++)a[e*2-1]=t+e,a[e*2]=n[e];i=a.join(``)}let a=this.statements??{};return a[e]=i,this.statements=a,i}};function raw(e,...n){if(n.length!==0||typeof e!=`string`&&e.length!==1)throw TypeError(`raw templates cannot interpolate values; use sql for parameters or raw(trustedText) for explicit SQL text.`);return typeof e==`string`?new t([e],[]):new t(e,[])}function join(e,n=`,`,r=``,i=``){let a=e.length;if(a===0)return new t([r+i],[]);let o=Array(a+1);o[0]=r;for(let e=1;e<a;e++)o[e]=n;return o[a]=i,new t(o,e)}const n=raw``;function sql(e,...n){return new t(e,n)}const r=Object.assign(sql,{raw,empty:n,join});function isSql(e){if(e instanceof t)return!0;if(typeof e!=`object`||!e)return!1;let n=Reflect.get(e,`strings`);if(!Array.isArray(n))return!1;let r=Reflect.get(e,`values`);return Array.isArray(r)&&n.length===r.length+1&&n.every(e=>typeof e==`string`)&&typeof Reflect.get(e,`toStatement`)==`function`}export{raw as a,join as i,n,r as o,isSql as r,t};
|
|
2
|
-
//# sourceMappingURL=sql-Bp7jicEX.mjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"sql-Bp7jicEX.mjs","names":["result"],"sources":["../src/sql/sql.ts"],"sourcesContent":["/**\n * Values supported by SQL engine.\n */\nexport type Value = unknown;\n\n/**\n * Supported value or SQL instance.\n */\nexport type RawValue = Value | Sql;\n\ntype Placeholder = \"$n\" | \":n\" | \"?\";\n\ninterface SqlProjection {\n strings: string[];\n values: Value[];\n}\n\ntype StatementCache = Partial<Record<Placeholder, string>>;\n\n/**\n * A SQL instance can be nested within each other to build SQL strings.\n *\n * Composition is lazy: constructing a Sql just stores the raw fragments.\n * The nested tree is flattened in a single pass over raw fragments when\n * `strings`/`values` is first read (typically only on the root query), so\n * intermediate fragments never pay flattening or allocation.\n */\nexport class Sql {\n private rawStrings: readonly string[];\n private rawValues: readonly RawValue[];\n\n private projection: SqlProjection | undefined;\n private statements: StatementCache | undefined;\n\n constructor(rawStrings: readonly string[], rawValues: readonly RawValue[]) {\n if (rawStrings.length - 1 !== rawValues.length) {\n if (rawStrings.length === 0) {\n throw new TypeError(\"Expected at least 1 string\");\n }\n throw new TypeError(\n `Expected ${rawStrings.length} strings to have ${\n rawStrings.length - 1\n } values`\n );\n }\n\n this.rawStrings = rawStrings;\n this.rawValues = rawValues;\n }\n\n get values(): Value[] {\n return this.flatten().values;\n }\n\n get strings(): string[] {\n return this.flatten().strings;\n }\n\n /**\n * Flatten the raw fragment tree in one pass, walking children's raw\n * fragments directly so nested Sql instances are never flattened themselves.\n * The flat arrays then replace the raw tree as the canonical representation,\n * releasing child fragments that are not referenced elsewhere.\n */\n private flatten(): SqlProjection {\n if (this.projection !== undefined) {\n return this.projection;\n }\n\n const strings: string[] = [];\n const values: Value[] = [];\n let current = \"\";\n\n const walk = (\n rawStrings: readonly string[],\n rawValues: readonly RawValue[]\n ): void => {\n current += rawStrings[0]!;\n for (let i = 0; i < rawValues.length; i++) {\n const child = rawValues[i]!;\n if (child instanceof Sql) {\n walk(child.rawStrings, child.rawValues);\n } else {\n values.push(child);\n strings.push(current);\n current = \"\";\n }\n current += rawStrings[i + 1]!;\n }\n };\n\n walk(this.rawStrings, this.rawValues);\n strings.push(current);\n\n const projection: SqlProjection = { strings, values };\n\n this.rawStrings = strings;\n this.rawValues = values;\n this.projection = projection;\n\n return projection;\n }\n\n /**\n * Build the final SQL statement string with placeholders.\n * Results are cached per placeholder type for reuse.\n */\n toStatement(placeholder: Placeholder = \"?\"): string {\n const cached = this.statements?.[placeholder];\n if (cached !== undefined) return cached;\n\n const strings = this.strings;\n const len = strings.length;\n\n if (len === 1) {\n const result = strings[0]!;\n this.statements = { $n: result, \":n\": result, \"?\": result };\n return result;\n }\n\n let result: string;\n\n if (placeholder === \"?\") {\n result = strings.join(\"?\");\n } else {\n const prefix = placeholder === \"$n\" ? \"$\" : \":\";\n const parts = new Array<string>(len * 2 - 1);\n parts[0] = strings[0]!;\n for (let i = 1; i < len; i++) {\n parts[i * 2 - 1] = prefix + i;\n parts[i * 2] = strings[i]!;\n }\n result = parts.join(\"\");\n }\n\n const statements = this.statements ?? {};\n statements[placeholder] = result;\n this.statements = statements;\n\n return result;\n }\n}\n\n/**\n * Splice text into a statement verbatim — nothing here is bound as a\n * parameter. Two shapes live under this one name:\n *\n * - `raw(\"ORDER BY name DESC\")` — Prisma's unsafe string splice. The caller\n * owns the escaping; never hand it user input.\n * - ``raw`TRUE` `` — the tagged-template form the adapters use for dialect\n * keywords. Interpolations are refused; use `sql` for bound values.\n */\nfunction raw(value: string | readonly string[]): Sql;\nfunction raw(\n strings: string | readonly string[],\n ...values: readonly RawValue[]\n): Sql {\n if (\n values.length !== 0 ||\n (typeof strings !== \"string\" && strings.length !== 1)\n )\n throw new TypeError(\n \"raw templates cannot interpolate values; use sql for parameters or raw(trustedText) for explicit SQL text.\"\n );\n if (typeof strings === \"string\") {\n return new Sql([strings], []);\n }\n return new Sql(strings, []);\n}\n\n/**\n * Create a SQL query for a list of values.\n *\n * Values are `RawValue`s, matching Prisma: a nested `Sql` is spliced as a\n * fragment, anything else becomes a bound parameter.\n */\nfunction join(\n values: readonly RawValue[],\n separator = \",\",\n prefix = \"\",\n suffix = \"\"\n) {\n const len = values.length;\n if (len === 0) {\n return new Sql([prefix + suffix], []);\n }\n\n // Pre-allocate array with exact size instead of spread + fill\n const strings = new Array<string>(len + 1);\n strings[0] = prefix;\n for (let i = 1; i < len; i++) {\n strings[i] = separator;\n }\n strings[len] = suffix;\n\n return new Sql(strings, values);\n}\n\n/**\n * Placeholder value for \"no text\".\n */\nconst empty = raw``;\n\n/**\n * Create a SQL object from a template string.\n */\nfunction sql(strings: readonly string[], ...values: readonly RawValue[]) {\n return new Sql(strings, values);\n}\n\nconst sqlTag = Object.assign(sql, { raw, empty, join });\n\nexport { empty, join, raw, sqlTag as sql };\n\n/**\n * Type guard for Sql fragments. Structural check rather than instanceof so it\n * also matches fragments from a duplicated module instance. A document with\n * strings/values arrays is data; executable SQL also has the renderer method.\n */\nexport function isSql(value: unknown): value is Sql {\n if (value instanceof Sql) return true;\n if (value === null || typeof value !== \"object\") return false;\n\n const strings = Reflect.get(value, \"strings\");\n if (!Array.isArray(strings)) return false;\n\n const values = Reflect.get(value, \"values\");\n return (\n Array.isArray(values) &&\n strings.length === values.length + 1 &&\n strings.every((part) => typeof part === \"string\") &&\n typeof Reflect.get(value, \"toStatement\") === \"function\"\n );\n}\n"],"mappings":"yCA2BA,IAAa,EAAb,MAAa,GAAI,CACf,WACA,UAEA,WACA,WAEA,YAAY,EAA+B,EAAgC,CACzE,GAAI,EAAW,OAAS,IAAM,EAAU,OAItC,MAHI,EAAW,SAAW,EACd,UAAU,6BAA6B,CAEzC,UACR,YAAY,EAAW,OAAO,mBAC5B,EAAW,OAAS,EACrB,SACF,CAGH,KAAK,WAAa,EAClB,KAAK,UAAY,EAGnB,IAAI,QAAkB,CACpB,OAAO,KAAK,SAAS,CAAC,OAGxB,IAAI,SAAoB,CACtB,OAAO,KAAK,SAAS,CAAC,QASxB,SAAiC,CAC/B,GAAI,KAAK,aAAe,IAAA,GACtB,OAAO,KAAK,WAGd,IAAM,EAAoB,EAAE,CACtB,EAAkB,EAAE,CACtB,EAAU,GAER,MACJ,EACA,IACS,CACT,GAAW,EAAW,GACtB,IAAK,IAAI,EAAI,EAAG,EAAI,EAAU,OAAQ,IAAK,CACzC,IAAM,EAAQ,EAAU,GACpB,aAAiB,IACnB,KAAK,EAAM,WAAY,EAAM,UAAU,EAEvC,EAAO,KAAK,EAAM,CAClB,EAAQ,KAAK,EAAQ,CACrB,EAAU,IAEZ,GAAW,EAAW,EAAI,KAI9B,KAAK,KAAK,WAAY,KAAK,UAAU,CACrC,EAAQ,KAAK,EAAQ,CAErB,IAAM,EAA4B,CAAE,UAAS,SAAQ,CAMrD,MAJA,MAAK,WAAa,EAClB,KAAK,UAAY,EACjB,KAAK,WAAa,EAEX,EAOT,YAAY,EAA2B,IAAa,CAClD,IAAM,EAAS,KAAK,aAAa,GACjC,GAAI,IAAW,IAAA,GAAW,OAAO,EAEjC,IAAM,EAAU,KAAK,QACf,EAAM,EAAQ,OAEpB,GAAI,IAAQ,EAAG,CACb,IAAMA,EAAS,EAAQ,GAEvB,MADA,MAAK,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