viborm 1.2.3 → 1.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +6 -1
- package/dist/{adapter-internals-n3Mf3css.mjs → adapter-internals-AGgQRu5t.mjs} +1 -1
- package/dist/{adapter-internals-n3Mf3css.mjs.map → adapter-internals-AGgQRu5t.mjs.map} +1 -1
- package/dist/adapter-namespace-BpMbLKpL.mjs +2 -0
- package/dist/{adapter-namespace-DqkJQdrD.mjs.map → adapter-namespace-BpMbLKpL.mjs.map} +1 -1
- package/dist/adapters.d.mts +1 -1
- package/dist/adapters.mjs +1 -1
- package/dist/{array-literal-BsbbSLw3.mjs → array-literal-BKdLfNzM.mjs} +1 -1
- package/dist/{array-literal-BsbbSLw3.mjs.map → array-literal-BKdLfNzM.mjs.map} +1 -1
- package/dist/{base-AdXAoy6l.mjs → base-D3m1S7Uc.mjs} +2 -2
- package/dist/{base-AdXAoy6l.mjs.map → base-D3m1S7Uc.mjs.map} +1 -1
- package/dist/{batch-refs-4L8ECdPU.mjs → batch-refs-B4zn-FAu.mjs} +2 -2
- package/dist/{batch-refs-4L8ECdPU.mjs.map → batch-refs-B4zn-FAu.mjs.map} +1 -1
- package/dist/{bind-parameter-capacity-CjPgqnmx.mjs → bind-parameter-capacity-qfEejeOX.mjs} +2 -2
- package/dist/{bind-parameter-capacity-CjPgqnmx.mjs.map → bind-parameter-capacity-qfEejeOX.mjs.map} +1 -1
- package/dist/builder-Df24l2Bd.mjs +2 -0
- package/dist/builder-Df24l2Bd.mjs.map +1 -0
- package/dist/bun-sql.d.mts +3 -1
- package/dist/bun-sql.mjs +1 -1
- package/dist/bun-sql.mjs.map +1 -1
- package/dist/bun-sqlite.d.mts +1 -1
- package/dist/bun-sqlite.mjs +1 -1
- package/dist/cache/cloudflare-kv.d.mts +1 -1
- package/dist/cache/cloudflare-kv.mjs +1 -1
- package/dist/cache/memory.d.mts +1 -1
- package/dist/cache/memory.mjs +1 -1
- package/dist/{cache-BO57X0TT.mjs → cache-CIPRF-pz.mjs} +2 -2
- package/dist/{cache-BO57X0TT.mjs.map → cache-CIPRF-pz.mjs.map} +1 -1
- package/dist/cache.d.mts +1 -1
- package/dist/cache.mjs +1 -1
- package/dist/cache.mjs.map +1 -1
- package/dist/{canonical-json-rfC2Dg0X.mjs → canonical-json-BReb5nFO.mjs} +2 -2
- package/dist/{canonical-json-rfC2Dg0X.mjs.map → canonical-json-BReb5nFO.mjs.map} +1 -1
- package/dist/chain-C7c1YTXD.mjs +2 -0
- package/dist/chain-C7c1YTXD.mjs.map +1 -0
- package/dist/cli.mjs +2 -2
- package/dist/cli.mjs.map +1 -1
- package/dist/{client-GoDZgqdq.d.mts → client-70MrTq1E.d.mts} +3 -3
- package/dist/client-DM1UHfYG.mjs +49 -0
- package/dist/client-DM1UHfYG.mjs.map +1 -0
- package/dist/client-_WKrPNmm.mjs +2 -0
- package/dist/client-_WKrPNmm.mjs.map +1 -0
- package/dist/client.d.mts +2 -2
- package/dist/client.mjs +1 -1
- package/dist/{clock-CK41KO7t.mjs → clock-C24RcpwO.mjs} +1 -1
- package/dist/{clock-CK41KO7t.mjs.map → clock-C24RcpwO.mjs.map} +1 -1
- package/dist/config.d.mts +2 -2
- package/dist/config.mjs +1 -1
- package/dist/controls-Da-efekX.mjs +2 -0
- package/dist/controls-Da-efekX.mjs.map +1 -0
- package/dist/{current-DyzK6OCh.mjs → current-oXcxSCBQ.mjs} +1 -1
- package/dist/{current-DyzK6OCh.mjs.map → current-oXcxSCBQ.mjs.map} +1 -1
- package/dist/d1.d.mts +1 -1
- package/dist/d1.mjs +1 -1
- package/dist/d1.mjs.map +1 -1
- package/dist/{datetime-physical-codec-oIhiYZEP.mjs → datetime-physical-codec-BEqQbIP_.mjs} +2 -2
- package/dist/{datetime-physical-codec-oIhiYZEP.mjs.map → datetime-physical-codec-BEqQbIP_.mjs.map} +1 -1
- package/dist/driver-B9fIori_.mjs +2 -0
- package/dist/driver-B9fIori_.mjs.map +1 -0
- package/dist/{driver-B19QlFqn.mjs → driver-CPD0Xxw2.mjs} +2 -2
- package/dist/{driver-B19QlFqn.mjs.map → driver-CPD0Xxw2.mjs.map} +1 -1
- package/dist/driver.d.mts +1 -1
- package/dist/driver.mjs +1 -1
- package/dist/error-mapping-C9WgitPi.mjs +2 -0
- package/dist/error-mapping-C9WgitPi.mjs.map +1 -0
- package/dist/every-1pKZteeB.mjs +2 -0
- package/dist/{every-DCY4HV0X.mjs.map → every-1pKZteeB.mjs.map} +1 -1
- package/dist/{execution-context-BKR3bgES.mjs → execution-context-rJXTRVrJ.mjs} +1 -1
- package/dist/{execution-context-BKR3bgES.mjs.map → execution-context-rJXTRVrJ.mjs.map} +1 -1
- package/dist/{fs-estate-CAhDg7nY.mjs → fs-estate-i8Zlr1OQ.mjs} +2 -2
- package/dist/{fs-estate-CAhDg7nY.mjs.map → fs-estate-i8Zlr1OQ.mjs.map} +1 -1
- package/dist/{geo-area-codec-1SY9im7O.mjs → geo-area-codec-CbkmFArQ.mjs} +2 -2
- package/dist/{geo-area-codec-1SY9im7O.mjs.map → geo-area-codec-CbkmFArQ.mjs.map} +1 -1
- package/dist/geo-point-codec-DyEHMdJg.mjs +2 -0
- package/dist/geo-point-codec-DyEHMdJg.mjs.map +1 -0
- package/dist/hydration-DsyHNSDS.mjs +2 -0
- package/dist/{hydration-CAxOL4aI.mjs.map → hydration-DsyHNSDS.mjs.map} +1 -1
- package/dist/identifier-conversion-DaZ9yNpv.mjs +2 -0
- package/dist/{identifier-conversion-GgbwHc2G.mjs.map → identifier-conversion-DaZ9yNpv.mjs.map} +1 -1
- package/dist/{identity-CLFhCTZx.mjs → identity-oQvIe7u8.mjs} +2 -2
- package/dist/{identity-CLFhCTZx.mjs.map → identity-oQvIe7u8.mjs.map} +1 -1
- package/dist/{index-BaK35ze2.d.mts → index-VsM29vYN.d.mts} +5269 -4918
- package/dist/index.d.mts +3 -3
- package/dist/index.mjs +1 -1
- package/dist/index.mjs.map +1 -1
- package/dist/instrumentation.d.mts +1 -1
- package/dist/instrumentation.mjs +1 -1
- package/dist/{invariant-BnLYqsHO.mjs → invariant-D57gi_yW.mjs} +1 -1
- package/dist/{invariant-BnLYqsHO.mjs.map → invariant-D57gi_yW.mjs.map} +1 -1
- package/dist/{json-number-CGXpPu4D.mjs → json-number-DvmiNx0n.mjs} +1 -1
- package/dist/{json-number-CGXpPu4D.mjs.map → json-number-DvmiNx0n.mjs.map} +1 -1
- package/dist/key-D_kagnFv.mjs +2 -0
- package/dist/{key-BeoOwGr3.mjs.map → key-D_kagnFv.mjs.map} +1 -1
- package/dist/{libsql-x0RPVRDS.mjs → libsql-DFAoHXrI.mjs} +3 -3
- package/dist/{libsql-x0RPVRDS.mjs.map → libsql-DFAoHXrI.mjs.map} +1 -1
- package/dist/libsql.d.mts +1 -1
- package/dist/libsql.mjs +1 -1
- package/dist/{memory-gv5jLGYm.mjs → memory-GTWgeDNY.mjs} +2 -2
- package/dist/{memory-gv5jLGYm.mjs.map → memory-GTWgeDNY.mjs.map} +1 -1
- package/dist/migrations/mysql.d.mts +5 -5
- package/dist/migrations/mysql.mjs +1 -1
- package/dist/migrations/postgres.d.mts +5 -5
- package/dist/migrations/postgres.mjs +1 -1
- package/dist/migrations/sqlite.d.mts +5 -5
- package/dist/migrations/sqlite.mjs +1 -1
- package/dist/migrations/storage/durable-object.d.mts +1 -1
- package/dist/migrations/storage/durable-object.mjs +1 -1
- package/dist/migrations/storage/fs.d.mts +1 -1
- package/dist/migrations/storage/fs.mjs +1 -1
- package/dist/migrations/storage/r2.d.mts +1 -1
- package/dist/migrations/storage/r2.mjs +1 -1
- package/dist/migrations/tenant.d.mts +3 -3
- package/dist/migrations/tenant.mjs +1 -1
- package/dist/{migrations-DTObIjAm.mjs → migrations-Bn1SatyB.mjs} +2 -2
- package/dist/{migrations-DTObIjAm.mjs.map → migrations-Bn1SatyB.mjs.map} +1 -1
- package/dist/migrations.d.mts +5 -5
- package/dist/migrations.mjs +1 -1
- package/dist/mysql-adapter-C6c5govr.mjs +2 -0
- package/dist/{mysql-adapter-DkJPfoGf.mjs.map → mysql-adapter-C6c5govr.mjs.map} +1 -1
- package/dist/{mysql-B5cqxG99.mjs → mysql-xChEivOe.mjs} +6 -6
- package/dist/{mysql-B5cqxG99.mjs.map → mysql-xChEivOe.mjs.map} +1 -1
- package/dist/mysql2.d.mts +1 -1
- package/dist/mysql2.mjs +1 -1
- package/dist/{native-types-veeTk36s.mjs → native-types-asNCr26n.mjs} +1 -1
- package/dist/{native-types-veeTk36s.mjs.map → native-types-asNCr26n.mjs.map} +1 -1
- package/dist/neon-http.d.mts +3 -1
- package/dist/neon-http.mjs +1 -1
- package/dist/neon-http.mjs.map +1 -1
- package/dist/{object-store-DQR6bTBY.mjs → object-store-ChYHlOMD.mjs} +2 -2
- package/dist/{object-store-DQR6bTBY.mjs.map → object-store-ChYHlOMD.mjs.map} +1 -1
- package/dist/{object-store-Cj8Cnnba.d.mts → object-store-D9mvOHP4.d.mts} +4 -4
- package/dist/{observation-DUSm7oXK.mjs → observation-Co72iCd1.mjs} +2 -2
- package/dist/{observation-DUSm7oXK.mjs.map → observation-Co72iCd1.mjs.map} +1 -1
- package/dist/permissions.d.mts +424 -0
- package/dist/permissions.mjs +2 -0
- package/dist/permissions.mjs.map +1 -0
- package/dist/pg.d.mts +9 -1
- package/dist/pg.mjs +1 -1
- package/dist/pg.mjs.map +1 -1
- package/dist/pglite.d.mts +3 -1
- package/dist/pglite.mjs +1 -1
- package/dist/pglite.mjs.map +1 -1
- package/dist/{physical-6V_LNU3L.mjs → physical-CAOaNM4R.mjs} +2 -2
- package/dist/{physical-6V_LNU3L.mjs.map → physical-CAOaNM4R.mjs.map} +1 -1
- package/dist/{pinned-session-CLxj5M5e.mjs → pinned-session-BTplL3iZ.mjs} +2 -2
- package/dist/{pinned-session-CLxj5M5e.mjs.map → pinned-session-BTplL3iZ.mjs.map} +1 -1
- package/dist/planetscale.d.mts +1 -1
- package/dist/planetscale.mjs +1 -1
- package/dist/{planner-DH-K2gSq.d.mts → planner-C1NzLBge.d.mts} +1 -1
- package/dist/{postgres-DrXDok0O.mjs → postgres-BqAxDWTQ.mjs} +4 -4
- package/dist/{postgres-DrXDok0O.mjs.map → postgres-BqAxDWTQ.mjs.map} +1 -1
- package/dist/postgres-adapter-CGthb5yh.mjs +2 -0
- package/dist/postgres-adapter-CGthb5yh.mjs.map +1 -0
- package/dist/postgres-adapter-CxEit2-v.mjs +2 -0
- package/dist/postgres-adapter-CxEit2-v.mjs.map +1 -0
- package/dist/{postgres-result-7F0DllQe.mjs → postgres-result-KyBKBNJr.mjs} +2 -2
- package/dist/{postgres-result-7F0DllQe.mjs.map → postgres-result-KyBKBNJr.mjs.map} +1 -1
- package/dist/postgres.d.mts +3 -1
- package/dist/postgres.mjs +1 -1
- package/dist/postgres.mjs.map +1 -1
- package/dist/{provider-limits-BHATED_m.mjs → provider-limits-Da00ilvv.mjs} +2 -2
- package/dist/{provider-limits-BHATED_m.mjs.map → provider-limits-Da00ilvv.mjs.map} +1 -1
- package/dist/{result-parsing-DRXC89ek.mjs → result-parsing-8wEK3GY1.mjs} +1 -1
- package/dist/{result-parsing-DRXC89ek.mjs.map → result-parsing-8wEK3GY1.mjs.map} +1 -1
- package/dist/result-shape-CDgX_vzn.mjs +2 -0
- package/dist/result-shape-CDgX_vzn.mjs.map +1 -0
- package/dist/scalar-S8yMvdmx.mjs +4 -0
- package/dist/scalar-S8yMvdmx.mjs.map +1 -0
- package/dist/schema/json.d.mts +1 -1
- package/dist/schema/json.mjs +1 -1
- package/dist/schema/json.mjs.map +1 -1
- package/dist/schema-9N9jQlVL.mjs +2 -0
- package/dist/{schema-Cjem1-0f.mjs.map → schema-9N9jQlVL.mjs.map} +1 -1
- package/dist/{schema-introspection-DEYGC2qg.mjs → schema-introspection-CyXKReK1.mjs} +4 -4
- package/dist/{schema-introspection-DEYGC2qg.mjs.map → schema-introspection-CyXKReK1.mjs.map} +1 -1
- package/dist/schema.d.mts +1 -1
- package/dist/schema.mjs +1 -1
- package/dist/{select-assembly-f1UGoblh.mjs → select-assembly-CkGe2ABs.mjs} +2 -2
- package/dist/{select-assembly-f1UGoblh.mjs.map → select-assembly-CkGe2ABs.mjs.map} +1 -1
- package/dist/{settle-B9Vg1FnP.mjs → settle-CS_k6Ztm.mjs} +2 -2
- package/dist/{settle-B9Vg1FnP.mjs.map → settle-CS_k6Ztm.mjs.map} +1 -1
- package/dist/soft-delete.d.mts +27 -96
- package/dist/soft-delete.mjs +1 -1
- package/dist/soft-delete.mjs.map +1 -1
- package/dist/sql-Bhxq9arK.mjs +2 -0
- package/dist/sql-Bhxq9arK.mjs.map +1 -0
- package/dist/{sql-BvfwUKIh.d.mts → sql-EsoN_7Et.d.mts} +24 -0
- package/dist/{sql-statement-tokens-BBcoGmJb.mjs → sql-statement-tokens-CFi1y3bK.mjs} +1 -1
- package/dist/{sql-statement-tokens-BBcoGmJb.mjs.map → sql-statement-tokens-CFi1y3bK.mjs.map} +1 -1
- package/dist/sql.d.mts +1 -1
- package/dist/sql.mjs +1 -1
- package/dist/sqlite-adapter-BXAJy3mI.mjs +2 -0
- package/dist/sqlite-adapter-BXAJy3mI.mjs.map +1 -0
- package/dist/{sqlite-utils-DlgokMJN.mjs → sqlite-utils-D_cypcyW.mjs} +2 -2
- package/dist/{sqlite-utils-DlgokMJN.mjs.map → sqlite-utils-D_cypcyW.mjs.map} +1 -1
- package/dist/sqlite3.d.mts +3 -1
- package/dist/sqlite3.mjs +1 -1
- package/dist/sqlite3.mjs.map +1 -1
- package/dist/{standard-sql-Bk4RZPqJ.mjs → standard-sql-CoGqv-iX.mjs} +3 -3
- package/dist/standard-sql-CoGqv-iX.mjs.map +1 -0
- package/dist/{suppressed-failure-BwULh-8h.mjs → suppressed-failure-Bdo2aK81.mjs} +1 -1
- package/dist/{suppressed-failure-BwULh-8h.mjs.map → suppressed-failure-Bdo2aK81.mjs.map} +1 -1
- package/dist/to-many-C1PuFIpf.mjs +2 -0
- package/dist/to-many-C1PuFIpf.mjs.map +1 -0
- package/dist/{transaction-Bnl6ULTw.mjs → transaction-4dfqals6.mjs} +2 -2
- package/dist/{transaction-Bnl6ULTw.mjs.map → transaction-4dfqals6.mjs.map} +1 -1
- package/dist/{transaction-operation-CKK3l_9x.mjs → transaction-operation-CU1zlxiG.mjs} +2 -2
- package/dist/{transaction-operation-CKK3l_9x.mjs.map → transaction-operation-CU1zlxiG.mjs.map} +1 -1
- package/dist/{types-C4v6iAmY.mjs → types-C5Oxz9yp.mjs} +1 -1
- package/dist/{types-C4v6iAmY.mjs.map → types-C5Oxz9yp.mjs.map} +1 -1
- package/dist/{utils-CZNaOZR7.mjs → utils-CtFUE8UN.mjs} +4 -4
- package/dist/{utils-CZNaOZR7.mjs.map → utils-CtFUE8UN.mjs.map} +1 -1
- package/dist/v-CYTUI0H5.mjs +2 -0
- package/dist/v-CYTUI0H5.mjs.map +1 -0
- package/dist/validation-BQtO6srU.mjs +2 -0
- package/dist/{validation-PF9-_nKd.mjs.map → validation-BQtO6srU.mjs.map} +1 -1
- package/dist/validation-BamBwne9.mjs +2 -0
- package/dist/validation-BamBwne9.mjs.map +1 -0
- package/dist/validation.d.mts +1 -1
- package/dist/validation.mjs +1 -1
- package/dist/validator-DgffZq9C.mjs +2 -0
- package/dist/validator-DgffZq9C.mjs.map +1 -0
- package/dist/version-CXuJzC-q.mjs +2 -0
- package/dist/{version-Bemp-64P.mjs.map → version-CXuJzC-q.mjs.map} +1 -1
- package/package.json +35 -9
- package/dist/adapter-namespace-DqkJQdrD.mjs +0 -2
- package/dist/builder-Ycvq3ETg.mjs +0 -2
- package/dist/builder-Ycvq3ETg.mjs.map +0 -1
- package/dist/chain-Dh0FV72b.mjs +0 -2
- package/dist/chain-Dh0FV72b.mjs.map +0 -1
- package/dist/client-B1p6Le_h.mjs +0 -49
- package/dist/client-B1p6Le_h.mjs.map +0 -1
- package/dist/client-BLiBmykn.mjs +0 -2
- package/dist/client-BLiBmykn.mjs.map +0 -1
- package/dist/controls-DXgIn4zh.mjs +0 -2
- package/dist/controls-DXgIn4zh.mjs.map +0 -1
- package/dist/driver-BlnKXPFF.mjs +0 -2
- package/dist/driver-BlnKXPFF.mjs.map +0 -1
- package/dist/error-mapping-CnPCv1dm.mjs +0 -2
- package/dist/error-mapping-CnPCv1dm.mjs.map +0 -1
- package/dist/every-DCY4HV0X.mjs +0 -2
- package/dist/geo-point-codec-lhxH42SK.mjs +0 -2
- package/dist/geo-point-codec-lhxH42SK.mjs.map +0 -1
- package/dist/hydration-CAxOL4aI.mjs +0 -2
- package/dist/identifier-conversion-GgbwHc2G.mjs +0 -2
- package/dist/identifier-hQCs8M1n.mjs +0 -2
- package/dist/identifier-hQCs8M1n.mjs.map +0 -1
- package/dist/key-BeoOwGr3.mjs +0 -2
- package/dist/mysql-adapter-DkJPfoGf.mjs +0 -2
- package/dist/postgres-adapter-B3SQvcV1.mjs +0 -2
- package/dist/postgres-adapter-B3SQvcV1.mjs.map +0 -1
- package/dist/postgres-adapter-CQD2oGuD.mjs +0 -2
- package/dist/postgres-adapter-CQD2oGuD.mjs.map +0 -1
- package/dist/registration-preflight-DEjv050M.mjs +0 -4
- package/dist/registration-preflight-DEjv050M.mjs.map +0 -1
- package/dist/result-shape-CTNdNSW3.mjs +0 -2
- package/dist/result-shape-CTNdNSW3.mjs.map +0 -1
- package/dist/scalar-U0wD5bKy.mjs +0 -2
- package/dist/scalar-U0wD5bKy.mjs.map +0 -1
- package/dist/schema-Cjem1-0f.mjs +0 -2
- package/dist/sql-Bp7jicEX.mjs +0 -2
- package/dist/sql-Bp7jicEX.mjs.map +0 -1
- package/dist/sqlite-adapter-CW_3l6ea.mjs +0 -2
- package/dist/sqlite-adapter-CW_3l6ea.mjs.map +0 -1
- package/dist/standard-sql-Bk4RZPqJ.mjs.map +0 -1
- package/dist/terminal-C8cq1WWX.mjs +0 -2
- package/dist/terminal-C8cq1WWX.mjs.map +0 -1
- package/dist/v-D5Z06FKN.mjs +0 -2
- package/dist/v-D5Z06FKN.mjs.map +0 -1
- package/dist/validation-Dk9Q_-C7.mjs +0 -2
- package/dist/validation-Dk9Q_-C7.mjs.map +0 -1
- package/dist/validation-PF9-_nKd.mjs +0 -2
- package/dist/validator-X9-bwtRo.mjs +0 -2
- package/dist/validator-X9-bwtRo.mjs.map +0 -1
- package/dist/version-Bemp-64P.mjs +0 -2
- /package/dist/{contract-CIIqgFyb.d.mts → contract-Dw0FR78e.d.mts} +0 -0
package/dist/schema/json.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"json.mjs","names":["date","model","modelFactory","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 */\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\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, \"Reading this value threw\");\n throw refuseDocument(issues, toError(thrown));\n }\n}\n\n/** `isPlainRecord`, with a throwing `getPrototypeOf` trap owned as a refusal. */\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, \"Inspecting this value's prototype threw\");\n throw refuseDocument(issues, toError(thrown));\n }\n}\n\n/** `declaredKeys`, with a throwing `ownKeys` trap owned as a refusal. */\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, \"Enumerating this value's keys 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.\n//\n// A default is the only place a document holds a value from a domain the FIELD\n// chose rather than the 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}' (a decimal integer string), '${DATE_TAG}' (an ISO timestamp), '${BYTES_TAG}' (base64), '${RAW_TAG}' (the literal it wraps), '${JSON_NULL_TAG}' ('JsonNull' or 'DbNull')`;\n\n/**\n * The tag a record spells, if it spells one.\n *\n * Exactly one own key, beginning with `$`. Two keys is an ordinary object that\n * merely mentions a tag name, and is left alone in both directions.\n */\nfunction 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\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): JsonValue | undefined {\n return readValue(value, path, issues, new Set());\n}\n\nfunction readValue(\n value: unknown,\n path: string,\n issues: DocumentIssues,\n seen: Set<object>\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(issues, path, \"J004\", \"A default must be a finite number\");\n return;\n }\n if (Array.isArray(value)) return readArray(value, path, issues, seen);\n if (inspectPlainRecord(value, path, issues, \"J004\")) {\n return readRecord(value, path, issues, seen);\n }\n addIssue(\n issues,\n path,\n \"J004\",\n isFunction(value)\n ? \"A function default has no document spelling — use `generate`, a literal, or a database default through `native`\"\n : `A default must be a JSON value; a value outside JSON takes a tag — ${TAGS}`\n );\n return;\n}\n\nfunction readArray(\n value: readonly unknown[],\n path: string,\n issues: DocumentIssues,\n seen: Set<object>\n): JsonValue[] | undefined {\n if (enterCycle(value, path, issues, seen, \"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 seen\n );\n if (item === undefined) return;\n items.push(item);\n }\n seen.delete(value);\n return items;\n}\n\nfunction readRecord(\n value: Record<string, unknown>,\n path: string,\n issues: DocumentIssues,\n seen: Set<object>\n): Record<string, JsonValue> | undefined {\n if (enterCycle(value, path, issues, seen, \"J004\")) return;\n const keys = inspectKeys(value, path, issues, \"J004\");\n const tag = reservedKey(keys);\n if (tag !== undefined && !KNOWN_TAGS.has(tag)) {\n // An unknown `$`-tag is a DOCUMENT-shape fact, caught HERE during the\n // accumulating walk — so two bad tags in two fields both surface — rather\n // than at decode time, which is fail-fast. Payload well-formedness for a\n // KNOWN tag stays the decoder's, where a single default is being built.\n addIssue(\n issues,\n path,\n \"J008\",\n `'${tag}' is not a tag this format defines. The tags are ${TAGS}`\n );\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 seen\n );\n if (entry === undefined) return;\n put(record, key, entry);\n }\n 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 seen: Set<object>,\n code: \"J004\" | \"J009\"\n): boolean {\n if (!seen.has(value)) {\n seen.add(value);\n return false;\n }\n addIssue(\n issues,\n path,\n code,\n \"This default contains a cycle; a document holds a finite value\"\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): JsonValue | undefined {\n return encodeValue(value, path, issues, new Set());\n}\n\nfunction encodeValue(\n value: unknown,\n path: string,\n issues: DocumentIssues,\n seen: Set<object>\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(\n issues,\n path,\n \"A non-finite number has no JSON spelling; `JSON.stringify` would write it as `null`\"\n );\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(\n issues,\n path,\n \"This byte string has a detached buffer and cannot be serialized\"\n );\n }\n }\n if (isDate(value)) {\n if (Number.isNaN(Date.prototype.getTime.call(value))) {\n return refuseValue(issues, path, \"An invalid Date names no instant\");\n }\n return tagged(DATE_TAG, Date.prototype.toISOString.call(value));\n }\n if (Array.isArray(value)) return encodeArray(value, path, issues, seen);\n if (inspectPlainRecord(value, path, issues, \"J009\")) {\n return encodeRecord(value, path, issues, seen);\n }\n return refuseValue(\n issues,\n path,\n \"This default holds a value the document cannot state — a JSON value, a bigint, a Date or a byte string is what a default may be\"\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 seen: Set<object>\n): JsonValue[] | undefined {\n if (enterCycle(value, path, issues, seen, \"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 seen\n );\n if (item === undefined) return;\n items.push(item);\n }\n 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 seen: Set<object>\n): Record<string, JsonValue> | undefined {\n if (enterCycle(value, path, issues, seen, \"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 seen\n );\n if (entry === undefined) return;\n put(record, key, entry);\n }\n 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 * 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\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}\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/** The junction's physical names: its table and its two side tokens. */\nexport interface JunctionNamesDocument {\n table?: 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 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 ModelDocument,\n ModelTargetDocument,\n RelationFieldDocument,\n ScalarFieldDocument,\n SchemaDocument,\n VariantTargetDocument,\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\";\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 */\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 registry[modelKey] = buildModel(\n modelKey,\n modelDocument,\n document,\n registry,\n pointer(modelsPath, modelKey),\n fieldSchemas\n );\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}' does not name a scalar field of this schema; spell it '<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 for (const [position, index] of (document.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 model = call(indexPath, () =>\n Reflect.apply(model.index, model, [index.fields, indexOptions])\n );\n }\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 return model;\n}\n\nfunction options(name: string | undefined): { name?: string } {\n return name === undefined ? {} : { name };\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 if (document.array) {\n scalar = modify(scalar, \"array\", [], type, pointer(path, \"array\"));\n }\n if (document.nullable) {\n scalar = modify(scalar, \"nullable\", [], type, pointer(path, \"nullable\"));\n }\n if (document.id) {\n // An IMPLICIT generator is `.id()`'s own, prefix included: applying it here\n // is what keeps a key a key. Declaring the ULID separately afterwards would\n // NAME the format, which is a different field — a validated domain in a\n // compact column — so the generate node below stands down for it.\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 scalar = modify(scalar, \"id\", args, type, pointer(path, \"id\"));\n }\n if (document.unique) {\n scalar = modify(scalar, \"unique\", [], type, pointer(path, \"unique\"));\n }\n if (document.withoutTimezone) {\n scalar = modify(\n scalar,\n \"withoutTimezone\",\n [],\n type,\n pointer(path, \"withoutTimezone\")\n );\n }\n if (document.dimension !== undefined) {\n scalar = modify(\n scalar,\n \"dimension\",\n [document.dimension],\n type,\n pointer(path, \"dimension\")\n );\n }\n if (document.generate !== undefined && document.generate.implicit !== true) {\n scalar = applyGenerate(scalar, document.generate, type, path);\n }\n const literal = document.default;\n if (literal !== undefined) {\n scalar = applyDefault(scalar, document, literal, path);\n }\n if (document.column !== undefined) {\n scalar = modify(\n scalar,\n \"map\",\n [document.column],\n type,\n pointer(path, \"column\")\n );\n }\n if (fieldSchema !== undefined) {\n scalar = modify(\n scalar,\n \"schema\",\n [fieldSchema],\n type,\n pointer(path, \"schema\")\n );\n }\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 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 const issues: DocumentIssues = [];\n addIssue(\n issues,\n pointer(path, \"enum\"),\n \"J006\",\n `\\`enum\\` names '${reference}', which \\`enums\\` does not declare`\n );\n throw refuseDocument(issues);\n}\n\n/**\n * Apply one modifier BY NAME.\n *\n * The scalar class surface is the only table of which modifiers a type has, and\n * an absent method is exactly what \"this type has no such modifier\" means. Blob\n * refuses `array`/`id`/`unique` by throwing instead — a deliberate runtime\n * refusal — and that throw comes back as this node's own issue.\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 const issues: DocumentIssues = [];\n addIssue(\n issues,\n path,\n \"J007\",\n `A '${type}' field has no '${name}' modifier`\n );\n throw refuseDocument(issues);\n }\n return call(path, () => method.apply(scalar, args));\n}\n\n/**\n * `generate.kind` names the scalar method that installs the generator, so the\n * nine tokens are the nine methods.\n *\n * Whether that method TAKES a prefix or a length is read back from the state it\n * wrote rather than from a second arity table: a generator that ignored the\n * argument records nothing, and a declaration the builder cannot honor is\n * refused instead of silently dropped.\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 const issues: DocumentIssues = [];\n addIssue(\n issues,\n generatePath,\n \"J007\",\n `The '${generate.kind}' generator does not take the 'prefix' or 'length' this node declares`\n );\n throw refuseDocument(issues);\n}\n\n/**\n * A literal default, converted into the value the field's own domain holds.\n *\n * The codec owns the conversion — which tag denotes which domain, how deep it\n * reaches, and what a cycle costs. What is owned HERE is the check that follows\n * it: defaults BYPASS validation downstream — the create schema substitutes a\n * default without checking it — so a wrong-typed one is a late failure at bind\n * time. The field's own base schema is the single statement of its domain, and\n * checking against it here moves that failure to the document that wrote it.\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 // A bigint field also READS integer text, the spelling a JSON payload\n // carries; a default is the value the domain holds, so it stays tagged.\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 : 'a bigint is written {\"$bigint\": \"<integer>\"}';\n const issues: DocumentIssues = [];\n addIssue(\n issues,\n defaultPath,\n \"J008\",\n `A '${document.type}' default must be a value of the field's own domain: ${reason}`\n );\n throw refuseDocument(issues);\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, 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 five 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 [\"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 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](value)\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 { readDefaultValue } 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} 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\", \"enums\", \"models\"];\nconst ENUM_KEYS = [\"values\", \"name\"];\nconst MODEL_KEYS = [\"table\", \"fields\", \"indexes\", \"ids\", \"uniques\", \"omit\"];\nconst INDEX_KEYS = [\"fields\", \"name\", \"unique\", \"type\", \"where\"];\nconst COMPOUND_KEYS = [\"fields\", \"name\"];\nconst NATIVE_KEYS = [\"db\", \"type\"];\nconst GENERATE_KEYS = [\"kind\", \"prefix\", \"length\", \"implicit\", \"generate\"];\nconst JUNCTION_KEYS = [\n \"table\",\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 refuseUnknownKeys(\n record: Record<string, unknown>,\n allowed: readonly string[],\n path: string,\n issues: DocumentIssues,\n declarer = \"this node\"\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}'; ${declarer} declares ${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}' is \\`undefined\\`; a document omits an absent key rather than setting it to \\`undefined\\``\n );\n }\n }\n}\n\n/**\n * A key that names a model, a field, a variant or an enum definition.\n *\n * It runs BEFORE anything is constructed. `isValidSchemaIdentifier` already\n * owns the rule at hydration, but a `__proto__` model key assigned into the\n * registry first would set a prototype and create no own key at all, so\n * hydration's own enumeration would never see it — the rule has to be applied\n * at the first boundary that reads the key.\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(\n issues,\n path,\n \"J005\",\n `${what} '${key}' is not a valid schema identifier`\n );\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\n/**\n * Read a document from JSON text or a caller-built object.\n *\n * Every shape issue in the whole artifact is collected, then thrown once. What\n * comes back is the document the author wrote — not yet a schema: `interpret`\n * turns it into models.\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 document version ${renderValue(version)}; this parser reads 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 const enums = readEnums(node, issues);\n if (enums !== undefined) document.enums = enums;\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 // `JSON.parse` answers a `SyntaxError` naming the offset it stopped at.\n addIssue(\n issues,\n documentRoot,\n \"J001\",\n `The document is not valid JSON: ${String(thrown)}`\n );\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 if (record === undefined) return;\n const enums: Record<string, EnumDocument> = {};\n for (const key of inspectKeys(record, path, issues, \"J004\")) {\n const entryPath = pointer(path, key);\n if (!refuseInvalidKey(key, entryPath, issues, \"Enum reference\")) continue;\n const definition = readEnumNode(\n member(record, key, path, issues),\n entryPath,\n issues\n );\n if (definition !== undefined) enums[key] = definition;\n }\n return enums;\n}\n\nfunction readEnumNode(\n value: unknown,\n path: string,\n issues: DocumentIssues\n): EnumDocument | undefined {\n const node = asRecord(value, path, issues, \"An 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 = member(node, \"name\", path, issues);\n if (name !== undefined) {\n const text = asString(name, pointer(path, \"name\"), issues, \"`name`\");\n if (text !== undefined) definition.name = text;\n }\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 models: Record<string, ModelDocument> = {};\n const record = asRecord(\n member(node, \"models\", documentRoot, issues),\n path,\n issues,\n \"`models`\"\n );\n if (record === undefined) return models;\n for (const key of inspectKeys(record, path, issues, \"J004\")) {\n const modelPath = pointer(path, key);\n if (!refuseInvalidKey(key, modelPath, issues, \"Model key\")) continue;\n const model = readModelNode(\n member(record, key, path, issues),\n modelPath,\n issues\n );\n if (model !== undefined) models[key] = model;\n }\n return models;\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, \"A 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 = member(node, \"table\", path, issues);\n if (table !== undefined) {\n const text = asString(table, pointer(path, \"table\"), issues, \"`table`\");\n if (text !== undefined) model.table = text;\n }\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 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 fields: Record<string, FieldDocument> = {};\n const record = asRecord(\n member(node, \"fields\", modelPath, issues),\n path,\n issues,\n \"`fields`\"\n );\n if (record === undefined) return fields;\n for (const key of inspectKeys(record, path, issues, \"J004\")) {\n const fieldPath = pointer(path, key);\n if (!refuseInvalidKey(key, fieldPath, issues, \"Field key\")) continue;\n const field = readFieldNode(\n member(record, key, path, issues),\n fieldPath,\n issues\n );\n if (field !== undefined) fields[key] = field;\n }\n return fields;\n}\n\nfunction readIndexes(\n node: Record<string, unknown>,\n modelPath: string,\n issues: DocumentIssues\n): IndexDocument[] | undefined {\n const path = pointer(modelPath, \"indexes\");\n const raw = member(node, \"indexes\", modelPath, issues);\n if (raw === undefined) return;\n if (!Array.isArray(raw)) {\n addIssue(issues, path, \"J004\", \"`indexes` must be an array\");\n return;\n }\n const indexes: IndexDocument[] = [];\n for (const [position, entry] of elements(raw, path, issues).entries()) {\n const index = readIndexNode(entry, pointer(path, String(position)), issues);\n if (index !== undefined) indexes.push(index);\n }\n return indexes;\n}\n\nfunction readIndexNode(\n value: unknown,\n path: string,\n issues: DocumentIssues\n): IndexDocument | undefined {\n const node = asRecord(value, path, issues, \"An index\");\n if (node === undefined) return;\n // `where` is a KNOWN key with its own refusal, not an unknown one: it exists\n // in the builder, and an author who spells it is told why v1 has no slot for\n // it rather than that the key does not exist.\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: it is raw SQL interpolated unescaped into DDL, and a machine-written document must not carry an execution channel. It returns when a structured predicate form exists\"\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 = member(node, \"name\", path, issues);\n if (name !== undefined) {\n const text = asString(name, pointer(path, \"name\"), issues, \"`name`\");\n if (text !== undefined) index.name = text;\n }\n const unique = member(node, \"unique\", path, issues);\n if (unique !== undefined) {\n const flag = asBoolean(unique, pointer(path, \"unique\"), issues, \"`unique`\");\n if (flag !== undefined) index.unique = flag;\n }\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 one of ${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 const path = pointer(modelPath, key);\n const raw = member(node, key, modelPath, 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 constraints: CompoundKeyDocument[] = [];\n for (const [position, entry] of elements(raw, path, issues).entries()) {\n const constraint = readCompoundKeyNode(\n entry,\n pointer(path, String(position)),\n issues\n );\n if (constraint !== undefined) constraints.push(constraint);\n }\n return constraints;\n}\n\nfunction readCompoundKeyNode(\n value: unknown,\n path: string,\n issues: DocumentIssues\n): CompoundKeyDocument | undefined {\n const node = asRecord(value, path, issues, \"A 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 = member(node, \"name\", path, issues);\n if (name !== undefined) {\n const text = asString(name, pointer(path, \"name\"), issues, \"`name`\");\n if (text !== undefined) constraint.name = text;\n }\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, \"A 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 one of ${renderKeys([...SCALAR_TYPE_NAMES])}`\n );\n // The node is still read for the keys no arm declares: an author who\n // misspelled `type` AND a modifier deserves both, in one pass.\n refuseUnknownKeys(node, ANY_FIELD_KEYS, path, issues, \"a field node\");\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 = member(node, \"column\", path, issues);\n if (column !== undefined) {\n const text = asString(column, pointer(path, \"column\"), issues, \"`column`\");\n if (text !== undefined) field.column = text;\n }\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` does not belong to a decimal field; its physical type is derived from `precision` and `scale`\"\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` does not belong to a decimal field; its physical type is derived from `precision` and `scale`\"\n : \"`native` and `nativeByDialect` are two spellings of one declaration; a field carries at most one\"\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\n/**\n * One half of a decimal's declared domain. The document carries the two numbers\n * verbatim. This reader owns their required presence and number representation;\n * `s.decimal` still owns whether the pair names a domain — integrality, range,\n * and `scale <= precision` — through the interpreter's construction boundary.\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 `A decimal field must declare \\`${key}\\``\n );\n return;\n }\n const bound = asNumber(value, pointer(path, key), issues, `\\`${key}\\``);\n return bound;\n}\n\n/** A fixed-decimal domain has no meaning on any other scalar arm. */\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}\\` belongs only to a field of type '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(\n issues,\n enumPath,\n \"J003\",\n \"`enum` belongs to a field of type 'enum'\"\n );\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(\n issues,\n enumPath,\n \"J004\",\n \"An enum field declares `enum` as an `enums` reference or an inline array of values\"\n );\n return;\n }\n if (typeof raw === \"string\") return { type, enum: raw };\n const values = asStringArray(raw, enumPath, issues, \"`enum`\");\n if (values === undefined) return;\n return { 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 `A 'point' field 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 one of ${renderKeys(NATIVE_DIALECTS)}`\n );\n return;\n }\n if (type === undefined) return;\n // The catalog is closed PER DIALECT: a value belongs only to the catalog of\n // its own `db`. `text` is a pg type, `TEXT` a mysql/sqlite one.\n if (!isNativeTypeInCatalog(db, type)) {\n addIssue(issues, pointer(path, \"type\"), \"J011\", nativeTypeRefusal(db));\n return;\n }\n return { db, type };\n}\n\n/**\n * A map by dialect. Its keys are the three dialects and each entry is a\n * `native` node of its own key's dialect; whether the map names any dialect at\n * all is the scalar factory's refusal, which `interpret.ts` locates here.\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 `The '${dialect}' entry's \\`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 one of ${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 \"An explicit generation choice belongs only to string identifier formats\"\n );\n } else if (flag !== undefined) declaration.generate = flag;\n }\n const prefix = member(node, \"prefix\", path, issues);\n if (prefix !== undefined) {\n const text = asString(prefix, pointer(path, \"prefix\"), issues, \"`prefix`\");\n if (text !== undefined) declaration.prefix = text;\n }\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 const implicit = member(node, \"implicit\", path, issues);\n if (implicit !== undefined) {\n const flag = asBoolean(\n implicit,\n pointer(path, \"implicit\"),\n issues,\n \"`implicit`\"\n );\n if (flag === true) {\n // `implicit` says \"this is the ULID `.id()` installs\". It describes ONE\n // declaration — that kind, on that flag — and either half missing makes\n // it a claim about a generator nothing installed. On another kind it\n // would silently drop that format's domain, its admission and its\n // compact column; without `id` the interpreter installs NOTHING at all\n // (its `.id()` arm needs the flag and its `applyGenerate` arm stands\n // down for an implicit node), so the declared generator vanishes and the\n // field round-trips back as a bare `{\"type\":\"string\"}`.\n if (kind !== \"ulid\") {\n addIssue(\n issues,\n pointer(path, \"implicit\"),\n \"J004\",\n '`generate.implicit` describes the ULID `.id()` installs, so it belongs only to `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` describes the ULID `.id()` installs, so it belongs only beside `id: true`\"\n );\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 \"A relation names exactly one target domain: `target` for one model, or `variants` for named 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 = readName(node, 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 readName(\n node: Record<string, unknown>,\n path: string,\n issues: DocumentIssues\n): string | undefined {\n const name = member(node, \"name\", path, issues);\n if (name === undefined) return;\n return asString(name, pointer(path, \"name\"), issues, \"`name`\");\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 one of ${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 = readVariantMap(\n relation.variants,\n pointer(path, \"variants\"),\n issues\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 = member(node, \"optional\", path, issues);\n if (optional !== undefined) {\n const flag = asBoolean(\n optional,\n pointer(path, \"optional\"),\n issues,\n \"`optional`\"\n );\n if (flag !== undefined) declaration.optional = flag;\n }\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 readVariantMap(\n value: unknown,\n path: string,\n issues: DocumentIssues\n): Record<string, string> | undefined {\n const record = asRecord(value, path, issues, \"`variants`\");\n if (record === undefined) return;\n const variants: Record<string, string> = {};\n for (const key of inspectKeys(record, path, issues, \"J004\")) {\n const entryPath = pointer(path, key);\n if (!refuseInvalidKey(key, entryPath, issues, \"Variant key\")) continue;\n const target = asString(\n member(record, key, path, issues),\n entryPath,\n issues,\n \"A variant target\"\n );\n if (target !== undefined) variants[key] = target;\n }\n return variants;\n}\n\n/**\n * A map keyed by variant, read into a fresh record.\n *\n * The identifier check is what stops a `__proto__` key from setting that\n * record's prototype instead of becoming an entry — the one thing the factory's\n * own exactness rule could then only report as a MISSING key.\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 if (record === undefined) return;\n const map: Record<string, string> = {};\n for (const key of inspectKeys(record, path, issues, \"J004\")) {\n const entryPath = pointer(path, key);\n if (!refuseInvalidKey(key, entryPath, issues, \"Variant key\")) continue;\n const text = asString(\n member(record, key, path, issues),\n entryPath,\n issues,\n what\n );\n if (text !== undefined) map[key] = text;\n }\n return map;\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 if (record === undefined) return;\n const map: Record<string, VariantJunctionDocument> = {};\n for (const key of inspectKeys(record, path, issues, \"J004\")) {\n const entryPath = pointer(path, key);\n if (!refuseInvalidKey(key, entryPath, issues, \"Variant key\")) continue;\n const override = readVariantJunctionNode(\n member(record, key, path, issues),\n entryPath,\n issues\n );\n if (override !== undefined) map[key] = override;\n }\n return map;\n}\n\nfunction readVariantJunctionNode(\n value: unknown,\n path: string,\n issues: DocumentIssues\n): VariantJunctionDocument | undefined {\n const node = asRecord(value, path, issues, \"A member junction\");\n if (node === undefined) return;\n refuseUnknownKeys(node, VARIANT_JUNCTION_KEYS, path, issues);\n const table = asString(\n member(node, \"table\", path, issues),\n pointer(path, \"table\"),\n issues,\n \"`table`\"\n );\n const source = asString(\n member(node, \"source\", path, issues),\n pointer(path, \"source\"),\n issues,\n \"`source`\"\n );\n const target = asString(\n member(node, \"target\", path, issues),\n pointer(path, \"target\"),\n issues,\n \"`target`\"\n );\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 // Trusted junction state is `AtLeastOne`: it stores an override only when one\n // was declared, so `{}` becomes no builder call at all and nothing downstream\n // could refuse it. The DECLARED keys decide, not the ones that survived\n // reading — a rejected value is a different failure, already reported.\n if (inspectKeys(node, path, issues, \"J004\").length === 0) {\n addIssue(\n issues,\n path,\n \"J004\",\n \"`junction` declares at least one of 'table', 'source', 'target', 'onDelete', 'onUpdate', 'onDeleteSides', 'onUpdateSides'; omit it to keep the derived defaults\"\n );\n return;\n }\n const names: JunctionNamesDocument = {};\n for (const key of [\"table\", \"source\", \"target\"] as const) {\n const raw = member(node, key, path, issues);\n if (raw === undefined) continue;\n const text = asString(raw, pointer(path, key), issues, `\\`${key}\\``);\n if (text !== undefined) names[key] = text;\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\n/**\n * One action's spelling: one action for both foreign keys (`onDelete`), or\n * one per side (`onDeleteSides`), never both.\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 `\\`${key}\\` and \\`${sidesKey}\\` are exclusive: one action for both foreign keys, or one per side`\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\n/** `{ source, target }`, both sides stated: an omitted side is not a default. */\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}\\` states both 'source' and 'target'; '${side}' is missing`\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 `A junction \\`${key}\\` must be one of ${renderKeys(Object.keys(JUNCTION_ACTIONS))}; 'setNull' cannot null a membership-key member`\n );\n return;\n}\n\n// =============================================================================\n// DOCUMENT-LOCAL REFERENCES\n// =============================================================================\n\n/**\n * The two references a document alone can resolve: a relation's target model\n * key, and an `omit` entry.\n *\n * A missing model key would otherwise reach the resolution gate as\n * `R006`/`P001` over a getter that answered `undefined`, with no document\n * location; an `omit` typo is refused only at the TYPE level in code, and a\n * machine-written document has no types — a silently ignored entry is a leaked\n * column. An `enums` reference belongs to the interpreter instead: that is the\n * first place that needs the definition, so nothing checks it twice.\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}\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 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(\n issues,\n path,\n \"J006\",\n `Model '${target}' is not declared in \\`models\\``\n );\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\\` names '${name}', which is not a scalar field of this model`\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}'; this call declares ${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 } 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 { 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 } 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} 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 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 modelsPath = pointer(documentRoot, \"models\");\n for (const [modelKey, model] of Object.entries(schema)) {\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 models,\n };\n if (Object.keys(enums.definitions).length > 0) {\n document.enums = enums.definitions;\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 = model[\"~\"].state;\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 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 // Canonical order: `omit` is a set spelled as an array.\n document.omit = Object.keys(state.omit).sort();\n }\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 \"This index carries a `where` predicate — raw SQL the v1 document refuses to carry. Drop the partial index or keep this schema in code\"\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 = scalar[\"~\"].state;\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 \"A fixed decimal cannot carry a native-type override\"\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 \"This field carries a custom `.schema()` validator — arbitrary code the document cannot hold. Re-attach it with `attachFieldSchemas`\"\n );\n }\n const literal = serializeDefault(state, path, issues);\n if (literal !== undefined) document.default = literal;\n return document;\n}\n\n/** A native-type map restated as document data, every entry copied. */\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 `A GeoPoint cannot carry a '${key}' declaration`\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 type '${name}' is declared with two different value sets; one database enum type holds one set`\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 \"This field carries a function default, which the document cannot hold. Use one of the nine `generate` kinds, a literal default, or a database default through `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 = relation[\"~\"].state;\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 );\n if (state.name !== undefined) document.name = state.name;\n return document;\n}\n\nfunction withModelTargetFacts(\n document: ModelTargetDocument,\n state: RelationState\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.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 const target = readTarget(getter, path);\n for (const [modelKey, model] of Object.entries(schema)) {\n if (model === target) return modelKey;\n }\n addIssue(\n issues,\n path,\n \"J006\",\n \"This relation targets a model that is not a member of the schema record being serialized\"\n );\n return \"\";\n}\n\n/**\n * Invoke one target getter. The factories admit only a function here, so the\n * one thing that can go wrong is the getter itself throwing — which a document\n * cannot describe, and which the caller is told about rather than handed as a\n * half-written model.\n */\nfunction readTarget(getter: Getter, path: string): unknown {\n try {\n return getter();\n } catch (thrown) {\n const issue: DocumentIssues = [];\n addIssue(\n issue,\n path,\n \"J006\",\n \"This relation's target getter threw; the schema cannot be serialized\"\n );\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} 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":"kwBA0CA,MAEM,EAAgB,KAChB,EAAgB,MAGtB,SAAgB,QAAQ,EAAgB,GAAG,EAAiC,CAC1E,IAAI,EAAO,EACX,IAAK,IAAM,KAAO,EAChB,GAAQ,IAAI,EAAI,QAAQ,EAAe,KAAK,CAAC,QAAQ,EAAe,KAAK,GAE3E,OAAO,EAeT,SAAgB,SACd,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,OACd,EACA,EACA,EACA,EACS,CACT,OAAO,aAAa,EAAQ,EAAK,EAAM,EAAQ,OAAO,CAoBxD,SAAgB,aACd,EACA,EACA,EACA,EACA,EACS,CACT,GAAI,CACF,OAAO,QAAQ,IAAI,EAAQ,EAAI,OACxB,EAAQ,CAEf,MADA,SAAS,EAAQ,QAAQ,EAAM,EAAI,CAAE,EAAM,2BAA2B,CAChE,eAAe,EAAQ,EAAQ,EAAO,CAAC,EAKjD,SAAgB,mBACd,EACA,EACA,EACA,EACkC,CAClC,GAAI,CACF,OAAO,EAAc,EAAM,OACpB,EAAQ,CAEf,MADA,SAAS,EAAQ,EAAM,EAAM,0CAA0C,CACjE,eAAe,EAAQ,EAAQ,EAAO,CAAC,EAKjD,SAAgB,YACd,EACA,EACA,EACA,EACU,CACV,GAAI,CACF,OAAO,EAAa,EAAO,OACpB,EAAQ,CAEf,MADA,SAAS,EAAQ,EA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MANA,SACE,EACA,EACA,OACA,uEACD,CACK,eAAe,EAAO,EAAQ,EAAO,CAAC,EAchD,SAAS,cACP,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,EC5nBtB,SAAgB,YAEd,EAAwB,EAAmD,CAC3E,IAAM,EAAW,mBAAmBE,EAAQ,CACtC,EAAS,UAAU,aAAa,EAAM,CAAC,CAE7C,OADI,GAAU,cAAc,EAAO,CAC5B,EAcT,SAAgB,mBACd,EACA,EACQ,CACR,OAAO,UAAU,aAAa,gBAAgB,EAAO,CAAC,CAAE,EAAa"}
|
|
1
|
+
{"version":3,"file":"json.mjs","names":["date","model","modelFactory","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 */\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\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, \"Reading this value threw\");\n throw refuseDocument(issues, toError(thrown));\n }\n}\n\n/** `isPlainRecord`, with a throwing `getPrototypeOf` trap owned as a refusal. */\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, \"Inspecting this value's prototype threw\");\n throw refuseDocument(issues, toError(thrown));\n }\n}\n\n/** `declaredKeys`, with a throwing `ownKeys` trap owned as a refusal. */\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, \"Enumerating this value's keys 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.\n//\n// A default is the only place a document holds a value from a domain the FIELD\n// chose rather than the 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}' (a decimal integer string), '${DATE_TAG}' (an ISO timestamp), '${BYTES_TAG}' (base64), '${RAW_TAG}' (the literal it wraps), '${JSON_NULL_TAG}' ('JsonNull' or 'DbNull')`;\n\n/**\n * The tag a record spells, if it spells one.\n *\n * Exactly one own key, beginning with `$`. Two keys is an ordinary object that\n * merely mentions a tag name, and is left alone in both directions.\n */\nfunction 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\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): JsonValue | undefined {\n return readValue(value, path, issues, new Set());\n}\n\nfunction readValue(\n value: unknown,\n path: string,\n issues: DocumentIssues,\n seen: Set<object>\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(issues, path, \"J004\", \"A default must be a finite number\");\n return;\n }\n if (Array.isArray(value)) return readArray(value, path, issues, seen);\n if (inspectPlainRecord(value, path, issues, \"J004\")) {\n return readRecord(value, path, issues, seen);\n }\n addIssue(\n issues,\n path,\n \"J004\",\n isFunction(value)\n ? \"A function default has no document spelling — use `generate`, a literal, or a database default through `native`\"\n : `A default must be a JSON value; a value outside JSON takes a tag — ${TAGS}`\n );\n return;\n}\n\nfunction readArray(\n value: readonly unknown[],\n path: string,\n issues: DocumentIssues,\n seen: Set<object>\n): JsonValue[] | undefined {\n if (enterCycle(value, path, issues, seen, \"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 seen\n );\n if (item === undefined) return;\n items.push(item);\n }\n seen.delete(value);\n return items;\n}\n\nfunction readRecord(\n value: Record<string, unknown>,\n path: string,\n issues: DocumentIssues,\n seen: Set<object>\n): Record<string, JsonValue> | undefined {\n if (enterCycle(value, path, issues, seen, \"J004\")) return;\n const keys = inspectKeys(value, path, issues, \"J004\");\n const tag = reservedKey(keys);\n if (tag !== undefined && !KNOWN_TAGS.has(tag)) {\n // An unknown `$`-tag is a DOCUMENT-shape fact, caught HERE during the\n // accumulating walk — so two bad tags in two fields both surface — rather\n // than at decode time, which is fail-fast. Payload well-formedness for a\n // KNOWN tag stays the decoder's, where a single default is being built.\n addIssue(\n issues,\n path,\n \"J008\",\n `'${tag}' is not a tag this format defines. The tags are ${TAGS}`\n );\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 seen\n );\n if (entry === undefined) return;\n put(record, key, entry);\n }\n 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 seen: Set<object>,\n code: \"J004\" | \"J009\"\n): boolean {\n if (!seen.has(value)) {\n seen.add(value);\n return false;\n }\n addIssue(\n issues,\n path,\n code,\n \"This default contains a cycle; a document holds a finite value\"\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): JsonValue | undefined {\n return encodeValue(value, path, issues, new Set());\n}\n\nfunction encodeValue(\n value: unknown,\n path: string,\n issues: DocumentIssues,\n seen: Set<object>\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(\n issues,\n path,\n \"A non-finite number has no JSON spelling; `JSON.stringify` would write it as `null`\"\n );\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(\n issues,\n path,\n \"This byte string has a detached buffer and cannot be serialized\"\n );\n }\n }\n if (isDate(value)) {\n if (Number.isNaN(Date.prototype.getTime.call(value))) {\n return refuseValue(issues, path, \"An invalid Date names no instant\");\n }\n return tagged(DATE_TAG, Date.prototype.toISOString.call(value));\n }\n if (Array.isArray(value)) return encodeArray(value, path, issues, seen);\n if (inspectPlainRecord(value, path, issues, \"J009\")) {\n return encodeRecord(value, path, issues, seen);\n }\n return refuseValue(\n issues,\n path,\n \"This default holds a value the document cannot state — a JSON value, a bigint, a Date or a byte string is what a default may be\"\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 seen: Set<object>\n): JsonValue[] | undefined {\n if (enterCycle(value, path, issues, seen, \"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 seen\n );\n if (item === undefined) return;\n items.push(item);\n }\n 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 seen: Set<object>\n): Record<string, JsonValue> | undefined {\n if (enterCycle(value, path, issues, seen, \"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 seen\n );\n if (entry === undefined) return;\n put(record, key, entry);\n }\n 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 * 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\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}\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/** The junction's physical names: its table and its two side tokens. */\nexport interface JunctionNamesDocument {\n table?: 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 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 ModelDocument,\n ModelTargetDocument,\n RelationFieldDocument,\n ScalarFieldDocument,\n SchemaDocument,\n VariantTargetDocument,\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\";\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 */\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 registry[modelKey] = buildModel(\n modelKey,\n modelDocument,\n document,\n registry,\n pointer(modelsPath, modelKey),\n fieldSchemas\n );\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}' does not name a scalar field of this schema; spell it '<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 for (const [position, index] of (document.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 model = call(indexPath, () =>\n Reflect.apply(model.index, model, [index.fields, indexOptions])\n );\n }\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 return model;\n}\n\nfunction options(name: string | undefined): { name?: string } {\n return name === undefined ? {} : { name };\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 if (document.array) {\n scalar = modify(scalar, \"array\", [], type, pointer(path, \"array\"));\n }\n if (document.nullable) {\n scalar = modify(scalar, \"nullable\", [], type, pointer(path, \"nullable\"));\n }\n if (document.id) {\n // An IMPLICIT generator is `.id()`'s own, prefix included: applying it here\n // is what keeps a key a key. Declaring the ULID separately afterwards would\n // NAME the format, which is a different field — a validated domain in a\n // compact column — so the generate node below stands down for it.\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 scalar = modify(scalar, \"id\", args, type, pointer(path, \"id\"));\n }\n if (document.unique) {\n scalar = modify(scalar, \"unique\", [], type, pointer(path, \"unique\"));\n }\n if (document.withoutTimezone) {\n scalar = modify(\n scalar,\n \"withoutTimezone\",\n [],\n type,\n pointer(path, \"withoutTimezone\")\n );\n }\n if (document.dimension !== undefined) {\n scalar = modify(\n scalar,\n \"dimension\",\n [document.dimension],\n type,\n pointer(path, \"dimension\")\n );\n }\n if (document.generate !== undefined && document.generate.implicit !== true) {\n scalar = applyGenerate(scalar, document.generate, type, path);\n }\n const literal = document.default;\n if (literal !== undefined) {\n scalar = applyDefault(scalar, document, literal, path);\n }\n if (document.column !== undefined) {\n scalar = modify(\n scalar,\n \"map\",\n [document.column],\n type,\n pointer(path, \"column\")\n );\n }\n if (fieldSchema !== undefined) {\n scalar = modify(\n scalar,\n \"schema\",\n [fieldSchema],\n type,\n pointer(path, \"schema\")\n );\n }\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 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 const issues: DocumentIssues = [];\n addIssue(\n issues,\n pointer(path, \"enum\"),\n \"J006\",\n `\\`enum\\` names '${reference}', which \\`enums\\` does not declare`\n );\n throw refuseDocument(issues);\n}\n\n/**\n * Apply one modifier BY NAME.\n *\n * The scalar class surface is the only table of which modifiers a type has, and\n * an absent method is exactly what \"this type has no such modifier\" means. Blob\n * refuses `array`/`id`/`unique` by throwing instead — a deliberate runtime\n * refusal — and that throw comes back as this node's own issue.\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 const issues: DocumentIssues = [];\n addIssue(\n issues,\n path,\n \"J007\",\n `A '${type}' field has no '${name}' modifier`\n );\n throw refuseDocument(issues);\n }\n return call(path, () => method.apply(scalar, args));\n}\n\n/**\n * `generate.kind` names the scalar method that installs the generator, so the\n * nine tokens are the nine methods.\n *\n * Whether that method TAKES a prefix or a length is read back from the state it\n * wrote rather than from a second arity table: a generator that ignored the\n * argument records nothing, and a declaration the builder cannot honor is\n * refused instead of silently dropped.\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 const issues: DocumentIssues = [];\n addIssue(\n issues,\n generatePath,\n \"J007\",\n `The '${generate.kind}' generator does not take the 'prefix' or 'length' this node declares`\n );\n throw refuseDocument(issues);\n}\n\n/**\n * A literal default, converted into the value the field's own domain holds.\n *\n * The codec owns the conversion — which tag denotes which domain, how deep it\n * reaches, and what a cycle costs. What is owned HERE is the check that follows\n * it: defaults BYPASS validation downstream — the create schema substitutes a\n * default without checking it — so a wrong-typed one is a late failure at bind\n * time. The field's own base schema is the single statement of its domain, and\n * checking against it here moves that failure to the document that wrote it.\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 // A bigint field also READS integer text, the spelling a JSON payload\n // carries; a default is the value the domain holds, so it stays tagged.\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 : 'a bigint is written {\"$bigint\": \"<integer>\"}';\n const issues: DocumentIssues = [];\n addIssue(\n issues,\n defaultPath,\n \"J008\",\n `A '${document.type}' default must be a value of the field's own domain: ${reason}`\n );\n throw refuseDocument(issues);\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, 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 five 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 [\"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 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](value)\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 { readDefaultValue } 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} 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\", \"enums\", \"models\"];\nconst ENUM_KEYS = [\"values\", \"name\"];\nconst MODEL_KEYS = [\"table\", \"fields\", \"indexes\", \"ids\", \"uniques\", \"omit\"];\nconst INDEX_KEYS = [\"fields\", \"name\", \"unique\", \"type\", \"where\"];\nconst COMPOUND_KEYS = [\"fields\", \"name\"];\nconst NATIVE_KEYS = [\"db\", \"type\"];\nconst GENERATE_KEYS = [\"kind\", \"prefix\", \"length\", \"implicit\", \"generate\"];\nconst JUNCTION_KEYS = [\n \"table\",\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 refuseUnknownKeys(\n record: Record<string, unknown>,\n allowed: readonly string[],\n path: string,\n issues: DocumentIssues,\n declarer = \"this node\"\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}'; ${declarer} declares ${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}' is \\`undefined\\`; a document omits an absent key rather than setting it to \\`undefined\\``\n );\n }\n }\n}\n\n/**\n * A key that names a model, a field, a variant or an enum definition.\n *\n * It runs BEFORE anything is constructed. `isValidSchemaIdentifier` already\n * owns the rule at hydration, but a `__proto__` model key assigned into the\n * registry first would set a prototype and create no own key at all, so\n * hydration's own enumeration would never see it — the rule has to be applied\n * at the first boundary that reads the key.\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(\n issues,\n path,\n \"J005\",\n `${what} '${key}' is not a valid schema identifier`\n );\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\n/**\n * Read a document from JSON text or a caller-built object.\n *\n * Every shape issue in the whole artifact is collected, then thrown once. What\n * comes back is the document the author wrote — not yet a schema: `interpret`\n * turns it into models.\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 document version ${renderValue(version)}; this parser reads 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 const enums = readEnums(node, issues);\n if (enums !== undefined) document.enums = enums;\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 // `JSON.parse` answers a `SyntaxError` naming the offset it stopped at.\n addIssue(\n issues,\n documentRoot,\n \"J001\",\n `The document is not valid JSON: ${String(thrown)}`\n );\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 if (record === undefined) return;\n const enums: Record<string, EnumDocument> = {};\n for (const key of inspectKeys(record, path, issues, \"J004\")) {\n const entryPath = pointer(path, key);\n if (!refuseInvalidKey(key, entryPath, issues, \"Enum reference\")) continue;\n const definition = readEnumNode(\n member(record, key, path, issues),\n entryPath,\n issues\n );\n if (definition !== undefined) enums[key] = definition;\n }\n return enums;\n}\n\nfunction readEnumNode(\n value: unknown,\n path: string,\n issues: DocumentIssues\n): EnumDocument | undefined {\n const node = asRecord(value, path, issues, \"An 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 = member(node, \"name\", path, issues);\n if (name !== undefined) {\n const text = asString(name, pointer(path, \"name\"), issues, \"`name`\");\n if (text !== undefined) definition.name = text;\n }\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 models: Record<string, ModelDocument> = {};\n const record = asRecord(\n member(node, \"models\", documentRoot, issues),\n path,\n issues,\n \"`models`\"\n );\n if (record === undefined) return models;\n for (const key of inspectKeys(record, path, issues, \"J004\")) {\n const modelPath = pointer(path, key);\n if (!refuseInvalidKey(key, modelPath, issues, \"Model key\")) continue;\n const model = readModelNode(\n member(record, key, path, issues),\n modelPath,\n issues\n );\n if (model !== undefined) models[key] = model;\n }\n return models;\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, \"A 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 = member(node, \"table\", path, issues);\n if (table !== undefined) {\n const text = asString(table, pointer(path, \"table\"), issues, \"`table`\");\n if (text !== undefined) model.table = text;\n }\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 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 fields: Record<string, FieldDocument> = {};\n const record = asRecord(\n member(node, \"fields\", modelPath, issues),\n path,\n issues,\n \"`fields`\"\n );\n if (record === undefined) return fields;\n for (const key of inspectKeys(record, path, issues, \"J004\")) {\n const fieldPath = pointer(path, key);\n if (!refuseInvalidKey(key, fieldPath, issues, \"Field key\")) continue;\n const field = readFieldNode(\n member(record, key, path, issues),\n fieldPath,\n issues\n );\n if (field !== undefined) fields[key] = field;\n }\n return fields;\n}\n\nfunction readIndexes(\n node: Record<string, unknown>,\n modelPath: string,\n issues: DocumentIssues\n): IndexDocument[] | undefined {\n const path = pointer(modelPath, \"indexes\");\n const raw = member(node, \"indexes\", modelPath, issues);\n if (raw === undefined) return;\n if (!Array.isArray(raw)) {\n addIssue(issues, path, \"J004\", \"`indexes` must be an array\");\n return;\n }\n const indexes: IndexDocument[] = [];\n for (const [position, entry] of elements(raw, path, issues).entries()) {\n const index = readIndexNode(entry, pointer(path, String(position)), issues);\n if (index !== undefined) indexes.push(index);\n }\n return indexes;\n}\n\nfunction readIndexNode(\n value: unknown,\n path: string,\n issues: DocumentIssues\n): IndexDocument | undefined {\n const node = asRecord(value, path, issues, \"An index\");\n if (node === undefined) return;\n // `where` is a KNOWN key with its own refusal, not an unknown one: it exists\n // in the builder, and an author who spells it is told why v1 has no slot for\n // it rather than that the key does not exist.\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: it is raw SQL interpolated unescaped into DDL, and a machine-written document must not carry an execution channel. It returns when a structured predicate form exists\"\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 = member(node, \"name\", path, issues);\n if (name !== undefined) {\n const text = asString(name, pointer(path, \"name\"), issues, \"`name`\");\n if (text !== undefined) index.name = text;\n }\n const unique = member(node, \"unique\", path, issues);\n if (unique !== undefined) {\n const flag = asBoolean(unique, pointer(path, \"unique\"), issues, \"`unique`\");\n if (flag !== undefined) index.unique = flag;\n }\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 one of ${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 const path = pointer(modelPath, key);\n const raw = member(node, key, modelPath, 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 constraints: CompoundKeyDocument[] = [];\n for (const [position, entry] of elements(raw, path, issues).entries()) {\n const constraint = readCompoundKeyNode(\n entry,\n pointer(path, String(position)),\n issues\n );\n if (constraint !== undefined) constraints.push(constraint);\n }\n return constraints;\n}\n\nfunction readCompoundKeyNode(\n value: unknown,\n path: string,\n issues: DocumentIssues\n): CompoundKeyDocument | undefined {\n const node = asRecord(value, path, issues, \"A 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 = member(node, \"name\", path, issues);\n if (name !== undefined) {\n const text = asString(name, pointer(path, \"name\"), issues, \"`name`\");\n if (text !== undefined) constraint.name = text;\n }\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, \"A 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 one of ${renderKeys([...SCALAR_TYPE_NAMES])}`\n );\n // The node is still read for the keys no arm declares: an author who\n // misspelled `type` AND a modifier deserves both, in one pass.\n refuseUnknownKeys(node, ANY_FIELD_KEYS, path, issues, \"a field node\");\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 = member(node, \"column\", path, issues);\n if (column !== undefined) {\n const text = asString(column, pointer(path, \"column\"), issues, \"`column`\");\n if (text !== undefined) field.column = text;\n }\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` does not belong to a decimal field; its physical type is derived from `precision` and `scale`\"\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` does not belong to a decimal field; its physical type is derived from `precision` and `scale`\"\n : \"`native` and `nativeByDialect` are two spellings of one declaration; a field carries at most one\"\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\n/**\n * One half of a decimal's declared domain. The document carries the two numbers\n * verbatim. This reader owns their required presence and number representation;\n * `s.decimal` still owns whether the pair names a domain — integrality, range,\n * and `scale <= precision` — through the interpreter's construction boundary.\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 `A decimal field must declare \\`${key}\\``\n );\n return;\n }\n const bound = asNumber(value, pointer(path, key), issues, `\\`${key}\\``);\n return bound;\n}\n\n/** A fixed-decimal domain has no meaning on any other scalar arm. */\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}\\` belongs only to a field of type '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(\n issues,\n enumPath,\n \"J003\",\n \"`enum` belongs to a field of type 'enum'\"\n );\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(\n issues,\n enumPath,\n \"J004\",\n \"An enum field declares `enum` as an `enums` reference or an inline array of values\"\n );\n return;\n }\n if (typeof raw === \"string\") return { type, enum: raw };\n const values = asStringArray(raw, enumPath, issues, \"`enum`\");\n if (values === undefined) return;\n return { 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 `A 'point' field 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 one of ${renderKeys(NATIVE_DIALECTS)}`\n );\n return;\n }\n if (type === undefined) return;\n // The catalog is closed PER DIALECT: a value belongs only to the catalog of\n // its own `db`. `text` is a pg type, `TEXT` a mysql/sqlite one.\n if (!isNativeTypeInCatalog(db, type)) {\n addIssue(issues, pointer(path, \"type\"), \"J011\", nativeTypeRefusal(db));\n return;\n }\n return { db, type };\n}\n\n/**\n * A map by dialect. Its keys are the three dialects and each entry is a\n * `native` node of its own key's dialect; whether the map names any dialect at\n * all is the scalar factory's refusal, which `interpret.ts` locates here.\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 `The '${dialect}' entry's \\`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 one of ${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 \"An explicit generation choice belongs only to string identifier formats\"\n );\n } else if (flag !== undefined) declaration.generate = flag;\n }\n const prefix = member(node, \"prefix\", path, issues);\n if (prefix !== undefined) {\n const text = asString(prefix, pointer(path, \"prefix\"), issues, \"`prefix`\");\n if (text !== undefined) declaration.prefix = text;\n }\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 const implicit = member(node, \"implicit\", path, issues);\n if (implicit !== undefined) {\n const flag = asBoolean(\n implicit,\n pointer(path, \"implicit\"),\n issues,\n \"`implicit`\"\n );\n if (flag === true) {\n // `implicit` says \"this is the ULID `.id()` installs\". It describes ONE\n // declaration — that kind, on that flag — and either half missing makes\n // it a claim about a generator nothing installed. On another kind it\n // would silently drop that format's domain, its admission and its\n // compact column; without `id` the interpreter installs NOTHING at all\n // (its `.id()` arm needs the flag and its `applyGenerate` arm stands\n // down for an implicit node), so the declared generator vanishes and the\n // field round-trips back as a bare `{\"type\":\"string\"}`.\n if (kind !== \"ulid\") {\n addIssue(\n issues,\n pointer(path, \"implicit\"),\n \"J004\",\n '`generate.implicit` describes the ULID `.id()` installs, so it belongs only to `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` describes the ULID `.id()` installs, so it belongs only beside `id: true`\"\n );\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 \"A relation names exactly one target domain: `target` for one model, or `variants` for named 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 = readName(node, 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 readName(\n node: Record<string, unknown>,\n path: string,\n issues: DocumentIssues\n): string | undefined {\n const name = member(node, \"name\", path, issues);\n if (name === undefined) return;\n return asString(name, pointer(path, \"name\"), issues, \"`name`\");\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 one of ${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 = readVariantMap(\n relation.variants,\n pointer(path, \"variants\"),\n issues\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 = member(node, \"optional\", path, issues);\n if (optional !== undefined) {\n const flag = asBoolean(\n optional,\n pointer(path, \"optional\"),\n issues,\n \"`optional`\"\n );\n if (flag !== undefined) declaration.optional = flag;\n }\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 readVariantMap(\n value: unknown,\n path: string,\n issues: DocumentIssues\n): Record<string, string> | undefined {\n const record = asRecord(value, path, issues, \"`variants`\");\n if (record === undefined) return;\n const variants: Record<string, string> = {};\n for (const key of inspectKeys(record, path, issues, \"J004\")) {\n const entryPath = pointer(path, key);\n if (!refuseInvalidKey(key, entryPath, issues, \"Variant key\")) continue;\n const target = asString(\n member(record, key, path, issues),\n entryPath,\n issues,\n \"A variant target\"\n );\n if (target !== undefined) variants[key] = target;\n }\n return variants;\n}\n\n/**\n * A map keyed by variant, read into a fresh record.\n *\n * The identifier check is what stops a `__proto__` key from setting that\n * record's prototype instead of becoming an entry — the one thing the factory's\n * own exactness rule could then only report as a MISSING key.\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 if (record === undefined) return;\n const map: Record<string, string> = {};\n for (const key of inspectKeys(record, path, issues, \"J004\")) {\n const entryPath = pointer(path, key);\n if (!refuseInvalidKey(key, entryPath, issues, \"Variant key\")) continue;\n const text = asString(\n member(record, key, path, issues),\n entryPath,\n issues,\n what\n );\n if (text !== undefined) map[key] = text;\n }\n return map;\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 if (record === undefined) return;\n const map: Record<string, VariantJunctionDocument> = {};\n for (const key of inspectKeys(record, path, issues, \"J004\")) {\n const entryPath = pointer(path, key);\n if (!refuseInvalidKey(key, entryPath, issues, \"Variant key\")) continue;\n const override = readVariantJunctionNode(\n member(record, key, path, issues),\n entryPath,\n issues\n );\n if (override !== undefined) map[key] = override;\n }\n return map;\n}\n\nfunction readVariantJunctionNode(\n value: unknown,\n path: string,\n issues: DocumentIssues\n): VariantJunctionDocument | undefined {\n const node = asRecord(value, path, issues, \"A member junction\");\n if (node === undefined) return;\n refuseUnknownKeys(node, VARIANT_JUNCTION_KEYS, path, issues);\n const table = asString(\n member(node, \"table\", path, issues),\n pointer(path, \"table\"),\n issues,\n \"`table`\"\n );\n const source = asString(\n member(node, \"source\", path, issues),\n pointer(path, \"source\"),\n issues,\n \"`source`\"\n );\n const target = asString(\n member(node, \"target\", path, issues),\n pointer(path, \"target\"),\n issues,\n \"`target`\"\n );\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 // Trusted junction state is `AtLeastOne`: it stores an override only when one\n // was declared, so `{}` becomes no builder call at all and nothing downstream\n // could refuse it. The DECLARED keys decide, not the ones that survived\n // reading — a rejected value is a different failure, already reported.\n if (inspectKeys(node, path, issues, \"J004\").length === 0) {\n addIssue(\n issues,\n path,\n \"J004\",\n \"`junction` declares at least one of 'table', 'source', 'target', 'onDelete', 'onUpdate', 'onDeleteSides', 'onUpdateSides'; omit it to keep the derived defaults\"\n );\n return;\n }\n const names: JunctionNamesDocument = {};\n for (const key of [\"table\", \"source\", \"target\"] as const) {\n const raw = member(node, key, path, issues);\n if (raw === undefined) continue;\n const text = asString(raw, pointer(path, key), issues, `\\`${key}\\``);\n if (text !== undefined) names[key] = text;\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\n/**\n * One action's spelling: one action for both foreign keys (`onDelete`), or\n * one per side (`onDeleteSides`), never both.\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 `\\`${key}\\` and \\`${sidesKey}\\` are exclusive: one action for both foreign keys, or one per side`\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\n/** `{ source, target }`, both sides stated: an omitted side is not a default. */\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}\\` states both 'source' and 'target'; '${side}' is missing`\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 `A junction \\`${key}\\` must be one of ${renderKeys(Object.keys(JUNCTION_ACTIONS))}; 'setNull' cannot null a membership-key member`\n );\n return;\n}\n\n// =============================================================================\n// DOCUMENT-LOCAL REFERENCES\n// =============================================================================\n\n/**\n * The two references a document alone can resolve: a relation's target model\n * key, and an `omit` entry.\n *\n * A missing model key would otherwise reach the resolution gate as\n * `R006`/`P001` over a getter that answered `undefined`, with no document\n * location; an `omit` typo is refused only at the TYPE level in code, and a\n * machine-written document has no types — a silently ignored entry is a leaked\n * column. An `enums` reference belongs to the interpreter instead: that is the\n * first place that needs the definition, so nothing checks it twice.\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}\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 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(\n issues,\n path,\n \"J006\",\n `Model '${target}' is not declared in \\`models\\``\n );\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\\` names '${name}', which is not a scalar field of this model`\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}'; this call declares ${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 } 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 { 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 } 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} 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 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 modelsPath = pointer(documentRoot, \"models\");\n for (const [modelKey, model] of Object.entries(schema)) {\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 models,\n };\n if (Object.keys(enums.definitions).length > 0) {\n document.enums = enums.definitions;\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 = model[\"~\"].state;\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 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 // Canonical order: `omit` is a set spelled as an array.\n document.omit = Object.keys(state.omit).sort();\n }\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 \"This index carries a `where` predicate — raw SQL the v1 document refuses to carry. Drop the partial index or keep this schema in code\"\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 = scalar[\"~\"].state;\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 \"A fixed decimal cannot carry a native-type override\"\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 \"This field carries a custom `.schema()` validator — arbitrary code the document cannot hold. Re-attach it with `attachFieldSchemas`\"\n );\n }\n const literal = serializeDefault(state, path, issues);\n if (literal !== undefined) document.default = literal;\n return document;\n}\n\n/** A native-type map restated as document data, every entry copied. */\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 `A GeoPoint cannot carry a '${key}' declaration`\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 type '${name}' is declared with two different value sets; one database enum type holds one set`\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 \"This field carries a function default, which the document cannot hold. Use one of the nine `generate` kinds, a literal default, or a database default through `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 = relation[\"~\"].state;\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 );\n if (state.name !== undefined) document.name = state.name;\n return document;\n}\n\nfunction withModelTargetFacts(\n document: ModelTargetDocument,\n state: RelationState\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.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 const target = readTarget(getter, path);\n for (const [modelKey, model] of Object.entries(schema)) {\n if (model === target) return modelKey;\n }\n addIssue(\n issues,\n path,\n \"J006\",\n \"This relation targets a model that is not a member of the schema record being serialized\"\n );\n return \"\";\n}\n\n/**\n * Invoke one target getter. The factories admit only a function here, so the\n * one thing that can go wrong is the getter itself throwing — which a document\n * cannot describe, and which the caller is told about rather than handed as a\n * half-written model.\n */\nfunction readTarget(getter: Getter, path: string): unknown {\n try {\n return getter();\n } catch (thrown) {\n const issue: DocumentIssues = [];\n addIssue(\n issue,\n path,\n \"J006\",\n \"This relation's target getter threw; the schema cannot be serialized\"\n );\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} 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":"kvBA0CA,MAEM,EAAgB,KAChB,EAAgB,MAGtB,SAAgB,QAAQ,EAAgB,GAAG,EAAiC,CAC1E,IAAI,EAAO,EACX,IAAK,IAAM,KAAO,EAChB,GAAQ,IAAI,EAAI,QAAQ,EAAe,KAAK,CAAC,QAAQ,EAAe,KAAK,GAE3E,OAAO,EAeT,SAAgB,SACd,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,OACd,EACA,EACA,EACA,EACS,CACT,OAAO,aAAa,EAAQ,EAAK,EAAM,EAAQ,OAAO,CAoBxD,SAAgB,aACd,EACA,EACA,EACA,EACA,EACS,CACT,GAAI,CACF,OAAO,QAAQ,IAAI,EAAQ,EAAI,OACxB,EAAQ,CAEf,MADA,SAA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