viborm 1.2.3 → 1.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +6 -1
- package/dist/{adapter-internals-n3Mf3css.mjs → adapter-internals-AGgQRu5t.mjs} +1 -1
- package/dist/{adapter-internals-n3Mf3css.mjs.map → adapter-internals-AGgQRu5t.mjs.map} +1 -1
- package/dist/adapter-namespace-BpMbLKpL.mjs +2 -0
- package/dist/{adapter-namespace-DqkJQdrD.mjs.map → adapter-namespace-BpMbLKpL.mjs.map} +1 -1
- package/dist/adapters.d.mts +1 -1
- package/dist/adapters.mjs +1 -1
- package/dist/{array-literal-BsbbSLw3.mjs → array-literal-BKdLfNzM.mjs} +1 -1
- package/dist/{array-literal-BsbbSLw3.mjs.map → array-literal-BKdLfNzM.mjs.map} +1 -1
- package/dist/{base-AdXAoy6l.mjs → base-D3m1S7Uc.mjs} +2 -2
- package/dist/{base-AdXAoy6l.mjs.map → base-D3m1S7Uc.mjs.map} +1 -1
- package/dist/{batch-refs-4L8ECdPU.mjs → batch-refs-B4zn-FAu.mjs} +2 -2
- package/dist/{batch-refs-4L8ECdPU.mjs.map → batch-refs-B4zn-FAu.mjs.map} +1 -1
- package/dist/{bind-parameter-capacity-CjPgqnmx.mjs → bind-parameter-capacity-qfEejeOX.mjs} +2 -2
- package/dist/{bind-parameter-capacity-CjPgqnmx.mjs.map → bind-parameter-capacity-qfEejeOX.mjs.map} +1 -1
- package/dist/builder-Df24l2Bd.mjs +2 -0
- package/dist/builder-Df24l2Bd.mjs.map +1 -0
- package/dist/bun-sql.d.mts +3 -1
- package/dist/bun-sql.mjs +1 -1
- package/dist/bun-sql.mjs.map +1 -1
- package/dist/bun-sqlite.d.mts +1 -1
- package/dist/bun-sqlite.mjs +1 -1
- package/dist/cache/cloudflare-kv.d.mts +1 -1
- package/dist/cache/cloudflare-kv.mjs +1 -1
- package/dist/cache/memory.d.mts +1 -1
- package/dist/cache/memory.mjs +1 -1
- package/dist/{cache-BO57X0TT.mjs → cache-CIPRF-pz.mjs} +2 -2
- package/dist/{cache-BO57X0TT.mjs.map → cache-CIPRF-pz.mjs.map} +1 -1
- package/dist/cache.d.mts +1 -1
- package/dist/cache.mjs +1 -1
- package/dist/cache.mjs.map +1 -1
- package/dist/{canonical-json-rfC2Dg0X.mjs → canonical-json-BReb5nFO.mjs} +2 -2
- package/dist/{canonical-json-rfC2Dg0X.mjs.map → canonical-json-BReb5nFO.mjs.map} +1 -1
- package/dist/chain-C7c1YTXD.mjs +2 -0
- package/dist/chain-C7c1YTXD.mjs.map +1 -0
- package/dist/cli.mjs +2 -2
- package/dist/cli.mjs.map +1 -1
- package/dist/{client-GoDZgqdq.d.mts → client-70MrTq1E.d.mts} +3 -3
- package/dist/client-DM1UHfYG.mjs +49 -0
- package/dist/client-DM1UHfYG.mjs.map +1 -0
- package/dist/client-_WKrPNmm.mjs +2 -0
- package/dist/client-_WKrPNmm.mjs.map +1 -0
- package/dist/client.d.mts +2 -2
- package/dist/client.mjs +1 -1
- package/dist/{clock-CK41KO7t.mjs → clock-C24RcpwO.mjs} +1 -1
- package/dist/{clock-CK41KO7t.mjs.map → clock-C24RcpwO.mjs.map} +1 -1
- package/dist/config.d.mts +2 -2
- package/dist/config.mjs +1 -1
- package/dist/controls-Da-efekX.mjs +2 -0
- package/dist/controls-Da-efekX.mjs.map +1 -0
- package/dist/{current-DyzK6OCh.mjs → current-oXcxSCBQ.mjs} +1 -1
- package/dist/{current-DyzK6OCh.mjs.map → current-oXcxSCBQ.mjs.map} +1 -1
- package/dist/d1.d.mts +1 -1
- package/dist/d1.mjs +1 -1
- package/dist/d1.mjs.map +1 -1
- package/dist/{datetime-physical-codec-oIhiYZEP.mjs → datetime-physical-codec-BEqQbIP_.mjs} +2 -2
- package/dist/{datetime-physical-codec-oIhiYZEP.mjs.map → datetime-physical-codec-BEqQbIP_.mjs.map} +1 -1
- package/dist/driver-B9fIori_.mjs +2 -0
- package/dist/driver-B9fIori_.mjs.map +1 -0
- package/dist/{driver-B19QlFqn.mjs → driver-CPD0Xxw2.mjs} +2 -2
- package/dist/{driver-B19QlFqn.mjs.map → driver-CPD0Xxw2.mjs.map} +1 -1
- package/dist/driver.d.mts +1 -1
- package/dist/driver.mjs +1 -1
- package/dist/error-mapping-C9WgitPi.mjs +2 -0
- package/dist/error-mapping-C9WgitPi.mjs.map +1 -0
- package/dist/every-1pKZteeB.mjs +2 -0
- package/dist/{every-DCY4HV0X.mjs.map → every-1pKZteeB.mjs.map} +1 -1
- package/dist/{execution-context-BKR3bgES.mjs → execution-context-rJXTRVrJ.mjs} +1 -1
- package/dist/{execution-context-BKR3bgES.mjs.map → execution-context-rJXTRVrJ.mjs.map} +1 -1
- package/dist/{fs-estate-CAhDg7nY.mjs → fs-estate-i8Zlr1OQ.mjs} +2 -2
- package/dist/{fs-estate-CAhDg7nY.mjs.map → fs-estate-i8Zlr1OQ.mjs.map} +1 -1
- package/dist/{geo-area-codec-1SY9im7O.mjs → geo-area-codec-CbkmFArQ.mjs} +2 -2
- package/dist/{geo-area-codec-1SY9im7O.mjs.map → geo-area-codec-CbkmFArQ.mjs.map} +1 -1
- package/dist/geo-point-codec-DyEHMdJg.mjs +2 -0
- package/dist/geo-point-codec-DyEHMdJg.mjs.map +1 -0
- package/dist/hydration-DsyHNSDS.mjs +2 -0
- package/dist/{hydration-CAxOL4aI.mjs.map → hydration-DsyHNSDS.mjs.map} +1 -1
- package/dist/identifier-conversion-DaZ9yNpv.mjs +2 -0
- package/dist/{identifier-conversion-GgbwHc2G.mjs.map → identifier-conversion-DaZ9yNpv.mjs.map} +1 -1
- package/dist/{identity-CLFhCTZx.mjs → identity-oQvIe7u8.mjs} +2 -2
- package/dist/{identity-CLFhCTZx.mjs.map → identity-oQvIe7u8.mjs.map} +1 -1
- package/dist/{index-BaK35ze2.d.mts → index-VsM29vYN.d.mts} +5269 -4918
- package/dist/index.d.mts +3 -3
- package/dist/index.mjs +1 -1
- package/dist/index.mjs.map +1 -1
- package/dist/instrumentation.d.mts +1 -1
- package/dist/instrumentation.mjs +1 -1
- package/dist/{invariant-BnLYqsHO.mjs → invariant-D57gi_yW.mjs} +1 -1
- package/dist/{invariant-BnLYqsHO.mjs.map → invariant-D57gi_yW.mjs.map} +1 -1
- package/dist/{json-number-CGXpPu4D.mjs → json-number-DvmiNx0n.mjs} +1 -1
- package/dist/{json-number-CGXpPu4D.mjs.map → json-number-DvmiNx0n.mjs.map} +1 -1
- package/dist/key-D_kagnFv.mjs +2 -0
- package/dist/{key-BeoOwGr3.mjs.map → key-D_kagnFv.mjs.map} +1 -1
- package/dist/{libsql-x0RPVRDS.mjs → libsql-DFAoHXrI.mjs} +3 -3
- package/dist/{libsql-x0RPVRDS.mjs.map → libsql-DFAoHXrI.mjs.map} +1 -1
- package/dist/libsql.d.mts +1 -1
- package/dist/libsql.mjs +1 -1
- package/dist/{memory-gv5jLGYm.mjs → memory-GTWgeDNY.mjs} +2 -2
- package/dist/{memory-gv5jLGYm.mjs.map → memory-GTWgeDNY.mjs.map} +1 -1
- package/dist/migrations/mysql.d.mts +5 -5
- package/dist/migrations/mysql.mjs +1 -1
- package/dist/migrations/postgres.d.mts +5 -5
- package/dist/migrations/postgres.mjs +1 -1
- package/dist/migrations/sqlite.d.mts +5 -5
- package/dist/migrations/sqlite.mjs +1 -1
- package/dist/migrations/storage/durable-object.d.mts +1 -1
- package/dist/migrations/storage/durable-object.mjs +1 -1
- package/dist/migrations/storage/fs.d.mts +1 -1
- package/dist/migrations/storage/fs.mjs +1 -1
- package/dist/migrations/storage/r2.d.mts +1 -1
- package/dist/migrations/storage/r2.mjs +1 -1
- package/dist/migrations/tenant.d.mts +3 -3
- package/dist/migrations/tenant.mjs +1 -1
- package/dist/{migrations-DTObIjAm.mjs → migrations-Bn1SatyB.mjs} +2 -2
- package/dist/{migrations-DTObIjAm.mjs.map → migrations-Bn1SatyB.mjs.map} +1 -1
- package/dist/migrations.d.mts +5 -5
- package/dist/migrations.mjs +1 -1
- package/dist/mysql-adapter-C6c5govr.mjs +2 -0
- package/dist/{mysql-adapter-DkJPfoGf.mjs.map → mysql-adapter-C6c5govr.mjs.map} +1 -1
- package/dist/{mysql-B5cqxG99.mjs → mysql-xChEivOe.mjs} +6 -6
- package/dist/{mysql-B5cqxG99.mjs.map → mysql-xChEivOe.mjs.map} +1 -1
- package/dist/mysql2.d.mts +1 -1
- package/dist/mysql2.mjs +1 -1
- package/dist/{native-types-veeTk36s.mjs → native-types-asNCr26n.mjs} +1 -1
- package/dist/{native-types-veeTk36s.mjs.map → native-types-asNCr26n.mjs.map} +1 -1
- package/dist/neon-http.d.mts +3 -1
- package/dist/neon-http.mjs +1 -1
- package/dist/neon-http.mjs.map +1 -1
- package/dist/{object-store-DQR6bTBY.mjs → object-store-ChYHlOMD.mjs} +2 -2
- package/dist/{object-store-DQR6bTBY.mjs.map → object-store-ChYHlOMD.mjs.map} +1 -1
- package/dist/{object-store-Cj8Cnnba.d.mts → object-store-D9mvOHP4.d.mts} +4 -4
- package/dist/{observation-DUSm7oXK.mjs → observation-Co72iCd1.mjs} +2 -2
- package/dist/{observation-DUSm7oXK.mjs.map → observation-Co72iCd1.mjs.map} +1 -1
- package/dist/permissions.d.mts +424 -0
- package/dist/permissions.mjs +2 -0
- package/dist/permissions.mjs.map +1 -0
- package/dist/pg.d.mts +9 -1
- package/dist/pg.mjs +1 -1
- package/dist/pg.mjs.map +1 -1
- package/dist/pglite.d.mts +3 -1
- package/dist/pglite.mjs +1 -1
- package/dist/pglite.mjs.map +1 -1
- package/dist/{physical-6V_LNU3L.mjs → physical-CAOaNM4R.mjs} +2 -2
- package/dist/{physical-6V_LNU3L.mjs.map → physical-CAOaNM4R.mjs.map} +1 -1
- package/dist/{pinned-session-CLxj5M5e.mjs → pinned-session-BTplL3iZ.mjs} +2 -2
- package/dist/{pinned-session-CLxj5M5e.mjs.map → pinned-session-BTplL3iZ.mjs.map} +1 -1
- package/dist/planetscale.d.mts +1 -1
- package/dist/planetscale.mjs +1 -1
- package/dist/{planner-DH-K2gSq.d.mts → planner-C1NzLBge.d.mts} +1 -1
- package/dist/{postgres-DrXDok0O.mjs → postgres-BqAxDWTQ.mjs} +4 -4
- package/dist/{postgres-DrXDok0O.mjs.map → postgres-BqAxDWTQ.mjs.map} +1 -1
- package/dist/postgres-adapter-CGthb5yh.mjs +2 -0
- package/dist/postgres-adapter-CGthb5yh.mjs.map +1 -0
- package/dist/postgres-adapter-CxEit2-v.mjs +2 -0
- package/dist/postgres-adapter-CxEit2-v.mjs.map +1 -0
- package/dist/{postgres-result-7F0DllQe.mjs → postgres-result-KyBKBNJr.mjs} +2 -2
- package/dist/{postgres-result-7F0DllQe.mjs.map → postgres-result-KyBKBNJr.mjs.map} +1 -1
- package/dist/postgres.d.mts +3 -1
- package/dist/postgres.mjs +1 -1
- package/dist/postgres.mjs.map +1 -1
- package/dist/{provider-limits-BHATED_m.mjs → provider-limits-Da00ilvv.mjs} +2 -2
- package/dist/{provider-limits-BHATED_m.mjs.map → provider-limits-Da00ilvv.mjs.map} +1 -1
- package/dist/{result-parsing-DRXC89ek.mjs → result-parsing-8wEK3GY1.mjs} +1 -1
- package/dist/{result-parsing-DRXC89ek.mjs.map → result-parsing-8wEK3GY1.mjs.map} +1 -1
- package/dist/result-shape-CDgX_vzn.mjs +2 -0
- package/dist/result-shape-CDgX_vzn.mjs.map +1 -0
- package/dist/scalar-S8yMvdmx.mjs +4 -0
- package/dist/scalar-S8yMvdmx.mjs.map +1 -0
- package/dist/schema/json.d.mts +1 -1
- package/dist/schema/json.mjs +1 -1
- package/dist/schema/json.mjs.map +1 -1
- package/dist/schema-9N9jQlVL.mjs +2 -0
- package/dist/{schema-Cjem1-0f.mjs.map → schema-9N9jQlVL.mjs.map} +1 -1
- package/dist/{schema-introspection-DEYGC2qg.mjs → schema-introspection-CyXKReK1.mjs} +4 -4
- package/dist/{schema-introspection-DEYGC2qg.mjs.map → schema-introspection-CyXKReK1.mjs.map} +1 -1
- package/dist/schema.d.mts +1 -1
- package/dist/schema.mjs +1 -1
- package/dist/{select-assembly-f1UGoblh.mjs → select-assembly-CkGe2ABs.mjs} +2 -2
- package/dist/{select-assembly-f1UGoblh.mjs.map → select-assembly-CkGe2ABs.mjs.map} +1 -1
- package/dist/{settle-B9Vg1FnP.mjs → settle-CS_k6Ztm.mjs} +2 -2
- package/dist/{settle-B9Vg1FnP.mjs.map → settle-CS_k6Ztm.mjs.map} +1 -1
- package/dist/soft-delete.d.mts +27 -96
- package/dist/soft-delete.mjs +1 -1
- package/dist/soft-delete.mjs.map +1 -1
- package/dist/sql-Bhxq9arK.mjs +2 -0
- package/dist/sql-Bhxq9arK.mjs.map +1 -0
- package/dist/{sql-BvfwUKIh.d.mts → sql-EsoN_7Et.d.mts} +24 -0
- package/dist/{sql-statement-tokens-BBcoGmJb.mjs → sql-statement-tokens-CFi1y3bK.mjs} +1 -1
- package/dist/{sql-statement-tokens-BBcoGmJb.mjs.map → sql-statement-tokens-CFi1y3bK.mjs.map} +1 -1
- package/dist/sql.d.mts +1 -1
- package/dist/sql.mjs +1 -1
- package/dist/sqlite-adapter-BXAJy3mI.mjs +2 -0
- package/dist/sqlite-adapter-BXAJy3mI.mjs.map +1 -0
- package/dist/{sqlite-utils-DlgokMJN.mjs → sqlite-utils-D_cypcyW.mjs} +2 -2
- package/dist/{sqlite-utils-DlgokMJN.mjs.map → sqlite-utils-D_cypcyW.mjs.map} +1 -1
- package/dist/sqlite3.d.mts +3 -1
- package/dist/sqlite3.mjs +1 -1
- package/dist/sqlite3.mjs.map +1 -1
- package/dist/{standard-sql-Bk4RZPqJ.mjs → standard-sql-CoGqv-iX.mjs} +3 -3
- package/dist/standard-sql-CoGqv-iX.mjs.map +1 -0
- package/dist/{suppressed-failure-BwULh-8h.mjs → suppressed-failure-Bdo2aK81.mjs} +1 -1
- package/dist/{suppressed-failure-BwULh-8h.mjs.map → suppressed-failure-Bdo2aK81.mjs.map} +1 -1
- package/dist/to-many-C1PuFIpf.mjs +2 -0
- package/dist/to-many-C1PuFIpf.mjs.map +1 -0
- package/dist/{transaction-Bnl6ULTw.mjs → transaction-4dfqals6.mjs} +2 -2
- package/dist/{transaction-Bnl6ULTw.mjs.map → transaction-4dfqals6.mjs.map} +1 -1
- package/dist/{transaction-operation-CKK3l_9x.mjs → transaction-operation-CU1zlxiG.mjs} +2 -2
- package/dist/{transaction-operation-CKK3l_9x.mjs.map → transaction-operation-CU1zlxiG.mjs.map} +1 -1
- package/dist/{types-C4v6iAmY.mjs → types-C5Oxz9yp.mjs} +1 -1
- package/dist/{types-C4v6iAmY.mjs.map → types-C5Oxz9yp.mjs.map} +1 -1
- package/dist/{utils-CZNaOZR7.mjs → utils-CtFUE8UN.mjs} +4 -4
- package/dist/{utils-CZNaOZR7.mjs.map → utils-CtFUE8UN.mjs.map} +1 -1
- package/dist/v-CYTUI0H5.mjs +2 -0
- package/dist/v-CYTUI0H5.mjs.map +1 -0
- package/dist/validation-BQtO6srU.mjs +2 -0
- package/dist/{validation-PF9-_nKd.mjs.map → validation-BQtO6srU.mjs.map} +1 -1
- package/dist/validation-BamBwne9.mjs +2 -0
- package/dist/validation-BamBwne9.mjs.map +1 -0
- package/dist/validation.d.mts +1 -1
- package/dist/validation.mjs +1 -1
- package/dist/validator-DgffZq9C.mjs +2 -0
- package/dist/validator-DgffZq9C.mjs.map +1 -0
- package/dist/version-CXuJzC-q.mjs +2 -0
- package/dist/{version-Bemp-64P.mjs.map → version-CXuJzC-q.mjs.map} +1 -1
- package/package.json +35 -9
- package/dist/adapter-namespace-DqkJQdrD.mjs +0 -2
- package/dist/builder-Ycvq3ETg.mjs +0 -2
- package/dist/builder-Ycvq3ETg.mjs.map +0 -1
- package/dist/chain-Dh0FV72b.mjs +0 -2
- package/dist/chain-Dh0FV72b.mjs.map +0 -1
- package/dist/client-B1p6Le_h.mjs +0 -49
- package/dist/client-B1p6Le_h.mjs.map +0 -1
- package/dist/client-BLiBmykn.mjs +0 -2
- package/dist/client-BLiBmykn.mjs.map +0 -1
- package/dist/controls-DXgIn4zh.mjs +0 -2
- package/dist/controls-DXgIn4zh.mjs.map +0 -1
- package/dist/driver-BlnKXPFF.mjs +0 -2
- package/dist/driver-BlnKXPFF.mjs.map +0 -1
- package/dist/error-mapping-CnPCv1dm.mjs +0 -2
- package/dist/error-mapping-CnPCv1dm.mjs.map +0 -1
- package/dist/every-DCY4HV0X.mjs +0 -2
- package/dist/geo-point-codec-lhxH42SK.mjs +0 -2
- package/dist/geo-point-codec-lhxH42SK.mjs.map +0 -1
- package/dist/hydration-CAxOL4aI.mjs +0 -2
- package/dist/identifier-conversion-GgbwHc2G.mjs +0 -2
- package/dist/identifier-hQCs8M1n.mjs +0 -2
- package/dist/identifier-hQCs8M1n.mjs.map +0 -1
- package/dist/key-BeoOwGr3.mjs +0 -2
- package/dist/mysql-adapter-DkJPfoGf.mjs +0 -2
- package/dist/postgres-adapter-B3SQvcV1.mjs +0 -2
- package/dist/postgres-adapter-B3SQvcV1.mjs.map +0 -1
- package/dist/postgres-adapter-CQD2oGuD.mjs +0 -2
- package/dist/postgres-adapter-CQD2oGuD.mjs.map +0 -1
- package/dist/registration-preflight-DEjv050M.mjs +0 -4
- package/dist/registration-preflight-DEjv050M.mjs.map +0 -1
- package/dist/result-shape-CTNdNSW3.mjs +0 -2
- package/dist/result-shape-CTNdNSW3.mjs.map +0 -1
- package/dist/scalar-U0wD5bKy.mjs +0 -2
- package/dist/scalar-U0wD5bKy.mjs.map +0 -1
- package/dist/schema-Cjem1-0f.mjs +0 -2
- package/dist/sql-Bp7jicEX.mjs +0 -2
- package/dist/sql-Bp7jicEX.mjs.map +0 -1
- package/dist/sqlite-adapter-CW_3l6ea.mjs +0 -2
- package/dist/sqlite-adapter-CW_3l6ea.mjs.map +0 -1
- package/dist/standard-sql-Bk4RZPqJ.mjs.map +0 -1
- package/dist/terminal-C8cq1WWX.mjs +0 -2
- package/dist/terminal-C8cq1WWX.mjs.map +0 -1
- package/dist/v-D5Z06FKN.mjs +0 -2
- package/dist/v-D5Z06FKN.mjs.map +0 -1
- package/dist/validation-Dk9Q_-C7.mjs +0 -2
- package/dist/validation-Dk9Q_-C7.mjs.map +0 -1
- package/dist/validation-PF9-_nKd.mjs +0 -2
- package/dist/validator-X9-bwtRo.mjs +0 -2
- package/dist/validator-X9-bwtRo.mjs.map +0 -1
- package/dist/version-Bemp-64P.mjs +0 -2
- /package/dist/{contract-CIIqgFyb.d.mts → contract-Dw0FR78e.d.mts} +0 -0
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"client-B1p6Le_h.mjs","names":["refuse","factor","quote","refusalOf","refuse","refuse","actual","currentPk","desiredPk","droppedTable","quote","control","QUALIFIED","RENAME_TO","refusal","quote","refusal","present","resetFailure","value","refusal","result","table","namespace","namespace","epochMilliseconds","quote","matches","refusal","columns","members","getModelTableName","index","table","column","refuse","column","refusal","refusal","isResolveCallback","index","byName","refusal"],"sources":["../src/migrations/input-boundary.ts","../src/migrations/limits.ts","../src/adapters/databases/sqlite/storage/sql-lexing.ts","../src/adapters/databases/sqlite/storage/column-constraints.ts","../src/adapters/databases/sqlite/storage/geo-point.ts","../src/adapters/databases/sqlite/storage/decimal.ts","../src/migrations/decimal.ts","../src/migrations/drivers/type-mapping.ts","../src/migrations/native-rename.ts","../src/migrations/types.ts","../src/migrations/drop-order.ts","../src/migrations/utils.ts","../src/migrations/base64.ts","../src/migrations/v1-parse-shared.ts","../src/migrations/v1-parse-dispatch.ts","../src/migrations/v1-parse-control.ts","../src/migrations/v1-parse-snapshot.ts","../src/migrations/v1-parse.ts","../src/migrations/resolver.ts","../src/migrations/push/enum-removals.ts","../src/migrations/differ.ts","../src/migrations/catalog-probes.ts","../src/migrations/invert.ts","../src/migrations/sql-blob.ts","../src/migrations/statement-safety.ts","../src/migrations/compile.ts","../src/migrations/execute-dispatch.ts","../src/migrations/foreign-keys.ts","../src/migrations/pinned-session.ts","../src/migrations/push-fingerprint.ts","../src/migrations/drivers/postgres/catalog-refusal.ts","../src/migrations/control.ts","../src/migrations/target.ts","../src/migrations/binary-conversion.ts","../src/migrations/drivers/base.ts","../src/migrations/drivers/index.ts","../src/adapters/databases/sqlite/storage/datetime.ts","../src/migrations/sqlite-storage-audit.ts","../src/migrations/empty-snapshot.ts","../src/migrations/graph.ts","../src/migrations/push/format.ts","../src/migrations/admission.ts","../src/migrations/serializer.ts","../src/migrations/push/planner.ts","../src/migrations/live-reset.ts","../src/migrations/sql-assembly.ts","../src/migrations/push-plan.ts","../src/migrations/proof.ts","../src/migrations/resume.ts","../src/migrations/apply-v1.ts","../src/migrations/check.ts","../src/migrations/generate-input.ts","../src/migrations/public-view.ts","../src/migrations/push-consent.ts","../src/migrations/push-v1.ts","../src/migrations/generate-v1.ts","../src/migrations/down-input.ts","../src/migrations/reset-v1.ts","../src/migrations/operators.ts","../src/migrations/storage/contract.ts","../src/migrations/client.ts"],"sourcesContent":["/** Settles one hostile record into an exact immutable property snapshot. */\n\nimport { errorCause } from \"../errors/diagnostic-safety\";\n\ntype RefuseInput = (message: string, cause?: Error) => never;\n\nexport function snapshotExactRecord(\n value: unknown,\n allowed: readonly string[],\n label: string,\n refuse: RefuseInput\n): Readonly<Record<string, unknown>> {\n let objectValue: object | undefined;\n let keys: readonly PropertyKey[] = [];\n try {\n if (value !== null && typeof value === \"object\" && !Array.isArray(value)) {\n objectValue = value;\n keys = Reflect.ownKeys(value);\n }\n } catch (failure) {\n return refuse(`${label} could not be inspected`, errorCause(failure));\n }\n if (!objectValue) return refuse(`${label} must be an object`);\n const snapshot: Record<string, unknown> = {};\n for (const key of keys) {\n if (typeof key !== \"string\" || !allowed.includes(key)) {\n return refuse(`${label} contains unknown key ${String(key)}`);\n }\n try {\n snapshot[key] = Reflect.get(objectValue, key);\n } catch (failure) {\n return refuse(`${label}.${key} could not be read`, errorCause(failure));\n }\n }\n return Object.freeze(snapshot);\n}\n\nexport function snapshotExactArray(\n value: unknown,\n label: string,\n refuse: RefuseInput\n): readonly unknown[] {\n let entries: unknown[] | undefined;\n try {\n if (Array.isArray(value)) entries = Array.from(value);\n } catch (failure) {\n return refuse(`${label} could not be read`, errorCause(failure));\n }\n if (!entries) return refuse(`${label} must be an array`);\n return Object.freeze(entries);\n}\n","/**\n * The limits of one migration command (plans S1, T5a): their type, their\n * defaults and the one resolver. Only migration code imports this module, so\n * an application bundle carries none of it.\n */\n\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\nimport { snapshotExactRecord } from \"./input-boundary\";\n\n/**\n * The limits of one migration command's pinned session (plan S1), and the\n * table size it may rewrite in-request (plan T5a).\n *\n * Every value but `largeTableRows` is in milliseconds. `lockTimeout`, `statementTimeout` and\n * `idleTimeout` are PostgreSQL server settings, where 0 means \"no limit\";\n * `lockWait` and `connectionWait` are waits VibORM itself bounds. `lockWait`\n * also bounds SQLite's `BEGIN IMMEDIATE`, and `connectionWait` applies to\n * MySQL as well; the others, `largeTableRows` included, are PostgreSQL-only,\n * and MySQL keeps its fixed named-lock wait.\n */\nexport interface MigrationLimits {\n /**\n * `lock_timeout`, for the session and, with `SET LOCAL`, every migration\n * transaction: how long one DDL statement may queue for a table lock.\n */\n readonly lockTimeout?: number;\n /**\n * `statement_timeout`, for every migration transaction and for the session\n * around the lock and stepwise programs. 0, or longer than `lockWait`.\n */\n readonly statementTimeout?: number;\n /**\n * `idle_in_transaction_session_timeout` and, on PostgreSQL 14+,\n * `idle_session_timeout`: how long the server keeps a migration session\n * whose client stopped talking — the one that vanished holding the lock.\n * It also bounds the client's own pauses between two statements of a\n * command, so the default (30 s) frees a dead client's lock within half a\n * minute while a loaded client's pause between parts never ends the\n * session (1 s did, before 1.2.3).\n */\n readonly idleTimeout?: number;\n /** How long the command waits for the migration lock another one holds. */\n readonly lockWait?: number;\n /** How long the command waits for its pinned connection. */\n readonly connectionWait?: number;\n /**\n * A row count, not milliseconds: the planner's estimate above which a\n * statement that rewrites or scans a table under a lock that blocks it (a\n * column type change, `SET NOT NULL`, a volatile `ADD COLUMN` default, a\n * FOREIGN KEY or CHECK added without `NOT VALID`) is refused before any\n * effect, because it would hold that lock longer than a request should.\n * 0 admits every size.\n */\n readonly largeTableRows?: number;\n}\n\nexport type ResolvedMigrationLimits = Readonly<Required<MigrationLimits>>;\n\nexport const DEFAULT_MIGRATION_LIMITS: ResolvedMigrationLimits = Object.freeze({\n lockTimeout: 4000,\n statementTimeout: 600_000,\n idleTimeout: 30_000,\n lockWait: 10_000,\n connectionWait: 10_000,\n largeTableRows: 1_000_000,\n});\n\n/** The largest PostgreSQL timeout setting, and the largest timer delay. */\nconst MAX_TIME_LIMIT_MS = 2_147_483_647;\n\nconst LIMIT_KEYS = [\n \"lockTimeout\",\n \"statementTimeout\",\n \"idleTimeout\",\n \"lockWait\",\n \"connectionWait\",\n \"largeTableRows\",\n] as const satisfies readonly (keyof MigrationLimits)[];\n\n/**\n * The limits a migration client was given, settled once: each key a whole\n * number (milliseconds, rows for `largeTableRows`), the defaults filling in\n * the rest.\n *\n * `lockWait` and `connectionWait` are waits VibORM bounds and must be\n * positive; the server settings accept 0 (\"no limit\"). Every key stops at\n * {@link MAX_TIME_LIMIT_MS}, the most both PostgreSQL's settings and a timer\n * hold. A `statementTimeout` must outlast `lockWait`, which runs as one\n * statement under it.\n */\nexport function resolveMigrationLimits(\n input: unknown\n): ResolvedMigrationLimits {\n if (input === undefined) return DEFAULT_MIGRATION_LIMITS;\n const record = snapshotExactRecord(\n input,\n LIMIT_KEYS,\n \"migration limits\",\n refuseLimits\n );\n const limits: Record<(typeof LIMIT_KEYS)[number], number> = {\n ...DEFAULT_MIGRATION_LIMITS,\n };\n for (const key of LIMIT_KEYS) {\n const value = record[key];\n if (value === undefined) continue;\n const least = key === \"lockWait\" || key === \"connectionWait\" ? 1 : 0;\n if (\n typeof value !== \"number\" ||\n !Number.isInteger(value) ||\n value < least ||\n value > MAX_TIME_LIMIT_MS\n ) {\n refuseLimits(\n `migration limit ${key} must be a whole number of ${key === \"largeTableRows\" ? \"rows\" : \"milliseconds\"}, from ${least} to ${MAX_TIME_LIMIT_MS}`\n );\n }\n limits[key] = value;\n }\n if (\n limits.statementTimeout !== 0 &&\n limits.statementTimeout <= limits.lockWait\n ) {\n refuseLimits(\n `migration limit statementTimeout (${limits.statementTimeout} ms) must be 0 or longer than lockWait (${limits.lockWait} ms): the lock wait runs as one statement under it`\n );\n }\n return Object.freeze(limits);\n}\n\nfunction refuseLimits(message: string, cause?: Error): never {\n throw new MigrationError(message, VibORMErrorCode.INVALID_INPUT, { cause });\n}\n","/** SQLite token boundaries shared by stored-DDL readers. */\n\n/** An identifier token and where it ends. */\nexport interface SqliteIdentifierToken {\n readonly value: string;\n readonly quoted: boolean;\n readonly end: number;\n}\n\nconst IDENTIFIER_CLOSERS: Readonly<Record<string, string>> = {\n '\"': '\"',\n \"`\": \"`\",\n \"[\": \"]\",\n};\n\nconst BARE_IDENTIFIER_CHARACTER = /[A-Za-z0-9_$]/;\nconst WHITESPACE = /\\s/;\n\n/** Whether one character can occur in SQLite's bare identifier spelling. */\nexport function isSqliteBareIdentifierCharacter(character: string): boolean {\n return BARE_IDENTIFIER_CHARACTER.test(character);\n}\n\n/**\n * Read the identifier at or after `index`, in any of SQLite's four spellings.\n *\n * A doubled quote inside a `\"…\"` or a `` `…` `` token is an escaped one.\n */\nexport function readSqliteIdentifier(\n text: string,\n index: number\n): SqliteIdentifierToken | undefined {\n let cursor = index;\n while (cursor < text.length) {\n while (cursor < text.length && WHITESPACE.test(text.charAt(cursor))) {\n cursor++;\n }\n const isComment =\n (text[cursor] === \"-\" && text[cursor + 1] === \"-\") ||\n (text[cursor] === \"/\" && text[cursor + 1] === \"*\");\n if (!isComment) break;\n cursor = skipSqlNonStructuralRegion(text, cursor);\n }\n const opener = text[cursor];\n if (opener === undefined) return undefined;\n\n const closer = IDENTIFIER_CLOSERS[opener];\n if (closer !== undefined) {\n let value = \"\";\n cursor++;\n while (cursor < text.length) {\n if (text[cursor] === closer) {\n if (text[cursor + 1] === closer && closer !== \"]\") {\n value += closer;\n cursor += 2;\n continue;\n }\n return { value, quoted: true, end: cursor + 1 };\n }\n value += text[cursor];\n cursor++;\n }\n return undefined;\n }\n\n const start = cursor;\n while (\n cursor < text.length &&\n isSqliteBareIdentifierCharacter(text.charAt(cursor))\n ) {\n cursor++;\n }\n if (cursor === start) return undefined;\n return { value: text.slice(start, cursor), quoted: false, end: cursor };\n}\n\n/**\n * The offset just past the quoted token or SQL comment starting at `index`, or\n * `index` itself when structural SQL starts there.\n */\nexport function skipSqlNonStructuralRegion(\n text: string,\n index: number\n): number {\n const opener = text[index];\n if (opener === undefined) return index;\n if (opener === \"-\" && text[index + 1] === \"-\") {\n const end = text.indexOf(\"\\n\", index + 2);\n return end === -1 ? text.length : end;\n }\n if (opener === \"/\" && text[index + 1] === \"*\") {\n const end = text.indexOf(\"*/\", index + 2);\n return end === -1 ? text.length : end + 2;\n }\n const closer = opener === \"'\" ? \"'\" : IDENTIFIER_CLOSERS[opener];\n if (closer === undefined) return index;\n\n let cursor = index + 1;\n while (cursor < text.length) {\n if (text[cursor] === closer) {\n // A doubled quote is an escaped one, not the end of the token. `]` has\n // no escape in SQLite's bracket spelling.\n if (text[cursor + 1] === closer && closer !== \"]\") {\n cursor += 2;\n continue;\n }\n return cursor + 1;\n }\n cursor++;\n }\n return text.length;\n}\n","import {\n isSqliteBareIdentifierCharacter,\n readSqliteIdentifier,\n skipSqlNonStructuralRegion,\n} from \"./sql-lexing\";\n\n/** One top-level entry of a `CREATE TABLE` definition list. */\nexport interface SqliteTableDefinition {\n readonly text: string;\n /** The column this entry defines, or `undefined` for a table constraint. */\n readonly columnName: string | undefined;\n}\n\n/** A `CONSTRAINT <name>` at the top level of one definition. */\nexport interface SqliteConstraintClause {\n readonly name: string;\n /** Where the `CONSTRAINT` keyword starts inside the definition text. */\n readonly offset: number;\n}\n\n/** Keywords that open a table constraint rather than a column definition. */\nconst TABLE_CONSTRAINT_KEYWORDS = new Set([\n \"CONSTRAINT\",\n \"PRIMARY\",\n \"UNIQUE\",\n \"CHECK\",\n \"FOREIGN\",\n]);\n\n/**\n * Every top-level entry of the definition list, with the column each one\n * defines. Quoted tokens and comments are skipped before structural commas and\n * parentheses are interpreted.\n */\nexport function sqliteTableDefinitions(sql: string): SqliteTableDefinition[] {\n let open = -1;\n let scan = 0;\n while (scan < sql.length) {\n const skipped = skipSqlNonStructuralRegion(sql, scan);\n if (skipped !== scan) {\n scan = skipped;\n continue;\n }\n if (sql[scan] === \"(\") {\n open = scan;\n break;\n }\n scan++;\n }\n if (open === -1) return [];\n\n const definitions: SqliteTableDefinition[] = [];\n let depth = 1;\n let start = open + 1;\n let cursor = start;\n while (cursor < sql.length) {\n const skipped = skipSqlNonStructuralRegion(sql, cursor);\n if (skipped !== cursor) {\n cursor = skipped;\n continue;\n }\n const char = sql[cursor];\n if (char === \"(\") depth++;\n else if (char === \")\") {\n depth--;\n if (depth === 0) break;\n } else if (char === \",\" && depth === 1) {\n definitions.push(describeDefinition(sql.slice(start, cursor)));\n start = cursor + 1;\n }\n cursor++;\n }\n definitions.push(describeDefinition(sql.slice(start, cursor)));\n return definitions;\n}\n\nfunction describeDefinition(raw: string): SqliteTableDefinition {\n const text = raw.trim();\n const first = readSqliteIdentifier(text, 0);\n if (first === undefined) return { text, columnName: undefined };\n if (first.quoted) return { text, columnName: first.value };\n return {\n text,\n columnName: TABLE_CONSTRAINT_KEYWORDS.has(first.value.toUpperCase())\n ? undefined\n : first.value,\n };\n}\n\n/** Every structural `CONSTRAINT <name>` at depth zero of one definition. */\nexport function sqliteConstraintClauses(\n definition: string\n): SqliteConstraintClause[] {\n const clauses: SqliteConstraintClause[] = [];\n let depth = 0;\n let cursor = 0;\n while (cursor < definition.length) {\n const skipped = skipSqlNonStructuralRegion(definition, cursor);\n if (skipped !== cursor) {\n cursor = skipped;\n continue;\n }\n const char = definition.charAt(cursor);\n const word = isSqliteBareIdentifierCharacter(char)\n ? readSqliteIdentifier(definition, cursor)\n : undefined;\n if (word !== undefined) {\n if (depth === 0 && word.value.toUpperCase() === \"CONSTRAINT\") {\n const name = readSqliteIdentifier(definition, word.end);\n if (name) {\n clauses.push({ name: name.value, offset: cursor });\n cursor = name.end;\n continue;\n }\n }\n cursor = word.end;\n continue;\n }\n if (char === \"(\") depth++;\n else if (char === \")\") depth--;\n cursor++;\n }\n return clauses;\n}\n\n/** Structural keywords outside expression bodies, quoted tokens and comments. */\nexport function sqliteDefinitionKeywords(definition: string): string[] {\n const words: string[] = [];\n let depth = 0;\n let cursor = 0;\n while (cursor < definition.length) {\n const skipped = skipSqlNonStructuralRegion(definition, cursor);\n if (skipped !== cursor) {\n cursor = skipped;\n continue;\n }\n const word = readSqliteIdentifier(definition, cursor);\n if (word && !word.quoted) {\n if (depth === 0) words.push(word.value.toUpperCase());\n cursor = word.end;\n continue;\n }\n if (definition[cursor] === \"(\") depth++;\n else if (definition[cursor] === \")\") depth--;\n cursor++;\n }\n return words;\n}\n","import { MigrationError, VibORMErrorCode } from \"../../../../errors\";\nimport {\n GEO_LATITUDE_MAX,\n GEO_LATITUDE_MIN,\n GEO_LONGITUDE_MAX,\n GEO_LONGITUDE_MIN,\n} from \"../../../../validation/primitives/geo-values\";\nimport { sqliteBinary64JsonNumber } from \"./json-number\";\n\ninterface PhysicalColumn {\n readonly name: string;\n readonly type: string;\n readonly nullable: boolean;\n}\n\nimport {\n sqliteConstraintClauses,\n sqliteTableDefinitions,\n} from \"./column-constraints\";\n\n/** TEXT-affinity spelling reserved for VibORM's canonical GeoPoint carrier. */\nexport const SQLITE_GEO_POINT_TYPE = \"VIBORM_GEO_TEXT\";\n\n/** Fixed so a native column rename cannot stale the constraint identity. */\nconst SQLITE_GEO_POINT_CONSTRAINT = \"viborm_geo\";\n\n/** The complete writer-owned column constraint for one GeoPoint carrier. */\nexport function sqliteGeoPointCheck(\n column: Pick<PhysicalColumn, \"name\" | \"nullable\">,\n escapeIdentifier: (name: string) => string,\n encoding: \"legacy\" | \"binary64\" = \"binary64\"\n): string {\n const col = escapeIdentifier(column.name);\n const longitude = `json_extract(${col}, '$.longitude')`;\n const latitude = `json_extract(${col}, '$.latitude')`;\n const valid =\n `CASE WHEN typeof(${col}) = 'text' AND json_valid(${col}) THEN (` +\n `json_type(${col}) = 'object' AND ` +\n `json_type(${col}, '$.longitude') IN ('integer', 'real') AND ` +\n `json_type(${col}, '$.latitude') IN ('integer', 'real') AND ` +\n `${longitude} > ${GEO_LONGITUDE_MIN} AND ${longitude} <= ${GEO_LONGITUDE_MAX} AND ` +\n `${latitude} >= ${GEO_LATITUDE_MIN} AND ${latitude} <= ${GEO_LATITUDE_MAX} AND ` +\n `${col} = ${sqliteGeoPointCarrier(col, encoding)}` +\n \") ELSE 0 END\";\n const body = column.nullable ? `${col} IS NULL OR (${valid})` : valid;\n return `CONSTRAINT ${escapeIdentifier(SQLITE_GEO_POINT_CONSTRAINT)} CHECK (${body})`;\n}\n\n/**\n * Proves that SQLite's reserved declared type is paired with the exact\n * writer-owned constraint. A reserved type without its proof is refused rather\n * than published as a GeoPoint or silently normalized into one.\n */\nexport function readSqliteGeoPointColumn(\n tableSql: string | null | undefined,\n column: Pick<PhysicalColumn, \"name\" | \"type\" | \"nullable\">,\n escapeIdentifier: (name: string) => string\n): \"legacy\" | \"binary64\" | undefined {\n if (column.type.toUpperCase() !== SQLITE_GEO_POINT_TYPE) return undefined;\n const expected = sqliteGeoPointCheck(column, escapeIdentifier);\n const legacy = sqliteGeoPointCheck(column, escapeIdentifier, \"legacy\");\n let encoding: \"legacy\" | \"binary64\" = \"binary64\";\n let matching = 0;\n for (const definition of sqliteTableDefinitions(tableSql ?? \"\")) {\n if (definition.columnName !== column.name) continue;\n for (const clause of sqliteConstraintClauses(definition.text)) {\n if (clause.name !== SQLITE_GEO_POINT_CONSTRAINT) continue;\n if (definition.text.startsWith(expected, clause.offset))\n encoding = \"binary64\";\n else if (definition.text.startsWith(legacy, clause.offset))\n encoding = \"legacy\";\n else refuseUnprovenGeoPoint(column);\n matching++;\n }\n }\n if (matching !== 1) refuseUnprovenGeoPoint(column);\n return encoding;\n}\n\nfunction refuseUnprovenGeoPoint(\n column: Pick<PhysicalColumn, \"name\" | \"type\">\n): never {\n throw new MigrationError(\n `SQLite column \"${column.name}\" uses VibORM's reserved GeoPoint type \"${column.type}\" without the exact canonical GeoPoint CHECK constraint. ` +\n \"Migration introspection is refused rather than treating an unproven JSON carrier as a GeoPoint.\",\n VibORMErrorCode.MIGRATION_INVALID_STATE,\n {\n meta: {\n dialect: \"sqlite\",\n column: column.name,\n type: column.type,\n },\n }\n );\n}\n\n/** Copying legacy storage preserves the double still present, not earlier lost digits. */\nexport function sqliteGeoPointCarrier(\n source: string,\n encoding: \"legacy\" | \"binary64\" = \"binary64\"\n): string {\n const longitude = `json_extract(${source}, '$.longitude')`;\n const latitude = `json_extract(${source}, '$.latitude')`;\n return `json_object('longitude', ${encoding === \"legacy\" ? longitude : sqliteBinary64JsonNumber(longitude)}, 'latitude', ${encoding === \"legacy\" ? latitude : sqliteBinary64JsonNumber(latitude)})`;\n}\n\n/** Format-1 snapshots predating the precision annotation describe the legacy CHECK. */\nexport function sqliteGeoPointEncoding(column: {\n readonly type: string;\n readonly geoPointEncoding?: \"legacy\" | \"binary64\" | undefined;\n}): \"legacy\" | \"binary64\" | undefined {\n return column.type.toUpperCase() === SQLITE_GEO_POINT_TYPE\n ? (column.geoPointEncoding ?? \"legacy\")\n : undefined;\n}\n","/**\n * SQLite fixed-decimal migration storage.\n *\n * SQLite cannot carry a decimal descriptor in its declared storage type, so\n * this module owns the reserved CHECK carrier, its structural reader, and the\n * exact table-rebuild expressions that rescale scalar and list coefficients.\n */\n\nimport { MigrationError, VibORMErrorCode } from \"../../../../errors\";\nimport {\n type DecimalDescriptor,\n decimalColumnType,\n describeDecimalDomain,\n readStoredDecimalDescriptor,\n sameDecimalDescriptor,\n} from \"../../../../validation/primitives/decimal-codec\";\nexport type DecimalStorageKind = \"scalar\" | \"list\";\ninterface PhysicalColumn {\n readonly name: string;\n readonly type: string;\n readonly nullable: boolean;\n readonly decimal?: DecimalDescriptor | undefined;\n}\nexport function sqliteDecimalStorageKind(\n column: Pick<PhysicalColumn, \"type\" | \"decimal\">\n): DecimalStorageKind | undefined {\n if (column.decimal === undefined) return undefined;\n const type = column.type.toUpperCase();\n if (type === decimalColumnType(\"sqlite\", column.decimal)) return \"scalar\";\n return type === \"TEXT\" ? \"list\" : undefined;\n}\n\nimport {\n type SqliteConstraintClause,\n type SqliteTableDefinition,\n sqliteConstraintClauses,\n sqliteTableDefinitions,\n} from \"./column-constraints\";\n\n/**\n * The reserved SQLite constraint name for one decimal column.\n *\n * SQLite's declared type is the wrong carrier twice over: it stores `INTEGER`\n * (or `TEXT` for a list) whatever the domain is, and a CHECK written INTO the\n * type string never reads back — `PRAGMA table_info.type` reports only the\n * `type-name` production, so the desired `TEXT CHECK(...)` can never equal the\n * introspected `TEXT` and a full table recreation is planned on every push,\n * forever. (That is measured behaviour of the enum column type, not a\n * hypothetical.) So the descriptor rides in a NAMED constraint, and\n * introspection recovers it from the name.\n */\nexport function sqliteDecimalConstraintName(\n columnName: string,\n descriptor: DecimalDescriptor\n): string {\n return `viborm_decimal_${columnName}_${descriptor.precision}_${descriptor.scale}`;\n}\n\n/** The namespace VibORM reserves for the constraints it writes itself. */\nconst RESERVED_CONSTRAINT_PREFIX = \"viborm_decimal_\";\n\n/** `<precision>_<scale>`: what follows the column name in a reserved name. */\nconst RESERVED_CONSTRAINT_TAIL = /^(\\d+)_(\\d+)$/;\n\n/**\n * The declared domain of one column, read back out of the `CREATE TABLE` text\n * SQLite stored — or `undefined` when this column carries no reserved\n * constraint. The matching PRAGMA type and nullability travel with the column:\n * the stored clause is owned only when it is the exact writer rendering for\n * those physical facts.\n *\n * This PARSES, it does not search. The name alone is not evidence: SQLite\n * stores the statement verbatim, so any string literal a user can write — an\n * enum value, a string default, an index predicate — appears in the same text\n * and can spell VibORM's reserved prefix. A first-hit substring scan therefore\n * reads a user's data as a descriptor, and with an earlier offset it OVERRIDES\n * the real constraint: the next push plans a conversion between two domains\n * neither side declared and rewrites every stored coefficient. So the reader\n * walks the column-definition list the same quote-aware way\n * `partialIndexPredicate` walks a `CREATE INDEX` (`introspect.ts`), finds real\n * `CONSTRAINT <name> CHECK (…)` clauses, and binds each to the column definition\n * it actually sits in.\n *\n * A reserved name the module could not have written is REFUSED, not ignored.\n * Ignoring it is not the safe reading: the name is in a namespace only this\n * module writes, so its presence means either a corrupted carrier or a\n * collision, and both make every later push either wrong (a conversion between\n * invented domains) or non-convergent (a descriptor the desired side can never\n * match). The refusal names the constraint so the estate can be repaired.\n *\n * Ownership is proved by RE-RENDERING: the clause must be, byte for byte, what\n * {@link sqliteDecimalCheck} would emit for this column at the descriptor the\n * name declares. That is the only test that cannot be forged by a name alone,\n * and it is exact because SQLite re-spells nothing it stores.\n */\nexport function readSqliteDecimalConstraint(\n tableSql: string | null | undefined,\n column: Pick<PhysicalColumn, \"name\" | \"type\" | \"nullable\">,\n escapeIdentifier: (name: string) => string\n): DecimalDescriptor | undefined {\n if (!tableSql) return undefined;\n // The reserved namespace has to appear at all before the statement is worth\n // parsing: introspection reads every column of every table, and the\n // overwhelming majority carry no decimal.\n if (!tableSql.includes(RESERVED_CONSTRAINT_PREFIX)) return undefined;\n\n let found: DecimalDescriptor | undefined;\n for (const definition of sqliteTableDefinitions(tableSql)) {\n for (const clause of sqliteConstraintClauses(definition.text)) {\n if (!clause.name.startsWith(RESERVED_CONSTRAINT_PREFIX)) continue;\n // This reader is invoked once for every PRAGMA column. A reserved\n // column constraint is adjudicated when its own physical column is in\n // hand, because only that invocation knows the type and nullability the\n // database actually reported. TABLE constraints have no such invocation\n // and are always namespace squatters.\n if (\n definition.columnName !== undefined &&\n definition.columnName !== column.name\n ) {\n continue;\n }\n const descriptor = ownedDescriptor(\n definition,\n clause,\n column,\n escapeIdentifier\n );\n if (descriptor === undefined) {\n throw new MigrationError(\n `The stored definition carries a constraint named \"${clause.name}\", which is inside the namespace VibORM reserves for the fixed-decimal descriptor it writes itself, but it is not a constraint VibORM wrote. ` +\n \"A reserved constraint is the ONLY place a SQLite column's declared precision and scale survive — the storage class is INTEGER or TEXT at every domain — so reading this one as a descriptor would plan conversions between domains the schema never declared, and ignoring it would re-plan the same alteration on every push. \" +\n \"Rename or drop the constraint, or restore the definition VibORM wrote for this column.\",\n VibORMErrorCode.INVALID_INPUT,\n {\n meta: {\n constraint: clause.name,\n // Absent for a TABLE constraint, which belongs to no column.\n ...(definition.columnName === undefined\n ? {}\n : { column: definition.columnName }),\n },\n }\n );\n }\n if (found !== undefined) {\n throw new MigrationError(\n `The stored definition carries more than one fixed-decimal descriptor for column \"${column.name}\": ${describeDecimalDomain(found)} and ${describeDecimalDomain(descriptor)}. ` +\n \"One physical column can have only one logical decimal domain, so introspection refuses the ambiguous reserved carriers instead of choosing one by order.\",\n VibORMErrorCode.INVALID_INPUT,\n { meta: { column: column.name } }\n );\n }\n found = descriptor;\n }\n }\n return found;\n}\n\n/**\n * Whether one catalog column is the checked scaled-integer storage VibORM\n * writes for `descriptor`: INTEGER (TEXT for a list) carrying exactly that\n * descriptor's reserved CHECK. Typed queries never ask; `viborm check --db`\n * does, for a table VibORM did not create.\n */\nexport function isSqliteDecimalStorage(\n tableSql: string | null | undefined,\n column: Pick<PhysicalColumn, \"name\" | \"type\" | \"nullable\">,\n descriptor: DecimalDescriptor,\n kind: DecimalStorageKind,\n escapeIdentifier: (name: string) => string\n): boolean {\n const stored = readSqliteDecimalConstraint(\n tableSql,\n column,\n escapeIdentifier\n );\n return (\n sameDecimalDescriptor(stored, descriptor) &&\n sqliteDecimalStorageKind({ type: column.type, decimal: stored }) === kind\n );\n}\n\n/** One top-level entry of a `CREATE TABLE`'s parenthesized definition list. */\n/**\n * The reserved constraint this clause carries, or `undefined` when the clause\n * is one this module could not have written.\n *\n * Three things must hold together, and each is a way the namespace gets\n * squatted: the clause sits in a COLUMN definition (never a table constraint,\n * which VibORM never writes); its name is this column's name followed by the\n * two numbers; and the whole clause re-renders byte for byte.\n */\nfunction ownedDescriptor(\n definition: SqliteTableDefinition,\n clause: SqliteConstraintClause,\n physicalColumn: Pick<PhysicalColumn, \"name\" | \"type\" | \"nullable\">,\n escapeIdentifier: (name: string) => string\n): DecimalDescriptor | undefined {\n const column = definition.columnName;\n if (column === undefined) return undefined;\n const prefix = `${RESERVED_CONSTRAINT_PREFIX}${column}_`;\n if (!clause.name.startsWith(prefix)) return undefined;\n const match = RESERVED_CONSTRAINT_TAIL.exec(clause.name.slice(prefix.length));\n if (!match) return undefined;\n const descriptor = readStoredDecimalDescriptor(match[1], match[2], \"sqlite\");\n if (descriptor === undefined) return undefined;\n // PRAGMA owns the physical type and nullability. Re-render ONLY the shape\n // those facts permit; trying all four writer spellings lets an impossible\n // INTEGER/list or nullable/non-null carrier masquerade as a valid domain.\n const kind = sqliteDecimalStorageKind({\n ...physicalColumn,\n decimal: descriptor,\n });\n if (kind === undefined) return undefined;\n const rendered = sqliteDecimalCheck(\n physicalColumn,\n descriptor,\n kind,\n escapeIdentifier\n );\n if (definition.text.startsWith(rendered, clause.offset)) {\n return descriptor;\n }\n return undefined;\n}\n\n/**\n * Whether one generated table definition carries this column's reserved\n * decimal descriptor name in the structural column clause that owns it.\n *\n * Apply uses this only after it has proved the surrounding statement sequence\n * is VibORM's exact generated table-recreation program. It distinguishes the\n * decimal-column rename variant, whose copy expression needs no conversion\n * sentinel, from an unrelated recreation of a table that merely contains some\n * other decimal column.\n */\nexport function sqliteColumnDefinitionCarriesDecimalDescriptor(\n tableSql: string,\n columnName: string\n): boolean {\n const prefix = `${RESERVED_CONSTRAINT_PREFIX}${columnName}_`;\n for (const definition of sqliteTableDefinitions(tableSql)) {\n if (definition.columnName !== columnName) continue;\n for (const clause of sqliteConstraintClauses(definition.text)) {\n if (!clause.name.startsWith(prefix)) continue;\n const match = RESERVED_CONSTRAINT_TAIL.exec(\n clause.name.slice(prefix.length)\n );\n if (\n match &&\n readStoredDecimalDescriptor(match[1], match[2], \"sqlite\") !== undefined\n ) {\n return true;\n }\n }\n }\n return false;\n}\n\n/** `10^precision - 1`: the widest coefficient the domain can hold. */\nfunction maxCoefficient(precision: number): bigint {\n return 10n ** BigInt(precision) - 1n;\n}\n\n/**\n * The reserved CHECK a SQLite decimal column carries, as a complete column\n * constraint (`CONSTRAINT <name> CHECK (<body>)`).\n *\n * A scalar is the signed integer coefficient. A list is TEXT holding a JSON\n * array of coefficient strings. NULL passes only for a nullable column.\n */\nexport function sqliteDecimalCheck(\n column: { readonly name: string; readonly nullable: boolean },\n descriptor: DecimalDescriptor,\n kind: DecimalStorageKind,\n escapeIdentifier: (name: string) => string\n): string {\n const col = escapeIdentifier(column.name);\n const name = escapeIdentifier(\n sqliteDecimalConstraintName(column.name, descriptor)\n );\n const bound = maxCoefficient(descriptor.precision).toString();\n const body =\n kind === \"list\"\n ? `typeof(${col}) = 'text' AND json_valid(${col}) AND json_type(${col}) = 'array'`\n : `typeof(${col}) = 'integer' AND ${col} BETWEEN -${bound} AND ${bound}`;\n const guarded = column.nullable ? `${col} IS NULL OR (${body})` : body;\n return `CONSTRAINT ${name} CHECK (${guarded})`;\n}\n\n/**\n * The value a row lands in the rebuilt table when it does not fit the target\n * domain. It fails the target column's own reserved CHECK and aborts the whole\n * recreation atomically.\n */\nconst SCALAR_SENTINEL = \"'viborm:decimal-out-of-domain'\";\nconst LIST_SENTINEL = \"'viborm:decimal-list-out-of-domain'\";\n\ninterface Rescale {\n /** `10^|scale delta|`, as an integer literal. */\n readonly factor: string;\n readonly direction: \"up\" | \"down\" | \"none\";\n /** The inclusive absolute bound the SOURCE coefficient must satisfy. */\n readonly bound: string;\n}\n\n/** The one arithmetic decision behind every SQLite conversion expression. */\nfunction rescale(\n from: DecimalDescriptor | undefined,\n to: DecimalDescriptor\n): Rescale {\n const targetMax = maxCoefficient(to.precision);\n const sourceMax = from ? maxCoefficient(from.precision) : targetMax;\n const delta = to.scale - (from?.scale ?? 0);\n if (delta === 0) {\n return {\n factor: \"1\",\n direction: \"none\",\n bound: min(sourceMax, targetMax).toString(),\n };\n }\n if (delta > 0) {\n const factor = 10n ** BigInt(delta);\n return {\n factor: factor.toString(),\n direction: \"up\",\n bound: min(sourceMax, targetMax / factor).toString(),\n };\n }\n const factor = 10n ** BigInt(-delta);\n return {\n factor: factor.toString(),\n direction: \"down\",\n bound: min(sourceMax, targetMax * factor).toString(),\n };\n}\n\nfunction min(a: bigint, b: bigint): bigint {\n return a < b ? a : b;\n}\n\n/**\n * The per-column source expression used by SQLite table recreation. It\n * converts stored values from `from`'s physical spelling to `to`'s without a\n * REAL intermediate and routes every malformed or out-of-domain value to the\n * target CHECK's sentinel.\n */\nexport function sqliteDecimalCopyExpression(\n source: string,\n from: DecimalDescriptor | undefined,\n to: DecimalDescriptor,\n kind: DecimalStorageKind\n): string {\n const { factor, direction, bound } = rescale(from, to);\n const exact = direction === \"down\" ? ` AND ${source} % ${factor} = 0` : \"\";\n if (kind === \"scalar\") {\n const converted = convertedCoefficient(source, direction, factor);\n return (\n `CASE WHEN ${source} IS NULL THEN NULL WHEN typeof(${source}) = 'integer' ` +\n `AND ${source} BETWEEN -${bound} AND ${bound}${exact} THEN ${converted} ` +\n `ELSE ${SCALAR_SENTINEL} END`\n );\n }\n return listCopyExpression(source, direction, factor, bound);\n}\n\nfunction convertedCoefficient(\n operand: string,\n direction: Rescale[\"direction\"],\n factor: string\n): string {\n if (direction === \"up\") return `${operand} * ${factor}`;\n if (direction === \"down\") return `${operand} / ${factor}`;\n return operand;\n}\n\n/** Convert a SQLite JSON coefficient-string list without losing order. */\nfunction listCopyExpression(\n source: string,\n direction: Rescale[\"direction\"],\n factor: string,\n bound: string\n): string {\n const member = `\"m\".\"value\"`;\n const asInteger = `CAST(${member} AS INTEGER)`;\n const exact = direction === \"down\" ? ` AND ${asInteger} % ${factor} = 0` : \"\";\n const admissible =\n `\"m\".\"type\" = 'text' AND CAST(${asInteger} AS TEXT) = ${member} ` +\n `AND ${asInteger} BETWEEN -${bound} AND ${bound}${exact}`;\n const converted = `CAST(${convertedCoefficient(`CAST(\"value\" AS INTEGER)`, direction, factor)} AS TEXT)`;\n return (\n `CASE WHEN ${source} IS NULL THEN NULL WHEN typeof(${source}) = 'text' AND json_valid(${source}) = 1 THEN ` +\n `CASE WHEN json_type(${source}) = 'array' THEN CASE WHEN ` +\n `(SELECT count(*) FROM json_each(${source}) AS \"m\" WHERE NOT (${admissible})) = 0 THEN ` +\n `(SELECT json_group_array(${converted}) FROM (SELECT \"value\" FROM json_each(${source}) AS \"m\" ORDER BY \"m\".\"key\")) ` +\n `ELSE ${LIST_SENTINEL} END ELSE ${LIST_SENTINEL} END ELSE ${LIST_SENTINEL} END`\n );\n}\n","/**\n * The migration layer's decimal renders.\n *\n * `@validation/primitives/decimal-codec` owns everything VALUE-shaped: the\n * grammar, canonical text, the logical <-> coefficient conversion, and the two\n * DDL renderings (`decimalColumnType`, `decimalDefaultText`). This module owns\n * what only a MIGRATION asks — the questions whose subject is a pair of\n * descriptors or a stored column rather than a value:\n *\n * - whether two snapshots describe the same domain, whether a change narrows\n * it, and which scalar/list storage shape a decimal column carries;\n * - the MySQL column-comment marker for a JSON-backed list; and\n * - the shared validation predicates used by native-decimal migration drivers.\n *\n * Everything here is PURE and connection-free: migration DDL is generated into\n * durable artifacts, so none of it may consult a database.\n *\n * Nothing here re-derives a precision or a scale. Every entry takes the frozen\n * descriptor its caller already holds (plan §1.1: no migration component stores\n * an independent precision or scale decision).\n */\n\nimport {\n type DecimalDescriptor,\n decimalColumnType,\n readStoredDecimalDescriptor,\n sameDecimalDescriptor,\n} from \"@validation/primitives/decimal-codec\";\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\nimport type { ColumnDef } from \"./types\";\n\n/**\n * Whether moving from `from` to `to` SHRINKS the set of representable values —\n * the destructive half of a descriptor change.\n *\n * Two independent limits move: the fractional digits (`scale`) and the integer\n * digits (`precision - scale`). A change that lowers either one can find a\n * stored value it cannot hold, and the conversion then refuses; a change that\n * raises both is exact for every existing row. Widening the scale while keeping\n * the precision therefore counts as narrowing, because it takes an integer\n * digit away — `NUMERIC(10,2)` holds 99999999.99 and `NUMERIC(10,5)` does not.\n */\nexport function decimalDomainNarrows(\n from: DecimalDescriptor,\n to: DecimalDescriptor\n): boolean {\n const integerDigitsLost =\n to.precision - to.scale < from.precision - from.scale;\n return integerDigitsLost || to.scale < from.scale;\n}\n\n/**\n * Whether this alteration moves stored values INTO a declared decimal domain —\n * the ONE signal every provider's conversion route reads.\n *\n * Only the TARGET has to declare a domain. An absent source descriptor does not\n * make the change descriptor-free: it means the stored values were written\n * under some other reading, and adopting them under this one is exactly the\n * transition §7.3 governs. Skipping the conversion there is what silently\n * reinterprets a PostgreSQL `numeric` by rounding it through the `USING` cast,\n * and what copies a SQLite integer into a coefficient column at a scale it was\n * never written at. Each provider answers the absent source in its own terms —\n * PostgreSQL's target-domain CHECK is a complete proof on its own, and the\n * SQLite copy reads an untyped `INTEGER` as the logical integer it is — but the\n * QUESTION is one, so this is one predicate.\n *\n * The physical type is part of it beside the descriptor, because a scalar that\n * becomes a list keeps its precision and scale while changing storage class\n * completely. It is compared case-insensitively, the same reading the differ\n * takes: one snapshot side is the serializer's spelling and the other is\n * whatever the catalog answered.\n */\nexport function decimalConversionRequired(\n from: ColumnDef,\n to: ColumnDef\n): boolean {\n if (to.decimal === undefined) return false;\n return (\n !sameDecimalDescriptor(from.decimal, to.decimal) ||\n from.type.toUpperCase() !== to.type.toUpperCase()\n );\n}\n\n/**\n * Whether this alteration can lose data because the target domain is smaller.\n * The migration differ's destructive classifier is the sole consumer-facing\n * decision owner; this function owns only the decimal-domain question it asks.\n */\nexport function decimalChangeNarrows(from: ColumnDef, to: ColumnDef): boolean {\n if (from.decimal === undefined || to.decimal === undefined) return false;\n return decimalDomainNarrows(from.decimal, to.decimal);\n}\n\n/**\n * A storage shape, spelled for a refusal MESSAGE.\n *\n * `undefined` is a real answer here and it has to say so: it means the column's\n * declared type is neither of the two spellings this layer writes, which is a\n * different fact from \"the domain moved\" and must not be reported as one.\n */\nexport function describeDecimalStorageKind(\n kind: DecimalStorageKind | undefined\n): string {\n return kind ?? \"unrecognized\";\n}\n\n// =============================================================================\n// THE MYSQL DESCRIPTOR CARRIER\n// =============================================================================\n\n/**\n * The deterministic VibORM-owned column-comment marker for a JSON-backed MySQL\n * decimal list.\n *\n * A `DECIMAL(p,s)` column spells its own domain, but a decimal LIST is stored\n * as `JSON` (MySQL has no array type), and JSON carries nothing. The marker is\n * that column's descriptor, and it is the whole comment: introspection\n * recognizes only the exact marker (§6.2), so a hand-written comment that\n * merely mentions a decimal is not a descriptor.\n */\nexport function mysqlDecimalListMarker(descriptor: DecimalDescriptor): string {\n return `viborm:decimal(${descriptor.precision},${descriptor.scale})`;\n}\n\nconst MYSQL_LIST_MARKER = /^viborm:decimal\\((\\d+),(\\d+)\\)$/;\n\n/**\n * The domain a MySQL column comment declares, or `undefined` when it is not the\n * reserved marker. A marker-shaped comment with an invalid domain refuses.\n */\nexport function readMysqlDecimalListMarker(\n comment: string | null | undefined\n): DecimalDescriptor | undefined {\n if (!comment) return undefined;\n const match = MYSQL_LIST_MARKER.exec(comment);\n if (!match) return undefined;\n const descriptor = readStoredDecimalDescriptor(match[1], match[2], \"mysql\");\n if (descriptor !== undefined) return descriptor;\n throw new MigrationError(\n \"The stored MySQL column comment uses VibORM's reserved decimal-list marker but carries an invalid fixed-decimal descriptor. \" +\n \"A reserved marker must contain finite safe integers inside the complete MySQL decimal domain; repair or remove the comment before running migrations.\",\n VibORMErrorCode.INVALID_INPUT\n );\n}\n\n// =============================================================================\n// THE DIALECT STORAGE SHAPES\n// =============================================================================\n\n/**\n * How one dialect physically holds a decimal: one value, or a container of\n * them. The migration layer reads it off the column rather than the model,\n * because a snapshot side may have come from introspection.\n */\nexport type { DecimalStorageKind } from \"../adapters/databases/sqlite/storage/decimal\";\n\nimport {\n type DecimalStorageKind,\n sqliteDecimalStorageKind,\n} from \"../adapters/databases/sqlite/storage/decimal\";\n\nexport {\n describeDecimalDomain,\n readStoredDecimalDescriptor,\n} from \"@validation/primitives/decimal-codec\";\nexport { sqliteDecimalStorageKind } from \"../adapters/databases/sqlite/storage/decimal\";\n\n/**\n * The storage shape of a MySQL decimal column, or `undefined` when the column\n * holds no decimal.\n *\n * A scalar spells its own domain in `DECIMAL(p,s)` — introspection reads it\n * back lowercased, so the comparison is case-insensitive — and a list is the\n * `JSON` container every MySQL list gets, carrying its domain in the\n * column-comment marker instead.\n *\n * A MODIFIER after the domain does not change the storage shape.\n * `decimal(10,2) unsigned` and `decimal(10,2) zerofill` are the same physical\n * decimal, introspected verbatim through `formatColumnType`'s modifier arm, and\n * a shape of `undefined` for them would refuse the very ALTER that normalizes\n * them — an estate that could never converge. The domain token itself still has\n * to match the descriptor EXACTLY, so `DECIMAL(10,20)` is not `DECIMAL(10,2)`\n * with a modifier.\n */\nexport function mysqlDecimalStorageKind(\n column: ColumnDef\n): DecimalStorageKind | undefined {\n if (column.decimal === undefined) return undefined;\n const type = column.type.toUpperCase().replace(/\\s+/g, \" \").trim();\n const scalar = decimalColumnType(\"mysql\", column.decimal);\n if (type === scalar || type.startsWith(`${scalar} `)) return \"scalar\";\n return type === MYSQL_DECIMAL_LIST_TYPE ? \"list\" : undefined;\n}\n\n/** PostgreSQL's native scalar and native-array decimal storage shapes. */\nexport function postgresDecimalStorageKind(\n column: ColumnDef\n): DecimalStorageKind | undefined {\n if (column.decimal === undefined) return undefined;\n const type = column.type.toUpperCase().replace(/\\s+/g, \"\").trim();\n const scalar = decimalColumnType(\"pg\", column.decimal);\n if (type === scalar) return \"scalar\";\n return type === `${scalar}[]` ? \"list\" : undefined;\n}\n\n/**\n * The provider-independent scalar/list identity of a migration decimal.\n *\n * Rename detection needs the shape, not typmod equality: changing a decimal\n * descriptor necessarily changes PostgreSQL/MySQL's physical type spelling,\n * while it keeps the same value/container identity and can still be a native\n * column rename followed by one exact conversion.\n */\nexport function migrationDecimalStorageKind(\n column: ColumnDef\n): DecimalStorageKind | undefined {\n return (\n postgresDecimalStorageKind(column) ??\n mysqlDecimalStorageKind(column) ??\n sqliteDecimalStorageKind(column)\n );\n}\n\n/** MySQL has no array type; every list is JSON, decimal lists included. */\nexport const MYSQL_DECIMAL_LIST_TYPE = \"JSON\";\n\n/**\n * TEXT, not the blanket `JSON` every other SQLite list gets: the list's\n * reserved CHECK asserts `typeof = 'text'`, and `JSON` has NUMERIC affinity\n * under SQLite's rules (it contains none of INT/CHAR/CLOB/TEXT/BLOB/REAL/FLOA/\n * DOUB), which would try to convert a numeric-looking container on the way in.\n */\nexport const SQLITE_DECIMAL_LIST_TYPE = \"TEXT\";\n\n// =============================================================================\n// THE PostgreSQL / MySQL VALIDATION PREDICATE\n// =============================================================================\n\n/**\n * The transient constraint a native-decimal conversion validates through.\n *\n * It is added, kept live ACROSS the type change, and dropped after. That\n * ordering is the whole design: the constraint proves every EXISTING row\n * already fits the target domain, and — because it stays — no concurrent write\n * can land a value the target would have to round while the conversion runs.\n * It is how \"while writes are excluded\" is spelled on MySQL, whose `LOCK\n * TABLES` the artifact classifier refuses as a transaction leader.\n */\n/**\n * The compact identity of one transient conversion proof.\n *\n * The table and column deliberately stay out of this identity: MySQL can\n * publish a different table-name spelling through `lower_case_table_names`,\n * while an interrupted proof must authenticate before the original spelling\n * is available again. The exact catalog CHECK authenticates its table and\n * column instead. Kind, precision and scale are already a small, bounded,\n * collision-free identity, so spelling them directly is both shorter and\n * stronger than hashing them: recovery can authenticate the declared proof\n * without searching or trusting a lossy digest.\n */\nexport function decimalConversionConstraintName(\n kind: DecimalStorageKind,\n descriptor: DecimalDescriptor\n): string {\n return `viborm_decimal_${kind === \"scalar\" ? \"s\" : \"l\"}_${descriptor.precision}_${descriptor.scale}`;\n}\n\n/**\n * \"The target domain admits this value UNCHANGED\", as a CHECK body.\n *\n * One idea, spelled in each dialect's cast syntax: a cast to the target type\n * rounds a value with too many fractional digits and refuses one with too many\n * integer digits, so a value that survives the cast intact is exactly a value\n * the conversion does not have to change. That is §7.3's rule — \"convert only\n * when every value fits\", and \"no descriptor change rounds existing data\" —\n * without a per-digit predicate. PostgreSQL's `numeric` also admits special\n * non-finite values, and `NaN` compares equal to itself, so finiteness is an\n * independent part of the proof. Arrays prove it for every member beside the\n * existing NULL-member refusal, while the outer `column IS NULL` continues to\n * admit a nullable whole list.\n *\n * The type token is the one `decimalColumnType` produced for the target column,\n * array suffix included; nothing here re-spells it.\n */\nexport function postgresDecimalFitsCheck(\n column: string,\n targetType: string\n): string {\n const unchanged = `${column} = ${column}::${targetType}`;\n if (targetType.endsWith(\"[]\")) {\n const hasNoNonFiniteMember = [\"NaN\", \"Infinity\", \"-Infinity\"]\n .map((value) => `array_position(${column}, '${value}'::numeric) IS NULL`)\n .join(\" AND \");\n return `${column} IS NULL OR (array_position(${column}, NULL) IS NULL AND ${hasNoNonFiniteMember} AND ${unchanged})`;\n }\n const hasFiniteValue = `${column} NOT IN ('NaN'::numeric, 'Infinity'::numeric, '-Infinity'::numeric)`;\n return `${column} IS NULL OR (${hasFiniteValue} AND ${unchanged})`;\n}\n\n/** {@link postgresDecimalFitsCheck}'s MySQL spelling. */\nexport function mysqlDecimalFitsCheck(\n column: string,\n targetType: string\n): string {\n return `${column} IS NULL OR ${column} = CAST(${column} AS ${targetType})`;\n}\n\n/** MySQL's catalog-normalized shape for {@link mysqlDecimalFitsCheck}. */\nexport function mysqlDecimalFitsCatalogCheck(\n column: string,\n targetType: string\n): string {\n return `((${column} is null) or (${column} = cast(${column} as ${targetType})))`;\n}\n\nfunction mysqlDecimalListCheckParts(\n column: string,\n descriptor: DecimalDescriptor\n): { readonly rendered: string; readonly normalizedContainer: string } {\n const coefficient = `(\"0\"|\"-?[1-9][0-9]{0,${descriptor.precision - 1}}\")`;\n return {\n rendered: `CAST(${column} AS CHAR CHARACTER SET utf8mb4)`,\n normalizedContainer: `^.(${coefficient}(, ${coefficient})*)?.$`,\n };\n}\n\n/**\n * A MySQL JSON decimal list is already in the target domain without changing\n * one stored byte.\n *\n * MySQL CHECK expressions cannot contain a subquery, so this validates the\n * provider's own normalized JSON rendering as one anchored language. Every\n * member must be a JSON string carrying the canonical coefficient grammar,\n * and the digit bound comes from the narrower descriptor that must remain true\n * across the marker change. `LEFT` and `RIGHT` prove the two brackets while\n * the anchored regular expression uses one character for each. That avoids a\n * backslash whose SQL meaning would depend on `NO_BACKSLASH_ESCAPES`.\n */\nexport function mysqlDecimalListFitsCheck(\n column: string,\n descriptor: DecimalDescriptor\n): string {\n const { rendered, normalizedContainer } = mysqlDecimalListCheckParts(\n column,\n descriptor\n );\n return (\n `${column} IS NULL OR (` +\n `LEFT(${rendered}, 1) = '[' AND RIGHT(${rendered}, 1) = ']' AND ` +\n `REGEXP_LIKE(${rendered}, '${normalizedContainer}', 'c'))`\n );\n}\n\n/** MySQL's catalog-normalized shape for {@link mysqlDecimalListFitsCheck}. */\nexport function mysqlDecimalListFitsCatalogCheck(\n column: string,\n descriptor: DecimalDescriptor\n): string {\n const { rendered, normalizedContainer } = mysqlDecimalListCheckParts(\n column,\n descriptor\n );\n const catalogRendered = rendered.replace(\n \"CHAR CHARACTER SET\",\n \"char charset\"\n );\n return (\n `((${column} is null) or (` +\n `(${`LEFT(${catalogRendered}, 1)`} = '[') and ` +\n `(${`RIGHT(${catalogRendered}, 1)`} = ']') and ` +\n `${`REGEXP_LIKE(${catalogRendered}, '${normalizedContainer}', 'c')`}))`\n );\n}\n","/**\n * Centralized Type Mapping for Migration Drivers\n *\n * Maps VibORM scalar types to native database column types.\n * Uses constants from native-types.ts to ensure consistency.\n */\n\nimport { PG, SQLITE } from \"@schema/scalars/native-types\";\nimport {\n type DecimalDescriptor,\n decimalColumnType,\n} from \"@validation/primitives/decimal-codec\";\nimport { SQLITE_GEO_POINT_TYPE } from \"../../adapters/databases/sqlite/storage/geo-point\";\nimport { MigrationError, VibORMErrorCode } from \"../../errors\";\nimport { SQLITE_DECIMAL_LIST_TYPE } from \"../decimal\";\n\n// =============================================================================\n// TYPE MAPPING CONSTANTS\n// =============================================================================\n\n/**\n * Default PostgreSQL type mappings for each VibORM scalar type.\n * Uses the same type names as defined in native-types.ts.\n */\nexport const PG_TYPE_DEFAULTS = {\n string: PG.STRING.TEXT.type,\n int: PG.INT.INTEGER.type,\n number: PG.FLOAT.DOUBLE_PRECISION.type,\n boolean: PG.BOOLEAN.BOOLEAN.type,\n datetime: PG.DATETIME.TIMESTAMP(3).type,\n datetimetz: PG.DATETIME.TIMESTAMPTZ(3).type,\n date: PG.DATETIME.DATE.type,\n time: PG.DATETIME.TIME(3).type,\n timetz: PG.DATETIME.TIMETZ(3).type,\n bigint: PG.BIGINT.BIGINT.type,\n json: PG.JSON.JSONB.type,\n blob: PG.BLOB.BYTEA.type,\n vector: \"vector\",\n point: \"geography(Point,4326)\",\n enum: PG.STRING.TEXT.type,\n} as const;\n\n/**\n * Default SQLite type mappings for each VibORM scalar type.\n * SQLite has limited type affinity - most types map to TEXT, INTEGER, REAL, or BLOB.\n */\nexport const SQLITE_TYPE_DEFAULTS = {\n string: SQLITE.STRING.TEXT.type,\n int: SQLITE.INT.INTEGER.type,\n number: SQLITE.FLOAT.REAL.type,\n boolean: SQLITE.BOOLEAN.INTEGER.type,\n datetime: SQLITE.DATETIME.TEXT.type,\n date: SQLITE.DATETIME.TEXT.type,\n time: SQLITE.DATETIME.TEXT.type,\n bigint: SQLITE.BIGINT.INTEGER.type,\n json: \"JSON\", // SQLite JSON functions work with TEXT but JSON is more semantic\n blob: SQLITE.BLOB.BLOB.type,\n vector: \"JSON\", // Store as JSON array in SQLite\n point: SQLITE_GEO_POINT_TYPE,\n enum: SQLITE.STRING.TEXT.type,\n} as const;\n\n/**\n * Default MySQL type mappings for each VibORM scalar type.\n * MySQL has full type support but uses TINYINT(1) for booleans\n * and doesn't support native arrays (use JSON instead).\n */\nexport const MYSQL_TYPE_DEFAULTS = {\n string: \"TEXT\",\n int: \"INT\",\n number: \"DOUBLE\",\n boolean: \"TINYINT(1)\", // MySQL uses TINYINT(1) for boolean\n datetime: \"DATETIME(3)\", // Use DATETIME(3) to preserve JavaScript Date millisecond precision\n datetimetz: \"DATETIME(3)\", // MySQL DATETIME can store with timezone via application\n date: \"DATE\",\n time: \"TIME(3)\", // Use TIME(3) to preserve millisecond precision\n timetz: \"TIME(3)\", // MySQL TIME doesn't have timezone variant\n bigint: \"BIGINT\",\n json: \"JSON\",\n blob: \"BLOB\",\n vector: \"JSON\", // No native vector support, use JSON\n point: \"POINT SRID 4326\",\n enum: \"TEXT\", // Default for unspecified enums; usually use inline ENUM()\n} as const;\n\n/**\n * THE MySQL inline enum type — one spelling, both snapshot producers.\n *\n * MySQL has no standalone enum object: the values ARE the column type, so this\n * text is also the enum's identity in a snapshot. The desired side spells it\n * (`MySQLMigrationDriver.getEnumColumnType`) and the live side re-spells the\n * catalog's `COLUMN_TYPE` through the very same function\n * (`mysql/introspect.ts`), because `information_schema` prints its own\n * canonical rendering — `enum('a','b')`, no space after the comma, and an\n * identity of its own invention — and two spellings of ONE type read as a\n * changed column on every push and as the mismatch the final push attestation\n * refuses.\n *\n * A member IS a MySQL string literal, so it is spelled by the one function that\n * spells those (`mysqlStringLiteral` below) rather than by a second rule of its\n * own. Doubling `'` alone was that second rule: `ENUM('a\\b')` declared a member\n * holding a BACKSPACE, `ENUM('end\\')` did not parse at all, and once the\n * default beside such a member went through the shared spelling the two\n * disagreed and MySQL refused the CREATE/MODIFY with errno 1067 (all measured).\n */\nexport function mysqlEnumType(values: readonly string[]): string {\n return `ENUM(${values.map((value) => mysqlStringLiteral(value)).join(\", \")})`;\n}\n\n/**\n * THE characters MySQL's string literals carry as an escape — the one table\n * both directions read.\n *\n * MySQL reads `\\` inside a string literal as an escape introducer (only\n * `NO_BACKSLASH_ESCAPES` stops it, a mode this estate never sets and the\n * pinned session does not promise), so doubling `'` alone spells a DIFFERENT\n * value: `DEFAULT ('a\\b')` stored a BACKSPACE and `DEFAULT ('end\\')` did not\n * even parse. The four control characters are escaped for the same reason\n * they cannot be written raw: a generated statement is also the review blob,\n * which is UTF-8/LF with no carriage returns (`sql-blob.ts`).\n *\n * `information_schema` prints an expression default with exactly these escapes\n * plus `\\'` (measured on 8.4.11 — every other character, tab and backspace\n * included, is printed raw), so `mysql/introspect.ts` undoes this same table\n * before re-spelling the value through `mysqlStringLiteral` below.\n */\nexport const MYSQL_LITERAL_ESCAPES: ReadonlyMap<string, string> = new Map([\n [\"\\\\\", \"\\\\\\\\\"],\n [\"\\n\", \"\\\\n\"],\n [\"\\r\", \"\\\\r\"],\n [\"\\0\", \"\\\\0\"],\n [\"\\u001a\", \"\\\\Z\"],\n]);\n\n/**\n * THE MySQL string literal — one spelling, both snapshot producers.\n *\n * The desired side writes it (`MySQLMigrationDriver.escapeValue`) and the live\n * side re-spells the value it read out of the catalog through the very same\n * function (`mysql/introspect.ts`), because two spellings of ONE value read as\n * a changed column on every push and as the mismatch the final push\n * attestation refuses.\n */\nexport function mysqlStringLiteral(value: string): string {\n let escaped = \"\";\n for (const character of value) {\n escaped += MYSQL_LITERAL_ESCAPES.get(character) ?? character;\n }\n return `'${escaped.replace(/'/g, \"''\")}'`;\n}\n\nconst ENUM_VALUES_REGEX = /enum\\((.+)\\)/i;\n\n/**\n * What MySQL's printer writes, read backwards: the WRITE table\n * (`mysqlStringLiteral`) inverted, plus the apostrophe, which MySQL prints as\n * `\\'` although the DDL spelling doubles it instead. Every other character —\n * tab, backspace, `\"` — is printed raw (measured on 8.4.11), so an escape\n * outside this table is one this inverse does not own.\n *\n * ONE table, both catalog vocabularies, because both are MySQL printing a\n * string literal it parsed: the expression default below, and an ENUM's members\n * inside `COLUMN_TYPE`. The enum printer writes a strict SUBSET of it (`\\\\`,\n * `\\n`, `\\r`, `\\0`; it doubles `'` and prints ctrl-Z raw, measured), so reading\n * one table backwards covers both and leaves the same remainder unowned.\n */\nexport const MYSQL_PRINTED_CHARACTERS: ReadonlyMap<string, string> = new Map([\n [\"'\", \"'\"],\n ...[...MYSQL_LITERAL_ESCAPES].map(\n ([character, sequence]) =>\n [sequence.slice(1), character] as [string, string]\n ),\n]);\n\n/**\n * Parse enum values from MySQL COLUMN_TYPE string, or `null` when the catalog\n * spelled one this inverse does not own.\n *\n * Handles values containing commas, doubled single quotes (''), and the\n * backslash escapes MySQL's printer writes (`MYSQL_PRINTED_CHARACTERS`).\n * Example: \"enum('a,b','it''s','c')\" -> ['a,b', \"it's\", 'c']\n * Example: String.raw`enum('a\\\\b','line1\\nline2')` -> [\"a\\\\b\", \"line1\\nline2\"]\n *\n * Reading `\\x` as a bare `x` — which is what \"skip the backslash\" does — turned\n * the printed `\\n` of a declared NEWLINE into the letter `n`, a value the\n * declaration never held. An escape outside the table is not one this server\n * printed for a member the estate spelled, so inverting it would be a guess:\n * the column keeps MySQL's own `COLUMN_TYPE` instead and the push fails at the\n * final attestation, the same fail-closed direction the string inverse takes.\n */\nexport function parseMySqlEnumValues(columnType: string): string[] | null {\n const match = columnType.match(ENUM_VALUES_REGEX);\n if (!match?.[1]) return null;\n\n const content = match[1];\n const values: string[] = [];\n let i = 0;\n\n while (i < content.length) {\n // Skip whitespace and commas\n while (i < content.length && (content[i] === \" \" || content[i] === \",\")) {\n i++;\n }\n if (i >= content.length) break;\n\n // Expect opening quote\n if (content[i] !== \"'\") {\n i++;\n continue;\n }\n i++; // Skip opening quote\n\n // Collect value until closing quote (handle escaped quotes '' and \\')\n let value = \"\";\n while (i < content.length) {\n if (content[i] === \"\\\\\" && i + 1 < content.length) {\n // Backslash escape - the character MySQL's printer wrote it for\n const printed = MYSQL_PRINTED_CHARACTERS.get(content[i + 1] ?? \"\");\n if (printed === undefined) return null;\n value += printed;\n i += 2;\n } else if (content[i] === \"'\" && content[i + 1] === \"'\") {\n // Doubled quote escape - add single quote and skip both\n value += \"'\";\n i += 2;\n } else if (content[i] === \"'\") {\n // Closing quote\n i++;\n break;\n } else {\n value += content[i];\n i++;\n }\n }\n values.push(value);\n }\n\n return values.length > 0 ? values : null;\n}\n\n// =============================================================================\n// TYPE MAPPING FUNCTIONS\n// =============================================================================\n\nexport interface ScalarTypeContext {\n type: string;\n array?: boolean;\n withTimezone?: boolean;\n dimension?: number | undefined;\n /**\n * The declared fixed-decimal domain, for a `decimal` scalar. Every decimal\n * type on every dialect is DERIVED from it — there is no unconstrained\n * `numeric`, no `DECIMAL(65,30)`, and no TEXT decimal to fall back to.\n */\n decimal?: DecimalDescriptor | undefined;\n}\n\n/**\n * The declared domain of a decimal context.\n *\n * A decimal column with no descriptor has no physical type at all: the numbers\n * cannot be inferred from storage, a value, a driver, or an operation (plan\n * §1.1), so the alternative to refusing is inventing a second precision — which\n * is exactly the `DECIMAL(65,30)` this program deletes. The public decimal\n * factory cannot produce such a state; a hand-built or externally-deserialized\n * scalar state can, and this is where it stops.\n */\nfunction requireDecimalDomain(context: ScalarTypeContext): DecimalDescriptor {\n if (context.decimal) return context.decimal;\n throw new MigrationError(\n \"A decimal column has no declared precision and scale. \" +\n \"The fixed-decimal domain is declared once, on the scalar, and every physical type is derived from it.\",\n VibORMErrorCode.INVALID_INPUT,\n { meta: { scalarType: \"decimal\" } }\n );\n}\n\n/**\n * Gets the PostgreSQL column type for a VibORM scalar type.\n */\nexport function getPostgresType(context: ScalarTypeContext): string {\n let baseType: string;\n\n switch (context.type) {\n case \"string\":\n baseType = PG_TYPE_DEFAULTS.string;\n break;\n case \"int\":\n baseType = PG_TYPE_DEFAULTS.int;\n break;\n case \"number\":\n baseType = PG_TYPE_DEFAULTS.number;\n break;\n case \"decimal\":\n // `NUMERIC(p,s)`, and `NUMERIC(p,s)[]` through the array suffix below:\n // PostgreSQL carries the domain in the element typmod, which is the one\n // place introspection can read it back from.\n baseType = decimalColumnType(\"pg\", requireDecimalDomain(context));\n break;\n case \"boolean\":\n baseType = PG_TYPE_DEFAULTS.boolean;\n break;\n case \"datetime\":\n baseType = context.withTimezone\n ? PG_TYPE_DEFAULTS.datetimetz\n : PG_TYPE_DEFAULTS.datetime;\n break;\n case \"date\":\n baseType = PG_TYPE_DEFAULTS.date;\n break;\n case \"time\":\n baseType = context.withTimezone\n ? PG_TYPE_DEFAULTS.timetz\n : PG_TYPE_DEFAULTS.time;\n break;\n case \"bigint\":\n baseType = PG_TYPE_DEFAULTS.bigint;\n break;\n case \"json\":\n baseType = PG_TYPE_DEFAULTS.json;\n break;\n case \"blob\":\n baseType = PG_TYPE_DEFAULTS.blob;\n break;\n case \"vector\":\n baseType =\n context.dimension === undefined\n ? PG_TYPE_DEFAULTS.vector\n : `${PG_TYPE_DEFAULTS.vector}(${context.dimension})`;\n break;\n case \"point\":\n baseType = PG_TYPE_DEFAULTS.point;\n break;\n case \"enum\":\n baseType = PG_TYPE_DEFAULTS.enum;\n break;\n default:\n baseType = PG_TYPE_DEFAULTS.string;\n }\n\n return context.array ? `${baseType}[]` : baseType;\n}\n\n/**\n * Gets the SQLite column type for a VibORM scalar type.\n * SQLite doesn't support native arrays - they are stored as JSON.\n */\nexport function getSQLiteType(context: ScalarTypeContext): string {\n // SQLite doesn't support native arrays - use JSON.\n //\n // A decimal list is the one exception, and it is TEXT rather than JSON for a\n // physical reason: its reserved CHECK asserts `typeof = 'text'`, and the\n // literal type `JSON` has NUMERIC affinity under SQLite's rules, which would\n // convert a numeric-looking container on the way in.\n if (context.array) {\n return context.type === \"decimal\" ? SQLITE_DECIMAL_LIST_TYPE : \"JSON\";\n }\n\n switch (context.type) {\n case \"string\":\n case \"enum\":\n return SQLITE_TYPE_DEFAULTS.string;\n case \"json\":\n case \"vector\":\n return \"JSON\";\n case \"point\":\n return SQLITE_TYPE_DEFAULTS.point;\n case \"int\":\n case \"bigint\":\n case \"boolean\":\n return SQLITE_TYPE_DEFAULTS.int;\n case \"number\":\n return SQLITE_TYPE_DEFAULTS.number;\n // The signed INTEGER coefficient scaled by 10^scale. SQLite has no exact\n // decimal type at all — `DECIMAL(10,5)` is a NUMERIC-affinity spelling\n // whose numbers it ignores, and REAL rounds a fractional value into a\n // double as it is stored — so the exact value lives in an integer and the\n // declared precision is made real by the reserved CHECK the driver adds.\n case \"decimal\":\n return decimalColumnType(\"sqlite\", requireDecimalDomain(context));\n case \"datetime\":\n case \"date\":\n case \"time\":\n return SQLITE_TYPE_DEFAULTS.datetime;\n case \"blob\":\n return SQLITE_TYPE_DEFAULTS.blob;\n default:\n return SQLITE_TYPE_DEFAULTS.string;\n }\n}\n\n/**\n * Gets the MySQL column type for a VibORM scalar type.\n * MySQL doesn't support native arrays - they are stored as JSON.\n */\nexport function getMySQLType(context: ScalarTypeContext): string {\n // MySQL doesn't support native arrays - use JSON\n if (context.array) {\n return \"JSON\";\n }\n\n switch (context.type) {\n case \"string\":\n return MYSQL_TYPE_DEFAULTS.string;\n case \"int\":\n return MYSQL_TYPE_DEFAULTS.int;\n case \"number\":\n return MYSQL_TYPE_DEFAULTS.number;\n // Never bare `DECIMAL`: MySQL reads that as `DECIMAL(10,0)` and silently\n // truncates every fraction. A decimal LIST is caught by the array arm\n // above, where it is JSON like every other MySQL list and carries its\n // domain in the column-comment marker instead.\n case \"decimal\":\n return decimalColumnType(\"mysql\", requireDecimalDomain(context));\n case \"boolean\":\n return MYSQL_TYPE_DEFAULTS.boolean;\n case \"datetime\":\n return context.withTimezone\n ? MYSQL_TYPE_DEFAULTS.datetimetz\n : MYSQL_TYPE_DEFAULTS.datetime;\n case \"date\":\n return MYSQL_TYPE_DEFAULTS.date;\n case \"time\":\n return context.withTimezone\n ? MYSQL_TYPE_DEFAULTS.timetz\n : MYSQL_TYPE_DEFAULTS.time;\n case \"bigint\":\n return MYSQL_TYPE_DEFAULTS.bigint;\n case \"json\":\n return MYSQL_TYPE_DEFAULTS.json;\n case \"blob\":\n return MYSQL_TYPE_DEFAULTS.blob;\n case \"vector\":\n return MYSQL_TYPE_DEFAULTS.vector;\n case \"point\":\n return MYSQL_TYPE_DEFAULTS.point;\n case \"enum\":\n return MYSQL_TYPE_DEFAULTS.enum;\n default:\n return MYSQL_TYPE_DEFAULTS.string;\n }\n}\n","import type { DiffOperation, SchemaSnapshot, TableDef } from \"./types\";\n\nconst DOLLAR_QUOTE = /^\\$(?:[A-Za-z_][A-Za-z0-9_]*)?\\$/;\nconst IDENTIFIER_START = /[A-Za-z_]/;\nconst IDENTIFIER_PART = /[A-Za-z0-9_$]/;\nconst BARE_IDENTIFIER = /^[a-z_][a-z0-9_$]*$/;\nconst SQL_WHITESPACE = /\\s/;\n\nexport type NativeRenameOperation = Extract<\n DiffOperation,\n { type: \"renameTable\" | \"renameColumn\" }\n>;\n\n/**\n * Applies the schema-wide effect a database native rename has already made.\n *\n * The resolver uses this as its next differ input, generated down migrations\n * use it to address definitions before the inverse rename runs, and SQLite's\n * batch replay uses it before a later table reconstruction. It never mutates\n * the snapshot supplied by the caller.\n */\nexport function applyNativeRename(\n snapshot: SchemaSnapshot,\n operation: NativeRenameOperation\n): SchemaSnapshot {\n return {\n ...snapshot,\n tables:\n operation.type === \"renameTable\"\n ? renameTable(snapshot.tables, operation.from, operation.to)\n : renameColumn(\n snapshot.tables,\n operation.tableName,\n operation.from,\n operation.to\n ),\n };\n}\n\nfunction renameTable(\n tables: readonly TableDef[],\n from: string,\n to: string\n): TableDef[] {\n return tables.map((table) => ({\n ...table,\n name: table.name === from ? to : table.name,\n foreignKeys: table.foreignKeys.map((foreignKey) =>\n foreignKey.referencedTable === from\n ? { ...foreignKey, referencedTable: to }\n : foreignKey\n ),\n }));\n}\n\nfunction renameColumn(\n tables: readonly TableDef[],\n tableName: string,\n from: string,\n to: string\n): TableDef[] {\n const renamed = (name: string) => (name === from ? to : name);\n\n return tables.map((table) => {\n const ownsColumn = table.name === tableName;\n return {\n ...table,\n columns: ownsColumn\n ? table.columns.map((column) =>\n column.name === from ? { ...column, name: to } : column\n )\n : table.columns,\n ...(ownsColumn && table.primaryKey\n ? {\n primaryKey: {\n ...table.primaryKey,\n columns: table.primaryKey.columns.map(renamed),\n },\n }\n : {}),\n indexes: ownsColumn\n ? table.indexes.map((index) => ({\n ...index,\n columns: index.columns.map(renamed),\n ...(index.where === undefined\n ? {}\n : { where: renameSqlIdentifier(index.where, from, to) }),\n }))\n : table.indexes,\n foreignKeys: table.foreignKeys.map((foreignKey) => ({\n ...foreignKey,\n columns: ownsColumn\n ? foreignKey.columns.map(renamed)\n : foreignKey.columns,\n referencedColumns:\n foreignKey.referencedTable === tableName\n ? foreignKey.referencedColumns.map(renamed)\n : foreignKey.referencedColumns,\n })),\n uniqueConstraints: ownsColumn\n ? table.uniqueConstraints.map((constraint) => ({\n ...constraint,\n columns: constraint.columns.map(renamed),\n }))\n : table.uniqueConstraints,\n };\n });\n}\n\n/**\n * Rewrites one identifier in an opaque SQL expression without touching values.\n *\n * PostgreSQL and SQLite persist partial-index predicates as SQL text, but a\n * native column rename changes the parsed column references in those\n * predicates. Snapshot replay must model the same effect before a later table\n * recreation. Quoted identifiers retain their delimiter; ordinary identifiers\n * retain their spelling style when the target can be written bare. Strings,\n * dollar-quoted bodies, and comments are copied byte-for-byte.\n */\nfunction renameSqlIdentifier(sql: string, from: string, to: string): string {\n let rewritten = \"\";\n let cursor = 0;\n\n while (cursor < sql.length) {\n const quote = sql[cursor];\n\n if (quote === \"'\") {\n const end = quotedRegionEnd(sql, cursor, \"'\", \"'\");\n rewritten += sql.slice(cursor, end);\n cursor = end;\n continue;\n }\n if (quote === '\"' || quote === \"`\") {\n const end = quotedRegionEnd(sql, cursor, quote, quote);\n if (sql[end - 1] !== quote) {\n rewritten += sql.slice(cursor, end);\n cursor = end;\n continue;\n }\n const body = sql.slice(cursor + 1, end - 1);\n const identifier = body.replaceAll(`${quote}${quote}`, quote);\n rewritten +=\n identifier === from && !isNonColumnIdentifier(sql, cursor, end)\n ? `${quote}${to.replaceAll(quote, `${quote}${quote}`)}${quote}`\n : sql.slice(cursor, end);\n cursor = end;\n continue;\n }\n if (quote === \"[\") {\n const end = quotedRegionEnd(sql, cursor, \"]\", \"]\");\n if (sql[end - 1] !== \"]\") {\n rewritten += sql.slice(cursor, end);\n cursor = end;\n continue;\n }\n const body = sql.slice(cursor + 1, end - 1);\n const identifier = body.replaceAll(\"]]\", \"]\");\n rewritten +=\n identifier === from && !isNonColumnIdentifier(sql, cursor, end)\n ? `[${escapeBracketIdentifier(to)}]`\n : sql.slice(cursor, end);\n cursor = end;\n continue;\n }\n if (quote === \"-\" && sql[cursor + 1] === \"-\") {\n const newline = sql.indexOf(\"\\n\", cursor + 2);\n const end = newline < 0 ? sql.length : newline;\n rewritten += sql.slice(cursor, end);\n cursor = end;\n continue;\n }\n if (quote === \"/\" && sql[cursor + 1] === \"*\") {\n const end = blockCommentEnd(sql, cursor);\n rewritten += sql.slice(cursor, end);\n cursor = end;\n continue;\n }\n if (quote === \"$\") {\n const delimiter = dollarQuoteDelimiter(sql, cursor);\n if (delimiter !== undefined) {\n const closing = sql.indexOf(delimiter, cursor + delimiter.length);\n const end = closing < 0 ? sql.length : closing + delimiter.length;\n rewritten += sql.slice(cursor, end);\n cursor = end;\n continue;\n }\n }\n if (isIdentifierStart(quote)) {\n let end = cursor + 1;\n while (end < sql.length && isIdentifierPart(sql[end]!)) end += 1;\n const identifier = sql.slice(cursor, end);\n const lowercaseIdentifier = identifier.toLowerCase();\n const escapeStringQuote =\n lowercaseIdentifier === \"e\" && sql[end] === \"'\"\n ? end\n : lowercaseIdentifier === \"u\" &&\n sql[end] === \"&\" &&\n sql[end + 1] === \"'\"\n ? end + 1\n : undefined;\n if (escapeStringQuote !== undefined) {\n const literalEnd = quotedRegionEnd(\n sql,\n escapeStringQuote,\n \"'\",\n \"'\",\n true\n );\n rewritten += sql.slice(cursor, literalEnd);\n cursor = literalEnd;\n continue;\n }\n const isStringPrefix =\n sql[end] === \"'\" ||\n (lowercaseIdentifier === \"u\" &&\n sql[end] === \"&\" &&\n sql[end + 1] === \"'\");\n rewritten +=\n !(isStringPrefix || isNonColumnIdentifier(sql, cursor, end)) &&\n unquotedIdentifierMatches(identifier, from)\n ? bareIdentifierOrQuoted(to)\n : identifier;\n cursor = end;\n continue;\n }\n\n rewritten += quote;\n cursor += 1;\n }\n\n return rewritten;\n}\n\nfunction quotedRegionEnd(\n sql: string,\n start: number,\n closingQuote: string,\n escapedQuote: string,\n backslashEscapes = false\n): number {\n let cursor = start + 1;\n while (cursor < sql.length) {\n if (backslashEscapes && sql[cursor] === \"\\\\\") {\n cursor += 2;\n continue;\n }\n if (sql[cursor] !== closingQuote) {\n cursor += 1;\n continue;\n }\n if (sql[cursor + 1] === escapedQuote) {\n cursor += 2;\n continue;\n }\n return cursor + 1;\n }\n return sql.length;\n}\n\nfunction blockCommentEnd(sql: string, start: number): number {\n let cursor = start + 2;\n let depth = 1;\n while (cursor < sql.length && depth > 0) {\n if (sql[cursor] === \"/\" && sql[cursor + 1] === \"*\") {\n depth += 1;\n cursor += 2;\n } else if (sql[cursor] === \"*\" && sql[cursor + 1] === \"/\") {\n depth -= 1;\n cursor += 2;\n } else {\n cursor += 1;\n }\n }\n return cursor;\n}\n\nfunction dollarQuoteDelimiter(sql: string, start: number): string | undefined {\n const rest = sql.slice(start);\n const match = DOLLAR_QUOTE.exec(rest);\n return match?.[0];\n}\n\nfunction isIdentifierStart(character: string | undefined): boolean {\n return character !== undefined && IDENTIFIER_START.test(character);\n}\n\nfunction isIdentifierPart(character: string): boolean {\n return IDENTIFIER_PART.test(character);\n}\n\nfunction unquotedIdentifierMatches(identifier: string, from: string): boolean {\n return from === from.toLowerCase() && identifier.toLowerCase() === from;\n}\n\nfunction isNonColumnIdentifier(\n sql: string,\n start: number,\n end: number\n): boolean {\n let next = end;\n while (next < sql.length && SQL_WHITESPACE.test(sql[next]!)) next += 1;\n if (sql[next] === \"(\" || (sql[next] === \"=\" && sql[next + 1] === \">\")) {\n return true;\n }\n\n let previous = start - 1;\n while (previous >= 0 && SQL_WHITESPACE.test(sql[previous]!)) previous -= 1;\n if (sql[previous] === \".\") return true;\n if (sql[previous] === \":\" && sql[previous - 1] === \":\") return true;\n\n const previousEnd = previous + 1;\n while (previous >= 0 && isIdentifierPart(sql[previous]!)) previous -= 1;\n const previousWord = sql.slice(previous + 1, previousEnd).toLowerCase();\n return previousWord === \"as\" || previousWord === \"collate\";\n}\n\nfunction bareIdentifierOrQuoted(identifier: string): string {\n return BARE_IDENTIFIER.test(identifier)\n ? identifier\n : `\"${identifier.replaceAll('\"', '\"\"')}\"`;\n}\n\nfunction escapeBracketIdentifier(identifier: string): string {\n return identifier.split(\"]\").join(\"]]\");\n}\n","import type { DateTimePhysicalForm } from \"@validation/primitives/datetime-physical-codec\";\nimport type { DecimalDescriptor } from \"@validation/primitives/decimal-codec\";\n\n// =============================================================================\n// SCHEMA SNAPSHOT (database-agnostic representation)\n// =============================================================================\n\nexport interface SchemaSnapshot {\n tables: TableDef[];\n enums?: EnumDef[] | undefined;\n /**\n * Generated-file history for polymorphic discriminator members.\n * This is descriptive metadata only; the structural differ ignores it.\n */\n polymorphicStorage?: readonly PolymorphicSnapshotStorage[] | undefined;\n}\n\nexport interface PolymorphicToOneSnapshotMember {\n readonly publicType: string;\n readonly storedType: string;\n readonly targetTable: string;\n}\n\n/**\n * Logical-only history for a to-one polymorphic relation. The physical\n * facts (columns, index) live in the owner's {@link TableDef} where the\n * structural differ owns them; `storageRef` is the join key into the owner\n * table's `relationStorage` registry — the physical type-column name at\n * serialization time, opaque to every reader and normalized through accepted\n * rename operations before history joins.\n */\nexport interface PolymorphicToOneSnapshot {\n readonly ownerTable: string;\n readonly relation: string;\n readonly kind: \"toOne\";\n readonly storageRef: string;\n readonly members: readonly PolymorphicToOneSnapshotMember[];\n}\n\nexport interface PolymorphicToManySnapshotMember {\n readonly publicType: string;\n readonly storedType: string;\n readonly targetTable: string;\n readonly memberJunctionTable: string;\n readonly inverseCardinality: \"one\" | \"many\";\n}\n\n/**\n * Logical-only history for a collection polymorphic relation: nothing\n * physical (no side columns, constraint names, or referential actions) — each\n * member names its junction table and the structural differ owns that table's\n * shape entirely.\n */\nexport interface PolymorphicToManySnapshot {\n readonly ownerTable: string;\n readonly relation: string;\n readonly kind: \"toMany\";\n readonly members: readonly PolymorphicToManySnapshotMember[];\n}\n\nexport type PolymorphicSnapshotStorage =\n | PolymorphicToOneSnapshot\n | PolymorphicToManySnapshot;\n\n/**\n * One relation-owned physical storage annotation on the table that carries it,\n * keyed in {@link TableDef.relationStorage} by the storage ref (the physical\n * type-column name at serialization time).\n */\nexport interface PolymorphicToOneStorageRegistryEntry {\n readonly kind: \"polymorphicToOne\";\n readonly typeColumn: string;\n readonly idColumn: string;\n readonly index: string;\n}\n\nexport interface TableDef {\n name: string;\n columns: ColumnDef[];\n primaryKey?: PrimaryKeyDef | undefined;\n indexes: IndexDef[];\n foreignKeys: ForeignKeyDef[];\n uniqueConstraints: UniqueConstraintDef[];\n /**\n * Relation-owned storage registry, annotation ONLY: the structural differ\n * ignores it, drivers pass it through `finalizeTable` untouched, no DDL\n * reads it, and introspected snapshots never carry it. Its sole reader is\n * polymorphic member history, which joins\n * {@link PolymorphicToOneSnapshot.storageRef} into it.\n */\n relationStorage?:\n | Readonly<Record<string, PolymorphicToOneStorageRegistryEntry>>\n | undefined;\n}\n\nexport interface ColumnDef {\n name: string;\n type: string; // Normalized type (e.g., \"varchar(255)\", \"integer\", \"boolean\")\n nullable: boolean;\n default?: string | undefined; // SQL expression for default value\n autoIncrement?: boolean | undefined;\n /**\n * The declared fixed-decimal domain this column stores, when it stores one.\n *\n * `type` is the ACTIVE PHYSICAL representation and this is the ONE logical\n * descriptor beside it — the pair every consumer reads (serializer, snapshot,\n * differ, DDL, introspection, defaults, table reconstruction). They are not\n * redundant: on PostgreSQL and MySQL the physical type spells the domain, but\n * on SQLite the class is `INTEGER` (scalar) or `TEXT` (list) whatever the\n * precision and scale are, so a descriptor change is invisible in `type`\n * alone and the differ would plan nothing for it.\n *\n * Every snapshot producer carries it — the serializer from\n * `ScalarState[\"decimal\"]`, and each introspection from the fact its dialect\n * can prove (a PostgreSQL typmod, a MySQL `DECIMAL(p,s)` or column-comment\n * marker, a SQLite reserved CHECK constraint name) — because a side that\n * cannot recover it would read as a change on every push, forever.\n *\n * There is no parallel decimal metadata map on `Model`, adapter, or\n * migration driver (plan §7.2): this field is the migration layer's only\n * copy, and it is a copy of the frozen descriptor the resolved scalar owns.\n */\n decimal?: DecimalDescriptor | undefined;\n /**\n * The declared SQLite storage vocabulary for one scalar DateTime column.\n *\n * SQLite's three physical types do not identify the logical domain: TEXT,\n * INTEGER, and REAL also store unrelated scalar families. The serializer\n * therefore carries the declaration beside the physical type so an explicit\n * migration can translate an existing DateTime instead of reinterpreting its\n * bytes. Live introspection cannot recover this logical fact and omits it.\n */\n dateTime?: DateTimePhysicalForm | undefined;\n /** SQLite writer CHECK version; physical metadata, never a public point language. */\n geoPointEncoding?: \"legacy\" | \"binary64\" | undefined;\n}\n\nexport interface PrimaryKeyDef {\n columns: string[];\n name?: string | undefined;\n}\n\nexport interface IndexDef {\n name: string;\n columns: string[];\n unique: boolean;\n type?: \"btree\" | \"hash\" | \"gin\" | \"gist\" | \"fulltext\" | \"spatial\" | undefined;\n where?: string | undefined; // For partial indexes\n}\n\nexport interface ForeignKeyDef {\n name: string;\n columns: string[];\n referencedTable: string;\n referencedColumns: string[];\n onDelete?: ReferentialAction | undefined;\n onUpdate?: ReferentialAction | undefined;\n}\n\nexport type ReferentialAction =\n | \"cascade\"\n | \"setNull\"\n | \"restrict\"\n | \"noAction\"\n | \"setDefault\";\n\nexport interface UniqueConstraintDef {\n name: string;\n columns: string[];\n}\n\nexport interface EnumDef {\n name: string;\n values: string[];\n}\n\n// =============================================================================\n// DIFF OPERATIONS (resolved, ready to execute)\n// =============================================================================\n\nexport type DiffOperation =\n | { type: \"createTable\"; table: TableDef }\n | { type: \"dropTable\"; tableName: string }\n | { type: \"renameTable\"; from: string; to: string }\n | { type: \"addColumn\"; tableName: string; column: ColumnDef }\n | { type: \"dropColumn\"; tableName: string; columnName: string }\n | { type: \"renameColumn\"; tableName: string; from: string; to: string }\n | {\n type: \"alterColumn\";\n tableName: string;\n columnName: string;\n from: ColumnDef;\n to: ColumnDef;\n }\n | { type: \"createIndex\"; tableName: string; index: IndexDef }\n | { type: \"dropIndex\"; tableName: string; indexName: string }\n | { type: \"addForeignKey\"; tableName: string; fk: ForeignKeyDef }\n | { type: \"dropForeignKey\"; tableName: string; fkName: string }\n | {\n type: \"addUniqueConstraint\";\n tableName: string;\n constraint: UniqueConstraintDef;\n }\n | { type: \"dropUniqueConstraint\"; tableName: string; constraintName: string }\n | { type: \"addPrimaryKey\"; tableName: string; primaryKey: PrimaryKeyDef }\n | { type: \"dropPrimaryKey\"; tableName: string; constraintName: string }\n | { type: \"createEnum\"; enumDef: EnumDef }\n | {\n type: \"dropEnum\";\n enumName: string;\n /**\n * Columns that depend on this enum.\n * Required for SQLite to know which columns need CHECK constraint removal.\n */\n dependentColumns?: Array<{ tableName: string; columnName: string }>;\n }\n | {\n type: \"alterEnum\";\n enumName: string;\n addValues?: string[] | undefined;\n removeValues?: string[] | undefined;\n /**\n * Full list of desired enum values (required when removing values)\n * Used to recreate the enum type in PostgreSQL\n */\n newValues?: string[] | undefined;\n /**\n * Columns that depend on this enum (required when removing values)\n * Each entry is { tableName, columnName }\n */\n dependentColumns?:\n | Array<{ tableName: string; columnName: string }>\n | undefined;\n /**\n * Global replacement values for removed enum values.\n * Used as fallback when no column-specific mapping exists.\n * Maps old value -> new value for data migration.\n *\n * Example: { \"pending\": \"inactive\" } - rows with \"pending\" become \"inactive\"\n * Use null to set rows to NULL: { \"pending\": null }\n */\n valueReplacements?: Record<string, string | null> | undefined;\n /**\n * Per-column replacement values for removed enum values.\n * Allows different columns to have different mappings.\n * Key is \"tableName.columnName\", value is the replacement map.\n *\n * Example: { \"users.status\": { \"pending\": \"inactive\" }, \"orders.status\": { \"pending\": \"cancelled\" } }\n */\n columnValueReplacements?:\n | Record<string, Record<string, string | null>>\n | undefined;\n /**\n * Default replacement for any removed values without explicit mapping.\n * Useful when the enum field has a default value - use that here.\n * Use null to set rows to NULL.\n *\n * Example: If your field has `.default(\"active\")`, set defaultReplacement: \"active\"\n */\n defaultReplacement?: string | null | undefined;\n };\n\n// =============================================================================\n// AMBIGUOUS CHANGES (require user input to resolve)\n// =============================================================================\n\n/** Detected when columns are added AND dropped in the same table */\nexport type AmbiguousColumnChange = {\n type: \"ambiguousColumn\";\n tableName: string;\n droppedColumn: ColumnDef;\n addedColumn: ColumnDef;\n};\n\n/** Detected when tables are added AND dropped */\nexport type AmbiguousTableChange = {\n type: \"ambiguousTable\";\n droppedTable: string;\n addedTable: string;\n droppedTableDef: TableDef;\n addedTableDef: TableDef;\n};\n\nexport type AmbiguousChange = AmbiguousColumnChange | AmbiguousTableChange;\n\n/** User's resolution for an ambiguous change */\nexport type ChangeResolution =\n | { type: \"rename\" } // Treat as rename (preserve data)\n | { type: \"addAndDrop\" }; // Treat as separate add + drop (data loss)\n\n// =============================================================================\n// DIFF RESULT (output of differ, before resolution)\n// =============================================================================\n\nexport interface DiffResult {\n /** Operations that are unambiguous and ready to execute */\n operations: DiffOperation[];\n /** Changes that need user input to resolve */\n ambiguousChanges: AmbiguousChange[];\n}\n\n// =============================================================================\n// RESOLVER (handles ambiguous changes)\n// =============================================================================\n\n/** Callback to resolve ambiguous changes (used by CLI or programmatic API) */\nexport type Resolver = (\n changes: AmbiguousChange[]\n) => Promise<Map<AmbiguousChange, ChangeResolution>>;\n\n// =============================================================================\n// UNIFIED RESOLVE CALLBACK\n// =============================================================================\n\n/**\n * Valid resolution results.\n * - \"proceed\": Accept the change (for destructive)\n * - \"reject\": Reject the change and abort\n * - \"rename\": Treat as a rename (for ambiguous)\n * - \"addAndDrop\": Treat as separate add + drop (for ambiguous)\n * - \"enumMapped\": Enum values have been mapped (for enumValueRemoval)\n */\nexport type ResolveResult =\n | \"proceed\"\n | \"reject\"\n | \"rename\"\n | \"addAndDrop\"\n | \"enumMapped\";\n\n/**\n * Base properties shared by destructive and ambiguous changes.\n */\ninterface BaseResolveChange {\n /** The specific operation type */\n operation:\n | \"dropTable\"\n | \"dropColumn\"\n | \"addColumn\"\n | \"alterColumn\"\n | \"renameTable\"\n | \"renameColumn\";\n\n /** The table involved */\n table: string;\n\n /** The column involved (if applicable) */\n column?: string;\n\n /** Human-readable description of the change */\n description: string;\n\n /** Reject this change and abort the operation */\n reject(): \"reject\";\n}\n\n/**\n * A destructive change that will cause data loss.\n * Available methods: `proceed()`, `reject()`\n */\nexport interface DestructiveResolveChange extends BaseResolveChange {\n type: \"destructive\";\n\n /** Accept the destructive change (causes data loss) */\n proceed(): \"proceed\";\n}\n\n/**\n * An ambiguous change that could be a rename or add+drop.\n * Available methods: `rename()`, `addAndDrop()`, `reject()`\n */\nexport interface AmbiguousResolveChange extends BaseResolveChange {\n type: \"ambiguous\";\n\n /** The old name (for renames) */\n oldName?: string;\n\n /** The new name (for renames) */\n newName?: string;\n\n /** The old type (for alterColumn) */\n oldType?: string;\n\n /** The new type (for alterColumn) */\n newType?: string;\n\n /** Treat as a rename (preserves data) */\n rename(): \"rename\";\n\n /** Treat as separate add + drop (causes data loss) */\n addAndDrop(): \"addAndDrop\";\n}\n\n/**\n * An enum value removal that needs replacement mappings for a specific column.\n * Called once per column that uses the enum, allowing different mappings per column.\n * Available methods: `mapValues()`, `useNull()`, `reject()`\n */\nexport interface EnumValueRemovalChange {\n type: \"enumValueRemoval\";\n\n /** The enum name */\n enumName: string;\n\n /** The table containing the column */\n tableName: string;\n\n /** The column using this enum */\n columnName: string;\n\n /** Whether this column is nullable (if true, useNull() is safe) */\n isNullable: boolean;\n\n /** Values being removed */\n removedValues: string[];\n\n /** Available values to map to */\n availableValues: string[];\n\n /** Human-readable description */\n description: string;\n\n /**\n * Map removed values to replacement values.\n * @param replacements - Map of old value → new value (or null for NULL)\n */\n mapValues(replacements: Record<string, string | null>): \"enumMapped\";\n\n /**\n * Set all removed values to NULL.\n * This is a shorthand for mapValues where all values map to null.\n * Note: Only safe if the column is nullable.\n */\n useNull(): \"enumMapped\";\n\n /** Reject this change and abort the operation */\n reject(): \"reject\";\n}\n\n/**\n * A change that requires user resolution.\n * Use the type discriminant to determine which methods are available:\n * - `destructive`: `proceed()`, `reject()`\n * - `ambiguous`: `rename()`, `addAndDrop()`, `reject()`\n * - `enumValueRemoval`: `mapValues()`, `reject()`\n */\nexport type ResolveChange =\n | DestructiveResolveChange\n | AmbiguousResolveChange\n | EnumValueRemovalChange;\n\nexport type EnumResolutionDecision =\n | {\n readonly kind: \"mapValues\";\n readonly mappings: Record<string, string | null>;\n }\n | { readonly kind: \"useNull\" }\n | { readonly kind: \"mixed\" };\n\nconst enumResolutionDecisions = new WeakMap<\n ResolveChange,\n EnumResolutionDecision\n>();\n\n/** Internal authoritative decision made through an enum change's own methods. */\nexport function readEnumResolutionDecision(\n change: ResolveChange\n): EnumResolutionDecision | undefined {\n return enumResolutionDecisions.get(change);\n}\n\nfunction recordEnumResolutionDecision(\n change: EnumValueRemovalChange,\n decision: Exclude<EnumResolutionDecision, { readonly kind: \"mixed\" }>\n): void {\n const previous = enumResolutionDecisions.get(change);\n enumResolutionDecisions.set(\n change,\n previous !== undefined && previous.kind !== decision.kind\n ? { kind: \"mixed\" }\n : decision\n );\n}\n\n/**\n * Unified callback for resolving changes that need user input.\n * Called once per change, allowing granular control over each decision.\n *\n * @param change - The change requiring resolution\n * @returns The resolution decision (call a method on change to get this)\n *\n * @example\n * ```ts\n * resolve: async (change) => {\n * console.log(change.description);\n *\n * if (change.type === \"destructive\") {\n * return confirm(\"Accept data loss?\") ? change.proceed() : change.reject();\n * }\n *\n * if (change.type === \"ambiguous\") {\n * return change.rename();\n * }\n *\n * if (change.type === \"enumValueRemoval\") {\n * // Map removed enum values to new values\n * return change.mapValues({\n * 'PENDING': 'INACTIVE',\n * 'OLD_VALUE': null, // Set to NULL\n * });\n * }\n * }\n * ```\n */\nexport type ResolveCallback = (\n change: ResolveChange\n) =>\n | Promise<ResolveResult | undefined | void>\n | ResolveResult\n | undefined\n | void;\n\n/**\n * Create a destructive change object with resolution methods.\n */\nexport function createDestructiveChange(props: {\n operation: \"dropTable\" | \"dropColumn\" | \"addColumn\" | \"alterColumn\";\n table: string;\n column?: string;\n description: string;\n}): DestructiveResolveChange {\n return {\n type: \"destructive\",\n ...props,\n proceed: () => \"proceed\",\n reject: () => \"reject\",\n };\n}\n\n/**\n * Create an ambiguous change object with resolution methods.\n */\nexport function createAmbiguousChange(props: {\n operation: \"renameTable\" | \"renameColumn\";\n table: string;\n column?: string;\n oldName?: string;\n newName?: string;\n oldType?: string;\n newType?: string;\n description: string;\n}): AmbiguousResolveChange {\n return {\n type: \"ambiguous\",\n ...props,\n rename: () => \"rename\",\n addAndDrop: () => \"addAndDrop\",\n reject: () => \"reject\",\n };\n}\n\n/**\n * Create an enum value removal change object with resolution methods.\n */\nexport function createEnumValueRemovalChange(props: {\n enumName: string;\n tableName: string;\n columnName: string;\n isNullable: boolean;\n removedValues: string[];\n availableValues: string[];\n description: string;\n}): EnumValueRemovalChange {\n const change: EnumValueRemovalChange = {\n type: \"enumValueRemoval\",\n ...props,\n mapValues: (replacements: Record<string, string | null>) => {\n const mappings: Record<string, string | null> = {};\n for (const [value, replacement] of Object.entries(replacements)) {\n mappings[value] = replacement;\n }\n Object.freeze(mappings);\n recordEnumResolutionDecision(change, { kind: \"mapValues\", mappings });\n return \"enumMapped\";\n },\n useNull: () => {\n recordEnumResolutionDecision(change, { kind: \"useNull\" });\n return \"enumMapped\";\n },\n reject: () => \"reject\",\n };\n return change;\n}\n\nexport type Dialect = \"postgresql\" | \"sqlite\" | \"mysql\";\n\n/**\n * The durable estate target a migration history is generated for.\n *\n * PostgreSQL carries its schema because generated artifacts are\n * schema-qualified: a history generated for `billing` cannot be replayed as a\n * `public` estate. MySQL and SQLite arms carry ONLY their dialect — MySQL\n * artifacts are database-relative on purpose, so one estate deploys to\n * `app_dev`, `app_test` and `app_prod`, and SQLite has no namespace concept.\n *\n * This is the DURABLE compatibility claim, not the live execution destination.\n * The live destination is the adapter's namespace, which MySQL reads at its\n * live boundary and never persists here.\n */\nexport type MigrationTarget = (\n | { readonly dialect: \"postgresql\"; readonly namespace: string }\n | { readonly dialect: \"mysql\" }\n | { readonly dialect: \"sqlite\" }\n) & { readonly tables?: readonly string[] };\n","/**\n * The order in which tables are dropped: children before parents.\n *\n * Two callers need it, with different premises. A generated program\n * (`orderTableDrops`, reached through `prepareSchemaProgram`) still has live\n * foreign keys when it drops a table, so an order that violates one fails,\n * and a cycle is broken only where a key's delete action allows it. A\n * namespace reset (`live-reset.ts`) has already dropped every key it can see,\n * so its order is defence and a cycle falls back to inventory order.\n * `childrenBeforeParents` is the one rule they share; what a cycle means stays\n * with each caller.\n */\n\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\nimport type { DiffOperation, ReferentialAction, SchemaSnapshot } from \"./types\";\n\n/** `from` holds a foreign key that references `to`. */\nexport interface TableReference {\n readonly from: string;\n readonly to: string;\n}\n\n/**\n * Orders `items` so that no item comes after a table it is referenced by.\n *\n * Each round takes every item no remaining item references, in input order, so\n * independent tables keep their given order. What a cycle leaves unordered is\n * returned as `blocked`, in input order; a reference from an item to itself\n * blocks that item.\n */\nexport function childrenBeforeParents<T>(\n items: readonly T[],\n nameOf: (item: T) => string,\n references: readonly TableReference[]\n): { ordered: T[]; blocked: T[] } {\n const referencedBy = new Map<string, string[]>();\n for (const { from, to } of references) {\n const children = referencedBy.get(to);\n if (children) {\n children.push(from);\n } else {\n referencedBy.set(to, [from]);\n }\n }\n\n let remaining = [...items];\n const ordered: T[] = [];\n for (;;) {\n const names = new Set(remaining.map(nameOf));\n const isFree = (item: T) =>\n !referencedBy.get(nameOf(item))?.some((child) => names.has(child));\n const free = remaining.filter(isFree);\n if (free.length === 0) {\n return { ordered, blocked: remaining };\n }\n ordered.push(...free);\n remaining = remaining.filter((item) => !isFree(item));\n }\n}\n\ntype DropTable = Extract<DiffOperation, { type: \"dropTable\" }>;\n\nconst tableOf = (drop: DropTable) => drop.tableName;\n\n/** A key still active when its tables are dropped. */\ninterface ActiveKey extends TableReference {\n readonly columns: readonly string[];\n readonly onDelete: ReferentialAction | undefined;\n}\n\n/**\n * Orders a prepared program's `dropTable` operations from the foreign keys\n * the CURRENT snapshot says exist, children first wherever the keys allow.\n *\n * A key matters while it is still active when its tables are dropped: both of\n * its tables are dropped, and the program does not remove it with an explicit\n * `dropForeignKey`. PostgreSQL and MySQL remove every such key first\n * (`materializeDroppedTableForeignKeys`), so their drops keep the order they\n * were given. A retained table never references a dropped one: the desired\n * schema cannot, so the differ removes that key, and `sortOperations` runs\n * every `dropForeignKey` before every `dropTable`.\n *\n * SQLite holds keys inline and drops with enforcement on. `DROP TABLE` first\n * deletes every row, applying each key's delete action (`refusalOf`), so a\n * cycle is broken at a table whose drop no key can refuse, and refused before\n * any statement exists when no such table remains. The drops replace the band\n * of drops `sortOperations` emitted, where that band begins.\n */\nexport function orderTableDrops(\n operations: DiffOperation[],\n current: SchemaSnapshot\n): DiffOperation[] {\n const drops = operations.filter(\n (operation): operation is DropTable => operation.type === \"dropTable\"\n );\n if (drops.length === 0) {\n return operations;\n }\n\n const dropped = new Set(drops.map(tableOf));\n const removedKeys = new Set<string>();\n for (const operation of operations) {\n if (operation.type === \"dropForeignKey\") {\n removedKeys.add(`${operation.tableName} ${operation.fkName}`);\n }\n }\n const keys: ActiveKey[] = [];\n for (const table of current.tables) {\n for (const fk of table.foreignKeys) {\n const active =\n dropped.has(table.name) &&\n dropped.has(fk.referencedTable) &&\n !removedKeys.has(`${table.name} ${fk.name}`);\n if (active) {\n keys.push({\n from: table.name,\n to: fk.referencedTable,\n columns: fk.columns,\n onDelete: fk.onDelete,\n });\n }\n }\n }\n // Children first: every key between two tables, and a self-reference that\n // refuses even its own table's delete.\n const childFirst = keys.filter(\n (key) => key.from !== key.to || key.onDelete === \"restrict\"\n );\n\n const ordered: DropTable[] = [];\n let remaining = drops;\n for (;;) {\n const step = childrenBeforeParents(remaining, tableOf, childFirst);\n ordered.push(...step.ordered);\n if (step.blocked.length === 0) {\n break;\n }\n const left = new Set(step.blocked.map(tableOf));\n const next = step.blocked.find(\n (drop) => !refusalOf(drop.tableName, keys, left)\n );\n if (!next) {\n throw cyclicDropRefusal(step.blocked.map(tableOf), keys);\n }\n ordered.push(next);\n remaining = step.blocked.filter((drop) => drop !== next);\n }\n\n const first = operations.findIndex(\n (operation) => operation.type === \"dropTable\"\n );\n const rest = operations.filter((operation) => operation.type !== \"dropTable\");\n return [...rest.slice(0, first), ...ordered, ...rest.slice(first)];\n}\n\n/**\n * The key that may refuse dropping `table` while the `existing` tables,\n * `table` among them, remain, if any.\n *\n * The implicit delete removes every row of `table`, and CASCADE extends it to\n * the rows of each remaining table that cascades from a deleted one. A\n * remaining key into a deleted table then decides: CASCADE deleted its rows\n * too and SET NULL clears them; RESTRICT refuses at once; NO ACTION and SET\n * DEFAULT are settled when the statement ends, by when a key held by `table`\n * has lost every row, while one held by another table may still point at\n * nothing. Measured on better-sqlite3 over random populated rows, for every\n * pair of actions on a two-table cycle in both orders and for each action on\n * a self-reference.\n */\nfunction refusalOf(\n table: string,\n keys: readonly ActiveKey[],\n existing: ReadonlySet<string>\n): ActiveKey | undefined {\n const deleted = new Set([table]);\n for (const name of deleted) {\n for (const key of keys) {\n if (\n key.to === name &&\n key.onDelete === \"cascade\" &&\n existing.has(key.from)\n ) {\n deleted.add(key.from);\n }\n }\n }\n return keys.find(\n (key) =>\n deleted.has(key.to) &&\n existing.has(key.from) &&\n key.onDelete !== \"cascade\" &&\n key.onDelete !== \"setNull\" &&\n (key.onDelete === \"restrict\" || key.from !== table)\n );\n}\n\nconst ACTION_SQL: Record<ReferentialAction, string> = {\n cascade: \"CASCADE\",\n setNull: \"SET NULL\",\n restrict: \"RESTRICT\",\n noAction: \"NO ACTION\",\n setDefault: \"SET DEFAULT\",\n};\n\n/**\n * Names every blocked table and a key that refuses its drop, by columns:\n * SQLite introspection cannot read a key's name back.\n */\nfunction cyclicDropRefusal(\n blocked: readonly string[],\n keys: readonly ActiveKey[]\n): MigrationError {\n const left = new Set(blocked);\n const reasons = blocked.flatMap((table) => {\n const key = refusalOf(table, keys, left);\n return key\n ? [\n `dropping \"${table}\" is refused by ${key.from}(${key.columns.join(\", \")}) -> ${key.to} ON DELETE ${ACTION_SQL[key.onDelete ?? \"noAction\"]}`,\n ]\n : [];\n });\n return new MigrationError(\n `Tables ${blocked.map((name) => `\"${name}\"`).join(\", \")} cannot be dropped in an order that satisfies their foreign keys: ${reasons.join(\"; \")}. This database enforces those keys while it drops a table and cannot drop a key without rebuilding its table, so the whole plan is refused before any statement runs. ` +\n \"Remove one of these relations, or change its delete action to SET NULL, in a separate change first; then drop the tables.\",\n VibORMErrorCode.MIGRATION_INVALID_STATE,\n { meta: { type: \"cyclic-table-drop\" } }\n );\n}\n","/**\n * Shared migration helpers that do not own a V1 command.\n */\n\nimport type { AnyDriver } from \"../drivers/driver\";\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\nimport type { MigrationDriver } from \"./drivers\";\nimport { orderTableDrops } from \"./drop-order\";\nimport { sha256Hex, utf8Bytes } from \"./identity\";\nimport type { Dialect, DiffOperation, SchemaSnapshot } from \"./types\";\n\n/** PostgreSQL/MySQL derived identifiers keep their uniqueness under byte caps. */\nexport function derivedMigrationName(name: string): string {\n if (utf8Bytes(name).length <= 63) return name;\n let prefix = \"\";\n for (const character of name) {\n if (utf8Bytes(prefix + character).length > 54) break;\n prefix += character;\n }\n return `${prefix}_${sha256Hex(utf8Bytes(name)).slice(0, 8)}`;\n}\n\n/** Default generated-key spelling; dialects may supply their physical rule. */\nexport function defaultGeneratedPrimaryKeyName(\n tableName: string,\n name?: string\n): string {\n return name || `${tableName}_pkey`;\n}\n\n// DIALECT UTILITIES\n// =============================================================================\n\n/**\n * Validates and normalizes the database dialect for migrations.\n * Throws if the dialect is not supported.\n */\nexport function normalizeDialect(dialect: string): Dialect {\n if (dialect === \"postgresql\" || dialect === \"postgres\") {\n return \"postgresql\";\n }\n if (dialect === \"sqlite\") {\n return \"sqlite\";\n }\n if (dialect === \"mysql\") {\n return \"mysql\";\n }\n throw new MigrationError(\n `Unsupported dialect for migrations: \"${dialect}\". ` +\n \"Supported dialects: postgresql, sqlite, mysql.\",\n VibORMErrorCode.MIGRATION_DIALECT_MISMATCH,\n { meta: { dialect } }\n );\n}\n\n// QUERY EXECUTOR\n// =============================================================================\n\n/**\n * Type for executing SQL queries and returning rows.\n */\nexport type QueryExecutor = (\n sql: string,\n params?: unknown[]\n) => Promise<unknown[]>;\n\n/**\n * Creates a query executor from a driver.\n * Extracts rows from the QueryResult.\n */\nexport function createQueryExecutor(driver: AnyDriver): QueryExecutor {\n return async (sql: string, params?: unknown[]) => {\n const result = await driver._executeRaw<Record<string, unknown>>(\n sql,\n params\n );\n return result.rows;\n };\n}\n\n// =============================================================================\n// OPERATION UTILITIES\n// =============================================================================\n\n/**\n * Operation execution order priorities.\n * Lower numbers execute first.\n */\nconst OPERATION_PRIORITY: Record<DiffOperation[\"type\"], number> = {\n createEnum: 1,\n dropForeignKey: 2,\n dropIndex: 3,\n dropUniqueConstraint: 4,\n dropPrimaryKey: 5,\n dropColumn: 6,\n dropTable: 7,\n createTable: 8,\n renameTable: 9,\n addColumn: 10,\n renameColumn: 11,\n alterColumn: 12,\n addPrimaryKey: 13,\n addUniqueConstraint: 14,\n createIndex: 15,\n addForeignKey: 16,\n alterEnum: 1.5,\n dropEnum: 18,\n};\n\n/**\n * Slot for the index drops that have to run *after* the batch's index creates.\n * Between `createIndex` and `addForeignKey`, so a superseded index is gone\n * before a new constraint is bound to whatever is left.\n */\nconst SUPERSEDED_INDEX_DROP_PRIORITY =\n (OPERATION_PRIORITY.createIndex + OPERATION_PRIORITY.addForeignKey) / 2;\n\n/**\n * Picks out the `dropIndex` operations whose replacement has to exist first.\n *\n * MySQL binds a foreign key to whichever index covers its columns and refuses\n * to drop that index while it is the last one covering them (errno 1553). A\n * schema edit that supersedes such an index — widening it, or covering the same\n * columns with a unique constraint — plans the drop and its replacement in the\n * same batch, so the replacement has to be in place before the drop runs.\n *\n * Two arrangements keep a drop in its early slot instead:\n * - The batch creates an index of the *same name*, which the drop has to free\n * first. The name is matched on its own, not per table: PostgreSQL and SQLite\n * scope an index name to the schema/database, so a batch that frees a name on\n * one table and takes it on another collides too (Postgres 42P07). Matching\n * on the name alone can only keep a drop early, never defer one, so it cannot\n * reopen the 1553 case — there the created index has a different name.\n * - A table that also drops a column loses that column's indexes along with it,\n * so a drop deferred past the column drop would address an index already\n * gone. (A dropped *table* cannot collide: index diffs are only produced for\n * tables present in both snapshots.)\n */\nfunction supersededIndexDrops(operations: DiffOperation[]): Set<DiffOperation> {\n const createdIndexNames = new Set<string>();\n const tablesLosingColumns = new Set<string>();\n for (const op of operations) {\n if (op.type === \"createIndex\") {\n createdIndexNames.add(op.index.name);\n } else if (op.type === \"addUniqueConstraint\") {\n createdIndexNames.add(op.constraint.name);\n } else if (op.type === \"addPrimaryKey\" && op.primaryKey.name) {\n createdIndexNames.add(op.primaryKey.name);\n } else if (op.type === \"dropColumn\") {\n tablesLosingColumns.add(op.tableName);\n }\n }\n\n const superseded = new Set<DiffOperation>();\n for (const op of operations) {\n if (\n op.type === \"dropIndex\" &&\n !createdIndexNames.has(op.indexName) &&\n !tablesLosingColumns.has(op.tableName)\n ) {\n superseded.add(op);\n }\n }\n return superseded;\n}\n\n/**\n * Sorts operations for proper execution order:\n * 1. Create enums (before tables that use them)\n * 2. Drop foreign keys (before dropping tables/columns)\n * 3. Drop indexes, constraints, columns\n * 4. Drop tables\n * 5. Create tables\n * 6. Establish table and column renames before operations using the new names\n * 7. Add or alter columns and constraints\n * 8. Create indexes\n * 9. Drop the indexes those creates supersede (see `supersededIndexDrops`)\n * 10. Add foreign keys (after tables/columns exist)\n */\nexport function sortOperations(operations: DiffOperation[]): DiffOperation[] {\n const superseded = supersededIndexDrops(operations);\n const priorityOf = (op: DiffOperation) =>\n superseded.has(op)\n ? SUPERSEDED_INDEX_DROP_PRIORITY\n : OPERATION_PRIORITY[op.type];\n const baseline = operations\n .map((operation, index) => ({ operation, index }))\n .sort((a, b) => priorityOf(a.operation) - priorityOf(b.operation));\n const renames = baseline.filter(\n ({ operation }) =>\n operation.type === \"renameTable\" || operation.type === \"renameColumn\"\n );\n if (renames.length === 0) return baseline.map(({ operation }) => operation);\n const ordered: DiffOperation[] = [];\n const visited = new Set<number>();\n const active = new Set<number>();\n const visit = (entry: (typeof baseline)[number]): void => {\n if (visited.has(entry.index)) return;\n if (active.has(entry.index)) {\n throw new MigrationError(\n \"Migration operations contain a cyclic native rename dependency\",\n VibORMErrorCode.MIGRATION_INVALID_STATE\n );\n }\n active.add(entry.index);\n for (const prerequisite of renames) {\n if (prerequisite.index === entry.index) continue;\n const rename = prerequisite.operation;\n const operation = entry.operation;\n if (rename.type === \"renameTable\") {\n // A later producer can reuse an earlier table name. A column rename\n // before that name was consumed addresses the earlier identity.\n if (\n operation.type === \"renameColumn\" &&\n prerequisite.index > entry.index &&\n renames.some(\n (earlier) =>\n earlier.index > entry.index &&\n earlier.index < prerequisite.index &&\n earlier.operation.type === \"renameTable\" &&\n earlier.operation.from === operation.tableName\n )\n )\n continue;\n const needed =\n operation.type === \"renameTable\"\n ? prerequisite.index < entry.index && rename.to === operation.from\n : operationTargetsTable(operation, rename.to);\n if (needed) visit(prerequisite);\n } else if (rename.type === \"renameColumn\") {\n const needed =\n operation.type === \"renameTable\"\n ? prerequisite.index < entry.index &&\n rename.tableName === operation.from\n : operation.type === \"renameColumn\"\n ? prerequisite.index < entry.index &&\n rename.tableName === operation.tableName &&\n rename.to === operation.from\n : operationTargetsColumn(operation, rename.tableName, rename.to);\n if (needed) visit(prerequisite);\n }\n }\n active.delete(entry.index);\n visited.add(entry.index);\n ordered.push(entry.operation);\n };\n for (const entry of baseline) visit(entry);\n return ordered;\n}\n\n/** A table operation that must address the post-rename identity. */\nfunction operationTargetsTable(\n operation: DiffOperation,\n tableName: string\n): boolean {\n if (operation.type === \"createTable\") {\n return operation.table.name === tableName;\n }\n if (operation.type === \"alterEnum\" || operation.type === \"dropEnum\") {\n return (\n operation.dependentColumns?.some(\n (column) => column.tableName === tableName\n ) ?? false\n );\n }\n return \"tableName\" in operation && operation.tableName === tableName;\n}\n\nfunction operationTargetsColumn(\n operation: DiffOperation,\n tableName: string,\n columnName: string\n): boolean {\n // A drop names a key as the rename left it: on PostgreSQL a derived key\n // name follows its column.\n if (\n operation.type === \"dropIndex\" ||\n operation.type === \"dropUniqueConstraint\" ||\n operation.type === \"dropForeignKey\"\n ) {\n return operation.tableName === tableName;\n }\n if (operation.type === \"alterEnum\" || operation.type === \"dropEnum\") {\n return (\n operation.dependentColumns?.some(\n (column) =>\n column.tableName === tableName && column.columnName === columnName\n ) ?? false\n );\n }\n return (\n \"tableName\" in operation &&\n operation.tableName === tableName &&\n \"columnName\" in operation &&\n operation.columnName === columnName\n );\n}\n\n/**\n * Lifts *forward-reference* foreign keys out of `createTable` operations into\n * separate `addForeignKey` operations, so a table whose FK points at a table\n * created later in the same batch does not emit the constraint before its\n * referenced table exists.\n *\n * This is the DDL-ordering fix for `push()` / generated migrations: a schema\n * that declares a child model (the endpoint holding the FK) *before* its parent\n * would otherwise emit `ALTER TABLE child ADD ... FOREIGN KEY REFERENCES parent`\n * (Postgres) or an inline FK (MySQL) immediately after `CREATE TABLE child`,\n * before `CREATE TABLE parent` runs — Postgres `42P01`, MySQL analogous — and\n * the whole transactional push aborts with zero tables created.\n *\n * The transform is capability-gated and deliberately *surgical*:\n * - Drivers that cannot `ALTER TABLE ADD FOREIGN KEY` (SQLite/LibSQL) keep FKs\n * inline and are returned untouched — they resolve forward references lazily\n * and rewriting an FK into an `addForeignKey` op would trigger a table\n * recreation against an introspected-empty current schema.\n * - Only FKs that reference a table created *later* in this batch are lifted.\n * Backward references (referenced-first schemas, self-references, FKs to\n * pre-existing tables) already work and are left byte-identical, preserving\n * the DDL of schemas that were never broken.\n *\n * Lifted `addForeignKey` operations are appended after every other operation so\n * they run once all `CREATE TABLE`s have executed. Non-lifted operations retain\n * their exact input order.\n */\nexport function extractForwardReferenceForeignKeys(\n operations: DiffOperation[],\n migrationDriver: MigrationDriver\n): DiffOperation[] {\n if (!migrationDriver.capabilities.supportsAddForeignKeyViaAlter) {\n return operations;\n }\n\n // Position of each table within the sequence of createTable operations.\n const createdTablePosition = new Map<string, number>();\n let position = 0;\n for (const op of operations) {\n if (op.type === \"createTable\") {\n createdTablePosition.set(op.table.name, position);\n position += 1;\n }\n }\n\n const result: DiffOperation[] = [];\n const liftedForeignKeys: DiffOperation[] = [];\n\n for (const op of operations) {\n if (op.type !== \"createTable\") {\n result.push(op);\n continue;\n }\n\n const selfPosition = createdTablePosition.get(op.table.name);\n // Partition this table's FKs into those that must stay inline and those\n // that point forward to a table created later in the batch.\n const retained = op.table.foreignKeys.filter((fk) => {\n const targetPosition = createdTablePosition.get(fk.referencedTable);\n const isForwardReference =\n targetPosition !== undefined &&\n selfPosition !== undefined &&\n targetPosition > selfPosition;\n return !isForwardReference;\n });\n\n if (retained.length === op.table.foreignKeys.length) {\n // No forward references — leave the operation byte-identical.\n result.push(op);\n continue;\n }\n\n const forwardForeignKeys = op.table.foreignKeys.filter(\n (fk) => !retained.includes(fk)\n );\n\n result.push({\n ...op,\n table: { ...op.table, foreignKeys: retained },\n });\n for (const fk of forwardForeignKeys) {\n liftedForeignKeys.push({\n type: \"addForeignKey\",\n tableName: op.table.name,\n fk,\n });\n }\n }\n\n return [...result, ...liftedForeignKeys];\n}\n\n/**\n * Materializes the foreign-key drops a dropped-table graph needs, ONCE, for\n * every consumer: push, generated up SQL, and inverted generated down SQL.\n *\n * The differ omits a foreign-key drop when both endpoint tables disappear —\n * there is no surviving table to alter, so nothing produces the operation — and\n * §6.1 removes the `CASCADE` that used to paper over it. Without this stage a\n * `RESTRICT` drop of two mutually-referencing tables fails no matter which\n * order they are emitted in, and a cycle fails in every order.\n *\n * Every implicated key is included regardless of the table order the batch\n * happens to have, including keys whose owning AND referenced tables are both\n * being dropped, and including cycles. `sortOperations` then puts every\n * `dropForeignKey` (priority 2) ahead of every `dropTable` (priority 7).\n *\n * Drivers that cannot `ALTER TABLE ... DROP CONSTRAINT` keep their operations\n * byte-identical: SQLite and LibSQL hold foreign keys inline and rebuild tables\n * instead, so an explicit drop is not a statement they can emit.\n */\nexport function materializeDroppedTableForeignKeys(\n operations: DiffOperation[],\n current: SchemaSnapshot,\n migrationDriver: MigrationDriver\n): DiffOperation[] {\n if (!migrationDriver.capabilities.supportsAddForeignKeyViaAlter) {\n return operations;\n }\n\n const droppedTables = new Set<string>();\n const plannedDrops = new Set<string>();\n for (const op of operations) {\n if (op.type === \"dropTable\") {\n droppedTables.add(op.tableName);\n } else if (op.type === \"dropForeignKey\") {\n plannedDrops.add(`${op.tableName} ${op.fkName}`);\n }\n }\n if (droppedTables.size === 0) {\n return operations;\n }\n\n const materialized: DiffOperation[] = [];\n for (const table of current.tables) {\n for (const fk of table.foreignKeys) {\n const implicated =\n droppedTables.has(table.name) || droppedTables.has(fk.referencedTable);\n if (implicated && !plannedDrops.has(`${table.name} ${fk.name}`)) {\n materialized.push({\n type: \"dropForeignKey\",\n tableName: table.name,\n fkName: fk.name,\n });\n }\n }\n }\n\n return materialized.length === 0\n ? operations\n : [...materialized, ...operations];\n}\n\n/**\n * One compile-order owner for generated schema programs. Generate and push\n * both hand this result to the compiler, and nothing sorts it afterwards. Do\n * not lift, materialize or order drops at a second call site. Drops are\n * ordered last, once every foreign-key removal the program makes is known.\n */\nexport function prepareSchemaProgram(\n operations: DiffOperation[],\n current: SchemaSnapshot,\n migrationDriver: MigrationDriver\n): DiffOperation[] {\n return orderTableDrops(\n materializeDroppedTableForeignKeys(\n extractForwardReferenceForeignKeys(operations, migrationDriver),\n current,\n migrationDriver\n ),\n current\n );\n}\n\n// =============================================================================\n// MIGRATION FILE UTILITIES\n// =============================================================================\n\n/**\n * Generate a migration name based on the operations.\n */\nexport function generateMigrationName(operations: DiffOperation[]): string {\n if (operations.length === 0) {\n return \"empty\";\n }\n\n const primaryOp = operations[0];\n if (!primaryOp) {\n return \"migration\";\n }\n\n switch (primaryOp.type) {\n case \"createTable\":\n return operations.length === 1\n ? `create-${primaryOp.table.name}`\n : \"initial\";\n case \"dropTable\":\n return `drop-${primaryOp.tableName}`;\n case \"addColumn\":\n return `add-${primaryOp.column.name}-to-${primaryOp.tableName}`;\n case \"dropColumn\":\n return `drop-${primaryOp.columnName}-from-${primaryOp.tableName}`;\n case \"renameTable\":\n return `rename-${primaryOp.from}-to-${primaryOp.to}`;\n case \"renameColumn\":\n return `rename-${primaryOp.from}-to-${primaryOp.to}`;\n case \"createIndex\":\n return `add-index-${primaryOp.index.name}`;\n case \"dropIndex\":\n return `drop-index-${primaryOp.indexName}`;\n case \"addForeignKey\":\n return `add-fk-${primaryOp.fk.name}`;\n case \"dropForeignKey\":\n return `drop-fk-${primaryOp.fkName}`;\n case \"createEnum\":\n return `create-enum-${primaryOp.enumDef.name}`;\n case \"dropEnum\":\n return `drop-enum-${primaryOp.enumName}`;\n case \"alterEnum\":\n return `alter-enum-${primaryOp.enumName}`;\n default:\n return \"migration\";\n }\n}\n","/** Runtime-neutral canonical Base64 for persisted migration parameters. */\n\nconst ALPHABET =\n \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\";\nconst CANONICAL_SHAPE =\n /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;\n\nexport function encodeBase64(bytes: Uint8Array): string {\n let encoded = \"\";\n for (let index = 0; index < bytes.length; index += 3) {\n const first = bytes[index]!;\n const hasSecond = index + 1 < bytes.length;\n const hasThird = index + 2 < bytes.length;\n const second = hasSecond ? bytes[index + 1]! : 0;\n const third = hasThird ? bytes[index + 2]! : 0;\n encoded += ALPHABET[Math.floor(first / 4)];\n encoded += ALPHABET[(first % 4) * 16 + Math.floor(second / 16)];\n encoded += hasSecond\n ? ALPHABET[(second % 16) * 4 + Math.floor(third / 64)]\n : \"=\";\n encoded += hasThird ? ALPHABET[third % 64] : \"=\";\n }\n return encoded;\n}\n\nexport function decodeCanonicalBase64(text: string): Uint8Array | undefined {\n if (!CANONICAL_SHAPE.test(text)) return;\n const padding = text.endsWith(\"==\") ? 2 : text.endsWith(\"=\") ? 1 : 0;\n const decoded = new Uint8Array((text.length / 4) * 3 - padding);\n let offset = 0;\n for (let index = 0; index < text.length; index += 4) {\n const first = ALPHABET.indexOf(text.charAt(index));\n const second = ALPHABET.indexOf(text.charAt(index + 1));\n const thirdCharacter = text.charAt(index + 2);\n const fourthCharacter = text.charAt(index + 3);\n const third = thirdCharacter === \"=\" ? 0 : ALPHABET.indexOf(thirdCharacter);\n const fourth =\n fourthCharacter === \"=\" ? 0 : ALPHABET.indexOf(fourthCharacter);\n decoded[offset] = first * 4 + Math.floor(second / 16);\n offset += 1;\n if (thirdCharacter !== \"=\") {\n decoded[offset] = (second % 16) * 16 + Math.floor(third / 4);\n offset += 1;\n }\n if (fourthCharacter !== \"=\") {\n decoded[offset] = (third % 4) * 64 + fourth;\n offset += 1;\n }\n }\n return encodeBase64(decoded) === text ? decoded : undefined;\n}\n","/**\n * Shared hostile-parse primitives for Migration V1.\n *\n * Exact-key admission and primitive field readers. Artifact parsers own\n * their shapes; this file owns only the reusable refuse/key helpers.\n */\n\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\nimport { isNumber, isRecord, isString } from \"../validation/value-guards\";\n\nexport function refuse(message: string): never {\n throw new MigrationError(message, VibORMErrorCode.MIGRATION_INVALID_ESTATE);\n}\n\nexport function exactObject(\n value: unknown,\n allowed: readonly string[],\n required: readonly string[],\n label: string\n): Record<string, unknown> {\n if (!isRecord(value)) refuse(`${label} must be an object`);\n for (const key of Object.keys(value)) {\n if (!allowed.includes(key)) refuse(`${label} has unknown key ${key}`);\n }\n for (const key of required) {\n if (!(key in value)) refuse(`${label} is missing ${key}`);\n }\n return value;\n}\n\nexport function parseFormat(value: unknown, label: string): \"1\" {\n if (value !== \"1\") refuse(`${label} format must be \"1\"`);\n return \"1\";\n}\n\nexport function parseFiniteInteger(value: unknown, label: string): number {\n if (\n !(isNumber(value) && Number.isInteger(value) && Number.isSafeInteger(value))\n ) {\n refuse(`${label} must be a safe integer`);\n }\n return value;\n}\n\nexport function parseRequiredString(value: unknown, label: string): string {\n if (!isString(value) || value.length === 0)\n refuse(`${label} must be a non-empty string`);\n return value;\n}\n\nexport function parseStringArray(value: unknown, label: string): string[] {\n if (!Array.isArray(value)) refuse(`${label} must be an array`);\n return value.map((entry, index) => {\n if (!isString(entry)) refuse(`${label}[${index}] must be a string`);\n return entry;\n });\n}\n\nexport function parseIdentifierArray(value: unknown, label: string): string[] {\n if (!Array.isArray(value)) refuse(`${label} must be an array`);\n return value.map((entry, index) =>\n parseRequiredString(entry, `${label}[${index}]`)\n );\n}\n\n/** One of a closed list of literals, or the refusal `message`. */\nexport function parseMember<T>(\n value: unknown,\n allowed: readonly T[],\n message: string\n): T {\n const member = allowed.find((entry) => entry === value);\n if (member === undefined) refuse(message);\n return member;\n}\n\nconst TRUE_FLAGS: readonly unknown[] = [true, 1, 1n, \"1\", \"t\", \"true\"];\nconst FALSE_FLAGS: readonly unknown[] = [false, 0, 0n, \"0\", \"f\", \"false\"];\n\n/** A boolean as any provider spells it in a catalog row, or `undefined`. */\nexport function readFlag(value: unknown): boolean | undefined {\n if (TRUE_FLAGS.includes(value)) return true;\n return FALSE_FLAGS.includes(value) ? false : undefined;\n}\n","/**\n * Dispatch identity and hostile parameter admission.\n * Reset-plan and state parsers share this owner; they do not import each other.\n */\n\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\nimport { canonicalizeDecimal } from \"../validation/primitives/decimal-codec\";\nimport {\n isBoolean,\n isNumber,\n isRecord,\n isString,\n} from \"../validation/value-guards\";\nimport { decodeCanonicalBase64 } from \"./base64\";\nimport { canonicalizeJson } from \"./canonical-json\";\nimport { domainHash, HASH_DOMAIN, parseSha256, type Sha256 } from \"./identity\";\nimport { exactObject, parseFiniteInteger, refuse } from \"./v1-parse-shared\";\nimport type { MigrationDispatchV1, MigrationParameterV1 } from \"./v1-types\";\n\nconst DISPATCH_KEYS = [\n \"dispatchId\",\n \"length\",\n \"offset\",\n \"parameters\",\n \"sqlHash\",\n] as const;\n\nconst CANONICAL_BIGINT = /^(?:0|-?[1-9]\\d*)$/;\n\nexport function encodeDispatchIdentity(\n sqlHash: Sha256,\n offset: number,\n length: number,\n parameters: readonly MigrationParameterV1[]\n): Sha256 {\n return domainHash(\n HASH_DOMAIN.dispatch,\n canonicalizeJson({ sqlHash, offset, length, parameters })\n );\n}\n\nexport function parseDispatch(\n value: unknown,\n label: string\n): MigrationDispatchV1 {\n const record = exactObject(value, DISPATCH_KEYS, DISPATCH_KEYS, label);\n const offset = parseFiniteInteger(record.offset, `${label}.offset`);\n const length = parseFiniteInteger(record.length, `${label}.length`);\n if (offset < 0 || length < 0) refuse(`${label} range must be non-negative`);\n if (!Array.isArray(record.parameters))\n refuse(`${label}.parameters must be an array`);\n const parameters = record.parameters.map((parameter, index) =>\n parseParameter(parameter, `${label}.parameters[${index}]`)\n );\n const sqlHash = parseSha256(record.sqlHash, `${label}.sqlHash`);\n const dispatchId = parseSha256(record.dispatchId, `${label}.dispatchId`);\n const expected = encodeDispatchIdentity(sqlHash, offset, length, parameters);\n if (dispatchId !== expected) {\n throw new MigrationError(\n `${label}.dispatchId does not match its SQL range and parameters`,\n VibORMErrorCode.MIGRATION_CORRUPTION\n );\n }\n return { dispatchId, sqlHash, offset, length, parameters };\n}\n\nfunction parseParameter(value: unknown, label: string): MigrationParameterV1 {\n if (!(isRecord(value) && isString(value.kind))) {\n refuse(`${label} must be a tagged parameter`);\n }\n switch (value.kind) {\n case \"null\":\n exactObject(value, [\"kind\"], [\"kind\"], label);\n return { kind: \"null\" };\n case \"target-namespace\":\n exactObject(value, [\"kind\"], [\"kind\"], label);\n return { kind: \"target-namespace\" };\n case \"boolean\": {\n const record = exactObject(\n value,\n [\"kind\", \"value\"],\n [\"kind\", \"value\"],\n label\n );\n if (!isBoolean(record.value)) refuse(`${label}.value must be boolean`);\n return { kind: \"boolean\", value: record.value };\n }\n case \"string\": {\n const record = exactObject(\n value,\n [\"kind\", \"value\"],\n [\"kind\", \"value\"],\n label\n );\n if (!isString(record.value)) refuse(`${label}.value must be a string`);\n return { kind: \"string\", value: record.value };\n }\n case \"number\": {\n const record = exactObject(\n value,\n [\"kind\", \"value\"],\n [\"kind\", \"value\"],\n label\n );\n if (!(isNumber(record.value) && Number.isFinite(record.value))) {\n refuse(`${label}.value must be a finite number`);\n }\n return { kind: \"number\", value: record.value };\n }\n case \"bigint\":\n case \"bytes\":\n case \"date-time\":\n case \"decimal\": {\n const record = exactObject(\n value,\n [\"kind\", \"value\"],\n [\"kind\", \"value\"],\n label\n );\n if (!isString(record.value))\n refuse(`${label}.value must be canonical text`);\n assertCanonicalParameterText(value.kind, record.value, label);\n return { kind: value.kind, value: record.value };\n }\n case \"json\": {\n const record = exactObject(\n value,\n [\"kind\", \"value\"],\n [\"kind\", \"value\"],\n label\n );\n return { kind: \"json\", value: record.value };\n }\n default:\n refuse(`${label}.kind is not a V1 parameter tag`);\n }\n}\n\nfunction assertCanonicalParameterText(\n kind: \"bigint\" | \"bytes\" | \"date-time\" | \"decimal\",\n value: string,\n label: string\n): void {\n if (kind === \"bigint\" && !CANONICAL_BIGINT.test(value)) {\n refuse(`${label}.value must be canonical bigint text`);\n }\n if (kind === \"bytes\" && decodeCanonicalBase64(value) === undefined) {\n refuse(`${label}.value must be canonical base64 text`);\n }\n if (kind === \"date-time\") {\n try {\n if (new Date(value).toISOString() !== value) {\n refuse(`${label}.value must be canonical date-time text`);\n }\n } catch {\n refuse(`${label}.value must be canonical date-time text`);\n }\n }\n if (kind === \"decimal\" && canonicalizeDecimal(value) !== value) {\n refuse(`${label}.value must be canonical decimal text`);\n }\n}\n","/**\n * Hostile parsers and hash owner for Migration V1 marker and ledger rows.\n *\n * Path identity lives next to the marker it authenticates. Reset-plan\n * admission lives next to the ledger event that carries it.\n */\n\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\nimport { isBoolean, isRecord, isString } from \"../validation/value-guards\";\nimport { canonicalizeJson } from \"./canonical-json\";\nimport { domainHash, HASH_DOMAIN, parseSha256, type Sha256 } from \"./identity\";\nimport { parseDispatch } from \"./v1-parse-dispatch\";\nimport {\n exactObject,\n parseFiniteInteger,\n parseFormat,\n parseMember,\n parseRequiredString,\n refuse,\n} from \"./v1-parse-shared\";\nimport type {\n LedgerEffectStateV1,\n LedgerEventKindV1,\n LedgerEventV1,\n MarkerIndexPredicateV1,\n MarkerPathEdgeV1,\n MigrationMarkerV1,\n ResetPlanV1,\n} from \"./v1-types\";\n\nexport function encodePathHash(path: readonly MarkerPathEdgeV1[]): Sha256 {\n return domainHash(HASH_DOMAIN.path, canonicalizeJson(path));\n}\n\nexport function eventIdFor(event: Omit<LedgerEventV1, \"eventId\">): Sha256 {\n return domainHash(HASH_DOMAIN.event, canonicalizeJson(event));\n}\n\nconst MARKER_KEYS = [\n \"estateHash\",\n \"format\",\n \"path\",\n \"pathHash\",\n \"revision\",\n \"snapshotHash\",\n \"stateId\",\n \"updatedAt\",\n] as const;\nconst PATH_EDGE_KEYS = [\n \"baselineBoundary\",\n \"stateId\",\n \"transitionHash\",\n] as const;\n\nexport function parseMarkerRow(value: unknown): MigrationMarkerV1 {\n const record = exactObject(\n value,\n MARKER_KEYS,\n MARKER_KEYS,\n \"migration marker\"\n );\n if (!Array.isArray(record.path)) refuse(\"marker.path must be an array\");\n const path = record.path.map((edge, index) => {\n const item = exactObject(\n edge,\n PATH_EDGE_KEYS,\n PATH_EDGE_KEYS,\n `marker.path[${index}]`\n );\n if (!isBoolean(item.baselineBoundary)) {\n refuse(`marker.path[${index}].baselineBoundary must be boolean`);\n }\n return {\n stateId: parseSha256(item.stateId, `marker.path[${index}].stateId`),\n transitionHash: parseSha256(\n item.transitionHash,\n `marker.path[${index}].transitionHash`\n ),\n baselineBoundary: item.baselineBoundary,\n };\n });\n const pathHash = parseSha256(record.pathHash, \"marker.pathHash\");\n if (pathHash !== encodePathHash(path)) {\n throw new MigrationError(\n \"marker.pathHash does not match the stored path\",\n VibORMErrorCode.MIGRATION_CORRUPTION\n );\n }\n if (!isString(record.updatedAt) || record.updatedAt.length === 0) {\n refuse(\"marker.updatedAt must be an ISO timestamp\");\n }\n return {\n format: parseFormat(record.format, \"marker\"),\n estateHash: parseSha256(record.estateHash, \"marker.estateHash\"),\n stateId:\n record.stateId === null\n ? null\n : parseSha256(record.stateId, \"marker.stateId\"),\n snapshotHash: parseSha256(record.snapshotHash, \"marker.snapshotHash\"),\n path,\n pathHash,\n revision: parseFiniteInteger(record.revision, \"marker.revision\"),\n updatedAt: record.updatedAt,\n };\n}\n\nconst PREDICATE_KEYS = [\"deparsed\", \"index\", \"table\"] as const;\n\n/**\n * The marker row: the marker and, beside it, the partial-index predicates an\n * apply on PostgreSQL recorded as the server deparsed them (`casMarker`).\n */\nexport function parseMarkerPayload(value: unknown): {\n readonly marker: MigrationMarkerV1;\n readonly predicates: readonly MarkerIndexPredicateV1[];\n} {\n if (!(isRecord(value) && \"predicates\" in value)) {\n return { marker: parseMarkerRow(value), predicates: [] };\n }\n const { predicates, ...marker } = value;\n if (!Array.isArray(predicates)) refuse(\"marker predicates must be an array\");\n return {\n marker: parseMarkerRow(marker),\n predicates: predicates.map((item: unknown, position) => {\n const label = `marker predicates[${position}]`;\n const record = exactObject(item, PREDICATE_KEYS, PREDICATE_KEYS, label);\n return {\n table: parseRequiredString(record.table, `${label}.table`),\n index: parseRequiredString(record.index, `${label}.index`),\n deparsed: parseRequiredString(record.deparsed, `${label}.deparsed`),\n };\n }),\n };\n}\n\nconst LEDGER_KINDS: readonly LedgerEventKindV1[] = [\n \"started\",\n \"step-confirmed\",\n \"applied\",\n \"failed\",\n \"rolled-back\",\n \"baselined\",\n \"reanchored\",\n \"resolved\",\n \"reset-started\",\n \"reset-step-confirmed\",\n \"reset-applied\",\n];\nconst EFFECT_STATES: readonly LedgerEffectStateV1[] = [\n \"none\",\n \"committed\",\n \"partial\",\n \"may-have-committed\",\n];\nconst DIRECTIONS: readonly LedgerEventV1[\"direction\"][] = [\n \"forward\",\n \"rollback\",\n \"reset\",\n \"baseline\",\n \"resolve\",\n];\nconst LEDGER_KEYS = [\n \"attemptId\",\n \"direction\",\n \"dispatchId\",\n \"effectState\",\n \"estateHash\",\n \"eventId\",\n \"failure\",\n \"finishedAt\",\n \"format\",\n \"fromState\",\n \"kind\",\n \"operationId\",\n \"snapshotHash\",\n \"sqlHash\",\n \"startedAt\",\n \"toState\",\n \"toolVersion\",\n \"transitionHash\",\n] as const;\nconst RESET_LEDGER_KEYS = [...LEDGER_KEYS, \"resetPlan\"] as const;\nconst RESET_PLAN_KEYS = [\n \"clearDispatches\",\n \"estateHash\",\n \"referencedStates\",\n \"replayPath\",\n \"resetPlanHash\",\n \"sourceFingerprint\",\n \"sourceRevision\",\n \"targetIdentity\",\n] as const;\n\nexport function parseLedgerEvent(value: unknown): LedgerEventV1 {\n if (!isRecord(value)) refuse(\"ledger event must be an object\");\n const kind = parseMember(\n value.kind,\n LEDGER_KINDS,\n \"ledger event.kind is not a V1 kind\"\n );\n const record = exactObject(\n value,\n kind === \"reset-started\" ? RESET_LEDGER_KEYS : LEDGER_KEYS,\n kind === \"reset-started\" ? RESET_LEDGER_KEYS : LEDGER_KEYS,\n \"ledger event\"\n );\n const event = {\n format: parseFormat(record.format, \"ledger event\"),\n eventId: parseSha256(record.eventId, \"ledger.eventId\"),\n attemptId: parseSha256(record.attemptId, \"ledger.attemptId\"),\n kind,\n estateHash: parseSha256(record.estateHash, \"ledger.estateHash\"),\n snapshotHash: parseSha256(record.snapshotHash, \"ledger.snapshotHash\"),\n sqlHash:\n record.sqlHash === null\n ? null\n : parseSha256(record.sqlHash, \"ledger.sqlHash\"),\n fromState:\n record.fromState === null\n ? null\n : parseSha256(record.fromState, \"ledger.fromState\"),\n toState:\n record.toState === null\n ? null\n : parseSha256(record.toState, \"ledger.toState\"),\n transitionHash:\n record.transitionHash === null\n ? null\n : parseSha256(record.transitionHash, \"ledger.transitionHash\"),\n direction: parseMember(\n record.direction,\n DIRECTIONS,\n \"ledger event.direction is invalid\"\n ),\n operationId:\n record.operationId === null\n ? null\n : parseRequiredString(record.operationId, \"ledger.operationId\"),\n dispatchId:\n record.dispatchId === null\n ? null\n : parseSha256(record.dispatchId, \"ledger.dispatchId\"),\n effectState: parseMember(\n record.effectState,\n EFFECT_STATES,\n \"ledger event.effectState is invalid\"\n ),\n startedAt: parseRequiredString(record.startedAt, \"ledger.startedAt\"),\n finishedAt:\n record.finishedAt === null\n ? null\n : parseRequiredString(record.finishedAt, \"ledger.finishedAt\"),\n toolVersion: parseRequiredString(record.toolVersion, \"ledger.toolVersion\"),\n failure:\n record.failure === null\n ? null\n : parseRequiredString(record.failure, \"ledger.failure\"),\n };\n const admitted =\n kind === \"reset-started\"\n ? { ...event, resetPlan: parseResetPlan(record.resetPlan) }\n : event;\n const { eventId, ...body } = admitted;\n if (eventId !== eventIdFor(body)) {\n throw new MigrationError(\n \"ledger eventId does not match the canonical event\",\n VibORMErrorCode.MIGRATION_CORRUPTION\n );\n }\n return admitted;\n}\n\nfunction parseResetPlan(value: unknown): ResetPlanV1 {\n const record = exactObject(\n value,\n RESET_PLAN_KEYS,\n RESET_PLAN_KEYS,\n \"reset plan\"\n );\n if (\n !(\n Array.isArray(record.replayPath) &&\n Array.isArray(record.clearDispatches) &&\n Array.isArray(record.referencedStates)\n )\n ) {\n refuse(\"reset plan arrays are malformed\");\n }\n const plan: ResetPlanV1 = {\n estateHash: parseSha256(record.estateHash, \"resetPlan.estateHash\"),\n targetIdentity: parseRequiredString(\n record.targetIdentity,\n \"resetPlan.targetIdentity\"\n ),\n sourceRevision: parseFiniteInteger(\n record.sourceRevision,\n \"resetPlan.sourceRevision\"\n ),\n sourceFingerprint: parseSha256(\n record.sourceFingerprint,\n \"resetPlan.sourceFingerprint\"\n ),\n replayPath: record.replayPath.map((id, index) =>\n parseSha256(id, `resetPlan.replayPath[${index}]`)\n ),\n clearDispatches: record.clearDispatches.map((dispatch, index) =>\n parseDispatch(dispatch, `resetPlan.clearDispatches[${index}]`)\n ),\n referencedStates: record.referencedStates.map((id, index) =>\n parseSha256(id, `resetPlan.referencedStates[${index}]`)\n ),\n resetPlanHash: parseSha256(record.resetPlanHash, \"resetPlan.resetPlanHash\"),\n };\n const { resetPlanHash, ...body } = plan;\n if (\n resetPlanHash !== domainHash(HASH_DOMAIN.resetPlan, canonicalizeJson(body))\n ) {\n throw new MigrationError(\n \"resetPlanHash does not match the canonical reset plan\",\n VibORMErrorCode.MIGRATION_CORRUPTION\n );\n }\n return plan;\n}\n","/**\n * Hostile parser and hash owner for Migration V1 schema snapshots.\n *\n * Snapshot bytes are admitted only after exact-key validation,\n * re-canonicalization against the original bytes, and hash recomputation.\n */\n\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\nimport type { DecimalDescriptor } from \"../validation/primitives/decimal-codec\";\nimport {\n isBoolean,\n isNumber,\n isRecord,\n isString,\n} from \"../validation/value-guards\";\nimport {\n assertCanonicalBytes,\n canonicalizeJson,\n parseJsonBytes,\n} from \"./canonical-json\";\nimport { domainHash, HASH_DOMAIN, type Sha256 } from \"./identity\";\nimport type {\n ColumnDef,\n EnumDef,\n ForeignKeyDef,\n IndexDef,\n PolymorphicSnapshotStorage,\n PolymorphicToManySnapshotMember,\n PolymorphicToOneSnapshotMember,\n PolymorphicToOneStorageRegistryEntry,\n PrimaryKeyDef,\n ReferentialAction,\n SchemaSnapshot,\n TableDef,\n UniqueConstraintDef,\n} from \"./types\";\nimport {\n exactObject,\n parseIdentifierArray,\n parseMember,\n parseRequiredString,\n parseStringArray,\n refuse,\n} from \"./v1-parse-shared\";\n\nconst SNAPSHOT_KEYS = [\"enums\", \"polymorphicStorage\", \"tables\"] as const;\nconst TABLE_KEYS = [\n \"columns\",\n \"foreignKeys\",\n \"indexes\",\n \"name\",\n \"primaryKey\",\n \"relationStorage\",\n \"uniqueConstraints\",\n] as const;\nconst TABLE_REQUIRED_KEYS = [\n \"columns\",\n \"foreignKeys\",\n \"indexes\",\n \"name\",\n \"uniqueConstraints\",\n] as const;\nconst COLUMN_KEYS = [\n \"autoIncrement\",\n \"dateTime\",\n \"geoPointEncoding\",\n \"decimal\",\n \"default\",\n \"name\",\n \"nullable\",\n \"type\",\n] as const;\nconst DECIMAL_KEYS = [\"precision\", \"scale\"] as const;\nconst PRIMARY_KEY_KEYS = [\"columns\", \"name\"] as const;\nconst INDEX_KEYS = [\"columns\", \"name\", \"type\", \"unique\", \"where\"] as const;\nconst FOREIGN_KEY_KEYS = [\n \"columns\",\n \"name\",\n \"onDelete\",\n \"onUpdate\",\n \"referencedColumns\",\n \"referencedTable\",\n] as const;\nconst UNIQUE_CONSTRAINT_KEYS = [\"columns\", \"name\"] as const;\nconst ENUM_KEYS = [\"name\", \"values\"] as const;\nconst RELATION_STORAGE_KEYS = [\n \"idColumn\",\n \"index\",\n \"kind\",\n \"typeColumn\",\n] as const;\nconst POLYMORPHIC_TO_ONE_KEYS = [\n \"kind\",\n \"members\",\n \"ownerTable\",\n \"relation\",\n \"storageRef\",\n] as const;\nconst POLYMORPHIC_TO_MANY_KEYS = [\n \"kind\",\n \"members\",\n \"ownerTable\",\n \"relation\",\n] as const;\nconst POLYMORPHIC_TO_ONE_MEMBER_KEYS = [\n \"publicType\",\n \"storedType\",\n \"targetTable\",\n] as const;\nconst POLYMORPHIC_TO_MANY_MEMBER_KEYS = [\n \"inverseCardinality\",\n \"memberJunctionTable\",\n \"publicType\",\n \"storedType\",\n \"targetTable\",\n] as const;\n\nfunction parseColumn(value: unknown, label: string): ColumnDef {\n const record = exactObject(\n value,\n COLUMN_KEYS,\n [\"name\", \"nullable\", \"type\"],\n label\n );\n if (!isBoolean(record.nullable)) refuse(`${label}.nullable must be boolean`);\n const column: ColumnDef = {\n name: parseRequiredString(record.name, `${label}.name`),\n type: parseRequiredString(record.type, `${label}.type`),\n nullable: record.nullable,\n };\n if (\"default\" in record) {\n if (!isString(record.default)) refuse(`${label}.default must be a string`);\n column.default = record.default;\n }\n if (\"autoIncrement\" in record) {\n if (!isBoolean(record.autoIncrement)) {\n refuse(`${label}.autoIncrement must be boolean`);\n }\n column.autoIncrement = record.autoIncrement;\n }\n if (\"decimal\" in record) {\n column.decimal = parseDecimalDescriptor(record.decimal, `${label}.decimal`);\n }\n if (\"geoPointEncoding\" in record) {\n if (\n (record.geoPointEncoding !== \"legacy\" &&\n record.geoPointEncoding !== \"binary64\") ||\n column.type.toUpperCase() !== \"VIBORM_GEO_TEXT\" ||\n column.decimal !== undefined ||\n \"dateTime\" in record\n )\n refuse(`${label}.geoPointEncoding contradicts its physical type`);\n column.geoPointEncoding = record.geoPointEncoding;\n }\n if (\"dateTime\" in record) {\n if (\n !isString(record.dateTime) ||\n (record.dateTime !== \"text\" &&\n record.dateTime !== \"epochMillis\" &&\n record.dateTime !== \"julianDay\")\n ) {\n refuse(`${label}.dateTime must name a DateTime physical form`);\n }\n const physicalType =\n record.dateTime === \"text\"\n ? \"TEXT\"\n : record.dateTime === \"epochMillis\"\n ? \"INTEGER\"\n : \"REAL\";\n if (column.type.toUpperCase() !== physicalType) {\n refuse(`${label}.dateTime contradicts its physical type`);\n }\n if (column.decimal !== undefined) {\n refuse(`${label} cannot be both DateTime and fixed-decimal storage`);\n }\n column.dateTime = record.dateTime;\n }\n return column;\n}\n\nfunction parseDecimalDescriptor(\n value: unknown,\n label: string\n): DecimalDescriptor {\n const record = exactObject(value, DECIMAL_KEYS, DECIMAL_KEYS, label);\n if (\n !(isNumber(record.precision) && Number.isSafeInteger(record.precision)) ||\n record.precision < 1\n ) {\n refuse(`${label}.precision must be a positive safe integer`);\n }\n if (\n !(isNumber(record.scale) && Number.isSafeInteger(record.scale)) ||\n Object.is(record.scale, -0) ||\n record.scale < 0 ||\n record.scale > record.precision\n ) {\n refuse(`${label}.scale must be a safe integer between 0 and precision`);\n }\n return { precision: record.precision, scale: record.scale };\n}\n\nfunction parsePrimaryKey(value: unknown, label: string): PrimaryKeyDef {\n const record = exactObject(value, PRIMARY_KEY_KEYS, [\"columns\"], label);\n const primaryKey: PrimaryKeyDef = {\n columns: parseIdentifierArray(record.columns, `${label}.columns`),\n };\n if (\"name\" in record) {\n primaryKey.name = parseRequiredString(record.name, `${label}.name`);\n }\n return primaryKey;\n}\n\nfunction parseIndex(value: unknown, label: string): IndexDef {\n const record = exactObject(\n value,\n INDEX_KEYS,\n [\"columns\", \"name\", \"unique\"],\n label\n );\n if (!isBoolean(record.unique)) refuse(`${label}.unique must be boolean`);\n const index: IndexDef = {\n name: parseRequiredString(record.name, `${label}.name`),\n columns: parseIdentifierArray(record.columns, `${label}.columns`),\n unique: record.unique,\n };\n if (\"type\" in record) {\n if (\n record.type !== \"btree\" &&\n record.type !== \"hash\" &&\n record.type !== \"gin\" &&\n record.type !== \"gist\" &&\n record.type !== \"fulltext\" &&\n record.type !== \"spatial\"\n ) {\n refuse(`${label}.type is invalid`);\n }\n index.type = record.type;\n }\n if (\"where\" in record) {\n if (!isString(record.where)) refuse(`${label}.where must be a string`);\n index.where = record.where;\n }\n return index;\n}\n\nconst REFERENTIAL_ACTIONS: readonly ReferentialAction[] = [\n \"cascade\",\n \"setNull\",\n \"restrict\",\n \"noAction\",\n \"setDefault\",\n];\n\nfunction parseForeignKey(value: unknown, label: string): ForeignKeyDef {\n const record = exactObject(\n value,\n FOREIGN_KEY_KEYS,\n [\"columns\", \"name\", \"referencedColumns\", \"referencedTable\"],\n label\n );\n const foreignKey: ForeignKeyDef = {\n name: parseRequiredString(record.name, `${label}.name`),\n columns: parseIdentifierArray(record.columns, `${label}.columns`),\n referencedTable: parseRequiredString(\n record.referencedTable,\n `${label}.referencedTable`\n ),\n referencedColumns: parseIdentifierArray(\n record.referencedColumns,\n `${label}.referencedColumns`\n ),\n };\n if (\"onDelete\" in record) {\n foreignKey.onDelete = parseMember(\n record.onDelete,\n REFERENTIAL_ACTIONS,\n `${label}.onDelete is not a referential action`\n );\n }\n if (\"onUpdate\" in record) {\n foreignKey.onUpdate = parseMember(\n record.onUpdate,\n REFERENTIAL_ACTIONS,\n `${label}.onUpdate is not a referential action`\n );\n }\n return foreignKey;\n}\n\nfunction parseUniqueConstraint(\n value: unknown,\n label: string\n): UniqueConstraintDef {\n const record = exactObject(\n value,\n UNIQUE_CONSTRAINT_KEYS,\n UNIQUE_CONSTRAINT_KEYS,\n label\n );\n return {\n name: parseRequiredString(record.name, `${label}.name`),\n columns: parseIdentifierArray(record.columns, `${label}.columns`),\n };\n}\n\nfunction parseRelationStorage(\n value: unknown,\n label: string\n): Readonly<Record<string, PolymorphicToOneStorageRegistryEntry>> {\n if (!isRecord(value)) refuse(`${label} must be an object`);\n const entries: Record<string, PolymorphicToOneStorageRegistryEntry> = {};\n for (const [storageRef, rawEntry] of Object.entries(value)) {\n const entryLabel = `${label}.${storageRef}`;\n const record = exactObject(\n rawEntry,\n RELATION_STORAGE_KEYS,\n RELATION_STORAGE_KEYS,\n entryLabel\n );\n if (record.kind !== \"polymorphicToOne\") {\n refuse(`${entryLabel}.kind must be polymorphicToOne`);\n }\n Object.defineProperty(entries, storageRef, {\n configurable: true,\n enumerable: true,\n value: {\n kind: \"polymorphicToOne\",\n typeColumn: parseRequiredString(\n record.typeColumn,\n `${entryLabel}.typeColumn`\n ),\n idColumn: parseRequiredString(\n record.idColumn,\n `${entryLabel}.idColumn`\n ),\n index: parseRequiredString(record.index, `${entryLabel}.index`),\n },\n writable: true,\n });\n }\n return entries;\n}\n\nfunction parseTable(value: unknown, label: string): TableDef {\n const record = exactObject(value, TABLE_KEYS, TABLE_REQUIRED_KEYS, label);\n if (!Array.isArray(record.columns))\n refuse(`${label}.columns must be an array`);\n if (!Array.isArray(record.indexes))\n refuse(`${label}.indexes must be an array`);\n if (!Array.isArray(record.foreignKeys)) {\n refuse(`${label}.foreignKeys must be an array`);\n }\n if (!Array.isArray(record.uniqueConstraints)) {\n refuse(`${label}.uniqueConstraints must be an array`);\n }\n const table: TableDef = {\n name: parseRequiredString(record.name, `${label}.name`),\n columns: record.columns.map((column, index) =>\n parseColumn(column, `${label}.columns[${index}]`)\n ),\n indexes: record.indexes.map((index, position) =>\n parseIndex(index, `${label}.indexes[${position}]`)\n ),\n foreignKeys: record.foreignKeys.map((foreignKey, index) =>\n parseForeignKey(foreignKey, `${label}.foreignKeys[${index}]`)\n ),\n uniqueConstraints: record.uniqueConstraints.map((constraint, index) =>\n parseUniqueConstraint(constraint, `${label}.uniqueConstraints[${index}]`)\n ),\n };\n if (\"primaryKey\" in record) {\n table.primaryKey = parsePrimaryKey(\n record.primaryKey,\n `${label}.primaryKey`\n );\n }\n if (\"relationStorage\" in record) {\n table.relationStorage = parseRelationStorage(\n record.relationStorage,\n `${label}.relationStorage`\n );\n }\n return table;\n}\n\nfunction parseEnum(value: unknown, label: string): EnumDef {\n const record = exactObject(value, ENUM_KEYS, ENUM_KEYS, label);\n return {\n name: parseRequiredString(record.name, `${label}.name`),\n values: parseStringArray(record.values, `${label}.values`),\n };\n}\n\nfunction parseToOneMember(\n value: unknown,\n label: string\n): PolymorphicToOneSnapshotMember {\n const record = exactObject(\n value,\n POLYMORPHIC_TO_ONE_MEMBER_KEYS,\n POLYMORPHIC_TO_ONE_MEMBER_KEYS,\n label\n );\n return {\n publicType: parseRequiredString(record.publicType, `${label}.publicType`),\n storedType: parseRequiredString(record.storedType, `${label}.storedType`),\n targetTable: parseRequiredString(\n record.targetTable,\n `${label}.targetTable`\n ),\n };\n}\n\nfunction parseToManyMember(\n value: unknown,\n label: string\n): PolymorphicToManySnapshotMember {\n const record = exactObject(\n value,\n POLYMORPHIC_TO_MANY_MEMBER_KEYS,\n POLYMORPHIC_TO_MANY_MEMBER_KEYS,\n label\n );\n if (\n record.inverseCardinality !== \"one\" &&\n record.inverseCardinality !== \"many\"\n ) {\n refuse(`${label}.inverseCardinality must be one or many`);\n }\n return {\n publicType: parseRequiredString(record.publicType, `${label}.publicType`),\n storedType: parseRequiredString(record.storedType, `${label}.storedType`),\n targetTable: parseRequiredString(\n record.targetTable,\n `${label}.targetTable`\n ),\n memberJunctionTable: parseRequiredString(\n record.memberJunctionTable,\n `${label}.memberJunctionTable`\n ),\n inverseCardinality: record.inverseCardinality,\n };\n}\n\nfunction parsePolymorphicStorage(\n value: unknown,\n label: string\n): PolymorphicSnapshotStorage {\n if (!isRecord(value)) refuse(`${label} must be an object`);\n if (value.kind === \"toOne\") {\n const record = exactObject(\n value,\n POLYMORPHIC_TO_ONE_KEYS,\n POLYMORPHIC_TO_ONE_KEYS,\n label\n );\n if (!Array.isArray(record.members)) {\n refuse(`${label}.members must be an array`);\n }\n return {\n ownerTable: parseRequiredString(record.ownerTable, `${label}.ownerTable`),\n relation: parseRequiredString(record.relation, `${label}.relation`),\n kind: \"toOne\",\n storageRef: parseRequiredString(record.storageRef, `${label}.storageRef`),\n members: record.members.map((member, index) =>\n parseToOneMember(member, `${label}.members[${index}]`)\n ),\n };\n }\n if (value.kind === \"toMany\") {\n const record = exactObject(\n value,\n POLYMORPHIC_TO_MANY_KEYS,\n POLYMORPHIC_TO_MANY_KEYS,\n label\n );\n if (!Array.isArray(record.members)) {\n refuse(`${label}.members must be an array`);\n }\n return {\n ownerTable: parseRequiredString(record.ownerTable, `${label}.ownerTable`),\n relation: parseRequiredString(record.relation, `${label}.relation`),\n kind: \"toMany\",\n members: record.members.map((member, index) =>\n parseToManyMember(member, `${label}.members[${index}]`)\n ),\n };\n }\n refuse(`${label}.kind must be toOne or toMany`);\n}\n\nexport function parseSnapshotDocument(\n bytes: Uint8Array,\n expectedHash: Sha256\n): SchemaSnapshot {\n const parsed = parseJsonBytes(bytes, `snapshots/${expectedHash}.json`);\n const record = exactObject(parsed, SNAPSHOT_KEYS, [\"tables\"], \"snapshot\");\n if (!Array.isArray(record.tables)) refuse(\"snapshot.tables must be an array\");\n const snapshot: SchemaSnapshot = {\n tables: record.tables.map((table, index) =>\n parseTable(table, `snapshot.tables[${index}]`)\n ),\n };\n if (\"enums\" in record) {\n if (!Array.isArray(record.enums)) refuse(\"snapshot.enums must be an array\");\n snapshot.enums = record.enums.map((enumDef, index) =>\n parseEnum(enumDef, `snapshot.enums[${index}]`)\n );\n }\n if (\"polymorphicStorage\" in record) {\n if (!Array.isArray(record.polymorphicStorage)) {\n refuse(\"snapshot.polymorphicStorage must be an array\");\n }\n snapshot.polymorphicStorage = record.polymorphicStorage.map(\n (storage, index) =>\n parsePolymorphicStorage(\n storage,\n `snapshot.polymorphicStorage[${index}]`\n )\n );\n }\n assertCanonicalBytes(bytes, snapshot, `snapshots/${expectedHash}.json`);\n const actual = domainHash(HASH_DOMAIN.snapshot, bytes);\n if (actual !== expectedHash) {\n throw new MigrationError(\n \"snapshot filename does not match its canonical bytes\",\n VibORMErrorCode.MIGRATION_CORRUPTION\n );\n }\n return snapshot;\n}\n\nexport function encodeSnapshot(snapshot: SchemaSnapshot): {\n bytes: Uint8Array;\n snapshotHash: Sha256;\n} {\n const bytes = canonicalizeJson(omitUndefinedKeys(snapshot));\n return { bytes, snapshotHash: domainHash(HASH_DOMAIN.snapshot, bytes) };\n}\n\nfunction omitUndefinedKeys(value: unknown): unknown {\n if (Array.isArray(value)) {\n return value.map((item) => omitUndefinedKeys(item));\n }\n if (!isRecord(value)) return value;\n const admitted: Record<string, unknown> = {};\n for (const key of Object.keys(value)) {\n const item = value[key];\n if (item === undefined) continue;\n admitted[key] = omitUndefinedKeys(item);\n }\n return admitted;\n}\n","import { normalizeManagedTables } from \"./target\";\n/**\n * Hostile parsers and hash owners for Migration V1 estate, dispatch,\n * state, and transition artifacts.\n *\n * Snapshot and control admission live in sibling modules. This file\n * re-exports them so existing `./v1-parse` imports keep working.\n * Every JSON boundary admits a value only after exact-key validation,\n * re-canonicalization against the original bytes, and hash recomputation.\n * No `JSON.parse(...) as SchemaSnapshot` remains.\n */\n\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\nimport { isBoolean, isRecord, isString } from \"../validation/value-guards\";\nimport {\n assertCanonicalBytes,\n canonicalizeJson,\n parseJsonBytes,\n} from \"./canonical-json\";\nimport {\n domainHash,\n HASH_ALGORITHM,\n HASH_DOMAIN,\n parseSha256,\n type Sha256,\n} from \"./identity\";\nimport type { MigrationTarget } from \"./types\";\nimport { parseDispatch } from \"./v1-parse-dispatch\";\nimport { exactObject, parseFormat, refuse } from \"./v1-parse-shared\";\nimport type {\n MigrationApprovalV1,\n MigrationBooleanCheckV1,\n MigrationEstateDescriptorV1,\n MigrationOperationV1,\n MigrationParentTransitionV1,\n MigrationRollbackV1,\n MigrationStateManifestV1,\n MigrationStepV1,\n} from \"./v1-types\";\n\nexport {\n encodePathHash,\n eventIdFor,\n parseLedgerEvent,\n parseMarkerRow,\n} from \"./v1-parse-control\";\nexport { encodeDispatchIdentity, parseDispatch } from \"./v1-parse-dispatch\";\nexport {\n encodeSnapshot,\n parseSnapshotDocument,\n} from \"./v1-parse-snapshot\";\n\nconst ESTATE_KEYS = [\"format\", \"hash\", \"target\"] as const;\nconst PG_TARGET_KEYS = [\"dialect\", \"namespace\", \"tables\"] as const;\nconst DIALECT_ONLY_TARGET_KEYS = [\"dialect\", \"tables\"] as const;\nconst CHECK_KEYS = [\"equals\", \"id\", \"kind\", \"query\"] as const;\nconst PROVEN_STEP_KEYS = [\"execute\", \"postcheck\", \"precheck\", \"retry\"] as const;\nconst OPAQUE_STEP_KEYS = [\"execute\", \"retry\"] as const;\nconst OPERATION_KEYS = [\"id\", \"label\", \"origin\", \"risk\", \"steps\"] as const;\nconst SCHEMA_ROLLBACK_KEYS = [\"kind\", \"operations\"] as const;\nconst MANUAL_ROLLBACK_KEYS = [\n \"kind\",\n \"operations\",\n \"requestedBoundary\",\n] as const;\nconst IRREVERSIBLE_KEYS = [\"kind\", \"reason\"] as const;\nconst PARENT_KEYS = [\n \"approvals\",\n \"fromState\",\n \"operations\",\n \"originChecks\",\n \"requestedForwardBoundary\",\n \"rollback\",\n \"transitionHash\",\n] as const;\nconst STATE_KEYS = [\n \"destinationChecks\",\n \"estateHash\",\n \"format\",\n \"name\",\n \"parents\",\n \"snapshotHash\",\n \"sqlHash\",\n \"stateId\",\n] as const;\nconst STATE_HASH_KEYS = [\n \"destinationChecks\",\n \"estateHash\",\n \"format\",\n \"name\",\n \"parents\",\n \"snapshotHash\",\n \"sqlHash\",\n] as const;\nconst PARENT_REQUIRED_KEYS = PARENT_KEYS.filter((key) => key !== \"approvals\");\nconst TRANSITION_HASH_KEYS = [\n \"approvals\",\n \"fromState\",\n \"operations\",\n \"originChecks\",\n \"requestedForwardBoundary\",\n \"rollback\",\n] as const;\nconst APPROVAL_KEYS = [\"column\", \"operation\", \"table\"] as const;\nconst APPROVAL_OPERATIONS: readonly MigrationApprovalV1[\"operation\"][] = [\n \"addColumn\",\n \"alterColumn\",\n \"dropColumn\",\n \"dropTable\",\n];\n\nfunction parseManagedTables(value: unknown, label: string): readonly string[] {\n try {\n const tables = normalizeManagedTables(value);\n if (tables !== undefined) return tables;\n } catch {\n refuse(\n `${label}.tables must be a sorted, unique array of physical table names`\n );\n }\n return refuse(`${label}.tables must be an array`);\n}\n\nexport function parseMigrationTarget(\n value: unknown,\n label: string\n): MigrationTarget {\n if (!isRecord(value)) refuse(`${label} must be an object`);\n const dialect = value.dialect;\n if (dialect === \"postgresql\") {\n const record = exactObject(\n value,\n PG_TARGET_KEYS,\n [\"dialect\", \"namespace\"],\n label\n );\n if (!isString(record.namespace) || record.namespace.length === 0) {\n refuse(`${label}.namespace must be a non-empty string`);\n }\n return {\n dialect: \"postgresql\",\n namespace: record.namespace,\n ...(value.tables === undefined\n ? {}\n : { tables: parseManagedTables(value.tables, label) }),\n };\n }\n if (dialect === \"mysql\" || dialect === \"sqlite\") {\n exactObject(value, DIALECT_ONLY_TARGET_KEYS, [\"dialect\"], label);\n return {\n dialect,\n ...(value.tables === undefined\n ? {}\n : { tables: parseManagedTables(value.tables, label) }),\n };\n }\n refuse(`${label}.dialect is not a V1 migration target`);\n}\n\nexport function parseEstateDescriptor(bytes: Uint8Array): {\n descriptor: MigrationEstateDescriptorV1;\n estateHash: Sha256;\n} {\n const parsed = parseJsonBytes(bytes, \"estate.json\");\n const record = exactObject(parsed, ESTATE_KEYS, ESTATE_KEYS, \"estate.json\");\n if (record.hash !== HASH_ALGORITHM) {\n refuse('estate.json hash algorithm must be \"sha256\"');\n }\n const descriptor: MigrationEstateDescriptorV1 = {\n format: parseFormat(record.format, \"estate.json\"),\n target: parseMigrationTarget(record.target, \"estate.json.target\"),\n hash: \"sha256\",\n };\n assertCanonicalBytes(bytes, descriptor, \"estate.json\");\n return { descriptor, estateHash: domainHash(HASH_DOMAIN.estate, bytes) };\n}\n\nexport function encodeEstateDescriptor(target: MigrationTarget): {\n bytes: Uint8Array;\n estateHash: Sha256;\n descriptor: MigrationEstateDescriptorV1;\n} {\n const descriptor: MigrationEstateDescriptorV1 = {\n format: \"1\",\n target,\n hash: \"sha256\",\n };\n const bytes = canonicalizeJson(descriptor);\n return {\n bytes,\n estateHash: domainHash(HASH_DOMAIN.estate, bytes),\n descriptor,\n };\n}\n\nfunction parseCheck(value: unknown, label: string): MigrationBooleanCheckV1 {\n const record = exactObject(value, CHECK_KEYS, CHECK_KEYS, label);\n if (record.kind !== \"driver\" && record.kind !== \"trusted-read\") {\n refuse(`${label}.kind must be driver or trusted-read`);\n }\n if (!isString(record.id) || record.id.length === 0) {\n refuse(`${label}.id must be a non-empty string`);\n }\n if (!isBoolean(record.equals)) refuse(`${label}.equals must be boolean`);\n return {\n kind: record.kind,\n id: record.id,\n query: parseDispatch(record.query, `${label}.query`),\n equals: record.equals,\n };\n}\n\nfunction parseStep(value: unknown, label: string): MigrationStepV1 {\n if (\n !isRecord(value) ||\n (value.retry !== \"proven\" && value.retry !== \"opaque\")\n ) {\n refuse(`${label}.retry must be proven or opaque`);\n }\n if (value.retry === \"proven\") {\n const record = exactObject(\n value,\n PROVEN_STEP_KEYS,\n PROVEN_STEP_KEYS,\n label\n );\n return {\n retry: \"proven\",\n precheck: parseCheck(record.precheck, `${label}.precheck`),\n execute: parseDispatch(record.execute, `${label}.execute`),\n postcheck: parseCheck(record.postcheck, `${label}.postcheck`),\n };\n }\n const record = exactObject(value, OPAQUE_STEP_KEYS, OPAQUE_STEP_KEYS, label);\n return {\n retry: \"opaque\",\n execute: parseDispatch(record.execute, `${label}.execute`),\n };\n}\n\nfunction parseOperation(value: unknown, label: string): MigrationOperationV1 {\n const record = exactObject(value, OPERATION_KEYS, OPERATION_KEYS, label);\n if (!isString(record.id) || record.id.length === 0)\n refuse(`${label}.id is required`);\n if (!isString(record.label) || record.label.length === 0) {\n refuse(`${label}.label is required`);\n }\n if (record.origin !== \"generated\" && record.origin !== \"manual\") {\n refuse(`${label}.origin must be generated or manual`);\n }\n if (\n record.risk !== \"safe\" &&\n record.risk !== \"destructive\" &&\n record.risk !== \"opaque\"\n ) {\n refuse(`${label}.risk is not a V1 risk class`);\n }\n if (!Array.isArray(record.steps) || record.steps.length === 0) {\n refuse(`${label}.steps must be a non-empty array`);\n }\n return {\n id: record.id,\n label: record.label,\n origin: record.origin,\n risk: record.risk,\n steps: record.steps.map((step, index) =>\n parseStep(step, `${label}.steps[${index}]`)\n ),\n };\n}\n\nfunction parseRollback(value: unknown, label: string): MigrationRollbackV1 {\n if (!(isRecord(value) && isString(value.kind)))\n refuse(`${label} must be a tagged rollback`);\n if (value.kind === \"schema\") {\n const record = exactObject(\n value,\n SCHEMA_ROLLBACK_KEYS,\n SCHEMA_ROLLBACK_KEYS,\n label\n );\n if (!Array.isArray(record.operations))\n refuse(`${label}.operations must be an array`);\n return {\n kind: \"schema\",\n operations: record.operations.map((operation, index) =>\n parseOperation(operation, `${label}.operations[${index}]`)\n ),\n };\n }\n if (value.kind === \"manual\") {\n const record = exactObject(\n value,\n MANUAL_ROLLBACK_KEYS,\n MANUAL_ROLLBACK_KEYS,\n label\n );\n if (\n record.requestedBoundary !== \"transactional\" &&\n record.requestedBoundary !== \"stepwise\"\n ) {\n refuse(`${label}.requestedBoundary must be transactional or stepwise`);\n }\n if (!Array.isArray(record.operations))\n refuse(`${label}.operations must be an array`);\n return {\n kind: \"manual\",\n requestedBoundary: record.requestedBoundary,\n operations: record.operations.map((operation, index) =>\n parseOperation(operation, `${label}.operations[${index}]`)\n ),\n };\n }\n if (value.kind === \"irreversible\") {\n const record = exactObject(\n value,\n IRREVERSIBLE_KEYS,\n IRREVERSIBLE_KEYS,\n label\n );\n if (!isString(record.reason) || record.reason.trim().length === 0) {\n refuse(`${label}.reason must be a non-empty string`);\n }\n return { kind: \"irreversible\", reason: record.reason };\n }\n refuse(`${label}.kind is not a V1 rollback`);\n}\n\n/** Absent, never empty: one encoding for \"no destructive change\". */\nfunction parseApprovals(\n value: unknown,\n label: string\n): readonly MigrationApprovalV1[] {\n if (!Array.isArray(value) || value.length === 0) {\n refuse(`${label} must be a non-empty array`);\n }\n return value.map((entry, index) => {\n const at = `${label}[${index}]`;\n return parseApproval(\n exactObject(entry, APPROVAL_KEYS, APPROVAL_KEYS, at),\n at\n );\n });\n}\n\n/**\n * One approval's fields, wherever an approval is spelled: a stored\n * transition's, or a predefined resolver's `destructive` decision, which\n * refuses as its own input (`refuseWith`).\n */\nexport function parseApproval(\n fields: Readonly<Record<string, unknown>>,\n at: string,\n refuseWith: (message: string) => never = refuse\n): MigrationApprovalV1 {\n const { column, operation, table } = fields;\n const known = APPROVAL_OPERATIONS.find((name) => name === operation);\n if (!known) refuseWith(`${at}.operation is not a destructive operation`);\n if (!isString(table) || table.length === 0) {\n refuseWith(`${at}.table must be a non-empty string`);\n }\n if (column !== null && !(isString(column) && column.length > 0)) {\n refuseWith(`${at}.column must be a non-empty string or null`);\n }\n return { operation: known, table, column };\n}\n\nexport function encodeTransitionHash(\n transition: Omit<MigrationParentTransitionV1, \"transitionHash\">\n): Sha256 {\n const body: Record<string, unknown> = {};\n for (const key of TRANSITION_HASH_KEYS) {\n if (transition[key] !== undefined) body[key] = transition[key];\n }\n return domainHash(HASH_DOMAIN.transition, canonicalizeJson(body));\n}\n\nfunction parseParent(\n value: unknown,\n label: string\n): MigrationParentTransitionV1 {\n const record = exactObject(value, PARENT_KEYS, PARENT_REQUIRED_KEYS, label);\n const fromState =\n record.fromState === null\n ? null\n : parseSha256(record.fromState, `${label}.fromState`);\n if (\n record.requestedForwardBoundary !== null &&\n record.requestedForwardBoundary !== \"transactional\" &&\n record.requestedForwardBoundary !== \"stepwise\"\n ) {\n refuse(`${label}.requestedForwardBoundary is invalid`);\n }\n if (!Array.isArray(record.originChecks))\n refuse(`${label}.originChecks must be an array`);\n if (!Array.isArray(record.operations))\n refuse(`${label}.operations must be an array`);\n const operations = record.operations.map((operation, index) =>\n parseOperation(operation, `${label}.operations[${index}]`)\n );\n const rollback = parseRollback(record.rollback, `${label}.rollback`);\n const origins = new Set(operations.map((operation) => operation.origin));\n if (origins.size > 1) {\n refuse(`${label} mixes generated and manual operations`);\n }\n if (record.requestedForwardBoundary !== null && origins.has(\"generated\")) {\n refuse(\n `${label}.requestedForwardBoundary is only valid on a manual transition`\n );\n }\n if (rollback.kind === \"manual\" && origins.has(\"generated\")) {\n refuse(`${label}.rollback cannot be manual on a generated transition`);\n }\n const parsed: Omit<MigrationParentTransitionV1, \"transitionHash\"> = {\n fromState,\n originChecks: record.originChecks.map((check, index) =>\n parseCheck(check, `${label}.originChecks[${index}]`)\n ),\n requestedForwardBoundary: record.requestedForwardBoundary,\n operations,\n rollback,\n ...(record.approvals === undefined\n ? {}\n : { approvals: parseApprovals(record.approvals, `${label}.approvals`) }),\n };\n const transitionHash = parseSha256(\n record.transitionHash,\n `${label}.transitionHash`\n );\n const expected = encodeTransitionHash(parsed);\n if (transitionHash !== expected) {\n throw new MigrationError(\n `${label}.transitionHash does not match its transition`,\n VibORMErrorCode.MIGRATION_CORRUPTION\n );\n }\n return { ...parsed, transitionHash };\n}\n\nexport function compareFromState(\n left: Sha256 | null,\n right: Sha256 | null\n): number {\n if (left === right) return 0;\n if (left === null) return -1;\n if (right === null) return 1;\n return left < right ? -1 : 1;\n}\n\nexport function sortParents(\n parents: readonly MigrationParentTransitionV1[]\n): MigrationParentTransitionV1[] {\n return [...parents].sort((left, right) =>\n compareFromState(left.fromState, right.fromState)\n );\n}\n\nexport function encodeStateId(\n manifest: Omit<MigrationStateManifestV1, \"stateId\">\n): Sha256 {\n const body: Record<string, unknown> = {};\n for (const key of STATE_HASH_KEYS) {\n body[key] = manifest[key];\n }\n return domainHash(HASH_DOMAIN.state, canonicalizeJson(body));\n}\n\nexport function parseStateManifest(\n bytes: Uint8Array,\n expectedId: Sha256\n): MigrationStateManifestV1 {\n const parsed = parseJsonBytes(bytes, `states/${expectedId}.json`);\n const record = exactObject(parsed, STATE_KEYS, STATE_KEYS, \"state manifest\");\n if (!Array.isArray(record.parents) || record.parents.length === 0) {\n refuse(\"state manifest must have at least one parent transition\");\n }\n if (!Array.isArray(record.destinationChecks)) {\n refuse(\"state manifest.destinationChecks must be an array\");\n }\n if (!isString(record.name) || record.name.length === 0) {\n refuse(\"state manifest.name must be a non-empty string\");\n }\n const parents = record.parents.map((parent, index) =>\n parseParent(parent, `state.parents[${index}]`)\n );\n // Strictly ascending, so no fromState appears twice.\n for (let i = 1; i < parents.length; i++) {\n if (\n compareFromState(parents[i - 1]!.fromState, parents[i]!.fromState) >= 0\n ) {\n refuse(\n \"state manifest parents must be sorted by fromState with null first\"\n );\n }\n }\n const withoutId: Omit<MigrationStateManifestV1, \"stateId\"> = {\n format: parseFormat(record.format, \"state manifest\"),\n estateHash: parseSha256(record.estateHash, \"state.estateHash\"),\n name: record.name,\n snapshotHash: parseSha256(record.snapshotHash, \"state.snapshotHash\"),\n sqlHash: parseSha256(record.sqlHash, \"state.sqlHash\"),\n destinationChecks: record.destinationChecks.map((check, index) =>\n parseCheck(check, `state.destinationChecks[${index}]`)\n ),\n parents,\n };\n assertCanonicalBytes(\n bytes,\n { ...withoutId, stateId: expectedId },\n `states/${expectedId}.json`\n );\n const stateId = parseSha256(record.stateId, \"state.stateId\");\n const expected = encodeStateId(withoutId);\n if (stateId !== expected || stateId !== expectedId) {\n throw new MigrationError(\n \"stateId does not match the canonical manifest or filename\",\n VibORMErrorCode.MIGRATION_CORRUPTION\n );\n }\n return { ...withoutId, stateId };\n}\n\nexport function encodeStateManifest(\n manifest: Omit<MigrationStateManifestV1, \"stateId\">\n): { bytes: Uint8Array; stateId: Sha256; manifest: MigrationStateManifestV1 } {\n const parents = sortParents(manifest.parents);\n const sorted = { ...manifest, parents };\n const stateId = encodeStateId(sorted);\n const complete = { ...sorted, stateId };\n return { bytes: canonicalizeJson(complete), stateId, manifest: complete };\n}\n\nexport function encodeSqlBlob(bytes: Uint8Array): Sha256 {\n return domainHash(HASH_DOMAIN.sql, bytes);\n}\n","/**\n * Resolver System\n *\n * Handles ambiguous changes that require user input to resolve.\n * Provides utilities for converting user resolutions into concrete operations.\n */\n\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\nimport { isRecord } from \"../validation/value-guards\";\nimport {\n type DiffOptions,\n diff,\n getDestructiveOperationDescriptions,\n isDestructiveOperation,\n} from \"./differ\";\nimport { snapshotExactArray, snapshotExactRecord } from \"./input-boundary\";\nimport { applyNativeRename } from \"./native-rename\";\nimport type {\n AmbiguousChange,\n AmbiguousResolveChange,\n ChangeResolution,\n DestructiveResolveChange,\n DiffOperation,\n DiffResult,\n EnumValueRemovalChange,\n ResolveCallback,\n ResolveChange,\n ResolveResult,\n Resolver,\n SchemaSnapshot,\n} from \"./types\";\nimport {\n createAmbiguousChange,\n createDestructiveChange,\n readEnumResolutionDecision,\n} from \"./types\";\nimport { sortOperations } from \"./utils\";\nimport { parseApproval } from \"./v1-parse\";\nimport type { MigrationApprovalV1, MigrationDecisionV1 } from \"./v1-types\";\n\nexport function validateResolveResult(\n expected: \"ambiguous\",\n change: AmbiguousResolveChange,\n result: unknown\n): \"rename\" | \"addAndDrop\" | \"reject\" | undefined;\nexport function validateResolveResult(\n expected: \"destructive\",\n change: DestructiveResolveChange,\n result: unknown\n): \"proceed\" | \"reject\" | undefined;\nexport function validateResolveResult(\n expected: \"enumValueRemoval\",\n change: EnumValueRemovalChange,\n result: unknown\n): \"enumMapped\" | \"reject\" | undefined;\nexport function validateResolveResult(\n expected: ResolveChange[\"type\"],\n change: ResolveChange,\n result: unknown\n): ResolveResult | undefined {\n if (result === undefined) return undefined;\n\n if (result === \"reject\") return result;\n if (\n expected === \"ambiguous\" &&\n (result === \"rename\" || result === \"addAndDrop\")\n ) {\n return result;\n }\n if (expected === \"destructive\" && result === \"proceed\") {\n return result;\n }\n if (expected === \"enumValueRemoval\" && result === \"enumMapped\") {\n const decision = readEnumResolutionDecision(change);\n if (decision !== undefined && decision.kind !== \"mixed\") return result;\n }\n\n const received =\n typeof result === \"string\"\n ? `\"${result}\"`\n : result === null\n ? \"null\"\n : typeof result;\n throw new MigrationError(\n `The resolve callback returned an invalid resolution result ${received} for a ${expected} change. ` +\n \"Return one of the methods on the exact change object that was supplied; a result for another change kind cannot authorize this migration.\",\n VibORMErrorCode.MIGRATION_INVALID_STATE,\n {\n meta: {\n type: \"invalid-resolution-result\",\n },\n }\n );\n}\n\n// =============================================================================\n// RESOLUTION APPLICATION\n// =============================================================================\n\n/** The operations one resolved ambiguous change stands for. */\nexport function operationsFor(\n change: AmbiguousChange,\n resolution: ChangeResolution\n): DiffOperation[] {\n if (change.type === \"ambiguousColumn\") {\n return resolution.type === \"rename\"\n ? [\n {\n type: \"renameColumn\",\n tableName: change.tableName,\n from: change.droppedColumn.name,\n to: change.addedColumn.name,\n },\n ]\n : [\n {\n type: \"dropColumn\",\n tableName: change.tableName,\n columnName: change.droppedColumn.name,\n },\n {\n type: \"addColumn\",\n tableName: change.tableName,\n column: change.addedColumn,\n },\n ];\n }\n return resolution.type === \"rename\"\n ? [\n {\n type: \"renameTable\",\n from: change.droppedTable,\n to: change.addedTable,\n },\n ]\n : [\n { type: \"dropTable\", tableName: change.droppedTable },\n { type: \"createTable\", table: change.addedTableDef },\n ];\n}\n\n/**\n * Resolves every ambiguity exposed by accepted changes.\n *\n * Each decision is applied to a working source snapshot, then the ordinary\n * differ runs again with the original options. Native renames therefore expose\n * nested ambiguities and descriptor alterations through the same owner that\n * found the outer change; no local table differ or pre-rename operation list is\n * retained.\n */\nexport async function resolveAmbiguousChanges(\n initialDiffResult: DiffResult,\n currentSnapshot: SchemaSnapshot,\n desiredSnapshot: SchemaSnapshot,\n resolver: Resolver,\n options: DiffOptions = {}\n): Promise<DiffOperation[]> {\n let workingSnapshot = currentSnapshot;\n let diffResult = initialDiffResult;\n const resolutionOperations: DiffOperation[] = [];\n const resolvedAmbiguities = new Set<string>();\n const liveTableNames = new Map(\n currentSnapshot.tables.map((table) => [table.name, table.name])\n );\n\n while (diffResult.ambiguousChanges.length > 0) {\n const resolutions = await resolver(diffResult.ambiguousChanges);\n\n for (const change of diffResult.ambiguousChanges) {\n const key = ambiguityKey(change);\n if (resolvedAmbiguities.has(key)) {\n throw new MigrationError(\n `Ambiguous migration change did not converge after resolution: ${key}`,\n VibORMErrorCode.INTERNAL_ERROR\n );\n }\n resolvedAmbiguities.add(key);\n\n const resolution = resolutions.get(change);\n if (!resolution)\n throw new MigrationError(\n `Missing resolution for ${formatAmbiguousChange(change)}`,\n VibORMErrorCode.MIGRATION_DESTRUCTIVE_REJECTED\n );\n const operations = operationsFor(change, resolution);\n resolutionOperations.push(...operations);\n\n for (const operation of operations) {\n workingSnapshot = applyResolutionEffect(\n workingSnapshot,\n operation,\n options.projectRename\n );\n if (operation.type === \"renameTable\") {\n const liveName = liveTableNames.get(operation.from) ?? operation.from;\n liveTableNames.delete(operation.from);\n liveTableNames.set(operation.to, liveName);\n } else if (operation.type === \"dropTable\") {\n liveTableNames.delete(operation.tableName);\n }\n }\n }\n\n diffResult = await diff(\n workingSnapshot,\n desiredSnapshot,\n optionsForWorkingSnapshot(options, liveTableNames)\n );\n }\n\n return sortOperations([...resolutionOperations, ...diffResult.operations]);\n}\n\nfunction ambiguityKey(change: AmbiguousChange): string {\n return change.type === \"ambiguousTable\"\n ? `table:${change.droppedTable}\\u0000${change.addedTable}`\n : `column:${change.tableName}\\u0000${change.droppedColumn.name}\\u0000${change.addedColumn.name}`;\n}\n\nfunction optionsForWorkingSnapshot(\n options: DiffOptions,\n liveTableNames: ReadonlyMap<string, string>\n): DiffOptions {\n const canonicalize = options.canonicalizeIndexPredicate;\n if (!canonicalize) return options;\n return {\n ...options,\n canonicalizeIndexPredicate: (tableName, predicates) =>\n canonicalize(liveTableNames.get(tableName) ?? tableName, predicates),\n };\n}\n\nfunction applyResolutionEffect(\n snapshot: SchemaSnapshot,\n operation: DiffOperation,\n projectRename: typeof applyNativeRename = applyNativeRename\n): SchemaSnapshot {\n if (operation.type === \"renameTable\" || operation.type === \"renameColumn\") {\n return projectRename(snapshot, operation);\n }\n if (operation.type === \"dropTable\") {\n return {\n ...snapshot,\n tables: snapshot.tables.filter(\n (table) => table.name !== operation.tableName\n ),\n };\n }\n if (operation.type === \"createTable\") {\n return { ...snapshot, tables: [...snapshot.tables, operation.table] };\n }\n if (operation.type === \"dropColumn\") {\n return {\n ...snapshot,\n tables: snapshot.tables.map((table) =>\n table.name === operation.tableName\n ? {\n ...table,\n columns: table.columns.filter(\n (column) => column.name !== operation.columnName\n ),\n }\n : table\n ),\n };\n }\n if (operation.type === \"addColumn\") {\n return {\n ...snapshot,\n tables: snapshot.tables.map((table) =>\n table.name === operation.tableName\n ? { ...table, columns: [...table.columns, operation.column] }\n : table\n ),\n };\n }\n return snapshot;\n}\n\nexport function ambiguousToResolveChange(\n change: AmbiguousChange\n): AmbiguousResolveChange {\n if (change.type === \"ambiguousColumn\") {\n return createAmbiguousChange({\n operation: \"renameColumn\",\n table: change.tableName,\n column: change.addedColumn.name,\n oldName: change.droppedColumn.name,\n newName: change.addedColumn.name,\n oldType: change.droppedColumn.type,\n newType: change.addedColumn.type,\n description: `Column \"${change.droppedColumn.name}\" → \"${change.addedColumn.name}\" in table \"${change.tableName}\" (rename or add+drop?)`,\n });\n }\n return createAmbiguousChange({\n operation: \"renameTable\",\n table: change.addedTable,\n oldName: change.droppedTable,\n newName: change.addedTable,\n description: `Table \"${change.droppedTable}\" → \"${change.addedTable}\" (rename or add+drop?)`,\n });\n}\n\n/**\n * `admittedDrops` collects the drop each `addAndDrop` answer already decided,\n * so the destructive question is not asked a second time for it.\n */\nexport function callbackAsResolver(\n callback: ResolveCallback,\n admittedDrops?: Set<string>\n): Resolver {\n return async (changes) => {\n const resolutions = new Map<AmbiguousChange, ChangeResolution>();\n for (const change of changes) {\n const resolveChange = ambiguousToResolveChange(change);\n const result = await callback(resolveChange);\n if (result === \"rename\") {\n resolutions.set(change, { type: \"rename\" });\n continue;\n }\n if (result === \"addAndDrop\") {\n resolutions.set(change, { type: \"addAndDrop\" });\n admittedDrops?.add(ambiguousDropKey(change));\n continue;\n }\n throw new MigrationError(\n `Unresolved ambiguous change: ${resolveChange.description}\\n` +\n \"Generate requires change.rename() or change.addAndDrop() from the resolver.\",\n VibORMErrorCode.MIGRATION_DESTRUCTIVE_REJECTED\n );\n }\n return resolutions;\n };\n}\n\n// =============================================================================\n// DESTRUCTIVE CHANGES\n// =============================================================================\n\nexport function ambiguousDropKey(change: AmbiguousChange): string {\n return change.type === \"ambiguousTable\"\n ? `table\\u0000${change.droppedTable}`\n : `column\\u0000${change.tableName}\\u0000${change.droppedColumn.name}`;\n}\n\nfunction destructiveDropKey(operation: DiffOperation): string {\n if (operation.type === \"dropTable\") {\n return `table\\u0000${operation.tableName}`;\n }\n if (operation.type === \"dropColumn\") {\n return `column\\u0000${operation.tableName}\\u0000${operation.columnName}`;\n }\n return \"\";\n}\n\n/**\n * Puts every destructive operation (enum value removals excepted: they have\n * their own mapping question) to `resolve` once, for push and generate alike.\n * A rejected or unanswered change refuses, unless `force` admits an unanswered\n * one. Without a callback nothing is asked: the refusal names every change.\n * Returns the approval of every destructive change, in operation order; a drop\n * an `addAndDrop` answer already decided is approved by that answer.\n */\nexport async function approveDestructiveOperations(\n operations: readonly DiffOperation[],\n resolve: ResolveCallback | undefined,\n force: boolean,\n admittedDrops: ReadonlySet<string> = new Set()\n): Promise<MigrationApprovalV1[]> {\n const destructive = operations.filter(\n (operation) =>\n operation.type !== \"alterEnum\" && isDestructiveOperation(operation)\n );\n const facts = destructive.map(describeDestructiveOperation);\n const changes = facts.map(({ column, ...change }) =>\n createDestructiveChange(column === null ? change : { ...change, column })\n );\n if (!resolve && changes.length > 0) {\n throw new MigrationError(\n `Destructive changes need an approval:\\n${changes.map((change) => `- ${change.description}`).join(\"\\n\")}\\n\\n` +\n \"Pass a resolve callback that returns change.proceed() or change.reject() for each one.\",\n VibORMErrorCode.MIGRATION_CONSENT_REQUIRED,\n {\n meta: {\n hint: \"Review the changes, then pass a resolve callback (generate() or down()) that approves them with change.proceed(); for the CLI, set migrations.resolve in viborm.config.ts.\",\n },\n }\n );\n }\n for (const [index, change] of changes.entries()) {\n if (!admittedDrops.has(destructiveDropKey(destructive[index]!))) {\n const result = validateResolveResult(\n \"destructive\",\n change,\n await resolve?.(change)\n );\n if (result === \"reject\") {\n throw new MigrationError(\n `Change rejected: ${change.description}`,\n VibORMErrorCode.MIGRATION_DESTRUCTIVE_REJECTED\n );\n }\n if (result === undefined && !force) {\n throw new MigrationError(\n `Unresolved destructive change: ${change.description}\\n` +\n \"Return change.proceed() or change.reject() from the resolver.\",\n VibORMErrorCode.MIGRATION_DESTRUCTIVE_REJECTED\n );\n }\n }\n }\n return facts.map(({ operation, table, column }) => ({\n operation,\n table,\n column,\n }));\n}\n\nfunction describeDestructiveOperation(\n op: DiffOperation\n): MigrationApprovalV1 & { readonly description: string } {\n switch (op.type) {\n case \"dropTable\":\n return {\n operation: \"dropTable\",\n table: op.tableName,\n column: null,\n description: `Drop table \"${op.tableName}\" (all data will be lost)`,\n };\n case \"dropColumn\":\n return {\n operation: \"dropColumn\",\n table: op.tableName,\n column: op.columnName,\n description: `Drop column \"${op.columnName}\" from table \"${op.tableName}\" (data will be lost)`,\n };\n case \"addColumn\":\n return {\n operation: \"addColumn\",\n table: op.tableName,\n column: op.column.name,\n description: `Add required column \"${op.tableName}.${op.column.name}\" without a backfill default (fails on populated tables)`,\n };\n case \"alterColumn\":\n return {\n operation: \"alterColumn\",\n table: op.tableName,\n column: op.columnName,\n // The SAME sentences the differ already writes for this operation, and\n // not a second summary of it. Rendering `from.type → to.type` here was\n // silent about the one change whose type does not move: a narrowing\n // decimal domain on SQLite reads `(INTEGER → INTEGER)`, so the user was\n // asked to accept a data-refusing change with nothing on screen to say\n // what it was. Every destructive alterColumn produces at least one\n // description, because the differ's description and classifier share\n // the same owner and ask the same three questions.\n description: getDestructiveOperationDescriptions([op]).join(\"; \"),\n };\n default:\n throw new MigrationError(\n `Unexpected operation type: ${op.type}`,\n VibORMErrorCode.INTERNAL_ERROR\n );\n }\n}\n\n// =============================================================================\n// DEFAULT RESOLVERS\n// =============================================================================\n\n/**\n * Resolver that always chooses \"addAndDrop\" for all ambiguous changes.\n * Useful for clean slate scenarios where data loss is acceptable.\n */\nexport const alwaysAddDropResolver: Resolver = async (changes) => {\n const resolutions = new Map<AmbiguousChange, ChangeResolution>();\n for (const change of changes) {\n resolutions.set(change, { type: \"addAndDrop\" });\n }\n return resolutions;\n};\n\n/**\n * Resolver that throws an error if any ambiguous changes are detected.\n * Useful for CI/CD pipelines where human intervention is not possible.\n */\nexport const strictResolver: Resolver = async (changes) => {\n if (changes.length > 0) {\n const descriptions = changes.map((change) => {\n if (change.type === \"ambiguousColumn\") {\n return `Column \"${change.droppedColumn.name}\" was removed and \"${change.addedColumn.name}\" was added in table \"${change.tableName}\"`;\n }\n return `Table \"${change.droppedTable}\" was removed and \"${change.addedTable}\" was added`;\n });\n\n throw new MigrationError(\n `Ambiguous changes detected that require resolution:\\n${descriptions.join(\"\\n\")}\\n\\n` +\n \"Supply a resolve callback choosing rename() or addAndDrop() for each change.\",\n VibORMErrorCode.MIGRATION_DESTRUCTIVE_REJECTED\n );\n }\n return new Map();\n};\n\n// =============================================================================\n// RESOLVER HELPERS\n// =============================================================================\n\nconst DECISION_KEYS = {\n column: [\"type\", \"tableName\", \"from\", \"to\", \"resolution\"],\n table: [\"type\", \"from\", \"to\", \"resolution\"],\n enumValueRemoval: [\"type\", \"tableName\", \"columnName\", \"mapValues\"],\n destructive: [\"type\", \"operation\", \"table\", \"column\"],\n} as const satisfies Record<MigrationDecisionV1[\"type\"], readonly string[]>;\nconst DECISION_TYPES = Object.keys(\n DECISION_KEYS\n) as readonly (keyof typeof DECISION_KEYS)[];\nconst ALL_DECISION_KEYS = [...new Set(Object.values(DECISION_KEYS).flat())];\nconst RESOLUTIONS = [\"rename\", \"addAndDrop\"] as const;\n\n/** Each predefined resolver's decisions, and those a plan used since the last check. */\nconst decisionUse = new WeakMap<\n ResolveCallback,\n {\n readonly decisions: readonly MigrationDecisionV1[];\n readonly used: Set<MigrationDecisionV1>;\n }\n>();\n\n/**\n * Intent as data (plan T2): a resolve callback built from plain JSON\n * decisions, so an API can carry them. It answers each change one decision\n * names and leaves every other change unanswered, which refuses it. An entry\n * that is not a decision is refused here (V4002); `generate` refuses (V4002)\n * a decision that answered no change of its plan, such as one naming a table\n * or column the plan does not touch. It serves one request: build one per\n * `generate`.\n */\nexport function createPredefinedResolver(\n decisions: readonly MigrationDecisionV1[]\n): ResolveCallback {\n const admitted = snapshotExactArray(\n decisions,\n \"decisions\",\n refuseDecision\n ).map(parseDecision);\n const used = new Set<MigrationDecisionV1>();\n const resolve: ResolveCallback = (change) => {\n for (const decision of admitted) {\n const answer = answerChange(decision, change);\n if (answer === undefined) continue;\n used.add(decision);\n return answer;\n }\n return undefined;\n };\n decisionUse.set(resolve, { decisions: admitted, used });\n return resolve;\n}\n\n/** Refuses the decisions of a predefined resolver that answered no change. */\nexport function refuseUnusedDecisions(\n resolve: ResolveCallback | undefined\n): void {\n const use = resolve && decisionUse.get(resolve);\n if (!use) return;\n const unused = use.decisions.filter((decision) => !use.used.has(decision));\n use.used.clear();\n if (unused.length > 0) {\n refuseDecision(\n `These decisions match no change of the plan (an unknown table or column, or nothing to decide): ${JSON.stringify(unused)}`\n );\n }\n}\n\nfunction answerChange(\n decision: MigrationDecisionV1,\n change: ResolveChange\n): ResolveResult | undefined {\n switch (decision.type) {\n case \"destructive\":\n return change.type === \"destructive\" &&\n change.operation === decision.operation &&\n change.table === decision.table &&\n (change.column ?? null) === decision.column\n ? change.proceed()\n : undefined;\n case \"enumValueRemoval\":\n return change.type === \"enumValueRemoval\" &&\n change.tableName === decision.tableName &&\n change.columnName === decision.columnName\n ? change.mapValues(decision.mapValues)\n : undefined;\n default: {\n const named =\n change.type === \"ambiguous\" &&\n change.oldName === decision.from &&\n change.newName === decision.to &&\n (decision.type === \"table\"\n ? change.operation === \"renameTable\"\n : change.operation === \"renameColumn\" &&\n change.table === decision.tableName);\n if (!named) return undefined;\n return decision.resolution === \"rename\"\n ? change.rename()\n : change.addAndDrop();\n }\n }\n}\n\nfunction parseDecision(entry: unknown, index: number): MigrationDecisionV1 {\n const label = `decisions[${index}]`;\n const raw = snapshotExactRecord(\n entry,\n ALL_DECISION_KEYS,\n label,\n refuseDecision\n );\n const type =\n DECISION_TYPES.find((name) => name === raw.type) ??\n refuseDecision(`${label}.type must be one of ${DECISION_TYPES.join(\", \")}`);\n // A missing key is refused by its reader below.\n const record = snapshotExactRecord(\n raw,\n DECISION_KEYS[type],\n label,\n refuseDecision\n );\n const text = (key: string): string => {\n const value = record[key];\n return typeof value === \"string\"\n ? value\n : refuseDecision(`${label}.${key} must be a string`);\n };\n const resolution = () =>\n RESOLUTIONS.find((name) => name === record.resolution) ??\n refuseDecision(`${label}.resolution must be rename or addAndDrop`);\n switch (type) {\n case \"column\":\n return {\n type,\n tableName: text(\"tableName\"),\n from: text(\"from\"),\n to: text(\"to\"),\n resolution: resolution(),\n };\n case \"table\":\n return {\n type,\n from: text(\"from\"),\n to: text(\"to\"),\n resolution: resolution(),\n };\n case \"enumValueRemoval\":\n return {\n type,\n tableName: text(\"tableName\"),\n columnName: text(\"columnName\"),\n mapValues: parseValueMapping(record.mapValues, `${label}.mapValues`),\n };\n default:\n return {\n type,\n ...parseApproval(record, label, refuseDecision),\n };\n }\n}\n\nfunction parseValueMapping(\n value: unknown,\n label: string\n): Readonly<Record<string, string | null>> {\n if (!isRecord(value)) return refuseDecision(`${label} must be an object`);\n const mapping: Record<string, string | null> = {};\n for (const [from, to] of Object.entries(value)) {\n if (!(typeof to === \"string\" || to === null)) {\n refuseDecision(`${label}.${from} must be a string or null`);\n }\n mapping[from] = to;\n }\n return Object.freeze(mapping);\n}\n\nfunction refuseDecision(message: string, cause?: Error): never {\n throw new MigrationError(message, VibORMErrorCode.INVALID_INPUT, { cause });\n}\n\n/**\n * Formats ambiguous changes for display\n */\nexport function formatAmbiguousChange(change: AmbiguousChange): string {\n if (change.type === \"ambiguousColumn\") {\n return (\n `Column rename detected in table \"${change.tableName}\":\\n` +\n ` \"${change.droppedColumn.name}\" (${change.droppedColumn.type}) → \"${change.addedColumn.name}\" (${change.addedColumn.type})`\n );\n }\n return (\n \"Table rename detected:\\n\" +\n ` \"${change.droppedTable}\" → \"${change.addedTable}\"`\n );\n}\n\n// =============================================================================\n// UNIFIED RESOLVE CALLBACKS\n// =============================================================================\n\n/**\n * Rejects all changes requiring resolution.\n * Useful for CI/CD pipelines where human intervention is not possible.\n */\nexport const rejectAllResolver: ResolveCallback = async (change) =>\n change.reject();\n\n/**\n * Accepts destructive changes, treats ambiguous column changes as renames,\n * and maps enum value removals to NULL.\n * A table pair stays undecided, so the plan refuses: the dropped side may be\n * another application's table, and only a callback naming the pair may\n * rename it.\n */\nexport const lenientResolver: ResolveCallback = async (change) => {\n if (change.type === \"destructive\") {\n return change.proceed();\n }\n if (change.type === \"ambiguous\") {\n return change.operation === \"renameColumn\" ? change.rename() : undefined;\n }\n\n // enumValueRemoval: set all removed values to null\n return change.useNull();\n};\n\n/**\n * Accepts destructive changes, treats ambiguous changes as add+drop,\n * and maps enum value removals to NULL.\n * Useful when you don't care about preserving data in ambiguous scenarios.\n */\nexport const addDropResolver: ResolveCallback = async (change) => {\n if (change.type === \"destructive\") {\n return change.proceed();\n }\n if (change.type === \"ambiguous\") {\n return change.addAndDrop();\n }\n // enumValueRemoval: set all removed values to null\n return change.useNull();\n};\n","import { MigrationError, VibORMErrorCode } from \"../../errors\";\nimport { parseMySqlEnumValues } from \"../drivers/type-mapping\";\nimport { validateResolveResult } from \"../resolver\";\nimport {\n createEnumValueRemovalChange,\n type DiffOperation,\n type ResolveCallback,\n readEnumResolutionDecision,\n type SchemaSnapshot,\n} from \"../types\";\n\nconst INLINE_ENUM_TOKEN =\n /^(?:enum\\(|text check\\(\"(?:[^\"]|\"\")*\"\\s+in\\s+\\()(\\s*'(?:[^']|'')*'(?:\\s*,\\s*'(?:[^']|'')*')*\\s*)\\)\\)?$/i;\n\n/** The closed inline enum carriers emitted by MySQL and SQLite drivers. */\nexport function inlineEnumValues(type: string): string[] | undefined {\n const match = INLINE_ENUM_TOKEN.exec(type.trim());\n if (!match?.[1]) return;\n if (type.trim().toLowerCase().startsWith(\"enum(\"))\n return parseMySqlEnumValues(type) ?? undefined;\n return Array.from(match[1].matchAll(/'((?:[^']|'')*)'/g), (item) =>\n item[1]!.replaceAll(\"''\", \"'\")\n );\n}\n\nexport interface EnumRemoval {\n enumName: string;\n tableName: string;\n columnName: string;\n isNullable: boolean;\n removedValues: string[];\n availableValues: string[];\n}\n\ntype ColumnMappings = Record<string, string | null>;\n\nexport type EnumColumnMappings = Map<string, Map<string, ColumnMappings>>;\n\n/**\n * Detects enum value removals that need resolution.\n * Returns one removal per column that uses the enum.\n * Nullability never supplies a data-mapping decision.\n */\nexport function detectEnumValueRemovals(\n operations: DiffOperation[],\n currentSchema: SchemaSnapshot\n): EnumRemoval[] {\n const removals: EnumRemoval[] = [];\n\n for (const op of operations) {\n if (\n op.type === \"alterEnum\" &&\n op.removeValues &&\n op.removeValues.length > 0\n ) {\n const unresolvedValues = op.removeValues.filter((value) => {\n const hasExplicit =\n op.valueReplacements !== undefined && value in op.valueReplacements;\n const hasDefault = op.defaultReplacement !== undefined;\n return !(hasExplicit || hasDefault);\n });\n\n if (unresolvedValues.length > 0) {\n const dependentColumns = op.dependentColumns || [];\n\n for (const dependentColumn of dependentColumns) {\n const table = currentSchema.tables.find(\n (tableDef) => tableDef.name === dependentColumn.tableName\n );\n if (!table) {\n throw new MigrationError(\n `Table \"${dependentColumn.tableName}\" not found in current schema for enum \"${op.enumName}\"`,\n VibORMErrorCode.INTERNAL_ERROR\n );\n }\n\n const column = table.columns.find(\n (columnDef) => columnDef.name === dependentColumn.columnName\n );\n if (!column) {\n throw new MigrationError(\n `Column \"${dependentColumn.columnName}\" not found in table \"${dependentColumn.tableName}\" for enum \"${op.enumName}\"`,\n VibORMErrorCode.INTERNAL_ERROR\n );\n }\n\n removals.push({\n enumName: op.enumName,\n tableName: dependentColumn.tableName,\n columnName: dependentColumn.columnName,\n isNullable: column.nullable,\n removedValues: unresolvedValues,\n availableValues: op.newValues || [],\n });\n }\n }\n }\n }\n\n return removals;\n}\n\n/**\n * Applies force mode resolutions for enum value removals.\n * Sets all removed values to NULL for each column.\n */\nexport function applyForceEnumResolutions(\n operations: DiffOperation[],\n enumRemovals: EnumRemoval[]\n): DiffOperation[] {\n if (enumRemovals.length === 0) {\n return operations;\n }\n\n const removalsByEnum = new Map<string, EnumRemoval[]>();\n for (const removal of enumRemovals) {\n const existing = removalsByEnum.get(removal.enumName) || [];\n existing.push(removal);\n removalsByEnum.set(removal.enumName, existing);\n }\n\n return operations.map((op) => {\n if (op.type !== \"alterEnum\" || !op.removeValues) {\n return op;\n }\n\n const removals = removalsByEnum.get(op.enumName);\n if (!removals || removals.length === 0) {\n return op;\n }\n\n const columnValueReplacements: Record<string, ColumnMappings> = {\n ...op.columnValueReplacements,\n };\n\n for (const removal of removals) {\n const columnKey = getColumnKey(removal);\n columnValueReplacements[columnKey] = {\n ...columnValueReplacements[columnKey],\n ...createNullMappings(removal.removedValues),\n };\n }\n\n return {\n ...op,\n columnValueReplacements,\n };\n });\n}\n\nexport async function resolveEnumValueRemovalMappings(\n enumRemovals: EnumRemoval[],\n resolve: ResolveCallback,\n force: boolean\n): Promise<EnumColumnMappings> {\n const columnMappings: EnumColumnMappings = new Map();\n\n for (const removal of enumRemovals) {\n const change = createEnumValueRemovalChange({\n enumName: removal.enumName,\n tableName: removal.tableName,\n columnName: removal.columnName,\n isNullable: removal.isNullable,\n removedValues: removal.removedValues,\n availableValues: removal.availableValues,\n description:\n `Column \"${removal.tableName}.${removal.columnName}\" uses enum \"${removal.enumName}\" - ` +\n `removing values: ${removal.removedValues.join(\", \")}. ` +\n `Map to: ${removal.availableValues.join(\", \")} or NULL`,\n });\n\n const result = validateResolveResult(\n \"enumValueRemoval\",\n change,\n await resolve(change)\n );\n\n if (result === \"reject\") {\n throw new MigrationError(\n `Change rejected: ${change.description}`,\n VibORMErrorCode.MIGRATION_DESTRUCTIVE_REJECTED\n );\n }\n\n const columnKey = getColumnKey(removal);\n\n if (result === undefined) {\n if (force) {\n setColumnMappings(\n columnMappings,\n removal.enumName,\n columnKey,\n createNullMappings(removal.removedValues)\n );\n } else {\n throw new MigrationError(\n `Unresolved enum value removal: ${change.description}\\n` +\n \"Return change.mapValues() or change.useNull() from the resolver.\",\n VibORMErrorCode.MIGRATION_DESTRUCTIVE_REJECTED\n );\n }\n continue;\n }\n\n if (result === \"enumMapped\") {\n const decision = readEnumResolutionDecision(change);\n if (decision?.kind === \"mapValues\") {\n setColumnMappings(\n columnMappings,\n removal.enumName,\n columnKey,\n decision.mappings\n );\n } else if (decision?.kind === \"useNull\") {\n setColumnMappings(\n columnMappings,\n removal.enumName,\n columnKey,\n createNullMappings(removal.removedValues)\n );\n }\n }\n }\n\n return columnMappings;\n}\n\nexport function applyResolvedEnumMappings(\n operations: DiffOperation[],\n columnMappings: EnumColumnMappings\n): DiffOperation[] {\n const enumOperations: DiffOperation[] = [];\n\n for (const op of operations) {\n if (op.type === \"alterEnum\") {\n const enumColumnMappings = columnMappings.get(op.enumName);\n if (enumColumnMappings && enumColumnMappings.size > 0) {\n const columnValueReplacements: Record<string, ColumnMappings> = {\n ...op.columnValueReplacements,\n };\n\n for (const [columnKey, mappings] of enumColumnMappings) {\n columnValueReplacements[columnKey] = {\n ...columnValueReplacements[columnKey],\n ...mappings,\n };\n }\n\n enumOperations.push({\n ...op,\n columnValueReplacements,\n });\n } else {\n enumOperations.push(op);\n }\n }\n }\n\n return enumOperations;\n}\n\nfunction setColumnMappings(\n columnMappings: EnumColumnMappings,\n enumName: string,\n columnKey: string,\n mappings: ColumnMappings\n): void {\n let enumMappings = columnMappings.get(enumName);\n if (!enumMappings) {\n enumMappings = new Map();\n columnMappings.set(enumName, enumMappings);\n }\n enumMappings.set(columnKey, mappings);\n}\n\nfunction createNullMappings(values: string[]): Record<string, null> {\n const nullMappings: Record<string, null> = {};\n for (const value of values) {\n nullMappings[value] = null;\n }\n return nullMappings;\n}\n\nfunction getColumnKey(removal: EnumRemoval): string {\n return `${removal.tableName}.${removal.columnName}`;\n}\n","import { sqliteGeoPointEncoding } from \"../adapters/databases/sqlite/storage/geo-point\";\n\n/**\n * Schema Differ\n *\n * Compares two SchemaSnapshots and produces a list of DiffOperations,\n * detecting ambiguous changes that require user input.\n */\n\nimport { sameDecimalDescriptor } from \"@validation/primitives/decimal-codec\";\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\nimport {\n decimalChangeNarrows,\n describeDecimalDomain,\n migrationDecimalStorageKind,\n} from \"./decimal\";\nimport type { applyNativeRename } from \"./native-rename\";\nimport { inlineEnumValues } from \"./push/enum-removals\";\nimport {\n canonicalUniqueEntities,\n normalizeDefault,\n normalizeType,\n} from \"./push-fingerprint\";\nimport type {\n AmbiguousChange,\n ColumnDef,\n DiffOperation,\n DiffResult,\n EnumDef,\n ForeignKeyDef,\n IndexDef,\n ReferentialAction,\n SchemaSnapshot,\n TableDef,\n UniqueConstraintDef,\n} from \"./types\";\nimport { sortOperations } from \"./utils\";\n\n// =============================================================================\n// PARTIAL-INDEX PREDICATE CANONICALIZATION (Decision 7.4)\n// =============================================================================\n\n/**\n * Asks the database for its own spelling of each declared index predicate.\n *\n * The differ has no connection of its own; the push path owns one and hands\n * this in (`planPush`). One call carries every predicate of one table, so the\n * round trip is paid once per table that has a partial index whose two\n * spellings differ — usually never, at most once per push.\n *\n * The result is positional. `undefined` at a position means the database did\n * not answer for that predicate, and the differ then treats it as\n * uncomparable — never as equal.\n */\nexport type IndexPredicateCanonicalizer = (\n tableName: string,\n predicates: readonly string[]\n) => Promise<ReadonlyArray<string | undefined>>;\n\nexport interface DiffOptions {\n /**\n * Compares the declared SQLite DateTime storage vocabulary carried by V1\n * snapshots. Enable only when both sides preserve that declaration. Live\n * SQLite introspection cannot recover it from TEXT, INTEGER, or REAL and\n * therefore leaves this off so an unchanged push does not drift forever.\n */\n compareDateTimeDeclarations?: boolean;\n\n /**\n * Canonicalizes partial-index predicates through the live database. Omitted\n * by callers with no connection (`generate`, which diffs two snapshots) and\n * by dialects whose catalog stores the declared statement verbatim; the\n * differ then compares the two texts raw, which is the fail-closed reading.\n */\n canonicalizeIndexPredicate?: IndexPredicateCanonicalizer;\n\n /**\n * Recognizes a foreign key and a unique constraint by its SHAPE instead of by\n * its name — see `foreignKeyShape` below for why, and for what breaks without\n * it. Set by `planPush` from the migration driver's\n * `introspectionReadsConstraintNames` capability; left off by `generate`,\n * which diffs two snapshots the serializer wrote and where every name is\n * therefore the declared one.\n */\n matchConstraintsByShape?: boolean;\n\n /** Effectful planning admission; diagnostic diffs must retain drift evidence. */\n refuseConstraintNameChurn?: boolean;\n\n /** The exact producer's additional physical effects of an accepted rename. */\n projectRename?: typeof applyNativeRename;\n}\n\n/** Canonical spellings, keyed by table and by the predicate as declared. */\ntype CanonicalPredicates = ReadonlyMap<string, string>;\n\nconst EMPTY_CANONICAL_PREDICATES: CanonicalPredicates = new Map();\n\n/** NUL joins the halves: no table name and no SQL text can contain one. */\nfunction predicateKey(tableName: string, predicate: string): string {\n return `${tableName}\\u0000${predicate}`;\n}\n\n/**\n * Asks the database for its spelling of every predicate that a partial index\n * present in both snapshots spells two ways.\n *\n * Scoped on purpose. A predicate only one side carries, or that both sides\n * spell identically, is settled without a round trip — so a schema with no\n * partial index, or one that already converged, costs nothing.\n */\nasync function canonicalizeChangedPredicates(\n currentTables: ReadonlyMap<string, TableDef>,\n desiredTables: ReadonlyMap<string, TableDef>,\n canonicalize: IndexPredicateCanonicalizer | undefined\n): Promise<CanonicalPredicates> {\n if (!canonicalize) return EMPTY_CANONICAL_PREDICATES;\n\n const canonical = new Map<string, string>();\n\n for (const [tableName, desiredTable] of desiredTables) {\n const currentTable = currentTables.get(tableName);\n if (!currentTable) continue;\n\n const currentIndexes = new Map(\n currentTable.indexes.map((i) => [i.name, i])\n );\n const pending = new Set<string>();\n\n for (const desiredIndex of desiredTable.indexes) {\n const currentIndex = currentIndexes.get(desiredIndex.name);\n if (!currentIndex) continue;\n const left = normalizeIndexWhere(currentIndex.where);\n const right = normalizeIndexWhere(desiredIndex.where);\n if (left === undefined || right === undefined || left === right) continue;\n pending.add(left);\n pending.add(right);\n }\n\n if (pending.size === 0) continue;\n\n const predicates = [...pending];\n const spellings = await canonicalize(tableName, predicates);\n for (const [position, predicate] of predicates.entries()) {\n const spelling = spellings[position];\n if (spelling !== undefined) {\n canonical.set(predicateKey(tableName, predicate), spelling);\n }\n }\n }\n\n return canonical;\n}\n\n// =============================================================================\n// HELPER FUNCTIONS\n// =============================================================================\n\nfunction columnPropertiesEqual(\n a: ColumnDef,\n b: ColumnDef,\n compareDateTimeDeclarations: boolean\n): boolean {\n return (\n normalizeType(a.type) === normalizeType(b.type) &&\n a.nullable === b.nullable &&\n normalizeDefault(a.default, a.type) ===\n normalizeDefault(b.default, b.type) &&\n // The declared domain is compared beside the physical type, not instead of\n // it, because the two carry different amounts of the fact per dialect: a\n // PostgreSQL `numeric(10,5)` spells its whole domain in the type, while a\n // SQLite decimal is `INTEGER` (or `TEXT` for a list) at every precision and\n // scale there is. Left out, a SQLite descriptor change plans NOTHING —\n // the type is byte-identical on both sides — and the column silently keeps\n // storing coefficients at the old scale.\n sqliteGeoPointEncoding(a) === sqliteGeoPointEncoding(b) &&\n sameDecimalDescriptor(a.decimal, b.decimal) &&\n (!compareDateTimeDeclarations || a.dateTime === b.dateTime)\n );\n}\n\nfunction columnsEqual(\n a: ColumnDef,\n b: ColumnDef,\n compareDateTimeDeclarations: boolean\n): boolean {\n return (\n a.name === b.name &&\n columnPropertiesEqual(a, b, compareDateTimeDeclarations)\n );\n}\n\nfunction columnsCanBeRenamed(a: ColumnDef, b: ColumnDef): boolean {\n if (normalizeType(a.type) === normalizeType(b.type)) return true;\n const aDecimalKind = migrationDecimalStorageKind(a);\n return (\n aDecimalKind !== undefined &&\n aDecimalKind === migrationDecimalStorageKind(b)\n );\n}\n\nfunction normalizeIndexType(type: IndexDef[\"type\"]): string {\n // An index with no declared type is a B-tree on every dialect. The two\n // snapshot producers spell that differently — introspection reads \"btree\"\n // back from the Postgres/MySQL catalog, SQLite reports no type at all, and\n // the serializer leaves an undeclared type undefined — so the same index\n // must not read as a change.\n return type ?? \"btree\";\n}\n\nfunction normalizeIndexUnique(unique: IndexDef[\"unique\"]): boolean {\n // `type`'s twin (above): the serializer leaves a plain `.index()`'s `unique`\n // undefined while every introspection reads a boolean back from the catalog,\n // so the same index must not read as a change. Left raw, every push re-plans\n // drop+create forever — and on MySQL the drop is a hard 1553 abort when the\n // declared index is the one InnoDB bound the FK to.\n return unique ?? false;\n}\n\nfunction normalizeIndexWhere(where: IndexDef[\"where\"]): string | undefined {\n // `type`'s and `unique`'s third twin, and the one place the partial index's\n // two spellings are reconciled. The serializer passes the declared predicate\n // through untouched; the emitter writes ` WHERE ${where}`, and SQLite stores\n // that statement verbatim, padding and all. Reading it back consumes the\n // whitespace run that separates `WHERE` from the predicate, so a declaration\n // written with padding comes back without its leading part — the same index\n // in two spellings. Left raw, every push re-plans drop+create forever.\n const trimmed = where?.trim();\n return trimmed ? trimmed : undefined;\n}\n\n/**\n * The one place the two snapshots' predicates are compared, and the reader of\n * the canonical spellings the database supplied (Decision 7.4).\n *\n * `normalizeIndexWhere` above reconciles the *padding* of one text; it cannot\n * reconcile two texts. PostgreSQL's catalog does not store the declared\n * statement — `pg_get_expr(indpred, indrelid)` deparses it, so a declared\n * `published = true` reads back as `(published = true)`, and every push drops\n * and re-creates every partial index. No client-side normalization closes that\n * while staying fail-closed: flatten whitespace and parentheses and\n * `a AND (b OR c)` starts comparing equal to `(a AND b) OR c`, so a real change\n * would stop being seen. So the database is asked, and `canonical` holds what\n * it answered. Two predicates are the same predicate only when BOTH were\n * canonicalized and the two canonical spellings are identical.\n */\nfunction indexWhereEqual(\n tableName: string,\n a: IndexDef,\n b: IndexDef,\n canonical: CanonicalPredicates\n): boolean {\n const left = normalizeIndexWhere(a.where);\n const right = normalizeIndexWhere(b.where);\n if (left === right) return true;\n // A predicate that appears or disappears is a real change on every dialect,\n // and no round trip can make a partial index equal to a total one.\n if (left === undefined || right === undefined) return false;\n\n const leftCanonical = canonical.get(predicateKey(tableName, left));\n const rightCanonical = canonical.get(predicateKey(tableName, right));\n // Fail closed. Without both spellings — no canonicalizer, a dialect that has\n // none, a connection that refused, a predicate the database could not parse —\n // two texts that do not read alike stay a change.\n return leftCanonical !== undefined && leftCanonical === rightCanonical;\n}\n\nfunction indexesEqual(\n tableName: string,\n a: IndexDef,\n b: IndexDef,\n canonical: CanonicalPredicates\n): boolean {\n return (\n a.name === b.name &&\n normalizeIndexUnique(a.unique) === normalizeIndexUnique(b.unique) &&\n arraysEqual(a.columns, b.columns) &&\n normalizeIndexType(a.type) === normalizeIndexType(b.type) &&\n indexWhereEqual(tableName, a, b, canonical)\n );\n}\n\nfunction arraysEqual<T>(a: T[], b: T[]): boolean {\n if (a.length !== b.length) return false;\n return a.every((val, idx) => val === b[idx]);\n}\n\n// =============================================================================\n// CONSTRAINT IDENTITY\n// =============================================================================\n\nfunction normalizeReferentialAction(\n action: ReferentialAction | undefined\n): ReferentialAction {\n // `normalizeIndexUnique`'s twin on the foreign-key side. Every introspection\n // reads a concrete action back from the catalog — \"NO ACTION\" when the DDL\n // declared none — while a snapshot may leave it undefined, and both spell the\n // same constraint: SQLite and MySQL omit the clause for `noAction`,\n // PostgreSQL writes `ON DELETE NO ACTION`, which is what omitting it means.\n // Left raw, the same key reads as a change and is dropped and re-added on\n // every push.\n return action ?? \"noAction\";\n}\n\n/**\n * What a foreign key IS, with the name left out: the columns it binds, what\n * they point at, and what happens on delete and on update. NUL joins the\n * columns and SOH the parts — no SQL identifier and no action name holds\n * either, so two shapes read alike only when every part does.\n *\n * The name is left out because on some dialects it is not readable. On\n * PostgreSQL and MySQL the catalog carries the name the DDL gave the\n * constraint, so a name IS an identity there and the differ matches on it.\n * SQLite carries no name for either constraint this file matches:\n * `PRAGMA foreign_key_list` has no name column at all, so introspection\n * synthesises `<table>_fk_<n>`, and an inline `CONSTRAINT x UNIQUE (...)` is\n * reported only under SQLite's own `sqlite_autoindex_<table>_<n>`. Matched by\n * name, the declared constraint is therefore missing and the read one extra on\n * every push of an unchanged schema, forever — and the two repairs the differ\n * plans are both wrong:\n *\n * - the foreign key is dropped and re-added, and SQLite has no\n * `ALTER TABLE ADD FOREIGN KEY`, so each of those rebuilds the whole table\n * — copy included — twice per push, for a schema nobody edited;\n * - the unique constraint's drop is `DROP INDEX \"sqlite_autoindex_...\"`,\n * which SQLite refuses (\"index associated with UNIQUE or PRIMARY KEY\n * constraint cannot be dropped\"), so the SECOND push of any SQLite schema\n * carrying a compound unique fails outright.\n *\n * So where the name cannot be read, the shape is the identity: two constraints\n * of one shape are one constraint, whatever the reader called them.\n */\nfunction foreignKeyShape(fk: ForeignKeyDef): string {\n return [\n fk.columns.join(\"\\u0000\"),\n fk.referencedTable,\n fk.referencedColumns.join(\"\\u0000\"),\n normalizeReferentialAction(fk.onDelete),\n normalizeReferentialAction(fk.onUpdate),\n ].join(\"\\u0001\");\n}\n\n/** `foreignKeyShape`'s twin: a unique constraint is its column list. */\nfunction uniqueConstraintShape(constraint: UniqueConstraintDef): string {\n return constraint.columns.join(\"\\u0000\");\n}\n\n/**\n * Pairs each `current` constraint with the `desired` one it is, under whichever\n * identity the dialect supports, and reports what `desired` had left over.\n *\n * Multisets, not maps, on purpose. A database written before\n * `SQLite3MigrationDriver.getCurrentTable` learned to replay the batch can hold\n * several byte-identical foreign keys on one table — they accumulated, one per\n * push, without bound. Keying by identity alone would collapse those into one\n * entry and leave the extras attached forever; pairing k of n leaves n-k\n * unmatched, and unmatched is what gets dropped.\n */\nfunction matchByIdentity<T>(\n current: readonly T[],\n desired: readonly T[],\n identityOf: (item: T) => string\n): { matches: Array<T | undefined>; unmatchedDesired: T[] } {\n const availableByIdentity = new Map<string, number[]>();\n for (const [position, item] of desired.entries()) {\n const identity = identityOf(item);\n const positions = availableByIdentity.get(identity);\n if (positions) {\n positions.push(position);\n } else {\n availableByIdentity.set(identity, [position]);\n }\n }\n\n const consumed = new Set<number>();\n const matches = current.map((item) => {\n const position = availableByIdentity.get(identityOf(item))?.shift();\n if (position === undefined) return undefined;\n consumed.add(position);\n return desired[position];\n });\n\n return {\n matches,\n unmatchedDesired: desired.filter(\n (_, position) => !consumed.has(position)\n ) as T[],\n };\n}\n\n/**\n * A table's keyed members: each current one is dropped when nothing desired\n * matches it, or dropped and re-added when its match differs; each unmatched\n * desired one is then added. Current order first, then desired order.\n */\nfunction diffKeyed<T>(\n current: readonly T[],\n desired: readonly T[],\n identityOf: (item: T) => string,\n equal: (from: T, to: T) => boolean,\n drop: (item: T) => DiffOperation,\n add: (item: T) => DiffOperation\n): DiffOperation[] {\n const { matches, unmatchedDesired } = matchByIdentity(\n current,\n desired,\n identityOf\n );\n return [\n ...current.flatMap((item, position) => {\n const match = matches[position];\n if (match === undefined) return [drop(item)];\n return equal(item, match) ? [] : [drop(item), add(match)];\n }),\n ...unmatchedDesired.map(add),\n ];\n}\n\nfunction enumsEqual(a: EnumDef, b: EnumDef): boolean {\n return a.name === b.name && arraysEqual(a.values, b.values);\n}\n\n// =============================================================================\n// TABLE DIFFER\n// =============================================================================\n\ninterface TableDiffResult {\n operations: DiffOperation[];\n ambiguousChanges: AmbiguousChange[];\n}\n\nfunction refuseConstraintNameMismatch(\n table: string,\n actual: string,\n desired: string\n): never {\n throw new MigrationError(\n `Constraint \"${table}.${actual}\" already enforces the desired definition under a different physical name (\"${desired}\"). This declaration cannot faithfully adopt that name. Synchronization refuses before effects instead of dropping and recreating an equivalent constraint. Public key names select fields; they do not declare physical constraint names.`,\n VibORMErrorCode.FEATURE_NOT_SUPPORTED,\n { meta: { table, constraint: actual } }\n );\n}\n\nfunction diffTable(\n tableName: string,\n current: TableDef,\n desired: TableDef,\n canonical: CanonicalPredicates,\n matchConstraintsByShape: boolean,\n compareDateTimeDeclarations: boolean,\n refuseConstraintNameChurn: boolean,\n projectRename: DiffOptions[\"projectRename\"]\n): TableDiffResult {\n const operations: DiffOperation[] = [];\n const ambiguousChanges: AmbiguousChange[] = [];\n\n if (!matchConstraintsByShape && refuseConstraintNameChurn) {\n for (const constraint of desired.foreignKeys) {\n if (current.foreignKeys.some((actual) => actual.name === constraint.name))\n continue;\n const actual = current.foreignKeys.find(\n (actual) => foreignKeyShape(actual) === foreignKeyShape(constraint)\n );\n if (actual)\n refuseConstraintNameMismatch(tableName, actual.name, constraint.name);\n }\n for (const constraint of desired.uniqueConstraints) {\n if (\n current.uniqueConstraints.some(\n (actual) => actual.name === constraint.name\n )\n )\n continue;\n const actual = current.uniqueConstraints.find(\n (actual) =>\n uniqueConstraintShape(actual) === uniqueConstraintShape(constraint)\n );\n if (actual)\n refuseConstraintNameMismatch(tableName, actual.name, constraint.name);\n }\n const currentPk = current.primaryKey,\n desiredPk = desired.primaryKey;\n if (\n currentPk &&\n desiredPk &&\n arraysEqual(currentPk.columns, desiredPk.columns)\n ) {\n const actual = currentPk.name ?? `${tableName}_pkey`,\n wanted = desiredPk.name ?? `${tableName}_pkey`;\n if (actual !== wanted)\n refuseConstraintNameMismatch(tableName, actual, wanted);\n }\n }\n\n // Build column maps\n const currentColumns = new Map(current.columns.map((c) => [c.name, c]));\n const desiredColumns = new Map(desired.columns.map((c) => [c.name, c]));\n\n // Find dropped and added columns\n const droppedColumns: ColumnDef[] = [];\n const addedColumns: ColumnDef[] = [];\n\n for (const [name, col] of currentColumns) {\n if (!desiredColumns.has(name)) {\n droppedColumns.push(col);\n }\n }\n\n for (const [name, col] of desiredColumns) {\n if (!currentColumns.has(name)) {\n addedColumns.push(col);\n }\n }\n\n // Detect potential column renames (ambiguous changes)\n // A rename is suspected when a column is dropped and another is added\n // with compatible types\n const usedDropped = new Set<string>();\n const usedAdded = new Set<string>();\n\n // The dropped column as the rename would leave it: a type derived from its\n // name (a PostgreSQL per-column enum) follows the column.\n const asRenamed = (dropped: ColumnDef, added: ColumnDef): ColumnDef =>\n projectRename?.(\n { tables: [current] },\n { type: \"renameColumn\", tableName, from: dropped.name, to: added.name }\n ).tables[0]?.columns.find((column) => column.name === added.name) ??\n dropped;\n\n for (const dropped of droppedColumns) {\n for (const added of addedColumns) {\n if (usedDropped.has(dropped.name) || usedAdded.has(added.name)) continue;\n\n if (columnsCanBeRenamed(asRenamed(dropped, added), added)) {\n // This could be a rename - mark as ambiguous\n ambiguousChanges.push({\n type: \"ambiguousColumn\",\n tableName,\n droppedColumn: dropped,\n addedColumn: added,\n });\n usedDropped.add(dropped.name);\n usedAdded.add(added.name);\n }\n }\n }\n\n // Add operations for non-ambiguous drops and adds\n for (const dropped of droppedColumns) {\n if (!usedDropped.has(dropped.name)) {\n operations.push({\n type: \"dropColumn\",\n tableName,\n columnName: dropped.name,\n });\n }\n }\n\n for (const added of addedColumns) {\n if (!usedAdded.has(added.name)) {\n operations.push({\n type: \"addColumn\",\n tableName,\n column: added,\n });\n }\n }\n\n // Check for column modifications (same name, different properties)\n for (const [name, desiredCol] of desiredColumns) {\n const currentCol = currentColumns.get(name);\n if (\n currentCol &&\n !columnsEqual(currentCol, desiredCol, compareDateTimeDeclarations)\n ) {\n const previousValues = inlineEnumValues(currentCol.type);\n const nextValues = inlineEnumValues(desiredCol.type);\n if (\n previousValues &&\n nextValues &&\n normalizeType(currentCol.type) !== normalizeType(desiredCol.type)\n ) {\n operations.push({\n type: \"alterEnum\",\n enumName: desiredCol.type,\n newValues: nextValues,\n addValues: nextValues.filter(\n (value) => !previousValues.includes(value)\n ),\n removeValues: previousValues.filter(\n (value) => !nextValues.includes(value)\n ),\n dependentColumns: [{ tableName, columnName: name }],\n });\n const converted = { ...currentCol, type: desiredCol.type };\n if (\n !columnPropertiesEqual(\n converted,\n desiredCol,\n compareDateTimeDeclarations\n )\n )\n operations.push({\n type: \"alterColumn\",\n tableName,\n columnName: name,\n from: converted,\n to: desiredCol,\n });\n } else {\n operations.push({\n type: \"alterColumn\",\n tableName,\n columnName: name,\n from: currentCol,\n to: desiredCol,\n });\n }\n }\n }\n\n // Foreign keys and uniques match under whichever identity this dialect's\n // introspection supports (see `foreignKeyShape`). Under shape identity a\n // pair IS one shape, so a changed definition — a referential action, a\n // referenced column — is the name-identity dialects' drop and re-add.\n operations.push(\n ...diffKeyed(\n current.indexes,\n desired.indexes,\n (index) => index.name,\n (from, to) => indexesEqual(tableName, from, to, canonical),\n (index) => ({ type: \"dropIndex\", tableName, indexName: index.name }),\n (index) => ({ type: \"createIndex\", tableName, index })\n ),\n ...diffKeyed(\n current.foreignKeys,\n desired.foreignKeys,\n matchConstraintsByShape ? foreignKeyShape : (fk) => fk.name,\n (from, to) => foreignKeyShape(from) === foreignKeyShape(to),\n (fk) => ({ type: \"dropForeignKey\", tableName, fkName: fk.name }),\n (fk) => ({ type: \"addForeignKey\", tableName, fk })\n ),\n ...diffKeyed(\n current.uniqueConstraints,\n desired.uniqueConstraints,\n matchConstraintsByShape ? uniqueConstraintShape : (uq) => uq.name,\n (from, to) => uniqueConstraintShape(from) === uniqueConstraintShape(to),\n (uq) => ({\n type: \"dropUniqueConstraint\",\n tableName,\n constraintName: uq.name,\n }),\n (constraint) => ({ type: \"addUniqueConstraint\", tableName, constraint })\n )\n );\n\n // Diff primary key\n const currentPk = current.primaryKey;\n const desiredPk = desired.primaryKey;\n\n if (currentPk && !desiredPk) {\n operations.push({\n type: \"dropPrimaryKey\",\n tableName,\n constraintName: currentPk.name || `${tableName}_pkey`,\n });\n } else if (!currentPk && desiredPk) {\n operations.push({\n type: \"addPrimaryKey\",\n tableName,\n primaryKey: desiredPk,\n });\n } else if (\n currentPk &&\n desiredPk &&\n !arraysEqual(currentPk.columns, desiredPk.columns)\n ) {\n operations.push({\n type: \"dropPrimaryKey\",\n tableName,\n constraintName: currentPk.name || `${tableName}_pkey`,\n });\n operations.push({\n type: \"addPrimaryKey\",\n tableName,\n primaryKey: desiredPk,\n });\n }\n\n return { operations, ambiguousChanges };\n}\n\n// =============================================================================\n// MAIN DIFFER\n// =============================================================================\n\n/**\n * Compares two schema snapshots and returns the operations needed to\n * transform the current schema into the desired schema.\n */\nexport async function diff(\n physicalCurrent: SchemaSnapshot,\n physicalDesired: SchemaSnapshot,\n options: DiffOptions = {}\n): Promise<DiffResult> {\n const current = canonicalUniqueEntities(physicalCurrent);\n const desired = canonicalUniqueEntities(physicalDesired);\n const operations: DiffOperation[] = [];\n const ambiguousChanges: AmbiguousChange[] = [];\n\n // Logical polymorphic vocabulary is persisted only in authored snapshots.\n // Never publish an empty transition which changes the meaning of stored ids.\n for (const previous of current.polymorphicStorage ?? []) {\n const next = desired.polymorphicStorage?.find(\n (item) =>\n item.ownerTable === previous.ownerTable &&\n item.relation === previous.relation &&\n item.kind === previous.kind\n );\n if (!next) continue;\n for (const member of previous.members) {\n const destination = next.members.find(\n (item) => item.publicType === member.publicType\n );\n if (\n destination &&\n (destination.storedType !== member.storedType ||\n destination.targetTable !== member.targetTable)\n ) {\n throw new MigrationError(\n `Polymorphic storage \"${previous.ownerTable}.${previous.relation}\" changes stored meaning for \"${member.publicType}\"; author an explicit manual data transition`,\n VibORMErrorCode.MIGRATION_DESTRUCTIVE_REJECTED\n );\n }\n }\n }\n\n // Build table maps\n const currentTables = new Map(current.tables.map((t) => [t.name, t]));\n const desiredTables = new Map(desired.tables.map((t) => [t.name, t]));\n\n const canonicalPredicates = await canonicalizeChangedPredicates(\n currentTables,\n desiredTables,\n options.canonicalizeIndexPredicate\n );\n\n // Find dropped and added tables\n const droppedTables: string[] = [];\n const addedTables: string[] = [];\n\n for (const [name] of currentTables) {\n if (!desiredTables.has(name)) {\n droppedTables.push(name);\n }\n }\n\n for (const [name] of desiredTables) {\n if (!currentTables.has(name)) {\n addedTables.push(name);\n }\n }\n\n // Detect potential table renames (ambiguous changes)\n const usedDropped = new Set<string>();\n const usedAdded = new Set<string>();\n\n // Similarity orders questions, never answers them: even a zero-overlap\n // drop/create pair still requires an explicit author decision. Present the\n // strongest matches first so an unrelated drop cannot consume a clear rename.\n const candidates = droppedTables\n .flatMap((droppedName) => {\n const droppedTable = currentTables.get(droppedName)!;\n return addedTables.map((addedName) => {\n const addedTable = desiredTables.get(addedName)!;\n const matchingColumns = droppedTable.columns.filter((column) =>\n addedTable.columns.some((other) => columnsEqual(column, other, true))\n ).length;\n const matchingNames = droppedTable.columns.filter((column) =>\n addedTable.columns.some((other) => column.name === other.name)\n ).length;\n return {\n droppedName,\n addedName,\n droppedTable,\n addedTable,\n matchingColumns,\n matchingNames,\n };\n });\n })\n .sort(\n (a, b) =>\n b.matchingNames - a.matchingNames ||\n b.matchingColumns - a.matchingColumns\n );\n for (const candidate of candidates) {\n const { droppedName, addedName, droppedTable, addedTable } = candidate;\n if (usedDropped.has(droppedName) || usedAdded.has(addedName)) continue;\n ambiguousChanges.push({\n type: \"ambiguousTable\",\n droppedTable: droppedName,\n addedTable: addedName,\n droppedTableDef: droppedTable,\n addedTableDef: addedTable,\n });\n usedDropped.add(droppedName);\n usedAdded.add(addedName);\n }\n\n // Add operations for non-ambiguous table drops and creates\n for (const name of droppedTables) {\n if (!usedDropped.has(name)) {\n operations.push({ type: \"dropTable\", tableName: name });\n }\n }\n\n for (const name of addedTables) {\n if (!usedAdded.has(name)) {\n const table = desiredTables.get(name)!;\n operations.push({ type: \"createTable\", table });\n }\n }\n\n // Diff existing tables\n for (const [name, desiredTable] of desiredTables) {\n const currentTable = currentTables.get(name);\n if (currentTable) {\n const tableDiff = diffTable(\n name,\n currentTable,\n desiredTable,\n canonicalPredicates,\n options.matchConstraintsByShape ?? false,\n options.compareDateTimeDeclarations ?? false,\n options.refuseConstraintNameChurn ?? false,\n options.projectRename\n );\n operations.push(...tableDiff.operations);\n ambiguousChanges.push(...tableDiff.ambiguousChanges);\n }\n }\n\n // Diff enums (PostgreSQL specific)\n if (current.enums || desired.enums) {\n const currentEnums = new Map((current.enums || []).map((e) => [e.name, e]));\n const desiredEnums = new Map((desired.enums || []).map((e) => [e.name, e]));\n\n // Dropped enums\n for (const [name] of currentEnums) {\n if (!desiredEnums.has(name)) {\n // Find all columns that depend on this enum\n const dependentColumns: Array<{\n tableName: string;\n columnName: string;\n }> = [];\n for (const table of current.tables) {\n for (const column of table.columns) {\n if (column.type === name || column.type === `${name}[]`) {\n dependentColumns.push({\n tableName: table.name,\n columnName: column.name,\n });\n }\n }\n }\n operations.push({\n type: \"dropEnum\",\n enumName: name,\n dependentColumns:\n dependentColumns.length > 0 ? dependentColumns : undefined,\n });\n }\n }\n\n // Added enums\n for (const [name, enumDef] of desiredEnums) {\n if (!currentEnums.has(name)) {\n operations.push({ type: \"createEnum\", enumDef });\n }\n }\n\n // Modified enums\n for (const [name, desiredEnum] of desiredEnums) {\n const currentEnum = currentEnums.get(name);\n if (currentEnum && !enumsEqual(currentEnum, desiredEnum)) {\n const addValues = desiredEnum.values.filter(\n (v) => !currentEnum.values.includes(v)\n );\n const removeValues = currentEnum.values.filter(\n (v) => !desiredEnum.values.includes(v)\n );\n\n if (\n addValues.length > 0 ||\n removeValues.length > 0 ||\n !arraysEqual(currentEnum.values, desiredEnum.values)\n ) {\n // When removing values, we need to find all columns that use this enum\n // so we can temporarily convert them to text during the recreation\n let dependentColumns:\n | Array<{ tableName: string; columnName: string }>\n | undefined;\n dependentColumns = [];\n // Search through all tables (current schema) for columns using this enum\n for (const table of current.tables) {\n for (const column of table.columns) {\n if (column.type === name || column.type === `${name}[]`) {\n dependentColumns.push({\n tableName: table.name,\n columnName: column.name,\n });\n }\n }\n }\n\n operations.push({\n type: \"alterEnum\",\n enumName: name,\n addValues: addValues.length > 0 ? addValues : undefined,\n removeValues: removeValues.length > 0 ? removeValues : undefined,\n newValues: desiredEnum.values,\n dependentColumns:\n dependentColumns && dependentColumns.length > 0\n ? dependentColumns\n : undefined,\n });\n }\n }\n }\n }\n\n // Sort operations for proper execution order\n return {\n operations: sortOperations(\n operations.map((operation): DiffOperation => {\n if (operation.type === \"createTable\")\n return {\n ...operation,\n table:\n physicalDesired.tables.find(\n (table) => table.name === operation.table.name\n ) ?? operation.table,\n };\n if (operation.type === \"addUniqueConstraint\") {\n const index = physicalDesired.tables\n .find((table) => table.name === operation.tableName)\n ?.indexes.find((item) => item.name === operation.constraint.name);\n if (index)\n return {\n type: \"createIndex\",\n tableName: operation.tableName,\n index,\n };\n }\n if (operation.type === \"dropUniqueConstraint\") {\n const index = physicalCurrent.tables\n .find((table) => table.name === operation.tableName)\n ?.indexes.find((item) => item.name === operation.constraintName);\n if (index)\n return {\n type: \"dropIndex\",\n tableName: operation.tableName,\n indexName: index.name,\n };\n }\n return operation;\n })\n ),\n ambiguousChanges,\n };\n}\n\n// =============================================================================\n// DESTRUCTIVE OPERATION CHECKS\n// =============================================================================\n\n/** The one destructive-operation classification used by every consumer. */\nexport function isDestructiveOperation(operation: DiffOperation): boolean {\n if (operation.type === \"alterEnum\")\n return (operation.removeValues?.length ?? 0) > 0;\n if (operation.type === \"addColumn\")\n return !operation.column.nullable && operation.column.default === undefined;\n if (operation.type === \"dropTable\" || operation.type === \"dropColumn\") {\n return true;\n }\n return (\n operation.type === \"alterColumn\" &&\n (normalizeType(operation.from.type) !== normalizeType(operation.to.type) ||\n (operation.from.nullable && !operation.to.nullable) ||\n decimalChangeNarrows(operation.from, operation.to))\n );\n}\n\n/** What each destructive column alteration risks, one sentence per risk. */\nexport function getDestructiveOperationDescriptions(\n operations: DiffOperation[]\n): string[] {\n const descriptions: string[] = [];\n\n for (const op of operations) {\n if (op.type === \"alterColumn\") {\n if (normalizeType(op.from.type) !== normalizeType(op.to.type)) {\n descriptions.push(\n `Change type of \"${op.tableName}\".\"${op.columnName}\" from ${op.from.type} to ${op.to.type} (may cause data loss)`\n );\n }\n if (op.from.nullable && !op.to.nullable) {\n descriptions.push(\n `Make \"${op.tableName}\".\"${op.columnName}\" NOT NULL (may fail if column contains NULL values)`\n );\n }\n if (\n op.from.decimal &&\n op.to.decimal &&\n decimalChangeNarrows(op.from, op.to)\n ) {\n // The numbers go in the SENTENCE: `precision` and `scale` are not\n // error-metadata keys, so a refusal that put them in `meta` would drop\n // them silently.\n descriptions.push(\n `Narrow the decimal domain of \"${op.tableName}\".\"${op.columnName}\" from ${describeDecimalDomain(op.from.decimal)} to ${describeDecimalDomain(op.to.decimal)} (the conversion refuses every value that no longer fits, rather than rounding it)`\n );\n }\n }\n }\n\n return descriptions;\n}\n","import { renderQualifiedIdentifier } from \"../sql/identifiers\";\n/**\n * Driver catalog probes. These are the only checks the ORM proves read-only.\n * Manual trusted-read checks are a different arm.\n */\n\nimport type { AnyDriver } from \"../drivers/driver\";\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\nimport type { BoundMigrationDriver, MigrationDriver } from \"./drivers\";\nimport type { DiffOperation } from \"./types\";\nimport type { MigrationParameterV1 } from \"./v1-types\";\n\nexport interface CatalogProbe {\n readonly id: string;\n readonly sql: string;\n readonly parameters: readonly MigrationParameterV1[];\n readonly equals: boolean;\n}\n\ntype CatalogProbeLifetime = \"live-command\" | \"stored-artifact\";\n\nfunction namespace(driver: MigrationDriver): string | undefined {\n return (\n driver.namespace ??\n (driver.target?.dialect === \"postgresql\"\n ? driver.target.namespace\n : undefined)\n );\n}\n\nfunction boundCatalogNamespace(driver: MigrationDriver): string {\n const value = namespace(driver);\n if (value) return value;\n throw new MigrationError(\n \"A catalog probe needs the bound migration namespace and this driver has none\",\n VibORMErrorCode.MIGRATION_INVALID_STATE,\n { meta: { driver: driver.dialect } }\n );\n}\n\nfunction stringParam(value: string): MigrationParameterV1 {\n return { kind: \"string\", value };\n}\n\nfunction mysqlNamespaceParam(\n driver: MigrationDriver,\n lifetime: CatalogProbeLifetime\n): MigrationParameterV1 {\n return lifetime === \"stored-artifact\"\n ? { kind: \"target-namespace\" }\n : stringParam(boundCatalogNamespace(driver));\n}\n\nexport function tableExistsProbe(\n driver: MigrationDriver,\n tableName: string,\n exists: boolean,\n lifetime: CatalogProbeLifetime = \"live-command\"\n): CatalogProbe {\n const dialect = driver.dialect;\n if (dialect === \"postgresql\") {\n const schema = boundCatalogNamespace(driver);\n return {\n id: `table:${exists ? \"exists\" : \"absent\"}:${tableName}`,\n sql: `SELECT EXISTS (SELECT 1 FROM pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname = $1 AND c.relname = $2 AND c.relkind IN ('r', 'p'))`,\n parameters: [stringParam(schema), stringParam(tableName)],\n equals: exists,\n };\n }\n if (dialect === \"mysql\") {\n return {\n id: `table:${exists ? \"exists\" : \"absent\"}:${tableName}`,\n sql: \"SELECT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_schema = ? AND table_name = ?)\",\n parameters: [\n mysqlNamespaceParam(driver, lifetime),\n stringParam(tableName),\n ],\n equals: exists,\n };\n }\n return {\n id: `table:${exists ? \"exists\" : \"absent\"}:${tableName}`,\n sql: `SELECT EXISTS (SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?)`,\n parameters: [stringParam(tableName)],\n equals: exists,\n };\n}\n\nexport function columnExistsProbe(\n driver: MigrationDriver,\n tableName: string,\n columnName: string,\n exists: boolean,\n lifetime: CatalogProbeLifetime = \"live-command\"\n): CatalogProbe {\n const dialect = driver.dialect;\n if (dialect === \"postgresql\") {\n const schema = boundCatalogNamespace(driver);\n return {\n id: `column:${exists ? \"exists\" : \"absent\"}:${tableName}.${columnName}`,\n sql: \"SELECT EXISTS (SELECT 1 FROM pg_catalog.pg_attribute a JOIN pg_catalog.pg_class c ON c.oid = a.attrelid JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname = $1 AND c.relname = $2 AND a.attname = $3 AND a.attnum > 0 AND NOT a.attisdropped)\",\n parameters: [\n stringParam(schema),\n stringParam(tableName),\n stringParam(columnName),\n ],\n equals: exists,\n };\n }\n if (dialect === \"mysql\") {\n return {\n id: `column:${exists ? \"exists\" : \"absent\"}:${tableName}.${columnName}`,\n sql: \"SELECT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema = ? AND table_name = ? AND column_name = ?)\",\n parameters: [\n mysqlNamespaceParam(driver, lifetime),\n stringParam(tableName),\n stringParam(columnName),\n ],\n equals: exists,\n };\n }\n return {\n id: `column:${exists ? \"exists\" : \"absent\"}:${tableName}.${columnName}`,\n sql: \"SELECT EXISTS (SELECT 1 FROM pragma_table_info(?) WHERE name = ?)\",\n parameters: [stringParam(tableName), stringParam(columnName)],\n equals: exists,\n };\n}\n\nexport function indexExistsProbe(\n driver: MigrationDriver,\n tableName: string,\n indexName: string,\n exists: boolean,\n lifetime: CatalogProbeLifetime = \"live-command\"\n): CatalogProbe {\n const dialect = driver.dialect;\n if (dialect === \"postgresql\") {\n const schema = boundCatalogNamespace(driver);\n return {\n id: `index:${exists ? \"exists\" : \"absent\"}:${indexName}`,\n // An index exists only once it is VALID: an interrupted CONCURRENTLY\n // build leaves the relation behind with indisvalid = false. Absence\n // still means no relation of that name at all.\n sql: `SELECT EXISTS (SELECT 1 FROM pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace${exists ? \" JOIN pg_catalog.pg_index x ON x.indexrelid = c.oid AND x.indisvalid\" : \"\"} WHERE n.nspname = $1 AND c.relname = $2 AND c.relkind = 'i')`,\n parameters: [stringParam(schema), stringParam(indexName)],\n equals: exists,\n };\n }\n if (dialect === \"mysql\") {\n return {\n id: `index:${exists ? \"exists\" : \"absent\"}:${indexName}`,\n sql: \"SELECT EXISTS (SELECT 1 FROM information_schema.statistics WHERE table_schema = ? AND table_name = ? AND index_name = ?)\",\n parameters: [\n mysqlNamespaceParam(driver, lifetime),\n stringParam(tableName),\n stringParam(indexName),\n ],\n equals: exists,\n };\n }\n return {\n id: `index:${exists ? \"exists\" : \"absent\"}:${indexName}`,\n sql: `SELECT EXISTS (SELECT 1 FROM sqlite_master WHERE type = 'index' AND name = ?)`,\n parameters: [stringParam(indexName)],\n equals: exists,\n };\n}\n\nexport function probeForGeneratedStatement(\n driver: MigrationDriver,\n operation: DiffOperation,\n statement: string\n): { pre: CatalogProbe; post: CatalogProbe } | null {\n if (\n (driver.dialect === \"postgresql\" || driver.dialect === \"mysql\") &&\n namespace(driver) === undefined\n ) {\n return null;\n }\n const text = statement.trim().toUpperCase();\n if (\n text.startsWith(\"PRAGMA\") ||\n text.startsWith(\"INSERT \") ||\n text.startsWith(\"--\")\n ) {\n return null;\n }\n switch (operation.type) {\n case \"createTable\":\n if (text.startsWith(\"CREATE TABLE\")) {\n return {\n pre: tableExistsProbe(\n driver,\n operation.table.name,\n false,\n \"stored-artifact\"\n ),\n post: tableExistsProbe(\n driver,\n operation.table.name,\n true,\n \"stored-artifact\"\n ),\n };\n }\n if (text.startsWith(\"CREATE \") && text.includes(\"INDEX\")) {\n const index = operation.table.indexes.find((item) =>\n statement.includes(item.name)\n );\n if (!index) return null;\n return {\n pre: indexExistsProbe(\n driver,\n operation.table.name,\n index.name,\n false,\n \"stored-artifact\"\n ),\n post: indexExistsProbe(\n driver,\n operation.table.name,\n index.name,\n true,\n \"stored-artifact\"\n ),\n };\n }\n return null;\n case \"dropTable\":\n return {\n pre: tableExistsProbe(\n driver,\n operation.tableName,\n true,\n \"stored-artifact\"\n ),\n post: tableExistsProbe(\n driver,\n operation.tableName,\n false,\n \"stored-artifact\"\n ),\n };\n case \"addColumn\": {\n const pre = columnExistsProbe(\n driver,\n operation.tableName,\n operation.column.name,\n false,\n \"stored-artifact\"\n );\n const required =\n !operation.column.nullable &&\n operation.column.default === undefined &&\n !operation.column.autoIncrement;\n const table = renderQualifiedIdentifier(\n (name) => driver.escapeIdentifier(name),\n driver.dialect === \"postgresql\" ? namespace(driver) : undefined,\n operation.tableName\n );\n return {\n pre: required\n ? {\n ...pre,\n id: `column:absent-and-empty-table:${operation.tableName}.${operation.column.name}`,\n sql: `SELECT (${pre.sql.slice(\"SELECT \".length)}) OR EXISTS (SELECT 1 FROM ${table} LIMIT 1)`,\n }\n : pre,\n post: columnExistsProbe(\n driver,\n operation.tableName,\n operation.column.name,\n true,\n \"stored-artifact\"\n ),\n };\n }\n case \"dropColumn\":\n return {\n pre: columnExistsProbe(\n driver,\n operation.tableName,\n operation.columnName,\n true,\n \"stored-artifact\"\n ),\n post: columnExistsProbe(\n driver,\n operation.tableName,\n operation.columnName,\n false,\n \"stored-artifact\"\n ),\n };\n case \"createIndex\":\n return {\n pre: indexExistsProbe(\n driver,\n operation.tableName,\n operation.index.name,\n false,\n \"stored-artifact\"\n ),\n post: indexExistsProbe(\n driver,\n operation.tableName,\n operation.index.name,\n true,\n \"stored-artifact\"\n ),\n };\n case \"dropIndex\":\n return {\n pre: indexExistsProbe(\n driver,\n operation.tableName,\n operation.indexName,\n true,\n \"stored-artifact\"\n ),\n post: indexExistsProbe(\n driver,\n operation.tableName,\n operation.indexName,\n false,\n \"stored-artifact\"\n ),\n };\n default:\n return null;\n }\n}\n\n/** One index an interrupted CONCURRENTLY build left INVALID. */\nexport interface InvalidIndex {\n readonly table: string;\n readonly index: string;\n}\n\n/**\n * The INVALID indexes on the estate's managed tables. Only PostgreSQL has the\n * state: MySQL and SQLite build an index or fail without leaving one behind.\n */\nexport async function readInvalidIndexes(\n producer: AnyDriver,\n driver: BoundMigrationDriver\n): Promise<readonly InvalidIndex[]> {\n if (driver.dialect !== \"postgresql\") return [];\n const result = await producer._executeRaw<InvalidIndex>(\n `SELECT t.relname AS \"table\", i.relname AS \"index\" FROM pg_catalog.pg_index x JOIN pg_catalog.pg_class i ON i.oid = x.indexrelid JOIN pg_catalog.pg_class t ON t.oid = x.indrelid JOIN pg_catalog.pg_namespace n ON n.oid = t.relnamespace WHERE n.nspname = $1 AND t.relkind = 'r' AND NOT (x.indisvalid AND x.indisready) ORDER BY t.relname, i.relname`,\n [boundCatalogNamespace(driver)]\n );\n const managed = driver.target.tables;\n return result.rows.filter(\n (row) => managed === undefined || managed.includes(row.table)\n );\n}\n\nexport function boundNamespace(\n driver: BoundMigrationDriver\n): string | undefined {\n return namespace(driver);\n}\n\n/**\n * One object's name as a live statement spells it: qualified with the bound\n * namespace, or bare on SQLite and on unbound MySQL.\n */\nexport function qualifiedName(\n driver: BoundMigrationDriver,\n name: string\n): string {\n return renderQualifiedIdentifier(\n (part) => driver.escapeIdentifier(part),\n driver.target.dialect === \"sqlite\" ? undefined : namespace(driver),\n name\n );\n}\n","/**\n * Inverse owner for generated DiffOperation programs.\n * Empty programs invert to an empty schema rollback. Missing inverses are\n * irreversible. This is the only place that answers that question.\n */\n\nimport { applyNativeRename } from \"./native-rename\";\nimport type { DiffOperation, SchemaSnapshot, TableDef } from \"./types\";\nimport { defaultGeneratedPrimaryKeyName } from \"./utils\";\n\nexport interface InvertedOperations {\n operations: DiffOperation[];\n warnings: string[];\n}\n\nexport function invertOperations(\n operations: DiffOperation[],\n previousSnapshot: SchemaSnapshot,\n projectRename: typeof applyNativeRename = applyNativeRename,\n primaryKeyName: typeof defaultGeneratedPrimaryKeyName = defaultGeneratedPrimaryKeyName\n): InvertedOperations {\n const warnings: string[] = [];\n const inverted: DiffOperation[] = [];\n // At the inverse of operation i, every rename that preceded i in the up\n // program is still active and every rename that followed it has already been\n // inverted. Keep the previous definitions at each exact prefix so a restored\n // FK targets the identity that exists at that point — neither always-old nor\n // always-new is correct.\n let previousAtOperationIdentity = previousSnapshot;\n const previousIdentityBefore: SchemaSnapshot[] = [];\n // A key the up program drops by itself (PostgreSQL/MySQL drop every key of\n // a dropped table first) comes back through that drop's own inverse, which\n // runs after every recreated table exists. The recreated table leaves it\n // out: restored inline it would name a table not yet recreated, and then be\n // added a second time.\n const keysRestoredByTheirOwnInverse = new Set<string>();\n for (const op of operations) {\n previousIdentityBefore.push(previousAtOperationIdentity);\n if (op.type === \"dropForeignKey\") {\n keysRestoredByTheirOwnInverse.add(\n foreignKeyIdentity(op.tableName, op.fkName)\n );\n }\n if (op.type === \"renameTable\" || op.type === \"renameColumn\") {\n previousAtOperationIdentity = projectRename(\n previousAtOperationIdentity,\n op\n );\n }\n }\n\n for (let i = operations.length - 1; i >= 0; i--) {\n const op = operations[i]!;\n const previousAtIdentity = previousIdentityBefore[i] ?? previousSnapshot;\n const findPrevTable = (name: string): TableDef | undefined =>\n previousAtIdentity.tables.find((table) => table.name === name);\n const inverse = invertOperation(\n op,\n previousSnapshot,\n findPrevTable,\n keysRestoredByTheirOwnInverse,\n warnings,\n primaryKeyName\n );\n if (inverse) inverted.push(...inverse);\n }\n\n return { operations: inverted, warnings };\n}\n\nconst foreignKeyIdentity = (tableName: string, fkName: string) =>\n `${tableName}\\u0000${fkName}`;\n\nfunction invertOperation(\n op: DiffOperation,\n previousSnapshot: SchemaSnapshot,\n findPrevTable: (name: string) => TableDef | undefined,\n keysRestoredByTheirOwnInverse: ReadonlySet<string>,\n warnings: string[],\n primaryKeyName: typeof defaultGeneratedPrimaryKeyName\n): DiffOperation[] | null {\n switch (op.type) {\n case \"createTable\":\n warnings.push(\n `createTable \"${op.table.name}\" inverts to dropTable: rolling back drops the table and every row created after this migration. No data is preserved.`\n );\n return [{ type: \"dropTable\", tableName: op.table.name }];\n\n case \"dropTable\": {\n const table = findPrevTable(op.tableName);\n if (!table) {\n warnings.push(\n `Cannot invert dropTable \"${op.tableName}\": table not found in previous snapshot.`\n );\n return null;\n }\n warnings.push(\n `dropTable \"${op.tableName}\" was lossy: rolling back recreates the table structure but not its data.`\n );\n const foreignKeys = table.foreignKeys.filter(\n (fk) =>\n !keysRestoredByTheirOwnInverse.has(\n foreignKeyIdentity(table.name, fk.name)\n )\n );\n return [{ type: \"createTable\", table: { ...table, foreignKeys } }];\n }\n\n case \"renameTable\":\n return [{ type: \"renameTable\", from: op.to, to: op.from }];\n\n case \"addColumn\":\n return [\n {\n type: \"dropColumn\",\n tableName: op.tableName,\n columnName: op.column.name,\n },\n ];\n\n case \"dropColumn\": {\n const table = findPrevTable(op.tableName);\n const column = table?.columns.find((c) => c.name === op.columnName);\n if (!column) {\n warnings.push(\n `Cannot invert dropColumn \"${op.tableName}.${op.columnName}\": column not found in previous snapshot.`\n );\n return null;\n }\n warnings.push(\n `dropColumn \"${op.tableName}.${op.columnName}\" was lossy: rolling back restores the column but not its data.`\n );\n return [{ type: \"addColumn\", tableName: op.tableName, column }];\n }\n\n case \"renameColumn\":\n return [\n {\n type: \"renameColumn\",\n tableName: op.tableName,\n from: op.to,\n to: op.from,\n },\n ];\n\n case \"alterColumn\":\n return [\n {\n type: \"alterColumn\",\n tableName: op.tableName,\n columnName: op.columnName,\n from: op.to,\n to: op.from,\n },\n ];\n\n case \"createIndex\":\n return [\n {\n type: \"dropIndex\",\n tableName: op.tableName,\n indexName: op.index.name,\n },\n ];\n\n case \"dropIndex\": {\n const table = findPrevTable(op.tableName);\n const index = table?.indexes.find((i) => i.name === op.indexName);\n if (!index) {\n warnings.push(\n `Cannot invert dropIndex \"${op.indexName}\" on \"${op.tableName}\": index not found in previous snapshot.`\n );\n return null;\n }\n return [{ type: \"createIndex\", tableName: op.tableName, index }];\n }\n\n case \"addForeignKey\":\n return [\n { type: \"dropForeignKey\", tableName: op.tableName, fkName: op.fk.name },\n ];\n\n case \"dropForeignKey\": {\n const table = findPrevTable(op.tableName);\n const fk = table?.foreignKeys.find((f) => f.name === op.fkName);\n if (!fk) {\n warnings.push(\n `Cannot invert dropForeignKey \"${op.fkName}\" on \"${op.tableName}\": foreign key not found in previous snapshot.`\n );\n return null;\n }\n return [{ type: \"addForeignKey\", tableName: op.tableName, fk }];\n }\n\n case \"addUniqueConstraint\":\n return [\n {\n type: \"dropUniqueConstraint\",\n tableName: op.tableName,\n constraintName: op.constraint.name,\n },\n ];\n\n case \"dropUniqueConstraint\": {\n const table = findPrevTable(op.tableName);\n const constraint = table?.uniqueConstraints.find(\n (u) => u.name === op.constraintName\n );\n if (!constraint) {\n warnings.push(\n `Cannot invert dropUniqueConstraint \"${op.constraintName}\" on \"${op.tableName}\": constraint not found in previous snapshot.`\n );\n return null;\n }\n return [\n { type: \"addUniqueConstraint\", tableName: op.tableName, constraint },\n ];\n }\n\n case \"addPrimaryKey\":\n return [\n {\n type: \"dropPrimaryKey\",\n tableName: op.tableName,\n constraintName: primaryKeyName(op.tableName, op.primaryKey.name),\n },\n ];\n\n case \"dropPrimaryKey\": {\n const table = findPrevTable(op.tableName);\n if (!table?.primaryKey) {\n warnings.push(\n `Cannot invert dropPrimaryKey on \"${op.tableName}\": primary key not found in previous snapshot.`\n );\n return null;\n }\n return [\n {\n type: \"addPrimaryKey\",\n tableName: op.tableName,\n primaryKey: table.primaryKey,\n },\n ];\n }\n\n case \"createEnum\":\n return [{ type: \"dropEnum\", enumName: op.enumDef.name }];\n\n case \"dropEnum\": {\n const enumDef = previousSnapshot.enums?.find(\n (e) => e.name === op.enumName\n );\n if (!enumDef) {\n warnings.push(\n `Cannot invert dropEnum \"${op.enumName}\": enum not found in previous snapshot.`\n );\n return null;\n }\n return [{ type: \"createEnum\", enumDef }];\n }\n\n case \"alterEnum\": {\n const prevEnum = previousSnapshot.enums?.find(\n (e) => e.name === op.enumName\n );\n if (!prevEnum) {\n warnings.push(\n `Cannot invert alterEnum \"${op.enumName}\": enum not found in previous snapshot.`\n );\n return null;\n }\n if (op.removeValues?.length) {\n warnings.push(\n `alterEnum \"${op.enumName}\" removed values [${op.removeValues.join(\", \")}]: rolling back restores the values but not replaced row data.`\n );\n }\n if (op.addValues?.length) {\n warnings.push(\n `alterEnum \"${op.enumName}\" rollback removes values [${op.addValues.join(\", \")}]: rows using them will fail unless remapped manually.`\n );\n }\n return [\n {\n type: \"alterEnum\",\n enumName: op.enumName,\n addValues: op.removeValues,\n removeValues: op.addValues,\n newValues: prevEnum.values,\n dependentColumns: op.dependentColumns,\n },\n ];\n }\n\n default:\n warnings.push(\"Cannot invert an unknown generated operation.\");\n return null;\n }\n}\n","/**\n * Exact SQL framing for Migration V1.\n *\n * The blob is the human review artifact. Execution slices UTF-8 byte ranges.\n * There is no delimiter parser, breakpoint marker, or comment search.\n */\n\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\nimport { decodeUtf8, type Sha256 } from \"./identity\";\nimport { encodeSqlBlob } from \"./v1-parse\";\nimport type { MigrationDispatchV1, MigrationSqlRangeV1 } from \"./v1-types\";\n\nconst DISPLAY_SEPARATOR = new TextEncoder().encode(\"\\n\\n\");\n\nexport function encodeSqlText(text: string): Uint8Array {\n if (text.includes(\"\\r\")) {\n throw new MigrationError(\n \"Manual SQL fragments containing carriage returns are refused\",\n VibORMErrorCode.MIGRATION_INVALID_ESTATE\n );\n }\n if (text.startsWith(\"\\uFEFF\")) {\n throw new MigrationError(\n \"SQL blobs must be UTF-8 without a BOM\",\n VibORMErrorCode.MIGRATION_INVALID_ESTATE\n );\n }\n return new TextEncoder().encode(text);\n}\n\nexport function composeSqlBlob(fragments: readonly string[]): {\n bytes: Uint8Array;\n ranges: MigrationSqlRangeV1[];\n sqlHash: Sha256;\n} {\n const encoded = fragments.map(encodeSqlText);\n let total = 0;\n for (let i = 0; i < encoded.length; i++) {\n if (i > 0) total += DISPLAY_SEPARATOR.length;\n total += encoded[i]!.length;\n }\n const bytes = new Uint8Array(total);\n const ranges: MigrationSqlRangeV1[] = [];\n let offset = 0;\n for (let i = 0; i < encoded.length; i++) {\n if (i > 0) {\n bytes.set(DISPLAY_SEPARATOR, offset);\n offset += DISPLAY_SEPARATOR.length;\n }\n const fragment = encoded[i]!;\n bytes.set(fragment, offset);\n ranges.push({\n dispatchId: \"\",\n offset,\n length: fragment.length,\n });\n offset += fragment.length;\n }\n return {\n bytes,\n sqlHash: encodeSqlBlob(bytes),\n ranges,\n };\n}\n\nexport function validateSqlRanges(\n bytes: Uint8Array,\n dispatches: readonly MigrationDispatchV1[]\n): void {\n if (\n bytes.length >= 3 &&\n bytes[0] === 0xef &&\n bytes[1] === 0xbb &&\n bytes[2] === 0xbf\n ) {\n throw new MigrationError(\n \"SQL blobs must be UTF-8 without a BOM\",\n VibORMErrorCode.MIGRATION_INVALID_ESTATE\n );\n }\n if (bytes.includes(0x0d)) {\n throw new MigrationError(\n \"SQL blobs must be UTF-8/LF without carriage returns\",\n VibORMErrorCode.MIGRATION_INVALID_ESTATE\n );\n }\n try {\n decodeUtf8(bytes);\n } catch {\n throw new MigrationError(\n \"SQL blobs must be valid UTF-8\",\n VibORMErrorCode.MIGRATION_INVALID_ESTATE\n );\n }\n const sqlHash = encodeSqlBlob(bytes);\n const unique: MigrationDispatchV1[] = [];\n const seen = new Set<string>();\n for (const dispatch of dispatches) {\n if (seen.has(dispatch.dispatchId)) continue;\n seen.add(dispatch.dispatchId);\n unique.push(dispatch);\n }\n const ordered = unique.sort(\n (left, right) => left.offset - right.offset || left.length - right.length\n );\n let previousEnd = 0;\n for (let index = 0; index < ordered.length; index++) {\n const dispatch = ordered[index]!;\n if (dispatch.sqlHash !== sqlHash) {\n throw new MigrationError(\n \"Dispatch sqlHash does not match the SQL blob\",\n VibORMErrorCode.MIGRATION_CORRUPTION\n );\n }\n if (\n !(\n Number.isSafeInteger(dispatch.offset) &&\n Number.isSafeInteger(dispatch.length)\n ) ||\n dispatch.offset < 0 ||\n dispatch.length < 0\n ) {\n throw new MigrationError(\n \"SQL ranges must use non-negative safe integers\",\n VibORMErrorCode.MIGRATION_INVALID_ESTATE\n );\n }\n if (dispatch.offset + dispatch.length > bytes.length) {\n throw new MigrationError(\n \"SQL range exceeds the blob\",\n VibORMErrorCode.MIGRATION_INVALID_ESTATE\n );\n }\n if (index === 0) {\n if (dispatch.offset !== 0) {\n throw new MigrationError(\n \"SQL ranges must begin at byte zero\",\n VibORMErrorCode.MIGRATION_INVALID_ESTATE\n );\n }\n } else {\n const expectedOffset = previousEnd + DISPLAY_SEPARATOR.length;\n if (dispatch.offset !== expectedOffset) {\n throw new MigrationError(\n dispatch.offset < expectedOffset\n ? \"SQL ranges overlap or omit their separator\"\n : \"SQL ranges contain an unclaimed gap\",\n VibORMErrorCode.MIGRATION_INVALID_ESTATE\n );\n }\n if (bytes[previousEnd] !== 0x0a || bytes[previousEnd + 1] !== 0x0a) {\n throw new MigrationError(\n \"SQL range separators must be exactly two newline bytes\",\n VibORMErrorCode.MIGRATION_INVALID_ESTATE\n );\n }\n }\n previousEnd = dispatch.offset + dispatch.length;\n }\n if (ordered.length === 0) {\n if (bytes.length === 0) return;\n throw new MigrationError(\n \"A SQL blob without dispatches must be empty\",\n VibORMErrorCode.MIGRATION_INVALID_ESTATE\n );\n }\n if (previousEnd === bytes.length) return;\n if (previousEnd + 1 === bytes.length && bytes[previousEnd] === 0x0a) {\n return;\n }\n throw new MigrationError(\n \"SQL blobs contain bytes after the final range\",\n VibORMErrorCode.MIGRATION_INVALID_ESTATE\n );\n}\n\nexport function sliceDispatch(\n bytes: Uint8Array,\n dispatch: MigrationDispatchV1\n): string {\n return new TextDecoder(\"utf-8\", { fatal: true }).decode(\n bytes.subarray(dispatch.offset, dispatch.offset + dispatch.length)\n );\n}\n\nconst MYSQL_DELIMITER = /(^|\\s)DELIMITER\\s/i;\n\nexport function refuseMysqlDelimiter(text: string): void {\n if (MYSQL_DELIMITER.test(text)) {\n throw new MigrationError(\n \"MySQL DELIMITER is a client command, not server SQL\",\n VibORMErrorCode.MIGRATION_INVALID_ESTATE\n );\n }\n}\n","/**\n * The ONE lexical classifier for migration-artifact execution safety.\n *\n * VibORM opens an enclosing boundary around every artifact it executes: an\n * apply/down/reset transaction on PostgreSQL, and a session lock on both\n * PostgreSQL and MySQL. This module refuses the DIRECT statements that would\n * end or reframe it — a `COMMIT` inside an artifact ends the rollback scope\n * VibORM promised, and a `RELEASE_LOCK`/`pg_advisory_unlock` inside one frees\n * the lock that is excluding every other migration command (§3.5).\n *\n * It refuses direct lexical controls and is NOT a sandbox for procedural or\n * dynamic SQL. That distinction is the module's contract, not a caveat on it.\n * Manual migration SQL is trusted last-mile authority: its author owns what it\n * does, this included. A dollar-quoted body is DATA to this scan — it has to\n * be, or every ordinary `CREATE FUNCTION` is refused — and the same bytes are a\n * statement to the server, so `DO $$ BEGIN PERFORM pg_advisory_unlock_all();\n * END $$` frees the migration lock while the command holds it. A pre-existing\n * safe-named function, a function the artifact creates, and `EXECUTE` over a\n * built string are the same escape by another route. It is executed rather than\n * asserted: `tests/unit/migrations/pinned-migration-session.core.test.ts` runs\n * that exact artifact through `apply()` on a real PostgreSQL and pins the lock\n * gone. Do not answer a procedural escape with another spelling here — the\n * enumeration does not close, and every addition costs valid author SQL.\n *\n * What the refusals do buy is the ACCIDENT and the audit: an author who typed a\n * `COMMIT` or a `pg_advisory_unlock(...)` straight into an artifact learns\n * before any of it runs, and a deliberate escape has to be WRITTEN as one, in\n * the artifact, where a reviewer sees it. The deliberate case is answered\n * afterwards instead, by the release proof in `pinned-session.ts`: a lock the\n * command acquired and no longer holds fails that command loudly and discards\n * the session, rather than letting it report a migration that ran outside the\n * boundary it published.\n *\n * The scanner is comment- and string-safe, which is the whole reason this is a\n * classifier rather than a regular expression: `-- COMMIT`, `'COMMIT'`, a\n * column named `\"commit\"`, and a dollar-quoted body that merely mentions\n * `pg_advisory_unlock` are all valid SQL and must stay valid. Only executable\n * tokens are classified.\n *\n * Executable is not enough on its own, because a spelling is not a role. A\n * table named `pg_advisory_notes`, a column named `release_lock`, and MySQL's\n * `@autocommit` user variable are executable tokens that call nothing and set\n * nothing, and refusing them refused valid author SQL over a resemblance. So\n * every scanned word carries the role its POSITION gives it, and the lock\n * refusals key on a call — one owner deciding it for bare and quoted\n * identifiers alike.\n *\n * Comment- and string-safety is DIALECT-SPECIFIC, so the scan takes the dialect\n * rather than reading one lexical grammar into both servers. Every arm below\n * that branches exists because the two servers disagree about what is data:\n * MySQL's `#` line comments and its `--` whitespace rule, its executable\n * `/*!…` comments whose contents the server RUNS, its backslash escapes inside\n * string literals, PostgreSQL's `E'…'` escape strings, and PostgreSQL's nested\n * block comments. Reading one server's grammar on the other either blinds the\n * scanner to a real statement or refuses an artifact that is entirely a\n * comment.\n */\n\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\nimport type { MigrationTarget } from \"./types\";\n\n/**\n * Statement-leading PHRASES that open, close, or reframe a transaction.\n *\n * The test is on the LEADING word because that is what makes the word a\n * statement rather than a name: `END` opens nothing in `CREATE TABLE end_state`,\n * and `RELEASE` is only `RELEASE SAVEPOINT` at the start of a statement.\n *\n * `PREPARE TRANSACTION` is the entry that needs a second word, and it needs it\n * in both directions. It DETACHES the running transaction from this session for\n * a later `COMMIT PREPARED`, so where the server allows it at all\n * (`max_prepared_transactions > 0`) the entry's DDL is left unresolved while\n * the tracking write that records it lands in the autocommit that follows. And\n * `PREPARE plan AS SELECT …` begins with the same word while controlling\n * nothing, so refusing the leader alone would ban ordinary author SQL. The\n * phrase is the unit of the test; `PREPARE` alone is not an entry. Its two\n * siblings need no entry of their own — `COMMIT PREPARED` and\n * `ROLLBACK PREPARED` already lead with a refused word.\n */\nconst POSTGRES_TRANSACTION_LEADERS = new Set([\n \"ABORT\",\n \"BEGIN\",\n \"COMMIT\",\n \"END\",\n \"PREPARE TRANSACTION\",\n \"RELEASE\",\n \"ROLLBACK\",\n \"SAVEPOINT\",\n \"START\",\n]);\n\nconst MYSQL_TRANSACTION_LEADERS = new Set([\n \"BEGIN\",\n \"COMMIT\",\n \"LOCK\",\n \"RELEASE\",\n \"ROLLBACK\",\n \"SAVEPOINT\",\n \"START\",\n \"UNLOCK\",\n \"XA\",\n]);\n\n/** SQLite controls over the transaction boundary owned by the migration run. */\nconst SQLITE_TRANSACTION_LEADERS = new Set([\n \"BEGIN\",\n \"COMMIT\",\n \"END\",\n \"RELEASE\",\n \"ROLLBACK\",\n \"SAVEPOINT\",\n]);\n\n/**\n * PostgreSQL's advisory-lock family, by prefix.\n *\n * A prefix rather than a list because the family is closed by naming\n * convention and open by variant: session and transaction scope, shared and\n * exclusive, blocking and `try_`. Enumerating them invites the one that is\n * missed.\n *\n * Being this wide is only safe because the prefix is read at a CALL and nowhere\n * else. `pg_advisory_notes` is a table an author may have kept for years, and\n * `pg_advisory_note` a column in it; the family's spelling makes neither of them\n * a function, and refusing them refused valid SQL over a resemblance.\n */\nconst POSTGRES_ADVISORY_PREFIXES = [\"PG_ADVISORY\", \"PG_TRY_ADVISORY\"];\n\n/**\n * Words after which an identifier is the NAME of the object a statement\n * defines, never a function it calls — even with a `(` right behind it.\n *\n * `CREATE TABLE pg_advisory_notes (id INT)` opens a COLUMN list, and\n * `CREATE FUNCTION \"pg_advisory_unlock_all\"()` an argument declaration; neither\n * calls anything. These are the only words a `(`-followed identifier can sit\n * behind without being a call, and the two servers agree on them: neither has\n * an expression in which a called function's name follows the bare word TABLE,\n * VIEW, FUNCTION, PROCEDURE, AGGREGATE, or the EXISTS of `IF NOT EXISTS`.\n *\n * MySQL's inline index names — `UNIQUE KEY get_lock (id)` — are the one\n * definition this set does not reach, and `KEY`/`INDEX` stay out of it on\n * purpose: unlike the six above, each is also an ordinary column name, so the\n * set would start being reached from expressions and exempt what follows one.\n * A refused index name costs its author a rename; that exemption costs the\n * boundary.\n */\nconst OBJECT_NAME_KEYWORDS = new Set([\n \"AGGREGATE\",\n \"EXISTS\",\n \"FUNCTION\",\n \"PROCEDURE\",\n \"TABLE\",\n \"VIEW\",\n]);\n\n/** MySQL's named-lock family: acquisition, release, and both probes. */\nconst MYSQL_LOCK_FUNCTIONS = new Set([\n \"GET_LOCK\",\n \"IS_FREE_LOCK\",\n \"IS_USED_LOCK\",\n \"RELEASE_ALL_LOCKS\",\n \"RELEASE_LOCK\",\n]);\n\n/** The tag body of a PostgreSQL dollar quote: `$tag$`. */\nconst DOLLAR_TAG_PART = /[A-Za-z0-9_]/;\n/** The optional server-version prefix of a MySQL executable comment. */\nconst VERSION_DIGIT = /[0-9]/;\n\n/**\n * MySQL's SYSTEM-variable sigil, which the bare spelling of the same name also\n * reaches: `SET @@autocommit = 0` and `SET autocommit = 0` change one setting,\n * so the sigil folds away and both meet the same refusal.\n *\n * ONE `@` does not fold. `@autocommit` is a user variable — a slot with a name\n * that happens to read like the setting, which no server behavior consults —\n * and folding it refused `SET @autocommit = 0`, valid MySQL, as a commit-\n * boundary change. `SELECT @release_lock` was refused as a lock call the same\n * way.\n */\nconst SYSTEM_VARIABLE_SIGIL = /^@@/;\n\n/**\n * The dialects this classifier reads.\n */\nexport type ClassifiedDialect = \"postgresql\" | \"mysql\" | \"sqlite\";\n\n/**\n * The characters that make a bare word, per dialect.\n *\n * `@` is the whole difference and it is not cosmetic. In MySQL the sigil is\n * part of the identifier — `@name` and `@@name` are two different names, and\n * neither is the bare one. PostgreSQL has no variable sigil at all: `@` is an\n * operator character there, so joining it to the word behind it would read\n * `SELECT @pg_advisory_unlock(1)` as one name the advisory prefix no longer\n * matches, hiding a call the server still makes.\n */\nconst WORD_CHARACTERS: Record<\n ClassifiedDialect,\n { readonly start: RegExp; readonly part: RegExp }\n> = {\n mysql: { start: /[A-Za-z_@]/, part: /[A-Za-z0-9_$@]/ },\n postgresql: { start: /[A-Za-z_]/, part: /[A-Za-z0-9_$]/ },\n sqlite: { start: /[A-Za-z_]/, part: /[A-Za-z0-9_$]/ },\n};\n\n/**\n * One executable word and the syntactic role its POSITION gives it.\n *\n * The role is the point. A lock-function refusal that reads spelling alone\n * refuses `CREATE TABLE get_lock (id INT)` and `CREATE TABLE t (release_lock\n * INT)`, which call nothing and are the author's to keep. `calls` is decided\n * once, by {@link callsArguments}, for bare and quoted identifiers alike.\n */\ntype ScannedWord = {\n /**\n * The folded spelling. A bare word arrives uppercased, minus MySQL's system\n * sigil; a called quoted identifier arrives in its own lowercase spelling,\n * which is the only one that names a PostgreSQL built-in.\n */\n readonly text: string;\n /** Whether an argument list opens behind it, in a position that may call. */\n readonly calls: boolean;\n};\n\n/**\n * What sits immediately in front of the cursor, whitespace and comments apart.\n *\n * `qualifier` is the `.` of a qualified name, and it is why the role of\n * `alpha.pg_advisory_notes` is decided by the word in front of `alpha`:\n * `CREATE TABLE` defines that name and `SELECT` calls it, and the qualifier\n * between them changes neither.\n */\ntype PrecedingToken = \"word\" | \"qualifier\" | \"other\";\n\n/**\n * The EXECUTABLE bare words of an artifact chunk, grouped per statement.\n *\n * Grouping on the top-level `;` is load-bearing, not cosmetic: VibORM's\n * artifact parser splits on its own breakpoint marker, so ONE parsed chunk\n * routinely holds several SQL statements. A classifier that only looked at the\n * first word of the chunk would read `CREATE TABLE t; COMMIT;` as a `CREATE`\n * and let the `COMMIT` through — which is precisely the statement that ends the\n * transaction VibORM promised.\n *\n * Quoted identifiers are excluded rather than included WHEN THEY ARE NAMED: a\n * table or column the author quoted is a name, never a keyword, so\n * `CREATE TABLE \"commit\"` and a column named `` `get_lock` `` stay valid. Text\n * inside comments, single-quoted literals and PostgreSQL dollar-quoted bodies\n * is skipped for the same reason — it is data, not a statement.\n *\n * A quoted identifier the statement CALLS is the exception: quoting a\n * function's name does not stop PostgreSQL calling it, so\n * `pg_catalog.\"pg_advisory_unlock_all\"()` frees the lock excluding every other\n * migration command while every word the scan retained says\n * `SELECT pg_catalog`. Which of the two a quoted run is comes from\n * {@link callsArguments}, the same owner that decides it for bare words.\n *\n * The dialect decides which runs are data. A MySQL executable comment is the\n * clearest case: its contents are not data at all, and the server runs them.\n */\nexport function readExecutableStatements(\n sql: string,\n dialect: ClassifiedDialect\n): string[][] {\n return scanStatements(sql, dialect).map((words) =>\n words.map((word) => word.text)\n );\n}\n\n/**\n * The scan itself: executable words with the role their position gives them,\n * grouped per statement.\n *\n * {@link readExecutableStatements} is this without the roles, which is all the\n * enum-boundary question needs; {@link classifyOne} needs them, because a\n * spelling in a name position is not the call it refuses.\n */\nfunction scanStatements(\n sql: string,\n dialect: ClassifiedDialect\n): ScannedWord[][] {\n const characters = WORD_CHARACTERS[dialect];\n const statements: ScannedWord[][] = [];\n let words: ScannedWord[] = [];\n let index = 0;\n let preceding: PrecedingToken = \"other\";\n /** The previous identifier RUN, whether or not the scan retained it. */\n let previousWord: string | undefined;\n /** The word governing the identifier position the cursor stands in. */\n let governing: string | undefined;\n\n while (index < sql.length) {\n const char = sql.charAt(index);\n const next = sql.charAt(index + 1);\n\n if (char === \"-\" && next === \"-\" && opensLineComment(sql, index, dialect)) {\n index = skipLine(sql, index);\n continue;\n }\n // MySQL's second line-comment spelling. PostgreSQL has none: `#` is an\n // operator character there, and skipping to end of line on it would blind\n // the scan to whatever followed on that line.\n if (dialect === \"mysql\" && char === \"#\") {\n index = skipLine(sql, index);\n continue;\n }\n if (char === \"/\" && next === \"*\") {\n if (dialect === \"mysql\" && sql[index + 2] === \"!\") {\n index = openExecutableComment(sql, index);\n continue;\n }\n index = skipBlockComment(sql, index, dialect);\n continue;\n }\n if (char === \"'\" || char === '\"' || char === \"`\") {\n const quoteEnd = skipQuoted(\n sql,\n index,\n char,\n escapesWithBackslash(dialect, char)\n );\n governing = governingWord(preceding, previousWord, governing);\n const name = readQuotedIdentifier(sql, index, quoteEnd, char, dialect);\n if (name !== null && callsArguments(sql, quoteEnd, governing, dialect)) {\n words.push({ text: name, calls: true });\n }\n // A quoted run ends the reach of whatever governed it: nothing that\n // follows a closing quote directly is the name of a defined object.\n preceding = \"other\";\n index = quoteEnd;\n continue;\n }\n if (dialect === \"sqlite\" && char === \"[\") {\n index = skipBracketQuoted(sql, index);\n preceding = \"other\";\n continue;\n }\n if (dialect === \"postgresql\" && char === \"$\") {\n const dollarEnd = skipDollarQuoted(sql, index);\n if (dollarEnd !== null) {\n index = dollarEnd;\n preceding = \"other\";\n continue;\n }\n }\n if (char === \";\") {\n if (words.length > 0) {\n statements.push(words);\n words = [];\n }\n index += 1;\n preceding = \"other\";\n continue;\n }\n if (characters.start.test(char)) {\n const start = index;\n index += 1;\n while (index < sql.length && characters.part.test(sql.charAt(index))) {\n index += 1;\n }\n const text = sql\n .slice(start, index)\n .toUpperCase()\n .replace(SYSTEM_VARIABLE_SIGIL, \"\");\n // PostgreSQL's `E'…'` escape string. The `E` is the literal's prefix, not\n // a bare word, and it is the ONE PostgreSQL string form where a backslash\n // escapes the closing quote — reading it as a standard literal closes it\n // early at `\\'` and hides every statement up to the next quote.\n if (dialect === \"postgresql\" && text === \"E\" && sql[index] === \"'\") {\n index = skipQuoted(sql, index, \"'\", true);\n preceding = \"other\";\n continue;\n }\n governing = governingWord(preceding, previousWord, governing);\n words.push({\n text,\n calls: callsArguments(sql, index, governing, dialect),\n });\n previousWord = text;\n preceding = \"word\";\n continue;\n }\n if (char.trim() !== \"\") {\n preceding = char === \".\" ? \"qualifier\" : \"other\";\n }\n index += 1;\n }\n\n if (words.length > 0) {\n statements.push(words);\n }\n return statements;\n}\n\n/**\n * The word that governs the identifier position at the cursor, or undefined\n * when no word reaches it.\n *\n * Directly in front of an identifier, a word governs it: the `TABLE` of\n * `CREATE TABLE get_lock (…)` says that name is being defined. Across a `.`\n * the governor is inherited rather than replaced, so a qualified name is\n * decided by whatever opened the chain — `CREATE TABLE alpha.pg_advisory_notes\n * (…)` defines, `SELECT pg_catalog.\"pg_advisory_unlock_all\"()` calls.\n *\n * Any other punctuation ends the reach, and that is the half that keeps the\n * exemption honest: a comma away from a column named `view`,\n * `SELECT view, \"pg_advisory_unlock\"(1)` is a call, and reading the previous\n * WORD alone admitted it as a definition.\n */\nfunction governingWord(\n preceding: PrecedingToken,\n previousWord: string | undefined,\n chainGovernor: string | undefined\n): string | undefined {\n if (preceding === \"word\") {\n return previousWord;\n }\n if (preceding === \"qualifier\") {\n return chainGovernor;\n }\n return undefined;\n}\n\n/**\n * The unquoted-equivalent spelling of a quoted identifier, or null when the\n * quoted run is a literal or a spelling no built-in answers to.\n *\n * PostgreSQL is the only dialect that reaches a decision here. MySQL's `\"` is a\n * STRING quote, so the same bytes are data there, and its backtick-quoted names\n * resolve to stored functions rather than to the built-in named-lock family —\n * `` SELECT `release_lock`('k') `` does not run MySQL's `RELEASE_LOCK`.\n *\n * A quoted identifier is CASE-SENSITIVE, so only the folded spelling names the\n * built-in: `\"PG_ADVISORY_UNLOCK_ALL\"` is a function PostgreSQL does not have,\n * and refusing it would ban a name over a call that cannot happen. The name is\n * returned in that folded (lowercase) spelling, which is also what keeps it out\n * of every keyword test in this module — bare words arrive uppercased.\n */\nfunction readQuotedIdentifier(\n sql: string,\n start: number,\n end: number,\n quote: string,\n dialect: ClassifiedDialect\n): string | null {\n if (dialect !== \"postgresql\" || quote !== '\"') {\n return null;\n }\n // An UNTERMINATED quote ran to the end of the input; nothing follows it, so\n // nothing calls it.\n if (end - start < 2 || sql[end - 1] !== '\"') {\n return null;\n }\n const name = sql.slice(start + 1, end - 1).replaceAll('\"\"', '\"');\n return name === name.toLowerCase() ? name : null;\n}\n\n/**\n * The ONE call-position owner: whether the identifier ending at `end` is CALLED\n * where it stands.\n *\n * Two halves, and both are needed. A governing keyword makes the identifier the\n * name of an object being defined, `(` behind it or not — that is what keeps\n * `CREATE TABLE pg_advisory_notes (id INT)` and\n * `CREATE TABLE \"pg_advisory_unlock_all\" (id INT)` valid, since both open a\n * column list. Otherwise an argument list has to actually open, modulo what\n * sits between a function's name and its `(`: whitespace is the obvious case\n * and comments are the one that matters, because\n * `pg_catalog.\"pg_advisory_unlock_all\"/**\\/()` is one call to the server and a\n * lookahead that stopped at the first non-space would read it as a name.\n *\n * A qualifier is not read: `myschema.\"pg_advisory_unlock\"()` is a call too,\n * because a `search_path` this classifier cannot see decides what that name\n * resolves to. Whitespace before the `(` is admitted on MySQL as well, where\n * only `IGNORE_SPACE` makes the server accept it — refusing a call the server\n * might make is the direction this classifier can afford to be wrong in.\n */\nfunction callsArguments(\n sql: string,\n end: number,\n governing: string | undefined,\n dialect: ClassifiedDialect\n): boolean {\n if (governing !== undefined && OBJECT_NAME_KEYWORDS.has(governing)) {\n return false;\n }\n let cursor = end;\n while (cursor < sql.length) {\n const char = sql.charAt(cursor);\n if (\n char === \"-\" &&\n sql[cursor + 1] === \"-\" &&\n opensLineComment(sql, cursor, dialect)\n ) {\n cursor = skipLine(sql, cursor);\n continue;\n }\n if (dialect === \"mysql\" && char === \"#\") {\n cursor = skipLine(sql, cursor);\n continue;\n }\n if (char === \"/\" && sql[cursor + 1] === \"*\") {\n cursor = skipBlockComment(sql, cursor, dialect);\n continue;\n }\n if (char.trim() !== \"\") {\n return char === \"(\";\n }\n cursor += 1;\n }\n return false;\n}\n\n/**\n * Whether the `--` at `start` opens a line comment.\n *\n * PostgreSQL's always does. MySQL's requires whitespace (or a control\n * character, or end of input) after the second dash, so\n * `SELECT 1--RELEASE_LOCK('viborm_migration_…')` is arithmetic over a REAL\n * function call there rather than a comment. Reading it as a comment hides\n * exactly the statement this classifier exists to refuse.\n */\nfunction opensLineComment(\n sql: string,\n start: number,\n dialect: ClassifiedDialect\n): boolean {\n if (dialect !== \"mysql\") {\n return true;\n }\n const after = sql[start + 2];\n if (after === undefined) {\n return true;\n }\n return after.trim() === \"\" || after.charCodeAt(0) < 0x20;\n}\n\n/** Past SQLite's square-bracket identifier quote. */\nfunction skipBracketQuoted(sql: string, start: number): number {\n const end = sql.indexOf(\"]\", start + 1);\n return end < 0 ? sql.length : end + 1;\n}\n\n/** Past a line comment, including its newline. */\nfunction skipLine(sql: string, start: number): number {\n const lineEnd = sql.indexOf(\"\\n\", start);\n return lineEnd < 0 ? sql.length : lineEnd + 1;\n}\n\n/**\n * Past the OPENING of a MySQL executable comment (`/*!`, optionally followed by\n * a server-version prefix), leaving its contents to be scanned as statements.\n *\n * MySQL RUNS what is inside these — that is what they are for — so skipping\n * them the way an ordinary comment is skipped admits\n * `/*!50000 DO RELEASE_LOCK('viborm_migration_…')`, which frees the lock the\n * running command holds, and `/*!40101 SET AUTOCOMMIT=0`, which reframes the\n * commit boundary of everything after it. The closing delimiter needs no arm of\n * its own: neither of its characters starts a word.\n */\nfunction openExecutableComment(sql: string, start: number): number {\n let cursor = start + 3;\n while (cursor < sql.length && VERSION_DIGIT.test(sql.charAt(cursor))) {\n cursor += 1;\n }\n return cursor;\n}\n\n/**\n * Past a block comment.\n *\n * PostgreSQL NESTS them, so an outer comment holding a complete inner one is\n * entirely a comment there; stopping at the first close would leave the outer\n * comment's tail scanned as SQL and refuse a valid artifact over a `COMMIT` no\n * server ever sees. MySQL does not nest, so its depth never rises and it stops\n * at the first close — which is also where the server stops.\n */\nfunction skipBlockComment(\n sql: string,\n start: number,\n dialect: ClassifiedDialect\n): number {\n let cursor = start + 2;\n let depth = 1;\n while (cursor < sql.length) {\n if (sql[cursor] === \"*\" && sql[cursor + 1] === \"/\") {\n depth -= 1;\n cursor += 2;\n if (depth === 0) {\n return cursor;\n }\n continue;\n }\n if (\n dialect === \"postgresql\" &&\n sql[cursor] === \"/\" &&\n sql[cursor + 1] === \"*\"\n ) {\n depth += 1;\n cursor += 2;\n continue;\n }\n cursor += 1;\n }\n return sql.length;\n}\n\n/**\n * Whether a backslash escapes the next character inside this quote.\n *\n * MySQL's default mode treats `\\` as an escape inside both string quotes, so\n * `'a\\'b'` is ONE literal there; its backtick identifiers take no escapes.\n * PostgreSQL's strings are standard-conforming, so a backslash is an ordinary\n * character in `'…'` and `\"…\"` — its one escape-bearing form, `E'…'`, is\n * recognised at the `E` in the scan above.\n */\nfunction escapesWithBackslash(\n dialect: ClassifiedDialect,\n quote: string\n): boolean {\n return dialect === \"mysql\" && quote !== \"`\";\n}\n\n/**\n * Past a quoted run, honoring the doubling escape every admitted dialect uses\n * (`''`, `\"\"`, ` `` `) and, where the dialect has them, backslash escapes. An\n * unterminated quote consumes the rest of the statement, which is what a\n * database would also do with it.\n */\nfunction skipQuoted(\n sql: string,\n start: number,\n quote: string,\n backslashEscapes: boolean\n): number {\n let cursor = start + 1;\n while (cursor < sql.length) {\n if (backslashEscapes && sql[cursor] === \"\\\\\") {\n cursor += 2;\n continue;\n }\n if (sql[cursor] !== quote) {\n cursor += 1;\n continue;\n }\n if (sql[cursor + 1] === quote) {\n cursor += 2;\n continue;\n }\n return cursor + 1;\n }\n return sql.length;\n}\n\n/**\n * Past a PostgreSQL dollar-quoted body (`$$…$$`, `$tag$…$tag$`), or null when\n * this `$` does not open one.\n *\n * Function bodies are the common shape of a hand-written PostgreSQL artifact,\n * and their contents are a string, not statements. Reading them as statements\n * would refuse a perfectly ordinary `CREATE FUNCTION` whose body happens to\n * contain `COMMIT` or `BEGIN`.\n */\nfunction skipDollarQuoted(sql: string, start: number): number | null {\n let cursor = start + 1;\n while (cursor < sql.length && DOLLAR_TAG_PART.test(sql.charAt(cursor))) {\n cursor += 1;\n }\n if (sql[cursor] !== \"$\") {\n return null;\n }\n const tag = sql.slice(start, cursor + 1);\n const bodyEnd = sql.indexOf(tag, cursor + 1);\n return bodyEnd < 0 ? sql.length : bodyEnd + tag.length;\n}\n\n/** The refusal a classified statement raises, naming its artifact and cause. */\nfunction refuse(\n artifact: string,\n statement: string,\n reason: string\n): MigrationError {\n return new MigrationError(\n `Migration \"${artifact}\" contains a statement VibORM cannot execute inside the boundary it publishes: ${reason}. ` +\n `The offending statement begins \"${statement.trim().slice(0, 80)}\". ` +\n \"Manual migration SQL owns its object effects; VibORM refuses only the direct controls over its rollback scope, its migration lock, and its tracking boundary, so write the migration without them.\",\n VibORMErrorCode.MIGRATION_INVALID_STATE,\n { meta: { migrationName: artifact } }\n );\n}\n\n/**\n * Refuses an artifact that DIRECTLY reframes the execution boundary.\n *\n * Runs BEFORE any of the artifact's effects, so a refusal leaves the estate\n * exactly as it was. SQLite has no advisory lock, but the migration runner\n * still owns its transaction and savepoint boundary.\n */\nexport function assertArtifactExecutionSafe(\n statements: readonly string[],\n dialect: MigrationTarget[\"dialect\"],\n artifact: string\n): void {\n for (const chunk of statements) {\n const scanned = scanStatements(chunk, dialect);\n if (dialect === \"sqlite\" && isSqliteTrigger(scanned[0])) {\n continue;\n }\n for (const words of scanned) {\n classifyOne(words, chunk, dialect, artifact);\n }\n }\n}\n\n/**\n * A SQLite trigger body uses `BEGIN … END` as grammar, not transaction control.\n * Stock SQLite execution accepts one prepared statement per dispatch, so the\n * whole trigger is the provider statement and its body controls stay inside it.\n */\nfunction isSqliteTrigger(first: readonly ScannedWord[] | undefined): boolean {\n if (first?.[0]?.text !== \"CREATE\") {\n return false;\n }\n const second = first[1]?.text;\n return (\n second === \"TRIGGER\" ||\n ((second === \"TEMP\" || second === \"TEMPORARY\") &&\n first[2]?.text === \"TRIGGER\")\n );\n}\n\n/**\n * The refusable leading phrase of one statement, or undefined.\n *\n * Two lookups, because an entry is one word or two and the longer one decides:\n * `COMMIT PREPARED 'g'` is refused for its `COMMIT`, `PREPARE TRANSACTION 'g'`\n * for the pair, and `PREPARE plan AS …` for neither. These are the statement's\n * EXECUTABLE words, so the pair is already case-folded and already free of\n * whatever whitespace or comment the author wrote between the two.\n */\nfunction leadingTransactionCommand(\n words: readonly ScannedWord[],\n leaders: ReadonlySet<string>\n): string | undefined {\n const first = words[0]?.text;\n const second = words[1]?.text;\n const pair = second === undefined ? undefined : `${first} ${second}`;\n if (pair !== undefined && leaders.has(pair)) {\n return pair;\n }\n return first !== undefined && leaders.has(first) ? first : undefined;\n}\n\n/** Classifies ONE statement's executable words. */\nfunction classifyOne(\n words: readonly ScannedWord[],\n statement: string,\n dialect: ClassifiedDialect,\n artifact: string\n): void {\n // `scanStatements` keeps only statements with at least one word.\n const leader = words[0]!.text;\n\n if (dialect === \"postgresql\") {\n const control = leadingTransactionCommand(\n words,\n POSTGRES_TRANSACTION_LEADERS\n );\n if (control !== undefined) {\n throw refuse(\n artifact,\n statement,\n `the transaction-control statement \"${control}\", which would end the transaction this migration runs inside`\n );\n }\n // One fold reaches both forms the scan retains: a bare word arrives\n // uppercased, and a called quoted identifier arrives in its own folded\n // spelling, which is the only spelling that names the built-in.\n const advisory = words.find(\n (word) =>\n word.calls &&\n POSTGRES_ADVISORY_PREFIXES.some((prefix) =>\n word.text.toUpperCase().startsWith(prefix)\n )\n );\n if (advisory !== undefined) {\n throw refuse(\n artifact,\n statement,\n `a call to \"${advisory.text.toLowerCase()}\", which would change the advisory-lock state this migration command holds`\n );\n }\n return;\n }\n\n if (dialect === \"sqlite\") {\n const control = leadingTransactionCommand(\n words,\n SQLITE_TRANSACTION_LEADERS\n );\n if (control !== undefined) {\n throw refuse(\n artifact,\n statement,\n `the transaction-control statement \"${control}\", which would change the transaction boundary this migration runs inside`\n );\n }\n return;\n }\n\n const control = leadingTransactionCommand(words, MYSQL_TRANSACTION_LEADERS);\n if (control !== undefined) {\n throw refuse(\n artifact,\n statement,\n `the transaction- or table-lock statement \"${control}\", which would change the boundary this migration runs inside`\n );\n }\n // `SET autocommit` reframes every following statement's commit boundary, and\n // it is a SET, not a leader of its own — hence the word test. The scan folds\n // `@@autocommit` to that same word and leaves `@autocommit` under its own\n // name, so the setting is reached under both its spellings and the user\n // variable under neither.\n if (leader === \"SET\" && words.some((word) => word.text === \"AUTOCOMMIT\")) {\n throw refuse(\n artifact,\n statement,\n \"a change to `autocommit`, which would change the commit boundary of every statement that follows\"\n );\n }\n const named = words.find(\n (word) => word.calls && MYSQL_LOCK_FUNCTIONS.has(word.text)\n );\n if (named !== undefined) {\n throw refuse(\n artifact,\n statement,\n `a call to \"${named.text.toLowerCase()}\", which would change the named-lock state this migration command holds`\n );\n }\n}\n\n/**\n * Whether a PostgreSQL migration edge must commit before the next one runs.\n *\n * `ALTER TYPE ... ADD VALUE` cannot be used by a later statement of the\n * transaction that added it (55P04), so apply, rollback and reset end their\n * shared transaction after such an edge. Reset creates the type in its own\n * transaction, but only PostgreSQL 17 and later exempt such a type's values.\n *\n * The question is PostgreSQL's alone — no other dialect has the statement — so\n * the scan reads PostgreSQL's lexical grammar rather than taking a dialect its\n * callers would each have to answer for.\n */\nexport function needsEnumAdditionCommitBoundary(\n statements: readonly string[]\n): boolean {\n for (const chunk of statements) {\n for (const words of readExecutableStatements(chunk, \"postgresql\")) {\n if (\n words[0] === \"ALTER\" &&\n words[1] === \"TYPE\" &&\n words.includes(\"ADD\") &&\n words.includes(\"VALUE\")\n ) {\n return true;\n }\n }\n }\n return false;\n}\n\n/** A PostgreSQL statement that changes the schema. */\nconst SCHEMA_CHANGES = new Set([\"ALTER\", \"COMMENT\", \"CREATE\", \"DROP\"]);\n/**\n * Statements that are neither schema changes nor planned against the\n * committed schema on Neki: each ran there as on PostgreSQL after any schema\n * change of its own transaction (measured: see {@link catalogCommitBoundaries}).\n */\nconst UNPLANNED = new Set([\"GRANT\", \"SET\", \"TRUNCATE\"]);\n/** A block, a procedure or a prepared statement: what it changes is not in its text. */\nconst OPAQUE = new Set([\"CALL\", \"DO\", \"EXECUTE\"]);\n\nconst NAME_START = /[A-Za-z_]/;\nconst NAME_PART = /[A-Za-z0-9_$]/;\nconst NAME_UNSAFE = /[^A-Za-z0-9_$]/g;\nconst LEADING_WORDS = /^([A-Za-z_]+)(?:\\s+([A-Za-z_]+))?/;\nconst NAME = String.raw`(?:\"[^\"]*\"|[A-Za-z_][\\w$]*)`;\nconst QUALIFIED = String.raw`${NAME}(?:\\s*\\.\\s*${NAME}){0,2}`;\n/** A parenthesized run, three levels deep; the structural text has no literal. */\nconst GROUP = String.raw`\\((?:[^()]|\\((?:[^()]|\\([^()]*\\))*\\))*\\)`;\nconst LAST_NAME = new RegExp(`${NAME}$`);\nconst ALTER_TABLE = new RegExp(\n String.raw`^ALTER\\s+TABLE\\s+(?:IF\\s+EXISTS\\s+)?(?:ONLY\\s+)?(${QUALIFIED})\\s*\\*?\\s*([\\s\\S]*)$`,\n \"i\"\n);\nconst TABLE_PREFIX = String.raw`^CREATE\\s+(?:(?:GLOBAL|LOCAL|TEMP|TEMPORARY|UNLOGGED)\\s+)*`;\nconst CREATE_TABLE = new RegExp(\n String.raw`${TABLE_PREFIX}TABLE\\s+(?:IF\\s+NOT\\s+EXISTS\\s+)?(${QUALIFIED})`,\n \"i\"\n);\n/** `CREATE TABLE … AS` and `CREATE MATERIALIZED VIEW … AS` plan a query. */\nconst CREATE_AS = new RegExp(\n String.raw`${TABLE_PREFIX}(?:TABLE|MATERIALIZED\\s+VIEW)\\b[\\s\\S]*\\bAS\\s+(?:SELECT|WITH|TABLE|VALUES|EXECUTE)\\b`,\n \"i\"\n);\nconst RENAME_TO = new RegExp(String.raw`^RENAME\\s+TO\\s+(${NAME})\\s*$`, \"i\");\n/**\n * The unregistered-relation refusal's actions (NK316): a type change, a\n * column rename, a column drop, a move to another schema.\n */\nconst UNREGISTERED_ACTION = new RegExp(\n String.raw`(?:^|,)\\s*(?:ALTER\\s+(?:COLUMN\\s+)?${NAME}\\s+(?:SET\\s+DATA\\s+)?TYPE\\b|RENAME\\s+(?:COLUMN\\s+)?(?!(?:TO|CONSTRAINT)\\b)${NAME}\\s+TO\\b|DROP\\s+(?:COLUMN\\s+)?(?!(?:CONSTRAINT|DEFAULT|NOT|IDENTITY|EXPRESSION)\\b)(?:IF\\s+EXISTS\\s+)?${NAME}|SET\\s+SCHEMA\\b)`,\n \"i\"\n);\n/**\n * The `ALTER TABLE` actions Neki's planner needs no commit for: what they\n * change is enforced where the row is written, never resolved where the\n * statement is planned (defaults, NOT NULL, CHECK and foreign keys, a\n * validated constraint). A relation created or dropped, an index or a\n * constraint's own included, is not one: a literal naming it resolves\n * against the committed schema (`to_regclass`, `::regclass`, measured stale).\n */\nconst SEEN_ACTION = String.raw`(?:ALTER\\s+(?:COLUMN\\s+)?${NAME}\\s+(?:SET\\s+DEFAULT\\s+(?:[^,()]|${GROUP})+|DROP\\s+DEFAULT|(?:SET|DROP)\\s+NOT\\s+NULL)|ADD\\s+(?:CONSTRAINT\\s+${NAME}\\s+)?(?:CHECK\\s*${GROUP}|FOREIGN\\s+KEY\\s*${GROUP}\\s*REFERENCES\\s+${QUALIFIED}(?:\\s*${GROUP})?)(?:\\s+[A-Za-z]+|\\s*${GROUP})*|VALIDATE\\s+CONSTRAINT\\s+${NAME})`;\nconst SEEN_ALTERATION = new RegExp(\n String.raw`^${SEEN_ACTION}(?:\\s*,\\s*${SEEN_ACTION})*\\s*$`,\n \"i\"\n);\nconst SEEN_STATEMENT = /^COMMENT\\b/i;\n\n/**\n * The PostgreSQL statements of `sql` as their structure alone: comments\n * dropped, every literal, dollar-quoted body and `BEGIN ATOMIC … END` body\n * emptied (`''`), and every quoted identifier spelled with characters that\n * open or close nothing, so a pattern over what is left reads clauses, never\n * data. Its only readers are {@link catalogCommitBoundaries}' patterns.\n */\nfunction structuralStatements(sql: string): string[] {\n const statements: string[] = [];\n let text = \"\";\n let index = 0;\n let previous = \"\";\n // The CASE … END depth inside an open `BEGIN ATOMIC` body, whose `;` end\n // its own statements, not this one.\n let body = 0;\n const emit = (part: string) => {\n if (body === 0) text += part;\n };\n const end = () => {\n if (text.trim() !== \"\") statements.push(text.trim());\n text = \"\";\n };\n while (index < sql.length) {\n const char = sql.charAt(index);\n const next = sql.charAt(index + 1);\n if (char === \"-\" && next === \"-\") {\n index = skipLine(sql, index);\n emit(\" \");\n } else if (char === \"/\" && next === \"*\") {\n index = skipBlockComment(sql, index, \"postgresql\");\n emit(\" \");\n } else if (char === \"'\") {\n index = skipQuoted(sql, index, \"'\", false);\n emit(\"''\");\n } else if (char === '\"') {\n const close = skipQuoted(sql, index, '\"', false);\n const name = sql.slice(index + 1, close - 1).replaceAll('\"\"', '\"');\n emit(\n `\"${name.replace(NAME_UNSAFE, (unsafe) => `_${unsafe.charCodeAt(0).toString(16)}_`)}\"`\n );\n index = close;\n } else if (char === \"$\" && skipDollarQuoted(sql, index) !== null) {\n index = skipDollarQuoted(sql, index)!;\n emit(\"''\");\n } else if (char === \";\") {\n if (body === 0) end();\n index += 1;\n } else if (NAME_START.test(char)) {\n const start = index;\n index += 1;\n while (index < sql.length && NAME_PART.test(sql.charAt(index))) {\n index += 1;\n }\n const word = sql.slice(start, index);\n const upper = word.toUpperCase();\n // `E'…'`, the one PostgreSQL string a backslash escapes in.\n if (upper === \"E\" && sql[index] === \"'\") {\n index = skipQuoted(sql, index, \"'\", true);\n emit(\"''\");\n } else if (body > 0) {\n if (upper === \"CASE\") body += 1;\n if (upper === \"END\") body -= 1;\n if (body === 0) text += \"'' END\";\n } else {\n text += word;\n if (upper === \"ATOMIC\" && previous === \"BEGIN\") body = 1;\n }\n previous = upper;\n } else {\n emit(char);\n index += 1;\n }\n }\n end();\n return statements;\n}\n\n/** A relation as {@link structuralStatements} spells it, schema dropped: quoted as written, bare folded. */\nfunction relationName(qualified: string): string {\n const last = LAST_NAME.exec(qualified)?.[0] ?? qualified;\n return last.startsWith('\"') ? last.slice(1, -1) : last.toLowerCase();\n}\n\n/** One statement of a program: its position there and its leading words. */\nexport interface CatalogStatement {\n readonly position: number;\n readonly words: string;\n}\n\n/** What one Neki transaction changed since it began that a later statement may not see. */\nexport interface CatalogChanges {\n /** Its first change Neki plans later row statements without. */\n readonly unseen?: CatalogStatement;\n /** The relations it created or renamed, by name: Neki has not registered them (NK316). */\n readonly unregistered: ReadonlyMap<string, CatalogStatement>;\n}\n\n/** A statement that needs `change` committed before it runs on Neki. */\nexport interface CatalogHazard {\n /**\n * `rows`: a statement planned against the committed schema after a change\n * its planner does not see (`42P01`, `42703`, `42704`, `42883`, `22P02`, or\n * a silently stale `*` or column type); `columns`: a column type change,\n * rename or drop of a relation created or renamed in the same transaction\n * (`NK316`).\n */\n readonly kind: \"rows\" | \"columns\";\n readonly change: CatalogStatement;\n readonly statement: CatalogStatement;\n}\n\nexport const UNCHANGED_CATALOG: CatalogChanges = { unregistered: new Map() };\n\n/** One program entry read against `since`: its first hazard, and the changes after it. */\nfunction readCatalogChunk(\n chunk: string,\n position: number,\n since: CatalogChanges\n): { readonly hazard?: CatalogHazard; readonly changes: CatalogChanges } {\n let { unseen } = since;\n const unregistered = new Map(since.unregistered);\n let hazard: CatalogHazard | undefined;\n for (const text of structuralStatements(chunk)) {\n const [, first = \"\", second] = LEADING_WORDS.exec(text) ?? [];\n const leader = first.toUpperCase();\n const site = {\n position,\n words: [leader, second?.toUpperCase()].filter(Boolean).join(\" \"),\n };\n const schema = SCHEMA_CHANGES.has(leader);\n const plans = !(schema || UNPLANNED.has(leader)) || CREATE_AS.test(text);\n const table = leader === \"ALTER\" ? ALTER_TABLE.exec(text) : null;\n const created = table ? undefined : CREATE_TABLE.exec(text)?.[1];\n const relation = table ? relationName(table[1]!) : undefined;\n const clause = table?.[2] ?? \"\";\n const registering = relation && unregistered.get(relation);\n if (hazard === undefined && plans && unseen) {\n hazard = {\n kind: \"rows\",\n change: unseen,\n statement: { position, words: leader },\n };\n } else if (\n hazard === undefined &&\n registering &&\n UNREGISTERED_ACTION.test(clause)\n ) {\n hazard = { kind: \"columns\", change: registering, statement: site };\n }\n const seen =\n SEEN_STATEMENT.test(text) ||\n (table !== null && SEEN_ALTERATION.test(clause));\n if (unseen === undefined && (schema ? !seen : OPAQUE.has(leader))) {\n unseen = site;\n }\n const renamed = RENAME_TO.exec(clause)?.[1];\n if (created) unregistered.set(relationName(created), site);\n if (renamed) unregistered.set(relationName(renamed), site);\n }\n return { hazard, changes: { unseen, unregistered } };\n}\n\n/**\n * Where PlanetScale's Neki needs a commit inside a PostgreSQL transaction\n * that runs `chunks` in order, its changes since its last commit `since`.\n *\n * Neki's router plans a statement against the schema committed before its\n * transaction, and only the server it routes to sees the transaction's own\n * changes. Measured on Neki's PostgreSQL 18.6 (2026-10-13), and held by\n * `tests/providers/hosted/neki-migrations.test.ts` and the simulation in\n * `tests/unit/migrations/postgres-neki-apply.test.ts`: a statement that\n * resolves a name, a `*`, a column's type, an enum label or an ON CONFLICT\n * target the transaction changed fails there, or reads the old schema without\n * an error; a schema statement sees the transaction, except that a relation it\n * created or renamed has no column it can retype, rename or drop, and cannot\n * move to another schema (`NK316`). Defaults, NOT NULL, CHECK and foreign\n * keys, validated constraints and comments change nothing a statement is\n * planned by. A routine, a view's body or a literal (`nextval('…')`,\n * `to_regclass('…')`, stale for a created or dropped table, index or\n * constraint) can reach any relation, so a row statement after any other\n * schema change needs the commit, whichever relation it names; a `DO` block,\n * a `CALL` or an `EXECUTE` may change the schema itself (what it creates is\n * not read for `NK316`).\n *\n * `boundaries` are the entries a commit must precede, each counted with the\n * changes since the previous one; `first` is the first hazard as `since`\n * leaves it; `inside` is the first entry whose own statements need a commit\n * between them, where none can be placed; `changes` are what the last\n * boundary leaves for whatever follows.\n */\nexport function catalogCommitBoundaries(\n chunks: readonly string[],\n since: CatalogChanges = UNCHANGED_CATALOG\n): {\n readonly boundaries: readonly number[];\n readonly first?: CatalogHazard;\n readonly inside?: CatalogHazard;\n readonly changes: CatalogChanges;\n} {\n let changes = since;\n const boundaries: number[] = [];\n let first: CatalogHazard | undefined;\n let inside: CatalogHazard | undefined;\n for (const [position, chunk] of chunks.entries()) {\n let read = readCatalogChunk(chunk, position, changes);\n if (read.hazard) {\n first ??= read.hazard;\n read = readCatalogChunk(chunk, position, UNCHANGED_CATALOG);\n inside ??= read.hazard;\n boundaries.push(position);\n }\n changes = read.changes;\n }\n return { boundaries, first, inside, changes };\n}\n\n/**\n * Whether `sql` holds a PostgreSQL statement run `CONCURRENTLY` that refuses\n * a transaction block: `CREATE [UNIQUE] INDEX CONCURRENTLY`, `DROP INDEX\n * CONCURRENTLY`, a `REINDEX … CONCURRENTLY` or `ALTER TABLE … DETACH\n * PARTITION … CONCURRENTLY`. Only these wait, by design, for every older\n * transaction without blocking anyone (plan S1). Read from each statement's\n * executable words, so the words in a comment or a literal are not one, and\n * neither is `REFRESH MATERIALIZED VIEW CONCURRENTLY`.\n */\nexport function runsConcurrently(sql: string): boolean {\n return readExecutableStatements(sql, \"postgresql\").some((words) => {\n const [verb] = words;\n if (verb === \"REINDEX\") return words.includes(\"CONCURRENTLY\");\n if (verb === \"ALTER\") {\n return [\"DETACH\", \"PARTITION\", \"CONCURRENTLY\"].every((word) =>\n words.includes(word)\n );\n }\n const index = verb === \"CREATE\" && words[1] === \"UNIQUE\" ? 2 : 1;\n return (\n (verb === \"CREATE\" || verb === \"DROP\") &&\n words[index] === \"INDEX\" &&\n words[index + 1] === \"CONCURRENTLY\"\n );\n });\n}\n","import { isDestructiveOperation } from \"./differ\";\n/**\n * One compiler: DiffOperation and manual Sql become structured operations\n * that share one SQL blob. No delimiter split.\n */\n\nimport type { Sql } from \"@sql\";\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\nimport { canonicalDecimalText } from \"../validation/primitives/decimal-value\";\nimport { decodeCanonicalBase64, encodeBase64 } from \"./base64\";\nimport {\n type CatalogProbe,\n probeForGeneratedStatement,\n} from \"./catalog-probes\";\nimport type { DDLContext, MigrationDriver } from \"./drivers\";\nimport { invertOperations } from \"./invert\";\nimport type { SqlAssembly } from \"./sql-assembly\";\nimport { sliceDispatch } from \"./sql-blob\";\nimport {\n needsEnumAdditionCommitBoundary,\n runsConcurrently,\n} from \"./statement-safety\";\nimport type { DiffOperation, SchemaSnapshot } from \"./types\";\nimport { encodeTransitionHash } from \"./v1-parse\";\nimport type {\n AtomicityClass,\n MigrationApprovalV1,\n MigrationBooleanCheckV1,\n MigrationCheckInput,\n MigrationDispatchV1,\n MigrationOperationV1,\n MigrationParameterV1,\n MigrationParentTransitionV1,\n MigrationRollbackV1,\n MigrationStepV1,\n} from \"./v1-types\";\n\nexport interface CompiledTransition {\n readonly operations: readonly MigrationOperationV1[];\n readonly rollback: MigrationRollbackV1;\n readonly originChecks: readonly MigrationBooleanCheckV1[];\n readonly requestedForwardBoundary: \"transactional\" | \"stepwise\" | null;\n readonly atomicity: AtomicityClass;\n readonly warnings?: readonly string[];\n}\n\n/** The SQL each step of `operations` executes, in order. */\nexport function stepStatements(\n blob: Uint8Array,\n operations: readonly MigrationOperationV1[]\n): string[] {\n return operations.flatMap((operation) =>\n operation.steps.map((step) => sliceDispatch(blob, step.execute))\n );\n}\n\nconst VALIDATE_CONSTRAINT = /\\bVALIDATE\\s+CONSTRAINT\\b/i;\n\n/**\n * Contiguous edges of one boundary share a commit, except that an edge adding\n * a PostgreSQL enum value ends its group: a later edge may use that value,\n * which PostgreSQL refuses until the addition commits (55P04). An edge that\n * validates a constraint commits alone (T5b): sharing a transaction with the\n * edge that added it `NOT VALID` would hold that addition's lock through the\n * scan the split exists to free.\n */\nexport function groupContiguousAtomicity<\n T extends { readonly boundary: string },\n>(\n items: readonly T[],\n statementsOf: (item: T) => readonly string[]\n): readonly {\n readonly boundary: T[\"boundary\"];\n readonly items: readonly T[];\n}[] {\n const groups: {\n boundary: T[\"boundary\"];\n items: T[];\n }[] = [];\n let mustCommit = false;\n for (const item of items) {\n const statements = statementsOf(item);\n const alone = statements.some((text) => VALIDATE_CONSTRAINT.test(text));\n const current = groups.at(-1);\n if (current?.boundary === item.boundary && !(mustCommit || alone)) {\n current.items.push(item);\n } else {\n groups.push({ boundary: item.boundary, items: [item] });\n }\n mustCommit = alone || needsEnumAdditionCommitBoundary(statements);\n }\n return groups;\n}\n\n/**\n * The context a generated statement compiles in. `lowLock` asks PostgreSQL\n * for the form of a step that blocks no write while it reads the table (T5b):\n * `\"add\"` builds an index `CONCURRENTLY` or adds a foreign key `NOT VALID`,\n * `\"validate\"` validates that key. Only `generate({ lowLock: true })` sets\n * it, and only on a table that existed before the migration.\n */\nexport type LowLockContext = DDLContext & {\n readonly lowLock?: \"add\" | \"validate\";\n};\n\n/** One state of a generated program split at its low-lock steps. */\nexport interface LowLockState {\n readonly operations: readonly DiffOperation[];\n /** The schema the state reaches. */\n readonly snapshot: SchemaSnapshot;\n /** Whether it validates the keys an earlier state added `NOT VALID`. */\n readonly validates: boolean;\n}\n\n/**\n * Splits a generated PostgreSQL program into the states that give each\n * low-lock step its own commit (T5b), or returns `undefined` when it has none\n * to give. A step is an index built on, or a foreign key added to, a table\n * the program does not create (a table it creates is empty). Each index build\n * is a state of its own: `CREATE INDEX CONCURRENTLY` runs outside any\n * transaction, and an interrupted build is then one unfinished single-step\n * attempt that `resolve` repairs either way. The keys are added `NOT VALID`\n * with the last state, and a final state validates them in a commit of its\n * own; a failed validation rolls back alone and `apply` resumes from the\n * marker.\n *\n * The schemas between states are the target's with the later states' effects\n * undone, so only an index build, an index drop or a key may follow the first\n * build; otherwise, or when a dropped index cannot be read back from the\n * origin, the program is not split and keeps its blocking forms.\n */\nexport function lowLockStates(\n operations: readonly DiffOperation[],\n current: SchemaSnapshot,\n desired: SchemaSnapshot\n): { states: LowLockState[]; steps: ReadonlySet<DiffOperation> } | undefined {\n const steps = lowLockSteps(operations);\n if (steps.size === 0) return;\n const first = operations.findIndex(\n (op) => op.type === \"createIndex\" && steps.has(op)\n );\n const tail = first < 0 ? [] : operations.slice(first);\n const renames = operations.some(\n (op) => op.type === \"renameTable\" || op.type === \"renameColumn\"\n );\n if (\n !tail.every((op) =>\n op.type === \"createIndex\"\n ? steps.has(op)\n : op.type === \"addForeignKey\" || (op.type === \"dropIndex\" && !renames)\n )\n ) {\n return;\n }\n const ends: number[] = [];\n for (const [index, op] of operations.entries()) {\n if (op.type === \"createIndex\" && steps.has(op)) {\n if (index > (ends.at(-1) ?? 0)) ends.push(index);\n ends.push(index + 1);\n }\n }\n if (ends.at(-1) !== operations.length) ends.push(operations.length);\n const states: LowLockState[] = [];\n for (const [index, end] of ends.entries()) {\n const snapshot = withoutEffects(desired, current, operations.slice(end));\n if (!snapshot) return;\n states.push({\n operations: operations.slice(ends[index - 1] ?? 0, end),\n snapshot,\n validates: false,\n });\n }\n const keys = operations.filter(\n (op) => op.type === \"addForeignKey\" && steps.has(op)\n );\n if (keys.length > 0) {\n states.push({ operations: keys, snapshot: desired, validates: true });\n }\n return { states, steps };\n}\n\n/** The index builds and keys of `operations` on tables it does not create. */\nexport function lowLockSteps(\n operations: readonly DiffOperation[]\n): ReadonlySet<DiffOperation> {\n const created = new Set(\n operations.flatMap((op) => (op.type === \"createTable\" ? op.table.name : []))\n );\n return new Set(\n operations.filter(\n (op) =>\n (op.type === \"createIndex\" || op.type === \"addForeignKey\") &&\n !created.has(op.tableName)\n )\n );\n}\n\n/** `desired` before `later`: an index build, an index drop or a key. */\nfunction withoutEffects(\n desired: SchemaSnapshot,\n current: SchemaSnapshot,\n later: readonly DiffOperation[]\n): SchemaSnapshot | undefined {\n let readable = later.every(\n (op) =>\n \"tableName\" in op &&\n desired.tables.some((table) => table.name === op.tableName)\n );\n const tables = desired.tables.map((table) => {\n const own = later.filter(\n (op) => \"tableName\" in op && op.tableName === table.name\n );\n if (own.length === 0) return table;\n const built = new Set(\n own.flatMap((op) => (op.type === \"createIndex\" ? op.index.name : []))\n );\n const keys = new Set(\n own.flatMap((op) => (op.type === \"addForeignKey\" ? op.fk.name : []))\n );\n const restored = own.flatMap((op) => {\n if (op.type !== \"dropIndex\") return [];\n const index = current.tables\n .find((origin) => origin.name === table.name)\n ?.indexes.find((item) => item.name === op.indexName);\n if (!index) readable = false;\n return index ?? [];\n });\n return {\n ...table,\n indexes: [\n ...table.indexes.filter((index) => !built.has(index.name)),\n ...restored,\n ],\n foreignKeys: table.foreignKeys.filter((key) => !keys.has(key.name)),\n };\n });\n return readable ? { ...desired, tables } : undefined;\n}\n\nexport function compileGeneratedTransition(\n operations: readonly DiffOperation[],\n driver: MigrationDriver,\n destination: DDLContext[\"destination\"],\n currentSchema: SchemaSnapshot,\n desiredSchema: SchemaSnapshot,\n assembly: SqlAssembly,\n lowLock: ReadonlySet<DiffOperation> = new Set()\n): CompiledTransition {\n const compiled = operations\n .map((operation, index) =>\n compileGeneratedOperation(\n operation,\n driver,\n destination,\n currentSchema,\n operations,\n index,\n assembly,\n lowLock.has(operation) ? \"add\" : undefined\n )\n )\n .filter((operation) => operation.steps.length > 0);\n const inverse = invertOperations(\n [...operations],\n currentSchema,\n driver.projectNativeRename.bind(driver),\n driver.generatedPrimaryKeyName.bind(driver)\n );\n const missingBackfill = inverse.operations.find(\n (operation) =>\n operation.type === \"addColumn\" &&\n !operation.column.nullable &&\n operation.column.default === undefined\n );\n const irreversibleReason =\n missingBackfill && missingBackfill.type === \"addColumn\"\n ? `Rollback cannot restore required column \"${missingBackfill.tableName}.${missingBackfill.column.name}\" without its lost data or an explicit backfill. Author a manual rollback.`\n : inverse.operations\n .map((operation) => driver.getIrreversibleRollbackReason(operation))\n .find((reason) => reason !== undefined);\n const rollback: MigrationRollbackV1 =\n inverse.operations.length === 0 && operations.length === 0\n ? { kind: \"schema\", operations: [] }\n : irreversibleReason !== undefined\n ? { kind: \"irreversible\", reason: irreversibleReason }\n : inverse.operations.length === 0\n ? {\n kind: \"irreversible\",\n reason:\n inverse.warnings[0] ??\n \"Generated operations have no automatic inverse\",\n }\n : {\n kind: \"schema\",\n operations: inverse.operations\n .map((operation, index) =>\n compileGeneratedOperation(\n operation,\n driver,\n destination,\n desiredSchema,\n inverse.operations,\n index,\n assembly\n )\n )\n .filter((operation) => operation.steps.length > 0),\n };\n return {\n operations: compiled,\n rollback,\n warnings: inverse.warnings,\n originChecks: [],\n requestedForwardBoundary: null,\n atomicity: classifyGeneratedAtomicity(driver, operations),\n };\n}\n\n/**\n * The state that validates the foreign keys an earlier state added `NOT VALID`\n * (T5b). Undoing it is nothing: the keys stay, as their state declares them.\n */\nexport function compileValidationTransition(\n keys: readonly DiffOperation[],\n driver: MigrationDriver,\n currentSchema: SchemaSnapshot,\n assembly: SqlAssembly\n): CompiledTransition {\n return {\n operations: keys.map((key, index) =>\n compileGeneratedOperation(\n key,\n driver,\n \"artifact\",\n currentSchema,\n keys,\n index,\n assembly,\n \"validate\"\n )\n ),\n rollback: { kind: \"schema\", operations: [] },\n originChecks: [],\n requestedForwardBoundary: null,\n atomicity: \"transactional\",\n };\n}\n\nfunction compileGeneratedOperation(\n operation: DiffOperation,\n driver: MigrationDriver,\n destination: DDLContext[\"destination\"],\n currentSchema: SchemaSnapshot,\n batch: readonly DiffOperation[],\n index: number,\n assembly: SqlAssembly,\n lowLock?: LowLockContext[\"lowLock\"]\n): MigrationOperationV1 {\n const context: LowLockContext = {\n destination,\n currentSchema,\n precedingOperations: batch.slice(0, index),\n followingOperations: batch.slice(index + 1),\n ...(lowLock === undefined ? {} : { lowLock }),\n };\n const statements = driver.compileStatements(operation, context);\n const steps: MigrationStepV1[] = statements.map((statement) => {\n const probes = probeForGeneratedStatement(driver, operation, statement);\n const execute = addDispatch(assembly, statement, []);\n if (!probes) {\n return { retry: \"opaque\", execute };\n }\n return {\n retry: \"proven\",\n precheck: checkFromProbe(assembly, probes.pre),\n execute,\n postcheck: checkFromProbe(assembly, probes.post),\n };\n });\n return {\n id: `${operation.type}:${index}`,\n label:\n \"tableName\" in operation\n ? `${operation.type} ${operation.tableName}${\"columnName\" in operation ? `.${operation.columnName}` : \"column\" in operation ? `.${operation.column.name}` : \"\"}`\n : operation.type,\n origin: \"generated\",\n risk: isDestructiveOperation(operation) ? \"destructive\" : \"safe\",\n steps,\n };\n}\n\nexport function compileManualTransition(\n up: readonly Sql[],\n rollback:\n | {\n readonly kind: \"manual\";\n readonly execution: AtomicityClass;\n readonly sql: readonly Sql[];\n }\n | { readonly kind: \"irreversible\"; readonly reason: string },\n dialect: \"postgresql\" | \"mysql\" | \"sqlite\",\n requested: AtomicityClass,\n originChecks: readonly MigrationCheckInput[] | undefined,\n assembly: SqlAssembly\n): CompiledTransition {\n const operations = compileManualOperations(\n up,\n dialect,\n assembly,\n \"forward\",\n requested\n );\n if (rollback.kind === \"irreversible\" && rollback.reason.trim().length === 0) {\n throw new MigrationError(\n \"Irreversible rollback requires a non-empty reason\",\n VibORMErrorCode.MIGRATION_INVALID_ESTATE\n );\n }\n const compiledRollback: MigrationRollbackV1 =\n rollback.kind === \"irreversible\"\n ? rollback\n : {\n kind: \"manual\",\n requestedBoundary: rollback.execution,\n operations: compileManualOperations(\n rollback.sql,\n dialect,\n assembly,\n \"rollback\",\n rollback.execution\n ),\n };\n return {\n operations,\n rollback: compiledRollback,\n originChecks: (originChecks ?? []).map((check, index) =>\n compileTrustedCheck(check, dialect, assembly, `origin:${index}`)\n ),\n requestedForwardBoundary: requested,\n atomicity: requested,\n };\n}\n\nexport function assertManualStepwiseProof(\n compiled: CompiledTransition,\n destinationChecks: readonly MigrationBooleanCheckV1[]\n): void {\n const forwardStepwise = compiled.requestedForwardBoundary === \"stepwise\";\n const rollbackStepwise =\n compiled.rollback.kind === \"manual\" &&\n compiled.rollback.requestedBoundary === \"stepwise\";\n if (!(forwardStepwise || rollbackStepwise)) return;\n if (compiled.originChecks.length === 0 || destinationChecks.length === 0) {\n throw new MigrationError(\n \"Stepwise data-only manual work without complete origin and destination checks is refused before dispatch\",\n VibORMErrorCode.MIGRATION_INVALID_ESTATE\n );\n }\n}\n\nfunction compileManualOperations(\n fragments: readonly Sql[],\n dialect: \"postgresql\" | \"mysql\" | \"sqlite\",\n assembly: SqlAssembly,\n prefix: string,\n execution: AtomicityClass\n): MigrationOperationV1[] {\n if (fragments.length === 0) {\n throw new MigrationError(\n `Manual ${prefix} program must contain at least one SQL dispatch`,\n VibORMErrorCode.MIGRATION_INVALID_ESTATE\n );\n }\n // Plan S5, refused before the state is published: apply refuses it, so no\n // SQLite database could ever reach the state.\n if (execution === \"stepwise\" && dialect === \"sqlite\") {\n throw new MigrationError(\n `SQLite runs no stepwise manual ${prefix} program: only a transaction holds the write lock under which a migration runs exactly once, and every SQLite statement can run in one. Declare execution: \"transactional\" for it.`,\n VibORMErrorCode.MIGRATION_UNSUPPORTED_PROVIDER,\n { meta: { dialect, feature: \"stepwise execution\" } }\n );\n }\n return fragments.map((fragment, index) => {\n const text = fragment.toStatement(dialect === \"postgresql\" ? \"$n\" : \"?\");\n if (text.trim().length === 0) {\n throw new MigrationError(\n `Manual ${prefix} SQL dispatch ${index} must contain non-whitespace text`,\n VibORMErrorCode.MIGRATION_INVALID_ESTATE\n );\n }\n // Refused before the state is published: sent after BEGIN, PostgreSQL\n // rejects it (25001), so the transition could never apply.\n if (\n execution === \"transactional\" &&\n dialect === \"postgresql\" &&\n runsConcurrently(text)\n ) {\n throw new MigrationError(\n `Manual ${prefix} SQL dispatch ${index} runs CONCURRENTLY, which PostgreSQL refuses inside a transaction. Declare execution: \"stepwise\" for it.`,\n VibORMErrorCode.MIGRATION_INVALID_ESTATE\n );\n }\n const parameters = fragment.values.map((value) => encodeParameter(value));\n return {\n id: `manual:${prefix}:${index}`,\n label: \"manual\",\n origin: \"manual\" as const,\n risk: \"opaque\" as const,\n steps: [\n {\n retry: \"opaque\" as const,\n execute: addDispatch(assembly, text, parameters),\n },\n ],\n };\n });\n}\n\nexport function compileTrustedCheck(\n input: MigrationCheckInput,\n dialect: \"postgresql\" | \"mysql\" | \"sqlite\",\n assembly: SqlAssembly,\n id: string\n): MigrationBooleanCheckV1 & { readonly kind: \"trusted-read\" } {\n const text = input.query.toStatement(dialect === \"postgresql\" ? \"$n\" : \"?\");\n const parameters = input.query.values.map((value) => encodeParameter(value));\n return {\n kind: \"trusted-read\" as const,\n id,\n query: addDispatch(assembly, text, parameters),\n equals: input.equals,\n };\n}\n\nexport function sealParent(\n fromState: string | null,\n compiled: CompiledTransition,\n approvals: readonly MigrationApprovalV1[] = []\n): Omit<MigrationParentTransitionV1, \"transitionHash\"> {\n const parent = {\n fromState,\n originChecks: compiled.originChecks,\n requestedForwardBoundary: compiled.requestedForwardBoundary,\n operations: compiled.operations,\n rollback: compiled.rollback,\n };\n return approvals.length === 0 ? parent : { ...parent, approvals };\n}\n\nexport function hashParent(\n parent: Omit<MigrationParentTransitionV1, \"transitionHash\">\n): MigrationParentTransitionV1 {\n return { ...parent, transitionHash: encodeTransitionHash(parent) };\n}\n\nfunction addDispatch(\n assembly: SqlAssembly,\n text: string,\n parameters: readonly MigrationParameterV1[]\n): MigrationDispatchV1 {\n const index = assembly.add(text, parameters);\n return {\n dispatchId: \"0\".repeat(64),\n sqlHash: \"0\".repeat(64),\n offset: index,\n length: 0,\n parameters,\n };\n}\n\nfunction checkFromProbe(\n assembly: SqlAssembly,\n probe: CatalogProbe\n): MigrationBooleanCheckV1 {\n return {\n kind: \"driver\",\n id: probe.id,\n query: addDispatch(assembly, probe.sql, probe.parameters),\n equals: probe.equals,\n };\n}\n\nexport function rebindDispatches(\n operations: readonly MigrationOperationV1[],\n dispatches: readonly MigrationDispatchV1[]\n): MigrationOperationV1[] {\n return operations.map((operation) => ({\n ...operation,\n steps: operation.steps.map((step) => rebindStep(step, dispatches)),\n }));\n}\n\nfunction rebindStep(\n step: MigrationStepV1,\n dispatches: readonly MigrationDispatchV1[]\n): MigrationStepV1 {\n const execute = dispatchAt(dispatches, step.execute.offset);\n if (step.retry === \"opaque\") {\n return { retry: \"opaque\", execute };\n }\n return {\n retry: \"proven\",\n precheck: {\n ...step.precheck,\n query: dispatchAt(dispatches, step.precheck.query.offset),\n },\n execute,\n postcheck: {\n ...step.postcheck,\n query: dispatchAt(dispatches, step.postcheck.query.offset),\n },\n };\n}\n\n/** The sealed dispatch at an index the same assembly handed out. */\nexport function dispatchAt(\n dispatches: readonly MigrationDispatchV1[],\n index: number\n): MigrationDispatchV1 {\n const found = dispatches[index];\n if (!found) {\n throw new MigrationError(\n \"Compiled dispatch is missing from the SQL assembly\",\n VibORMErrorCode.INTERNAL_ERROR\n );\n }\n return found;\n}\n\nexport function rebindChecks(\n checks: readonly MigrationBooleanCheckV1[],\n dispatches: readonly MigrationDispatchV1[]\n): MigrationBooleanCheckV1[] {\n return checks.map((check) => ({\n ...check,\n query: dispatchAt(dispatches, check.query.offset),\n }));\n}\n\nexport function rebindRollback(\n rollback: MigrationRollbackV1,\n dispatches: readonly MigrationDispatchV1[]\n): MigrationRollbackV1 {\n if (rollback.kind === \"irreversible\") return rollback;\n return {\n ...rollback,\n operations: rebindDispatches(rollback.operations, dispatches),\n };\n}\n\nconst IDENTIFIER = String.raw`(?:\"(?:[^\"]|\"\")+\"|[A-Za-z_][\\w$]*)`;\nconst QUALIFIED = String.raw`${IDENTIFIER}(?:\\.${IDENTIFIER})?`;\n\nconst ALTER_TYPE_ADD_VALUE = /ALTER\\s+TYPE\\s+\\S+\\s+ADD\\s+VALUE/i;\n\n/** `CREATE TABLE <name>` (group 1), or `ALTER TABLE <name>` (2) and its actions (3). */\nconst TABLE_STATEMENT = new RegExp(\n String.raw`\\bCREATE\\s+(?:(?:GLOBAL|LOCAL|TEMP|TEMPORARY|UNLOGGED)\\s+)*TABLE\\s+(?!IF\\s+NOT\\s+EXISTS\\b)(${QUALIFIED})|\\bALTER\\s+TABLE\\s+(?:IF\\s+EXISTS\\s+)?(?:ONLY\\s+)?(${QUALIFIED})([^;]*)`,\n \"gi\"\n);\n/** `RENAME TO <name>`, the whole action of an `ALTER TABLE`. */\nconst RENAME_TO = new RegExp(\n String.raw`^\\s*RENAME\\s+TO\\s+(${IDENTIFIER})\\s*$`,\n \"i\"\n);\nconst LAST_IDENTIFIER = new RegExp(`${IDENTIFIER}$`);\n/** Each action that rewrites or scans the table, and how a refusal names it. */\nconst TABLE_REWRITES: readonly (readonly [RegExp, (name: string) => string])[] =\n [\n [\n new RegExp(\n String.raw`\\bALTER\\s+(?:COLUMN\\s+)?(${IDENTIFIER})\\s+(?:SET\\s+DATA\\s+)?TYPE\\b`,\n \"i\"\n ),\n (column) => `column type change of ${column}`,\n ],\n [\n new RegExp(\n String.raw`\\bALTER\\s+(?:COLUMN\\s+)?(${IDENTIFIER})\\s+SET\\s+NOT\\s+NULL\\b`,\n \"i\"\n ),\n (column) => `SET NOT NULL on ${column}`,\n ],\n [\n new RegExp(\n String.raw`\\bADD\\s+(?:COLUMN\\s+)?(?:IF\\s+NOT\\s+EXISTS\\s+)?(?!(?:CONSTRAINT|PRIMARY|UNIQUE|FOREIGN|CHECK|EXCLUDE)\\b)(${IDENTIFIER})[\\s\\S]*?(?:\\b(?:gen_random_uuid|uuidv[47]|uuid_generate_v[14]|random|clock_timestamp|timeofday|nextval)\\s*\\(|\\b(?:SMALL|BIG)?SERIAL\\b|\\bGENERATED\\b)`,\n \"i\"\n ),\n (column) => `volatile default on new column ${column}`,\n ],\n [\n // `NOT VALID` counts up to the next `, ADD` action, not past it.\n new RegExp(\n String.raw`\\bADD\\s+(?:CONSTRAINT\\s+${IDENTIFIER}\\s+)?(FOREIGN\\s+KEY|CHECK)\\b(?!(?:(?!,\\s*ADD\\b)[\\s\\S])*\\bNOT\\s+VALID\\b)`,\n \"i\"\n ),\n (constraint) => `${constraint.toUpperCase()} validation`,\n ],\n ];\n\n/**\n * The PostgreSQL statements of `program` that rewrite or scan an existing\n * table while holding a lock that blocks it (T5a): a column type change (an\n * enum replacement and a decimal descriptor change are ones), `SET NOT NULL`,\n * a new column whose default is volatile, and a FOREIGN KEY or CHECK added\n * without `NOT VALID`. One entry per `ALTER TABLE`, naming its table as the\n * statement spells it and its first such action; a table an earlier\n * `RENAME TO` of the program renamed is named by its spelling before the\n * program ran, the one the live catalog holds. A table the program has\n * already created by that spelling is empty, so it is left out (a force\n * reset, a drop and recreate), as it is once renamed. A plain `CREATE INDEX`\n * (writes blocked, reads not) is not one.\n */\nexport function tableRewrites(\n program: readonly string[]\n): { readonly table: string; readonly operation: string }[] {\n const created = new Set<string>();\n const before = new Map<string, string>();\n return program.flatMap((statement) =>\n [...statement.matchAll(TABLE_STATEMENT)].flatMap(\n ([, made, table, clause]) => {\n if (made) created.add(made);\n if (!table) return [];\n const renamedTo = RENAME_TO.exec(clause ?? \"\")?.[1];\n if (renamedTo) {\n const next = table.replace(LAST_IDENTIFIER, renamedTo);\n if (created.has(table)) created.add(next);\n else before.set(next, before.get(table) ?? table);\n return [];\n }\n if (created.has(table)) return [];\n for (const [pattern, name] of TABLE_REWRITES) {\n const action = pattern.exec(clause ?? \"\")?.[1];\n if (action) {\n return [\n { table: before.get(table) ?? table, operation: name(action) },\n ];\n }\n }\n return [];\n }\n )\n );\n}\n\nfunction isNonTransactionalSql(driver: MigrationDriver, sql: string): boolean {\n if (runsConcurrently(sql)) return true;\n return (\n ALTER_TYPE_ADD_VALUE.test(sql) &&\n !driver.capabilities.supportsAddEnumValueInTransaction\n );\n}\n\nexport function classifyGeneratedAtomicity(\n driver: MigrationDriver,\n operations: readonly DiffOperation[]\n): AtomicityClass {\n if (driver.dialect === \"mysql\") return \"stepwise\";\n if (\n operations.some(\n (operation) =>\n operation.type === \"alterEnum\" &&\n (operation.addValues?.length ?? 0) > 0 &&\n !driver.capabilities.supportsAddEnumValueInTransaction\n )\n ) {\n return \"stepwise\";\n }\n return \"transactional\";\n}\n\nexport function assertTransactionalBoundaryHonored(\n supportsTransactions: boolean,\n requested: \"transactional\" | \"stepwise\" | null\n): void {\n if (requested === \"transactional\" && !supportsTransactions) {\n throw new MigrationError(\n \"This producer cannot honor a transactional manual boundary\",\n VibORMErrorCode.MIGRATION_UNSUPPORTED_PROVIDER\n );\n }\n}\n\n/**\n * Plan S5, refused while a stored path is prepared, before any of it runs:\n * only a transaction holds SQLite's write lock, under which a migration runs\n * exactly once, and every SQLite statement can run in one. Generate refuses\n * such a program since 1.2.0; this refuses one 1.1.0 published, whichever\n * command would run it. Resolve's retry does not ask: it finishes an attempt\n * 1.1.0 left open.\n */\nexport function refuseSqliteStepwise(\n driver: MigrationDriver,\n requested: \"transactional\" | \"stepwise\" | null,\n toState: string\n): void {\n if (requested !== \"stepwise\" || driver.dialect !== \"sqlite\") return;\n throw new MigrationError(\n 'SQLite runs no stepwise program: only a transaction holds the write lock under which a migration runs exactly once, and every SQLite statement can run in one. Nothing ran. Run it with VibORM 1.1.0, or, if no database applied it, remove its state from migration storage and generate it again with `execution: \"transactional\"`.',\n VibORMErrorCode.MIGRATION_UNSUPPORTED_PROVIDER,\n { meta: { dialect: \"sqlite\", toState, feature: \"stepwise execution\" } }\n );\n}\n\nexport function classifyStoredAtomicity(\n driver: MigrationDriver,\n requested: \"transactional\" | \"stepwise\" | null,\n operations: readonly MigrationOperationV1[],\n blob?: Uint8Array\n): AtomicityClass {\n if (requested === \"transactional\") {\n if (driver.dialect === \"mysql\") {\n throw new MigrationError(\n \"This provider cannot honor a transactional manual boundary\",\n VibORMErrorCode.MIGRATION_UNSUPPORTED_PROVIDER\n );\n }\n return \"transactional\";\n }\n if (requested === \"stepwise\") return \"stepwise\";\n if (driver.dialect === \"mysql\") return \"stepwise\";\n if (\n blob &&\n stepStatements(blob, operations).some((text) =>\n isNonTransactionalSql(driver, text)\n )\n ) {\n return \"stepwise\";\n }\n return \"transactional\";\n}\n\nexport function encodeParameter(value: unknown): MigrationParameterV1 {\n if (value === null || value === undefined) return { kind: \"null\" };\n if (typeof value === \"boolean\") return { kind: \"boolean\", value };\n if (typeof value === \"string\") return { kind: \"string\", value };\n if (typeof value === \"number\") {\n if (!Number.isFinite(value)) {\n throw new MigrationError(\n \"SQL parameters refuse NaN and Infinity\",\n VibORMErrorCode.MIGRATION_INVALID_ESTATE\n );\n }\n return { kind: \"number\", value };\n }\n if (typeof value === \"bigint\")\n return { kind: \"bigint\", value: value.toString() };\n if (value instanceof Date)\n return { kind: \"date-time\", value: value.toISOString() };\n if (value instanceof Uint8Array) {\n return { kind: \"bytes\", value: encodeBase64(value) };\n }\n const decimal = canonicalDecimalText(value);\n if (decimal !== undefined) return { kind: \"decimal\", value: decimal };\n if (typeof value === \"function\" || typeof value === \"symbol\") {\n throw new MigrationError(\n \"SQL parameters refuse functions and symbols\",\n VibORMErrorCode.MIGRATION_INVALID_ESTATE\n );\n }\n return { kind: \"json\", value };\n}\n\nexport function decodeParameter(\n parameter: MigrationParameterV1,\n targetNamespace?: string\n): unknown {\n switch (parameter.kind) {\n case \"null\":\n return null;\n case \"target-namespace\":\n if (targetNamespace === undefined) {\n throw new MigrationError(\n \"A stored target-namespace parameter requires a resolved migration namespace\",\n VibORMErrorCode.MIGRATION_INVALID_STATE\n );\n }\n return targetNamespace;\n case \"boolean\":\n case \"string\":\n case \"number\":\n case \"json\":\n return parameter.value;\n case \"bigint\":\n return BigInt(parameter.value);\n case \"bytes\": {\n const bytes = decodeCanonicalBase64(parameter.value);\n if (bytes === undefined) {\n throw new MigrationError(\n \"Stored bytes parameter is not canonical Base64\",\n VibORMErrorCode.MIGRATION_INVALID_ESTATE\n );\n }\n return bytes;\n }\n case \"date-time\":\n return new Date(parameter.value);\n case \"decimal\":\n return parameter.value;\n default: {\n const kind: never = parameter;\n throw new MigrationError(\n `Unknown SQL parameter kind: ${JSON.stringify(kind)}`,\n VibORMErrorCode.MIGRATION_INVALID_ESTATE\n );\n }\n }\n}\n","import { errorCause } from \"../errors/diagnostic-safety\";\n/**\n * One execution owner for authenticated SQL slices and typed parameters.\n * Apply, down, reset, and push consume this. There is no second executor.\n */\n\nimport type { AnyDriver } from \"../drivers/driver\";\nimport {\n ConnectionError,\n isVibORMError,\n MigrationError,\n type MigrationErrorMeta,\n type VibORMError,\n VibORMErrorCode,\n} from \"../errors\";\nimport { decodeParameter } from \"./compile\";\nimport type { MigrationBatch } from \"./pinned-session\";\nimport { sliceDispatch } from \"./sql-blob\";\nimport { readExecutableStatements } from \"./statement-safety\";\nimport { readFlag } from \"./v1-parse-shared\";\nimport type {\n LedgerEffectStateV1,\n MigrationBooleanCheckV1,\n MigrationDispatchV1,\n MigrationOperationV1,\n MigrationStepV1,\n} from \"./v1-types\";\n\nexport async function executeExactSql(\n producer: AnyDriver,\n sql: string,\n parameters: readonly unknown[] = []\n): Promise<void> {\n await producer._executeRaw(sql, [...parameters]);\n}\n\n/** A dispatch's exact text and its decoded parameters. */\nfunction dispatchQuery(\n blob: Uint8Array,\n dispatch: MigrationDispatchV1,\n targetNamespace: string | undefined\n): { readonly sql: string; readonly params: unknown[] } {\n return {\n sql: sliceDispatch(blob, dispatch),\n params: dispatch.parameters.map((parameter) =>\n decodeParameter(parameter, targetNamespace)\n ),\n };\n}\n\nexport async function executeDispatch(\n producer: AnyDriver,\n blob: Uint8Array,\n dispatch: MigrationDispatchV1,\n targetNamespace?: string\n): Promise<void> {\n const { sql, params } = dispatchQuery(blob, dispatch, targetNamespace);\n await executeExactSql(producer, sql, params);\n}\n\nexport async function evaluateCheck(\n producer: AnyDriver,\n blob: Uint8Array,\n check: MigrationBooleanCheckV1,\n targetNamespace?: string\n): Promise<boolean> {\n const { sql, params } = dispatchQuery(blob, check.query, targetNamespace);\n const result = await producer._executeRaw<Record<string, unknown>>(\n sql,\n params\n );\n if (result.rows.length !== 1) {\n throw new MigrationError(\n `Check ${check.id} must return exactly one row`,\n VibORMErrorCode.MIGRATION_INVALID_STATE\n );\n }\n const values = Object.values(result.rows[0]!);\n if (values.length !== 1) {\n throw new MigrationError(\n `Check ${check.id} must return exactly one column`,\n VibORMErrorCode.MIGRATION_INVALID_STATE\n );\n }\n const flag = readFlag(values[0]);\n if (flag === undefined) {\n throw new MigrationError(\n `Check ${check.id} did not return a boolean`,\n VibORMErrorCode.MIGRATION_INVALID_STATE\n );\n }\n return flag === check.equals;\n}\n\nconst TRAILING_SEMICOLON = /;\\s*$/;\n\n/**\n * {@link evaluateCheck} as a condition one request asserts (plan D7): the\n * check's one row holds one value, `check.equals` in a spelling\n * `readFlag` reads. No row, more rows, or another value do not hold. A\n * check with another number of columns is refused, as `evaluateCheck`\n * refuses it: the `UNION ALL` with one column fails the request, which rolls\n * back. Columns are named, never read as one whole row, which PlanetScale\n * Neki refuses.\n */\nexport function checkCondition(\n blob: Uint8Array,\n check: MigrationBooleanCheckV1,\n targetNamespace: string | undefined\n): { readonly sql: string; readonly params: unknown[] } {\n const { sql, params } = dispatchQuery(blob, check.query, targetNamespace);\n const spellings = check.equals ? \"'true', 't', '1'\" : \"'false', 'f', '0'\";\n return {\n sql: `(SELECT CASE WHEN count(*) = 1 THEN min(one.value::text) END FROM (SELECT * FROM (\\n${sql.replace(TRAILING_SEMICOLON, \"\")}\\n) AS checked UNION ALL SELECT NULL WHERE false) AS one(value)) IN (${spellings})`,\n params,\n };\n}\n\n/**\n * Whether `error` is the provider refusing a statement — its answer carries a\n * provider code — rather than a failure of the transport.\n */\nexport function providerRefused(error: unknown): error is VibORMError {\n return (\n isVibORMError(error) &&\n !(error instanceof ConnectionError) &&\n (error.meta.providerCode !== undefined ||\n error.meta.providerSqlState !== undefined)\n );\n}\n\n/**\n * The provider's SQLSTATE and code of a refusal, for the meta of the\n * migration error that wraps it (both are on the error-metadata allow-list;\n * the provider's text stays in the cause, disclosed as the driver's\n * diagnostics allow). Nothing for a transport failure.\n */\nexport function providerFacts(error: unknown): {\n readonly providerCode?: unknown;\n readonly providerSqlState?: unknown;\n} {\n if (!providerRefused(error)) return {};\n const { providerCode, providerSqlState } = error.meta;\n return {\n ...(providerCode === undefined ? {} : { providerCode }),\n ...(providerSqlState === undefined ? {} : { providerSqlState }),\n };\n}\n\nexport interface StepProgress {\n readonly operationId: string;\n readonly dispatchId: string;\n readonly skipped: boolean;\n}\n\n/**\n * Records one step's progress. An opaque stepwise step is announced (`none`)\n * before it runs, then answered: `committed`, or — refused whole, nothing of\n * it committed — `none` again with the refusal as `failure`. An announcement\n * never answered may have committed.\n */\ntype OnProgress = (\n progress: StepProgress,\n effect: LedgerEffectStateV1,\n failure?: string\n) => Promise<void>;\n\n/** The edge a program runs: every dispatch failure names it. */\nexport interface DispatchEdge {\n readonly fromState: string | null;\n readonly toState: string | null;\n}\n\n/** Where one dispatch sits: its edge, operation and statement position. */\ninterface DispatchSite {\n readonly edge: DispatchEdge | undefined;\n readonly operationId: string;\n readonly statementIndex: number;\n}\n\n/**\n * `atomic` is a program inside a real transaction (plan D5): its rollback\n * undoes whatever a failure leaves half done, so no step is probed, and the\n * caller proves the destination once. Its progress is reported only when\n * asked (one part of an edge split at Neki's commit boundaries,\n * `apply-v1.ts`): each report lands in the step's own transaction, so it\n * commits with the step or not at all.\n */\nexport async function executeOperations(\n producer: AnyDriver,\n blob: Uint8Array,\n operations: readonly MigrationOperationV1[],\n boundary: \"transactional\" | \"stepwise\" | \"atomic\",\n onProgress?: OnProgress,\n targetNamespace?: string,\n edge?: DispatchEdge\n): Promise<void> {\n let statementIndex = 0;\n for (const operation of operations) {\n for (const step of operation.steps) {\n await executeStep(\n producer,\n blob,\n { edge, operationId: operation.id, statementIndex },\n step,\n boundary,\n onProgress,\n targetNamespace\n );\n statementIndex += 1;\n }\n }\n}\n\nfunction siteMeta(site: DispatchSite, dispatchId: string): MigrationErrorMeta {\n return {\n ...(site.edge?.fromState ? { fromState: site.edge.fromState } : {}),\n ...(site.edge?.toState ? { toState: site.edge.toState } : {}),\n operationId: site.operationId,\n dispatchId,\n statementIndex: site.statementIndex,\n };\n}\n\n/**\n * Runs one dispatch. A statement the provider refused — its answer carries a\n * provider code — becomes a MigrationError naming its edge, operation,\n * dispatch and statement, with that code; SQL and parameters stay on the\n * cause, behind diagnostics. A transport failure is not a refusal: it stays\n * what it is, and the pinned session reports a lost connection as the\n * retryable failure it is (plan S2).\n */\nasync function runDispatch(\n producer: AnyDriver,\n blob: Uint8Array,\n site: DispatchSite,\n dispatch: MigrationDispatchV1,\n targetNamespace: string | undefined\n): Promise<void> {\n try {\n await executeDispatch(producer, blob, dispatch, targetNamespace);\n } catch (error) {\n if (!providerRefused(error)) throw error;\n throw refusal(site, dispatch.dispatchId, error);\n }\n}\n\nfunction refusal(\n site: DispatchSite,\n dispatchId: string,\n error: VibORMError,\n meta?: MigrationErrorMeta\n): MigrationError {\n return new MigrationError(\n `Migration statement ${site.statementIndex} of operation ${site.operationId} failed`,\n VibORMErrorCode.MIGRATION_FAILED,\n {\n cause: error,\n meta: {\n ...siteMeta(site, dispatchId),\n providerCode: error.meta.providerCode,\n providerSqlState: error.meta.providerSqlState,\n ...meta,\n },\n }\n );\n}\n\n/**\n * Leaders of a statement that may COMMIT part of its work before it fails: a\n * procedure, a PostgreSQL `DO` block, a statement prepared earlier.\n */\nconst COMMITS_INSIDE = new Set([\"CALL\", \"DO\", \"EXECUTE\"]);\n\n/**\n * Whether the provider's refusal of `sql` proves none of it committed: one\n * statement, run bare as a transaction of its own, which the server undoes\n * whole when it refuses it (VibORM's MySQL tables are InnoDB). Not one led by\n * {@link COMMITS_INSIDE}, nor a `CONCURRENTLY` statement, which commits in\n * phases.\n */\nfunction refusedWhole(\n error: unknown,\n sql: string,\n dialect: AnyDriver[\"dialect\"]\n): error is VibORMError {\n if (!providerRefused(error)) return false;\n const statements = readExecutableStatements(sql, dialect);\n const [leader = \"\", ...rest] = statements[0] ?? [];\n return (\n statements.length === 1 &&\n !COMMITS_INSIDE.has(leader) &&\n !rest.includes(\"CONCURRENTLY\")\n );\n}\n\nasync function executeStep(\n producer: AnyDriver,\n blob: Uint8Array,\n site: DispatchSite,\n step: MigrationStepV1,\n boundary: \"transactional\" | \"stepwise\" | \"atomic\",\n onProgress?: OnProgress,\n targetNamespace?: string\n): Promise<void> {\n const { operationId } = site;\n if (boundary === \"atomic\") {\n await runDispatch(producer, blob, site, step.execute, targetNamespace);\n // Recorded, when asked, in the transaction the step ran in: with it.\n await onProgress?.(\n { operationId, dispatchId: step.execute.dispatchId, skipped: false },\n \"committed\"\n );\n return;\n }\n if (step.retry === \"proven\") {\n if (await evaluateCheck(producer, blob, step.postcheck, targetNamespace)) {\n await onProgress?.(\n { operationId, dispatchId: step.execute.dispatchId, skipped: true },\n \"none\"\n );\n return;\n }\n if (\n !(await evaluateCheck(producer, blob, step.precheck, targetNamespace))\n ) {\n throw new MigrationError(\n `Proven step ${operationId} is neither at origin nor destination`,\n VibORMErrorCode.MIGRATION_INVALID_STATE,\n { meta: { lastConfirmedStep: step.execute.dispatchId } }\n );\n }\n await runDispatch(producer, blob, site, step.execute, targetNamespace);\n if (\n !(await evaluateCheck(producer, blob, step.postcheck, targetNamespace))\n ) {\n throw new MigrationError(\n `Proven step ${operationId} failed its postcheck`,\n VibORMErrorCode.MIGRATION_PARTIAL_EFFECT,\n {\n meta: {\n lastConfirmedStep: step.execute.dispatchId,\n effectState: \"partial\",\n partial: true,\n },\n }\n );\n }\n await onProgress?.(\n { operationId, dispatchId: step.execute.dispatchId, skipped: false },\n \"committed\"\n );\n return;\n }\n\n if (boundary === \"stepwise\") {\n const progress = {\n operationId,\n dispatchId: step.execute.dispatchId,\n skipped: false,\n };\n await onProgress?.(progress, \"none\");\n try {\n await executeDispatch(producer, blob, step.execute, targetNamespace);\n } catch (error) {\n const sql = sliceDispatch(blob, step.execute);\n if (refusedWhole(error, sql, producer.dialect)) {\n const refused = refusal(site, step.execute.dispatchId, error, {\n effectState: \"none\",\n partial: true,\n });\n // Unrecorded, the announcement stands: it may have committed.\n await onProgress?.(\n progress,\n \"none\",\n `${refused.code}: ${refused.message}`\n )?.catch(() => undefined);\n throw refused;\n }\n throw new MigrationError(\n `Opaque stepwise dispatch ${step.execute.dispatchId} failed with an ambiguous outcome`,\n VibORMErrorCode.MIGRATION_AMBIGUOUS_COMMIT,\n {\n cause: errorCause(error),\n meta: {\n ...siteMeta(site, step.execute.dispatchId),\n lastConfirmedStep: step.execute.dispatchId,\n effectState: \"may-have-committed\",\n partial: true,\n },\n }\n );\n }\n await onProgress?.(progress, \"committed\");\n return;\n }\n\n await runDispatch(producer, blob, site, step.execute, targetNamespace);\n await onProgress?.(\n { operationId, dispatchId: step.execute.dispatchId, skipped: false },\n \"committed\"\n );\n}\n\nexport async function evaluateAllChecks(\n producer: AnyDriver,\n blob: Uint8Array,\n checks: readonly MigrationBooleanCheckV1[],\n targetNamespace?: string\n): Promise<boolean> {\n for (const check of checks) {\n if (!(await evaluateCheck(producer, blob, check, targetNamespace))) {\n return false;\n }\n }\n return true;\n}\n\n/**\n * The one owner of \"authored checks must hold\": every one of `checks` holds,\n * else `refusal` is the command's MIGRATION_DRIFT. Inside one request (plan\n * D7) each is asserted there instead, as its {@link checkCondition}.\n */\nexport async function assertAllChecks(\n producer: AnyDriver,\n blob: Uint8Array,\n checks: readonly MigrationBooleanCheckV1[],\n targetNamespace: string | undefined,\n refusal: string,\n batch?: MigrationBatch\n): Promise<void> {\n const drift = () =>\n new MigrationError(refusal, VibORMErrorCode.MIGRATION_DRIFT);\n if (batch) {\n for (const check of checks) {\n const { sql, params } = checkCondition(blob, check, targetNamespace);\n batch.assert(sql, params, drift());\n }\n return;\n }\n if (!(await evaluateAllChecks(producer, blob, checks, targetNamespace))) {\n throw drift();\n }\n}\n","/**\n * The one DDL statement a transaction silently swallows.\n *\n * SQLite cannot alter a table in place, so `alterColumn`, `addForeignKey` and\n * both halves of a unique-constraint change go through\n * `SQLite3MigrationDriver.generateTableRecreation`: create `__new_<t>`, copy\n * the rows, `DROP TABLE <t>`, rename. `DROP TABLE` is the step that needs\n * foreign keys really disabled — with enforcement on, SQLite performs an\n * implicit `DELETE FROM` before removing the table, which either raises the\n * constraint or fires the referential action on every child row.\n *\n * `PRAGMA foreign_keys` is documented by SQLite as a NO-OP inside a\n * transaction, and all three places that execute generated DDL run the batch\n * inside one — `execute-dispatch.ts` and the SQLite recreation path.\n * MEASURED on better-sqlite3 at `5e5bc60`, recreating a populated table a\n * single child row pointed at:\n *\n * - `onDelete: noAction` -> `DROP TABLE` threw `FOREIGN KEY constraint\n * failed` and the push applied nothing;\n * - `onDelete: cascade` -> no error, and every child row was gone;\n * - `onDelete: setNull` -> no error, and every child's key was NULL.\n *\n * `PRAGMA defer_foreign_keys=ON` — the spelling SQLite does honor inside a\n * transaction — does not close it: it defers the violation counter the\n * implicit delete already incremented, so `noAction` merely moves its failure\n * from `DROP TABLE` to `COMMIT`, and the two silent halves stay silent.\n *\n * So the pragma is lifted out to bracket the transaction, which is SQLite's own\n * documented procedure — its step 1 (`PRAGMA foreign_keys=OFF`) precedes its\n * step 2 (`BEGIN`). Lifting it is what makes the disable real for the first\n * time, and a real disable is fail-open for the rest of the batch: a\n * `dropTable` sharing the batch would now orphan its children instead of\n * refusing. `assertForeignKeysIntact` is that hole closed — step 10 of the same\n * procedure — and it runs inside the transaction so a violation rolls the whole\n * batch back.\n */\n\nimport type { AnyDriver } from \"../drivers/driver\";\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\nimport { createIdentifierQuoter } from \"../sql/identifiers\";\n\n/**\n * `PRAGMA foreign_keys = OFF` / `= ON`, the only statement any migration driver\n * emits whose effect a transaction discards. Written by\n * `generateTableRecreation`; no other dialect emits it.\n */\nconst MATCH_FOREIGN_KEYS_PRAGMA =\n /^PRAGMA\\s+foreign_keys\\s*=\\s*(ON|OFF)\\s*;?$/i;\n\n/** A statement's leading whitespace and SQL comments. */\nconst LEADING_TRIVIA = /^(?:\\s+|--[^\\n]*(?:\\n|$)|\\/\\*[\\s\\S]*?\\*\\/)*/;\n\nconst DROPS_TABLE = /^DROP\\s+TABLE\\b/i;\n\n/**\n * The `DROP TABLE` a recreation or a `dropTable` renders (`\"name\"`), and the\n * plain spelling a hand-written transition may use, optionally in `main`.\n */\nconst MATCH_DROP_TABLE =\n /^DROP\\s+TABLE\\s+(?:IF\\s+EXISTS\\s+)?(?:(?:main|\"main\")\\s*\\.\\s*)?(?:\"((?:[^\"]|\"\")+)\"|([A-Za-z_][\\w$]*))\\s*;?\\s*$/i;\n\nconst quote = createIdentifierQuoter('\"');\n\nexport interface ForeignKeyBracket {\n /** Runs before the transaction opens. */\n readonly disable: string;\n /** Runs after it closes, however it closes. */\n readonly enable: string;\n}\n\nexport interface LiftedStatements {\n /** `null` when nothing was lifted; the statements are then untouched. */\n readonly bracket: ForeignKeyBracket | null;\n readonly statements: string[];\n}\n\n/**\n * Whether this driver has no transaction to lift the pragmas out of — and so\n * nothing to prove the lift in.\n *\n * What the pragma does is the driver's declared claim: effectful SQLite work is\n * admitted only on a driver declaring `sqliteMigrationCapability`, whose\n * `foreignKeys: \"pragma\"` says `PRAGMA foreign_keys` between transactions takes\n * effect and reads back (`admission.ts` is that claim's one reader). The claim\n * is then verified on every lift. What is left is the transaction: without one,\n * a recreation that went wrong can neither be checked before it commits nor\n * rolled back, so it is refused (D1 is the stock case: one native batch, no\n * transaction).\n *\n * Exported because the SQLite driver asks the same question before it plans a\n * relation-bearing domain conversion (plan §7.4's D1 prerequisite).\n */\nexport function foreignKeyPragmasCannotBeLifted(driver: AnyDriver): boolean {\n return !driver.supportsTransactions;\n}\n\n/**\n * Takes the foreign-key pragmas out of a DDL batch so the caller can run them\n * around its transaction instead of inside it.\n *\n * Returns `bracket: null` — and the statements unchanged — when there is\n * nothing to lift, so every caller can run the result unconditionally. A batch\n * that needs the lift on a driver that cannot prove one is refused here,\n * before any of it runs.\n */\nexport function liftForeignKeyPragmas(\n driver: AnyDriver,\n statements: string[]\n): LiftedStatements {\n let disable: string | null = null;\n let enable: string | null = null;\n const rest: string[] = [];\n\n for (const statement of statements) {\n const trimmed = statement.trim();\n const match = trimmed.match(MATCH_FOREIGN_KEYS_PRAGMA);\n if (!match) {\n rest.push(statement);\n continue;\n }\n if (match[1]?.toUpperCase() === \"OFF\") {\n disable ??= trimmed;\n } else {\n enable ??= trimmed;\n }\n }\n\n // Half a bracket would leave enforcement off past the batch. Leave the batch\n // exactly as it came instead, so it fails the way it failed before rather\n // than succeeding with the database unguarded.\n if (!(disable && enable)) {\n return { bracket: null, statements };\n }\n if (foreignKeyPragmasCannotBeLifted(driver)) {\n throw new MigrationError(\n `The driver \"${driver.driverName}\" runs migrations without a transaction, so a SQLite table recreation cannot be proven to keep the rows that reference it: if \\`PRAGMA foreign_keys=OFF\\` did not take, \\`DROP TABLE\\` would delete or null every child row and nothing could roll it back. ` +\n \"The change is refused before any statement runs. Run it through a driver with transactions.\",\n VibORMErrorCode.MIGRATION_UNSUPPORTED_PROVIDER,\n {\n meta: { driver: driver.driverName, feature: \"SQLite table recreation\" },\n }\n );\n }\n\n return { bracket: { disable, enable }, statements: rest };\n}\n\ninterface ForeignKeyCheckRow {\n table?: unknown;\n parent?: unknown;\n}\n\n/**\n * Runs one body inside the lifted transaction: on `transaction`, with every\n * `DROP TABLE` counted around, then `PRAGMA foreign_key_check`.\n */\nexport type InsideLift = <R>(\n transaction: AnyDriver,\n body: (producer: AnyDriver) => Promise<R>\n) => Promise<R>;\n\nconst unlifted: InsideLift = (transaction, body) => body(transaction);\n\n/**\n * Runs `work` with enforcement really off, restoring it however `work` ends.\n * Call it OUTSIDE the transaction `work` opens — that placement is the whole\n * point — and run that transaction's statements through the `inside` it is\n * handed. Without a bracket nothing is lifted and `inside` adds nothing.\n *\n * The lift is verified, not assumed. The driver's `beforeForeignKeysOff` hook\n * runs first, and `PRAGMA foreign_keys` must read 0 after the disable — or the\n * change is refused before any of it runs — and 1 after the re-enable. Inside,\n * every table referencing a dropped table must keep its rows and its keys\n * across that `DROP TABLE`, which still catches a driver whose read-back lies,\n * and `PRAGMA foreign_key_check` must find nothing before the commit.\n */\nexport async function withForeignKeysLifted<T>(\n driver: AnyDriver,\n bracket: ForeignKeyBracket | null,\n work: (inside: InsideLift) => Promise<T>\n): Promise<T> {\n if (!bracket) {\n return await work(unlifted);\n }\n\n await driver[\"beforeForeignKeysOff\"]?.();\n await driver._executeRaw(terminate(bracket.disable));\n let completed = false;\n try {\n await assertEnforcement(driver, 0);\n const result = await work(async (transaction, body) => {\n const value = await body(keepingChildren(transaction));\n await assertForeignKeysIntact(transaction);\n return value;\n });\n completed = true;\n return result;\n } finally {\n await driver._executeRaw(terminate(bracket.enable));\n if (completed) await assertEnforcement(driver, 1);\n }\n}\n\nfunction terminate(statement: string): string {\n const trimmed = statement.trim();\n return trimmed.endsWith(\";\") ? trimmed : `${trimmed};`;\n}\n\nasync function assertEnforcement(\n driver: AnyDriver,\n expected: 0 | 1\n): Promise<void> {\n const { rows } = await driver._executeRaw<{ foreign_keys?: unknown }>(\n \"PRAGMA foreign_keys;\"\n );\n const read = rows[0]?.foreign_keys;\n if (Number(read) === expected) return;\n throw new MigrationError(\n expected === 0\n ? `PRAGMA foreign_keys reads ${String(read)} after PRAGMA foreign_keys=OFF on the driver \"${driver.driverName}\", so a SQLite table recreation would delete or null the rows that reference it. The change is refused before any statement runs; foreign keys were re-enabled.`\n : `The change committed, but PRAGMA foreign_keys reads ${String(read)} after PRAGMA foreign_keys=ON on the driver \"${driver.driverName}\": foreign keys may not be enforced on this connection. Disconnect the client before running other queries on it.`,\n VibORMErrorCode.MIGRATION_UNSUPPORTED_PROVIDER,\n { meta: { driver: driver.driverName, pragma: \"foreign_keys\", expected } }\n );\n}\n\n/**\n * `transaction`, with every `DROP TABLE` run between two counts of each table\n * that references the dropped one (built the way every execution view in this\n * layer is: an `Object.create` restating one member).\n *\n * With enforcement really off, `DROP TABLE` touches no other table. With it on\n * — a driver whose `PRAGMA foreign_keys` read-back lies — it deletes or nulls\n * every child row, which `foreign_key_check` cannot see afterwards. Counting\n * right around the statement, rather than around the whole batch, leaves the\n * batch free to write those rows itself.\n */\nfunction keepingChildren(transaction: AnyDriver): AnyDriver {\n const view: AnyDriver = Object.create(transaction);\n Object.defineProperty(view, \"_executeRaw\", {\n value: async (sql: string, params?: unknown[]) => {\n const parent = droppedTable(sql);\n if (parent === undefined) {\n return await transaction._executeRaw(sql, params);\n }\n const children = await referencingColumns(transaction, parent);\n const before = await countChildren(transaction, children);\n const result = await transaction._executeRaw(sql, params);\n const after = await countChildren(transaction, children);\n const changed = [...children].flatMap(([child, columns], i) =>\n [`\"${child}\" rows`, ...columns.map((c) => `\"${child}\".\"${c}\" non-null`)]\n .map((label, k) => `${label} ${before[i]?.[k]} -> ${after[i]?.[k]}`)\n .filter((_, k) => before[i]?.[k] !== after[i]?.[k])\n );\n if (changed.length > 0) {\n throw new MigrationError(\n `Rows referencing \"${parent}\" changed when it was dropped with foreign keys lifted (${changed.join(\", \")}), so the batch was rolled back. ` +\n \"The driver did not really disable foreign keys, and DROP TABLE fired the referential actions.\",\n VibORMErrorCode.MIGRATION_FAILED,\n { meta: { driver: transaction.driverName, table: parent } }\n );\n }\n return result;\n },\n });\n return view;\n}\n\n/**\n * The table a `DROP TABLE` statement drops, or `undefined` for any other\n * statement. A drop whose name it cannot read is refused: its children could\n * not be counted, and the census must not be skipped silently.\n */\nfunction droppedTable(sql: string): string | undefined {\n const statement = sql.replace(LEADING_TRIVIA, \"\");\n if (!DROPS_TABLE.test(statement)) return;\n const match = statement.match(MATCH_DROP_TABLE);\n const name = match?.[1]?.replaceAll('\"\"', '\"') ?? match?.[2];\n if (name !== undefined) return name;\n throw new MigrationError(\n \"A SQLite migration that recreates a table also runs a DROP TABLE whose table name cannot be read, so the rows referencing that table cannot be counted around the drop. \" +\n 'The batch was rolled back. Spell the drop as DROP TABLE \"name\" (or a plain identifier) in its own statement.',\n VibORMErrorCode.MIGRATION_FAILED\n );\n}\n\n/** Every other table with a foreign key to `parent`, and its referencing columns. */\nasync function referencingColumns(\n transaction: AnyDriver,\n parent: string\n): Promise<Map<string, string[]>> {\n const { rows } = await transaction._executeRaw<{\n child: unknown;\n column: unknown;\n }>(\n `SELECT DISTINCT m.\"name\" AS \"child\", f.\"from\" AS \"column\" FROM sqlite_master AS m, pragma_foreign_key_list(m.\"name\") AS f WHERE m.\"type\" = 'table' AND f.\"table\" = ? COLLATE NOCASE AND m.\"name\" <> ? COLLATE NOCASE`,\n [parent, parent]\n );\n const children = new Map<string, string[]>();\n for (const row of rows) {\n const child = String(row.child);\n const columns = children.get(child) ?? [];\n columns.push(String(row.column));\n children.set(child, columns);\n }\n return children;\n}\n\n/** Per child: its row count, then the non-null count of each referencing column. */\nasync function countChildren(\n transaction: AnyDriver,\n children: ReadonlyMap<string, readonly string[]>\n): Promise<number[][]> {\n const counts: number[][] = [];\n for (const [child, columns] of children) {\n const keys = columns.map(\n (column, k) => `, count(${quote(column)}) AS \"k${k}\"`\n );\n const { rows } = await transaction._executeRaw<Record<string, unknown>>(\n `SELECT count(*) AS \"rows\"${keys.join(\"\")} FROM ${quote(child)}`\n );\n const row = rows[0] ?? {};\n counts.push([row.rows, ...columns.map((_, k) => row[`k${k}`])].map(Number));\n }\n return counts;\n}\n\n/**\n * Refuses a lifted batch that would commit against a broken reference: the\n * last statement `inside` runs, in the transaction, so the throw takes the\n * batch back.\n *\n * This is why the lift is not a fail-open trade. Lifting the pragma disables\n * enforcement for the whole batch, not just the recreation, so a `dropTable`\n * or a rebuild that sheds a referenced column could commit orphans the\n * un-lifted — and therefore never actually disabled — batch would have refused.\n * `PRAGMA foreign_key_check` is step 10 of SQLite's own recreation procedure.\n *\n * It cannot tell a reference the batch broke from one it merely found, and\n * refuses either way: SQLite's procedure says a reported violation means the\n * schema change is to be abandoned.\n */\nexport async function assertForeignKeysIntact(\n transaction: AnyDriver\n): Promise<void> {\n const result = await transaction._executeRaw<ForeignKeyCheckRow>(\n \"PRAGMA foreign_key_check;\"\n );\n if (result.rows.length === 0) {\n return;\n }\n\n const offenders = [\n ...new Set(\n result.rows.map(\n (row) => `${String(row.table)} -> ${String(row.parent ?? \"?\")}`\n )\n ),\n ];\n throw new MigrationError(\n `Migration left ${result.rows.length} row(s) violating a foreign key (${offenders.join(\", \")}). ` +\n \"A SQLite table recreation runs with foreign keys disabled, so the batch was rolled back rather than committed against a broken reference.\",\n VibORMErrorCode.MIGRATION_FAILED\n );\n}\n","/**\n * The ONE pinned migration session (§3.5): one physical producer reserved for\n * a command, the lock proven on it, its loss and limits tracked, and the\n * producer condemned whenever a lock or unlock proof fails. PostgreSQL and\n * SQLite hold the lock in their transactions instead (plans D1, S5); only\n * PostgreSQL stepwise work, PlanetScale's Neki (the whole command) and MySQL\n * keep a session lock. The dialect's lock and session statements come from\n * the bound migration driver.\n */\n\nimport type { AnyDriver } from \"../drivers/driver\";\nimport { normalizeDriverError } from \"../drivers/error-mapping\";\nimport {\n CLEANUP_BOUND_MS,\n leasePinnedCommand,\n type PinnedSessionControl,\n type PinnedSessionReservation,\n} from \"../drivers/shared/pinned-session\";\nimport { settleWithin } from \"../drivers/shared/settle\";\nimport { withSuppressedFailure } from \"../drivers/shared/suppressed-failure\";\nimport type { TransactionOptionSupport } from \"../drivers/shared/transaction-options\";\nimport { runTransactionLifecycle } from \"../drivers/shared/transactions\";\nimport type { BatchQuery, QueryExecutionContext } from \"../drivers/types\";\nimport {\n ConnectionError,\n FeatureNotSupportedError,\n MigrationError,\n VibORMError,\n VibORMErrorCode,\n} from \"../errors\";\nimport { errorCause } from \"../errors/diagnostic-safety\";\nimport type { BoundMigrationDriver } from \"./drivers\";\nimport { providerFacts, providerRefused } from \"./execute-dispatch\";\nimport { liftForeignKeyPragmas, withForeignKeysLifted } from \"./foreign-keys\";\nimport {\n DEFAULT_MIGRATION_LIMITS,\n type ResolvedMigrationLimits,\n} from \"./limits\";\nimport { runsConcurrently } from \"./statement-safety\";\nimport { type CatalogRead, readsCommandNamespace } from \"./target\";\nimport { createQueryExecutor } from \"./utils\";\n\n/**\n * The migration lock's key, \"viborm\" in hex. PostgreSQL's advisory lock is\n * database-wide, so estates in one database serialize with each other; MySQL\n * names its lock after the database instead (`drivers/mysql/pinned-session.ts`).\n */\nconst MIGRATION_LOCK_ID = 0x76_69_62_6f_72_6d;\n/**\n * The first pause between two PostgreSQL lock tries, doubled up to the cap. A\n * longer cap sends fewer tries but lets newcomers take a freed lock first: at\n * 1 s, waits under contention stretched to `lockWait`.\n */\nconst LOCK_RETRY_MS = 50;\nconst LOCK_RETRY_CAP_MS = 250;\n\n/**\n * A condition true while no command holds the migration lock (plan D5), for a\n * decision read before the lock.\n */\nexport function migrationLockFree(command: BoundMigrationDriver): string {\n return command.generateLockFree(MIGRATION_LOCK_ID);\n}\n\n/**\n * Whether this driver can pin a session: the provider's `pinnedSession()`\n * hook is the capability, asked by admission before any provider work.\n */\nexport function canPinSession(driver: AnyDriver): boolean {\n return driver[\"pinnedSession\"] !== undefined;\n}\n\n/**\n * Whether `driver` runs migration work with no session, one atomic request per\n * transactional group (plan D7): Neon HTTP is the shipped case.\n */\nexport function runsMigrationBatches(driver: AnyDriver): boolean {\n return (\n driver.dialect === \"postgresql\" &&\n !canPinSession(driver) &&\n driver.supportsBatch &&\n driver.supportsOrderedCommittedSegments\n );\n}\n\n/**\n * One transactional group as ONE request on a transport with no session\n * (plan D7). Statements sent to `producer` are recorded, not run; the request\n * opens with the limits and the bounded transaction lock, and what the command\n * would read inside its transaction is asserted there instead.\n */\nexport interface MigrationBatch {\n readonly producer: AnyDriver;\n /** `condition`, SQL with its own `$n` parameters, holds here, else `refusal` is the command's failure. */\n assert(\n condition: string,\n params: readonly unknown[],\n refusal: MigrationError\n ): void;\n /**\n * Resolves once the request committed, even when its reply was then\n * unreadable. Throws a `MigrationError` when the server refused (and rolled\n * back) the request; any other failure is a lost reply, after which the\n * request may have committed.\n */\n send(): Promise<void>;\n}\n\n/**\n * An assertion's refusal leaves its SQLSTATE (`P0V` + its position in base 36)\n * in a transaction-local setting, which this block raises: the SQLSTATE\n * survives diagnostics redaction where the message does not.\n */\nconst RAISE_REFUSAL = `DO $viborm$BEGIN IF current_setting('viborm.refusal') <> '' THEN RAISE EXCEPTION 'VibORM migration assertion %', current_setting('viborm.refusal') USING ERRCODE = current_setting('viborm.refusal'); END IF; END$viborm$`;\nconst REFUSAL = /^P0V([0-9A-Z]{2})$/;\n\nexport function openMigrationBatch(\n driver: AnyDriver,\n migrationDriver: BoundMigrationDriver\n): MigrationBatch {\n const queries: BatchQuery[] = [\n { sql: postgresSessionLimits(migrationDriver.limits).transaction },\n ];\n const refusals: MigrationError[] = [];\n const producer: AnyDriver = Object.create(driver);\n Object.defineProperty(producer, \"_executeRaw\", {\n value: (sql: string, params?: unknown[]) => {\n queries.push({ sql, params });\n return Promise.resolve({ rows: [], rowCount: 0 });\n },\n });\n const batch: MigrationBatch = {\n producer,\n assert(condition, params, refusal) {\n queries.push(\n {\n sql: `SELECT set_config('viborm.refusal', CASE WHEN ${condition} THEN '' ELSE 'P0V${refusals.length.toString(36).toUpperCase().padStart(2, \"0\")}' END, true)`,\n params: [...params],\n },\n { sql: RAISE_REFUSAL }\n );\n refusals.push(refusal);\n },\n async send() {\n let committed = false;\n try {\n await driver._executeBatch(queries, undefined, undefined, () => {\n committed = true;\n return Promise.resolve();\n });\n } catch (failure) {\n if (committed) return;\n if (!providerRefused(failure)) throw failure;\n const position = REFUSAL.exec(String(failure.meta.providerSqlState));\n const refusal = position && refusals[Number.parseInt(position[1]!, 36)];\n if (refusal) throw refusal;\n throw new MigrationError(\n \"The server refused the migration request, which rolled back: nothing of it was applied.\",\n VibORMErrorCode.MIGRATION_FAILED,\n {\n cause: failure,\n meta: { providerSqlState: failure.meta.providerSqlState },\n }\n );\n }\n },\n };\n batch.assert(\n `(SELECT acquired FROM (${migrationDriver.generateAcquireLock(MIGRATION_LOCK_ID)}) AS lock)`,\n [],\n lockNotConfirmed(migrationDriver)\n );\n return batch;\n}\n\n/**\n * What a pinned session runs under besides its body (plan S1): the bound on\n * its reservation, the PostgreSQL command's limits, and, for a driver whose\n * one connection IS the session (SQLite), that session.\n */\nexport interface PinnedSessionScope {\n readonly connectionWait: number;\n readonly limits?: PostgresSessionLimits | undefined;\n readonly session?: () => Promise<PinnedSessionReservation<unknown>>;\n}\n\n/** The statements that impose, lift and reset one PostgreSQL session's limits. */\ninterface PostgresSessionLimits {\n /** Which of the optional settings this server has, read before `enter`. */\n readonly settings: string;\n /** Imposes the limits on the session, naming only `present` settings. */\n enter(present: readonly string[]): string;\n /** Resets what `enter(present)` set, one constant `RESET` each. */\n exit(present: readonly string[]): readonly string[];\n readonly transaction: string;\n readonly unbound: string;\n readonly rebound: string;\n}\n\nconst DEFAULT_SCOPE: PinnedSessionScope = {\n connectionWait: DEFAULT_MIGRATION_LIMITS.connectionWait,\n};\n\n/**\n * Runs `body` against ONE reserved producer: this driver with its client\n * pinned to the reservation, so every statement, transactions included, runs\n * on one physical session (§3.5).\n *\n * The producer is discarded rather than released when the body throws or\n * condemns it; a LOST session is never written to again, and its failure\n * surfaces as the retryable connection error it is (plan S2).\n */\nexport async function withPinnedSession<D extends AnyDriver, T>(\n driver: D,\n body: (pinned: D, control: SessionControl) => Promise<T>,\n scope: PinnedSessionScope = DEFAULT_SCOPE\n): Promise<T> {\n const reserve = scope.session ?? driver[\"pinnedSession\"];\n if (reserve === undefined) {\n // A custom driver with no hook, or a view that IS a reserved session\n // (`createPinnedSessionView` withdraws the hook); admission refuses the\n // shipped paths earlier.\n throw new FeatureNotSupportedError(\n driver.driverName,\n \"pinnedSession\",\n \"No session can be reserved through this driver: either the transport has no interactive session at all, or this view is itself one reserved session and reserving again would take a SECOND connection. A migration lock is session-scoped, so either way it could be released by a different connection — or never released at all.\"\n );\n }\n\n const runSession = async (): Promise<T> => {\n // A server that accepts the socket and never answers is bounded here.\n const reservation = await settleWithin(\n reserve.call(driver),\n scope.connectionWait,\n () => connectionWaitError(driver.driverName, scope.connectionWait),\n (late) => {\n late.release(true).catch(() => undefined);\n }\n );\n const control = controlSession(driver, reservation);\n const { limits } = scope;\n const view = createPinnedSessionView(\n driver,\n reservation.session,\n control,\n limits\n );\n\n // Converted only when the failure IS the loss: a failure the command hit\n // first, whose cleanup then went unanswered, stays primary.\n const surface = (failure: unknown): unknown =>\n control.lost(failure, true)\n ? connectionLostError(driver.driverName, failure)\n : failure;\n\n // Limits a stepwise program set on the session must not go back to the\n // pool; a failed reset is RETURNED, so the release after it always runs.\n // A session whose reset failed still carries them: it is abandoned\n // (destroyed, never released to the pool) and the failure surfaces.\n const resetLimits = async (): Promise<unknown> => {\n const present = control.limited();\n if (limits === undefined || present === undefined || control.lost()) {\n return undefined;\n }\n try {\n await control.cleanup(async () => {\n for (const statement of limits.exit(present)) {\n await view._executeRaw(statement);\n }\n });\n return undefined;\n } catch (resetFailure) {\n const lostConnection = control.lost(resetFailure, true);\n control.abandon();\n return lostConnection\n ? resetFailure\n : limitsRefused(driver.driverName, \"reset\", resetFailure);\n }\n };\n\n // The first failure stays primary; later ones are recorded beside it.\n const releaseAfter = async (\n surfaced: unknown,\n resetFailure: unknown\n ): Promise<unknown> => {\n let failure =\n resetFailure === undefined\n ? surfaced\n : withSuppressedFailure(surfaced, resetFailure);\n try {\n await reservation.release(true, control.lost());\n } catch (releaseFailure) {\n failure = withSuppressedFailure(failure, releaseFailure);\n }\n return failure;\n };\n\n let value: T;\n try {\n value = await body(view, control);\n } catch (bodyFailure) {\n // Surfaced first: it is what tells the reset the session is lost.\n throw await releaseAfter(surface(bodyFailure), await resetLimits());\n }\n const resetFailure = await resetLimits();\n if (resetFailure !== undefined) {\n throw await releaseAfter(surface(resetFailure), undefined);\n }\n // Nothing else failed, so a release failure IS the failure.\n await reservation.release(control.discarded(), false);\n return value;\n };\n\n // A dedicated connection needs no lease: the real lock arbitrates.\n if (!driver[\"serializeTransactions\"]) {\n return runSession();\n }\n // A single-connection driver runs the whole session as ONE job of its queue\n // (§3.5): a narrower lease lets a second command in, and a PostgreSQL\n // session advisory lock is reentrant. A transaction-bound caller is refused\n // before the lease rather than waiting on its own holder.\n driver[\"assertBaseOperationAllowedDuringTransaction\"](\n driver[\"resolveExecutionContext\"](undefined, \"pinnedSession\")\n );\n const queue = driver[\"connectionQueue\"];\n const identify = driver[\"physicalPinnedSession\"];\n if (identify === undefined) {\n return queue.enqueue(runSession);\n }\n // The physical lease keeps ANOTHER driver over the same client out, and\n // refuses one whose advisory-lock state was condemned.\n const session = await identify.call(driver);\n return leasePinnedCommand(driver.driverName, session, () =>\n queue.enqueue(runSession)\n );\n}\n\n/** The control of one reserved session, and what it knows about its connection. */\ninterface SessionControl extends PinnedSessionControl {\n discarded(): boolean;\n lost(failure?: unknown, reported?: boolean): boolean;\n /** Sends nothing more on this session, whose state can no longer be made clean. */\n abandon(): void;\n /** Records that the session itself now carries the command's limits, with the optional settings `present`. */\n limit(present: readonly string[]): void;\n /** The optional settings it carries when it does, and so must be reset before it goes back. */\n limited(): readonly string[] | undefined;\n}\n\nfunction controlSession(\n driver: AnyDriver,\n reservation: PinnedSessionReservation<unknown>\n): SessionControl {\n let discarded = false;\n let lost = false;\n let limited: readonly string[] | undefined;\n const control = {\n discard: () => {\n discarded = true;\n },\n discarded: () => discarded,\n abandon: () => {\n lost = true;\n },\n limit: (present: readonly string[]) => {\n limited = present;\n },\n limited: () => limited,\n /** With `reported`, whether `failure` itself reports the loss. */\n lost: (failure?: unknown, reported = false) => {\n const reports =\n reservation.lost?.() !== undefined ||\n reportsLostConnection(driver, failure);\n lost ||= reports;\n return reported ? reports : lost;\n },\n cleanup: <R>(run: () => Promise<R>) =>\n settleWithin(run(), CLEANUP_BOUND_MS, () => {\n lost = true;\n return new ConnectionError(\n `A cleanup statement of the pinned migration session on driver \"${driver.driverName}\" went unanswered for ${CLEANUP_BOUND_MS} ms; its connection is treated as lost.`,\n {\n code: VibORMErrorCode.CONNECTION_TIMEOUT,\n meta: { driver: driver.driverName, operation: \"pinnedSession\" },\n }\n );\n }),\n };\n return control;\n}\n\n/**\n * Whether `failure`, or anything it was caused by, is the provider reporting\n * that the connection itself failed, by the driver error mapping's one\n * classifier.\n */\nfunction reportsLostConnection(driver: AnyDriver, failure: unknown): boolean {\n let link: unknown = failure;\n for (let depth = 0; depth < 8 && link instanceof Error; depth += 1) {\n const normalized =\n link instanceof VibORMError\n ? link\n : normalizeDriverError(link, {\n driverName: driver.driverName,\n dialect: driver.dialect,\n });\n if (normalized instanceof ConnectionError) return true;\n link = link.cause;\n }\n return false;\n}\n\n/**\n * The failure a command on a lost session surfaces: the provider's own report\n * when it already is a connection error or a migration outcome, otherwise a\n * retryable connection error carrying it (pg reports a dead socket as an\n * ordinary query failure).\n */\nfunction connectionLostError(driverName: string, failure: unknown): unknown {\n if (failure instanceof ConnectionError || failure instanceof MigrationError) {\n return failure;\n }\n return new ConnectionError(\n `The connection of the pinned migration session on driver \"${driverName}\" was lost. VibORM sent nothing more on it: the server rolls back its open transaction and frees its migration lock when that session ends. Run the command again; it re-reads the marker under the lock.`,\n {\n code: VibORMErrorCode.CONNECTION_FAILED,\n cause: errorCause(failure),\n meta: { driver: driverName, operation: \"pinnedSession\" },\n }\n );\n}\n\nfunction connectionWaitError(driverName: string, ms: number): ConnectionError {\n return new ConnectionError(\n `Driver \"${driverName}\" got no connection for the migration session within ${ms} ms (connectionWait). Nothing was sent; the command can be retried.`,\n {\n code: VibORMErrorCode.CONNECTION_TIMEOUT,\n meta: { driver: driverName, operation: \"pinnedSession\" },\n }\n );\n}\n\n/**\n * This driver, viewed with its client pinned to one reserved session: the\n * same driver in every other respect, with the transport assertion forwarded\n * exactly. Every statement it sends records a lost connection (plan S2).\n */\nfunction createPinnedSessionView<D extends AnyDriver>(\n driver: D,\n session: unknown,\n control: PinnedSessionControl,\n limits: PostgresSessionLimits | undefined\n): D {\n const view: D = Object.create(driver);\n const support = driver[\"transactionOptionSupport\"]();\n const executeRaw = driver[\"executeRaw\"];\n const beforeForeignKeysOff = driver[\"beforeForeignKeysOff\"];\n Object.defineProperties(view, {\n client: { value: session, writable: true },\n // A pinned view must never start a second connection.\n initPromise: { value: null, writable: true },\n // The view IS the queue's serialized job: waiting on the queue would wait\n // for its own holder.\n serializeTransactions: { value: false },\n // The view is the reservation, so it has none to give (§3.5): a nested\n // lock refuses instead of taking a second connection.\n pinnedSession: { value: undefined },\n // The provider's own `transaction()` acquires a connection.\n transaction: {\n value(\n this: AnyDriver,\n pinned: unknown,\n fn: (tx: unknown) => Promise<unknown>,\n context?: QueryExecutionContext\n ) {\n return runPinnedTransaction(this, pinned, fn, context, control, limits);\n },\n },\n executeRaw: {\n async value(\n this: AnyDriver,\n client: unknown,\n sql: string,\n params: unknown[] | undefined,\n context?: QueryExecutionContext\n ) {\n // Nothing more is sent on a lost connection (plan S2).\n if (control.lost())\n throw connectionLostError(driver.driverName, undefined);\n const locked = LOCKED.get(this);\n await locked?.before(sql);\n // A `CONCURRENTLY` statement runs without the session's limits, which\n // would cut it short: an INVALID index, a pending detach (plan S1).\n const send = (statement: string, parameters?: unknown[]) =>\n executeRaw.call(this, client, statement, parameters, context);\n const run = async () => {\n try {\n if (limits === undefined || !runsConcurrently(sql)) {\n return await send(sql, params);\n }\n await send(limits.unbound);\n const result = await send(sql, params);\n await send(limits.rebound);\n return result;\n } catch (failure) {\n control.lost(failure);\n throw failure;\n }\n };\n return locked === undefined\n ? run()\n : run().catch((failure: unknown) => locked.failed(failure));\n },\n },\n // The lease holds the queue for the whole session, so there is no queue\n // wait left to bound.\n transactionOptionSupport: {\n value: (): TransactionOptionSupport =>\n support.maxWait === \"queue\"\n ? {\n ...support,\n maxWait: \"unsupported\",\n maxWaitReason:\n \"the pinned session holds the connection queue's lease for its whole duration, so there is no queue wait to bound\",\n }\n : support,\n },\n migrationNamespaceAttestation: {\n value: driver.migrationNamespaceAttestation,\n },\n // The hook runs outside any transaction: a SQLite command's locked\n // transaction ends before it.\n beforeForeignKeysOff: {\n async value(this: AnyDriver) {\n await LOCKED.get(this)?.between();\n await beforeForeignKeysOff?.call(this);\n },\n },\n });\n return view;\n}\n\n/**\n * One transaction on the already-reserved session, as `BEGIN`/`COMMIT`/\n * `ROLLBACK` on that producer: under a lock the session already holds\n * (MySQL's, or a PostgreSQL stepwise program's), opening with the PostgreSQL\n * limits (plan S1), and sending no `ROLLBACK` after a lost connection (S2).\n */\nfunction runPinnedTransaction<T>(\n view: AnyDriver,\n session: unknown,\n fn: (tx: unknown) => Promise<T>,\n context: QueryExecutionContext | undefined,\n control: PinnedSessionControl,\n limits: PostgresSessionLimits | undefined\n): Promise<T> {\n const locked = LOCKED.get(view)?.group(() => fn(session));\n if (locked !== undefined) return locked;\n const statement = (sql: string) =>\n view[\"executeRaw\"](session, sql, undefined, context);\n return runTransactionLifecycle({\n begin: () => statement(\"BEGIN\"),\n // The session IS the transaction: a nested `$transaction` is a SAVEPOINT.\n callback: async () => {\n if (limits !== undefined) await statement(limits.transaction);\n return fn(session);\n },\n commit: () => statement(\"COMMIT\"),\n rollback: () =>\n control.lost() ? undefined : control.cleanup(() => statement(\"ROLLBACK\")),\n });\n}\n\n/**\n * Runs `body` on ONE reserved producer holding this estate's migration lock,\n * with the migration driver THIS command renders from (§5.2).\n *\n * MySQL holds a session lock for the whole command, and so does PostgreSQL\n * where the server mixes no session and transaction advisory locks\n * (`holdsSessionLock`, PlanetScale's Neki); PostgreSQL and SQLite otherwise\n * run it in locked transactions ({@link lockTransactions}); a batch transport\n * locks each request (plan D7). `unlocked` (PostgreSQL) runs first, before any\n * lock, for a decision one statement proves while no command holds the lock\n * (plan D5); a failure that is not the lost connection only means it could not\n * decide. It is not asked where the session lock is held alone: its proof\n * takes the transaction lock.\n */\nexport function withLockedMigrationProducer<T>(\n driver: AnyDriver,\n migrationDriver: BoundMigrationDriver,\n body: (pinned: AnyDriver, command: BoundMigrationDriver) => Promise<T>,\n unlocked?: (session: AnyDriver, lockFree: string) => Promise<T | undefined>\n): Promise<T> {\n const { dialect } = migrationDriver.target;\n const limits = migrationDriver.limits;\n const lockFree = migrationLockFree(migrationDriver);\n const run = async (producer: AnyDriver) =>\n body(\n producer,\n await validateAndSelectMigrationTarget(producer, migrationDriver)\n );\n const scope: PinnedSessionScope = {\n connectionWait: limits.connectionWait,\n limits:\n dialect === \"postgresql\" ? postgresSessionLimits(limits) : undefined,\n session:\n dialect === \"sqlite\"\n ? async () => ({\n session: await driver[\"getClient\"]({ operation: \"pinnedSession\" }),\n release: () => Promise.resolve(),\n })\n : undefined,\n };\n if (runsMigrationBatches(driver)) {\n return (async () => {\n const answer = await unlocked?.(driver, lockFree).catch(() => undefined);\n if (answer !== undefined) return answer;\n return run(driver);\n })();\n }\n if (dialect === \"mysql\") {\n return withPinnedSession(\n driver,\n async (pinned, control) => {\n // A lock never proven is not this session's to release (§3.5).\n await acquireLock(pinned, migrationDriver, control);\n let result: T;\n try {\n result = await run(pinned);\n } catch (error) {\n await releaseAfterFailure(pinned, migrationDriver, control, error);\n throw error;\n }\n await releaseLock(pinned, migrationDriver, control);\n return result;\n },\n scope\n );\n }\n return withPinnedSession(\n driver,\n async (pinned, control) => {\n // PlanetScale's Neki holds the session lock alone, for the whole\n // command; its decision is read under that lock, never before it.\n const holdsSession =\n dialect === \"postgresql\" &&\n (await migrationDriver.holdsSessionLock((sql, params) =>\n pinned._executeRaw(sql, params)\n ));\n try {\n const answer = holdsSession\n ? undefined\n : await unlocked?.(pinned, lockFree);\n if (answer !== undefined) return answer;\n } catch (failure) {\n if (control.lost(failure)) throw failure;\n }\n // An admitted SQLite driver without transactions runs under the\n // driver's queue lease alone.\n if (!pinned.supportsTransactions) return run(pinned);\n const locked = lockTransactions(\n pinned,\n migrationDriver,\n control,\n scope.limits\n );\n LOCKED.set(pinned, locked);\n let result: T;\n try {\n if (holdsSession) await locked.hold();\n result = await run(pinned);\n } catch (error) {\n await locked.abort(error);\n throw error;\n }\n await locked.finish();\n return result;\n },\n scope\n );\n}\n\n/**\n * The locked transactions one PostgreSQL or SQLite command runs in (plans D1,\n * S5), opened on demand before each statement: PostgreSQL `BEGIN`, its limits\n * and the bounded transaction lock; SQLite `BEGIN IMMEDIATE`. The first opens\n * before the namespace proof, so every decision is read under the lock.\n *\n * PostgreSQL stepwise work and `CONCURRENTLY` statements take the session lock\n * inside the open locked transaction, so the lock is never let go between the\n * decision and the work; where the command holds the session lock from its\n * start (`hold`, PlanetScale's Neki), no transaction lock is taken at all. SQLite's `PRAGMA foreign_keys` switch runs between\n * two transactions. A commit without the session lock lets the lock go, and\n * {@link lockedSinceDecision} is then false.\n */\ninterface LockedTransactions {\n /** Readies the session for one statement sent outside a group. */\n before(sql: string): Promise<void>;\n /** Ends what one statement's failure ended, then rethrows it. */\n failed(failure: unknown): Promise<never>;\n /** Runs one transactional group, or `undefined` once stepwise work took the session lock. */\n group<T>(fn: () => Promise<T>): Promise<T> | undefined;\n /** Marks the work about to run as stepwise (PostgreSQL). */\n stepwise(): void;\n /**\n * Takes the session lock alone, in autocommit, before the command's first\n * statement, waiting as `begin` does; the session's limits follow it\n * (PlanetScale's Neki). Every transaction after it is a plain one.\n */\n hold(): Promise<void>;\n /** Ends the open locked transaction: SQLite's pragma, a PostgreSQL bootstrap. */\n between(): Promise<void>;\n /** Whether the lock has been held without a gap since the first read. */\n continuous(): boolean;\n /** Ends a command that succeeded: commits, then releases the session lock. */\n finish(): Promise<void>;\n /** Ends a command that failed: rolls back, releases, never replaces `cause`. */\n abort(cause: unknown): Promise<void>;\n}\n\nconst LOCKED = new WeakMap<object, LockedTransactions>();\n\n/** The switch SQLite ignores inside a transaction; its read form runs anywhere. */\nconst FOREIGN_KEYS_SWITCH = /^\\s*PRAGMA\\s+foreign_keys\\s*=/i;\n\nfunction lockTransactions(\n pinned: AnyDriver,\n migrationDriver: BoundMigrationDriver,\n control: SessionControl,\n limits: PostgresSessionLimits | undefined\n): LockedTransactions {\n const sqlite = migrationDriver.target.dialect === \"sqlite\";\n // The protocol's own statements, on the same session, past `before`.\n const direct: AnyDriver = Object.create(pinned);\n const run = <T = Record<string, unknown>>(sql: string) =>\n direct._executeRaw<T>(sql);\n let open = false;\n let sessionLocked = false;\n // Held from the command's start (`hold`): each committed group still ends\n // `continuous`, so every group re-reads the marker as one under\n // transaction locks does, and Neki's split parts prove their attempt.\n let heldAlone = false;\n let armed = false;\n let continuous = true;\n let grouped = false;\n\n const rollback = async (): Promise<void> => {\n if (!open) return;\n open = false;\n continuous &&= sessionLocked && !heldAlone;\n if (control.lost()) return;\n await control.cleanup(() => run(\"ROLLBACK\"));\n };\n const commit = async (): Promise<void> => {\n await run(\"COMMIT\");\n open = false;\n continuous &&= sessionLocked && !heldAlone;\n };\n // SQLite's lock IS its BEGIN IMMEDIATE: `lockWait` bounds that one\n // statement's busy wait, then the connection's own timeout is restored.\n const beginImmediate = async (): Promise<void> => {\n const [own] = (await run<{ timeout: unknown }>(\"PRAGMA busy_timeout\")).rows;\n await run(`PRAGMA busy_timeout = ${migrationDriver.limits.lockWait}`);\n try {\n await run(\"BEGIN IMMEDIATE\");\n } finally {\n // Interpolated, so only an integer is written back.\n if (Number.isInteger(own?.timeout)) {\n await run(`PRAGMA busy_timeout = ${own?.timeout}`);\n }\n }\n };\n // A PostgreSQL transaction takes its limits and tries the lock in one\n // statement. A refused try waits outside any transaction, so the wait holds\n // no snapshot: another command's `CREATE INDEX CONCURRENTLY` under the\n // session lock would otherwise wait for this one to give up. Each jittered\n // pause doubles up to the cap and ends in one autocommit try, which lets go\n // of what it takes, until the lock is free or `lockWait` is spent.\n const lockFree = `${migrationLockFree(migrationDriver)} AS acquired`;\n const tryLock = sqlite ? null : `SELECT ${lockFree}`;\n const enter =\n limits === undefined ? tryLock : `${limits.transaction}, ${lockFree}`;\n // Each jittered pause doubles up to the cap; past `lockWait` the lock is\n // not held.\n const waiting = () => {\n const deadline = Date.now() + migrationDriver.limits.lockWait;\n let pause = LOCK_RETRY_MS;\n return async (): Promise<void> => {\n const left = deadline - Date.now();\n if (left <= 0) throw lockNotConfirmed(migrationDriver);\n const jittered = pause * (0.5 + Math.random() / 2);\n await new Promise((resolve) =>\n setTimeout(resolve, Math.min(left, jittered))\n );\n pause = Math.min(pause * 2, LOCK_RETRY_CAP_MS);\n };\n };\n const begin = async (): Promise<void> => {\n const wait = waiting();\n for (;;) {\n try {\n await (sqlite ? beginImmediate() : run(\"BEGIN\"));\n } catch (error) {\n // SQLite's lock IS its BEGIN IMMEDIATE: a busy database is a lock wait.\n if (!sqlite || control.lost(error)) throw error;\n throw lockStatementFailed(migrationDriver, error);\n }\n open = true;\n let held: boolean;\n try {\n held = await lockHeld(direct, migrationDriver, control, enter);\n } catch (error) {\n await rollback().catch((cleanup: unknown) => {\n throw withSuppressedFailure(error, cleanup);\n });\n throw error;\n }\n if (held) return;\n // Nothing was read under a lock never held: not a gap in `continuous`.\n open = false;\n await control.cleanup(() => run(\"ROLLBACK\"));\n do {\n await wait();\n } while (!(await lockHeld(direct, migrationDriver, control, tryLock)));\n }\n };\n const sessionLock = migrationDriver.generateSessionLock(MIGRATION_LOCK_ID);\n const imposeLimits = async (): Promise<void> => {\n if (limits === undefined) return;\n try {\n const { rows } = await run<{ name: unknown }>(limits.settings);\n const present = rows.flatMap(({ name }) =>\n typeof name === \"string\" ? [name] : []\n );\n await run(limits.enter(present));\n control.limit(present);\n } catch (failure) {\n if (control.lost(failure)) throw failure;\n throw limitsRefused(pinned.driverName, \"enter\", failure);\n }\n };\n // A transaction under the session lock held alone: its limits, no lock.\n const beginUnderSessionLock = async (): Promise<void> => {\n await run(\"BEGIN\");\n open = true;\n if (limits !== undefined) await run(limits.transaction);\n };\n const hold = async (): Promise<void> => {\n const wait = waiting();\n while (!(await lockHeld(direct, migrationDriver, control, sessionLock))) {\n await wait();\n }\n sessionLocked = true;\n heldAlone = true;\n await imposeLimits();\n };\n const escalate = async (): Promise<void> => {\n if (!open) await begin();\n await acquireLock(direct, migrationDriver, control, sessionLock);\n sessionLocked = true;\n armed = false;\n await imposeLimits();\n await commit();\n };\n\n const between = async (): Promise<void> => {\n if (open) await commit();\n };\n const abort = async (cause: unknown): Promise<void> => {\n // A failure that IS the lost connection: nothing more is sent (plan S2).\n control.lost(cause);\n try {\n await rollback();\n } catch (cleanup) {\n throw withSuppressedFailure(cause, cleanup);\n }\n if (sessionLocked) {\n await releaseAfterFailure(direct, migrationDriver, control, cause);\n }\n };\n\n return {\n async failed(failure) {\n if (!(sqlite || grouped || control.lost(failure))) {\n await rollback().catch((cleanup: unknown) => {\n throw withSuppressedFailure(failure, cleanup);\n });\n }\n throw failure;\n },\n async before(sql) {\n if (grouped || sessionLocked) return;\n if (sqlite && FOREIGN_KEYS_SWITCH.test(sql)) {\n await between();\n return;\n }\n if (!sqlite && (armed || runsConcurrently(sql))) {\n await escalate();\n return;\n }\n if (!open) await begin();\n },\n group(fn) {\n if (sessionLocked && !heldAlone) return undefined;\n return runTransactionLifecycle({\n begin: () => {\n if (open) return undefined;\n return heldAlone ? beginUnderSessionLock() : begin();\n },\n callback: async () => {\n grouped = true;\n try {\n return await fn();\n } finally {\n grouped = false;\n }\n },\n commit,\n rollback,\n });\n },\n stepwise() {\n armed = true;\n },\n hold,\n between,\n continuous: () => continuous,\n async finish() {\n if (open) {\n try {\n await commit();\n } catch (failure) {\n await abort(failure);\n throw failure;\n }\n }\n if (sessionLocked) await releaseLock(direct, migrationDriver, control);\n },\n abort,\n };\n}\n\n/**\n * Commits a PostgreSQL command's open locked transaction after a bootstrap,\n * before any statement writes the control tables: PlanetScale's Neki plans a\n * statement against the schema committed before its transaction, so a control\n * table created in the same one is not there for it. SQLite writes them in the\n * transaction that made them; MySQL commits each DDL as it runs. The next\n * statement opens another, and {@link lockedSinceDecision} is then false.\n */\nexport async function commitLockedTransaction(\n pinned: AnyDriver,\n command: BoundMigrationDriver\n): Promise<void> {\n if (command.target.dialect === \"postgresql\") {\n await LOCKED.get(pinned)?.between();\n }\n}\n\n/**\n * Ends the command's open locked transaction before the caller's own work,\n * such as a `resolve` callback, which no transaction waits on: past\n * `idleTimeout` PostgreSQL ends the session, and SQLite's `BEGIN IMMEDIATE`\n * holds every other writer. The next statement takes the lock again, and\n * {@link lockedSinceDecision} is then false.\n */\nexport async function letLockGo(pinned: AnyDriver): Promise<void> {\n await LOCKED.get(pinned)?.between();\n}\n\n/**\n * Whether `producer`'s command has held its migration lock without a gap since\n * it read its decision; always true on MySQL, which holds a session lock.\n */\nexport function lockedSinceDecision(producer: AnyDriver): boolean {\n return LOCKED.get(producer)?.continuous() ?? true;\n}\n\n/** The settings a session's limits set only where the server has them. */\nconst OPTIONAL_SESSION_SETTINGS = [\n \"idle_in_transaction_session_timeout\",\n \"idle_session_timeout\",\n \"client_connection_check_interval\",\n] as const;\n\n/**\n * The PostgreSQL statements behind one command's time limits (plan S1).\n *\n * Every migration transaction opens with its own `SET LOCAL` limits, which\n * leave with it (plan D1); the session carries them only while it holds the\n * session lock (stepwise work, or PlanetScale's Neki for the whole command),\n * and is `RESET` before it goes back. Every setting is named by a constant:\n * Neki refuses `set_config` with a computed name in a routine body (`42501`)\n * and a `set_config` over `pg_settings` rows (`NK013`). Which optional\n * settings the server has is read first (`settings`); the idle limits are\n * never set on PGlite, whose in-process backend hangs on either idle timer.\n */\nfunction postgresSessionLimits(\n limits: ResolvedMigrationLimits\n): PostgresSessionLimits {\n const bound = (lock: number, statement: number, local: boolean) =>\n `set_config('lock_timeout', '${lock}', ${local}), set_config('statement_timeout', '${statement}', ${local})`;\n const { lockTimeout, statementTimeout, idleTimeout } = limits;\n const set = (name: string, value: number) =>\n `, set_config('${name}', '${value}', false)`;\n return {\n settings: `SELECT name FROM pg_catalog.pg_settings WHERE name IN (${OPTIONAL_SESSION_SETTINGS.map((name) => `'${name}'`).join(\", \")}) AND pg_catalog.version() NOT LIKE '%emscripten%' ORDER BY name`,\n enter: (present) => {\n const idle = OPTIONAL_SESSION_SETTINGS.slice(0, 2)\n .filter((name) => present.includes(name))\n .map((name) => set(name, idleTimeout))\n .join(\"\");\n // Refused where the platform cannot check the socket, which is no\n // reason to refuse the command.\n const check = present.includes(\"client_connection_check_interval\")\n ? `\nBEGIN\nPERFORM set_config('client_connection_check_interval', '1000', false);\nEXCEPTION WHEN invalid_parameter_value THEN NULL;\nEND;`\n : \"\";\n return `DO $viborm_limits$BEGIN\nPERFORM ${bound(lockTimeout, statementTimeout, false)}${idle};${check}\nEND$viborm_limits$`;\n },\n exit: (present) =>\n [\"lock_timeout\", \"statement_timeout\", ...present].map(\n (name) => `RESET ${name}`\n ),\n // Repeated in each transaction under the session lock too: a migration's\n // own SQL may change the session's values.\n transaction: `SELECT ${bound(lockTimeout, statementTimeout, true)}, set_config('idle_in_transaction_session_timeout', CASE WHEN pg_catalog.version() LIKE '%emscripten%' THEN pg_catalog.current_setting('idle_in_transaction_session_timeout') ELSE '${idleTimeout}' END, true)`,\n unbound: `SELECT ${bound(0, 0, false)}`,\n rebound: `SELECT ${bound(lockTimeout, statementTimeout, false)}`,\n };\n}\n\n/**\n * The server refused to impose (`enter`) or reset (`reset`) the migration\n * session's limits: part of holding the session lock, so a lock failure\n * (V11005), named as itself rather than as the statement it preceded. A\n * session whose reset was refused is never returned to the pool.\n */\nfunction limitsRefused(\n driverName: string,\n step: \"enter\" | \"reset\",\n failure: unknown\n): MigrationError {\n const what =\n step === \"enter\"\n ? \"refused the migration session's time limits, so the command stopped there and its session lock was let go\"\n : \"refused to reset the migration session's time limits; the connection was closed rather than returned to the pool\";\n return new MigrationError(\n `Driver \"${driverName}\": the server ${what}.`,\n VibORMErrorCode.MIGRATION_LOCK_FAILED,\n {\n cause: errorCause(failure),\n meta: {\n driver: driverName,\n operation: \"pinnedSession\",\n ...providerFacts(failure),\n },\n }\n );\n}\n\n/**\n * Selects the live migration target on a pinned producer, if this dialect has\n * one: when the lock is taken and again before every relative artifact, since\n * a manual artifact may issue its own `USE` (§10).\n */\nexport async function selectMigrationTarget(\n pinned: AnyDriver,\n migrationDriver: BoundMigrationDriver\n): Promise<void> {\n const statement = migrationDriver.generateSelectTarget();\n if (statement === null) {\n return;\n }\n await pinned._executeRaw(statement);\n}\n\n/**\n * §5.3's step 2, once per locked session: the namespace proof (§3.3), the\n * target selection, then the dialect's own proof of the session.\n */\nasync function validateAndSelectMigrationTarget(\n pinned: AnyDriver,\n migrationDriver: BoundMigrationDriver\n): Promise<BoundMigrationDriver> {\n const command = await resolveCommandDriver(pinned, migrationDriver);\n await selectMigrationTarget(pinned, command);\n return command.proveSession((sql, params) => pinned._executeRaw(sql, params));\n}\n\n/**\n * The ONE owner of the migration driver a command renders from, after its\n * namespace proof (§5.2): on the dialect that resolves a command-local\n * spelling (MySQL), a frozen view carrying the server's own spelling, which\n * lives exactly as long as the command. Read-only commands reach it too.\n */\nexport async function resolveCommandDriver(\n producer: AnyDriver,\n migrationDriver: BoundMigrationDriver\n): Promise<BoundMigrationDriver> {\n const read: CatalogRead = (sql, params) => producer._executeRaw(sql, params);\n if (!readsCommandNamespace(migrationDriver)) {\n await migrationDriver.proveNamespaceExists(read);\n return migrationDriver;\n }\n\n const spelling = await migrationDriver.resolveCommandNamespace(read);\n const command: BoundMigrationDriver = Object.create(migrationDriver);\n Object.defineProperty(command, \"namespace\", {\n value: spelling,\n enumerable: true,\n });\n Object.freeze(command);\n return command;\n}\n\n/**\n * Whether a group of `transactional` work runs in a transaction on this\n * producer: never on MySQL, nor without transactions. Asked of each group\n * right before it runs, which is where a PostgreSQL command hears of stepwise\n * work and takes the session lock it needs (plan D1).\n */\nexport function mayWrapTransaction(\n producer: Pick<AnyDriver, \"supportsTransactions\">,\n dialect: string,\n transactional: boolean\n): boolean {\n if (!transactional) LOCKED.get(producer)?.stepwise();\n return transactional && dialect !== \"mysql\" && producer.supportsTransactions;\n}\n\n/**\n * Runs one program of a command, the one owner of how it runs: on MySQL as a\n * sequential program; else, given its `program`, in a transaction where\n * {@link mayWrapTransaction} admits one, SQLite's foreign-key pragmas lifted\n * around it (a recreation is refused where nothing can lift them), and\n * directly otherwise; without one, directly. `atomic` tells the body which.\n * `phase` records how far a transaction got: past its body and checks\n * (`committing`), past its COMMIT (`committed`), for a caller that classifies\n * a failure at COMMIT (plan S3).\n */\nexport async function runProgram<T>(\n pinned: AnyDriver,\n command: BoundMigrationDriver,\n program:\n | {\n readonly transactional: boolean;\n readonly statements: string[];\n readonly phase?: { committing: boolean; committed: boolean };\n }\n | undefined,\n body: (producer: AnyDriver, atomic: boolean) => Promise<T>\n): Promise<T> {\n const { dialect } = command.target;\n if (dialect === \"mysql\") {\n return runSequentialProgram(pinned, command, (producer) =>\n body(producer, false)\n );\n }\n if (!program) return body(pinned, false);\n const { bracket } = liftForeignKeyPragmas(pinned, program.statements);\n if (!mayWrapTransaction(pinned, dialect, program.transactional)) {\n return body(pinned, false);\n }\n const { phase } = program;\n return withForeignKeysLifted(pinned, bracket, async (inside) => {\n const result = await pinned.withTransaction(async (transaction) => {\n const value = await inside(transaction, (producer) =>\n body(producer, true)\n );\n if (phase) phase.committing = true;\n return value;\n });\n if (phase) phase.committed = true;\n return result;\n });\n}\n\n/**\n * Runs a MySQL sequential program on `producer`, after the command's\n * `programPreamble`, and reports the boundary it reached (§6.2, §6.3): MySQL\n * commits DDL as each statement runs, so a failure part-way through is the\n * partial commit it is, recorded by the producer the body runs on.\n */\nexport async function runSequentialProgram<T>(\n producer: AnyDriver,\n migrationDriver: BoundMigrationDriver,\n body: (recording: AnyDriver) => Promise<T>\n): Promise<T> {\n const preamble = await migrationDriver.programPreamble(producer);\n /** The last statement that RAN TO COMPLETION, which here IS committed. */\n let committed: string | undefined;\n const recording: AnyDriver = Object.create(producer);\n Object.defineProperty(recording, \"_executeRaw\", {\n value: async (sql: string, params?: unknown[]) => {\n const result = await producer._executeRaw(sql, params);\n committed = sql;\n return result;\n },\n });\n\n try {\n for (const statement of preamble) {\n await recording._executeRaw(statement);\n }\n return await body(recording);\n } catch (cause) {\n throw partialProgramFailure(cause, committed);\n }\n}\n\n/**\n * The honest report for a program that cannot be undone (§6.2, §6.3): the\n * last statement known to have completed, no claim of a rollback, and the\n * provider's failure as the cause.\n */\nfunction partialProgramFailure(\n cause: unknown,\n committed: string | undefined\n): MigrationError {\n const boundary =\n committed ?? \"(none — the failure came before any statement completed)\";\n return new MigrationError(\n \"This migration program failed partway through. MySQL commits DDL as each statement runs, so NOTHING was rolled back: every statement that completed stands, and VibORM makes no claim about whether the statement that failed took effect. \" +\n `The last statement that completed was: ${boundary}. ` +\n \"Estate artifacts and the control plane were not rewritten as a successful apply — fix the cause and re-run.\",\n VibORMErrorCode.MIGRATION_PARTIAL_EFFECT,\n { cause: errorCause(cause), meta: providerFacts(cause) }\n );\n}\n\n/**\n * Acquires the lock and PROVES it. The target is selected after the lock\n * (§5.3), by the caller's scope that releases.\n */\nasync function acquireLock(\n pinned: AnyDriver,\n migrationDriver: BoundMigrationDriver,\n control: PinnedSessionControl,\n statement = migrationDriver.generateAcquireLock(MIGRATION_LOCK_ID)\n): Promise<void> {\n if (!(await lockHeld(pinned, migrationDriver, control, statement))) {\n throw lockNotConfirmed(migrationDriver);\n }\n}\n\n/** Runs one lock statement: whether the provider proved the lock held. */\nasync function lockHeld(\n pinned: AnyDriver,\n migrationDriver: BoundMigrationDriver,\n control: PinnedSessionControl,\n statement: string | null\n): Promise<boolean> {\n if (statement === null) {\n return true;\n }\n\n const executor = createQueryExecutor(pinned);\n let rows: unknown[];\n try {\n rows = await executor(statement);\n } catch (error) {\n // A lost connection is retryable, not a lock failure.\n if (control.lost(error)) throw error;\n throw lockStatementFailed(migrationDriver, error);\n }\n return migrationDriver.provesLockAcquired(rows);\n}\n\nfunction lockNotConfirmed(\n migrationDriver: BoundMigrationDriver\n): MigrationError {\n return new MigrationError(\n `Failed to acquire the migration lock for ${describeEstate(migrationDriver)}: the provider did not confirm the lock. ` +\n \"A wait that timed out, an error, or a malformed answer all mean the lock is NOT held; VibORM will not run migration work on that assumption.\",\n VibORMErrorCode.MIGRATION_LOCK_FAILED\n );\n}\n\nfunction lockStatementFailed(\n migrationDriver: BoundMigrationDriver,\n error: unknown\n): MigrationError {\n return new MigrationError(\n `Failed to acquire the migration lock for ${describeEstate(migrationDriver)}: the lock statement itself failed.`,\n VibORMErrorCode.MIGRATION_LOCK_FAILED,\n { cause: errorCause(error), meta: providerFacts(error) }\n );\n}\n\n/**\n * Releases the lock after the protected work FAILED: the release still runs\n * and its own failure is recorded beside `cause` (§3.5), never replacing it.\n * A lost session holds no lock to release (plan S2).\n */\nasync function releaseAfterFailure(\n pinned: AnyDriver,\n migrationDriver: BoundMigrationDriver,\n control: PinnedSessionControl,\n cause: unknown\n): Promise<void> {\n if (control.lost(cause)) return;\n try {\n await releaseLock(pinned, migrationDriver, control);\n } catch (releaseFailure) {\n throw withSuppressedFailure(cause, releaseFailure);\n }\n}\n\n/**\n * Releases the lock and PROVES the release, through the driver the command\n * was GIVEN (only it names the lock acquired); an unproven release condemns\n * the producer.\n */\nasync function releaseLock(\n pinned: AnyDriver,\n migrationDriver: BoundMigrationDriver,\n control: PinnedSessionControl\n): Promise<void> {\n const statement = migrationDriver.generateReleaseLock(MIGRATION_LOCK_ID);\n if (statement === null) {\n return;\n }\n\n const executor = createQueryExecutor(pinned);\n let rows: unknown[];\n try {\n rows = await control.cleanup(() => executor(statement));\n } catch (error) {\n control.discard();\n if (control.lost(error)) throw error;\n throw new MigrationError(\n `Failed to release the migration lock for ${describeEstate(migrationDriver)}. The pinned session was discarded rather than returned to the pool.`,\n VibORMErrorCode.MIGRATION_LOCK_FAILED,\n { cause: errorCause(error), meta: providerFacts(error) }\n );\n }\n\n if (!migrationDriver.provesLockReleased(rows)) {\n control.discard();\n throw new MigrationError(\n `Failed to release the migration lock for ${describeEstate(migrationDriver)}: the provider did not confirm the release. The pinned session was discarded rather than returned to the pool, so the lock cannot outlive the connection.`,\n VibORMErrorCode.MIGRATION_LOCK_FAILED\n );\n }\n}\n\n/** The estate a lock failure is about. */\nfunction describeEstate(migrationDriver: BoundMigrationDriver): string {\n const { target } = migrationDriver;\n if (target.dialect === \"sqlite\") return \"the SQLite database\";\n return target.dialect === \"postgresql\"\n ? `schema \"${target.namespace}\"`\n : `database \"${migrationDriver.namespace ?? \"(unbound)\"}\"`;\n}\n","import { readArrayLiteralText } from \"../adapters/databases/postgres/array-literal\";\nimport { sqliteGeoPointEncoding } from \"../adapters/databases/sqlite/storage/geo-point\";\nimport { decodeProviderTimestamp } from \"../validation/primitives/datetime-physical-codec\";\n/**\n * Live schema fingerprint and push target identity.\n *\n * The target identity names the database itself (dialect, database and\n * namespace), never a client instance: a consent previewed by one client is\n * replayed by any other on the same database, and the plan hash it carries\n * still binds it to the exact live fingerprint and statements. This module\n * hashes the snapshot it is given; callers strip control tables before\n * fingerprinting.\n */\n\nimport type { AnyDriver } from \"../drivers/driver\";\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\nimport { isRecord } from \"../validation/value-guards\";\nimport { canonicalizeJson, canonicalizeJsonText } from \"./canonical-json\";\nimport type { IndexPredicateCanonicalizer } from \"./differ\";\nimport type { BoundMigrationDriver, MigrationDriver } from \"./drivers\";\nimport { domainHash, HASH_DOMAIN, type Sha256 } from \"./identity\";\nimport { canPinSession, runsMigrationBatches } from \"./pinned-session\";\nimport type { SchemaSnapshot, TableDef } from \"./types\";\nimport { encodeSnapshot } from \"./v1-parse-snapshot\";\nimport type { MarkerIndexPredicateV1, PushTargetIdentity } from \"./v1-types\";\n\nexport async function pushTargetIdentity(\n producer: AnyDriver,\n driver: BoundMigrationDriver\n): Promise<PushTargetIdentity> {\n if (driver.target.dialect === \"postgresql\") {\n const result = await producer._executeRaw<{ database: unknown }>(\n \"SELECT current_database() AS database\"\n );\n const database = result.rows[0]?.database;\n if (typeof database !== \"string\" || database.length === 0) {\n throw new MigrationError(\n \"PostgreSQL did not return its current database identity\",\n VibORMErrorCode.MIGRATION_INVALID_STATE\n );\n }\n return {\n dialect: \"postgresql\",\n database,\n namespace: driver.namespace ?? driver.target.namespace,\n };\n }\n if (driver.target.dialect === \"mysql\") {\n if (!driver.namespace) {\n throw new MigrationError(\n \"MySQL push has no resolved database identity\",\n VibORMErrorCode.MIGRATION_INVALID_STATE\n );\n }\n return {\n dialect: \"mysql\",\n database: driver.namespace,\n };\n }\n return { dialect: \"sqlite\", location: null };\n}\n\nexport function hashSnapshot(snapshot: SchemaSnapshot): Sha256 {\n return encodeSnapshot(snapshot).snapshotHash;\n}\n\nexport function bindIndexPredicateCanonicalizer(\n producer: AnyDriver,\n driver: MigrationDriver\n): IndexPredicateCanonicalizer | undefined {\n const canonicalize = driver.canonicalizeIndexPredicates;\n if (!canonicalize) return;\n return async (tableName, predicates) => {\n const run = (on: AnyDriver) =>\n canonicalize.call(\n driver,\n tableName,\n predicates,\n (sql, params) => on._executeRaw(sql, params),\n runsMigrationBatches(on)\n ? <T>(statements: readonly string[]) =>\n on._executeBatch<T>(statements.map((sql) => ({ sql })))\n : undefined\n );\n try {\n // Its scratch views exist only inside their transaction, so on a\n // pool, or behind a transaction pooler, its statements share one. A\n // locked command's pinned producer is already inside one (plan D1).\n // With no session at all, each pass is one request (plan D7).\n return await (canPinSession(producer) && producer.supportsTransactions\n ? producer.withTransaction(run)\n : run(producer));\n } catch {\n return predicates.map(() => undefined);\n }\n };\n}\n\nexport async function canonicalizeSnapshotPredicates(\n snapshot: SchemaSnapshot,\n canonicalize: IndexPredicateCanonicalizer | undefined\n): Promise<SchemaSnapshot> {\n if (!canonicalize) return snapshot;\n const tables: TableDef[] = [];\n for (const table of snapshot.tables) {\n const pending = table.indexes.filter((index) => index.where);\n if (pending.length === 0) {\n tables.push(table);\n continue;\n }\n const predicates = pending.map((index) => index.where!);\n const spellings = await canonicalize(table.name, predicates);\n let next = 0;\n tables.push({\n ...table,\n indexes: table.indexes.map((index) => {\n if (!index.where) return index;\n const spelling = spellings[next++];\n return spelling === undefined ? index : { ...index, where: spelling };\n }),\n });\n }\n return { ...snapshot, tables };\n}\n\nexport async function fingerprintLive(\n snapshot: SchemaSnapshot,\n driver: MigrationDriver,\n producer: AnyDriver\n): Promise<Sha256> {\n return fingerprintSnapshot(\n await canonicalizeSnapshotPredicates(\n snapshot,\n bindIndexPredicateCanonicalizer(producer, driver)\n ),\n driver\n );\n}\n\n/**\n * `fingerprintSnapshot` with each partial-index predicate as PostgreSQL\n * deparsed it, from the record beside the marker: what the catalog digest\n * hashes when it reads predicates as deparsed. `undefined` when the record\n * lacks one of them.\n */\nexport function fingerprintDeparsed(\n snapshot: SchemaSnapshot,\n predicates: readonly MarkerIndexPredicateV1[],\n driver: MigrationDriver\n): Sha256 | undefined {\n let recorded = true;\n const tables = snapshot.tables.map((table) => ({\n ...table,\n indexes: table.indexes.map((index) => {\n if (!index.where) return index;\n const where = predicates.find(\n (record) => record.table === table.name && record.index === index.name\n )?.deparsed;\n recorded &&= where !== undefined;\n return { ...index, where };\n }),\n }));\n return recorded\n ? fingerprintSnapshot({ ...snapshot, tables }, driver)\n : undefined;\n}\n\nexport function fingerprintSnapshot(\n snapshot: SchemaSnapshot,\n driver: MigrationDriver\n): Sha256 {\n const tables = canonicalUniqueEntities(snapshot)\n .tables.map((table) => ({\n name: table.name,\n columns: table.columns\n .map((column) => ({\n name: column.name,\n type: normalizeType(column.type),\n nullable: column.nullable,\n default: normalizeDefault(column.default, column.type) ?? null,\n autoIncrement: column.autoIncrement ?? false,\n ...(sqliteGeoPointEncoding(column)\n ? { geoPointEncoding: sqliteGeoPointEncoding(column) }\n : {}),\n }))\n .sort(byName),\n primaryKey: table.primaryKey\n ? {\n columns: table.primaryKey.columns,\n ...(driver.dialect === \"postgresql\"\n ? { name: table.primaryKey.name || `${table.name}_pkey` }\n : {}),\n }\n : null,\n indexes: table.indexes\n .map((index) => ({\n name: index.name,\n columns: index.columns,\n unique: index.unique ?? false,\n type: index.type ?? \"btree\",\n where: index.where?.trim() || null,\n }))\n .sort(byName),\n foreignKeys: table.foreignKeys\n .map((foreignKey) => ({\n name: driver.capabilities.introspectionReadsConstraintNames\n ? foreignKey.name\n : null,\n columns: foreignKey.columns,\n referencedTable: foreignKey.referencedTable,\n referencedColumns: foreignKey.referencedColumns,\n onDelete: foreignKey.onDelete ?? \"noAction\",\n onUpdate: foreignKey.onUpdate ?? \"noAction\",\n }))\n .sort(byCanonicalValue),\n uniqueConstraints: table.uniqueConstraints\n .map((constraint) => ({\n name: driver.capabilities.introspectionReadsConstraintNames\n ? constraint.name\n : null,\n columns: constraint.columns,\n }))\n .sort(byCanonicalValue),\n }))\n .sort(byName);\n const enums = [...(snapshot.enums ?? [])]\n .map((item) => ({ name: item.name, values: item.values }))\n .sort(byName);\n return domainHash(HASH_DOMAIN.snapshot, canonicalizeJson({ tables, enums }));\n}\n\n/** A total btree unique index and a unique constraint enforce the same key. */\nexport function canonicalUniqueEntities(\n snapshot: SchemaSnapshot\n): SchemaSnapshot {\n return {\n ...snapshot,\n tables: snapshot.tables.map((table) => ({\n ...table,\n uniqueConstraints: [\n ...table.uniqueConstraints,\n ...table.indexes\n .filter(\n (index) =>\n index.unique &&\n !index.where &&\n (!index.type || index.type === \"btree\")\n )\n .map((index) => ({ name: index.name, columns: index.columns })),\n ],\n indexes: table.indexes.filter(\n (index) =>\n !(\n index.unique &&\n !index.where &&\n (!index.type || index.type === \"btree\")\n )\n ),\n })),\n };\n}\n\nexport function normalizeType(type: string): string {\n const tokens =\n type.trim().match(/'(?:[^']|'')*'|\"(?:[^\"]|\"\")*\"|[^'\"]+/g) ?? [];\n return tokens\n .map((token) => {\n if (token.startsWith(\"'\") || token.startsWith('\"')) return token;\n return token\n .toLowerCase()\n .replace(/\\s+/g, \" \")\n .replace(/\\s*,\\s*/g, \",\")\n .replace(/\\s+\\[\\]/g, \"[]\")\n .replace(/\\bcharacter varying\\b/g, \"varchar\")\n .replace(/\\bcharacter\\b/g, \"char\")\n .replace(/\\bbit varying\\b/g, \"varbit\")\n .replace(/\\btimestamptz(\\(\\d+\\))?/g, \"timestamp$1 with time zone\")\n .replace(/\\btimetz(\\(\\d+\\))?/g, \"time$1 with time zone\")\n .replace(/\\b(timestamp|time)(\\(\\d+\\))? without time zone/g, \"$1$2\")\n .replace(/\\bint4\\b/g, \"integer\")\n .replace(/\\bint8\\b/g, \"bigint\")\n .replace(/\\bint2\\b/g, \"smallint\")\n .replace(/\\bfloat4\\b/g, \"real\")\n .replace(/\\bfloat8\\b/g, \"double precision\")\n .replace(/\\bbool\\b/g, \"boolean\");\n })\n .join(\"\");\n}\n\nconst UTC_NOW_DEFAULT =\n /^(?:now\\(\\) at time zone 'utc'|timezone\\(\\s*'utc'\\s*,\\s*now\\(\\)\\s*\\))$/;\nconst MILLISECOND_NOW_DEFAULT =\n /^date_trunc\\(\\s*'milliseconds'\\s*,([\\s\\S]+)\\)$/;\nconst UTC_CURRENT_TIME_DEFAULT =\n /^timezone\\(\\s*'utc'\\s*,\\s*current_time(?:\\(3\\))?\\s*\\)$/;\nconst NUMERIC_PHYSICAL_TYPE =\n /^(integer|bigint|smallint|real|double precision|float|int|tinyint)/;\nconst INTEGER_PHYSICAL_TYPE = /^(integer|bigint|smallint|int|tinyint)/;\nconst INTEGER_LITERAL = /^[-+]?\\d+$/;\nconst TEMPORAL_PHYSICAL_TYPE = /^(timestamp|time|date)/;\nconst ISO_UTC_SUFFIX = /Z$/;\nconst TEMPORAL_UTC_SUFFIX = /(?:Z|[+]00(?::00)?)$/;\nconst MINUTE_CLOCK_SUFFIX = /(^| )(\\d{2}:\\d{2})(?=$|[+-])/;\nconst TRAILING_FRACTION_ZEROES = /(\\.\\d*?)0+(?=$|[+-])/;\nconst EMPTY_FRACTION = /\\.(?=$|[+-])/;\nconst BARE_FUNCTION_DEFAULT = /^[a-z_][a-z0-9_]*\\(\\)$/;\nconst NUMBER_LITERAL = /^[+-]?(?:\\d+(?:\\.\\d*)?|\\.\\d+)(?:e[+-]?\\d+)?$/i;\n\nfunction stripDefaultParentheses(value: string): string {\n let text = value.trim();\n while (text.startsWith(\"(\") && text.endsWith(\")\")) {\n const structural = text.replace(\n /'(?:[^']|'')*'|\"(?:[^\"]|\"\")*\"/g,\n (literal) => \" \".repeat(literal.length)\n );\n let depth = 0;\n let whole = true;\n for (let index = 0; index < structural.length; index++) {\n if (structural[index] === \"(\") depth++;\n else if (structural[index] === \")\") depth--;\n if (depth === 0 && index < structural.length - 1) {\n whole = false;\n break;\n }\n }\n if (!whole || depth !== 0) break;\n text = text.slice(1, -1).trim();\n }\n return text;\n}\n\nexport function normalizeDefault(\n value: string | undefined,\n type?: string\n): string | undefined {\n if (value === undefined) return;\n const spelling = stripDefaultParentheses(value);\n const normalized = spelling.toLowerCase();\n if (normalized === \"null\") return;\n const utcNow = normalized\n .replaceAll(\"::text\", \"\")\n .replaceAll(\"current_timestamp\", \"now()\");\n if (UTC_NOW_DEFAULT.test(utcNow)) return \"now() at time zone 'utc'\";\n const truncated = MILLISECOND_NOW_DEFAULT.exec(utcNow);\n if (truncated?.[1]) {\n const clock = normalizeDefault(truncated[1], type);\n if (clock === \"now()\" || clock === \"now() at time zone 'utc'\")\n return `date_trunc('milliseconds',${clock})`;\n }\n if (UTC_CURRENT_TIME_DEFAULT.test(utcNow))\n return utcNow.includes(\"current_time(3)\")\n ? \"timezone('utc',current_time(3))\"\n : \"timezone('utc',current_time)\";\n if (normalized === \"current_timestamp\" || normalized === \"now()\")\n return \"now()\";\n const boolean = type === undefined || normalizeType(type) === \"boolean\";\n if (\n boolean &&\n (normalized === \"true\" || normalized === \"'t'\" || normalized === \"1\")\n )\n return \"true\";\n if (\n boolean &&\n (normalized === \"false\" || normalized === \"'f'\" || normalized === \"0\")\n )\n return \"false\";\n if (BARE_FUNCTION_DEFAULT.test(normalized)) return normalized;\n const unquoted =\n normalized.startsWith(\"'\") && normalized.endsWith(\"'\")\n ? normalized.slice(1, -1)\n : normalized;\n const physical = type === undefined ? \"\" : normalizeType(type);\n if (spelling.startsWith(\"'\") && spelling.endsWith(\"'\")) {\n const literal = spelling.slice(1, -1).replaceAll(\"''\", \"'\");\n if (physical.endsWith(\"[]\")) {\n const values = readArrayLiteralText(literal);\n if (values)\n return canonicalizeJsonText(\n values.map((value) =>\n value === null\n ? null\n : normalizeDefault(\n `'${(physical.slice(0, -2) === \"boolean\" && (value === \"t\" || value === \"f\") ? (value === \"t\" ? \"true\" : \"false\") : value).replaceAll(\"'\", \"''\")}'`,\n physical.slice(0, -2)\n )\n )\n );\n }\n if (physical === \"json\" || physical === \"jsonb\") {\n try {\n return canonicalizeJsonText(JSON.parse(literal));\n } catch {\n /* A SQL expression is not a JSON document literal. */\n }\n }\n }\n if (NUMERIC_PHYSICAL_TYPE.test(physical) && NUMBER_LITERAL.test(unquoted)) {\n // BigInt keeps integer columns exact; a float catalog spells 1e21 as\n // '1000000000000000000000', which only Number() reads back as 1e+21.\n return INTEGER_PHYSICAL_TYPE.test(physical) &&\n INTEGER_LITERAL.test(unquoted)\n ? BigInt(unquoted).toString()\n : String(Number(unquoted));\n }\n if (\n TEMPORAL_PHYSICAL_TYPE.test(physical) &&\n spelling.startsWith(\"'\") &&\n spelling.endsWith(\"'\")\n ) {\n let temporal = spelling\n .slice(1, -1)\n .replace(\"T\", \" \")\n .replace(ISO_UTC_SUFFIX, \"+00:00\");\n const era = temporal.endsWith(\" BC\") ? \" BC\" : \"\";\n if (era) temporal = temporal.slice(0, -3);\n if (\n physical.includes(\"with time zone\") &&\n physical.startsWith(\"timestamp\")\n ) {\n const instant = decodeProviderTimestamp(`${temporal}${era}`);\n if (instant) return instant.toISOString();\n }\n temporal = temporal\n .replace(TEMPORAL_UTC_SUFFIX, \"\")\n .replace(MINUTE_CLOCK_SUFFIX, \"$1$2:00\")\n .replace(TRAILING_FRACTION_ZEROES, \"$1\")\n .replace(EMPTY_FRACTION, \"\");\n return `${temporal}${era}`;\n }\n return spelling;\n}\n\nexport function canonicalValue(value: unknown): unknown {\n if (Array.isArray(value)) {\n return value.map((item) => canonicalValue(item));\n }\n if (isRecord(value)) {\n const result: Record<string, unknown> = {};\n for (const [key, item] of Object.entries(value)) {\n if (item !== undefined) result[key] = canonicalValue(item);\n }\n return result;\n }\n return value;\n}\n\nexport function freezeDeep<T>(value: T): T {\n if (typeof value !== \"object\" || value === null) return value;\n if (ArrayBuffer.isView(value)) return value;\n for (const member of Object.values(value)) freezeDeep(member);\n return Object.freeze(value);\n}\n\nfunction byName(\n left: { readonly name: string },\n right: { readonly name: string }\n): number {\n return left.name < right.name ? -1 : left.name > right.name ? 1 : 0;\n}\n\nfunction byCanonicalValue(left: unknown, right: unknown): number {\n const a = canonicalizeJsonText(left);\n const b = canonicalizeJsonText(right);\n return a < b ? -1 : a > b ? 1 : 0;\n}\n","/**\n * How a refused PostgreSQL catalog read is reported. Apart from\n * introspection, so the shared control-table read (`control.ts`) brings no\n * PostgreSQL introspection into another dialect's bundle.\n */\n\nimport { MigrationError, VibORMErrorCode } from \"../../../errors\";\nimport { providerRefused } from \"../../execute-dispatch\";\n\n/**\n * A catalog read the provider refused, thrown named with its SQLSTATE: a\n * server that speaks PostgreSQL but not all of its catalog SQL (PlanetScale's\n * Neki) must say which read it refused, not that the estate is wrong. The\n * server's own text stays in the cause, disclosed as the driver's diagnostics\n * allow. A transport failure is not a refusal, nor is a migration error\n * already named: the caller handles them.\n */\nexport function throwIfCatalogRefusal(query: string, error: unknown): void {\n // A migration outcome raised before the read was sent (the lock protocol's\n // own statements, such as the session's limits) is not the read's refusal.\n if (!providerRefused(error) || error instanceof MigrationError) return;\n const { providerCode, providerSqlState } = error.meta;\n throw new MigrationError(\n `PostgreSQL catalog query \"${query}\" failed with SQLSTATE ${String(providerSqlState ?? providerCode)}: ${error.message}`,\n VibORMErrorCode.MIGRATION_FAILED,\n { cause: error, meta: { providerCode, providerSqlState } }\n );\n}\n","import { normalizeType } from \"./push-fingerprint\";\n/**\n * Marker and ledger control tables: one reserved pair.\n * Read-only commands never bootstrap. Parsers in v1-parse own row truth.\n */\n\nimport type { AnyDriver } from \"../drivers/driver\";\nimport { isRetryableError, MigrationError, VibORMErrorCode } from \"../errors\";\nimport { errorCause } from \"../errors/diagnostic-safety\";\nimport { isRecord } from \"../validation/value-guards\";\nimport { canonicalizeJsonText } from \"./canonical-json\";\nimport {\n boundNamespace,\n qualifiedName,\n tableExistsProbe,\n} from \"./catalog-probes\";\nimport type { BoundMigrationDriver } from \"./drivers\";\nimport { throwIfCatalogRefusal } from \"./drivers/postgres/catalog-refusal\";\nimport { providerFacts } from \"./execute-dispatch\";\nimport { isSha256, type Sha256 } from \"./identity\";\nimport type { SchemaSnapshot, TableDef } from \"./types\";\nimport { encodePathHash, eventIdFor, parseLedgerEvent } from \"./v1-parse\";\nimport { parseMarkerPayload } from \"./v1-parse-control\";\nimport { readFlag } from \"./v1-parse-shared\";\nimport type {\n LedgerEventV1,\n MarkerIndexPredicateV1,\n MigrationMarkerV1,\n} from \"./v1-types\";\n\n/** The reserved control pair: the marker's table and the ledger's. */\nexport const CONTROL_TABLES: { readonly state: string; readonly log: string } =\n Object.freeze({\n state: \"_viborm_migration_state\",\n log: \"_viborm_migration_log\",\n });\n\nconst CHECK_PREFIX = /^\\s*check\\s*/i;\nconst CHECK_FORMATTING = /[\\s()\"`]/g;\n\nexport type ControlPresence =\n | { readonly kind: \"missing-table\"; readonly table: \"state\" | \"log\" | \"both\" }\n | { readonly kind: \"recoverable-state-only\" }\n | { readonly kind: \"present\" };\n\nfunction placeholder(\n dialect: BoundMigrationDriver[\"target\"][\"dialect\"],\n index: number\n): string {\n return dialect === \"postgresql\" ? `$${index}` : \"?\";\n}\n\ntype ControlTable = keyof typeof CONTROL_TABLES;\n\n/**\n * The one declaration of a control table: its columns, primary key first,\n * with the types VibORM's DDL spells.\n */\nfunction controlColumns(\n dialect: BoundMigrationDriver[\"target\"][\"dialect\"],\n table: ControlTable\n): readonly (readonly [name: string, type: string])[] {\n if (table === \"state\") {\n return [\n [\"singleton\", \"INTEGER\"],\n [\"payload\", \"TEXT\"],\n ];\n }\n const id = dialect === \"mysql\" ? \"VARCHAR(64)\" : \"TEXT\";\n return [\n [\"event_id\", id],\n [\"attempt_id\", id],\n [\"kind\", dialect === \"mysql\" ? \"VARCHAR(32)\" : \"TEXT\"],\n [\"payload\", \"TEXT\"],\n ];\n}\n\n/** The parenthesized definition `CREATE TABLE` writes for one control table. */\nfunction controlDefinition(\n dialect: BoundMigrationDriver[\"target\"][\"dialect\"],\n table: ControlTable\n): string {\n const check = table === \"state\" ? \" CHECK (singleton = 1)\" : \"\";\n const columns = controlColumns(dialect, table).map(([name, type], index) =>\n index === 0\n ? `${name} ${type} PRIMARY KEY${check}`\n : `${name} ${type} NOT NULL`\n );\n return `(\\n ${columns.join(\",\\n \")}\\n )`;\n}\n\n/** Exact writer-owned state definition; the control owner authenticates its contents separately. */\nexport function isSqliteStateControlDefinition(\n name: string,\n sql: string | null\n): boolean {\n return (\n name === CONTROL_TABLES.state &&\n sql !== null &&\n sqliteDefinitionBody(sql) ===\n sqliteDefinitionBody(controlDefinition(\"sqlite\", \"state\"))\n );\n}\n\nexport function createControlTableSQL(driver: BoundMigrationDriver): {\n state: string;\n log: string;\n} {\n const create = (table: ControlTable) =>\n `CREATE TABLE IF NOT EXISTS ${qualifiedName(driver, CONTROL_TABLES[table])} ${controlDefinition(driver.target.dialect, table)}`;\n return { state: create(\"state\"), log: create(\"log\") };\n}\n\nexport function refusePartialControl(presence: ControlPresence): void {\n if (presence.kind === \"recoverable-state-only\") {\n throw new MigrationError(\n \"Migration control tables are inconsistent: log is missing after interrupted bootstrap\",\n VibORMErrorCode.MIGRATION_INVALID_STATE\n );\n }\n if (presence.kind === \"missing-table\" && presence.table !== \"both\") {\n throw new MigrationError(\n `Migration control tables are inconsistent: ${presence.table} is missing`,\n VibORMErrorCode.MIGRATION_INVALID_STATE\n );\n }\n}\n\n/** The events of attempts that never reached a state. */\nconst CLOSED_WITHOUT_STATE: ReadonlySet<LedgerEventV1[\"kind\"]> = new Set([\n \"started\",\n \"step-confirmed\",\n \"failed\",\n \"rolled-back\",\n \"resolved\",\n]);\n\n/**\n * Without a marker, history may only hold attempts closed by `failed`,\n * `rolled-back` or `resolved`, so `apply` can start again (plan S4). An\n * unfinished attempt is its caller's refusal.\n */\nexport function refuseIncompatibleHistory(\n marker: MigrationMarkerV1 | null,\n ledger: readonly LedgerEventV1[]\n): void {\n if (marker !== null) return;\n if (unfinishedAttempts(ledger).length > 0) return;\n if (ledger.every((event) => CLOSED_WITHOUT_STATE.has(event.kind))) return;\n throw new MigrationError(\n \"Migration ledger history exists without a current marker\",\n VibORMErrorCode.MIGRATION_INVALID_STATE\n );\n}\n\n/**\n * Which control tables exist. PostgreSQL answers from `catalog`, the one\n * statement that also authenticates them (plan D5), read here when not given.\n */\nexport async function inspectControlPresence(\n producer: AnyDriver,\n driver: BoundMigrationDriver,\n catalog?: PostgresControlCatalog\n): Promise<ControlPresence> {\n const read = catalog ?? (await postgresControlCatalog(producer, driver));\n const stateMissing = read\n ? !read.state\n : await isTableMissing(producer, driver, CONTROL_TABLES.state);\n const logMissing = read\n ? !read.log\n : await isTableMissing(producer, driver, CONTROL_TABLES.log);\n if (stateMissing && logMissing)\n return { kind: \"missing-table\", table: \"both\" };\n if (stateMissing) return { kind: \"missing-table\", table: \"state\" };\n if (logMissing) {\n // Bootstrap creates state before log. If the second CREATE failed, the\n // empty state table is the one recognizable partial state that can be\n // completed idempotently. A marker row means this is real history with a\n // missing ledger and must remain a hard refusal.\n await assertControlTablesAuthentic(producer, driver, \"state\", read);\n if (await isStateControlEmpty(producer, driver)) {\n return { kind: \"recoverable-state-only\" };\n }\n return { kind: \"missing-table\", table: \"log\" };\n }\n return { kind: \"present\" };\n}\n\n/**\n * Introspects with the managed-table scope narrowed to the two control tables.\n *\n * Every dialect's introspection already reads an unselected table without\n * interpreting it (no refusal of its indexes, types or defaults), so a managed\n * table's state — an INVALID index left by an interrupted `CREATE INDEX\n * CONCURRENTLY` among them — can no longer make the control plane unreadable\n * and take `status()` and `log()` down with it. The view restates `target`\n * only, the way every execution view in this layer restates one member.\n */\nfunction introspectControlTables(\n producer: AnyDriver,\n driver: BoundMigrationDriver\n): Promise<SchemaSnapshot> {\n const scoped: BoundMigrationDriver = Object.create(driver);\n Object.defineProperty(scoped, \"target\", {\n value: Object.freeze({\n ...driver.target,\n tables: [CONTROL_TABLES.log, CONTROL_TABLES.state],\n }),\n enumerable: true,\n });\n return Object.freeze(scoped).introspect((sql, params) =>\n producer._executeRaw(sql, params)\n );\n}\n\n/** The refusals of the pair, and of a state table left without its log. */\nconst UNAUTHENTIC = {\n pair: {\n unreadable: \"Migration control tables cannot be authenticated\",\n unexpected: \"Migration control tables have an unexpected definition\",\n attached: \"Migration control tables have executable attachments\",\n },\n state: {\n unreadable:\n \"A partial migration control state table cannot be authenticated\",\n unexpected:\n \"A partial migration control state table has an unexpected definition\",\n attached:\n \"A partial migration control state table has executable attachments\",\n },\n} as const;\n\n/**\n * Proves that both reserved control tables — or, with `scope` \"state\", the\n * state table bootstrap left without its log — still have VibORM's exact\n * shape. PostgreSQL reads `catalog` when presence already read it.\n */\nexport async function assertControlTablesAuthentic(\n producer: AnyDriver,\n driver: BoundMigrationDriver,\n scope: keyof typeof UNAUTHENTIC = \"pair\",\n catalog?: PostgresControlCatalog\n): Promise<void> {\n if (driver.target.dialect === \"postgresql\") {\n assertPostgresControlAuthentic(\n catalog ?? (await readPostgresControlCatalog(producer, driver)),\n scope\n );\n return;\n }\n const refusal = UNAUTHENTIC[scope];\n let snapshot: SchemaSnapshot;\n try {\n snapshot = await introspectControlTables(producer, driver);\n } catch (failure) {\n // The pair keeps introspection's own refusal; the partial state wraps it.\n if (failure instanceof MigrationError && scope === \"pair\") throw failure;\n throw unreadable(refusal.unreadable, failure);\n }\n const matches = (name: string) =>\n snapshot.tables.filter((table) => table.name === name);\n const [state, ...otherStates] = matches(CONTROL_TABLES.state);\n const [log, ...otherLogs] = matches(CONTROL_TABLES.log);\n if (\n !state ||\n otherStates.length > 0 ||\n !hasExpectedShape(state, driver, \"state\") ||\n (scope === \"pair\" &&\n !(log && otherLogs.length === 0 && hasExpectedShape(log, driver, \"log\")))\n ) {\n throw new MigrationError(\n refusal.unexpected,\n VibORMErrorCode.MIGRATION_INVALID_STATE\n );\n }\n let hasSingletonCheck: boolean;\n try {\n hasSingletonCheck = await hasExpectedSingletonCheck(producer, driver);\n } catch (failure) {\n throw unreadable(refusal.unreadable, failure);\n }\n if (!hasSingletonCheck) {\n throw new MigrationError(\n refusal.unexpected,\n VibORMErrorCode.MIGRATION_INVALID_STATE\n );\n }\n let hasAttachments: boolean;\n try {\n hasAttachments = await hasControlAttachments(producer, driver);\n } catch (failure) {\n if (failure instanceof MigrationError) throw failure;\n throw unreadable(refusal.unreadable, failure);\n }\n if (hasAttachments) {\n throw new MigrationError(\n refusal.attached,\n VibORMErrorCode.MIGRATION_INVALID_STATE\n );\n }\n}\n\n/**\n * The definition VibORM creates, as introspection reads it back: the declared\n * columns, NOT NULL with no default, and the primary key alone. MySQL reports\n * the singleton's INTEGER as `int`.\n */\nfunction hasExpectedShape(\n table: TableDef,\n driver: BoundMigrationDriver,\n kind: ControlTable\n): boolean {\n const mysql = driver.target.dialect === \"mysql\";\n const columns = controlColumns(driver.target.dialect, kind);\n return (\n table.columns.length === columns.length &&\n table.columns.every((column, index) => {\n const [name, type] = columns[index]!;\n return (\n column.name === name &&\n (name === \"singleton\"\n ? normalizeType(column.type) === normalizeType(mysql ? \"INT\" : type)\n : column.type.toLowerCase() === type.toLowerCase()) &&\n column.nullable === false &&\n column.default === undefined &&\n column.autoIncrement !== true &&\n column.decimal === undefined\n );\n }) &&\n table.primaryKey?.name ===\n (mysql ? \"PRIMARY\" : `${CONTROL_TABLES[kind]}_pkey`) &&\n table.primaryKey.columns.length === 1 &&\n table.primaryKey.columns[0] === columns[0]![0] &&\n table.indexes.length === 0 &&\n table.foreignKeys.length === 0 &&\n table.uniqueConstraints.length === 0 &&\n table.relationStorage === undefined\n );\n}\n\nasync function hasExpectedSingletonCheck(\n producer: AnyDriver,\n driver: BoundMigrationDriver\n): Promise<boolean> {\n if (driver.target.dialect === \"sqlite\") {\n const result = await producer._executeRaw<{ sql: unknown }>(\n \"SELECT sql FROM sqlite_master WHERE type = 'table' AND name = ?\",\n [CONTROL_TABLES.state]\n );\n const sql = result.rows[0]?.sql;\n return (\n result.rows.length === 1 &&\n typeof sql === \"string\" &&\n isSqliteStateControlDefinition(CONTROL_TABLES.state, sql)\n );\n }\n const result = await producer._executeRaw<{ definition: unknown }>(\n `SELECT cc.CHECK_CLAUSE AS definition\nFROM information_schema.TABLE_CONSTRAINTS tc\nJOIN information_schema.CHECK_CONSTRAINTS cc\n ON cc.CONSTRAINT_SCHEMA = tc.CONSTRAINT_SCHEMA\n AND cc.CONSTRAINT_NAME = tc.CONSTRAINT_NAME\nWHERE tc.CONSTRAINT_SCHEMA = ?\n AND tc.TABLE_NAME = ?\n AND tc.CONSTRAINT_TYPE = 'CHECK'\nORDER BY tc.CONSTRAINT_NAME`,\n [driver.namespace, CONTROL_TABLES.state]\n );\n return (\n result.rows.length === 1 &&\n normalizeSingletonCheck(result.rows[0]?.definition) === \"singleton=1\"\n );\n}\n\nfunction sqliteDefinitionBody(sql: string): string {\n const body = sql.slice(sql.indexOf(\"(\"));\n return body.replace(/[\\s\"`]/g, \"\").toLowerCase();\n}\n\nfunction normalizeSingletonCheck(value: unknown): string | undefined {\n if (typeof value !== \"string\") return undefined;\n return value\n .replace(CHECK_PREFIX, \"\")\n .replace(CHECK_FORMATTING, \"\")\n .toLowerCase();\n}\n\nasync function hasControlAttachments(\n producer: AnyDriver,\n driver: BoundMigrationDriver\n): Promise<boolean> {\n const names = [CONTROL_TABLES.state, CONTROL_TABLES.log];\n const result =\n driver.target.dialect === \"sqlite\"\n ? await producer._executeRaw<Record<string, unknown>>(\n \"SELECT EXISTS (SELECT 1 FROM sqlite_master WHERE type = 'trigger' AND tbl_name IN (?, ?)) AS attached\",\n names\n )\n : await producer._executeRaw<Record<string, unknown>>(\n \"SELECT EXISTS (SELECT 1 FROM information_schema.TRIGGERS WHERE TRIGGER_SCHEMA = ? AND EVENT_OBJECT_TABLE IN (?, ?)) AS attached\",\n [driver.namespace, ...names]\n );\n if (result.rows.length !== 1) {\n throw new MigrationError(\n \"Migration control attachment probe must return exactly one row\",\n VibORMErrorCode.MIGRATION_INVALID_STATE\n );\n }\n const attached = readFlag(Object.values(result.rows[0]!)[0]);\n if (attached !== undefined) return attached;\n throw new MigrationError(\n \"Migration control attachment probe returned an invalid flag\",\n VibORMErrorCode.MIGRATION_INVALID_STATE\n );\n}\n\nasync function isStateControlEmpty(\n producer: AnyDriver,\n driver: BoundMigrationDriver\n): Promise<boolean> {\n const table = qualifiedName(driver, CONTROL_TABLES.state);\n try {\n const result = await producer._executeRaw(\n `SELECT payload FROM ${table} WHERE singleton = 1`\n );\n return result.rows.length === 0;\n } catch (failure) {\n throw unreadable(\n \"A partial migration control state table cannot be proven empty\",\n failure\n );\n }\n}\n\n/**\n * The refusal `message` for a control-table read that failed, or the failure\n * itself when it says nothing about the tables: the migration lock not taken\n * (the read may be the statement that reopens a command's locked transaction,\n * after a commit let the lock go), a lost connection or another retryable\n * failure, which the caller retries.\n */\nfunction unreadable(message: string, failure: unknown): unknown {\n const transient =\n isRetryableError(failure) ||\n (failure instanceof MigrationError &&\n failure.code === VibORMErrorCode.MIGRATION_LOCK_FAILED);\n return transient\n ? failure\n : new MigrationError(message, VibORMErrorCode.MIGRATION_INVALID_STATE, {\n cause: errorCause(failure),\n meta: providerFacts(failure),\n });\n}\n\nexport async function isTableMissing(\n producer: AnyDriver,\n driver: BoundMigrationDriver,\n tableName: string\n): Promise<boolean> {\n const probe = tableExistsProbe(driver, tableName, true);\n const result = await producer._executeRaw<Record<string, unknown>>(\n probe.sql,\n probeParameters(probe.parameters)\n );\n if (result.rows.length !== 1) {\n throw new MigrationError(\n \"Control catalog probe must return exactly one row\",\n VibORMErrorCode.MIGRATION_INVALID_STATE\n );\n }\n return readFlag(Object.values(result.rows[0]!)[0]) !== true;\n}\n\nfunction probeParameters(\n parameters: ReturnType<typeof tableExistsProbe>[\"parameters\"]\n): unknown[] {\n return parameters.map((parameter) => {\n if (parameter.kind !== \"string\") {\n throw new MigrationError(\n \"Control catalog probe parameters must be strings\",\n VibORMErrorCode.INTERNAL_ERROR\n );\n }\n return parameter.value;\n });\n}\n\nexport interface MigrationControlRead {\n readonly presence: ControlPresence;\n readonly marker: MigrationMarkerV1 | null;\n /**\n * The ledger events, in causal order (`inCausalOrder`): every event, or\n * with `{ ledger: \"open\" }` those of an unfinished attempt and the latest\n * `failed` one (plan D5, new defect 6). Without a marker the history may\n * only hold attempts that never reached a state, and all of it is read so\n * `refuseIncompatibleHistory` can say so.\n */\n readonly ledger: readonly LedgerEventV1[];\n}\n\n/** The event kinds that open an attempt, and those that close one. */\nconst OPENING_KINDS: ReadonlySet<LedgerEventV1[\"kind\"]> = new Set([\n \"started\",\n \"reset-started\",\n]);\nconst CLOSING_KINDS: ReadonlySet<LedgerEventV1[\"kind\"]> = new Set([\n \"applied\",\n \"rolled-back\",\n \"failed\",\n \"baselined\",\n \"reanchored\",\n \"resolved\",\n \"reset-applied\",\n]);\n\n/**\n * Reads the control-plane view. A present pair is authenticated once before\n * either table is trusted; callers decide whether total absence or the\n * recoverable bootstrap arm is valid for their command.\n */\nexport async function readControlState(\n producer: AnyDriver,\n driver: BoundMigrationDriver,\n { ledger: scope = \"all\" }: { readonly ledger?: \"open\" | \"all\" } = {}\n): Promise<MigrationControlRead> {\n const catalog = await postgresControlCatalog(producer, driver);\n const presence = await inspectControlPresence(producer, driver, catalog);\n if (presence.kind !== \"present\") {\n return { presence, marker: null, ledger: [] };\n }\n await assertControlTablesAuthentic(producer, driver, \"pair\", catalog);\n const markerResult = await producer._executeRaw<{ payload: unknown }>(\n `SELECT payload FROM ${qualifiedName(driver, CONTROL_TABLES.state)} WHERE singleton = 1`\n );\n // Without a marker every event is read: `refuseIncompatibleHistory` judges\n // the whole history then.\n const all = scope === \"all\" || markerResult.rows.length === 0;\n const ledgerResult = await producer._executeRaw<{ payload: unknown }>(\n ledgerSql(driver, all)\n );\n const { marker, ledger } = decodeControlRows(\n markerResult.rows,\n ledgerResult.rows\n );\n return { presence, marker, ledger };\n}\n\n/**\n * The ledger events a command reads, selected by their columns, which the\n * one writer (`appendLedger`) fills from the event it appends: every event,\n * or those of an unfinished attempt and the latest `failed` one (plan D5,\n * new defect 6).\n */\nfunction ledgerSql(driver: BoundMigrationDriver, all: boolean): string {\n const log = qualifiedName(driver, CONTROL_TABLES.log);\n if (all) return `SELECT payload FROM ${log}`;\n return `SELECT payload FROM ${log} WHERE ${openAttempt(log)}\n OR event_id = (SELECT event_id FROM ${log} WHERE kind = 'failed' ORDER BY ${jsonField(driver.target.dialect, \"startedAt\")} DESC, event_id DESC LIMIT 1)`;\n}\n\n/** The ledger rows of an unfinished attempt, as `unfinishedAttempts` reads them. */\nfunction openAttempt(log: string): string {\n const list = (kinds: ReadonlySet<string>) =>\n [...kinds].map((kind) => `'${kind}'`).join(\", \");\n return `(attempt_id IN (SELECT attempt_id FROM ${log} WHERE kind IN (${list(OPENING_KINDS)}))\n AND attempt_id NOT IN (SELECT attempt_id FROM ${log} WHERE kind IN (${list(CLOSING_KINDS)})))`;\n}\n\n/**\n * `assertLockedSinceDecision` as a condition one request asserts under its\n * own lock (plan D7): the marker is still `expected`, or there is none when\n * that is null, and no attempt is open.\n */\nexport function markerUnmovedCondition(\n driver: BoundMigrationDriver,\n expected: MarkerIdentity | null\n): { readonly sql: string; readonly params: unknown[] } {\n const log = qualifiedName(driver, CONTROL_TABLES.log);\n const at = expected && markerAt(driver.target.dialect, 1, expected);\n const marker = `EXISTS (SELECT 1 FROM ${qualifiedName(driver, CONTROL_TABLES.state)}${at ? ` WHERE singleton = 1 AND ${at.sql}` : \"\"})`;\n return {\n sql: `(${at ? \"\" : \"NOT \"}${marker} AND NOT EXISTS (SELECT 1 FROM ${log} WHERE ${openAttempt(log)}))`,\n params: at ? at.params : [],\n };\n}\n\n/** What identifies a marker: `markerAt` matches it in SQL, `sameMarker` in JS. */\nexport type MarkerIdentity = Pick<MigrationMarkerV1, \"revision\" | \"pathHash\">;\n\n/** The marker row is `expected`, bound from `$first` on. */\nfunction markerAt(\n dialect: BoundMigrationDriver[\"target\"][\"dialect\"],\n first: number,\n { revision, pathHash }: MarkerIdentity\n): { readonly sql: string; readonly params: unknown[] } {\n const slot = placeholder(dialect, first);\n const revisionMatch =\n dialect === \"postgresql\"\n ? `(payload::json->>'revision')::bigint = ${slot}`\n : dialect === \"mysql\"\n ? `CAST(JSON_UNQUOTE(JSON_EXTRACT(payload, '$.revision')) AS UNSIGNED) = ${slot}`\n : `CAST(json_extract(payload, '$.revision') AS INTEGER) = ${slot}`;\n return {\n sql: `${revisionMatch} AND ${jsonField(dialect, \"pathHash\")} = ${placeholder(dialect, first + 1)}`,\n params: [revision, pathHash],\n };\n}\n\nfunction decodeControlRows(\n markerRows: readonly { readonly payload: unknown }[],\n ledgerRows: readonly { readonly payload: unknown }[]\n): {\n readonly marker: MigrationMarkerV1 | null;\n readonly predicates: readonly MarkerIndexPredicateV1[];\n readonly ledger: readonly LedgerEventV1[];\n} {\n const markerRow = markerRows[0];\n const stored =\n markerRow && parseMarkerPayload(parsePayload(markerRow.payload));\n return {\n marker: stored ? stored.marker : null,\n predicates: stored ? stored.predicates : [],\n ledger: inCausalOrder(\n ledgerRows.map((row) => parseLedgerEvent(parsePayload(row.payload)))\n ),\n };\n}\n\n/**\n * Plan D5: what a PostgreSQL no-op decides on, in two statements: the control\n * tables' definition, then the marker, the open attempts and the catalog\n * digest, read together and so in one snapshot, provided `lockFree` (the\n * migration lock taken and released at once) holds. Without a marker there is\n * no no-op to prove, so the ledger is never read whole here. `undefined`\n * unless both control tables are present, so no statement here names a table\n * that is not there, and while another command holds the lock; a pair that is\n * not exactly VibORM's is refused. The digest hashes partial-index predicates\n * as the server deparses them, for comparison with those recorded beside the\n * marker.\n */\nexport async function readPostgresDecision(\n producer: AnyDriver,\n driver: BoundMigrationDriver,\n lockFree: string\n): Promise<\n | {\n readonly marker: MigrationMarkerV1 | null;\n readonly predicates: readonly MarkerIndexPredicateV1[];\n readonly ledger: readonly LedgerEventV1[];\n readonly digest: Sha256 | undefined;\n }\n | undefined\n> {\n const catalog = await readPostgresControlCatalog(producer, driver);\n if (!(catalog.state && catalog.log)) return;\n assertPostgresControlAuthentic(catalog, \"pair\");\n // Only PostgreSQL reads a decision in one statement: its driver owns this.\n const digest = driver.catalogDigestQuery!(CONTROL_TABLES, true);\n const { rows } = await producer._executeRaw<{\n marker: unknown;\n ledger: unknown;\n digest: unknown;\n }>(\n `SELECT (SELECT json_agg(json_build_object('payload', marker.payload)) FROM (SELECT payload FROM ${qualifiedName(driver, CONTROL_TABLES.state)} WHERE singleton = 1) marker)::text AS marker,\n (SELECT json_agg(json_build_object('payload', ledger.payload)) FROM (${ledgerSql(driver, false)}) ledger)::text AS ledger,\n (${digest.sql}) AS digest WHERE ${lockFree}`,\n digest.parameters\n );\n if (rows.length === 0) return;\n return {\n ...decodeControlRows(\n readPayloadRows(rows[0]?.marker),\n readPayloadRows(rows[0]?.ledger)\n ),\n digest: isSha256(rows[0]?.digest) ? rows[0].digest : undefined,\n };\n}\n\n/** The `{ payload }` rows a JSON aggregate carries; none for SQL NULL. */\nfunction readPayloadRows(value: unknown): { readonly payload: unknown }[] {\n const rows: unknown = readCatalogJson(value);\n return Array.isArray(rows)\n ? rows.flatMap((row: unknown) =>\n isRecord(row) ? [{ payload: row.payload }] : []\n )\n : [];\n}\n\n/**\n * The ledger in causal order (new defect 6). Without a sequence column the\n * clock is the order, and it ties: one millisecond can hold a whole\n * transactional group, or one attempt's close and the next one's start. The\n * events of one instant come attempt by attempt — the one opened earliest\n * first, then along the state chain (an attempt leaving the state another one\n * arrives at follows it), then by attempt id — and inside an attempt as it\n * ran: it opens, confirms steps, then closes. Only a cycle of attempts within\n * one millisecond (up, down, up) falls back to attempt ids.\n */\nfunction inCausalOrder(events: readonly LedgerEventV1[]): LedgerEventV1[] {\n const opened = new Map<Sha256, string>();\n for (const { attemptId, startedAt } of events) {\n const first = opened.get(attemptId);\n if (first === undefined || startedAt < first) {\n opened.set(attemptId, startedAt);\n }\n }\n const byTime = [...events].sort((left, right) =>\n compareText(left.startedAt, right.startedAt)\n );\n const ordered: LedgerEventV1[] = [];\n for (let start = 0; start < byTime.length; ) {\n const instant = byTime[start]!.startedAt;\n let end = start;\n while (byTime[end]?.startedAt === instant) end += 1;\n ordered.push(...instantInOrder(byTime.slice(start, end), opened));\n start = end;\n }\n return ordered;\n}\n\nfunction instantInOrder(\n events: readonly LedgerEventV1[],\n opened: ReadonlyMap<Sha256, string>\n): LedgerEventV1[] {\n const pending = new Map<Sha256, LedgerEventV1[]>();\n for (const event of events) {\n const attempt = pending.get(event.attemptId);\n if (attempt) attempt.push(event);\n else pending.set(event.attemptId, [event]);\n }\n const follows = ({ attemptId, fromState }: LedgerEventV1) =>\n fromState !== null &&\n [...pending.values()].some(\n ([other]) =>\n other!.attemptId !== attemptId && other!.toState === fromState\n );\n const ordered: LedgerEventV1[] = [];\n while (pending.size > 0) {\n const [next] = [...pending.values()]\n .map(([first]) => first!)\n .sort(\n (left, right) =>\n compareText(\n opened.get(left.attemptId)!,\n opened.get(right.attemptId)!\n ) ||\n Number(follows(left)) - Number(follows(right)) ||\n compareText(left.attemptId, right.attemptId)\n );\n ordered.push(\n ...pending\n .get(next!.attemptId)!\n .sort(\n (left, right) =>\n causalRank(left) - causalRank(right) ||\n compareText(left.eventId, right.eventId)\n )\n );\n pending.delete(next!.attemptId);\n }\n return ordered;\n}\n\nfunction compareText(left: string, right: string): number {\n return Number(left > right) - Number(left < right);\n}\n\nfunction causalRank(event: LedgerEventV1): number {\n if (OPENING_KINDS.has(event.kind)) return 0;\n return CLOSING_KINDS.has(event.kind) ? 2 : 1;\n}\n\n/** The text of one top-level field of a JSON payload, per dialect. */\nfunction jsonField(\n dialect: BoundMigrationDriver[\"target\"][\"dialect\"],\n field: string\n): string {\n if (dialect === \"postgresql\") return `payload::json->>'${field}'`;\n if (dialect === \"mysql\") {\n return `JSON_UNQUOTE(JSON_EXTRACT(payload, '$.${field}'))`;\n }\n return `json_extract(payload, '$.${field}')`;\n}\n\n/** One control table as the PostgreSQL catalog read reports it. */\ninterface PostgresControlTable {\n readonly kind: unknown;\n readonly partition: unknown;\n readonly columns: unknown;\n readonly constraints: unknown;\n readonly indexes: unknown;\n readonly executable: unknown;\n}\n\ninterface PostgresControlCatalog {\n readonly state: PostgresControlTable | undefined;\n readonly log: PostgresControlTable | undefined;\n}\n\n/**\n * Both control tables' definitions in one statement (plan D5): the columns,\n * the constraints but PostgreSQL 18's catalogued NOT NULLs, how many indexes,\n * and whether a trigger, rule, policy or row security is attached. It reads\n * these two relations only, so no managed table's state — an INVALID index\n * among them (plan S7) — can make the control plane unreadable.\n */\nconst POSTGRES_CONTROL_CATALOG = `SELECT control.position, c.relkind::text AS kind, c.relispartition AS partition,\n (SELECT json_agg(json_build_array(a.attname::text, pg_catalog.format_type(a.atttypid, a.atttypmod), a.attnotnull, a.atthasdef, a.attidentity::text, a.attgenerated::text) ORDER BY a.attnum) FROM pg_catalog.pg_attribute a WHERE a.attrelid = c.oid AND a.attnum > 0 AND NOT a.attisdropped)::text AS columns,\n (SELECT json_agg(json_build_array(k.contype::text, k.conname::text, pg_catalog.pg_get_constraintdef(k.oid, true)) ORDER BY k.conname) FROM pg_catalog.pg_constraint k WHERE k.conrelid = c.oid AND k.contype <> 'n')::text AS constraints,\n (SELECT count(*) FROM pg_catalog.pg_index i WHERE i.indrelid = c.oid)::text AS indexes,\n (EXISTS (SELECT 1 FROM pg_catalog.pg_trigger g WHERE g.tgrelid = c.oid AND NOT g.tgisinternal)\n OR EXISTS (SELECT 1 FROM pg_catalog.pg_rewrite w WHERE w.ev_class = c.oid AND w.rulename <> '_RETURN')\n OR EXISTS (SELECT 1 FROM pg_catalog.pg_policy p WHERE p.polrelid = c.oid)\n OR c.relrowsecurity OR c.relforcerowsecurity) AS executable\nFROM (VALUES (1, $2::text), (2, $3::text)) AS control(position, name)\nLEFT JOIN pg_catalog.pg_class c ON c.relname = control.name AND c.relkind IN ('r', 'p')\n AND c.relnamespace = (SELECT oid FROM pg_catalog.pg_namespace WHERE nspname = $1::text)\nORDER BY control.position`;\n\n/** {@link readPostgresControlCatalog} on PostgreSQL; nothing elsewhere. */\nfunction postgresControlCatalog(\n producer: AnyDriver,\n driver: BoundMigrationDriver\n): Promise<PostgresControlCatalog | undefined> {\n return driver.target.dialect === \"postgresql\"\n ? readPostgresControlCatalog(producer, driver)\n : Promise.resolve(undefined);\n}\n\nasync function readPostgresControlCatalog(\n producer: AnyDriver,\n driver: BoundMigrationDriver\n): Promise<PostgresControlCatalog> {\n let rows: readonly Record<string, unknown>[];\n try {\n ({ rows } = await producer._executeRaw<Record<string, unknown>>(\n POSTGRES_CONTROL_CATALOG,\n [boundNamespace(driver), CONTROL_TABLES.state, CONTROL_TABLES.log]\n ));\n } catch (failure) {\n throwIfCatalogRefusal(\"control catalog\", failure);\n throw unreadable(UNAUTHENTIC.pair.unreadable, failure);\n }\n if (rows.length !== 2) {\n throw new MigrationError(\n \"Migration control catalog read must return one row per control table\",\n VibORMErrorCode.MIGRATION_INVALID_STATE\n );\n }\n return {\n state: presentControlTable(rows[0]),\n log: presentControlTable(rows[1]),\n };\n}\n\n/** One row of the catalog read, or `undefined` when that table is absent. */\nfunction presentControlTable(row: unknown): PostgresControlTable | undefined {\n if (!isRecord(row) || row.kind === null || row.kind === undefined) return;\n const { kind, partition, columns, constraints, indexes, executable } = row;\n return { kind, partition, columns, constraints, indexes, executable };\n}\n\nfunction assertPostgresControlAuthentic(\n { state, log }: PostgresControlCatalog,\n scope: keyof typeof UNAUTHENTIC\n): void {\n const pair = scope === \"pair\";\n if (\n !(\n state &&\n hasPostgresShape(state, \"state\") &&\n (!pair || (log && hasPostgresShape(log, \"log\")))\n )\n ) {\n throw new MigrationError(\n UNAUTHENTIC[scope].unexpected,\n VibORMErrorCode.MIGRATION_INVALID_STATE\n );\n }\n if (\n readFlag(state.executable) !== false ||\n (pair && readFlag(log?.executable) !== false)\n ) {\n throw new MigrationError(\n UNAUTHENTIC[scope].attached,\n VibORMErrorCode.MIGRATION_INVALID_STATE\n );\n }\n}\n\n/**\n * The exact definition VibORM creates: an ordinary table of NOT NULL columns\n * with no default, identity or generation, its primary key, the state\n * table's one `singleton = 1` CHECK, and no other constraint or index.\n */\nfunction hasPostgresShape(\n table: PostgresControlTable,\n kind: ControlTable\n): boolean {\n const columns = controlColumns(\"postgresql\", kind);\n const constraints = readCatalogRows(table.constraints);\n if (constraints === undefined) return false;\n const checks = constraints.filter((constraint) => constraint[0] === \"c\");\n const keys = constraints.filter((constraint) => constraint[0] === \"p\");\n return (\n table.kind === \"r\" &&\n readFlag(table.partition) === false &&\n String(table.indexes) === \"1\" &&\n canonicalizeJsonText(readCatalogJson(table.columns)) ===\n canonicalizeJsonText(\n columns.map(([name, type]) => [\n name,\n type.toLowerCase(),\n true,\n false,\n \"\",\n \"\",\n ])\n ) &&\n constraints.length === keys.length + checks.length &&\n keys.length === 1 &&\n keys[0]?.[1] === `${CONTROL_TABLES[kind]}_pkey` &&\n keys[0]?.[2] === `PRIMARY KEY (${columns[0]![0]})` &&\n checks.length === (kind === \"state\" ? 1 : 0) &&\n checks.every((check) => normalizeSingletonCheck(check[2]) === \"singleton=1\")\n );\n}\n\n/** A JSON column of the catalog read, or `null` when it is not JSON text. */\nfunction readCatalogJson(value: unknown): unknown {\n if (typeof value !== \"string\") return null;\n try {\n return JSON.parse(value);\n } catch {\n return null;\n }\n}\n\n/** A JSON array of arrays (no rows: SQL NULL), or `undefined`. */\nfunction readCatalogRows(\n value: unknown\n): readonly (readonly unknown[])[] | undefined {\n if (value === null) return [];\n const rows: unknown = readCatalogJson(value);\n if (!Array.isArray(rows)) return undefined;\n const checked: (readonly unknown[])[] = [];\n for (const row of rows) {\n const entry: unknown = row;\n if (!Array.isArray(entry)) return undefined;\n checked.push(entry);\n }\n return checked;\n}\n\n/**\n * Creates the pair, or completes the one a failed bootstrap left, under the\n * migration lock: no other command bootstraps between the presence read and\n * the CREATE, so presence is read once.\n */\nexport async function ensureControlTables(\n producer: AnyDriver,\n driver: BoundMigrationDriver\n): Promise<void> {\n const catalog = await postgresControlCatalog(producer, driver);\n const presence = await inspectControlPresence(producer, driver, catalog);\n if (presence.kind === \"present\") {\n await assertControlTablesAuthentic(producer, driver, \"pair\", catalog);\n return;\n }\n if (presence.kind === \"missing-table\") refusePartialControl(presence);\n else {\n await producer._executeRaw(\n `DROP TABLE ${qualifiedName(driver, CONTROL_TABLES.state)}`\n );\n }\n const sql = createControlTableSQL(driver);\n await producer._executeRaw(sql.state);\n await producer._executeRaw(sql.log);\n await assertControlTablesAuthentic(producer, driver);\n}\n\n/**\n * Moves the marker. `predicates`, recorded beside it, are the partial-index\n * predicates of `next`'s snapshot as PostgreSQL deparsed them; a marker\n * without them proves its no-op under the lock.\n */\nexport async function casMarker(\n producer: AnyDriver,\n driver: BoundMigrationDriver,\n expected: MarkerIdentity | null,\n next: MigrationMarkerV1,\n predicates: readonly MarkerIndexPredicateV1[] = []\n): Promise<void> {\n const { sql, params } = markerWrite(driver, expected, next, predicates);\n if (expected === null) {\n try {\n const result = await producer._executeRaw(sql, params);\n if (result.rowCount !== 1) {\n throw new MigrationError(\n \"Migration marker insert did not create the singleton row\",\n VibORMErrorCode.MIGRATION_MARKER_CONFLICT\n );\n }\n } catch (error) {\n if (error instanceof MigrationError) throw error;\n throw new MigrationError(\n \"Migration marker compare-and-swap failed\",\n VibORMErrorCode.MIGRATION_MARKER_CONFLICT,\n { cause: error instanceof Error ? error : undefined }\n );\n }\n return;\n }\n\n const result = await producer._executeRaw(sql, params);\n if (result.rowCount !== 1) {\n throw new MigrationError(\n \"Migration marker compare-and-swap failed\",\n VibORMErrorCode.MIGRATION_MARKER_CONFLICT\n );\n }\n}\n\n/**\n * The statement {@link casMarker} sends: the first marker's INSERT, or the\n * UPDATE that matches only the `expected` marker. One request (plan D7)\n * sends it after asserting that marker under its lock.\n */\nexport function markerWrite(\n driver: BoundMigrationDriver,\n expected: MarkerIdentity | null,\n next: MigrationMarkerV1,\n predicates: readonly MarkerIndexPredicateV1[] = []\n): { readonly sql: string; readonly params: unknown[] } {\n const table = qualifiedName(driver, CONTROL_TABLES.state);\n const payload = canonicalizeJsonText(\n predicates.length > 0 ? { ...next, predicates } : next\n );\n const dialect = driver.target.dialect;\n const at = expected && markerAt(dialect, 2, expected);\n return at\n ? {\n sql: `UPDATE ${table} SET payload = ${placeholder(dialect, 1)} WHERE singleton = 1 AND ${at.sql}`,\n params: [payload, ...at.params],\n }\n : {\n sql: `INSERT INTO ${table} (singleton, payload) VALUES (1, ${placeholder(dialect, 1)})`,\n params: [payload],\n };\n}\n\n/** Appends events in one statement, in their order. */\nexport async function appendLedger(\n producer: AnyDriver,\n driver: BoundMigrationDriver,\n ...events: readonly LedgerEventV1[]\n): Promise<void> {\n const table = qualifiedName(driver, CONTROL_TABLES.log);\n const dialect = driver.target.dialect;\n const rows = events.map((_, index) =>\n [1, 2, 3, 4].map((column) => placeholder(dialect, index * 4 + column))\n );\n await producer._executeRaw(\n `INSERT INTO ${table} (event_id, attempt_id, kind, payload) VALUES ${rows.map((row) => `(${row.join(\", \")})`).join(\", \")}`,\n events.flatMap((event) => [\n event.eventId,\n event.attemptId,\n event.kind,\n canonicalizeJsonText(event),\n ])\n );\n}\n\nexport function markerFromPath(\n estateHash: Sha256,\n snapshotHash: Sha256,\n path: MigrationMarkerV1[\"path\"],\n revision: number\n): MigrationMarkerV1 {\n const stateId = path.length === 0 ? null : path.at(-1)!.stateId;\n return {\n format: \"1\",\n estateHash,\n stateId,\n snapshotHash,\n path,\n pathHash: encodePathHash(path),\n revision,\n updatedAt: new Date().toISOString(),\n };\n}\n\n/** Every ledger event's sealed fields: format, times, tool version and id. */\nexport function ledgerEvent({\n open = false,\n failure = null,\n ...fields\n}: Omit<\n LedgerEventV1,\n \"format\" | \"eventId\" | \"toolVersion\" | \"startedAt\" | \"finishedAt\" | \"failure\"\n> & { failure?: string | null; open?: boolean }): LedgerEventV1 {\n const startedAt = new Date().toISOString();\n const event = {\n format: \"1\" as const,\n ...fields,\n startedAt,\n finishedAt: open ? null : startedAt,\n toolVersion: \"v1\",\n failure,\n };\n return { ...event, eventId: eventIdFor(event) };\n}\n\n/** The fields every event of one attempt carries. */\ntype AttemptSeed = Pick<\n LedgerEventV1,\n | \"estateHash\"\n | \"snapshotHash\"\n | \"sqlHash\"\n | \"fromState\"\n | \"toState\"\n | \"transitionHash\"\n | \"direction\"\n>;\n\n/** An attempt's id: the id of its `started` event under the zero attempt. */\nexport function attemptIdFor(seed: AttemptSeed): Sha256 {\n return ledgerEvent({\n ...seed,\n attemptId: \"0\".repeat(64),\n kind: \"started\",\n operationId: null,\n dispatchId: null,\n effectState: \"none\",\n open: true,\n }).eventId;\n}\n\n/** The builder of one attempt's ledger events. */\nexport interface AttemptEvents {\n readonly attemptId: Sha256;\n event(\n kind: LedgerEventV1[\"kind\"],\n effectState: LedgerEventV1[\"effectState\"],\n step?: {\n readonly operationId: string | null;\n readonly dispatchId: Sha256 | null;\n },\n failure?: string\n ): LedgerEventV1;\n}\n\n/**\n * One attempt's events: each carries `seed` (and a reset plan, when it has\n * one) and `attemptId`, by default the id of the attempt's own `started`\n * event. An opening kind leaves its event unfinished.\n */\nexport function attemptEvents(\n seed: AttemptSeed & Pick<LedgerEventV1, \"resetPlan\">,\n attemptId: Sha256 = attemptIdFor(seed)\n): AttemptEvents {\n return {\n attemptId,\n event: (kind, effectState, step, failure) =>\n ledgerEvent({\n ...seed,\n attemptId,\n kind,\n effectState,\n operationId: step?.operationId ?? null,\n dispatchId: step?.dispatchId ?? null,\n failure,\n open: OPENING_KINDS.has(kind),\n }),\n };\n}\n\n/** Whether a read marker is the one expected; two absent markers are. */\nexport function sameMarker(\n marker: MarkerIdentity | null,\n expected: MarkerIdentity | null\n): boolean {\n return (\n marker?.revision === expected?.revision &&\n marker?.pathHash === expected?.pathHash\n );\n}\n\n/** Compare-and-swaps the marker from `current` to the one `path` ends at. */\nexport async function advanceMarker(\n producer: AnyDriver,\n driver: BoundMigrationDriver,\n estateHash: Sha256,\n current: MigrationMarkerV1 | null,\n path: MigrationMarkerV1[\"path\"],\n snapshotHash: Sha256,\n revisionStep = 1,\n predicates?: readonly MarkerIndexPredicateV1[]\n): Promise<MigrationMarkerV1> {\n const next = markerFromPath(\n estateHash,\n snapshotHash,\n path,\n (current?.revision ?? 0) + revisionStep\n );\n await casMarker(producer, driver, current, next, predicates);\n return next;\n}\n\nfunction parsePayload(value: unknown): unknown {\n if (typeof value === \"string\") return JSON.parse(value);\n return value;\n}\n\nexport function unfinishedAttempts(\n events: readonly LedgerEventV1[]\n): readonly LedgerEventV1[] {\n const started = new Map<string, LedgerEventV1>();\n const closed = new Set<string>();\n for (const event of events) {\n if (OPENING_KINDS.has(event.kind)) started.set(event.attemptId, event);\n if (CLOSING_KINDS.has(event.kind)) closed.add(event.attemptId);\n }\n return [...started.values()].filter((event) => !closed.has(event.attemptId));\n}\n","/**\n * Migration Estate Target\n *\n * ONE resolver derives the durable estate target from a concrete execution\n * driver, and ONE pair of readers reaches the two runtime facts installed on\n * the adapter and the driver (`adapter.namespace`,\n * `driver.migrationNamespaceAttestation`). Every migration verb, the registry\n * binding, and the live-capability admission owner reach those facts through\n * here, so no command re-decides dialect, namespace or attestation for itself.\n */\n\nimport type { AnyDriver } from \"../drivers/driver\";\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\nimport { CONTROL_TABLES } from \"./control\";\nimport { snapshotExactArray } from \"./input-boundary\";\nimport type { MigrationTarget, SchemaSnapshot } from \"./types\";\nimport { normalizeDialect } from \"./utils\";\n\nexport const MANAGED_TABLES = Symbol(\"migration managed tables\");\n/** The client's resolved limits (plans S1, T5a), bound with its driver. */\nexport const MIGRATION_LIMITS = Symbol(\"migration limits\");\n\n/** Exact physical membership, authenticated as part of the estate target. */\nexport function normalizeManagedTables(\n value: unknown\n): readonly string[] | undefined {\n if (value === undefined) return;\n const entries = snapshotExactArray(value, \"managed tables\", (message) => {\n throw new MigrationError(message, VibORMErrorCode.MIGRATION_INVALID_STATE);\n });\n const names: string[] = [];\n for (const name of entries) {\n if (typeof name !== \"string\" || name.length === 0 || name.includes(\"\\0\"))\n throw new MigrationError(\n \"Managed tables must contain non-empty physical names\",\n VibORMErrorCode.MIGRATION_INVALID_STATE\n );\n if (names.includes(name))\n throw new MigrationError(\n `Managed table \"${name}\" is repeated`,\n VibORMErrorCode.MIGRATION_INVALID_STATE\n );\n names.push(name);\n }\n return Object.freeze(names.sort());\n}\n\nexport function selectManagedSnapshot(\n snapshot: SchemaSnapshot,\n target: MigrationTarget,\n desired = false\n): SchemaSnapshot {\n const names = target.tables;\n if (names === undefined) return snapshot;\n // Control authenticity reads the same inventory, independently of user scope.\n const selected = (name: string) =>\n names.includes(name) ||\n name === CONTROL_TABLES.state ||\n name === CONTROL_TABLES.log;\n if (desired && snapshot.tables.some((table) => !names.includes(table.name)))\n throw new MigrationError(\n \"The schema declares a physical table outside the authenticated managed-table list\",\n VibORMErrorCode.MIGRATION_INVALID_STATE\n );\n for (const table of snapshot.tables)\n for (const fk of table.foreignKeys) {\n if (selected(table.name) !== selected(fk.referencedTable))\n throw new MigrationError(\n `Foreign key \"${table.name}.${fk.name}\" crosses the managed-table boundary`,\n VibORMErrorCode.MIGRATION_INVALID_STATE\n );\n }\n const tables = snapshot.tables.filter((table) => selected(table.name));\n const used = new Set(\n tables.flatMap((table) =>\n table.columns.map((column) =>\n column.type.endsWith(\"[]\") ? column.type.slice(0, -2) : column.type\n )\n )\n );\n const enums = snapshot.enums?.filter((item) => used.has(item.name));\n for (const table of snapshot.tables.filter(\n (table) => !selected(table.name)\n )) {\n if (\n target.dialect === \"postgresql\" &&\n table.columns.some((column) =>\n enums?.some(\n (item) =>\n (column.type.endsWith(\"[]\")\n ? column.type.slice(0, -2)\n : column.type) === item.name\n )\n )\n )\n throw new MigrationError(\n `Table \"${table.name}\" shares a managed enum across the managed-table boundary`,\n VibORMErrorCode.MIGRATION_INVALID_STATE\n );\n }\n return { ...snapshot, tables, ...(enums === undefined ? {} : { enums }) };\n}\n\n/**\n * The live namespace the adapter is bound to, or undefined when the adapter\n * exposes none.\n *\n * Module-private on purpose: `resolveMigrationEstate` is the ONE reader of this\n * fact in the whole migration layer, so no second caller can take a second look\n * at a value a custom adapter may answer differently each time.\n *\n * The property is read reflectively for one reason: it is an OPTIONAL runtime\n * fact whose declaration lives on the adapter contract, and reading it as\n * untyped data keeps the migration layer from claiming any adapter it is handed\n * — including a caller-supplied custom adapter — has already declared it. A\n * present-but-non-string value is the same as absent: unproven.\n *\n * So is the EMPTY STRING. §1.3 settles it for the shipped path — an empty\n * candidate \"is not passed to identifier validation\" and preserves unbound mode\n * — and `normalizeNamespace` (`src/schema/identifier.ts`) rejects `\"\"` against\n * the identifier grammar, so no stock constructor can produce one. A custom\n * adapter can, and this reader is the seam that admits it: an empty name proves\n * no schema and no database, and reading it as proven would qualify every live\n * statement with an EMPTY quoted segment (`\"\".\"users\"`).\n */\nfunction readAdapterNamespace(driver: AnyDriver): string | undefined {\n const value: unknown = Reflect.get(driver.adapter, \"namespace\");\n return typeof value === \"string\" && value !== \"\" ? value : undefined;\n}\n\n/**\n * The driver's immutable non-redirecting migration-namespace attestation, or\n * undefined when the driver makes no such claim.\n *\n * Only the exact string `\"non-redirecting\"` is an attestation. There is no\n * provider-name fallback and no inference from class, URL, handshake or\n * server version: a driver that does not carry this exact value is unproven,\n * which is what keeps PlanetScale (and any MySQL2 connection reaching Vitess\n * through the ordinary MySQL protocol) out of effectful migration work.\n */\nexport function readNamespaceAttestation(\n driver: AnyDriver\n): \"non-redirecting\" | undefined {\n const value: unknown = Reflect.get(driver, \"migrationNamespaceAttestation\");\n return value === \"non-redirecting\" ? value : undefined;\n}\n\n/**\n * Reads one catalog statement with its bound values.\n *\n * The same shape the dialect base class's `proveNamespaceExists` takes, spelled\n * here so the migration layer's shared owners can name a catalog read without\n * importing a dialect module for the type.\n */\nexport type CatalogRead = <T>(\n sql: string,\n params?: unknown[]\n) => Promise<{ rows: T[] }>;\n\n/**\n * A dialect whose CONFIGURED namespace and the server's own spelling of it can\n * differ, and which therefore answers one command-local spelling (§5.2).\n *\n * MySQL is the only such dialect: `lower_case_table_names` can make a\n * differently cased configured value name the same physical database, so\n * catalog resolution accepts a single case-folded candidate — and every later\n * statement of that command has to speak the spelling the SERVER answered with,\n * not the one the configuration carried. `information_schema` rows carry the\n * server's spelling, and on a case-sensitive server so does `USE`.\n *\n * PostgreSQL has no such projection (its `pg_namespace` proof is byte-exact)\n * and SQLite has no namespace at all, so both answer nothing here and their\n * commands keep the exact bound driver they started with.\n *\n * The capability is STRUCTURAL, exactly like the pinned-session hook: a dialect\n * declares it by implementing it. This interface is what the implementation is\n * checked against; {@link readsCommandNamespace} is what a shared owner asks.\n */\nexport interface CommandNamespaceResolver {\n resolveCommandNamespace(read: CatalogRead): Promise<string>;\n}\n\n/**\n * Whether this migration driver resolves a command-local namespace spelling.\n *\n * Read as an optional runtime capability rather than declared on the dialect\n * base class, for the same reason `adapter.namespace` is read reflectively\n * above: it is a fact only one dialect has, and a base-class declaration would\n * make every dialect — including a caller-supplied one — answer for it.\n */\nexport function readsCommandNamespace<T extends object>(\n migrationDriver: T\n): migrationDriver is T & CommandNamespaceResolver {\n return (\n typeof Reflect.get(migrationDriver, \"resolveCommandNamespace\") ===\n \"function\"\n );\n}\n\n/**\n * The two estate facts a bound migration driver carries, derived together.\n *\n * `target` is the DURABLE estate generated artifacts claim;\n * `namespace` is the LIVE execution destination. They coincide for PostgreSQL\n * and deliberately differ for MySQL, whose artifacts are database-relative, so\n * both have to be published — but both come from ONE read of the adapter.\n */\nexport interface MigrationEstate {\n readonly target: MigrationTarget;\n readonly namespace: string | undefined;\n}\n\n/**\n * Derives the one frozen estate target and the one live namespace for a\n * concrete execution driver, from a SINGLE read of `adapter.namespace`.\n *\n * The single read is load-bearing, not tidiness. A custom adapter may expose\n * `namespace` as an accessor; two reads could answer two different strings, and\n * the durable target would then name one estate while live DDL rendered\n * another. Reading once and publishing both facts from that one value makes the\n * disagreement structurally impossible (plan §14).\n *\n * The dialect goes through `normalizeDialect` here and nowhere else in the\n * migration layer's target decisions, so a driver cannot resolve to two targets\n * by being read raw on one path and normalized on another.\n *\n * A PostgreSQL driver whose adapter exposes no namespace is UNPROVEN and\n * refused. It must not silently acquire the `\"public\"` default: generated\n * PostgreSQL SQL contains the schema, so a defaulted target would write a\n * durable claim nothing established.\n */\nexport function resolveMigrationEstate(driver: AnyDriver): MigrationEstate {\n const dialect = normalizeDialect(driver.dialect);\n const namespace = readAdapterNamespace(driver);\n\n if (dialect === \"postgresql\") {\n if (namespace === undefined) {\n throw new MigrationError(\n `The PostgreSQL driver \"${driver.driverName}\" exposes no adapter namespace, so its migration estate has no proven schema. ` +\n 'Generated PostgreSQL migration SQL is schema-qualified, so the estate cannot fall back to \"public\": construct the driver with an explicit `namespace`, or supply an adapter that declares one.',\n VibORMErrorCode.MIGRATION_INVALID_STATE,\n { meta: { driver: driver.driverName, dialect } }\n );\n }\n return { target: Object.freeze({ dialect, namespace }), namespace };\n }\n\n // MySQL and SQLite estates are namespace-free BY DESIGN. MySQL artifacts are\n // database-relative so one history deploys to several database names; SQLite\n // has no namespace concept at all. The live MySQL destination rides beside\n // the target on the bound view, never inside it.\n return { target: Object.freeze({ dialect }), namespace };\n}\n\n/**\n * Human-readable estate description for refusal messages and safe metadata.\n *\n * The live namespace is a SECOND argument because the two facts are separate\n * for MySQL: its durable target is namespace-free by design (§3.1), so the\n * database a command actually touches rides beside it on the bound view. A\n * caller that has it passes it; a caller describing a stored estate target —\n * which carries no database name and must not appear to — does not.\n *\n * Naming it matters wherever the description is what a person consents to: the\n * CLI's `--force-reset` confirmation used to read \"This will DROP ALL TABLES in\n * mysql\", which identifies nothing on the one dialect whose estate target is\n * namespace-free (DECISIONS N6: the confirmation \"must name the target\n * namespace\").\n */\nexport function formatMigrationTarget(\n target: MigrationTarget,\n namespace?: string\n): string {\n if (target.dialect === \"postgresql\") {\n return `${target.dialect} schema \"${target.namespace}\"`;\n }\n return namespace === undefined\n ? target.dialect\n : `${target.dialect} database \"${namespace}\"`;\n}\n\n/**\n * A stored estate is bound to one durable target. PostgreSQL artifacts are\n * schema-qualified, so `alpha` cannot generate or apply as `beta`. MySQL and\n * SQLite compare dialect only.\n */\nexport function assertEstateTargetMatches(\n stored: MigrationTarget,\n live: MigrationTarget\n): void {\n if (JSON.stringify(stored.tables) !== JSON.stringify(live.tables)) {\n throw new MigrationError(\n \"Estate managed-table scope does not match this client\",\n VibORMErrorCode.MIGRATION_DIALECT_MISMATCH\n );\n }\n if (stored.dialect !== live.dialect) {\n throw new MigrationError(\n \"Estate target dialect does not match this client\",\n VibORMErrorCode.MIGRATION_DIALECT_MISMATCH\n );\n }\n if (\n stored.dialect === \"postgresql\" &&\n live.dialect === \"postgresql\" &&\n stored.namespace !== live.namespace\n ) {\n throw new MigrationError(\n \"Estate target namespace does not match this client\",\n VibORMErrorCode.MIGRATION_DIALECT_MISMATCH\n );\n }\n}\n","/**\n * The one conversion no dialect can perform in SQL: a column BECOMING binary.\n *\n * Every generated `ALTER COLUMN` is a blind re-reading of the bytes already\n * stored. That is harmless when the two types share a reading — `varchar(40)`\n * and `text` are the same characters, `numeric(10,2)` and `numeric(12,2)` the\n * same number — and it is data loss the moment the target is a BINARY column,\n * because the only cast a dialect offers there re-encodes the source's own\n * spelling:\n *\n * · PostgreSQL's `USING col::bytea` writes the ASCII of the old text. A\n * 26-character ULID becomes 26 bytes, not the 16 its codec reads, and every\n * later read is refused as \"not in this column's declared identifier\n * domain\" (measured live on PostgreSQL 16).\n * · SQLite's table rebuild copies the value VERBATIM into the new BLOB\n * column, so `typeof()` still answers `'text'` afterwards — the migration\n * type and the engine binding disagree with no error at all.\n * · MySQL's `MODIFY COLUMN … BINARY(n)` truncates or pads to the declared\n * width without a word in a non-strict `sql_mode`.\n *\n * So the conversion is REFUSED where it is generated, with the manual route\n * named. This is the rule `docs/architecture/native-ids-plan.md` §3 states for\n * an identifier (\"a blind `USING col::bytea` would re-encode text bytes, so it\n * is never emitted\"), and it is stated here in the terms a migration driver\n * actually has: the two column TYPES. A snapshot carries no logical marker that\n * would say \"this BLOB decodes identifiers\", and it does not need one — a\n * verbatim copy into a binary column is unreadable whatever the column holds.\n *\n * PostgreSQL's `uuid` target is deliberately NOT here. `col::uuid` is a real\n * conversion PostgreSQL performs value by value: it succeeds for an estate of\n * canonical uuids and aborts the whole transaction for one that is not, leaving\n * the column as it was. That is a conversion with a wrong answer for nobody.\n *\n * Pure and connection-free, like every other module in this layer.\n */\n\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\nimport type { Dialect } from \"./drivers/types\";\n\n/** MySQL's two width-carrying binary column spellings. */\nconst MYSQL_SIZED_BINARY = /^(?:BINARY|VARBINARY)\\(\\d+\\)$/i;\nconst MYSQL_BLOB_FAMILY = /^(?:TINYBLOB|BLOB|MEDIUMBLOB|LONGBLOB)$/i;\n\n/** Whether this dialect spells `type` as a column of raw bytes. */\nfunction isBinaryColumnType(type: string, dialect: Dialect): boolean {\n const spelling = type.trim();\n switch (dialect) {\n case \"postgresql\":\n return spelling.toLowerCase() === \"bytea\";\n case \"mysql\":\n return (\n MYSQL_SIZED_BINARY.test(spelling) || MYSQL_BLOB_FAMILY.test(spelling)\n );\n default:\n return spelling.toUpperCase() === \"BLOB\";\n }\n}\n\n/**\n * Refuse an alteration that turns a non-binary column into a binary one.\n *\n * Both sides binary is a WIDTH change and is left alone: `VARBINARY(100)` to\n * `VARBINARY(200)` re-reads the same bytes as the same bytes, which is the\n * property this refusal exists to require.\n */\nexport function refuseBinaryReencoding(\n table: string,\n column: string,\n fromType: string,\n toType: string,\n dialect: Dialect\n): void {\n if (!isBinaryColumnType(toType, dialect)) return;\n if (isBinaryColumnType(fromType, dialect)) return;\n throw new MigrationError(\n `Column \"${column}\" of \"${table}\" would change from ${fromType} to ${toType}, and no dialect can re-read the stored values as bytes: ` +\n \"the generated cast would store the old value's own spelling, which nothing can decode afterwards. \" +\n \"Convert the rows yourself — add the new column, write the decoded values into it, drop the old one and rename — \" +\n \"or, for a declared identifier format, keep the column as it is with a text-family native type, which validates the domain without changing storage.\",\n VibORMErrorCode.INVALID_INPUT\n );\n}\n","import { stringifyJson } from \"../../adapters/shared/standard-sql\";\n/**\n * MigrationDriver Base Class\n *\n * Abstract base class for database-specific migration drivers.\n * Each driver implements DDL generation and introspection for its database.\n */\n\nimport { jsonNullKindOf } from \"@schema/json-null\";\nimport type { Scalar, ScalarState } from \"@schema/scalars\";\nimport {\n type DecimalDialect,\n decimalDefaultText,\n decimalListDefaultText,\n} from \"@validation/primitives/decimal-codec\";\nimport type { IdDomain } from \"@validation/primitives/id-codec\";\nimport type { AnyDriver } from \"../../drivers/driver\";\nimport { MigrationError, VibORMErrorCode } from \"../../errors\";\nimport { refuseBinaryReencoding } from \"../binary-conversion\";\nimport type { Sha256 } from \"../identity\";\nimport type { ResolvedMigrationLimits } from \"../limits\";\nimport {\n applyNativeRename,\n type NativeRenameOperation,\n} from \"../native-rename\";\nimport type {\n ColumnDef,\n DiffOperation,\n MigrationTarget,\n ReferentialAction,\n SchemaSnapshot,\n TableDef,\n} from \"../types\";\nimport { defaultGeneratedPrimaryKeyName, derivedMigrationName } from \"../utils\";\nimport type { BoundMigrationDriver } from \".\";\nimport type { Dialect, MigrationCapabilities } from \"./types\";\n\nconst ARRAY_TYPE = /\\[\\]$/;\n\n/** How the serializer ends an index, unique or foreign key name it derives. */\nconst DERIVED_TAIL = /_(?:idx|f?key)$/;\n\n/** A name a native rename carries along, and the statement kind that does. */\nexport interface DerivedRename {\n readonly kind: \"constraint\" | \"index\" | \"type\";\n readonly to: string;\n}\n\n/** The two control tables the fingerprint leaves out. */\nexport interface ControlTableNames {\n readonly state: string;\n readonly log: string;\n}\n\n/**\n * Context passed to DDL generation methods.\n * Contains information needed for operations that require knowledge of the current schema.\n */\nexport interface DDLContext {\n /**\n * Where the rendered statement is going.\n *\n * REQUIRED, and deliberately not defaulted anywhere: an artifact is durable\n * and a live statement is not, and the two differ for MySQL (relative\n * artifacts, qualified live SQL). A dispatcher default would reintroduce\n * exactly the implicit mode this fact replaces, so every caller states it.\n * Generation and generated rollback pass `\"artifact\"`; push, live reset and\n * every immediate DDL path pass `\"live\"`. SQLite ignores the distinction.\n */\n readonly destination: \"artifact\" | \"live\";\n\n /**\n * Current database schema snapshot.\n * Required for SQLite table recreation operations.\n */\n currentSchema?: SchemaSnapshot;\n\n /**\n * The operations of this batch that run *before* the one being generated.\n *\n * `currentSchema` is introspected once, before the batch starts, so on its\n * own it describes the database as it was — not as the statements already\n * emitted have left it. A SQLite table recreation has to name the indexes the\n * table holds at the moment it runs, because `DROP TABLE` takes them with it;\n * see `SQLite3MigrationDriver.getCurrentTable`.\n */\n precedingOperations?: DiffOperation[];\n /** Remaining intent in this same compilation batch, for physical coalescing. */\n followingOperations?: readonly DiffOperation[];\n}\n\n// Extract individual operation types from the DiffOperation union\nexport type CreateTableOperation = Extract<\n DiffOperation,\n { type: \"createTable\" }\n>;\nexport type DropTableOperation = Extract<DiffOperation, { type: \"dropTable\" }>;\nexport type RenameTableOperation = Extract<\n DiffOperation,\n { type: \"renameTable\" }\n>;\nexport type AddColumnOperation = Extract<DiffOperation, { type: \"addColumn\" }>;\nexport type DropColumnOperation = Extract<\n DiffOperation,\n { type: \"dropColumn\" }\n>;\nexport type RenameColumnOperation = Extract<\n DiffOperation,\n { type: \"renameColumn\" }\n>;\nexport type AlterColumnOperation = Extract<\n DiffOperation,\n { type: \"alterColumn\" }\n>;\nexport type CreateIndexOperation = Extract<\n DiffOperation,\n { type: \"createIndex\" }\n>;\nexport type DropIndexOperation = Extract<DiffOperation, { type: \"dropIndex\" }>;\nexport type AddForeignKeyOperation = Extract<\n DiffOperation,\n { type: \"addForeignKey\" }\n>;\nexport type DropForeignKeyOperation = Extract<\n DiffOperation,\n { type: \"dropForeignKey\" }\n>;\nexport type AddUniqueConstraintOperation = Extract<\n DiffOperation,\n { type: \"addUniqueConstraint\" }\n>;\nexport type DropUniqueConstraintOperation = Extract<\n DiffOperation,\n { type: \"dropUniqueConstraint\" }\n>;\nexport type AddPrimaryKeyOperation = Extract<\n DiffOperation,\n { type: \"addPrimaryKey\" }\n>;\nexport type DropPrimaryKeyOperation = Extract<\n DiffOperation,\n { type: \"dropPrimaryKey\" }\n>;\nexport type CreateEnumOperation = Extract<\n DiffOperation,\n { type: \"createEnum\" }\n>;\nexport type DropEnumOperation = Extract<DiffOperation, { type: \"dropEnum\" }>;\nexport type AlterEnumOperation = Extract<DiffOperation, { type: \"alterEnum\" }>;\n\n/**\n * What a dialect states one operation compiles to: one statement, or the\n * ordered statements it needs. {@link MigrationDriver.compileStatements}\n * filters blanks once for every operation.\n */\ntype GeneratedStatements = string | readonly string[];\n\n/**\n * Abstract base class for migration drivers.\n *\n * Each database (PostgreSQL, SQLite, LibSQL, etc.) extends this class\n * to provide database-specific DDL generation and schema introspection.\n */\nexport abstract class MigrationDriver {\n /**\n * The SQL dialect this driver targets.\n */\n abstract readonly dialect: Dialect;\n\n /**\n * The specific driver name (e.g., \"pg\", \"postgres\", \"pglite\", \"sqlite3\", \"libsql\").\n * Used for driver-specific registration and lookup.\n */\n abstract readonly driverName: string;\n\n /**\n * Capabilities supported by this driver.\n */\n abstract readonly capabilities: MigrationCapabilities;\n\n // ===========================================================================\n // ESTATE BINDING (installed by the registry, never mutated on a singleton)\n // ===========================================================================\n\n // All three are `declare`: the class DECLARES the shape a bound view has and\n // emits no field for it. Under `useDefineForClassFields` (tsconfig target\n // es2022) an ordinary optional field would install a writable, enumerable own\n // property valued `undefined` on the REGISTERED SINGLETON — module-level\n // state that `Reflect.set` could then fill in, which §3.1 forbids. With\n // `declare`, `\"namespace\" in postgresMigrationDriver` is false, and the only\n // instances carrying these facts are the frozen views the registry defines\n // them on.\n\n /**\n * The estate target this instance is bound to.\n *\n * Absent on the REGISTERED singleton, which stays stateless: binding happens\n * at lookup and produces a separate frozen view whose prototype is the\n * singleton. Renderers that need the estate must handle the unbound case\n * rather than assume one, because a singleton reached by name renders\n * artifact SQL with no estate behind it.\n */\n declare readonly target?: MigrationTarget;\n\n /**\n * The exact concrete execution driver this instance was bound to, retained\n * for live admission (its immutable attestation) and for the adapter's\n * capabilities. Absent on the unbound singleton.\n */\n declare readonly executionDriver?: AnyDriver;\n\n /**\n * The live execution namespace read once from the bound adapter.\n *\n * Present for PostgreSQL (its target proved it) and for a bound MySQL\n * adapter; absent for an unbound MySQL adapter used for artifact-only work\n * and for SQLite, which has no namespace.\n */\n declare readonly namespace?: string;\n\n /**\n * The limits of the command this instance is bound for (plans S1, T5a).\n * Absent on the unbound singleton, which renders under the defaults.\n */\n declare readonly limits?: ResolvedMigrationLimits;\n\n // ===========================================================================\n // INTROSPECTION\n // ===========================================================================\n\n /**\n * Introspects the current database schema.\n *\n * @param executeRaw - Function to execute raw SQL queries\n * @returns The current schema snapshot\n */\n abstract introspect(\n executeRaw: <T>(sql: string, params?: unknown[]) => Promise<{ rows: T[] }>\n ): Promise<SchemaSnapshot>;\n\n /**\n * Proves external physical requirements encoded by authenticated snapshots.\n * Dialects with no such requirement keep the no-op owner here.\n *\n * `program` is the statement list the command is about to run (empty when\n * it runs none), so a dialect can refuse what that program would destroy\n * (SQLite: a recreation's dependent triggers and views). Required: a caller\n * cannot skip these refusals by leaving it out.\n *\n * Answers whether the program must commit where `catalogCommitBoundaries`\n * names (PlanetScale's Neki). A caller that `splits` commits there itself\n * and is told so; any other is refused such a program before effects.\n */\n async preflightSchemaRequirements(\n _snapshots: readonly SchemaSnapshot[],\n _executeRaw: <T>(sql: string, params?: unknown[]) => Promise<{ rows: T[] }>,\n _program: readonly string[],\n _splits?: boolean\n ): Promise<boolean> {\n // Most dialects have no external schema requirement to prove.\n return false;\n }\n\n /**\n * Returns this database's own spelling of each declared partial-index\n * predicate, so the differ can compare a declaration against what the catalog\n * gave back (Decision 7.4).\n *\n * Optional, and implemented only where the two spellings can differ.\n * PostgreSQL deparses through `pg_get_expr`, so a declared `active = true`\n * reads back as `(active = true)` and every push re-creates the index;\n * SQLite stores the CREATE INDEX statement verbatim and has nothing to\n * reconcile; MySQL refuses a partial index outright.\n *\n * `executeRaw` runs on ONE pinned connection for the whole call — the\n * canonicalization may need session-local scratch objects, which a pooled\n * connection per statement would scatter. Positional result; `undefined` at\n * a position means the database did not answer, and the differ then refuses\n * to call that predicate equal to anything. `executeBatch` is given where\n * no connection can be pinned (Neon HTTP): each request may be a new\n * session, so session-local work goes out as one request.\n */\n canonicalizeIndexPredicates?(\n tableName: string,\n predicates: readonly string[],\n executeRaw: <T>(sql: string, params?: unknown[]) => Promise<{ rows: T[] }>,\n executeBatch?: <T>(\n statements: readonly string[]\n ) => Promise<ReadonlyArray<{ rows: T[] }>>\n ): Promise<ReadonlyArray<string | undefined>>;\n\n /**\n * The live managed schema's fingerprint in one statement, where this\n * dialect can compute it (PostgreSQL, `postgres/catalog-digest.ts`): the\n * statement for a caller that embeds it, and the digest read, `undefined`\n * where it abstains. Absent elsewhere, and the caller introspects. The bound\n * driver owns it, so another dialect's bundle never carries it.\n */\n catalogDigestQuery?(\n this: BoundMigrationDriver,\n control: ControlTableNames,\n deparsedPredicates?: boolean\n ): { readonly sql: string; readonly parameters: unknown[] };\n catalogDigest?(\n this: BoundMigrationDriver,\n producer: AnyDriver,\n control: ControlTableNames\n ): Promise<Sha256 | undefined>;\n\n /**\n * Explains why one inverted operation cannot be rendered as an automatic\n * rollback on this dialect. Generation owns the persisted rollback policy;\n * the driver owns the physical boundary that makes an inverse unsafe.\n */\n getIrreversibleRollbackReason(_operation: DiffOperation): string | undefined {\n return undefined;\n }\n\n // ===========================================================================\n // TYPE MAPPING\n // ===========================================================================\n\n /**\n * Maps a VibORM scalar type to the native database column type.\n *\n * @param scalar - The scalar definition\n * @param scalarState - The scalar state with type info\n * @returns The native column type string\n */\n /**\n * `idDomain` is the identifier domain this column holds, which a foreign key\n * DERIVES from the key it references and therefore cannot be read off the\n * scalar. The physical type comes from the one storage owner\n * ({@link idStorageOf}), so the column this creates and the parameter the\n * engine binds into it are one decision.\n */\n abstract mapScalarType(\n scalar: Scalar,\n scalarState: ScalarState,\n idDomain?: IdDomain\n ): string;\n\n /**\n * Final pass over a serialized table before diffing/DDL generation.\n * Lets drivers apply table-aware type adjustments (e.g. MySQL rewrites\n * keyed TEXT columns to VARCHAR, since TEXT cannot be indexed without a\n * key length). Default: identity.\n */\n finalizeTable(table: TableDef): TableDef {\n return table;\n }\n\n /** The exact generated PK name used by this driver's DDL and its inverse. */\n generatedPrimaryKeyName(tableName: string, name?: string): string {\n return defaultGeneratedPrimaryKeyName(tableName, name);\n }\n\n /** Project exactly this driver's compiled rename before diffing or inversion. */\n projectNativeRename(\n snapshot: SchemaSnapshot,\n operation: NativeRenameOperation\n ): SchemaSnapshot {\n const projected = applyNativeRename(snapshot, operation);\n const renames = this.derivedRenames(operation, snapshot);\n if (renames.size === 0) return projected;\n const name = (from: string) => renames.get(from)?.to ?? from;\n const renamed = <T extends { readonly name: string }>(\n items: readonly T[]\n ) => items.map((item) => ({ ...item, name: name(item.name) }));\n const owner =\n operation.type === \"renameTable\" ? operation.to : operation.tableName;\n return {\n ...projected,\n ...(projected.enums ? { enums: renamed(projected.enums) } : {}),\n tables: projected.tables.map((table) => {\n if (table.name !== owner) return table;\n const { primaryKey } = table;\n return {\n ...table,\n columns: table.columns.map((column) => {\n const element = column.type.replace(ARRAY_TYPE, \"\");\n const type = name(element) + column.type.slice(element.length);\n return { ...column, type };\n }),\n ...(primaryKey?.name\n ? { primaryKey: { ...primaryKey, name: name(primaryKey.name) } }\n : {}),\n indexes: renamed(table.indexes),\n uniqueConstraints: renamed(table.uniqueConstraints),\n foreignKeys: renamed(table.foreignKeys),\n };\n }),\n };\n }\n\n /**\n * The statements that move `renames`, the names a native rename of `owner`\n * carries along, on a dialect whose renames carry them (PostgreSQL,\n * MySQL). `table` is the owner as the rename leaves it, still holding the\n * old names. Absent where a rename leaves every name as it is (SQLite).\n */\n protected renameDerivedNames?(\n owner: string,\n renames: ReadonlyMap<string, DerivedRename>,\n table: TableDef,\n context: DDLContext\n ): string[];\n\n /**\n * The names a native rename carries along, each derived from what it\n * renames: the default primary key's (`<table>_pkey`), a per-column enum\n * type (`<table>_<column>_enum`), and an index, unique or foreign key named\n * after its own columns (`<table>_<columns>_idx`, `_key`, `_fkey`). A table\n * rename also moves an index, unique or foreign key named `<table>_<rest>`\n * that ends as the serializer ends them (`_idx`, `_key`, `_fkey`), whatever\n * the rest is: field names, a compound key's name. Both spellings must fit\n * unbounded (63 bytes) so the inverse rename reads the rest back. Any other\n * name is custom, and stays; a self-set index name of that derived shape\n * cannot be told apart, and moves.\n */\n private derivedRenames(\n operation: NativeRenameOperation,\n snapshot: SchemaSnapshot | undefined\n ): Map<string, DerivedRename> {\n const [from, to] =\n operation.type === \"renameTable\"\n ? [operation.from, operation.to]\n : [operation.tableName, operation.tableName];\n const renamed = (column: string) =>\n operation.type === \"renameColumn\" && column === operation.from\n ? operation.to\n : column;\n const renames = new Map<string, DerivedRename>();\n const follow = (\n kind: DerivedRename[\"kind\"],\n name: string | undefined,\n derive: (table: string, column: (name: string) => string) => string,\n tailed = false\n ) => {\n if (name === undefined) return;\n const tail = name.slice(from.length);\n const next =\n name === derive(from, (column) => column)\n ? derive(to, renamed)\n : tailed &&\n name.startsWith(`${from}_`) &&\n DERIVED_TAIL.test(tail) &&\n derivedMigrationName(to + tail) === to + tail\n ? to + tail\n : name;\n if (next !== name) renames.set(name, { kind, to: next });\n };\n const named =\n (columns: readonly string[], suffix: string) =>\n (owner: string, column: (name: string) => string) =>\n derivedMigrationName(\n `${owner}_${columns.map(column).join(\"_\")}_${suffix}`\n );\n const table = snapshot?.tables.find((item) => item.name === from);\n if (!(table && this.renameDerivedNames)) return renames;\n follow(\"constraint\", table.primaryKey?.name, (owner) =>\n this.generatedPrimaryKeyName(owner)\n );\n for (const column of table.columns) {\n follow(\"type\", column.type.replace(ARRAY_TYPE, \"\"), (owner, renamedTo) =>\n this.getEnumColumnType(owner, renamedTo(column.name), [])\n );\n }\n for (const index of table.indexes) {\n follow(\"index\", index.name, named(index.columns, \"idx\"), true);\n }\n // A unique constraint's index carries its name: renaming it renames both.\n for (const unique of table.uniqueConstraints) {\n follow(\"index\", unique.name, named(unique.columns, \"key\"), true);\n }\n for (const key of table.foreignKeys) {\n follow(\"constraint\", key.name, named(key.columns, \"fkey\"), true);\n }\n return renames;\n }\n\n private compileDerivedRenames(\n operation: NativeRenameOperation,\n context: DDLContext\n ): string[] {\n const snapshot = this.schemaAtOperation(context);\n const renames = this.derivedRenames(operation, snapshot);\n if (renames.size === 0) return [];\n const owner =\n operation.type === \"renameTable\" ? operation.to : operation.tableName;\n const table = applyNativeRename(snapshot!, operation).tables.find(\n (item) => item.name === owner\n )!;\n return this.renameDerivedNames!(owner, renames, table, context);\n }\n\n /** Native identity and PK effects needed by rename and enum DDL at this prefix. */\n protected schemaAtOperation(context: DDLContext): SchemaSnapshot | undefined {\n let snapshot = context.currentSchema;\n if (!snapshot) return undefined;\n for (const operation of context.precedingOperations ?? []) {\n if (\n operation.type === \"renameTable\" ||\n operation.type === \"renameColumn\"\n ) {\n snapshot = this.projectNativeRename(snapshot, operation);\n } else if (operation.type === \"createTable\") {\n const table = operation.table;\n snapshot = {\n ...snapshot,\n tables: [\n ...snapshot.tables,\n table.primaryKey\n ? {\n ...table,\n primaryKey: {\n ...table.primaryKey,\n name: this.generatedPrimaryKeyName(\n table.name,\n table.primaryKey.name\n ),\n },\n }\n : table,\n ],\n };\n } else if (operation.type === \"dropTable\") {\n snapshot = {\n ...snapshot,\n tables: snapshot.tables.filter(\n (table) => table.name !== operation.tableName\n ),\n };\n } else if (\n operation.type === \"addPrimaryKey\" ||\n operation.type === \"dropPrimaryKey\"\n ) {\n snapshot = {\n ...snapshot,\n tables: snapshot.tables.map((table) =>\n table.name === operation.tableName\n ? {\n ...table,\n primaryKey:\n operation.type === \"addPrimaryKey\"\n ? {\n ...operation.primaryKey,\n name: this.generatedPrimaryKeyName(\n operation.tableName,\n operation.primaryKey.name\n ),\n }\n : undefined,\n }\n : table\n ),\n };\n }\n }\n return snapshot;\n }\n\n // Note: getDefaultExpression is implemented below as a common method\n // Override it in subclasses only if database-specific behavior is needed\n\n /**\n * Gets the column type for an enum field.\n *\n * @param tableName - The table name\n * @param columnName - The column name\n * @param values - The enum values\n * @returns The column type (e.g., \"users_status_enum\" for PG, \"TEXT\" for SQLite)\n */\n abstract getEnumColumnType(\n tableName: string,\n columnName: string,\n values: string[]\n ): string;\n\n // ===========================================================================\n // DDL GENERATION - Table Operations\n // ===========================================================================\n\n abstract generateCreateTable(\n op: CreateTableOperation,\n context: DDLContext\n ): GeneratedStatements;\n abstract generateDropTable(\n op: DropTableOperation,\n context: DDLContext\n ): GeneratedStatements;\n abstract generateRenameTable(\n op: RenameTableOperation,\n context: DDLContext\n ): GeneratedStatements;\n\n // ===========================================================================\n // DDL GENERATION - Column Operations\n // ===========================================================================\n\n abstract generateAddColumn(\n op: AddColumnOperation,\n context: DDLContext\n ): GeneratedStatements;\n abstract generateDropColumn(\n op: DropColumnOperation,\n context: DDLContext\n ): GeneratedStatements;\n abstract generateRenameColumn(\n op: RenameColumnOperation,\n context: DDLContext\n ): GeneratedStatements;\n abstract generateAlterColumn(\n op: AlterColumnOperation,\n context: DDLContext\n ): GeneratedStatements;\n\n // ===========================================================================\n // DDL GENERATION - Index Operations\n // ===========================================================================\n\n abstract generateCreateIndex(\n op: CreateIndexOperation,\n context: DDLContext\n ): GeneratedStatements;\n abstract generateDropIndex(\n op: DropIndexOperation,\n context: DDLContext\n ): GeneratedStatements;\n\n // ===========================================================================\n // DDL GENERATION - Foreign Key Operations\n // ===========================================================================\n\n abstract generateAddForeignKey(\n op: AddForeignKeyOperation,\n context: DDLContext\n ): GeneratedStatements;\n abstract generateDropForeignKey(\n op: DropForeignKeyOperation,\n context: DDLContext\n ): GeneratedStatements;\n\n // ===========================================================================\n // DDL GENERATION - Unique Constraint Operations\n // ===========================================================================\n\n abstract generateAddUniqueConstraint(\n op: AddUniqueConstraintOperation,\n context: DDLContext\n ): GeneratedStatements;\n abstract generateDropUniqueConstraint(\n op: DropUniqueConstraintOperation,\n context: DDLContext\n ): GeneratedStatements;\n\n // ===========================================================================\n // DDL GENERATION - Primary Key Operations\n // ===========================================================================\n\n abstract generateAddPrimaryKey(\n op: AddPrimaryKeyOperation,\n context: DDLContext\n ): GeneratedStatements;\n abstract generateDropPrimaryKey(\n op: DropPrimaryKeyOperation,\n context: DDLContext\n ): GeneratedStatements;\n\n // ===========================================================================\n // DDL GENERATION - Enum Operations\n // ===========================================================================\n\n abstract generateCreateEnum(\n op: CreateEnumOperation,\n context: DDLContext\n ): GeneratedStatements;\n abstract generateDropEnum(\n op: DropEnumOperation,\n context: DDLContext\n ): GeneratedStatements;\n abstract generateAlterEnum(\n op: AlterEnumOperation,\n context: DDLContext\n ): GeneratedStatements;\n\n // ===========================================================================\n // DDL COMPILATION\n // ===========================================================================\n\n protected filterStatements(\n statements: readonly (string | null | undefined)[]\n ): string[] {\n return statements.filter(\n (statement): statement is string =>\n statement !== null &&\n statement !== undefined &&\n statement.trim().length > 0\n );\n }\n\n /**\n * Resolves the replacement for a removed enum value on a specific column.\n * Precedence: per-column mapping (columnValueReplacements, keyed\n * \"tableName.columnName\") → flat valueReplacements → defaultReplacement.\n * Returns undefined when no replacement is configured.\n */\n protected getEnumValueReplacement(\n op: AlterEnumOperation,\n tableName: string,\n columnName: string,\n removedValue: string\n ): string | null | undefined {\n const perColumn =\n op.columnValueReplacements?.[`${tableName}.${columnName}`];\n if (perColumn && removedValue in perColumn) {\n return perColumn[removedValue];\n }\n if (op.valueReplacements && removedValue in op.valueReplacements) {\n return op.valueReplacements[removedValue];\n }\n return op.defaultReplacement;\n }\n\n /**\n * Builds the UPDATE statements that migrate rows off removed enum values,\n * honoring per-column mappings. Dialects run these before the type change\n * (Postgres: while columns are text; MySQL: before MODIFY COLUMN).\n */\n protected buildEnumReplacementUpdates(\n op: AlterEnumOperation,\n context: DDLContext\n ): string[] {\n return (op.dependentColumns ?? []).flatMap(({ tableName, columnName }) =>\n this.enumColumnReplacementUpdates(op, tableName, columnName, context)\n );\n }\n\n /** One dependent column's UPDATEs, one per removed value it replaces. */\n protected enumColumnReplacementUpdates(\n op: AlterEnumOperation,\n tableName: string,\n columnName: string,\n context: DDLContext\n ): string[] {\n const table = this.tableRef(tableName, context.destination);\n const column = this.escapeIdentifier(columnName);\n return (op.removeValues ?? []).flatMap((removedValue) => {\n const replacement = this.getEnumValueReplacement(\n op,\n tableName,\n columnName,\n removedValue\n );\n return replacement === undefined\n ? []\n : [\n `UPDATE ${table} SET ${column} = ${this.escapeValue(replacement)} WHERE ${column} = ${this.escapeValue(removedValue)}`,\n ];\n });\n }\n\n /** The `WHEN removed THEN replacement` arms of a column's value mapping. */\n protected enumReplacementCases(\n op: AlterEnumOperation,\n tableName: string,\n columnName: string\n ): string[] {\n return (op.removeValues ?? []).flatMap((value) => {\n const replacement = this.getEnumValueReplacement(\n op,\n tableName,\n columnName,\n value\n );\n return replacement === undefined\n ? []\n : [\n `WHEN ${this.escapeValue(value)} THEN ${this.escapeValue(replacement)}`,\n ];\n });\n }\n\n // ===========================================================================\n // HELPER METHODS (can be overridden)\n // ===========================================================================\n\n /**\n * Escapes an identifier (table name, column name, etc.).\n * Default uses double quotes with proper escaping.\n */\n escapeIdentifier(name: string): string {\n if (name == null) {\n throw new MigrationError(\n \"Cannot escape null or undefined identifier\",\n VibORMErrorCode.INVALID_INPUT\n );\n }\n return `\"${String(name).replace(/\"/g, '\"\"')}\"`;\n }\n\n /**\n * A table position. Default: one identifier. PostgreSQL qualifies it with\n * the estate schema; MySQL names the database in a live statement.\n */\n protected tableRef(\n tableName: string,\n _destination: DDLContext[\"destination\"]\n ): string {\n return this.escapeIdentifier(tableName);\n }\n\n /**\n * Escapes a string value for SQL.\n * Default uses single quotes with proper escaping.\n * Returns \"NULL\" for null/undefined values.\n */\n escapeValue(value: string | null | undefined): string {\n if (value == null) {\n return \"NULL\";\n }\n return `'${String(value).replace(/'/g, \"''\")}'`;\n }\n\n /**\n * Formats a referential action for foreign keys.\n */\n formatReferentialAction(action: ReferentialAction): string {\n switch (action) {\n case \"cascade\":\n return \"CASCADE\";\n case \"setNull\":\n return \"SET NULL\";\n case \"restrict\":\n return \"RESTRICT\";\n case \"setDefault\":\n return \"SET DEFAULT\";\n default:\n return \"NO ACTION\";\n }\n }\n\n // ===========================================================================\n // COMMON IMPLEMENTATIONS (can be overridden for database-specific behavior)\n // ===========================================================================\n\n /**\n * Gets the SQL default expression for a field.\n * Common implementation that handles most cases.\n * Override for database-specific behavior (e.g., UUID generation, boolean representation).\n *\n * @param scalar - The scalar declaration, including its native type\n * @param scalarState - The scalar state\n * @returns SQL default expression or undefined if no default\n */\n getDefaultExpression(\n _scalar: Scalar,\n scalarState: ScalarState\n ): string | undefined {\n // Auto-generated values - check for database-level support first\n if (scalarState.autoGenerate) {\n return this.getAutoGenerateExpression(scalarState.autoGenerate);\n }\n\n // Check for explicit default value\n if (!scalarState.hasDefault || scalarState.default === undefined) {\n return undefined;\n }\n\n const defaultVal = this.literalDefaultValue(scalarState);\n\n // Function defaults are generated at runtime\n if (typeof defaultVal === \"function\") {\n return undefined;\n }\n\n // A JSON null document and absent SQL value are distinct physical defaults.\n // Scalar admission already resolves bare-null ambiguity and authenticates\n // sentinels; JSON primitives must also be quoted as documents, not SQL data.\n if (scalarState.type === \"json\" && !scalarState.array) {\n const kind = jsonNullKindOf(defaultVal);\n if (kind === \"DbNull\")\n return this.dialect === \"sqlite\" ? \"NULL\" : undefined;\n if (kind === \"JsonNull\") return this.escapeValue(\"null\");\n // A schema's null output is a document; only the original nullable\n // bare-null default declares an absent SQL value.\n if (defaultVal === null && scalarState.default !== null)\n return this.escapeValue(\"null\");\n if (\n defaultVal !== null &&\n [\"string\", \"number\", \"boolean\"].includes(typeof defaultVal)\n )\n return this.escapeValue(stringifyJson(defaultVal));\n }\n\n // Null default\n if (defaultVal === null) {\n return \"NULL\";\n }\n\n // A literal decimal-list default is already a trusted list of canonical\n // logical strings: the field codec normalized it at `.default()`. Render\n // its provider value through that same codec, then let the migration driver\n // own quoting and MySQL's required expression parentheses. No generic\n // array/object default enters this arm.\n if (scalarState.decimal && scalarState.array && Array.isArray(defaultVal)) {\n return this.escapeValue(\n decimalListDefaultText(\n this.decimalDialect(),\n defaultVal,\n scalarState.decimal\n )\n );\n }\n\n if (scalarState.array && Array.isArray(defaultVal))\n return this.escapeValue(stringifyJson(defaultVal));\n if (scalarState.type === \"json\" && typeof defaultVal === \"object\")\n return this.escapeValue(stringifyJson(defaultVal));\n if (typeof defaultVal === \"bigint\") return defaultVal.toString();\n\n // Primitive defaults\n if (typeof defaultVal === \"string\") {\n // A decimal default is canonical text by the time it reaches here\n // (`.default()` normalizes at definition time), and canonical text is the\n // WRONG DDL spelling: it strips trailing zeros, while MySQL reads a\n // `DECIMAL(p,s)` default back from `information_schema` padded to the\n // scale. Two renderings, one owner — this is the DDL one, and emitting\n // the identity one instead would make the differ see a changed default\n // on every push. It is also unquoted, because a decimal default is a\n // numeric literal and not a string on any of the three dialects.\n if (scalarState.decimal) {\n return decimalDefaultText(\n this.decimalDialect(),\n defaultVal,\n scalarState.decimal\n );\n }\n return this.escapeValue(defaultVal);\n }\n if (typeof defaultVal === \"number\") {\n if (!Number.isFinite(defaultVal)) {\n throw new MigrationError(\n `Invalid default value: ${defaultVal} is not a finite number`,\n VibORMErrorCode.INVALID_INPUT\n );\n }\n return String(defaultVal);\n }\n if (typeof defaultVal === \"boolean\") {\n return this.formatBooleanDefault(defaultVal);\n }\n\n // Arrays and objects are handled at application level, not as SQL defaults\n if (typeof defaultVal === \"object\") {\n return undefined;\n }\n\n return undefined;\n }\n\n /** Literal defaults cross the scalar's authoritative write admission once. */\n protected literalDefaultValue(state: ScalarState): unknown {\n const value = state.default;\n if (\n value == null ||\n typeof value === \"function\" ||\n state.autoGenerate ||\n jsonNullKindOf(value) ||\n state.decimal !== undefined\n )\n return value;\n if (typeof value === \"number\" && !Number.isFinite(value))\n throw new MigrationError(\n `Invalid default value: ${value} is not a finite number`,\n VibORMErrorCode.INVALID_INPUT\n );\n const result = state.base[\"~standard\"].validate(value);\n if (!(\"value\" in result))\n throw new MigrationError(\n `Invalid ${state.type} literal default; the declared scalar schema refused it before DDL.`,\n VibORMErrorCode.MIGRATION_INVALID_STATE\n );\n return result.value;\n }\n\n /**\n * Formats a boolean default value.\n * Override for databases that use different representations (e.g., SQLite uses 1/0).\n */\n protected formatBooleanDefault(value: boolean): string {\n return value ? \"true\" : \"false\";\n }\n\n /**\n * This driver's dialect in the codec's vocabulary.\n *\n * Two vocabularies exist because they name different things: `Dialect` is the\n * migration ESTATE's dialect, and `DecimalDialect` is the set of dialects\n * that spell a fixed decimal differently. They are not extended together, so\n * the translation is stated once here rather than at each of the codec's\n * call sites.\n */\n protected decimalDialect(): DecimalDialect {\n if (this.dialect === \"postgresql\") return \"pg\";\n if (this.dialect === \"mysql\") return \"mysql\";\n return \"sqlite\";\n }\n\n /**\n * Gets the SQL expression for an auto-generated value.\n * Override for databases that support specific generation functions.\n *\n * By default, returns undefined for all types (handled at application level).\n * PostgreSQL overrides this to use gen_random_uuid() for UUID.\n *\n * @param autoGenerate - The auto-generate type\n * @returns SQL expression or undefined if handled at application level\n */\n protected getAutoGenerateExpression(\n _autoGenerate: ScalarState[\"autoGenerate\"]\n ): string | undefined {\n // By default, all auto-generate types are handled at application level\n // Databases can override to provide native support (e.g., gen_random_uuid())\n return undefined;\n }\n\n /**\n * Validates an index type against supported capabilities.\n * Throws MigrationError if the index type is not supported.\n *\n * @param indexType - The index type to validate (e.g., \"btree\", \"hash\", \"gin\")\n * @param indexName - The index name (for error messages)\n */\n protected validateIndexType(\n indexType: string | undefined,\n indexName: string\n ): void {\n if (!indexType) return; // Default index type is always supported\n\n const supported = this.capabilities.supportsIndexTypes;\n if (!supported.includes(indexType)) {\n throw new MigrationError(\n `Index \"${indexName}\" uses unsupported index type \"${indexType}\". ` +\n `Supported types for ${this.dialect}: ${supported.join(\", \")}`,\n VibORMErrorCode.FEATURE_NOT_SUPPORTED\n );\n }\n }\n\n /**\n * Generates a column definition string.\n * Common implementation that can be overridden for database-specific syntax.\n *\n * @param column - The column definition\n * @returns SQL column definition string\n */\n protected generateColumnDef(column: ColumnDef, context: DDLContext): string {\n const parts: string[] = [this.escapeIdentifier(column.name)];\n\n // Handle type (may be overridden for auto-increment handling)\n const columnType = this.formatColumnType(column, context);\n parts.push(columnType);\n\n // NOT NULL constraint\n if (!column.nullable) {\n parts.push(\"NOT NULL\");\n }\n\n // DEFAULT clause (skip for auto-increment columns)\n if (column.default !== undefined && !column.autoIncrement) {\n parts.push(`DEFAULT ${column.default}`);\n }\n\n return parts.join(\" \");\n }\n\n /**\n * Formats the column type, handling auto-increment and other special cases.\n * Override for database-specific type handling (e.g., PostgreSQL SERIAL).\n *\n * Takes the DDL context because a column type can name a managed enum type,\n * and a managed enum type is qualified exactly like any other persistent\n * object — which is a destination-dependent decision.\n */\n protected formatColumnType(column: ColumnDef, _context: DDLContext): string {\n return column.type;\n }\n\n // ===========================================================================\n // LIVE CONTROL AND NAMESPACE\n // ===========================================================================\n\n /**\n * Proves the configured namespace exists before an empty inventory or an\n * empty applied set may be published.\n *\n * A catalog-driven read cannot otherwise tell a configured-but-absent\n * namespace from an existing namespace holding zero managed objects, and\n * PostgreSQL reports a missing schema and a missing table with the same\n * SQLSTATE. Default: nothing to prove — SQLite has no namespace, and this\n * is not a SQLite namespace feature. PostgreSQL (`pg_namespace`) and MySQL\n * (`information_schema.SCHEMATA`) install their proofs in their own units.\n */\n proveNamespaceExists(\n _executeRaw: <T>(sql: string, params?: unknown[]) => Promise<{ rows: T[] }>\n ): Promise<void> {\n return Promise.resolve();\n }\n\n // ===========================================================================\n // MIGRATION LOCKING\n // ===========================================================================\n\n /**\n * Generates SQL for acquiring a migration lock, with a stable `acquired`\n * alias so the caller reads one known column rather than a provider-shaped\n * name derived from the expression text.\n *\n * Returns null when this dialect takes no session lock (SQLite/LibSQL, which\n * keep their own single-connection queue).\n *\n * @param lockId - A numeric lock identifier\n * @returns SQL statement or null\n */\n abstract generateAcquireLock(lockId: number): string | null;\n\n /**\n * Generates SQL for releasing a migration lock, with a stable `released`\n * alias. Returns null on the dialects that take no lock.\n *\n * @param lockId - A numeric lock identifier\n * @returns SQL statement or null\n */\n abstract generateReleaseLock(lockId: number): string | null;\n\n /**\n * Whether the provider's answer to {@link generateAcquireLock} PROVES the\n * lock is held.\n *\n * Asked only when a lock statement was emitted, so the dialects that emit\n * none never reach it. The default is `false` because a lock nobody proved is\n * a lock nobody holds: MySQL's `GET_LOCK` returns `0` on timeout and `NULL`\n * on error, and the previous owner discarded that answer entirely and ran the\n * \"protected\" work anyway.\n */\n provesLockAcquired(_rows: readonly unknown[]): boolean {\n return false;\n }\n\n /**\n * Whether the provider's answer to {@link generateReleaseLock} PROVES the\n * lock was released. A false answer condemns the session: it is holding a\n * lock nobody will release, and returning it to a pool would strand it.\n */\n provesLockReleased(_rows: readonly unknown[]): boolean {\n return false;\n }\n\n /**\n * Selects the live migration target on a pinned session, or null when this\n * dialect has nothing to select.\n *\n * MySQL is the only arm: its generated artifacts are database-relative, so\n * the target has to be selected on the connection that executes them. Every\n * other dialect qualifies its statements and must never touch session state\n * (§13).\n */\n generateSelectTarget(): string | null {\n return null;\n }\n\n /**\n * Whether this server holds one command's migration lock as the session\n * lock alone, taken once before its first transaction and never mixed with\n * the transaction lock (PlanetScale's Neki). Asked once per command, on its\n * pinned session, before any lock. Default: no.\n */\n holdsSessionLock(\n _read: <T>(sql: string, params?: unknown[]) => Promise<{ rows: T[] }>\n ): Promise<boolean> {\n return Promise.resolve(false);\n }\n\n /**\n * The session lock PostgreSQL stepwise work keeps (plan D1), taken while\n * the session holds the transaction lock on the same key (or alone, where\n * {@link holdsSessionLock}); null elsewhere.\n */\n generateSessionLock(_lockId: number): string | null {\n return null;\n }\n\n /**\n * A condition true while no command holds the migration lock (plan D5).\n * The default never proves it: only PostgreSQL can ask.\n */\n generateLockFree(_lockId: number): string {\n return \"false\";\n }\n\n /**\n * Proves a locked session may run this command's work, once, after its\n * target is selected, and returns the driver the command renders from.\n * Default: nothing to prove.\n */\n proveSession(\n _read: <T>(sql: string, params?: unknown[]) => Promise<{ rows: T[] }>\n ): Promise<this> {\n return Promise.resolve(this);\n }\n\n /** The statements a sequential program runs first, on its producer. */\n programPreamble(_producer: AnyDriver): Promise<readonly string[]> {\n return Promise.resolve([]);\n }\n\n // ===========================================================================\n // SCHEMA INTROSPECTION HELPERS\n // ===========================================================================\n\n /**\n * The live-namespace table inventory: the exact set of tables a reset may\n * drop, as a BOUND read.\n *\n * `{ sql, params }` rather than a bare string because §4.2/§5.2 require the\n * namespace to reach a catalog predicate through the parameter channel: a\n * bare-string seam has nothing to bind through, so it can only splice the\n * name into the statement as an escaped literal.\n *\n * @returns Bound SELECT returning rows with a `name` column\n */\n abstract generateInventoryTables(): { sql: string; params: unknown[] };\n\n /**\n * The live-namespace enum inventory, or null for dialects with no standalone\n * enum types.\n */\n abstract generateInventoryEnums(): {\n sql: string;\n params: unknown[];\n } | null;\n\n /**\n * Generates SQL for dropping a table.\n *\n * There is no `CASCADE` arm. §6.1: a namespace is a containment boundary, and\n * `DROP TABLE ... CASCADE` drops dependants in OTHER namespaces even when the\n * enumeration that produced this name only ever selected one. The dependency\n * graph is materialized as explicit foreign-key drops before the table drops\n * instead, and an unknown external dependency then aborts the operation\n * through PostgreSQL's default `RESTRICT` rather than deleting collaterally.\n *\n * @param tableName - The table name\n * @returns SQL DROP TABLE statement\n */\n generateDropTableSQL(tableName: string): string {\n return `DROP TABLE IF EXISTS ${this.tableRef(tableName, \"live\")}`;\n }\n\n /**\n * Generates SQL for dropping an enum type.\n * Returns null for databases that don't support enums.\n *\n * @param enumName - The enum name\n * @returns SQL DROP TYPE statement or null\n */\n generateDropEnumSQL(_enumName: string): string | null {\n return null; // Override in PostgreSQL driver\n }\n\n // ===========================================================================\n // DISPATCH (final - not meant to be overridden)\n // ===========================================================================\n\n /**\n * The one owner of provider statement boundaries for generated DDL.\n */\n compileStatements(\n operation: DiffOperation,\n context: DDLContext\n ): readonly string[] {\n const generated = this.generateOperation(operation, context);\n const statements = typeof generated === \"string\" ? [generated] : generated;\n return this.filterStatements(\n operation.type === \"renameTable\" || operation.type === \"renameColumn\"\n ? [...statements, ...this.compileDerivedRenames(operation, context)]\n : statements\n );\n }\n\n private generateOperation(\n operation: DiffOperation,\n context: DDLContext\n ): GeneratedStatements {\n switch (operation.type) {\n case \"createTable\":\n return this.generateCreateTable(operation, context);\n case \"dropTable\":\n return this.generateDropTable(operation, context);\n case \"renameTable\":\n return this.generateRenameTable(operation, context);\n case \"addColumn\":\n return this.generateAddColumn(operation, context);\n case \"dropColumn\":\n return this.generateDropColumn(operation, context);\n case \"renameColumn\":\n return this.generateRenameColumn(operation, context);\n case \"alterColumn\":\n // Asked HERE rather than in each driver's `generateAlterColumn`: the\n // question is one — \"can this dialect re-read the stored bytes as the\n // new type?\" — and three copies of it would drift the way the three\n // conversion routes already did (PostgreSQL cast, SQLite rebuild,\n // MySQL MODIFY, each silently wrong in its own way).\n refuseBinaryReencoding(\n operation.tableName,\n operation.columnName,\n operation.from.type,\n operation.to.type,\n this.dialect\n );\n return this.generateAlterColumn(operation, context);\n case \"createIndex\":\n return this.generateCreateIndex(operation, context);\n case \"dropIndex\":\n return this.generateDropIndex(operation, context);\n case \"addForeignKey\":\n return this.generateAddForeignKey(operation, context);\n case \"dropForeignKey\":\n return this.generateDropForeignKey(operation, context);\n case \"addUniqueConstraint\":\n return this.generateAddUniqueConstraint(operation, context);\n case \"dropUniqueConstraint\":\n return this.generateDropUniqueConstraint(operation, context);\n case \"addPrimaryKey\":\n return this.generateAddPrimaryKey(operation, context);\n case \"dropPrimaryKey\":\n return this.generateDropPrimaryKey(operation, context);\n case \"createEnum\":\n return this.generateCreateEnum(operation, context);\n case \"dropEnum\":\n return this.generateDropEnum(operation, context);\n case \"alterEnum\":\n return this.generateAlterEnum(operation, context);\n default:\n throw new MigrationError(\n `Unknown operation type: ${(operation as any).type}`,\n VibORMErrorCode.INTERNAL_ERROR\n );\n }\n }\n\n /**\n * Generates display DDL for a diff operation.\n */\n generateDDL(operation: DiffOperation, context: DDLContext): string {\n return this.compileStatements(operation, context).join(\";\\n\");\n }\n}\n","/**\n * Migration Driver Registry\n *\n * Central registry for migration drivers. Drivers are registered by their\n * driver name and can be looked up by driver name or dialect.\n *\n * This module registers nothing: the entry an application imports does\n * (`dialects/*.ts`), so a bundle carries only the dialects it registers.\n */\n\nimport type {\n AnyDriver,\n SqliteMigrationCapability,\n} from \"../../drivers/driver\";\nimport { MigrationError, VibORMErrorCode } from \"../../errors\";\nimport {\n DEFAULT_MIGRATION_LIMITS,\n type ResolvedMigrationLimits,\n} from \"../limits\";\nimport { resolveMigrationEstate, selectManagedSnapshot } from \"../target\";\nimport type { MigrationTarget } from \"../types\";\nimport type { MigrationDriver } from \"./base\";\nimport type { Dialect } from \"./types\";\n\nexport type {\n AddColumnOperation,\n AddForeignKeyOperation,\n AddPrimaryKeyOperation,\n AddUniqueConstraintOperation,\n AlterColumnOperation,\n AlterEnumOperation,\n CreateEnumOperation,\n CreateIndexOperation,\n CreateTableOperation,\n DDLContext,\n DropColumnOperation,\n DropEnumOperation,\n DropForeignKeyOperation,\n DropIndexOperation,\n DropPrimaryKeyOperation,\n DropTableOperation,\n DropUniqueConstraintOperation,\n RenameColumnOperation,\n RenameTableOperation,\n} from \"./base\";\n// Export base class and types\nexport { MigrationDriver } from \"./base\";\nexport type { Dialect, MigrationCapabilities } from \"./types\";\n\n// =============================================================================\n// REGISTRY\n// =============================================================================\n\n/**\n * Registry of migration drivers by driver name.\n */\nconst driverRegistry = new Map<string, MigrationDriver>();\n\n/**\n * The implementation each stock SQLite driver binds to, by name.\n *\n * SQLite is the one dialect with two implementations, so a SQLite driver never\n * binds by dialect: a driver declaring `sqliteMigrationCapability` binds to\n * `sqlite3` whatever its name (so a declaring libSQL subclass never reaches the\n * libsql implementation's unvalidated native ALTER COLUMN), an undeclared stock\n * driver binds here, and an undeclared custom one has no binding at all.\n * Binding is not admission: effectful work still needs the declaration\n * (`admission.ts`). PostgreSQL and MySQL have one implementation each,\n * registered under the dialect's name.\n */\nconst STOCK_SQLITE_BINDINGS: ReadonlyMap<string, string> = new Map([\n [\"sqlite3\", \"sqlite3\"],\n [\"bun-sqlite\", \"sqlite3\"],\n [\"d1\", \"sqlite3\"],\n [\"libsql\", \"libsql\"],\n]);\n\n/**\n * The one admitted declaration, as bound. Its type admits no other value, so\n * it cannot drift from the `SQLITE_MIGRATION_CAPABILITY` drivers declare; it is\n * spelled here so the migration bundle does not import the driver module.\n */\nconst SQLITE_MIGRATION_CAPABILITY: SqliteMigrationCapability = Object.freeze({\n foreignKeys: \"pragma\",\n reservedTablePrefixes: \"none\",\n exclusion: \"database-write-lock\",\n});\n\n/**\n * Registers a migration driver.\n *\n * @param driver - The migration driver to register\n */\nexport function registerMigrationDriver(driver: MigrationDriver): void {\n driverRegistry.set(driver.driverName, driver);\n}\n\n/**\n * A migration driver bound to one estate.\n *\n * Binding narrows two of the base class's optional facts — the durable target\n * and the execution driver — to present ones, so an admitted live boundary\n * never has to ask whether its driver knows which estate it serves. The live\n * `namespace` stays optional: an unbound MySQL adapter binds to a real estate,\n * and refusing it for effectful work belongs to the admission owner.\n */\nexport interface BoundMigrationDriver extends MigrationDriver {\n readonly target: MigrationTarget;\n readonly executionDriver: AnyDriver;\n /** The SQLite capability read once at binding; admission decides from it. */\n readonly sqliteMigrationCapability: SqliteMigrationCapability | undefined;\n /** The command's limits: the client's own, or the defaults. */\n readonly limits: ResolvedMigrationLimits;\n}\n\n/**\n * Looks up the dialect implementation and returns it BOUND to this driver's\n * estate.\n *\n * The registry stays the dialect implementation registry and its entries stay\n * stateless: binding never mutates a registered singleton and never parks an\n * active namespace in module-level state. The bound value is a frozen view\n * whose prototype is the registered instance, so two clients on two schemas\n * hold two immutable targets over one implementation.\n *\n * This is the ONE place a driver becomes a migration estate. Resolving the\n * estate here is what makes an unproven PostgreSQL adapter fail at lookup\n * rather than at some later statement.\n *\n * The durable target and the live namespace are BOTH taken from one\n * `resolveMigrationEstate` call, which reads `adapter.namespace` exactly once.\n * Binding must never read that fact a second time: an accessor-backed custom\n * adapter could answer differently, and the frozen view would then name one\n * estate in its target and render another in its DDL.\n *\n * @throws MigrationError if no implementation is registered, or if the estate\n * target cannot be proven\n */\nexport function getMigrationDriver(\n driver: AnyDriver,\n tables?: readonly string[],\n limits: ResolvedMigrationLimits = DEFAULT_MIGRATION_LIMITS\n): BoundMigrationDriver {\n const { target: baseTarget, namespace } = resolveMigrationEstate(driver);\n const target =\n tables === undefined\n ? baseTarget\n : Object.freeze({ ...baseTarget, tables });\n const capability =\n target.dialect === \"sqlite\"\n ? readSqliteMigrationCapability(driver)\n : undefined;\n const implementation = findMigrationDriver(\n driver.driverName,\n target.dialect,\n capability\n );\n\n const bound: BoundMigrationDriver = Object.create(implementation);\n Object.defineProperties(bound, {\n target: { value: target, enumerable: true },\n executionDriver: { value: driver, enumerable: true },\n namespace: { value: namespace, enumerable: true },\n sqliteMigrationCapability: { value: capability, enumerable: true },\n limits: { value: limits, enumerable: true },\n introspect: {\n async value(\n this: MigrationDriver,\n executeRaw: Parameters<MigrationDriver[\"introspect\"]>[0]\n ) {\n return selectManagedSnapshot(\n await implementation.introspect.call(this, executeRaw),\n target\n );\n },\n },\n });\n Object.freeze(bound);\n return bound;\n}\n\n/**\n * The driver's SQLite migration capability, read ONCE, or undefined when it\n * declares none. Only the exact values count: each is a safety claim, and a\n * mistyped claim must not read as an approximate one.\n */\nfunction readSqliteMigrationCapability(\n driver: AnyDriver\n): SqliteMigrationCapability | undefined {\n const declared: unknown = driver.sqliteMigrationCapability;\n if (typeof declared !== \"object\" || declared === null) return;\n for (const [key, value] of Object.entries(SQLITE_MIGRATION_CAPABILITY)) {\n if (Reflect.get(declared, key) !== value) return;\n }\n return SQLITE_MIGRATION_CAPABILITY;\n}\n\n/** Resolves the registered implementation this driver binds to. */\nfunction findMigrationDriver(\n driverName: string,\n dialect: Dialect,\n capability: SqliteMigrationCapability | undefined\n): MigrationDriver {\n let name: string | undefined = dialect;\n if (dialect === \"sqlite\") {\n name = capability ? \"sqlite3\" : STOCK_SQLITE_BINDINGS.get(driverName);\n }\n const driver = name === undefined ? undefined : driverRegistry.get(name);\n if (driver) return driver;\n throw new MigrationError(\n name === undefined\n ? `The SQLite driver \"${driverName}\" declares no \\`sqliteMigrationCapability\\`, so no migration implementation binds to it.`\n : `No migration driver registered for \"${driverName}\" (dialect: ${dialect}).`,\n VibORMErrorCode.DRIVER_NOT_SUPPORTED,\n { meta: { driver: driverName, dialect } }\n );\n}\n","import type { DateTimePhysicalForm } from \"@validation/primitives/datetime-physical-codec\";\nimport {\n MAX_DATETIME_EPOCH_MILLISECONDS,\n MIN_DATETIME_EPOCH_MILLISECONDS,\n} from \"@validation/primitives/datetime-values\";\nimport { createIdentifierQuoter } from \"../../../../sql/identifiers\";\n\nconst MILLISECONDS_PER_DAY = 86_400_000;\nconst UNIX_EPOCH_JULIAN_DAY = 2_440_587.5;\n/**\n * `abs(INT64_MIN)` raises SQLite's \"integer overflow\" error: the one abort\n * every copy and rewrite expression uses to stop on a value it cannot convert.\n */\nexport const SQLITE_ABORT = \"abs(-9223372036854775808)\";\n\nconst ISO_DATE = \"[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]\";\nconst ISO_TIME = \"[0-9][0-9]:[0-9][0-9]:[0-9][0-9]\";\nconst ISO_OFFSET = \"[+-][0-9][0-9]:[0-9][0-9]\";\n/**\n * The stored-text grammar: the client's ISO input grammar plus SQLite's own\n * zone-less spelling (`datetime('now')`, `CURRENT_TIMESTAMP`), which SQLite\n * defines as UTC.\n */\nconst ISO_TIMESTAMP_SHAPES = [\n `${ISO_DATE} ${ISO_TIME}`,\n `${ISO_DATE} ${ISO_TIME}.[0-9]`,\n `${ISO_DATE} ${ISO_TIME}.[0-9][0-9]`,\n `${ISO_DATE} ${ISO_TIME}.[0-9][0-9][0-9]`,\n `${ISO_DATE}T${ISO_TIME}Z`,\n `${ISO_DATE}T${ISO_TIME}.[0-9]Z`,\n `${ISO_DATE}T${ISO_TIME}.[0-9][0-9]Z`,\n `${ISO_DATE}T${ISO_TIME}.[0-9][0-9][0-9]Z`,\n `${ISO_DATE}T${ISO_TIME}${ISO_OFFSET}`,\n `${ISO_DATE}T${ISO_TIME}.[0-9]${ISO_OFFSET}`,\n `${ISO_DATE}T${ISO_TIME}.[0-9][0-9]${ISO_OFFSET}`,\n `${ISO_DATE}T${ISO_TIME}.[0-9][0-9][0-9]${ISO_OFFSET}`,\n];\n\nexport function sqliteDateTimeTargetRequiresRecreation(\n from: DateTimePhysicalForm | undefined,\n to: DateTimePhysicalForm | undefined\n): boolean {\n return to !== undefined && from !== to;\n}\n\n/** SQLite spelling of JavaScript's `Math.round`, including negative halves. */\nfunction roundToInteger(expression: string): string {\n const integer = `CAST(${expression} AS INTEGER)`;\n const fraction = `(${expression} - ${integer})`;\n return (\n `(${integer} + CASE ` +\n `WHEN ${fraction} >= 0.5 THEN 1 ` +\n `WHEN ${fraction} < -0.5 THEN -1 ELSE 0 END)`\n );\n}\n\nfunction julianToEpochMilliseconds(julianDay: string): string {\n return roundToInteger(\n `((${julianDay} - ${UNIX_EPOCH_JULIAN_DAY}) * ${MILLISECONDS_PER_DAY})`\n );\n}\n\nfunction epochMillisecondsToJulian(epochMilliseconds: string): string {\n return (\n `((${epochMilliseconds} / ${MILLISECONDS_PER_DAY}.0) + ` +\n `${UNIX_EPOCH_JULIAN_DAY})`\n );\n}\n\nfunction textFractionMilliseconds(source: string): string {\n const first = `CAST(substr(${source}, 21, 1) AS INTEGER)`;\n const second = `CAST(substr(${source}, 22, 1) AS INTEGER)`;\n const third = `CAST(substr(${source}, 23, 1) AS INTEGER)`;\n return (\n `(CASE WHEN substr(${source}, 20, 1) <> '.' THEN 0 ELSE ` +\n `${first} * 100 + ` +\n `CASE WHEN substr(${source}, 22, 1) GLOB '[0-9]' THEN ${second} * 10 + ` +\n `CASE WHEN substr(${source}, 23, 1) GLOB '[0-9]' THEN ${third} ELSE 0 END ` +\n \"ELSE 0 END END)\"\n );\n}\n\n/** SQLite's zone-less UTC spelling separates date and time with a space. */\nfunction isZoneless(source: string): string {\n return `substr(${source}, 11, 1) = ' '`;\n}\n\nfunction textOffsetMilliseconds(source: string): string {\n const magnitude =\n `((CAST(substr(${source}, -5, 2) AS INTEGER) * 60 + ` +\n `CAST(substr(${source}, -2, 2) AS INTEGER)) * 60000)`;\n return (\n `(CASE WHEN substr(${source}, -1, 1) = 'Z' OR ${isZoneless(source)} THEN 0 ` +\n `WHEN substr(${source}, -6, 1) = '+' THEN ${magnitude} ` +\n `ELSE -${magnitude} END)`\n );\n}\n\n/** Epoch milliseconds without SQLite's narrower timezone-offset parser. */\nfunction textToEpochMilliseconds(source: string): string {\n const day = julianToEpochMilliseconds(\n `julianday(substr(${source}, 1, 10) || 'T00:00:00Z')`\n );\n const local =\n `(${day} + CAST(substr(${source}, 12, 2) AS INTEGER) * 3600000 + ` +\n `CAST(substr(${source}, 15, 2) AS INTEGER) * 60000 + ` +\n `CAST(substr(${source}, 18, 2) AS INTEGER) * 1000 + ` +\n `${textFractionMilliseconds(source)})`;\n return `(${local} - ${textOffsetMilliseconds(source)})`;\n}\n\n/** Canonical ISO text for an admitted SQLite-range epoch millisecond. */\nfunction epochMillisecondsToText(epochMilliseconds: string): string {\n const wholeSeconds =\n `(CASE WHEN ${epochMilliseconds} < 0 AND ` +\n `${epochMilliseconds} % 1000 <> 0 ` +\n `THEN ${epochMilliseconds} / 1000 - 1 ` +\n `ELSE ${epochMilliseconds} / 1000 END)`;\n const milliseconds = `(((${epochMilliseconds} % 1000) + 1000) % 1000)`;\n return (\n \"(\" +\n `strftime('%Y-%m-%dT%H:%M:%S', ${wholeSeconds}, 'unixepoch') || ` +\n `printf('.%03dZ', ${milliseconds})` +\n \")\"\n );\n}\n\nfunction epochMilliseconds(source: string, form: DateTimePhysicalForm): string {\n if (form === \"epochMillis\") return source;\n if (form === \"julianDay\") return julianToEpochMilliseconds(source);\n return textToEpochMilliseconds(source);\n}\n\n/** SQL transcription of the stored-text grammar (`ISO_TIMESTAMP_SHAPES`). */\nfunction isIsoTimestamp(source: string): string {\n return `(${ISO_TIMESTAMP_SHAPES.map((shape) => `${source} GLOB '${shape}'`).join(\" OR \")})`;\n}\n\n/** Component rules used by the public ISO timestamp admission boundary. */\nfunction isAdmittedIsoTimestamp(source: string): string {\n const year = `CAST(substr(${source}, 1, 4) AS INTEGER)`;\n const month = `CAST(substr(${source}, 6, 2) AS INTEGER)`;\n const day = `CAST(substr(${source}, 9, 2) AS INTEGER)`;\n const hour = `CAST(substr(${source}, 12, 2) AS INTEGER)`;\n const minute = `CAST(substr(${source}, 15, 2) AS INTEGER)`;\n const second = `CAST(substr(${source}, 18, 2) AS INTEGER)`;\n const zulu = `substr(${source}, -1, 1) = 'Z'`;\n const offsetHour = `CAST(substr(${source}, -5, 2) AS INTEGER)`;\n const offsetMinute = `CAST(substr(${source}, -2, 2) AS INTEGER)`;\n const isLeapYear = `(${year} % 4 = 0 AND (${year} % 100 <> 0 OR ${year} % 400 = 0))`;\n const lastDay =\n `(CASE ${month} ` +\n `WHEN 2 THEN CASE WHEN ${isLeapYear} THEN 29 ELSE 28 END ` +\n \"WHEN 4 THEN 30 WHEN 6 THEN 30 WHEN 9 THEN 30 WHEN 11 THEN 30 \" +\n \"ELSE 31 END)\";\n return (\n `${isIsoTimestamp(source)} AND ${month} BETWEEN 1 AND 12 AND ` +\n `${day} BETWEEN 1 AND ${lastDay} AND ${hour} BETWEEN 0 AND 23 AND ` +\n `${minute} BETWEEN 0 AND 59 AND ${second} BETWEEN 0 AND 59 AND ` +\n `(${zulu} OR ${isZoneless(source)} OR (${offsetHour} BETWEEN 0 AND 23 AND ${offsetMinute} BETWEEN 0 AND 59)) AND ` +\n `julianday(substr(${source}, 1, 10) || 'T00:00:00Z') IS NOT NULL`\n );\n}\n\nfunction sourceIsExact(\n source: string,\n form: DateTimePhysicalForm,\n epoch: string\n): string {\n if (form === \"text\") {\n return (\n `typeof(${source}) = 'text' AND ${isAdmittedIsoTimestamp(source)} AND ` +\n `${epoch} BETWEEN ${MIN_DATETIME_EPOCH_MILLISECONDS} AND ${MAX_DATETIME_EPOCH_MILLISECONDS}`\n );\n }\n if (form === \"epochMillis\") {\n return (\n `typeof(${source}) = 'integer' AND ` +\n `${epoch} BETWEEN ${MIN_DATETIME_EPOCH_MILLISECONDS} AND ${MAX_DATETIME_EPOCH_MILLISECONDS}`\n );\n }\n return (\n `typeof(${source}) = 'real' AND ` +\n `${epoch} BETWEEN ${MIN_DATETIME_EPOCH_MILLISECONDS} AND ${MAX_DATETIME_EPOCH_MILLISECONDS} AND ` +\n `${epochMillisecondsToJulian(epoch)} = ${source}`\n );\n}\n\nfunction targetValue(epoch: string, form: DateTimePhysicalForm): string {\n if (form === \"text\") return epochMillisecondsToText(epoch);\n if (form === \"epochMillis\") return epoch;\n return epochMillisecondsToJulian(epoch);\n}\n\nfunction targetIsExact(\n epoch: string,\n form: DateTimePhysicalForm,\n value: string\n): string {\n if (form === \"text\") {\n return `${value} IS NOT NULL AND ${isIsoTimestamp(value)}`;\n }\n if (form === \"epochMillis\") return \"1\";\n return `${julianToEpochMilliseconds(value)} = ${epoch}`;\n}\n\n/**\n * Converts one copied SQLite DateTime between its declared physical forms.\n *\n * The guard is the sole integrity boundary. It accepts only a value that is an\n * exact member of the source vocabulary and whose target representation\n * decodes to the same millisecond. `abs(INT64_MIN)` is SQLite's built-in,\n * deterministic error expression; it makes malformed, out-of-range, and\n * inexact rows abort the recreation instead of being rounded or reinterpreted.\n * An authenticated snapshot proves a same-form source and can retain it\n * unchanged. A live-introspected source has no logical marker, so even a\n * same-physical-form adoption crosses this guard before it becomes DateTime.\n */\nexport function sqliteDateTimeCopyExpression(\n source: string,\n from: DateTimePhysicalForm,\n to: DateTimePhysicalForm,\n isDeclaredSource: boolean\n): string {\n if (from === to && isDeclaredSource) return source;\n const epoch = epochMilliseconds(source, from);\n const value = from === to ? source : targetValue(epoch, to);\n const exact =\n from === to\n ? sourceIsExact(source, from, epoch)\n : `${sourceIsExact(source, from, epoch)} AND ${targetIsExact(epoch, to, value)}`;\n return (\n `CASE WHEN ${source} IS NULL THEN NULL ` +\n `WHEN ${exact} THEN ${value} ` +\n `ELSE ${SQLITE_ABORT} END`\n );\n}\n\n/** A reviewed manual-migration expression; the argument is a physical column name. */\nexport function sqliteCanonicalDateTimeExpression(columnName: string): string {\n const source = createIdentifierQuoter('\"')(columnName);\n const epoch = textToEpochMilliseconds(source);\n const value = epochMillisecondsToText(epoch);\n return `CASE WHEN ${source} IS NULL THEN NULL WHEN ${sourceIsExact(source, \"text\", epoch)} AND ${targetIsExact(epoch, \"text\", value)} THEN ${value} ELSE ${SQLITE_ABORT} END`;\n}\n\n/** The Time writer, the `viborm check --db` audit and the repair share one physical grammar. */\nfunction timeSource(source: string): { valid: string; value: string } {\n const shapes = [\n ISO_TIME,\n `${ISO_TIME}.[0-9]`,\n `${ISO_TIME}.[0-9][0-9]`,\n `${ISO_TIME}.[0-9][0-9][0-9]`,\n ];\n const valid = `typeof(${source}) = 'text' AND (${shapes.map((shape) => `${source} GLOB '${shape}'`).join(\" OR \")}) AND CAST(substr(${source},1,2) AS INTEGER) BETWEEN 0 AND 23 AND CAST(substr(${source},4,2) AS INTEGER) BETWEEN 0 AND 59 AND CAST(substr(${source},7,2) AS INTEGER) BETWEEN 0 AND 59`;\n const value = `substr(${source},1,8) || '.' || substr(CASE WHEN length(${source}) = 8 THEN '000' ELSE substr(${source},10) || '000' END,1,3)`;\n return { valid, value };\n}\n\n/** Canonical millisecond Time storage; malformed source rows abort the statement. */\nexport function sqliteCanonicalTimeExpression(columnName: string): string {\n const source = createIdentifierQuoter('\"')(columnName);\n const { valid, value } = timeSource(source);\n return `CASE WHEN ${source} IS NULL THEN NULL WHEN ${valid} THEN ${value} ELSE ${SQLITE_ABORT} END`;\n}\n\n/** Exact canonical carrier predicates for `viborm check --db`: NULL passes, unknown/malformed does not. */\nexport function sqliteCanonicalDateTimePredicate(columnName: string): string {\n const source = createIdentifierQuoter('\"')(columnName);\n const epoch = textToEpochMilliseconds(source);\n const value = epochMillisecondsToText(epoch);\n return `CASE WHEN ${source} IS NULL THEN 1 WHEN ${sourceIsExact(source, \"text\", epoch)} AND ${targetIsExact(epoch, \"text\", value)} AND ${source} = ${value} THEN 1 ELSE 0 END`;\n}\n\nexport function sqliteCanonicalTimePredicate(columnName: string): string {\n const source = createIdentifierQuoter('\"')(columnName);\n const { valid, value } = timeSource(source);\n return `CASE WHEN ${source} IS NULL THEN 1 WHEN ${valid} AND ${source} = ${value} THEN 1 ELSE 0 END`;\n}\n\ntype TemporalType = \"datetime\" | \"time\";\n\n/**\n * One text DateTime/Time column (scalar or JSON list): which rows lie outside\n * the canonical carrier, and the canonical value a row rewrites to. NULL is\n * canonical. A list is rewritten member by member, in array order; a non-text\n * member or a non-array carrier aborts like a malformed scalar.\n */\nfunction temporalCarrier(\n table: string,\n column: string,\n type: TemporalType,\n list: boolean\n): { readonly noncanonical: string; readonly canonical: string } {\n const [predicate, expression] =\n type === \"time\"\n ? [sqliteCanonicalTimePredicate, sqliteCanonicalTimeExpression]\n : [sqliteCanonicalDateTimePredicate, sqliteCanonicalDateTimeExpression];\n if (!list) {\n return {\n noncanonical: `NOT ${predicate(column)}`,\n canonical: expression(column),\n };\n }\n const quote = createIdentifierQuoter('\"');\n const name = `${quote(table)}.${quote(column)}`;\n // json_each is reached only after proving an array carrier.\n const array = `json_valid(${name}) AND json_type(${name}) = 'array'`;\n return {\n noncanonical: `CASE WHEN ${name} IS NULL THEN 0 WHEN ${array} THEN EXISTS (SELECT 1 FROM json_each(${name}) WHERE type <> 'text' OR NOT ${predicate(\"value\")}) ELSE 1 END`,\n canonical: `CASE WHEN ${array} THEN (SELECT json_group_array(CASE WHEN \"type\" = 'text' THEN ${expression(\"value\")} ELSE ${SQLITE_ABORT} END) FROM (SELECT \"value\", \"type\" FROM json_each(${name}) ORDER BY \"key\")) ELSE ${SQLITE_ABORT} END`,\n };\n}\n\n/** Counts one text DateTime/Time column's rows outside the canonical carrier. */\nexport function sqliteNoncanonicalTemporalCount(\n table: string,\n column: string,\n type: TemporalType,\n list: boolean\n): string {\n const { noncanonical } = temporalCarrier(table, column, type, list);\n return `SELECT count(*) AS noncanonical FROM ${createIdentifierQuoter('\"')(table)} WHERE ${noncanonical}`;\n}\n\n/** Rewrites one column's noncanonical rows into canonical text; a malformed value aborts the statement. */\nexport function sqliteCanonicalTemporalUpdate(\n table: string,\n column: string,\n type: TemporalType,\n list: boolean\n): string {\n const quote = createIdentifierQuoter('\"');\n const { noncanonical, canonical } = temporalCarrier(\n table,\n column,\n type,\n list\n );\n return `UPDATE ${quote(table)} SET ${quote(column)} = ${canonical} WHERE ${noncanonical}`;\n}\n","import { errorCause } from \"../errors/diagnostic-safety\";\n/**\n * SQLite storage that typed queries compare but never inspect: text DateTime\n * and Time (scalar or JSON list) and checked decimals.\n *\n * `auditStorage` counts what needs repair (`viborm check --db`, runtime and\n * Durable Object callers). `canonicalizeSqliteStorage` rewrites it after\n * manual SQL, inside that program's transaction. Time columns and\n * DateTime lists come from the client's models, because a schema snapshot\n * marks only scalar DateTime and decimals.\n */\n\nimport {\n sqliteCanonicalTemporalUpdate,\n sqliteNoncanonicalTemporalCount,\n} from \"../adapters/databases/sqlite/storage/datetime\";\nimport {\n isSqliteDecimalStorage,\n sqliteDecimalCopyExpression,\n sqliteDecimalStorageKind,\n} from \"../adapters/databases/sqlite/storage/decimal\";\nimport type { AnyDriver } from \"../drivers/driver\";\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\nimport { type AnyModel, getTableName, type ModelState } from \"../schema/model\";\nimport { sqliteDateTimePhysicalForm } from \"../schema/scalars/datetime/physical\";\nimport { createIdentifierQuoter } from \"../sql/identifiers\";\nimport type { DecimalDescriptor } from \"../validation/primitives/decimal-codec\";\nimport { executeExactSql } from \"./execute-dispatch\";\nimport type { MigrationClient } from \"./push/planner\";\nimport type { ColumnDef, SchemaSnapshot } from \"./types\";\nimport type { MigrationOperationV1 } from \"./v1-types\";\n\n/** One audited column; `null` counts and declarations mean the column is missing. */\nexport type StorageColumnAudit = {\n readonly table: string;\n readonly column: string;\n} & (\n | {\n readonly type: \"datetime\" | \"time\";\n readonly list: boolean;\n readonly noncanonical: number | null;\n }\n | {\n readonly type: \"decimal\";\n /** The catalog's declared type. */\n readonly declared: string | null;\n readonly checked: boolean;\n }\n);\n\ntype StorageColumn = {\n readonly table: string;\n readonly column: string;\n readonly list: boolean;\n} & (\n | { readonly type: \"datetime\" | \"time\" }\n | { readonly type: \"decimal\"; readonly decimal: DecimalDescriptor }\n);\n\ninterface CatalogColumn {\n readonly definition: string | null;\n readonly name: string;\n readonly type: string;\n readonly nullable: boolean;\n}\n\nconst quote = createIdentifierQuoter('\"');\n\n/** Every decimal column, and every DateTime/Time column stored as text. */\nfunction storageColumns(models: Record<string, AnyModel>): StorageColumn[] {\n const columns: StorageColumn[] = [];\n for (const [name, model] of Object.entries(models)) {\n const table = getTableName(model, name);\n const state: ModelState = model[\"~\"].state;\n for (const [field, scalar] of Object.entries(state.scalars)) {\n const definition = scalar[\"~\"].state;\n const list = definition.array === true;\n const column = model[\"~\"].getFieldName(field).sql;\n if (definition.type === \"decimal\") {\n columns.push({\n table,\n column,\n list,\n type: \"decimal\",\n decimal: definition.decimal,\n });\n } else if (\n definition.type === \"time\" ||\n (definition.type === \"datetime\" &&\n (list ||\n sqliteDateTimePhysicalForm(scalar[\"~\"].nativeType) === \"text\"))\n ) {\n columns.push({ table, column, list, type: definition.type });\n }\n }\n }\n return columns;\n}\n\n/** One SQLite table's declared columns, each beside the table's stored definition. */\nasync function readCatalog(\n driver: AnyDriver,\n table: string\n): Promise<CatalogColumn[]> {\n const { rows } = await driver._executeRaw<\n Omit<CatalogColumn, \"nullable\"> & { notnull: number; pk: number }\n >(\n `SELECT s.sql AS definition, p.name, p.type, p.\"notnull\", p.pk FROM sqlite_schema AS s JOIN pragma_table_info(s.name) AS p WHERE s.type = 'table' AND s.name = ?`,\n [table]\n );\n // SQLite reports a primary key nullable; VibORM writes it NOT NULL.\n return rows.map(({ notnull, pk, ...column }) => ({\n ...column,\n nullable: Number(notnull) === 0 && Number(pk) === 0,\n }));\n}\n\n/**\n * Audit the SQLite storage of `client`'s models: one catalog read per table\n * decides which audited columns exist; each existing text DateTime/Time\n * column's noncanonical rows are counted (one scan each), and each decimal\n * column is checked against the scaled-integer storage of its descriptor.\n * Other dialects store native types and return no audit.\n */\nexport async function auditStorage(\n client: Pick<MigrationClient, \"$driver\" | \"$schema\">\n): Promise<StorageColumnAudit[]> {\n const driver = client.$driver;\n if (driver.dialect !== \"sqlite\") return [];\n const catalogs = new Map<string, Promise<CatalogColumn[]>>();\n const audits: StorageColumnAudit[] = [];\n for (const target of storageColumns(client.$schema)) {\n const { table, column } = target;\n let catalog = catalogs.get(table);\n if (!catalog) {\n catalog = readCatalog(driver, table);\n catalogs.set(table, catalog);\n }\n // A missing table has no catalog rows: each audited column is missing.\n const row = (await catalog).find((entry) => entry.name === column);\n if (target.type === \"decimal\") {\n audits.push({\n table,\n column,\n type: \"decimal\",\n declared: row?.type ?? null,\n checked:\n row !== undefined &&\n isSqliteDecimalStorage(\n row.definition,\n row,\n target.decimal,\n target.list ? \"list\" : \"scalar\",\n quote\n ),\n });\n continue;\n }\n // Never scan a missing column: SQLite may read its quoted name as text.\n const scan =\n row &&\n (await driver._executeRaw<{ noncanonical: number }>(\n sqliteNoncanonicalTemporalCount(table, column, target.type, target.list)\n ));\n audits.push({\n table,\n column,\n type: target.type,\n list: target.list,\n noncanonical: scan ? Number(scan.rows[0]?.noncanonical) : null,\n });\n }\n return audits;\n}\n\n/**\n * The storage one destination column needs canonical, or `undefined`. The\n * snapshot proves scalar text DateTime and decimal lists (a decimal scalar's\n * CHECK already refuses foreign values); it does not mark Time or DateTime\n * lists, so those come from the client's models, held to the column's\n * physical type.\n */\nfunction destinationTarget(\n table: string,\n column: ColumnDef,\n declared: StorageColumn | undefined\n): StorageColumn | undefined {\n const base = { table, column: column.name };\n if (column.dateTime === \"text\") {\n return { ...base, list: false, type: \"datetime\" };\n }\n if (column.decimal) {\n return sqliteDecimalStorageKind(column) === \"list\"\n ? { ...base, list: true, type: \"decimal\", decimal: column.decimal }\n : undefined;\n }\n const temporal =\n declared?.type === \"time\" ||\n (declared?.type === \"datetime\" && declared.list);\n return temporal &&\n column.type.toUpperCase() === (declared.list ? \"JSON\" : \"TEXT\")\n ? declared\n : undefined;\n}\n\n/** Rewrites one column into canonical storage; a value outside its domain aborts the statement. */\nfunction canonicalStatement(target: StorageColumn): string {\n if (target.type !== \"decimal\") {\n return sqliteCanonicalTemporalUpdate(\n target.table,\n target.column,\n target.type,\n target.list\n );\n }\n // The identity conversion routes a member outside the domain to the\n // sentinel the column's own CHECK refuses.\n const source = `${quote(target.table)}.${quote(target.column)}`;\n const checked = sqliteDecimalCopyExpression(\n source,\n target.decimal,\n target.decimal,\n \"list\"\n );\n return `UPDATE ${quote(target.table)} SET ${quote(target.column)} = ${checked} WHERE ${source} IS NOT ${checked}`;\n}\n\n/**\n * After manual SQL — a manual transition, its manual rollback, or the\n * `resolve` that completes one — and inside that program's transaction:\n * rewrite the destination's text DateTime/Time columns (scalar and JSON list)\n * into canonical text, reading SQLite's zone-less text as UTC, and check\n * decimal-list members. A program without a manual operation, or another\n * dialect, has nothing to rewrite. A row that cannot be rewritten stops the\n * program before its marker moves.\n */\nexport async function canonicalizeSqliteStorage(\n producer: AnyDriver,\n operations: readonly MigrationOperationV1[],\n models: Record<string, AnyModel>,\n destination: SchemaSnapshot\n): Promise<void> {\n if (\n producer.dialect !== \"sqlite\" ||\n !operations.some((operation) => operation.origin === \"manual\")\n ) {\n return;\n }\n const declared = new Map(\n storageColumns(models).map((target) => [\n `${target.table}\\0${target.column}`,\n target,\n ])\n );\n for (const table of destination.tables) {\n for (const column of table.columns) {\n const target = destinationTarget(\n table.name,\n column,\n declared.get(`${table.name}\\0${column.name}`)\n );\n if (!target) continue;\n try {\n await executeExactSql(producer, canonicalStatement(target));\n } catch (error) {\n // A malformed value aborts the rewrite; so does a constraint the\n // rewrite meets, such as two spellings of one instant in a unique column.\n throw new MigrationError(\n `The manual SQL left \"${target.table}\".\"${target.column}\" holding a ${target.type}${target.list ? \" list\" : \"\"} value that cannot be rewritten into canonical storage (${error instanceof Error ? error.message : String(error)}); the marker did not move`,\n VibORMErrorCode.MIGRATION_DRIFT,\n { cause: errorCause(error) }\n );\n }\n }\n }\n}\n","/**\n * The one virtual-root snapshot. Not a stored second root.\n */\n\nimport type { SchemaSnapshot } from \"./types\";\n\nexport function emptyManagedSnapshot(): SchemaSnapshot {\n return { tables: [], enums: [] };\n}\n","/**\n * One immutable estate graph. Commands consume this instance; they do not\n * rescan storage or invent apply order from names.\n */\n\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\nimport { bytesEqual } from \"./canonical-json\";\nimport { emptyManagedSnapshot } from \"./empty-snapshot\";\nimport type { Sha256 } from \"./identity\";\nimport { freezeDeep } from \"./push-fingerprint\";\nimport { sliceDispatch, validateSqlRanges } from \"./sql-blob\";\nimport { assertArtifactExecutionSafe } from \"./statement-safety\";\nimport type { MigrationStorageReader } from \"./storage/contract\";\nimport type { SchemaSnapshot } from \"./types\";\nimport {\n encodeSnapshot,\n encodeSqlBlob,\n parseEstateDescriptor,\n parseSnapshotDocument,\n parseStateManifest,\n} from \"./v1-parse\";\nimport type {\n MigrationBooleanCheckV1,\n MigrationDispatchV1,\n MigrationEstateDescriptorV1,\n MigrationOperationV1,\n MigrationParentTransitionV1,\n MigrationStateManifestV1,\n PathWitness,\n StateSelector,\n} from \"./v1-types\";\n\nexport interface MigrationGraph {\n readonly estateHash: Sha256;\n readonly descriptor: MigrationEstateDescriptorV1;\n readonly states: ReadonlyMap<Sha256, MigrationStateManifestV1>;\n readonly snapshots: ReadonlyMap<Sha256, SchemaSnapshot>;\n readonly sql: ReadonlyMap<Sha256, Uint8Array>;\n readonly roots: readonly Sha256[];\n readonly leaves: readonly Sha256[];\n readonly emptySnapshotHash: Sha256;\n}\n\n/** Resolve one authenticated graph state to its already-parsed snapshot. */\nexport function requireStateSnapshot(\n graph: MigrationGraph,\n stateId: Sha256 | null\n): SchemaSnapshot {\n const snapshotHash =\n stateId === null\n ? graph.emptySnapshotHash\n : graph.states.get(stateId)?.snapshotHash;\n const snapshot = snapshotHash ? graph.snapshots.get(snapshotHash) : undefined;\n if (!snapshot) {\n throw new MigrationError(\n \"A selected state is missing its authenticated snapshot\",\n VibORMErrorCode.MIGRATION_CORRUPTION\n );\n }\n return snapshot;\n}\n\ntype CachedArtifact =\n | { readonly bytes: Uint8Array; readonly snapshot: SchemaSnapshot }\n | { readonly bytes: Uint8Array; readonly manifest: MigrationStateManifestV1 };\n\n/**\n * Parsed artifacts, keyed by their own content hash: never by the estate\n * hash, which every estate with the same target shares. Only the parse is\n * skipped. Every command still lists and reads the tenant's storage, and an\n * entry answers only bytes identical to the ones it was parsed from, so\n * changed bytes are parsed, and refused, as if nothing were cached. Values\n * are deep-frozen because commands and tenants share them. Least recently\n * used entries are dropped once the held bytes exceed `maxBytes`.\n */\nexport class ArtifactCache {\n private readonly entries = new Map<Sha256, CachedArtifact>();\n private readonly maxBytes: number;\n private held = 0;\n\n constructor(maxBytes: number) {\n this.maxBytes = maxBytes;\n }\n\n get heldBytes(): number {\n return this.held;\n }\n\n snapshot(hash: Sha256, bytes: Uint8Array): SchemaSnapshot {\n const hit = this.hit(hash, bytes);\n if (hit && \"snapshot\" in hit) return hit.snapshot;\n const snapshot = freezeDeep(parseSnapshotDocument(bytes, hash));\n return this.keep(hash, { bytes: bytes.slice(), snapshot }).snapshot;\n }\n\n manifest(id: Sha256, bytes: Uint8Array): MigrationStateManifestV1 {\n const hit = this.hit(id, bytes);\n if (hit && \"manifest\" in hit) return hit.manifest;\n const manifest = freezeDeep(parseStateManifest(bytes, id));\n return this.keep(id, { bytes: bytes.slice(), manifest }).manifest;\n }\n\n private hit(hash: Sha256, bytes: Uint8Array): CachedArtifact | undefined {\n const entry = this.entries.get(hash);\n if (!(entry && bytesEqual(entry.bytes, bytes))) return undefined;\n this.entries.delete(hash);\n this.entries.set(hash, entry);\n return entry;\n }\n\n private keep<T extends CachedArtifact>(hash: Sha256, entry: T): T {\n // Only a miss parses, and a miss on a held hash has other bytes, which\n // the parse refuses, so `hash` is never already held here.\n this.entries.set(hash, entry);\n this.held += entry.bytes.length;\n for (const [key, oldest] of this.entries) {\n if (this.held <= this.maxBytes) break;\n this.entries.delete(key);\n this.held -= oldest.bytes.length;\n }\n return entry;\n }\n}\n\n/**\n * One per isolate. 8 MiB of artifact bytes hold a 200-state estate of twenty\n * 15-column tables; the parsed values add about as much again.\n */\nconst artifacts = new ArtifactCache(8 * 1024 * 1024);\n\nexport async function loadMigrationGraph(\n storage: MigrationStorageReader,\n cache: ArtifactCache = artifacts\n): Promise<MigrationGraph> {\n const estateBytes = await storage.readEstate();\n if (!estateBytes) {\n throw new MigrationError(\n \"Estate descriptor is missing\",\n VibORMErrorCode.MIGRATION_INVALID_ESTATE\n );\n }\n const { descriptor, estateHash } = parseEstateDescriptor(estateBytes);\n const emptySnapshotHash = encodeSnapshot(emptyManagedSnapshot()).snapshotHash;\n const stateIds = await storage.listStates();\n const states = new Map<Sha256, MigrationStateManifestV1>();\n const neededSnapshots = new Set<Sha256>([emptySnapshotHash]);\n const neededSql = new Set<Sha256>();\n\n for (const id of stateIds) {\n const bytes = await storage.readState(id);\n if (!bytes) {\n throw new MigrationError(\n `State ${id} is listed but unreadable`,\n VibORMErrorCode.MIGRATION_CORRUPTION\n );\n }\n if (states.has(id)) {\n throw new MigrationError(\n `State ${id} is listed more than once`,\n VibORMErrorCode.MIGRATION_CORRUPTION\n );\n }\n const manifest = cache.manifest(id, bytes);\n if (manifest.estateHash !== estateHash) {\n throw new MigrationError(\n `State ${id} belongs to a different estate`,\n VibORMErrorCode.MIGRATION_INVALID_ESTATE\n );\n }\n states.set(id, manifest);\n neededSnapshots.add(manifest.snapshotHash);\n neededSql.add(manifest.sqlHash);\n }\n\n const snapshots = new Map<Sha256, SchemaSnapshot>();\n snapshots.set(emptySnapshotHash, emptyManagedSnapshot());\n for (const hash of neededSnapshots) {\n if (hash === emptySnapshotHash) continue;\n const bytes = await storage.readSnapshot(hash);\n if (!bytes) {\n throw new MigrationError(\n `Snapshot ${hash} is referenced but missing`,\n VibORMErrorCode.MIGRATION_CORRUPTION\n );\n }\n snapshots.set(hash, cache.snapshot(hash, bytes));\n }\n\n const sql = new Map<Sha256, Uint8Array>();\n for (const hash of neededSql) {\n const bytes = await storage.readSql(hash);\n if (!bytes) {\n throw new MigrationError(\n `SQL blob ${hash} is referenced but missing`,\n VibORMErrorCode.MIGRATION_CORRUPTION\n );\n }\n if (encodeSqlBlob(bytes) !== hash) {\n throw new MigrationError(\n `SQL blob ${hash} does not match its bytes`,\n VibORMErrorCode.MIGRATION_CORRUPTION\n );\n }\n sql.set(hash, bytes);\n }\n\n for (const manifest of states.values()) {\n const blob = sql.get(manifest.sqlHash)!;\n const dispatches: MigrationDispatchV1[] = [];\n for (const parent of manifest.parents) {\n collectDispatches(parent, dispatches);\n }\n collectChecks(manifest.destinationChecks, dispatches);\n validateSqlRanges(blob, dispatches);\n assertStoredParameterDialect(\n dispatches,\n descriptor.target.dialect,\n manifest.name\n );\n assertArtifactExecutionSafe(\n dispatches.map((dispatch) => sliceDispatch(blob, dispatch)),\n descriptor.target.dialect,\n manifest.name\n );\n }\n\n const outgoing = new Map<Sha256, Sha256[]>();\n for (const id of states.keys()) {\n outgoing.set(id, []);\n }\n\n for (const [id, manifest] of states) {\n for (const parent of manifest.parents) {\n if (parent.fromState === null) continue;\n if (!states.has(parent.fromState)) {\n throw new MigrationError(\n `State ${id} has a dangling parent`,\n VibORMErrorCode.MIGRATION_INVALID_ESTATE\n );\n }\n outgoing.get(parent.fromState)!.push(id);\n }\n }\n\n const roots = [...states.keys()].filter((id) =>\n states.get(id)!.parents.some((parent) => parent.fromState === null)\n );\n const leaves = [...states.keys()].filter(\n (id) => (outgoing.get(id) ?? []).length === 0\n );\n assertNoCycle(states, outgoing);\n\n if (states.size > 0 && roots.length === 0) {\n throw new MigrationError(\n \"Estate has states but no virtual-root transition\",\n VibORMErrorCode.MIGRATION_INVALID_ESTATE\n );\n }\n assertReachableFromEmpty(states, outgoing, roots);\n\n return {\n estateHash,\n descriptor,\n states,\n snapshots,\n sql,\n roots,\n leaves,\n emptySnapshotHash,\n };\n}\n\n/**\n * The symbolic namespace is one portable MySQL artifact value. PostgreSQL\n * stores its schema in the estate target and SQLite has no namespace, so the\n * tag in either estate is corruption rather than an executable parameter.\n */\nfunction assertStoredParameterDialect(\n dispatches: readonly MigrationDispatchV1[],\n dialect: MigrationEstateDescriptorV1[\"target\"][\"dialect\"],\n artifact: string\n): void {\n if (dialect === \"mysql\") {\n return;\n }\n for (const dispatch of dispatches) {\n if (\n dispatch.parameters.some(\n (parameter) => parameter.kind === \"target-namespace\"\n )\n ) {\n throw new MigrationError(\n `Migration \"${artifact}\" contains a target-namespace parameter outside a MySQL estate`,\n VibORMErrorCode.MIGRATION_INVALID_STATE,\n { meta: { migrationName: artifact } }\n );\n }\n }\n}\n\nfunction collectDispatches(\n parent: MigrationParentTransitionV1,\n into: MigrationDispatchV1[]\n): void {\n collectChecks(parent.originChecks, into);\n collectOperations(parent.operations, into);\n if (parent.rollback.kind !== \"irreversible\") {\n collectOperations(parent.rollback.operations, into);\n }\n}\n\nfunction collectOperations(\n operations: readonly MigrationOperationV1[],\n into: MigrationDispatchV1[]\n): void {\n for (const operation of operations) {\n for (const step of operation.steps) {\n if (step.retry === \"proven\") {\n into.push(step.precheck.query);\n }\n into.push(step.execute);\n if (step.retry === \"proven\") {\n into.push(step.postcheck.query);\n }\n }\n }\n}\n\nfunction collectChecks(\n checks: readonly MigrationBooleanCheckV1[],\n into: MigrationDispatchV1[]\n): void {\n for (const check of checks) {\n into.push(check.query);\n }\n}\n\nfunction assertNoCycle(\n states: ReadonlyMap<Sha256, MigrationStateManifestV1>,\n outgoing: ReadonlyMap<Sha256, readonly Sha256[]>\n): void {\n const color = new Map<Sha256, 0 | 1 | 2>();\n for (const id of states.keys()) color.set(id, 0);\n for (const start of states.keys()) {\n if (color.get(start) !== 0) continue;\n const stack: Array<{ id: Sha256; next: number }> = [{ id: start, next: 0 }];\n color.set(start, 1);\n while (stack.length > 0) {\n const frame = stack.at(-1)!;\n const edges = outgoing.get(frame.id) ?? [];\n if (frame.next < edges.length) {\n const next = edges[frame.next++]!;\n const seen = color.get(next) ?? 0;\n if (seen === 1) {\n throw new MigrationError(\n \"Estate graph contains a cycle\",\n VibORMErrorCode.MIGRATION_INVALID_ESTATE\n );\n }\n if (seen === 0) {\n color.set(next, 1);\n stack.push({ id: next, next: 0 });\n }\n continue;\n }\n color.set(frame.id, 2);\n stack.pop();\n }\n }\n}\n\nfunction assertReachableFromEmpty(\n states: ReadonlyMap<Sha256, MigrationStateManifestV1>,\n outgoing: ReadonlyMap<Sha256, readonly Sha256[]>,\n roots: readonly Sha256[]\n): void {\n const reachable = new Set<Sha256>();\n const pending = [...roots];\n while (pending.length > 0) {\n const id = pending.pop()!;\n if (reachable.has(id)) continue;\n reachable.add(id);\n for (const child of outgoing.get(id) ?? []) {\n pending.push(child);\n }\n }\n for (const id of states.keys()) {\n if (!reachable.has(id)) {\n throw new MigrationError(\n `State ${id} is not reachable from the empty state`,\n VibORMErrorCode.MIGRATION_INVALID_ESTATE\n );\n }\n }\n}\n\nexport function resolveStateSelector(\n graph: MigrationGraph,\n selector: StateSelector | undefined\n): Sha256 {\n if (!selector) {\n if (graph.leaves.length === 1) return graph.leaves[0]!;\n if (graph.leaves.length === 0) {\n throw new MigrationError(\n \"Estate has no states to target\",\n VibORMErrorCode.MIGRATION_NOT_FOUND\n );\n }\n throw pathRequired(\n graph.leaves.map((leaf) => [leaf]),\n \"Multiple leaf states exist; choose the target with --to / { to }\"\n );\n }\n if (\"id\" in selector) {\n if (!graph.states.has(selector.id)) {\n throw new MigrationError(\n `Unknown state ${selector.id}`,\n VibORMErrorCode.MIGRATION_NOT_FOUND\n );\n }\n return selector.id;\n }\n if (\"prefix\" in selector) {\n const matches = [...graph.states.keys()].filter((id) =>\n id.startsWith(selector.prefix)\n );\n if (matches.length === 1) return matches[0]!;\n if (matches.length === 0) {\n throw new MigrationError(\n `No state has prefix ${selector.prefix}`,\n VibORMErrorCode.MIGRATION_NOT_FOUND\n );\n }\n throw pathRequired(\n matches.map((id) => [id]),\n AMBIGUOUS_SELECTOR\n );\n }\n const matches = [...graph.states.values()]\n .filter((state) => state.name === selector.name)\n .map((state) => state.stateId);\n if (matches.length === 1) return matches[0]!;\n if (matches.length === 0) {\n throw new MigrationError(\n `No state is named ${selector.name}`,\n VibORMErrorCode.MIGRATION_NOT_FOUND\n );\n }\n throw pathRequired(\n matches.map((id) => [id]),\n AMBIGUOUS_SELECTOR\n );\n}\n\nexport function selectRoute(\n graph: MigrationGraph,\n origin: Sha256 | null,\n target: Sha256,\n via?: readonly Sha256[]\n): readonly Sha256[] {\n if (via && via.length > 0) {\n if (via.at(-1) !== target) {\n throw new MigrationError(\n \"via must end at the resolved target\",\n VibORMErrorCode.MIGRATION_PATH_REQUIRED\n );\n }\n const seen = new Set<string>();\n let previous = origin;\n for (const step of via) {\n if (seen.has(step)) {\n throw new MigrationError(\n \"via repeats a state\",\n VibORMErrorCode.MIGRATION_PATH_REQUIRED\n );\n }\n seen.add(step);\n if (!hasEdge(graph, previous, step)) {\n throw new MigrationError(\n \"via is not a real estate edge\",\n VibORMErrorCode.MIGRATION_PATH_REQUIRED\n );\n }\n previous = step;\n }\n return via;\n }\n\n const routes = enumerateRoutes(graph, origin, target, 2);\n if (routes.length === 1) return routes[0]!;\n if (routes.length === 0) {\n throw new MigrationError(\n \"No path exists from the current marker to the target\",\n VibORMErrorCode.MIGRATION_NOT_FOUND\n );\n }\n throw pathRequired(\n routes,\n \"Multiple migration paths exist; choose one with --via / { via }\"\n );\n}\n\nfunction hasEdge(\n graph: MigrationGraph,\n from: Sha256 | null,\n to: Sha256\n): boolean {\n const state = graph.states.get(to);\n if (!state) return false;\n return state.parents.some((parent) => parent.fromState === from);\n}\n\n/**\n * Plan T4: what a history pruned at `checkpoint` keeps. The checkpoint, every\n * state after it, and every state those name as a parent, so no kept\n * transition dangles: a merge with older history keeps that history.\n */\nexport function statesFrom(\n graph: MigrationGraph,\n checkpoint: Sha256\n): ReadonlySet<Sha256> {\n const children = childrenIndex(graph);\n const closure = (\n start: Iterable<Sha256>,\n next: (id: Sha256) => readonly (Sha256 | null)[]\n ) => {\n const seen = new Set<Sha256>();\n const pending = [...start];\n while (pending.length > 0) {\n const id = pending.pop()!;\n if (seen.has(id)) continue;\n seen.add(id);\n for (const step of next(id)) if (step !== null) pending.push(step);\n }\n return seen;\n };\n return closure(\n closure([checkpoint], (id) => children.get(id) ?? []),\n (id) => graph.states.get(id)!.parents.map((parent) => parent.fromState)\n );\n}\n\nfunction childrenIndex(graph: MigrationGraph): Map<string, Sha256[]> {\n const index = new Map<string, Sha256[]>();\n index.set(\"null\", []);\n for (const id of graph.states.keys()) {\n index.set(id, []);\n }\n for (const [id, state] of graph.states) {\n for (const parent of state.parents) {\n const key = parent.fromState ?? \"null\";\n const list = index.get(key) ?? [];\n list.push(id);\n index.set(key, list);\n }\n }\n return index;\n}\n\nfunction enumerateRoutes(\n graph: MigrationGraph,\n origin: Sha256 | null,\n target: Sha256,\n limit: number\n): Sha256[][] {\n const children = childrenIndex(graph);\n const found: Sha256[][] = [];\n const stack: Array<{ from: Sha256 | null; path: Sha256[] }> = [\n { from: origin, path: [] },\n ];\n while (stack.length > 0 && found.length < limit) {\n const frame = stack.pop()!;\n for (const child of children.get(frame.from ?? \"null\") ?? []) {\n if (frame.path.includes(child)) continue;\n const next = [...frame.path, child];\n if (child === target) {\n found.push(next);\n if (found.length >= limit) break;\n continue;\n }\n stack.push({ from: child, path: next });\n }\n }\n return found;\n}\n\nconst AMBIGUOUS_SELECTOR =\n \"The state selector matches several states; pass a longer prefix or the full state id\";\n\nfunction pathRequired(\n routes: readonly (readonly Sha256[])[],\n hint: string\n): never {\n const witness: PathWitness = {\n routes: routes.slice(0, 2),\n frontier: firstFrontier(routes),\n more: routes.length > 2,\n };\n throw new MigrationError(\n `${hint}. Candidates: ${witness.routes\n .map((route) => route.join(\" -> \"))\n .join(\" | \")}`,\n VibORMErrorCode.MIGRATION_PATH_REQUIRED,\n { meta: { pathWitness: witness } }\n );\n}\n\nfunction firstFrontier(routes: readonly (readonly Sha256[])[]): Sha256[] {\n if (routes.length < 2) return [];\n const first = routes[0]!;\n const second = routes[1]!;\n const frontier: Sha256[] = [];\n const max = Math.min(first.length, second.length);\n for (let i = 0; i < max; i++) {\n if (first[i] !== second[i]) {\n frontier.push(first[i]!, second[i]!);\n return frontier;\n }\n }\n return frontier;\n}\n\n/** One edge of a route: its endpoints, transition, arrival state and SQL. */\nexport interface RouteEdge {\n readonly from: Sha256 | null;\n readonly to: Sha256;\n readonly transition: MigrationParentTransitionV1;\n readonly state: MigrationStateManifestV1;\n readonly blob: Uint8Array;\n}\n\n/**\n * The edges of `path` walked from `origin`. `parentTransition` refuses a\n * missing edge; the loaded graph holds every state and blob an edge names.\n */\nexport function routeEdges(\n graph: MigrationGraph,\n origin: Sha256 | null,\n path: readonly Sha256[]\n): RouteEdge[] {\n return path.map((to, index) => {\n const from = index === 0 ? origin : path[index - 1]!;\n const transition = parentTransition(graph, from, to);\n const state = graph.states.get(to)!;\n return { from, to, transition, state, blob: graph.sql.get(state.sqlHash)! };\n });\n}\n\nexport function parentTransition(\n graph: MigrationGraph,\n from: Sha256 | null,\n to: Sha256\n): MigrationParentTransitionV1 {\n const state = graph.states.get(to);\n if (!state) {\n throw new MigrationError(\n `Unknown state ${to}`,\n VibORMErrorCode.MIGRATION_NOT_FOUND\n );\n }\n const found = state.parents.find((parent) => parent.fromState === from);\n if (!found) {\n throw new MigrationError(\n \"Selected edge has no parent transition\",\n VibORMErrorCode.MIGRATION_INVALID_ESTATE\n );\n }\n return found;\n}\n","import type { AmbiguousChange, DiffOperation } from \"../types\";\n\n/**\n * Formats an operation for human-readable display.\n */\nexport function formatOperation(op: DiffOperation): string {\n switch (op.type) {\n case \"createTable\":\n return `+ Create table \"${op.table.name}\" with ${op.table.columns.length} columns`;\n case \"dropTable\":\n return `- Drop table \"${op.tableName}\"`;\n case \"renameTable\":\n return `~ Rename table \"${op.from}\" → \"${op.to}\"`;\n case \"addColumn\":\n return `+ Add column \"${op.column.name}\" (${op.column.type}) to \"${op.tableName}\"`;\n case \"dropColumn\":\n return `- Drop column \"${op.columnName}\" from \"${op.tableName}\"`;\n case \"renameColumn\":\n return `~ Rename column \"${op.from}\" → \"${op.to}\" in \"${op.tableName}\"`;\n case \"alterColumn\":\n return `~ Alter column \"${op.columnName}\" in \"${op.tableName}\"`;\n case \"createIndex\":\n return `+ Create index \"${op.index.name}\" on \"${op.tableName}\"`;\n case \"dropIndex\":\n return `- Drop index \"${op.indexName}\"`;\n case \"addForeignKey\":\n return `+ Add foreign key \"${op.fk.name}\" to \"${op.tableName}\"`;\n case \"dropForeignKey\":\n return `- Drop foreign key \"${op.fkName}\" from \"${op.tableName}\"`;\n case \"addUniqueConstraint\":\n return `+ Add unique constraint \"${op.constraint.name}\" to \"${op.tableName}\"`;\n case \"dropUniqueConstraint\":\n return `- Drop unique constraint \"${op.constraintName}\" from \"${op.tableName}\"`;\n case \"addPrimaryKey\":\n return `+ Add primary key to \"${op.tableName}\"`;\n case \"dropPrimaryKey\":\n return `- Drop primary key \"${op.constraintName}\" from \"${op.tableName}\"`;\n case \"createEnum\":\n return `+ Create enum \"${op.enumDef.name}\" with values [${op.enumDef.values.join(\", \")}]`;\n case \"dropEnum\":\n return `- Drop enum \"${op.enumName}\"`;\n case \"alterEnum\": {\n const parts: string[] = [];\n if (op.addValues?.length) parts.push(`add: ${op.addValues.join(\", \")}`);\n if (op.removeValues?.length) {\n parts.push(`remove: ${op.removeValues.join(\", \")}`);\n }\n return `~ Alter enum \"${op.enumName}\" (${parts.join(\"; \")})`;\n }\n default:\n return `Unknown operation: ${getOperationType(op)}`;\n }\n}\n\nexport function formatDestructiveOperation(op: DiffOperation): string {\n switch (op.type) {\n case \"dropTable\":\n return `[destructive] Drop table \"${op.tableName}\"`;\n case \"dropColumn\":\n return `[destructive] Drop column \"${op.columnName}\" from \"${op.tableName}\"`;\n case \"addColumn\":\n return `[destructive] Add required column \"${op.tableName}.${op.column.name}\" without a backfill default`;\n case \"alterColumn\":\n return `[destructive] Alter column \"${op.columnName}\" in \"${op.tableName}\"`;\n default:\n return `[destructive] ${getOperationType(op)}`;\n }\n}\n\nexport function formatAmbiguousChangeDescription(\n change: AmbiguousChange\n): string {\n if (change.type === \"ambiguousColumn\") {\n return `[ambiguous] Column \"${change.droppedColumn.name}\" → \"${change.addedColumn.name}\" in \"${change.tableName}\"`;\n }\n return `[ambiguous] Table \"${change.droppedTable}\" → \"${change.addedTable}\"`;\n}\n\nfunction getOperationType(operation: { type: string }): string {\n return operation.type;\n}\n","/**\n * Live-capability admission\n *\n * ONE decision admits a migration command to live database state. Direct\n * `push()` and every high-level migration command reach it here; no command\n * reinterprets either fact for itself.\n */\n\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\nimport type { BoundMigrationDriver } from \"./drivers\";\nimport { canPinSession, runsMigrationBatches } from \"./pinned-session\";\nimport { formatMigrationTarget, readNamespaceAttestation } from \"./target\";\n\n/**\n * What a command asks of live state.\n *\n * - `effectful` — the command can write, or promises a concurrency-stable\n * decision read from live state (apply/down/reset/verify/push, and the live\n * dry down/reset decisions the CLI confirms against).\n * - `batch` — effectful work whose every effect can go out as one atomic\n * request per transactional group (apply): admitted as `effectful` is, and\n * also on a PostgreSQL transport with no session that runs such a request\n * (plan D7), where that work refuses any step needing a session itself.\n * - `read-only` — a point-in-time read that changes nothing (status, log,\n * apply dry-run, push dry-run introspection).\n *\n * Offline and storage-only work — generate, check — never reaches this owner\n * at all.\n */\nexport type MigrationLiveRequirement = \"effectful\" | \"batch\" | \"read-only\";\n\n/**\n * Admits (or refuses) live migration work for one command.\n *\n * The failure precedence for MySQL is exact and is the whole point of the\n * owner: an absent attestation is `DRIVER_NOT_SUPPORTED`, and only AFTER the\n * capability is admitted does an absent namespace become\n * `MIGRATION_INVALID_STATE`. Reversing them would report a missing database\n * name for a driver whose routing was never provable in the first place.\n *\n * PostgreSQL namespaces are proven earlier, when the estate target is resolved\n * — a PostgreSQL driver with no adapter namespace never reaches a live\n * boundary. SQLite has no namespace to prove.\n */\nexport function admitLiveMigrationCapability(\n migrationDriver: BoundMigrationDriver,\n requirement: MigrationLiveRequirement,\n command: string\n): void {\n const { target } = migrationDriver;\n\n if (target.dialect === \"postgresql\") {\n admitPinnedSessionCapability(migrationDriver, requirement, command);\n return;\n }\n\n if (target.dialect === \"sqlite\") {\n admitSqliteFamilyCapability(migrationDriver, requirement, command);\n return;\n }\n\n if (target.dialect !== \"mysql\") {\n return;\n }\n\n if (requirement !== \"read-only\") {\n const attestation = readNamespaceAttestation(\n migrationDriver.executionDriver\n );\n if (attestation === undefined) {\n throw new MigrationError(\n `${command} needs proof that this MySQL driver does not redirect qualified table references, and the driver \"${migrationDriver.executionDriver.driverName}\" carries no non-redirecting migration-namespace attestation. ` +\n \"Effectful and concurrency-stable live migration work is refused: a successful handshake, a driver class, a URL shape or a server version is not proof that a proxy leaves qualified names in the requested database.\",\n VibORMErrorCode.DRIVER_NOT_SUPPORTED,\n {\n meta: {\n driver: migrationDriver.executionDriver.driverName,\n command,\n target: formatMigrationTarget(target, migrationDriver.namespace),\n },\n }\n );\n }\n }\n\n if (migrationDriver.namespace === undefined) {\n throw new MigrationError(\n `${command} needs a live MySQL database and this client's adapter is unbound. ` +\n \"MySQL migration artifacts are database-relative on purpose, so the live destination comes from the driver's `namespace` — supply it explicitly, in the connection URL, or through the driver's database option.\",\n VibORMErrorCode.MIGRATION_INVALID_STATE,\n {\n meta: {\n driver: migrationDriver.executionDriver.driverName,\n command,\n target: formatMigrationTarget(target),\n },\n }\n );\n }\n}\n\n/**\n * Admits effectful SQLite work only on a driver that declared the migration\n * capability.\n *\n * The declaration was read once when the driver was bound (`getMigrationDriver`,\n * where it also chose the implementation); this is where it decides. Stock\n * sqlite3 and bun-sqlite declare it; D1 and libSQL do not, and stay refused for\n * effectful work while generation, check and read-only status stay available.\n * Whether the driver runs callback transactions is its `supportsTransactions`,\n * which each command already reads for its own transaction shape.\n */\nfunction admitSqliteFamilyCapability(\n migrationDriver: BoundMigrationDriver,\n requirement: MigrationLiveRequirement,\n command: string\n): void {\n if (\n requirement === \"read-only\" ||\n migrationDriver.sqliteMigrationCapability !== undefined\n ) {\n return;\n }\n const { driverName } = migrationDriver.executionDriver;\n throw new MigrationError(\n `${command} is refused: the SQLite driver \"${driverName}\" declares no \\`sqliteMigrationCapability\\`. Generation, check and status remain available.`,\n VibORMErrorCode.DRIVER_NOT_SUPPORTED,\n {\n meta: {\n driver: driverName,\n command,\n target: formatMigrationTarget(migrationDriver.target),\n },\n }\n );\n}\n\n/**\n * Refuses an effectful PostgreSQL command on a transport that cannot hold a\n * session lock for it.\n *\n * Neon's HTTP driver is the shipped case of a transport with no interactive\n * session: it speaks a stateless request/reply API, so a `pg_advisory_lock` it\n * issued would be acquired by one request and could never be released by\n * another — the lock would be neither held for the work nor released after it.\n * The answer is `canPinSession(driver)` — the presence of the driver's own\n * pinned-session hook — so nothing declares a capability it does not\n * implement, and a custom PostgreSQL driver is judged by the same fact as a\n * stock one. `batch` work is the exception: such a transport sends each\n * transactional group as one request holding the transaction lock\n * (`runsMigrationBatches`, plan D7).\n *\n * A transaction-pooling endpoint is the same failure behind an ordinary\n * session: Cloudflare Hyperdrive and Neon's `-pooler` endpoints hand\n * consecutive transactions to whichever server session is free, so the lock\n * is taken on one backend and the DDL runs on another. Those hosts, read from\n * the driver's own configuration, are refused unless the caller attests a\n * dedicated session, at their risk. Every path that mutates, or that makes a\n * concurrency-stable decision from live state, is refused HERE: before the\n * connection, before storage writes, and before any other provider work.\n * Application queries, read-only introspection, status/log, push dry-run, and\n * every offline path stay available.\n */\nfunction admitPinnedSessionCapability(\n migrationDriver: BoundMigrationDriver,\n requirement: MigrationLiveRequirement,\n command: string\n): void {\n const driver = migrationDriver.executionDriver;\n if (\n requirement === \"read-only\" ||\n (requirement === \"batch\" && runsMigrationBatches(driver))\n ) {\n return;\n }\n const meta = {\n driver: driver.driverName,\n command,\n target: formatMigrationTarget(migrationDriver.target),\n };\n if (!canPinSession(driver)) {\n throw new MigrationError(\n `${command} needs one physical database session it can hold a migration lock on, and the driver \"${driver.driverName}\" has no interactive session to reserve. ` +\n \"Effectful and concurrency-stable live migration work is refused: a session-scoped lock taken over a stateless transport would be acquired by one request and released by another, so it would protect nothing. Runtime queries, introspection, status, log, push dry-run and every offline command remain available.\",\n VibORMErrorCode.DRIVER_NOT_SUPPORTED,\n { meta }\n );\n }\n if (driver.migrationSessionAttestation === \"dedicated-session\") {\n return;\n }\n const pooler = driver[\"migrationSessionEndpoints\"]?.()\n .flatMap(endpointHosts)\n .find((host) => HYPERDRIVE_HOST.test(host) || NEON_POOLER_HOST.test(host));\n if (pooler === undefined) {\n return;\n }\n throw new MigrationError(\n `${command} is refused: \"${pooler}\" is a transaction pooler, which cannot hold the migration lock. Use the direct endpoint, or pass migrationSessionAttestation: \"dedicated-session\" at your own risk.`,\n VibORMErrorCode.DRIVER_NOT_SUPPORTED,\n { meta }\n );\n}\n\n/** Cloudflare Hyperdrive's local endpoint, as a Worker binding names it. */\nconst HYPERDRIVE_HOST = /\\.hyperdrive\\.local\\.?$/i;\n/** A Neon endpoint id with the pooled-connection suffix. */\nconst NEON_POOLER_HOST = /^ep-[^.]*-pooler\\./i;\n/**\n * A URL's host list and query. Userinfo runs to the LAST `@` before the path,\n * as WHATWG URL (and so `pg-connection-string`) reads an unencoded `@`.\n */\nconst URL_PARTS =\n /^[a-z][a-z\\d+.-]*:\\/\\/(?:[^/?#]*@)?([^/?#]*)[^?#]*\\??([^#]*)/i;\nconst PORT = /:\\d*$/;\n\n/**\n * The host names one configured endpoint names, without ports: a bare host,\n * or every host of a (possibly multi-host) connection URL, including the\n * libpq `host` query parameter that overrides it.\n */\nfunction endpointHosts(endpoint: unknown): string[] {\n if (typeof endpoint !== \"string\") return [];\n const url = URL_PARTS.exec(endpoint);\n const hosts = url\n ? [url[1] ?? \"\", ...new URLSearchParams(url[2]).getAll(\"host\")]\n : [endpoint];\n return hosts.flatMap((list) =>\n list.split(\",\").map((host) => host.replace(PORT, \"\"))\n );\n}\n","import { selectManagedSnapshot } from \"./target\";\n/**\n * Model-to-SchemaSnapshot Serializer\n *\n * Converts VibORM model definitions into a database-agnostic SchemaSnapshot\n * that can be compared with the current database state.\n *\n * Database-specific logic is delegated to the MigrationDriver:\n * - Type mapping (mapScalarType)\n * - Default expressions (getDefaultExpression)\n * - Enum handling (capabilities.supportsNativeEnums, getEnumColumnType)\n */\n\nimport type { Dialect } from \"../drivers/types\";\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\nimport { hydrateSchemaNames } from \"../schema/hydration\";\nimport {\n type AnyModel,\n getModelKeyCatalog,\n getTableName as getModelTableName,\n isTotalIndex,\n type ModelState,\n} from \"../schema/model\";\nimport type { RelationSlot } from \"../schema/relation\";\nimport { automaticForeignKeyIndexName } from \"../schema/relation/helpers\";\nimport type { Scalar } from \"../schema/scalars/base\";\nimport { sqliteDateTimePhysicalForm } from \"../schema/scalars/datetime/physical\";\nimport {\n describeDecimalProviderLimitRefusal,\n findDecimalProviderLimitRefusal,\n} from \"../schema/scalars/decimal/provider-limits\";\nimport { idDomainOf } from \"../schema/validation/id-domains\";\nimport {\n foreignKeyOnDelete,\n junctionOnDelete,\n type ResolvedRelationEdge,\n type ResolvedRelationIndex,\n type ResolvedVariantJunctionEdge,\n type ResolvedVariantJunctionMember,\n type ResolvedVariantRowEdge,\n resolvedEdges,\n} from \"../schema/validation/relation-resolution\";\nimport { resolveSchemaOrThrow } from \"../schema/validation/validator\";\nimport type { MigrationDriver } from \"./drivers\";\nimport type {\n ColumnDef,\n EnumDef,\n ForeignKeyDef,\n IndexDef,\n PolymorphicSnapshotStorage,\n PolymorphicToManySnapshotMember,\n PolymorphicToOneSnapshotMember,\n PolymorphicToOneStorageRegistryEntry,\n PrimaryKeyDef,\n SchemaSnapshot,\n TableDef,\n UniqueConstraintDef,\n} from \"./types\";\n\n// =============================================================================\n// SERIALIZER\n// =============================================================================\n\nexport interface SerializeOptions {\n migrationDriver: MigrationDriver;\n}\n\n/** Translate the shared pure refusal into the migration boundary's error. */\nexport function assertMigrationDecimalDomainsFitProvider(\n models: Record<string, AnyModel>,\n dialect: Dialect\n): void {\n const refusal = findDecimalProviderLimitRefusal(models, dialect);\n if (refusal === undefined) return;\n throw new MigrationError(\n describeDecimalProviderLimitRefusal(refusal),\n VibORMErrorCode.MIGRATION_INVALID_STATE\n );\n}\n\n/** One model's edges, bucketed at their anchors in declaration order. */\ninterface ModelEdges {\n readonly variants: ResolvedVariantEdgeRef[];\n readonly foreignKeys: ResolvedForeignKeyEdge[];\n}\n\ntype ResolvedVariantEdgeRef =\n | ResolvedVariantRowEdge\n | ResolvedVariantJunctionEdge;\ntype ResolvedForeignKeyEdge = Extract<\n ResolvedRelationEdge,\n { kind: \"foreignKey\" }\n>;\ntype ResolvedJunctionEdge = Extract<ResolvedRelationEdge, { kind: \"junction\" }>;\n\n/**\n * Stage the ONE derived edge iterator into the two emission buckets the\n * serializer already had (D4): per-model variant storage and foreign keys for\n * the model phase, and ordinary junctions for the phase that follows it.\n *\n * `resolvedEdges` yields each edge exactly once, at its canonical anchor, in\n * schema/model/field order — which is the order both phases already walked. No\n * topology is stored here and none is re-expanded (§11.5.9).\n */\nfunction stageEdges(index: ResolvedRelationIndex): {\n readonly byModel: ReadonlyMap<AnyModel, ModelEdges>;\n readonly junctions: readonly ResolvedJunctionEdge[];\n} {\n const byModel = new Map<AnyModel, ModelEdges>();\n const junctions: ResolvedJunctionEdge[] = [];\n const bucket = (model: AnyModel): ModelEdges => {\n const held = byModel.get(model);\n if (held) return held;\n const created: ModelEdges = { variants: [], foreignKeys: [] };\n byModel.set(model, created);\n return created;\n };\n for (const edge of resolvedEdges(index)) {\n if (edge.kind === \"junction\") {\n junctions.push(edge);\n continue;\n }\n if (edge.kind === \"foreignKey\") {\n bucket(edge.owner.source).foreignKeys.push(edge);\n continue;\n }\n bucket(edge.carrier.source).variants.push(edge);\n }\n return { byModel, junctions };\n}\n\n/** `(model, field)` is the whole contextual identity of a slot. */\nfunction isSlot(one: RelationSlot, other: RelationSlot): boolean {\n return one.source === other.source && one.field === other.field;\n}\n\n/** The endpoint an ordinary edge reaches FROM the given one. */\nfunction partnerOf(\n edge: ResolvedForeignKeyEdge | ResolvedJunctionEdge,\n from: RelationSlot\n): RelationSlot {\n const [first, second] = edge.endpoints;\n return isSlot(first, from) ? second : first;\n}\n\n/**\n * Serializes a collection of VibORM models into a SchemaSnapshot\n */\nexport function serializeModels(\n models: Record<string, AnyModel>,\n options: SerializeOptions\n): SchemaSnapshot {\n hydrateSchemaNames(models);\n assertMigrationDecimalDomainsFitProvider(\n models,\n options.migrationDriver.dialect\n );\n return serializeResolvedModels(\n models,\n options.migrationDriver,\n resolveSchemaOrThrow(models)\n );\n}\n\n/** Internal composition seam for a boundary that already owns resolution. */\nexport function serializeResolvedModels(\n models: Record<string, AnyModel>,\n migrationDriver: MigrationDriver,\n index: ResolvedRelationIndex\n): SchemaSnapshot {\n const { byModel, junctions } = stageEdges(index);\n const tables: TableDef[] = [];\n const enums: EnumDef[] = [];\n const enumsSet = new Set<string>();\n const polymorphicStorage: PolymorphicSnapshotStorage[] = [];\n // One registry for EVERY junction-shaped table — polymorphic member\n // junctions (registered by the model loop below, model iteration order then\n // member declaration order) and ordinary many-to-many junctions (registered\n // by the walk that follows) — so the \"one table name, one definition\"\n // invariant covers both routes through the same map.\n const junctionTables = new Map<string, { def: TableDef; pairKey: string }>();\n\n for (const [modelName, model] of Object.entries(models)) {\n const modelState = model[\"~\"].state;\n const tableName =\n model[\"~\"].names.sql || modelState.tableName || modelName.toLowerCase();\n\n const columns: ColumnDef[] = [];\n const indexes: IndexDef[] = [];\n const foreignKeys: ForeignKeyDef[] = [];\n const uniqueConstraints: UniqueConstraintDef[] = [];\n const relationStorage: Record<\n string,\n PolymorphicToOneStorageRegistryEntry\n > = {};\n let primaryKey: PrimaryKeyDef | undefined;\n const pkColumns: string[] = [];\n\n // Process scalars\n for (const [fieldName, scalar] of Object.entries<Scalar>(\n modelState.scalars\n )) {\n const scalarState = scalar[\"~\"].state;\n // Use model's nameRegistry for column name resolution (supports field reuse)\n const columnName = model[\"~\"].getFieldName(fieldName).sql;\n\n // Handle enum types (only for databases that support native enums)\n let columnType: string;\n // The LIST representation is decided before enum identity is spelled. A\n // dialect with native arrays keeps both — `enumname[]` — while the others\n // store the list in the same container every other list uses, where an\n // element type has no expression at all: an inline `ENUM(...)` or a\n // `TEXT CHECK(col IN ...)` describes ONE member, so spelling it for a\n // list produces a column that refuses every value the field can hold.\n const spellsEnumColumn =\n scalarState.type === \"enum\" &&\n (scalarState.array !== true ||\n migrationDriver.capabilities.supportsNativeArrays);\n if (spellsEnumColumn) {\n const enumScalar = scalar as any;\n const enumValues = enumScalar.enumValues as string[] | undefined;\n\n if (migrationDriver.capabilities.supportsNativeEnums && enumValues) {\n // Use explicit enum name if provided, otherwise auto-generate\n const enumName =\n scalarState.enumName && migrationDriver.dialect === \"postgresql\"\n ? scalarState.enumName\n : migrationDriver.getEnumColumnType(\n tableName,\n columnName,\n enumValues\n );\n\n const previousEnum = enums.find((item) => item.name === enumName);\n if (\n previousEnum &&\n JSON.stringify(previousEnum.values) !== JSON.stringify(enumValues)\n )\n throw new MigrationError(\n `Enum type \"${enumName}\" is declared with incompatible values`,\n VibORMErrorCode.MIGRATION_INVALID_STATE\n );\n if (!enumsSet.has(enumName)) {\n enums.push({\n name: enumName,\n values: enumValues,\n });\n enumsSet.add(enumName);\n }\n columnType = scalarState.array ? `${enumName}[]` : enumName;\n } else {\n // Fall back to driver's default enum column type\n columnType = migrationDriver.getEnumColumnType(\n tableName,\n columnName,\n enumValues || []\n );\n }\n } else {\n // A foreign key's identifier domain is DERIVED from the key it\n // references, so it is read against the model through the same\n // resolved index this serialization is already built from.\n columnType = migrationDriver.mapScalarType(\n scalar,\n scalarState,\n idDomainOf(model, fieldName, index)\n );\n }\n\n const columnDef: ColumnDef = {\n name: columnName,\n type: columnType,\n nullable: scalarState.nullable,\n default: migrationDriver.getDefaultExpression(scalar, scalarState),\n autoIncrement: scalarState.autoGenerate?.kind === \"increment\",\n // Carried by REFERENCE off the resolved scalar, never rebuilt: the\n // frozen descriptor is the one source of truth, and the physical type\n // above is derived from it. On SQLite that type is `INTEGER` or `TEXT`\n // whatever the domain is, so without this the differ would see no\n // change when the domain moved.\n decimal: scalarState.decimal,\n geoPointEncoding:\n migrationDriver.dialect === \"sqlite\" && scalarState.type === \"point\"\n ? \"binary64\"\n : undefined,\n dateTime:\n migrationDriver.dialect === \"sqlite\" &&\n scalarState.type === \"datetime\" &&\n scalarState.array !== true\n ? sqliteDateTimePhysicalForm(scalar[\"~\"].nativeType)\n : undefined,\n };\n\n columns.push(columnDef);\n\n // Track primary key columns\n if (scalarState.isId) {\n pkColumns.push(columnName);\n }\n\n // Handle unique constraints on individual fields\n if (scalarState.isUnique && !scalarState.isId) {\n uniqueConstraints.push({\n name: `${tableName}_${columnName}_key`,\n columns: [columnName],\n });\n }\n }\n\n // Handle compound primary key\n if (modelState.compoundId) {\n const firstKey = Object.keys(modelState.compoundId)[0];\n const compoundIdSchema = firstKey\n ? modelState.compoundId[firstKey]\n : undefined;\n if (compoundIdSchema?.entries) {\n pkColumns.push(\n ...Object.keys(compoundIdSchema.entries).map(\n (field) => model[\"~\"].getFieldName(field).sql\n )\n );\n }\n }\n\n // Set primary key\n if (pkColumns.length > 0) {\n primaryKey = {\n columns: pkColumns,\n name: `${tableName}_pkey`,\n };\n }\n\n // Handle compound unique constraints\n const compoundUniques: ModelState[\"compoundUniques\"] =\n modelState.compoundUniques;\n if (compoundUniques) {\n for (const [constraintName, schema] of Object.entries(compoundUniques)) {\n if (schema?.entries) {\n uniqueConstraints.push({\n name: `${tableName}_${constraintName}_key`,\n columns: Object.keys(schema.entries).map(\n (field) => model[\"~\"].getFieldName(field).sql\n ),\n });\n }\n }\n }\n\n // Process indexes from model state\n const declaredIndexColumns: string[][] = [];\n for (const indexDef of modelState.indexes) {\n const indexName =\n indexDef.options.name ||\n `${tableName}_${indexDef.fields.join(\"_\")}_idx`;\n // `.map()` renames the column, so the DDL has to name the column and not\n // the TypeScript field — the same resolution the compound uniques and the\n // FK columns already do. One resolution serves both readers: the CREATE\n // INDEX below, and the foreign-key index's coverage decision, which has\n // to compare the same names or it emits a duplicate index.\n const columns = indexDef.fields.map(\n (field) => model[\"~\"].getFieldName(field).sql\n );\n const declared: IndexDef = {\n name: indexName,\n columns,\n unique: indexDef.options.unique ?? false,\n type: indexDef.options.type,\n where: indexDef.options.where,\n };\n indexes.push(declared);\n if (isTotalIndex(declared)) {\n declaredIndexColumns.push(columns);\n }\n }\n\n // Variant storage is relation-owned, so it never appears in the public\n // scalar map. The RESOLVED CARRIER EDGE is the single source for the\n // row-held private columns and index, the collection member junction\n // tables, and generated-file member history.\n const modelEdges = byModel.get(model) ?? { variants: [], foreignKeys: [] };\n for (const edge of modelEdges.variants) {\n if (edge.kind === \"variantJunctionCarrier\") {\n const members: PolymorphicToManySnapshotMember[] = [];\n for (const member of edge.members) {\n const memberDef = serializeMemberJunction(\n model,\n tableName,\n member,\n migrationDriver,\n index\n );\n // pairName is always set for a member junction: the resolved topology\n // is built exclusively by the gate, which passes\n // `${model}.${relation}.${publicType}` — already distinct from every\n // ordinary pairKey spelling.\n const pairKey = member.topology.pairName!;\n const existing = junctionTables.get(memberDef.name);\n if (\n existing &&\n (existing.pairKey !== pairKey ||\n JSON.stringify(existing.def) !== JSON.stringify(memberDef))\n ) {\n throw new Error(\n `Junction table \"${memberDef.name}\" is shared by multiple distinct relation pairs. ` +\n \"Give each pair a distinct .name() or its own .through() table name.\"\n );\n }\n if (!existing) {\n junctionTables.set(memberDef.name, { def: memberDef, pairKey });\n }\n\n const memberTarget = member.topology.target.model;\n const targetModelName = memberTarget[\"~\"].names.ts;\n members.push({\n publicType: member.variant,\n storedType: member.entry.storedValue,\n targetTable: getModelTableName(\n memberTarget,\n targetModelName?.toLowerCase() ?? \"unknown\"\n ),\n memberJunctionTable: member.topology.table,\n inverseCardinality: member.uniqueTarget ? \"one\" : \"many\",\n });\n }\n polymorphicStorage.push({\n ownerTable: tableName,\n relation: edge.carrier.field,\n kind: \"toMany\",\n members,\n });\n continue;\n }\n const storage = edge.storage;\n const typeScalarState = storage.typeColumn.scalar[\"~\"].state;\n const idScalarState = storage.idColumn.scalar[\"~\"].state;\n columns.push(\n {\n name: storage.typeColumn.name,\n type: migrationDriver.mapScalarType(\n storage.typeColumn.scalar,\n typeScalarState\n ),\n nullable: storage.typeColumn.nullable,\n },\n {\n name: storage.idColumn.name,\n // The carrier's id column holds every variant's KEY, and a key's\n // domain may be DERIVED, so the column names the key it stands in for\n // and that key is resolved against the index. Every variant agrees on\n // the answer or this storage does not exist (P002).\n type: migrationDriver.mapScalarType(\n storage.idColumn.scalar,\n idScalarState,\n storage.idColumn.reference === undefined\n ? undefined\n : idDomainOf(\n storage.idColumn.reference.model,\n storage.idColumn.reference.field,\n index\n )\n ),\n nullable: storage.idColumn.nullable,\n }\n );\n indexes.push({\n name: storage.indexName,\n columns: [storage.typeColumn.name, storage.idColumn.name],\n unique: edge.uniqueTarget,\n });\n // The physical facts stay in the TableDef above where the structural\n // differ owns them; the registry annotates which of those parts are\n // relation-owned, keyed by the storage ref the metadata entry carries.\n relationStorage[storage.typeColumn.name] = {\n kind: \"polymorphicToOne\",\n typeColumn: storage.typeColumn.name,\n idColumn: storage.idColumn.name,\n index: storage.indexName,\n };\n\n const members: PolymorphicToOneSnapshotMember[] = [];\n for (const member of edge.members) {\n const targetModelName = member.targetModel[\"~\"].names.ts;\n members.push({\n publicType: member.variant,\n storedType: member.entry.storedValue,\n targetTable: getModelTableName(\n member.targetModel,\n targetModelName?.toLowerCase() ?? \"unknown\"\n ),\n });\n }\n polymorphicStorage.push({\n ownerTable: tableName,\n relation: edge.carrier.field,\n kind: \"toOne\",\n storageRef: storage.typeColumn.name,\n members,\n });\n }\n\n // A UNIQUE foreign key gets a unique constraint at the bottom of the\n // relation loop, and that constraint is an index — so it covers the\n // foreign-key index exactly as a declared unique does. It is collected HERE,\n // before the loop, because `uniqueConstraints` grows INSIDE it: one model may\n // name the same columns from a plural and from a singular edge (legal, and\n // measured through `serializeModels`), and reading the half-built list made\n // the answer depend on which relation the schema happened to spell first —\n // `many` before `one` emitted the redundant index, `one` before `many` did\n // not. The condition mirrors the branch that pushes the constraint, so this\n // claims coverage only where the constraint follows.\n const oneToOneFkColumns: string[][] = [];\n for (const edge of modelEdges.foreignKeys) {\n if (!edge.unique) continue;\n oneToOneFkColumns.push(\n edge.reference.members.map(\n (member) => model[\"~\"].getFieldName(member.foreignField).sql\n )\n );\n }\n\n // Process foreign keys. ONE edge per stored reference, at its OWNER, in the\n // owner's declaration order — the gate decided which endpoint stores the\n // reference, so there is no family label to test and no inverse to discover.\n for (const edge of modelEdges.foreignKeys) {\n const targetSlot = partnerOf(edge, edge.owner);\n const targetModel = targetSlot.source;\n const targetModelState = targetModel[\"~\"].state;\n const targetTableName =\n targetModel[\"~\"].names.sql ||\n targetModelState.tableName ||\n edge.owner.field.toLowerCase();\n\n // Resolve TS field names to actual column names (.map() support)\n const fkFields = edge.reference.members.map(\n (member) => member.foreignField\n );\n const fkColumns = fkFields.map(\n (field) => model[\"~\"].getFieldName(field).sql\n );\n const referencedColumns = edge.reference.members.map(\n (member) => targetModel[\"~\"].getFieldName(member.referencedField).sql\n );\n\n // Prisma parity: without an explicit .onDelete(), a stored reference whose\n // every local member is nullable defaults to SET NULL and a required one to\n // RESTRICT, so deletes behave identically across databases (MySQL checks\n // self-referencing FKs row-by-row where PG/SQLite validate at statement\n // end). The rule has one owner, `foreignKeyOnDelete`, which the engine's\n // referential requirement reads too.\n foreignKeys.push({\n name: `${tableName}_${fkColumns.join(\"_\")}_fkey`,\n columns: fkColumns,\n referencedTable: targetTableName,\n referencedColumns,\n onDelete: foreignKeyOnDelete(edge),\n onUpdate: edge.reference.onUpdate ?? \"noAction\",\n });\n\n // The inverse of a plural stored reference is to-many: every include,\n // relation filter and nested-write locate reads this table through the FK\n // columns. MySQL/InnoDB indexes an FK constraint by itself;\n // PostgreSQL and SQLite do not, so serialize the index on every\n // dialect — one snapshot shape for the differ, and on MySQL the\n // explicit index takes the place of the implicit one. A UNIQUE FK\n // needs nothing here: the unique constraint below is its index.\n if (edge.unique) {\n // 1:1 FK must be unique at the DB level, or it degrades to N:1\n const fkKey = [...fkColumns].sort().join(\",\");\n const alreadyUnique =\n [...pkColumns].sort().join(\",\") === fkKey ||\n uniqueConstraints.some(\n (u) => [...u.columns].sort().join(\",\") === fkKey\n ) ||\n indexes.some(\n (i) =>\n i.unique &&\n isTotalIndex(i) &&\n [...i.columns].sort().join(\",\") === fkKey\n );\n if (!alreadyUnique) {\n uniqueConstraints.push({\n name: `${tableName}_${fkColumns.join(\"_\")}_key`,\n columns: fkColumns,\n });\n }\n continue;\n }\n\n // The primary key, every unique constraint and every declared index\n // is backed by an index on all three dialects, and an index serves\n // any prefix of its columns — so a FK index over such a prefix\n // would only duplicate one the database already has.\n const coveringColumns = [\n pkColumns,\n ...uniqueConstraints.map((unique) => unique.columns),\n ...oneToOneFkColumns,\n ...declaredIndexColumns,\n ];\n const alreadyIndexed = coveringColumns.some((columns) =>\n fkColumns.every((column, position) => columns[position] === column)\n );\n if (alreadyIndexed) continue;\n // An index the schema declares over exactly these columns but\n // does not cover them — a partial index — auto-names itself the\n // way this one does, and a database keeps one index per name. So\n // the automatic index falls back on the name of the constraint it\n // serves. Only a schema that has no foreign-key index today can\n // take the fallback, so no database that already holds the index\n // is renamed into a drop and a create.\n //\n // A schema may of course have spent BOTH names on indexes of its\n // own — `.index([...], { name: \"<table>_<cols>_fkey_idx\" })` is\n // legal. Then this index has no name left to take, and pushing it\n // anyway put two entries under one name into the snapshot: the\n // differ emitted two `CREATE INDEX` and the second failed the\n // whole push (measured on better-sqlite3: `index\n // zz_fb_kid_ownerId_fkey_idx already exists`). The index is a read\n // optimization, not a correctness requirement, so it yields to the\n // names the schema declared.\n const name = automaticForeignKeyIndexName(\n tableName,\n fkColumns,\n new Set(indexes.map((index) => index.name))\n );\n if (name !== undefined) {\n indexes.push({ name, columns: fkColumns, unique: false });\n }\n }\n\n tables.push({\n name: tableName,\n columns,\n primaryKey,\n indexes,\n foreignKeys,\n uniqueConstraints,\n // Key omitted when empty so ordinary tables keep their exact shape.\n ...(Object.keys(relationStorage).length > 0 ? { relationStorage } : {}),\n });\n }\n\n // ==========================================================================\n // ORDINARY JUNCTION TABLES\n //\n // One edge per resolved pair, at `endpoints[0]` — the canonically first\n // endpoint, which is the very endpoint the old two-model walk registered from.\n // A member VIEW of a variant carrier never appears here: the gate resolved\n // that slot onto its carrier's edge, so the skip that used to rescan for a\n // compatible binding is now structural.\n // ==========================================================================\n for (const edge of junctions) {\n const sourceSlot = edge.endpoints[0];\n const model = sourceSlot.source;\n const modelName = model[\"~\"].names.ts;\n const sourceTableName =\n model[\"~\"].names.sql ||\n model[\"~\"].state.tableName ||\n (modelName ?? \"\").toLowerCase();\n const targetSlot = partnerOf(edge, sourceSlot);\n const targetModel = targetSlot.source;\n const targetModelName = targetModel[\"~\"].names.ts;\n if (!(modelName && targetModelName)) {\n throw new Error(\n `Target model for relation \"${sourceSlot.field}\" has no name. ` +\n \"Schema may not be hydrated. Call hydrateSchemaNames() first.\"\n );\n }\n const targetTableName = targetModel[\"~\"].names.sql;\n if (!targetTableName) {\n throw new Error(\n `Target model \"${targetModelName}\" has no SQL table name. ` +\n \"Schema may not be hydrated. Call hydrateSchemaNames() first.\"\n );\n }\n\n const sourcePkFields = getPrimaryKeyFieldDefs(\n model,\n migrationDriver,\n index\n );\n const targetPkFields = getPrimaryKeyFieldDefs(\n targetModel,\n migrationDriver,\n index\n );\n const topology = edge.topology;\n // Decorate the owner's members with the driver-typed key defs by index:\n // the members were zipped from these same row-key lists, so both sides\n // carry exactly one member per key def and the lookup cannot miss.\n const sourceMembers = topology.source.members.map((member, index) => ({\n column: member.junctionField,\n pk: sourcePkFields[index]!,\n }));\n const targetMembers = topology.target.members.map((member, index) => ({\n column: member.junctionField,\n pk: targetPkFields[index]!,\n }));\n\n // Canonical column order: sorted model names decide (as the generated\n // table name does), so both sides serialize the identical table. Each\n // side carries its own foreign key's actions, so the reorder below moves\n // an action with the table and columns it constrains. Prisma parity: an\n // action the owner left unstated is CASCADE, so deleting an endpoint row\n // removes its associations.\n const sourceSide = {\n members: sourceMembers,\n table: sourceTableName,\n sortKey: modelName.toLowerCase(),\n onDelete: junctionOnDelete(topology.source),\n onUpdate: topology.source.onUpdate ?? \"cascade\",\n };\n const targetSide = {\n members: targetMembers,\n table: targetTableName,\n sortKey: targetModelName.toLowerCase(),\n onDelete: junctionOnDelete(topology.target),\n onUpdate: topology.target.onUpdate ?? \"cascade\",\n };\n let [first, second] = [sourceSide, targetSide];\n if (!topology.sourceIsFirst) {\n [first, second] = [second, first];\n }\n\n const firstColumns = first.members.map((member) => member.column);\n const secondColumns = second.members.map((member) => member.column);\n\n const junctionDef: TableDef = {\n name: topology.table,\n columns: [\n ...first.members.map((member) => ({\n name: member.column,\n type: member.pk.type,\n nullable: false,\n })),\n ...second.members.map((member) => ({\n name: member.column,\n type: member.pk.type,\n nullable: false,\n })),\n ],\n primaryKey: { columns: [...firstColumns, ...secondColumns] },\n // The PK covers first-side lookups; reverse traversal needs one\n // index over the complete second-side stored reference.\n indexes: [\n {\n name: topology.reverseIndexName(),\n columns: secondColumns,\n unique: false,\n },\n ],\n foreignKeys: [\n {\n name: topology.foreignKeyName(\n topology.sourceIsFirst ? \"source\" : \"target\"\n ),\n columns: firstColumns,\n referencedTable: first.table,\n referencedColumns: first.members.map((member) => member.pk.column),\n onDelete: first.onDelete,\n onUpdate: first.onUpdate,\n },\n {\n name: topology.foreignKeyName(\n topology.sourceIsFirst ? \"target\" : \"source\"\n ),\n columns: secondColumns,\n referencedTable: second.table,\n referencedColumns: second.members.map((member) => member.pk.column),\n onDelete: second.onDelete,\n onUpdate: second.onUpdate,\n },\n ],\n uniqueConstraints: [],\n };\n\n // Both sides of a pair serialize identically after canonicalization, so\n // a mismatch means two different relation pairs collide on one table.\n // Pair identity (models + relation name) catches collisions even when\n // the column defs happen to be byte-identical.\n const pairKey = `${[first.sortKey, second.sortKey].join(\"::\")}::${\n topology.pairName ?? \"\"\n }`;\n const existing = junctionTables.get(topology.table);\n if (existing) {\n if (\n existing.pairKey !== pairKey ||\n JSON.stringify(existing.def) !== JSON.stringify(junctionDef)\n ) {\n throw new Error(\n `Junction table \"${topology.table}\" is shared by multiple distinct many-to-many relation pairs. ` +\n \"Give each pair a distinct .name() or its own .through() table name.\"\n );\n }\n continue;\n }\n junctionTables.set(topology.table, { def: junctionDef, pairKey });\n }\n\n // Append junction tables to the tables array\n for (const { def } of junctionTables.values()) {\n tables.push(def);\n }\n\n const snapshot: SchemaSnapshot = {\n tables: tables.map((table) => migrationDriver.finalizeTable(table)),\n enums: enums.length > 0 ? enums : undefined,\n ...(polymorphicStorage.length > 0 ? { polymorphicStorage } : {}),\n };\n return migrationDriver.target\n ? selectManagedSnapshot(snapshot, migrationDriver.target, true)\n : snapshot;\n}\n\n// =============================================================================\n// HELPER FUNCTIONS\n// =============================================================================\n\n/**\n * Serialize ONE polymorphic collection member's junction table, byte-reusing\n * the ordinary junction template: canonical orientation, driver types zipped\n * BY INDEX against the stored topology's sides, PK without a name, one\n * reverse index when uniqueness does not cover it, and two FIXED-cascade foreign keys —\n * `resolveJunctionPairActions` is NEVER called on this path (member actions\n * are cascade by design; a hostile referential-action spelling never reaches\n * this DDL). Consumes ONLY the stored `ResolvedJunctionTopology`: every\n * physical name comes from the topology's own methods, never reconstructed\n * from naming conventions.\n */\nfunction serializeMemberJunction(\n ownerModel: AnyModel,\n ownerTableName: string,\n member: ResolvedVariantJunctionMember,\n migrationDriver: MigrationDriver,\n relations: ResolvedRelationIndex\n): TableDef {\n const junction = member.topology;\n const targetModel = junction.target.model;\n const targetModelName = targetModel[\"~\"].names.ts;\n const targetTableName = getModelTableName(\n targetModel,\n targetModelName?.toLowerCase() ?? \"unknown\"\n );\n const sourcePkFields = getPrimaryKeyFieldDefs(\n ownerModel,\n migrationDriver,\n relations\n );\n const targetPkFields = getPrimaryKeyFieldDefs(\n targetModel,\n migrationDriver,\n relations\n );\n // Decorate the sides with the driver-typed key defs by index: the stored\n // topology zipped its members from the same model-key-catalog row keys these\n // defs come from, so both lists carry exactly one entry per key def.\n const sourceMembers = junction.source.members.map(\n (junctionMember, index) => ({\n column: junctionMember.junctionField,\n pk: sourcePkFields[index]!,\n })\n );\n const targetMembers = junction.target.members.map(\n (junctionMember, index) => ({\n column: junctionMember.junctionField,\n pk: targetPkFields[index]!,\n })\n );\n\n const sourceSide = { members: sourceMembers, table: ownerTableName };\n const targetSide = { members: targetMembers, table: targetTableName };\n let [first, second] = [sourceSide, targetSide];\n if (!junction.sourceIsFirst) {\n [first, second] = [second, first];\n }\n\n const firstColumns = first.members.map(\n (junctionMember) => junctionMember.column\n );\n const secondColumns = second.members.map(\n (junctionMember) => junctionMember.column\n );\n\n return {\n name: junction.table,\n columns: [\n ...first.members.map((junctionMember) => ({\n name: junctionMember.column,\n type: junctionMember.pk.type,\n nullable: false,\n })),\n ...second.members.map((junctionMember) => ({\n name: junctionMember.column,\n type: junctionMember.pk.type,\n nullable: false,\n })),\n ],\n primaryKey: { columns: [...firstColumns, ...secondColumns] },\n // The PK covers the first side. A singular target on the second side has\n // its unique constraint already; otherwise reverse lookup needs an index.\n indexes:\n member.uniqueTarget && junction.sourceIsFirst\n ? []\n : [\n {\n name: junction.reverseIndexName(),\n columns: secondColumns,\n unique: false,\n },\n ],\n foreignKeys: [\n {\n name: junction.foreignKeyName(\n junction.sourceIsFirst ? \"source\" : \"target\"\n ),\n columns: firstColumns,\n referencedTable: first.table,\n referencedColumns: first.members.map(\n (junctionMember) => junctionMember.pk.column\n ),\n onDelete: \"cascade\",\n onUpdate: \"cascade\",\n },\n {\n name: junction.foreignKeyName(\n junction.sourceIsFirst ? \"target\" : \"source\"\n ),\n columns: secondColumns,\n referencedTable: second.table,\n referencedColumns: second.members.map(\n (junctionMember) => junctionMember.pk.column\n ),\n onDelete: \"cascade\",\n onUpdate: \"cascade\",\n },\n ],\n // The unique side is the complete ordered TARGET side, NOT the reverse\n // index flipped: when the target sorts canonical-first the reverse index\n // covers the OWNER side, and the PK prefix does not make target columns\n // unique. The name is asked LAST (idx → first fkey → second fkey → key)\n // so the other three refusal positions stay where they are.\n uniqueConstraints: member.uniqueTarget\n ? [\n {\n name: junction.uniqueTargetName(),\n columns: targetMembers.map(\n (junctionMember) => junctionMember.column\n ),\n },\n ]\n : [],\n };\n}\n\n/**\n * Get every primary-key member in model-key order.\n */\nfunction getPrimaryKeyFieldDefs(\n model: AnyModel,\n migrationDriver: MigrationDriver,\n relations: ResolvedRelationIndex\n): readonly { field: string; column: string; type: string }[] {\n const modelState = model[\"~\"].state;\n const modelName = model[\"~\"].names.ts;\n const rowKey = getModelKeyCatalog(model).rowKey?.fields;\n if (!rowKey || rowKey.length === 0) {\n throw new Error(\n `Model \"${modelName}\" has no primary key. Schema may not be hydrated.`\n );\n }\n return rowKey.map((field) => {\n const scalar = modelState.scalars[field];\n if (!scalar) {\n throw new Error(\n `Primary-key field '${field}' of model \"${modelName}\" is not a scalar.`\n );\n }\n const scalarState = scalar[\"~\"].state;\n return {\n field,\n column: model[\"~\"].getFieldName(field).sql,\n // A junction column holds the referenced primary KEY's values, and that\n // key's identifier domain may be DERIVED — the one-to-one child whose\n // primary key is its parent foreign key is the ordinary case — so it is\n // read against the model through the same resolved index every other\n // column of this serialization is typed from. Reading the scalar's own\n // declaration types the junction column as text beside the sixteen-byte\n // column it references, which PostgreSQL refuses to key at all.\n type: migrationDriver.mapScalarType(\n scalar,\n scalarState,\n idDomainOf(model, field, relations)\n ),\n };\n });\n}\n\nexport { getColumnName } from \"../schema/model\";\n\n/**\n * Gets the SQL table name for a model\n */\nexport function getTableName(model: AnyModel, modelName: string): string {\n return getModelTableName(model, modelName.toLowerCase());\n}\n","import type { AnyDriver } from \"../../drivers/driver\";\nimport { MigrationError, VibORMErrorCode } from \"../../errors\";\nimport type { AnyModel } from \"../../schema/model\";\nimport type { ResolvedRelationIndex } from \"../../schema/validation/relation-resolution\";\nimport { admitLiveMigrationCapability } from \"../admission\";\nimport {\n type DiffOptions,\n diff,\n type IndexPredicateCanonicalizer,\n isDestructiveOperation,\n} from \"../differ\";\nimport type { BoundMigrationDriver, MigrationDriver } from \"../drivers\";\nimport { getMigrationDriver } from \"../drivers\";\nimport { emptyManagedSnapshot } from \"../empty-snapshot\";\nimport type { ResolvedMigrationLimits } from \"../limits\";\nimport { applyNativeRename } from \"../native-rename\";\nimport {\n alwaysAddDropResolver,\n ambiguousDropKey,\n ambiguousToResolveChange,\n approveDestructiveOperations,\n resolveAmbiguousChanges,\n validateResolveResult,\n} from \"../resolver\";\nimport { serializeResolvedModels } from \"../serializer\";\nimport { MANAGED_TABLES, MIGRATION_LIMITS } from \"../target\";\nimport type {\n AmbiguousChange,\n ChangeResolution,\n DiffOperation,\n DiffResult,\n ResolveCallback,\n Resolver,\n SchemaSnapshot,\n} from \"../types\";\nimport { prepareSchemaProgram, sortOperations } from \"../utils\";\nimport {\n applyForceEnumResolutions,\n applyResolvedEnumMappings,\n detectEnumValueRemovals,\n type EnumRemoval,\n resolveEnumValueRemovalMappings,\n} from \"./enum-removals\";\nimport {\n formatAmbiguousChangeDescription,\n formatDestructiveOperation,\n} from \"./format\";\n\n/**\n * Minimal client interface required for migrations.\n * This allows push() to work with any object that has $driver and $schema.\n */\nexport interface MigrationClient {\n $driver: AnyDriver;\n $schema: Record<string, AnyModel>;\n readonly [MANAGED_TABLES]?: readonly string[] | undefined;\n readonly [MIGRATION_LIMITS]?: ResolvedMigrationLimits | undefined;\n}\n\nexport interface PushOptions {\n /** Planner-only auto-resolution; public V1 push does not expose this key. */\n force?: boolean;\n /**\n * Skip schema validation before pushing. Validation catches definition\n * errors that would otherwise corrupt data silently (e.g. two relation\n * pairs sharing one junction table) — only skip it when deliberately\n * pushing a shape the validator flags.\n */\n skipValidation?: boolean;\n /** Preview SQL without executing */\n dryRun?: boolean;\n /**\n * Rebuild from the empty snapshot. Public V1 requires preview consent before\n * executing the resulting force-reset plan.\n */\n forceReset?: boolean;\n /**\n * Unified callback for resolving changes that require user input.\n * Called once per change, allowing granular control over each decision.\n *\n * Each change has methods for valid resolutions:\n * - Destructive: `change.proceed()`, `change.reject()`\n * - Ambiguous: `change.rename()`, `change.addAndDrop()`, `change.reject()`\n * - Enum value removal: `change.mapValues({...})`, `change.useNull()`, `change.reject()`\n *\n * A change the callback leaves undecided (returns `undefined`) refuses the\n * plan with MIGRATION_DESTRUCTIVE_REJECTED. Public `migrations.push()` has no\n * `force`; only the planner-internal `force` above turns an undecided change\n * into add+drop, acceptance or NULL.\n *\n * @example\n * ```ts\n * // Accept dropping a column, refuse everything else\n * await migrations.push({\n * dryRun: true,\n * resolve: async (change) => {\n * if (change.type === \"destructive\" && change.operation === \"dropColumn\") {\n * return change.proceed();\n * }\n * return change.reject();\n * },\n * });\n * ```\n */\n resolve?: ResolveCallback;\n}\n\n// Push deliberately carries NO storage owner. Ordinary push and force-reset\n// synchronize the live namespace and nothing else: they read no journal, write\n// no journal or snapshot, and cannot rewrite an estate's history as a side\n// effect of a schema sync.\n\nexport interface PushPlan {\n operations: DiffOperation[];\n currentSchema: SchemaSnapshot;\n}\n\nexport function getPushMigrationDriver(\n client: MigrationClient\n): BoundMigrationDriver {\n return getMigrationDriver(\n client.$driver,\n client[MANAGED_TABLES],\n client[MIGRATION_LIMITS]\n );\n}\n\n/**\n * Introspects the current database schema without making any changes.\n * Useful for debugging or displaying current state.\n *\n * It changes nothing, but it READS live state, so it is a live migration\n * command and takes the one shared admission owner like every other one —\n * before any provider work. Without this gate an unbound MySQL client would\n * publish an inventory of whatever database its connection happened to default\n * to, which is exactly the ambient-default target §3.3 refuses to accept.\n * `push({ dryRun: true })` performs the same introspection behind the same\n * `read-only` admission; this entry point must not be the way around it.\n */\nexport async function introspect(\n client: MigrationClient\n): Promise<SchemaSnapshot> {\n const migrationDriver = getPushMigrationDriver(client);\n admitLiveMigrationCapability(migrationDriver, \"read-only\", \"introspect()\");\n return introspectSchema(client.$driver, migrationDriver);\n}\n\nexport async function introspectSchema(\n driver: AnyDriver,\n migrationDriver: MigrationDriver\n): Promise<SchemaSnapshot> {\n return migrationDriver.introspect((sql, params) =>\n driver._executeRaw(sql, params)\n );\n}\n\n/**\n * Hands the differ a way to ask the database for its own spelling of a declared\n * partial-index predicate (Decision 7.4). Returns undefined when nobody can\n * answer, and the differ then compares the two texts raw — the reading that\n * plans a drop and a create, which is the safe direction.\n *\n * The whole canonicalization runs inside ONE transaction, for two reasons that\n * both matter: it pins a single connection (the scratch objects it needs exist\n * only inside their transaction, and a pool hands out a different connection\n * per statement), and a failure anywhere rolls the scratch away instead of\n * leaving it attached to a table this push may be about to drop.\n */\nfunction buildIndexPredicateCanonicalizer(\n driver: AnyDriver,\n migrationDriver: MigrationDriver\n): IndexPredicateCanonicalizer | undefined {\n const canonicalize = migrationDriver.canonicalizeIndexPredicates;\n if (!(canonicalize && driver.supportsTransactions)) return;\n\n return async (tableName, predicates) => {\n try {\n return await driver.withTransaction((tx) =>\n canonicalize.call(\n migrationDriver,\n tableName,\n predicates,\n (sql, params) => tx._executeRaw(sql, params)\n )\n );\n } catch {\n // Fail closed, and stay out of the way. A predicate the database cannot\n // parse, a connection that refused, a dialect that changed under us —\n // none of it may make a push fail, and none of it may be read as \"these\n // two predicates are the same\". Answering nothing leaves the differ with\n // the raw texts, which is exactly the pre-7.4 behavior.\n return predicates.map(() => undefined);\n }\n };\n}\n\n/**\n * The COMPLETE empty-to-desired program, compiled before a force-reset entry.\n *\n * §6.2: \"Before entry, serialize and validate the desired schema, resolve its\n * relation index, compile the empty-to-desired DDL, and prove that program\n * contains no commit-boundary statement.\" Diffing against the LIVE database\n * would describe a program for a database this command is about to empty, so\n * the baseline is the empty snapshot — the state the clear produces.\n *\n * Nothing here reads live state, so it runs before the clear and its result is\n * what the one locked transaction executes.\n */\nexport async function planRebuildFromEmpty(\n client: MigrationClient,\n migrationDriver: MigrationDriver,\n options: PushOptions,\n relations: ResolvedRelationIndex\n): Promise<PushPlan> {\n const desired = serializeResolvedModels(\n client.$schema,\n migrationDriver,\n relations\n );\n const current = emptyManagedSnapshot();\n const diffOptions: DiffOptions = {\n projectRename: migrationDriver.projectNativeRename.bind(migrationDriver),\n refuseConstraintNameChurn:\n migrationDriver.capabilities.introspectionReadsConstraintNames,\n matchConstraintsByShape:\n !migrationDriver.capabilities.introspectionReadsConstraintNames,\n };\n const diffResult = await diff(current, desired, diffOptions);\n const operations = await resolvePushOperations(\n diffResult,\n desired,\n current,\n options,\n diffOptions\n );\n\n return {\n operations: prepareSchemaProgram(operations, current, migrationDriver),\n currentSchema: current,\n };\n}\n\nexport async function planPush(\n client: MigrationClient,\n migrationDriver: MigrationDriver,\n options: PushOptions,\n relations: ResolvedRelationIndex\n): Promise<PushPlan> {\n const desired = serializeResolvedModels(\n client.$schema,\n migrationDriver,\n relations\n );\n // Live introspection sees the private columns and index, but a text\n // discriminator cannot reveal historical public/stored member mappings.\n // Push therefore compares structure only. Stored-value history is owned by\n // file-based generate(), where both serialized snapshots are available.\n const current = await introspectSchema(client.$driver, migrationDriver);\n const diffOptions: DiffOptions = {\n projectRename: migrationDriver.projectNativeRename.bind(migrationDriver),\n canonicalizeIndexPredicate: buildIndexPredicateCanonicalizer(\n client.$driver,\n migrationDriver\n ),\n // `current` was just introspected. Where that introspection cannot read a\n // constraint's name back, the name it carries is a synthesis and matching\n // on it would make every unchanged constraint read as a change.\n refuseConstraintNameChurn:\n migrationDriver.capabilities.introspectionReadsConstraintNames,\n matchConstraintsByShape:\n !migrationDriver.capabilities.introspectionReadsConstraintNames,\n };\n const diffResult = await diff(current, desired, diffOptions);\n const operations = await resolvePushOperations(\n diffResult,\n desired,\n current,\n options,\n diffOptions\n );\n\n return {\n operations: prepareSchemaProgram(operations, current, migrationDriver),\n currentSchema: current,\n };\n}\n\nasync function resolvePushOperations(\n diffResult: DiffResult,\n desired: SchemaSnapshot,\n current: SchemaSnapshot,\n options: PushOptions,\n diffOptions: DiffOptions\n): Promise<DiffOperation[]> {\n const force = options.force ?? false;\n const allEnumRemovals = detectEnumValueRemovals(\n diffResult.operations,\n current\n );\n\n if (options.resolve) {\n return resolveWithCallback(\n diffResult,\n current,\n desired,\n diffOptions,\n allEnumRemovals,\n options.resolve,\n force\n );\n }\n\n if (force) {\n const resolvedOperations = await resolveAmbiguousChanges(\n diffResult,\n current,\n desired,\n alwaysAddDropResolver,\n diffOptions\n );\n return applyForceEnumResolutions(resolvedOperations, allEnumRemovals);\n }\n\n rejectUnresolvedChanges(diffResult, allEnumRemovals);\n return [...diffResult.operations];\n}\n\nasync function resolveWithCallback(\n diffResult: DiffResult,\n current: SchemaSnapshot,\n desired: SchemaSnapshot,\n diffOptions: DiffOptions,\n enumRemovals: EnumRemoval[],\n resolve: ResolveCallback,\n force = false\n): Promise<DiffOperation[]> {\n const admittedAmbiguousDrops = new Set<string>();\n const ambiguityResolver: Resolver = async (changes) => {\n const resolutions = new Map<AmbiguousChange, ChangeResolution>();\n for (const change of changes) {\n const resolveChange = ambiguousToResolveChange(change);\n const result = validateResolveResult(\n \"ambiguous\",\n resolveChange,\n await resolve(resolveChange)\n );\n\n if (result === \"reject\") {\n throw new MigrationError(\n `Change rejected: ${resolveChange.description}`,\n VibORMErrorCode.MIGRATION_DESTRUCTIVE_REJECTED\n );\n }\n if (result === undefined) {\n if (force) {\n resolutions.set(change, { type: \"addAndDrop\" });\n admittedAmbiguousDrops.add(ambiguousDropKey(change));\n continue;\n }\n const advice =\n change.type === \"ambiguousTable\"\n ? `If \"${change.droppedTable}\" is not this schema's table, set migrations.tables so push does not manage it; otherwise name the pair with change.rename() or change.addAndDrop().`\n : \"Return change.rename() or change.addAndDrop() from the resolver.\";\n throw new MigrationError(\n `Unresolved ambiguous change: ${resolveChange.description}\\n${advice}`,\n VibORMErrorCode.MIGRATION_DESTRUCTIVE_REJECTED\n );\n }\n resolutions.set(change, {\n type: result === \"rename\" ? \"rename\" : \"addAndDrop\",\n });\n if (result !== \"rename\") {\n admittedAmbiguousDrops.add(ambiguousDropKey(change));\n }\n }\n return resolutions;\n };\n\n const resolvedOperations = await resolveAmbiguousChanges(\n diffResult,\n current,\n desired,\n ambiguityResolver,\n diffOptions\n );\n const resolvedEnumRemovals = retargetEnumRemovals(\n enumRemovals,\n current,\n resolvedOperations,\n diffOptions.projectRename\n );\n await approveDestructiveOperations(\n resolvedOperations,\n resolve,\n force,\n admittedAmbiguousDrops\n );\n const finalOperations: DiffOperation[] = resolvedOperations.filter(\n (op) => op.type !== \"alterEnum\"\n );\n const enumColumnMappings = await resolveEnumValueRemovalMappings(\n resolvedEnumRemovals,\n resolve,\n force\n );\n\n finalOperations.push(\n ...applyResolvedEnumMappings(resolvedOperations, enumColumnMappings)\n );\n\n return sortOperations(finalOperations);\n}\n\nfunction retargetEnumRemovals(\n removals: EnumRemoval[],\n current: SchemaSnapshot,\n operations: DiffOperation[],\n projectRename: typeof applyNativeRename = applyNativeRename\n): EnumRemoval[] {\n let renamedCurrent = current;\n for (const operation of operations) {\n if (operation.type === \"renameTable\" || operation.type === \"renameColumn\") {\n renamedCurrent = projectRename(renamedCurrent, operation);\n }\n }\n\n return removals.map((removal) => {\n const tablePosition = current.tables.findIndex(\n (table) => table.name === removal.tableName\n );\n const currentTable = current.tables[tablePosition];\n const columnPosition = currentTable?.columns.findIndex(\n (column) => column.name === removal.columnName\n );\n const table = renamedCurrent.tables[tablePosition];\n const column =\n columnPosition === undefined ? undefined : table?.columns[columnPosition];\n if (!(currentTable && table && column)) {\n throw new MigrationError(\n `Cannot retarget enum removal for \"${removal.tableName}.${removal.columnName}\" through the accepted renames.`,\n VibORMErrorCode.INTERNAL_ERROR\n );\n }\n return { ...removal, tableName: table.name, columnName: column.name };\n });\n}\n\nfunction rejectUnresolvedChanges(\n diffResult: {\n operations: DiffOperation[];\n ambiguousChanges: AmbiguousChange[];\n },\n enumRemovalsNeedingResolution: EnumRemoval[]\n): void {\n const destructiveOps = diffResult.operations.filter(isDestructiveOperation);\n const hasAmbiguous = diffResult.ambiguousChanges.length > 0;\n\n if (\n destructiveOps.length === 0 &&\n !hasAmbiguous &&\n enumRemovalsNeedingResolution.length === 0\n ) {\n return;\n }\n\n const descriptions: string[] = [];\n\n for (const op of destructiveOps) {\n descriptions.push(formatDestructiveOperation(op));\n }\n\n for (const change of diffResult.ambiguousChanges) {\n descriptions.push(formatAmbiguousChangeDescription(change));\n }\n\n for (const removal of enumRemovalsNeedingResolution) {\n descriptions.push(\n `[enumValueRemoval] \"${removal.tableName}.${removal.columnName}\" uses enum \"${removal.enumName}\" - removing values: ${removal.removedValues.join(\", \")} (non-nullable)`\n );\n }\n\n throw new MigrationError(\n `Changes requiring resolution detected:\\n${descriptions.join(\"\\n\")}\\n\\n` +\n \"Provide a resolve callback to choose each change explicitly.\",\n VibORMErrorCode.MIGRATION_DESTRUCTIVE_REJECTED\n );\n}\n","/**\n * The ONE live-namespace reset owner (§6.2).\n *\n * Three programs used to invent reset SQL: the CLI's own dynamic loop, the\n * dialect drivers' `generateResetSQL()`, and `push({ forceReset: true })`. They\n * disagreed — MySQL's dialect answer dropped nothing at all, and PostgreSQL's\n * enumerated `public` regardless of the estate — so this module replaces all\n * three. Migration `reset()` and force-reset push both keep the migration\n * control pair: a clear drops neither table.\n *\n * Containment is the point: the inventory is a bound catalog read scoped to the\n * configured namespace, foreign keys inside it are dropped explicitly rather\n * than cascaded away, and nothing here issues `DROP SCHEMA`, `DROP DATABASE`,\n * or `FOREIGN_KEY_CHECKS = 0`.\n *\n * {@link planLiveNamespaceReset} decides and renders the whole clear from\n * catalog reads, before the first effect. Every refusal lives there, so no\n * caller's commit-model reporter can restate a containment refusal as a failure\n * part-way through a program that never began.\n */\n\nimport type { AnyDriver } from \"../drivers/driver\";\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\nimport { errorCause } from \"../errors/diagnostic-safety\";\nimport { CONTROL_TABLES } from \"./control\";\nimport type { BoundMigrationDriver } from \"./drivers\";\nimport { childrenBeforeParents, type TableReference } from \"./drop-order\";\nimport { introspectSchema } from \"./push/planner\";\nimport type { ForeignKeyDef, SchemaSnapshot } from \"./types\";\nimport { createQueryExecutor } from \"./utils\";\n\n/** One table this reset drops, and the statement that drops it. */\ninterface PlannedTableDrop {\n readonly name: string;\n readonly sql: string;\n}\n\n/**\n * The COMPLETE clear, decided and rendered — and nothing executed.\n *\n * The split is the point (§6.2). Everything that can REFUSE the clear —\n * proving the namespace, reading the inventory, both containment refusals, the\n * drop order — is answered from catalog reads, so it belongs before the caller\n * enters a commit model at all. A refusal that has already been wrapped in\n * MySQL's partial-commit reporter tells the caller a database nothing touched\n * \"failed partway through\", and loses the metadata naming the constraint that\n * made it refuse.\n */\nexport interface LiveNamespaceResetPlan {\n /**\n * Every foreign key the estate owns, as an explicit drop, or SQLite's one\n * deferral of them all ({@link clearForeignKeys}).\n */\n readonly dropForeignKeys: string[];\n /** The tables this reset drops, in the order they will be dropped. */\n readonly dropTables: readonly PlannedTableDrop[];\n /** Managed enum drops, which run after the tables that use them. */\n readonly dropEnums: string[];\n /** The whole clear, in the order it runs: keys, then tables, then enums. */\n readonly clear: readonly string[];\n}\n\nexport interface LiveNamespaceInventory {\n /** The estate's dependency graph, as the catalog describes it. */\n readonly snapshot: SchemaSnapshot;\n /** Every table in the configured namespace. */\n readonly tables: string[];\n /** Every managed enum type, on dialects that have them. */\n readonly enums: string[];\n}\n\n/**\n * Proves the configured namespace and reads what a reset would touch.\n *\n * ONE owner for both consumers — the effectful reset and the dry run that\n * previews it — because a preview computed a different way is not a preview.\n * `introspect` is what proves the namespace exists before anything is\n * published, and it refuses a foreign key with exactly one side inside the\n * estate, so a cross-namespace dependency is refused BEFORE the first DDL\n * rather than discovered after half the estate is gone.\n *\n * The snapshot describes the GRAPH; the bound catalog read decides MEMBERSHIP,\n * because a table the snapshot cannot model is still a table in this namespace\n * and a reset that skipped it would leave the estate half-cleared. For the same\n * reason the membership read is the one provider result this owner refuses to\n * treat as advisory: see {@link readNames}.\n */\nexport async function inventoryLiveNamespace(\n driver: AnyDriver,\n migrationDriver: BoundMigrationDriver\n): Promise<LiveNamespaceInventory> {\n const snapshot = await introspectSchema(driver, migrationDriver);\n\n const executor = createQueryExecutor(driver);\n const inventory = migrationDriver.generateInventoryTables();\n const tables = readNames(\n await executor(inventory.sql, inventory.params),\n \"table\"\n ).filter(\n (name) =>\n migrationDriver.target.tables === undefined ||\n migrationDriver.target.tables.includes(name)\n );\n\n const enumInventory = migrationDriver.generateInventoryEnums();\n const enums = enumInventory\n ? readNames(\n await executor(enumInventory.sql, enumInventory.params),\n \"managed enum\"\n )\n : [];\n\n return {\n snapshot,\n tables,\n enums:\n migrationDriver.target.tables === undefined\n ? enums\n : enums.filter((name) =>\n snapshot.enums?.some((item) => item.name === name)\n ),\n };\n}\n\n/**\n * Decides and renders the COMPLETE clear, without executing any of it.\n *\n * Namespace proof, inventory, both containment refusals, foreign-key\n * materialization and drop order all happen here, so every way this clear can\n * refuse is answered from catalog reads alone — before the caller enters a\n * transaction or a sequential program, and therefore before anything can\n * describe a refusal as a partial commit (§6.2). It is also what lets a dry run\n * preview the effectful path rather than a second computation of it.\n *\n * @param driver - the producer to read the catalog on; the caller has already\n * pinned and locked it where its dialect has a lock to take\n * @param migrationDriver - the estate-bound migration driver\n */\nexport async function planLiveNamespaceReset(\n driver: AnyDriver,\n migrationDriver: BoundMigrationDriver\n): Promise<LiveNamespaceResetPlan> {\n const { snapshot, tables, enums } = await inventoryLiveNamespace(\n driver,\n migrationDriver\n );\n\n // MySQL is the one dialect whose DDL commits as it runs, and it cannot make\n // the tracking clear and the destructive DDL one transaction — so an inbound\n // foreign key to the declared tracking table has no safe order: dropping that\n // key first opens a window where the history rows are still there and their\n // schema is going away, and clearing or dropping the referenced table first\n // can simply be blocked.\n if (migrationDriver.target.dialect === \"mysql\") {\n assertNoInboundTrackingReference(snapshot, CONTROL_TABLES.state);\n }\n\n // Drop every foreign key the estate owns, explicitly, before any table\n // drop. This is what replaces `CASCADE` and `FOREIGN_KEY_CHECKS = 0`:\n // cycles and mutually-dropped tables are handled, and a dependency this\n // inventory does NOT represent aborts the operation instead of being\n // deleted with it.\n const dropForeignKeys = clearForeignKeys(\n migrationDriver,\n ownedForeignKeys(snapshot, tables)\n );\n\n // The control pair survives every clear: its structure is the history.\n const droppable = tables.filter(\n (name) => name !== CONTROL_TABLES.state && name !== CONTROL_TABLES.log\n );\n\n const dropTables: PlannedTableDrop[] = [];\n for (const table of dependencySafeOrder(droppable, snapshot)) {\n dropTables.push({\n name: table,\n sql: migrationDriver.generateDropTableSQL(table),\n });\n }\n\n // Managed enums go after their tables: a type still used by a column is\n // a dependency, and `RESTRICT` is the point.\n const dropEnums: string[] = [];\n for (const enumName of enums) {\n const statement = migrationDriver.generateDropEnumSQL(enumName);\n if (statement) {\n dropEnums.push(statement);\n }\n }\n\n return {\n dropForeignKeys,\n dropTables,\n dropEnums,\n clear: [\n ...dropForeignKeys,\n ...dropTables.map((table) => table.sql),\n ...dropEnums,\n ],\n };\n}\n\n/**\n * The statements that take the owned keys out of the way of the table drops.\n *\n * A dialect that keeps keys inline in `CREATE TABLE` (SQLite) cannot drop one\n * short of rebuilding its table, and its `DROP TABLE` checks the keys of every\n * row it removes, which a cycle or a self-referencing `RESTRICT` fails in any\n * order. There one statement defers every key to the COMMIT, by which point\n * each table holding one is gone.\n */\nfunction clearForeignKeys(\n migrationDriver: BoundMigrationDriver,\n owned: Iterable<{ table: string; foreignKey: ForeignKeyDef }>\n): string[] {\n const statements: string[] = [];\n for (const { table, foreignKey } of owned) {\n if (!migrationDriver.capabilities.supportsAddForeignKeyViaAlter) {\n return [\"PRAGMA defer_foreign_keys = ON\"];\n }\n statements.push(\n migrationDriver.generateDDL(\n { type: \"dropForeignKey\", tableName: table, fkName: foreignKey.name },\n { destination: \"live\" }\n )\n );\n }\n return statements;\n}\n\n/** Every foreign key owned by a table this reset is about to drop. */\nfunction* ownedForeignKeys(\n snapshot: SchemaSnapshot,\n tables: readonly string[]\n): Generator<{ table: string; foreignKey: ForeignKeyDef }> {\n const inventoried = new Set(tables);\n for (const table of snapshot.tables) {\n if (!inventoried.has(table.name)) {\n continue;\n }\n for (const foreignKey of table.foreignKeys) {\n yield { table: table.name, foreignKey };\n }\n }\n}\n\n/**\n * Children before parents, with a stable fallback for cycles.\n *\n * Every foreign key inside the estate has already been dropped by the time\n * these run, so the order is defence rather than necessity: it keeps a\n * constraint the inventory could not see from turning a reset into a failure\n * that has already dropped half the estate. A cycle's keys are already\n * dropped too, so its tables go in inventory order rather than deadlocking.\n */\nfunction dependencySafeOrder(\n tables: readonly string[],\n snapshot: SchemaSnapshot\n): string[] {\n const references: TableReference[] = [];\n for (const table of snapshot.tables) {\n for (const foreignKey of table.foreignKeys) {\n if (foreignKey.referencedTable !== table.name) {\n references.push({ from: table.name, to: foreignKey.referencedTable });\n }\n }\n }\n const { ordered, blocked } = childrenBeforeParents(\n tables,\n (name) => name,\n references\n );\n return [...ordered, ...blocked];\n}\n\n/** Refuses an inbound foreign key to the declared tracking table. */\nfunction assertNoInboundTrackingReference(\n snapshot: SchemaSnapshot,\n trackingTableName: string\n): void {\n for (const table of snapshot.tables) {\n for (const foreignKey of table.foreignKeys) {\n if (foreignKey.referencedTable !== trackingTableName) {\n continue;\n }\n throw new MigrationError(\n `Table \"${table.name}\" holds a foreign key \"${foreignKey.name}\" referencing the migration tracking table \"${trackingTableName}\", so this reset has no safe order and is refused before any statement runs. ` +\n \"MySQL commits DDL implicitly, so the tracking rows cannot be cleared and the schema torn down as one operation; drop the constraint yourself and re-run.\",\n VibORMErrorCode.MIGRATION_INVALID_STATE,\n {\n meta: {\n table: table.name,\n constraint: foreignKey.name,\n referencedTable: trackingTableName,\n },\n }\n );\n }\n }\n}\n\n/**\n * Why an inventory this read cannot trust refuses the WHOLE clear.\n *\n * One sentence for both refusals below, because they have one reason: the\n * alternative to refusing is a reset that clears part of a namespace and\n * reports success.\n */\nconst UNTRUSTED_INVENTORY =\n \"A reset drops exactly what its inventory names and leaves everything else, so an inventory this read cannot trust would clear part of the namespace and report that it cleared all of it. The whole clear is refused before any statement runs.\";\n\n/**\n * Reads the `name` column off provider-shaped inventory rows, or REFUSES.\n *\n * The inventory is not a report; it is the DROP LIST. Everything it names is\n * destroyed and everything it does not name survives, so a row this read\n * SKIPPED took a real object off the list — the clear then reported success\n * over a namespace it had half cleared, and the rebuild that followed collided\n * with what was left. A repeated name is the same defect written differently:\n * one object planned twice while another was never planned at all.\n *\n * So the read fails closed, and it fails HERE — among\n * {@link planLiveNamespaceReset}'s catalog reads, before a destructive\n * statement exists to have run.\n */\nfunction readNames(rows: readonly unknown[], inventory: string): string[] {\n const names: string[] = [];\n const seen = new Set<string>();\n for (const [index, row] of rows.entries()) {\n const name = readName(row, index, inventory);\n if (seen.has(name)) {\n throw new MigrationError(\n `The ${inventory} inventory for this reset named \"${name}\" twice, at position ${index}. ${UNTRUSTED_INVENTORY}`,\n VibORMErrorCode.MIGRATION_INVALID_STATE,\n {\n meta: { type: \"duplicate-reset-inventory-name\", resultIndex: index },\n }\n );\n }\n seen.add(name);\n names.push(name);\n }\n return names;\n}\n\n/** The one object an inventory row names, or the refusal it earns. */\nfunction readName(row: unknown, index: number, inventory: string): string {\n // The cause is already an `Error` here: the one caller that has a thrown value\n // normalizes it through {@link errorCause} first. Deciding it here instead\n // meant a bare `thrown instanceof Error`, which BOTH dropped every non-`Error`\n // a provider row threw and, against a Proxy whose `getPrototypeOf` trap\n // throws, replaced this typed refusal with the trap's own error.\n const refuse = (reason: string, cause?: Error): MigrationError =>\n new MigrationError(\n `The ${inventory} inventory for this reset returned a row at position ${index} that does not name one object: ${reason}. ${UNTRUSTED_INVENTORY}`,\n VibORMErrorCode.MIGRATION_INVALID_STATE,\n {\n cause,\n meta: { type: \"unreadable-reset-inventory\", resultIndex: index },\n }\n );\n\n // The executor's contract is `unknown[]`, so this is where a provider row\n // becomes an object at all. A driver's own result contract already refuses a\n // non-object row (`drivers/normalized-result.ts`), which is why no falsifier\n // reaches this line through a driver; what it decides is that the answer for\n // a row from anywhere else is a refusal rather than a shorter drop list.\n if (typeof row !== \"object\" || row === null) {\n throw refuse(`the row is ${row === null ? \"null\" : `a ${typeof row}`}`);\n }\n\n let name: unknown;\n try {\n // Reading a column off a provider's row runs the provider's code, and its\n // failure is still this inventory refusing to be read.\n //\n // OWN properties only, because this inventory names objects a CATALOG\n // reported and a catalog reports columns: a `name` reached through the\n // prototype chain is a carrier's property or `Object.prototype` pollution,\n // and honouring one puts an object on the DROP LIST that no catalog ever\n // named. Asking whether the row owns the column runs the provider's code\n // too — a proxy answers that with a trap — so the ownership test shares\n // this `try` and refuses identically. It is not a second read of the value:\n // it consults the descriptor, not the getter.\n name = Object.hasOwn(row, \"name\") ? Reflect.get(row, \"name\") : undefined;\n } catch (failure) {\n throw refuse(\"reading its `name` threw\", errorCause(failure));\n }\n\n if (typeof name !== \"string\") {\n throw refuse(\n `its \\`name\\` is ${name === undefined ? \"not a column of the row\" : `a ${typeof name}`}`\n );\n }\n // An empty name renders as a quoted nothing, so the statement it would\n // produce does not drop the object the provider meant to report.\n if (name.length === 0) {\n throw refuse(\"its `name` is the empty string\");\n }\n return name;\n}\n","/**\n * One SQL blob builder. Every check and effect dispatch in a state shares\n * one content-addressed blob. No second blob for rollback.\n */\n\nimport type { Sha256 } from \"./identity\";\nimport { composeSqlBlob, refuseMysqlDelimiter } from \"./sql-blob\";\nimport { encodeDispatchIdentity } from \"./v1-parse\";\nimport type { MigrationDispatchV1, MigrationParameterV1 } from \"./v1-types\";\n\ninterface PendingFragment {\n readonly text: string;\n readonly parameters: readonly MigrationParameterV1[];\n}\n\nexport class SqlAssembly {\n private readonly pending: PendingFragment[] = [];\n\n add(text: string, parameters: readonly MigrationParameterV1[] = []): number {\n refuseMysqlDelimiter(text);\n this.pending.push({ text, parameters });\n return this.pending.length - 1;\n }\n\n seal(): {\n readonly bytes: Uint8Array;\n readonly sqlHash: Sha256;\n readonly dispatches: readonly MigrationDispatchV1[];\n } {\n const blob = composeSqlBlob(this.pending.map((fragment) => fragment.text));\n const dispatches = this.pending.map((fragment, index) => {\n const range = blob.ranges[index]!;\n return {\n dispatchId: encodeDispatchIdentity(\n blob.sqlHash,\n range.offset,\n range.length,\n fragment.parameters\n ),\n sqlHash: blob.sqlHash,\n offset: range.offset,\n length: range.length,\n parameters: fragment.parameters,\n };\n });\n return { bytes: blob.bytes, sqlHash: blob.sqlHash, dispatches };\n }\n}\n","import { errorCause } from \"../errors/diagnostic-safety\";\nimport { isDestructiveOperation } from \"./differ\";\nimport { formatOperation } from \"./push/format\";\n/**\n * History-free push plan: live diff or force-reset rebuild, compiled\n * statements, and plan hash. This module does not execute SQL.\n */\n\nimport type { AnyDriver } from \"../drivers/driver\";\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\nimport type { ResolvedRelationIndex } from \"../schema/validation/relation-resolution\";\nimport { sql } from \"../sql/sql\";\nimport { isRecord } from \"../validation/value-guards\";\nimport { canonicalizeJson, canonicalizeJsonText } from \"./canonical-json\";\nimport { classifyGeneratedAtomicity, dispatchAt } from \"./compile\";\nimport { CONTROL_TABLES } from \"./control\";\nimport type {\n BoundMigrationDriver,\n DDLContext,\n MigrationDriver,\n} from \"./drivers\";\nimport { emptyManagedSnapshot } from \"./empty-snapshot\";\nimport { domainHash, HASH_DOMAIN, type Sha256 } from \"./identity\";\nimport {\n type LiveNamespaceResetPlan,\n planLiveNamespaceReset,\n} from \"./live-reset\";\nimport {\n type MigrationClient,\n type PushOptions as PlannerPushOptions,\n planPush,\n planRebuildFromEmpty,\n} from \"./push/planner\";\nimport type { ParsedPlanningOptions } from \"./push-consent\";\nimport {\n canonicalValue,\n fingerprintLive,\n freezeDeep,\n hashSnapshot,\n pushTargetIdentity,\n} from \"./push-fingerprint\";\nimport { serializeResolvedModels } from \"./serializer\";\nimport { SqlAssembly } from \"./sql-assembly\";\nimport { sliceDispatch } from \"./sql-blob\";\nimport {\n type DiffOperation,\n type ResolveCallback,\n type ResolveChange,\n type ResolveResult,\n readEnumResolutionDecision,\n type SchemaSnapshot,\n} from \"./types\";\nimport type {\n AtomicityClass,\n MigrationDispatchV1,\n PushConsent,\n PushOperation,\n PushResolution,\n PushStatementPreview,\n PushTargetIdentity,\n} from \"./v1-types\";\n\nexport interface PlannedStatement {\n readonly kind: \"clear\" | \"effect\";\n readonly operationId: string;\n readonly dispatch: MigrationDispatchV1;\n}\n\nexport interface InternalPushPlan {\n readonly mode: PushConsent[\"mode\"];\n readonly validation: PushConsent[\"validation\"];\n readonly target: PushTargetIdentity;\n readonly sourceFingerprint: Sha256;\n readonly desiredFingerprint: Sha256;\n readonly desiredSchema: SchemaSnapshot;\n readonly schemaHash: Sha256;\n readonly planHash: Sha256;\n readonly resolutions: readonly PushResolution[];\n readonly operations: readonly DiffOperation[];\n readonly reportedOperations: readonly PushOperation[];\n readonly statements: readonly PlannedStatement[];\n readonly previewStatements: readonly PushStatementPreview[];\n readonly sqlBlob: Uint8Array;\n readonly atomicity: AtomicityClass;\n readonly destructive: boolean;\n}\n\ntype ResolutionSource =\n | {\n readonly kind: \"record\";\n readonly callback: ResolveCallback | undefined;\n }\n | {\n readonly kind: \"replay\";\n readonly resolutions: readonly PushResolution[];\n };\n\ninterface ResolutionController {\n readonly callback: ResolveCallback;\n finish(): readonly PushResolution[];\n}\n\nexport async function buildPushPlan(\n client: MigrationClient,\n producer: AnyDriver,\n command: BoundMigrationDriver,\n relations: ResolvedRelationIndex,\n options: ParsedPlanningOptions,\n resolutionSource: ResolutionSource\n): Promise<InternalPushPlan> {\n const controller = resolutionController(resolutionSource);\n const plannerOptions: PlannerPushOptions = {\n skipValidation: options.skipValidation,\n resolve: controller.callback,\n };\n const planningDriver = managedPlanningDriver(command);\n const desired = serializeResolvedModels(\n client.$schema,\n planningDriver,\n relations\n );\n await command.preflightSchemaRequirements(\n [desired],\n (sql, params) => producer._executeRaw(sql, params),\n []\n );\n const mode: PushConsent[\"mode\"] = options.forceReset ? \"force-reset\" : \"diff\";\n\n let reset: LiveNamespaceResetPlan | undefined;\n let current: SchemaSnapshot;\n let operations: readonly DiffOperation[];\n if (options.forceReset) {\n current = await introspectManaged(producer, command);\n reset = await planLiveNamespaceReset(producer, command);\n const rebuild = await planRebuildFromEmpty(\n { $driver: producer, $schema: client.$schema },\n planningDriver,\n plannerOptions,\n relations\n );\n operations = rebuild.operations;\n } else {\n const planned = await planPush(\n { $driver: producer, $schema: client.$schema },\n planningDriver,\n plannerOptions,\n relations\n );\n current = planned.currentSchema;\n operations = planned.operations;\n }\n if (!options.forceReset)\n for (const operation of operations) {\n if (\n operation.type !== \"addColumn\" ||\n operation.column.nullable ||\n operation.column.default !== undefined ||\n operation.column.autoIncrement\n )\n continue;\n const tableName = liveTableName(operations, operation.tableName);\n if (!current.tables.some((table) => table.name === tableName)) continue;\n const reference = producer.adapter.identifiers.table(tableName);\n const populated = await producer._executeRaw(\n `SELECT 1 AS present FROM ${reference.toStatement()} LIMIT 1`\n );\n if (populated.rows.length > 0)\n throw new MigrationError(\n `Cannot add required column \"${operation.tableName}.${operation.column.name}\" without a database default to a populated table. Application function/generator defaults do not backfill stored rows. Author a manual data migration that adds a nullable column, fills it, and then makes it required. No migration effects were executed.`,\n VibORMErrorCode.MIGRATION_INVALID_STATE,\n {\n meta: {\n table: operation.tableName,\n column: operation.column.name,\n command: \"push\",\n hint: \"Use a reviewed manual migration for explicit backfill before making the column required.\",\n },\n }\n );\n }\n if (!options.forceReset)\n await refuseOrphanedDiscriminators(producer, desired, current, operations);\n const resolutions = controller.finish();\n const target = await pushTargetIdentity(producer, command);\n const sourceFingerprint = await fingerprintLive(current, command, producer);\n const desiredFingerprint = await fingerprintLive(desired, command, producer);\n const schemaHash = hashSnapshot(desired);\n const compiled = compilePlanStatements(\n reset,\n operations,\n planningDriver,\n options.forceReset ? emptyManagedSnapshot() : current\n );\n await command.preflightSchemaRequirements(\n [],\n (sql, params) => producer._executeRaw(sql, params),\n compiled.statements.map((statement) =>\n sliceDispatch(compiled.bytes, statement.dispatch)\n )\n );\n const reportedOperations: PushOperation[] = operations.map(\n (operation, index) => ({\n id: `${operation.type}:${index}`,\n label: formatOperation(operation),\n // A live table rename takes its old name from every other reader, and a\n // history-free push cannot prove that table was ever this schema's.\n risk:\n isDestructiveOperation(operation) || operation.type === \"renameTable\"\n ? \"destructive\"\n : \"safe\",\n })\n );\n const atomicity = classifyGeneratedAtomicity(command, operations);\n const destructive =\n mode === \"force-reset\" ||\n reportedOperations.some((operation) => operation.risk === \"destructive\");\n const validation: PushConsent[\"validation\"] = options.skipValidation\n ? \"structural-only\"\n : \"full\";\n const planHash = hashPushPlan({\n mode,\n validation,\n target,\n sourceFingerprint,\n desiredFingerprint,\n schemaHash,\n resolutions,\n operations,\n statements: compiled.statements,\n atomicity,\n });\n\n return freezeDeep({\n mode,\n validation,\n target,\n sourceFingerprint,\n desiredFingerprint,\n desiredSchema: desired,\n schemaHash,\n planHash,\n resolutions,\n operations,\n reportedOperations,\n statements: compiled.statements,\n previewStatements: compiled.statements.map((statement) => ({\n sql: sliceDispatch(compiled.bytes, statement.dispatch),\n parameters: statement.dispatch.parameters,\n })),\n sqlBlob: compiled.bytes,\n atomicity,\n destructive,\n });\n}\n\nexport function compilePlanStatements(\n reset: LiveNamespaceResetPlan | undefined,\n operations: readonly DiffOperation[],\n driver: MigrationDriver,\n currentSchema: SchemaSnapshot\n): {\n readonly bytes: Uint8Array;\n readonly statements: readonly PlannedStatement[];\n} {\n const assembly = new SqlAssembly();\n const pending: Array<{\n readonly kind: PlannedStatement[\"kind\"];\n readonly operationId: string;\n readonly index: number;\n }> = [];\n\n for (const [index, sql] of (reset?.clear ?? []).entries()) {\n pending.push({\n kind: \"clear\",\n operationId: `force-reset:clear:${index}`,\n index: assembly.add(sql),\n });\n }\n\n for (const [operationIndex, operation] of operations.entries()) {\n const context: DDLContext = {\n destination: \"live\",\n currentSchema,\n precedingOperations: operations.slice(0, operationIndex),\n followingOperations: operations.slice(operationIndex + 1),\n };\n const statements = driver.compileStatements(operation, context);\n for (const [statementIndex, sql] of statements.entries()) {\n pending.push({\n kind: \"effect\",\n operationId: `${operation.type}:${operationIndex}:${statementIndex}`,\n index: assembly.add(sql),\n });\n }\n }\n\n const sealed = assembly.seal();\n return {\n bytes: sealed.bytes,\n statements: pending.map((statement) => ({\n kind: statement.kind,\n operationId: statement.operationId,\n dispatch: dispatchAt(sealed.dispatches, statement.index),\n })),\n };\n}\n\nexport function hashPushPlan(input: {\n readonly mode: PushConsent[\"mode\"];\n readonly validation: PushConsent[\"validation\"];\n readonly target: PushTargetIdentity;\n readonly sourceFingerprint: Sha256;\n readonly desiredFingerprint: Sha256;\n readonly schemaHash: Sha256;\n readonly resolutions: readonly PushResolution[];\n readonly operations: readonly DiffOperation[];\n readonly statements: readonly PlannedStatement[];\n readonly atomicity: AtomicityClass;\n}): Sha256 {\n return domainHash(\n HASH_DOMAIN.plan,\n canonicalizeJson(\n canonicalValue({\n mode: input.mode,\n validation: input.validation,\n target: input.target,\n sourceFingerprint: input.sourceFingerprint,\n desiredFingerprint: input.desiredFingerprint,\n schemaHash: input.schemaHash,\n resolutions: input.resolutions,\n operations: input.operations,\n atomicity: input.atomicity,\n // Review SQL is intentionally absent. Dispatch identity authenticates\n // the sealed statement bytes, exact ranges, and typed parameters.\n statements: input.statements.map((statement) => ({\n kind: statement.kind,\n operationId: statement.operationId,\n dispatch: statement.dispatch,\n })),\n })\n )\n );\n}\n\nexport async function introspectManaged(\n producer: AnyDriver,\n driver: MigrationDriver\n): Promise<SchemaSnapshot> {\n return withoutControlTables(\n await driver.introspect((sql, params) => producer._executeRaw(sql, params))\n );\n}\n\nfunction managedPlanningDriver(\n driver: BoundMigrationDriver\n): BoundMigrationDriver {\n const managed: BoundMigrationDriver = Object.create(driver);\n Object.defineProperty(managed, \"introspect\", {\n value: async (\n executeRaw: <T>(sql: string, params?: unknown[]) => Promise<{ rows: T[] }>\n ) => withoutControlTables(await driver.introspect(executeRaw)),\n });\n Object.freeze(managed);\n return managed;\n}\n\nfunction withoutControlTables(snapshot: SchemaSnapshot): SchemaSnapshot {\n return {\n ...snapshot,\n tables: snapshot.tables.filter(\n (table) =>\n table.name !== CONTROL_TABLES.state && table.name !== CONTROL_TABLES.log\n ),\n };\n}\n\n/** The live name of a desired table: an accepted rename still reads the old one. */\nfunction liveTableName(\n operations: readonly DiffOperation[],\n tableName: string\n): string {\n const rename = operations.find(\n (candidate) =>\n candidate.type === \"renameTable\" && candidate.to === tableName\n );\n return rename?.type === \"renameTable\" ? rename.from : tableName;\n}\n\n/**\n * Push keeps no polymorphic history — `diff` refuses a stored-value change only\n * between authored snapshots — so the stored discriminators are that history:\n * a row whose discriminator the desired schema no longer declares would be\n * orphaned. Only a to-one slot stores its discriminator in rows; a collection\n * member's junction table is the member itself.\n */\nasync function refuseOrphanedDiscriminators(\n producer: AnyDriver,\n desired: SchemaSnapshot,\n current: SchemaSnapshot,\n operations: readonly DiffOperation[]\n): Promise<void> {\n const { identifiers, literals, operators } = producer.adapter;\n for (const slot of desired.polymorphicStorage ?? []) {\n if (slot.kind !== \"toOne\") continue;\n const tableName = liveTableName(operations, slot.ownerTable);\n const rename = operations.find(\n (candidate) =>\n candidate.type === \"renameColumn\" &&\n candidate.tableName === slot.ownerTable &&\n candidate.to === slot.storageRef\n );\n const columnName =\n rename?.type === \"renameColumn\" ? rename.from : slot.storageRef;\n const live = current.tables.find((table) => table.name === tableName);\n if (!live?.columns.some((column) => column.name === columnName)) continue;\n const column = identifiers.escape(columnName);\n const declared = literals.list(\n slot.members.map((member) => literals.value(member.storedType))\n );\n const probe = producer._prepare(\n sql`SELECT ${identifiers.aliased(column, \"stored\")} FROM ${identifiers.table(tableName)} WHERE ${operators.notIn(column, declared)} LIMIT 1`\n );\n const [orphan] = (\n await producer._executeRaw<{ stored: unknown }>(probe.sql, probe.params)\n ).rows;\n if (orphan)\n throw new MigrationError(\n `Polymorphic storage \"${slot.ownerTable}.${slot.relation}\" stores \"${String(orphan.stored)}\", which the desired schema no longer declares; those rows would lose their target. Author an explicit manual data transition that rewrites the stored values. No migration effects were executed.`,\n VibORMErrorCode.MIGRATION_DESTRUCTIVE_REJECTED,\n {\n meta: {\n table: slot.ownerTable,\n relation: slot.relation,\n command: \"push\",\n },\n }\n );\n }\n}\n\nfunction resolutionController(source: ResolutionSource): ResolutionController {\n if (source.kind === \"record\") {\n const recorded: PushResolution[] = [];\n return {\n callback: async (change) => {\n const result = source.callback\n ? await source.callback(change)\n : defaultResolution(change);\n const decision = closeResolution(change, result);\n if (decision) {\n recorded.push({ id: resolutionId(change), decision });\n }\n return result;\n },\n finish: () => freezeDeep([...recorded]),\n };\n }\n\n let cursor = 0;\n return {\n callback: (change) => {\n const expected = source.resolutions[cursor++];\n if (!expected || expected.id !== resolutionId(change)) {\n throw new MigrationError(\n \"The locked push requested a different set of resolutions\",\n VibORMErrorCode.MIGRATION_CONSENT_MISMATCH\n );\n }\n return replayResolution(change, expected.decision);\n },\n finish: () => {\n if (cursor !== source.resolutions.length) {\n throw new MigrationError(\n \"The locked push no longer requests every consented resolution\",\n VibORMErrorCode.MIGRATION_CONSENT_MISMATCH\n );\n }\n return source.resolutions;\n },\n };\n}\n\nfunction defaultResolution(change: ResolveChange): ResolveResult | undefined {\n // Destructive operations have one interpretation. Closing `proceed` lets a\n // preview describe it, while exact plan consent remains mandatory.\n if (change.type === \"destructive\") return change.proceed();\n return undefined;\n}\n\nfunction closeResolution(\n change: ResolveChange,\n result: ResolveResult | undefined | void\n): string | undefined {\n if (result === undefined) return undefined;\n if (result === \"reject\") return \"reject\";\n if (change.type === \"destructive\") {\n if (result !== \"proceed\") invalidResolution(change);\n return \"proceed\";\n }\n if (change.type === \"ambiguous\") {\n if (result !== \"rename\" && result !== \"addAndDrop\") {\n invalidResolution(change);\n }\n return result;\n }\n if (result !== \"enumMapped\") invalidResolution(change);\n const decision = readEnumResolutionDecision(change);\n if (decision?.kind === \"mapValues\") {\n return `map:${canonicalizeJsonText(canonicalValue(decision.mappings))}`;\n }\n if (decision?.kind === \"useNull\") {\n if (!change.isNullable) {\n throw new MigrationError(\n \"A non-nullable enum column cannot resolve removed values to NULL\",\n VibORMErrorCode.MIGRATION_DESTRUCTIVE_REJECTED\n );\n }\n return \"useNull\";\n }\n invalidResolution(change);\n}\n\nfunction invalidResolution(change: ResolveChange): never {\n throw new MigrationError(\n `The resolve callback returned an invalid resolution result for a ${change.type} change. ` +\n \"Return one of the methods on the exact change object that was supplied; a result for another change kind cannot authorize this migration.\",\n VibORMErrorCode.MIGRATION_INVALID_STATE,\n { meta: { type: \"invalid-resolution-result\" } }\n );\n}\n\nfunction replayResolution(\n change: ResolveChange,\n decision: string\n): ResolveResult {\n if (change.type === \"destructive\" && decision === \"proceed\") {\n return change.proceed();\n }\n if (change.type === \"ambiguous\") {\n if (decision === \"rename\") return change.rename();\n if (decision === \"addAndDrop\") return change.addAndDrop();\n }\n if (change.type === \"enumValueRemoval\") {\n if (decision === \"useNull\" && change.isNullable) return change.useNull();\n if (decision.startsWith(\"map:\")) {\n return change.mapValues(parseResolutionMap(decision.slice(4)));\n }\n }\n throw new MigrationError(\n \"Push consent contains a resolution that is invalid for the locked request\",\n VibORMErrorCode.MIGRATION_CONSENT_MISMATCH\n );\n}\n\nfunction resolutionId(change: ResolveChange): string {\n const identity =\n change.type === \"enumValueRemoval\"\n ? {\n type: change.type,\n enumName: change.enumName,\n tableName: change.tableName,\n columnName: change.columnName,\n isNullable: change.isNullable,\n removedValues: change.removedValues,\n availableValues: change.availableValues,\n }\n : {\n type: change.type,\n operation: change.operation,\n table: change.table,\n column: change.column ?? null,\n oldName:\n change.type === \"ambiguous\" ? (change.oldName ?? null) : null,\n newName:\n change.type === \"ambiguous\" ? (change.newName ?? null) : null,\n oldType:\n change.type === \"ambiguous\" ? (change.oldType ?? null) : null,\n newType:\n change.type === \"ambiguous\" ? (change.newType ?? null) : null,\n };\n return domainHash(HASH_DOMAIN.plan, canonicalizeJson(identity));\n}\n\nfunction parseResolutionMap(text: string): Record<string, string | null> {\n let parsed: unknown;\n try {\n parsed = JSON.parse(text);\n } catch (cause) {\n throw new MigrationError(\n \"Push consent contains a malformed enum resolution\",\n VibORMErrorCode.MIGRATION_CONSENT_MISMATCH,\n { cause: errorCause(cause) }\n );\n }\n if (!isRecord(parsed) || canonicalizeJsonText(parsed) !== text) {\n throw new MigrationError(\n \"Push consent contains a non-canonical enum resolution\",\n VibORMErrorCode.MIGRATION_CONSENT_MISMATCH\n );\n }\n const result: Record<string, string | null> = {};\n for (const [key, value] of Object.entries(parsed)) {\n if (typeof value !== \"string\" && value !== null) {\n throw new MigrationError(\n \"Push consent enum mappings must contain only strings or null\",\n VibORMErrorCode.MIGRATION_CONSENT_MISMATCH\n );\n }\n result[key] = value;\n }\n return result;\n}\n","/**\n * Whether the live database is what the durable record says (plan D5, S5):\n * the marker's standing in a history, drift against an authenticated\n * snapshot, and the lock not let go since a decision. One function per proof;\n * nothing here knows a command or a transport.\n */\n\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\nimport {\n type appendLedger,\n CONTROL_TABLES,\n readControlState,\n sameMarker,\n unfinishedAttempts,\n} from \"./control\";\nimport { diff } from \"./differ\";\nimport type { BoundMigrationDriver } from \"./drivers\";\nimport type { MigrationGraph } from \"./graph\";\nimport type { Sha256 } from \"./identity\";\nimport { lockedSinceDecision } from \"./pinned-session\";\nimport { fingerprintLive } from \"./push-fingerprint\";\nimport { introspectManaged } from \"./push-plan\";\nimport type { MarkerIndexPredicateV1, MigrationMarkerV1 } from \"./v1-types\";\n\n/**\n * Where the live marker stands relative to this history. A marker naming a\n * state the graph holds — or no state — is `known`, and `assertNoDrift` proves\n * the rest. Otherwise its arrival path tells version skew from a stranger: the\n * marker is `ahead` when that path passes through a state of this estate\n * before leaving it (newer code applied the rest), and `unknown` when nothing\n * on it belongs here.\n */\nexport function markerStanding(\n graph: MigrationGraph,\n marker: MigrationMarkerV1 | null\n): \"known\" | \"ahead\" | \"unknown\" {\n if (!marker?.stateId || graph.states.has(marker.stateId)) return \"known\";\n return marker.estateHash === graph.estateHash &&\n marker.path.some((edge) => graph.states.has(edge.stateId))\n ? \"ahead\"\n : \"unknown\";\n}\n\n/**\n * Refuses a group whose decision was taken under a lock the command has since\n * let go (plans D1, S5): an earlier group committed, or SQLite committed the\n * decision's transaction to switch foreign keys. Read as the group's first\n * statements, under its own lock: if another command moved the marker in\n * between, nothing of this group runs. Apply leaves an attempt of its own open\n * between two groups only inside an edge split at Neki's commit boundaries,\n * and passes it with the steps it has confirmed: the attempt must be the only\n * one open, as far as this command left it, or another command resumed it.\n * Any other unfinished one is another command's. `down` passes `ownAttempt`\n * only for the attempt it resumes, and `reset` once its own attempt is open:\n * while it is, no other command opens one.\n */\nexport async function assertLockedSinceDecision(\n pinned: Parameters<typeof appendLedger>[0],\n producer: Parameters<typeof appendLedger>[0],\n command: BoundMigrationDriver,\n expected: MigrationMarkerV1 | null,\n ownAttempt:\n | boolean\n | { readonly attemptId: Sha256; readonly steps: number } = false\n): Promise<void> {\n if (lockedSinceDecision(pinned)) return;\n const { marker, ledger } = await readControlState(producer, command, {\n ledger: \"open\",\n });\n const open = unfinishedAttempts(ledger);\n const own =\n typeof ownAttempt === \"boolean\"\n ? ownAttempt || open.length === 0\n : open.length === 1 &&\n open[0]!.attemptId === ownAttempt.attemptId &&\n ledger.filter(\n (event) =>\n event.attemptId === ownAttempt.attemptId &&\n event.kind === \"step-confirmed\" &&\n event.effectState === \"committed\"\n ).length === ownAttempt.steps;\n if (sameMarker(marker, expected) && own) {\n return;\n }\n throw new MigrationError(\n \"Another migration command moved the marker between two of this command's transactions. Nothing of the remaining path ran; running the command again re-reads the marker.\",\n VibORMErrorCode.MIGRATION_MARKER_CONFLICT\n );\n}\n\nexport async function assertNoDrift(\n producer: Parameters<typeof introspectManaged>[0],\n command: BoundMigrationDriver,\n graph: MigrationGraph,\n marker: MigrationMarkerV1\n): Promise<void> {\n await proveLive(producer, command, graph, markedSnapshotHash(graph, marker));\n}\n\n/** The authenticated snapshot a marker names, once its identity is proven. */\nexport function markedSnapshotHash(\n graph: MigrationGraph,\n marker: MigrationMarkerV1\n): Sha256 {\n if (marker.estateHash !== graph.estateHash) {\n throw new MigrationError(\n \"Live marker estate does not match storage\",\n VibORMErrorCode.MIGRATION_DRIFT,\n { meta: { estateHash: marker.estateHash } }\n );\n }\n if (marker.stateId) {\n const state = graph.states.get(marker.stateId);\n if (!state) {\n throw new MigrationError(\n \"Marker state is missing from the estate\",\n VibORMErrorCode.MIGRATION_CORRUPTION\n );\n }\n if (state.snapshotHash !== marker.snapshotHash) {\n throw new MigrationError(\n \"Marker snapshot does not match the authenticated state\",\n VibORMErrorCode.MIGRATION_DRIFT\n );\n }\n } else if (marker.snapshotHash !== graph.emptySnapshotHash) {\n throw new MigrationError(\n \"An empty-path marker must name the empty managed snapshot\",\n VibORMErrorCode.MIGRATION_DRIFT\n );\n }\n if ((marker.path.at(-1)?.stateId ?? null) !== marker.stateId) {\n throw new MigrationError(\n \"Marker path does not end at the marked state\",\n VibORMErrorCode.MIGRATION_CORRUPTION\n );\n }\n let from: Sha256 | null = null;\n for (const edge of marker.path) {\n const state = graph.states.get(edge.stateId);\n const parent = state?.parents.find(\n (item) =>\n item.transitionHash === edge.transitionHash && item.fromState === from\n );\n if (!(state && parent)) {\n throw new MigrationError(\n \"Marker path is not an authenticated arrival route\",\n VibORMErrorCode.MIGRATION_CORRUPTION\n );\n }\n from = edge.stateId;\n }\n // Proven above to be the marked state's, which the graph holds.\n return marker.snapshotHash;\n}\n\n/**\n * Proves the live managed schema is the snapshot: on PostgreSQL in one\n * statement (plan D5, the driver's `catalogDigest`), else, and where that digest\n * abstains, through an introspection, read once. On PostgreSQL it returns each\n * partial-index predicate that introspection read, the server's own deparse\n * (`pg_get_expr`), which a forward apply records beside the marker\n * (`casMarker`) for the no-op; the digest abstains on any partial index, so\n * a proof without introspection has none to record. `refusal` words the\n * drift; `differences` describes it on demand.\n */\nexport async function proveLive(\n producer: Parameters<typeof introspectManaged>[0],\n command: BoundMigrationDriver,\n graph: MigrationGraph,\n snapshotHash: Sha256,\n refusal: (\n differences: () => Promise<string>\n ) => Promise<string> | string = async (differences) =>\n `Live managed schema drifted from the authenticated snapshot. Differences: ${await differences()}`\n): Promise<readonly MarkerIndexPredicateV1[]> {\n // `loadMigrationGraph` loads every state's snapshot and seeds the empty one.\n const expected = graph.snapshots.get(snapshotHash)!;\n const fingerprint = await fingerprintLive(expected, command, producer);\n const digest = await command.catalogDigest?.(producer, CONTROL_TABLES);\n if (digest !== undefined && digest === fingerprint) return [];\n const live = await introspectManaged(producer, command);\n if ((await fingerprintLive(live, command, producer)) !== fingerprint) {\n throw new MigrationError(\n await refusal(async () => JSON.stringify(await diff(live, expected))),\n VibORMErrorCode.MIGRATION_DRIFT\n );\n }\n if (digest !== undefined) {\n throw new MigrationError(\n \"The PostgreSQL catalog digest disagrees with the introspected schema, which matches the authenticated snapshot. This is a VibORM defect in the digest (drivers/postgres/catalog-digest.ts), not drift: nothing ran. Please report it with the snapshot.\",\n VibORMErrorCode.INTERNAL_ERROR\n );\n }\n if (command.target.dialect !== \"postgresql\") return [];\n return live.tables.flatMap((table) =>\n table.indexes.flatMap((index) =>\n index.where\n ? [{ table: table.name, index: index.name, deparsed: index.where }]\n : []\n )\n );\n}\n\nexport async function assertEmptyManaged(\n producer: Parameters<typeof introspectManaged>[0],\n command: BoundMigrationDriver\n): Promise<void> {\n const live = await introspectManaged(producer, command);\n if (live.tables.length > 0 || (live.enums?.length ?? 0) > 0) {\n throw new MigrationError(\n \"Ordinary apply requires an empty managed target; use baseline to adopt an existing schema\",\n VibORMErrorCode.MIGRATION_INVALID_STATE\n );\n }\n}\n","/**\n * The steps the operator commands and reset share: the command prologue, the\n * control read with its presence policy, and resuming an unfinished attempt\n * from its confirmed prefix (plan S3). Each caller keeps its own event filter:\n * which ledger rows confirm a step is its own rule.\n */\n\nimport type { AnyDriver } from \"../drivers/driver\";\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\nimport {\n admitLiveMigrationCapability,\n type MigrationLiveRequirement,\n} from \"./admission\";\nimport {\n type MigrationControlRead,\n readControlState,\n refusePartialControl,\n} from \"./control\";\nimport type { BoundMigrationDriver } from \"./drivers\";\nimport type { MigrationGraph } from \"./graph\";\nimport type { Sha256 } from \"./identity\";\nimport { getPushMigrationDriver, type MigrationClient } from \"./push/planner\";\nimport { assertEstateTargetMatches } from \"./target\";\nimport type {\n LedgerEventV1,\n MigrationOperationV1,\n MigrationStepV1,\n} from \"./v1-types\";\n\n/** The client's migration driver, proven to address this estate's target. */\nexport function openCommand(\n client: MigrationClient,\n graph: MigrationGraph,\n requirement: MigrationLiveRequirement,\n label: string\n): BoundMigrationDriver {\n const driver = getPushMigrationDriver(client);\n assertEstateTargetMatches(graph.descriptor.target, driver.target);\n admitLiveMigrationCapability(driver, requirement, label);\n return driver;\n}\n\n/**\n * The marker and the open ledger, partial control refused; `bootstrap`\n * admits what bootstrapping completes (both tables absent, or the log lost\n * after an interrupted bootstrap).\n */\nexport async function readCommandControl(\n producer: AnyDriver,\n command: BoundMigrationDriver,\n bootstrap = false\n): Promise<MigrationControlRead> {\n const control = await readControlState(producer, command, { ledger: \"open\" });\n if (!bootstrap || control.presence.kind === \"missing-table\") {\n refusePartialControl(control.presence);\n }\n return control;\n}\n\n/** The length of the confirmed prefix; a confirmed step past a gap is refused. */\nexport function confirmedPrefix(\n confirmed: ReadonlySet<number>,\n refusal: string\n): number {\n let length = 0;\n while (confirmed.has(length)) length += 1;\n if ([...confirmed].some((index) => index >= length)) {\n throw new MigrationError(refusal, VibORMErrorCode.MIGRATION_CORRUPTION);\n }\n return length;\n}\n\n/**\n * Refuses to resume at an opaque stepwise dispatch announced and never\n * answered (confirmed, or its refusal recorded): it may have committed, and\n * running it again could repeat it.\n */\nexport function refuseAmbiguousNext(\n next: MigrationStepV1 | undefined,\n boundary: \"transactional\" | \"stepwise\" | undefined,\n announced: boolean,\n refusal: string\n): void {\n if (!(next?.retry === \"opaque\" && boundary === \"stepwise\" && announced)) {\n return;\n }\n throw new MigrationError(\n refusal,\n VibORMErrorCode.MIGRATION_AMBIGUOUS_COMMIT,\n {\n meta: {\n lastConfirmedStep: next.execute.dispatchId,\n effectState: \"may-have-committed\",\n partial: true,\n },\n }\n );\n}\n\n/** `operations` without their first `skip` steps. */\nexport function sliceOperations(\n operations: readonly MigrationOperationV1[],\n skip: number\n): MigrationOperationV1[] {\n let remaining = skip;\n return operations.flatMap((operation) => {\n if (remaining >= operation.steps.length) {\n remaining -= operation.steps.length;\n return [];\n }\n const steps = operation.steps.slice(remaining);\n remaining = 0;\n return [{ ...operation, steps }];\n });\n}\n\n/** The authenticated edge an attempt's `step-confirmed` events must name. */\nexport interface AttemptEdge {\n readonly direction: \"forward\" | \"rollback\";\n readonly estateHash: Sha256;\n readonly fromState: Sha256 | null;\n readonly toState: Sha256 | null;\n readonly transitionHash: Sha256;\n readonly sqlHash: Sha256;\n readonly operations: readonly MigrationOperationV1[];\n readonly boundary: \"transactional\" | \"stepwise\";\n}\n\n/**\n * What an unfinished attempt left to run of `edge`: its confirmed prefix of\n * steps, read from the attempt's own `step-confirmed` events, and the\n * operations past it. Progress naming another edge or an unknown dispatch, a\n * confirmed step past a gap, and an announced opaque stepwise step neither\n * confirmed nor answered by its recorded refusal (the server refused it\n * whole: it left nothing) are refused. `noun` names the direction in each\n * refusal.\n */\nexport function remainingSteps(\n ledger: readonly LedgerEventV1[],\n attempt: LedgerEventV1,\n edge: AttemptEdge,\n noun: \"Forward\" | \"Rollback\"\n): { readonly completed: number; readonly operations: MigrationOperationV1[] } {\n const steps = edge.operations.flatMap((operation) =>\n operation.steps.map((step) => ({ operation, step }))\n );\n const byDispatch = new Map(\n steps.map(({ step }, index) => [step.execute.dispatchId, index])\n );\n const committed = new Set<number>();\n // Announcements not answered by a recorded refusal, per step.\n const unanswered = new Map<number, number>();\n for (const event of ledger) {\n if (\n event.attemptId !== attempt.attemptId ||\n event.kind !== \"step-confirmed\"\n )\n continue;\n if (\n event.direction !== edge.direction ||\n event.estateHash !== edge.estateHash ||\n event.fromState !== edge.fromState ||\n event.toState !== edge.toState ||\n event.transitionHash !== edge.transitionHash ||\n event.sqlHash !== edge.sqlHash ||\n !event.dispatchId\n ) {\n throw new MigrationError(\n `${noun} progress does not match its authenticated edge`,\n VibORMErrorCode.MIGRATION_CORRUPTION\n );\n }\n const index = byDispatch.get(event.dispatchId);\n if (\n index === undefined ||\n steps[index]!.operation.id !== event.operationId\n ) {\n throw new MigrationError(\n `${noun} progress names an unknown dispatch`,\n VibORMErrorCode.MIGRATION_CORRUPTION\n );\n }\n if (event.effectState === \"committed\") committed.add(index);\n if (event.effectState === \"none\") {\n unanswered.set(\n index,\n (unanswered.get(index) ?? 0) + (event.failure ? -1 : 1)\n );\n }\n }\n const completed = confirmedPrefix(\n committed,\n `${noun} progress is not a contiguous dispatch prefix`\n );\n refuseAmbiguousNext(\n steps[completed]?.step,\n edge.boundary,\n (unanswered.get(completed) ?? 0) > 0,\n `The next ${noun.toLowerCase()} dispatch has an ambiguous commit outcome`\n );\n return { completed, operations: sliceOperations(edge.operations, completed) };\n}\n","/**\n * Apply V1: authenticate the graph, lock, refuse drift, execute exact slices,\n * then CAS the marker. Production never evaluates TypeScript.\n */\n\nimport { isVibORMError, MigrationError, VibORMErrorCode } from \"../errors\";\nimport {\n assertTransactionalBoundaryHonored,\n classifyStoredAtomicity,\n groupContiguousAtomicity,\n refuseSqliteStepwise,\n stepStatements,\n} from \"./compile\";\nimport {\n type AttemptEvents,\n advanceMarker,\n appendLedger,\n attemptEvents,\n CONTROL_TABLES,\n ensureControlTables,\n markerFromPath,\n markerUnmovedCondition,\n markerWrite,\n readControlState,\n readPostgresDecision,\n refuseIncompatibleHistory,\n sameMarker,\n unfinishedAttempts,\n} from \"./control\";\nimport type { BoundMigrationDriver } from \"./drivers\";\nimport { assertAllChecks, executeOperations } from \"./execute-dispatch\";\nimport {\n loadMigrationGraph,\n type MigrationGraph,\n type RouteEdge,\n requireStateSnapshot,\n resolveStateSelector,\n routeEdges,\n selectRoute,\n} from \"./graph\";\nimport type { Sha256 } from \"./identity\";\nimport {\n commitLockedTransaction,\n type MigrationBatch,\n migrationLockFree,\n openMigrationBatch,\n runProgram,\n runsMigrationBatches,\n withLockedMigrationProducer,\n} from \"./pinned-session\";\nimport {\n assertEmptyManaged,\n assertLockedSinceDecision,\n assertNoDrift,\n markedSnapshotHash,\n markerStanding,\n proveLive,\n} from \"./proof\";\nimport type { MigrationClient } from \"./push/planner\";\nimport { fingerprintDeparsed, fingerprintSnapshot } from \"./push-fingerprint\";\nimport type { introspectManaged } from \"./push-plan\";\nimport { openCommand, readCommandControl, remainingSteps } from \"./resume\";\nimport { sliceDispatch } from \"./sql-blob\";\nimport { canonicalizeSqliteStorage } from \"./sqlite-storage-audit\";\nimport { catalogCommitBoundaries, UNCHANGED_CATALOG } from \"./statement-safety\";\nimport type { MigrationStorageReader } from \"./storage/contract\";\nimport type { SchemaSnapshot } from \"./types\";\nimport type {\n ApplyV1Options,\n LedgerEventV1,\n MarkerPathEdgeV1,\n MigrationBooleanCheckV1,\n MigrationMarkerV1,\n MigrationOperationV1,\n} from \"./v1-types\";\n\nexport interface ApplyV1Result {\n readonly outcome: \"applied\" | \"noop\" | \"preview\";\n readonly path: readonly Sha256[];\n readonly statements: readonly string[];\n /**\n * Present only when the migration committed but releasing a session lock\n * failed after it (MySQL, PostgreSQL). The session was discarded, so the\n * lock does not outlive it.\n */\n readonly warnings?: readonly string[];\n}\n\nexport async function applyV1(\n client: MigrationClient,\n storage: MigrationStorageReader,\n options: ApplyV1Options = {}\n): Promise<ApplyV1Result> {\n const graph = await loadMigrationGraph(storage);\n const dryRun = options.dryRun === true;\n const driver = openCommand(\n client,\n graph,\n dryRun ? \"read-only\" : \"batch\",\n dryRun ? \"apply({ dryRun: true })\" : \"apply()\"\n );\n const target = resolveStateSelector(graph, options.to);\n\n if (dryRun) {\n const control = await readCommandControl(client.$driver, driver);\n const decision = decide(graph, control.marker, target, options);\n if (!decision || decision.origin === target) {\n return { outcome: \"noop\", path: [], statements: [] };\n }\n const { origin, path, statements } = decision;\n // An edge split at Neki's commit boundaries previews what is left of it.\n const unfinished = unfinishedAttempts(control.ledger);\n const resume = mayResume(unfinished, control.marker)\n ? resumableAttempt(\n driver,\n graph,\n decision,\n unfinished[0]!,\n control.ledger\n )\n : undefined;\n return {\n outcome: \"preview\",\n path,\n statements: resume\n ? routeSql(graph, origin, path, resume).statements\n : statements,\n };\n }\n\n // Set once the path committed: a failure after it is the lock's release.\n const committed: { result?: ApplyV1Result } = {};\n const locked = withLockedMigrationProducer<ApplyV1Result>(\n client.$driver,\n driver,\n async (pinned, command) => {\n const control = await readCommandControl(pinned, command, true);\n const { marker, ledger } = control;\n const needsBootstrap = control.presence.kind !== \"present\";\n refuseIncompatibleHistory(marker, ledger);\n const unfinished = unfinishedAttempts(ledger);\n if (unfinished.length > 0 && !mayResume(unfinished, marker)) {\n throw unfinishedAttemptBlocks();\n }\n const decision = decide(graph, marker, target, options);\n // A transport with no session runs no edge as committed parts.\n const resume =\n unfinished.length === 0 || runsMigrationBatches(pinned)\n ? undefined\n : resumableAttempt(command, graph, decision, unfinished[0]!, ledger);\n if (unfinished.length > 0 && !resume) throw unfinishedAttemptBlocks();\n if (!decision) return { outcome: \"noop\", path: [], statements: [] };\n const { origin, path } = decision;\n const route = routeSql(graph, origin, path, resume);\n const splits = await command.preflightSchemaRequirements(\n [\n requireStateSnapshot(graph, origin),\n ...path.map((stateId) => requireStateSnapshot(graph, stateId)),\n ],\n (sql, params) => pinned._executeRaw(sql, params),\n route.chunks,\n // One request per group holds no part's progress: refused instead.\n !runsMigrationBatches(pinned)\n );\n // A resumed edge's committed parts are already past the marker's\n // snapshot: the destination proof of its last part proves the rest.\n if (resume === undefined && marker) {\n await assertNoDrift(pinned, command, graph, marker);\n } else if (resume === undefined) {\n await assertEmptyManaged(pinned, command);\n }\n if (origin === target) {\n return { outcome: \"noop\", path: [], statements: [] };\n }\n // On MySQL the whole path is one sequential program.\n await runProgram(pinned, command, undefined, (producer) =>\n applyPathUnderLock(\n producer,\n command,\n graph,\n marker,\n origin,\n path,\n client.$schema,\n needsBootstrap,\n { splits, resume }\n )\n );\n committed.result = {\n outcome: \"applied\",\n path,\n statements: resume ? route.statements : decision.statements,\n };\n return committed.result;\n },\n driver.target.dialect === \"postgresql\"\n ? (session, lockFree) =>\n provenNoop(session, lockFree, driver, graph, target, options)\n : undefined\n );\n return keepCommittedOutcome(committed, locked);\n}\n\n/**\n * Plan D5 (decision 7): a PostgreSQL apply with nothing to do proves it\n * before the lock, in two statements: the control tables' definition, then\n * the marker, the open attempts and the catalog digest, read in one snapshot\n * while no other command holds the lock (`lockFree`). A database at the\n * target, with nothing open and no drift, was there at that instant, which is\n * all a no-op claims, and it writes nothing a lock would protect. Anything\n * else — another command at work included — or anything this read cannot\n * decide, goes to the locked path, which decides again under the lock.\n */\nasync function provenNoop(\n session: Parameters<typeof introspectManaged>[0],\n lockFree: string,\n driver: BoundMigrationDriver,\n graph: MigrationGraph,\n target: Sha256,\n options: ApplyV1Options\n): Promise<ApplyV1Result | undefined> {\n const decision = await readPostgresDecision(session, driver, lockFree);\n const marker = decision?.marker;\n if (!marker || unfinishedAttempts(decision.ledger).length > 0) return;\n // A refusal thrown here is decided again, and thrown, under the lock.\n if (followsAheadPolicy(graph, marker, options)) {\n return { outcome: \"noop\", path: [], statements: [] };\n }\n if (marker.stateId !== target || decision.digest === undefined) return;\n // `markedSnapshotHash` proved the snapshot is in the estate. Partial-index\n // predicates compare as the server deparsed them: the live ones in the\n // digest, the snapshot's from the record beside the marker.\n const expected = graph.snapshots.get(markedSnapshotHash(graph, marker))!;\n return decision.digest ===\n fingerprintDeparsed(expected, decision.predicates, driver)\n ? { outcome: \"noop\", path: [], statements: [] }\n : undefined;\n}\n\n/**\n * The outcome of a command whose work committed, even when ending its session\n * afterwards failed (releasing a session lock, or closing a locked read): the\n * marker already proves the commit (plan S3).\n */\nasync function keepCommittedOutcome(\n committed: { readonly result?: ApplyV1Result },\n command: Promise<ApplyV1Result>\n): Promise<ApplyV1Result> {\n try {\n return await command;\n } catch (failure) {\n if (committed.result === undefined) throw failure;\n return {\n ...committed.result,\n warnings: [\n `The migration committed, but ending its session failed (${describeFailure(failure)}).`,\n ],\n };\n }\n}\n\n/** True when `ifAhead: \"noop\"` applies; refuses every other marker this history does not hold. */\nfunction followsAheadPolicy(\n graph: MigrationGraph,\n marker: MigrationMarkerV1 | null,\n options: ApplyV1Options\n): boolean {\n const standing = markerStanding(graph, marker);\n if (standing === \"known\") return false;\n if (standing === \"ahead\" && options.ifAhead === \"noop\") return true;\n throw new MigrationError(\n standing === \"ahead\"\n ? `The database marker is ahead of this migration history: it names state ${marker?.stateId}, which newer code applied after a state this estate holds. Deploy that code, or pass apply({ ifAhead: \"noop\" }) to run against the newer schema without migrating.`\n : `The database marker names state ${marker?.stateId}, which is unknown to this migration estate: no state on its arrival path belongs to this history.`,\n VibORMErrorCode.MIGRATION_NOT_FOUND\n );\n}\n\n/**\n * What apply does from `marker`, shared by the dry run and the locked apply:\n * its ahead policy, origin, route and authenticated artifacts. `undefined`\n * when `ifAhead: \"noop\"` applies.\n */\nfunction decide(\n graph: MigrationGraph,\n marker: MigrationMarkerV1 | null,\n target: Sha256,\n options: ApplyV1Options\n):\n | { origin: Sha256 | null; path: readonly Sha256[]; statements: string[] }\n | undefined {\n if (followsAheadPolicy(graph, marker, options)) return;\n const origin = marker?.stateId ?? null;\n const path =\n origin === target ? [] : selectRoute(graph, origin, target, options.via);\n return { origin, path, statements: previewStatements(graph, origin, path) };\n}\n\nasync function applyPathUnderLock(\n pinned: import(\"../drivers/driver\").AnyDriver,\n command: BoundMigrationDriver,\n graph: MigrationGraph,\n marker: MigrationMarkerV1 | null,\n origin: Sha256 | null,\n path: readonly Sha256[],\n models: MigrationClient[\"$schema\"],\n needsBootstrap: boolean,\n { splits, resume }: { readonly splits: boolean; readonly resume?: Resume }\n): Promise<void> {\n const batched = runsMigrationBatches(pinned);\n const prepared = routeEdges(graph, origin, path).map((edge) => {\n const requested = edge.transition.requestedForwardBoundary;\n assertTransactionalBoundaryHonored(\n pinned.supportsTransactions || batched,\n requested\n );\n const boundary = classifyStoredAtomicity(\n command,\n requested,\n edge.transition.operations,\n edge.blob\n );\n refuseSqliteStepwise(command, requested, edge.to);\n if (batched && boundary === \"stepwise\") {\n refuseBatchedStepwise(pinned, edge.to);\n }\n return { ...edge, boundary };\n });\n\n let current = marker;\n const nextPath = marker ? [...marker.path] : [];\n // Before the program, as statements of their own: one request cannot read\n // what the bootstrap reads (plan D7), and a PostgreSQL bootstrap commits.\n if (needsBootstrap) {\n await ensureControlTables(pinned, command);\n await commitLockedTransaction(pinned, command);\n }\n const statementsOf = ({ transition, blob }: PreparedForwardEdge) =>\n stepStatements(blob, transition.operations);\n const groups = groupContiguousAtomicity(prepared, statementsOf);\n const first = groups[0]?.items[0];\n for (const group of splits || resume\n ? splitAtCatalogBoundaries(graph, groups, splits, resume)\n : groups) {\n if (\"split\" in group) {\n current = await applySplitEdge(\n pinned,\n command,\n graph,\n group.split,\n current,\n nextPath,\n models\n );\n continue;\n }\n if (batched) {\n current = await applyGroupBatch(\n pinned,\n command,\n graph,\n group.items,\n current,\n nextPath,\n models\n );\n continue;\n }\n const running: { attempt?: ForwardAttempt } = {};\n // A resumed stepwise edge: its attempt stays open, as apply left it.\n const resumed = group.items[0] === first ? resume : undefined;\n const run = async (\n producer: Parameters<typeof appendLedger>[0],\n atomic: boolean\n ) => {\n await assertLockedSinceDecision(\n pinned,\n producer,\n command,\n current,\n resumed && {\n attemptId: resumed.attempt.attemptId,\n steps: resumed.completed,\n }\n );\n if (atomic) {\n current = await executeAtomicGroup(\n producer,\n command,\n graph,\n group.items,\n running,\n current,\n nextPath,\n models\n );\n return;\n }\n // Edge by edge, each step probed and recorded as it runs.\n for (const [index, item] of group.items.entries()) {\n const own = index === 0 ? resumed : undefined;\n const attempt = forwardAttempt(graph, item, own?.attempt.attemptId);\n if (own === undefined) {\n await appendLedger(\n producer,\n command,\n attempt.event(\"started\", \"none\")\n );\n }\n await runForwardEdge(\n producer,\n command,\n graph,\n attempt,\n nextPath,\n models,\n true,\n undefined,\n own && {\n operations: own.operations,\n origin: false,\n destination: true,\n }\n );\n const { snapshotHash } = item.state;\n current = await advanceMarker(\n producer,\n command,\n graph.estateHash,\n current,\n [...nextPath],\n snapshotHash,\n 1,\n await proveLive(producer, command, graph, snapshotHash)\n );\n await appendLedger(\n producer,\n command,\n attempt.event(\"applied\", \"committed\")\n );\n }\n };\n const phase = { committing: false, committed: false };\n const program = {\n transactional: group.boundary === \"transactional\",\n statements: group.items.flatMap(statementsOf),\n phase,\n };\n try {\n // On MySQL the path already runs as one sequential program (`applyV1`).\n await (command.target.dialect === \"mysql\"\n ? run(pinned, false)\n : runProgram(pinned, command, program, run));\n } catch (failure) {\n // Past the commit only the foreign-key restore can fail: it is reported.\n if (phase.committed) throw failure;\n if (\n phase.committing &&\n (await commitLanded(pinned, command, group.items, current, failure))\n ) {\n continue;\n }\n await recordFailedAttempt(pinned, command, running, failure);\n throw failure;\n }\n }\n}\n\n/**\n * Plan D7, refused while the path is prepared, before any of it runs: a\n * transport with no session runs only transactional groups, each as one\n * request.\n */\nfunction refuseBatchedStepwise(\n pinned: import(\"../drivers/driver\").AnyDriver,\n toState: Sha256\n): never {\n throw new MigrationError(\n `The driver \"${pinned.driverName}\" sends each transactional group as one request and has no session for a stepwise transition (CONCURRENTLY, or a manual stepwise step). Nothing ran. Apply it over a session driver: viborm/pg, Neon's WebSocket Pool included.`,\n VibORMErrorCode.MIGRATION_UNSUPPORTED_PROVIDER,\n { meta: { dialect: \"postgresql\", toState, feature: \"stepwise execution\" } }\n );\n}\n\n/** One committed part of a forward edge: its steps, and which checks it runs. */\ninterface ForwardPart {\n readonly operations: readonly MigrationOperationV1[];\n readonly origin: boolean;\n readonly destination: boolean;\n}\n\n/**\n * One forward edge, from its origin checks to its destination checks, its\n * arrival pushed onto `nextPath`; the caller proves the destination, moves\n * the marker and records the arrival. A `probed` edge runs step by step and\n * records each confirmed step; otherwise it runs inside a real transaction,\n * or one request (`batch`), whose rollback is the proof of every step. A\n * `part` of an edge split at Neki's commit boundaries runs only its steps,\n * each recorded in the part's transaction, and the checks it holds.\n */\nasync function runForwardEdge(\n producer: Parameters<typeof appendLedger>[0],\n command: BoundMigrationDriver,\n graph: MigrationGraph,\n attempt: ForwardAttempt,\n nextPath: MarkerPathEdgeV1[],\n models: MigrationClient[\"$schema\"],\n probed: boolean,\n batch?: MigrationBatch,\n part?: ForwardPart\n): Promise<void> {\n const { from, to, transition, state, blob, boundary } = attempt.item;\n if (part?.origin ?? true) {\n await assertAllChecks(\n producer,\n blob,\n transition.originChecks,\n command.namespace,\n \"Origin checks failed before the first dispatch\",\n batch\n );\n }\n await executeOperations(\n producer,\n blob,\n part?.operations ?? transition.operations,\n probed ? boundary : \"atomic\",\n probed || part\n ? (progress, effect, failure) =>\n appendLedger(\n producer,\n command,\n attempt.event(\"step-confirmed\", effect, progress, failure)\n )\n : undefined,\n command.namespace,\n { fromState: from, toState: to }\n );\n if (!(part?.destination ?? true)) return;\n // Manual SQL may store text typed queries cannot compare (`datetime('now')`).\n await canonicalizeSqliteStorage(\n producer,\n transition.operations,\n models,\n requireStateSnapshot(graph, to)\n );\n await assertAllChecks(\n producer,\n blob,\n state.destinationChecks,\n command.namespace,\n \"Destination checks failed before the marker could advance\",\n batch\n );\n nextPath.push({\n stateId: to,\n transitionHash: transition.transitionHash,\n baselineBoundary: false,\n });\n}\n\n/**\n * One group inside a real transaction (plan D5). Its rollback is the proof\n * of every step, so the statements run unprobed and leave no progress rows\n * or `started` events; the group's last state is proven once, the marker\n * moves once (by one revision per edge, as edge by edge), and every edge's\n * `applied` event lands in one statement. Between the first DDL and the\n * COMMIT this sends the DDL, the authored checks and three control\n * statements.\n */\nasync function executeAtomicGroup(\n producer: Parameters<typeof appendLedger>[0],\n command: BoundMigrationDriver,\n graph: MigrationGraph,\n items: readonly PreparedForwardEdge[],\n running: { attempt?: ForwardAttempt },\n current: MigrationMarkerV1 | null,\n nextPath: MarkerPathEdgeV1[],\n models: MigrationClient[\"$schema\"],\n batch?: MigrationBatch\n): Promise<MigrationMarkerV1> {\n const arrivals: LedgerEventV1[] = [];\n for (const item of items) {\n running.attempt = forwardAttempt(graph, item);\n await runForwardEdge(\n producer,\n command,\n graph,\n running.attempt,\n nextPath,\n models,\n false,\n batch\n );\n arrivals.push(running.attempt.event(\"applied\", \"committed\"));\n }\n const last = items.at(-1)!;\n const { snapshotHash } = last.state;\n let next: MigrationMarkerV1;\n if (batch) {\n assertDigest(batch, command, requireStateSnapshot(graph, last.to));\n next = markerFromPath(\n graph.estateHash,\n snapshotHash,\n [...nextPath],\n (current?.revision ?? 0) + items.length\n );\n // The request asserted `current` under its lock first.\n const write = markerWrite(command, current, next);\n await producer._executeRaw(write.sql, write.params);\n } else {\n next = await advanceMarker(\n producer,\n command,\n graph.estateHash,\n current,\n [...nextPath],\n snapshotHash,\n items.length,\n await proveLive(producer, command, graph, snapshotHash)\n );\n }\n await appendLedger(producer, command, ...arrivals);\n return next;\n}\n\n/**\n * Plan D7: one transactional group as ONE request, on a transport with no\n * session. The request takes the transaction lock, asserts that the marker\n * is still the one this command decided on and that no attempt is open\n * ({@link assertLockedSinceDecision} in SQL), then runs the group as\n * {@link executeAtomicGroup} does, its checks and destination proof asserted\n * in SQL. A request the server refused rolled back; after a lost reply the\n * marker says whether it committed ({@link commitLanded}).\n */\nasync function applyGroupBatch(\n driver: Parameters<typeof appendLedger>[0],\n command: BoundMigrationDriver,\n graph: MigrationGraph,\n items: readonly PreparedForwardEdge[],\n current: MigrationMarkerV1 | null,\n nextPath: MarkerPathEdgeV1[],\n models: MigrationClient[\"$schema\"]\n): Promise<MigrationMarkerV1> {\n const batch = openMigrationBatch(driver, command);\n const unmoved = markerUnmovedCondition(command, current);\n batch.assert(\n unmoved.sql,\n unmoved.params,\n new MigrationError(\n \"Another migration command moved the marker, or opened an attempt, after this command read it. Nothing of this request was applied; running the command again re-reads the marker.\",\n VibORMErrorCode.MIGRATION_MARKER_CONFLICT\n )\n );\n const running: { attempt?: ForwardAttempt } = {};\n const next = await executeAtomicGroup(\n batch.producer,\n command,\n graph,\n items,\n running,\n current,\n nextPath,\n models,\n batch\n );\n try {\n await batch.send();\n } catch (failure) {\n if (\n !(failure instanceof MigrationError) &&\n (await commitLanded(driver, command, items, next, failure))\n ) {\n return next;\n }\n // Refused for the lock or a moved marker, the request ran none of the\n // group: a session refuses both before the attempt, recording nothing.\n const refusedBeforeGroup =\n failure instanceof MigrationError &&\n (failure.code === VibORMErrorCode.MIGRATION_LOCK_FAILED ||\n failure.code === VibORMErrorCode.MIGRATION_MARKER_CONFLICT);\n if (!refusedBeforeGroup) {\n await recordFailedAttempt(driver, command, running, failure);\n }\n throw failure;\n }\n return next;\n}\n\n/**\n * The destination proof inside one request (plan D7): the catalog digest\n * (`catalog-digest.ts`) is the snapshot's fingerprint. Where the digest\n * abstains, the request cannot prove the destination, and is refused.\n */\nfunction assertDigest(\n batch: MigrationBatch,\n command: BoundMigrationDriver,\n snapshot: SchemaSnapshot\n): void {\n // A batch runs only on PostgreSQL, whose driver owns the digest.\n const digest = command.catalogDigestQuery!(CONTROL_TABLES);\n batch.assert(\n `(${digest.sql}) IS NOT NULL`,\n digest.parameters,\n new MigrationError(\n \"This change cannot be proven inside one request: the catalog digest abstains on the destination schema (a partial index, or a default it cannot reproduce; see drivers/postgres/catalog-digest.ts). Nothing was applied. Apply it over a session driver: viborm/pg, Neon's WebSocket Pool included.\",\n VibORMErrorCode.MIGRATION_UNSUPPORTED_PROVIDER\n )\n );\n batch.assert(\n `(${digest.sql}) = $7`,\n [...digest.parameters, fingerprintSnapshot(snapshot, command)],\n new MigrationError(\n \"Live managed schema drifted from the authenticated snapshot\",\n VibORMErrorCode.MIGRATION_DRIFT\n )\n );\n}\n\n/**\n * Whether a transaction whose COMMIT was sent, and then failed, committed.\n * The marker it compare-and-swapped answers: it commits with the transition\n * or not at all. When even the marker cannot be read, the outcome is the\n * ambiguous commit V11020 it is (plan S3). Without a session (plan D7) it is\n * read only while no command holds the lock, so never while the request\n * whose reply was lost may still run.\n */\nasync function commitLanded(\n pinned: Parameters<typeof appendLedger>[0],\n command: BoundMigrationDriver,\n items: readonly PreparedForwardEdge[],\n expected: MigrationMarkerV1 | null,\n failure: unknown\n): Promise<boolean> {\n // On a lost connection the pinned view refuses this read (plan S2).\n const marker = await (runsMigrationBatches(pinned)\n ? readPostgresDecision(pinned, command, migrationLockFree(command)).then(\n (decision) => decision?.marker\n )\n : readControlState(pinned, command, {\n ledger: \"open\",\n }).then((control) => control.marker)\n ).catch(() => undefined);\n if (marker === undefined) {\n const fromState = items[0]?.from ?? null;\n throw new MigrationError(\n \"The migration's COMMIT was sent but its reply was lost, and the marker cannot be re-read, or another request still holds the migration lock: the transition may have committed. status() and apply() re-read the marker.\",\n VibORMErrorCode.MIGRATION_AMBIGUOUS_COMMIT,\n {\n cause: failure instanceof Error ? failure : undefined,\n meta: {\n ...(fromState === null ? {} : { fromState }),\n toState: items.at(-1)?.to,\n effectState: \"may-have-committed\",\n commitCertainty: \"may-have-committed\",\n },\n }\n );\n }\n return marker !== null && sameMarker(marker, expected);\n}\n\n/**\n * Leaves the durable record of a rolled-back attempt, whose own events the\n * rollback took with it: a `failed` event, in a transaction of its own, after\n * bootstrapping the control tables a failed first apply rolled back. The pinned\n * view sends nothing on a lost connection (plan S2), and a record that cannot be written\n * never replaces the failure it records.\n */\nasync function recordFailedAttempt(\n pinned: Parameters<typeof appendLedger>[0],\n command: BoundMigrationDriver,\n running: { readonly attempt?: ForwardAttempt },\n failure: unknown\n): Promise<void> {\n const { attempt } = running;\n if (attempt === undefined) return;\n const meta = isVibORMError(failure) ? failure.meta : {};\n const event = attempt.event(\n \"failed\",\n \"none\",\n {\n operationId:\n typeof meta.operationId === \"string\" ? meta.operationId : null,\n dispatchId: typeof meta.dispatchId === \"string\" ? meta.dispatchId : null,\n },\n describeFailure(failure)\n );\n try {\n if (runsMigrationBatches(pinned)) {\n // Its control tables were made before the request (plan D7).\n await appendLedger(pinned, command, event);\n return;\n }\n await pinned.withTransaction(async (transaction) => {\n await ensureControlTables(transaction, command);\n await appendLedger(transaction, command, event);\n });\n } catch {\n // Best effort: the caller is owed the failure itself, not this one.\n }\n}\n\nfunction describeFailure(failure: unknown): string {\n if (isVibORMError(failure)) return `${failure.code}: ${failure.message}`;\n return failure instanceof Error ? failure.name : \"a non-error value\";\n}\n\ninterface PreparedForwardEdge extends RouteEdge {\n readonly boundary: \"transactional\" | \"stepwise\";\n}\n\n/** One edge's attempt: the edge, and the builder of its ledger events. */\ninterface ForwardAttempt extends AttemptEvents {\n readonly item: PreparedForwardEdge;\n}\n\nfunction forwardAttempt(\n graph: MigrationGraph,\n item: PreparedForwardEdge,\n attemptId?: Sha256\n): ForwardAttempt {\n return {\n item,\n ...attemptEvents(\n {\n estateHash: graph.estateHash,\n snapshotHash: item.state.snapshotHash,\n sqlHash: item.state.sqlHash,\n fromState: item.from,\n toState: item.to,\n transitionHash: item.transition.transitionHash,\n direction: \"forward\",\n },\n attemptId\n ),\n };\n}\n\nfunction previewStatements(\n graph: MigrationGraph,\n origin: Sha256 | null,\n path: readonly Sha256[]\n): string[] {\n return routeEdges(graph, origin, path).flatMap(({ blob, transition }) =>\n stepStatements(blob, transition.operations)\n );\n}\n\nfunction unfinishedAttemptBlocks(): MigrationError {\n return new MigrationError(\n \"An unfinished migration attempt is blocking ordinary work\",\n VibORMErrorCode.MIGRATION_UNFINISHED_ATTEMPT\n );\n}\n\n/**\n * Whether the open attempts may be one apply resumes: one forward attempt,\n * opened from the marker. Read before the route, so any other open attempt\n * blocks as it always has.\n */\nfunction mayResume(\n unfinished: readonly LedgerEventV1[],\n marker: MigrationMarkerV1 | null\n): boolean {\n const [attempt] = unfinished;\n return (\n unfinished.length === 1 &&\n attempt?.kind === \"started\" &&\n attempt.direction === \"forward\" &&\n attempt.fromState === (marker?.stateId ?? null)\n );\n}\n\n/**\n * An unfinished edge apply resumes: one split at Neki's commit boundaries\n * whose first parts committed, or a stepwise one stopped at a step the server\n * refused whole.\n */\ninterface Resume {\n readonly attempt: LedgerEventV1;\n /** The steps its committed parts confirmed. */\n readonly completed: number;\n /** The operations past them. */\n readonly operations: readonly MigrationOperationV1[];\n}\n\n/**\n * What apply resumes of `attempt`, which {@link mayResume} admitted, or\n * `undefined`, on the first edge of the route apply selected, on PostgreSQL:\n * - a transactional edge split at Neki's commit boundaries: each committed\n * part recorded its steps in its own transaction, so their prefix is exact;\n * - a stepwise edge whose next step the server refused whole, recorded as\n * such (`execute-dispatch.ts`): that step left nothing, and the steps\n * before it each recorded their commit. Any other stepwise stop — a lost\n * connection, an outcome the server could not prove, a failed check —\n * still blocks.\n * Either way the origin checks ran before the first step, against the\n * origin; the resumed steps run without them, against the confirmed prefix,\n * and the destination checks and proof close the edge.\n */\nfunction resumableAttempt(\n command: BoundMigrationDriver,\n graph: MigrationGraph,\n decision: ReturnType<typeof decide>,\n attempt: LedgerEventV1,\n ledger: readonly LedgerEventV1[]\n): Resume | undefined {\n if (!decision?.path.length || command.target.dialect !== \"postgresql\") {\n return;\n }\n const [edge] = routeEdges(graph, decision.origin, decision.path);\n const { from, to, transition, state, blob } = edge!;\n const boundary = classifyStoredAtomicity(\n command,\n transition.requestedForwardBoundary,\n transition.operations,\n blob\n );\n const refused = new Set(\n ledger.flatMap((event) =>\n event.attemptId === attempt.attemptId &&\n event.kind === \"step-confirmed\" &&\n event.failure\n ? [event.dispatchId]\n : []\n )\n );\n // Its progress events are matched to this edge by `remainingSteps`; a\n // stepwise attempt that recorded no refusal blocks before they are read.\n if (\n attempt.toState !== to ||\n attempt.transitionHash !== transition.transitionHash ||\n (boundary === \"stepwise\" && refused.size === 0)\n ) {\n return;\n }\n const remaining = remainingSteps(\n ledger,\n attempt,\n {\n direction: \"forward\",\n estateHash: graph.estateHash,\n fromState: from,\n toState: to,\n transitionHash: transition.transitionHash,\n sqlHash: state.sqlHash,\n operations: transition.operations,\n boundary,\n },\n \"Forward\"\n );\n const next = remaining.operations[0]?.steps[0]?.execute.dispatchId;\n if (boundary === \"stepwise\" && !(next && refused.has(next))) return;\n return { attempt, ...remaining };\n}\n\n/**\n * The SQL one transaction runs for an edge, in its order: the origin checks\n * (unless `origin` is false: a resumed edge ran them), `operations`' steps\n * and the destination checks. `before` counts the origin checks.\n */\nfunction edgeSql(\n { transition, state, blob }: RouteEdge,\n operations: readonly MigrationOperationV1[],\n origin: boolean\n): {\n readonly chunks: string[];\n readonly steps: string[];\n readonly before: number;\n} {\n const checks = (list: readonly MigrationBooleanCheckV1[]) =>\n list.map((check) => sliceDispatch(blob, check.query));\n const before = origin ? checks(transition.originChecks) : [];\n const steps = stepStatements(blob, operations);\n return {\n chunks: [...before, ...steps, ...checks(state.destinationChecks)],\n steps,\n before: before.length,\n };\n}\n\n/**\n * What apply runs along `path`, a resumed first edge from its remaining\n * steps: every edge's checks and steps (`chunks`, which PlanetScale's Neki\n * reads for commit boundaries) and the steps alone (`statements`).\n */\nfunction routeSql(\n graph: MigrationGraph,\n origin: Sha256 | null,\n path: readonly Sha256[],\n resume: Resume | undefined\n): { readonly chunks: string[]; readonly statements: string[] } {\n const chunks: string[] = [];\n const statements: string[] = [];\n for (const [index, edge] of routeEdges(graph, origin, path).entries()) {\n const resumed = index === 0 ? resume : undefined;\n const sql = edgeSql(\n edge,\n resumed?.operations ?? edge.transition.operations,\n resumed === undefined\n );\n chunks.push(...sql.chunks);\n statements.push(...sql.steps);\n }\n return { chunks, statements };\n}\n\n/** One edge apply runs as committed parts, alone in its group. */\ninterface SplitEdge {\n readonly attempt: ForwardAttempt;\n /** Whether its attempt is open already: its first parts committed earlier. */\n readonly resumed: boolean;\n /** The steps confirmed before this command. */\n readonly completed: number;\n /**\n * Each part's operations, in order. The origin checks run with the first,\n * the destination checks and the marker with the last, which holds no step\n * when the checks themselves need a commit.\n */\n readonly parts: readonly (readonly MigrationOperationV1[])[];\n}\n\ntype PlannedGroup =\n | ReturnType<typeof groupContiguousAtomicity<PreparedForwardEdge>>[number]\n | { readonly split: SplitEdge };\n\n/** The steps `from` (inclusive) to `to` (exclusive) of `operations`. */\nfunction stepRange(\n operations: readonly MigrationOperationV1[],\n from: number,\n to: number\n): MigrationOperationV1[] {\n let index = 0;\n return operations.flatMap((operation) => {\n const first = index;\n index += operation.steps.length;\n const steps = operation.steps.filter(\n (_, position) => first + position >= from && first + position < to\n );\n return steps.length === 0 ? [] : [{ ...operation, steps }];\n });\n}\n\n/**\n * Plan D5's groups, on PlanetScale's Neki (`splits`), cut where its planner\n * needs a commit (`catalogCommitBoundaries`): an edge joins the group before\n * it while none of its statements needs one; one that needs one only because\n * of that group starts a group of its own; one that needs one because of its\n * own changes runs alone, as committed parts. A resumed first edge runs alone\n * from its remaining steps, on any PostgreSQL. A stepwise group commits each\n * statement already.\n */\nfunction splitAtCatalogBoundaries(\n graph: MigrationGraph,\n groups: ReturnType<typeof groupContiguousAtomicity<PreparedForwardEdge>>,\n splits: boolean,\n resume: Resume | undefined\n): PlannedGroup[] {\n const planned: PlannedGroup[] = [];\n const first = groups[0]?.items[0];\n for (const group of groups) {\n if (group.boundary !== \"transactional\") {\n planned.push(group);\n continue;\n }\n let items: PreparedForwardEdge[] = [];\n let changes = UNCHANGED_CATALOG;\n const flush = () => {\n if (items.length > 0) planned.push({ boundary: group.boundary, items });\n items = [];\n changes = UNCHANGED_CATALOG;\n };\n const read = (chunks: readonly string[], since = UNCHANGED_CATALOG) =>\n splits\n ? catalogCommitBoundaries(chunks, since)\n : { boundaries: [], changes: UNCHANGED_CATALOG };\n for (const item of group.items) {\n const resumed = item === first ? resume : undefined;\n const operations = resumed?.operations ?? item.transition.operations;\n const sql = edgeSql(item, operations, resumed === undefined);\n const joined = read(sql.chunks, changes);\n if (resumed === undefined && joined.boundaries.length === 0) {\n items.push(item);\n changes = joined.changes;\n continue;\n }\n flush();\n const alone = read(sql.chunks);\n if (resumed === undefined && alone.boundaries.length === 0) {\n items = [item];\n changes = alone.changes;\n continue;\n }\n // A commit before an origin check or the first step divides nothing.\n const cuts = [\n ...new Set(\n alone.boundaries\n .map((position) =>\n Math.min(position - sql.before, sql.steps.length)\n )\n .filter((cut) => cut > 0)\n ),\n ];\n const ends = [0, ...cuts, sql.steps.length];\n planned.push({\n split: {\n attempt: forwardAttempt(graph, item, resumed?.attempt.attemptId),\n resumed: resumed !== undefined,\n completed: resumed?.completed ?? 0,\n parts: ends\n .slice(1)\n .map((end, index) => stepRange(operations, ends[index]!, end)),\n },\n });\n }\n flush();\n }\n return planned;\n}\n\n/**\n * One edge as successive committed parts (PlanetScale's Neki), each in its\n * own locked transaction: the first runs the origin checks and opens the\n * attempt (`started`), each records its steps (`step-confirmed`) in the\n * transaction they ran in, and the last runs the destination checks, proves\n * the destination, moves the marker and closes the attempt (`applied`).\n *\n * Between two parts the lock is let go, so each part first proves the marker\n * unmoved and the attempt as far as this command left it. A first part that\n * fails leaves nothing, recorded as one `failed` event, as an atomic group\n * does. A later failure leaves the attempt open at its last committed part,\n * the marker on the edge's origin: `status()` reports it unfinished, and the\n * next `apply()` resumes the remaining parts ({@link resumableAttempt}).\n */\nasync function applySplitEdge(\n pinned: import(\"../drivers/driver\").AnyDriver,\n command: BoundMigrationDriver,\n graph: MigrationGraph,\n { attempt, resumed, completed, parts }: SplitEdge,\n current: MigrationMarkerV1 | null,\n nextPath: MarkerPathEdgeV1[],\n models: MigrationClient[\"$schema\"]\n): Promise<MigrationMarkerV1 | null> {\n const { item } = attempt;\n let confirmed = completed;\n let next = current;\n for (const [index, operations] of parts.entries()) {\n const opens = index === 0 && !resumed;\n const closes = index === parts.length - 1;\n const phase = { committing: false, committed: false };\n // Set once the part holds the lock as this command left it: a failure\n // before that is another command's doing, and records nothing.\n let admitted = false;\n try {\n await runProgram(\n pinned,\n command,\n {\n transactional: true,\n statements: stepStatements(item.blob, operations),\n phase,\n },\n async (producer) => {\n await assertLockedSinceDecision(\n pinned,\n producer,\n command,\n current,\n opens ? false : { attemptId: attempt.attemptId, steps: confirmed }\n );\n admitted = true;\n if (opens) {\n await assertAllChecks(\n producer,\n item.blob,\n item.transition.originChecks,\n command.namespace,\n \"Origin checks failed before the first dispatch\"\n );\n await appendLedger(\n producer,\n command,\n attempt.event(\"started\", \"none\")\n );\n }\n await runForwardEdge(\n producer,\n command,\n graph,\n attempt,\n nextPath,\n models,\n false,\n undefined,\n { operations, origin: false, destination: closes }\n );\n if (!closes) return;\n const { snapshotHash } = item.state;\n next = await advanceMarker(\n producer,\n command,\n graph.estateHash,\n current,\n [...nextPath],\n snapshotHash,\n 1,\n await proveLive(producer, command, graph, snapshotHash)\n );\n await appendLedger(\n producer,\n command,\n attempt.event(\"applied\", \"committed\")\n );\n }\n );\n } catch (failure) {\n if (phase.committed) throw failure;\n if (\n closes &&\n phase.committing &&\n (await commitLanded(pinned, command, [item], next, failure))\n ) {\n return next;\n }\n // Only a first part that rolled back left nothing open to resume: one\n // whose COMMIT failed did when its attempt is open, or unreadable.\n if (\n opens &&\n admitted &&\n !(\n phase.committing &&\n (await attemptOpened(pinned, command, attempt.attemptId))\n )\n ) {\n await recordFailedAttempt(pinned, command, { attempt }, failure);\n }\n throw failure;\n }\n confirmed += operations.reduce(\n (count, operation) => count + operation.steps.length,\n 0\n );\n }\n return next;\n}\n\n/**\n * Whether the attempt `attemptId` is open, read after its first part's\n * COMMIT failed: `true` too when the ledger cannot be read, so a `failed`\n * event never closes an attempt whose part may have committed.\n */\nfunction attemptOpened(\n pinned: Parameters<typeof appendLedger>[0],\n command: BoundMigrationDriver,\n attemptId: Sha256\n): Promise<boolean> {\n return readControlState(pinned, command, { ledger: \"open\" }).then(\n ({ ledger }) =>\n unfinishedAttempts(ledger).some((event) => event.attemptId === attemptId),\n () => true\n );\n}\n","/**\n * Offline estate check. CI-safe. Never creates control tables.\n */\n\nimport { loadMigrationGraph } from \"./graph\";\nimport type { Sha256 } from \"./identity\";\nimport type { MigrationStorageReader } from \"./storage/contract\";\nimport {\n encodeSqlBlob,\n parseSnapshotDocument,\n parseStateManifest,\n} from \"./v1-parse\";\n\nexport interface CheckFinding {\n readonly code: string;\n readonly message: string;\n}\n\nexport interface CheckResult {\n readonly ok: boolean;\n readonly findings: readonly CheckFinding[];\n}\n\nexport async function checkEstate(\n storage: MigrationStorageReader\n): Promise<CheckResult> {\n const findings: CheckFinding[] = [];\n try {\n const graph = await loadMigrationGraph(storage);\n if (graph.leaves.length > 1) {\n findings.push({\n code: \"unresolved-branch\",\n message: `Estate has ${graph.leaves.length} leaves; apply requires an explicit target or via`,\n });\n }\n const referencedSnapshots = new Set<Sha256>([graph.emptySnapshotHash]);\n const referencedSql = new Set<Sha256>();\n for (const state of graph.states.values()) {\n referencedSnapshots.add(state.snapshotHash);\n referencedSql.add(state.sqlHash);\n }\n for (const hash of await storage.listSnapshots()) {\n if (!referencedSnapshots.has(hash)) {\n findings.push({\n code: \"orphan-snapshot\",\n message: `Snapshot ${hash} is not referenced by any state`,\n });\n }\n const bytes = await storage.readSnapshot(hash);\n if (bytes) parseSnapshotDocument(bytes, hash);\n }\n for (const hash of await storage.listSql()) {\n if (!referencedSql.has(hash)) {\n findings.push({\n code: \"orphan-sql\",\n message: `SQL blob ${hash} is not referenced by any state`,\n });\n }\n const bytes = await storage.readSql(hash);\n if (bytes && encodeSqlBlob(bytes) !== hash) {\n findings.push({\n code: \"corrupt-sql\",\n message: `SQL blob ${hash} does not match its bytes`,\n });\n }\n }\n for (const id of await storage.listStates()) {\n const bytes = await storage.readState(id);\n if (bytes) parseStateManifest(bytes, id);\n }\n } catch (error) {\n findings.push({\n code: \"invalid-estate\",\n message: error instanceof Error ? error.message : String(error),\n });\n }\n return {\n ok: findings.every((finding) => finding.code.startsWith(\"orphan-\")),\n findings,\n };\n}\n","/**\n * One hostile-input boundary for generation options and manual definitions.\n * It settles every caller-owned accessor before estate or provider access.\n */\n\nimport { Sql } from \"@sql\";\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\nimport { errorCause } from \"../errors/diagnostic-safety\";\nimport { snapshotExactArray, snapshotExactRecord } from \"./input-boundary\";\nimport type { ResolveCallback } from \"./types\";\nimport type {\n GenerateV1Options,\n ManualMigrationInput,\n ManualTransitionInput,\n MigrationCheckInput,\n} from \"./v1-types\";\n\nexport function normalizeGenerateOptions(options: unknown): GenerateV1Options {\n const record = snapshotExactRecord(\n options,\n [\n \"name\",\n \"from\",\n \"dryRun\",\n \"resolve\",\n \"skipValidation\",\n \"manualMigration\",\n \"lowLock\",\n ],\n \"generate options\",\n refuseGenerateOptions\n );\n const {\n name,\n from,\n dryRun,\n resolve,\n skipValidation,\n manualMigration,\n lowLock,\n } = record;\n if (name !== undefined && typeof name !== \"string\") {\n return refuseGenerateOptions(\"generate name must be a string\");\n }\n if (from !== undefined && from !== null && typeof from !== \"string\") {\n return refuseGenerateOptions(\"generate from must be a state id or null\");\n }\n if (dryRun !== undefined && typeof dryRun !== \"boolean\") {\n return refuseGenerateOptions(\"generate dryRun must be a boolean\");\n }\n if (skipValidation !== undefined && typeof skipValidation !== \"boolean\") {\n return refuseGenerateOptions(\"generate skipValidation must be a boolean\");\n }\n if (lowLock !== undefined && typeof lowLock !== \"boolean\") {\n return refuseGenerateOptions(\"generate lowLock must be a boolean\");\n }\n if (resolve !== undefined && !isResolveCallback(resolve)) {\n return refuseGenerateOptions(\"generate resolve must be a function\");\n }\n return Object.freeze({\n ...(name === undefined ? {} : { name }),\n ...(from === undefined ? {} : { from }),\n ...(dryRun === undefined ? {} : { dryRun }),\n ...(resolve === undefined ? {} : { resolve }),\n ...(skipValidation === undefined ? {} : { skipValidation }),\n ...(lowLock === undefined ? {} : { lowLock }),\n ...(manualMigration === undefined\n ? {}\n : { manualMigration: snapshotManualMigration(manualMigration) }),\n });\n}\n\nfunction snapshotManualMigration(value: unknown): ManualMigrationInput {\n const record = snapshotExactRecord(\n value,\n [\"transitions\", \"destinationChecks\"],\n \"manual migration\",\n refuseManualDefinition\n );\n const transitions = snapshotExactArray(\n record.transitions,\n \"manual migration transitions\",\n refuseManualDefinition\n ).map((transition, index) =>\n snapshotManualTransition(transition, `manual transition ${index}`)\n );\n if (transitions.length === 0) {\n return refuseManualDefinition(\n \"A manual migration must define at least one parent transition\"\n );\n }\n const destinationChecks =\n record.destinationChecks === undefined\n ? undefined\n : snapshotExactArray(\n record.destinationChecks,\n \"manual destination checks\",\n refuseManualDefinition\n ).map((check, index) =>\n snapshotManualCheck(check, `manual destination check ${index}`)\n );\n return Object.freeze({\n transitions: Object.freeze(transitions),\n ...(destinationChecks === undefined\n ? {}\n : { destinationChecks: Object.freeze(destinationChecks) }),\n });\n}\n\nfunction snapshotManualTransition(\n value: unknown,\n label: string\n): ManualTransitionInput {\n const record = snapshotExactRecord(\n value,\n [\"from\", \"execution\", \"up\", \"originChecks\", \"rollback\"],\n label,\n refuseManualDefinition\n );\n const { from, execution } = record;\n if (from !== null && typeof from !== \"string\") {\n return refuseManualDefinition(`${label}.from must be a state id or null`);\n }\n if (execution !== \"transactional\" && execution !== \"stepwise\") {\n return refuseManualDefinition(\n `${label}.execution must be transactional or stepwise`\n );\n }\n const up = snapshotSqlArray(record.up, `${label}.up`);\n const originChecks =\n record.originChecks === undefined\n ? undefined\n : snapshotExactArray(\n record.originChecks,\n `${label}.originChecks`,\n refuseManualDefinition\n ).map((check, index) =>\n snapshotManualCheck(check, `${label}.originChecks[${index}]`)\n );\n return Object.freeze({\n from,\n execution,\n up,\n ...(originChecks === undefined\n ? {}\n : { originChecks: Object.freeze(originChecks) }),\n rollback: snapshotManualRollback(record.rollback, `${label}.rollback`),\n });\n}\n\nfunction snapshotManualRollback(\n value: unknown,\n label: string\n): ManualTransitionInput[\"rollback\"] {\n const discriminant = snapshotExactRecord(\n value,\n [\"kind\", \"execution\", \"sql\", \"reason\"],\n label,\n refuseManualDefinition\n );\n if (discriminant.kind === \"irreversible\") {\n if (\n discriminant.execution !== undefined ||\n discriminant.sql !== undefined ||\n typeof discriminant.reason !== \"string\"\n ) {\n return refuseManualDefinition(\n `${label} has an invalid irreversible shape`\n );\n }\n return Object.freeze({\n kind: \"irreversible\",\n reason: discriminant.reason,\n });\n }\n if (discriminant.kind !== \"manual\") {\n return refuseManualDefinition(`${label}.kind is invalid`);\n }\n if (\n discriminant.reason !== undefined ||\n (discriminant.execution !== \"transactional\" &&\n discriminant.execution !== \"stepwise\")\n ) {\n return refuseManualDefinition(`${label} has an invalid manual shape`);\n }\n return Object.freeze({\n kind: \"manual\",\n execution: discriminant.execution,\n sql: snapshotSqlArray(discriminant.sql, `${label}.sql`),\n });\n}\n\nfunction snapshotManualCheck(\n value: unknown,\n label: string\n): MigrationCheckInput {\n const record = snapshotExactRecord(\n value,\n [\"kind\", \"query\", \"equals\"],\n label,\n refuseManualDefinition\n );\n if (record.kind !== \"trusted-read\" || typeof record.equals !== \"boolean\") {\n return refuseManualDefinition(`${label} has an invalid check shape`);\n }\n return Object.freeze({\n kind: \"trusted-read\",\n query: snapshotSql(record.query, `${label}.query`),\n equals: record.equals,\n });\n}\n\nfunction snapshotSqlArray(value: unknown, label: string): readonly Sql[] {\n const entries = snapshotExactArray(value, label, refuseManualDefinition);\n const sql: Sql[] = [];\n for (let index = 0; index < entries.length; index++) {\n sql.push(snapshotSql(entries[index], `${label}[${index}]`));\n }\n return Object.freeze(sql);\n}\n\nfunction snapshotSql(value: unknown, label: string): Sql {\n try {\n if (!(value instanceof Sql)) {\n return refuseManualDefinition(`${label} must be a Sql value`);\n }\n const rawStrings: unknown = Reflect.get(value, \"strings\");\n const rawValues: unknown = Reflect.get(value, \"values\");\n if (!(Array.isArray(rawStrings) && Array.isArray(rawValues))) {\n return refuseManualDefinition(\n `${label}.strings and ${label}.values must be arrays`\n );\n }\n const strings = Array.from(rawStrings);\n const values = Array.from(rawValues);\n if (!strings.every((entry) => typeof entry === \"string\")) {\n return refuseManualDefinition(`${label}.strings must contain strings`);\n }\n if (strings.length !== values.length + 1) {\n return refuseManualDefinition(\n `${label} has an invalid strings and values shape`\n );\n }\n return new Sql(Object.freeze(strings), Object.freeze(values));\n } catch (failure) {\n return refuseManualDefinition(\n `${label} could not be read`,\n errorCause(failure)\n );\n }\n}\n\nfunction isResolveCallback(value: unknown): value is ResolveCallback {\n return typeof value === \"function\";\n}\n\nfunction refuseGenerateOptions(message: string, cause?: Error): never {\n throw new MigrationError(message, VibORMErrorCode.INVALID_INPUT, { cause });\n}\n\nfunction refuseManualDefinition(message: string, cause?: Error): never {\n throw new MigrationError(message, VibORMErrorCode.MIGRATION_INVALID_ESTATE, {\n cause,\n });\n}\n","/** Immutable, non-executable migration graph projections for public tooling. */\n\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\nimport type { MigrationGraph } from \"./graph\";\nimport type { Sha256 } from \"./identity\";\nimport { sliceDispatch } from \"./sql-blob\";\nimport type { MigrationTarget } from \"./types\";\nimport type {\n MigrationApprovalV1,\n MigrationBooleanCheckV1,\n MigrationDispatchV1,\n MigrationOperationV1,\n MigrationParentTransitionV1,\n MigrationStateManifestV1,\n} from \"./v1-types\";\n\nexport interface MigrationStateListItem {\n readonly stateId: Sha256;\n readonly name: string;\n}\n\nexport interface MigrationStateMetadata extends MigrationStateListItem {\n readonly snapshotHash: Sha256;\n readonly sqlHash: Sha256;\n readonly root: boolean;\n readonly leaf: boolean;\n}\n\nexport type MigrationRollbackMetadata =\n | {\n readonly kind: \"schema\" | \"manual\";\n readonly operationCount: number;\n readonly stepCount: number;\n }\n | {\n readonly kind: \"irreversible\";\n readonly reason: string;\n readonly operationCount: 0;\n readonly stepCount: 0;\n };\n\nexport interface MigrationEdgeMetadata {\n readonly fromState: Sha256 | null;\n readonly toState: Sha256;\n readonly transitionHash: Sha256;\n readonly requestedBoundary: \"transactional\" | \"stepwise\" | null;\n readonly operationCount: number;\n readonly stepCount: number;\n readonly origins: readonly (\"generated\" | \"manual\")[];\n readonly risks: readonly (\"safe\" | \"destructive\" | \"opaque\")[];\n /** The destructive changes approved at `generate`; empty when none was asked. */\n readonly approvals: readonly MigrationApprovalV1[];\n readonly rollback: MigrationRollbackMetadata;\n}\n\nexport interface MigrationStateDetails extends MigrationStateMetadata {\n readonly incoming: readonly MigrationEdgeMetadata[];\n readonly outgoing: readonly MigrationEdgeMetadata[];\n}\n\nexport interface GraphResult {\n readonly estateHash: Sha256;\n readonly target: MigrationTarget;\n readonly roots: readonly Sha256[];\n readonly leaves: readonly Sha256[];\n readonly states: readonly MigrationStateMetadata[];\n readonly edges: readonly MigrationEdgeMetadata[];\n}\n\nexport type ListResult = readonly MigrationStateListItem[];\nexport type ShowResult = MigrationStateDetails;\n\nexport function listMigrationStates(graph: MigrationGraph): ListResult {\n return Object.freeze(\n sortedStates(graph).map((state) =>\n Object.freeze({ stateId: state.stateId, name: state.name })\n )\n );\n}\n\nexport function showMigrationState(\n graph: MigrationGraph,\n stateId: Sha256\n): ShowResult {\n const state = graph.states.get(stateId);\n if (!state) {\n throw new MigrationError(\n \"Resolved migration state is absent from its graph\",\n VibORMErrorCode.INTERNAL_ERROR\n );\n }\n const edges = graphEdges(graph);\n return Object.freeze({\n ...stateMetadata(graph, state),\n incoming: Object.freeze(edges.filter((edge) => edge.toState === stateId)),\n outgoing: Object.freeze(edges.filter((edge) => edge.fromState === stateId)),\n });\n}\n\nexport function migrationGraphResult(graph: MigrationGraph): GraphResult {\n return Object.freeze({\n estateHash: graph.estateHash,\n target: migrationTarget(graph.descriptor.target),\n roots: Object.freeze([...graph.roots].sort()),\n leaves: Object.freeze([...graph.leaves].sort()),\n states: Object.freeze(\n sortedStates(graph).map((state) => stateMetadata(graph, state))\n ),\n edges: graphEdges(graph),\n });\n}\n\nfunction sortedStates(graph: MigrationGraph): MigrationStateManifestV1[] {\n return [...graph.states.values()].sort((left, right) =>\n left.stateId.localeCompare(right.stateId)\n );\n}\n\nfunction stateMetadata(\n graph: MigrationGraph,\n state: MigrationStateManifestV1\n): MigrationStateMetadata {\n return Object.freeze({\n stateId: state.stateId,\n name: state.name,\n snapshotHash: state.snapshotHash,\n sqlHash: state.sqlHash,\n root: graph.roots.includes(state.stateId),\n leaf: graph.leaves.includes(state.stateId),\n });\n}\n\nfunction graphEdges(graph: MigrationGraph): readonly MigrationEdgeMetadata[] {\n const edges: MigrationEdgeMetadata[] = [];\n for (const state of sortedStates(graph)) {\n for (const transition of state.parents) {\n edges.push(edgeMetadata(state.stateId, transition));\n }\n }\n edges.sort((left, right) => {\n const from = (left.fromState ?? \"\").localeCompare(right.fromState ?? \"\");\n return from === 0 ? left.toState.localeCompare(right.toState) : from;\n });\n return Object.freeze(edges);\n}\n\nfunction edgeMetadata(\n toState: Sha256,\n transition: MigrationParentTransitionV1\n): MigrationEdgeMetadata {\n return Object.freeze({\n fromState: transition.fromState,\n toState,\n transitionHash: transition.transitionHash,\n requestedBoundary: transition.requestedForwardBoundary,\n operationCount: transition.operations.length,\n stepCount: stepCount(transition.operations),\n origins: uniqueOperationValues(transition.operations, \"origin\"),\n risks: uniqueOperationValues(transition.operations, \"risk\"),\n approvals: Object.freeze(\n (transition.approvals ?? []).map((approval) =>\n Object.freeze({ ...approval })\n )\n ),\n rollback: rollbackMetadata(transition),\n });\n}\n\nfunction rollbackMetadata(\n transition: MigrationParentTransitionV1\n): MigrationRollbackMetadata {\n if (transition.rollback.kind === \"irreversible\") {\n return Object.freeze({\n kind: transition.rollback.kind,\n reason: transition.rollback.reason,\n operationCount: 0,\n stepCount: 0,\n });\n }\n const operations = transition.rollback.operations;\n return Object.freeze({\n kind: transition.rollback.kind,\n operationCount: operations.length,\n stepCount: stepCount(operations),\n });\n}\n\nfunction stepCount(operations: readonly MigrationOperationV1[]): number {\n let count = 0;\n for (const operation of operations) count += operation.steps.length;\n return count;\n}\n\nfunction uniqueOperationValues<K extends \"origin\" | \"risk\">(\n operations: readonly MigrationOperationV1[],\n key: K\n): readonly MigrationOperationV1[K][] {\n const values: MigrationOperationV1[K][] = [];\n for (const operation of operations) {\n const value = operation[key];\n if (!values.includes(value)) values.push(value);\n }\n return Object.freeze(values);\n}\n\nfunction migrationTarget(target: MigrationTarget): MigrationTarget {\n return target.dialect === \"postgresql\"\n ? Object.freeze({ dialect: target.dialect, namespace: target.namespace })\n : Object.freeze({ dialect: target.dialect });\n}\n\nconst LINE_BREAKS = /[\\r\\n\\u2028\\u2029]/g;\nconst oneLine = (text: string) => text.replace(LINE_BREAKS, \" \");\n\n/**\n * A labelled read-only projection; dispatch offsets remain the execution authority.\n * `approvalLabel` names the approvals: a preview made without a resolver lists\n * the ones publishing will need, not ones given.\n */\nexport function renderMigrationReview(\n parents: readonly MigrationParentTransitionV1[],\n destinationChecks: readonly MigrationBooleanCheckV1[],\n blob: Uint8Array,\n approvalLabel = \"Approved at generate\"\n): string {\n const lines = [\n \"-- VibORM review: forward, checks and rollback are separate sections.\",\n \"-- Execute authenticated states with migrate apply/down; this review is not an apply script.\",\n ];\n const emit = (label: string, dispatch: MigrationDispatchV1) => {\n lines.push(`-- ${oneLine(label)}`, `${sliceDispatch(blob, dispatch)};`);\n if (dispatch.parameters.length > 0)\n lines.push(`-- Parameters: ${JSON.stringify(dispatch.parameters)}`);\n };\n const operations = (\n direction: string,\n values: readonly MigrationOperationV1[]\n ) => {\n for (const operation of values)\n for (const step of operation.steps) {\n if (step.retry === \"proven\")\n emit(`${direction} precheck ${operation.label}`, step.precheck.query);\n emit(`${direction} execute ${operation.label}`, step.execute);\n if (step.retry === \"proven\")\n emit(\n `${direction} postcheck ${operation.label}`,\n step.postcheck.query\n );\n }\n };\n for (const parent of parents) {\n lines.push(`\\n-- Parent ${parent.fromState ?? \"empty\"}`);\n for (const { operation, table, column } of parent.approvals ?? [])\n lines.push(\n `-- ${approvalLabel}: ${oneLine(`${operation} ${table}${column === null ? \"\" : `.${column}`}`)}`\n );\n for (const check of parent.originChecks)\n emit(`Origin check ${check.id}`, check.query);\n operations(\"FORWARD\", parent.operations);\n if (parent.rollback.kind === \"irreversible\")\n lines.push(`-- ROLLBACK unavailable: ${oneLine(parent.rollback.reason)}`);\n else operations(\"ROLLBACK\", parent.rollback.operations);\n }\n for (const check of destinationChecks)\n emit(`Destination check ${check.id}`, check.query);\n return `${lines.join(\"\\n\\n\")}\\n`;\n}\n","/**\n * Hostile admission for push options and inert consent.\n *\n * Consent is not authority. A forged or stale value can only refuse\n * execution. Apply replans under the lock and compares this closed shape.\n */\n\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\nimport { canonicalizeJsonText } from \"./canonical-json\";\nimport { isSha256, type Sha256 } from \"./identity\";\nimport { snapshotExactArray, snapshotExactRecord } from \"./input-boundary\";\nimport { freezeDeep } from \"./push-fingerprint\";\nimport type { ResolveCallback } from \"./types\";\nimport type {\n PushConsent,\n PushResolution,\n PushTargetIdentity,\n} from \"./v1-types\";\n\ninterface ConsentedPlan {\n readonly mode: PushConsent[\"mode\"];\n readonly validation: PushConsent[\"validation\"];\n readonly target: PushTargetIdentity;\n readonly sourceFingerprint: Sha256;\n readonly planHash: Sha256;\n readonly resolutions: readonly PushResolution[];\n}\n\nexport interface ParsedPlanningOptions {\n readonly forceReset: boolean;\n readonly skipValidation: boolean;\n readonly resolve: ResolveCallback | undefined;\n readonly dryRun: boolean;\n}\n\nexport function snapshotPushOptions(\n value: unknown\n): Readonly<Record<string, unknown>> {\n return snapshotExactRecord(\n value,\n [\"consent\", \"dryRun\", \"forceReset\", \"resolve\", \"skipValidation\"],\n \"push options\",\n invalidOptions\n );\n}\n\nexport function parsePlanningOptions(\n value: unknown,\n dryRun: boolean\n): ParsedPlanningOptions {\n const record = snapshotExactRecord(\n value,\n [\"dryRun\", \"forceReset\", \"resolve\", \"skipValidation\"],\n \"push options\",\n invalidOptions\n );\n return parseSnapshottedPlanningOptions(record, dryRun);\n}\n\nexport function parseSnapshottedPlanningOptions(\n record: Readonly<Record<string, unknown>>,\n dryRun: boolean\n): ParsedPlanningOptions {\n if (record.dryRun !== undefined && typeof record.dryRun !== \"boolean\") {\n invalidOptions(\"push options.dryRun must be boolean\");\n }\n if (\n record.forceReset !== undefined &&\n typeof record.forceReset !== \"boolean\"\n ) {\n invalidOptions(\"push options.forceReset must be boolean\");\n }\n if (\n record.skipValidation !== undefined &&\n typeof record.skipValidation !== \"boolean\"\n ) {\n invalidOptions(\"push options.skipValidation must be boolean\");\n }\n const candidate = record.resolve;\n if (candidate !== undefined && typeof candidate !== \"function\") {\n invalidOptions(\"push options.resolve must be a function\");\n }\n const resolve: ResolveCallback | undefined =\n typeof candidate === \"function\"\n ? (change) => Reflect.apply(candidate, undefined, [change])\n : undefined;\n return {\n dryRun: dryRun || record.dryRun === true,\n forceReset: record.forceReset === true,\n skipValidation: record.skipValidation === true,\n resolve,\n };\n}\n\nexport function parseConsent(value: unknown): PushConsent {\n const record = snapshotExactRecord(\n value,\n [\"format\", \"mode\", \"planHash\", \"resolutions\", \"target\", \"validation\"],\n \"push consent\",\n consentMismatch\n );\n if (record.format !== \"1\") consentMismatch(\"consent.format must be 1\");\n if (record.mode !== \"diff\" && record.mode !== \"force-reset\") {\n consentMismatch(\"consent.mode is invalid\");\n }\n if (record.validation !== \"full\" && record.validation !== \"structural-only\") {\n consentMismatch(\"consent.validation is invalid\");\n }\n if (!isSha256(record.planHash)) {\n consentMismatch(\"consent.planHash is invalid\");\n }\n const resolutionEntries = snapshotExactArray(\n record.resolutions,\n \"consent.resolutions\",\n consentMismatch\n );\n const resolutions = resolutionEntries.map((resolution, index) => {\n const item = snapshotExactRecord(\n resolution,\n [\"decision\", \"id\"],\n `consent.resolutions[${index}]`,\n consentMismatch\n );\n if (typeof item.id !== \"string\" || typeof item.decision !== \"string\") {\n consentMismatch(`consent.resolutions[${index}] is invalid`);\n }\n return { id: item.id, decision: item.decision };\n });\n return freezeDeep({\n format: \"1\",\n target: parseTarget(record.target),\n planHash: record.planHash,\n mode: record.mode,\n validation: record.validation,\n resolutions,\n });\n}\n\nexport function assertAcceptedPlan(\n accepted: ConsentedPlan,\n locked: ConsentedPlan\n): void {\n if (\n accepted.sourceFingerprint !== locked.sourceFingerprint ||\n accepted.planHash !== locked.planHash\n ) {\n throw new MigrationError(\n \"The live push plan changed before the locked replan\",\n VibORMErrorCode.MIGRATION_CONSENT_MISMATCH,\n {\n meta: {\n expectedChecksum: accepted.planHash,\n actualChecksum: locked.planHash,\n planHash: locked.planHash,\n expectedFingerprint: accepted.sourceFingerprint,\n actualFingerprint: locked.sourceFingerprint,\n },\n }\n );\n }\n}\n\nexport function assertConsent(consent: PushConsent, plan: ConsentedPlan): void {\n const targetMatches =\n canonicalizeJsonText(consent.target) === canonicalizeJsonText(plan.target);\n const resolutionsMatch =\n canonicalizeJsonText(consent.resolutions) ===\n canonicalizeJsonText(plan.resolutions);\n if (\n consent.mode !== plan.mode ||\n consent.validation !== plan.validation ||\n !targetMatches ||\n !resolutionsMatch ||\n consent.planHash !== plan.planHash\n ) {\n throw new MigrationError(\n \"Push consent does not match the locked live plan\",\n VibORMErrorCode.MIGRATION_CONSENT_MISMATCH,\n {\n meta: {\n expectedChecksum: consent.planHash,\n actualChecksum: plan.planHash,\n planHash: plan.planHash,\n fingerprint: plan.sourceFingerprint,\n },\n }\n );\n }\n}\n\nexport function hasConsent(\n options: Readonly<Record<string, unknown>>\n): options is Readonly<Record<string, unknown>> & {\n readonly consent: unknown;\n} {\n return \"consent\" in options;\n}\n\nfunction parseTarget(value: unknown): PushTargetIdentity {\n const record = snapshotExactRecord(\n value,\n [\"database\", \"dialect\", \"location\", \"namespace\"],\n \"consent.target\",\n consentMismatch\n );\n if (record.dialect === \"postgresql\") {\n refuseTargetKeys(record, [\"database\", \"dialect\", \"namespace\"]);\n return {\n dialect: \"postgresql\",\n database: requiredString(record.database, \"consent.target.database\"),\n namespace: requiredString(record.namespace, \"consent.target.namespace\"),\n };\n }\n if (record.dialect === \"mysql\") {\n refuseTargetKeys(record, [\"database\", \"dialect\"]);\n return {\n dialect: \"mysql\",\n database: requiredString(record.database, \"consent.target.database\"),\n };\n }\n if (record.dialect === \"sqlite\") {\n refuseTargetKeys(record, [\"dialect\", \"location\"]);\n if (record.location !== null && typeof record.location !== \"string\") {\n consentMismatch(\"consent.target.location must be string or null\");\n }\n return { dialect: \"sqlite\", location: record.location };\n }\n consentMismatch(\"consent.target.dialect is invalid\");\n}\n\nfunction refuseTargetKeys(\n target: Readonly<Record<string, unknown>>,\n allowed: readonly string[]\n): void {\n for (const key of Object.keys(target)) {\n if (!allowed.includes(key)) {\n consentMismatch(`consent.target contains unknown key ${key}`);\n }\n }\n}\n\nfunction requiredString(value: unknown, label: string): string {\n if (typeof value !== \"string\" || value.length === 0) {\n consentMismatch(`${label} must be a non-empty string`);\n }\n return value;\n}\n\nfunction invalidOptions(message: string, cause?: Error): never {\n throw new MigrationError(message, VibORMErrorCode.INVALID_INPUT, { cause });\n}\n\nfunction consentMismatch(message: string, cause?: Error): never {\n throw new MigrationError(\n message,\n VibORMErrorCode.MIGRATION_CONSENT_MISMATCH,\n {\n cause,\n }\n );\n}\n","/**\n * Authenticated, history-free push.\n *\n * A preview exposes review text and inert consent. The executable program stays\n * private, is rebuilt from the live catalog under the target lock, and is\n * dispatched only through the structured-statement compiler.\n */\n\nimport type { AnyDriver } from \"../drivers/driver\";\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\nimport { hydrateSchemaNames } from \"../schema/hydration\";\nimport type { ResolvedRelationIndex } from \"../schema/validation/relation-resolution\";\nimport { allRules } from \"../schema/validation/rules\";\nimport {\n resolveSchemaOrThrow,\n validateResolvedSchemaOrThrow,\n} from \"../schema/validation/validator\";\nimport { admitLiveMigrationCapability } from \"./admission\";\nimport { canonicalizeJson } from \"./canonical-json\";\nimport { refuseIncompatibleHistory, unfinishedAttempts } from \"./control\";\nimport { diff } from \"./differ\";\nimport type { BoundMigrationDriver } from \"./drivers\";\nimport { executeDispatch } from \"./execute-dispatch\";\nimport { domainHash, HASH_DOMAIN, type Sha256 } from \"./identity\";\nimport {\n resolveCommandDriver,\n runProgram,\n withLockedMigrationProducer,\n} from \"./pinned-session\";\nimport { getPushMigrationDriver, type MigrationClient } from \"./push/planner\";\nimport {\n assertAcceptedPlan,\n assertConsent,\n hasConsent,\n parseConsent,\n parsePlanningOptions,\n parseSnapshottedPlanningOptions,\n snapshotPushOptions,\n} from \"./push-consent\";\nimport { fingerprintLive, freezeDeep } from \"./push-fingerprint\";\nimport {\n buildPushPlan,\n type InternalPushPlan,\n introspectManaged,\n} from \"./push-plan\";\nimport { readCommandControl } from \"./resume\";\nimport { assertMigrationDecimalDomainsFitProvider } from \"./serializer\";\nimport { sliceDispatch } from \"./sql-blob\";\nimport type {\n PushApplyResult as BasePushApplyResult,\n PushPreview as BasePushPreview,\n ExactPushOptions,\n PushConsent,\n PushOptionsV1,\n PushPlanningOptions,\n} from \"./v1-types\";\n\nexport type {\n ExactPushOptions,\n PushConsent,\n PushOperation,\n PushOptionsV1,\n PushOptionsV1 as PushOptions,\n PushPlanningOptions,\n PushResolution,\n PushStatementPreview,\n PushTargetIdentity,\n} from \"./v1-types\";\n\nexport interface PushAttestation {\n readonly pathHash: Sha256;\n readonly planHash: Sha256;\n readonly schemaHash: Sha256;\n readonly fingerprint: Sha256;\n}\n\nexport interface PushApplyResult extends BasePushApplyResult {\n readonly attestation: PushAttestation;\n}\n\nexport interface PushPreview extends BasePushPreview {\n readonly schemaHash: Sha256;\n readonly fingerprint: Sha256;\n}\n\nexport type PushResultFor<O> = [O] extends [{ readonly dryRun: true }]\n ? PushPreview\n : PushApplyResult;\n\n/**\n * Effect-free planning. It does not acquire a lock and never receives estate\n * storage. A force reset plans the empty-to-target rebuild rather than diffing\n * the desired schema from the live schema.\n */\nexport async function previewPush(\n client: MigrationClient,\n options: PushPlanningOptions = {}\n): Promise<PushPreview> {\n const parsed = parsePlanningOptions(options, true);\n const { relations, driver } = prepareSchema(client, parsed.skipValidation);\n admitLiveMigrationCapability(\n driver,\n \"read-only\",\n parsed.forceReset ? \"push({ forceReset: true })\" : \"push()\"\n );\n const command = await resolveCommandDriver(client.$driver, driver);\n const plan = await buildPushPlan(\n client,\n client.$driver,\n command,\n relations,\n parsed,\n { kind: \"record\", callback: parsed.resolve }\n );\n return publicPreview(plan);\n}\n\n/**\n * Replans and executes on one pinned producer under the target lock.\n *\n * Generic force is deliberately absent. Destructive diff work and every\n * force-reset plan require exact preview consent.\n */\nexport function pushV1<O extends PushOptionsV1>(\n client: MigrationClient,\n options?: ExactPushOptions<O>\n): Promise<PushResultFor<O>>;\nexport async function pushV1(\n client: MigrationClient,\n options?: PushOptionsV1\n): Promise<PushApplyResult | PushPreview> {\n const given = snapshotPushOptions(options ?? {});\n if (hasConsent(given)) {\n return applyWithConsent(client, parseConsent(given.consent));\n }\n\n const parsed = parseSnapshottedPlanningOptions(given, given.dryRun === true);\n if (parsed.dryRun) {\n return previewPush(client, parsed);\n }\n\n const { relations, driver } = prepareSchema(client, parsed.skipValidation);\n\n // A resolver may perform arbitrary user work. Run it only during an unlocked\n // read-only plan, then close its normalized answers for the locked replan.\n let accepted: InternalPushPlan | undefined;\n if (parsed.resolve) {\n admitLiveMigrationCapability(driver, \"read-only\", \"push()\");\n const command = await resolveCommandDriver(client.$driver, driver);\n accepted = await buildPushPlan(\n client,\n client.$driver,\n command,\n relations,\n parsed,\n { kind: \"record\", callback: parsed.resolve }\n );\n }\n\n admitLiveMigrationCapability(\n driver,\n \"effectful\",\n parsed.forceReset ? \"push({ forceReset: true })\" : \"push()\"\n );\n return withLockedMigrationProducer(\n client.$driver,\n driver,\n async (pinned, command) => {\n const plan = await buildPushPlan(\n client,\n pinned,\n command,\n relations,\n parsed,\n accepted\n ? { kind: \"replay\", resolutions: accepted.resolutions }\n : { kind: \"record\", callback: undefined }\n );\n if (accepted) assertAcceptedPlan(accepted, plan);\n await assertPushControlInterlock(pinned, command, plan);\n if (plan.destructive) {\n throw new MigrationError(\n \"Destructive or force-reset push requires exact preview consent. Call push({ dryRun: true }), review the plan, then pass its consent unchanged to push({ consent }).\",\n VibORMErrorCode.MIGRATION_CONSENT_REQUIRED,\n {\n meta: {\n command: \"push\",\n dialect: plan.target.dialect,\n expectedChecksum: plan.planHash,\n expectedStatementCount: plan.statements.length,\n hint: \"Review push({ dryRun: true }) and pass the returned consent unchanged to push({ consent }).\",\n },\n }\n );\n }\n return executeLockedPlan(pinned, command, plan);\n }\n );\n}\n\nasync function applyWithConsent(\n client: MigrationClient,\n consent: PushConsent\n): Promise<PushApplyResult> {\n const skipValidation = consent.validation === \"structural-only\";\n const { relations, driver } = prepareSchema(client, skipValidation);\n admitLiveMigrationCapability(\n driver,\n \"effectful\",\n consent.mode === \"force-reset\"\n ? \"push({ consent: forceResetPreview.consent })\"\n : \"push({ consent })\"\n );\n return withLockedMigrationProducer(\n client.$driver,\n driver,\n async (pinned, command) => {\n const plan = await buildPushPlan(\n client,\n pinned,\n command,\n relations,\n {\n forceReset: consent.mode === \"force-reset\",\n skipValidation,\n resolve: undefined,\n dryRun: false,\n },\n { kind: \"replay\", resolutions: consent.resolutions }\n );\n assertConsent(consent, plan);\n await assertPushControlInterlock(pinned, command, plan);\n return executeLockedPlan(pinned, command, plan);\n }\n );\n}\n\nasync function executeLockedPlan(\n pinned: AnyDriver,\n command: BoundMigrationDriver,\n plan: InternalPushPlan\n): Promise<PushApplyResult> {\n // A plan with nothing to do still has a MySQL sequential program to run: the\n // interrupted-decimal-conversion recovery belongs to the LOCKED COMMAND, not\n // to having statements. A conversion interrupted after its MODIFY leaves the\n // column already carrying the target domain, so the differ sees no change\n // and the plan is empty — and the remnant CHECK, which no snapshot\n // vocabulary describes, would then survive every later push while refusing\n // values the declared domain admits.\n if (plan.statements.length === 0 && command.target.dialect !== \"mysql\") {\n return appliedResult(plan, plan.sourceFingerprint, \"noop\");\n }\n\n // In a transaction the destination is proven before its COMMIT, and the\n // lifted foreign-key bracket runs around it (its pragmas, sent again\n // inside, are no-ops there); otherwise once the statements ran — on MySQL\n // after its sequential program.\n const fingerprint = await runProgram(\n pinned,\n command,\n {\n transactional: plan.atomicity === \"transactional\",\n statements: plan.statements.map((statement) =>\n sliceDispatch(plan.sqlBlob, statement.dispatch)\n ),\n },\n async (producer, atomic) => {\n for (const statement of plan.statements) {\n await executeDispatch(\n producer,\n plan.sqlBlob,\n statement.dispatch,\n command.namespace\n );\n }\n return atomic ? attestFinalFingerprint(producer, command, plan) : null;\n }\n );\n if (plan.statements.length === 0) {\n return appliedResult(plan, plan.sourceFingerprint, \"noop\");\n }\n return appliedResult(\n plan,\n fingerprint ?? (await attestFinalFingerprint(pinned, command, plan)),\n \"applied\"\n );\n}\n\nasync function attestFinalFingerprint(\n producer: AnyDriver,\n command: BoundMigrationDriver,\n plan: InternalPushPlan\n): Promise<Sha256> {\n const finalSnapshot = await introspectManaged(producer, command);\n const fingerprint = await fingerprintLive(finalSnapshot, command, producer);\n const expected = await fingerprintLive(plan.desiredSchema, command, producer);\n if (fingerprint !== expected) {\n throw new MigrationError(\n `Push completed its statements but the final live fingerprint does not match the desired schema: ${JSON.stringify(await diff(finalSnapshot, plan.desiredSchema))}`,\n VibORMErrorCode.MIGRATION_DRIFT,\n {\n meta: {\n planHash: plan.planHash,\n schemaHash: plan.schemaHash,\n fingerprint,\n },\n }\n );\n }\n return fingerprint;\n}\n\nfunction appliedResult(\n plan: InternalPushPlan,\n fingerprint: Sha256,\n outcome: PushApplyResult[\"outcome\"]\n): PushApplyResult {\n const pathHash = domainHash(\n HASH_DOMAIN.path,\n canonicalizeJson({\n target: plan.target,\n sourceFingerprint: plan.sourceFingerprint,\n fingerprint,\n planHash: plan.planHash,\n schemaHash: plan.schemaHash,\n })\n );\n return freezeDeep({\n outcome,\n target: plan.target,\n planHash: plan.planHash,\n operations: plan.reportedOperations,\n statements: plan.previewStatements,\n attestation: {\n pathHash,\n planHash: plan.planHash,\n schemaHash: plan.schemaHash,\n fingerprint,\n },\n });\n}\n\nasync function assertPushControlInterlock(\n producer: AnyDriver,\n command: BoundMigrationDriver,\n plan: InternalPushPlan\n): Promise<void> {\n const control = await readCommandControl(producer, command);\n if (control.presence.kind !== \"present\") return;\n const { marker, ledger } = control;\n if (unfinishedAttempts(ledger).length > 0) {\n throw new MigrationError(\n \"An unfinished migration attempt is blocking push\",\n VibORMErrorCode.MIGRATION_UNFINISHED_ATTEMPT\n );\n }\n refuseIncompatibleHistory(marker, ledger);\n if (!marker) {\n return;\n }\n if (plan.operations.length > 0 || plan.mode === \"force-reset\") {\n throw new MigrationError(\n \"Non-empty push against a migration marker is refused; use generate/apply or history-aware reset\",\n VibORMErrorCode.MIGRATION_INVALID_STATE,\n { meta: { planHash: plan.planHash } }\n );\n }\n if (\n marker.snapshotHash !== plan.schemaHash ||\n plan.sourceFingerprint !== plan.desiredFingerprint\n ) {\n throw new MigrationError(\n \"A no-op push cannot prove agreement between the marker, live schema, and desired schema\",\n VibORMErrorCode.MIGRATION_DRIFT,\n {\n meta: {\n planHash: plan.planHash,\n expectedChecksum: marker.snapshotHash,\n actualChecksum: plan.schemaHash,\n },\n }\n );\n }\n}\n\nfunction publicPreview(plan: InternalPushPlan): PushPreview {\n const consent: PushConsent = {\n format: \"1\",\n target: plan.target,\n planHash: plan.planHash,\n mode: plan.mode,\n validation: plan.validation,\n resolutions: plan.resolutions,\n };\n return freezeDeep({\n outcome: plan.statements.length === 0 ? \"noop\" : \"planned\",\n target: plan.target,\n planHash: plan.planHash,\n schemaHash: plan.schemaHash,\n fingerprint: plan.sourceFingerprint,\n destructive: plan.destructive,\n operations: plan.reportedOperations,\n statements: plan.previewStatements,\n consent,\n });\n}\n\nexport function prepareSchema(\n client: MigrationClient,\n skipValidation: boolean\n): {\n readonly relations: ResolvedRelationIndex;\n readonly driver: BoundMigrationDriver;\n} {\n hydrateSchemaNames(client.$schema);\n const relations = skipValidation\n ? resolveSchemaOrThrow(client.$schema)\n : validateResolvedSchemaOrThrow(client.$schema, allRules);\n const driver = getPushMigrationDriver(client);\n assertMigrationDecimalDomainsFitProvider(client.$schema, driver.dialect);\n return { relations, driver };\n}\n","/**\n * V1 generation: one new state from parent leaves, published atomically.\n * Snapshot and SQL are published before the state manifest.\n */\n\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\nimport {\n assertManualStepwiseProof,\n type CompiledTransition,\n compileGeneratedTransition,\n compileManualTransition,\n compileTrustedCheck,\n compileValidationTransition,\n hashParent,\n type LowLockState,\n lowLockStates,\n lowLockSteps,\n rebindChecks,\n rebindDispatches,\n rebindRollback,\n sealParent,\n} from \"./compile\";\nimport { type DiffOptions, diff } from \"./differ\";\nimport { emptyManagedSnapshot } from \"./empty-snapshot\";\nimport { normalizeGenerateOptions } from \"./generate-input\";\nimport {\n loadMigrationGraph,\n type MigrationGraph,\n requireStateSnapshot,\n} from \"./graph\";\nimport type { Sha256 } from \"./identity\";\nimport { renderMigrationReview } from \"./public-view\";\nimport {\n applyResolvedEnumMappings,\n detectEnumValueRemovals,\n resolveEnumValueRemovalMappings,\n} from \"./push/enum-removals\";\nimport type { getPushMigrationDriver, MigrationClient } from \"./push/planner\";\nimport { prepareSchema } from \"./push-v1\";\nimport {\n approveDestructiveOperations,\n callbackAsResolver,\n refuseUnusedDecisions,\n rejectAllResolver,\n resolveAmbiguousChanges,\n strictResolver,\n} from \"./resolver\";\nimport { serializeResolvedModels } from \"./serializer\";\nimport { SqlAssembly } from \"./sql-assembly\";\nimport { sliceDispatch } from \"./sql-blob\";\nimport { assertArtifactExecutionSafe } from \"./statement-safety\";\nimport type { MigrationStorageWriter } from \"./storage/contract\";\nimport { assertEstateTargetMatches } from \"./target\";\nimport type { DiffOperation, ResolveCallback, SchemaSnapshot } from \"./types\";\nimport { generateMigrationName, prepareSchemaProgram } from \"./utils\";\nimport {\n encodeEstateDescriptor,\n encodeSnapshot,\n encodeStateManifest,\n parseEstateDescriptor,\n} from \"./v1-parse\";\nimport type {\n GenerateV1Options,\n ManualMigrationInput,\n ManualTransitionInput,\n MigrationApprovalV1,\n MigrationBooleanCheckV1,\n MigrationParentTransitionV1,\n} from \"./v1-types\";\n\nexport interface GenerateV1Result {\n readonly outcome: \"published\" | \"preview\" | \"noop\";\n readonly stateId: Sha256 | null;\n readonly name: string | null;\n readonly estateHash: Sha256 | null;\n readonly snapshotHash: Sha256 | null;\n readonly sqlHash: Sha256 | null;\n readonly operations: readonly DiffOperation[];\n readonly warnings: readonly string[];\n readonly operationsByParent: readonly {\n readonly fromState: string | null;\n readonly operations: readonly DiffOperation[];\n }[];\n readonly sql: string;\n readonly reviewSql: string;\n}\n\nconst AUTHENTICATED_SNAPSHOT_DIFF_OPTIONS: DiffOptions = {\n compareDateTimeDeclarations: true,\n};\n\n/**\n * A dry run without a resolver previews the state as an approval would publish\n * it, as push's preview does; publishing still needs the resolver's answer.\n */\nconst previewApproval: ResolveCallback = (change) =>\n change.type === \"destructive\" ? change.proceed() : undefined;\n\nexport async function generateV1(\n client: MigrationClient,\n storage: MigrationStorageWriter,\n options: GenerateV1Options = {}\n): Promise<GenerateV1Result> {\n const request = normalizeGenerateOptions(options);\n const { relations, driver } = prepareSchema(\n client,\n request.skipValidation ?? false\n );\n const publishedEstate = await storage.readEstate();\n const estateBytes =\n publishedEstate ?? encodeEstateDescriptor(driver.target).bytes;\n const { estateHash, descriptor } = parseEstateDescriptor(estateBytes);\n assertEstateTargetMatches(descriptor.target, driver.target);\n const loaded = publishedEstate\n ? await loadMigrationGraph(storage)\n : emptyGraph(estateHash, descriptor);\n\n const desired = serializeResolvedModels(client.$schema, driver, relations);\n const desiredEncoded = encodeSnapshot(desired);\n const parents = resolveParents(loaded, request, desired);\n refuseUnprovedMerge(loaded, parents, request.manualMigration);\n const parentState =\n parents.length === 1 && parents[0]\n ? loaded.states.get(parents[0])\n : undefined;\n const parentSnapshot =\n parentState && loaded.snapshots.get(parentState.snapshotHash);\n const unchangedSnapshot =\n parentSnapshot !== undefined && sameSchema(parentSnapshot, desired);\n\n const assembly = new SqlAssembly();\n const parentBodies: Omit<MigrationParentTransitionV1, \"transitionHash\">[] =\n [];\n const reported: DiffOperation[] = [];\n const warnings: string[] = [];\n const operationsByParent: {\n fromState: string | null;\n operations: DiffOperation[];\n }[] = [];\n const destinationPlaceholders: MigrationBooleanCheckV1[] = [];\n // Each state a low-lock split publishes before this one, parent first.\n const stepStates: SealedLowLockState[] = [];\n\n if (request.manualMigration) {\n assertManualParents(loaded, request.manualMigration.transitions);\n for (const transition of request.manualMigration.transitions) {\n const compiled = compileManualTransition(\n transition.up,\n transition.rollback,\n driver.target.dialect,\n transition.execution,\n transition.originChecks,\n assembly\n );\n parentBodies.push(sealParent(transition.from, compiled));\n }\n for (const [index, check] of (\n request.manualMigration.destinationChecks ?? []\n ).entries()) {\n destinationPlaceholders.push(\n compileTrustedCheck(\n check,\n driver.target.dialect,\n assembly,\n `destination:${index}`\n )\n );\n }\n for (const compiled of parentBodies) {\n assertManualStepwiseProof(\n {\n operations: compiled.operations,\n rollback: compiled.rollback,\n originChecks: compiled.originChecks,\n requestedForwardBoundary: compiled.requestedForwardBoundary,\n atomicity: compiled.requestedForwardBoundary ?? \"transactional\",\n },\n destinationPlaceholders\n );\n }\n } else {\n for (const [index, from] of parents.entries()) {\n const current = requireStateSnapshot(loaded, from);\n const diffOptions = {\n ...AUTHENTICATED_SNAPSHOT_DIFF_OPTIONS,\n projectRename: driver.projectNativeRename.bind(driver),\n refuseConstraintNameChurn:\n driver.capabilities.introspectionReadsConstraintNames,\n };\n const diffed = await diff(current, desired, diffOptions);\n const admittedDrops = new Set<string>();\n const resolved = await resolveAmbiguousChanges(\n diffed,\n current,\n desired,\n request.resolve\n ? callbackAsResolver(request.resolve, admittedDrops)\n : strictResolver,\n diffOptions\n );\n const approvals = await approveDestructiveOperations(\n resolved,\n request.resolve ?? (request.dryRun ? previewApproval : undefined),\n false,\n admittedDrops\n );\n const enumMappings = await resolveEnumValueRemovalMappings(\n detectEnumValueRemovals(resolved, current),\n request.resolve ?? rejectAllResolver,\n false\n );\n const withEnumMappings = resolved.map((operation) =>\n operation.type === \"alterEnum\"\n ? applyResolvedEnumMappings([operation], enumMappings)[0]!\n : operation\n );\n const staged = prepareSchemaProgram(withEnumMappings, current, driver);\n reported.push(...staged);\n operationsByParent.push({ fromState: from, operations: staged });\n // T2: the plan has asked every decision once its last parent is\n // planned, before a low-lock split publishes. A document already\n // published (a re-drive) asks none and stays a noop.\n if (index === parents.length - 1 && !unchangedSnapshot) {\n refuseUnusedDecisions(request.resolve);\n }\n // T5b, asked for with `lowLock`: one parent's PostgreSQL program gives\n // each low-lock step a commit of its own, as states published before\n // this one. Opt-in, because a step outside a transaction needs the\n // direct session a transaction pooler cannot give.\n const lowLock =\n request.lowLock === true && driver.dialect === \"postgresql\";\n const split =\n lowLock && parents.length === 1\n ? lowLockStates(staged, current, desired)\n : undefined;\n if (lowLock && !split && lowLockSteps(staged).size > 0) {\n warnings.push(\n \"lowLock: this change keeps its blocking index builds and validating foreign keys, because it merges several parents or changes something other than an index or a foreign key after its first index build. Generate those indexes and keys in a migration of their own to get their step form.\"\n );\n }\n let origin = { from, current, approvals };\n const before = split?.states.slice(0, -1) ?? [];\n for (const [index, state] of before.entries()) {\n const step = sealLowLockState(\n estateHash,\n driver,\n `${request.name?.trim() || generateMigrationName(staged)} (step ${index + 1} of ${before.length + 1})`,\n origin,\n state,\n split?.steps\n );\n warnings.push(...step.warnings);\n stepStates.push(step);\n origin = {\n from: step.encoded.stateId,\n current: state.snapshot,\n approvals: [],\n };\n }\n const last = split?.states.at(-1);\n const compiled = last?.validates\n ? compileValidationTransition(\n last.operations,\n driver,\n origin.current,\n assembly\n )\n : compileGeneratedTransition(\n last?.operations ?? staged,\n driver,\n \"artifact\",\n origin.current,\n desired,\n assembly,\n split?.steps\n );\n warnings.push(...transitionWarnings(compiled));\n parentBodies.push(sealParent(origin.from, compiled, origin.approvals));\n }\n }\n\n const named = request.name?.trim() || generateMigrationName(reported);\n const { sealed, hashedParents, destinationChecks, encoded } = sealState(\n assembly,\n parentBodies,\n destinationPlaceholders,\n driver.target.dialect,\n estateHash,\n named,\n desiredEncoded.snapshotHash\n );\n\n // Decision 8: field and model order is cosmetic, so a document that only\n // reorders them is a noop and publishes nothing.\n const emptyProgram = hashedParents.every((parent) =>\n parent.operations.every((operation) => operation.steps.length === 0)\n );\n if (!request.manualMigration && unchangedSnapshot && emptyProgram) {\n return {\n outcome: \"noop\",\n stateId: null,\n name: null,\n estateHash,\n snapshotHash: desiredEncoded.snapshotHash,\n sqlHash: null,\n operations: [],\n warnings: [],\n operationsByParent: [],\n sql: \"\",\n reviewSql: \"\",\n };\n }\n\n const final = { snapshot: desiredEncoded, sealed, encoded };\n const states = [...stepStates, final];\n const sqlText = states\n .map((state) => new TextDecoder().decode(state.sealed.bytes))\n .join(\"\\n\\n\");\n const reviewSql = [\n ...stepStates.map(({ review }) => review),\n renderMigrationReview(\n hashedParents,\n destinationChecks,\n sealed.bytes,\n request.resolve ? undefined : \"Needs approval at generate\"\n ),\n ].join(\"\\n\\n\");\n const candidate = {\n stateId: encoded.stateId,\n name: named,\n estateHash,\n snapshotHash: desiredEncoded.snapshotHash,\n sqlHash: sealed.sqlHash,\n operations: reported,\n warnings,\n operationsByParent,\n sql: sqlText,\n reviewSql,\n };\n if (request.dryRun) return { outcome: \"preview\", ...candidate };\n\n if (!publishedEstate) {\n await storage.publishEstate(estateBytes);\n }\n // Every state is complete before the first publishes. A low-lock split's\n // states publish parent first, each manifest after its snapshot and SQL.\n for (const { snapshot, sealed: sql, encoded: manifest } of states) {\n await storage.publishSnapshot(snapshot.snapshotHash, snapshot.bytes);\n await storage.publishSql(sql.sqlHash, sql.bytes);\n await storage.publishState(manifest.stateId, manifest.bytes);\n }\n return { outcome: \"published\", ...candidate };\n}\n\n/** Decision 8: two snapshots that differ only in field and model order. */\nfunction sameSchema(a: SchemaSnapshot, b: SchemaSnapshot): boolean {\n return (\n encodeSnapshot(orderFree(a)).snapshotHash ===\n encodeSnapshot(orderFree(b)).snapshotHash\n );\n}\n\n/** A snapshot with its tables, columns, keys and enums sorted by name. */\nfunction orderFree(snapshot: SchemaSnapshot): SchemaSnapshot {\n const byName = (a: { name: string }, b: { name: string }) =>\n a.name < b.name ? -1 : Number(a.name > b.name);\n return {\n ...snapshot,\n tables: snapshot.tables\n .map((table) => ({\n ...table,\n columns: [...table.columns].sort(byName),\n indexes: [...table.indexes].sort(byName),\n foreignKeys: [...table.foreignKeys].sort(byName),\n uniqueConstraints: [...table.uniqueConstraints].sort(byName),\n }))\n .sort(byName),\n enums: snapshot.enums && [...snapshot.enums].sort(byName),\n };\n}\n\n/**\n * Seals one state's manifest from its compiled parents: refuses unsafe SQL,\n * binds every check and dispatch to the sealed bytes and hashes each parent.\n */\nfunction sealState(\n assembly: SqlAssembly,\n parentBodies: readonly Omit<MigrationParentTransitionV1, \"transitionHash\">[],\n destinationPlaceholders: readonly MigrationBooleanCheckV1[],\n dialect: Parameters<typeof assertArtifactExecutionSafe>[1],\n estateHash: Sha256,\n name: string,\n snapshotHash: Sha256\n) {\n const sealed = assembly.seal();\n assertArtifactExecutionSafe(\n sealed.dispatches.map((dispatch) => sliceDispatch(sealed.bytes, dispatch)),\n dialect,\n name\n );\n const hashedParents = parentBodies.map((parent) =>\n hashParent({\n ...parent,\n originChecks: rebindChecks(parent.originChecks, sealed.dispatches),\n operations: rebindDispatches(parent.operations, sealed.dispatches),\n rollback: rebindRollback(parent.rollback, sealed.dispatches),\n })\n );\n const destinationChecks = rebindChecks(\n destinationPlaceholders,\n sealed.dispatches\n );\n const encoded = encodeStateManifest({\n format: \"1\",\n estateHash,\n name,\n snapshotHash,\n sqlHash: sealed.sqlHash,\n destinationChecks,\n parents: hashedParents,\n });\n return { sealed, hashedParents, destinationChecks, encoded };\n}\n\ntype SealedLowLockState = ReturnType<typeof sealLowLockState>;\n\n/**\n * Seals one state a low-lock split puts before the generated one (T5b); it\n * becomes the next state's parent. Nothing publishes until every state of the\n * candidate is sealed.\n */\nfunction sealLowLockState(\n estateHash: Sha256,\n driver: ReturnType<typeof getPushMigrationDriver>,\n name: string,\n origin: {\n readonly from: Sha256 | null;\n readonly current: SchemaSnapshot;\n readonly approvals: readonly MigrationApprovalV1[];\n },\n state: LowLockState,\n steps: ReadonlySet<DiffOperation> | undefined\n) {\n const assembly = new SqlAssembly();\n const compiled = compileGeneratedTransition(\n state.operations,\n driver,\n \"artifact\",\n origin.current,\n state.snapshot,\n assembly,\n steps\n );\n const snapshot = encodeSnapshot(state.snapshot);\n const sealed = sealState(\n assembly,\n [sealParent(origin.from, compiled, origin.approvals)],\n [],\n driver.target.dialect,\n estateHash,\n name,\n snapshot.snapshotHash\n );\n return {\n ...sealed,\n snapshot,\n review: renderMigrationReview(\n sealed.hashedParents,\n [],\n sealed.sealed.bytes\n ),\n warnings: transitionWarnings(compiled),\n };\n}\n\n/** What a compiled transition warns of: its own warnings, then irreversibility. */\nfunction transitionWarnings(compiled: CompiledTransition): string[] {\n return [\n ...(compiled.warnings ?? []),\n ...(compiled.rollback.kind === \"irreversible\"\n ? [compiled.rollback.reason]\n : []),\n ];\n}\n\nfunction assertManualParents(\n graph: MigrationGraph,\n transitions: readonly ManualTransitionInput[]\n): void {\n const seen = new Set<string>();\n for (const transition of transitions) {\n if (transition.from === null) {\n if (graph.states.size > 0) {\n throw new MigrationError(\n \"A second virtual-root transition is refused\",\n VibORMErrorCode.MIGRATION_INVALID_ESTATE\n );\n }\n } else if (!graph.states.has(transition.from)) {\n throw new MigrationError(\n `Unknown parent state ${transition.from}`,\n VibORMErrorCode.MIGRATION_NOT_FOUND\n );\n }\n const key = transition.from ?? \"null\";\n if (seen.has(key)) {\n throw new MigrationError(\n \"A manual migration names a parent more than once\",\n VibORMErrorCode.MIGRATION_INVALID_ESTATE\n );\n }\n seen.add(key);\n }\n}\n\nfunction resolveParents(\n graph: MigrationGraph,\n options: GenerateV1Options,\n desired: SchemaSnapshot\n): Array<Sha256 | null> {\n if (options.from !== undefined) {\n if (options.from === null) {\n // Plan T4 (decision 11): on a populated estate `from: null` authors a\n // checkpoint, a second root restating the single leaf's schema, which\n // reanchor() can move a marker onto once prune() dropped what precedes it.\n const [leaf, ...more] = graph.leaves;\n if (\n leaf &&\n (more.length > 0 ||\n !sameSchema(requireStateSnapshot(graph, leaf), desired))\n ) {\n throw new MigrationError(\n \"A second virtual-root transition is an authored checkpoint: it must restate the schema of the estate's single leaf. Generate the change first, then the checkpoint.\",\n VibORMErrorCode.MIGRATION_INVALID_ESTATE\n );\n }\n return [null];\n }\n if (!graph.states.has(options.from)) {\n throw new MigrationError(\n `Unknown parent state ${options.from}`,\n VibORMErrorCode.MIGRATION_NOT_FOUND\n );\n }\n return [options.from];\n }\n if (graph.states.size === 0) return [null];\n // `loadMigrationGraph` refuses a cycle, so a graph with states has a leaf.\n return [...graph.leaves];\n}\n\nfunction emptyGraph(\n estateHash: Sha256,\n descriptor: ReturnType<typeof parseEstateDescriptor>[\"descriptor\"]\n): MigrationGraph {\n const emptySnapshotHash = encodeSnapshot(emptyManagedSnapshot()).snapshotHash;\n return {\n estateHash,\n descriptor,\n states: new Map(),\n snapshots: new Map([[emptySnapshotHash, emptyManagedSnapshot()]]),\n sql: new Map(),\n roots: [],\n leaves: [],\n emptySnapshotHash,\n };\n}\n\nfunction ancestryHasCustom(\n graph: MigrationGraph,\n stateId: Sha256 | null,\n seen: Set<string> = new Set()\n): boolean {\n if (stateId === null || seen.has(stateId)) return false;\n seen.add(stateId);\n // Every id here is a validated state or a validated parent edge's source.\n const state = graph.states.get(stateId)!;\n for (const transition of state.parents) {\n if (\n transition.operations.some(\n (operation) => operation.origin === \"manual\"\n ) ||\n transition.requestedForwardBoundary !== null\n ) {\n return true;\n }\n if (ancestryHasCustom(graph, transition.fromState, seen)) return true;\n }\n return false;\n}\n\nfunction refuseUnprovedMerge(\n graph: MigrationGraph,\n parents: Array<Sha256 | null>,\n manual: ManualMigrationInput | undefined\n): void {\n if (parents.length < 2 || manual) return;\n for (const parent of parents) {\n if (ancestryHasCustom(graph, parent)) {\n throw new MigrationError(\n \"A custom or data transition cannot be merged structurally; supply manualMigration for every parent\",\n VibORMErrorCode.MIGRATION_INVALID_ESTATE\n );\n }\n }\n}\n","/** One hostile-input boundary for the public down() selector. */\n\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\nimport { snapshotExactRecord } from \"./input-boundary\";\nimport type { ResolveCallback } from \"./types\";\nimport type { StateSelector } from \"./v1-types\";\n\nexport interface NormalizedDownOptions {\n readonly steps: number;\n readonly to?: StateSelector;\n readonly dryRun: boolean;\n readonly expectRevision?: number;\n readonly resolve?: ResolveCallback;\n}\n\nexport function normalizeDownOptions(options: unknown): NormalizedDownOptions {\n const record = snapshotExactRecord(\n options,\n [\"steps\", \"to\", \"dryRun\", \"expectRevision\", \"resolve\"],\n \"down options\",\n refuseDownOptions\n );\n const { steps, to, dryRun, expectRevision, resolve } = record;\n if (steps !== undefined && to !== undefined) {\n return refuseDownOptions(\"down accepts either steps or to, not both\");\n }\n let normalizedSteps = 1;\n if (steps !== undefined) {\n if (\n typeof steps !== \"number\" ||\n !Number.isSafeInteger(steps) ||\n steps <= 0\n ) {\n return refuseDownOptions(\"down steps must be a positive safe integer\");\n }\n normalizedSteps = steps;\n }\n if (dryRun !== undefined && typeof dryRun !== \"boolean\") {\n return refuseDownOptions(\"down dryRun must be a boolean\");\n }\n if (\n expectRevision !== undefined &&\n (typeof expectRevision !== \"number\" ||\n !Number.isSafeInteger(expectRevision) ||\n expectRevision <= 0)\n ) {\n return refuseDownOptions(\n \"down expectRevision must be a positive safe integer\"\n );\n }\n if (resolve !== undefined && !isResolveCallback(resolve)) {\n return refuseDownOptions(\"down resolve must be a function\");\n }\n return Object.freeze({\n steps: normalizedSteps,\n ...(to === undefined ? {} : { to: normalizeStateSelector(to) }),\n dryRun: dryRun === true,\n ...(expectRevision === undefined ? {} : { expectRevision }),\n ...(resolve === undefined ? {} : { resolve }),\n });\n}\n\nfunction normalizeStateSelector(value: unknown): StateSelector {\n const record = snapshotExactRecord(\n value,\n [\"id\", \"prefix\", \"name\"],\n \"down to\",\n refuseDownOptions\n );\n const keys = Object.keys(record);\n if (keys.length !== 1) {\n return refuseDownOptions(\"down to must contain exactly one selector key\");\n }\n // The sole OWN key. `\"id\" in record` walks the prototype chain, so a polluted\n // Object.prototype.id made `down({ to: { name: \"baseline\" } })` select the\n // inherited id and roll back to the wrong state.\n const key = keys[0]!;\n const selected = record[key];\n if (typeof selected !== \"string\" || selected.length === 0) {\n return refuseDownOptions(`down to.${key} must be a non-empty string`);\n }\n if (key === \"id\") return { id: selected };\n if (key === \"prefix\") return { prefix: selected };\n return { name: selected };\n}\n\nfunction isResolveCallback(value: unknown): value is ResolveCallback {\n return typeof value === \"function\";\n}\n\nfunction refuseDownOptions(message: string, cause?: Error): never {\n throw new MigrationError(message, VibORMErrorCode.INVALID_INPUT, { cause });\n}\n","/**\n * History-aware reset. One lock. Clear, replay from null, then one marker CAS.\n * Never re-enters applyV1.\n */\n\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\nimport { canonicalizeJson } from \"./canonical-json\";\nimport { tableExistsProbe } from \"./catalog-probes\";\nimport {\n assertTransactionalBoundaryHonored,\n classifyStoredAtomicity,\n groupContiguousAtomicity,\n refuseSqliteStepwise,\n stepStatements,\n} from \"./compile\";\nimport {\n advanceMarker,\n appendLedger,\n attemptEvents,\n ensureControlTables,\n ledgerEvent,\n markerFromPath,\n refuseIncompatibleHistory,\n sameMarker,\n unfinishedAttempts,\n} from \"./control\";\nimport type { BoundMigrationDriver } from \"./drivers\";\nimport {\n assertAllChecks,\n executeExactSql,\n executeOperations,\n} from \"./execute-dispatch\";\nimport {\n loadMigrationGraph,\n type MigrationGraph,\n type RouteEdge,\n requireStateSnapshot,\n resolveStateSelector,\n routeEdges,\n selectRoute,\n} from \"./graph\";\nimport { domainHash, HASH_DOMAIN, type Sha256 } from \"./identity\";\nimport { planLiveNamespaceReset } from \"./live-reset\";\nimport {\n commitLockedTransaction,\n resolveCommandDriver,\n runProgram,\n withLockedMigrationProducer,\n} from \"./pinned-session\";\nimport { assertLockedSinceDecision, proveLive } from \"./proof\";\nimport type { MigrationClient } from \"./push/planner\";\nimport { fingerprintLive } from \"./push-fingerprint\";\nimport { introspectManaged } from \"./push-plan\";\nimport {\n confirmedPrefix,\n openCommand,\n readCommandControl,\n refuseAmbiguousNext,\n sliceOperations,\n} from \"./resume\";\nimport { encodeSqlText } from \"./sql-blob\";\nimport { canonicalizeSqliteStorage } from \"./sqlite-storage-audit\";\nimport type { MigrationStorageWriter } from \"./storage/contract\";\nimport { encodeDispatchIdentity, encodeSqlBlob } from \"./v1-parse\";\nimport type {\n LedgerEventV1,\n MarkerPathEdgeV1,\n MigrationDispatchV1,\n MigrationMarkerV1,\n MigrationOperationV1,\n ResetPlanV1,\n ResetV1Options,\n} from \"./v1-types\";\n\nexport async function resetV1(\n client: MigrationClient,\n storage: MigrationStorageWriter,\n options: ResetV1Options = {}\n): Promise<{\n readonly preview: boolean;\n readonly path: readonly Sha256[];\n readonly tables?: readonly string[];\n}> {\n const graph = await loadMigrationGraph(storage);\n const target = resolveStateSelector(graph, options.to);\n const path = selectRoute(graph, null, target, options.via);\n const dryRun = options.dryRun === true;\n const driver = openCommand(\n client,\n graph,\n dryRun ? \"read-only\" : \"effectful\",\n \"reset()\"\n );\n if (dryRun) {\n const command = await resolveCommandDriver(client.$driver, driver);\n const plan = await planLiveNamespaceReset(client.$driver, command);\n await command.preflightSchemaRequirements(\n path.map((stateId) => requireStateSnapshot(graph, stateId)),\n (sql, params) => client.$driver._executeRaw(sql, params),\n resetProgram(\n plan,\n prepareResetReplay(\n client.$driver.supportsTransactions,\n command,\n graph,\n path\n )\n )\n );\n return {\n preview: true,\n path,\n tables: plan.dropTables.map((table) => table.name),\n };\n }\n return withLockedMigrationProducer(\n client.$driver,\n driver,\n async (pinned, command) => {\n const control = await readCommandControl(pinned, command, true);\n const { marker, ledger } = control;\n const needsBootstrap = control.presence.kind !== \"present\";\n const open = unfinishedAttempts(ledger);\n const resetAttempt =\n open.length === 1 && open[0]!.kind === \"reset-started\"\n ? open[0]!\n : undefined;\n if (open.length > 0 && !resetAttempt) {\n throw new MigrationError(\n \"An unfinished migration attempt is blocking reset\",\n VibORMErrorCode.MIGRATION_UNFINISHED_ATTEMPT\n );\n }\n const targetIdentity = `${command.target.dialect}:${command.namespace ?? \"\"}`;\n const storedResetPlan = resetAttempt\n ? matchingResetPlan(resetAttempt, graph, target, path, targetIdentity)\n : undefined;\n if (!resetAttempt) {\n refuseIncompatibleHistory(marker, ledger);\n }\n const targetSnapshot = requireStateSnapshot(graph, target);\n const targetSnapshotHash = graph.states.get(target)!.snapshotHash;\n const edges: MarkerPathEdgeV1[] = routeEdges(graph, null, path).map(\n ({ to, transition }) => ({\n stateId: to,\n transitionHash: transition.transitionHash,\n baselineBoundary: false,\n })\n );\n const resetEvent = {\n estateHash: graph.estateHash,\n snapshotHash: targetSnapshotHash,\n sqlHash: null,\n fromState: marker?.stateId ?? null,\n toState: target,\n transitionHash: null,\n direction: \"reset\",\n } as const;\n if (\n resetAttempt &&\n storedResetPlan &&\n marker &&\n resetMarkerProvesApplied(\n marker,\n graph,\n edges,\n targetSnapshotHash,\n storedResetPlan\n ) &&\n (await fingerprintLive(\n await introspectManaged(pinned, command),\n command,\n pinned\n )) === (await fingerprintLive(targetSnapshot, command, pinned))\n ) {\n await appendLedger(\n pinned,\n command,\n attemptEvents(\n { ...resetEvent, fromState: resetAttempt.fromState },\n resetAttempt.attemptId\n ).event(\"reset-applied\", \"committed\")\n );\n return { preview: false, path };\n }\n if (\n resetAttempt &&\n storedResetPlan &&\n !resetSourceMarkerMatches(\n marker,\n resetAttempt,\n storedResetPlan,\n graph.emptySnapshotHash\n )\n ) {\n throw new MigrationError(\n \"The unfinished reset source marker no longer matches its plan\",\n VibORMErrorCode.MIGRATION_MARKER_CONFLICT\n );\n }\n const hasReplayEvidence = resetAttempt\n ? ledger.some(\n (event) =>\n event.attemptId === resetAttempt.attemptId &&\n event.kind === \"reset-step-confirmed\" &&\n (event.fromState !== null ||\n event.toState !== null ||\n event.transitionHash !== null ||\n event.operationId !== null)\n )\n : false;\n const livePlan = hasReplayEvidence\n ? undefined\n : await planLiveNamespaceReset(pinned, command);\n const clearDispatches = resetProgram(livePlan, []).map((sql) =>\n dispatchForClearSql(sql)\n );\n if (\n livePlan &&\n command.target.dialect === \"mysql\" &&\n (livePlan.dropForeignKeys.length > 0 || livePlan.dropEnums.length > 0)\n ) {\n throw new MigrationError(\n \"Stepwise reset refuses clear dispatches without driver-owned pre/post proof\",\n VibORMErrorCode.MIGRATION_UNSUPPORTED_PROVIDER\n );\n }\n const planBody = {\n estateHash: graph.estateHash,\n targetIdentity,\n sourceRevision: marker?.revision ?? 0,\n sourceFingerprint: marker?.snapshotHash ?? graph.emptySnapshotHash,\n replayPath: path,\n clearDispatches,\n referencedStates: path,\n };\n const stored = storedResetPlan;\n if (stored && livePlan) {\n assertStoredResetPlan(stored, planBody);\n }\n const resetPlanHash = stored\n ? stored.resetPlanHash\n : domainHash(HASH_DOMAIN.resetPlan, canonicalizeJson(planBody));\n const plan: ResetPlanV1 = stored ?? { ...planBody, resetPlanHash };\n const prepared = prepareResetReplay(\n pinned.supportsTransactions,\n command,\n graph,\n path\n );\n const remaining = resetAttempt\n ? remainingResetReplay(graph, prepared, resetAttempt, plan, ledger)\n : prepared;\n // The statements this command runs, as apply hands its path over: the\n // dialect refuses what they would lose (S11, T5a, Neki) before effects.\n await command.preflightSchemaRequirements(\n [\n requireStateSnapshot(graph, marker?.stateId ?? null),\n ...path.map((stateId) => requireStateSnapshot(graph, stateId)),\n ],\n (sql, params) => pinned._executeRaw(sql, params),\n resetProgram(livePlan, remaining)\n );\n const begin = resetAttempt\n ? undefined\n : (producer: Parameters<typeof appendLedger>[0]) =>\n appendLedger(\n producer,\n command,\n attemptEvents(\n { ...resetEvent, resetPlan: plan },\n resetPlanHash\n ).event(\"reset-started\", \"none\")\n );\n const finish = async (producer: Parameters<typeof appendLedger>[0]) => {\n await proveLive(\n producer,\n command,\n graph,\n targetSnapshotHash,\n () => \"Reset replay did not reach the target snapshot\"\n );\n await advanceMarker(\n producer,\n command,\n graph.estateHash,\n marker,\n edges,\n targetSnapshotHash\n );\n await appendLedger(\n producer,\n command,\n attemptEvents(resetEvent, resetPlanHash).event(\n \"reset-applied\",\n \"committed\"\n )\n );\n };\n // Committed before the program, whose first group re-reads the marker.\n if (needsBootstrap) {\n await ensureControlTables(pinned, command);\n await commitLockedTransaction(pinned, command);\n }\n await runProgram(pinned, command, undefined, (producer) =>\n executeResetProgram(\n pinned,\n producer,\n command,\n marker,\n graph,\n livePlan,\n plan,\n remaining,\n resetPlanHash,\n begin,\n finish,\n client.$schema\n )\n );\n return { preview: false, path };\n }\n );\n}\n\nfunction matchingResetPlan(\n attempt: LedgerEventV1,\n graph: MigrationGraph,\n target: Sha256,\n path: readonly Sha256[],\n targetIdentity: string\n): ResetPlanV1 {\n const targetState = graph.states.get(target);\n const plan = attempt.resetPlan;\n const sourceSnapshotHash =\n attempt.fromState === null\n ? graph.emptySnapshotHash\n : graph.states.get(attempt.fromState)?.snapshotHash;\n if (\n !(targetState && plan) ||\n attempt.direction !== \"reset\" ||\n attempt.attemptId !== plan.resetPlanHash ||\n attempt.estateHash !== graph.estateHash ||\n attempt.snapshotHash !== targetState.snapshotHash ||\n attempt.toState !== target ||\n plan.estateHash !== graph.estateHash ||\n plan.targetIdentity !== targetIdentity ||\n plan.sourceFingerprint !== sourceSnapshotHash ||\n !sameIds(plan.replayPath, path) ||\n !sameIds(plan.referencedStates, path)\n ) {\n throw new MigrationError(\n \"The unfinished reset does not match the requested reset\",\n VibORMErrorCode.MIGRATION_INVALID_STATE\n );\n }\n return plan;\n}\n\nfunction resetMarkerProvesApplied(\n marker: MigrationMarkerV1,\n graph: MigrationGraph,\n edges: MigrationMarkerV1[\"path\"],\n snapshotHash: Sha256,\n plan: ResetPlanV1\n): boolean {\n const expected = markerFromPath(\n graph.estateHash,\n snapshotHash,\n edges,\n plan.sourceRevision + 1\n );\n return (\n marker.estateHash === expected.estateHash &&\n marker.stateId === expected.stateId &&\n marker.snapshotHash === expected.snapshotHash &&\n sameMarker(marker, expected)\n );\n}\n\nfunction resetSourceMarkerMatches(\n marker: MigrationMarkerV1 | null,\n attempt: LedgerEventV1,\n plan: ResetPlanV1,\n emptySnapshotHash: Sha256\n): boolean {\n return marker\n ? marker.stateId === attempt.fromState &&\n marker.revision === plan.sourceRevision &&\n marker.snapshotHash === plan.sourceFingerprint\n : attempt.fromState === null &&\n plan.sourceRevision === 0 &&\n plan.sourceFingerprint === emptySnapshotHash;\n}\n\nfunction assertStoredResetPlan(\n stored: ResetPlanV1,\n live: Omit<ResetPlanV1, \"resetPlanHash\">\n): void {\n if (stored.estateHash !== live.estateHash) {\n throw new MigrationError(\n \"A stored reset plan does not match the current estate\",\n VibORMErrorCode.MIGRATION_INVALID_STATE\n );\n }\n if (stored.targetIdentity !== live.targetIdentity) {\n throw new MigrationError(\n \"A stored reset plan does not match the current target\",\n VibORMErrorCode.MIGRATION_INVALID_STATE\n );\n }\n if (\n stored.sourceRevision !== live.sourceRevision ||\n stored.sourceFingerprint !== live.sourceFingerprint\n ) {\n throw new MigrationError(\n \"A stored reset plan does not match the current marker\",\n VibORMErrorCode.MIGRATION_INVALID_STATE\n );\n }\n if (!sameIds(stored.replayPath, live.replayPath)) {\n throw new MigrationError(\n \"A stored reset plan does not match the requested replay path\",\n VibORMErrorCode.MIGRATION_INVALID_STATE\n );\n }\n const storedIds = new Set(\n stored.clearDispatches.map((dispatch) => dispatch.dispatchId)\n );\n for (const dispatch of live.clearDispatches) {\n if (!storedIds.has(dispatch.dispatchId)) {\n throw new MigrationError(\n \"Live remaining reset clears are not in the stored reset plan\",\n VibORMErrorCode.MIGRATION_INVALID_STATE\n );\n }\n }\n}\n\nfunction sameIds(left: readonly Sha256[], right: readonly Sha256[]): boolean {\n if (left.length !== right.length) return false;\n return left.every((id, index) => id === right[index]);\n}\n\n/** The clear, in the order it runs, then the replay's statements. */\nfunction resetProgram(\n livePlan: Awaited<ReturnType<typeof planLiveNamespaceReset>> | undefined,\n replay: readonly Pick<PreparedResetReplayEdge, \"blob\" | \"operations\">[]\n): string[] {\n return [\n ...(livePlan?.clear ?? []),\n ...replay.flatMap(({ blob, operations }) =>\n stepStatements(blob, operations)\n ),\n ];\n}\n\nfunction dispatchForClearSql(sql: string): MigrationDispatchV1 {\n const bytes = encodeSqlText(sql);\n const sqlHash = encodeSqlBlob(bytes);\n return {\n dispatchId: encodeDispatchIdentity(sqlHash, 0, bytes.length, []),\n sqlHash,\n offset: 0,\n length: bytes.length,\n parameters: [],\n };\n}\n\nasync function executeResetClear(\n pinned: Parameters<typeof executeExactSql>[0],\n command: Parameters<typeof planLiveNamespaceReset>[1],\n livePlan: Awaited<ReturnType<typeof planLiveNamespaceReset>>,\n attemptId: Sha256,\n graph: MigrationGraph\n): Promise<void> {\n for (const sql of livePlan.dropForeignKeys) {\n await executeExactSql(pinned, sql);\n await confirmResetStep(pinned, command, graph, attemptId, sql);\n }\n for (const table of livePlan.dropTables) {\n const pre = tableExistsProbe(command, table.name, true);\n const post = tableExistsProbe(command, table.name, false);\n if (!(await evaluateProbe(pinned, pre))) {\n await confirmResetStep(pinned, command, graph, attemptId, table.sql);\n continue;\n }\n await executeExactSql(pinned, table.sql);\n if (!(await evaluateProbe(pinned, post))) {\n throw new MigrationError(\n `Reset clear did not drop table ${table.name}`,\n VibORMErrorCode.MIGRATION_PARTIAL_EFFECT\n );\n }\n await confirmResetStep(pinned, command, graph, attemptId, table.sql);\n }\n for (const sql of livePlan.dropEnums) {\n await executeExactSql(pinned, sql);\n await confirmResetStep(pinned, command, graph, attemptId, sql);\n }\n}\n\nasync function evaluateProbe(\n pinned: Parameters<typeof executeExactSql>[0],\n probe: ReturnType<typeof tableExistsProbe>\n): Promise<boolean> {\n const result = await pinned._executeRaw<Record<string, unknown>>(\n probe.sql,\n probe.parameters.map((parameter) =>\n parameter.kind === \"string\" ? parameter.value : null\n )\n );\n const value = Object.values(result.rows[0] ?? {})[0];\n return (\n (value === true || value === 1 || value === \"1\" || value === \"t\") ===\n probe.equals\n );\n}\n\nasync function confirmResetStep(\n pinned: Parameters<typeof appendLedger>[0],\n command: Parameters<typeof appendLedger>[1],\n graph: MigrationGraph,\n attemptId: Sha256,\n sql: string\n): Promise<void> {\n await confirmResetDispatch(\n pinned,\n command,\n graph,\n attemptId,\n dispatchForClearSql(sql)\n );\n}\n\nasync function confirmResetDispatch(\n pinned: Parameters<typeof appendLedger>[0],\n command: Parameters<typeof appendLedger>[1],\n graph: MigrationGraph,\n attemptId: Sha256,\n dispatch: MigrationDispatchV1\n): Promise<void> {\n await appendLedger(\n pinned,\n command,\n ledgerEvent({\n attemptId,\n kind: \"reset-step-confirmed\",\n estateHash: graph.estateHash,\n snapshotHash: graph.emptySnapshotHash,\n sqlHash: dispatch.sqlHash,\n fromState: null,\n toState: null,\n transitionHash: null,\n direction: \"reset\",\n operationId: null,\n dispatchId: dispatch.dispatchId,\n effectState: \"committed\",\n })\n );\n}\n\ninterface PreparedResetReplayEdge extends RouteEdge {\n readonly boundary: \"transactional\" | \"stepwise\";\n readonly operations: readonly MigrationOperationV1[];\n}\n\nfunction prepareResetReplay(\n supportsTransactions: boolean,\n command: BoundMigrationDriver,\n graph: MigrationGraph,\n path: readonly Sha256[]\n): readonly PreparedResetReplayEdge[] {\n return routeEdges(graph, null, path).map((edge) => {\n const requested = edge.transition.requestedForwardBoundary;\n const boundary = classifyStoredAtomicity(\n command,\n requested,\n edge.transition.operations,\n edge.blob\n );\n assertTransactionalBoundaryHonored(supportsTransactions, requested);\n refuseSqliteStepwise(command, requested, edge.to);\n return { ...edge, boundary, operations: edge.transition.operations };\n });\n}\n\nfunction remainingResetReplay(\n graph: MigrationGraph,\n prepared: readonly PreparedResetReplayEdge[],\n attempt: LedgerEventV1,\n plan: ResetPlanV1,\n ledger: readonly LedgerEventV1[]\n): readonly PreparedResetReplayEdge[] {\n const clearByDispatch = new Map(\n plan.clearDispatches.map((dispatch, index) => [dispatch.dispatchId, index])\n );\n const clearCommitted = new Set<number>();\n const steps = prepared.flatMap((edge, edgeIndex) =>\n edge.operations.flatMap((operation) =>\n operation.steps.map((step) => ({ edge, edgeIndex, operation, step }))\n )\n );\n const byDispatch = new Map(\n steps.map((entry, index) => [entry.step.execute.dispatchId, index])\n );\n const completed = new Set<number>();\n const announced = new Set<number>();\n let hasReplayEvidence = false;\n for (const event of ledger) {\n if (\n event.attemptId !== attempt.attemptId ||\n event.kind !== \"reset-step-confirmed\"\n ) {\n continue;\n }\n if (\n event.direction !== \"reset\" ||\n event.estateHash !== graph.estateHash ||\n !event.dispatchId\n ) {\n refuseResetProgress(\n \"Reset progress does not match its authenticated plan\"\n );\n }\n const isClear =\n event.fromState === null &&\n event.toState === null &&\n event.transitionHash === null &&\n event.operationId === null;\n if (isClear) {\n const clearIndex = clearByDispatch.get(event.dispatchId);\n if (\n clearIndex === undefined ||\n event.sqlHash !== plan.clearDispatches[clearIndex]!.sqlHash ||\n event.snapshotHash !== graph.emptySnapshotHash ||\n event.effectState !== \"committed\"\n ) {\n refuseResetProgress(\"Reset clear progress names an unknown dispatch\");\n }\n clearCommitted.add(clearIndex);\n continue;\n }\n hasReplayEvidence = true;\n const index = byDispatch.get(event.dispatchId);\n if (index === undefined) {\n refuseResetProgress(\"Reset replay progress names an unknown dispatch\");\n }\n const entry = steps[index];\n if (\n !entry ||\n event.fromState !== entry.edge.from ||\n event.toState !== entry.edge.to ||\n event.transitionHash !== entry.edge.transition.transitionHash ||\n event.snapshotHash !== entry.edge.state.snapshotHash ||\n event.sqlHash !== entry.edge.state.sqlHash ||\n event.operationId !== entry.operation.id\n ) {\n refuseResetProgress(\"Reset replay progress names an unknown dispatch\");\n }\n if (event.effectState === \"committed\") {\n completed.add(index);\n } else if (event.effectState === \"none\") {\n if (entry.step.retry === \"proven\") completed.add(index);\n else announced.add(index);\n } else {\n throw new MigrationError(\n \"Reset replay progress has an ambiguous commit outcome\",\n VibORMErrorCode.MIGRATION_AMBIGUOUS_COMMIT\n );\n }\n }\n confirmedPrefix(\n clearCommitted,\n \"Reset clear progress is not a contiguous dispatch prefix\"\n );\n if (\n hasReplayEvidence &&\n clearCommitted.size !== plan.clearDispatches.length\n ) {\n refuseResetProgress(\n \"Reset replay progress exists before the clear prefix is complete\"\n );\n }\n if (!hasReplayEvidence) return prepared;\n const completedCount = confirmedPrefix(\n completed,\n \"Reset replay progress is not a contiguous dispatch prefix\"\n );\n if (\n [...announced].some(\n (index) => !completed.has(index) && index !== completedCount\n )\n ) {\n refuseResetProgress(\"Reset replay progress is not contiguous\");\n }\n const next = steps[completedCount];\n refuseAmbiguousNext(\n next?.step,\n next?.edge.boundary,\n announced.has(completedCount),\n \"The next reset dispatch has an ambiguous commit outcome\"\n );\n const verificationEdge =\n completedCount === 0 ? undefined : steps[completedCount - 1]?.edgeIndex;\n let skipped = completedCount;\n return prepared.flatMap((edge, edgeIndex) => {\n const operationCount = edge.operations.reduce(\n (count, operation) => count + operation.steps.length,\n 0\n );\n if (skipped >= operationCount) {\n skipped -= operationCount;\n return edgeIndex === verificationEdge\n ? [{ ...edge, operations: [] }]\n : [];\n }\n const operations = sliceOperations(edge.operations, skipped);\n skipped = 0;\n return [{ ...edge, operations }];\n });\n}\n\nfunction refuseResetProgress(message: string): never {\n throw new MigrationError(message, VibORMErrorCode.MIGRATION_CORRUPTION);\n}\n\nasync function executeResetProgram(\n pinned: Parameters<typeof executeOperations>[0],\n producer: Parameters<typeof executeOperations>[0],\n command: BoundMigrationDriver,\n marker: MigrationMarkerV1 | null,\n graph: MigrationGraph,\n livePlan: Awaited<ReturnType<typeof planLiveNamespaceReset>> | undefined,\n plan: ResetPlanV1,\n replay: readonly PreparedResetReplayEdge[],\n attemptId: Sha256,\n beforeFirstEffect:\n | ((producer: Parameters<typeof appendLedger>[0]) => Promise<void>)\n | undefined,\n finish: (producer: Parameters<typeof appendLedger>[0]) => Promise<void>,\n models: MigrationClient[\"$schema\"]\n): Promise<void> {\n const groups = groupContiguousAtomicity(replay, (edge) =>\n resetProgram(undefined, [edge])\n );\n const liveClear = resetProgram(livePlan, []);\n const liveClearDispatches = new Set(\n liveClear.map((sql) => dispatchForClearSql(sql).dispatchId)\n );\n let clearPending = liveClear.length > 0 ? livePlan : undefined;\n let clearEvidencePending = livePlan !== undefined;\n let admissionPending = beforeFirstEffect;\n // `statements` are the ones the boundary runs: apply's program, so SQLite's\n // foreign keys are lifted (and proven) around a replayed recreation.\n const runBoundary = async (\n boundary: \"transactional\" | \"stepwise\",\n statements: string[],\n body: (target: Parameters<typeof appendLedger>[0]) => Promise<void>\n ) => {\n const guarded = async (target: Parameters<typeof appendLedger>[0]) => {\n // The reset's own attempt is open once admitted (or resumed): before\n // that, an open one was opened while the lock was let go.\n await assertLockedSinceDecision(\n pinned,\n target,\n command,\n marker,\n admissionPending === undefined\n );\n await body(target);\n };\n // On MySQL the reset already runs as one sequential program (`resetV1`).\n await (command.target.dialect === \"mysql\"\n ? guarded(producer)\n : runProgram(\n pinned,\n command,\n { transactional: boundary === \"transactional\", statements },\n guarded\n ));\n };\n const completeClearEvidence = async (\n target: Parameters<typeof appendLedger>[0]\n ) => {\n for (const dispatch of plan.clearDispatches) {\n if (!liveClearDispatches.has(dispatch.dispatchId)) {\n await confirmResetDispatch(target, command, graph, attemptId, dispatch);\n }\n }\n };\n const admit = async (target: Parameters<typeof appendLedger>[0]) => {\n const pending = admissionPending;\n if (!pending) return;\n admissionPending = undefined;\n await pending(target);\n };\n if (clearPending && groups[0]?.boundary === \"stepwise\") {\n const clear = clearPending;\n clearPending = undefined;\n await runBoundary(\n \"transactional\",\n resetProgram(clear, []),\n async (target) => {\n await admit(target);\n await executeResetClear(target, command, clear, attemptId, graph);\n await completeClearEvidence(target);\n clearEvidencePending = false;\n }\n );\n }\n if (!clearPending && groups[0]?.boundary === \"stepwise\" && admissionPending) {\n await runBoundary(\"transactional\", [], admit);\n }\n if (groups.length === 0) {\n const statements = resetProgram(clearPending, []);\n await runBoundary(\"transactional\", statements, async (target) => {\n await admit(target);\n if (clearPending) {\n await executeResetClear(\n target,\n command,\n clearPending,\n attemptId,\n graph\n );\n }\n if (clearEvidencePending) {\n await completeClearEvidence(target);\n clearEvidencePending = false;\n }\n await finish(target);\n });\n return;\n }\n for (const [index, group] of groups.entries()) {\n const statements = resetProgram(clearPending, group.items);\n await runBoundary(group.boundary, statements, async (target) => {\n await admit(target);\n if (clearPending) {\n await executeResetClear(\n target,\n command,\n clearPending,\n attemptId,\n graph\n );\n clearPending = undefined;\n }\n if (clearEvidencePending) {\n await completeClearEvidence(target);\n clearEvidencePending = false;\n }\n for (const edge of group.items) {\n await executeResetReplayEdge(\n target,\n command,\n graph,\n edge,\n attemptId,\n models\n );\n }\n if (index === groups.length - 1) await finish(target);\n });\n }\n}\n\nasync function executeResetReplayEdge(\n pinned: Parameters<typeof executeOperations>[0],\n command: BoundMigrationDriver,\n graph: MigrationGraph,\n edge: PreparedResetReplayEdge,\n attemptId: Sha256,\n models: MigrationClient[\"$schema\"]\n): Promise<void> {\n const { from, to, transition, state, blob, boundary, operations } = edge;\n const events = attemptEvents(\n {\n estateHash: graph.estateHash,\n snapshotHash: state.snapshotHash,\n sqlHash: state.sqlHash,\n fromState: from,\n toState: to,\n transitionHash: transition.transitionHash,\n direction: \"reset\",\n },\n attemptId\n );\n await executeOperations(\n pinned,\n blob,\n operations,\n boundary,\n (progress, effect, failure) =>\n appendLedger(\n pinned,\n command,\n events.event(\"reset-step-confirmed\", effect, progress, failure)\n ),\n command.namespace\n );\n // Replayed manual SQL is canonicalized exactly as apply canonicalizes it.\n await canonicalizeSqliteStorage(\n pinned,\n operations,\n models,\n requireStateSnapshot(graph, to)\n );\n await assertAllChecks(\n pinned,\n blob,\n state.destinationChecks,\n command.namespace,\n \"Reset replay failed destination checks\"\n );\n}\n","/**\n * V1 operator commands: status, verify, log, baseline, reanchor, prune,\n * down, resolve, reset.\n * Status/verify/log are read-only and never bootstrap missing control tables.\n */\n\nimport type { AnyDriver } from \"../drivers/driver\";\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\nimport { admitLiveMigrationCapability } from \"./admission\";\nimport {\n type InvalidIndex,\n qualifiedName,\n readInvalidIndexes,\n} from \"./catalog-probes\";\nimport {\n assertTransactionalBoundaryHonored,\n classifyStoredAtomicity,\n groupContiguousAtomicity,\n refuseSqliteStepwise,\n stepStatements,\n} from \"./compile\";\nimport {\n advanceMarker,\n appendLedger,\n attemptEvents,\n ensureControlTables,\n isTableMissing,\n ledgerEvent,\n type MigrationControlRead,\n readControlState,\n refuseIncompatibleHistory,\n refusePartialControl,\n unfinishedAttempts,\n} from \"./control\";\nimport { diff, isDestructiveOperation } from \"./differ\";\nimport { type NormalizedDownOptions, normalizeDownOptions } from \"./down-input\";\nimport {\n assertAllChecks,\n evaluateAllChecks,\n executeOperations,\n} from \"./execute-dispatch\";\nimport {\n loadMigrationGraph,\n type MigrationGraph,\n parentTransition,\n requireStateSnapshot,\n resolveStateSelector,\n routeEdges,\n selectRoute,\n statesFrom,\n} from \"./graph\";\nimport type { Sha256 } from \"./identity\";\nimport {\n commitLockedTransaction,\n letLockGo,\n resolveCommandDriver,\n runProgram,\n withLockedMigrationProducer,\n} from \"./pinned-session\";\nimport {\n assertLockedSinceDecision,\n assertNoDrift,\n markerStanding,\n proveLive,\n} from \"./proof\";\nimport { renderMigrationReview } from \"./public-view\";\nimport { getPushMigrationDriver, type MigrationClient } from \"./push/planner\";\nimport { fingerprintLive } from \"./push-fingerprint\";\nimport { introspectManaged } from \"./push-plan\";\nimport { approveDestructiveOperations } from \"./resolver\";\nimport { openCommand, readCommandControl, remainingSteps } from \"./resume\";\nimport { sliceDispatch } from \"./sql-blob\";\nimport { canonicalizeSqliteStorage } from \"./sqlite-storage-audit\";\nimport type {\n MigrationStorageReader,\n MigrationStorageWriter,\n} from \"./storage/contract\";\nimport type {\n AmbiguousChange,\n DiffOperation,\n ResolveCallback,\n SchemaSnapshot,\n} from \"./types\";\nimport type {\n BaselineOptions,\n DownPreviewEdgeV1,\n DownV1Options,\n DownV1Result,\n LedgerEventV1,\n MarkerPathEdgeV1,\n MigrationMarkerV1,\n ReanchorOptions,\n ResolveV1Options,\n StateSelector,\n} from \"./v1-types\";\n\nexport { resetV1 } from \"./reset-v1\";\n\nexport interface StatusV1Result {\n readonly control: \"absent\" | \"present\";\n readonly marker: MigrationMarkerV1 | null;\n readonly pending: readonly Sha256[];\n readonly unfinished: boolean;\n /**\n * Present only when the marker names a state this estate does not hold:\n * `\"ahead\"` when its arrival path leaves this history after a state it holds\n * (newer code migrated the database), `\"unknown\"` when nothing on that path\n * belongs here. `pending` is then empty.\n */\n readonly markerState?: \"ahead\" | \"unknown\";\n /** Present only when a managed table carries an INVALID index (PostgreSQL). */\n readonly invalidIndexes?: readonly InvalidIndex[];\n /**\n * The latest `failed` ledger event, present once a rolled-back attempt left\n * one: its `toState`, `dispatchId` and `failure` say what failed and why.\n */\n readonly lastFailure?: LedgerEventV1;\n}\n\nexport async function statusV1(\n client: MigrationClient,\n storage: MigrationStorageReader\n): Promise<StatusV1Result> {\n const graph = await loadMigrationGraph(storage);\n const driver = openCommand(client, graph, \"read-only\", \"status()\");\n const command = await resolveCommandDriver(client.$driver, driver);\n const control = await readCommandControl(client.$driver, command);\n const invalidIndexes = await readInvalidIndexes(client.$driver, command);\n const listed = invalidIndexes.length === 0 ? {} : { invalidIndexes };\n if (control.presence.kind !== \"present\") {\n return {\n control: \"absent\",\n marker: null,\n pending: [...graph.roots],\n unfinished: false,\n ...listed,\n };\n }\n const { marker, ledger } = control;\n const unfinished = unfinishedAttempts(ledger).length > 0;\n let lastFailure: LedgerEventV1 | undefined;\n for (const event of ledger) {\n if (event.kind === \"failed\") lastFailure = event;\n }\n const standing = markerStanding(graph, marker);\n let pending: Sha256[] = [];\n if (standing === \"known\" && graph.leaves.length === 1) {\n const leaf = graph.leaves[0]!;\n if ((marker?.stateId ?? null) !== leaf) {\n pending = [...selectRoute(graph, marker?.stateId ?? null, leaf)];\n }\n }\n return {\n control: \"present\",\n marker,\n pending,\n unfinished,\n ...(standing === \"known\" ? {} : { markerState: standing }),\n ...listed,\n ...(lastFailure ? { lastFailure } : {}),\n };\n}\n\nexport interface VerifyV1Result {\n readonly ok: boolean;\n /** Present, with `ok: false`, when the marker names a state this estate does not hold. */\n readonly markerState?: \"ahead\" | \"unknown\";\n}\n\nexport async function verifyV1(\n client: MigrationClient,\n storage: MigrationStorageReader\n): Promise<VerifyV1Result> {\n const graph = await loadMigrationGraph(storage);\n const driver = openCommand(client, graph, \"effectful\", \"verify()\");\n return withLockedMigrationProducer(\n client.$driver,\n driver,\n async (pinned, command) => {\n const control = await readCommandControl(pinned, command);\n if (control.presence.kind !== \"present\") {\n throw new MigrationError(\n \"verify requires present control tables\",\n VibORMErrorCode.MIGRATION_NOT_FOUND\n );\n }\n const { marker } = control;\n if (!marker) {\n throw new MigrationError(\n \"verify requires a migration marker\",\n VibORMErrorCode.MIGRATION_NOT_FOUND\n );\n }\n const standing = markerStanding(graph, marker);\n if (standing !== \"known\") return { ok: false, markerState: standing };\n const markedSnapshot = requireStateSnapshot(graph, marker.stateId);\n await command.preflightSchemaRequirements(\n [markedSnapshot],\n (sql, params) => pinned._executeRaw(sql, params),\n []\n );\n await assertNoDrift(pinned, command, graph, marker);\n return { ok: true };\n }\n );\n}\n\nexport async function logV1(\n client: MigrationClient\n): Promise<readonly LedgerEventV1[]> {\n const driver = getPushMigrationDriver(client);\n admitLiveMigrationCapability(driver, \"read-only\", \"log()\");\n const command = await resolveCommandDriver(client.$driver, driver);\n const control = await readControlState(client.$driver, command);\n if (control.presence.kind !== \"present\") {\n refusePartialControl(control.presence);\n throw new MigrationError(\n \"log requires present control tables\",\n VibORMErrorCode.MIGRATION_NOT_FOUND\n );\n }\n return control.ledger;\n}\n\nexport async function baselineV1(\n client: MigrationClient,\n storage: MigrationStorageReader,\n options: BaselineOptions\n): Promise<{ readonly stateId: Sha256 }> {\n const graph = await loadMigrationGraph(storage);\n const driver = openCommand(client, graph, \"effectful\", \"baseline()\");\n const target = resolveStateSelector(graph, options.to);\n const path = selectRoute(graph, null, target, options.via);\n return withLockedMigrationProducer(\n client.$driver,\n driver,\n async (pinned, command) => {\n const control = await readCommandControl(pinned, command, true);\n const { marker, ledger } = control;\n if (marker || unfinishedAttempts(ledger).length > 0) {\n throw new MigrationError(\n \"baseline requires an unmarked database without an unfinished attempt\",\n VibORMErrorCode.MIGRATION_INVALID_STATE\n );\n }\n refuseIncompatibleHistory(marker, ledger);\n assertStructuralRoute(graph, path, \"baseline\");\n await command.preflightSchemaRequirements(\n [requireStateSnapshot(graph, target)],\n (sql, params) => pinned._executeRaw(sql, params),\n []\n );\n // Committed before the proof, which then runs under the lock taken\n // again, as does the marker it publishes.\n if (control.presence.kind !== \"present\") {\n await ensureControlTables(pinned, command);\n await commitLockedTransaction(pinned, command);\n await assertLockedSinceDecision(pinned, pinned, command, null);\n }\n await proveLive(\n pinned,\n command,\n graph,\n graph.states.get(target)!.snapshotHash,\n async (differences) =>\n `baseline requires exact live equality with the target snapshot. Differences: ${await differences()}`\n );\n await adoptRoute(pinned, command, graph, path, null);\n return { stateId: target };\n }\n );\n}\n\n/**\n * Plan T3: after a restore left this history older than the database, moves\n * a marker naming a state the history lacks onto the one known state the live\n * schema matches, with baseline's proof and a baseline boundary. `to` adopts\n * the state it names instead: the consent several matching states need.\n */\nexport async function reanchorV1(\n client: MigrationClient,\n storage: MigrationStorageReader,\n options: ReanchorOptions = {}\n): Promise<{ readonly stateId: Sha256 }> {\n const graph = await loadMigrationGraph(storage);\n const driver = openCommand(client, graph, \"effectful\", \"reanchor()\");\n const named = options.to && resolveStateSelector(graph, options.to);\n return withLockedMigrationProducer(\n client.$driver,\n driver,\n async (pinned, command) => {\n const { marker, ledger } = await readCommandControl(pinned, command);\n if (!marker || markerStanding(graph, marker) === \"known\") {\n throw new MigrationError(\n \"reanchor moves only a marker naming a state this history does not hold; apply, verify and baseline handle the others\",\n VibORMErrorCode.MIGRATION_INVALID_STATE\n );\n }\n if (unfinishedAttempts(ledger).length > 0) {\n throw new MigrationError(\n \"reanchor refuses while an attempt is unfinished: resolve it first\",\n VibORMErrorCode.MIGRATION_INVALID_STATE\n );\n }\n const live = await introspectManaged(pinned, command);\n const liveHash = await fingerprintLive(live, command, pinned);\n const matches: Sha256[] = [];\n for (const stateId of named ? [named] : graph.states.keys()) {\n const snapshot = requireStateSnapshot(graph, stateId);\n if ((await fingerprintLive(snapshot, command, pinned)) === liveHash) {\n matches.push(stateId);\n }\n }\n const reference =\n named ?? (graph.leaves.length === 1 ? graph.leaves[0] : undefined);\n if (matches.length === 0) {\n const differences = reference\n ? ` Differences from ${reference}: ${JSON.stringify(await diff(live, requireStateSnapshot(graph, reference)))}`\n : \"\";\n throw new MigrationError(\n `reanchor found no state of this history that the live schema matches.${differences}`,\n VibORMErrorCode.MIGRATION_DRIFT\n );\n }\n if (matches.length > 1) {\n throw new MigrationError(\n `Several states of this history match the live schema (${matches.join(\", \")}), and equal schemas never say which data the database holds: name one with reanchor({ to }).`,\n VibORMErrorCode.MIGRATION_INVALID_STATE\n );\n }\n const target = matches[0]!;\n if (marker.path.some((edge) => edge.stateId === target)) {\n throw new MigrationError(\n `reanchor refuses ${target}: the marker passed through it, so the transitions lost after it changed no schema and may have moved data. Regenerate the lost states from the same documents instead: their ids come back identical.`,\n VibORMErrorCode.MIGRATION_INVALID_STATE\n );\n }\n const path = selectRoute(graph, null, target, options.via);\n assertStructuralRoute(graph, path, \"reanchor\");\n await command.preflightSchemaRequirements(\n [requireStateSnapshot(graph, target)],\n (sql, params) => pinned._executeRaw(sql, params),\n []\n );\n await adoptRoute(pinned, command, graph, path, marker);\n return { stateId: target };\n }\n );\n}\n\n/** Baseline's proof of a root route: no manual, opaque or data-only edge. */\nfunction assertStructuralRoute(\n graph: MigrationGraph,\n path: readonly Sha256[],\n command: \"baseline\" | \"reanchor\"\n): void {\n for (const { from, transition, state } of routeEdges(graph, null, path)) {\n const parentSnapshot =\n from === null\n ? graph.emptySnapshotHash\n : graph.states.get(from)?.snapshotHash;\n if (\n transition.operations.some(\n (operation) =>\n operation.origin === \"manual\" || operation.risk === \"opaque\"\n ) ||\n parentSnapshot === state.snapshotHash\n ) {\n throw new MigrationError(\n `${command} refuses a path containing manual, opaque, or data-only transitions`,\n VibORMErrorCode.MIGRATION_INVALID_STATE\n );\n }\n }\n}\n\n/**\n * Publishes the marker re-rooted on `path`, its first edge a baseline\n * boundary, in place of `current` (compare-and-swap), with the event that\n * says so: `baselined` without a marker before, `reanchored` with one. In one\n * transaction when the producer can.\n */\nasync function adoptRoute(\n pinned: AnyDriver,\n command: Parameters<typeof appendLedger>[1],\n graph: MigrationGraph,\n path: readonly Sha256[],\n current: MigrationMarkerV1 | null\n): Promise<void> {\n const edges = routeEdges(graph, null, path).map(\n ({ to, transition }, index) => ({\n stateId: to,\n transitionHash: transition.transitionHash,\n baselineBoundary: index === 0,\n })\n );\n const target = path.at(-1)!;\n const publish = async (producer: AnyDriver) => {\n const next = await advanceMarker(\n producer,\n command,\n graph.estateHash,\n current,\n edges,\n graph.states.get(target)!.snapshotHash\n );\n await appendLedger(\n producer,\n command,\n ledgerEvent({\n attemptId: next.pathHash,\n kind: current ? \"reanchored\" : \"baselined\",\n estateHash: graph.estateHash,\n snapshotHash: next.snapshotHash,\n sqlHash: null,\n fromState: current?.stateId ?? null,\n toState: target,\n transitionHash: null,\n direction: \"baseline\",\n operationId: null,\n dispatchId: null,\n effectState: \"none\",\n })\n );\n };\n if (pinned.supportsTransactions) {\n await pinned.withTransaction((transaction) => publish(transaction));\n } else {\n await publish(pinned);\n }\n}\n\nexport interface PruneOptions {\n /** The authored checkpoint (`generate({ from: null })`) to keep history from. */\n readonly checkpoint: StateSelector;\n /** A fresh history: the source is never changed. */\n readonly into: MigrationStorageWriter;\n}\n\nexport interface PruneResult {\n /** The states `into` now holds from this history. */\n readonly states: readonly Sha256[];\n}\n\n/**\n * Plan T4: copies the checkpoint and the states `statesFrom` keeps after it\n * into a fresh history. Storage stays append-only, so pruning is a copy: what\n * it leaves out is what `check()` would report as orphaned, once the earlier\n * manifests were gone. A marker on a dropped state is moved by `reanchor()`.\n */\nexport async function pruneV1(\n storage: MigrationStorageReader,\n options: PruneOptions\n): Promise<PruneResult> {\n const graph = await loadMigrationGraph(storage);\n const kept = statesFrom(\n graph,\n resolveStateSelector(graph, options.checkpoint)\n );\n const { into } = options;\n await into.publishEstate(await present(storage.readEstate(), \"estate.json\"));\n for (const id of kept) {\n const { snapshotHash, sqlHash } = graph.states.get(id)!;\n const snapshot = storage.readSnapshot(snapshotHash);\n await into.publishSnapshot(snapshotHash, await present(snapshot, id));\n await into.publishSql(sqlHash, graph.sql.get(sqlHash)!);\n await into.publishState(id, await present(storage.readState(id), id));\n }\n return { states: [...kept] };\n}\n\n/** Bytes the loaded graph authenticated, gone by the time prune copies them. */\nasync function present(\n read: Promise<Uint8Array | null>,\n artifact: string\n): Promise<Uint8Array> {\n const bytes = await read;\n if (!bytes) {\n throw new MigrationError(\n `${artifact} vanished from the history while prune copied it`,\n VibORMErrorCode.MIGRATION_CORRUPTION\n );\n }\n return bytes;\n}\n\nexport async function downV1(\n client: MigrationClient,\n storage: MigrationStorageReader,\n options: DownV1Options = {}\n): Promise<DownV1Result> {\n const request = normalizeDownOptions(options);\n const graph = await loadMigrationGraph(storage);\n const driver = openCommand(\n client,\n graph,\n request.dryRun ? \"read-only\" : \"effectful\",\n \"down()\"\n );\n if (request.dryRun) {\n const producer = client.$driver;\n const command = await resolveCommandDriver(producer, driver);\n const { close, removed, refusal } = await planRollback(\n producer,\n command,\n graph,\n await readCommandControl(producer, command),\n request,\n true\n );\n return {\n path: close\n ? [close.item.edge.stateId]\n : removed.map((edge) => edge.stateId),\n preview: true,\n edges: [...removed]\n .reverse()\n .map((edge) => previewRollbackEdge(graph, edge)),\n refusal,\n };\n }\n return withLockedMigrationProducer(\n client.$driver,\n driver,\n async (pinned, command) => {\n const control = await readCommandControl(pinned, command);\n const { close, removed, run } = await planRollback(\n pinned,\n command,\n graph,\n control,\n request,\n false\n );\n if (close) {\n await command.preflightSchemaRequirements(\n [requireStateSnapshot(graph, close.item.nextState)],\n (sql, params) => pinned._executeRaw(sql, params),\n []\n );\n await runProgram(pinned, command, undefined, (producer) =>\n closeCompletedRollback(\n producer,\n command,\n graph,\n close.item,\n close.attempt,\n control.ledger,\n control.marker\n )\n );\n return { path: [close.item.edge.stateId], preview: false };\n }\n if (!run) return { path: [], preview: false };\n const { prepared, attempt } = run;\n const statementsOf = (item: PreparedRollback) =>\n stepStatements(item.blob, item.rollback.operations);\n let current = run.marker;\n for (const group of groupContiguousAtomicity(prepared, statementsOf)) {\n await runProgram(\n pinned,\n command,\n {\n transactional: group.boundary === \"transactional\",\n statements: group.items.flatMap(statementsOf),\n },\n async (producer) => {\n // Only the attempt `down` resumes is its own: any other one open\n // now was opened while the lock was let go.\n await assertLockedSinceDecision(\n pinned,\n producer,\n command,\n current,\n group.items[0] === prepared[0] && attempt !== undefined\n );\n for (const item of group.items) {\n current = await executeRollbackEdge(\n producer,\n command,\n graph,\n item,\n current,\n item === prepared[0] ? attempt : undefined,\n control.ledger,\n client.$schema\n );\n }\n }\n );\n }\n return { path: removed.map((edge) => edge.stateId), preview: false };\n }\n );\n}\n\ntype PreparedRollback = ReturnType<typeof prepareRollbackEdge>;\n\ninterface RollbackPlan {\n /** The first refusal of a preview; `down` throws it instead. */\n readonly refusal: { code: string; message: string } | null;\n /** A rollback that finished before it was recorded: `down` closes it. */\n readonly close?: {\n readonly item: PreparedRollback;\n readonly attempt: LedgerEventV1;\n };\n /** The marker edges `down` removes. */\n readonly removed: MigrationMarkerV1[\"path\"];\n /** Present when `down` reverses `removed`, newest edge first. */\n readonly run?: {\n readonly marker: MigrationMarkerV1;\n readonly prepared: readonly PreparedRollback[];\n readonly attempt: LedgerEventV1 | undefined;\n };\n}\n\n/**\n * What `down` decides before its first effect, read-only and in its order, so\n * the preview refuses where `down` refuses. `previewing` returns a refusal of\n * the attempt or of the checks as data (`down` throws it); without one, a\n * preview still names the edges.\n */\nasync function planRollback(\n producer: AnyDriver,\n command: Parameters<typeof appendLedger>[1],\n graph: MigrationGraph,\n { marker, ledger }: MigrationControlRead,\n request: NormalizedDownOptions,\n previewing: boolean\n): Promise<RollbackPlan> {\n assertExpectedRevision(marker, request);\n let refusal: RollbackPlan[\"refusal\"] = null;\n let attempt: LedgerEventV1 | undefined;\n try {\n attempt = admitRollbackAttempt(ledger);\n } catch (error) {\n if (!previewing) throw error;\n refusal = refusalOf(error);\n }\n const { supportsTransactions } = producer;\n if (attempt && attempt.toState === (marker?.stateId ?? null)) {\n const item = prepareRollbackAttempt(\n graph,\n command,\n supportsTransactions,\n attempt\n );\n return { refusal, close: { item, attempt }, removed: [] };\n }\n if (!marker) {\n // `down` refuses the attempt before it finds nothing to roll back.\n if (refusal) return { refusal, removed: [] };\n throw new MigrationError(\n \"Nothing to roll back\",\n VibORMErrorCode.MIGRATION_NOT_FOUND\n );\n }\n const removed = rollbackSlice(graph, marker, request);\n // `down` checks nothing more when it has nothing to roll back.\n if (refusal || removed.length === 0) return { refusal, removed };\n try {\n const reverse = [...removed].reverse();\n for (const edge of reverse) assertReversibleEdge(graph, edge);\n const prepared = reverse.map((edge) =>\n prepareRollbackEdge(graph, command, supportsTransactions, edge)\n );\n await command.preflightSchemaRequirements(\n [\n requireStateSnapshot(graph, marker.stateId),\n ...prepared.map((item) => requireStateSnapshot(graph, item.nextState)),\n ],\n (sql, params) => producer._executeRaw(sql, params),\n prepared.flatMap((item) =>\n stepStatements(item.blob, item.rollback.operations)\n )\n );\n if (attempt) {\n assertResumesSelectedPath(\n graph,\n command,\n supportsTransactions,\n attempt,\n prepared[0]!\n );\n } else {\n await assertNoDrift(producer, command, graph, marker);\n }\n await approveRollbackLosses(\n producer,\n command,\n graph,\n prepared,\n request.resolve\n );\n return { refusal, removed, run: { marker, prepared, attempt } };\n } catch (error) {\n if (!previewing) throw error;\n return { refusal: refusalOf(error), removed };\n }\n}\n\nexport async function resolveV1(\n client: MigrationClient,\n storage: MigrationStorageReader,\n options: ResolveV1Options\n): Promise<{ readonly outcome: ResolveV1Options[\"outcome\"] }> {\n const graph = await loadMigrationGraph(storage);\n const driver = openCommand(client, graph, \"effectful\", \"resolve()\");\n return withLockedMigrationProducer(\n client.$driver,\n driver,\n async (pinned, command) => {\n const { ledger } = await readCommandControl(pinned, command);\n const open = unfinishedAttempts(ledger);\n if (open.length !== 1) {\n throw new MigrationError(\n open.length === 0\n ? \"resolve requires an unfinished attempt\"\n : \"resolve requires exactly one unfinished attempt\",\n VibORMErrorCode.MIGRATION_INVALID_STATE\n );\n }\n const attempt = open[0]!;\n if (attempt.kind === \"reset-started\") {\n throw new MigrationError(\n \"An unfinished reset can only be resumed by reset()\",\n VibORMErrorCode.MIGRATION_INVALID_STATE\n );\n }\n if (attempt.direction === \"rollback\") {\n throw new MigrationError(\n \"An unfinished rollback can only be resumed by down()\",\n VibORMErrorCode.MIGRATION_INVALID_STATE\n );\n }\n const to = attempt.toState;\n const from = attempt.fromState;\n if (!to) {\n throw new MigrationError(\n \"Unfinished attempt is missing its target state\",\n VibORMErrorCode.MIGRATION_CORRUPTION\n );\n }\n const state = graph.states.get(to);\n if (!state) {\n throw new MigrationError(\n \"Unfinished attempt target is absent from the estate\",\n VibORMErrorCode.MIGRATION_CORRUPTION\n );\n }\n const blob = graph.sql.get(state.sqlHash)!;\n const transition = parentTransition(graph, from, to);\n const destSnapshot = requireStateSnapshot(graph, to);\n const originSnapshot = requireStateSnapshot(graph, from);\n const statements = stepStatements(blob, transition.operations);\n // Only a retry runs the transition: its program is refused as apply's.\n await command.preflightSchemaRequirements(\n [originSnapshot, destSnapshot],\n (sql, params) => pinned._executeRaw(sql, params),\n options.outcome === \"retry\" ? statements : []\n );\n if (options.outcome !== \"retry\") {\n await repairInvalidIndexes(\n pinned,\n command,\n statements,\n options.outcome === \"complete\" ? destSnapshot : originSnapshot\n );\n }\n const liveHash = await fingerprintLive(\n await introspectManaged(pinned, command),\n command,\n pinned\n );\n const destHolds =\n liveHash === (await fingerprintLive(destSnapshot, command, pinned)) &&\n (await evaluateAllChecks(\n pinned,\n blob,\n state.destinationChecks,\n command.namespace\n ));\n const originHolds =\n liveHash === (await fingerprintLive(originSnapshot, command, pinned)) &&\n (await evaluateAllChecks(\n pinned,\n blob,\n transition.originChecks,\n command.namespace\n ));\n const manualOpaque = transition.operations.some(\n (operation) =>\n operation.origin === \"manual\" &&\n operation.steps.some((step) => step.retry === \"opaque\")\n );\n // Marking an outcome is one transaction where the producer has one.\n const record = { transactional: true, statements: [] };\n if (options.outcome === \"complete\") {\n if (\n !destHolds ||\n (manualOpaque && state.destinationChecks.length === 0)\n ) {\n throw new MigrationError(\n \"resolve cannot mark complete without destination proof\",\n VibORMErrorCode.MIGRATION_INVALID_STATE\n );\n }\n await runProgram(pinned, command, record, async (producer) => {\n // Completing manual SQL canonicalizes what it stored, as apply does.\n await canonicalizeSqliteStorage(\n producer,\n transition.operations,\n client.$schema,\n destSnapshot\n );\n await finishResolve(producer, command, graph, attempt, \"applied\", to);\n });\n return { outcome: \"complete\" };\n }\n if (options.outcome === \"rolled-back\") {\n refuseOpaqueEffect(transition, blob, attempt, ledger);\n if (\n !originHolds ||\n (manualOpaque && transition.originChecks.length === 0)\n ) {\n throw new MigrationError(\n \"resolve cannot mark rolled back without origin proof\",\n VibORMErrorCode.MIGRATION_INVALID_STATE\n );\n }\n await runProgram(pinned, command, record, (producer) =>\n finishResolve(producer, command, graph, attempt, \"rolled-back\", from)\n );\n return { outcome: \"rolled-back\" };\n }\n if (manualOpaque) {\n throw new MigrationError(\n \"resolve cannot retry an opaque dispatch without origin or destination proof\",\n VibORMErrorCode.MIGRATION_INVALID_STATE\n );\n }\n if (\n transition.operations.some((operation) =>\n operation.steps.some((step) => step.retry === \"opaque\")\n ) &&\n !originHolds\n ) {\n throw new MigrationError(\n \"resolve cannot retry a generated structural transition except from the origin\",\n VibORMErrorCode.MIGRATION_INVALID_STATE\n );\n }\n assertTransactionalBoundaryHonored(\n pinned.supportsTransactions,\n transition.requestedForwardBoundary\n );\n const boundary = classifyStoredAtomicity(\n command,\n transition.requestedForwardBoundary,\n transition.operations,\n blob\n );\n // A recreation is refused without a transaction: its lift is unproven.\n await runProgram(\n pinned,\n command,\n { transactional: boundary === \"transactional\", statements },\n async (producer) => {\n await executeOperations(\n producer,\n blob,\n transition.operations,\n boundary,\n undefined,\n command.namespace,\n { fromState: from, toState: to }\n );\n await assertAllChecks(\n producer,\n blob,\n state.destinationChecks,\n command.namespace,\n \"Retry did not reach the destination\"\n );\n await proveLive(\n producer,\n command,\n graph,\n state.snapshotHash,\n () => \"Retry did not reach the destination\"\n );\n await finishResolve(producer, command, graph, attempt, \"applied\", to);\n }\n );\n return { outcome: \"retry\" };\n }\n );\n}\n\n/**\n * The index a `CREATE`/`DROP`/`REINDEX INDEX CONCURRENTLY` statement names,\n * schema prefix dropped. An unnamed `CREATE INDEX CONCURRENTLY ON t` is never\n * matched; its PG-chosen name is left to the V11023 refusal. (DROP INDEX\n * CONCURRENTLY takes one name only.)\n */\nconst CONCURRENT_INDEX_NAME =\n /\\bINDEX\\s+CONCURRENTLY\\s+(?:IF\\s+(?:NOT\\s+)?EXISTS\\s+)?(?!ON\\b)(?:(?:\"(?:[^\"]|\"\")+\"|[A-Za-z_][\\w$]*)\\s*\\.\\s*)?(\"(?:[^\"]|\"\")+\"|[A-Za-z_][\\w$]*)/gi;\n/** The suffix of the `_ccnew`/`_ccold` copy an interrupted `REINDEX CONCURRENTLY` leaves INVALID. */\nconst REINDEX_REMNANT = /^_cc(?:new|old)\\d*$/;\n\n/**\n * Repairs the INVALID indexes the unfinished attempt's own CONCURRENTLY\n * statements left behind — the index each names, and the `<name>_ccnew` /\n * `<name>_ccold` remnant of an interrupted `REINDEX CONCURRENTLY` — towards the snapshot the\n * requested outcome asserts: an index that snapshot declares is rebuilt, any\n * other is dropped, both CONCURRENTLY so writes keep flowing. An invalid index\n * the attempt never named (another session's build, still running perhaps) is\n * left alone, and the proof that follows refuses on it with V11023. An invalid\n * index belongs to neither state, so the repair cannot turn a false proof true.\n */\nasync function repairInvalidIndexes(\n pinned: Parameters<typeof appendLedger>[0],\n command: Parameters<typeof appendLedger>[1],\n statements: readonly string[],\n expected: SchemaSnapshot\n): Promise<void> {\n const named = statements.flatMap(concurrentIndexNames);\n if (named.length === 0) return;\n for (const { table, index } of await readInvalidIndexes(pinned, command)) {\n if (\n !named.some(\n (name) =>\n index === name ||\n (index.startsWith(name) &&\n REINDEX_REMNANT.test(index.slice(name.length)))\n )\n )\n continue;\n const rebuild = expected.tables.some(\n (declared) =>\n declared.name === table &&\n declared.indexes.some((item) => item.name === index)\n );\n await pinned._executeRaw(\n `${rebuild ? \"REINDEX INDEX\" : \"DROP INDEX\"} CONCURRENTLY ${qualifiedName(command, index)}`\n );\n }\n}\n\n/** The indexes a statement's `INDEX CONCURRENTLY` clauses name. */\nfunction concurrentIndexNames(text: string): string[] {\n return [...text.matchAll(CONCURRENT_INDEX_NAME)].map(([, name = \"\"]) =>\n name.startsWith('\"')\n ? name.slice(1, -1).replaceAll('\"\"', '\"')\n : name.toLowerCase()\n );\n}\n\nasync function finishResolve(\n pinned: AnyDriver,\n command: Parameters<typeof appendLedger>[1],\n graph: MigrationGraph,\n attempt: LedgerEventV1,\n kind: \"applied\" | \"rolled-back\",\n to: Sha256 | null\n): Promise<void> {\n const { marker } = await readCommandControl(pinned, command);\n if (kind === \"applied\" && to && marker?.stateId !== to) {\n const transition = parentTransition(graph, attempt.fromState, to);\n await advanceMarker(\n pinned,\n command,\n graph.estateHash,\n marker,\n [\n ...(marker?.path ?? []),\n {\n stateId: to,\n transitionHash: attempt.transitionHash ?? transition.transitionHash,\n baselineBoundary: false,\n },\n ],\n graph.states.get(to)!.snapshotHash\n );\n }\n if (kind === \"rolled-back\" && marker && marker.stateId === attempt.toState) {\n const nextPath = marker.path.slice(0, -1);\n await advanceMarker(\n pinned,\n command,\n graph.estateHash,\n marker,\n nextPath,\n snapshotHashOf(graph, nextPath.at(-1)?.stateId ?? null)\n );\n }\n await appendLedger(\n pinned,\n command,\n ledgerEvent({\n attemptId: attempt.attemptId,\n kind: \"resolved\",\n estateHash: graph.estateHash,\n snapshotHash: snapshotHashOf(graph, to),\n sqlHash: attempt.sqlHash,\n fromState: attempt.fromState,\n toState: to,\n transitionHash: attempt.transitionHash,\n direction: \"resolve\",\n operationId: null,\n dispatchId: null,\n effectState: \"none\",\n })\n );\n}\n\n/** The snapshot a state, or the empty origin, authenticates. */\nfunction snapshotHashOf(graph: MigrationGraph, stateId: Sha256 | null): Sha256 {\n return stateId\n ? graph.states.get(stateId)!.snapshotHash\n : graph.emptySnapshotHash;\n}\n\nfunction prepareRollbackEdge(\n graph: MigrationGraph,\n command: Parameters<typeof appendLedger>[1],\n supportsTransactions: boolean,\n edge: MarkerPathEdgeV1\n) {\n const state = graph.states.get(edge.stateId)!;\n const parent = state.parents.find(\n (item) => item.transitionHash === edge.transitionHash\n )!;\n const blob = graph.sql.get(state.sqlHash)!;\n const rollback = parent.rollback;\n if (rollback.kind === \"irreversible\") {\n throw new MigrationError(\n rollback.reason,\n VibORMErrorCode.MIGRATION_DESTRUCTIVE_REJECTED\n );\n }\n const requested =\n rollback.kind === \"manual\" ? rollback.requestedBoundary : null;\n assertTransactionalBoundaryHonored(supportsTransactions, requested);\n refuseSqliteStepwise(command, requested, edge.stateId);\n return {\n edge,\n state,\n parent,\n blob,\n rollback,\n boundary: classifyStoredAtomicity(\n command,\n requested,\n rollback.operations,\n blob\n ),\n nextState: parent.fromState,\n };\n}\n\n/**\n * One edge of a down preview: its rollback rendered as `show --sql` renders\n * it, without the forward half or its forward approvals.\n */\nfunction previewRollbackEdge(\n graph: MigrationGraph,\n edge: MarkerPathEdgeV1\n): DownPreviewEdgeV1 {\n const state = graph.states.get(edge.stateId);\n const parent = state?.parents.find(\n (item) => item.transitionHash === edge.transitionHash\n );\n const blob = state && graph.sql.get(state.sqlHash);\n if (!(parent && blob)) {\n throw new MigrationError(\n \"Rollback cannot find the arrival transition or its SQL\",\n VibORMErrorCode.MIGRATION_CORRUPTION\n );\n }\n const { approvals: _forward, ...transition } = parent;\n return {\n stateId: edge.stateId,\n toState: parent.fromState,\n sql: renderMigrationReview(\n [{ ...transition, originChecks: [], operations: [] }],\n [],\n blob\n ),\n };\n}\n\n/** A migration refusal as plain data; any other error is rethrown. */\nfunction refusalOf(error: unknown): { code: string; message: string } {\n if (!(error instanceof MigrationError)) throw error;\n return { code: error.code, message: error.message };\n}\n\n/**\n * The one unfinished attempt `down` may resume: none, or a started rollback.\n * Anything else needs repair first.\n */\nfunction admitRollbackAttempt(\n ledger: readonly LedgerEventV1[]\n): LedgerEventV1 | undefined {\n const open = unfinishedAttempts(ledger);\n if (open.length > 1) {\n throw new MigrationError(\n \"Multiple unfinished migration attempts require manual repair\",\n VibORMErrorCode.MIGRATION_UNFINISHED_ATTEMPT\n );\n }\n const attempt = open[0];\n if (\n attempt &&\n (attempt.kind !== \"started\" || attempt.direction !== \"rollback\")\n ) {\n throw new MigrationError(\n \"An unfinished migration attempt is blocking ordinary work\",\n VibORMErrorCode.MIGRATION_UNFINISHED_ATTEMPT\n );\n }\n return attempt;\n}\n\n/** An unfinished rollback resumes only as the first edge `down` selected. */\nfunction assertResumesSelectedPath(\n graph: MigrationGraph,\n command: Parameters<typeof appendLedger>[1],\n supportsTransactions: boolean,\n attempt: LedgerEventV1,\n first: PreparedRollback\n): void {\n const resumed = prepareRollbackAttempt(\n graph,\n command,\n supportsTransactions,\n attempt\n );\n if (\n resumed.edge.stateId !== first.edge.stateId ||\n resumed.nextState !== first.nextState ||\n resumed.edge.transitionHash !== first.edge.transitionHash\n ) {\n throw new MigrationError(\n \"An unfinished rollback does not match the selected reverse path\",\n VibORMErrorCode.MIGRATION_UNFINISHED_ATTEMPT\n );\n }\n}\n\nfunction prepareRollbackAttempt(\n graph: MigrationGraph,\n command: Parameters<typeof appendLedger>[1],\n supportsTransactions: boolean,\n attempt: LedgerEventV1\n): PreparedRollback {\n if (!(attempt.fromState && attempt.transitionHash)) {\n throw new MigrationError(\n \"Unfinished rollback is missing its authenticated edge identity\",\n VibORMErrorCode.MIGRATION_CORRUPTION\n );\n }\n const item = prepareRollbackEdge(graph, command, supportsTransactions, {\n stateId: attempt.fromState,\n transitionHash: attempt.transitionHash,\n baselineBoundary: false,\n });\n if (\n attempt.toState !== item.nextState ||\n attempt.estateHash !== graph.estateHash ||\n attempt.snapshotHash !== item.state.snapshotHash ||\n attempt.sqlHash !== item.state.sqlHash\n ) {\n throw new MigrationError(\n \"Unfinished rollback does not match an authenticated estate edge\",\n VibORMErrorCode.MIGRATION_CORRUPTION\n );\n }\n return item;\n}\n\nasync function executeRollbackEdge(\n producer: AnyDriver,\n command: Parameters<typeof appendLedger>[1],\n graph: MigrationGraph,\n item: PreparedRollback,\n current: MigrationMarkerV1,\n resume: LedgerEventV1 | undefined,\n ledger: readonly LedgerEventV1[],\n models: MigrationClient[\"$schema\"]\n): Promise<MigrationMarkerV1> {\n const { edge, state, blob, rollback, boundary, nextState } = item;\n if (\n current.stateId !== edge.stateId ||\n current.path.at(-1)?.stateId !== edge.stateId ||\n current.path.at(-1)?.transitionHash !== edge.transitionHash\n ) {\n throw new MigrationError(\n \"Rollback marker does not name the authenticated edge being reversed\",\n VibORMErrorCode.MIGRATION_MARKER_CONFLICT\n );\n }\n if (!resume) {\n await assertAllChecks(\n producer,\n blob,\n state.destinationChecks,\n command.namespace,\n \"Destination checks failed before rollback\"\n );\n }\n const events = attemptEvents(\n rollbackEventSeed(graph, item),\n resume?.attemptId\n );\n if (!resume) {\n await appendLedger(producer, command, events.event(\"started\", \"none\"));\n }\n await executeOperations(\n producer,\n blob,\n resume\n ? remainingRollbackOperations(graph, item, resume, ledger)\n : rollback.operations,\n boundary,\n (progress, effect, failure) =>\n appendLedger(\n producer,\n command,\n events.event(\"step-confirmed\", effect, progress, failure)\n ),\n command.namespace,\n { fromState: edge.stateId, toState: nextState }\n );\n // Manual rollback SQL may store text typed queries cannot compare.\n await canonicalizeSqliteStorage(\n producer,\n rollback.operations,\n models,\n requireStateSnapshot(graph, nextState)\n );\n const snapshotHash = await proveRolledBack(producer, command, graph, item);\n const next = await advanceMarker(\n producer,\n command,\n graph.estateHash,\n current,\n current.path.slice(0, -1),\n snapshotHash\n );\n await appendRolledBackEvent(producer, command, graph, item, events.attemptId);\n return next;\n}\n\nasync function closeCompletedRollback(\n producer: AnyDriver,\n command: Parameters<typeof appendLedger>[1],\n graph: MigrationGraph,\n item: PreparedRollback,\n attempt: LedgerEventV1,\n ledger: readonly LedgerEventV1[],\n marker: MigrationMarkerV1 | null\n): Promise<void> {\n remainingRollbackOperations(graph, item, attempt, ledger);\n if (marker ? marker.stateId !== item.nextState : item.nextState !== null) {\n throw new MigrationError(\n \"Rollback marker is neither before nor after the unfinished edge\",\n VibORMErrorCode.MIGRATION_MARKER_CONFLICT\n );\n }\n await proveRolledBack(producer, command, graph, item);\n await appendRolledBackEvent(\n producer,\n command,\n graph,\n item,\n attempt.attemptId\n );\n}\n\n/**\n * Proves a reversed edge reached its parent: the origin checks hold and the\n * live schema is the parent's snapshot, whose hash it returns.\n */\nasync function proveRolledBack(\n producer: AnyDriver,\n command: Parameters<typeof appendLedger>[1],\n graph: MigrationGraph,\n { parent, blob, nextState }: PreparedRollback\n): Promise<Sha256> {\n await assertAllChecks(\n producer,\n blob,\n parent.originChecks,\n command.namespace,\n \"Origin checks failed after rollback\"\n );\n const snapshotHash = snapshotHashOf(graph, nextState);\n await proveLive(\n producer,\n command,\n graph,\n snapshotHash,\n () => \"Rollback did not reach the parent snapshot\"\n );\n return snapshotHash;\n}\n\n/** The fields every event of one reversed edge carries. */\nfunction rollbackEventSeed(\n graph: MigrationGraph,\n { edge, state, nextState }: PreparedRollback\n) {\n return {\n estateHash: graph.estateHash,\n snapshotHash: state.snapshotHash,\n sqlHash: state.sqlHash,\n fromState: edge.stateId,\n toState: nextState,\n transitionHash: edge.transitionHash,\n direction: \"rollback\",\n } as const;\n}\n\nasync function appendRolledBackEvent(\n producer: AnyDriver,\n command: Parameters<typeof appendLedger>[1],\n graph: MigrationGraph,\n item: PreparedRollback,\n attemptId: Sha256\n): Promise<void> {\n const arrived = {\n ...rollbackEventSeed(graph, item),\n snapshotHash: snapshotHashOf(graph, item.nextState),\n };\n await appendLedger(\n producer,\n command,\n attemptEvents(arrived, attemptId).event(\"rolled-back\", \"committed\")\n );\n}\n\nfunction remainingRollbackOperations(\n graph: MigrationGraph,\n item: PreparedRollback,\n attempt: LedgerEventV1,\n ledger: readonly LedgerEventV1[]\n): PreparedRollback[\"rollback\"][\"operations\"] {\n return remainingSteps(\n ledger,\n attempt,\n {\n direction: \"rollback\",\n estateHash: graph.estateHash,\n fromState: item.edge.stateId,\n toState: item.nextState,\n transitionHash: item.edge.transitionHash,\n sqlHash: item.state.sqlHash,\n operations: item.rollback.operations,\n boundary: item.boundary,\n },\n \"Rollback\"\n ).operations;\n}\n\nfunction assertReversibleEdge(\n graph: MigrationGraph,\n edge: MarkerPathEdgeV1\n): void {\n const state = graph.states.get(edge.stateId);\n if (!state) {\n throw new MigrationError(\n \"Rollback target is missing from the estate\",\n VibORMErrorCode.MIGRATION_CORRUPTION\n );\n }\n const parent = state.parents.find(\n (item) => item.transitionHash === edge.transitionHash\n );\n if (!parent) {\n throw new MigrationError(\n \"Rollback cannot find the arrival transition\",\n VibORMErrorCode.MIGRATION_CORRUPTION\n );\n }\n if (parent.rollback.kind === \"irreversible\") {\n throw new MigrationError(\n parent.rollback.reason,\n VibORMErrorCode.MIGRATION_DESTRUCTIVE_REJECTED\n );\n }\n}\n\n/** `down({ expectRevision })`: the marker must still be the one the caller read. */\nfunction assertExpectedRevision(\n marker: MigrationMarkerV1 | null,\n request: NormalizedDownOptions\n): void {\n if (\n request.expectRevision === undefined ||\n marker?.revision === request.expectRevision\n ) {\n return;\n }\n throw new MigrationError(\n `down expected marker revision ${request.expectRevision}, but the marker is at revision ${marker?.revision ?? \"none\"}: another command moved it`,\n VibORMErrorCode.MIGRATION_MARKER_CONFLICT\n );\n}\n\n/**\n * Puts each destructive change the rollback makes to a table holding rows to\n * `resolve`, as generate and push ask (plan S4): a retried or mistaken `down`\n * cannot drop data unasked. Only edges whose stored rollback is destructive\n * are diffed: a manual rollback is SQL its author wrote and published, often\n * to move the rows back before a drop, so it is not asked again. An ambiguous\n * change counts as the drop it may be. A table an earlier edge of the path\n * recreates is absent live, and holds no rows.\n */\nasync function approveRollbackLosses(\n producer: Parameters<typeof appendLedger>[0],\n command: Parameters<typeof appendLedger>[1],\n graph: MigrationGraph,\n prepared: readonly PreparedRollback[],\n resolve: ResolveCallback | undefined\n): Promise<void> {\n const losses: DiffOperation[] = [];\n for (const item of prepared) {\n if (!item.rollback.operations.some((op) => op.risk === \"destructive\")) {\n continue;\n }\n const { operations, ambiguousChanges } = await diff(\n requireStateSnapshot(graph, item.edge.stateId),\n requireStateSnapshot(graph, item.nextState)\n );\n for (const change of [...operations, ...ambiguousChanges.map(asDrop)]) {\n if (\n \"tableName\" in change &&\n isDestructiveOperation(change) &&\n (await holdsRows(producer, command, change.tableName))\n ) {\n losses.push(change);\n }\n }\n }\n // The callback is the caller's work: no locked transaction waits on it.\n // Each group of `down` re-reads the marker under the lock it takes again.\n if (losses.length > 0 && resolve) await letLockGo(producer);\n await approveDestructiveOperations(losses, resolve, false);\n}\n\nfunction asDrop(change: AmbiguousChange): DiffOperation {\n return change.type === \"ambiguousTable\"\n ? { type: \"dropTable\", tableName: change.droppedTable }\n : {\n type: \"dropColumn\",\n tableName: change.tableName,\n columnName: change.droppedColumn.name,\n };\n}\n\n/**\n * The absent-and-empty-table probe: an absent table (a later state dropped it,\n * or a resumed rollback already did) holds no rows.\n */\nasync function holdsRows(\n producer: Parameters<typeof appendLedger>[0],\n command: Parameters<typeof appendLedger>[1],\n table: string\n): Promise<boolean> {\n if (await isTableMissing(producer, command, table)) return false;\n const result = await producer._executeRaw(\n `SELECT 1 AS populated FROM ${qualifiedName(command, table)} LIMIT 1`\n );\n return result.rows.length > 0;\n}\n\n/**\n * A rolled-back attempt must have left nothing behind. A manual opaque step of\n * it that committed, or was announced and never answered (it may have\n * committed), is an effect no fingerprint shows and that no rollback undid: a\n * forward attempt runs none. Marking it rolled back would let `apply` run the\n * step again — the double credit (plan S4). A step the server refused whole is\n * answered with its `failure`: nothing of it committed. Generated steps are\n * structural, and so is a CONCURRENTLY index statement, whose index resolve\n * repairs before the origin proof (plan S7): the fingerprint proves those\n * undone.\n */\nfunction refuseOpaqueEffect(\n transition: ReturnType<typeof parentTransition>,\n blob: Uint8Array,\n attempt: LedgerEventV1,\n ledger: readonly LedgerEventV1[]\n): void {\n const opaque = new Set(\n transition.operations.flatMap((operation) =>\n operation.steps.flatMap((step) =>\n operation.origin === \"manual\" &&\n step.retry === \"opaque\" &&\n concurrentIndexNames(sliceDispatch(blob, step.execute)).length === 0\n ? [step.execute.dispatchId]\n : []\n )\n )\n );\n const effects = ledger.filter(\n (event) =>\n event.attemptId === attempt.attemptId &&\n event.kind === \"step-confirmed\" &&\n opaque.has(event.dispatchId ?? \"\")\n );\n const refused = new Set(\n effects.flatMap((event) => (event.failure ? [event.dispatchId] : []))\n );\n const effect =\n effects.find((event) => event.effectState === \"committed\") ??\n effects.find((event) => !refused.has(event.dispatchId));\n if (effect === undefined) return;\n const committed = effect.effectState === \"committed\";\n throw new MigrationError(\n `resolve cannot mark this attempt rolled back: its opaque dispatch ${effect.dispatchId} ${committed ? \"committed\" : \"may have committed\"} and nothing undid it. Finish the transition by hand and resolve({ outcome: \"complete\" }).`,\n committed\n ? VibORMErrorCode.MIGRATION_PARTIAL_EFFECT\n : VibORMErrorCode.MIGRATION_AMBIGUOUS_COMMIT,\n {\n meta: {\n ...(attempt.fromState ? { fromState: attempt.fromState } : {}),\n ...(attempt.toState ? { toState: attempt.toState } : {}),\n operationId: effect.operationId ?? undefined,\n dispatchId: effect.dispatchId ?? undefined,\n lastConfirmedStep: effect.dispatchId ?? undefined,\n effectState: committed ? \"committed\" : \"may-have-committed\",\n partial: true,\n },\n }\n );\n}\n\nfunction rollbackSlice(\n graph: MigrationGraph,\n marker: MigrationMarkerV1,\n options: NormalizedDownOptions\n): MigrationMarkerV1[\"path\"] {\n if (marker.path.length === 0) {\n throw new MigrationError(\n \"Nothing to roll back\",\n VibORMErrorCode.MIGRATION_NOT_FOUND\n );\n }\n const steps = options.to\n ? distanceTo(\n marker.path.map((edge) => edge.stateId),\n resolveStateSelector(graph, options.to)\n )\n : options.steps;\n const removed = steps === 0 ? [] : marker.path.slice(-steps);\n if (removed.some((edge) => edge.baselineBoundary)) {\n throw new MigrationError(\n \"down cannot cross a baseline boundary\",\n VibORMErrorCode.MIGRATION_INVALID_STATE\n );\n }\n return removed;\n}\n\nfunction distanceTo(path: readonly Sha256[], target: Sha256): number {\n const index = path.lastIndexOf(target);\n if (index < 0) {\n throw new MigrationError(\n \"down target is not on the arrival path\",\n VibORMErrorCode.MIGRATION_NOT_FOUND\n );\n }\n return path.length - 1 - index;\n}\n","/**\n * Semantic migration storage. Path-level get/put/delete is gone.\n *\n * Readers return raw bytes. Parsers, not drivers, turn those bytes into\n * trusted domain values. Writers promise strongly consistent listing and\n * conditional create.\n */\n\nimport type { Sha256 } from \"../identity\";\n\nexport interface PublishResult {\n readonly outcome: \"created\" | \"identical\";\n}\n\nexport interface MigrationStorageReader {\n readEstate(): Promise<Uint8Array | null>;\n listStates(): Promise<readonly Sha256[]>;\n listSnapshots(): Promise<readonly Sha256[]>;\n listSql(): Promise<readonly Sha256[]>;\n readState(id: Sha256): Promise<Uint8Array | null>;\n readSnapshot(hash: Sha256): Promise<Uint8Array | null>;\n readSql(hash: Sha256): Promise<Uint8Array | null>;\n}\n\nexport interface MigrationStorageWriter extends MigrationStorageReader {\n publishEstate(bytes: Uint8Array): Promise<PublishResult>;\n publishSnapshot(hash: Sha256, bytes: Uint8Array): Promise<PublishResult>;\n publishSql(hash: Sha256, bytes: Uint8Array): Promise<PublishResult>;\n publishState(id: Sha256, bytes: Uint8Array): Promise<PublishResult>;\n}\n\nconst READER_METHODS = [\n \"readEstate\",\n \"listStates\",\n \"listSnapshots\",\n \"listSql\",\n \"readState\",\n \"readSnapshot\",\n \"readSql\",\n] as const;\n\nconst WRITER_METHODS = [\n \"publishEstate\",\n \"publishSnapshot\",\n \"publishSql\",\n \"publishState\",\n] as const;\n\nexport function isMigrationStorageReader(\n value: unknown\n): value is MigrationStorageReader {\n return hasStorageMethods(value, READER_METHODS);\n}\n\nexport function isMigrationStorageWriter(\n value: MigrationStorageReader\n): value is MigrationStorageWriter {\n return hasStorageMethods(value, WRITER_METHODS);\n}\n\nfunction hasStorageMethods(\n value: unknown,\n methods: readonly string[]\n): boolean {\n if (\n value === null ||\n (typeof value !== \"object\" && typeof value !== \"function\")\n ) {\n return false;\n }\n return methods.every(\n (method) => typeof Reflect.get(value, method) === \"function\"\n );\n}\n","/** One capability-sensitive migration client composition root. */\n\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\nimport { errorCause } from \"../errors/diagnostic-safety\";\nimport { type ApplyV1Result, applyV1 } from \"./apply-v1\";\nimport { type CheckResult, checkEstate } from \"./check\";\nimport { type GenerateV1Result, generateV1 } from \"./generate-v1\";\nimport { loadMigrationGraph, resolveStateSelector } from \"./graph\";\nimport { snapshotExactRecord } from \"./input-boundary\";\nimport { type MigrationLimits, resolveMigrationLimits } from \"./limits\";\nimport {\n baselineV1,\n downV1,\n logV1,\n type PruneOptions,\n type PruneResult,\n pruneV1,\n reanchorV1,\n resetV1,\n resolveV1,\n type StatusV1Result,\n statusV1,\n type VerifyV1Result,\n verifyV1,\n} from \"./operators\";\nimport {\n type GraphResult,\n type ListResult,\n listMigrationStates,\n migrationGraphResult,\n type ShowResult,\n showMigrationState,\n} from \"./public-view\";\nimport type { MigrationClient } from \"./push/planner\";\nimport { type PushResultFor, pushV1 } from \"./push-v1\";\nimport type {\n MigrationStorageReader,\n MigrationStorageWriter,\n} from \"./storage/contract\";\nimport {\n isMigrationStorageReader,\n isMigrationStorageWriter,\n} from \"./storage/contract\";\nimport {\n MANAGED_TABLES,\n MIGRATION_LIMITS,\n normalizeManagedTables,\n} from \"./target\";\nimport type {\n ApplyV1Options,\n BaselineOptions,\n DownV1Options,\n DownV1Result,\n ExactPushOptions,\n GenerateV1Options,\n LedgerEventV1,\n PushOptionsV1,\n ReanchorOptions,\n ResetV1Options,\n ResolveV1Options,\n StateSelector,\n} from \"./v1-types\";\n\nexport interface MigrationClientOptions<\n S extends MigrationStorageReader = MigrationStorageReader,\n> {\n readonly storage: S;\n readonly tables?: readonly string[];\n /**\n * PostgreSQL session limits and VibORM's own waits, in milliseconds, and\n * `largeTableRows`, the estimated table size above which a rewrite or scan\n * is refused in-request.\n */\n readonly limits?: MigrationLimits;\n}\n\n/** A storage-less client's options: managed tables, limits, or both. */\ntype LiveMigrationClientOptions =\n | {\n readonly tables: readonly string[];\n readonly limits?: MigrationLimits;\n }\n | {\n readonly tables?: readonly string[];\n readonly limits: MigrationLimits;\n };\n\ntype NoExtraMigrationClientOptionKeys<Given> = Record<\n Exclude<keyof Given, \"storage\" | \"tables\" | \"limits\">,\n never\n>;\n\nexport type GenerateResult = GenerateV1Result;\nexport type StatusResult = StatusV1Result;\nexport type VerifyResult = VerifyV1Result;\nexport type LogResult = readonly LedgerEventV1[];\nexport type ApplyResult = ApplyV1Result;\nexport type DownResult = DownV1Result;\nexport interface BaselineResult {\n readonly stateId: string;\n}\nexport interface ReanchorResult {\n readonly stateId: string;\n}\nexport interface ResolveResult {\n readonly outcome: ResolveV1Options[\"outcome\"];\n}\nexport interface ResetResult {\n /** Physical tables selected for a read-only reset preview. */\n readonly tables?: readonly string[];\n readonly preview: boolean;\n readonly path: readonly string[];\n}\nexport interface LiveMigrations {\n log(): Promise<LogResult>;\n push<O extends PushOptionsV1>(\n options?: ExactPushOptions<O>\n ): Promise<PushResultFor<O>>;\n}\n\nexport interface ReadableMigrations extends LiveMigrations {\n check(): Promise<CheckResult>;\n list(): Promise<ListResult>;\n show(selector: StateSelector): Promise<ShowResult>;\n graph(): Promise<GraphResult>;\n status(): Promise<StatusResult>;\n verify(): Promise<VerifyResult>;\n apply(options?: ApplyV1Options): Promise<ApplyResult>;\n down(options?: DownV1Options): Promise<DownResult>;\n baseline(options: BaselineOptions): Promise<BaselineResult>;\n reanchor(options?: ReanchorOptions): Promise<ReanchorResult>;\n prune(options: PruneOptions): Promise<PruneResult>;\n resolve(options: ResolveV1Options): Promise<ResolveResult>;\n}\n\nexport interface WritableMigrations extends ReadableMigrations {\n generate(options?: GenerateV1Options): Promise<GenerateResult>;\n reset(options?: ResetV1Options): Promise<ResetResult>;\n}\n\nexport function createMigrationClient<\n Options extends MigrationClientOptions<MigrationStorageWriter>,\n>(\n client: MigrationClient,\n options: Options & NoExtraMigrationClientOptionKeys<Options>\n): WritableMigrations;\nexport function createMigrationClient<\n Options extends MigrationClientOptions<MigrationStorageReader>,\n>(\n client: MigrationClient,\n options: Options & NoExtraMigrationClientOptionKeys<Options>\n): ReadableMigrations;\nexport function createMigrationClient<\n Options extends LiveMigrationClientOptions,\n>(\n client: MigrationClient,\n options: Options & NoExtraMigrationClientOptionKeys<Options>\n): LiveMigrations;\nexport function createMigrationClient(\n client: MigrationClient,\n options?: undefined\n): LiveMigrations;\nexport function createMigrationClient(\n client: MigrationClient,\n options?: MigrationClientOptions | LiveMigrationClientOptions\n): LiveMigrations | ReadableMigrations | WritableMigrations {\n const record =\n options === undefined\n ? undefined\n : snapshotExactRecord(\n options,\n [\"storage\", \"tables\", \"limits\"],\n \"migration client options\",\n refuseClientOptions\n );\n const tables = normalizeManagedTables(record?.tables);\n const limits =\n record?.limits === undefined\n ? undefined\n : resolveMigrationLimits(record.limits);\n const executionClient: MigrationClient =\n tables === undefined && limits === undefined\n ? client\n : {\n $driver: client.$driver,\n $schema: client.$schema,\n [MANAGED_TABLES]: tables,\n [MIGRATION_LIMITS]: limits,\n };\n const live: LiveMigrations = Object.freeze({\n log: () => logV1(executionClient),\n push<O extends PushOptionsV1>(\n pushOptions?: ExactPushOptions<O>\n ): Promise<PushResultFor<O>> {\n return pushV1(executionClient, pushOptions);\n },\n });\n if (record === undefined) return live;\n const storage = record.storage;\n if (storage === undefined) {\n if (tables !== undefined || limits !== undefined) return live;\n return refuseClientOptions(\n \"migration client options must include storage, tables or limits when supplied\"\n );\n }\n let readableStorage: MigrationStorageReader;\n try {\n if (!isMigrationStorageReader(storage)) {\n return refuseClientOptions(\n \"migration client storage must implement MigrationStorageReader\"\n );\n }\n readableStorage = storage;\n } catch (failure) {\n return refuseClientOptions(\n \"migration client storage could not be inspected\",\n errorCause(failure)\n );\n }\n\n const readable: ReadableMigrations = Object.freeze({\n ...live,\n check: () => checkEstate(readableStorage),\n list: async () =>\n listMigrationStates(await loadMigrationGraph(readableStorage)),\n show: async (selector) => {\n const graph = await loadMigrationGraph(readableStorage);\n return showMigrationState(graph, resolveStateSelector(graph, selector));\n },\n graph: async () =>\n migrationGraphResult(await loadMigrationGraph(readableStorage)),\n status: () => statusV1(executionClient, readableStorage),\n verify: () => verifyV1(executionClient, readableStorage),\n apply: (applyOptions) =>\n applyV1(executionClient, readableStorage, applyOptions),\n down: (downOptions) =>\n downV1(executionClient, readableStorage, downOptions),\n baseline: (baselineOptions) =>\n baselineV1(executionClient, readableStorage, baselineOptions),\n reanchor: (reanchorOptions) =>\n reanchorV1(executionClient, readableStorage, reanchorOptions),\n prune: (pruneOptions) => pruneV1(readableStorage, pruneOptions),\n resolve: (resolveOptions) =>\n resolveV1(executionClient, readableStorage, resolveOptions),\n });\n let writableStorage: MigrationStorageWriter;\n try {\n if (!isMigrationStorageWriter(readableStorage)) return readable;\n writableStorage = readableStorage;\n } catch (failure) {\n return refuseClientOptions(\n \"migration client storage could not be inspected\",\n errorCause(failure)\n );\n }\n\n return Object.freeze({\n ...readable,\n generate: (generateOptions) =>\n generateV1(executionClient, writableStorage, generateOptions),\n reset: (resetOptions) =>\n resetV1(executionClient, writableStorage, resetOptions),\n });\n}\n\nfunction refuseClientOptions(message: string, cause?: Error): never {\n throw new MigrationError(message, VibORMErrorCode.INVALID_INPUT, { cause });\n}\n"],"mappings":"i+CAMA,SAAgB,oBACd,EACA,EACA,EACA,EACmC,CACnC,IAAI,EACA,EAA+B,EAAE,CACrC,GAAI,CACoB,OAAO,GAAU,UAAnC,GAA+C,CAAC,MAAM,QAAQ,EAAM,GACtE,EAAc,EACd,EAAO,QAAQ,QAAQ,EAAM,QAExB,EAAS,CAChB,OAAOA,EAAO,GAAG,EAAM,yBAA0B,EAAW,EAAQ,CAAC,CAEvE,GAAI,CAAC,EAAa,OAAOA,EAAO,GAAG,EAAM,oBAAoB,CAC7D,IAAM,EAAoC,EAAE,CAC5C,IAAK,IAAM,KAAO,EAAM,CACtB,GAAI,OAAO,GAAQ,UAAY,CAAC,EAAQ,SAAS,EAAI,CACnD,OAAOA,EAAO,GAAG,EAAM,wBAAwB,OAAO,EAAI,GAAG,CAE/D,GAAI,CACF,EAAS,GAAO,QAAQ,IAAI,EAAa,EAAI,OACtC,EAAS,CAChB,OAAOA,EAAO,GAAG,EAAM,GAAG,EAAI,oBAAqB,EAAW,EAAQ,CAAC,EAG3E,OAAO,OAAO,OAAO,EAAS,CAGhC,SAAgB,mBACd,EACA,EACA,EACoB,CACpB,IAAI,EACJ,GAAI,CACE,MAAM,QAAQ,EAAM,GAAE,EAAU,MA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