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":"json-CsAdz9pg.mjs","names":["date","model","member","view","modelFactory","viewFactory","options","view","model","options","options","model","member","options"],"sources":["../src/schema/json/issues.ts","../src/schema/json/default-codec.ts","../src/schema/json/document.ts","../src/schema/json/factories.ts","../src/schema/json/interpret.ts","../src/schema/json/read.ts","../src/schema/json/validate.ts","../src/schema/json/serialize.ts","../src/schema/json/index.ts"],"sourcesContent":["// The document refusal vocabulary: the `J0xx` code family, JSON-pointer paths,\n// the one aggregate throw, and the one guarded read that turns caller code into\n// a member of that vocabulary.\n//\n// A document failure is never confused with a topology failure: the schema\n// resolver's `M0xx`/`R0xx`/`P0xx` codes describe a graph, these describe the\n// artifact the author wrote. Paths are JSON pointers INTO THE DOCUMENT for the\n// same reason.\n\nimport { ValidationError, type ValidationIssue } from \"@errors\";\nimport { declaredKeys, isPlainRecord } from \"@schema/relation/terminal\";\nimport { toError } from \"../../errors/diagnostic-safety\";\n\n/**\n * Why a document was refused.\n *\n * - `J001` the input is not a JSON document at all\n * - `J002` the `version` is not one this parser reads\n * - `J003` a node carries a key the format does not define\n * - `J004` a node is missing a required key, or a value has the wrong shape\n * - `J005` a key that must be a schema identifier is not one\n * - `J006` a reference names something the document does not declare\n * - `J007` the scalar type has no such modifier\n * - `J008` a default is outside the field's own domain\n * - `J009` the document spells a surface v1 refuses\n * - `J010` a builder refused the declaration this node denotes\n * - `J011` a native type is not in the declared dialect's catalog\n * - `J012` views read each other in a cycle\n * - `J013` a key names both a model and a view\n */\nexport type DocumentIssueCode =\n | \"J001\"\n | \"J002\"\n | \"J003\"\n | \"J004\"\n | \"J005\"\n | \"J006\"\n | \"J007\"\n | \"J008\"\n | \"J009\"\n | \"J010\"\n | \"J011\"\n | \"J012\"\n | \"J013\";\n\n/** The document root pointer, and the source path every refusal carries. */\nconst DOCUMENT_ROOT = \"\";\n\nconst POINTER_TILDE = /~/g;\nconst POINTER_SLASH = /\\//g;\n\n/** One document location, spelled as an RFC 6901 JSON pointer. */\nexport function pointer(parent: string, ...keys: readonly string[]): string {\n let path = parent;\n for (const key of keys) {\n path += `/${key.replace(POINTER_TILDE, \"~0\").replace(POINTER_SLASH, \"~1\")}`;\n }\n return path;\n}\n\nexport const documentRoot = DOCUMENT_ROOT;\n\n/**\n * The accumulator every reader threads.\n *\n * `v.object` is strict but fail-fast — one issue per validate — so a document\n * walk that wants to tell an author everything wrong with their artifact at\n * once collects its own list, exactly as the schema validator and the relation\n * resolver do.\n */\nexport type DocumentIssues = ValidationIssue[];\n\nexport function addIssue(\n issues: DocumentIssues,\n path: string,\n code: DocumentIssueCode,\n message: string\n): void {\n issues.push({ path, message: `[${code}] ${message}` });\n}\n\n/**\n * The one aggregate refusal. `V4002` with a `schema-builder` source names this\n * boundary in the message; the issue list carries every pointer.\n */\nexport function refuseDocument(\n issues: DocumentIssues,\n cause?: Error\n): ValidationError {\n return new ValidationError(\n { kind: \"schema-builder\", builder: \"schema-json\", path: DOCUMENT_ROOT },\n issues,\n cause === undefined ? undefined : { cause }\n );\n}\n\n/** Throw the accumulated issues, if the walk found any. */\nexport function throwIfRefused(issues: DocumentIssues): void {\n if (issues.length > 0) {\n throw refuseDocument(issues);\n }\n}\n\n/**\n * Read one property of a caller-supplied object exactly once.\n *\n * Every value this module reads from outside — a document node, an array\n * element by index, a default, the options bag — is reached through here, and\n * for one reason: `parseSchema` and `serializeSchema` accept objects the caller\n * built, so a property read is EXECUTABLE input. A throwing accessor becomes\n * this boundary's own issue instead of escaping as the caller's value, and what\n * it threw survives as the refusal's cause.\n *\n * It also ENDS the walk. A document that runs code while being read is not one\n * to keep collecting shape issues from, so everything found so far is carried\n * out with it.\n *\n * `key` is a property name; an array element is read by its index spelled as\n * one. Array `length` is not read through here: on a value `Array.isArray`\n * accepts it is a non-configurable own data property, which no accessor can\n * replace.\n */\nexport function member(\n record: object,\n key: string,\n path: string,\n issues: DocumentIssues\n): unknown {\n return guardedValue(record, key, path, issues, \"J004\");\n}\n\n// =============================================================================\n// GUARDED INSPECTION — the JSON boundary's total owner (external review 3)\n// =============================================================================\n//\n// `isPlainRecord` and `declaredKeys` in relation/terminal stay the RULE OWNERS:\n// they decide what a plain record IS and what its declaration keys ARE. The\n// three wrappers here add only the boundary adaptation the JSON entry points\n// need — the hostile-trap guarding (a proxy's `getPrototypeOf` or `ownKeys`\n// trap is executable input, exactly as a property accessor is) and the\n// conversion of a caught throw into this family's J-code. They restate none of\n// the predicates' logic; the `code` argument is the one direction-dependent\n// fact (`J004` inbound, `J009` for the serializer's own read of a coded value).\n\n/**\n * Read one caller-owned property, converting a throwing accessor into a coded\n * refusal that carries what it threw. `member` is this at `J004`.\n */\nexport function guardedValue(\n record: object,\n key: string,\n path: string,\n issues: DocumentIssues,\n code: DocumentIssueCode\n): unknown {\n try {\n return Reflect.get(record, key);\n } catch (thrown) {\n addIssue(issues, pointer(path, key), code, \"Property read threw\");\n throw refuseDocument(issues, toError(thrown));\n }\n}\n\nexport function inspectPlainRecord(\n value: unknown,\n path: string,\n issues: DocumentIssues,\n code: DocumentIssueCode\n): value is Record<string, unknown> {\n try {\n return isPlainRecord(value);\n } catch (thrown) {\n addIssue(issues, path, code, \"Prototype read threw\");\n throw refuseDocument(issues, toError(thrown));\n }\n}\n\nexport function inspectKeys(\n record: Record<string, unknown>,\n path: string,\n issues: DocumentIssues,\n code: DocumentIssueCode\n): string[] {\n try {\n return declaredKeys(record);\n } catch (thrown) {\n addIssue(issues, path, code, \"Key enumeration threw\");\n throw refuseDocument(issues, toError(thrown));\n }\n}\n\n/**\n * A caller VALUE of unknown type, rendered into an issue message without running\n * caller code. `JSON.stringify` throws on a `bigint`, and coercing an object\n * would run its own `toString`; this does neither. Keys and tags are already\n * strings and interpolate directly — this is for the values, like a `version`,\n * that are not.\n */\nexport function renderValue(value: unknown): string {\n if (typeof value === \"bigint\") {\n return `${value}n`;\n }\n if (typeof value === \"object\") {\n // `typeof null === \"object\"` too; both render by type, never coerced.\n return `[${typeof value}]`;\n }\n return String(value);\n}\n\n/**\n * Re-throw a builder's refusal with the document location that produced it.\n *\n * The builders own every semantic refusal in the declaration surface; this\n * boundary owns only the fact that the author wrote it HERE. The original error\n * stays attached as the cause, so its own message and type survive.\n *\n * The refusal is always an `Error`: the relation factories throw\n * `ValidationError`, blob throws `Error`, and every caller-supplied value that\n * could throw anything else was already read through the document reader's own\n * guarded accessor, which never reaches a builder.\n */\nexport function refuseFromBuilder(path: string, thrown: Error): never {\n const issues: DocumentIssues = [];\n addIssue(issues, path, \"J010\", thrown.message);\n throw refuseDocument(issues, thrown);\n}\n","// The default codec: the one conversion between a declaration's default value\n// and the JSON that states it, in both directions. A view's query holds values\n// from the same domains (a `Date` or a `bigint` in a filter), so it is written\n// by the same codec and the same tags.\n//\n// A default holds a value from a domain the FIELD chose rather than the\n// format. `.default(...)` takes the scalar's own input\n// domain, and three members of those domains have no JSON spelling — `bigint`,\n// `Date`, `Uint8Array` — while a `json` field's domain is an arbitrarily deep\n// structure that may contain them at any position.\n//\n// Hence one RECURSIVE codec rather than a table of top-level envelopes, and\n// four properties it owns end to end:\n//\n// - TAGGED, not positional. `{\"$date\": \"...\"}` is a `Date`; a bare ISO string\n// is a string. The distinction is observable — DDL emits a string default as\n// a SQL `DEFAULT` clause and leaves a `Date` to the application — so a codec\n// that inferred the type from the FIELD would round-trip one declaration\n// into a different table.\n// - DETACHED. Both directions build new structures. A document is a value the\n// caller owns and edits; declaration state is not.\n// - `__proto__`-SAFE. Every record is constructed key by key, because\n// `record[\"__proto__\"] = value` sets a prototype and creates no own key —\n// losing the entry silently, which is the one failure mode a walk cannot\n// report afterwards.\n// - TOTAL. A cycle is a refusal with a pointer, never a `RangeError`; a value\n// the document cannot state is named, never dropped.\n//\n// The `$`-prefixed one-key object is a RESERVED namespace: an unknown one is\n// refused rather than read as a literal, so a later version can add a tag\n// without changing what an existing document means. `$raw` is how a literal\n// whose own shape collides with a tag says which it is.\n\nimport { DbNull, JsonNull, jsonNullKindOf } from \"@schema/json-null\";\nimport { emptyRecord, put } from \"@schema/record\";\nimport type { JsonValue } from \"@validation/primitives/json\";\nimport { isDate, isFunction, isUint8Array } from \"@validation/value-guards\";\nimport {\n addIssue,\n type DocumentIssues,\n guardedValue,\n inspectKeys,\n inspectPlainRecord,\n member,\n pointer,\n refuseDocument,\n} from \"./issues\";\n\nconst BIGINT_TAG = \"$bigint\";\nconst DATE_TAG = \"$date\";\nconst BYTES_TAG = \"$bytes\";\nconst RAW_TAG = \"$raw\";\nconst JSON_NULL_TAG = \"$jsonNull\";\n\n/** The reserved namespace this format defines; anything else `$`-prefixed is refused. */\nconst KNOWN_TAGS = new Set([\n BIGINT_TAG,\n DATE_TAG,\n BYTES_TAG,\n RAW_TAG,\n JSON_NULL_TAG,\n]);\n\nconst RESERVED_PREFIX = \"$\";\nconst DECIMAL_INTEGER = /^-?\\d+$/;\n\nconst TAGS = `'${BIGINT_TAG}', '${DATE_TAG}', '${BYTES_TAG}', '${RAW_TAG}', '${JSON_NULL_TAG}'`;\n\nexport function reservedKey(keys: readonly string[]): string | undefined {\n const only = keys.length === 1 ? keys[0] : undefined;\n return only?.startsWith(RESERVED_PREFIX) === true ? only : undefined;\n}\n\nexport type ValueRole = \"default\" | \"query\";\n\nconst ROLE_WORDS: Readonly<\n Record<\n ValueRole,\n {\n readonly value: string;\n readonly whole: string;\n readonly function: string;\n readonly admitted: string;\n }\n >\n> = {\n default: {\n value: \"Default\",\n whole: \"Default\",\n function:\n \"Function default not allowed; use `generate`, a literal, or `native`\",\n admitted: \"JSON, bigint, Date, or Uint8Array\",\n },\n query: {\n value: \"View query value\",\n whole: \"View query\",\n function: \"Functions not allowed in view query\",\n admitted: \"JSON, bigint, Date, Uint8Array, or JSON null sentinel\",\n },\n};\n\n/** One walk: the containers on the path being walked, and whose value it is. */\ninterface Walk {\n readonly seen: Set<object>;\n readonly role: ValueRole;\n}\n\n// =============================================================================\n// READING A DOCUMENT'S DEFAULT\n// =============================================================================\n\n/**\n * A JSON value, read out of caller-controlled input.\n *\n * A caller-built object may hold a function, a symbol, a `bigint` or a `Date`\n * where JSON text cannot; refusing them here is what keeps a document and its\n * serialization the same artifact. What comes back is a fresh structure — the\n * caller keeps no reference into the schema that is about to be built.\n */\nexport function readDefaultValue(\n value: unknown,\n path: string,\n issues: DocumentIssues,\n role: ValueRole = \"default\"\n): JsonValue | undefined {\n return readValue(value, path, issues, { seen: new Set(), role });\n}\n\n/** A plain record's members, each read as {@link readDefaultValue} reads a value. */\nexport function readValueRecord(\n value: Record<string, unknown>,\n path: string,\n issues: DocumentIssues,\n role: ValueRole\n): Record<string, JsonValue> | undefined {\n return readRecord(value, path, issues, { seen: new Set(), role });\n}\n\nfunction readValue(\n value: unknown,\n path: string,\n issues: DocumentIssues,\n walk: Walk\n): JsonValue | undefined {\n if (value === null || typeof value === \"string\") return value;\n if (typeof value === \"boolean\") return value;\n if (typeof value === \"number\") {\n if (Number.isFinite(value)) return value;\n addIssue(\n issues,\n path,\n \"J004\",\n `${ROLE_WORDS[walk.role].value} must be a finite number`\n );\n return;\n }\n if (Array.isArray(value)) return readArray(value, path, issues, walk);\n if (inspectPlainRecord(value, path, issues, \"J004\")) {\n return readRecord(value, path, issues, walk);\n }\n addIssue(\n issues,\n path,\n \"J004\",\n isFunction(value)\n ? ROLE_WORDS[walk.role].function\n : `${ROLE_WORDS[walk.role].value} must be JSON or tagged (${TAGS})`\n );\n return;\n}\n\nfunction readArray(\n value: readonly unknown[],\n path: string,\n issues: DocumentIssues,\n walk: Walk\n): JsonValue[] | undefined {\n if (enterCycle(value, path, issues, walk, \"J004\")) return;\n const items: JsonValue[] = [];\n for (let index = 0; index < value.length; index += 1) {\n const entryPath = pointer(path, String(index));\n const item = readValue(\n member(value, String(index), path, issues),\n entryPath,\n issues,\n walk\n );\n if (item === undefined) return;\n items.push(item);\n }\n walk.seen.delete(value);\n return items;\n}\n\nfunction readRecord(\n value: Record<string, unknown>,\n path: string,\n issues: DocumentIssues,\n walk: Walk\n): Record<string, JsonValue> | undefined {\n if (enterCycle(value, path, issues, walk, \"J004\")) return;\n const keys = inspectKeys(value, path, issues, \"J004\");\n const tag = reservedKey(keys);\n if (tag !== undefined && !KNOWN_TAGS.has(tag)) {\n addIssue(issues, path, \"J008\", `Unknown tag '${tag}', expected ${TAGS}`);\n return;\n }\n const record = emptyRecord<JsonValue>();\n for (const key of keys) {\n const entry = readValue(\n member(value, key, path, issues),\n pointer(path, key),\n issues,\n walk\n );\n if (entry === undefined) return;\n put(record, key, entry);\n }\n walk.seen.delete(value);\n return record;\n}\n\n/**\n * Whether this value is already on the path being walked.\n *\n * A default is the one node whose depth the format does not bound, so it is the\n * one walk a caller-built object can make non-terminating. Membership is\n * released on the way back up: the same object twice in different branches is a\n * shared subtree, which copies fine.\n */\nfunction enterCycle(\n value: object,\n path: string,\n issues: DocumentIssues,\n walk: Walk,\n code: \"J004\" | \"J009\"\n): boolean {\n if (!walk.seen.has(value)) {\n walk.seen.add(value);\n return false;\n }\n addIssue(\n issues,\n path,\n code,\n `${ROLE_WORDS[walk.role].whole} contains a cycle`\n );\n return true;\n}\n\n// =============================================================================\n// DOCUMENT → DECLARATION\n// =============================================================================\n\n/**\n * The value a document's `default` denotes.\n *\n * Every tag is decoded here and nowhere else, and the result is a fresh\n * structure. What comes back still has to satisfy the field's own base schema —\n * that check has one owner in the interpreter, and this codec never duplicates\n * it: `{\"$date\": ...}` on a `json` field decodes to a real `Date` and is\n * refused there, by the domain that says so.\n */\nexport function decodeDefault(value: JsonValue, path: string): unknown {\n if (Array.isArray(value)) {\n return value.map((entry, index) =>\n decodeDefault(entry, pointer(path, String(index)))\n );\n }\n if (value === null || typeof value !== \"object\") return value;\n const tag = reservedKey(Object.keys(value));\n if (tag === undefined) return decodeBody(value, path);\n const payload = value[tag];\n // `readDefaultValue` already refused every reserved-key envelope whose tag is\n // not one of these four, during the accumulating walk — so an unknown tag\n // never reaches decoding and this dispatch is total, `$bytes` being the last.\n // One guard per invariant: the unknown-tag refusal lives in the reader alone.\n if (tag === RAW_TAG) return decodeRaw(payload, path);\n if (tag === BIGINT_TAG) return decodeBigInt(payload, path);\n if (tag === DATE_TAG) return decodeDate(payload, path);\n if (tag === JSON_NULL_TAG) {\n if (payload === \"JsonNull\") return JsonNull;\n if (payload === \"DbNull\") return DbNull;\n throw refuseTag(path, `'${JSON_NULL_TAG}' takes 'JsonNull' or 'DbNull'`);\n }\n return decodeBytes(payload, path);\n}\n\n/** Each value decoded; the record's OWN tag shape deliberately not read. */\nfunction decodeBody(\n value: Record<string, JsonValue>,\n path: string\n): Record<string, unknown> {\n const record = emptyRecord<unknown>();\n for (const key of Object.keys(value)) {\n put(record, key, decodeDefault(value[key] ?? null, pointer(path, key)));\n }\n return record;\n}\n\n/**\n * The escape. `$raw` suppresses tag reading at ITS OWN level only, which is the\n * one level the encoder had to escape; everything inside is an ordinary value.\n */\nfunction decodeRaw(payload: JsonValue | undefined, path: string): unknown {\n if (payload === null || typeof payload !== \"object\") return payload;\n if (Array.isArray(payload)) return decodeDefault(payload, path);\n return decodeBody(payload, path);\n}\n\nfunction decodeBigInt(payload: JsonValue | undefined, path: string): bigint {\n if (typeof payload === \"string\" && DECIMAL_INTEGER.test(payload)) {\n return BigInt(payload);\n }\n throw refuseTag(path, `'${BIGINT_TAG}' takes a decimal integer string`);\n}\n\nfunction decodeDate(payload: JsonValue | undefined, path: string): Date {\n if (typeof payload === \"string\") {\n const date = new Date(payload);\n if (!Number.isNaN(date.getTime())) return date;\n }\n throw refuseTag(path, `'${DATE_TAG}' takes a string naming an instant`);\n}\n\nfunction decodeBytes(payload: JsonValue | undefined, path: string): Uint8Array {\n if (typeof payload === \"string\") {\n try {\n return decodeBase64(payload);\n } catch {\n // Fall through to the one refusal below.\n }\n }\n throw refuseTag(path, `'${BYTES_TAG}' takes a base64 string`);\n}\n\nfunction refuseTag(path: string, reason: string): Error {\n const issues: DocumentIssues = [];\n addIssue(issues, path, \"J008\", `${reason}. The tags are ${TAGS}`);\n return refuseDocument(issues);\n}\n\nfunction decodeBase64(text: string): Uint8Array {\n const binary = atob(text);\n const bytes = new Uint8Array(binary.length);\n for (let index = 0; index < binary.length; index += 1) {\n bytes[index] = binary.charCodeAt(index);\n }\n return bytes;\n}\n\n// =============================================================================\n// DECLARATION → DOCUMENT\n// =============================================================================\n\n/**\n * The JSON a declaration's default value denotes.\n *\n * Every value outside JSON is tagged, every structure is copied, and anything\n * the document cannot state is named with its own pointer rather than dropped —\n * a dropped default parses back into a field that has none.\n */\nexport function encodeDefault(\n value: unknown,\n path: string,\n issues: DocumentIssues,\n role: ValueRole = \"default\"\n): JsonValue | undefined {\n return encodeValue(value, path, issues, { seen: new Set(), role });\n}\n\n/** A plain record's members, each written as {@link encodeDefault} writes a value. */\nexport function encodeValueRecord(\n value: Readonly<Record<string, unknown>>,\n path: string,\n issues: DocumentIssues,\n role: ValueRole\n): Record<string, JsonValue> | undefined {\n return encodeRecord(value, path, issues, { seen: new Set(), role });\n}\n\nfunction encodeValue(\n value: unknown,\n path: string,\n issues: DocumentIssues,\n walk: Walk\n): JsonValue | undefined {\n const nullKind = jsonNullKindOf(value);\n if (nullKind === \"JsonNull\" || nullKind === \"DbNull\")\n return tagged(JSON_NULL_TAG, nullKind);\n if (value === null || typeof value === \"string\") return value;\n if (typeof value === \"boolean\") return value;\n if (typeof value === \"number\") {\n if (Number.isFinite(value)) return value;\n return refuseValue(issues, path, \"Non-finite number cannot be serialized\");\n }\n if (typeof value === \"bigint\") return tagged(BIGINT_TAG, value.toString(10));\n if (isUint8Array(value)) {\n try {\n return tagged(BYTES_TAG, encodeBase64(value));\n } catch {\n return refuseValue(issues, path, \"Byte string has a detached buffer\");\n }\n }\n if (isDate(value)) {\n if (Number.isNaN(Date.prototype.getTime.call(value))) {\n return refuseValue(issues, path, \"Invalid Date\");\n }\n return tagged(DATE_TAG, Date.prototype.toISOString.call(value));\n }\n if (Array.isArray(value)) return encodeArray(value, path, issues, walk);\n if (inspectPlainRecord(value, path, issues, \"J009\")) {\n return encodeRecord(value, path, issues, walk);\n }\n return refuseValue(\n issues,\n path,\n `${ROLE_WORDS[walk.role].whole}: unsupported value (${ROLE_WORDS[walk.role].admitted})`\n );\n}\n\nfunction tagged(tag: string, payload: string): Record<string, JsonValue> {\n const record = emptyRecord<JsonValue>();\n put(record, tag, payload);\n return record;\n}\n\nfunction encodeArray(\n value: readonly unknown[],\n path: string,\n issues: DocumentIssues,\n walk: Walk\n): JsonValue[] | undefined {\n if (enterCycle(value, path, issues, walk, \"J009\")) return;\n const items: JsonValue[] = [];\n // An array INDEX is an ordinary property, so a coded default's element is read\n // through the same guarded accessor an inbound one is — a throwing index\n // accessor becomes the serializer's refusal, never a raw escape.\n for (let index = 0; index < value.length; index += 1) {\n const at = String(index);\n const item = encodeValue(\n guardedValue(value, at, path, issues, \"J009\"),\n pointer(path, at),\n issues,\n walk\n );\n if (item === undefined) return;\n items.push(item);\n }\n walk.seen.delete(value);\n return items;\n}\n\n/**\n * A record, then the escape decision.\n *\n * The encoded record is what a reader will see, so it is the encoded shape that\n * decides: one own key beginning with `$` would be read back as a tag, and\n * `$raw` says it is not one.\n */\nfunction encodeRecord(\n value: Record<string, unknown>,\n path: string,\n issues: DocumentIssues,\n walk: Walk\n): Record<string, JsonValue> | undefined {\n if (enterCycle(value, path, issues, walk, \"J009\")) return;\n const record = emptyRecord<JsonValue>();\n // A coded default's own keys and values are read through the same guarded\n // owner an inbound record is: a hostile `ownKeys` trap or a throwing accessor\n // becomes the serializer's refusal rather than escaping `serializeSchema`.\n for (const key of inspectKeys(value, path, issues, \"J009\")) {\n const entry = encodeValue(\n guardedValue(value, key, path, issues, \"J009\"),\n pointer(path, key),\n issues,\n walk\n );\n if (entry === undefined) return;\n put(record, key, entry);\n }\n walk.seen.delete(value);\n if (reservedKey(Object.keys(record)) === undefined) return record;\n const escaped = emptyRecord<JsonValue>();\n put(escaped, RAW_TAG, record);\n return escaped;\n}\n\nfunction refuseValue(\n issues: DocumentIssues,\n path: string,\n reason: string\n): undefined {\n addIssue(issues, path, \"J009\", reason);\n return;\n}\n\nfunction encodeBase64(bytes: Uint8Array): string {\n // One character at a time: spreading a large byte array into\n // `String.fromCharCode` overflows the stack.\n let binary = \"\";\n const values = Uint8Array.prototype.values.call(bytes);\n for (const byte of values) binary += String.fromCharCode(byte);\n return btoa(binary);\n}\n","// The JSON schema document format.\n//\n// This file is the FORMAT: the declaration-state algebra spelled as data, with\n// model-key strings where a coded schema writes a getter. Nothing here decides\n// anything — `read.ts` owns whether a value has this shape, `interpret.ts` owns\n// what the builders make of it, and `serialize.ts` owns the reverse direction.\n// One type serves all three, so the format has exactly one definition.\n\nimport type { IndexType } from \"@schema/model/model\";\nimport type {\n JunctionReferentialAction,\n ReferentialAction,\n} from \"@schema/relation/types\";\nimport type { AutoGenerateType, ScalarType } from \"@schema/scalars/common\";\nimport type { NativeType, NativeTypeMap } from \"@schema/scalars/native-types\";\nimport type { JsonValue } from \"@validation/primitives/json\";\n\n/**\n * The only supported document version.\n *\n * An unknown version is refused by name rather than tolerated: a document key\n * never changes meaning across versions, so evolution adds keys and a parser\n * that cannot read a version cannot guess at it either.\n */\nexport const SCHEMA_DOCUMENT_VERSION = 1;\n\n/** A schema stated as data. `parseSchema` reads it; `serializeSchema` writes it. */\nexport interface SchemaDocument {\n version: typeof SCHEMA_DOCUMENT_VERSION;\n /**\n * A light document: what a client needs and nothing only migrations read\n * (`introspectSchema({ light: true })` leaves out every index). A client\n * reads and writes through it; every migration path refuses its models.\n */\n light?: true;\n /**\n * Enum definitions addressable by a document-local reference. A definition\n * carrying `name` yields ONE database enum type shared by every field that\n * references it; without `name` each column keeps its own derived type,\n * exactly as an inline `\"enum\": [\"a\", \"b\"]` does.\n *\n * The KEY is that reference and must be a schema identifier; the database's\n * own type name lives in `name` alone, and may be anything the database\n * allows.\n */\n enums?: Record<string, EnumDocument>;\n models: Record<string, ModelDocument>;\n /**\n * Database views, `s.view(() => source, query)`, by schema key. A view key\n * and a model key share the schema's one namespace, so no key is both.\n */\n views?: Record<string, ViewDocument>;\n}\n\n/**\n * One view: the rows `findMany(query)` reads on `source`.\n *\n * Its columns, keys and JSON columns are not written: `s.view` derives them\n * from the source and the query, so stating them would be a second copy.\n */\nexport interface ViewDocument {\n /** The model key or view key the view reads. */\n source: string;\n /**\n * What `findMany` takes on the source, as JSON. A value JSON cannot spell\n * takes the tag a default takes: `{\"$date\": \"<iso>\"}`, `{\"$bigint\": \"5\"}`,\n * `{\"$bytes\": \"AQID\"}`, `{\"$jsonNull\": \"JsonNull\"}`, and `{\"$raw\": <value>}`\n * for a literal whose own shape is a tag (a `$through` filter, say). A\n * function or a caller `Sql` operand has no spelling.\n */\n query: Record<string, JsonValue>;\n /** `.map(viewName)`. */\n table?: string;\n /** `.materialized()`: present only as `true`. */\n materialized?: true;\n /** `.materialized({ refresh: \"auto\" })`: present only as `\"auto\"`, beside `materialized`. */\n refresh?: \"auto\";\n /**\n * `.index(fields, options)` calls in declaration order, as a model writes\n * them: a materialized view's, on its scalar columns (W002).\n */\n indexes?: IndexDocument[];\n}\n\nexport interface EnumDocument {\n values: string[];\n /**\n * The database enum type name — `.name()`. Not the reference key: a database\n * identifier is not a schema identifier, so the canonical document uses the\n * name as its key only when it already passes that grammar and derives\n * `enum_1`, `enum_2` … by declaration order otherwise.\n */\n name?: string;\n}\n\n/**\n * One model. Field ORDER is a declaration fact: DDL column order follows it,\n * and the format binds it to JSON key order — stable under `JSON.parse`, and\n * destroyed by a producer that sorts keys.\n */\nexport interface ModelDocument {\n /** `.map(tableName)`. */\n table?: string;\n fields: Record<string, FieldDocument>;\n indexes?: IndexDocument[];\n /** Compound `.id(fields, { name })` calls, in declaration order. */\n ids?: CompoundKeyDocument[];\n /** Compound `.unique(fields, { name })` calls, in declaration order. */\n uniques?: CompoundKeyDocument[];\n /** `.omit({ ... })` as a sorted array of scalar field keys. */\n omit?: string[];\n /** `.withoutRowid()`: present only as `true`. */\n withoutRowid?: true;\n}\n\n/**\n * `.index(fields, options)` with its options flattened onto the node.\n *\n * `where` has no spelling: it is the declaration surface's one raw-SQL string,\n * interpolated unescaped into DDL, and a machine-written document is exactly\n * the place that must not carry an execution channel. It returns when a\n * structured predicate form exists.\n */\nexport interface IndexDocument {\n fields: string[];\n name?: string;\n unique?: boolean;\n type?: IndexType;\n}\n\nexport interface CompoundKeyDocument {\n fields: string[];\n name?: string;\n}\n\nexport type FieldDocument = ScalarFieldDocument | RelationFieldDocument;\n\n/**\n * Which arm of the field union a node is. `type` carries both vocabularies —\n * the two cardinalities and the fourteen scalar types — so one read decides it.\n */\nexport function isRelationField(\n field: FieldDocument\n): field is RelationFieldDocument {\n return field.type === \"toOne\" || field.type === \"toMany\";\n}\n\n/**\n * One scalar field: its type plus every chainable modifier as an explicit key.\n *\n * Common chainable modifiers stay flat. Factory arguments are discriminated:\n * ordinary/enum fields may carry `native` or `nativeByDialect`, while a decimal\n * must carry `precision` and `scale` and carries neither. A document declaration is\n * never accepted by one arm and then silently ignored by its factory.\n */\nexport type ScalarFieldDocument =\n | ValueFieldDocument\n | PointFieldDocument\n | DecimalFieldDocument\n | EnumFieldDocument;\n\ninterface SharedScalarFieldModifiers {\n nullable?: boolean;\n /** `.map(columnName)`. */\n column?: string;\n /**\n * A literal default, at any depth. Values from domains JSON cannot spell take\n * a TAG — a one-key object naming the domain: `{\"$bigint\": \"5\"}`,\n * `{\"$bytes\": \"AQID\"}`, `{\"$date\": \"<iso>\"}`, and `{\"$raw\": <value>}` for a\n * literal whose own shape collides with one. A bare ISO string on a temporal\n * field stays a STRING, which is a different declaration from a `Date`.\n *\n * A function default has no spelling — use `generate`, a literal, or a\n * database default through `native`.\n */\n default?: JsonValue;\n}\n\ninterface ScalarFieldModifiers extends SharedScalarFieldModifiers {\n array?: boolean;\n id?: boolean;\n unique?: boolean;\n generate?: GenerateDocument;\n /** `.dimension(n)`. */\n dimension?: number;\n /** `.withoutTimezone()`. */\n withoutTimezone?: boolean;\n}\n\ninterface NativeScalarFieldModifiers extends ScalarFieldModifiers {\n /**\n * The factory's sole argument — `{ db, type }`, already plain data.\n *\n * `type` is emitted into DDL verbatim, so a document may carry only a member\n * of the declared dialect's closed native-type catalog (`J011`), in both\n * directions. `native-catalog.ts` owns that set.\n */\n native?: NativeType;\n /**\n * The factory's argument when it is a map by dialect —\n * `{ pg?: { db: \"pg\", type }, mysql?: …, sqlite?: … }`, the same value a\n * coded schema passes, each entry spelled like `native`. Every entry is in\n * its own dialect's catalog (`J011`), and a field carries at most one of\n * `native` and `nativeByDialect`: they are two spellings of one declaration.\n */\n nativeByDialect?: NativeTypeMap;\n precision?: never;\n scale?: never;\n}\n\nexport interface ValueFieldDocument extends NativeScalarFieldModifiers {\n type: Exclude<ScalarType, \"decimal\" | \"enum\" | \"point\">;\n enum?: never;\n}\n\n/** GeoPoint's fixed geography language has no key, list, or native modifiers. */\nexport interface PointFieldDocument extends SharedScalarFieldModifiers {\n type: \"point\";\n array?: never;\n id?: never;\n unique?: never;\n native?: never;\n nativeByDialect?: never;\n generate?: never;\n dimension?: never;\n withoutTimezone?: never;\n precision?: never;\n scale?: never;\n enum?: never;\n}\n\n/** The one scalar whose factory argument is its portable value domain. */\nexport interface DecimalFieldDocument extends ScalarFieldModifiers {\n type: \"decimal\";\n precision: number;\n scale: number;\n native?: never;\n nativeByDialect?: never;\n enum?: never;\n}\n\nexport interface EnumFieldDocument extends NativeScalarFieldModifiers {\n type: \"enum\";\n /** An `enums` reference, or the values inline. */\n enum: string | string[];\n}\n\n/**\n * A generator declaration. `kind` names the scalar method that installs it, so\n * the nine tokens are the nine methods and there is no second table.\n */\nexport interface GenerateDocument {\n kind: AutoGenerateType;\n /** String format generation choice; absence preserves legacy generation. */\n generate?: boolean;\n prefix?: string;\n length?: number;\n /**\n * This ULID is the one `.id()` installs, not a format the caller named.\n *\n * The two declarations produce the same generator and a DIFFERENT field: a\n * named `.ulid()` admits only ULIDs and stores sixteen bytes, while `.id()`\n * declares a key whose values a string column holds as text. The document\n * has to say which it was, or a round trip would silently promote every\n * `.id()` into a domain and change its column.\n *\n * Only ever `true`, only ever beside `kind: \"ulid\"` and `id: true`.\n */\n implicit?: true;\n}\n\n/**\n * One relation slot: the cardinality its `type` was spelled with, and the\n * target domain named by `target` (one model) XOR `variants` (named variants).\n *\n * The two target domains are two arms, not two optional keys: naming both or\n * neither is not a document the format has, and the `?: never` exclusions make\n * a cross-arm key fail under structural assignment as well as at parse time.\n */\nexport type RelationFieldDocument = ModelTargetDocument | VariantTargetDocument;\n\ninterface RelationSlotDocument {\n type: \"toOne\" | \"toMany\";\n /** The pairing label — free-form and non-empty, not an identifier. */\n name?: string;\n}\n\nexport interface ModelTargetDocument extends RelationSlotDocument {\n /** A model key. */\n target: string;\n /** `.fields(...)` — `toOne` only. */\n fields?: string[];\n /** `.references(...)` — `toOne` only. */\n references?: string[];\n onDelete?: ReferentialAction;\n onUpdate?: ReferentialAction;\n /**\n * Junction overrides for a `toMany`, nested so `target` here cannot collide\n * with the relation's own target key. At least one override, matching what\n * trusted state can hold.\n */\n junction?: JunctionDocument;\n variants?: never;\n values?: never;\n through?: never;\n optional?: never;\n}\n\nexport interface VariantTargetDocument extends RelationSlotDocument {\n /** Variant key → model key. */\n variants: Record<string, string>;\n /**\n * Stored discriminator per variant. All-or-nothing: when present it is exact\n * over the variant keys, because a partial bag is refused by the factory.\n */\n values?: Record<string, string>;\n /** Per-variant member junctions — `toMany` only. */\n through?: Record<string, VariantJunctionDocument>;\n /** `.optional()` — `toOne` only. */\n optional?: boolean;\n target?: never;\n fields?: never;\n references?: never;\n onDelete?: never;\n onUpdate?: never;\n junction?: never;\n}\n\n/**\n * Each action is spelled once: `onDelete` states one action for both junction\n * foreign keys, `onDeleteSides` one per key (`source` naming the declaring\n * model's side). The `?: never` arms make the two spellings exclusive, as the\n * reader refuses both together; the serializer writes the side map only when\n * the two sides differ.\n */\nexport type JunctionDocument = JunctionNamesDocument &\n (\n | { onDelete?: JunctionReferentialAction; onDeleteSides?: never }\n | { onDelete?: never; onDeleteSides?: JunctionSidesDocument }\n ) &\n (\n | { onUpdate?: JunctionReferentialAction; onUpdateSides?: never }\n | { onUpdate?: never; onUpdateSides?: JunctionSidesDocument }\n );\n\n/**\n * The junction's physical names: its table and its two side tokens. `model`\n * instead of `table` names a declared model (its schema key) as the junction,\n * and `source` / `target` then name that model's to-one relations.\n */\nexport interface JunctionNamesDocument {\n table?: string;\n model?: string;\n source?: string;\n target?: string;\n}\n\nexport interface JunctionSidesDocument {\n source: JunctionReferentialAction;\n target: JunctionReferentialAction;\n}\n\nexport interface VariantJunctionDocument {\n table: string;\n source: string;\n target: string;\n}\n","// How this module reaches the builders.\n//\n// An interpreter enters them dynamically: the typed overloads describe what a\n// human WRITES — a literal getter, literal variant keys, a literal modifier\n// name — and a declaration assembled from data satisfies none of them\n// statically. The two entries here are the whole of that.\n//\n// `ScalarType` (the state vocabulary) and the `s.*` factory names disagree in\n// two places for historical reasons — `bigint`/`bigInt` and `datetime`/\n// `dateTime` — so ONE record states the correspondence and the type system\n// keeps it exhaustive. `enum` and `decimal` are absent because their factories\n// take an argument their own node carries — an enum its values, a decimal its\n// `{ precision, scale }` domain — so each has its own construction site.\n\nimport {\n bigInt,\n blob,\n boolean,\n date,\n dateTime,\n int,\n json,\n number,\n point,\n string,\n time,\n vector,\n} from \"@schema/scalars\";\nimport type { Scalar } from \"@schema/scalars/base\";\nimport type { ScalarType } from \"@schema/scalars/common\";\nimport type { NativeTypeDeclaration } from \"@schema/scalars/native-types\";\n\nexport type ScalarFactory = (native?: NativeTypeDeclaration) => Scalar;\n\nexport const SCALAR_FACTORIES: Record<\n Exclude<ScalarType, \"enum\" | \"decimal\">,\n ScalarFactory\n> = {\n string,\n int,\n number,\n boolean,\n datetime: dateTime,\n date,\n time,\n bigint: bigInt,\n json,\n blob,\n vector,\n point,\n};\n\n/** Every `type` a scalar field node may declare. */\nexport const SCALAR_TYPE_NAMES: ReadonlySet<string> = new Set([\n ...Object.keys(SCALAR_FACTORIES),\n \"decimal\",\n \"enum\",\n]);\n\n/**\n * One builder method, reached by name.\n *\n * The class surface is the only table of which modifiers a scalar type has, so\n * an absent method is exactly what \"this type has no such modifier\" means —\n * both when the interpreter is asked to apply one and when the serializer asks\n * whether a state difference was even spellable.\n */\nexport function builderMethod(\n owner: object,\n name: string\n): ((...args: any[]) => any) | undefined {\n const candidate = Reflect.get(owner, name);\n return typeof candidate === \"function\" ? candidate : undefined;\n}\n","// The interpreter: a document, read through the SAME public builders a human\n// calls.\n//\n// There is no second schema representation here. `s.model`, `s.string()`,\n// `s.toOne(...)` produce the real classes, so hydration, the resolution gate,\n// the query engine and migrations consume the result unchanged and emit their\n// existing diagnostics for free. What this file owns is the ORDER in which\n// modifiers are applied and the conversion of a JSON literal into the value a\n// builder takes; every refusal below either belongs to a builder and is\n// re-thrown with the document location, or is a fact only a document can state.\n//\n// The parser never interns models, scalars or relation terminals across calls:\n// write-once model naming (`M003`) and the per-terminal `settleTarget` once-cell\n// both punish a reused declaration, so every parse is a fresh object graph.\n\nimport type { Schema } from \"@schema/hydration\";\nimport { jsonNullKindOf } from \"@schema/json-null\";\nimport type { AnyModel } from \"@schema/model\";\nimport type { ModelShape } from \"@schema/model/helper\";\nimport { model as modelFactory } from \"@schema/model/model\";\nimport { toMany, toOne } from \"@schema/relation\";\nimport type { Getter } from \"@schema/relation/types\";\nimport { enumScalar } from \"@schema/scalars\";\nimport type { Scalar } from \"@schema/scalars/base\";\nimport type { ScalarType } from \"@schema/scalars/common\";\nimport {\n buildDecimalScalar,\n DecimalScalar,\n withValidatedDecimalDefault,\n} from \"@schema/scalars/decimal/scalar\";\nimport { view as viewFactory } from \"@schema/view/view\";\nimport type { StandardSchemaV1 } from \"@standard-schema/spec\";\nimport type { JsonValue } from \"@validation/primitives/json\";\nimport { toError } from \"../../errors/diagnostic-safety\";\nimport { decodeDefault } from \"./default-codec\";\nimport type {\n EnumDocument,\n EnumFieldDocument,\n GenerateDocument,\n IndexDocument,\n ModelDocument,\n ModelTargetDocument,\n RelationFieldDocument,\n ScalarFieldDocument,\n SchemaDocument,\n VariantTargetDocument,\n ViewDocument,\n} from \"./document\";\nimport { isRelationField } from \"./document\";\nimport { builderMethod, SCALAR_FACTORIES } from \"./factories\";\nimport {\n addIssue,\n type DocumentIssues,\n documentRoot,\n pointer,\n refuseDocument,\n refuseFromBuilder,\n} from \"./issues\";\nimport { lightModels } from \"./light\";\n\n/**\n * Standard Schema validators to attach, keyed `\"<model>.<field>\"`.\n *\n * `.schema()` has no document spelling — a validator is arbitrary code — so a\n * hybrid codebase contributes them here, where the interpreter can apply them\n * LAST, after `.nullable()`/`.array()` have finished rebuilding the base.\n */\nexport type FieldSchemaMap = Record<string, StandardSchemaV1<any, any>>;\n\n/**\n * Build a schema from a document.\n *\n * Pass 1 creates every model against a registry that is still filling; a\n * relation target is `() => registry[key]`, and nothing invokes a getter before\n * the resolution gate, which runs after the registry is complete. The getter\n * returns the registered object BY IDENTITY, which is what the gate requires.\n *\n * Pass 2 creates the views, each after the view it reads: a view's source is a\n * getter too, but `.map()` derives the view at once, so its source must already\n * be built. They join the registry in the document's order.\n */\nexport function interpret(\n document: SchemaDocument,\n fieldSchemas?: FieldSchemaMap\n): Schema {\n const registry: Schema = {};\n const modelsPath = pointer(documentRoot, \"models\");\n refuseUnknownFieldSchemas(document, fieldSchemas);\n for (const [modelKey, modelDocument] of Object.entries(document.models)) {\n const model = buildModel(\n modelKey,\n modelDocument,\n document,\n registry,\n pointer(modelsPath, modelKey),\n fieldSchemas\n );\n registry[modelKey] = model;\n if (document.light) lightModels.add(model);\n }\n const views = document.views ?? {};\n const viewsPath = pointer(documentRoot, \"views\");\n const built = new Map<string, AnyModel>();\n const member = (key: string) => registry[key] ?? built.get(key);\n const build = (viewKey: string, view: ViewDocument): AnyModel => {\n const done = built.get(viewKey);\n if (done !== undefined) return done;\n const source = views[view.source];\n if (source !== undefined) build(view.source, source);\n const model = buildView(view, member, pointer(viewsPath, viewKey));\n built.set(viewKey, model);\n if (document.light) lightModels.add(model);\n return model;\n };\n for (const [viewKey, view] of Object.entries(views)) {\n registry[viewKey] = build(viewKey, view);\n }\n return registry;\n}\n\n/**\n * A validator keyed to a field the schema does not have hides nothing and\n * validates nothing — the same silence `.omit()` refuses at the type level.\n */\nfunction refuseUnknownFieldSchemas(\n document: SchemaDocument,\n fieldSchemas: FieldSchemaMap | undefined\n): void {\n if (fieldSchemas === undefined) return;\n const issues: DocumentIssues = [];\n for (const path of Object.keys(fieldSchemas)) {\n const separator = path.indexOf(\".\");\n const field =\n document.models[path.slice(0, separator)]?.fields[\n path.slice(separator + 1)\n ];\n if (field !== undefined && !isRelationField(field)) continue;\n addIssue(\n issues,\n documentRoot,\n \"J006\",\n `Field schema '${path}' is not a scalar ('<model>.<field>')`\n );\n }\n if (issues.length > 0) throw refuseDocument(issues);\n}\n\n// =============================================================================\n// MODEL\n// =============================================================================\n\nfunction buildModel(\n modelKey: string,\n document: ModelDocument,\n schema: SchemaDocument,\n registry: Schema,\n path: string,\n fieldSchemas: FieldSchemaMap | undefined\n): AnyModel {\n const fieldsPath = pointer(path, \"fields\");\n const shape: ModelShape = {};\n for (const [fieldKey, field] of Object.entries(document.fields)) {\n const fieldPath = pointer(fieldsPath, fieldKey);\n if (isRelationField(field)) {\n shape[fieldKey] = buildRelation(field, registry, fieldPath);\n continue;\n }\n shape[fieldKey] = buildScalar(\n field,\n schema,\n fieldPath,\n fieldSchemas?.[`${modelKey}.${fieldKey}`]\n );\n }\n\n let model: AnyModel = call(path, () => modelFactory(shape));\n if (document.table !== undefined) {\n const table = document.table;\n model = call(pointer(path, \"table\"), () => model.map(table));\n }\n model = buildIndexes(model, document.indexes, path);\n for (const [position, compound] of (document.ids ?? []).entries()) {\n const idPath = pointer(path, \"ids\", String(position));\n model = call(idPath, () =>\n model.id(compound.fields, options(compound.name))\n );\n }\n for (const [position, compound] of (document.uniques ?? []).entries()) {\n const uniquePath = pointer(path, \"uniques\", String(position));\n model = call(uniquePath, () =>\n model.unique(compound.fields, options(compound.name))\n );\n }\n if (document.omit !== undefined) {\n const hidden: Record<string, true> = {};\n for (const name of document.omit) hidden[name] = true;\n model = call(pointer(path, \"omit\"), () => model.omit(hidden));\n }\n if (document.withoutRowid === true) {\n model = call(pointer(path, \"withoutRowid\"), () => model.withoutRowid());\n }\n return model;\n}\n\nfunction options(name: string | undefined): { name?: string } {\n return name === undefined ? {} : { name };\n}\n\n/** A model's or a view's `.index()` calls, in the document's order. */\nfunction buildIndexes(\n model: AnyModel,\n indexes: readonly IndexDocument[] | undefined,\n path: string\n): AnyModel {\n let indexed = model;\n for (const [position, index] of (indexes ?? []).entries()) {\n const indexPath = pointer(path, \"indexes\", String(position));\n const indexOptions = {\n ...(index.name === undefined ? {} : { name: index.name }),\n ...(index.unique === undefined ? {} : { unique: index.unique }),\n ...(index.type === undefined ? {} : { type: index.type }),\n };\n const into = indexed;\n indexed = call(indexPath, () =>\n Reflect.apply(into.index, into, [index.fields, indexOptions])\n );\n }\n return indexed;\n}\n\n/**\n * One view, through `s.view`: its query with every tag decoded, as the\n * factory takes it from a human.\n */\nfunction buildView(\n document: ViewDocument,\n member: (key: string) => AnyModel | undefined,\n path: string\n): AnyModel {\n const source = document.source;\n const getter: Getter = () => member(source);\n const query = decodeDefault(document.query, pointer(path, \"query\"));\n let model: AnyModel = call(path, () =>\n Reflect.apply(viewFactory, undefined, [getter, query])\n );\n if (document.table !== undefined) {\n const table = document.table;\n model = call(pointer(path, \"table\"), () => model.map(table));\n }\n if (document.materialized === true) {\n const options =\n document.refresh === \"auto\" ? { refresh: \"auto\" as const } : undefined;\n model = call(pointer(path, \"materialized\"), () =>\n model.materialized(options)\n );\n }\n return buildIndexes(model, document.indexes, path);\n}\n\n// =============================================================================\n// SCALAR\n// =============================================================================\n\n/**\n * The fixed modifier order.\n *\n * `.array()` and `.nullable()` rebuild the base schema from the OTHER flags, so\n * they run first and in this order; `.id()` installs a generator that a later\n * `generate` may replace; `.default()` is validated against the base those\n * first two produced; `.map()` renames a column and depends on nothing.\n * `.schema()` rebuilds the base too, and runs last so a contributed validator\n * sees the finished nullability and arity.\n */\nfunction buildScalar(\n document: ScalarFieldDocument,\n schema: SchemaDocument,\n path: string,\n fieldSchema: StandardSchemaV1<any, any> | undefined\n): Scalar {\n const type = document.type;\n let scalar = createScalar(document, schema, path);\n const apply = (name: string, args: unknown[] = [], key = name) => {\n scalar = modify(scalar, name, args, type, pointer(path, key));\n };\n if (document.array) apply(\"array\");\n if (document.nullable) apply(\"nullable\");\n if (document.id) {\n const implicit = document.generate?.implicit === true;\n const args =\n document.generate?.generate === false\n ? [\n {\n generate: false,\n prefix: implicit ? document.generate.prefix : undefined,\n },\n ]\n : implicit && document.generate?.prefix !== undefined\n ? [document.generate.prefix]\n : [];\n apply(\"id\", args);\n }\n if (document.unique) apply(\"unique\");\n if (document.withoutTimezone) apply(\"withoutTimezone\");\n if (document.dimension !== undefined)\n apply(\"dimension\", [document.dimension]);\n if (document.generate !== undefined && document.generate.implicit !== true) {\n scalar = applyGenerate(scalar, document.generate, type, path);\n }\n if (document.default !== undefined) {\n scalar = applyDefault(scalar, document, document.default, path);\n }\n if (document.column !== undefined) apply(\"map\", [document.column], \"column\");\n if (fieldSchema !== undefined) apply(\"schema\", [fieldSchema]);\n return scalar;\n}\n\nfunction createScalar(\n document: ScalarFieldDocument,\n schema: SchemaDocument,\n path: string\n): Scalar {\n if (document.type === \"decimal\") {\n // The domain is the factory's ARGUMENT, not a modifier, because a decimal\n // has no state without it. The two numbers are handed over exactly as the\n // node carries them — `s.decimal` owns whether they name a domain, and\n // `call` turns its refusal into this node's issue.\n const { precision, scale } = document;\n return call(path, () => buildDecimalScalar({ precision, scale }));\n }\n // The reader admits at most one of the two spellings of the declaration.\n const native = document.native ?? document.nativeByDialect;\n if (document.type !== \"enum\") {\n const factory = SCALAR_FACTORIES[document.type];\n return call(path, () =>\n native === undefined ? factory() : factory(native)\n );\n }\n const definition = resolveEnum(document, schema, path);\n const scalar = call(path, () => enumScalar(definition.values, native));\n if (definition.name === undefined) return scalar;\n const name = definition.name;\n return modify(scalar, \"name\", [name], \"enum\", pointer(path, \"enum\"));\n}\n\n/**\n * An enum field states its values inline or names an `enums` definition. The\n * definition's `name` is the DB type; without one, each column keeps its own\n * derived type — the same fact `.name()` decides for a coded schema.\n *\n * This is the one owner of the `enums` reference: the first boundary that needs\n * the definition, so a dangling reference is refused exactly once.\n */\nfunction fail(\n path: string,\n code: \"J006\" | \"J007\" | \"J008\",\n message: string\n): never {\n const issues: DocumentIssues = [];\n addIssue(issues, path, code, message);\n throw refuseDocument(issues);\n}\n\nfunction resolveEnum(\n document: EnumFieldDocument,\n schema: SchemaDocument,\n path: string\n): EnumDocument {\n const reference = document.enum;\n if (Array.isArray(reference)) return { values: reference };\n const definition = schema.enums?.[reference];\n if (definition !== undefined) return definition;\n fail(pointer(path, \"enum\"), \"J006\", `Unknown enum '${reference}'`);\n}\n\nfunction modify(\n scalar: Scalar,\n name: string,\n args: unknown[],\n type: ScalarType,\n path: string\n): Scalar {\n const method = builderMethod(scalar, name);\n if (method === undefined) {\n fail(path, \"J007\", `'${type}' has no '${name}' modifier`);\n }\n return call(path, () => method.apply(scalar, args));\n}\n\nfunction applyGenerate(\n scalar: Scalar,\n generate: GenerateDocument,\n type: ScalarType,\n path: string\n): Scalar {\n const generatePath = pointer(path, \"generate\");\n const identifier = ![\"now\", \"updatedAt\", \"increment\"].includes(generate.kind);\n const configuration =\n generate.generate === false\n ? { prefix: generate.prefix, length: generate.length }\n : { prefix: generate.prefix, length: generate.length, generate: true };\n const args = identifier ? [configuration] : [generate.prefix];\n const generated = modify(scalar, generate.kind, args, type, generatePath);\n const applied = generated[\"~\"].state.autoGenerate;\n if (\n applied?.prefix === generate.prefix &&\n applied?.length === generate.length\n ) {\n return generated;\n }\n fail(\n generatePath,\n \"J007\",\n `'${generate.kind}' does not accept declared 'prefix'/'length'`\n );\n}\n\nfunction applyDefault(\n scalar: Scalar,\n document: ScalarFieldDocument,\n literal: JsonValue,\n path: string\n): Scalar {\n const defaultPath = pointer(path, \"default\");\n const value = decodeDefault(literal, defaultPath);\n if (document.type === \"json\" && jsonNullKindOf(value) !== undefined) {\n return modify(scalar, \"default\", [value], document.type, defaultPath);\n }\n const verdict = scalar[\"~\"].state.base[\"~standard\"].validate(value);\n const untaggedBigInt =\n document.type === \"bigint\" &&\n [value].flat().some((item) => typeof item === \"string\");\n if (verdict.issues || untaggedBigInt) {\n const reason = verdict.issues\n ? verdict.issues.map((issue) => issue.message).join(\"; \")\n : 'bigint requires {\"$bigint\": \"<integer>\"}';\n fail(defaultPath, \"J008\", `Invalid '${document.type}' default: ${reason}`);\n }\n if (scalar instanceof DecimalScalar) {\n return withValidatedDecimalDefault(scalar, verdict.value);\n }\n return modify(scalar, \"default\", [value], document.type, defaultPath);\n}\n\n// =============================================================================\n// RELATION\n// =============================================================================\n\nfunction buildRelation(\n document: RelationFieldDocument,\n registry: Schema,\n path: string\n) {\n const relation =\n document.target === undefined\n ? buildVariantRelation(document, registry, path)\n : buildModelRelation(document, registry, path);\n if (document.name === undefined) return relation;\n const name = document.name;\n return call(pointer(path, \"name\"), () => relation.name(name));\n}\n\nfunction buildModelRelation(\n document: ModelTargetDocument,\n registry: Schema,\n path: string\n) {\n const target = document.target;\n const getter: Getter = () => registry[target];\n const factory = document.type === \"toOne\" ? toOne : toMany;\n let relation = call(path, () => Reflect.apply(factory, undefined, [getter]));\n if (document.fields !== undefined) {\n const fields = document.fields;\n relation = call(pointer(path, \"fields\"), () => relation.fields(...fields));\n }\n if (document.references !== undefined) {\n const references = document.references;\n relation = call(pointer(path, \"references\"), () =>\n relation.references(...references)\n );\n }\n for (const action of [\"onDelete\", \"onUpdate\"] as const) {\n const value = document[action];\n if (value === undefined) continue;\n relation = call(pointer(path, action), () => relation[action](value));\n }\n if (document.junction !== undefined) {\n relation = applyJunction(relation, document.junction, registry, path);\n }\n return relation;\n}\n\nfunction buildVariantRelation(\n document: VariantTargetDocument,\n registry: Schema,\n path: string\n) {\n const variants: Record<string, Getter> = {};\n for (const [key, target] of Object.entries(document.variants)) {\n variants[key] = () => registry[target];\n }\n const factory = document.type === \"toOne\" ? toOne : toMany;\n const args =\n document.values === undefined\n ? [variants]\n : [variants, { values: document.values }];\n let relation = call(path, () => Reflect.apply(factory, undefined, args));\n if (document.through !== undefined) {\n const through = document.through;\n relation = call(pointer(path, \"through\"), () => relation.through(through));\n }\n if (document.optional) {\n relation = call(pointer(path, \"optional\"), () => relation.optional());\n }\n return relation;\n}\n\n/**\n * Junction overrides are independent modifiers, not one bag: the document\n * nests them so `target` cannot collide with the relation's own target key, and\n * each declared key becomes the call that writes it. An action's two spellings\n * (`onDelete` / `onDeleteSides`) are the builder's two argument forms, so the\n * builder alone normalizes them.\n */\nconst JUNCTION_MODIFIERS = [\n [\"table\", \"through\"],\n [\"model\", \"through\"],\n [\"source\", \"source\"],\n [\"target\", \"target\"],\n [\"onDelete\", \"onDelete\"],\n [\"onUpdate\", \"onUpdate\"],\n [\"onDeleteSides\", \"onDelete\"],\n [\"onUpdateSides\", \"onUpdate\"],\n] as const;\n\nfunction applyJunction(\n relation: any,\n junction: NonNullable<ModelTargetDocument[\"junction\"]>,\n registry: Schema,\n path: string\n) {\n let overridden = relation;\n const junctionPath = pointer(path, \"junction\");\n for (const [key, method] of JUNCTION_MODIFIERS) {\n const value = junction[key];\n if (value === undefined) continue;\n overridden = call(pointer(junctionPath, key), () =>\n overridden[method](\n key === \"model\" ? () => registry[value as string] : value\n )\n );\n }\n return overridden;\n}\n\n// =============================================================================\n// BUILDER ENTRY\n// =============================================================================\n\n/**\n * Enter a builder, and give its refusal the document location that produced it.\n *\n * Every semantic refusal in the declaration surface belongs to a builder — a\n * blob that cannot be an array, an incomplete foreign key, a stored-value bag\n * that is not exact, a junction token that is not an identifier. None of them\n * is restated here; each keeps its own message and becomes the `cause`.\n */\nfunction call<T>(path: string, build: () => T): T {\n try {\n return build();\n } catch (thrown) {\n return refuseFromBuilder(path, toError(thrown));\n }\n}\n","// Document SHAPE: the one owner of \"does this value have the format's shape\".\n//\n// It answers exactly that, and nothing semantic. Whether a scalar type HAS the\n// modifier a node spells, whether a foreign key pairs, whether a stored-value\n// bag is exact, whether a graph resolves — those belong to the scalar classes,\n// the relation factories and the resolution gate, which already refuse them by\n// name. What this boundary uniquely owns is the JSON POINTER: it is the first\n// place that knows where in the author's artifact a fact was written, and the\n// only place that can report every such fact at once instead of the first.\n//\n// The document is caller-controlled input, and inspecting it is executable too:\n// a property accessor, a `getPrototypeOf` trap and an `ownKeys` trap can all run\n// code. So every value read, every prototype check and every key enumeration\n// goes through the boundary's guarded inspection owner (`member`,\n// `inspectPlainRecord`, `inspectKeys`), and any value rendered into a message\n// through `renderValue` — a hostile object can neither smuggle inherited entries\n// nor throw its way out as the caller's own value.\n\nimport { isValidSchemaIdentifier } from \"@schema/identifier\";\nimport type { IndexType } from \"@schema/model/model\";\nimport type {\n JunctionReferentialAction,\n ReferentialAction,\n} from \"@schema/relation/types\";\nimport type { AutoGenerateType, ScalarType } from \"@schema/scalars/common\";\nimport {\n isNativeTypeInCatalog,\n nativeTypeRefusal,\n} from \"@schema/scalars/native-catalog\";\nimport {\n type DialectNativeType,\n NATIVE_DIALECTS,\n type NativeDialect,\n type NativeType,\n type NativeTypeMap,\n} from \"@schema/scalars/native-types\";\nimport type { JsonValue } from \"@validation/primitives/json\";\nimport {\n readDefaultValue,\n readValueRecord,\n reservedKey,\n} from \"./default-codec\";\nimport type {\n CompoundKeyDocument,\n EnumDocument,\n FieldDocument,\n GenerateDocument,\n IndexDocument,\n JunctionDocument,\n JunctionNamesDocument,\n JunctionSidesDocument,\n ModelDocument,\n ModelTargetDocument,\n RelationFieldDocument,\n ScalarFieldDocument,\n SchemaDocument,\n VariantJunctionDocument,\n VariantTargetDocument,\n ViewDocument,\n} from \"./document\";\nimport { isRelationField, SCHEMA_DOCUMENT_VERSION } from \"./document\";\nimport { SCALAR_TYPE_NAMES } from \"./factories\";\nimport {\n addIssue,\n type DocumentIssues,\n documentRoot,\n inspectKeys,\n inspectPlainRecord,\n member,\n pointer,\n refuseDocument,\n renderValue,\n throwIfRefused,\n} from \"./issues\";\n\n// =============================================================================\n// CLOSED VOCABULARIES\n// =============================================================================\n\n// Each vocabulary is spelled as a `Record<Union, true>` so the type it narrows\n// to is the only statement of its membership: a token added to the union and\n// not to the record is a compile error, and the reverse is too. The relation\n// terminal and the scalar classes still own these vocabularies for CODED\n// schemas; here they are part of the document's shape.\n\nconst REFERENTIAL_ACTIONS: Record<ReferentialAction, true> = {\n cascade: true,\n setNull: true,\n restrict: true,\n noAction: true,\n};\n\nconst JUNCTION_ACTIONS: Record<JunctionReferentialAction, true> = {\n cascade: true,\n restrict: true,\n noAction: true,\n};\n\nconst INDEX_TYPES: Record<IndexType, true> = {\n btree: true,\n hash: true,\n gin: true,\n gist: true,\n fulltext: true,\n spatial: true,\n};\n\nconst GENERATE_KINDS: Record<AutoGenerateType, true> = {\n uuid: true,\n uuidv7: true,\n ulid: true,\n ksuid: true,\n nanoid: true,\n cuid: true,\n increment: true,\n now: true,\n updatedAt: true,\n};\n\nconst isReferentialAction = (value: unknown): value is ReferentialAction =>\n typeof value === \"string\" && Object.hasOwn(REFERENTIAL_ACTIONS, value);\n\nconst isJunctionAction = (value: unknown): value is JunctionReferentialAction =>\n typeof value === \"string\" && Object.hasOwn(JUNCTION_ACTIONS, value);\n\nconst isIndexType = (value: unknown): value is IndexType =>\n typeof value === \"string\" && Object.hasOwn(INDEX_TYPES, value);\n\nconst isGenerateKind = (value: unknown): value is AutoGenerateType =>\n typeof value === \"string\" && Object.hasOwn(GENERATE_KINDS, value);\n\nconst isNativeDialect = (value: unknown): value is NativeDialect =>\n typeof value === \"string\" &&\n NATIVE_DIALECTS.some((dialect) => dialect === value);\n\nconst isScalarTypeName = (value: unknown): value is ScalarType =>\n typeof value === \"string\" && SCALAR_TYPE_NAMES.has(value);\n\n// =============================================================================\n// NODE KEY SETS\n// =============================================================================\n\nconst DOCUMENT_KEYS = [\"version\", \"light\", \"enums\", \"models\", \"views\"];\nconst ENUM_KEYS = [\"values\", \"name\"];\nconst MODEL_KEYS = [\n \"table\",\n \"fields\",\n \"indexes\",\n \"ids\",\n \"uniques\",\n \"omit\",\n \"withoutRowid\",\n];\nconst INDEX_KEYS = [\"fields\", \"name\", \"unique\", \"type\", \"where\"];\nconst COMPOUND_KEYS = [\"fields\", \"name\"];\nconst VIEW_KEYS = [\n \"source\",\n \"query\",\n \"table\",\n \"materialized\",\n \"refresh\",\n \"indexes\",\n];\nconst NATIVE_KEYS = [\"db\", \"type\"];\nconst GENERATE_KEYS = [\"kind\", \"prefix\", \"length\", \"implicit\", \"generate\"];\nconst JUNCTION_KEYS = [\n \"table\",\n \"model\",\n \"source\",\n \"target\",\n \"onDelete\",\n \"onUpdate\",\n \"onDeleteSides\",\n \"onUpdateSides\",\n];\nconst JUNCTION_SIDE_KEYS = [\"source\", \"target\"];\nconst VARIANT_JUNCTION_KEYS = [\"table\", \"source\", \"target\"];\nconst SCALAR_FIELD_KEYS = [\n \"type\",\n \"native\",\n \"nativeByDialect\",\n \"nullable\",\n \"array\",\n \"id\",\n \"unique\",\n \"column\",\n \"default\",\n \"generate\",\n \"enum\",\n \"dimension\",\n \"precision\",\n \"scale\",\n \"withoutTimezone\",\n];\n\n/**\n * Every key SOME field node declares.\n *\n * Used only when `type` names no field at all: the arm is then undecided, so\n * the keys that can still be called unknown are the ones no arm has. Reporting\n * `fields` beside an unknown `type` would be telling an author their `toOne`\n * key is wrong when the parser does not yet know it is not a `toOne`.\n */\nconst ANY_FIELD_KEYS = [\n ...new Set([\n ...SCALAR_FIELD_KEYS,\n ...relationKeys({ cardinality: \"one\", variants: false }),\n ...relationKeys({ cardinality: \"many\", variants: false }),\n ...relationKeys({ cardinality: \"one\", variants: true }),\n ...relationKeys({ cardinality: \"many\", variants: true }),\n ]),\n];\n\n/**\n * The keys one relation arm admits.\n *\n * The four arms are the four capability surfaces the factories publish — a\n * model-target `toOne` has `.fields()`, a variant-target `toOne` has\n * `.optional()`, and so on. Those surfaces exist only as TYPES over private\n * terminal classes, so the document's own exactness is stated here.\n */\nfunction relationKeys(node: RelationArm): string[] {\n const keys = [\"type\", \"name\"];\n if (node.variants) {\n keys.push(\"variants\", \"values\");\n keys.push(node.cardinality === \"one\" ? \"optional\" : \"through\");\n return keys;\n }\n keys.push(\"target\");\n if (node.cardinality === \"one\") {\n keys.push(\"fields\", \"references\", \"onDelete\", \"onUpdate\");\n return keys;\n }\n keys.push(\"junction\");\n return keys;\n}\n\ntype RelationArm = {\n readonly cardinality: \"one\" | \"many\";\n readonly variants: boolean;\n};\n\n// =============================================================================\n// GUARDED VALUE READS\n// =============================================================================\n\n/**\n * Every element of a caller-supplied array, read through the one guarded\n * accessor. An array's INDEXES are ordinary properties, so each of them is\n * executable input exactly as a named key is.\n */\nfunction elements(\n value: readonly unknown[],\n path: string,\n issues: DocumentIssues\n): unknown[] {\n const read: unknown[] = [];\n for (let index = 0; index < value.length; index += 1) {\n read.push(member(value, String(index), path, issues));\n }\n return read;\n}\n\nfunction asRecord(\n value: unknown,\n path: string,\n issues: DocumentIssues,\n what: string\n): Record<string, unknown> | undefined {\n if (inspectPlainRecord(value, path, issues, \"J004\")) return value;\n addIssue(issues, path, \"J004\", `${what} must be a plain JSON object`);\n return;\n}\n\nfunction asString(\n value: unknown,\n path: string,\n issues: DocumentIssues,\n what: string\n): string | undefined {\n if (typeof value === \"string\") return value;\n addIssue(issues, path, \"J004\", `${what} must be a string`);\n return;\n}\n\nfunction asBoolean(\n value: unknown,\n path: string,\n issues: DocumentIssues,\n what: string\n): boolean | undefined {\n if (typeof value === \"boolean\") return value;\n addIssue(issues, path, \"J004\", `${what} must be a boolean`);\n return;\n}\n\nfunction asNumber(\n value: unknown,\n path: string,\n issues: DocumentIssues,\n what: string\n): number | undefined {\n if (typeof value === \"number\" && Number.isFinite(value)) return value;\n addIssue(issues, path, \"J004\", `${what} must be a finite number`);\n return;\n}\n\nfunction asStringArray(\n value: unknown,\n path: string,\n issues: DocumentIssues,\n what: string\n): string[] | undefined {\n if (!Array.isArray(value)) {\n addIssue(issues, path, \"J004\", `${what} must be an array of strings`);\n return;\n }\n // Every bad element is reported, not the first: an author fixing a list of\n // names should see the whole list's verdict in one pass. The array itself is\n // still refused — a partial one would build a declaration nobody wrote.\n const strings: string[] = [];\n let complete = true;\n for (const [position, entry] of elements(value, path, issues).entries()) {\n const text = asString(entry, pointer(path, String(position)), issues, what);\n if (text === undefined) {\n complete = false;\n continue;\n }\n strings.push(text);\n }\n return complete ? strings : undefined;\n}\n\n/**\n * A node's own keys, walked ONCE: an unknown key is refused, and an own key\n * whose value is explicitly `undefined` is refused too.\n *\n * Object input can carry `key: undefined`; JSON text cannot, and object input\n * describes exactly what JSON text can — so absence is spelled by omitting the\n * key, never by setting it to `undefined`. Read as absent, an own `undefined`\n * silently became a node the author did not write. This is the ONE place that\n * rule lives (external review 7); the OPTIONS bag is the deliberate exception\n * and reads its own way — `validate?: boolean` admits `undefined` by the TS\n * optional-property idiom, which refusing would fight.\n */\nfunction optBool(\n node: Record<string, unknown>,\n key: string,\n path: string,\n issues: DocumentIssues\n): boolean | undefined {\n const raw = member(node, key, path, issues);\n return raw === undefined\n ? undefined\n : asBoolean(raw, pointer(path, key), issues, `\\`${key}\\``);\n}\n\nfunction readArrayNode<T>(\n node: Record<string, unknown>,\n key: string,\n parentPath: string,\n issues: DocumentIssues,\n readItem: (entry: unknown, entryPath: string) => T | undefined\n): T[] | undefined {\n const path = pointer(parentPath, key);\n const raw = member(node, key, parentPath, issues);\n if (raw === undefined) return;\n if (!Array.isArray(raw)) {\n addIssue(issues, path, \"J004\", `\\`${key}\\` must be an array`);\n return;\n }\n const out: T[] = [];\n for (const [position, entry] of elements(raw, path, issues).entries()) {\n const item = readItem(entry, pointer(path, String(position)));\n if (item !== undefined) out.push(item);\n }\n return out;\n}\n\nfunction optString(\n node: Record<string, unknown>,\n key: string,\n path: string,\n issues: DocumentIssues\n): string | undefined {\n const raw = member(node, key, path, issues);\n return raw === undefined\n ? undefined\n : asString(raw, pointer(path, key), issues, `\\`${key}\\``);\n}\n\nfunction readRecordMap<T>(\n record: Record<string, unknown>,\n path: string,\n issues: DocumentIssues,\n keyWhat: string,\n readEntry: (value: unknown, entryPath: string) => T | undefined\n): Record<string, T> {\n const map: Record<string, T> = {};\n for (const key of inspectKeys(record, path, issues, \"J004\")) {\n const entryPath = pointer(path, key);\n if (!refuseInvalidKey(key, entryPath, issues, keyWhat)) continue;\n const entry = readEntry(member(record, key, path, issues), entryPath);\n if (entry !== undefined) map[key] = entry;\n }\n return map;\n}\n\nfunction refuseUnknownKeys(\n record: Record<string, unknown>,\n allowed: readonly string[],\n path: string,\n issues: DocumentIssues\n): void {\n for (const key of inspectKeys(record, path, issues, \"J004\")) {\n if (!allowed.includes(key)) {\n addIssue(\n issues,\n pointer(path, key),\n \"J003\",\n `Unknown key '${key}'; expected ${renderKeys(allowed)}`\n );\n continue;\n }\n if (member(record, key, path, issues) === undefined) {\n addIssue(\n issues,\n pointer(path, key),\n \"J004\",\n `'${key}' cannot be \\`undefined\\`; omit absent keys`\n );\n }\n }\n}\n\nfunction refuseInvalidKey(\n key: string,\n path: string,\n issues: DocumentIssues,\n what: string\n): boolean {\n if (isValidSchemaIdentifier(key)) return true;\n addIssue(issues, path, \"J005\", `${what} '${key}' is not a valid identifier`);\n return false;\n}\n\nfunction renderKeys(keys: readonly string[]): string {\n return keys.map((key) => `'${key}'`).join(\", \");\n}\n\n// =============================================================================\n// DOCUMENT\n// =============================================================================\n\nexport function readDocument(input: string | object): SchemaDocument {\n const issues: DocumentIssues = [];\n const value = intake(input, issues);\n throwIfRefused(issues);\n const node = asRecord(value, documentRoot, issues, \"A schema document\");\n if (node === undefined) throw refuseDocument(issues);\n refuseUnknownKeys(node, DOCUMENT_KEYS, documentRoot, issues);\n\n const version = member(node, \"version\", documentRoot, issues);\n if (version !== SCHEMA_DOCUMENT_VERSION) {\n addIssue(\n issues,\n pointer(documentRoot, \"version\"),\n \"J002\",\n `Unsupported version ${renderValue(version)}; expected version ${SCHEMA_DOCUMENT_VERSION}`\n );\n throw refuseDocument(issues);\n }\n\n const document: SchemaDocument = {\n version: SCHEMA_DOCUMENT_VERSION,\n models: readModels(node, issues),\n };\n if (optBool(node, \"light\", documentRoot, issues)) document.light = true;\n const enums = readEnums(node, issues);\n if (enums !== undefined) document.enums = enums;\n const views = readViews(node, issues);\n if (views !== undefined) document.views = views;\n resolveReferences(document, issues);\n throwIfRefused(issues);\n return document;\n}\n\nfunction intake(input: string | object, issues: DocumentIssues): unknown {\n if (typeof input !== \"string\") return input;\n try {\n return JSON.parse(input);\n } catch (thrown) {\n addIssue(issues, documentRoot, \"J001\", `Invalid JSON: ${String(thrown)}`);\n return;\n }\n}\n\nfunction readEnums(\n node: Record<string, unknown>,\n issues: DocumentIssues\n): Record<string, EnumDocument> | undefined {\n const path = pointer(documentRoot, \"enums\");\n const raw = member(node, \"enums\", documentRoot, issues);\n if (raw === undefined) return;\n const record = asRecord(raw, path, issues, \"`enums`\");\n return (\n record &&\n readRecordMap(record, path, issues, \"Enum reference\", (v, p) =>\n readEnumNode(v, p, issues)\n )\n );\n}\n\nfunction readEnumNode(\n value: unknown,\n path: string,\n issues: DocumentIssues\n): EnumDocument | undefined {\n const node = asRecord(value, path, issues, \"Enum definition\");\n if (node === undefined) return;\n refuseUnknownKeys(node, ENUM_KEYS, path, issues);\n const values = asStringArray(\n member(node, \"values\", path, issues),\n pointer(path, \"values\"),\n issues,\n \"`values`\"\n );\n if (values === undefined) return;\n const definition: EnumDocument = { values };\n const name = optString(node, \"name\", path, issues);\n if (name !== undefined) definition.name = name;\n return definition;\n}\n\nfunction readModels(\n node: Record<string, unknown>,\n issues: DocumentIssues\n): Record<string, ModelDocument> {\n const path = pointer(documentRoot, \"models\");\n const record = asRecord(\n member(node, \"models\", documentRoot, issues),\n path,\n issues,\n \"`models`\"\n );\n return record === undefined\n ? {}\n : readRecordMap(record, path, issues, \"Model key\", (v, p) =>\n readModelNode(v, p, issues)\n );\n}\n\nfunction readViews(\n node: Record<string, unknown>,\n issues: DocumentIssues\n): Record<string, ViewDocument> | undefined {\n const path = pointer(documentRoot, \"views\");\n const raw = member(node, \"views\", documentRoot, issues);\n if (raw === undefined) return;\n const record = asRecord(raw, path, issues, \"`views`\");\n return (\n record &&\n readRecordMap(record, path, issues, \"View key\", (v, p) =>\n readViewNode(v, p, issues)\n )\n );\n}\n\nfunction readViewNode(\n value: unknown,\n path: string,\n issues: DocumentIssues\n): ViewDocument | undefined {\n const node = asRecord(value, path, issues, \"View\");\n if (node === undefined) return;\n refuseUnknownKeys(node, VIEW_KEYS, path, issues);\n const source = asString(\n member(node, \"source\", path, issues),\n pointer(path, \"source\"),\n issues,\n \"`source`\"\n );\n const query = readViewQuery(node, path, issues);\n if (source === undefined || query === undefined) return;\n const view: ViewDocument = { source, query };\n const table = optString(node, \"table\", path, issues);\n if (table !== undefined) view.table = table;\n if (optBool(node, \"materialized\", path, issues)) view.materialized = true;\n const refresh = member(node, \"refresh\", path, issues);\n if (refresh === \"auto\" && view.materialized) view.refresh = \"auto\";\n else if (refresh !== undefined)\n addIssue(\n issues,\n pointer(path, \"refresh\"),\n \"J004\",\n '`refresh` must be \"auto\" with `materialized: true`'\n );\n const indexes = readIndexes(node, path, issues);\n if (indexes !== undefined) view.indexes = indexes;\n return view;\n}\n\nfunction readViewQuery(\n node: Record<string, unknown>,\n viewPath: string,\n issues: DocumentIssues\n): Record<string, JsonValue> | undefined {\n const path = pointer(viewPath, \"query\");\n const record = asRecord(\n member(node, \"query\", viewPath, issues),\n path,\n issues,\n \"`query`\"\n );\n if (record === undefined) return;\n if (reservedKey(inspectKeys(record, path, issues, \"J004\")) !== undefined) {\n addIssue(issues, path, \"J004\", \"`query` cannot be a tagged value\");\n return;\n }\n return readValueRecord(record, path, issues, \"query\");\n}\n\n// =============================================================================\n// MODEL\n// =============================================================================\n\nfunction readModelNode(\n value: unknown,\n path: string,\n issues: DocumentIssues\n): ModelDocument | undefined {\n const node = asRecord(value, path, issues, \"Model\");\n if (node === undefined) return;\n refuseUnknownKeys(node, MODEL_KEYS, path, issues);\n const model: ModelDocument = { fields: readFields(node, path, issues) };\n\n const table = optString(node, \"table\", path, issues);\n if (table !== undefined) model.table = table;\n const indexes = readIndexes(node, path, issues);\n if (indexes !== undefined) model.indexes = indexes;\n const ids = readCompoundKeys(node, \"ids\", path, issues);\n if (ids !== undefined) model.ids = ids;\n const uniques = readCompoundKeys(node, \"uniques\", path, issues);\n if (uniques !== undefined) model.uniques = uniques;\n const omit = readOmit(node, path, issues);\n if (omit !== undefined) model.omit = omit;\n if (optBool(node, \"withoutRowid\", path, issues)) model.withoutRowid = true;\n return model;\n}\n\nfunction readFields(\n node: Record<string, unknown>,\n modelPath: string,\n issues: DocumentIssues\n): Record<string, FieldDocument> {\n const path = pointer(modelPath, \"fields\");\n const record = asRecord(\n member(node, \"fields\", modelPath, issues),\n path,\n issues,\n \"`fields`\"\n );\n return record === undefined\n ? {}\n : readRecordMap(record, path, issues, \"Field key\", (v, p) =>\n readFieldNode(v, p, issues)\n );\n}\n\nfunction readIndexes(\n node: Record<string, unknown>,\n modelPath: string,\n issues: DocumentIssues\n): IndexDocument[] | undefined {\n return readArrayNode(node, \"indexes\", modelPath, issues, (entry, entryPath) =>\n readIndexNode(entry, entryPath, issues)\n );\n}\n\nfunction readIndexNode(\n value: unknown,\n path: string,\n issues: DocumentIssues\n): IndexDocument | undefined {\n const node = asRecord(value, path, issues, \"Index\");\n if (node === undefined) return;\n if (inspectKeys(node, path, issues, \"J004\").includes(\"where\")) {\n addIssue(\n issues,\n pointer(path, \"where\"),\n \"J009\",\n \"`where` is refused in v1 (raw SQL)\"\n );\n }\n refuseUnknownKeys(node, INDEX_KEYS, path, issues);\n const fields = asStringArray(\n member(node, \"fields\", path, issues),\n pointer(path, \"fields\"),\n issues,\n \"`fields`\"\n );\n if (fields === undefined) return;\n const index: IndexDocument = { fields };\n const name = optString(node, \"name\", path, issues);\n if (name !== undefined) index.name = name;\n const unique = optBool(node, \"unique\", path, issues);\n if (unique !== undefined) index.unique = unique;\n const type = member(node, \"type\", path, issues);\n if (type !== undefined) {\n if (isIndexType(type)) {\n index.type = type;\n } else {\n addIssue(\n issues,\n pointer(path, \"type\"),\n \"J004\",\n `\\`type\\` must be ${renderKeys(Object.keys(INDEX_TYPES))}`\n );\n }\n }\n return index;\n}\n\nfunction readCompoundKeys(\n node: Record<string, unknown>,\n key: \"ids\" | \"uniques\",\n modelPath: string,\n issues: DocumentIssues\n): CompoundKeyDocument[] | undefined {\n return readArrayNode(node, key, modelPath, issues, (entry, entryPath) =>\n readCompoundKeyNode(entry, entryPath, issues)\n );\n}\n\nfunction readCompoundKeyNode(\n value: unknown,\n path: string,\n issues: DocumentIssues\n): CompoundKeyDocument | undefined {\n const node = asRecord(value, path, issues, \"Compound key\");\n if (node === undefined) return;\n refuseUnknownKeys(node, COMPOUND_KEYS, path, issues);\n const fields = asStringArray(\n member(node, \"fields\", path, issues),\n pointer(path, \"fields\"),\n issues,\n \"`fields`\"\n );\n if (fields === undefined) return;\n const constraint: CompoundKeyDocument = { fields };\n const name = optString(node, \"name\", path, issues);\n if (name !== undefined) constraint.name = name;\n return constraint;\n}\n\nfunction readOmit(\n node: Record<string, unknown>,\n modelPath: string,\n issues: DocumentIssues\n): string[] | undefined {\n const raw = member(node, \"omit\", modelPath, issues);\n if (raw === undefined) return;\n return asStringArray(raw, pointer(modelPath, \"omit\"), issues, \"`omit`\");\n}\n\n// =============================================================================\n// FIELD\n// =============================================================================\n\nfunction readFieldNode(\n value: unknown,\n path: string,\n issues: DocumentIssues\n): FieldDocument | undefined {\n const node = asRecord(value, path, issues, \"Field\");\n if (node === undefined) return;\n const type = member(node, \"type\", path, issues);\n if (type === \"toOne\" || type === \"toMany\") {\n return readRelationField(node, type, path, issues);\n }\n if (isScalarTypeName(type)) {\n return readScalarField(node, type, path, issues);\n }\n addIssue(\n issues,\n pointer(path, \"type\"),\n \"J004\",\n `\\`type\\` must be 'toOne', 'toMany', or ${renderKeys([...SCALAR_TYPE_NAMES])}`\n );\n refuseUnknownKeys(node, ANY_FIELD_KEYS, path, issues);\n return;\n}\n\nfunction readScalarField(\n node: Record<string, unknown>,\n type: ScalarType,\n path: string,\n issues: DocumentIssues\n): ScalarFieldDocument | undefined {\n refuseUnknownKeys(node, SCALAR_FIELD_KEYS, path, issues);\n const field = readScalarArm(node, type, path, issues);\n if (field === undefined) return;\n\n readFlag(node, \"nullable\", path, issues, field);\n readFlag(node, \"array\", path, issues, field);\n readFlag(node, \"id\", path, issues, field);\n readFlag(node, \"unique\", path, issues, field);\n readFlag(node, \"withoutTimezone\", path, issues, field);\n\n const column = optString(node, \"column\", path, issues);\n if (column !== undefined) field.column = column;\n const dimension = member(node, \"dimension\", path, issues);\n if (dimension !== undefined) {\n if (type === \"point\") {\n refusePointModifier(\"dimension\", path, issues);\n } else {\n const size = asNumber(\n dimension,\n pointer(path, \"dimension\"),\n issues,\n \"`dimension`\"\n );\n if (size !== undefined) field.dimension = size;\n }\n }\n if (type !== \"decimal\") {\n refuseDecimalDomainBound(node, \"precision\", path, issues);\n refuseDecimalDomainBound(node, \"scale\", path, issues);\n }\n const native = member(node, \"native\", path, issues);\n if (native !== undefined) {\n if (field.type === \"point\") {\n refusePointModifier(\"native\", path, issues);\n } else if (field.type === \"decimal\") {\n addIssue(\n issues,\n pointer(path, \"native\"),\n \"J003\",\n \"`native` is not allowed on decimal fields\"\n );\n } else {\n const nativeType = readNativeNode(\n native,\n pointer(path, \"native\"),\n issues\n );\n if (nativeType !== undefined) field.native = nativeType;\n }\n }\n const byDialect = member(node, \"nativeByDialect\", path, issues);\n if (byDialect !== undefined) {\n if (field.type === \"point\") {\n refusePointModifier(\"nativeByDialect\", path, issues);\n } else if (field.type === \"decimal\" || native !== undefined) {\n addIssue(\n issues,\n pointer(path, \"nativeByDialect\"),\n \"J003\",\n field.type === \"decimal\"\n ? \"`nativeByDialect` is not allowed on decimal fields\"\n : \"Use either `native` or `nativeByDialect`, not both\"\n );\n } else {\n const map = readNativeByDialectNode(\n byDialect,\n pointer(path, \"nativeByDialect\"),\n issues\n );\n if (map !== undefined) field.nativeByDialect = map;\n }\n }\n const generate = member(node, \"generate\", path, issues);\n if (generate !== undefined) {\n if (type === \"point\") {\n refusePointModifier(\"generate\", path, issues);\n } else {\n const declaration = readGenerateNode(\n generate,\n pointer(path, \"generate\"),\n issues,\n field.id === true\n );\n if (declaration !== undefined) field.generate = declaration;\n }\n }\n const defaultValue = member(node, \"default\", path, issues);\n if (defaultValue !== undefined) {\n const literal = readDefaultValue(\n defaultValue,\n pointer(path, \"default\"),\n issues\n );\n if (literal !== undefined) field.default = literal;\n }\n return field;\n}\n\nfunction readRequiredDomainBound(\n node: Record<string, unknown>,\n key: \"precision\" | \"scale\",\n path: string,\n issues: DocumentIssues\n): number | undefined {\n const value = member(node, key, path, issues);\n if (value === undefined) {\n addIssue(\n issues,\n pointer(path, key),\n \"J004\",\n `Decimal field requires \\`${key}\\``\n );\n return;\n }\n return asNumber(value, pointer(path, key), issues, `\\`${key}\\``);\n}\n\nfunction refuseDecimalDomainBound(\n node: Record<string, unknown>,\n key: \"precision\" | \"scale\",\n path: string,\n issues: DocumentIssues\n): void {\n if (member(node, key, path, issues) === undefined) return;\n addIssue(\n issues,\n pointer(path, key),\n \"J003\",\n `\\`${key}\\` is only valid on 'decimal'`\n );\n}\n\nfunction readScalarArm(\n node: Record<string, unknown>,\n type: ScalarType,\n path: string,\n issues: DocumentIssues\n): ScalarFieldDocument | undefined {\n const raw = member(node, \"enum\", path, issues);\n const enumPath = pointer(path, \"enum\");\n if (type !== \"enum\") {\n if (raw !== undefined) {\n addIssue(issues, enumPath, \"J003\", \"`enum` is only valid on 'enum'\");\n }\n if (type === \"decimal\") {\n const precision = readRequiredDomainBound(\n node,\n \"precision\",\n path,\n issues\n );\n const scale = readRequiredDomainBound(node, \"scale\", path, issues);\n if (precision === undefined || scale === undefined) return;\n return { type, precision, scale };\n }\n return { type };\n }\n if (raw === undefined) {\n addIssue(issues, enumPath, \"J004\", \"Enum field requires `enum`\");\n return;\n }\n if (typeof raw === \"string\") return { type, enum: raw };\n const values = asStringArray(raw, enumPath, issues, \"`enum`\");\n return values && { type, enum: values };\n}\n\ntype ScalarFlagKey = \"nullable\" | \"array\" | \"id\" | \"unique\" | \"withoutTimezone\";\n\nfunction readFlag(\n node: Record<string, unknown>,\n key: ScalarFlagKey,\n path: string,\n issues: DocumentIssues,\n field: ScalarFieldDocument\n): void {\n const raw = member(node, key, path, issues);\n if (raw === undefined) return;\n if (field.type === \"point\" && key !== \"nullable\") {\n refusePointModifier(key, path, issues);\n return;\n }\n const flag = asBoolean(raw, pointer(path, key), issues, `\\`${key}\\``);\n if (flag === undefined) return;\n if (key === \"nullable\") {\n field.nullable = flag;\n return;\n }\n if (field.type !== \"point\") field[key] = flag;\n}\n\nfunction refusePointModifier(\n key: string,\n path: string,\n issues: DocumentIssues\n): void {\n addIssue(\n issues,\n pointer(path, key),\n \"J007\",\n `'point' has no '${key}' modifier`\n );\n}\n\nfunction readNativeNode(\n value: unknown,\n path: string,\n issues: DocumentIssues\n): NativeType | undefined {\n const node = asRecord(value, path, issues, \"`native`\");\n if (node === undefined) return;\n refuseUnknownKeys(node, NATIVE_KEYS, path, issues);\n const db = member(node, \"db\", path, issues);\n const type = asString(\n member(node, \"type\", path, issues),\n pointer(path, \"type\"),\n issues,\n \"`native.type`\"\n );\n if (!isNativeDialect(db)) {\n addIssue(\n issues,\n pointer(path, \"db\"),\n \"J004\",\n `\\`native.db\\` must be ${renderKeys(NATIVE_DIALECTS)}`\n );\n return;\n }\n if (type === undefined) return;\n if (!isNativeTypeInCatalog(db, type)) {\n addIssue(issues, pointer(path, \"type\"), \"J011\", nativeTypeRefusal(db));\n return;\n }\n return { db, type };\n}\n\nfunction readNativeByDialectNode(\n value: unknown,\n path: string,\n issues: DocumentIssues\n): NativeTypeMap | undefined {\n const node = asRecord(value, path, issues, \"`nativeByDialect`\");\n if (node === undefined) return;\n refuseUnknownKeys(node, NATIVE_DIALECTS, path, issues);\n const map: {\n pg?: DialectNativeType<\"pg\">;\n mysql?: DialectNativeType<\"mysql\">;\n sqlite?: DialectNativeType<\"sqlite\">;\n } = {};\n const pg = readDialectEntry(node, \"pg\", path, issues);\n if (pg !== undefined) map.pg = pg;\n const mysql = readDialectEntry(node, \"mysql\", path, issues);\n if (mysql !== undefined) map.mysql = mysql;\n const sqlite = readDialectEntry(node, \"sqlite\", path, issues);\n if (sqlite !== undefined) map.sqlite = sqlite;\n return map;\n}\n\nfunction readDialectEntry<Dialect extends NativeDialect>(\n node: Record<string, unknown>,\n dialect: Dialect,\n path: string,\n issues: DocumentIssues\n): DialectNativeType<Dialect> | undefined {\n const value = member(node, dialect, path, issues);\n if (value === undefined) return;\n const entryPath = pointer(path, dialect);\n const entry = readNativeNode(value, entryPath, issues);\n if (entry === undefined) return;\n if (entry.db !== dialect) {\n addIssue(\n issues,\n pointer(entryPath, \"db\"),\n \"J004\",\n `'${dialect}' entry \\`db\\` must be '${dialect}'`\n );\n return;\n }\n return { db: dialect, type: entry.type };\n}\n\nfunction readGenerateNode(\n value: unknown,\n path: string,\n issues: DocumentIssues,\n isKey: boolean\n): GenerateDocument | undefined {\n const node = asRecord(value, path, issues, \"`generate`\");\n if (node === undefined) return;\n refuseUnknownKeys(node, GENERATE_KEYS, path, issues);\n const kind = member(node, \"kind\", path, issues);\n if (!isGenerateKind(kind)) {\n addIssue(\n issues,\n pointer(path, \"kind\"),\n \"J004\",\n `\\`generate.kind\\` must be ${renderKeys(Object.keys(GENERATE_KINDS))}`\n );\n return;\n }\n const declaration: GenerateDocument = { kind };\n const generated = member(node, \"generate\", path, issues);\n if (generated !== undefined) {\n const flag = asBoolean(\n generated,\n pointer(path, \"generate\"),\n issues,\n \"`generate`\"\n );\n if (kind === \"now\" || kind === \"updatedAt\" || kind === \"increment\") {\n addIssue(\n issues,\n pointer(path, \"generate\"),\n \"J004\",\n \"`generate` boolean is only for string ID formats\"\n );\n } else if (flag !== undefined) declaration.generate = flag;\n }\n const prefix = optString(node, \"prefix\", path, issues);\n if (prefix !== undefined) declaration.prefix = prefix;\n const length = member(node, \"length\", path, issues);\n if (length !== undefined) {\n const size = asNumber(length, pointer(path, \"length\"), issues, \"`length`\");\n if (size !== undefined) declaration.length = size;\n }\n if (optBool(node, \"implicit\", path, issues)) {\n if (kind !== \"ulid\") {\n addIssue(\n issues,\n pointer(path, \"implicit\"),\n \"J004\",\n '`generate.implicit` requires `kind: \"ulid\"`'\n );\n } else if (isKey) {\n declaration.implicit = true;\n } else {\n addIssue(\n issues,\n pointer(path, \"implicit\"),\n \"J004\",\n \"`generate.implicit` requires `id: true`\"\n );\n }\n }\n return declaration;\n}\n\n// =============================================================================\n// RELATION\n// =============================================================================\n\nfunction readRelationField(\n node: Record<string, unknown>,\n type: \"toOne\" | \"toMany\",\n path: string,\n issues: DocumentIssues\n): RelationFieldDocument | undefined {\n const target = member(node, \"target\", path, issues);\n const variants = member(node, \"variants\", path, issues);\n if ((target === undefined) === (variants === undefined)) {\n addIssue(\n issues,\n path,\n \"J004\",\n \"Relation requires either `target` or `variants`\"\n );\n return;\n }\n const cardinality = type === \"toOne\" ? \"one\" : \"many\";\n refuseUnknownKeys(\n node,\n relationKeys({ cardinality, variants: variants !== undefined }),\n path,\n issues\n );\n const name = optString(node, \"name\", path, issues);\n if (target === undefined) {\n return readVariantTargetArm(\n node,\n { type, variants },\n name,\n cardinality,\n path,\n issues\n );\n }\n const key = asString(target, pointer(path, \"target\"), issues, \"`target`\");\n if (key === undefined) return;\n return readModelTargetArm(\n node,\n { type, target: key },\n name,\n cardinality,\n path,\n issues\n );\n}\n\nfunction readModelTargetArm(\n node: Record<string, unknown>,\n relation: ModelTargetDocument,\n name: string | undefined,\n cardinality: \"one\" | \"many\",\n path: string,\n issues: DocumentIssues\n): ModelTargetDocument {\n if (name !== undefined) relation.name = name;\n if (cardinality === \"many\") {\n const junction = member(node, \"junction\", path, issues);\n if (junction !== undefined) {\n const overrides = readJunctionNode(\n junction,\n pointer(path, \"junction\"),\n issues\n );\n if (overrides !== undefined) relation.junction = overrides;\n }\n return relation;\n }\n for (const key of [\"fields\", \"references\"] as const) {\n const raw = member(node, key, path, issues);\n if (raw === undefined) continue;\n const keys = asStringArray(raw, pointer(path, key), issues, `\\`${key}\\``);\n if (keys !== undefined) relation[key] = keys;\n }\n for (const key of [\"onDelete\", \"onUpdate\"] as const) {\n const raw = member(node, key, path, issues);\n if (raw === undefined) continue;\n if (isReferentialAction(raw)) {\n relation[key] = raw;\n continue;\n }\n addIssue(\n issues,\n pointer(path, key),\n \"J004\",\n `\\`${key}\\` must be ${renderKeys(Object.keys(REFERENTIAL_ACTIONS))}`\n );\n }\n return relation;\n}\n\nfunction readVariantTargetArm(\n node: Record<string, unknown>,\n relation: { type: \"toOne\" | \"toMany\"; variants: unknown },\n name: string | undefined,\n cardinality: \"one\" | \"many\",\n path: string,\n issues: DocumentIssues\n): VariantTargetDocument | undefined {\n const map = readStringMap(\n relation.variants,\n pointer(path, \"variants\"),\n issues,\n \"`variants`\"\n );\n if (map === undefined) return;\n const declaration: VariantTargetDocument = {\n type: relation.type,\n variants: map,\n };\n if (name !== undefined) declaration.name = name;\n const values = member(node, \"values\", path, issues);\n if (values !== undefined) {\n const bag = readStringMap(\n values,\n pointer(path, \"values\"),\n issues,\n \"`values`\"\n );\n if (bag !== undefined) declaration.values = bag;\n }\n if (cardinality === \"one\") {\n const optional = optBool(node, \"optional\", path, issues);\n if (optional !== undefined) declaration.optional = optional;\n return declaration;\n }\n const through = member(node, \"through\", path, issues);\n if (through !== undefined) {\n const junctions = readThroughMap(through, pointer(path, \"through\"), issues);\n if (junctions !== undefined) declaration.through = junctions;\n }\n return declaration;\n}\n\nfunction readStringMap(\n value: unknown,\n path: string,\n issues: DocumentIssues,\n what: string\n): Record<string, string> | undefined {\n const record = asRecord(value, path, issues, what);\n return (\n record &&\n readRecordMap(record, path, issues, \"Variant key\", (v, p) =>\n asString(v, p, issues, what)\n )\n );\n}\n\nfunction readThroughMap(\n value: unknown,\n path: string,\n issues: DocumentIssues\n): Record<string, VariantJunctionDocument> | undefined {\n const record = asRecord(value, path, issues, \"`through`\");\n return (\n record &&\n readRecordMap(record, path, issues, \"Variant key\", (v, p) =>\n readVariantJunctionNode(v, p, issues)\n )\n );\n}\n\nfunction readVariantJunctionNode(\n value: unknown,\n path: string,\n issues: DocumentIssues\n): VariantJunctionDocument | undefined {\n const node = asRecord(value, path, issues, \"Member junction\");\n if (node === undefined) return;\n refuseUnknownKeys(node, VARIANT_JUNCTION_KEYS, path, issues);\n const req = (k: string) =>\n asString(\n member(node, k, path, issues),\n pointer(path, k),\n issues,\n `\\`${k}\\``\n );\n const table = req(\"table\");\n const source = req(\"source\");\n const target = req(\"target\");\n if (table === undefined || source === undefined || target === undefined) {\n return;\n }\n return { table, source, target };\n}\n\nfunction readJunctionNode(\n value: unknown,\n path: string,\n issues: DocumentIssues\n): JunctionDocument | undefined {\n const node = asRecord(value, path, issues, \"`junction`\");\n if (node === undefined) return;\n refuseUnknownKeys(node, JUNCTION_KEYS, path, issues);\n if (inspectKeys(node, path, issues, \"J004\").length === 0) {\n addIssue(\n issues,\n path,\n \"J004\",\n \"`junction` must declare at least one option\"\n );\n return;\n }\n const names: JunctionNamesDocument = {};\n for (const key of [\"table\", \"model\", \"source\", \"target\"] as const) {\n const text = optString(node, key, path, issues);\n if (text !== undefined) names[key] = text;\n }\n if (names.table !== undefined && names.model !== undefined)\n addIssue(\n issues,\n path,\n \"J004\",\n \"`junction` takes 'table' or 'model', never both\"\n );\n const onDelete = readJunctionActionSpelling(node, \"onDelete\", path, issues);\n const onUpdate = readJunctionActionSpelling(node, \"onUpdate\", path, issues);\n return {\n ...names,\n ...(typeof onDelete === \"string\"\n ? { onDelete }\n : onDelete && { onDeleteSides: onDelete }),\n ...(typeof onUpdate === \"string\"\n ? { onUpdate }\n : onUpdate && { onUpdateSides: onUpdate }),\n };\n}\n\nfunction readJunctionActionSpelling(\n node: Record<string, unknown>,\n key: \"onDelete\" | \"onUpdate\",\n path: string,\n issues: DocumentIssues\n): JunctionReferentialAction | JunctionSidesDocument | undefined {\n const raw = member(node, key, path, issues);\n const sidesKey = `${key}Sides` as const;\n const rawSides = member(node, sidesKey, path, issues);\n if (raw !== undefined && rawSides !== undefined) {\n addIssue(\n issues,\n pointer(path, sidesKey),\n \"J004\",\n `Use \\`${key}\\` or \\`${sidesKey}\\`, not both`\n );\n return;\n }\n if (rawSides !== undefined) {\n return readJunctionSides(\n rawSides,\n pointer(path, sidesKey),\n issues,\n sidesKey\n );\n }\n if (raw === undefined) return;\n return readJunctionAction(raw, pointer(path, key), issues, key);\n}\n\nfunction readJunctionSides(\n value: unknown,\n path: string,\n issues: DocumentIssues,\n key: \"onDeleteSides\" | \"onUpdateSides\"\n): JunctionSidesDocument | undefined {\n const node = asRecord(value, path, issues, `\\`${key}\\``);\n if (node === undefined) return;\n refuseUnknownKeys(node, JUNCTION_SIDE_KEYS, path, issues);\n const readSide = (side: \"source\" | \"target\") => {\n const raw = member(node, side, path, issues);\n if (raw !== undefined) {\n return readJunctionAction(\n raw,\n pointer(path, side),\n issues,\n `${key}.${side}`\n );\n }\n addIssue(\n issues,\n pointer(path, side),\n \"J004\",\n `\\`${key}\\` requires '${side}'`\n );\n return;\n };\n const source = readSide(\"source\");\n const target = readSide(\"target\");\n if (source === undefined || target === undefined) return;\n return { source, target };\n}\n\nfunction readJunctionAction(\n raw: unknown,\n path: string,\n issues: DocumentIssues,\n key: string\n): JunctionReferentialAction | undefined {\n if (isJunctionAction(raw)) return raw;\n addIssue(\n issues,\n path,\n \"J004\",\n `\\`${key}\\` must be ${renderKeys(Object.keys(JUNCTION_ACTIONS))}; 'setNull' cannot null a membership-key member`\n );\n return;\n}\n\n// =============================================================================\n// DOCUMENT-LOCAL REFERENCES\n// =============================================================================\n\nfunction resolveReferences(\n document: SchemaDocument,\n issues: DocumentIssues\n): void {\n const modelsPath = pointer(documentRoot, \"models\");\n for (const [modelKey, model] of Object.entries(document.models)) {\n const modelPath = pointer(modelsPath, modelKey);\n const fieldsPath = pointer(modelPath, \"fields\");\n for (const [fieldKey, field] of Object.entries(model.fields)) {\n resolveTargetReferences(\n document,\n field,\n pointer(fieldsPath, fieldKey),\n issues\n );\n }\n resolveOmitReferences(model, modelPath, issues);\n }\n resolveViewReferences(document, issues);\n}\n\nfunction resolveViewReferences(\n document: SchemaDocument,\n issues: DocumentIssues\n): void {\n const views = document.views ?? {};\n const viewsPath = pointer(documentRoot, \"views\");\n for (const [viewKey, view] of Object.entries(views)) {\n const viewPath = pointer(viewsPath, viewKey);\n if (Object.hasOwn(document.models, viewKey)) {\n addIssue(\n issues,\n viewPath,\n \"J013\",\n `'${viewKey}' is in both \\`models\\` and \\`views\\``\n );\n }\n const sourcePath = pointer(viewPath, \"source\");\n if (\n !(\n Object.hasOwn(document.models, view.source) ||\n Object.hasOwn(views, view.source)\n )\n ) {\n addIssue(\n issues,\n sourcePath,\n \"J006\",\n `\\`source\\` '${view.source}' not in \\`models\\` or \\`views\\``\n );\n continue;\n }\n if (readsItself(views, viewKey)) {\n addIssue(\n issues,\n sourcePath,\n \"J012\",\n `View '${viewKey}' reads itself in a cycle`\n );\n }\n }\n}\n\nfunction readsItself(\n views: Readonly<Record<string, ViewDocument>>,\n viewKey: string\n): boolean {\n const followed = new Set<string>();\n let key = views[viewKey]?.source;\n while (key !== undefined && Object.hasOwn(views, key)) {\n if (key === viewKey) return true;\n if (followed.has(key)) return false;\n followed.add(key);\n key = views[key]?.source;\n }\n return false;\n}\n\nfunction resolveTargetReferences(\n document: SchemaDocument,\n field: FieldDocument,\n path: string,\n issues: DocumentIssues\n): void {\n if (!isRelationField(field)) return;\n if (field.target !== undefined) {\n refuseUnknownModel(document, field.target, pointer(path, \"target\"), issues);\n }\n if (field.junction?.model !== undefined) {\n refuseUnknownModel(\n document,\n field.junction.model,\n pointer(path, \"junction\", \"model\"),\n issues\n );\n }\n for (const [variantKey, target] of Object.entries(field.variants ?? {})) {\n refuseUnknownModel(\n document,\n target,\n pointer(path, \"variants\", variantKey),\n issues\n );\n }\n}\n\nfunction refuseUnknownModel(\n document: SchemaDocument,\n target: string,\n path: string,\n issues: DocumentIssues\n): void {\n if (Object.hasOwn(document.models, target)) return;\n addIssue(issues, path, \"J006\", `Model '${target}' not in \\`models\\``);\n}\n\nfunction resolveOmitReferences(\n model: ModelDocument,\n modelPath: string,\n issues: DocumentIssues\n): void {\n for (const [position, name] of (model.omit ?? []).entries()) {\n const field = model.fields[name];\n if (field !== undefined && !isRelationField(field)) continue;\n addIssue(\n issues,\n pointer(modelPath, \"omit\", String(position)),\n \"J006\",\n `\\`omit\\` '${name}' is not a scalar field`\n );\n }\n}\n","// The `validate` option: how a call states it, and who it hands the schema to.\n//\n// The option is NOT part of the document — nothing about it describes a schema —\n// so it is read at the CALL boundary rather than by the document reader, and its\n// pointers name the options argument (`/options/...`) rather than a location in\n// the author's artifact. It gets the same discipline the document gets, down to\n// the guarded accessor: a program that builds its options from data can build\n// them from a getter, and a bag is no more the caller's own literal than a\n// document handed in as an object is.\n//\n// What `validate: true` RUNS is deliberately not written here.\n// `validateSchemaOrThrow` is the schema validator every effect-capable boundary\n// already runs — `push`, the CLI — and this option is a second CALLER of it,\n// never a second copy: the whole rule list, its `M0xx`/`R0xx`/`P0xx` codes and\n// its `SchemaValidationError` all arrive unfiltered and untranslated. The `J0xx`\n// family stays what it has always been, a vocabulary for the shape of the\n// ARTIFACT; a graph is refused in the graph's own words.\n\nimport { hydrateSchemaNames, type Schema } from \"@schema/hydration\";\nimport { validateSchemaOrThrow } from \"@schema/validation/validator\";\nimport {\n addIssue,\n type DocumentIssues,\n documentRoot,\n inspectKeys,\n inspectPlainRecord,\n member,\n pointer,\n refuseDocument,\n throwIfRefused,\n} from \"./issues\";\n\n/**\n * What a call may ask for beyond the conversion itself.\n *\n * `validate` runs the schema validator over the schema — the same full rule list\n * `push` and the CLI run, reporting in its own vocabulary. It defaults to\n * `false`: a document is legitimately read for inspection, canonicalization or\n * diffing without ever becoming a client, and a schema is legitimately dumped\n * for diagnosis while it is still broken.\n */\nexport type SchemaJsonOptions = {\n validate?: boolean;\n};\n\n/**\n * An options bag that carries this call's own keys and NOTHING else.\n *\n * `options?: SchemaJsonOptions` is no guard on its own: a bag with a stray key\n * is still assignable, and only excess-property checking stands between the\n * caller and a silent no-op — which needs a FRESH object literal. A bag built\n * from data and held in a variable, which is how a program actually writes one,\n * sails through. Demanding `never` for the unknown keys refuses structurally,\n * whatever the argument's freshness. Same instrument as the model builder's\n * `ExactOptions` and `push`'s `ExactPushOptions`.\n *\n * The runtime reader below stays: a caller in JavaScript, or one who built the\n * bag through `JSON.parse`, never met the compiler at all.\n */\nexport type ExactSchemaJsonOptions<Given> = Given &\n Record<Exclude<keyof Given, keyof SchemaJsonOptions>, never>;\n\nconst OPTION_KEYS = [\"validate\"];\nconst DECLARED_OPTIONS = OPTION_KEYS.map((key) => `'${key}'`).join(\", \");\n\n/** The options argument's own pointer root; no document node is spelled `options`. */\nconst OPTIONS_ROOT = pointer(documentRoot, \"options\");\n\n/**\n * Read the options argument, refusing anything this call does not declare.\n *\n * A misspelled option is the failure this owner exists for: `{ validat: true }`\n * would otherwise be a silent no-op, and a call that asked for validation and\n * did not get it is the one outcome worse than not asking. A non-boolean\n * `validate` is the same failure spelled by a program that built its options\n * from data — `\"true\"` is not `true`.\n */\nexport function readValidateOption(\n options: SchemaJsonOptions | undefined\n): boolean {\n if (options === undefined) return false;\n const issues: DocumentIssues = [];\n if (!inspectPlainRecord(options, OPTIONS_ROOT, issues, \"J004\")) {\n addIssue(issues, OPTIONS_ROOT, \"J004\", \"`options` must be a plain object\");\n throw refuseDocument(issues);\n }\n // The options bag TOLERATES own-`undefined` (the document does not): the loop\n // below reads `validate` and treats `undefined` as absent, because\n // `validate?: boolean` admits it by the TS optional-property idiom.\n for (const key of inspectKeys(options, OPTIONS_ROOT, issues, \"J004\")) {\n if (OPTION_KEYS.includes(key)) continue;\n addIssue(\n issues,\n pointer(OPTIONS_ROOT, key),\n \"J003\",\n `Unknown option '${key}'; allowed: ${DECLARED_OPTIONS}`\n );\n }\n const validate = member(options, \"validate\", OPTIONS_ROOT, issues);\n if (validate !== undefined && typeof validate !== \"boolean\") {\n addIssue(\n issues,\n pointer(OPTIONS_ROOT, \"validate\"),\n \"J004\",\n \"`validate` must be a boolean\"\n );\n }\n throwIfRefused(issues);\n return validate === true;\n}\n\n/**\n * The two ordered phases of the definition pipeline, at this boundary as at\n * every other: hydration binds names and proves model identity, then the\n * validator resolves the relation graph and runs the rule list over it.\n *\n * Both phases WRITE to the schema — write-once name binding, and the per-terminal\n * target once-cell — which is why the option that reaches them is off by\n * default.\n */\nexport function validateGraph(schema: Schema): void {\n hydrateSchemaNames(schema);\n validateSchemaOrThrow(schema);\n}\n","// The reverse direction: a coded schema stated as a document.\n//\n// It walks `model[\"~\"].state` and reads DECLARATIONS, not the resolved\n// topology — the resolver derives foreign-key ownership, junction naming and\n// slot nullability, and emitting those would put facts in the document the\n// author never wrote.\n//\n// It does NOT mutate the schema it is given. Hydration write-once-binds a model\n// to a schema key and `settleTarget` permanently caches a getter's outcome\n// (including a thrown Error), so a serializer that hydrated would foreclose\n// ever binding those models under other keys and would poison a terminal whose\n// getter throws. Target keys come from an identity scan of the caller's own\n// record instead, which means an unbound — or even topologically broken —\n// schema stays dumpable for diagnosis.\n//\n// `{ validate: true }` DELIBERATELY GIVES THAT UP, and is off by default for\n// exactly this reason. Refusing garbage before emitting it means running the\n// validator, and the validator hydrates and settles — so an opted-in call binds\n// the passed record's keys and settles its targets, precisely as `createClient`\n// would. Diagnosis keeps the default; a producer that means to publish a\n// document asks for the check.\n\nimport type { Schema } from \"@schema/hydration\";\nimport { isValidSchemaIdentifier } from \"@schema/identifier\";\nimport type { AnyModel } from \"@schema/model\";\nimport type { IndexDefinition } from \"@schema/model/model\";\nimport { emptyRecord, own, put, stateOf } from \"@schema/record\";\nimport type {\n AnyRelation,\n Getter,\n JunctionReferentialAction,\n JunctionSideActions,\n RelationState,\n VariantEntry,\n VariantRelationState,\n} from \"@schema/relation/types\";\nimport { isVariantRelationState } from \"@schema/relation/types\";\nimport type { Scalar } from \"@schema/scalars/base\";\nimport {\n type AutoGenerate,\n isGeneratorDefault,\n type ScalarState,\n} from \"@schema/scalars/common\";\nimport {\n isNativeTypeInCatalog,\n nativeTypeRefusal,\n} from \"@schema/scalars/native-catalog\";\nimport {\n type DialectNativeType,\n isTaggedNativeType,\n type NativeTypeMap,\n} from \"@schema/scalars/native-types\";\nimport { type ViewFacts, viewFacts } from \"@schema/view/facts\";\nimport type { JsonValue } from \"@validation/primitives/json\";\nimport type { ObjectSchema } from \"@validation/primitives/object\";\nimport { isFunction } from \"@validation/value-guards\";\nimport { toError } from \"../../errors/diagnostic-safety\";\nimport { encodeDefault, encodeValueRecord } from \"./default-codec\";\nimport type {\n CompoundKeyDocument,\n EnumDocument,\n FieldDocument,\n GenerateDocument,\n IndexDocument,\n JunctionNamesDocument,\n JunctionSidesDocument,\n ModelDocument,\n ModelTargetDocument,\n RelationFieldDocument,\n ScalarFieldDocument,\n SchemaDocument,\n VariantJunctionDocument,\n VariantTargetDocument,\n ViewDocument,\n} from \"./document\";\nimport { SCHEMA_DOCUMENT_VERSION } from \"./document\";\nimport { builderMethod } from \"./factories\";\nimport {\n addIssue,\n type DocumentIssues,\n documentRoot,\n pointer,\n refuseDocument,\n throwIfRefused,\n} from \"./issues\";\nimport { lightModels } from \"./light\";\nimport type { ExactSchemaJsonOptions, SchemaJsonOptions } from \"./validate\";\nimport { readValidateOption, validateGraph } from \"./validate\";\n\n/**\n * The `enums` section under construction: the definitions keyed by document\n * REF, plus the database-name → ref map that makes two fields naming one\n * database enum type share one definition.\n */\ntype EnumRegistry = {\n readonly refs: Map<string, string>;\n readonly definitions: Record<string, EnumDocument>;\n};\n\n/**\n * Write the document a schema denotes.\n *\n * Every refusal below names a fact the format cannot carry, loudly — a silent\n * drop would produce a document that parses into a DIFFERENT schema, which is\n * the one failure a round trip must not have.\n *\n * `{ validate: true }` runs the schema validator FIRST — the same full rule list\n * `push` and the CLI run — so a schema whose graph does not resolve is refused\n * before a single node is emitted, in the validator's own vocabulary\n * (`SchemaValidationError`, `M0xx`/`R0xx`/`P0xx`), never as a `J0xx` code.\n *\n * It costs the non-mutation guarantee: validating hydrates the schema under the\n * keys of the record passed here and settles its relation targets. The default\n * keeps the guarantee, and keeps a broken schema dumpable.\n */\nexport function serializeSchema<\n Options extends SchemaJsonOptions = SchemaJsonOptions,\n>(schema: Schema, options?: ExactSchemaJsonOptions<Options>): SchemaDocument {\n if (readValidateOption(options)) validateGraph(schema);\n const issues: DocumentIssues = [];\n const enums: EnumRegistry = { refs: new Map(), definitions: emptyRecord() };\n const models = emptyRecord<ModelDocument>();\n const views = emptyRecord<ViewDocument>();\n const modelsPath = pointer(documentRoot, \"models\");\n const viewsPath = pointer(documentRoot, \"views\");\n for (const [modelKey, model] of Object.entries(schema)) {\n const facts = readViewFacts(model, pointer(viewsPath, modelKey));\n if (facts !== undefined) {\n put(\n views,\n modelKey,\n serializeView(\n model,\n facts,\n schema,\n pointer(viewsPath, modelKey),\n issues\n )\n );\n continue;\n }\n put(\n models,\n modelKey,\n serializeModel(\n model,\n schema,\n enums,\n pointer(modelsPath, modelKey),\n issues\n )\n );\n }\n throwIfRefused(issues);\n const document: SchemaDocument = {\n version: SCHEMA_DOCUMENT_VERSION,\n // Light when any model is: a push of the document must stay refused.\n ...(Object.values(schema).some((model) => lightModels.has(model)) && {\n light: true,\n }),\n models,\n };\n if (Object.keys(enums.definitions).length > 0) {\n document.enums = enums.definitions;\n }\n if (Object.keys(views).length > 0) document.views = views;\n return document;\n}\n\n/**\n * Whether a schema member is a view, and what makes it one. A view's facts are\n * derived from its source on first read, so its source getter runs here; one\n * that throws is a schema the document cannot describe.\n */\nfunction readViewFacts(model: AnyModel, path: string): ViewFacts | undefined {\n try {\n return viewFacts(model);\n } catch (thrown) {\n const issue: DocumentIssues = [];\n addIssue(issue, path, \"J006\", \"View source could not be read\");\n throw refuseDocument(issue, toError(thrown));\n }\n}\n\nfunction serializeView(\n model: AnyModel,\n facts: ViewFacts,\n schema: Schema,\n path: string,\n issues: DocumentIssues\n): ViewDocument {\n const state = stateOf(model);\n const document: ViewDocument = {\n source: schemaKeyOf(facts.source, schema, pointer(path, \"source\"), issues),\n query:\n encodeValueRecord(facts.query, pointer(path, \"query\"), issues, \"query\") ??\n {},\n };\n if (state.tableName !== undefined) document.table = state.tableName;\n if (facts.materialized) document.materialized = true;\n if (facts.refresh === \"auto\") document.refresh = \"auto\";\n const indexes = serializeIndexes(state.indexes, path, issues);\n if (indexes.length > 0) document.indexes = indexes;\n const chained = [\n model[\"~\"].rawIndexes.length > 0 && \"raw index\",\n model[\"~\"].withoutRowid && \"withoutRowid\",\n state.omit !== undefined && \"omit\",\n ].filter((declared) => declared !== false);\n if (chained.length > 0) {\n addIssue(\n issues,\n path,\n \"J009\",\n `View cannot serialize ${chained.join(\", \")}`\n );\n }\n return document;\n}\n\nfunction serializeModel(\n model: AnyModel,\n schema: Schema,\n enums: EnumRegistry,\n path: string,\n issues: DocumentIssues\n): ModelDocument {\n const state = stateOf(model);\n const relations: Record<string, AnyRelation> = state.relations;\n const scalars: Record<string, Scalar> = state.scalars;\n const fields = emptyRecord<FieldDocument>();\n const fieldsPath = pointer(path, \"fields\");\n // `shape` holds scalars and relations interleaved in DECLARATION order, and\n // that order is the document's own — DDL column order follows it.\n for (const fieldKey of Object.keys(state.shape)) {\n const relation = own(relations, fieldKey);\n const scalar = own(scalars, fieldKey);\n const fieldPath = pointer(fieldsPath, fieldKey);\n if (relation !== undefined) {\n put(\n fields,\n fieldKey,\n serializeRelation(relation, schema, fieldPath, issues)\n );\n continue;\n }\n if (scalar !== undefined) {\n put(fields, fieldKey, serializeScalar(scalar, enums, fieldPath, issues));\n }\n // A shape member that is neither is one `s.model(...)` already dropped;\n // the document states what the model holds, not what was handed to it.\n }\n\n const document: ModelDocument = { fields };\n if (state.tableName !== undefined) document.table = state.tableName;\n const indexes = serializeIndexes(state.indexes, path, issues);\n if (indexes.length > 0) document.indexes = indexes;\n if (model[\"~\"].rawIndexes.length > 0) {\n addIssue(\n issues,\n pointer(path, \"rawIndexes\"),\n \"J009\",\n \"Raw index cannot be serialized (raw SQL)\"\n );\n }\n const ids = serializeCompound(state.compoundId);\n if (ids.length > 0) document.ids = ids;\n const uniques = serializeCompound(state.compoundUniques);\n if (uniques.length > 0) document.uniques = uniques;\n if (state.omit !== undefined) {\n document.omit = Object.keys(state.omit).sort();\n }\n if (model[\"~\"].withoutRowid) document.withoutRowid = true;\n return document;\n}\n\nfunction serializeIndexes(\n indexes: readonly IndexDefinition[],\n path: string,\n issues: DocumentIssues\n): IndexDocument[] {\n const documents: IndexDocument[] = [];\n for (const [position, index] of indexes.entries()) {\n const indexPath = pointer(path, \"indexes\", String(position));\n if (index.options.where !== undefined) {\n addIssue(\n issues,\n indexPath,\n \"J009\",\n \"Partial index `where` cannot be serialized (raw SQL)\"\n );\n continue;\n }\n const document: IndexDocument = { fields: [...index.fields] };\n if (index.options.name !== undefined) document.name = index.options.name;\n if (index.options.unique !== undefined) {\n document.unique = index.options.unique;\n }\n if (index.options.type !== undefined) document.type = index.options.type;\n documents.push(document);\n }\n return documents;\n}\n\n/**\n * A compound constraint's fields are the keys of the object schema `.id()` /\n * `.unique()` built, and its name is the record key. A name equal to the\n * default — the fields joined by `_` — is the ABSENCE of a name, so the\n * canonical document omits it.\n */\nfunction serializeCompound(\n constraints: Record<string, ObjectSchema<Record<string, unknown>>> | undefined\n): CompoundKeyDocument[] {\n const documents: CompoundKeyDocument[] = [];\n for (const [name, schema] of Object.entries(constraints ?? {})) {\n const fields = Object.keys(schema.entries);\n const document: CompoundKeyDocument = { fields };\n if (name !== fields.join(\"_\")) document.name = name;\n documents.push(document);\n }\n return documents;\n}\n\n// =============================================================================\n// SCALAR\n// =============================================================================\n\nfunction serializeScalar(\n scalar: Scalar,\n enums: EnumRegistry,\n path: string,\n issues: DocumentIssues\n): ScalarFieldDocument {\n const state = stateOf(scalar);\n const document: ScalarFieldDocument =\n state.type === \"enum\"\n ? {\n type: \"enum\",\n enum: serializeEnum(scalar, state, enums, path, issues),\n }\n : state.type === \"decimal\"\n ? {\n type: \"decimal\",\n precision: state.decimal.precision,\n scale: state.decimal.scale,\n }\n : { type: state.type };\n const native = scalar[\"~\"].nativeType;\n if (native !== undefined) {\n // The catalog owns `native.type` at the parse boundary, where the document\n // is untrusted. Emitting a value that gate would refuse would write a\n // document this parser cannot read back — a round trip that loses a schema —\n // so the same rule refuses it here, by name. A MAP was held to the catalog\n // when its scalar was built, so it is restated as it was declared, in its\n // own form (never collapsed to the tagged one): every entry, in dialect\n // order, each copied so the document does not alias the scalar's state.\n if (document.type === \"point\") {\n refusePointState(path, \"native\", issues);\n } else if (document.type === \"decimal\") {\n addIssue(\n issues,\n pointer(path, \"native\"),\n \"J009\",\n \"Decimal cannot carry native type\"\n );\n } else if (!isTaggedNativeType(native)) {\n document.nativeByDialect = nativeTypeMapDocument(native);\n } else if (isNativeTypeInCatalog(native.db, native.type)) {\n // Copy `{ db, type }`: the document is the caller's to edit, and it must\n // not alias the scalar's own native object (mutating one would reach the\n // other's declaration state).\n document.native = { db: native.db, type: native.type };\n } else {\n addIssue(\n issues,\n pointer(path, \"native\", \"type\"),\n \"J011\",\n nativeTypeRefusal(native.db)\n );\n }\n }\n if (state.array) {\n if (document.type === \"point\") refusePointState(path, \"array\", issues);\n else document.array = true;\n }\n if (state.nullable) document.nullable = true;\n if (state.isId) {\n if (document.type === \"point\") refusePointState(path, \"id\", issues);\n else document.id = true;\n }\n // `.id()` implies uniqueness; only a standalone `.unique()` is a declaration.\n if (state.isUnique && !state.isId) {\n if (document.type === \"point\") refusePointState(path, \"unique\", issues);\n else document.unique = true;\n }\n // `withTimezone` starts `false` for every scalar and `true` for the two whose\n // factories set it, so the modifier's PRESENCE is what tells a declaration\n // apart from a state that never had the fact.\n if (\n state.withTimezone === false &&\n builderMethod(scalar, \"withoutTimezone\") !== undefined\n ) {\n document.withoutTimezone = true;\n }\n if (state.dimension !== undefined) {\n if (document.type === \"point\") {\n refusePointState(path, \"dimension\", issues);\n } else {\n document.dimension = state.dimension;\n }\n }\n if (state.columnName !== undefined) document.column = state.columnName;\n if (state.autoGenerate !== undefined) {\n if (document.type === \"point\") {\n refusePointState(path, \"generate\", issues);\n } else {\n writeGenerate(\n document,\n state.autoGenerate,\n state.isId || isGeneratorDefault(state.default)\n );\n }\n }\n if (state.schema !== undefined) {\n addIssue(\n issues,\n path,\n \"J009\",\n \"Custom `.schema()` cannot be serialized, use `attachFieldSchemas`\"\n );\n }\n const literal = serializeDefault(state, path, issues);\n if (literal !== undefined) document.default = literal;\n return document;\n}\n\nfunction nativeTypeMapDocument(map: NativeTypeMap): NativeTypeMap {\n const document: {\n pg?: DialectNativeType<\"pg\">;\n mysql?: DialectNativeType<\"mysql\">;\n sqlite?: DialectNativeType<\"sqlite\">;\n } = {};\n if (map.pg !== undefined) document.pg = { db: \"pg\", type: map.pg.type };\n if (map.mysql !== undefined) {\n document.mysql = { db: \"mysql\", type: map.mysql.type };\n }\n if (map.sqlite !== undefined) {\n document.sqlite = { db: \"sqlite\", type: map.sqlite.type };\n }\n return document;\n}\n\nfunction refusePointState(\n path: string,\n key: string,\n issues: DocumentIssues\n): void {\n addIssue(\n issues,\n pointer(path, key),\n \"J009\",\n `GeoPoint cannot carry '${key}'`\n );\n}\n\n/**\n * The two names an enum has.\n *\n * `enumName` is the only fact that decides ONE database enum type, so a named\n * enum becomes a shared `enums` definition and an anonymous one stays inline,\n * keeping its per-column derived type. But a database identifier is NOT a\n * document reference: `status-v2` is a perfectly good database type name and\n * not a schema identifier, and `__proto__` is a name a caller can pass and a\n * property every object already has. The REF addresses the definition inside\n * this document and follows the identifier grammar the parser enforces; `name`\n * carries the database's own spelling. Two different value sets under one\n * database name are two types with one name: a state the document cannot hold\n * and the migration serializer silently resolves in favour of whichever it met\n * first.\n */\nfunction serializeEnum(\n scalar: Scalar,\n state: ScalarState,\n enums: EnumRegistry,\n path: string,\n issues: DocumentIssues\n): string | string[] {\n const values = readEnumValues(scalar);\n const name = state.enumName;\n if (name === undefined) return values;\n const existing = enums.refs.get(name);\n if (existing !== undefined) {\n const definition = own(enums.definitions, existing);\n if (!sameValues(definition?.values, values)) {\n addIssue(\n issues,\n path,\n \"J009\",\n `Enum '${name}' has conflicting value sets`\n );\n }\n return existing;\n }\n const ref = claimRef(name, enums);\n enums.refs.set(name, ref);\n put(enums.definitions, ref, { values, name });\n return ref;\n}\n\n/**\n * The document key one database enum name gets.\n *\n * Its own spelling when that is already an identifier and nothing has claimed\n * it, which keeps the ordinary document readable; otherwise the first free\n * `enum_<n>`, numbered by DECLARATION ORDER so one schema always writes one\n * document. The taken-check runs for the identifier case too: a database name\n * of `enum_1` can arrive after a derived key has taken it.\n */\nfunction claimRef(name: string, enums: EnumRegistry): string {\n const taken = (candidate: string): boolean =>\n own(enums.definitions, candidate) !== undefined;\n if (isValidSchemaIdentifier(name) && !taken(name)) return name;\n let index = enums.refs.size + 1;\n while (taken(`enum_${index}`)) index += 1;\n return `enum_${index}`;\n}\n\n/**\n * Two value sets are the same ONLY element for element. A joined-string compare\n * would call `[\"a b\", \"c\"]` and `[\"a\", \"b c\"]` equal — both join to `\"a b c\"` —\n * and let the second silently inherit the first's values.\n */\nfunction sameValues(\n left: readonly string[] | undefined,\n right: readonly string[]\n): boolean {\n return (\n left !== undefined &&\n left.length === right.length &&\n left.every((value, index) => value === right[index])\n );\n}\n\n/**\n * An enum scalar's values live in its base schema and are published by the\n * class's own `enumValues` getter — the same read the migration serializer\n * makes. `state.type === \"enum\"` is the guarantee that the getter is there.\n */\nfunction readEnumValues(scalar: Scalar): string[] {\n const values: string[] = Reflect.get(scalar, \"enumValues\");\n return [...values];\n}\n\n/**\n * The literal a `.default(...)` holds, stated as JSON by the codec.\n *\n * `.nullable()` installs `default: null` as a side effect, so a null default on\n * a nullable field is the nullability being restated and never a declaration.\n * `.increment()` installs a generator with no value at all.\n */\nfunction serializeDefault(\n state: ScalarState,\n path: string,\n issues: DocumentIssues\n): JsonValue | undefined {\n if (!state.hasDefault) return;\n const value = state.default;\n if (value === undefined) return;\n if (value === null) return state.nullable ? undefined : null;\n if (isFunction(value)) return serializeFunctionDefault(state, path, issues);\n return encodeDefault(value, pointer(path, \"default\"), issues);\n}\n\n/**\n * A function default is either the generator's own closure — already stated by\n * `generate`, so it is omitted — or a caller's, which the document cannot hold.\n *\n * `autoGenerate !== undefined` does NOT decide which: a generator writes both\n * facts, and a later `.default(fn)` replaces only the closure, leaving the\n * generator declaration in place. Emitting `generate` on that state would\n * publish a field that produces random values where the original produced a\n * fixed one, so the closure's own IDENTITY decides, recorded by the modifiers\n * that installed it.\n */\nfunction serializeFunctionDefault(\n state: ScalarState,\n path: string,\n issues: DocumentIssues\n): undefined {\n if (state.autoGenerate !== undefined && isGeneratorDefault(state.default)) {\n return;\n }\n addIssue(\n issues,\n pointer(path, \"default\"),\n \"J009\",\n \"Function default cannot be serialized; use `generate`, a literal, or `native`\"\n );\n return;\n}\n\n// =============================================================================\n// RELATION\n// =============================================================================\n\nfunction serializeRelation(\n relation: AnyRelation,\n schema: Schema,\n path: string,\n issues: DocumentIssues\n): RelationFieldDocument {\n const state = stateOf(relation);\n const type = state.cardinality === \"one\" ? \"toOne\" : \"toMany\";\n const document = isVariantRelationState(state)\n ? withVariantTargetFacts(type, state, schema, path, issues)\n : withModelTargetFacts(\n {\n type,\n target: resolveTargetKey(state.target.getter, schema, path, issues),\n },\n state,\n schema,\n path,\n issues\n );\n if (state.name !== undefined) document.name = state.name;\n return document;\n}\n\nfunction withModelTargetFacts(\n document: ModelTargetDocument,\n state: RelationState,\n schema: Schema,\n path: string,\n issues: DocumentIssues\n): ModelTargetDocument {\n const foreignKey = state.foreignKey;\n if (foreignKey !== undefined) {\n document.fields = [...foreignKey.fields];\n document.references = [...foreignKey.references];\n if (foreignKey.onDelete !== undefined) {\n document.onDelete = foreignKey.onDelete;\n }\n if (foreignKey.onUpdate !== undefined) {\n document.onUpdate = foreignKey.onUpdate;\n }\n }\n const junction = state.junction;\n if (junction !== undefined) {\n const names: JunctionNamesDocument = {};\n if (junction.table !== undefined) names.table = junction.table;\n if (junction.model !== undefined)\n names.model = resolveTargetKey(junction.model, schema, path, issues);\n if (junction.source !== undefined) names.source = junction.source;\n if (junction.target !== undefined) names.target = junction.target;\n const onDelete = canonicalJunctionActions(junction.onDelete);\n const onUpdate = canonicalJunctionActions(junction.onUpdate);\n document.junction = {\n ...names,\n ...(typeof onDelete === \"string\"\n ? { onDelete }\n : onDelete && { onDeleteSides: onDelete }),\n ...(typeof onUpdate === \"string\"\n ? { onUpdate }\n : onUpdate && { onUpdateSides: onUpdate }),\n };\n }\n return document;\n}\n\n/**\n * One canonical spelling per action: equal sides are the symmetric shorthand,\n * so only a genuinely asymmetric pair spells its sides.\n */\nfunction canonicalJunctionActions(\n actions: JunctionSideActions | undefined\n): JunctionReferentialAction | JunctionSidesDocument | undefined {\n if (actions === undefined) return;\n return actions.source === actions.target ? actions.source : { ...actions };\n}\n\n/**\n * `values` is all-or-nothing: the factory demands a bag exact over the variant\n * keys, so a partial one is illegal. The document carries the full bag, or none\n * at all when every stored value already equals its public key.\n */\nfunction withVariantTargetFacts(\n type: \"toOne\" | \"toMany\",\n state: VariantRelationState,\n schema: Schema,\n path: string,\n issues: DocumentIssues\n): VariantTargetDocument {\n const variants: Record<string, string> = {};\n const values: Record<string, string> = {};\n const through: Record<string, VariantJunctionDocument> = {};\n let renamed = false;\n for (const [variantKey, entry] of Object.entries(state.target.entries)) {\n const member: VariantEntry = entry;\n variants[variantKey] = resolveTargetKey(\n member.getter,\n schema,\n pointer(path, \"variants\", variantKey),\n issues\n );\n values[variantKey] = member.storedValue;\n if (member.storedValue !== variantKey) renamed = true;\n const junction = readVariantJunction(member);\n if (junction !== undefined) through[variantKey] = junction;\n }\n const document: VariantTargetDocument = { type, variants };\n if (renamed) document.values = values;\n if (Object.keys(through).length > 0) document.through = through;\n if (state.optional === true) document.optional = true;\n return document;\n}\n\nfunction readVariantJunction(\n entry: VariantEntry\n): VariantJunctionDocument | undefined {\n const junction = Reflect.get(entry, \"junction\");\n if (junction === undefined) return;\n return {\n table: junction.table,\n source: junction.source,\n target: junction.target,\n };\n}\n\n/**\n * The schema key a target getter names.\n *\n * The getter is invoked DIRECTLY, not through `settleTarget`: settling is a\n * once-cell whose outcome every later consumer inherits, and a diagnostic dump\n * must not decide it. The answer is matched by identity against the caller's\n * own record, which is the same identity the resolution gate requires.\n */\nfunction resolveTargetKey(\n getter: Getter,\n schema: Schema,\n path: string,\n issues: DocumentIssues\n): string {\n return schemaKeyOf(readTarget(getter, path), schema, path, issues);\n}\n\n/**\n * The key under which `schema` holds `member`, by identity: the identity the\n * resolution gate requires.\n */\nfunction schemaKeyOf(\n member: unknown,\n schema: Schema,\n path: string,\n issues: DocumentIssues\n): string {\n for (const [modelKey, model] of Object.entries(schema)) {\n if (model === member) return modelKey;\n }\n addIssue(issues, path, \"J006\", \"Referenced model not in schema\");\n return \"\";\n}\n\nfunction readTarget(getter: Getter, path: string): unknown {\n try {\n return getter();\n } catch (thrown) {\n const issue: DocumentIssues = [];\n addIssue(issue, path, \"J006\", \"Relation target getter threw\");\n throw refuseDocument(issue, toError(thrown));\n }\n}\n\n/**\n * Restate a generator DECLARATION.\n *\n * The implicit ULID `.id()` installs is not a declaration of its own: `id:\n * true` already says everything the caller spelled, and emitting `generate`\n * for it would be read back as a NAMED `.ulid()` — a validated domain in a\n * compact column, which is a different field. The one thing `id: true` cannot\n * carry is the prefix of `.id(prefix)`, so that single case emits the node and\n * marks it `implicit` to keep it a key.\n */\nfunction writeGenerate(\n document: { generate?: GenerateDocument },\n autoGenerate: AutoGenerate,\n generated: boolean\n): void {\n const implicit = autoGenerate.implicit === true;\n const enabled = autoGenerate.generate ?? generated;\n if (implicit && autoGenerate.prefix === undefined && enabled) return;\n const generate: GenerateDocument = { kind: autoGenerate.kind };\n if (\n [\"uuid\", \"uuidv7\", \"ulid\", \"ksuid\", \"nanoid\", \"cuid\"].includes(\n autoGenerate.kind\n ) &&\n !enabled\n )\n generate.generate = false;\n if (autoGenerate.prefix !== undefined) generate.prefix = autoGenerate.prefix;\n if (autoGenerate.length !== undefined) generate.length = autoGenerate.length;\n if (implicit) generate.implicit = true;\n document.generate = generate;\n}\n","/**\n * JSON-defined schemas — `viborm/schema/json`.\n *\n * A document is read through the SAME public builders a human calls, so what\n * comes back is a real schema: `createClient`, `push` and the query engine\n * consume it unchanged and emit their existing diagnostics. There is no second\n * schema representation and nothing to keep in sync.\n *\n * ```ts\n * import { parseSchema, serializeSchema } from \"viborm/schema/json\";\n *\n * const schema = parseSchema(document); // JSON text OR a plain object\n * const db = createClient({ schema, driver }); // an UntypedClient\n * const back = serializeSchema(schema); // the reverse direction\n * ```\n *\n * The canonical form of a document IS `serializeSchema(parseSchema(doc))`:\n * running the pair once normalizes every builder coupling, so two documents can\n * be compared by comparing their canonical forms.\n *\n * Distinct from `viborm/validation`'s `json-schema`, which converts VALIDATION\n * schemas to Draft-07 / OpenAPI documents.\n */\n\nimport type { VibORMClient, VibORMConfig } from \"@client/client\";\nimport type { Schema } from \"@schema/hydration\";\nimport type { FieldSchemaMap } from \"./interpret\";\nimport { interpret } from \"./interpret\";\nimport { readDocument } from \"./read\";\nimport { serializeSchema } from \"./serialize\";\nimport type { ExactSchemaJsonOptions, SchemaJsonOptions } from \"./validate\";\nimport { readValidateOption, validateGraph } from \"./validate\";\n\n/** The schema container every client takes: model key → model. */\nexport type { Schema } from \"@schema/hydration\";\nexport type {\n CompoundKeyDocument,\n EnumDocument,\n FieldDocument,\n GenerateDocument,\n IndexDocument,\n JunctionDocument,\n ModelDocument,\n RelationFieldDocument,\n ScalarFieldDocument,\n SchemaDocument,\n VariantJunctionDocument,\n ViewDocument,\n} from \"./document\";\nexport { SCHEMA_DOCUMENT_VERSION } from \"./document\";\nexport type { FieldSchemaMap } from \"./interpret\";\nexport type { DocumentIssueCode } from \"./issues\";\nexport { serializeSchema } from \"./serialize\";\nexport type { ExactSchemaJsonOptions, SchemaJsonOptions } from \"./validate\";\n\n/**\n * Read a schema from a document, given as JSON text or a plain object.\n *\n * Every shape issue in the artifact is collected and thrown as ONE\n * `ValidationError` (V4002) whose issues carry JSON pointers into the document\n * and a `J0xx` code. Semantic refusals stay with the builders and arrive with\n * the pointer of the node that caused them.\n *\n * Each call produces a FRESH object graph. Models, scalars and relation\n * terminals are never reused across calls: write-once model naming and the\n * per-terminal target once-cell both punish a shared declaration.\n *\n * `{ validate: true }` additionally runs the schema validator — the same full\n * rule list `push` and the CLI run — over the schema that was built, AFTER\n * interpretation, so a document whose SHAPE is fine but whose GRAPH is not fails\n * here instead of at `createClient`. It reports in the validator's own\n * vocabulary: a `SchemaValidationError` carrying `M0xx`/`R0xx`/`P0xx` issues,\n * never a `J0xx` code, which describes the artifact and not the graph.\n *\n * Validating hydrates: the models are name-bound write-once under the keys the\n * DOCUMENT gave them, and relation targets settle. Both are idempotent for the\n * `createClient` that follows with this same schema record — it binds the same\n * keys to the same objects — so the only call this forecloses is one that would\n * have re-keyed a parsed schema before constructing a client.\n */\nexport function parseSchema<\n Options extends SchemaJsonOptions = SchemaJsonOptions,\n>(input: string | object, options?: ExactSchemaJsonOptions<Options>): Schema {\n const validate = readValidateOption(options);\n const schema = interpret(readDocument(input));\n if (validate) validateGraph(schema);\n return schema;\n}\n\n/**\n * Re-read a schema with Standard Schema validators attached per field, keyed\n * `\"<model>.<field>\"`.\n *\n * `.schema()` takes arbitrary code, so it has no document spelling. This is the\n * hybrid escape hatch: the schema is stated as a document and read again with\n * the validators applied by the one owner that can apply them LAST — after\n * `.nullable()` and `.array()` have finished rebuilding each base. The result\n * is a new graph, and anything the document cannot carry is refused by name\n * rather than dropped.\n */\nexport function attachFieldSchemas(\n schema: Schema,\n fieldSchemas: FieldSchemaMap\n): Schema {\n return interpret(readDocument(serializeSchema(schema)), fieldSchemas);\n}\n\n/**\n * The client a schema with non-literal model keys produces.\n *\n * Model names are not statically known. This alias preserves the operation\n * surface but cannot recover field argument or result types from runtime JSON.\n * It is not an assignable supertype of every concrete client and does not make\n * query arguments `any`. Keep a literal TypeScript schema for typed queries;\n * runtime schema validation still owns admission for loaded documents.\n */\nexport type UntypedClient = VibORMClient<VibORMConfig>;\n"],"mappings":"yuBA8CA,MAEM,GAAgB,KAChB,GAAgB,MAGtB,SAAgB,EAAQ,EAAgB,GAAG,EAAiC,CAC1E,IAAI,EAAO,EACX,IAAK,IAAM,KAAO,EAChB,GAAQ,IAAI,EAAI,QAAQ,GAAe,KAAK,CAAC,QAAQ,GAAe,KAAK,GAE3E,OAAO,EAeT,SAAgB,EACd,EACA,EACA,EACA,EACM,CACN,EAAO,KAAK,CAAE,OAAM,QAAS,IAAI,EAAK,IAAI,IAAW,CAAC,CAOxD,SAAgB,EACd,EACA,EACiB,CACjB,OAAO,IAAI,EACT,CAAE,KAAM,iBAAkB,QAAS,cAAe,KAAM,GAAe,CACvE,EACA,IAAU,IAAA,GAAY,IAAA,GAAY,CAAE,QAAO,CAC5C,CAIH,SAAgB,EAAe,EAA8B,CAC3D,GAAI,EAAO,OAAS,EAClB,MAAM,EAAe,EAAO,CAuBhC,SAAgB,EACd,EACA,EACA,EACA,EACS,CACT,OAAO,GAAa,EAAQ,EAAK,EAAM,EAAQ,OAAO,CAoBxD,SAAgB,GACd,EACA,EACA,EACA,EACA,EACS,CACT,GAAI,CACF,OAAO,QAAQ,IAAI,EAAQ,EAAI,OACxB,EAAQ,CAEf,MADA,EA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AAQ,OAAO,EAG/B,OADA,EAAS,EAAQ,EAAM,OAAQ,iCAAiC,CACzD,GAGT,SAAS,GAAW,EAAgB,EAAuB,CACzD,GAAI,CACF,OAAO,GAAQ,OACR,EAAQ,CACf,IAAM,EAAwB,EAAE,CAEhC,MADA,EAAS,EAAO,EAAM,OAAQ,+BAA+B,CACvD,EAAe,EAAO,EAAQ,EAAO,CAAC,EAchD,SAAS,GACP,EACA,EACA,EACM,CACN,IAAM,EAAW,EAAa,WAAa,GACrC,EAAU,EAAa,UAAY,EACzC,GAAI,GAAY,EAAa,SAAW,IAAA,IAAa,EAAS,OAC9D,IAAM,EAA6B,CAAE,KAAM,EAAa,KAAM,CAE5D,CAAC,OAAQ,SAAU,OAAQ,QAAS,SAAU,OAAO,CAAC,SACpD,EAAa,KACd,EACD,CAAC,IAED,EAAS,SAAW,IAClB,EAAa,SAAW,IAAA,KAAW,EAAS,OAAS,EAAa,QAClE,EAAa,SAAW,IAAA,KAAW,EAAS,OAAS,EAAa,QAClE,IAAU,EAAS,SAAW,IAClC,EAAS,SAAW,ECjtBtB,SAAgB,GAEd,EAAwB,EAAmD,CAC3E,IAAM,EAAW,GAAmBC,EAAQ,CACtC,EAAS,GAAU,GAAa,EAAM,CAAC,CAE7C,OADI,GAAU,GAAc,EAAO,CAC5B,EAcT,SAAgB,GACd,EACA,EACQ,CACR,OAAO,GAAU,GAAa,GAAgB,EAAO,CAAC,CAAE,EAAa"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"json-number-
|
|
1
|
+
{"version":3,"file":"json-number-C09rsm1g.mjs","names":[],"sources":["../src/adapters/databases/sqlite/storage/json-number.ts"],"sourcesContent":["/** SQLite printf spelling that round-trips every finite binary64 coordinate. */\nexport const SQLITE_BINARY64_FORMAT = \"%!.17g\";\nexport function sqliteBinary64JsonNumber(expression: string): string {\n return `json(printf('${SQLITE_BINARY64_FORMAT}', ${expression}))`;\n}\n"],"mappings":"AACA,MAAa,EAAyB,SACtC,SAAgB,EAAyB,EAA4B,CACnE,MAAO,gBAAgB,EAAuB,KAAK,EAAW"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"json-parameter-
|
|
1
|
+
{"version":3,"file":"json-parameter-D7hDrVKw.mjs","names":[],"sources":["../src/sql/json-parameter.ts"],"sourcesContent":["/**\n * One JSON document, bound as one statement parameter.\n *\n * PostgreSQL's JSON literals bind CANONICAL JSON TEXT and let the server cast\n * that text from the parameter's column context. Nothing at the driver can\n * tell that text apart from an ordinary string, so every transport that\n * re-serializes a `json`/`jsonb` parameter has to be told not to, and only some\n * of them offer a place to say it: postgres.js takes a `json` type override\n * (`src/drivers/postgres/index.ts`), PGlite's own JSON serializer already\n * passes strings through, and node-postgres/Neon never touch a string. Bun SQL\n * offers no such hook and JSON-ENCODES a string bound to a `json`/`jsonb`\n * parameter, storing the physical document `\"[1,2,3]\"` — a JSON string — where\n * `[1,2,3]` was meant (upstream Drizzle #5287).\n *\n * This carrier is the missing distinction, and it needs no per-transport hook:\n * a PostgreSQL transport can only reach a bound value through string coercion\n * or through JSON serialization, and this renders as its canonical text under\n * BOTH. The text captured at construction is the ONE stored fact: `toJSON`\n * answers it parsed back, and `JSON.stringify` of its own output re-serializes\n * to those exact bytes, so both protocols agree even if the caller mutates the\n * original value after binding.\n * Bun, which serializes an object parameter for a `json`/`jsonb` column with\n * `JSON.stringify`, therefore stores the exact document for every JSON type,\n * including the number, boolean and null primitives that no bare JavaScript\n * value can express to it (a JS number is bound as `integer`, `null` as SQL\n * NULL).\n *\n * `json` is an own property rather than a private field because it is what a\n * parameter snapshot shows: diagnostics read own properties, so an opted-in\n * `includeParams` disclosure keeps the document instead of reporting `{}`.\n */\nexport class JsonParameter {\n /** The canonical JSON text — `JSON.stringify(value)`. */\n readonly json: string;\n\n private constructor(json: string) {\n this.json = json;\n Object.freeze(this);\n }\n\n /**\n * The carrier for `value`, or `undefined` when `JSON.stringify` has no text\n * for it (`undefined`, a function, a symbol). Those bound `undefined`\n * directly before this carrier existed, which providers send as SQL NULL;\n * carrying them would bind the text `\"undefined\"` instead.\n */\n static from(value: unknown): JsonParameter | undefined {\n // The lib signature says `string`, which is only true for the values it can\n // represent.\n const json: string | undefined = JSON.stringify(value);\n return json === undefined ? undefined : new JsonParameter(json);\n }\n\n toString(): string {\n return this.json;\n }\n\n toJSON(): unknown {\n return JSON.parse(this.json);\n }\n}\n"],"mappings":"AA+BA,IAAa,EAAb,MAAa,CAAc,CAEzB,KAEA,YAAoB,EAAc,CAChC,KAAK,KAAO,EACZ,OAAO,OAAO,KAAK,CASrB,OAAO,KAAK,EAA2C,CAGrD,IAAM,EAA2B,KAAK,UAAU,EAAM,CACtD,OAAO,IAAS,IAAA,GAAY,IAAA,GAAY,IAAI,EAAc,EAAK,CAGjE,UAAmB,CACjB,OAAO,KAAK,KAGd,QAAkB,CAChB,OAAO,KAAK,MAAM,KAAK,KAAK"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{m as e,o as t,r as n,t as r}from"./validation-ATmgN5RE.mjs";import{o as i,t as a}from"./sql-tegqTqGq.mjs";import{i as o,r as s}from"./extension-Dh1ddrlA.mjs";import{c}from"./datetime-physical-codec-DAF7WJpy.mjs";import{d as l,tt as u}from"./model-Dtd37Sky.mjs";import{C as d,it as f}from"./native-types-1ewJXVks.mjs";import{i as p}from"./keys-DZdKAd4n.mjs";import{D as m,i as h,o as g,s as _,v,y}from"./schema-DDkAUfOb.mjs";import{A as b,D as ee,E as x,H as te,O as ne,U as re,a as ie,c as S,k as ae,n as oe,r as se,st as ce,ut as le,z as ue}from"./query-BTb6iakn.mjs";import{i as de}from"./validation-BHjx13zG.mjs";import{_ as fe,b as C,f as pe,g as me,h as w,l as he,m as T,n as E,t as D,v as ge,y as _e}from"./rule-words-DMbQuvD2.mjs";import{I as O}from"./standard-sql-Bl2OHGfi.mjs";const k=Object.freeze({}),A=e=>e!==void 0;function j(e,t){let{update:n=k,delete:r=k}=e;return t.kind===`delete`?[r]:t.writes.length===0?[n]:[...new Set([...t.writes.map(t=>e.writes?.get(t)??n),...t.a3?[r]:[]])]}var M=class extends ge{lw(e,t){return super.lw(e,t)||this.rows.rules?.get(t[`~`].names.ts)!==void 0}},ve=class extends M{key(e,t,n){let r=this.rows.rules?.get(e)&&n;return r?`${e} ${t} ${r.kind}${r.a3?`+`:``} ${[...r.writes].sort()}`:super.key(e,t)}i0(e,t,n,r){let i=this.rows.rules?.get(e);if(i===void 0)return super.i0(e,t,n);let a=[],o=Math.max(t?.length??0,i.length);for(let e=0;e<o;e++){if(n.includes(e))continue;let o=i[e];a.push([e,[o?.read,t?.[e],...o&&r?j(o,r):[]].filter(A)])}return a}};const ye=C(M),N=C(ve),be=[`read`,`shown`,`update`,`delete`,`place`,`check`],xe=[`writes`,`moves`,`reads`,`facts`];function Se({schema:e,refuse:t},n,r){let i=e[n],{relations:a}=i[`~`].state,o=Object.keys(a).filter(e=>{let t=a[e][`~`];return t.state.foreignKey!==void 0&&t.settleTarget()===i}),s=e=>{if(!Array.isArray(e))return t(n,`${n}.acyclic`,`lists relations, or is a function returning them`);for(let r of e)o.includes(r)||t(n,`${n}.acyclic.${r}`,`names no to-one relation of the model to itself holding its key`);return e},c,l=()=>c??=s(typeof r==`function`?r():r);return typeof r!=`function`&&l(),{candidates:o,resolve:l}}function P(e,t,n,r,i){let a=(n,a)=>e.oz(t,`${t}.${n}`,a,r,i),o={pl:n.pl,as:n.as};n.acyclic!==void 0&&(o.cycles=Se(e,t,n.acyclic));for(let e of be)n[e]!==void 0&&(o[e]=a(e,n[e]));for(let e of xe){let t=n[e],r=e===`facts`?`read.select`:e;t!==void 0&&(o[e]=new Map([...t].map(([e,t])=>[e,a(`${r}.${e}`,t)])))}return o}function Ce(e){let t=e.rules,n={};for(let e of t)Object.assign(n,e.yp);let{pl:r,se:i,prepare:a=ye,keys:o,lazy:s}=n,c=e=>t.some(t=>Object.hasOwn(t.rules,e)),l=new Map,u=n=>c(n)?h(l,n,()=>{let r=t.map(({rules:t,extension:r})=>{let i=t[n];return typeof i==`function`?i(e,r):i});return o?.(n,r),r}):void 0;for(let e of t)for(let n of Object.keys(e.rules))t.every(e=>typeof e.rules[n]!=`function`)&&u(n);return{rules:{has:c,get:u},pl:r,se:i,...s&&{lazy:s,filters:(e,t)=>u(e)?.[t]?.filters},prepare:a}}const F={oz:(e,t,n,r)=>Object.fromEntries(Object.entries(t.rules).map(([t,i])=>[t,typeof i==`function`?i(e,n):P(e,t,i,r)])),bind:Ce};function I(e){let t=e.entry();return e.layer.host??=F,t}const we={refused:`JSON_EXTRACT('{}', '__viborm_refused__')`,jc:(e,t,n,r)=>L(e,t,i.join(n.map(e=>i`SELECT ${i.join(e,`, `)}`),` UNION ALL `),r)},Te={refused:`CAST((SELECT '__viborm_refused__') AS integer)`,jc:(e,t,n,r)=>{let{escape:a}=e.identifiers,o=a(t.alias),[s,...c]=n,l=s.map((e,n)=>i`COALESCE(${e}, (${o}."row").${a(t.columns[n])})`);return i`(SELECT NULL::${t.table} AS "row") AS ${o} CROSS JOIN LATERAL (VALUES ${i.join([l,...c].map(O),`, `)}) AS ${a(r)}(${i.join(t.columns.map(a),`, `)})`}},Ee={refused:`json_extract('{}', '__viborm_refused__')`,jc:(e,t,n,r)=>L(e,t,i`VALUES ${i.join(n.map(O),`, `)}`,r)},L=(e,t,n,r)=>i`(${t.head} UNION ALL ${n}) AS ${e.identifiers.escape(r)}`,R={postgresql:Te,sqlite:Ee,mysql:we},De=(e,t,n,r)=>i`SELECT CASE WHEN ${n} THEN 1 ELSE ${i.raw(t.refused)} END AS ${e.identifiers.escape(`__viborm_judged__`)}${r?i` FROM ${r}`:i``}`;function z(e,t,n,r=0){switch(e.kind){case`and`:case`or`:return e.predicates.some(e=>z(e,t,n,r));case`not`:case`layer`:return z(e.predicate,t,n,r);case`always`:case`condition`:return!1;case`relation`:case`exists`:return e.kind===`relation`&&r===0&&(e.edge.kind===`reference`?_(e.edge):n).some(e=>t.has(e))||e.predicate!==void 0&&z(e.predicate,t,n,r+1);case`operation`:{let n=[e.aw,...e.operands??[]],i=e=>e?.kind===`field`&&(r===0||e.up===r)&&t.has(e.scalar.field);return r>0?n.some(i):e.target.kind!==`column`||t.has(e.target.scalar.field)||n.some(e=>i(e)||e?.kind===`sql`&&e.operands.some(e=>e.kind===`field`&&t.has(e.scalar.field)))}default:return!0}}function B(e,t,n,r,a){let o=e.adapter,s=e.schema.rh(n),l=e.alias(),u=e.table(n,l),d=c(o,{columns:i.join(s.map(t=>e.column(n,t,l)),`, `),from:u,where:o.literals.false()});return t.jc(o,{head:d,from:u,table:e.table(n),alias:l,columns:s.map(t=>e.columnName(n,t))},r.map(e=>s.map(t=>e(t)??o.literals.null())),a)}function Oe(e,t,n,r){let a=e.adapter,{cte:o,t0:s,walk:l,vc:u}=e.walk(e.schema.membership(t,n),r,{depth:!1,self:!1},!1);return a.filters.none(i`${o} ${c(a,{columns:i.raw(`1`),from:a.identifiers.aliased(a.identifiers.escape(s),l),where:e.u5(t,r,u.map(e=>a.identifiers.column(l,e)))})}`)}const ke=(e,t)=>fe(e,e=>e.kind===`operation`&&e.operator===`equals`&&e.target.kind===`column`&&e.target.path===void 0&&e.aw?.kind===`value`&&e.aw.value===null&&e.target.scalar.ed.scalar[`~`].state.type!==`json`?t.get(e.target.scalar.field):void 0,!1);function V(e,t,n,r,i,a,o,s,l=S){let u=e.adapter;return e.n3(()=>{let d=e.known;e.known={alias:i,nulls:a,fold:ke};let f;try{f=r&&e.iw(r,i)}finally{e.known=d}let p=[...f===void 0?[]:[f],...l.map(t=>Oe(e,n,t,i))];return p.length===0?void 0:c(u,o(u.subqueries.scalar(De(u,t,u.operators.and(...p),s))))})}function Ae(e,t,n,r,o,s){let c=e.alias(),l=new Set(r),u=B(e,t,n,o.map(t=>r=>l.has(r)?e.vp(n,r,t[r]):void 0),c),d=new Map;for(let t of e.schema.rh(n)){let e=new Set(o.map(e=>{let n=l.has(t)?e[t]:null;return n instanceof a?void 0:n==null})),[n]=e;e.size===1&&n!==void 0&&d.set(t,n)}return V(e,t,n,s,c,d,t=>({columns:i.join(r.map(t=>e.column(n,t,c)),`, `),from:u,where:i`${t} = 1`}))}function je(e,t,n,r,o,s,c=S,l){if(s===void 0&&c.length===0)return;let u=e.adapter,d=e.alias(),f=e.alias(),p=t=>e.column(n,t,d),m=e.schema.keys(n),h=t=>!(e.jb(n,t,o[t])||s?.predicate&&z(s.predicate,new Set([t]),m)||c.some(r=>{let i=e.schema.membership(n,r);return i.kind===`reference`&&i.pairs.some(e=>e.source===t)})),g=B(e,t,n,[t=>o[t]===void 0||h(t)?p(t):e.bl(n,t,o[t],p(t))],f),_=new Map;for(let[e,t]of Object.entries(o)){let n=re(t);n&&!(n.value instanceof a)&&_.set(e,n.value===null)}let v=e.ej(n).map(p),y=V(e,t,n,s,f,_,t=>({columns:i.join(v,`, `),from:e.table(n,d),where:r(d),groupBy:i.join(v,`, `),having:i`${u.aggregates.min(t)} = 1`,...l!==void 0&&{orderBy:e.bc(n,d),limit:e.value(l)}}),g,c);if(y===void 0)return;let b=n[`~`].names.sql;return u.operators.in(ue(e.ej(n).map(t=>e.column(n,t,b))),u.subqueries.scalar(u.capabilities.supportsMutationTargetInSubquery?y:te(u,y,e.alias())))}const H=e=>{let n=new Map,r=t=>e.rows.rules?.get(t[`~`].names.ts),i={f3(e,t){let n=i.bz(t);return(n&&e.iw(n)?.values.length)??0},l5(e,t,n,r,a,o){let s=i.bz(n);if(s===void 0)return;r.length===0&&m(`Cannot create a '${y(n)}' row that writes no field: its placement is judged on the values it writes.`);let c=Ae(e,R[t.driver.dialect],n,r,a,s);return c&&{mv:c,pm:i.refusal(t.operation,n,void 0,`create`,o)}},updated(e,t,n,r,a,o,s){let{model:c}=n,l=je(e,R[t.driver.dialect],c,r,a,i.bz(c,o,Object.keys(a)),i.cycles(c,o),s);return l&&{where:l,pm:i.refusal(t.operation,c,o,n.gf,(n.member?.edge??n.through)?.name)}},refusal(e,t,n,i,a){if(i&&a)return{kind:`nestedWrite`,relation:a,message:`Cannot ${i} relation '${a}': the record it writes is not permitted.`,lg:!1};let o=r(t),s=n?.writes.filter(e=>o?.some(t=>t?.moves?.has(e)))??[];return{kind:`forbidden`,message:`${e} produced a row that is not permitted.`,lg:!1,...s.length>0&&{reason:`it writes ${s.join(`, `)}`}}},xe(e){return r(e)?.some(e=>{let t=e?.update,n=t?.OR;return Array.isArray(n)&&n.length===0&&Object.keys(t).length===1})?n=>new t(e[`~`].names.ts,`update`,{reason:`the row this upsert locates exists`,cause:n}):void 0},bz(t,i,a){let o=r(t);if(i?.kind===`delete`||o===void 0)return;let s=a&&new Set(a),c=e.queries.schema.keys(t);return h(n,i?`update ${t[`~`].names.ts} ${[...i.writes].sort()} ${a?[...a].sort():`*`}`:`create ${t[`~`].names.ts}`,()=>{let n=[];for(let[r,a]of o.entries()){if(a?.pl===void 0)continue;let o=i?[a.read??k,...j(a,i),a.check].filter(A):[],l=s!==void 0&&o.every(n=>{let{predicate:r}=e.prepare(t,n);return r===void 0||!z(r,s,c)}),u=i?[...l?[]:o,...i.writes.map(e=>a.moves?.get(e))]:[a.place];n.push([r,[...new Set(u.filter(A))]])}return e.conjunction(t,n)})??void 0},cycles(t,n){let i=r(t);if(n.kind===`delete`||i===void 0)return S;let a=new Set,o=r=>{let i=e.queries.schema.membership(t,r);return n.writes.includes(r)||i.kind===`reference`&&i.pairs.some(e=>n.writes.includes(e.source))};for(let e of i){let t=e?.cycles;if(t?.candidates.some(o))for(let e of t.resolve())o(e)&&a.add(e)}return a.size===0?S:[...a]}};return i};function Me(e){return Object.values(e).every(e=>{let t=e[`~`].state;return Object.values(t.scalars).every(e=>e[`~`].state.schema===void 0)})}const Ne=e=>e.length<2?e[0]:{AND:e};function Pe(e,t,r,i){let a=i??de(t),o=(e,t,i)=>{throw new n(`Extension "${r}" rule.${t}: ${i}.`,{meta:{extension:r,model:e}})},s=new Map,c=(e,n,r,i,c=``)=>{let d=a.getModelSchemas(t[e]).core.where,p={references:i,schema:t,registry:a},m=u({value:e=>e instanceof E?e.value?.(p):void 0,filter:e=>e instanceof E?e.filter?.(p):void 0},()=>f(d,r),h(s,c,()=>new WeakMap));if(l.reads??=p.reads,!m.issues)return m.value;let[g]=m.issues;return o(e,n,`at "${g.path?.map(String).join(`.`)||`root`}": ${g.message}`)},l={schema:t,oz:c,refuse:o},d=new Set,p={},m=(e,t,n,r)=>{let i={};for(let a of[`root`,`related`]){let o=Ne(t[a]??[]);o!==void 0&&(i[a]=c(e,`${e}.${a}`,o,n,r))}return i};for(let t of new Set([...Object.keys(e.root),...Object.keys(e.related)]))p[t]=m(t,{root:e.root[t],related:e.related[t]},d,``);let{host:g}=e,_=g?.oz(l,e,m,d)??{},v=e.confine?e.yp.n7.oz(l,e.confine,d):void 0,y=e.reads??l.reads;return{extension:r,models:p,rules:_,...g&&{host:g},...y&&{reads:y},...e.yp&&{yp:e.yp},...v&&{confine:v},references:[...d]}}function U(e,t,n){let r=new Map;return{get:i=>h(r,i,()=>{let r=null;for(let[a,o]of e.entries()){let e=(o.models[i]??n?.(i,a))?.[t];e!==void 0&&((r??=[])[a]=e)}return r})??void 0}}function W(e){let t=e.rules,{lazy:n=!1,filters:r,prepare:i=_e,...a}=(t.find(e=>e.host)?.host)?.bind(e)??{},{kept:o,fl:s,iy:c}=e,l={root:U(t,`root`,r),related:U(t,`related`,r),...a,...t.find(e=>e.confine)?.yp?.n7?.bind(t),...c&&{order:new Map(Object.entries(c))}},u=t.find(e=>e.reads)?.reads?.bind(e,n,l);u&&(l=u.domain);let d={domain:l,...s&&{fl:s.all},prepare:i},f=o===void 0?d:{...d,gm:o};return{call(e,t){let n=o?.u2(e,t)===!0?d:f;return s?.named===!0&&(n={...n,fl:s.of(t)}),u?.call(n,t)??n}}}function Fe(e){let t,n;return{join(r){let{name:i,next:a,schema:o,registry:s}=r,c=n??Pe(e,o,i,s);(t??=Me(o))&&(n=c),w(r,c.references),a.rules=[...a.rules??[],c],a.n6=W},seal(e){T(e,W)}}}var Ie=class extends Map{u2(e,t){let n=this.get(e);return n?.test!==void 0&&n.test.holds({args:t??{}})!==n.keeps}a3(e,t){let{scope:n,schema:r}=e.operation,i=this.get(t[`~`].names.ts);if(i)return e.values(t,`update`,r.update(t,i.at===void 0?i.assign:{...i.assign,[i.at]:n.instant()}),{})}referenced(e,t,n){let r=t&&e.dk(t.target).find(n=>e.index.get(t.target)?.get(n)?.edge===t.scope.edge&&!(t.target===t.source&&n===t.name));return r?{slot:r,identity:n}:!0}r9(e,t){let n=e.dk(t);return n.length>0?{kind:`foreignKey`,message:`Cannot delete '${t[`~`].names.ts}' record: a related record still references it through one of its relations whose foreign key restricts deletes: ${n.map(e=>`'${e}'`).join(`, `)}.`,lg:!1}:void 0}lock(e,t){let n=e,r=n.adapter,i=n.dz(),a=c(r,{columns:r.literals.true(),from:n.table(t.model,i),where:n.iw(t,i),sb:!0});return{sql:c(r,{columns:r.identifiers.aliased(r.aggregates.count(),`_count`),from:r.subqueries.correlate(a,n.alias())}),shape:{kind:`object`,fields:{_count:se}}}}selector(e,t,n,r){let i=e.schema.dk(t).map(i=>{let a=g(e.schema,t,i),o=[],s=n?.selector(a.target,`related`)?.predicate;return s&&o.push(s),r?.slot===i&&o.push(e.vd(`NOT`,[e.gy(a.target,r.identity,x(!1))])),{kind:`relation`,edge:a,sm:`some`,predicate:o.length===0?void 0:e.vd(`AND`,o),xg:!0}});return{model:t,facts:x(!1),predicate:e.vd(`OR`,i)}}};function Le(e,t){for(let[n,r]of Object.entries(e))for(let[e,i]of Object.entries(r[`~`].state.relations)){let r=i[`~`];if(r.state.junction?.model!==void 0&&r.settleJunctionModel()===t)return`${n}.${e}`}}function Re(e,t){return{join(n){let{next:r,schema:i,name:a}=n;w(n,[t.test?.parameter.arg]);let o=Le(i,i[e]);o!==void 0&&s(`Extension "${a}" rule.${e}.delete.instead: the model is the junction of '${o}', so a kept link would still be followed. Delete the link with the relation's disconnect, or the row through its delegate.`,a);let c=new Ie(r.kept);c.set(e,{extension:a,...t}),r.kept=c,r.n6=W},seal(e){T(e,W)}}}const G=new WeakMap,K=`is not readable on a returned row`;var ze=class extends Error{path;constructor(e){super(`The selected field at '${e}' ${K}`),this.path=e}refusal(e,t){return new r(e,[{path:this.path,message:K}],{meta:{model:t}})}};function Be(e,t,n,r,i,a,o=!1){let s=e.wg(oe,!1,t),c=n.gates,l=r.map(e=>n.gated[e]),u=l.map(e=>e===void 0?-1:c.indexOf(e.gate)),d=a&&[...r.map(e=>a.lastIndexOf(e)),...c.map(e=>a.lastIndexOf(e))],f=(e,t,n)=>o?Object.hasOwn(e,t)?e[t]:void 0:d===void 0?ee(e,n):e[d[t]];return e=>{let t=e;if(!d){if(t=o?b(e,r.length+c.length):ne(ae(e)),t===null)return null;if(t===void 0)throw new ie(`row`,`a requested document is not a provider row`)}let n=c.map((e,n)=>s(f(t,r.length+n,e))),a={};for(let e=0;e<r.length;e++){let o=r[e],s=u[e];if(s>=0&&n[s]!==!0){let t=l[e].refused;if(t!==void 0)throw new ze(t);continue}a[o]=i[e](f(t,e,o))}return a}}const Ve=new Set([`count`,`exist`,`aggregate`,`groupBy`]),He=e=>t=>typeof t==`boolean`?{value:t||void 0}:Array.isArray(t)&&t.length>0&&t.every(t=>e.some(([e])=>e===t))?{value:[...t]}:{issues:[{message:`expected true, false or a list of ${e.map(([e])=>e).join(`, `)}`}]};function q(e,t,n,r,i){if(!(l(r)&&l(i)))return;let a=l(r.select)?r.select:void 0,o=l(r.omit)?r.omit:void 0,s=new Set;for(let t of e.projected(n)?.gates.keys()??[])(a?a[t]===!0&&o?.[t]!==!0:o?.[t]===!1)&&s.add(t);s.size>0&&l(i.select)&&G.set(i.select,s);for(let a of[`select`,`include`]){let o=r[a],s=i[a];if(l(o)&&l(s))for(let r of Object.keys(o)){let i=n[`~`].state.relations[r]?t.index.get(n)?.get(r):void 0;if(i===void 0)continue;let a=i.edge.kind===`variantJunctionCarrier`,c=i.member||!(a||i.edge.kind===`variantRowCarrier`)?[void 0]:i.edge.members.map(({variant:e})=>e),u=(e,t)=>{if(t===void 0)return e;let n=l(e)&&a?e.variants:e;return l(n)?n[t]:void 0};for(let i of c)q(e,t,t.membership(n,r,i).target,u(o[r],i),u(s[r],i))}}}function Ue(e,t,n,r){let i=()=>e.oz(t,n,r);if(this.projected(t),Ve.has(n))return i();let a=d((t,n)=>{let r=t[0]===`$`?e.schema[t.slice(1)]:void 0,i=r&&this.projected(r)?.keys.get(n);return i&&He(i.names)},i);return q(this,e,t,r,a),a}function J(e,t){let r=new Set;for(let i of t){let t=i?.as;if(t!==void 0){if(t===`$through`||r.has(t))throw new n(`rule.${e}.read.select "${t}" ${t===`$through`?`is reserved for a relation's link row`:`is declared by two extensions of the chain`}.`,{meta:{model:e}});r.add(t)}}}const We=t=>{let n=new Map,r=new Map,i=new WeakMap,a=(e,t,n,r,i)=>e.iw(l.kz(t,n,r),i),o=e=>l.projected(e)?.gates;function s(e,t,n,r,i){let o=[];e.unbounded++;try{for(let[s,c,l]of n){let n=l===c?[c]:[c,l];for(let c of i?n.slice(1):n){let n=a(e,t,s,c,r);n!==void 0&&o.push(n)}}}finally{e.unbounded--}return o.length===0?void 0:e.adapter.operators.and(...o)}let l={lower(e,t,n,r,i){if(n.kind===`gate`)return e.p8(s(e,t,n.gate,r,i));let o=e.adapter,{layer:c,read:l}=n.evidence,u=i?void 0:a(e,t,c,l,r),d=e.vj(n.names.map(([n,i])=>[n,e.p8(i===l?void 0:a(e,t,c,i,r))]));return u===void 0?d:o.expressions.caseWhen([{when:u,then:d}],e.vj(n.names.map(([e])=>[e,o.literals.false()])))},window(e,t,n){if(!o(t)?.size)return;let r=e.adapter,i=e.alias();return c(r,{columns:v(e.schema.rh(t).map(n=>r.identifiers.aliased(l.t2(e,t,n,e.column(t,n,i),i),e.columnName(t,n)))),from:e.table(t,i),where:e.gs(t,n,i)})},zb:Be,t2(e,t,n,r,i){let a=o(t)?.get(n),c=a&&s(e,t,a,i,!0),l=e.adapter;return c===void 0?r:l.expressions.caseWhen([{when:c,then:r}],l.literals.null())},oz:Ue,jq(t,n,r,i){let a=o(n),s=a&&r.find(e=>a.has(e)),c=n[`~`].names.ts;if(s!==void 0)throw new e(`Cannot ${i} $through.${s} of relation '${t.name}': this client gates that field of '${c}'. Read it through the '${c}' delegate.`)},jz(t){let n=o(t);if(n?.size)throw new e(`${t[`~`].names.ts}.$rows() refuses read-gated fields: ${[...n.keys()]}`)},kz(e,n,i){let a=e[`~`].names.ts;return h(h(r,`${a} ${n}`,()=>new Map),i,()=>t.conjunction(e,[[n,[i]]]))},projected(e){let r=e[`~`].names.ts;return h(n,r,()=>{let e=new Map,n=new Map;for(let[i,a]of(t.rows.rules?.get(r)??[]).entries()){if(a===void 0)continue;let{as:t,facts:r}=a,o=a.shown??a.read??k;t!==void 0&&e.set(t,{layer:i,read:o,names:Object.entries(Object.fromEntries(r))});for(let[e,t]of a.reads??[])n.set(e,[...n.get(e)??[],[i,o,t]])}let i=[];for(let[e,t]of n){let r=i.find(e=>e.length===t.length&&e.every(([e,,n],r)=>e===t[r][0]&&n===t[r][2]));r===void 0&&i.push(t),n.set(e,r??t)}return e.size===0&&n.size===0?null:{keys:e,gates:n}})??void 0},o3(e,t,n){let r=l.projected(e);if(r===void 0)return;let a=G.get(t),o={},s=new Map;return{defaults:i,key:(e,t,n,i)=>{let a=r.keys.get(e);if(a===void 0)return!1;let o=t===!0?a.names:a.names.filter(([e])=>t.includes(e));return n[e]={kind:`object`,nullable:!1,fields:Object.fromEntries(o.map(([e])=>[e,oe]))},i.push({kind:`evidence`,name:e,evidence:a,names:o}),!0},field(e,t){let i=r.gates.get(e);if(i===void 0)return;let c=s.get(i);c===void 0&&(c=ce(s.size),s.set(i,c),t.push({kind:`gate`,name:c,gate:i})),o[e]=a?.has(e)?{gate:c,refused:`${n}select.${e}`}:{gate:c}},shape:()=>s.size>0?{gated:o,gates:[...s.values()]}:void 0}}};return l},Ge=new Set([`read`,`root`,`related`,`create`,`update`,`delete`,`acyclic`,`confine`]),Y=e=>l(e)?e:{},X=e=>e===void 0?[]:Array.isArray(e)?[...e]:[e];function Ke(e,t,n,{layer:r,wh:i},a,o){let s,c=Y(Y(e).read),u=(e,d,f,p=!1)=>{if(e===void 0)return;if(e instanceof D){e.join({model:t,key:d,field:f,schema:n,layer:r,wh:i,lazy:o,...!o&&{a5:c.where},entry:()=>s??={},refuse:a});return}p&&l(e)||a(p?`${d} is an object`:`${d} is written ${d.endsWith(`where`)?`only(where)`:`with a word`}`);let m=d.endsWith(`fields`)||d.endsWith(`select`);for(let[t,n]of Object.entries(e))u(n,`${d}.${t}`,m?t:f,d===`update.fields`||t===`fields`)};if(e instanceof D){u(e,`the entry`);return}if(!l(e))return a(typeof e==`function`?`an entry given as a function is written lazy(() => entry)`:`an entry is an object`);for(let t of Object.keys(e))Ge.has(t)||a(`"${t}" is not a rule key`);o&&c.where!==void 0&&((s??={}).read=c.where),u(e.confine,`confine`),u(c.fields,`read.fields`,void 0,!0),u(c.select,`read.select`,void 0,!0);for(let t of[`create`,`update`,`delete`])u(e[t],t,void 0,!0);let{acyclic:d}=e;return d!==void 0&&(s?.pl===void 0&&a(`acyclic needs a check() beside it`),s.acyclic=d),s}const qe=Object.freeze({});function Je(e,{layer:t,kb:n},r,i){let a=e=>{n.add(e)};for(let[n,o]of Object.entries(r)){Object.hasOwn(i,n)||s(`Extension "${e}" rule names unknown model "${n}".`,e);let r=t=>s(`Extension "${e}" rule.${n}: ${t}.`,e),c=Ke(o,n,i,{layer:t,wh:a},r,!1),l=Y(o),{where:u}=Y(l.read);for(let e of[`root`,`related`]){let r=X(l[e]);u!==void 0&&r.unshift(u),r.length>0&&(t[e][n]=[...t[e][n]??[],...r])}c!==void 0&&(Object.hasOwn(t.rules,n)&&r(`two rule parts of one extension judge the model`),t.rules[n]=c)}}function Ye(e){let t={declare(n){let{name:r,schema:i}=n,a=o(n,qe,()=>{let e={root:{},related:{},rules:{}};return{layer:e,kb:new Set([Fe(e)])}});o(n,t,()=>Je(r,a,typeof e==`function`?e(i):e,i));for(let e of a.kb)n.wh(e)}};return t}var Z=class extends D{held;constructor(e){super(),this.held=e}};const Q=e=>e.layer.yp??={};function Xe({schema:e,model:t,key:n,field:r,refuse:i},a,o,s,c,l,u){let{state:d}=e[t][`~`],f=c[n];f===void 0?l.test(n)?Object.hasOwn(d.scalars,r)||Object.hasOwn(d.relations,r)?(a[u]??=new Map).set(r,o):i(`update.fields names unknown field "${r}"`):i(`${n} does not take ${s}()`):a[f]=o}function $(e){let t=I(e);return t.shown=e.a5,Q(e).se=We,t}const Ze=/^update\.fields\.[^.]+\.where$/,Qe=/^update\.fields\.[^.]+\.check$/;var $e=class extends Z{join(e){let t=I(e);Q(e).prepare=N,Xe(e,t,this.held,`only`,{"update.where":`update`,"delete.where":`delete`},Ze,`writes`)}};function et(e){return new $e(e)}var tt=class extends Z{join(e){let t=I(e);t.pl=H,Q(e).pl=H,Xe(e,t,this.held,`check`,{"create.check":`place`,"update.check":`check`},Qe,`moves`)}};function nt(e){return new tt(e)}const rt=(e,t)=>p(e).wm.includes(t)||e[`~`].state.indexes.some(e=>e.options.unique&&e.fields.includes(t))||Object.values(e[`~`].state.relations).some(e=>e[`~`].state.foreignKey?.fields.includes(t)===!0);var it=class extends Z{join(e){let{key:t,field:n,model:r,schema:i,refuse:a}=e;t!==`read.fields.${n}`&&a(`${t} does not take gate()`);let o=i[r];Object.hasOwn(o[`~`].state.scalars,n)||a(`${t} names no scalar of the model`),rt(o,n)&&a(`${t} names a key, a unique or a foreign key field`),($(e).reads??=new Map).set(n,this.held)}};function at(e){return new it(e)}const ot=/^\$[a-zA-Z_][a-zA-Z0-9_]*$/;var st=class extends Z{join(e){let{key:t,field:n,refuse:r}=e;t!==`read.select.${n}`&&r(`${t} does not take facts()`),ot.test(n)||r(`${t} is not \`$\` and an identifier`);let i=$(e);i.as!==void 0&&r(`read.select holds one projection key`),Q(e).keys=J,i.as=n,i.facts=new Map(Object.entries(this.held))}};function ct(e){return new st(e)}var lt=class extends D{data;constructor(e){super(),this.data=e}join({key:e,model:t,schema:n,lazy:r,wh:i,refuse:a}){let o=a;(e!==`delete.instead`||r)&&o(`${r?`a lazy entry`:e} does not take keep()`);let s=this.data,c=s instanceof E&&s.kind!==`provided`?s:void 0,u;if(c?.arg!==void 0){let e=he(c.test);typeof e==`string`&&o(e),u=new le(c.arg.s1(),e),s=c.then}l(s)||o(`keep() takes the data the row is updated with`);let{state:d}=n[t][`~`],f,p={};for(let[e,t]of Object.entries(s))Object.hasOwn(d.scalars,e)||o(`keep() names unknown field "${e}"`),t instanceof E?t.s1?.()!==pe||f!==void 0?o(`keep() writes constants, and now in one field`):f=e:p[e]=t;i(Re(t,{...f!==void 0&&{at:f},assign:p,...u&&{test:u,keeps:c.kind===`when`}}))}};function ut(e){return new lt(e)}var dt=class extends Z{join(e){let{key:t,model:n,schema:r,lazy:i,refuse:a}=e;(t!==`the entry`||i)&&a(`${t} does not take lazy()`);let o=e.layer,{held:c}=this;Object.hasOwn(o.rules,n)&&a(`two rule parts of one extension judge the model`),o.host=F,o.reads=me,o.yp={pl:H,se:We,prepare:N,keys:J,lazy:!0};let u=(t,i)=>{let o;return(u,d)=>{if(o===void 0){let s=c(),u=l(s)?s:{},d=new Set,f=`lazy ${n}`,p=P(t,n,Ke(s,n,r,e,a,!0)??{},d,f);p.filters=i(n,{root:X(u.root),related:X(u.related)},d,f),p.references=[...d],o=p}let f=e=>u.extensions.findIndex(t=>t.name===e);for(let e of o.references)e!==void 0&&!u.args?.all.some(t=>t.name===e&&f(t.extension)<=f(d))&&s(`Extension "${d}" references undeclared argument "${e}".`,d);return o}};o.rules[n]=u}};function ft(e){return new dt(e)}export{ut as a,Ye as c,at as i,A as l,nt as n,ft as o,ct as r,et as s,Z as t};
|
|
2
|
+
//# sourceMappingURL=judge-words-k5GCc4cV.mjs.map
|