viborm 1.14.2 → 1.16.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/dist/adapter-namespace-DwFnfpED.mjs +2 -0
- package/dist/{adapter-namespace-DaRiTIIf.mjs.map → adapter-namespace-DwFnfpED.mjs.map} +1 -1
- package/dist/adapters.d.mts +26 -10
- package/dist/adapters.mjs +1 -1
- package/dist/args-7WgBFd_f.mjs +2 -0
- package/dist/{args-764KdWMr.mjs.map → args-7WgBFd_f.mjs.map} +1 -1
- package/dist/array-literal-BOzj0E2u.mjs +2 -0
- package/dist/{array-literal-DHinAnVs.mjs.map → array-literal-BOzj0E2u.mjs.map} +1 -1
- package/dist/base-17NSFtrA.mjs +2 -0
- package/dist/base-17NSFtrA.mjs.map +1 -0
- package/dist/batch-refs-Bd8HvwUc.mjs +2 -0
- package/dist/{batch-refs-C-gx7A4-.mjs.map → batch-refs-Bd8HvwUc.mjs.map} +1 -1
- package/dist/better-auth.d.mts +116 -0
- package/dist/better-auth.mjs +6 -0
- package/dist/better-auth.mjs.map +1 -0
- package/dist/bind-parameter-capacity-BAFQM9Jt.mjs +2 -0
- package/dist/{bind-parameter-capacity-BMD-bxMO.mjs.map → bind-parameter-capacity-BAFQM9Jt.mjs.map} +1 -1
- package/dist/bun-sql.d.mts +1 -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/bun-sqlite.mjs.map +1 -1
- package/dist/cache/cloudflare-kv.d.mts +1 -1
- package/dist/cache/cloudflare-kv.mjs +1 -1
- package/dist/cache/cloudflare-kv.mjs.map +1 -1
- package/dist/cache/memory.d.mts +1 -1
- package/dist/cache/memory.mjs +1 -1
- package/dist/cache/memory.mjs.map +1 -1
- package/dist/cache.d.mts +2 -2
- package/dist/cache.mjs +1 -1
- package/dist/cache.mjs.map +1 -1
- package/dist/call-0bd_B9Vp.mjs +2 -0
- package/dist/{call-Cz8XUmrl.mjs.map → call-0bd_B9Vp.mjs.map} +1 -1
- package/dist/cli.mjs +6 -6
- package/dist/cli.mjs.map +1 -1
- package/dist/client-D7sWgUt2.mjs +2 -0
- package/dist/client-D7sWgUt2.mjs.map +1 -0
- package/dist/client-DEfFqv4S.mjs +9 -0
- package/dist/client-DEfFqv4S.mjs.map +1 -0
- package/dist/{client-CRxfhw2y.d.mts → client-Dlz3-2JC.d.mts} +3 -3
- package/dist/client.d.mts +3 -3
- package/dist/client.mjs +1 -1
- package/dist/client.mjs.map +1 -1
- package/dist/config.d.mts +2 -2
- package/dist/config.mjs +1 -1
- package/dist/confine-CyI9IwjC.mjs +2 -0
- package/dist/{confine-DqFBTUw6.mjs.map → confine-CyI9IwjC.mjs.map} +1 -1
- package/dist/coordination-BxMskOgi.mjs +2 -0
- package/dist/coordination-BxMskOgi.mjs.map +1 -0
- package/dist/d1.d.mts +2 -30
- package/dist/d1.mjs +1 -1
- package/dist/d1.mjs.map +1 -1
- package/dist/{database-adapter-BGqvjeEy.d.mts → database-adapter-BMjJiBFm.d.mts} +8476 -8386
- package/dist/datetime-physical-codec-DAF7WJpy.mjs +2 -0
- package/dist/datetime-physical-codec-DAF7WJpy.mjs.map +1 -0
- package/dist/defaults-DAPb-tJ4.mjs +2 -0
- package/dist/{defaults-DwOHWI_M.mjs.map → defaults-DAPb-tJ4.mjs.map} +1 -1
- package/dist/{document-BVTQ-cF-.d.mts → document-CHaVF7Vn.d.mts} +36 -2
- package/dist/{driver-BBEmaJZy.d.mts → driver-BvTixv-m.d.mts} +1 -1
- package/dist/driver-diagnostics-aQ54bArn.mjs +2 -0
- package/dist/{driver-diagnostics-DW9NdckJ.mjs.map → driver-diagnostics-aQ54bArn.mjs.map} +1 -1
- package/dist/driver-kiIQS_Fd.mjs +2 -0
- package/dist/driver-kiIQS_Fd.mjs.map +1 -0
- package/dist/driver-lShUkDmf.mjs +2 -0
- package/dist/driver-lShUkDmf.mjs.map +1 -0
- package/dist/driver.d.mts +1 -1
- package/dist/driver.mjs +1 -1
- package/dist/durable-object.d.mts +1 -1
- package/dist/durable-object.mjs +2 -2
- package/dist/durable-object.mjs.map +1 -1
- package/dist/error-mapping-B9rSvgG9.mjs +2 -0
- package/dist/error-mapping-B9rSvgG9.mjs.map +1 -0
- package/dist/every-JpbiHdMb.mjs +2 -0
- package/dist/{every-tOgQmaIE.mjs.map → every-JpbiHdMb.mjs.map} +1 -1
- package/dist/execution-context-couU2tgh.mjs +2 -0
- package/dist/execution-context-couU2tgh.mjs.map +1 -0
- package/dist/{exports-COCJ8f2f.d.mts → exports-DYnTfvQo.d.mts} +1 -1
- package/dist/extension-Dh1ddrlA.mjs +2 -0
- package/dist/{extension-CGepsF-p.mjs.map → extension-Dh1ddrlA.mjs.map} +1 -1
- package/dist/fs-estate-n-QpsFqb.mjs +2 -0
- package/dist/{fs-estate-D1Nsg9G1.mjs.map → fs-estate-n-QpsFqb.mjs.map} +1 -1
- package/dist/geo-area-codec-Bti2PA2i.mjs +2 -0
- package/dist/geo-area-codec-Bti2PA2i.mjs.map +1 -0
- package/dist/id-domain-Cg65TLZ-.mjs +2 -0
- package/dist/id-domain-Cg65TLZ-.mjs.map +1 -0
- package/dist/identifier-conversion-BTDxDwDB.mjs +2 -0
- package/dist/identifier-conversion-BTDxDwDB.mjs.map +1 -0
- package/dist/identifiers-BxOf57qy.mjs +2 -0
- package/dist/identifiers-BxOf57qy.mjs.map +1 -0
- package/dist/identity-CJlRQA-m.mjs +2 -0
- package/dist/identity-CJlRQA-m.mjs.map +1 -0
- 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/instrumentation.mjs.map +1 -1
- package/dist/introspect-q3Rf_Xv8.mjs +2 -0
- package/dist/introspect-q3Rf_Xv8.mjs.map +1 -0
- package/dist/json-CsAdz9pg.mjs +2 -0
- package/dist/json-CsAdz9pg.mjs.map +1 -0
- package/dist/json-number-C09rsm1g.mjs +2 -0
- package/dist/{json-number-AI-SdUUn.mjs.map → json-number-C09rsm1g.mjs.map} +1 -1
- package/dist/json-parameter-D7hDrVKw.mjs +2 -0
- package/dist/{json-parameter-oQ8nGaKr.mjs.map → json-parameter-D7hDrVKw.mjs.map} +1 -1
- package/dist/judge-words-k5GCc4cV.mjs +2 -0
- package/dist/judge-words-k5GCc4cV.mjs.map +1 -0
- package/dist/key-BDH6oTyC.mjs +2 -0
- package/dist/key-BDH6oTyC.mjs.map +1 -0
- package/dist/keys-CIal55WQ.mjs +2 -0
- package/dist/{keys-BQxM4c_a.mjs.map → keys-CIal55WQ.mjs.map} +1 -1
- package/dist/keys-DZdKAd4n.mjs +2 -0
- package/dist/keys-DZdKAd4n.mjs.map +1 -0
- package/dist/libsql-DEZ0uhK2.mjs +3 -0
- package/dist/libsql-DEZ0uhK2.mjs.map +1 -0
- package/dist/libsql.d.mts +2 -20
- package/dist/libsql.mjs +1 -1
- package/dist/libsql.mjs.map +1 -1
- package/dist/light-D2wNSbzY.mjs +2 -0
- package/dist/{light-BkJe3-yW.mjs.map → light-D2wNSbzY.mjs.map} +1 -1
- package/dist/memory-BaGWNdvk.mjs +2 -0
- package/dist/{memory-G4cSuc6A.mjs.map → memory-BaGWNdvk.mjs.map} +1 -1
- package/dist/methods-part-BaNx3o7b.mjs +2 -0
- package/dist/methods-part-BaNx3o7b.mjs.map +1 -0
- 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/snowflake.d.mts +5 -5
- package/dist/migrations/snowflake.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/durable-object.mjs.map +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/storage/r2.mjs.map +1 -1
- package/dist/migrations/surrealdb.d.mts +5 -5
- package/dist/migrations/surrealdb.mjs +1 -1
- package/dist/migrations/tenant.d.mts +3 -3
- package/dist/migrations/tenant.mjs +1 -1
- package/dist/migrations/tenant.mjs.map +1 -1
- package/dist/migrations-DIUltjr3.mjs +2 -0
- package/dist/{migrations-BMiRjR-N.mjs.map → migrations-DIUltjr3.mjs.map} +1 -1
- package/dist/migrations.d.mts +5 -5
- package/dist/migrations.mjs +1 -1
- package/dist/model-Dtd37Sky.mjs +2 -0
- package/dist/model-Dtd37Sky.mjs.map +1 -0
- package/dist/mysql-BFPF8xyv.mjs +9 -0
- package/dist/mysql-BFPF8xyv.mjs.map +1 -0
- package/dist/mysql-adapter-BFWYPoM0.mjs +2 -0
- package/dist/mysql-adapter-BFWYPoM0.mjs.map +1 -0
- package/dist/mysql2.d.mts +2 -27
- package/dist/mysql2.mjs +1 -1
- package/dist/mysql2.mjs.map +1 -1
- package/dist/named-statements-CkOOD__I.mjs +2 -0
- package/dist/named-statements-CkOOD__I.mjs.map +1 -0
- package/dist/named-statements-NF7Iycjk.d.mts +13 -0
- package/dist/native-types-1ewJXVks.mjs +2 -0
- package/dist/native-types-1ewJXVks.mjs.map +1 -0
- package/dist/neon-http.d.mts +1 -1
- package/dist/neon-http.mjs +1 -1
- package/dist/neon-http.mjs.map +1 -1
- package/dist/normalized-result-D7nVkF36.mjs +2 -0
- package/dist/normalized-result-D7nVkF36.mjs.map +1 -0
- package/dist/{object-store-B_YMoW8u.d.mts → object-store-C4qmW7xf.d.mts} +4 -4
- package/dist/object-store-Chq1PMYz.mjs +2 -0
- package/dist/object-store-Chq1PMYz.mjs.map +1 -0
- package/dist/on-ZkOVmE4-.mjs +2 -0
- package/dist/{on-ylYaKuRu.mjs.map → on-ZkOVmE4-.mjs.map} +1 -1
- package/dist/on.d.mts +1 -1
- package/dist/on.mjs +1 -1
- package/dist/on.mjs.map +1 -1
- package/dist/ordering/keys.mjs +1 -1
- package/dist/ordering.d.mts +9 -3
- package/dist/ordering.mjs +10 -10
- package/dist/ordering.mjs.map +1 -1
- package/dist/pending-operation-D4gUKMxD.mjs +2 -0
- package/dist/pending-operation-D4gUKMxD.mjs.map +1 -0
- package/dist/permissions.d.mts +1 -1
- package/dist/permissions.mjs +1 -1
- package/dist/permissions.mjs.map +1 -1
- package/dist/pg.d.mts +16 -99
- 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-DO4PEYcc.mjs +2 -0
- package/dist/physical-DO4PEYcc.mjs.map +1 -0
- package/dist/pinned-session-Y7-2pRBJ.mjs +2 -0
- package/dist/pinned-session-Y7-2pRBJ.mjs.map +1 -0
- package/dist/planetscale.d.mts +1 -1
- package/dist/planetscale.mjs +1 -1
- package/dist/planetscale.mjs.map +1 -1
- package/dist/{planner-DHjdvjwk.d.mts → planner-C-zjj19U.d.mts} +123 -1
- package/dist/postgres-DQQE2ys_.mjs +34 -0
- package/dist/postgres-DQQE2ys_.mjs.map +1 -0
- package/dist/postgres-adapter-BpLizOaK.mjs +2 -0
- package/dist/{postgres-adapter-axapXX8d.mjs.map → postgres-adapter-BpLizOaK.mjs.map} +1 -1
- package/dist/postgres-adapter-psTVfuw7.mjs +2 -0
- package/dist/postgres-adapter-psTVfuw7.mjs.map +1 -0
- package/dist/postgres-result-133boRW-.mjs +2 -0
- package/dist/postgres-result-133boRW-.mjs.map +1 -0
- package/dist/postgres.d.mts +27 -59
- package/dist/postgres.mjs +1 -1
- package/dist/postgres.mjs.map +1 -1
- package/dist/provider-limits-Bcsz0EJv.mjs +2 -0
- package/dist/provider-limits-Bcsz0EJv.mjs.map +1 -0
- package/dist/provider-parameter-snapshot-cyTUDutH.mjs +2 -0
- package/dist/provider-parameter-snapshot-cyTUDutH.mjs.map +1 -0
- package/dist/quantized-BKBs0joq.mjs +2 -0
- package/dist/quantized-BKBs0joq.mjs.map +1 -0
- package/dist/query-BTb6iakn.mjs +2 -0
- package/dist/query-BTb6iakn.mjs.map +1 -0
- package/dist/query-backend-TisPjCPF.mjs +2 -0
- package/dist/query-backend-TisPjCPF.mjs.map +1 -0
- package/dist/query-inspection-DwYBKSDG.mjs +2 -0
- package/dist/query-inspection-DwYBKSDG.mjs.map +1 -0
- package/dist/raw-DqEb71JZ.mjs +2 -0
- package/dist/raw-DqEb71JZ.mjs.map +1 -0
- package/dist/relation-bound-CSNKLyDy.mjs +2 -0
- package/dist/{relation-bound-ku_cMdye.mjs.map → relation-bound-CSNKLyDy.mjs.map} +1 -1
- package/dist/result-parsing-BbffueEX.mjs +2 -0
- package/dist/{result-parsing-B0Y4KGDT.mjs.map → result-parsing-BbffueEX.mjs.map} +1 -1
- package/dist/routed-operations-CcKOdn51.mjs +2 -0
- package/dist/{routed-operations-wytpbYKv.mjs.map → routed-operations-CcKOdn51.mjs.map} +1 -1
- package/dist/rows-of-Bgl9GVtK.mjs +2 -0
- package/dist/rows-of-Bgl9GVtK.mjs.map +1 -0
- package/dist/rule-words-DMbQuvD2.mjs +2 -0
- package/dist/{rule-words-ZIGm7cDm.mjs.map → rule-words-DMbQuvD2.mjs.map} +1 -1
- package/dist/scalar-Dm9brvAU.mjs +4 -0
- package/dist/scalar-Dm9brvAU.mjs.map +1 -0
- package/dist/schema/introspect.d.mts +2 -2
- package/dist/schema/introspect.mjs +1 -1
- package/dist/schema/json.d.mts +6 -4
- package/dist/schema/json.mjs +1 -1
- package/dist/schema-DDkAUfOb.mjs +2 -0
- package/dist/schema-DDkAUfOb.mjs.map +1 -0
- package/dist/schema-DqR_Kcje.mjs +2 -0
- package/dist/schema-DqR_Kcje.mjs.map +1 -0
- package/dist/schema-introspection-Bbo4DN_d.mjs +4 -0
- package/dist/schema-introspection-Bbo4DN_d.mjs.map +1 -0
- package/dist/schema.d.mts +2 -2
- package/dist/schema.mjs +1 -1
- package/dist/select-assembly-CEpNu-Gw.mjs +2 -0
- package/dist/select-assembly-CEpNu-Gw.mjs.map +1 -0
- package/dist/serializer-ettLu5xG.mjs +33 -0
- package/dist/serializer-ettLu5xG.mjs.map +1 -0
- package/dist/settle-Pui-1tfJ.mjs +2 -0
- package/dist/{settle-1cy5x_52.mjs.map → settle-Pui-1tfJ.mjs.map} +1 -1
- package/dist/settled-DYYPcaBX.mjs +2 -0
- package/dist/{settled-BjyuA76m.mjs.map → settled-DYYPcaBX.mjs.map} +1 -1
- package/dist/snowflake-BfF8xwfP.mjs +2 -0
- package/dist/{snowflake-UOCC820W.mjs.map → snowflake-BfF8xwfP.mjs.map} +1 -1
- package/dist/snowflake.d.mts +3 -3
- package/dist/snowflake.mjs +2 -2
- package/dist/snowflake.mjs.map +1 -1
- package/dist/soft-delete.d.mts +9 -3
- package/dist/soft-delete.mjs +1 -1
- package/dist/soft-delete.mjs.map +1 -1
- package/dist/{spans-XDUFeTzC.mjs → spans-DwDXMvyd.mjs} +1 -1
- package/dist/{spans-XDUFeTzC.mjs.map → spans-DwDXMvyd.mjs.map} +1 -1
- package/dist/sql-Bu63iAfT.mjs +2 -0
- package/dist/sql-Bu63iAfT.mjs.map +1 -0
- package/dist/{sql-BVZ8QefY.d.mts → sql-C4_sFNDm.d.mts} +18 -5
- package/dist/sql-statement-tokens-Z5Ta4iDB.mjs +3 -0
- package/dist/{sql-statement-tokens-DbeMwHra.mjs.map → sql-statement-tokens-Z5Ta4iDB.mjs.map} +1 -1
- package/dist/sql-tegqTqGq.mjs +2 -0
- package/dist/sql-tegqTqGq.mjs.map +1 -0
- package/dist/sql.d.mts +1 -1
- package/dist/sql.mjs +1 -1
- package/dist/sqlite-adapter-Cb-SJw2f.mjs +2 -0
- package/dist/sqlite-adapter-Cb-SJw2f.mjs.map +1 -0
- package/dist/sqlite-statement-classifier-JBHiQO6Q.mjs +2 -0
- package/dist/{sqlite-statement-classifier-BAHl-WXS.mjs.map → sqlite-statement-classifier-JBHiQO6Q.mjs.map} +1 -1
- package/dist/sqlite-utils-Bfmtkt1b.mjs +2 -0
- package/dist/sqlite-utils-Bfmtkt1b.mjs.map +1 -0
- package/dist/sqlite3.d.mts +2 -46
- package/dist/sqlite3.mjs +1 -1
- package/dist/sqlite3.mjs.map +1 -1
- package/dist/standard-sql-Bl2OHGfi.mjs +6 -0
- package/dist/standard-sql-Bl2OHGfi.mjs.map +1 -0
- package/dist/suppressed-failure-CFUDJrUw.mjs +2 -0
- package/dist/{suppressed-failure-CQkQsMVS.mjs.map → suppressed-failure-CFUDJrUw.mjs.map} +1 -1
- package/dist/surrealdb.d.mts +2 -2
- package/dist/surrealdb.mjs +1 -1
- package/dist/surrealdb.mjs.map +1 -1
- package/dist/surrealql-DY74AUeD.mjs +2 -0
- package/dist/surrealql-DY74AUeD.mjs.map +1 -0
- package/dist/time-step-DJaIhpAz.mjs +2 -0
- package/dist/time-step-DJaIhpAz.mjs.map +1 -0
- package/dist/transaction-Bv5nyp-U.mjs +2 -0
- package/dist/{transaction-BNomMtme.mjs.map → transaction-Bv5nyp-U.mjs.map} +1 -1
- package/dist/transaction-operation-CaWzo7gE.mjs +2 -0
- package/dist/{transaction-operation-CVVJxQ19.mjs.map → transaction-operation-CaWzo7gE.mjs.map} +1 -1
- package/dist/types-Dy33vBdd.mjs +2 -0
- package/dist/{types-DtDnXhwa.mjs.map → types-Dy33vBdd.mjs.map} +1 -1
- package/dist/unit-DUPX5Sdd.mjs +2 -0
- package/dist/{unit-BhHbZyuJ.mjs.map → unit-DUPX5Sdd.mjs.map} +1 -1
- package/dist/unit-words-BXpLpyr2.mjs +2 -0
- package/dist/{unit-words-CT0yeqfZ.mjs.map → unit-words-BXpLpyr2.mjs.map} +1 -1
- package/dist/utils-BHkJsduV.mjs +26 -0
- package/dist/{utils-CpAojrCj.mjs.map → utils-BHkJsduV.mjs.map} +1 -1
- package/dist/v1-parse-shared-cJ-uD14P.mjs +2 -0
- package/dist/v1-parse-shared-cJ-uD14P.mjs.map +1 -0
- package/dist/validation-ATmgN5RE.mjs +2 -0
- package/dist/validation-ATmgN5RE.mjs.map +1 -0
- package/dist/validation-BHjx13zG.mjs +2 -0
- package/dist/validation-BHjx13zG.mjs.map +1 -0
- package/dist/validation.d.mts +1 -1
- package/dist/validation.mjs +1 -1
- package/dist/validator-DMzH5Tz0.mjs +2 -0
- package/dist/validator-DMzH5Tz0.mjs.map +1 -0
- package/dist/value-guards-CBVIJXlI.mjs +2 -0
- package/dist/{value-guards-CBuxSC66.mjs.map → value-guards-CBVIJXlI.mjs.map} +1 -1
- package/dist/values-Ch2cTlss.mjs +2 -0
- package/dist/{values-B4aj1i1f.mjs.map → values-Ch2cTlss.mjs.map} +1 -1
- package/dist/version-0BDwfy7C.mjs +2 -0
- package/dist/{version-CXGIA82S.mjs.map → version-0BDwfy7C.mjs.map} +1 -1
- package/dist/view-CHgjF2BO.mjs +2 -0
- package/dist/view-CHgjF2BO.mjs.map +1 -0
- package/dist/write-sinks-Bei5vFHP.mjs +2 -0
- package/dist/{write-sinks-3IKCDF-S.mjs.map → write-sinks-Bei5vFHP.mjs.map} +1 -1
- package/package.json +50 -37
- package/dist/adapter-internals-DOqI8IlQ.mjs +0 -2
- package/dist/adapter-internals-DOqI8IlQ.mjs.map +0 -1
- package/dist/adapter-namespace-DaRiTIIf.mjs +0 -2
- package/dist/adapter-result-parser-3WP82Cm-.mjs +0 -2
- package/dist/adapter-result-parser-3WP82Cm-.mjs.map +0 -1
- package/dist/args-764KdWMr.mjs +0 -2
- package/dist/array-literal-DHinAnVs.mjs +0 -2
- package/dist/base-z-cH5ZBI.mjs +0 -2
- package/dist/base-z-cH5ZBI.mjs.map +0 -1
- package/dist/batch-refs-C-gx7A4-.mjs +0 -2
- package/dist/bind-parameter-capacity-BMD-bxMO.mjs +0 -2
- package/dist/call-Cz8XUmrl.mjs +0 -2
- package/dist/canonical-json-Bl-fKFF_.mjs +0 -2
- package/dist/canonical-json-Bl-fKFF_.mjs.map +0 -1
- package/dist/chunk-BuuaeEvq.mjs +0 -1
- package/dist/client-DRpX3-vw.mjs +0 -2
- package/dist/client-DRpX3-vw.mjs.map +0 -1
- package/dist/client-y7TV0PRZ.mjs +0 -9
- package/dist/client-y7TV0PRZ.mjs.map +0 -1
- package/dist/confine-DqFBTUw6.mjs +0 -2
- package/dist/coordination-6qZHx_kl.mjs +0 -2
- package/dist/coordination-6qZHx_kl.mjs.map +0 -1
- package/dist/current-DBTlPsQg.mjs +0 -2
- package/dist/current-DBTlPsQg.mjs.map +0 -1
- package/dist/datetime-physical-codec-Dj-APo9f.mjs +0 -2
- package/dist/datetime-physical-codec-Dj-APo9f.mjs.map +0 -1
- package/dist/defaults-DwOHWI_M.mjs +0 -2
- package/dist/driver-BGVcgnIX.mjs +0 -2
- package/dist/driver-BGVcgnIX.mjs.map +0 -1
- package/dist/driver-BIXhOH2_.mjs +0 -2
- package/dist/driver-BIXhOH2_.mjs.map +0 -1
- package/dist/driver-diagnostics-DW9NdckJ.mjs +0 -2
- package/dist/error-mapping-B1-IWkCQ.mjs +0 -2
- package/dist/error-mapping-B1-IWkCQ.mjs.map +0 -1
- package/dist/every-tOgQmaIE.mjs +0 -2
- package/dist/execution-context-BXpcbyPe.mjs +0 -2
- package/dist/execution-context-BXpcbyPe.mjs.map +0 -1
- package/dist/extension-CGepsF-p.mjs +0 -2
- package/dist/fs-estate-D1Nsg9G1.mjs +0 -2
- package/dist/geo-area-codec-mHrM3b9A.mjs +0 -2
- package/dist/geo-area-codec-mHrM3b9A.mjs.map +0 -1
- package/dist/hydration-A3zffFWP.mjs +0 -2
- package/dist/hydration-A3zffFWP.mjs.map +0 -1
- package/dist/identifier-conversion-DHYPTgzr.mjs +0 -2
- package/dist/identifier-conversion-DHYPTgzr.mjs.map +0 -1
- package/dist/identifiers-s00pGES8.mjs +0 -2
- package/dist/identifiers-s00pGES8.mjs.map +0 -1
- package/dist/identity-CtW15WlB.mjs +0 -2
- package/dist/identity-CtW15WlB.mjs.map +0 -1
- package/dist/introspect-Bm6xnXcG.mjs +0 -2
- package/dist/introspect-Bm6xnXcG.mjs.map +0 -1
- package/dist/json-DgMc8-GU.mjs +0 -2
- package/dist/json-DgMc8-GU.mjs.map +0 -1
- package/dist/json-number-AI-SdUUn.mjs +0 -2
- package/dist/json-parameter-oQ8nGaKr.mjs +0 -2
- package/dist/judge-words-CzUyXtJ6.mjs +0 -2
- package/dist/judge-words-CzUyXtJ6.mjs.map +0 -1
- package/dist/key-hxFFCKed.mjs +0 -2
- package/dist/key-hxFFCKed.mjs.map +0 -1
- package/dist/keys-BQxM4c_a.mjs +0 -2
- package/dist/libsql-DuGR904j.mjs +0 -3
- package/dist/libsql-DuGR904j.mjs.map +0 -1
- package/dist/light-BkJe3-yW.mjs +0 -2
- package/dist/memory-G4cSuc6A.mjs +0 -2
- package/dist/methods-part-ZY0f2AV_.mjs +0 -2
- package/dist/methods-part-ZY0f2AV_.mjs.map +0 -1
- package/dist/migrations-BMiRjR-N.mjs +0 -2
- package/dist/mysql-BNXWfTOo.mjs +0 -100
- package/dist/mysql-BNXWfTOo.mjs.map +0 -1
- package/dist/mysql-adapter-C69j1sKh.mjs +0 -2
- package/dist/mysql-adapter-C69j1sKh.mjs.map +0 -1
- package/dist/native-types-DgjMUikz.mjs +0 -2
- package/dist/native-types-DgjMUikz.mjs.map +0 -1
- package/dist/normalized-result-B8pifWS0.mjs +0 -2
- package/dist/normalized-result-B8pifWS0.mjs.map +0 -1
- package/dist/object-store-DS0F0yZX.mjs +0 -2
- package/dist/object-store-DS0F0yZX.mjs.map +0 -1
- package/dist/on-ylYaKuRu.mjs +0 -2
- package/dist/pending-operation-C_eOFOBE.mjs +0 -2
- package/dist/pending-operation-C_eOFOBE.mjs.map +0 -1
- package/dist/physical-CeE2nYmI.mjs +0 -2
- package/dist/physical-CeE2nYmI.mjs.map +0 -1
- package/dist/pinned-session-DCoAZDOz.mjs +0 -2
- package/dist/pinned-session-DCoAZDOz.mjs.map +0 -1
- package/dist/postgres-CDdh5dSP.mjs +0 -437
- package/dist/postgres-CDdh5dSP.mjs.map +0 -1
- package/dist/postgres-adapter-Dlr3ZWd7.mjs +0 -2
- package/dist/postgres-adapter-Dlr3ZWd7.mjs.map +0 -1
- package/dist/postgres-adapter-axapXX8d.mjs +0 -2
- package/dist/postgres-result-DF6DmW3r.mjs +0 -2
- package/dist/postgres-result-DF6DmW3r.mjs.map +0 -1
- package/dist/provider-limits-Ccsb8PTb.mjs +0 -2
- package/dist/provider-limits-Ccsb8PTb.mjs.map +0 -1
- package/dist/provider-parameter-snapshot-BikrgKqI.mjs +0 -2
- package/dist/provider-parameter-snapshot-BikrgKqI.mjs.map +0 -1
- package/dist/query-BZVHfA0s.mjs +0 -2
- package/dist/query-BZVHfA0s.mjs.map +0 -1
- package/dist/query-inspection-BoG-yAln.mjs +0 -2
- package/dist/query-inspection-BoG-yAln.mjs.map +0 -1
- package/dist/raw-Dyq6Y6UX.mjs +0 -2
- package/dist/raw-Dyq6Y6UX.mjs.map +0 -1
- package/dist/relation-bound-ku_cMdye.mjs +0 -2
- package/dist/result-parsing-B0Y4KGDT.mjs +0 -2
- package/dist/routed-operations-wytpbYKv.mjs +0 -2
- package/dist/rule-words-ZIGm7cDm.mjs +0 -2
- package/dist/scalar-BHCh7aUz.mjs +0 -4
- package/dist/scalar-BHCh7aUz.mjs.map +0 -1
- package/dist/schema-BYA-_bpk.mjs +0 -2
- package/dist/schema-BYA-_bpk.mjs.map +0 -1
- package/dist/schema-CFIaebgi.mjs +0 -2
- package/dist/schema-CFIaebgi.mjs.map +0 -1
- package/dist/schema-introspection-D0f8cti4.mjs +0 -6
- package/dist/schema-introspection-D0f8cti4.mjs.map +0 -1
- package/dist/select-assembly-DVI7d3tf.mjs +0 -2
- package/dist/select-assembly-DVI7d3tf.mjs.map +0 -1
- package/dist/serializer-rBq3v1xr.mjs +0 -51
- package/dist/serializer-rBq3v1xr.mjs.map +0 -1
- package/dist/settle-1cy5x_52.mjs +0 -2
- package/dist/settled-BjyuA76m.mjs +0 -2
- package/dist/snowflake-UOCC820W.mjs +0 -2
- package/dist/sql-3o4DOKm9.mjs +0 -2
- package/dist/sql-3o4DOKm9.mjs.map +0 -1
- package/dist/sql-Dl6nykFV.mjs +0 -2
- package/dist/sql-Dl6nykFV.mjs.map +0 -1
- package/dist/sql-statement-tokens-DbeMwHra.mjs +0 -3
- package/dist/sqlite-adapter-Ad0d-m2t.mjs +0 -2
- package/dist/sqlite-adapter-Ad0d-m2t.mjs.map +0 -1
- package/dist/sqlite-statement-classifier-BAHl-WXS.mjs +0 -2
- package/dist/sqlite-utils-BRvbmlQ1.mjs +0 -2
- package/dist/sqlite-utils-BRvbmlQ1.mjs.map +0 -1
- package/dist/standard-sql-qLcQyCtK.mjs +0 -6
- package/dist/standard-sql-qLcQyCtK.mjs.map +0 -1
- package/dist/suppressed-failure-CQkQsMVS.mjs +0 -2
- package/dist/surrealql-C1dp1sWw.mjs +0 -2
- package/dist/surrealql-C1dp1sWw.mjs.map +0 -1
- package/dist/to-many-BybuKQM1.mjs +0 -2
- package/dist/to-many-BybuKQM1.mjs.map +0 -1
- package/dist/transaction-BNomMtme.mjs +0 -2
- package/dist/transaction-operation-CVVJxQ19.mjs +0 -2
- package/dist/types-DtDnXhwa.mjs +0 -2
- package/dist/unit-BhHbZyuJ.mjs +0 -2
- package/dist/unit-words-CT0yeqfZ.mjs +0 -2
- package/dist/utils-CpAojrCj.mjs +0 -26
- package/dist/validation--qS7OPmg.mjs +0 -2
- package/dist/validation--qS7OPmg.mjs.map +0 -1
- package/dist/validation-CYaJ8ndO.mjs +0 -2
- package/dist/validation-CYaJ8ndO.mjs.map +0 -1
- package/dist/validator-CZLW7aR3.mjs +0 -2
- package/dist/validator-CZLW7aR3.mjs.map +0 -1
- package/dist/value-guards-CBuxSC66.mjs +0 -2
- package/dist/values-B4aj1i1f.mjs +0 -2
- package/dist/version-CXGIA82S.mjs +0 -2
- package/dist/write-sinks-3IKCDF-S.mjs +0 -2
- /package/dist/{contract-CrIB-3ZJ.d.mts → contract-CxJn0_cV.d.mts} +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"scalar-Dm9brvAU.mjs","names":["v","state"],"sources":["../src/schema/registration-preflight.ts","../src/schema/validation/error.ts","../src/schema/scalars/native-catalog.ts","../src/validation/primitives/sha3.ts","../src/schema/scalars/string/autogenerate.ts","../src/schema/scalars/string/scalar.ts"],"sourcesContent":["import type { Model } from \"./model\";\nimport type { SchemaValidationIssue } from \"./validation/types\";\n\n/**\n * Prove that every model object in one registration batch has one schema key.\n *\n * The model's hydrated name is the lifetime claim. The local map covers the\n * still-unhydrated batch, so `{ alpha: shared, beta: shared }` is refused before\n * hydration writes either name. Repeating the same object under the same key is\n * deliberately idempotent.\n */\nexport function preflightModelRegistrationIdentity(\n registrations: Iterable<readonly [string, Model<any>]>\n): SchemaValidationIssue | undefined {\n const claimedInThisPass = new Map<Model<any>, string>();\n for (const [modelKey, model] of registrations) {\n if (\n model === null ||\n typeof model !== \"object\" ||\n !model[\"~\"]?.names ||\n !model[\"~\"]?.state?.scalars\n )\n return {\n code: \"M008\",\n message: `Schema entry '${modelKey}' is not an s.model()`,\n severity: \"error\",\n model: modelKey,\n };\n const claimed = model[\"~\"].names.ts ?? claimedInThisPass.get(model);\n if (claimed !== undefined && claimed !== modelKey)\n return {\n code: \"M003\",\n message: `Model '${claimed}' cannot also register as '${modelKey}'`,\n severity: \"error\",\n model: modelKey,\n };\n claimedInThisPass.set(model, modelKey);\n }\n return;\n}\n","import { VibORMError, VibORMErrorCode } from \"../../errors/base\";\nimport type { SchemaValidationIssue } from \"./types\";\n\nexport class SchemaValidationError extends VibORMError {\n static override readonly diagnosticName = \"SchemaValidationError\";\n\n declare readonly code: typeof VibORMErrorCode.INVALID_INPUT;\n readonly issues: readonly SchemaValidationIssue[];\n\n constructor(\n issues: readonly SchemaValidationIssue[],\n options?: { cause?: Error | undefined }\n ) {\n // `candidates` is the one array-valued field, so the snapshot freezes it\n // too: a shallow freeze would publish an immutable issue wrapping a\n // caller-mutable list.\n const snapshot = Object.freeze(\n issues.map((issue) =>\n Object.freeze(\n issue.candidates\n ? { ...issue, candidates: Object.freeze([...issue.candidates]) }\n : { ...issue }\n )\n )\n );\n const messages = snapshot.map((issue) =>\n [\n `[${issue.code}] ${issue.message}`,\n issue.candidates?.length\n ? `Candidates: ${issue.candidates.join(\", \")}`\n : \"\",\n issue.repair ?? \"\",\n ]\n .filter(Boolean)\n .join(\"\\n\")\n );\n super(\n `Schema validation failed:\\n${messages.join(\"\\n\")}`,\n VibORMErrorCode.INVALID_INPUT,\n options?.cause ? { cause: options.cause } : undefined\n );\n this.issues = snapshot;\n }\n\n override toJSON(): Record<string, unknown> {\n return { ...super.toJSON(), issues: this.issues };\n }\n}\n\nexport function isSchemaValidationError(\n error: unknown\n): error is SchemaValidationError {\n return error instanceof SchemaValidationError;\n}\n\nexport function err(\n code: string,\n message: string,\n extra?: Omit<SchemaValidationIssue, \"code\" | \"message\" | \"severity\">\n): SchemaValidationIssue {\n return { code, message, severity: \"error\", ...extra };\n}\n\nexport function warn(\n code: string,\n message: string,\n extra?: Omit<SchemaValidationIssue, \"code\" | \"message\" | \"severity\">\n): SchemaValidationIssue {\n return { code, message, severity: \"warning\", ...extra };\n}\n\nexport function relErr(\n code: string,\n model: string,\n relation: string,\n message: string,\n repair: string,\n extra?: Pick<SchemaValidationIssue, \"field\" | \"candidates\">\n): SchemaValidationIssue {\n return {\n code,\n message,\n severity: \"error\",\n model,\n relation,\n repair,\n ...extra,\n };\n}\n\n/**\n * ONE reading of a value pulled out of a `catch`, shared by every gate boundary\n * that turns a throw into a diagnostic.\n *\n * The throwers this gate catches are all in-repo and all throw `Error`s — the\n * target once-cell normalizes before the resolver ever sees a getter's throw,\n * and the physical-name owner throws its own error type. Each catch site\n * spelling this narrowing itself made three owners for one rule and three arms\n * that no schema can reach; the narrowing lives here instead, where it is\n * witnessed directly.\n */\nexport function thrownAsError(thrown: unknown): Error {\n return thrown instanceof Error ? thrown : new Error(String(thrown));\n}\n","// The closed per-dialect native-type catalog, and the scalar factories' one\n// native-type admission.\n//\n// A native type's `type` is the ONE declaration string a migration driver emits\n// into DDL verbatim — the three drivers write it as a column's type with no\n// escaping, because a coded schema takes it from a typed constant. A schema\n// document is written by whoever hands you one, so it decides what may occupy\n// that position here. Coded maps and tagged declarations share the historical\n// trusted schema-author escape hatch for custom type spellings. The round-1 answer was a word grammar; the reviewer proved it cannot\n// work: `TEXT REFERENCES victims(id)`, `TEXT UNIQUE` and `TEXT CHECK(0)` are\n// letters and spaces with an optional parenthesized group, indistinguishable\n// from a multi-word type name, yet each appends a CONSTRAINT to a column in DDL.\n// No regex over arbitrary SQL words separates a type from a clause.\n//\n// So the admissible set is CLOSED and derived, per dialect, from the one owner\n// that already enumerates native types: the shipped `PG`/`MYSQL`/`SQLITE`\n// constant trees. Derivation, not duplication —\n//\n// - a string leaf (`{ db, type: \"text\" }`) contributes its EXACT value;\n// - a function leaf (a parameterized type) is probe-called at zero, one and\n// two integer arguments to learn its base name and which argument arities it\n// publishes; the catalog then admits that base bare, or with one or two\n// INTEGER arguments, at exactly those arities.\n//\n// The trees produce no word-argument type THROUGH A FUNCTION — `geometry(Point)`\n// is a string leaf, matched exactly — so there is no word-argument rule, which\n// is the narrowest rule the trees justify. A coded schema's constants are\n// catalog members by construction. The schema-document reader and serializer\n// consult this owner for the tagged `native` form; `admitNativeType` validates coded maps structurally. A TAGGED declaration written in code keeps its historical\n// open contract (a custom `{ db, type }` still reaches DDL as written) — only a\n// document refuses one outside the catalog. Nothing downstream sanitizes native\n// types, and nothing can.\n//\n// This lives beside `native-types.ts` rather than in the document module because\n// the scalar factories need it; it imports the constant trees, so the trees'\n// module cannot import it back.\n\nimport { isRecord } from \"@validation/value-guards\";\nimport { mapGet } from \"../record\";\nimport { refuseBuilder } from \"./common\";\nimport {\n type DialectNativeType,\n isTaggedNativeType,\n MYSQL,\n NATIVE_DIALECTS,\n type NativeDialect,\n type NativeTypeDeclaration,\n type NativeTypeMap,\n PG,\n SQLITE,\n} from \"./native-types\";\n\ntype Dialect = NativeDialect;\n\ntype DialectCatalog = {\n /** The exact type strings every string leaf produces. */\n readonly exact: Set<string>;\n /** A parameterized base name → the argument arities it publishes (0 = bare). */\n readonly templates: Map<string, Set<number>>;\n};\n\n/** Distinct non-zero probe arguments, so a produced form is unambiguous. */\nconst PROBE_ARGUMENTS: readonly number[][] = [[], [1], [1, 2]];\n\n/** A parameterized-type argument the trees produce: a non-negative integer. */\nconst INTEGER_ARGUMENT = /^\\d+$/;\n\nconst TYPE_EXPRESSION = /^[A-Za-z_][A-Za-z0-9_]*(\\(\\d+(,\\d+)*\\))?$/;\n\nconst CONSTANT_NAMES: Record<Dialect, string> = {\n pg: \"PG\",\n mysql: \"MYSQL\",\n sqlite: \"SQLITE\",\n};\n\nlet catalogs: Record<Dialect, DialectCatalog> | undefined;\n\nexport function isNativeTypeInCatalog(db: Dialect, type: string): boolean {\n catalogs ??= buildCatalogs();\n const catalog = catalogs[db];\n if (catalog.exact.has(type)) return true;\n if (!TYPE_EXPRESSION.test(type)) return false;\n const open = type.indexOf(\"(\");\n if (open === -1) return catalog.templates.get(type)?.has(0) === true;\n const base = type.slice(0, open);\n const arity = type.slice(open + 1, -1).split(\",\").length;\n return catalog.templates.get(base)?.has(arity) === true;\n}\n\nexport function nativeTypeRefusal(db: Dialect): string {\n return `Native type must belong to '${db}' (${CONSTANT_NAMES[db]}) catalog`;\n}\n\n// =============================================================================\n// SCALAR FACTORY ADMISSION\n// =============================================================================\n\nexport function admitNativeType(\n builder: string,\n declaration: NativeTypeDeclaration | undefined\n): NativeTypeDeclaration | undefined {\n return declaration === undefined\n ? undefined\n : admitDeclaredNativeType(builder, declaration);\n}\n\n/** A declared native type, out of line: most scalars declare none. */\nfunction admitDeclaredNativeType(\n builder: string,\n declaration: NativeTypeDeclaration\n): NativeTypeDeclaration {\n if (!isRecord(declaration)) {\n refuseBuilder(builder, \"nativeType\", \"Invalid native type\");\n }\n if (isTaggedNativeType(declaration)) {\n const { db, type } = declaration;\n if (!NATIVE_DIALECTS.includes(db) || typeof type !== \"string\") {\n refuseBuilder(\n builder,\n \"nativeType\",\n `Tagged native type needs \\`db\\` (${NATIVE_DIALECTS.join(\"/\")}) and string \\`type\\``\n );\n }\n const beside = NATIVE_DIALECTS.find((dialect) =>\n Object.hasOwn(declaration, dialect)\n );\n if (beside !== undefined) {\n refuseBuilder(\n builder,\n `nativeType.${beside}`,\n `Tagged native type ('${db}') cannot also have '${beside}' entry`\n );\n }\n return declaration;\n }\n return admitNativeTypeMap(builder, declaration);\n}\n\nfunction admitNativeTypeMap(\n builder: string,\n map: NativeTypeMap\n): NativeTypeMap {\n const snapshot: {\n pg?: DialectNativeType<\"pg\">;\n mysql?: DialectNativeType<\"mysql\">;\n sqlite?: DialectNativeType<\"sqlite\">;\n } = {};\n const keys = Object.keys(map);\n if (keys.length === 0) {\n refuseBuilder(builder, \"nativeType\", \"Native-type map is empty\");\n }\n for (const key of keys) {\n if (key === \"pg\") snapshot.pg = admitEntry(builder, key, map.pg);\n else if (key === \"mysql\")\n snapshot.mysql = admitEntry(builder, key, map.mysql);\n else if (key === \"sqlite\")\n snapshot.sqlite = admitEntry(builder, key, map.sqlite);\n else\n refuseBuilder(\n builder,\n `nativeType.${key}`,\n `Unknown dialect '${key}' (expected ${NATIVE_DIALECTS.join(\"/\")})`\n );\n }\n return Object.freeze(snapshot);\n}\n\n/** One map entry: a native type of exactly its key's dialect, in its catalog. */\nfunction admitEntry<Entry extends Dialect>(\n builder: string,\n dialect: Entry,\n entry: unknown\n): DialectNativeType<Entry> {\n const rec = isRecord(entry) ? entry : undefined;\n const db = rec?.db;\n const type = rec?.type;\n if (db !== dialect || typeof type !== \"string\") {\n refuseBuilder(\n builder,\n `nativeType.${dialect}`,\n `'${dialect}' entry must be { db: \"${dialect}\", type: string }`\n );\n }\n return Object.freeze({ db: dialect, type });\n}\n\n// =============================================================================\n// CATALOG CONSTRUCTION\n// =============================================================================\n\nfunction buildCatalogs(): Record<Dialect, DialectCatalog> {\n const build = (tree: unknown): DialectCatalog => {\n const catalog: DialectCatalog = { exact: new Set(), templates: new Map() };\n walk(tree, catalog);\n return catalog;\n };\n return { pg: build(PG), mysql: build(MYSQL), sqlite: build(SQLITE) };\n}\n\nfunction walk(node: any, catalog: DialectCatalog): void {\n if (typeof node === \"function\") {\n deriveFunction(node, catalog);\n return;\n }\n if (typeof node.type === \"string\") {\n catalog.exact.add(node.type);\n return;\n }\n for (const value of Object.values(node)) walk(value, catalog);\n}\n\n/** A parameterized-type leaf, called generically — hence the erased type. */\nfunction deriveFunction(factory: any, catalog: DialectCatalog): void {\n for (const args of PROBE_ARGUMENTS) {\n const type: string = factory(...args).type;\n const open = type.indexOf(\"(\");\n if (open === -1) {\n mapGet(catalog.templates, type, () => new Set()).add(0);\n continue;\n }\n const parts = type.slice(open + 1, -1).split(\",\");\n if (parts.every((part) => INTEGER_ARGUMENT.test(part))) {\n mapGet(catalog.templates, type.slice(0, open), () => new Set()).add(\n parts.length\n );\n }\n }\n}\n","// biome-ignore-all lint/suspicious/noBitwiseOperators: Keccak-f[1600] is a bit\n// permutation. Every operator below is part of the published specification's\n// arithmetic, carried on 32-bit halves because JavaScript has no 64-bit word.\n\n/**\n * SHA3-512, the one hash VibORM computes.\n *\n * FIPS 202's Keccak-f[1600] over 25 lanes of 64 bits, rate 72 bytes, domain\n * padding `0x06 ... 0x80`. One exported function, no streaming, no options, no\n * configuration: the caller hands over the complete message and receives the\n * 64-byte digest.\n *\n * Each 64-bit lane is carried as TWO 32-bit halves rather than a `BigInt`.\n * JavaScript's bitwise operators are 32-bit, so a BigInt lane would allocate a\n * new arbitrary-precision value for every one of the roughly 1,200 operations a\n * single digest performs.\n *\n * Every read goes through a `DataView`, which is the one indexed read this\n * codebase has that is not `T | undefined`: a Keccak round has no in-range\n * check to make and no branch to take, so a fallback on a typed-array read\n * would be a guard whose coverage cannot be named. The halves are stored\n * little-endian at `lane * 8` and `lane * 8 + 4`, which is exactly the lane's\n * own little-endian byte layout — so absorbing a block is a word-wise XOR of\n * the message and squeezing is a copy of the first 64 bytes.\n *\n * The one caller is CUID2 (`@schema/scalars/string/autogenerate`). Nothing else\n * in VibORM may import this module without its own differential proof against a\n * reference implementation.\n */\n\n/** SHA3-512's rate: 1600 - 2*512 bits, as bytes. */\nconst RATE_BYTES = 72;\n/** 512 bits of output. */\nconst DIGEST_BYTES = 64;\nconst LANES = 25;\nconst STATE_BYTES = LANES * 8;\nconst ROUNDS = 24;\n/** SHA-3's domain separation: `01` then the pad10*1 rule's leading bit. */\nconst DOMAIN_PAD = 0x06;\n/** pad10*1's trailing bit, at the top of the block's last byte. */\nconst FINAL_PAD = 0x80;\n\n/**\n * The iota round constants, low half then high half of each round.\n *\n * Filled through the same little-endian writes every other buffer in this\n * module is filled with. A typed array would lay its bytes out in the HOST's\n * order, which is not what the read at the iota step asks for: the two would\n * agree on a little-endian machine and disagree on every other one.\n */\nconst stateBytes = new Uint8Array(STATE_BYTES);\nconst state = new DataView(stateBytes.buffer);\nconst plane = new DataView(new ArrayBuffer(STATE_BYTES));\nconst column = new DataView(new ArrayBuffer(5 * 8));\n\nconst get32 = (view: DataView, offset: number): number =>\n view.getInt32(offset, true);\nconst set32 = (view: DataView, offset: number, value: number): void =>\n view.setInt32(offset, value, true);\n\n/** Keccak-f[1600]: 24 rounds of theta, rho + pi, chi and iota. */\nfunction permute(): void {\n for (let round = 0, lfsr = 1; round < ROUNDS; round++) {\n // Theta: each column's parity, folded back into every lane of the column.\n for (let x = 0; x < 5; x++) {\n let low = 0;\n let high = 0;\n for (let y = 0; y < LANES; y += 5) {\n low ^= get32(state, (x + y) * 8);\n high ^= get32(state, (x + y) * 8 + 4);\n }\n set32(column, x * 8, low);\n set32(column, x * 8 + 4, high);\n }\n for (let x = 0; x < 5; x++) {\n const nextLow = get32(column, ((x + 1) % 5) * 8);\n const nextHigh = get32(column, ((x + 1) % 5) * 8 + 4);\n const deltaLow =\n get32(column, ((x + 4) % 5) * 8) ^ ((nextLow << 1) | (nextHigh >>> 31));\n const deltaHigh =\n get32(column, ((x + 4) % 5) * 8 + 4) ^\n ((nextHigh << 1) | (nextLow >>> 31));\n for (let y = 0; y < LANES; y += 5) {\n const at = (x + y) * 8;\n set32(state, at, get32(state, at) ^ deltaLow);\n set32(state, at + 4, get32(state, at + 4) ^ deltaHigh);\n }\n }\n\n // Rho and pi: rotate every lane and move it to its permuted position.\n set32(plane, 0, get32(state, 0));\n set32(plane, 4, get32(state, 4));\n for (let t = 0, x = 1, y = 0; t < ROUNDS; t++) {\n const lane = (x + 5 * y) * 8;\n const shift = (((t + 1) * (t + 2)) / 2) % 64;\n const nextX = y;\n const nextY = (2 * x + 3 * y) % 5;\n const target = (nextX + 5 * nextY) * 8;\n const low = get32(state, lane);\n const high = get32(state, lane + 4);\n const a = shift < 32 ? low : high;\n const b = shift < 32 ? high : low;\n const s = shift & 31;\n set32(plane, target, (a << s) | (b >>> (32 - s)));\n set32(plane, target + 4, (b << s) | (a >>> (32 - s)));\n x = nextX;\n y = nextY;\n }\n\n // Chi: each lane against the next two in its row.\n for (let y = 0; y < LANES; y += 5) {\n for (let x = 0; x < 5; x++) {\n const at = (y + x) * 8;\n const next = (y + ((x + 1) % 5)) * 8;\n const after = (y + ((x + 2) % 5)) * 8;\n set32(\n state,\n at,\n get32(plane, at) ^ (~get32(plane, next) & get32(plane, after))\n );\n set32(\n state,\n at + 4,\n get32(plane, at + 4) ^\n (~get32(plane, next + 4) & get32(plane, after + 4))\n );\n }\n }\n\n // Iota: round constant LFSR on lane 0.\n for (let bitIndex = 0; bitIndex < 7; bitIndex++) {\n const bit = (1 << bitIndex) - 1;\n if (lfsr & 1) {\n const offset = bit < 32 ? 0 : 4;\n set32(state, offset, get32(state, offset) ^ (1 << (bit & 31)));\n }\n lfsr = ((lfsr << 1) ^ (lfsr & 0x80 ? 0x71 : 0)) & 0xff;\n }\n }\n}\n\n/** Absorb one complete rate-sized block and run the permutation. */\nfunction absorb(block: DataView, offset: number): void {\n for (let at = 0; at < RATE_BYTES; at += 4) {\n set32(state, at, get32(state, at) ^ get32(block, offset + at));\n }\n permute();\n}\n\n/**\n * The SHA3-512 digest of one complete message.\n *\n * Byte-identical to the reference implementation for every input, which a\n * differential test pins against the NIST known-answer vectors and 10,000\n * random messages crossing every rate boundary.\n */\nexport function sha3_512(bytes: Uint8Array): Uint8Array {\n stateBytes.fill(0);\n\n const length = bytes.length;\n const message = new DataView(bytes.buffer, bytes.byteOffset, length);\n const wholeBlocks = Math.floor(length / RATE_BYTES);\n for (let block = 0; block < wholeBlocks; block++) {\n absorb(message, block * RATE_BYTES);\n }\n\n // The final block is the message tail plus pad10*1. A tail of exactly\n // `RATE_BYTES - 1` puts both pad bits in the same byte, which is the rule\n // rather than a special case.\n const tail = new Uint8Array(RATE_BYTES);\n const tailLength = length - wholeBlocks * RATE_BYTES;\n tail.set(bytes.subarray(wholeBlocks * RATE_BYTES));\n tail[tailLength] = DOMAIN_PAD;\n tail[RATE_BYTES - 1] =\n tailLength === RATE_BYTES - 1 ? DOMAIN_PAD | FINAL_PAD : FINAL_PAD;\n absorb(new DataView(tail.buffer), 0);\n\n // 512 bits is narrower than the rate, so one squeeze with no further\n // permutation is the whole digest — and the halves are already stored in the\n // little-endian order the digest is written in.\n return Uint8Array.from(stateBytes.subarray(0, DIGEST_BYTES));\n}\n","// biome-ignore-all lint/suspicious/noBitwiseOperators: NanoID selects a\n// character with `byte & 63`, the ULID counter carries a byte at a time, and\n// CUID2's digest is read as one big-endian integer. All three are bit layouts.\n\n/**\n * The six identifier generators a string scalar can declare.\n *\n * Each `default*` function is the DECLARATION: it validates what the modifier\n * was spelled with and returns the closure the scalar stores as its default.\n * The closure is what runs per row, synchronously, inside the field's own\n * create schema — so nothing here may be asynchronous, and nothing here may\n * draw entropy before it is called.\n *\n * The byte layouts, alphabets, widths and the one entropy source live in\n * `@validation/primitives/id-formats`, where the storage codec can read them\n * without pulling a scalar class. This module owns only what a GENERATOR adds\n * to a format: the clock it reads, the state it keeps between calls, and the\n * prefix it puts in front of the payload.\n */\n\nimport {\n applyIdPrefix,\n bytesToKsuid,\n bytesToUlid,\n bytesToUuid,\n KSUID_PAYLOAD_LENGTH,\n ksuidBytes,\n MAX_RANDOM_BYTES,\n NANOID_ALPHABET,\n NANOID_DEFAULT_LENGTH,\n randomBytes,\n refuseId,\n ULID_RANDOM_LENGTH,\n UUID_BYTE_LENGTH,\n UUIDV7_RANDOM_LENGTH,\n ulidBytes,\n uuidV4Bytes,\n uuidV7Bytes,\n} from \"@validation/primitives/id-formats\";\nimport { sha3_512 } from \"@validation/primitives/sha3\";\n\nconst MILLISECONDS_PER_SECOND = 1000;\n\n// =============================================================================\n// UUID\n// =============================================================================\n\n/**\n * A UUIDv4.\n *\n * `crypto.randomUUID()` when the runtime has it — it is the platform's own\n * implementation of exactly this format, and it is measurably faster than\n * drawing bytes and tagging them. The manual path is not a fallback to a weaker\n * value: it is the same 122 random bits with the same version and variant, from\n * the same entropy source, for runtimes that expose `getRandomValues` without\n * `randomUUID`.\n */\nconst prefixed = (prefix: string | undefined, make: () => string) => () =>\n applyIdPrefix(prefix, make());\n\nfunction uuidV4(): string {\n const source = globalThis.crypto;\n if (typeof source?.randomUUID === \"function\") return source.randomUUID();\n return bytesToUuid(uuidV4Bytes(randomBytes(UUID_BYTE_LENGTH, \"uuid\")));\n}\n\nexport const defaultUuid = (prefix?: string) => prefixed(prefix, uuidV4);\n\nexport const defaultUuidV7 = (prefix?: string) =>\n prefixed(prefix, () =>\n bytesToUuid(\n uuidV7Bytes(Date.now(), randomBytes(UUIDV7_RANDOM_LENGTH, \"uuidv7\"))\n )\n );\n\n// =============================================================================\n// ULID\n// =============================================================================\n\nfunction incrementUlidRandom(random: Uint8Array): Uint8Array {\n const next = Uint8Array.from(random);\n for (let i = next.length - 1; i >= 0; i--) {\n const inc = next[i]! + 1;\n next[i] = inc;\n if (inc <= 255) return next;\n }\n return refuseId(\n \"s.string().ulid\",\n \"generate\",\n \"ULID millisecond sequence exhausted (2^80)\"\n );\n}\n\nexport function createUlidGenerator(\n options: { now?: () => number; random?: (length: number) => Uint8Array } = {}\n): () => string {\n const now = options.now ?? Date.now;\n const draw = options.random ?? ((length) => randomBytes(length, \"ulid\"));\n let lastTime: number | undefined;\n let lastRandom: Uint8Array;\n return () => {\n const time = now();\n if (lastTime !== undefined && time <= lastTime) {\n lastRandom = incrementUlidRandom(lastRandom);\n } else {\n lastTime = time;\n lastRandom = draw(ULID_RANDOM_LENGTH);\n }\n return bytesToUlid(ulidBytes(lastTime, lastRandom));\n };\n}\n\nconst nextUlid = /*#__PURE__*/ createUlidGenerator();\n\nexport const defaultUlid = (prefix?: string) => prefixed(prefix, nextUlid);\n\n// =============================================================================\n// KSUID\n// =============================================================================\n\nexport const defaultKsuid = (prefix?: string) =>\n prefixed(prefix, () =>\n bytesToKsuid(\n ksuidBytes(\n Math.floor(Date.now() / MILLISECONDS_PER_SECOND),\n randomBytes(KSUID_PAYLOAD_LENGTH, \"ksuid\")\n )\n )\n );\n\n// =============================================================================\n// NANOID\n// =============================================================================\n\n/**\n * The lengths a nanoid can have, refused where the length is spelled.\n *\n * One character costs one byte of entropy, so the upper bound is the entropy\n * source's own per-call quota: asking for more used to declare cleanly and then\n * throw a raw `QuotaExceededError` from inside the closure, at row-create time,\n * for every row.\n */\nexport const defaultNanoid = (length?: number, prefix?: string) => {\n const size = length ?? NANOID_DEFAULT_LENGTH;\n if (!Number.isInteger(size) || size < 1 || size > MAX_RANDOM_BYTES) {\n refuseId(\n \"s.string().nanoid\",\n \"length\",\n `nanoid length must be an integer 1..${MAX_RANDOM_BYTES}; got ${size}`\n );\n }\n return () => {\n let id = \"\";\n for (const byte of randomBytes(size, \"nanoid\")) {\n id += NANOID_ALPHABET.charAt(byte & 63);\n }\n return applyIdPrefix(prefix, id);\n };\n};\n\n// =============================================================================\n// CUID2\n// =============================================================================\n\n/*\n * The CUID2 construction below is a port of @paralleldrive/cuid2 3.3.0, kept\n * byte-identical to it so that identifiers minted by VibORM and identifiers\n * minted by the upstream package belong to the same space. What changed is the\n * arithmetic (native `BigInt` in place of bignumber.js), the entropy source\n * (secure bytes only, never `Math.random()`), and the fingerprint's global\n * object (`globalThis`, which every supported runtime has). A differential test\n * pins the rest against the upstream package.\n *\n * MIT License\n *\n * Copyright (c) 2022 Eric Elliott\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nconst CUID_DEFAULT_LENGTH = 24;\nconst CUID_BIG_LENGTH = 32;\nconst CUID_ALPHABET_SIZE = 26;\nconst BASE36 = 36;\n/** ~22k hosts before a 50% chance of an initial counter collision (upstream). */\nconst CUID_INITIAL_COUNT_MAX = 476_782_367;\n\nlet textEncoder: TextEncoder | undefined;\nconst LOWERCASE_LETTERS = \"abcdefghijklmnopqrstuvwxyz\";\n\n/** A float in `[0, 1)` from four secure bytes, read as one 32-bit word. */\nfunction secureFloat(): number {\n const bytes = randomBytes(4, \"cuid\");\n const word = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);\n return word.getUint32(0, true) / 0x1_00_00_00_00;\n}\n\nfunction createEntropy(length: number, random: () => number): string {\n let entropy = \"\";\n while (entropy.length < length) {\n entropy += Math.floor(random() * BASE36).toString(BASE36);\n }\n return entropy;\n}\n\nfunction hashBase36(input: string): string {\n let value = 0n;\n for (const byte of sha3_512(\n (textEncoder ??= new TextEncoder()).encode(input)\n )) {\n value = (value << 8n) | BigInt(byte);\n }\n return value.toString(BASE36).slice(1);\n}\n\n/**\n * A fingerprint of the host environment, mixed into every id so that two\n * processes minting ids at the same millisecond with the same counter still\n * disagree.\n */\nfunction createFingerprint(random: () => number): string {\n const globals = Object.keys(globalThis).toString();\n const entropy = createEntropy(CUID_BIG_LENGTH, random);\n // Upstream writes `globals.length > 0 ? globals + entropy : entropy`. The two\n // arms are the same string — concatenating an empty `globals` IS `entropy` —\n // so the condition names no case, and a branch whose unique coverage cannot\n // be stated is one this codebase does not keep. The digest is unchanged,\n // which the differential test against the pinned upstream package proves.\n return hashBase36(globals + entropy).substring(0, CUID_BIG_LENGTH);\n}\n\n/**\n * One CUID2 sequence.\n *\n * Everything upstream lets a caller replace is replaceable here for the same\n * reason: the fingerprint, counter and random source are the parts that make\n * two processes differ, and a test that cannot fix them cannot compare two\n * implementations at all. `length` is replaceable for the same reason — the\n * salt is as long as the id, so a differential test that only ever saw 24\n * characters would compare one input shape.\n *\n * No length is spellable in a schema: `.cuid(prefix?)` takes none and always\n * mints the published 24, and a schema document that declares one is refused by\n * the reader (J007). The construction therefore states no bound of its own.\n */\nexport function createCuid2(\n options: {\n random?: () => number;\n counter?: () => number;\n length?: number;\n fingerprint?: string;\n } = {}\n): () => string {\n const random = options.random ?? secureFloat;\n const counter =\n options.counter ??\n (() => {\n let count = Math.floor(random() * CUID_INITIAL_COUNT_MAX);\n return () => count++;\n })();\n const length = options.length ?? CUID_DEFAULT_LENGTH;\n const fingerprint = options.fingerprint ?? createFingerprint(random);\n return () => {\n const firstLetter = LOWERCASE_LETTERS.charAt(\n Math.floor(random() * CUID_ALPHABET_SIZE)\n );\n const time = Date.now().toString(BASE36);\n const salt = createEntropy(length, random);\n return (\n firstLetter +\n hashBase36(\n time + salt + counter().toString(BASE36) + fingerprint\n ).substring(1, length)\n );\n };\n}\n\nlet processCuid: (() => string) | undefined;\n\nexport const defaultCuid = (prefix?: string) =>\n prefixed(prefix, () => (processCuid ??= createCuid2())());\n","// String Scalar\n// The modifiers every scalar shares are implemented once, in the chain this\n// class extends; the class types them for this scalar's own state\n\nimport type { StandardSchemaV1 } from \"@standard-schema/spec\";\nimport { hasIdPrefix, refuseId } from \"@validation/primitives/id-formats\";\nimport type { StringSchema } from \"@validation/primitives/string\";\nimport v from \"@validation/primitives/v\";\nimport type { ComputeInput, ComputeOutput } from \"@validation/types\";\nimport {\n type AutoGenerate,\n createDefaultState,\n type DefaultValueInput,\n type GeneratorDefaultBrand,\n generatorDefault,\n isGeneratorDefault,\n keyedScalarChain,\n rebaseOpts,\n refuseListGenerator,\n type ScalarState,\n type UpdateState,\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 {\n defaultCuid,\n defaultKsuid,\n defaultNanoid,\n defaultUlid,\n defaultUuid,\n defaultUuidV7,\n} from \"./autogenerate\";\n\ninterface FormatOptions {\n prefix?: string;\n generate?: true;\n}\ninterface NanoidOptions extends FormatOptions {\n length?: number;\n}\ninterface KeyOptions {\n generate: false;\n prefix?: string;\n}\ntype IdentifierKind = \"uuid\" | \"uuidv7\" | \"ulid\" | \"ksuid\" | \"nanoid\" | \"cuid\";\ntype ExactOptions<Given, Allowed> = Given extends string | number | undefined\n ? unknown\n : Record<Exclude<keyof Given, keyof Allowed>, never>;\ntype GenerationRequested<\n State extends ScalarState<\"string\">,\n Given,\n> = Given extends { generate: true }\n ? true\n : Given extends { generate: false }\n ? false\n : State[\"autoGenerate\"] extends { generate: false }\n ? false\n : State[\"autoGenerate\"] extends { generate: true }\n ? true\n : State[\"isId\"];\ntype GenerationChoice<\n State extends ScalarState<\"string\">,\n Given,\n> = Given extends { generate: true }\n ? true\n : Given extends { generate: false }\n ? false\n : State[\"autoGenerate\"] extends {\n generate: infer Choice extends boolean | undefined;\n }\n ? Choice\n : undefined;\ntype HasCustomDefault<State extends ScalarState<\"string\">> =\n State[\"default\"] extends GeneratorDefaultBrand ? false : State[\"hasDefault\"];\ntype FormatState<\n State extends ScalarState<\"string\">,\n Given,\n Kind extends IdentifierKind = IdentifierKind,\n> = {\n autoGenerate: AutoGenerate & {\n kind: Kind;\n implicit?: undefined;\n generate: GenerationChoice<State, Given>;\n };\n hasDefault: HasCustomDefault<State> extends true\n ? true\n : GenerationRequested<State, Given>;\n optional: HasCustomDefault<State> extends true\n ? true\n : GenerationRequested<State, Given>;\n default: HasCustomDefault<State> extends true\n ? State[\"default\"]\n : GenerationRequested<State, Given> extends true\n ? (() => string) & GeneratorDefaultBrand\n : undefined;\n};\ntype KeyState<State extends ScalarState<\"string\">, Given> = Omit<\n FormatState<UpdateState<State, { isId: true }>, Given>,\n \"autoGenerate\"\n> & {\n isId: true;\n isUnique: true;\n autoGenerate: State[\"autoGenerate\"] extends AutoGenerate\n ? Omit<State[\"autoGenerate\"], \"generate\"> & {\n generate: GenerationChoice<State, Given>;\n }\n : {\n kind: \"ulid\";\n implicit: true;\n prefix?: string;\n generate: GenerationChoice<State, Given>;\n };\n};\n\nfunction identifierGenerator(declaration: AutoGenerate): () => string {\n const { kind, prefix, length } = declaration;\n switch (kind) {\n case \"uuid\":\n return defaultUuid(prefix);\n case \"uuidv7\":\n return defaultUuidV7(prefix);\n case \"ulid\":\n return defaultUlid(prefix);\n case \"ksuid\":\n return defaultKsuid(prefix);\n case \"nanoid\":\n return defaultNanoid(length, prefix);\n case \"cuid\":\n return defaultCuid(prefix);\n default:\n return refuseId(\"s.string\", \"generate\", \"Not a string identifier format\");\n }\n}\n\nconst stringBase = /*#__PURE__*/ v.string();\n\nexport class StringScalar<\n State extends ScalarState<\"string\">,\n> extends keyedScalarChain<State> {\n private declare readonly state: State;\n private declare readonly _nativeType: NativeTypeDeclaration | undefined;\n declare readonly nullable: () => StringScalar<\n UpdateState<\n State,\n {\n readonly nullable: true;\n readonly hasDefault: true;\n readonly default: State[\"hasDefault\"] extends true\n ? State[\"default\"]\n : null;\n readonly optional: true;\n readonly base: StringSchema<\n ComputeInput<\n string,\n {\n nullable: true;\n array: State[\"array\"];\n schema: State[\"schema\"];\n }\n >,\n ComputeOutput<\n string,\n {\n nullable: true;\n array: State[\"array\"];\n schema: State[\"schema\"];\n }\n >\n >;\n }\n >\n >;\n declare readonly unique: () => StringScalar<\n UpdateState<\n State,\n {\n readonly isUnique: true;\n }\n >\n >;\n declare readonly default: <V extends DefaultValueInput<State>>(\n value: V\n ) => StringScalar<\n UpdateState<\n State,\n {\n readonly hasDefault: true;\n readonly default: V;\n readonly optional: true;\n }\n >\n >;\n declare readonly schema: <S extends StandardSchemaV1<string>>(\n schema: S\n ) => StringScalar<\n UpdateState<\n State,\n {\n readonly schema: S;\n readonly base: StringSchema<\n ComputeInput<\n string,\n {\n nullable: State[\"nullable\"];\n array: State[\"array\"];\n schema: S;\n }\n >,\n ComputeOutput<\n string,\n {\n nullable: State[\"nullable\"];\n array: State[\"array\"];\n schema: S;\n }\n >\n >;\n }\n >\n >;\n /**\n * Maps this scalar to a custom column name in the database\n */\n declare readonly map: (columnName: string) => StringScalar<\n UpdateState<\n State,\n {\n readonly columnName: string;\n }\n >\n >;\n declare readonly [\"~\"]: {\n state: State;\n nativeType: NativeTypeDeclaration | undefined;\n };\n\n protected rebase(state: State) {\n return v.string(rebaseOpts(state));\n }\n\n array() {\n if (isGeneratorDefault(this.state.default)) refuseListGenerator(\"s.string\");\n return new StringScalar(\n updateState(this, {\n array: true,\n base: v.string<{\n nullable: State[\"nullable\"];\n array: true;\n schema: State[\"schema\"];\n }>({\n ...rebaseOpts(this.state),\n array: true,\n }),\n }),\n this._nativeType\n );\n }\n\n id<const Given extends string | KeyOptions | undefined = undefined>(\n options?: Given & ExactOptions<Given, KeyOptions>\n ): StringScalar<UpdateState<State, KeyState<State, Given>>>;\n id(options?: string | KeyOptions): StringScalar<ScalarState<\"string\">> {\n const generate = typeof options === \"object\" ? options.generate : undefined;\n const prefix = typeof options === \"string\" ? options : options?.prefix;\n const declared = this.state.autoGenerate;\n if (declared && hasIdPrefix(prefix)) refuseSecondIdPrefix(declared);\n const declaration: AutoGenerate = declared\n ? { ...declared, generate: generate ?? declared.generate }\n : { kind: \"ulid\", prefix, implicit: true, generate };\n return this.withIdentifier(declaration, true);\n }\n\n uuid<const Given extends string | FormatOptions | undefined = undefined>(\n options?: Given & ExactOptions<Given, FormatOptions>\n ): StringScalar<UpdateState<State, FormatState<State, Given, \"uuid\">>>;\n uuid(options?: string | FormatOptions): StringScalar<ScalarState<\"string\">> {\n return this.withFormat(\"uuid\", options);\n }\n\n uuidv7<const Given extends string | FormatOptions | undefined = undefined>(\n options?: Given & ExactOptions<Given, FormatOptions>\n ): StringScalar<UpdateState<State, FormatState<State, Given, \"uuidv7\">>>;\n uuidv7(\n options?: string | FormatOptions\n ): StringScalar<ScalarState<\"string\">> {\n return this.withFormat(\"uuidv7\", options);\n }\n\n ksuid<const Given extends string | FormatOptions | undefined = undefined>(\n options?: Given & ExactOptions<Given, FormatOptions>\n ): StringScalar<UpdateState<State, FormatState<State, Given, \"ksuid\">>>;\n ksuid(options?: string | FormatOptions): StringScalar<ScalarState<\"string\">> {\n return this.withFormat(\"ksuid\", options);\n }\n\n ulid<const Given extends string | FormatOptions | undefined = undefined>(\n options?: Given & ExactOptions<Given, FormatOptions>\n ): StringScalar<UpdateState<State, FormatState<State, Given, \"ulid\">>>;\n ulid(options?: string | FormatOptions): StringScalar<ScalarState<\"string\">> {\n return this.withFormat(\"ulid\", options);\n }\n\n cuid<const Given extends string | FormatOptions | undefined = undefined>(\n options?: Given & ExactOptions<Given, FormatOptions>\n ): StringScalar<UpdateState<State, FormatState<State, Given, \"cuid\">>>;\n cuid(options?: string | FormatOptions): StringScalar<ScalarState<\"string\">> {\n return this.withFormat(\"cuid\", options);\n }\n\n nanoid<const Given extends number | NanoidOptions | undefined = undefined>(\n options?: Given & ExactOptions<Given, NanoidOptions>,\n prefix?: string\n ): StringScalar<UpdateState<State, FormatState<State, Given, \"nanoid\">>>;\n nanoid(\n options?: number | NanoidOptions,\n prefix?: string\n ): StringScalar<ScalarState<\"string\">> {\n return this.withFormat(\n \"nanoid\",\n typeof options === \"number\"\n ? { length: options, prefix }\n : (options ?? { prefix })\n );\n }\n\n private withFormat(kind: IdentifierKind, options?: string | NanoidOptions) {\n const configuration: NanoidOptions | undefined =\n typeof options === \"string\" ? { prefix: options } : options;\n return this.withIdentifier(\n {\n kind,\n prefix: configuration?.prefix,\n length: kind === \"nanoid\" ? configuration?.length : undefined,\n generate: configuration?.generate ?? this.state.autoGenerate?.generate,\n },\n this.state.isId\n );\n }\n\n private withIdentifier(declaration: AutoGenerate, isId: boolean) {\n const generator = identifierGenerator(declaration);\n const customDefault =\n this.state.hasDefault && !isGeneratorDefault(this.state.default);\n const generate =\n declaration.generate === true || (isId && declaration.generate !== false);\n const installed = generate && !customDefault;\n if (this.state.array && installed) refuseListGenerator(\"s.string\");\n const hasDefault = customDefault || installed;\n return new StringScalar(\n updateState(this, {\n isId,\n isUnique: isId || this.state.isUnique,\n autoGenerate: declaration,\n hasDefault,\n optional: hasDefault,\n default: installed\n ? generatorDefault(generator)\n : customDefault\n ? this.state.default\n : undefined,\n }),\n this._nativeType\n );\n }\n}\n\nexport const string = <\n Db extends NativeDialect = never,\n const Given extends ExactNativeTypeMap<Given> = never,\n>(\n nativeType?: NativeTypeArgument<Db, Given>\n) => {\n return new StringScalar(\n createDefaultState(\"string\", stringBase),\n admitNativeType(\"s.string\", nativeType)\n );\n};\n\nfunction refuseSecondIdPrefix(declared: {\n readonly kind: string;\n readonly prefix?: string | undefined;\n}): never {\n return refuseId(\n \"s.string().id\",\n \"prefix\",\n `Already declares '${declared.kind}'${declared.prefix ? ` (prefix '${declared.prefix}')` : \"\"}; spell prefix once on the format`\n );\n}\n"],"mappings":"yaAWA,SAAgB,EACd,EACmC,CACnC,IAAM,EAAoB,IAAI,IAC9B,IAAK,GAAM,CAAC,EAAU,KAAU,EAAe,CAC7C,GAEE,OAAO,GAAU,WADjB,GAEA,CAAC,EAAM,MAAM,OACb,CAAC,EAAM,MAAM,OAAO,QAEpB,MAAO,CACL,KAAM,OACN,QAAS,iBAAiB,EAAS,uBACnC,SAAU,QACV,MAAO,EACR,CACH,IAAM,EAAU,EAAM,KAAK,MAAM,IAAM,EAAkB,IAAI,EAAM,CACnE,GAAI,IAAY,IAAA,IAAa,IAAY,EACvC,MAAO,CACL,KAAM,OACN,QAAS,UAAU,EAAQ,6BAA6B,EAAS,GACjE,SAAU,QACV,MAAO,EACR,CACH,EAAkB,IAAI,EAAO,EAAS,ECjC1C,IAAa,EAAb,cAA2C,CAAY,CAAA,WAAA,MAAA,CAAA,MAAA,wBACrD,OAAyB,eAAiB,wBAG1C,OAEA,YACE,EACA,EACA,CAIA,IAAM,EAAW,OAAO,OACtB,EAAO,IAAK,GACV,OAAO,OACL,EAAM,WACF,CAAE,GAAG,EAAO,WAAY,OAAO,OAAO,CAAC,GAAG,EAAM,WAAW,CAAC,CAAC,CAC7D,CAAE,GAAG,EAAM,CACjB,CACF,CACD,CACK,EAAW,EAAS,IAAK,GAC7B,CACE,IAAI,EAAM,KAAK,IAAI,EAAM,UACzB,EAAM,YAAY,OACd,eAAe,EAAM,WAAW,KAAK,KAAK,GAC1C,GACJ,EAAM,QAAU,GAClB,CACG,OAAO,Q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AAM,QAAQ,CAG5D,GADJ,EAAY,WAAa,IAAS,GAAQ,EAAY,WAAa,KACvC,CAAC,EAC3B,KAAK,MAAM,OAAS,GAAW,EAAoB,WAAW,CAClE,IAAM,EAAa,GAAiB,EACpC,OAAO,IAAI,EACT,EAAY,KAAM,CAChB,OACA,SAAU,GAAQ,KAAK,MAAM,SAC7B,aAAc,EACd,aACA,SAAU,EACV,QAAS,EACL,EAAiB,EAAU,CAC3B,EACE,KAAK,MAAM,QACX,IAAA,GACP,CAAC,CACF,KAAK,YACN,GAIL,MAAa,GAIX,GAEO,IAAI,GACT,EAAmB,SAAU,EAAW,CACxC,EAAgB,WAAY,EAAW,CACxC,CAGH,SAAS,GAAqB,EAGpB,CACR,OAAO,EACL,gBACA,SACA,qBAAqB,EAAS,KAAK,GAAG,EAAS,OAAS,aAAa,EAAS,OAAO,IAAM,GAAG,mCAC/F"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { d as SchemaDocument } from "../document-
|
|
1
|
+
import { p as AnyDriver } from "../database-adapter-BMjJiBFm.mjs";
|
|
2
|
+
import { d as SchemaDocument } from "../document-CHaVF7Vn.mjs";
|
|
3
3
|
|
|
4
4
|
//#region src/migrations/introspect/types.d.ts
|
|
5
5
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{t as e}from"../introspect-
|
|
1
|
+
import{t as e}from"../introspect-q3Rf_Xv8.mjs";export{e as introspectSchema};
|
package/dist/schema/json.d.mts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { a as IndexDocument, c as RelationFieldDocument, d as SchemaDocument, f as VariantJunctionDocument, i as GenerateDocument, l as SCHEMA_DOCUMENT_VERSION, n as EnumDocument, o as JunctionDocument, r as FieldDocument, s as ModelDocument, t as CompoundKeyDocument, u as ScalarFieldDocument } from "../document-
|
|
1
|
+
import { mi as Schema, mt as VibORMConfig, pt as VibORMClient } from "../database-adapter-BMjJiBFm.mjs";
|
|
2
|
+
import { a as IndexDocument, c as RelationFieldDocument, d as SchemaDocument, f as VariantJunctionDocument, i as GenerateDocument, l as SCHEMA_DOCUMENT_VERSION, n as EnumDocument, o as JunctionDocument, p as ViewDocument, r as FieldDocument, s as ModelDocument, t as CompoundKeyDocument, u as ScalarFieldDocument } from "../document-CHaVF7Vn.mjs";
|
|
3
3
|
import { StandardSchemaV1 } from "@standard-schema/spec";
|
|
4
4
|
|
|
5
5
|
//#region src/schema/json/interpret.d.ts
|
|
@@ -57,8 +57,10 @@ type ExactSchemaJsonOptions<Given> = Given & Record<Exclude<keyof Given, keyof S
|
|
|
57
57
|
* - `J009` the document spells a surface v1 refuses
|
|
58
58
|
* - `J010` a builder refused the declaration this node denotes
|
|
59
59
|
* - `J011` a native type is not in the declared dialect's catalog
|
|
60
|
+
* - `J012` views read each other in a cycle
|
|
61
|
+
* - `J013` a key names both a model and a view
|
|
60
62
|
*/
|
|
61
|
-
type DocumentIssueCode = "J001" | "J002" | "J003" | "J004" | "J005" | "J006" | "J007" | "J008" | "J009" | "J010" | "J011";
|
|
63
|
+
type DocumentIssueCode = "J001" | "J002" | "J003" | "J004" | "J005" | "J006" | "J007" | "J008" | "J009" | "J010" | "J011" | "J012" | "J013";
|
|
62
64
|
//#endregion
|
|
63
65
|
//#region src/schema/json/serialize.d.ts
|
|
64
66
|
/**
|
|
@@ -129,4 +131,4 @@ declare function attachFieldSchemas(schema: Schema, fieldSchemas: FieldSchemaMap
|
|
|
129
131
|
*/
|
|
130
132
|
type UntypedClient = VibORMClient<VibORMConfig>;
|
|
131
133
|
//#endregion
|
|
132
|
-
export { type CompoundKeyDocument, type DocumentIssueCode, type EnumDocument, type ExactSchemaJsonOptions, type FieldDocument, type FieldSchemaMap, type GenerateDocument, type IndexDocument, type JunctionDocument, type ModelDocument, type RelationFieldDocument, SCHEMA_DOCUMENT_VERSION, type ScalarFieldDocument, type Schema, type SchemaDocument, type SchemaJsonOptions, UntypedClient, type VariantJunctionDocument, attachFieldSchemas, parseSchema, serializeSchema };
|
|
134
|
+
export { type CompoundKeyDocument, type DocumentIssueCode, type EnumDocument, type ExactSchemaJsonOptions, type FieldDocument, type FieldSchemaMap, type GenerateDocument, type IndexDocument, type JunctionDocument, type ModelDocument, type RelationFieldDocument, SCHEMA_DOCUMENT_VERSION, type ScalarFieldDocument, type Schema, type SchemaDocument, type SchemaJsonOptions, UntypedClient, type VariantJunctionDocument, type ViewDocument, attachFieldSchemas, parseSchema, serializeSchema };
|
package/dist/schema/json.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{i as e,n as t,r as n,t as r}from"../json-
|
|
1
|
+
import{i as e,n as t,r as n,t as r}from"../json-CsAdz9pg.mjs";export{e as SCHEMA_DOCUMENT_VERSION,r as attachFieldSchemas,t as parseSchema,n as serializeSchema};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{f as e,m as t,t as n}from"./validation-ATmgN5RE.mjs";import{o as r}from"./sql-tegqTqGq.mjs";import{o as i}from"./value-guards-CBVIJXlI.mjs";import{N as a}from"./model-Dtd37Sky.mjs";import{ct as o}from"./native-types-1ewJXVks.mjs";import{i as s}from"./keys-DZdKAd4n.mjs";import{c}from"./time-step-DJaIhpAz.mjs";import{c as l,r as u,t as d}from"./validation-BHjx13zG.mjs";import{f,n as p,p as m}from"./validator-DMzH5Tz0.mjs";var h=class{},g=class extends h{compute(){throw Error(`Stored has no value`)}},_=class extends h{};const v=new WeakMap,y=Object.keys,b=Object.entries,x=Object.values,S=Object.fromEntries,C=Object.hasOwn,w=Array.isArray,T=e=>typeof e==`object`&&!!e,E=e=>{if(!T(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null},D=(e,t,n)=>{let r=e.get(t);r?r.push(n):e.set(t,[n])},O=e=>e[`~`].names.ts,k=e=>e[`~`].names.sql,A=e=>e[`~`].state.scalars,j=e=>r.join(e,`, `),M=(e,t)=>e instanceof Date||t instanceof Date?e!=null&&t!=null&&+new Date(e)==+new Date(t):String(e)===String(t);function N(e){throw new t(e)}function P(t){throw new e(t)}function F(e,t,r,i,a){let s=d(e,t);if(s.issues){let e=i?[i]:[];throw new n(r,s.issues.map(t=>({path:[...e,...t.path?.map(String)??[]].join(`.`)||`root`,message:t.message})),{cause:o(s),meta:{model:O(a)}})}return s.value}function I(e){let t=new Set,n=[];for(let r of[e.ey,e.ev])for(let e of r.members)t.has(e.eh)||(t.add(e.eh),n.push({kf:r,pair:e}));return n}function L(e){if(e.kind===`reference`&&e.owner===`source`)return;let t=e.scope.edge,n=e.kind===`reference`&&t.kind===`foreignKey`?e.pairs.map(e=>e.target):[],r=t=>t.source===e.source&&t.field===e.name,i=t.kind===`foreignKey`||t.kind===`junction`?t.endpoints.find(e=>!r(e)):r(t.carrier)?e.scope.member?.inverse:t.carrier;return i&&n.push(i.field),{kind:`update`,writes:n}}function R(e,t,n,r){return e.membership(t,n,r)}function z(e,t,n,r){let i=e.index.get(t).get(n),a=i.edge,o=e.pb(i),s=t[`~`].state.relations[n][`~`].state.cardinality===`many`,c=e=>{let c=i.member??e.find(e=>e.variant===r),l=i.member===void 0;return[c,l,{scope:{edge:a,member:c},pb:o,name:l?`${n}.${c.variant}`:n,source:t,many:s}]};if(a.kind===`variantRowCarrier`){let[e,t,n]=c(a.members);return{...n,target:t?e.targetModel:a.carrier.source,kind:`reference`,owner:t?`source`:`target`,pairs:[{source:t?a.storage.idColumn.name:e.ee,target:t?e.ee:a.storage.idColumn.name}],ef:{kf:t?`source`:`target`,field:a.storage.typeColumn.name,value:e.entry.storedValue}}}if(a.kind===`variantJunctionCarrier`){let[e,t,n]=c(a.members);return{...n,target:t?e.tj.target.model:e.tj.source.model,kind:`junction`,table:e.tj.table,ey:t?e.tj.source:e.tj.target,ev:t?e.tj.target:e.tj.source,uz:e.md?t?`target`:`source`:void 0}}let l=i.slot.source,u=a.endpoints[0],d=u.source===l&&u.field===n?a.endpoints[1]:u,f={scope:i,pb:o,name:n,source:t,target:d.source,many:s};if(a.kind===`foreignKey`){let e=a.owner.source===l&&a.owner.field===n;return{...f,kind:`reference`,owner:e?`source`:`target`,reference:a.reference,pairs:a.reference.members.map(t=>({source:e?t.tw:t.ee,target:e?t.ee:t.tw}))}}let p=a.tj,m=d===a.endpoints[1];return{...f,kind:`junction`,table:p.table,ey:m?p.source:p.target,ev:m?p.target:p.source,declared:p.declared}}function B(e){return e.kind===`reference`?V(e,`source`):e.ey.members.map(e=>e.ee)}const V=(e,t)=>[...e.ef?.kf===t?[e.ef.field]:[],...e.pairs.map(e=>e[t])];function H(e,t,n){return e.uh(t,n)}function U(e,t){let n=[];for(let{edge:r,member:i}of e.index.get(t).values())r.kind===`variantRowCarrier`&&!i&&n.push(r.storage.typeColumn,r.storage.idColumn);return n}function W(e,t,n){let r=A(t)[n],i=r?{name:t[`~`].getFieldName(n).sql,scalar:r,nullable:r[`~`].state.nullable===!0}:U(e,t).find(e=>e.name===n),{state:a,nativeType:o}=i.scalar[`~`];return{...i,state:a,nativeType:o}}function G(e,t){return[...t[`~`].scalarFieldNames,...U(e,t).map(e=>e.name)]}const K=new Set([`findMany`,`findUnique`,`findFirst`,`count`,`exist`,`aggregate`,`groupBy`]);function q(e){return K.has(e)}function J(e,n){let r=O(e),i=q(n)?n===`findUnique`&&s(e).nv.length===0?`View '${r}' has no key for ${n}.`:void 0:`View '${r}' is read-only (${n}).`;if(i)throw new t(i,{meta:{model:r,operation:n}})}const Y=[`multiply`,`divide`],X=[`set`,`increment`,`decrement`,`multiply`,`divide`];function Z(e){return e}function Q(e){return w(e)?e:[Z(e)]}function $(e,t,n){let r=e.get(t);return r===void 0&&(r=n(),e.set(t,r)),r}const ee=()=>({leaves:new WeakMap,wq:new WeakMap,xk:new WeakMap,documents:new WeakMap}),te=[];var ne=class{index;registry;#e=new WeakMap;#t=new WeakMap;#n=new WeakMap;#r=new WeakMap;#i=new WeakMap;#a=new WeakMap;schema;constructor(e,t){if(this.schema=e,t){this.index=t.index,this.registry=t.registry;return}c(e),this.index=p(e),this.registry=u(e,this.index)}oz(e,t,n){a(e)!==void 0&&J(e,t);let r=this.#o(e,t,n);if(t===`update`||t===`updateMany`){let t=this.mg(e,r.data);if(t)throw t}return r}#o(e,t,n){let r=this.registry.getModelSchemas(e).args[t],a={},o=[],s=F(r,(t===`update`||t===`updateMany`)&&i(n)&&i(n.data)?{...n,data:S(b(n.data).filter(([e,t])=>t instanceof h?(t instanceof g?o.push(e):a[e]=t,!1):!0).sort(([t],[n])=>{let r=t=>e[`~`].state.relations[t]?.[`~`].state.target.kind===`variants`;return Number(r(t))-Number(r(n))}))}:n,t,``,e);if(y(a).length===0&&o.length===0)return s;let c={...s.data,...a};for(let e of o)delete c[e];return{...s,data:c}}mg(e,n){if(i(n))for(let r of this.keys(e)){let a=n[r];if(!i(a))continue;let o=X.filter(e=>a[e]!==void 0),s;if(o.length!==1)s=`PK '${r}' requires one update op; got ${o.join(`, `)||`none`}.`;else if(o[0]!==`set`){let t=A(e)[r]?.[`~`].state.type;t===`number`||t===`decimal`&&Y.includes(o[0])?s=`Arithmetic updates unsupported on ${t} PK '${r}'; use set.`:(a.divide===0||a.divide===0n)&&(s=`Cannot divide PK '${r}' by zero.`)}if(s)return new t(s)}}i1(e,t){let n=this.registry.getModelSchemas(e).scalars,r={};for(let[i,a]of b(t))r[i]=F(n[i].create,a,`create`,i,e);return r}vg(e,t){return $(this.#e,e,()=>{let n=A(e),r=y(n).filter(n=>!t.includes(this.uh(e,n).name));return{required:r.filter(e=>n[e][`~`].state.optional!==!0),defaults:r.filter(t=>n[t][`~`].state.hasDefault===!0&&this.i1(e,{[t]:void 0})[t]!==void 0)}})}update(e,t){return Z(F(this.registry.getModelSchemas(e).core.update,t,`updateMany`,`data`,e))}keys(e){return s(e).uf?.fields??te}identity(e,t){let n={};for(let r of this.keys(e))n[r]=t[r];return n}membership(e,t,n){return $($($(this.#t,e,()=>new Map),t,()=>new Map),n,()=>z(this,e,t,n))}dk(e){return $(this.#a,e,()=>{let t=[];for(let[n,r]of this.index.get(e)??[]){let i=r.edge;if(i.kind!==`foreignKey`&&i.kind!==`junction`)continue;let a=this.membership(e,n),o=a.kind===`junction`?m(a.ey):i.kind===`foreignKey`&&a.owner===`target`?f(i):void 0;(o===`restrict`||o===`noAction`)&&t.push(n)}return t})}pb(e){return $(this.#i,e,()=>l(e))}uh(e,t){return $($(this.#n,e,()=>new Map),t,()=>W(this,e,t))}#s=new WeakMap;m4(e){return $(this.#s,e,ee)}rh(e){return $(this.#r,e,()=>G(this,e))}scalars(e,t){let n={};for(let r of e[`~`].scalarFieldNames){let e=t[r];e!==void 0&&(n[r]=e)}return n}};export{g as A,D as C,N as D,k as E,h as O,x as S,A as T,E as _,Z as a,b,L as c,V as d,P as f,T as g,w as h,$ as i,v as j,_ as k,I as l,C as m,Q as n,R as o,S as p,q as r,B as s,ne as t,H as u,j as v,M as w,y as x,O as y};
|
|
2
|
+
//# sourceMappingURL=schema-DDkAUfOb.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"schema-DDkAUfOb.mjs","names":["sql","base","#linkFields","#membershipViews","#physicalFields","#storedFieldLists","#clearabilityViews","#restrictingSlotViews","#admitArguments","#queryViewsByAdapter"],"sources":["../src/query-engine/raptor3/shared/insert-value.ts","../src/query-engine/raptor3/shared/terms.ts","../src/query-engine/raptor3/shared/parse-boundary.ts","../src/query-engine/raptor3/shared/storage.ts","../src/query-engine/raptor3/shared/schema.ts"],"sourcesContent":["import type { Dialect } from \"@drivers/types\";\nimport type { Sql } from \"@sql\";\nimport type { Queries } from \"./query\";\nimport type { Input } from \"./schema\";\n\n/**\n * One model's names and values as its client's statements spell them: what a\n * fragment written by hand (a computed value, a filter's expression, a joined\n * source) names tables and columns and binds values with, so it reads what a\n * query of the client would.\n */\nexport interface ModelSql {\n readonly dialect: Dialect;\n /** The model's table, in its namespace, under `alias` where given. */\n table(alias?: string): Sql;\n /** A field's column, qualified by `alias` where given. */\n column(field: string, alias?: string): Sql;\n /** `value` bound as a value of `field` is written and compared. */\n value(field: string, value: unknown): Sql;\n /** An identifier quoted for the dialect: `name(\"r\", \"k\")` is `\"r\".\"k\"`. */\n name(...path: string[]): Sql;\n /**\n * A condition over the model's rows read under `alias`: those the call\n * holding the fragment may see; with `update`, those it may update by\n * writing these fields; with `where`, of those the ones it matches. Only a\n * fragment handed to a model operation holds one: that operation settles\n * it.\n */\n visible(\n alias: string,\n options?: { readonly update?: readonly string[]; readonly where?: object }\n ): Sql;\n}\n\n/** What a computed value is given to compute its values with. */\nexport interface InsertValueContext {\n /** The model written, by its name in the schema. */\n readonly model: string;\n /** The INSERT's rows, every value final but the computed ones. */\n readonly rows: readonly Input[];\n /** The field the value is written to. */\n readonly field: string;\n readonly sql: ModelSql;\n readonly dialect: ModelSql[\"dialect\"];\n /**\n * Run one read in the operation (its transaction, if any) and return its\n * raw rows; absent where the operation cannot read before writing (an\n * array transaction's batch), so the value must be an SQL expression.\n */\n readonly read?: (statement: Sql) => Promise<readonly Input[]>;\n}\n\n/**\n * A create value its extension computes once the rows of one INSERT are\n * final, after every incoming foreign key is assigned: a stamp of the `data`\n * capability that is an instance of this class is written where the caller\n * left the field out, not admitted as data. `compute` answers one value per\n * row it is asked about (the indexes of `rows` whose field holds this\n * instance), each a plain value or an SQL expression the INSERT evaluates.\n * An `update`'s data may hold one too: set aside from admission, its\n * expression is the SET's.\n */\nexport abstract class InsertValue {\n abstract compute(\n context: InsertValueContext,\n indexes: readonly number[]\n ): readonly unknown[] | Promise<readonly unknown[]>;\n}\n\n/**\n * An update value keeping the field as stored: set aside at admission as any\n * `InsertValue`, so no generated update value (`updatedAt()`) fills it,\n * then dropped from the data (an update left with nothing to write is one\n * that writes nothing), and not judged as a field the write writes. A write\n * that places a row without changing it keeps the row's instant so.\n */\nexport class Stored extends InsertValue {\n compute(): never {\n throw new Error(\"Stored has no value\");\n }\n}\n\n/**\n * An `updateMany` value read from a derived table the UPDATE joins: `join`\n * answers that table, aliased, and the condition matching it to the row written, over the\n * target's columns qualified by `target`; `compute` answers the SET\n * expression over the table's columns. The engine joins it (`UPDATE … FROM`,\n * MySQL's `UPDATE … JOIN`), so one statement writes each row its own value\n * and the source is read once, before any row changes.\n */\nexport abstract class JoinedValue extends InsertValue {\n abstract join(\n sql: ModelSql,\n target: string\n ): { readonly source: Sql; readonly on: Sql };\n /**\n * The same values as a list, for a database that joins no derived table:\n * each entry names one row by the values its fields hold and gives the\n * value it takes. The row is written only while it holds them. `read` asks\n * the database in the call's unit.\n */\n abstract rows(\n sql: ModelSql,\n read: (statement: Sql) => Promise<readonly Input[]>\n ): Promise<readonly JoinedEntry[]>;\n}\n\n/** One row a joined value is written to, as a list names it. */\nexport interface JoinedEntry {\n readonly where: Input;\n readonly value: unknown;\n}\n\n/**\n * Each engine's renderer, by its schema then its driver's adapter: what\n * spells a model for a fragment written by hand (`$sql`) names tables and\n * columns and binds values as the engine's queries do.\n */\nexport const renderers = new WeakMap<object, WeakMap<object, Queries>>();\n","import { QueryEngineError, UnsupportedOperationError } from \"@errors\";\nimport type { AnyModel } from \"@schema/model\";\nimport { type Sql, sql } from \"@sql\";\n\nexport const objKeys = Object.keys;\nexport const objEntries = Object.entries;\nexport const objValues = Object.values;\nexport const fromEntries = Object.fromEntries;\nexport const hasOwn = Object.hasOwn;\nexport const assign = Object.assign;\nexport const isArr = Array.isArray;\nexport const isObj = (v: unknown): v is Record<string, unknown> =>\n typeof v === \"object\" && v !== null;\nexport const isPlain = (v: unknown): v is Record<string, unknown> => {\n if (!isObj(v)) return false;\n const p = Object.getPrototypeOf(v);\n return p === Object.prototype || p === null;\n};\nexport const pushTo = <K, V>(map: Map<K, V[]>, key: K, value: V): void => {\n const list = map.get(key);\n if (list) list.push(value);\n else map.set(key, [value]);\n};\n\n/** A model's name, as the schema's keys say it. */\nexport const nameOf = (model: AnyModel): string => model[\"~\"].names.ts!;\n/** A model's table, as the database names it. */\nexport const tableOf = (model: AnyModel): string => model[\"~\"].names.sql!;\n/** The scalars a model declares, by field. */\nexport const scalarsOf = (model: AnyModel) => model[\"~\"].state.scalars;\n/** Parts of a statement, one after the other with a comma between. */\nexport const listed = (parts: readonly Sql[]): Sql => sql.join(parts, \", \");\n/**\n * Whether two values a field holds are one value: an instant is one as a\n * `Date` and as its text, wherever that text places it.\n */\nexport const same = (a: unknown, b: unknown): boolean =>\n a instanceof Date || b instanceof Date\n ? a != null && b != null && +new Date(a as Date) === +new Date(b as Date)\n : String(a) === String(b);\n\n/** Refuses what the engine does not support, in the caller's words. */\nexport function unsupported(message: string): never {\n throw new UnsupportedOperationError(message);\n}\n\n/** Stops on a state the engine itself should never reach. */\nexport function engineFault(message: string): never {\n throw new QueryEngineError(message);\n}\n","import { ValidationError } from \"@errors\";\nimport type { AnyModel } from \"@schema/model\";\nimport { type InferOutput, parse, type VibSchema } from \"@validation\";\nimport { readValidationFailureCause } from \"@validation/parse-failure\";\nimport type { Operation } from \"../../types\";\nimport { nameOf } from \"./terms\";\n\n/**\n * THE typed parse boundary (X2 — one home for validation). Every seam that turns a\n * user payload (or a sub-payload: a `where`, a `select`, a nested `create`) into a\n * validated value flows through here. It runs the schema, converts a validation\n * failure into V1's byte-identical {@link ValidationError} (operation name +\n * dotted issue path), and returns the schema's INFERRED output type — the `TOutput`\n * the `ObjectSchema` already computes — instead of erasing it to\n * `Record<string, unknown>`.\n *\n * The lone `as InferOutput<S>` below is the ONLY assertion the engine needs and the\n * ONLY one allowed outside a genuinely untyped I/O edge: after the issues guard the\n * schema has PROVEN `value` matches `S`, but `parse`'s conditional result type keeps\n * `value` erased, so the inferred output is re-attached here — the one place\n * inference cannot reach on its own. This is what makes the in-engine re-validation\n * branches (the `isRecord(result.value)` / `requireRecord` / `requires a … object`\n * guards this boundary replaced) dead: the schema layer already guarantees the shape.\n * The structural gate (parse-boundary-gate.core.test.ts) fails loudly if a future phase\n * reintroduces such a branch or an `as Record<string, unknown>` on a validated path.\n *\n * @param schema a concrete operation/core schema (its `TOutput` is the return type)\n * @param value the raw payload to validate\n * @param operation the operation name carried on the {@link ValidationError}\n * @param path the dotted prefix for issue paths (\"\" for a whole-args validate;\n * a field name like \"where\"/\"select\"/\"createMany\" for a sub-payload)\n * @param model the model the operation addresses, named in the error's\n * `meta.model`, its source and its message subject (`user.create`)\n */\nexport function parseValidated<S extends VibSchema>(\n schema: S,\n value: unknown,\n operation: Operation,\n path: string,\n model: AnyModel\n): InferOutput<S> {\n const result = parse(schema, value);\n if (result.issues) {\n const prefix = path ? [path] : [];\n throw new ValidationError(\n operation,\n result.issues.map((issue) => ({\n path:\n [...prefix, ...(issue.path?.map(String) ?? [])].join(\".\") || \"root\",\n message: issue.message,\n })),\n {\n cause: readValidationFailureCause(result),\n meta: { model: nameOf(model) },\n }\n );\n }\n return result.value as InferOutput<S>;\n}\n","import type { AnyModel } from \"@schema/model\";\nimport type { ClearableMembership } from \"@schema/relation/clearability\";\nimport type {\n DeclaredJunctionFacts,\n ResolvedJunctionMember,\n ResolvedJunctionSide,\n} from \"@schema/relation/junction-topology\";\nimport type { PolymorphicStorageColumn } from \"@schema/relation/polymorphic\";\nimport type { RelationSlot } from \"@schema/relation/types\";\nimport type { Scalar } from \"@schema/scalars/base\";\nimport type {\n ResolvedSlot,\n ResolvedStoredReference,\n ResolvedVariantJunctionMember,\n ResolvedVariantRowMember,\n} from \"@schema/validation/relation-resolution\";\nimport type { WriteJudgement } from \"./row-scope\";\nimport type { EngineSchema } from \"./schema\";\nimport { scalarsOf } from \"./terms\";\n\nexport type Membership = {\n scope: Pick<ResolvedSlot, \"edge\" | \"member\">;\n clearability: ClearableMembership;\n name: string;\n source: AnyModel;\n target: AnyModel;\n many: boolean;\n discriminator?: { side: \"source\" | \"target\"; field: string; value: string };\n} & (\n | {\n kind: \"reference\";\n owner: \"source\" | \"target\";\n pairs: readonly { source: string; target: string }[];\n reference?: ResolvedStoredReference;\n }\n | {\n kind: \"junction\";\n table: string;\n sourceSide: ResolvedJunctionSide;\n targetSide: ResolvedJunctionSide;\n uniqueSide?: \"source\" | \"target\";\n /** A declared model holds this junction: its key and its own columns. */\n declared?: DeclaredJunctionFacts;\n }\n);\n\n/**\n * One link row's stored columns, each once. A declared junction's column may\n * serve both sides (`organizationId`), and a statement names it once; the value\n * it holds is the source's, which {@link Link.shared} proved the target's too.\n */\nexport function linkMembers(\n edge: Extract<Membership, { kind: \"junction\" }>\n): readonly {\n readonly side: ResolvedJunctionSide;\n readonly pair: ResolvedJunctionMember;\n}[] {\n const seen = new Set<string>();\n const members: {\n side: ResolvedJunctionSide;\n pair: ResolvedJunctionMember;\n }[] = [];\n for (const side of [edge.sourceSide, edge.targetSide])\n for (const pair of side.members) {\n if (seen.has(pair.junctionField)) continue;\n seen.add(pair.junctionField);\n members.push({ side, pair });\n }\n return members;\n}\n\nexport type PhysicalField = {\n readonly name: string;\n readonly scalar: Scalar;\n /** What the scalar was declared with, and the native type it names: read at every comparison. */\n readonly state: Scalar[\"~\"][\"state\"];\n readonly nativeType: Scalar[\"~\"][\"nativeType\"];\n readonly nullable: boolean;\n /**\n * The KEY a private column stands in for — a polymorphic row carrier's id\n * column — which is what its identifier domain is resolved against\n * (`identifier.ts`). A declared scalar is its own key and carries none.\n */\n readonly reference?: PolymorphicStorageColumn[\"reference\"];\n};\n\n/**\n * What the row a link through `edge` reaches is judged at when the link\n * changes on it (R3): the key fields it holds and its own side of the\n * relation, so a join judges both endpoints, the source by its own data.\n * `undefined` where the source holds the key: the target's row does not\n * change, and is only read.\n */\nexport function linkJudgement(edge: Membership): WriteJudgement | undefined {\n if (edge.kind === \"reference\" && edge.owner === \"source\") return undefined;\n const resolved = edge.scope.edge;\n const writes =\n edge.kind === \"reference\" && resolved.kind === \"foreignKey\"\n ? edge.pairs.map((pair) => pair.target)\n : [];\n const own = (slot: RelationSlot) =>\n slot.source === edge.source && slot.field === edge.name;\n const inverse =\n resolved.kind === \"foreignKey\" || resolved.kind === \"junction\"\n ? resolved.endpoints.find((end) => !own(end))\n : own(resolved.carrier)\n ? edge.scope.member?.inverse\n : resolved.carrier;\n if (inverse) writes.push(inverse.field);\n return { kind: \"update\", writes };\n}\n\n/** Orient the already resolved storage once; no declaration getter or inverse search. */\nexport function bindMembership(\n schema: EngineSchema,\n source: AnyModel,\n name: string,\n variant?: string\n): Membership {\n return schema.membership(source, name, variant);\n}\n\nexport function buildMembershipView(\n schema: EngineSchema,\n source: AnyModel,\n name: string,\n variant?: string\n): Membership {\n const resolved = schema.index.get(source)!.get(name)!;\n const edge = resolved.edge;\n const clearability = schema.clearability(resolved);\n const many =\n source[\"~\"].state.relations[name]![\"~\"].state.cardinality === \"many\";\n /**\n * One variant-carrier member: the slot's own bound member, or the arm the\n * caller named. A carrier addressed with no variant names every arm at once,\n * which this one-membership view cannot represent; the caller addresses an arm\n * or composes the arms itself (g4/unit02/note.md §10.3).\n *\n * INVARIANT, not a refusal (N4 row 49). Every caller reads the slot first: a\n * bound inverse carries `resolved.member`, a carrier slot is walked arm by arm\n * over `edge.members`, and the one arm name a payload supplies is the tagged\n * grammar's `type`, which validation pins to a literal union of the configured\n * public variants before the engine sees it.\n */\n const arm = <Member extends { readonly variant: string }>(\n members: readonly Member[]\n ) => {\n const member = ((resolved.member as Member | undefined) ??\n members.find((each) => each.variant === variant))!;\n const direct = resolved.member === undefined;\n return [\n member,\n direct,\n {\n scope: { edge, member },\n clearability,\n name: direct ? `${name}.${member.variant}` : name,\n source,\n many,\n },\n ] as const;\n };\n if (edge.kind === \"variantRowCarrier\") {\n const [member, direct, base] = arm<ResolvedVariantRowMember>(edge.members);\n return {\n ...base,\n target: direct ? member.targetModel : edge.carrier.source,\n kind: \"reference\",\n owner: direct ? \"source\" : \"target\",\n pairs: [\n {\n source: direct ? edge.storage.idColumn.name : member.referencedField,\n target: direct ? member.referencedField : edge.storage.idColumn.name,\n },\n ],\n discriminator: {\n side: direct ? \"source\" : \"target\",\n field: edge.storage.typeColumn.name,\n value: member.entry.storedValue,\n },\n };\n }\n if (edge.kind === \"variantJunctionCarrier\") {\n const [member, direct, base] = arm<ResolvedVariantJunctionMember>(\n edge.members\n );\n return {\n ...base,\n target: direct\n ? member.topology.target.model\n : member.topology.source.model,\n kind: \"junction\",\n table: member.topology.table,\n sourceSide: direct ? member.topology.source : member.topology.target,\n targetSide: direct ? member.topology.target : member.topology.source,\n uniqueSide: member.uniqueTarget\n ? direct\n ? \"target\"\n : \"source\"\n : undefined,\n };\n }\n // The slot's own model says which end it is: a view reads its source's\n // slot, at its own rows (`buildIndex`).\n const at = resolved.slot.source;\n const endpoint = edge.endpoints[0];\n const opposite =\n endpoint.source === at && endpoint.field === name\n ? edge.endpoints[1]\n : endpoint;\n const base = {\n scope: resolved,\n clearability,\n name,\n source,\n target: opposite.source,\n many,\n };\n if (edge.kind === \"foreignKey\") {\n const owns = edge.owner.source === at && edge.owner.field === name;\n return {\n ...base,\n kind: \"reference\",\n owner: owns ? \"source\" : \"target\",\n reference: edge.reference,\n pairs: edge.reference.members.map((pair) => ({\n source: owns ? pair.foreignField : pair.referencedField,\n target: owns ? pair.referencedField : pair.foreignField,\n })),\n };\n }\n const topology = edge.topology;\n // The SLOT decides, not the model: a self junction names one model on both\n // sides and only its two fields tell the directions apart. `opposite` above\n // already resolved that identity, and `endpoints[0]`/`endpoints[1]` are the\n // slots `topology.source`/`topology.target` were built from.\n const forward = opposite === edge.endpoints[1];\n return {\n ...base,\n kind: \"junction\",\n table: topology.table,\n sourceSide: forward ? topology.source : topology.target,\n targetSide: forward ? topology.target : topology.source,\n declared: topology.declared,\n };\n}\n\n/** The fields of the row it leaves that one hop of `edge` reads. */\nexport function hopFieldsOf(edge: Membership): readonly string[] {\n return edge.kind === \"reference\"\n ? sideFields(edge, \"source\")\n : edge.sourceSide.members.map((member) => member.referencedField);\n}\n\n/** The fields a reference holds on one side, its discriminator first. */\nexport const sideFields = (\n edge: Extract<Membership, { kind: \"reference\" }>,\n side: \"source\" | \"target\"\n): string[] => [\n ...(edge.discriminator?.side === side ? [edge.discriminator.field] : []),\n ...edge.pairs.map((pair) => pair[side]),\n];\n\n/** Private carrier columns are resolved schema fields, never public scalar declarations. */\nexport function physicalField(\n schema: EngineSchema,\n model: AnyModel,\n field: string\n): PhysicalField {\n return schema.physicalField(model, field);\n}\n\n/**\n * The private `(type, id)` columns this model's variant ROW carriers store, in\n * declaration order. ONE enumeration of them, so what a field resolves to and\n * what {@link buildStoredFieldsView} says the row stores cannot drift apart.\n */\nfunction carrierColumns(\n schema: EngineSchema,\n model: AnyModel\n): PolymorphicStorageColumn[] {\n const columns: PolymorphicStorageColumn[] = [];\n for (const { edge, member } of schema.index.get(model)!.values())\n if (edge.kind === \"variantRowCarrier\" && !member)\n columns.push(edge.storage.typeColumn, edge.storage.idColumn);\n return columns;\n}\n\n/**\n * INVARIANT, not a refusal (N4 row 48): a model stores its declared scalars and\n * its row carriers' columns, and nothing asks this owner for anything else. A\n * field name arrives from admission, which matched it against the model's\n * declared scalar keys, or from the resolved topology itself — a membership\n * pair, a carrier discriminator, a junction side's referenced field, a row key,\n * or {@link buildStoredFieldsView}, which enumerates exactly those two sets.\n */\nexport function buildPhysicalFieldView(\n schema: EngineSchema,\n model: AnyModel,\n field: string\n): PhysicalField {\n const scalar = scalarsOf(model)[field];\n const view = scalar\n ? {\n name: model[\"~\"].getFieldName(field).sql,\n scalar,\n nullable: scalar[\"~\"].state.nullable === true,\n }\n : carrierColumns(schema, model).find(\n (candidate) => candidate.name === field\n )!;\n const { state, nativeType } = view.scalar[\"~\"];\n return { ...view, state, nativeType };\n}\n\nexport function buildStoredFieldsView(\n schema: EngineSchema,\n model: AnyModel\n): string[] {\n return [\n ...model[\"~\"].scalarFieldNames,\n ...carrierColumns(schema, model).map((column) => column.name),\n ];\n}\n","import type { EngineFacts } from \"@adapters/database-adapter\";\nimport type { AnyDriver } from \"@drivers/exports\";\nimport { UnsupportedOperationError } from \"@errors\";\nimport { hydrateSchemaNames, type Schema } from \"@schema/hydration\";\nimport { type AnyModel, getModelKeyCatalog } from \"@schema/model\";\nimport {\n type ClearableMembership,\n clearableMembership,\n} from \"@schema/relation/clearability\";\nimport { resolveSchemaOrThrow } from \"@schema/validation\";\nimport {\n foreignKeyOnDelete,\n junctionOnDelete,\n type ResolvedSlot,\n} from \"@schema/validation/relation-resolution\";\nimport { viewFacts } from \"@schema/view/facts\";\nimport { createResolvedSchemaRegistry } from \"@validation/builder\";\nimport type { GroupByMember } from \"@validation/model/args/time-step\";\nimport type { NormalizedRecurrence } from \"@validation/relations/recurrence\";\nimport type { VibSchema } from \"@validation/types\";\nimport { isRecord } from \"@validation/value-guards\";\nimport { InsertValue, Stored } from \"./insert-value\";\nimport { parseValidated } from \"./parse-boundary\";\nimport type {\n Leaf,\n PreparedProjection,\n PreparedProjectionField,\n Shape,\n} from \"./query\";\nimport {\n buildMembershipView,\n buildPhysicalFieldView,\n buildStoredFieldsView,\n type Membership,\n type PhysicalField,\n} from \"./storage\";\nimport {\n fromEntries,\n isArr,\n nameOf,\n objEntries,\n objKeys,\n scalarsOf,\n} from \"./terms\";\n\nexport type Input = Record<string, unknown>;\nexport type ReadOperation =\n | \"findMany\"\n | \"findUnique\"\n | \"findFirst\"\n | \"count\"\n | \"exist\"\n | \"aggregate\"\n | \"groupBy\";\nexport type Operation =\n | \"create\"\n | \"createMany\"\n | \"update\"\n | \"upsert\"\n | \"updateMany\"\n | \"delete\"\n | \"deleteMany\"\n | ReadOperation;\n\nconst READ_OPERATIONS: ReadonlySet<string> = new Set<ReadOperation>([\n \"findMany\",\n \"findUnique\",\n \"findFirst\",\n \"count\",\n \"exist\",\n \"aggregate\",\n \"groupBy\",\n]);\n\n/** One classification of an admitted operation; a read allocates no write work. */\nexport function isReadOperation(\n operation: Operation\n): operation is ReadOperation {\n return READ_OPERATIONS.has(operation);\n}\n\n/**\n * What a view admits of the operations: its reads, and a unique read only\n * when its query projects a key of its source.\n */\nfunction admitViewOperation(model: AnyModel, operation: Operation): void {\n const name = nameOf(model);\n const msg = isReadOperation(operation)\n ? operation === \"findUnique\" &&\n getModelKeyCatalog(model).addressableKeys.length === 0\n ? `View '${name}' has no key for ${operation}.`\n : undefined\n : `View '${name}' is read-only (${operation}).`;\n if (msg)\n throw new UnsupportedOperationError(msg, {\n meta: { model: name, operation },\n });\n}\n/**\n * The client's already-resolved schema views. A client that composed them once\n * hands them over by identity; the candidate never re-hydrates or re-validates\n * a schema a caller already resolved (g4/unit03/note.md B-3).\n */\nexport interface ResolvedSchemaViews {\n readonly index: ReturnType<typeof resolveSchemaOrThrow>;\n /**\n * Declared as the one member {@link EngineSchema} reads. A client hands over\n * its full resolved registry; anything carrying `getModelSchemas` satisfies\n * this, nothing is widened, and no consumer here reads `proxy`.\n */\n readonly registry: Pick<\n ReturnType<typeof createResolvedSchemaRegistry>,\n \"getModelSchemas\"\n >;\n}\nexport interface EngineConfig {\n schema: Schema;\n driver: AnyDriver;\n resolved?: ResolvedSchemaViews;\n}\nexport interface Arguments extends Input {\n data: Input;\n create?: Input;\n update?: Input;\n where?: Input;\n targetWhere?: Input;\n setWhere?: Input;\n select?: Input;\n include?: Input;\n orderBy?: Input | Input[];\n take?: number;\n skip?: number;\n cursor?: Input;\n distinct?: string[];\n by?: readonly GroupByMember[];\n /** A grouped read's IANA zone for its time steps (`time-step.ts`). */\n timeZone?: string;\n having?: Input;\n limit?: number;\n omit?: Input;\n recurse?: NormalizedRecurrence;\n skipDuplicates?: boolean;\n _count?: true | Input;\n _avg?: Input;\n _sum?: Input;\n _min?: Input;\n _max?: Input;\n}\n\n/**\n * The two update operators whose result a provider ROUNDS — the ones an exact\n * decimal row key cannot carry portably, and the ones phase 2 made reachable.\n */\nconst ROUNDING_KEY_UPDATES: readonly string[] = [\"multiply\", \"divide\"];\n\n/**\n * Every operation a key update may name, in the shipped engine's own order\n * (`operations/mutation-identity.ts` `assertPortablePrimaryKeyUpdateInput`),\n * because the refusal sentence lists them in it.\n */\nconst KEY_UPDATE_OPERATIONS = [\n \"set\",\n \"increment\",\n \"decrement\",\n \"multiply\",\n \"divide\",\n] as const;\n\n/** These casts attach the existing admission schema's dynamic model correlation. */\nexport function record(value: unknown): Input {\n return value as Input;\n}\nexport function entries(value: unknown): Input[] {\n return isArr(value) ? value : [record(value)];\n}\n/** `key`'s view in `views`, created on its first use and kept as long as `views`. */\nexport function memo<K, V>(\n views: { get(key: K): V | undefined; set(key: K, value: V): unknown },\n key: K,\n create: () => V\n): V {\n let view = views.get(key);\n if (view === undefined) {\n view = create();\n views.set(key, view);\n }\n return view;\n}\n\n/**\n * What this engine resolves once per (adapter, model) and never again.\n *\n * Every member is a pure function of the schema and the dialect, which is why\n * they may be shared at all (rule 1): a scalar leaf is the field's declared\n * type, nullability and the adapter's own `dateTime` representation; the\n * DEFAULT projection is `scalarFieldNames` minus the model's own `omit` (an\n * operation-level `omit` reaches the projection owner desugared into a\n * `select`, which shares it only where it names exactly those scalars); a\n * relation read at its target's default projection is its edge, an empty\n * window and that projection. Nothing admitted and nothing a provider\n * answered is stored (rule 5): the sharing is keyed by schema objects alone.\n *\n * The member types are the query owner's, imported for their names only:\n * `import type` adds no runtime edge, so `shared/query.ts` keeps its one\n * runtime import of this file and this file keeps none of it.\n */\nexport type QueryViews = {\n readonly leaves: WeakMap<AnyModel, Map<string, Leaf>>;\n readonly defaultProjections: WeakMap<AnyModel, PreparedProjection>;\n /**\n * A relation of a model read at its target's default projection (`rel:\n * true`, or a node naming every projectable scalar and nothing else) on a\n * read under no row domain: its edge, an empty window and the target's\n * default projection, all facts of the schema and the dialect.\n */\n readonly defaultRelations: WeakMap<AnyModel, Map<string, DefaultRelation>>;\n /**\n * A view's JSON columns, by name: the decoder shape its source read gives\n * each selection of its declared query, a fact of the schema and the\n * dialect.\n */\n readonly documents: WeakMap<AnyModel, Readonly<Record<string, Shape | Leaf>>>;\n};\n\n/** A relation member at its default projection, and its decoded shape. */\nexport type DefaultRelation = {\n readonly field: PreparedProjectionField;\n readonly shape: Shape;\n};\n\nconst createQueryViews = (): QueryViews => ({\n leaves: new WeakMap(),\n defaultProjections: new WeakMap(),\n defaultRelations: new WeakMap(),\n documents: new WeakMap(),\n});\n\nconst NO_KEY: readonly string[] = [];\n\nexport class EngineSchema {\n readonly index;\n readonly registry;\n readonly #linkFields = new WeakMap<\n AnyModel,\n {\n readonly required: readonly string[];\n readonly defaults: readonly string[];\n }\n >();\n readonly #membershipViews = new WeakMap<\n AnyModel,\n Map<string, Map<string | undefined, Membership>>\n >();\n readonly #physicalFields = new WeakMap<\n AnyModel,\n Map<string, PhysicalField>\n >();\n readonly #storedFieldLists = new WeakMap<AnyModel, readonly string[]>();\n readonly #clearabilityViews = new WeakMap<\n ResolvedSlot,\n ClearableMembership\n >();\n readonly #restrictingSlotViews = new WeakMap<AnyModel, readonly string[]>();\n readonly schema: Schema;\n constructor(schema: Schema, resolved?: ResolvedSchemaViews) {\n this.schema = schema;\n if (resolved) {\n this.index = resolved.index;\n this.registry = resolved.registry;\n return;\n }\n hydrateSchemaNames(schema);\n this.index = resolveSchemaOrThrow(schema);\n this.registry = createResolvedSchemaRegistry(schema, this.index);\n }\n admit(model: AnyModel, operation: Operation, raw: unknown): Arguments {\n // A view's rows are its query's: every root call is admitted here, so a\n // write is refused before any statement, whoever made the call, and so is\n // a unique read of a view that has no key to name a row by.\n if (viewFacts(model) !== undefined) admitViewOperation(model, operation);\n const admitted = this.#admitArguments(model, operation, raw);\n // What a key may be rewritten with is judged where an update is admitted;\n // an upsert's update arm is judged where it runs, on the row found.\n if (operation === \"update\" || operation === \"updateMany\") {\n const refusal = this.keyPortabilityRefusal(model, admitted.data);\n if (refusal) throw refusal;\n }\n return admitted;\n }\n #admitArguments(\n model: AnyModel,\n operation: Operation,\n raw: unknown\n ): Arguments {\n const schema = this.registry.getModelSchemas(model).args[operation];\n // A value the statement computes (`InsertValue`)\n // is no payload: it is set aside here and written as it is. A field kept\n // as stored (`Stored`) is set aside too, so no generated update value\n // (`updatedAt()`) fills it, and is then not written at all.\n const computed: Input = {};\n const kept: string[] = [];\n const input =\n (operation === \"update\" || operation === \"updateMany\") &&\n isRecord(raw) &&\n isRecord(raw.data)\n ? {\n ...raw,\n data: fromEntries(\n objEntries(raw.data)\n .filter(([field, value]) => {\n if (!(value instanceof InsertValue)) return true;\n if (value instanceof Stored) kept.push(field);\n else computed[field] = value;\n return false;\n })\n .sort(([left], [right]) => {\n const isVariant = (name: string) =>\n model[\"~\"].state.relations[name]?.[\"~\"].state.target\n .kind === \"variants\";\n return Number(isVariant(left)) - Number(isVariant(right));\n })\n ),\n }\n : raw;\n const admitted = parseValidated(\n schema,\n input,\n operation,\n \"\",\n model\n ) as Arguments;\n if (objKeys(computed).length === 0 && kept.length === 0) return admitted;\n const data: Record<string, unknown> = {\n ...(admitted.data as Input),\n ...computed,\n };\n for (const field of kept) delete data[field];\n return { ...admitted, data };\n }\n /**\n * The row key's PORTABILITY contract for the two operators phase 2 made\n * reachable, as one refusal the caller raises where the shipped engine raises\n * it — never a second walker, never a second sentence.\n *\n * A key's post-update value has to be NAMEABLE: a non-returning readback and\n * every dependent's key transition address the row by it. `multiply` and\n * `divide` carry a provider-chosen rounding on a `number` or `decimal` key\n * that no engine can name portably, and a `divide` by zero has no value at\n * all, so the shipped engine refuses both from its own validator\n * (`assertPortablePrimaryKeyUpdateInput`). Until phase 2 implemented the two\n * operators the candidate answered \"not implemented\" for every one of these\n * payloads; implementing them is what brought the shapes within reach, so the\n * refusals arrive with them, in the shipped engine's own sentences.\n *\n * WHAT it says is the shipped assertion with exactly ONE adopted divergence,\n * R-D2 (a) (Arnaud, 2026-09-15): an EXACT-DOMAIN arithmetic update of a\n * `decimal` key — `increment` / `decrement` — is supported, because it is\n * exact in coefficient space, and the registered G3 witness\n * `tests/raptor3/g3/review-execution-boundaries.test.ts` pins that capability.\n * `multiply` / `divide` on the same key still carry the provider's rounding,\n * so they stay refused. Everything else is parity: R-D2 (b), a `number` key\n * under any arithmetic, and R-D2 (c), `set` beside another operation, answer\n * the shipped sentences (they used to be divergences, pinned on both engines;\n * the decision reverted them). The shipped non-finite-operand arm is\n * deliberately NOT mirrored — after the rules below it is reachable only for\n * an `int`/`bigint` key, whose validation refuses a non-finite operand, so it\n * would be a guard whose unique coverage cannot be named.\n *\n * WHERE it is raised belongs to each caller, because the shipped engine does\n * not raise it in one place: `admit` raises it for `update`/`updateMany`, and\n * the upsert's found arm carries it (`commands.ts`) exactly when the update\n * payload names relations — the shipped gate, note §R3.1. A wider placement\n * refuses requests the shipped engine performs, including an upsert that\n * CREATES a row the arithmetic never touches.\n */\n keyPortabilityRefusal(model: AnyModel, data: unknown): Error | undefined {\n if (!isRecord(data)) return undefined;\n for (const keyField of this.keys(model)) {\n const update = data[keyField];\n if (!isRecord(update)) continue;\n const named = KEY_UPDATE_OPERATIONS.filter(\n (operation) => update[operation] !== undefined\n );\n let msg: string | undefined;\n if (named.length !== 1)\n msg = `PK '${keyField}' requires one update op; got ${named.join(\", \") || \"none\"}.`;\n else if (named[0] !== \"set\") {\n const scalarType = scalarsOf(model)[keyField]?.[\"~\"].state.type;\n if (\n scalarType === \"number\" ||\n (scalarType === \"decimal\" && ROUNDING_KEY_UPDATES.includes(named[0]!))\n )\n msg = `Arithmetic updates unsupported on ${scalarType} PK '${keyField}'; use set.`;\n else if (update.divide === 0 || update.divide === 0n)\n msg = `Cannot divide PK '${keyField}' by zero.`;\n }\n if (msg) return new UnsupportedOperationError(msg);\n }\n return undefined;\n }\n mkVals(model: AnyModel, source: Input): Input {\n const scalars = this.registry.getModelSchemas(model).scalars as Record<\n string,\n { readonly create: VibSchema }\n >;\n const admitted: Input = {};\n for (const [field, value] of objEntries(source))\n admitted[field] = parseValidated(\n scalars[field]!.create,\n value,\n \"create\",\n field,\n model\n );\n return admitted;\n }\n linkFields(model: AnyModel, members: readonly string[]) {\n return memo(this.#linkFields, model, () => {\n const scalars = scalarsOf(model);\n const beside = objKeys(scalars).filter(\n (field) => !members.includes(this.physicalField(model, field).name)\n );\n return {\n required: beside.filter(\n (field) => scalars[field]![\"~\"].state.optional !== true\n ),\n defaults: beside.filter(\n (field) =>\n scalars[field]![\"~\"].state.hasDefault === true &&\n this.mkVals(model, { [field]: undefined })[field] !== undefined\n ),\n };\n });\n }\n /** What an update writes of a row, admitted as an update's data is. */\n update(model: AnyModel, source: Input): Input {\n return record(\n parseValidated(\n this.registry.getModelSchemas(model).core.update,\n source,\n \"updateMany\",\n \"data\",\n model\n )\n );\n }\n /** The fields of a model's row key: none where the model has no key. */\n keys(model: AnyModel): readonly string[] {\n return getModelKeyCatalog(model).rowKey?.fields ?? NO_KEY;\n }\n identity(model: AnyModel, row: Input): Input {\n const identity: Input = {};\n for (const field of this.keys(model)) identity[field] = row[field];\n return identity;\n }\n membership(model: AnyModel, name: string, variant?: string): Membership {\n const modelViews = memo(this.#membershipViews, model, () => new Map());\n const slotViews = memo(modelViews, name, () => new Map());\n return memo(slotViews, variant, () =>\n buildMembershipView(this, model, name, variant)\n );\n }\n /**\n * The slots through which the database refuses a hard delete of a `model` row\n * while a member exists: an incoming foreign key, or the junction key on this\n * model's side, whose ON DELETE is `restrict` or `noAction`. The actions are\n * the schema's own answer (`foreignKeyOnDelete`, `junctionOnDelete`), the one\n * the migration spells. A polymorphic carrier stores no constraint.\n */\n restrictingSlots(model: AnyModel): readonly string[] {\n return memo(this.#restrictingSlotViews, model, () => {\n const found: string[] = [];\n for (const [name, resolved] of this.index.get(model) ?? []) {\n const edge = resolved.edge;\n if (edge.kind !== \"foreignKey\" && edge.kind !== \"junction\") continue;\n const view = this.membership(model, name);\n const action =\n view.kind === \"junction\"\n ? junctionOnDelete(view.sourceSide)\n : edge.kind === \"foreignKey\" && view.owner === \"target\"\n ? foreignKeyOnDelete(edge)\n : undefined;\n if (action === \"restrict\" || action === \"noAction\") found.push(name);\n }\n return found;\n });\n }\n clearability(resolved: ResolvedSlot): ClearableMembership {\n return memo(this.#clearabilityViews, resolved, () =>\n clearableMembership(resolved)\n );\n }\n physicalField(model: AnyModel, field: string): PhysicalField {\n return memo(\n memo(this.#physicalFields, model, () => new Map()),\n field,\n () => buildPhysicalFieldView(this, model, field)\n );\n }\n /**\n * One adapter's {@link QueryViews}, created on its first use.\n *\n * `EngineSchema` already owns the lazy immutable per-model views this engine\n * resolves from the schema alone, but these two are also a fact of the\n * DIALECT — a scalar leaf carries the adapter's own `dateTime`\n * representation — and a `Queries` instance is per-operation for writes, so\n * neither owner alone can hold them. The adapter is the second key and it is\n * held weakly, so a view store lives exactly as long as the adapter it\n * describes. What it may hold is what every view here may hold: facts\n * derived from the schema and the dialect, never an admitted input, an\n * alias, an operation demand or a provider row (rule 5).\n *\n * The accessor names its one fact, like every other view on this class, so\n * the store cannot be reached for a second shape: an anonymous\n * `scope(adapter, create)` would hand a second caller the first caller's\n * object under the second caller's type, and the cast would hide it.\n */\n readonly #queryViewsByAdapter = new WeakMap<EngineFacts, QueryViews>();\n qViews(adapter: EngineFacts): QueryViews {\n return memo(this.#queryViewsByAdapter, adapter, createQueryViews);\n }\n storedFields(model: AnyModel): readonly string[] {\n return memo(this.#storedFieldLists, model, () =>\n buildStoredFieldsView(this, model)\n );\n }\n /**\n * The admitted payload's scalar fields, in the model's own scalar order.\n *\n * One pass into one object. The model's scalar order is already memoised by\n * the model itself (`schema/model/model.ts`, `_scalarFieldNames ??=`), so the\n * only per-call cost left was the three intermediates\n * `Object.fromEntries(names.filter(…).map(…))` built — on a normalization\n * every row of every `createMany` crosses (`g4/cutover/perf-diagnosis.md`\n * §4.2). Same keys, same order, same values.\n */\n scalars(model: AnyModel, admitted: Input): Input {\n const values: Input = {};\n for (const field of model[\"~\"].scalarFieldNames) {\n const value = admitted[field];\n if (value !== undefined) values[field] = value;\n }\n return values;\n }\n}\n"],"mappings":"+aA8DA,IAAsB,EAAtB,KAAkC,GAcrB,EAAb,cAA4B,CAAY,CACtC,SAAiB,CACf,MAAU,MAAM,sBAAsB,GAYpB,EAAtB,cAA0C,CAAY,GA4BtD,MAAa,EAAY,IAAI,QClHhB,EAAU,OAAO,KACjB,EAAa,OAAO,QACpB,EAAY,OAAO,OACnB,EAAc,OAAO,YACrB,EAAS,OA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,EAAK,MAAA,EAA2B,EAAS,GAAiB,CAEnE,aAAa,EAAoC,CAC/C,OAAO,EAAK,MAAA,EAAwB,MAClC,EAAsB,KAAM,EAAM,CACnC,CAYH,QAAQ,EAAiB,EAAwB,CAC/C,IAAM,EAAgB,EAAE,CACxB,IAAK,IAAM,KAAS,EAAM,KAAK,iBAAkB,CAC/C,IAAM,EAAQ,EAAS,GACnB,IAAU,IAAA,KAAW,EAAO,GAAS,GAE3C,OAAO"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{a as e,o as t}from"./model-Dtd37Sky.mjs";import{t as n}from"./scalar-Dm9brvAU.mjs";import{_ as r,a as i,c as a,d as o,g as s,h as c,i as l,m as u,n as d,o as f,p,r as m,s as h,t as g,v as _}from"./view-CHgjF2BO.mjs";const v={model:e,string:n,boolean:s,int:h,number:i,decimal:o,bigInt:_,dateTime:u,date:c,time:p,json:f,blob:r,enum:a,point:l,vector:m,toOne:t,toMany:d,view:g};export{v as t};
|
|
2
|
+
//# sourceMappingURL=schema-DqR_Kcje.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"schema-DqR_Kcje.mjs","names":[],"sources":["../src/schema/index.ts"],"sourcesContent":["// Schema Builder Entry Point\n// Main API for defining models, scalars, and relations\n\nimport { model } from \"./model\";\nimport { toMany, toOne } from \"./relation\";\nimport {\n bigInt,\n blob,\n boolean,\n date,\n dateTime,\n decimal,\n enumScalar,\n int,\n json,\n number,\n point,\n string,\n time,\n vector,\n} from \"./scalars\";\nimport { view } from \"./view/view\";\n\n// =============================================================================\n// SCHEMA BUILDER API\n// =============================================================================\n\n/**\n * Main schema builder object\n * Use this to define models, scalars, and relations\n *\n * A relation states two independent facts: `s.toOne` / `s.toMany` states the\n * SLOT CARDINALITY, and the argument states the TARGET DOMAIN — one model\n * (`() => model`) or named variants (`{ post: () => post, video: () => video }`).\n * Everything else about an edge is derived from the full schema graph.\n *\n * @example\n * ```ts\n * import { s } from \"viborm\";\n *\n * const user = s.model({\n * id: s.string().id().ulid(),\n * name: s.string(),\n * email: s.string().unique(),\n * posts: s.toMany(() => post),\n * profile: s.toOne(() => profile),\n * }).map(\"users\");\n *\n * const post = s.model({\n * id: s.string().id().ulid(),\n * authorId: s.string(),\n * author: s.toOne(() => user).fields(\"authorId\").references(\"id\"),\n * }).map(\"posts\");\n * ```\n */\nexport const s = {\n // Model factory\n model,\n\n // Scalar factories\n string,\n boolean,\n /**\n * @description Creates a new int scalar.\n * @param nativeType - The native type to use for the scalar.\n * @returns A new int scalar.\n */\n int,\n number,\n decimal,\n bigInt,\n dateTime,\n date,\n time,\n json,\n blob,\n enum: enumScalar,\n point,\n vector,\n\n // Relation factories: slot cardinality here, target domain in the argument\n toOne,\n toMany,\n\n // A database view: a read of a model, kept by the migrations\n view,\n};\n\n// =============================================================================\n// RE-EXPORTS\n// =============================================================================\n\n// Hydration exports (excluding Schema type which conflicts with validation)\nexport {\n getFieldSqlName,\n getModelSqlName,\n hydrateSchemaNames,\n isSchemaHydrated,\n} from \"./hydration\";\n// JSON null sentinels — the two nulls of a nullable JSON column, told apart\nexport {\n type AnyJsonNullSentinel,\n AnyNull,\n DbNull,\n isJsonNullSentinel,\n JsonNull,\n type JsonNullKind,\n JsonNullSentinel,\n} from \"./json-null\";\nexport * from \"./model\";\nexport { Model } from \"./model\";\nexport * from \"./relation\";\n// Types\nexport type { NumericScalar, Scalar } from \"./scalars\";\n// Export all from submodules\nexport * from \"./scalars\";\n// Classes for advanced usage\nexport {\n BigIntScalar,\n BlobScalar,\n BooleanScalar,\n DateScalar,\n DateTimeScalar,\n EnumScalar,\n IntScalar,\n JsonScalar,\n NumberScalar,\n PointScalar,\n StringScalar,\n TimeScalar,\n VectorScalar,\n} from \"./scalars\";\nexport * as TYPES from \"./scalars/native-types\";\nexport * from \"./validation\";\nexport { type ViewFacts, viewFacts } from \"./view/facts\";\nexport type { ViewDeclaration, ViewQuery, ViewState } from \"./view/view\";\n\n// =============================================================================\n// TYPE INFERENCE EXPORTS\n// =============================================================================\n\n// Re-export core types from common\nexport type {\n AutoGenerate,\n AutoGenerateType,\n InferBaseType,\n InferCreateType,\n ScalarState as ScalarStateType,\n} from \"./scalars/common\";\n"],"mappings":"+NAuDA,MAAa,EAAI,CAEf,QAGA,SACA,UAMA,MACA,SACA,UACA,SACA,WACA,OACA,OACA,OACA,OACA,KAAM,EACN,QACA,SAGA,QACA,SAGA,OACD"}
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import{f as e,t}from"./validation-ATmgN5RE.mjs";import{n,t as r}from"./routed-operations-CcKOdn51.mjs";import{N as i,t as a}from"./model-Dtd37Sky.mjs";import{at as o,ct as s,et as c,nt as l,ot as u,rt as d}from"./query-BTb6iakn.mjs";import{c as f}from"./time-step-DJaIhpAz.mjs";import{i as p,l as m,r as h}from"./validation-BHjx13zG.mjs";import{n as g}from"./validator-DMzH5Tz0.mjs";import{t as _}from"./types-Dy33vBdd.mjs";import{t as v}from"./result-parsing-BbffueEX.mjs";function y(e,t,n){let r=Object.hasOwn(n,t)?n[t]:void 0;return e===`_count`?t===`_all`||r?{kind:`count`,nullable:!1}:{kind:`unknown`}:r?e===`_avg`&&r[`~`].state.type!==`decimal`?{kind:`number`,nullable:!0}:e===`_sum`?{kind:`widenedSum`,nullable:!0,scalar:r}:{kind:`scalar`,nullable:!0,scalar:r}:{kind:`unknown`}}function b(e,t,n){if(t===d)return{kind:`empty`};if(t===l)return{kind:`distance`,scalar:n.qm};let r=e[`~`].state.scalars,i=Object.hasOwn(r,t)?r[t]:void 0;if(i)return{kind:`scalar`,key:t,scalar:i};if(t===u)return{kind:`relationCounts`,relations:n.relationCounts};if(t===o&&n.relationAggregates)return{kind:`relationAggregates`,relations:n.relationAggregates};let a=e[`~`].state.relations,c=Object.hasOwn(a,t)?a[t]:void 0;if(c){if(_(c[`~`].state)){let e=n.polymorphic.get(t);return e?{kind:`polymorphic`,key:t,relation:c,expected:e}:{kind:`unknown`,key:t}}let e=n.relations.get(t);return e?{kind:`relation`,key:t,relation:c,expected:e}:{kind:`unknown`,key:t}}let f=s(t);if(f){let e=n.aggregates.get(t);return e?{kind:`aggregate`,name:f,expected:e}:{kind:`unknown`,key:t}}return{kind:`unknown`,key:t}}const x=/^[A-Za-z_$][A-Za-z0-9_$]*$/,S=e=>({k:`a`,v:e}),C=S(`null`),w=S(`number`),T=(e,t=!1)=>({k:`r`,e,ro:t}),E=e=>({k:`o`,f:e}),D=(t,n)=>{if(t)return t;throw new e(`Missing ${n}.`)};function O(...e){let t=[],n=new Set;for(let r of e)for(let e of r.k===`u`?r.m:[r]){let r=j(e,0);n.has(r)||(n.add(r),t.push(e))}return t.length===0?S(`never`):t.length===1?t[0]:{k:`u`,m:t}}function k(e){return x.test(e)?e:JSON.stringify(e)}const A=e=>` `.repeat(e);function j(t,n){switch(t.k){case`a`:return t.v;case`r`:return`${t.ro?`ReadonlyArray`:`Array`}<${j(t.e,n)}>`;case`u`:return t.m.map(e=>j(e,n)).join(` | `);case`o`:{if(t.f.length===0)return`{}`;let e=A(n+1);return`{\n${t.f.map(t=>`${e}${t.ro?`readonly `:``}${k(t.n)}${t.op?`?`:``}: ${j(t.t,n+1)};`).join(`
|
|
2
|
+
`)}\n${A(n)}}`}default:throw new e(`Unknown renderer node.`)}}function M(t){let n=Reflect.get(t[`~`].state.base,`values`);if(!(Array.isArray(n)&&n.every(e=>typeof e==`string`)))throw new e(`Invalid enum values.`);return O(...n.map(e=>S(JSON.stringify(e))))}const N=Object.freeze({string:`string`,time:`string`,int:`number`,number:`number`,decimal:`import("viborm").Decimal`,boolean:`boolean`,datetime:`Date`,date:`Date`,bigint:`bigint`,json:`unknown`,blob:`Uint8Array`});function P(t){let n=t[`~`].state,r;if(Object.hasOwn(N,n.type))r=S(N[n.type]);else if(n.type===`vector`)r=T(w);else if(n.type===`point`)r=E([{n:`longitude`,t:w},{n:`latitude`,t:w}]);else if(n.type===`enum`)r=M(t);else throw new e(`Unsupported renderer scalar.`);return n.array&&(r=T(r)),n.nullable?O(r,C):r}const F=e=>e[`~`].state.nullable?O(S(`string`),C):S(`string`);function I(t){switch(t.kind){case`count`:case`number`:return t.nullable?O(w,C):w;case`scalar`:case`widenedSum`:return O(P(t.scalar),C);case`unknown`:throw new e(`Unknown aggregate field.`);default:throw new e(`Unknown aggregate leaf.`)}}function L(e,t,n){return t===`_count`&&n?.fields===void 0?w:E([...D(n?.fields,`aggregate '${t}' shape`)].map(n=>({n,t:I(y(t,n,e[`~`].state.scalars))})))}function R(e,t,n){let r=e.map(([e,t])=>E([{n:`type`,t:S(JSON.stringify(e)),ro:!0},{n:`data`,t,ro:!0}])),i=r.length===0?S(`never`):O(...r);return t?T(i,!0):n?O(i,C):i}function ee(e,t){return R([...e.variants].map(([e,n])=>[e,V(n.model,n.shape,t)]),e.cardinality===`many`,e.optional)}const z=(e,t)=>e.cardinality===`many`?T(t):e.optional?O(t,C):t;function B(e,t,n,r){let i={n:`VibORMRecursiveNode${r.length+1}`,t:S(`never`)};r.push(i);let a=S(i.n);return i.t=E([...H(t.model,t.shape,r),{n:e,t:z(t,a),...n!==!1&&{op:!0}}]),a}const V=(e,t,n)=>E(H(e,t,n));function H(t,n,r){let i=[];for(let a of n.qu){let o=b(t,a,n);switch(o.kind){case`empty`:break;case`distance`:i.push({n:`_distance`,t:o.scalar?.[`~`].state.type===`point`&&o.scalar[`~`].state.nullable?O(w,C):w});break;case`scalar`:i.push({n:o.key,t:n.n0?.has(o.key)?F(o.scalar):P(o.scalar)});break;case`relation`:{let e=D(o.expected,`relation '${o.key}' shape`),t=e.recurrence?B(o.key,e,e.recurrence.depth,r):V(e.model,e.shape,r);i.push({n:o.key,t:z(e,t)});break}case`polymorphic`:i.push({n:o.key,t:ee(D(o.expected,`polymorphic '${o.key}' shape`),r)});break;case`relationCounts`:i.push({n:`_count`,t:E([...D(o.relations,`relation-count shape`)].map(e=>({n:e,t:w})))});break;case`relationAggregates`:i.push({n:`_aggregate`,t:E([...o.relations].map(([e,t])=>({n:e,t:V(t.model,t.shape,r)})))});break;case`aggregate`:i.push({n:o.name,t:L(t,o.name,o.expected)});break;case`unknown`:throw new e(`Unknown result column '${o.key}'.`);default:throw new e(`Unknown result column.`)}}return i}const U=e=>e.qu.length===1&&e.qu[0]===v?w:E(e.qu.map(e=>({n:e,t:w}))),W=e=>e.map(({n:e,t})=>`type ${e} = ${j(t,0)};`).join(`
|
|
3
|
+
`);function G(e,t,n,r,i){if((t===`createMany`||t===`updateMany`||t===`deleteMany`)&&n===t)return j(E([{n:`count`,t:w}]),0);let a=D(c(e,n,r,i),`result shape for '${t}'`),o=[],s=a.carrier===`existence`?S(`boolean`):a.carrier===`count`?U(a):V(e,a,o);return t===`findMany`||t===`groupBy`||n===`createManyAndReturn`||n===`updateManyAndReturn`||n===`deleteManyAndReturn`?s=T(s):(t===`findFirst`||t===`findUnique`)&&(s=O(s,C)),o.length===0?j(s,0):W([{n:`VibORMOperationResult`,t:s},...o])}function K(t,n){let r=t[`~`].settleTarget(n);if(r instanceof a)return r;throw new e(`Relation target is not a model.`)}function q(e){let t=D(e[`~`].names.ts,`hydrated model name`);return S(`VibORMSchema[${JSON.stringify(t)}]`)}function J(e,t,n,r){let i=D(r.get(e)?.get(t),`relation slot '${t}'`),a=n[`~`].state,o=a.cardinality===`many`,s=m(i);if(_(a))return R(Object.keys(a.target.entries).map(e=>[e,q(K(n,e))]),o,s);let c=q(K(n));return o?T(c):s?O(c,C):c}function Y(e,t,n,r){let a=i(e.source),o=a?Y(a,t,n,r):[];return e.documents.some(e=>!a?.documents.includes(e))&&o.push(...H(e.source,D(c(e.source,`findMany`,t(e.source,e.query),n),`view result shape`),r)),e.documents.map(e=>o.find(t=>t.n===e))}function X(t,n,r,a){let o=t[`~`].state,s=i(t),c=[];for(let r of Object.keys(o.shape)){let i=Object.hasOwn(o.scalars,r)?o.scalars[r]:void 0;if(i){c.push({n:r,t:P(i)});continue}let a=Object.hasOwn(o.relations,r)?o.relations[r]:void 0;if(a){if(s&&!n.get(t)?.has(r))continue;c.push({n:r,t:J(t,r,a,n)});continue}throw new e(`Model '${t[`~`].names.ts??`model`}' has unknown field '${r}'.`)}return s?.documents.length&&c.push(...Y(s,r,n,a)),E(c)}function Z(e,t,n){let r=[];return W([{n:`VibORMSchema`,t:E(Object.entries(e).map(([e,i])=>({n:e,t:X(i,t,n,r)})))},...r])}function Q(e,n){if(r.has(n))return n;throw new t({kind:`registry`,model:e,property:n},[{path:`operation`,message:`${n} does not exist`}])}function $(e,n){if(typeof e==`string`)return e;throw new t({kind:`registry`,property:n},[{path:n,message:`${n} must be a string`}])}function te(e,t){switch(e){case`createMany`:case`updateMany`:case`deleteMany`:return t.select===void 0?e:`${e}AndReturn`;default:return n(e)}}function ne(e,t,r){$(t,`model`);let i=Q(t,$(r,`operation`));return p(e).proxy[t].args[n(i)]}function re(e,t,r,i){let a=$(t,`model`),o=Q(a,$(r,`operation`));return p(e).validate(a,n(o),i??{})}function ie(e,r,i,a){let o=$(r,`model`),s=Q(o,$(i,`operation`)),c=n(s);f(e);let l=g(e),u=h(e,l).validate(o,c,a??{}),d=e[o];if(!d)throw new t({kind:`registry`,model:o},[{path:o,message:`${o} does not exist`}]);return G(d,s,te(s,u),u,l)}function ae(e){f(e);let t=g(e),n=h(e,t);return Z(e,t,(e,t)=>n.validate(e[`~`].names.ts??``,`findMany`,t))}export{re as i,ie as n,ae as r,ne as t};
|
|
4
|
+
//# sourceMappingURL=schema-introspection-Bbo4DN_d.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"schema-introspection-Bbo4DN_d.mjs","names":["expected"],"sources":["../src/query-engine/result/result-aggregate-leaf.ts","../src/query-engine/result/result-column.ts","../src/client/typescript-type-renderer.ts","../src/client/schema-introspection.ts"],"sourcesContent":["import type { Scalar } from \"@schema/scalars\";\nimport type { AggregateResultName } from \"../result-aliases\";\n\nexport type AggregateLeaf =\n | { readonly kind: \"count\"; readonly nullable: false }\n | { readonly kind: \"number\"; readonly nullable: true }\n | {\n readonly kind: \"scalar\";\n readonly nullable: true;\n readonly scalar: Scalar;\n }\n | {\n readonly kind: \"widenedSum\";\n readonly nullable: true;\n readonly scalar: Scalar;\n }\n | { readonly kind: \"unknown\" };\n\n/**\n * The one semantic classification of an aggregate result leaf. Provider\n * parsing and detached cache encoding must agree on widening and nullability.\n *\n * A `_sum` — admitted only on a decimal, bigint, number or int — is its OWN\n * leaf kind because it answers outside the column's declared domain: a number\n * sum may be `±Infinity`, an int sum may pass 2^53 (read as the nearest\n * double), a bigint sum may leave the int64 range, and summing\n * a million `precision: 10` rows is exact arithmetic whose result no single\n * column could store, so it keeps the field's scale and drops the field's\n * precision. Every other decimal aggregate stays in the field domain — `_min`\n * and `_max` are stored values, and `_avg` is quantized to the field's scale\n * by the shared half-even rounder before it leaves the database. Reading a sum\n * through the field decoder would refuse a correct answer; reading an average\n * through the widened one would accept a wrong one.\n */\nexport function classifyAggregateLeaf(\n name: AggregateResultName,\n field: string,\n scalars: Readonly<Record<string, Scalar>>\n): AggregateLeaf {\n const scalar: Scalar | undefined = Object.hasOwn(scalars, field)\n ? scalars[field]\n : undefined;\n if (name === \"_count\") {\n return field === \"_all\" || scalar\n ? { kind: \"count\", nullable: false }\n : { kind: \"unknown\" };\n }\n if (!scalar) return { kind: \"unknown\" };\n if (name === \"_avg\" && scalar[\"~\"].state.type !== \"decimal\") {\n return { kind: \"number\", nullable: true };\n }\n if (name === \"_sum\") return { kind: \"widenedSum\", nullable: true, scalar };\n return { kind: \"scalar\", nullable: true, scalar };\n}\n","import type { Model } from \"@schema/model\";\nimport { type AnyRelation, isVariantRelationState } from \"@schema/relation\";\nimport type { Scalar } from \"@schema/scalars\";\nimport {\n type AggregateResultName,\n DISTANCE_RESULT_KEY,\n EMPTY_ROW_RESULT_KEY,\n getAggregateResultName,\n RELATION_AGGREGATES_RESULT_KEY,\n RELATION_COUNTS_RESULT_KEY,\n} from \"../result-aliases\";\nimport type {\n ExpectedAggregateResultShape,\n ExpectedPolymorphicResultShape,\n ExpectedRelationAggregateShape,\n ExpectedRelationResultShape,\n ExpectedResultShape,\n} from \"../types\";\n\nexport type ResultColumn =\n | { readonly kind: \"empty\" }\n | { readonly kind: \"distance\"; readonly scalar: Scalar | undefined }\n | {\n readonly kind: \"scalar\";\n readonly key: string;\n readonly scalar: Scalar;\n }\n | {\n readonly kind: \"relationCounts\";\n readonly relations: ReadonlySet<string>;\n }\n | {\n readonly kind: \"relationAggregates\";\n readonly relations: ReadonlyMap<string, ExpectedRelationAggregateShape>;\n }\n | {\n readonly kind: \"relation\";\n readonly key: string;\n readonly relation: AnyRelation;\n readonly expected: ExpectedRelationResultShape;\n }\n | {\n readonly kind: \"polymorphic\";\n readonly key: string;\n readonly relation: AnyRelation;\n readonly expected: ExpectedPolymorphicResultShape;\n }\n | {\n readonly kind: \"aggregate\";\n readonly name: AggregateResultName;\n readonly expected: ExpectedAggregateResultShape;\n }\n | { readonly kind: \"unknown\"; readonly key: string };\n\n/**\n * The one semantic classification of a compiled raw result column. SQL aliases\n * are translated to their public result owners here; parsing and detached cache\n * encoding consume the same decision.\n */\nexport function classifyResultColumn(\n model: Model<any>,\n key: string,\n shape: ExpectedResultShape\n): ResultColumn {\n if (key === EMPTY_ROW_RESULT_KEY) return { kind: \"empty\" };\n if (key === DISTANCE_RESULT_KEY) {\n return { kind: \"distance\", scalar: shape.distanceScalar };\n }\n\n const scalars = model[\"~\"].state.scalars;\n const scalar: Scalar | undefined = Object.hasOwn(scalars, key)\n ? scalars[key]\n : undefined;\n if (scalar) return { kind: \"scalar\", key, scalar };\n\n if (key === RELATION_COUNTS_RESULT_KEY) {\n return { kind: \"relationCounts\", relations: shape.relationCounts };\n }\n if (key === RELATION_AGGREGATES_RESULT_KEY && shape.relationAggregates) {\n return { kind: \"relationAggregates\", relations: shape.relationAggregates };\n }\n\n const relations = model[\"~\"].state.relations;\n const relation: AnyRelation | undefined = Object.hasOwn(relations, key)\n ? relations[key]\n : undefined;\n if (relation) {\n if (isVariantRelationState(relation[\"~\"].state)) {\n const expected = shape.polymorphic.get(key);\n if (!expected) return { kind: \"unknown\", key };\n return {\n kind: \"polymorphic\",\n key,\n relation,\n expected,\n };\n }\n const expected = shape.relations.get(key);\n if (!expected) return { kind: \"unknown\", key };\n return {\n kind: \"relation\",\n key,\n relation,\n expected,\n };\n }\n\n const name = getAggregateResultName(key);\n if (name) {\n const expected = shape.aggregates.get(key);\n if (!expected) return { kind: \"unknown\", key };\n return {\n kind: \"aggregate\",\n name,\n expected,\n };\n }\n\n return { kind: \"unknown\", key };\n}\n","import { COUNT_RESULT_KEY } from \"@adapters/shared/result-parsing\";\nimport { QueryEngineError } from \"@errors\";\nimport {\n type AggregateLeaf,\n classifyAggregateLeaf,\n} from \"@query-engine/result/result-aggregate-leaf\";\nimport { classifyResultColumn } from \"@query-engine/result/result-column\";\nimport { buildExpectedResultShape } from \"@query-engine/result/result-shape\";\nimport type {\n ExpectedAggregateResultShape,\n ExpectedPolymorphicResultShape,\n ExpectedRelationResultShape,\n ExpectedResultShape,\n Operation,\n} from \"@query-engine/types\";\nimport { type AnyModel, Model } from \"@schema/model\";\nimport {\n type AnyRelation,\n isVariantRelationState,\n slotMayBeEmpty,\n} from \"@schema/relation\";\nimport type { Scalar, ScalarType } from \"@schema/scalars\";\nimport type { ResolvedRelationIndex } from \"@schema/validation/relation-resolution\";\nimport { type ViewFacts, viewFacts } from \"@schema/view/facts\";\nimport type { Operations, Schema } from \"./types\";\n\ntype TypeNode =\n | { readonly k: \"a\"; readonly v: string }\n | { readonly k: \"r\"; readonly e: TypeNode; readonly ro: boolean }\n | { readonly k: \"o\"; readonly f: readonly TypeField[] }\n | { readonly k: \"u\"; readonly m: readonly TypeNode[] };\n\ninterface TypeField {\n readonly n: string;\n readonly t: TypeNode;\n readonly ro?: true;\n readonly op?: true;\n}\n\ntype AliasDeclaration = { readonly n: string; t: TypeNode };\n\nconst IDENTIFIER = /^[A-Za-z_$][A-Za-z0-9_$]*$/;\nconst atom = (v: string): TypeNode => ({ k: \"a\", v });\nconst NULL_TYPE = atom(\"null\");\nconst NUM_TYPE = atom(\"number\");\nconst arrayOf = (e: TypeNode, ro = false): TypeNode => ({ k: \"r\", e, ro });\nconst objectOf = (f: readonly TypeField[]): TypeNode => ({ k: \"o\", f });\n\nconst need = <T>(v: T | undefined, what: string): T => {\n if (v) return v;\n throw new QueryEngineError(`Missing ${what}.`);\n};\n\nfunction unionOf(...nodes: readonly TypeNode[]): TypeNode {\n const members: TypeNode[] = [];\n const seen = new Set<string>();\n for (const node of nodes) {\n for (const c of node.k === \"u\" ? node.m : [node]) {\n const id = renderType(c, 0);\n if (seen.has(id)) continue;\n seen.add(id);\n members.push(c);\n }\n }\n return members.length === 0\n ? atom(\"never\")\n : members.length === 1\n ? members[0]!\n : { k: \"u\", m: members };\n}\n\nfunction renderPropertyName(name: string): string {\n return IDENTIFIER.test(name) ? name : JSON.stringify(name);\n}\n\nconst indent = (depth: number): string => \" \".repeat(depth);\n\nfunction renderType(node: TypeNode, depth: number): string {\n switch (node.k) {\n case \"a\":\n return node.v;\n case \"r\":\n return `${node.ro ? \"ReadonlyArray\" : \"Array\"}<${renderType(node.e, depth)}>`;\n case \"u\":\n return node.m.map((m) => renderType(m, depth)).join(\" | \");\n case \"o\": {\n if (node.f.length === 0) return \"{}\";\n const pad = indent(depth + 1);\n const fields = node.f.map(\n (f) =>\n `${pad}${f.ro ? \"readonly \" : \"\"}${renderPropertyName(f.n)}${f.op ? \"?\" : \"\"}: ${renderType(f.t, depth + 1)};`\n );\n return `{\\n${fields.join(\"\\n\")}\\n${indent(depth)}}`;\n }\n default:\n throw new QueryEngineError(\"Unknown renderer node.\");\n }\n}\n\nfunction enumType(scalar: Scalar): TypeNode {\n const values = Reflect.get(scalar[\"~\"].state.base, \"values\");\n if (!(Array.isArray(values) && values.every((v) => typeof v === \"string\")))\n throw new QueryEngineError(\"Invalid enum values.\");\n return unionOf(...values.map((v) => atom(JSON.stringify(v))));\n}\n\nconst SCALAR_ATOMS: Readonly<\n Record<Exclude<ScalarType, \"vector\" | \"point\" | \"enum\">, string>\n> = Object.freeze({\n string: \"string\",\n time: \"string\",\n int: \"number\",\n number: \"number\",\n decimal: 'import(\"viborm\").Decimal',\n boolean: \"boolean\",\n datetime: \"Date\",\n date: \"Date\",\n bigint: \"bigint\",\n json: \"unknown\",\n blob: \"Uint8Array\",\n});\n\nfunction scalarType(scalar: Scalar): TypeNode {\n const state = scalar[\"~\"].state;\n let value: TypeNode;\n if (Object.hasOwn(SCALAR_ATOMS, state.type)) {\n value = atom(SCALAR_ATOMS[state.type as keyof typeof SCALAR_ATOMS]);\n } else if (state.type === \"vector\") {\n value = arrayOf(NUM_TYPE);\n } else if (state.type === \"point\") {\n value = objectOf([\n { n: \"longitude\", t: NUM_TYPE },\n { n: \"latitude\", t: NUM_TYPE },\n ]);\n } else if (state.type === \"enum\") {\n value = enumType(scalar);\n } else {\n throw new QueryEngineError(\"Unsupported renderer scalar.\");\n }\n if (state.array) value = arrayOf(value);\n return state.nullable ? unionOf(value, NULL_TYPE) : value;\n}\n\nconst periodType = (scalar: Scalar): TypeNode =>\n scalar[\"~\"].state.nullable\n ? unionOf(atom(\"string\"), NULL_TYPE)\n : atom(\"string\");\n\nfunction aggregateLeafType(leaf: AggregateLeaf): TypeNode {\n switch (leaf.kind) {\n case \"count\":\n case \"number\":\n return leaf.nullable ? unionOf(NUM_TYPE, NULL_TYPE) : NUM_TYPE;\n case \"scalar\":\n case \"widenedSum\":\n return unionOf(scalarType(leaf.scalar), NULL_TYPE);\n case \"unknown\":\n throw new QueryEngineError(\"Unknown aggregate field.\");\n default:\n throw new QueryEngineError(\"Unknown aggregate leaf.\");\n }\n}\n\nfunction aggregateType(\n model: AnyModel,\n name: \"_count\" | \"_avg\" | \"_sum\" | \"_min\" | \"_max\",\n expected: ExpectedAggregateResultShape | undefined\n): TypeNode {\n if (name === \"_count\" && expected?.fields === undefined) return NUM_TYPE;\n const fields = need(expected?.fields, `aggregate '${name}' shape`);\n return objectOf(\n [...fields].map((n) => ({\n n,\n t: aggregateLeafType(\n classifyAggregateLeaf(name, n, model[\"~\"].state.scalars)\n ),\n }))\n );\n}\n\nfunction variantEnvelope(\n variants: readonly (readonly [string, TypeNode])[],\n many: boolean,\n optional: boolean\n): TypeNode {\n const arms = variants.map(([tag, data]) =>\n objectOf([\n { n: \"type\", t: atom(JSON.stringify(tag)), ro: true },\n { n: \"data\", t: data, ro: true },\n ])\n );\n const member = arms.length === 0 ? atom(\"never\") : unionOf(...arms);\n return many\n ? arrayOf(member, true)\n : optional\n ? unionOf(member, NULL_TYPE)\n : member;\n}\n\nfunction polymorphicType(\n expected: ExpectedPolymorphicResultShape,\n declarations: AliasDeclaration[]\n): TypeNode {\n return variantEnvelope(\n [...expected.variants].map(([tag, v]) => [\n tag,\n rowType(v.model, v.shape, declarations),\n ]),\n expected.cardinality === \"many\",\n expected.optional\n );\n}\n\nconst relationValue = (\n expected: ExpectedRelationResultShape,\n row: TypeNode\n): TypeNode =>\n expected.cardinality === \"many\"\n ? arrayOf(row)\n : expected.optional\n ? unionOf(row, NULL_TYPE)\n : row;\n\nfunction recursiveRowType(\n key: string,\n expected: ExpectedRelationResultShape,\n depth: number | false,\n declarations: AliasDeclaration[]\n): TypeNode {\n const declaration: AliasDeclaration = {\n n: `VibORMRecursiveNode${declarations.length + 1}`,\n t: atom(\"never\"),\n };\n declarations.push(declaration);\n const self = atom(declaration.n);\n declaration.t = objectOf([\n ...rowFields(expected.model, expected.shape, declarations),\n {\n n: key,\n t: relationValue(expected, self),\n ...(depth !== false && { op: true as const }),\n },\n ]);\n return self;\n}\n\nconst rowType = (\n model: AnyModel,\n shape: ExpectedResultShape,\n declarations: AliasDeclaration[]\n): TypeNode => objectOf(rowFields(model, shape, declarations));\n\nfunction rowFields(\n model: AnyModel,\n shape: ExpectedResultShape,\n declarations: AliasDeclaration[]\n): TypeField[] {\n const fields: TypeField[] = [];\n for (const rawKey of shape.rawKeys) {\n const column = classifyResultColumn(model, rawKey, shape);\n switch (column.kind) {\n case \"empty\":\n break;\n case \"distance\":\n fields.push({\n n: \"_distance\",\n t:\n column.scalar?.[\"~\"].state.type === \"point\" &&\n column.scalar[\"~\"].state.nullable\n ? unionOf(NUM_TYPE, NULL_TYPE)\n : NUM_TYPE,\n });\n break;\n case \"scalar\":\n fields.push({\n n: column.key,\n t: shape.periods?.has(column.key)\n ? periodType(column.scalar)\n : scalarType(column.scalar),\n });\n break;\n case \"relation\": {\n const expected = need(\n column.expected,\n `relation '${column.key}' shape`\n );\n const relatedRow = expected.recurrence\n ? recursiveRowType(\n column.key,\n expected,\n expected.recurrence.depth,\n declarations\n )\n : rowType(expected.model, expected.shape, declarations);\n fields.push({ n: column.key, t: relationValue(expected, relatedRow) });\n break;\n }\n case \"polymorphic\":\n fields.push({\n n: column.key,\n t: polymorphicType(\n need(column.expected, `polymorphic '${column.key}' shape`),\n declarations\n ),\n });\n break;\n case \"relationCounts\":\n fields.push({\n n: \"_count\",\n t: objectOf(\n [...need(column.relations, \"relation-count shape\")].map((n) => ({\n n,\n t: NUM_TYPE,\n }))\n ),\n });\n break;\n case \"relationAggregates\":\n fields.push({\n n: \"_aggregate\",\n t: objectOf(\n [...column.relations].map(([n, expected]) => ({\n n,\n t: rowType(expected.model, expected.shape, declarations),\n }))\n ),\n });\n break;\n case \"aggregate\":\n fields.push({\n n: column.name,\n t: aggregateType(model, column.name, column.expected),\n });\n break;\n case \"unknown\":\n throw new QueryEngineError(`Unknown result column '${column.key}'.`);\n default:\n throw new QueryEngineError(\"Unknown result column.\");\n }\n }\n return fields;\n}\n\nconst countType = (shape: ExpectedResultShape): TypeNode =>\n shape.rawKeys.length === 1 && shape.rawKeys[0] === COUNT_RESULT_KEY\n ? NUM_TYPE\n : objectOf(shape.rawKeys.map((n) => ({ n, t: NUM_TYPE })));\n\nconst renderDeclarations = (\n declarations: readonly AliasDeclaration[]\n): string =>\n declarations.map(({ n, t }) => `type ${n} = ${renderType(t, 0)};`).join(\"\\n\");\n\nexport function operationResultType(\n model: AnyModel,\n publicOperation: Operations,\n engineOperation: Operation,\n args: Record<string, unknown>,\n index: ResolvedRelationIndex\n): string {\n if (\n (publicOperation === \"createMany\" ||\n publicOperation === \"updateMany\" ||\n publicOperation === \"deleteMany\") &&\n engineOperation === publicOperation\n ) {\n return renderType(objectOf([{ n: \"count\", t: NUM_TYPE }]), 0);\n }\n\n const shape = need(\n buildExpectedResultShape(model, engineOperation, args, index),\n `result shape for '${publicOperation}'`\n );\n\n const declarations: AliasDeclaration[] = [];\n let value =\n shape.carrier === \"existence\"\n ? atom(\"boolean\")\n : shape.carrier === \"count\"\n ? countType(shape)\n : rowType(model, shape, declarations);\n\n if (\n publicOperation === \"findMany\" ||\n publicOperation === \"groupBy\" ||\n engineOperation === \"createManyAndReturn\" ||\n engineOperation === \"updateManyAndReturn\" ||\n engineOperation === \"deleteManyAndReturn\"\n ) {\n value = arrayOf(value);\n } else if (\n publicOperation === \"findFirst\" ||\n publicOperation === \"findUnique\"\n ) {\n value = unionOf(value, NULL_TYPE);\n }\n return declarations.length === 0\n ? renderType(value, 0)\n : renderDeclarations([\n { n: \"VibORMOperationResult\", t: value },\n ...declarations,\n ]);\n}\n\nfunction settledModel(relation: AnyRelation, variant?: string): AnyModel {\n const target = relation[\"~\"].settleTarget(variant);\n if (target instanceof Model) return target;\n throw new QueryEngineError(\"Relation target is not a model.\");\n}\n\nfunction schemaModelReference(model: AnyModel): TypeNode {\n const modelName = need(model[\"~\"].names.ts, \"hydrated model name\");\n return atom(`VibORMSchema[${JSON.stringify(modelName)}]`);\n}\n\nfunction schemaRelationType(\n model: AnyModel,\n fieldName: string,\n relation: AnyRelation,\n index: ResolvedRelationIndex\n): TypeNode {\n const resolved = need(\n index.get(model)?.get(fieldName),\n `relation slot '${fieldName}'`\n );\n const state = relation[\"~\"].state;\n const many = state.cardinality === \"many\";\n const optional = slotMayBeEmpty(resolved);\n if (isVariantRelationState(state)) {\n return variantEnvelope(\n Object.keys(state.target.entries).map((tag) => [\n tag,\n schemaModelReference(settledModel(relation, tag)),\n ]),\n many,\n optional\n );\n }\n const target = schemaModelReference(settledModel(relation));\n return many\n ? arrayOf(target)\n : optional\n ? unionOf(target, NULL_TYPE)\n : target;\n}\n\n/** A `findMany` payload on `model`, admitted as the client admits it. */\nexport type AdmitRead = (\n model: AnyModel,\n args: Readonly<Record<string, unknown>>\n) => Record<string, unknown>;\n\nfunction documentFields(\n facts: ViewFacts,\n admit: AdmitRead,\n index: ResolvedRelationIndex,\n declarations: AliasDeclaration[]\n): TypeField[] {\n const sourceFacts = viewFacts(facts.source);\n const read = sourceFacts\n ? documentFields(sourceFacts, admit, index, declarations)\n : [];\n if (facts.documents.some((name) => !sourceFacts?.documents.includes(name)))\n read.push(\n ...rowFields(\n facts.source,\n need(\n buildExpectedResultShape(\n facts.source,\n \"findMany\",\n admit(facts.source, facts.query),\n index\n ),\n \"view result shape\"\n ),\n declarations\n )\n );\n return facts.documents.map((name) => read.find((f) => f.n === name)!);\n}\n\nfunction schemaModelType(\n model: AnyModel,\n index: ResolvedRelationIndex,\n admit: AdmitRead,\n declarations: AliasDeclaration[]\n): TypeNode {\n const state = model[\"~\"].state;\n const facts = viewFacts(model);\n const fields: TypeField[] = [];\n for (const fieldName of Object.keys(state.shape)) {\n const scalar = Object.hasOwn(state.scalars, fieldName)\n ? state.scalars[fieldName]\n : undefined;\n if (scalar) {\n fields.push({ n: fieldName, t: scalarType(scalar) });\n continue;\n }\n const relation = Object.hasOwn(state.relations, fieldName)\n ? state.relations[fieldName]\n : undefined;\n if (relation) {\n if (facts && !index.get(model)?.has(fieldName)) continue;\n fields.push({\n n: fieldName,\n t: schemaRelationType(model, fieldName, relation, index),\n });\n continue;\n }\n throw new QueryEngineError(\n `Model '${model[\"~\"].names.ts ?? \"model\"}' has unknown field '${fieldName}'.`\n );\n }\n if (facts?.documents.length)\n fields.push(...documentFields(facts, admit, index, declarations));\n return objectOf(fields);\n}\n\nexport function schemaType(\n schema: Schema,\n index: ResolvedRelationIndex,\n admit: AdmitRead\n): string {\n const declarations: AliasDeclaration[] = [];\n const models = Object.entries(schema).map(([n, model]) => ({\n n,\n t: schemaModelType(model, index, admit, declarations),\n }));\n return renderDeclarations([\n { n: \"VibORMSchema\", t: objectOf(models) },\n ...declarations,\n ]);\n}\n","import { ValidationError } from \"@errors\";\nimport {\n baseOperation,\n ROUTED_OPERATIONS,\n} from \"@query-engine/routed-operations\";\nimport type { Operation } from \"@query-engine/types\";\nimport { hydrateSchemaNames } from \"@schema/hydration\";\nimport { resolveSchemaOrThrow } from \"@schema/validation\";\nimport {\n createResolvedSchemaRegistry,\n createSchemaRegistry,\n} from \"@validation/builder\";\nimport type {\n OperationPayloadSchema,\n Operations,\n Schema,\n ValidatedOperationPayload,\n} from \"./types\";\nimport { operationResultType, schemaType } from \"./typescript-type-renderer\";\n\nfunction publicOperationOrThrow(\n modelName: string,\n operation: string\n): Operations {\n if (ROUTED_OPERATIONS.has(operation)) return operation as Operations;\n throw new ValidationError(\n { kind: \"registry\", model: modelName, property: operation },\n [{ path: \"operation\", message: `${operation} does not exist` }]\n );\n}\n\nfunction requireIdentifier(\n value: unknown,\n path: \"model\" | \"operation\"\n): string {\n if (typeof value === \"string\") return value;\n throw new ValidationError({ kind: \"registry\", property: path }, [\n { path, message: `${path} must be a string` },\n ]);\n}\n\nfunction resultOperation(\n operation: Operations,\n args: Record<string, unknown>\n): Operation {\n switch (operation) {\n case \"createMany\":\n case \"updateMany\":\n case \"deleteMany\":\n return args.select === undefined ? operation : `${operation}AndReturn`;\n default:\n return baseOperation(operation);\n }\n}\n\n/** Return the canonical Standard Schema for one public operation payload. */\nexport function getOperationPayloadSchema<\n const S extends Schema,\n ModelName extends Extract<keyof S, string>,\n OperationName extends Operations,\n>(\n schema: S,\n modelName: ModelName,\n operation: OperationName\n): OperationPayloadSchema<OperationName, S[ModelName]>;\nexport function getOperationPayloadSchema<\n const S extends Schema,\n ModelName extends Extract<keyof S, string>,\n>(schema: S, modelName: ModelName, operation: unknown): unknown {\n requireIdentifier(modelName, \"model\");\n const validatedOperation = publicOperationOrThrow(\n modelName,\n requireIdentifier(operation, \"operation\")\n );\n return createSchemaRegistry(schema).proxy[modelName].args[\n baseOperation(validatedOperation)\n ];\n}\n\n/**\n * Validate one public model-operation payload and return its normalized value.\n * This is schema validation, not a driver-specific executability check.\n */\nexport function validateOperationPayload<\n const S extends Schema,\n ModelName extends Extract<keyof S, string>,\n OperationName extends Operations,\n>(\n schema: S,\n modelName: ModelName,\n operation: OperationName,\n payload: unknown\n): ValidatedOperationPayload<OperationName, S[ModelName]>;\nexport function validateOperationPayload(\n schema: Schema,\n modelName: unknown,\n operation: unknown,\n payload: unknown\n): unknown {\n const validatedModelName = requireIdentifier(modelName, \"model\");\n const validatedOperation = publicOperationOrThrow(\n validatedModelName,\n requireIdentifier(operation, \"operation\")\n );\n const registry = createSchemaRegistry(schema);\n return registry.validate(\n validatedModelName,\n baseOperation(validatedOperation),\n payload ?? {}\n );\n}\n\n/**\n * Render the concrete return type for one validated public operation payload.\n * Client extensions and `defaultOmit()` are not part of this schema-only view:\n * on a client whose rules hide rows, a to-one relation can read\n * `null` where the rendered type says it cannot.\n *\n * A payload with a recursive relation slot renders as declarations — a\n * `VibORMOperationResult` alias followed by one `VibORMRecursiveNodeN` alias per\n * recursive slot, numbered outer-first — because a finite recursive type needs\n * a name; every other result renders as one type expression.\n */\nexport function renderOperationResultType<\n const S extends Schema,\n ModelName extends Extract<keyof S, string>,\n>(\n schema: S,\n modelName: ModelName,\n operation: Operations,\n payload: unknown\n): string;\nexport function renderOperationResultType(\n schema: Schema,\n modelName: unknown,\n operation: unknown,\n payload: unknown\n): string {\n const validatedModelName = requireIdentifier(modelName, \"model\");\n const validatedOperation = publicOperationOrThrow(\n validatedModelName,\n requireIdentifier(operation, \"operation\")\n );\n const schemaOperation = baseOperation(validatedOperation);\n hydrateSchemaNames(schema);\n const index = resolveSchemaOrThrow(schema);\n const registry = createResolvedSchemaRegistry(schema, index);\n const validated = registry.validate(\n validatedModelName,\n schemaOperation,\n payload ?? {}\n );\n const model = schema[validatedModelName];\n if (!model) {\n throw new ValidationError({ kind: \"registry\", model: validatedModelName }, [\n {\n path: validatedModelName,\n message: `${validatedModelName} does not exist`,\n },\n ]);\n }\n return operationResultType(\n model,\n validatedOperation,\n resultOperation(validatedOperation, validated),\n validated,\n index\n );\n}\n\n/**\n * Render the complete schema graph as a recursive `VibORMSchema` declaration.\n * Custom JSON schema output is `unknown` because Standard Schema erases it at runtime.\n * A view's JSON columns are typed as the rows its query reads on its source.\n */\nexport function renderSchemaType<const S extends Schema>(schema: S): string {\n hydrateSchemaNames(schema);\n const index = resolveSchemaOrThrow(schema);\n const registry = createResolvedSchemaRegistry(schema, index);\n return schemaType(schema, index, (model, args) =>\n registry.validate(model[\"~\"].names.ts ?? \"\", \"findMany\", args)\n );\n}\n"],"mappings":"0dAkCA,SAAgB,EACd,EACA,EACA,EACe,CACf,IAAM,EAA6B,OAAO,OAAO,EAAS,EAAM,CAC5D,EAAQ,GACR,IAAA,GAWJ,OAVI,IAAS,SACJ,IAAU,QAAU,EACvB,CAAE,KAAM,QAAS,SAAU,GAAO,CAClC,CAAE,KAAM,UAAW,CAEpB,EACD,IAAS,QAAU,EAAO,KAAK,MAAM,OAAS,UACzC,CAAE,KAAM,SAAU,SAAU,GAAM,CAEvC,IAAS,OAAe,CAAE,KAAM,aAAc,SAAU,GAAM,SAAQ,CACnE,CAAE,KAAM,SAAU,SAAU,GAAM,SAAQ,CAL7B,CAAE,KAAM,UAAW,CCYzC,SAAgB,EACd,EACA,EACA,EACc,CACd,GAAI,IAAQ,EAAsB,MAAO,CAAE,KAAM,QAAS,CAC1D,GAAI,IAAQ,EACV,MAAO,CAAE,KAAM,WAAY,OAAQ,EAAM,eAAgB,CAG3D,IAAM,EAAU,EAAM,KAAK,MAAM,QAC3B,EAA6B,OAAO,OAAO,EAAS,EAAI,CAC1D,EAAQ,GACR,IAAA,GAC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AQ,EAAqB,EAAO,CACpC,EAAW,EAA6B,EAAQ,EAAM,CAC5D,OAAO,EAAW,EAAQ,GAAQ,EAAO,IACvC,EAAS,SAAS,EAAM,KAAK,MAAM,IAAM,GAAI,WAAY,EAAK,CAC/D"}
|
package/dist/schema.d.mts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { $
|
|
2
|
-
export { type AnyModel, type AnyRelation, type AutoGenerate, type BigIntScalar, type BigIntSchema, type BlobScalar, type BlobSchema, type BooleanScalar, type BooleanSchema, type DateScalar, type DateTimeScalar, type DecimalDescriptor, type DecimalScalar, type DecimalSchema, type EnumScalar, type EnumSchema, type GeneratorDefaultBrand, type GeoPoint, type Getter, type InitialModelState, type InitialScalarState, type IntScalar, type IntegerSchema, type IsoDateSchema, type IsoTimeSchema, type IsoTimestampSchema, type JsonScalar, type JsonSchema as JsonValueSchema, MYSQL, type Model, type ModelInternal, type ModelShape, type ModelState, type ModelToManyRelation, type ModelToOneRelation, type UpdateState as ModelUpdateState, type NativeType, type NativeTypeMap, type NumberScalar, type NumberSchema, type NumericScalar, PG, type PointScalar, type PointSchema, type ReferencesStage, type ReferentialAction, type RelationCardinality, type RelationSlot, SQLITE, type Scalar, type ScalarKeys, type ScalarState, type UpdateState$1 as ScalarUpdateState, type StringScalar, type StringSchema, type TimeScalar, type VariantToManyRelation, type VariantToOneRelation, type VectorScalar, type VectorSchema, s };
|
|
1
|
+
import { $i as UpdateState, Ai as ModelToOneRelation, At as AutoGenerate, Ba as Getter, Ci as BlobScalar, Da as BlobSchema, Dt as VariantToOneRelation, Et as VariantToManyRelation, Gi as AnyModel, Go as NativeTypeMap, Ha as ReferentialAction, Ho as MYSQL, Ii as VectorSchema, It as UpdateState$1, Ko as PG, Li as StringSchema, Mi as ModelToManyRelation, Mt as GeneratorDefaultBrand, Nt as InitialScalarState, Ot as Scalar, Pt as ScalarState, Qi as ModelState, Sa as DecimalDescriptor, Si as BooleanScalar, Ta as BooleanSchema, Tt as ScalarKeys, Ua as RelationCardinality, Uo as NativeType, Wa as RelationSlot, Xi as Model, Yi as InitialModelState, Zi as ModelInternal, _i as NumberScalar, ai as DecimalScalar, ba as EnumSchema, bi as DateTimeScalar, da as IsoDateSchema, ei as NumericScalar, fa as IsoTimeSchema, ga as GeoPoint, gi as StringScalar, hi as ViewState, ii as EnumScalar, ji as ReferencesStage, ka as BigIntSchema, kt as BigIntScalar, na as IntegerSchema, ni as PointScalar, oa as JsonSchema, oi as s, pa as IsoTimestampSchema, qo as SQLITE, ra as NumberSchema, ri as JsonScalar, ti as VectorScalar, vi as IntScalar, wt as ModelShape, xa as DecimalSchema, xi as DateScalar, yi as TimeScalar, za as AnyRelation, zi as PointSchema } from "./database-adapter-BMjJiBFm.mjs";
|
|
2
|
+
export { type AnyModel, type AnyRelation, type AutoGenerate, type BigIntScalar, type BigIntSchema, type BlobScalar, type BlobSchema, type BooleanScalar, type BooleanSchema, type DateScalar, type DateTimeScalar, type DecimalDescriptor, type DecimalScalar, type DecimalSchema, type EnumScalar, type EnumSchema, type GeneratorDefaultBrand, type GeoPoint, type Getter, type InitialModelState, type InitialScalarState, type IntScalar, type IntegerSchema, type IsoDateSchema, type IsoTimeSchema, type IsoTimestampSchema, type JsonScalar, type JsonSchema as JsonValueSchema, MYSQL, type Model, type ModelInternal, type ModelShape, type ModelState, type ModelToManyRelation, type ModelToOneRelation, type UpdateState as ModelUpdateState, type NativeType, type NativeTypeMap, type NumberScalar, type NumberSchema, type NumericScalar, PG, type PointScalar, type PointSchema, type ReferencesStage, type ReferentialAction, type RelationCardinality, type RelationSlot, SQLITE, type Scalar, type ScalarKeys, type ScalarState, type UpdateState$1 as ScalarUpdateState, type StringScalar, type StringSchema, type TimeScalar, type VariantToManyRelation, type VariantToOneRelation, type VectorScalar, type VectorSchema, type ViewState, s };
|
package/dist/schema.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{i as e,r as t,t as n}from"./native-types-
|
|
1
|
+
import{i as e,r as t,t as n}from"./native-types-1ewJXVks.mjs";import{t as r}from"./schema-DqR_Kcje.mjs";export{n as MYSQL,t as PG,e as SQLITE,r as s};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{o as e,t}from"./sql-tegqTqGq.mjs";function n(e){let t=(e,t)=>({name:t,fz:{table:e,constraint:t}});return{primaryKey:n=>t(n,e(n)),unique:(e,n)=>t(e,`${e}_${n}_key`)}}const r={primaryKey:(e,t)=>({name:`${e}_pkey`,fz:{table:e,columns:[...t]}}),unique:(e,t,n)=>({name:`${e}_${t}_key`,fz:{table:e,columns:[...n]}})};function i(e,t){let n;if(t){let e=t.withinPolygon,r=t.distance;n=Object.freeze({value:t.value,longitude:t.longitude,latitude:t.latitude,equals:t.equals,withinBounds:t.withinBounds,...e?{withinPolygon:e}:{},...r?{distance:r}:{}})}Object.defineProperty(e,`geoPoint`,{value:n,writable:!1,enumerable:!0,configurable:!1})}const a=t=>e.raw(`1${`0`.repeat(t)}`),o=t=>e.raw(t===0?`1`:`0.${`0`.repeat(t-1)}1`),s=(t,n,r)=>{let i=t.gu(n,r),a=t.remainder(n,r);return e`(${i} + (CASE WHEN ABS(${a}) > ${r} - ABS(${a}) OR (ABS(${a}) = ${r} - ABS(${a}) AND ${t.remainder(i,e.raw`2`)} <> 0) THEN (CASE WHEN ${a} < 0 THEN -1 ELSE 1 END) ELSE 0 END))`},c=(t,n)=>e`(CASE WHEN ${n} < 0 THEN -${t} ELSE ${t} END)`,l=(t,n,r,i)=>e`${n} = ${s(t,e`(${n} * ${r} * ${a(i.scale)})`,e.raw`1`)} * ${o(i.scale)}`,u=(t,n,r,i)=>e`${n} = ${s(t,c(e`(${n} * ${a(i.scale)})`,r),e`ABS(${r})`)} * ${o(i.scale)}`,d=(t,n,r)=>e`(${s(t,e`(SUM(${n}) * ${a(r.scale)})`,e`COUNT(${n})`)} * ${o(r.scale)})`;function f(t,n,r,i){return{equals(i,a){let o=t(i),s=r.eq(o,e`${a.longitude}`);return a.longitude===180&&(s=r.or(s,r.eq(o,e`${-180}`))),r.and(s,r.eq(n(i),e`${a.latitude}`))},withinBounds(a,o){let s=t(a),c=r.and(r.gte(n(a),e`${o.south}`),r.lte(n(a),e`${o.north}`)),l;if(o.west===-180&&o.east===180)l=c;else{let t=r.gte(s,e`${o.west}`),n=r.lte(s,e`${o.east}`),i=o.west>o.east?r.or(t,n):r.and(t,n);o.west===-180&&o.east<180&&(i=r.or(i,r.eq(s,e`${180}`))),o.east===180&&o.west>-180&&(i=r.or(i,r.eq(s,e`${-180}`))),l=r.and(c,i)}let u=i?.(a,o);return u?r.and(u,l):l}}}function p(e){return e.south===-90||e.north===90||e.south===e.north||e.west===e.east||e.west>e.east||e.west===-180||e.east===180?[]:[m(e.west,e.east,e.south,e.north)]}function m(e,t,n,r){let i=[e,...[-90,0,90].filter(n=>e<n&&n<t),t],a=i.map(e=>[e,n]),o=[...i].reverse().map(e=>[e,r]);return JSON.stringify({type:`Polygon`,coordinates:[[...a,...o,a[0]]]})}function h(e){let t=[g(e.outer)];if(e.holes)for(let n of e.holes)t.push(g(n));return JSON.stringify({type:`Polygon`,coordinates:t})}function g(e){let t=Array(e.length+1);for(let n=0;n<e.length;n+=1){let r=e[n];t[n]=[r.longitude,r.latitude]}let n=e[0];return t[e.length]=[n.longitude,n.latitude],t}const _=(e,t,n)=>{e.strings.push(t),e.values.push(n)},v=(e,t,n,r)=>{let i=[e,t,``,``,``,``,``,``],a=[n,r,n,n,n,n];return i.length=2,a.length=2,{strings:i,values:a}},y=(e,n=``)=>(e.strings.push(n),new t(e.strings,e.values)),b=(e,t,n)=>{let r=n?{strings:[`SELECT DISTINCT ON (`,`) `,` FROM `],values:[n,e.columns,e.from]}:v(`SELECT `,` FROM `,e.columns,e.from);return x(r,e),e.orderBy&&_(r,` ORDER BY `,e.orderBy),S(r,e.limit,e.offset,t.noLimitValue),y(r,t.sb===`append`&&e.sb?` FOR UPDATE`:``)},x=(e,t)=>{if(t.joins)for(let n of t.joins)_(e,` `,n);t.where&&_(e,` WHERE `,t.where),t.groupBy&&_(e,` GROUP BY `,t.groupBy),t.having&&_(e,` HAVING `,t.having)},S=(e,t,n,r)=>{t?_(e,` LIMIT `,t):n&&r&&_(e,` LIMIT `,r),n&&_(e,` OFFSET `,n)},C=(t,n,r,i)=>{let a=t.jx??t.orderBy??n,o=t.zg,s=[t.columns];o&&s.push(o.keys),s.push(e`ROW_NUMBER() OVER (PARTITION BY ${n} ORDER BY ${a}) AS ${r(`_rn`)}`);let c={strings:[`SELECT `,` FROM `],values:[e.join(s,`, `),t.from]};x(c,t);let l=y(c),u=t.mh.map(r),d={strings:[``],values:[e`SELECT ${e.join(u,`, `)} FROM (${l}) AS ${r(`_distinct_subquery`)} WHERE ${r(`_rn`)} = 1`]};return o&&_(d,` ORDER BY `,o.orderBy),S(d,t.limit,t.offset,i),y(d)};export{h as a,u as c,o as d,c as f,r as h,p as i,l,n as m,b as n,s as o,i as p,f as r,d as s,C as t,a as u};
|
|
2
|
+
//# sourceMappingURL=select-assembly-CEpNu-Gw.mjs.map
|