viborm 1.14.2 → 1.16.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/adapter-namespace-DwFnfpED.mjs +2 -0
- package/dist/{adapter-namespace-DaRiTIIf.mjs.map → adapter-namespace-DwFnfpED.mjs.map} +1 -1
- package/dist/adapters.d.mts +26 -10
- package/dist/adapters.mjs +1 -1
- package/dist/args-7WgBFd_f.mjs +2 -0
- package/dist/{args-764KdWMr.mjs.map → args-7WgBFd_f.mjs.map} +1 -1
- package/dist/array-literal-BOzj0E2u.mjs +2 -0
- package/dist/{array-literal-DHinAnVs.mjs.map → array-literal-BOzj0E2u.mjs.map} +1 -1
- package/dist/base-17NSFtrA.mjs +2 -0
- package/dist/base-17NSFtrA.mjs.map +1 -0
- package/dist/batch-refs-Bd8HvwUc.mjs +2 -0
- package/dist/{batch-refs-C-gx7A4-.mjs.map → batch-refs-Bd8HvwUc.mjs.map} +1 -1
- package/dist/better-auth.d.mts +116 -0
- package/dist/better-auth.mjs +6 -0
- package/dist/better-auth.mjs.map +1 -0
- package/dist/bind-parameter-capacity-BAFQM9Jt.mjs +2 -0
- package/dist/{bind-parameter-capacity-BMD-bxMO.mjs.map → bind-parameter-capacity-BAFQM9Jt.mjs.map} +1 -1
- package/dist/bun-sql.d.mts +1 -1
- package/dist/bun-sql.mjs +1 -1
- package/dist/bun-sql.mjs.map +1 -1
- package/dist/bun-sqlite.d.mts +1 -1
- package/dist/bun-sqlite.mjs +1 -1
- package/dist/bun-sqlite.mjs.map +1 -1
- package/dist/cache/cloudflare-kv.d.mts +1 -1
- package/dist/cache/cloudflare-kv.mjs +1 -1
- package/dist/cache/cloudflare-kv.mjs.map +1 -1
- package/dist/cache/memory.d.mts +1 -1
- package/dist/cache/memory.mjs +1 -1
- package/dist/cache/memory.mjs.map +1 -1
- package/dist/cache.d.mts +2 -2
- package/dist/cache.mjs +1 -1
- package/dist/cache.mjs.map +1 -1
- package/dist/call-0bd_B9Vp.mjs +2 -0
- package/dist/{call-Cz8XUmrl.mjs.map → call-0bd_B9Vp.mjs.map} +1 -1
- package/dist/cli.mjs +6 -6
- package/dist/cli.mjs.map +1 -1
- package/dist/client-D7sWgUt2.mjs +2 -0
- package/dist/client-D7sWgUt2.mjs.map +1 -0
- package/dist/client-DEfFqv4S.mjs +9 -0
- package/dist/client-DEfFqv4S.mjs.map +1 -0
- package/dist/{client-CRxfhw2y.d.mts → client-Dlz3-2JC.d.mts} +3 -3
- package/dist/client.d.mts +3 -3
- package/dist/client.mjs +1 -1
- package/dist/client.mjs.map +1 -1
- package/dist/config.d.mts +2 -2
- package/dist/config.mjs +1 -1
- package/dist/confine-CyI9IwjC.mjs +2 -0
- package/dist/{confine-DqFBTUw6.mjs.map → confine-CyI9IwjC.mjs.map} +1 -1
- package/dist/coordination-BxMskOgi.mjs +2 -0
- package/dist/coordination-BxMskOgi.mjs.map +1 -0
- package/dist/d1.d.mts +2 -30
- package/dist/d1.mjs +1 -1
- package/dist/d1.mjs.map +1 -1
- package/dist/{database-adapter-BGqvjeEy.d.mts → database-adapter-BMjJiBFm.d.mts} +8476 -8386
- package/dist/datetime-physical-codec-DAF7WJpy.mjs +2 -0
- package/dist/datetime-physical-codec-DAF7WJpy.mjs.map +1 -0
- package/dist/defaults-DAPb-tJ4.mjs +2 -0
- package/dist/{defaults-DwOHWI_M.mjs.map → defaults-DAPb-tJ4.mjs.map} +1 -1
- package/dist/{document-BVTQ-cF-.d.mts → document-CHaVF7Vn.d.mts} +36 -2
- package/dist/{driver-BBEmaJZy.d.mts → driver-BvTixv-m.d.mts} +1 -1
- package/dist/driver-diagnostics-aQ54bArn.mjs +2 -0
- package/dist/{driver-diagnostics-DW9NdckJ.mjs.map → driver-diagnostics-aQ54bArn.mjs.map} +1 -1
- package/dist/driver-kiIQS_Fd.mjs +2 -0
- package/dist/driver-kiIQS_Fd.mjs.map +1 -0
- package/dist/driver-lShUkDmf.mjs +2 -0
- package/dist/driver-lShUkDmf.mjs.map +1 -0
- package/dist/driver.d.mts +1 -1
- package/dist/driver.mjs +1 -1
- package/dist/durable-object.d.mts +1 -1
- package/dist/durable-object.mjs +2 -2
- package/dist/durable-object.mjs.map +1 -1
- package/dist/error-mapping-B9rSvgG9.mjs +2 -0
- package/dist/error-mapping-B9rSvgG9.mjs.map +1 -0
- package/dist/every-JpbiHdMb.mjs +2 -0
- package/dist/{every-tOgQmaIE.mjs.map → every-JpbiHdMb.mjs.map} +1 -1
- package/dist/execution-context-couU2tgh.mjs +2 -0
- package/dist/execution-context-couU2tgh.mjs.map +1 -0
- package/dist/{exports-COCJ8f2f.d.mts → exports-DYnTfvQo.d.mts} +1 -1
- package/dist/extension-Dh1ddrlA.mjs +2 -0
- package/dist/{extension-CGepsF-p.mjs.map → extension-Dh1ddrlA.mjs.map} +1 -1
- package/dist/fs-estate-n-QpsFqb.mjs +2 -0
- package/dist/{fs-estate-D1Nsg9G1.mjs.map → fs-estate-n-QpsFqb.mjs.map} +1 -1
- package/dist/geo-area-codec-Bti2PA2i.mjs +2 -0
- package/dist/geo-area-codec-Bti2PA2i.mjs.map +1 -0
- package/dist/id-domain-Cg65TLZ-.mjs +2 -0
- package/dist/id-domain-Cg65TLZ-.mjs.map +1 -0
- package/dist/identifier-conversion-BTDxDwDB.mjs +2 -0
- package/dist/identifier-conversion-BTDxDwDB.mjs.map +1 -0
- package/dist/identifiers-BxOf57qy.mjs +2 -0
- package/dist/identifiers-BxOf57qy.mjs.map +1 -0
- package/dist/identity-CJlRQA-m.mjs +2 -0
- package/dist/identity-CJlRQA-m.mjs.map +1 -0
- package/dist/index.d.mts +3 -3
- package/dist/index.mjs +1 -1
- package/dist/index.mjs.map +1 -1
- package/dist/instrumentation.d.mts +1 -1
- package/dist/instrumentation.mjs +1 -1
- package/dist/instrumentation.mjs.map +1 -1
- package/dist/introspect-q3Rf_Xv8.mjs +2 -0
- package/dist/introspect-q3Rf_Xv8.mjs.map +1 -0
- package/dist/json-CsAdz9pg.mjs +2 -0
- package/dist/json-CsAdz9pg.mjs.map +1 -0
- package/dist/json-number-C09rsm1g.mjs +2 -0
- package/dist/{json-number-AI-SdUUn.mjs.map → json-number-C09rsm1g.mjs.map} +1 -1
- package/dist/json-parameter-D7hDrVKw.mjs +2 -0
- package/dist/{json-parameter-oQ8nGaKr.mjs.map → json-parameter-D7hDrVKw.mjs.map} +1 -1
- package/dist/judge-words-k5GCc4cV.mjs +2 -0
- package/dist/judge-words-k5GCc4cV.mjs.map +1 -0
- package/dist/key-BDH6oTyC.mjs +2 -0
- package/dist/key-BDH6oTyC.mjs.map +1 -0
- package/dist/keys-CIal55WQ.mjs +2 -0
- package/dist/{keys-BQxM4c_a.mjs.map → keys-CIal55WQ.mjs.map} +1 -1
- package/dist/keys-DZdKAd4n.mjs +2 -0
- package/dist/keys-DZdKAd4n.mjs.map +1 -0
- package/dist/libsql-DEZ0uhK2.mjs +3 -0
- package/dist/libsql-DEZ0uhK2.mjs.map +1 -0
- package/dist/libsql.d.mts +2 -20
- package/dist/libsql.mjs +1 -1
- package/dist/libsql.mjs.map +1 -1
- package/dist/light-D2wNSbzY.mjs +2 -0
- package/dist/{light-BkJe3-yW.mjs.map → light-D2wNSbzY.mjs.map} +1 -1
- package/dist/memory-BaGWNdvk.mjs +2 -0
- package/dist/{memory-G4cSuc6A.mjs.map → memory-BaGWNdvk.mjs.map} +1 -1
- package/dist/methods-part-BaNx3o7b.mjs +2 -0
- package/dist/methods-part-BaNx3o7b.mjs.map +1 -0
- package/dist/migrations/mysql.d.mts +5 -5
- package/dist/migrations/mysql.mjs +1 -1
- package/dist/migrations/postgres.d.mts +5 -5
- package/dist/migrations/postgres.mjs +1 -1
- package/dist/migrations/snowflake.d.mts +5 -5
- package/dist/migrations/snowflake.mjs +1 -1
- package/dist/migrations/sqlite.d.mts +5 -5
- package/dist/migrations/sqlite.mjs +1 -1
- package/dist/migrations/storage/durable-object.d.mts +1 -1
- package/dist/migrations/storage/durable-object.mjs +1 -1
- package/dist/migrations/storage/durable-object.mjs.map +1 -1
- package/dist/migrations/storage/fs.d.mts +1 -1
- package/dist/migrations/storage/fs.mjs +1 -1
- package/dist/migrations/storage/r2.d.mts +1 -1
- package/dist/migrations/storage/r2.mjs +1 -1
- package/dist/migrations/storage/r2.mjs.map +1 -1
- package/dist/migrations/surrealdb.d.mts +5 -5
- package/dist/migrations/surrealdb.mjs +1 -1
- package/dist/migrations/tenant.d.mts +3 -3
- package/dist/migrations/tenant.mjs +1 -1
- package/dist/migrations/tenant.mjs.map +1 -1
- package/dist/migrations-DIUltjr3.mjs +2 -0
- package/dist/{migrations-BMiRjR-N.mjs.map → migrations-DIUltjr3.mjs.map} +1 -1
- package/dist/migrations.d.mts +5 -5
- package/dist/migrations.mjs +1 -1
- package/dist/model-Dtd37Sky.mjs +2 -0
- package/dist/model-Dtd37Sky.mjs.map +1 -0
- package/dist/mysql-BFPF8xyv.mjs +9 -0
- package/dist/mysql-BFPF8xyv.mjs.map +1 -0
- package/dist/mysql-adapter-BFWYPoM0.mjs +2 -0
- package/dist/mysql-adapter-BFWYPoM0.mjs.map +1 -0
- package/dist/mysql2.d.mts +2 -27
- package/dist/mysql2.mjs +1 -1
- package/dist/mysql2.mjs.map +1 -1
- package/dist/named-statements-CkOOD__I.mjs +2 -0
- package/dist/named-statements-CkOOD__I.mjs.map +1 -0
- package/dist/named-statements-NF7Iycjk.d.mts +13 -0
- package/dist/native-types-1ewJXVks.mjs +2 -0
- package/dist/native-types-1ewJXVks.mjs.map +1 -0
- package/dist/neon-http.d.mts +1 -1
- package/dist/neon-http.mjs +1 -1
- package/dist/neon-http.mjs.map +1 -1
- package/dist/normalized-result-D7nVkF36.mjs +2 -0
- package/dist/normalized-result-D7nVkF36.mjs.map +1 -0
- package/dist/{object-store-B_YMoW8u.d.mts → object-store-C4qmW7xf.d.mts} +4 -4
- package/dist/object-store-Chq1PMYz.mjs +2 -0
- package/dist/object-store-Chq1PMYz.mjs.map +1 -0
- package/dist/on-ZkOVmE4-.mjs +2 -0
- package/dist/{on-ylYaKuRu.mjs.map → on-ZkOVmE4-.mjs.map} +1 -1
- package/dist/on.d.mts +1 -1
- package/dist/on.mjs +1 -1
- package/dist/on.mjs.map +1 -1
- package/dist/ordering/keys.mjs +1 -1
- package/dist/ordering.d.mts +9 -3
- package/dist/ordering.mjs +10 -10
- package/dist/ordering.mjs.map +1 -1
- package/dist/pending-operation-D4gUKMxD.mjs +2 -0
- package/dist/pending-operation-D4gUKMxD.mjs.map +1 -0
- package/dist/permissions.d.mts +1 -1
- package/dist/permissions.mjs +1 -1
- package/dist/permissions.mjs.map +1 -1
- package/dist/pg.d.mts +16 -99
- package/dist/pg.mjs +1 -1
- package/dist/pg.mjs.map +1 -1
- package/dist/pglite.d.mts +3 -1
- package/dist/pglite.mjs +1 -1
- package/dist/pglite.mjs.map +1 -1
- package/dist/physical-DO4PEYcc.mjs +2 -0
- package/dist/physical-DO4PEYcc.mjs.map +1 -0
- package/dist/pinned-session-Y7-2pRBJ.mjs +2 -0
- package/dist/pinned-session-Y7-2pRBJ.mjs.map +1 -0
- package/dist/planetscale.d.mts +1 -1
- package/dist/planetscale.mjs +1 -1
- package/dist/planetscale.mjs.map +1 -1
- package/dist/{planner-DHjdvjwk.d.mts → planner-C-zjj19U.d.mts} +123 -1
- package/dist/postgres-DQQE2ys_.mjs +34 -0
- package/dist/postgres-DQQE2ys_.mjs.map +1 -0
- package/dist/postgres-adapter-BpLizOaK.mjs +2 -0
- package/dist/{postgres-adapter-axapXX8d.mjs.map → postgres-adapter-BpLizOaK.mjs.map} +1 -1
- package/dist/postgres-adapter-psTVfuw7.mjs +2 -0
- package/dist/postgres-adapter-psTVfuw7.mjs.map +1 -0
- package/dist/postgres-result-133boRW-.mjs +2 -0
- package/dist/postgres-result-133boRW-.mjs.map +1 -0
- package/dist/postgres.d.mts +27 -59
- package/dist/postgres.mjs +1 -1
- package/dist/postgres.mjs.map +1 -1
- package/dist/provider-limits-Bcsz0EJv.mjs +2 -0
- package/dist/provider-limits-Bcsz0EJv.mjs.map +1 -0
- package/dist/provider-parameter-snapshot-cyTUDutH.mjs +2 -0
- package/dist/provider-parameter-snapshot-cyTUDutH.mjs.map +1 -0
- package/dist/quantized-BKBs0joq.mjs +2 -0
- package/dist/quantized-BKBs0joq.mjs.map +1 -0
- package/dist/query-BTb6iakn.mjs +2 -0
- package/dist/query-BTb6iakn.mjs.map +1 -0
- package/dist/query-backend-TisPjCPF.mjs +2 -0
- package/dist/query-backend-TisPjCPF.mjs.map +1 -0
- package/dist/query-inspection-DwYBKSDG.mjs +2 -0
- package/dist/query-inspection-DwYBKSDG.mjs.map +1 -0
- package/dist/raw-DqEb71JZ.mjs +2 -0
- package/dist/raw-DqEb71JZ.mjs.map +1 -0
- package/dist/relation-bound-CSNKLyDy.mjs +2 -0
- package/dist/{relation-bound-ku_cMdye.mjs.map → relation-bound-CSNKLyDy.mjs.map} +1 -1
- package/dist/result-parsing-BbffueEX.mjs +2 -0
- package/dist/{result-parsing-B0Y4KGDT.mjs.map → result-parsing-BbffueEX.mjs.map} +1 -1
- package/dist/routed-operations-CcKOdn51.mjs +2 -0
- package/dist/{routed-operations-wytpbYKv.mjs.map → routed-operations-CcKOdn51.mjs.map} +1 -1
- package/dist/rows-of-Bgl9GVtK.mjs +2 -0
- package/dist/rows-of-Bgl9GVtK.mjs.map +1 -0
- package/dist/rule-words-DMbQuvD2.mjs +2 -0
- package/dist/{rule-words-ZIGm7cDm.mjs.map → rule-words-DMbQuvD2.mjs.map} +1 -1
- package/dist/scalar-Dm9brvAU.mjs +4 -0
- package/dist/scalar-Dm9brvAU.mjs.map +1 -0
- package/dist/schema/introspect.d.mts +2 -2
- package/dist/schema/introspect.mjs +1 -1
- package/dist/schema/json.d.mts +6 -4
- package/dist/schema/json.mjs +1 -1
- package/dist/schema-DDkAUfOb.mjs +2 -0
- package/dist/schema-DDkAUfOb.mjs.map +1 -0
- package/dist/schema-DqR_Kcje.mjs +2 -0
- package/dist/schema-DqR_Kcje.mjs.map +1 -0
- package/dist/schema-introspection-Bbo4DN_d.mjs +4 -0
- package/dist/schema-introspection-Bbo4DN_d.mjs.map +1 -0
- package/dist/schema.d.mts +2 -2
- package/dist/schema.mjs +1 -1
- package/dist/select-assembly-CEpNu-Gw.mjs +2 -0
- package/dist/select-assembly-CEpNu-Gw.mjs.map +1 -0
- package/dist/serializer-ettLu5xG.mjs +33 -0
- package/dist/serializer-ettLu5xG.mjs.map +1 -0
- package/dist/settle-Pui-1tfJ.mjs +2 -0
- package/dist/{settle-1cy5x_52.mjs.map → settle-Pui-1tfJ.mjs.map} +1 -1
- package/dist/settled-DYYPcaBX.mjs +2 -0
- package/dist/{settled-BjyuA76m.mjs.map → settled-DYYPcaBX.mjs.map} +1 -1
- package/dist/snowflake-BfF8xwfP.mjs +2 -0
- package/dist/{snowflake-UOCC820W.mjs.map → snowflake-BfF8xwfP.mjs.map} +1 -1
- package/dist/snowflake.d.mts +3 -3
- package/dist/snowflake.mjs +2 -2
- package/dist/snowflake.mjs.map +1 -1
- package/dist/soft-delete.d.mts +9 -3
- package/dist/soft-delete.mjs +1 -1
- package/dist/soft-delete.mjs.map +1 -1
- package/dist/{spans-XDUFeTzC.mjs → spans-DwDXMvyd.mjs} +1 -1
- package/dist/{spans-XDUFeTzC.mjs.map → spans-DwDXMvyd.mjs.map} +1 -1
- package/dist/sql-Bu63iAfT.mjs +2 -0
- package/dist/sql-Bu63iAfT.mjs.map +1 -0
- package/dist/{sql-BVZ8QefY.d.mts → sql-C4_sFNDm.d.mts} +18 -5
- package/dist/sql-statement-tokens-Z5Ta4iDB.mjs +3 -0
- package/dist/{sql-statement-tokens-DbeMwHra.mjs.map → sql-statement-tokens-Z5Ta4iDB.mjs.map} +1 -1
- package/dist/sql-tegqTqGq.mjs +2 -0
- package/dist/sql-tegqTqGq.mjs.map +1 -0
- package/dist/sql.d.mts +1 -1
- package/dist/sql.mjs +1 -1
- package/dist/sqlite-adapter-Cb-SJw2f.mjs +2 -0
- package/dist/sqlite-adapter-Cb-SJw2f.mjs.map +1 -0
- package/dist/sqlite-statement-classifier-JBHiQO6Q.mjs +2 -0
- package/dist/{sqlite-statement-classifier-BAHl-WXS.mjs.map → sqlite-statement-classifier-JBHiQO6Q.mjs.map} +1 -1
- package/dist/sqlite-utils-Bfmtkt1b.mjs +2 -0
- package/dist/sqlite-utils-Bfmtkt1b.mjs.map +1 -0
- package/dist/sqlite3.d.mts +2 -46
- package/dist/sqlite3.mjs +1 -1
- package/dist/sqlite3.mjs.map +1 -1
- package/dist/standard-sql-Bl2OHGfi.mjs +6 -0
- package/dist/standard-sql-Bl2OHGfi.mjs.map +1 -0
- package/dist/suppressed-failure-CFUDJrUw.mjs +2 -0
- package/dist/{suppressed-failure-CQkQsMVS.mjs.map → suppressed-failure-CFUDJrUw.mjs.map} +1 -1
- package/dist/surrealdb.d.mts +2 -2
- package/dist/surrealdb.mjs +1 -1
- package/dist/surrealdb.mjs.map +1 -1
- package/dist/surrealql-DY74AUeD.mjs +2 -0
- package/dist/surrealql-DY74AUeD.mjs.map +1 -0
- package/dist/time-step-DJaIhpAz.mjs +2 -0
- package/dist/time-step-DJaIhpAz.mjs.map +1 -0
- package/dist/transaction-Bv5nyp-U.mjs +2 -0
- package/dist/{transaction-BNomMtme.mjs.map → transaction-Bv5nyp-U.mjs.map} +1 -1
- package/dist/transaction-operation-CaWzo7gE.mjs +2 -0
- package/dist/{transaction-operation-CVVJxQ19.mjs.map → transaction-operation-CaWzo7gE.mjs.map} +1 -1
- package/dist/types-Dy33vBdd.mjs +2 -0
- package/dist/{types-DtDnXhwa.mjs.map → types-Dy33vBdd.mjs.map} +1 -1
- package/dist/unit-DUPX5Sdd.mjs +2 -0
- package/dist/{unit-BhHbZyuJ.mjs.map → unit-DUPX5Sdd.mjs.map} +1 -1
- package/dist/unit-words-BXpLpyr2.mjs +2 -0
- package/dist/{unit-words-CT0yeqfZ.mjs.map → unit-words-BXpLpyr2.mjs.map} +1 -1
- package/dist/utils-BHkJsduV.mjs +26 -0
- package/dist/{utils-CpAojrCj.mjs.map → utils-BHkJsduV.mjs.map} +1 -1
- package/dist/v1-parse-shared-cJ-uD14P.mjs +2 -0
- package/dist/v1-parse-shared-cJ-uD14P.mjs.map +1 -0
- package/dist/validation-ATmgN5RE.mjs +2 -0
- package/dist/validation-ATmgN5RE.mjs.map +1 -0
- package/dist/validation-BHjx13zG.mjs +2 -0
- package/dist/validation-BHjx13zG.mjs.map +1 -0
- package/dist/validation.d.mts +1 -1
- package/dist/validation.mjs +1 -1
- package/dist/validator-DMzH5Tz0.mjs +2 -0
- package/dist/validator-DMzH5Tz0.mjs.map +1 -0
- package/dist/value-guards-CBVIJXlI.mjs +2 -0
- package/dist/{value-guards-CBuxSC66.mjs.map → value-guards-CBVIJXlI.mjs.map} +1 -1
- package/dist/values-Ch2cTlss.mjs +2 -0
- package/dist/{values-B4aj1i1f.mjs.map → values-Ch2cTlss.mjs.map} +1 -1
- package/dist/version-0BDwfy7C.mjs +2 -0
- package/dist/{version-CXGIA82S.mjs.map → version-0BDwfy7C.mjs.map} +1 -1
- package/dist/view-CHgjF2BO.mjs +2 -0
- package/dist/view-CHgjF2BO.mjs.map +1 -0
- package/dist/write-sinks-Bei5vFHP.mjs +2 -0
- package/dist/{write-sinks-3IKCDF-S.mjs.map → write-sinks-Bei5vFHP.mjs.map} +1 -1
- package/package.json +50 -37
- package/dist/adapter-internals-DOqI8IlQ.mjs +0 -2
- package/dist/adapter-internals-DOqI8IlQ.mjs.map +0 -1
- package/dist/adapter-namespace-DaRiTIIf.mjs +0 -2
- package/dist/adapter-result-parser-3WP82Cm-.mjs +0 -2
- package/dist/adapter-result-parser-3WP82Cm-.mjs.map +0 -1
- package/dist/args-764KdWMr.mjs +0 -2
- package/dist/array-literal-DHinAnVs.mjs +0 -2
- package/dist/base-z-cH5ZBI.mjs +0 -2
- package/dist/base-z-cH5ZBI.mjs.map +0 -1
- package/dist/batch-refs-C-gx7A4-.mjs +0 -2
- package/dist/bind-parameter-capacity-BMD-bxMO.mjs +0 -2
- package/dist/call-Cz8XUmrl.mjs +0 -2
- package/dist/canonical-json-Bl-fKFF_.mjs +0 -2
- package/dist/canonical-json-Bl-fKFF_.mjs.map +0 -1
- package/dist/chunk-BuuaeEvq.mjs +0 -1
- package/dist/client-DRpX3-vw.mjs +0 -2
- package/dist/client-DRpX3-vw.mjs.map +0 -1
- package/dist/client-y7TV0PRZ.mjs +0 -9
- package/dist/client-y7TV0PRZ.mjs.map +0 -1
- package/dist/confine-DqFBTUw6.mjs +0 -2
- package/dist/coordination-6qZHx_kl.mjs +0 -2
- package/dist/coordination-6qZHx_kl.mjs.map +0 -1
- package/dist/current-DBTlPsQg.mjs +0 -2
- package/dist/current-DBTlPsQg.mjs.map +0 -1
- package/dist/datetime-physical-codec-Dj-APo9f.mjs +0 -2
- package/dist/datetime-physical-codec-Dj-APo9f.mjs.map +0 -1
- package/dist/defaults-DwOHWI_M.mjs +0 -2
- package/dist/driver-BGVcgnIX.mjs +0 -2
- package/dist/driver-BGVcgnIX.mjs.map +0 -1
- package/dist/driver-BIXhOH2_.mjs +0 -2
- package/dist/driver-BIXhOH2_.mjs.map +0 -1
- package/dist/driver-diagnostics-DW9NdckJ.mjs +0 -2
- package/dist/error-mapping-B1-IWkCQ.mjs +0 -2
- package/dist/error-mapping-B1-IWkCQ.mjs.map +0 -1
- package/dist/every-tOgQmaIE.mjs +0 -2
- package/dist/execution-context-BXpcbyPe.mjs +0 -2
- package/dist/execution-context-BXpcbyPe.mjs.map +0 -1
- package/dist/extension-CGepsF-p.mjs +0 -2
- package/dist/fs-estate-D1Nsg9G1.mjs +0 -2
- package/dist/geo-area-codec-mHrM3b9A.mjs +0 -2
- package/dist/geo-area-codec-mHrM3b9A.mjs.map +0 -1
- package/dist/hydration-A3zffFWP.mjs +0 -2
- package/dist/hydration-A3zffFWP.mjs.map +0 -1
- package/dist/identifier-conversion-DHYPTgzr.mjs +0 -2
- package/dist/identifier-conversion-DHYPTgzr.mjs.map +0 -1
- package/dist/identifiers-s00pGES8.mjs +0 -2
- package/dist/identifiers-s00pGES8.mjs.map +0 -1
- package/dist/identity-CtW15WlB.mjs +0 -2
- package/dist/identity-CtW15WlB.mjs.map +0 -1
- package/dist/introspect-Bm6xnXcG.mjs +0 -2
- package/dist/introspect-Bm6xnXcG.mjs.map +0 -1
- package/dist/json-DgMc8-GU.mjs +0 -2
- package/dist/json-DgMc8-GU.mjs.map +0 -1
- package/dist/json-number-AI-SdUUn.mjs +0 -2
- package/dist/json-parameter-oQ8nGaKr.mjs +0 -2
- package/dist/judge-words-CzUyXtJ6.mjs +0 -2
- package/dist/judge-words-CzUyXtJ6.mjs.map +0 -1
- package/dist/key-hxFFCKed.mjs +0 -2
- package/dist/key-hxFFCKed.mjs.map +0 -1
- package/dist/keys-BQxM4c_a.mjs +0 -2
- package/dist/libsql-DuGR904j.mjs +0 -3
- package/dist/libsql-DuGR904j.mjs.map +0 -1
- package/dist/light-BkJe3-yW.mjs +0 -2
- package/dist/memory-G4cSuc6A.mjs +0 -2
- package/dist/methods-part-ZY0f2AV_.mjs +0 -2
- package/dist/methods-part-ZY0f2AV_.mjs.map +0 -1
- package/dist/migrations-BMiRjR-N.mjs +0 -2
- package/dist/mysql-BNXWfTOo.mjs +0 -100
- package/dist/mysql-BNXWfTOo.mjs.map +0 -1
- package/dist/mysql-adapter-C69j1sKh.mjs +0 -2
- package/dist/mysql-adapter-C69j1sKh.mjs.map +0 -1
- package/dist/native-types-DgjMUikz.mjs +0 -2
- package/dist/native-types-DgjMUikz.mjs.map +0 -1
- package/dist/normalized-result-B8pifWS0.mjs +0 -2
- package/dist/normalized-result-B8pifWS0.mjs.map +0 -1
- package/dist/object-store-DS0F0yZX.mjs +0 -2
- package/dist/object-store-DS0F0yZX.mjs.map +0 -1
- package/dist/on-ylYaKuRu.mjs +0 -2
- package/dist/pending-operation-C_eOFOBE.mjs +0 -2
- package/dist/pending-operation-C_eOFOBE.mjs.map +0 -1
- package/dist/physical-CeE2nYmI.mjs +0 -2
- package/dist/physical-CeE2nYmI.mjs.map +0 -1
- package/dist/pinned-session-DCoAZDOz.mjs +0 -2
- package/dist/pinned-session-DCoAZDOz.mjs.map +0 -1
- package/dist/postgres-CDdh5dSP.mjs +0 -437
- package/dist/postgres-CDdh5dSP.mjs.map +0 -1
- package/dist/postgres-adapter-Dlr3ZWd7.mjs +0 -2
- package/dist/postgres-adapter-Dlr3ZWd7.mjs.map +0 -1
- package/dist/postgres-adapter-axapXX8d.mjs +0 -2
- package/dist/postgres-result-DF6DmW3r.mjs +0 -2
- package/dist/postgres-result-DF6DmW3r.mjs.map +0 -1
- package/dist/provider-limits-Ccsb8PTb.mjs +0 -2
- package/dist/provider-limits-Ccsb8PTb.mjs.map +0 -1
- package/dist/provider-parameter-snapshot-BikrgKqI.mjs +0 -2
- package/dist/provider-parameter-snapshot-BikrgKqI.mjs.map +0 -1
- package/dist/query-BZVHfA0s.mjs +0 -2
- package/dist/query-BZVHfA0s.mjs.map +0 -1
- package/dist/query-inspection-BoG-yAln.mjs +0 -2
- package/dist/query-inspection-BoG-yAln.mjs.map +0 -1
- package/dist/raw-Dyq6Y6UX.mjs +0 -2
- package/dist/raw-Dyq6Y6UX.mjs.map +0 -1
- package/dist/relation-bound-ku_cMdye.mjs +0 -2
- package/dist/result-parsing-B0Y4KGDT.mjs +0 -2
- package/dist/routed-operations-wytpbYKv.mjs +0 -2
- package/dist/rule-words-ZIGm7cDm.mjs +0 -2
- package/dist/scalar-BHCh7aUz.mjs +0 -4
- package/dist/scalar-BHCh7aUz.mjs.map +0 -1
- package/dist/schema-BYA-_bpk.mjs +0 -2
- package/dist/schema-BYA-_bpk.mjs.map +0 -1
- package/dist/schema-CFIaebgi.mjs +0 -2
- package/dist/schema-CFIaebgi.mjs.map +0 -1
- package/dist/schema-introspection-D0f8cti4.mjs +0 -6
- package/dist/schema-introspection-D0f8cti4.mjs.map +0 -1
- package/dist/select-assembly-DVI7d3tf.mjs +0 -2
- package/dist/select-assembly-DVI7d3tf.mjs.map +0 -1
- package/dist/serializer-rBq3v1xr.mjs +0 -51
- package/dist/serializer-rBq3v1xr.mjs.map +0 -1
- package/dist/settle-1cy5x_52.mjs +0 -2
- package/dist/settled-BjyuA76m.mjs +0 -2
- package/dist/snowflake-UOCC820W.mjs +0 -2
- package/dist/sql-3o4DOKm9.mjs +0 -2
- package/dist/sql-3o4DOKm9.mjs.map +0 -1
- package/dist/sql-Dl6nykFV.mjs +0 -2
- package/dist/sql-Dl6nykFV.mjs.map +0 -1
- package/dist/sql-statement-tokens-DbeMwHra.mjs +0 -3
- package/dist/sqlite-adapter-Ad0d-m2t.mjs +0 -2
- package/dist/sqlite-adapter-Ad0d-m2t.mjs.map +0 -1
- package/dist/sqlite-statement-classifier-BAHl-WXS.mjs +0 -2
- package/dist/sqlite-utils-BRvbmlQ1.mjs +0 -2
- package/dist/sqlite-utils-BRvbmlQ1.mjs.map +0 -1
- package/dist/standard-sql-qLcQyCtK.mjs +0 -6
- package/dist/standard-sql-qLcQyCtK.mjs.map +0 -1
- package/dist/suppressed-failure-CQkQsMVS.mjs +0 -2
- package/dist/surrealql-C1dp1sWw.mjs +0 -2
- package/dist/surrealql-C1dp1sWw.mjs.map +0 -1
- package/dist/to-many-BybuKQM1.mjs +0 -2
- package/dist/to-many-BybuKQM1.mjs.map +0 -1
- package/dist/transaction-BNomMtme.mjs +0 -2
- package/dist/transaction-operation-CVVJxQ19.mjs +0 -2
- package/dist/types-DtDnXhwa.mjs +0 -2
- package/dist/unit-BhHbZyuJ.mjs +0 -2
- package/dist/unit-words-CT0yeqfZ.mjs +0 -2
- package/dist/utils-CpAojrCj.mjs +0 -26
- package/dist/validation--qS7OPmg.mjs +0 -2
- package/dist/validation--qS7OPmg.mjs.map +0 -1
- package/dist/validation-CYaJ8ndO.mjs +0 -2
- package/dist/validation-CYaJ8ndO.mjs.map +0 -1
- package/dist/validator-CZLW7aR3.mjs +0 -2
- package/dist/validator-CZLW7aR3.mjs.map +0 -1
- package/dist/value-guards-CBuxSC66.mjs +0 -2
- package/dist/values-B4aj1i1f.mjs +0 -2
- package/dist/version-CXGIA82S.mjs +0 -2
- package/dist/write-sinks-3IKCDF-S.mjs +0 -2
- /package/dist/{contract-CrIB-3ZJ.d.mts → contract-CxJn0_cV.d.mts} +0 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types-DtDnXhwa.mjs","names":[],"sources":["../src/schema/relation/types.ts"],"sourcesContent":["// The canonical relation declaration representation.\n//\n// A declaration states exactly two independent facts: the SLOT CARDINALITY the\n// factory was spelled with (`toOne` / `toMany`) and the TARGET DOMAIN its\n// argument names (one model, or named variants). Everything else about an edge —\n// which endpoint owns the foreign key, whether storage is a row FK or a\n// junction, whether the pair is one-to-one or many-to-many, whether a\n// model-target singular slot may be empty — is DERIVED by the full-schema\n// topology owner and is deliberately absent from this union.\n\nimport type { AnyModel } from \"@schema/model\";\n\n/** Workaround to allow circular dependencies */\nexport type Getter = () => any;\n\n/** Referential action for foreign key constraints */\nexport type ReferentialAction = \"cascade\" | \"setNull\" | \"restrict\" | \"noAction\";\n\n/**\n * `setNull` is absent because every junction side is a non-null membership-key\n * member: the action would null a column that carries the membership itself.\n */\nexport type JunctionReferentialAction = Exclude<ReferentialAction, \"setNull\">;\n\n/**\n * One junction action per foreign key, named by the DECLARING endpoint:\n * `source` is the junction's foreign key to the model whose slot carries the\n * declaration, `target` the one to that slot's target model. Never the\n * alphabetical column order, and never whichever endpoint a query traverses.\n * A bare action is the symmetric shorthand for both.\n */\nexport type JunctionSideActions = {\n readonly source: JunctionReferentialAction;\n readonly target: JunctionReferentialAction;\n};\n\n/**\n * Last-call-wins at the type level: every modifier returns a new value whose\n * state REPLACES its own fact rather than intersecting with the prior one, so\n * repeating `.name(...)` keeps the last literal instead of collapsing to\n * `never`.\n */\nexport type Replace<State, Patch> = Omit<State, keyof Patch> & Patch;\n\n/**\n * The getter overload's phantom refusal — the counterpart of\n * `VariantMapGuard`. It uniquely owns \"not a map at all and not a getter\": the\n * map overload is tried first, so without this guard a direct model object or a\n * malformed map reaching the getter overload would answer `never`, and `never`\n * is assignable to a model shape, which makes the refusal vanish.\n */\nexport type GetterOnly<G> = G extends Getter\n ? unknown\n : {\n readonly \"a relation target is either `() => model` or a map of named `() => model` getters\": never;\n };\n\n/** How many rows one slot addresses. */\nexport type RelationCardinality = \"one\" | \"many\";\n\n// =============================================================================\n// TARGET DOMAIN\n// =============================================================================\n\nexport type ModelTarget<G = any> = {\n readonly kind: \"model\";\n readonly getter: G;\n};\n\n/** One member junction's table and its two DIRECTED side naming tokens. */\nexport type VariantJunctionOverride = {\n readonly table: string;\n readonly source: string;\n readonly target: string;\n};\n\n/**\n * One normalized variant. The public map key stays the query/result/mutation\n * discriminator; `storedValue` is the string written to storage. They are two\n * facts, and a renamed public key with a preserved stored value is\n * metadata-only.\n */\nexport type VariantEntry<G = any> = {\n readonly getter: G;\n readonly storedValue: string;\n};\n\nexport type VariantOneEntry<G = any> = VariantEntry<G> & {\n readonly junction?: never;\n};\n\nexport type VariantManyEntry<G = any> = VariantEntry<G> & {\n readonly junction?: VariantJunctionOverride;\n};\n\nexport type VariantTarget<\n Entries extends Readonly<Record<string, VariantEntry<any>>>,\n> = {\n readonly kind: \"variants\";\n readonly entries: Entries;\n};\n\n// =============================================================================\n// FOREIGN KEY AND JUNCTION CONFIGURATION\n// =============================================================================\n\nexport type NonEmptyFieldTuple = readonly [string, ...string[]];\n\n/**\n * The complete result of `.fields(...).references(...)`, plus the referential\n * actions that are only meaningful once that complete reference exists. A\n * partial foreign key is never a value of this type: the transient references\n * stage holds the local tuple until `.references(...)` completes the pair.\n */\nexport type ForeignKeyDeclaration<\n Fields extends NonEmptyFieldTuple = NonEmptyFieldTuple,\n References extends NonEmptyFieldTuple = NonEmptyFieldTuple,\n> = {\n readonly fields: Fields;\n readonly references: References;\n readonly onDelete?: ReferentialAction;\n readonly onUpdate?: ReferentialAction;\n};\n\ntype AtLeastOne<Value> = {\n [Key in keyof Value]-?: Required<Pick<Value, Key>> &\n Partial<Omit<Value, Key>>;\n}[keyof Value];\n\n/**\n * Any subset of the canonical junction defaults, but never the empty object:\n * trusted state stores an override only when an override was declared. An\n * action is stored in its one normalized form, the side pair, whichever\n * spelling declared it.\n */\nexport type OrdinaryJunctionOverrides = AtLeastOne<{\n readonly table?: string;\n /**\n * The declared model that IS the junction, as its thunk: the two overloads of\n * `.through()` write `table` or this, never both. `any`-returning for the same\n * reason as a relation's getter (above): a resolved return type here is\n * circular in the mutually recursive consts a junction model always forms.\n */\n readonly model?: () => any;\n /** With `model`, the to-one relations of the junction model each side reads. */\n readonly source?: string;\n readonly target?: string;\n readonly onDelete?: JunctionSideActions;\n readonly onUpdate?: JunctionSideActions;\n}>;\n\n// =============================================================================\n// THE CLOSED STATE UNION\n// =============================================================================\n\n/**\n * The broad state arms deliberately use `any` for the getter, not `G extends\n * Getter`: constraining a function-typed member forces TypeScript to resolve\n * recursive getter returns, and that resolution is circular in mutually\n * recursive schemas and silently collapses both model consts to `any`.\n * Comparing against `any` short-circuits without touching the return type.\n * Concrete factory states retain the exact getter or getter-map generic.\n */\nexport type ModelToOneState<\n G = any,\n ForeignKey extends ForeignKeyDeclaration | undefined =\n | ForeignKeyDeclaration\n | undefined,\n> = {\n readonly kind: \"relation\";\n readonly cardinality: \"one\";\n readonly target: ModelTarget<G>;\n readonly name?: string;\n readonly junction?: never;\n readonly optional?: never;\n} & (ForeignKey extends ForeignKeyDeclaration\n ? { readonly foreignKey: ForeignKey }\n : { readonly foreignKey?: never });\n\nexport type ModelToManyState<G = any> = {\n readonly kind: \"relation\";\n readonly cardinality: \"many\";\n readonly target: ModelTarget<G>;\n readonly name?: string;\n readonly junction?: OrdinaryJunctionOverrides;\n readonly foreignKey?: never;\n readonly optional?: never;\n};\n\nexport type VariantToOneState<\n Entries extends Readonly<Record<string, VariantOneEntry<any>>> = Readonly<\n Record<string, VariantOneEntry<any>>\n >,\n> = {\n readonly kind: \"relation\";\n readonly cardinality: \"one\";\n readonly target: VariantTarget<Entries>;\n readonly name?: string;\n readonly optional?: true;\n readonly foreignKey?: never;\n readonly junction?: never;\n};\n\nexport type VariantToManyState<\n Entries extends Readonly<Record<string, VariantManyEntry<any>>> = Readonly<\n Record<string, VariantManyEntry<any>>\n >,\n> = {\n readonly kind: \"relation\";\n readonly cardinality: \"many\";\n readonly target: VariantTarget<Entries>;\n readonly name?: string;\n readonly foreignKey?: never;\n readonly junction?: never;\n readonly optional?: never;\n};\n\n/**\n * Optional properties use one canonical representation: the property is absent,\n * or it holds the one normalized value. Trusted state never stores explicit\n * `undefined`, `false`, an empty override object, or a partial foreign key. The\n * `?: never` exclusions make illegal cross-arm configuration fail under\n * structural assignment too, so the algebra does not rely on excess-property\n * checking or factory etiquette.\n */\nexport type RelationState =\n | ModelToOneState\n | ModelToManyState\n | VariantToOneState\n | VariantToManyState;\n\n/**\n * The two arms of one TARGET DOMAIN, named because the derived views split on\n * that axis before they split on anything else (§8.2): a variant target has a\n * discriminated element union, a discriminated projection envelope, and its own\n * family key set, whatever its cardinality.\n */\nexport type VariantRelationState = VariantToOneState | VariantToManyState;\n\n/**\n * The predicate for {@link VariantRelationState} — one declared property read,\n * spelled once so both halves of a target-domain partition ask it the same way.\n * It classifies a declaration; it resolves nothing.\n */\nexport const isVariantRelationState = (\n state: RelationState\n): state is VariantRelationState => state.target.kind === \"variants\";\n\n// =============================================================================\n// INTERNAL ACCESSOR\n// =============================================================================\n\n/**\n * The internal accessor every terminal exposes under `\"~\"`.\n *\n * `settleTarget` is the source-independent lazy once-cell required by the\n * declaration algebra: the first caller settles a target's raw getter return OR\n * one normalized `Error`, and every later consumer — in this schema graph or\n * another one reusing the same immutable terminal — observes that same outcome.\n * It is derived cache state, not a declaration fact; the resolver decides\n * whether a settled return is a registered model and owns the contextual\n * diagnostic, so nothing model-specific is cached here.\n */\nexport type RelationInternal<State> = {\n readonly state: State;\n /** Variant key for a variant target; omitted for a model target. */\n readonly settleTarget: (variantKey?: string) => unknown;\n /** The `.through(() => model)` thunk's answer, read once; a model-target collection's only. */\n readonly settleJunctionModel?: () => unknown;\n};\n\n/** Any relation terminal, matched by its internal brand. */\nexport type AnyRelation = { readonly \"~\": RelationInternal<RelationState> };\n\n/**\n * The identity of a contextual relation reference.\n *\n * A relation object does not store its source model: `.extends()` may reuse one\n * terminal under more than one model or key, so the source model plus the field\n * key is the whole identity and the declaration is read from that model's\n * canonical relation map rather than copied into the identity.\n */\nexport type RelationSlot = {\n readonly source: AnyModel;\n readonly field: string;\n};\n"],"mappings":"yCAoPA,MAAa,uBACX,GACkC,EAAM,OAAO,OAAS"}
|
|
1
|
+
{"version":3,"file":"types-Dy33vBdd.mjs","names":[],"sources":["../src/schema/relation/types.ts"],"sourcesContent":["// The canonical relation declaration representation.\n//\n// A declaration states exactly two independent facts: the SLOT CARDINALITY the\n// factory was spelled with (`toOne` / `toMany`) and the TARGET DOMAIN its\n// argument names (one model, or named variants). Everything else about an edge —\n// which endpoint owns the foreign key, whether storage is a row FK or a\n// junction, whether the pair is one-to-one or many-to-many, whether a\n// model-target singular slot may be empty — is DERIVED by the full-schema\n// topology owner and is deliberately absent from this union.\n\nimport type { AnyModel } from \"@schema/model\";\n\n/** Workaround to allow circular dependencies */\nexport type Getter = () => any;\n\n/** Referential action for foreign key constraints */\nexport type ReferentialAction = \"cascade\" | \"setNull\" | \"restrict\" | \"noAction\";\n\n/**\n * `setNull` is absent because every junction side is a non-null membership-key\n * member: the action would null a column that carries the membership itself.\n */\nexport type JunctionReferentialAction = Exclude<ReferentialAction, \"setNull\">;\n\n/**\n * One junction action per foreign key, named by the DECLARING endpoint:\n * `source` is the junction's foreign key to the model whose slot carries the\n * declaration, `target` the one to that slot's target model. Never the\n * alphabetical column order, and never whichever endpoint a query traverses.\n * A bare action is the symmetric shorthand for both.\n */\nexport type JunctionSideActions = {\n readonly source: JunctionReferentialAction;\n readonly target: JunctionReferentialAction;\n};\n\n/**\n * Last-call-wins at the type level: every modifier returns a new value whose\n * state REPLACES its own fact rather than intersecting with the prior one, so\n * repeating `.name(...)` keeps the last literal instead of collapsing to\n * `never`.\n */\nexport type Replace<State, Patch> = Omit<State, keyof Patch> & Patch;\n\n/**\n * The getter overload's phantom refusal — the counterpart of\n * `VariantMapGuard`. It uniquely owns \"not a map at all and not a getter\": the\n * map overload is tried first, so without this guard a direct model object or a\n * malformed map reaching the getter overload would answer `never`, and `never`\n * is assignable to a model shape, which makes the refusal vanish.\n */\nexport type GetterOnly<G> = G extends Getter\n ? unknown\n : {\n readonly \"a relation target is either `() => model` or a map of named `() => model` getters\": never;\n };\n\n/** How many rows one slot addresses. */\nexport type RelationCardinality = \"one\" | \"many\";\n\n// =============================================================================\n// TARGET DOMAIN\n// =============================================================================\n\nexport type ModelTarget<G = any> = {\n readonly kind: \"model\";\n readonly getter: G;\n};\n\n/** One member junction's table and its two DIRECTED side naming tokens. */\nexport type VariantJunctionOverride = {\n readonly table: string;\n readonly source: string;\n readonly target: string;\n};\n\n/**\n * One normalized variant. The public map key stays the query/result/mutation\n * discriminator; `storedValue` is the string written to storage. They are two\n * facts, and a renamed public key with a preserved stored value is\n * metadata-only.\n */\nexport type VariantEntry<G = any> = {\n readonly getter: G;\n readonly storedValue: string;\n};\n\nexport type VariantOneEntry<G = any> = VariantEntry<G> & {\n readonly junction?: never;\n};\n\nexport type VariantManyEntry<G = any> = VariantEntry<G> & {\n readonly junction?: VariantJunctionOverride;\n};\n\nexport type VariantTarget<\n Entries extends Readonly<Record<string, VariantEntry<any>>>,\n> = {\n readonly kind: \"variants\";\n readonly entries: Entries;\n};\n\n// =============================================================================\n// FOREIGN KEY AND JUNCTION CONFIGURATION\n// =============================================================================\n\nexport type NonEmptyFieldTuple = readonly [string, ...string[]];\n\n/**\n * The complete result of `.fields(...).references(...)`, plus the referential\n * actions that are only meaningful once that complete reference exists. A\n * partial foreign key is never a value of this type: the transient references\n * stage holds the local tuple until `.references(...)` completes the pair.\n */\nexport type ForeignKeyDeclaration<\n Fields extends NonEmptyFieldTuple = NonEmptyFieldTuple,\n References extends NonEmptyFieldTuple = NonEmptyFieldTuple,\n> = {\n readonly fields: Fields;\n readonly references: References;\n readonly onDelete?: ReferentialAction;\n readonly onUpdate?: ReferentialAction;\n};\n\ntype AtLeastOne<Value> = {\n [Key in keyof Value]-?: Required<Pick<Value, Key>> &\n Partial<Omit<Value, Key>>;\n}[keyof Value];\n\n/**\n * Any subset of the canonical junction defaults, but never the empty object:\n * trusted state stores an override only when an override was declared. An\n * action is stored in its one normalized form, the side pair, whichever\n * spelling declared it.\n */\nexport type OrdinaryJunctionOverrides = AtLeastOne<{\n readonly table?: string;\n /**\n * The declared model that IS the junction, as its thunk: the two overloads of\n * `.through()` write `table` or this, never both. `any`-returning for the same\n * reason as a relation's getter (above): a resolved return type here is\n * circular in the mutually recursive consts a junction model always forms.\n */\n readonly model?: () => any;\n /** With `model`, the to-one relations of the junction model each side reads. */\n readonly source?: string;\n readonly target?: string;\n readonly onDelete?: JunctionSideActions;\n readonly onUpdate?: JunctionSideActions;\n}>;\n\n// =============================================================================\n// THE CLOSED STATE UNION\n// =============================================================================\n\n/**\n * The broad state arms deliberately use `any` for the getter, not `G extends\n * Getter`: constraining a function-typed member forces TypeScript to resolve\n * recursive getter returns, and that resolution is circular in mutually\n * recursive schemas and silently collapses both model consts to `any`.\n * Comparing against `any` short-circuits without touching the return type.\n * Concrete factory states retain the exact getter or getter-map generic.\n */\nexport type ModelToOneState<\n G = any,\n ForeignKey extends ForeignKeyDeclaration | undefined =\n | ForeignKeyDeclaration\n | undefined,\n> = {\n readonly kind: \"relation\";\n readonly cardinality: \"one\";\n readonly target: ModelTarget<G>;\n readonly name?: string;\n readonly junction?: never;\n readonly optional?: never;\n} & (ForeignKey extends ForeignKeyDeclaration\n ? { readonly foreignKey: ForeignKey }\n : { readonly foreignKey?: never });\n\nexport type ModelToManyState<G = any> = {\n readonly kind: \"relation\";\n readonly cardinality: \"many\";\n readonly target: ModelTarget<G>;\n readonly name?: string;\n readonly junction?: OrdinaryJunctionOverrides;\n readonly foreignKey?: never;\n readonly optional?: never;\n};\n\nexport type VariantToOneState<\n Entries extends Readonly<Record<string, VariantOneEntry<any>>> = Readonly<\n Record<string, VariantOneEntry<any>>\n >,\n> = {\n readonly kind: \"relation\";\n readonly cardinality: \"one\";\n readonly target: VariantTarget<Entries>;\n readonly name?: string;\n readonly optional?: true;\n readonly foreignKey?: never;\n readonly junction?: never;\n};\n\nexport type VariantToManyState<\n Entries extends Readonly<Record<string, VariantManyEntry<any>>> = Readonly<\n Record<string, VariantManyEntry<any>>\n >,\n> = {\n readonly kind: \"relation\";\n readonly cardinality: \"many\";\n readonly target: VariantTarget<Entries>;\n readonly name?: string;\n readonly foreignKey?: never;\n readonly junction?: never;\n readonly optional?: never;\n};\n\n/**\n * Optional properties use one canonical representation: the property is absent,\n * or it holds the one normalized value. Trusted state never stores explicit\n * `undefined`, `false`, an empty override object, or a partial foreign key. The\n * `?: never` exclusions make illegal cross-arm configuration fail under\n * structural assignment too, so the algebra does not rely on excess-property\n * checking or factory etiquette.\n */\nexport type RelationState =\n | ModelToOneState\n | ModelToManyState\n | VariantToOneState\n | VariantToManyState;\n\n/**\n * The two arms of one TARGET DOMAIN, named because the derived views split on\n * that axis before they split on anything else (§8.2): a variant target has a\n * discriminated element union, a discriminated projection envelope, and its own\n * family key set, whatever its cardinality.\n */\nexport type VariantRelationState = VariantToOneState | VariantToManyState;\n\n/**\n * The predicate for {@link VariantRelationState} — one declared property read,\n * spelled once so both halves of a target-domain partition ask it the same way.\n * It classifies a declaration; it resolves nothing.\n */\nexport const isVariantRelationState = (\n state: RelationState\n): state is VariantRelationState => state.target.kind === \"variants\";\n\n// =============================================================================\n// INTERNAL ACCESSOR\n// =============================================================================\n\n/**\n * The internal accessor every terminal exposes under `\"~\"`.\n *\n * `settleTarget` is the source-independent lazy once-cell required by the\n * declaration algebra: the first caller settles a target's raw getter return OR\n * one normalized `Error`, and every later consumer — in this schema graph or\n * another one reusing the same immutable terminal — observes that same outcome.\n * It is derived cache state, not a declaration fact; the resolver decides\n * whether a settled return is a registered model and owns the contextual\n * diagnostic, so nothing model-specific is cached here.\n */\nexport type RelationInternal<State> = {\n readonly state: State;\n /** Variant key for a variant target; omitted for a model target. */\n readonly settleTarget: (variantKey?: string) => unknown;\n /** The `.through(() => model)` thunk's answer, read once; a model-target collection's only. */\n readonly settleJunctionModel?: () => unknown;\n};\n\n/** Any relation terminal, matched by its internal brand. */\nexport type AnyRelation = { readonly \"~\": RelationInternal<RelationState> };\n\n/**\n * The identity of a contextual relation reference.\n *\n * A relation object does not store its source model: `.extends()` may reuse one\n * terminal under more than one model or key, so the source model plus the field\n * key is the whole identity and the declaration is read from that model's\n * canonical relation map rather than copied into the identity.\n */\nexport type RelationSlot = {\n readonly source: AnyModel;\n readonly field: string;\n};\n"],"mappings":"AAoPA,MAAa,EACX,GACkC,EAAM,OAAO,OAAS"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{S as e,g as t}from"./base-17NSFtrA.mjs";import{m as n,p as r}from"./unit-words-BXpLpyr2.mjs";function i(n,r={}){return t(e(n)?n:Error(`A non-Error value failed.`),{includeSql:r.sql===!0,includeParams:r.parameters===!0})}function a(e){let t={includeSql:e.sql===!0,includeParams:e.parameters===!0,includeProviderDetails:e.providerDetails===!0,includeCallsite:e.callsite===!0};return{join({next:e}){e.disclosure=t}}}function o(e){return{join({next:t,owner:n}){t.rewrites=r([...t.rewrites?.cq??[],{extension:n.name,handler:e}])}}}function s(e,t,r){return r?.rewrites===!0?o(e):n(e,t)}export{a as n,i as r,s as t};
|
|
2
|
+
//# sourceMappingURL=unit-DUPX5Sdd.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"unit-
|
|
1
|
+
{"version":3,"file":"unit-DUPX5Sdd.mjs","names":["disclosed"],"sources":["../src/extensions/disclosed.ts","../src/extensions/disclosure.ts","../src/extensions/statement.ts","../src/extensions/unit.ts"],"sourcesContent":["/**\n * `disclosed(error, { sql?, parameters? })`: what a log or a span may show of\n * a failure. A `unit` handler that presents `failure(u)`, or an error another\n * extension noted, presents this copy, never the error itself: the error may\n * carry a provider's message, its stack, statement text or parameter values\n * the application's `disclosure` hides, and it may be any value at all.\n */\nimport { sanitizeErrorForLogging } from \"@errors\";\nimport { isError } from \"../errors/diagnostic-safety\";\nimport type { DisclosurePolicy } from \"./disclosure\";\n\n/**\n * A new `Error`, safe to log or to put on a span, made from `error`.\n *\n * Of an error the package made (a `VibORMError`: every error the library\n * throws), it keeps what the package recorded when it built the error: its\n * `name`, `message`, `code`, `prismaCode`, `timestamp`, the `meta` keys the\n * package knows, and its causes. Of any other `Error`, it keeps the name\n * `\"Error\"`, the message `\"Error details redacted\"`, those of its own `code`,\n * `errno`, `sqlState`, `status` and `statusCode` that have the shape of a\n * code (`ECONNRESET`, a SQLSTATE, an HTTP status), and its causes.\n *\n * It removes the stack, always, and every property not named above. A\n * cause's message, `detail` and `hint` (a provider's words) are replaced by\n * `\"Underlying error details redacted\"` unless the application's\n * `disclosure` allowed `providerDetails` when the error was built; then they\n * are kept with the credentials in URLs, `password=…`, `token=…`,\n * `secret=…` and `Bearer …` redacted. A `callsite` is kept only where the\n * application's `disclosure` allowed `callsite`. Statement text (`meta.sql`)\n * is kept only with `allow.sql`, parameter values (`meta.params`) only with\n * `allow.parameters`; what the application's `disclosure` hid is not in the\n * error at all, so `allow` can only hide more.\n *\n * Bounds: a cause seen twice (a cycle) becomes an error `\"[Circular]\"`, a\n * chain deeper than eight causes `\"[Truncated]\"`; a string is cut at 4,096\n * characters, the whole copy at 32,768.\n *\n * A value that is not an `Error` (a string, a plain object, `undefined`)\n * gives `Error: Error details redacted`, and nothing of it but its prototype\n * chain is read.\n *\n * What it reads of an `Error`: its prototype chain (`instanceof`), the\n * package's own record of it, and its own data properties through their\n * descriptors, so a getter on them never runs; `originalCause` and `cause`\n * are read as properties, so a getter there runs, at most once per error of\n * the chain and per call. Each call reads again: call it once per failure\n * and keep the copy. It never throws: what cannot be read is left out.\n */\nexport function disclosed(\n error: unknown,\n allow: Pick<DisclosurePolicy, \"sql\" | \"parameters\"> = {}\n): Error {\n // An error the package did not make shows no message: this one neither.\n const made = isError(error) ? error : new Error(\"A non-Error value failed.\");\n return sanitizeErrorForLogging(made, {\n includeSql: allow.sql === true,\n includeParams: allow.parameters === true,\n });\n}\n","/**\n * `disclosure({ sql?, parameters?, providerDetails?, callsite? })`: what an\n * error thrown by a call of the chain may carry. The core reads the chain's\n * policy where it builds an error, naming no extension; without this part,\n * an error discloses what it does by default.\n */\nimport type { DiagnosticDisclosure } from \"@errors\";\nimport type { ExtensionPart } from \"./chain\";\nimport type { AnyTarget, EmptyFacts, Part } from \"./contract\";\n\n/** What one disclosure part allows, as an error reads it. */\nexport interface DisclosurePolicy {\n readonly sql?: boolean;\n readonly parameters?: boolean;\n readonly providerDetails?: boolean;\n readonly callsite?: boolean;\n}\n\n/** What an error thrown by a call of the chain may carry. */\nexport function disclosure<T extends AnyTarget>(\n policy: DisclosurePolicy\n): Part<T, EmptyFacts>;\nexport function disclosure(policy: DisclosurePolicy): unknown {\n const disclosed: DiagnosticDisclosure = {\n includeSql: policy.sql === true,\n includeParams: policy.parameters === true,\n includeProviderDetails: policy.providerDetails === true,\n includeCallsite: policy.callsite === true,\n };\n const part: ExtensionPart = {\n join({ next }) {\n next.disclosure = disclosed;\n },\n };\n return part;\n}\n","/**\n * The rewriting units of a chain (`unit(fn, kinds, { rewrites: true })`).\n * Each is a unit around one logical statement: `statement(unit)` reads the\n * statement as the earlier rewrites left it, `next(sql)` hands on what is\n * sent (unchanged without an argument), and resolves with how the statement\n * ended. Inside the innermost `next()` the statement is rendered and sent,\n * as its own `statement` unit around the provider call. A chain with one is\n * never served by the cache, and verbatim unsafe raw queries are never\n * rewritten.\n */\nimport type { ExtensionPart } from \"./chain\";\nimport { observationOf } from \"./observation\";\nimport type { UnitHandler } from \"./unit-source\";\n\n/** The part `unit(handler, kinds, { rewrites: true })` builds. */\nexport function rewritePart(handler: UnitHandler): ExtensionPart {\n return {\n join({ next, owner }) {\n next.rewrites = observationOf([\n ...(next.rewrites?.handlers ?? []),\n { extension: owner.name, handler },\n ]);\n },\n };\n}\n","/**\n * `unit((u, next) => …, kinds?, options?)`: a function around each unit of\n * real work (an operation, a statement, a batch, a transaction, a savepoint,\n * a connection, or a unit an extension emits with `work`). Observing is\n * calling `next()` and reading how the unit ended; what the handler throws\n * fails the call. A part declared `{ rewrites: true }` sends another\n * statement: `next(sql)`, once per logical statement, before rendering.\n */\nimport type { Sql } from \"@sql\";\nimport type {\n AnyTarget,\n EmptyFacts,\n Part,\n UnitContext,\n UnitKind,\n UnitOf,\n UnitOutcome,\n} from \"./contract\";\nimport { unitLayerPart } from \"./observation\";\nimport { rewritePart } from \"./statement\";\n\n/** A function around each unit of the kinds named (every kind when absent). */\nexport function unit<\n T extends AnyTarget,\n Rewrites extends true | undefined = undefined,\n>(\n around: (\n unit: UnitOf<Rewrites>,\n next: (sql?: Sql) => Promise<UnitOutcome>\n ) => unknown,\n kinds?: readonly UnitKind[],\n options?: { readonly rewrites?: Rewrites }\n): Part<T, EmptyFacts>;\nexport function unit(\n handler: (unit: UnitContext, next: () => Promise<UnitOutcome>) => unknown,\n kinds?: readonly UnitKind[],\n options?: { readonly rewrites?: true }\n): unknown {\n return options?.rewrites === true\n ? rewritePart(handler)\n : unitLayerPart(handler, kinds);\n}\n"],"mappings":"oGAgDA,SAAgB,EACd,EACA,EAAsD,EAAE,CACjD,CAGP,OAAO,EADM,EAAQ,EAAM,CAAG,EAAY,MAAM,4BAA4B,CACvC,CACnC,WAAY,EAAM,MAAQ,GAC1B,cAAe,EAAM,aAAe,GACrC,CAAC,CCnCJ,SAAgB,EAAW,EAAmC,CAC5D,IAAMA,EAAkC,CACtC,WAAY,EAAO,MAAQ,GAC3B,cAAe,EAAO,aAAe,GACrC,uBAAwB,EAAO,kBAAoB,GACnD,gBAAiB,EAAO,WAAa,GACtC,CAMD,MAL4B,CAC1B,KAAK,CAAE,QAAQ,CACb,EAAK,WAAaA,GAErB,CClBH,SAAgB,EAAY,EAAqC,CAC/D,MAAO,CACL,KAAK,CAAE,OAAM,SAAS,CACpB,EAAK,SAAW,EAAc,CAC5B,GAAI,EAAK,UAAU,UAAY,EAAE,CACjC,CAAE,UAAW,EAAM,KAAM,UAAS,CACnC,CAAC,EAEL,CCUH,SAAgB,EACd,EACA,EACA,EACS,CACT,OAAO,GAAS,WAAa,GACzB,EAAY,EAAQ,CACpB,EAAc,EAAS,EAAM"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{U as e,V as t,g as n,z as r}from"./error-mapping-B9rSvgG9.mjs";import{p as i}from"./validation-ATmgN5RE.mjs";import{t as a}from"./sql-tegqTqGq.mjs";import{f as o,i as s,m as c,o as l,r as u}from"./coordination-BxMskOgi.mjs";import{t as d}from"./execution-context-couU2tgh.mjs";import{i as f,n as p,t as m}from"./driver-diagnostics-aQ54bArn.mjs";var h=class{kind;model;operation;#e;constructor(e){this.kind=e.kind,this.model=e.model,this.operation=Object.hasOwn(e,`operation`)?e.operation:e.context?.operation,this.#e=e}static c6(e){return#e in e?e.#e:void 0}};const g=new WeakMap,_=e=>h.c6(e);function v(e){let t=new h(e);return e.notes??=[],e.kind===`operation`&&e.context!==void 0&&g.set(e.context,e),t}function y(e){let t=o(e)?.of?.context;return _(e)??(t===void 0?g.get(e):g.get(t))}const b=()=>void 0;function x(e,t,n,r){let i=v(t),a,o=()=>(a??=S(()=>n(t.statement)),a),s=t.kind===`transaction`?E(t,o):void 0,c=n=>{let a=e[n];return a?.f7?.includes(t.kind)===!1?c(n+1):a===void 0?(r?.(),s?.enter(),o()):C(a,i,t,()=>c(n+1))},l=c(0);return s===void 0?l:l.catch(s.fail)}function S(e){try{return e()}catch(e){return Promise.reject(e)}}async function C(e,t,n,r){let i,o,s=s=>{if(i!==void 0)return o??=T(e,t,`called next() more than once`),Promise.reject(o);let c=Date.now(),l=s!==void 0&&n.statement!==void 0;return l&&!(s instanceof a)?i=Promise.reject(T(e,t,`handed next() something not a statement`)):(l&&(n.statement=s),i=r()),i.then(()=>w(n,c,!1,void 0),e=>w(n,c,!0,e))},c;try{await e.handler(t,s)}catch(e){c={failure:e}}if(i===void 0)throw c?.failure??T(e,t,`settled without calling next()`);let l=await i;if(c!==void 0)throw c.failure;if(o!==void 0)throw o;return l}function w(e,n,r,i){e.failed=r,e.failure=i,e.settledAt??=Date.now();let a=e.certainty?.();return{status:r?`failure`:`success`,duration:Math.max(0,e.settledAt-n),...a===void 0?{}:{certainty:a},...r&&t(e.context)?{recovered:!0}:{}}}function T(e,t,n){return new i(`Extension "${e.extension}" unit() for ${t.kind} ${n}.`,{meta:{method:`unit`,operation:t.operation,model:t.model}})}function E(e,t){let n,r,a,o,s=!1,c,l,u=new Promise(e=>{l=e});return e.opened=e=>{if(n=e,l?.(e),o!==void 0)return Promise.reject(o.failure);if(!s)return new Promise((e,t)=>{r=e,a=t})},e.run=e=>n===void 0?(c??=t(),Promise.race([u,c.then(()=>{throw new i(`run() was called on a transaction that ended.`)})]).then(t=>t(e))):n(e),{enter:()=>{s=!0,r?.()},fail:e=>{if(c===void 0||s)throw e;return o={failure:e},a?.(e),c.catch(b).then(()=>{throw e})}}}function D(e){let t=(t,n)=>{let r,i=new Promise(e=>{r=e}),a=x(e,t,n,r);return a.then(r,r),{done:a,reached:i}},n=async e=>{let n=e.map(e=>e===void 0?void 0:t(e[0],e[1]));await Promise.all(n.map(e=>e?.reached));let r=Promise.all(n.map(e=>e?.done));return r.catch(()=>void 0),{done:r,h8:n}};return{cq:e,run:(t,n)=>x(e,t,n),members:n,xf:async(e,t,r)=>{let i=[],a,o=new Promise(e=>{a=e}),{done:s,h8:c}=await n(e.map((e,t)=>e===void 0?void 0:[e,e=>(i[t]=e,o)])),l=c.findIndex((e,t)=>e!==void 0&&!(t in i));if(l>=0){let e=await c[l]?.done.catch(e=>e);throw a(Promise.reject(e)),await s.catch(()=>void 0),r(l,e)}let u=t(i);a(u),o.catch(()=>void 0);try{let e=await u;return await s,e}finally{await s.catch(()=>void 0)}}}}function O(e,t){return{join({next:n,owner:r}){n.rq=D([...n.rq?.cq??[],{extension:r.name,handler:e,f7:t}]),s(n,u,l)}}}function k(t,n,i){let a=c(t),o=y(t)?.context??e(t)??(a&&d(n.model??a.extension,n.operation,a.engine.el)),s=r(o)?.rq,l={kind:n.kind,operation:n.operation,model:n.model,context:o,notes:n.note===void 0?[]:[n.note]};return s===void 0?i(v(l)):s.run(l,()=>i(v(l)))}function A(e){try{let t=e.adapter.namespace;return Object.freeze({dialect:e.dialect,driverName:e.driverName,...t===void 0?{}:{namespace:t}})}catch{return}}const j=e=>_(e)?.sql;function M(e,t,n){let r=Reflect.get(e,t);if(Array.isArray(r)&&r!==p)return r;let i=f(n);return Reflect.set(e,t,i),i}function N(e){let t=_(e);return t?.batch===void 0?t?.params===void 0?void 0:M(t,`shown`,t.params):t.batch.map(e=>M(e,m,e.params))}function P(e){let t=_(e)?.driver;return t===void 0?void 0:A(t)}const F=e=>_(e)?.failure,I=e=>_(e)?.context?.correlationId,L=e=>_(e)?.table;function R(e){return _(e)?.batch?.map(e=>({sql:e.sql,get parameters(){return M(e,m,e.params)},model:e.context?.model,operation:e.context?.operation,correlation:e.context?.correlationId}))}function z(e){return n(e)}function B(e){return _(e)?.statement}function V(e,t){let n=_(e)?.run;return n===void 0?Promise.reject(new i(`run() needs the transaction unit a unit() received.`)):n(t)}function H(e,t){let n=y(e);return n===void 0||n.failed!==void 0?!1:(n.notes?.push(t),!0)}const U=e=>_(e)?.notes??[];export{U as a,V as c,L as d,j as f,k as h,H as i,B as l,O as m,P as n,z as o,D as p,F as r,N as s,I as t,R as u};
|
|
2
|
+
//# sourceMappingURL=unit-words-BXpLpyr2.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"unit-words-CT0yeqfZ.mjs","names":["#source","origin","failure","statement","run","members","statements","settle","origin","driver"],"sources":["../src/extensions/unit-source.ts","../src/extensions/observation.ts","../src/drivers/driver-identity.ts","../src/extensions/unit-words.ts"],"sourcesContent":["/**\n * A unit of real work, as a handler receives it, and what its producer\n * already holds about it. The runner keeps the producer's record beside the\n * unit; each unit word (`text`, `parameters`, `driver`, …) reads that record\n * when it is called. A fact nobody reads is never computed, and a program\n * that imports no word carries none of their code.\n */\nimport type { DriverIdentitySource } from \"@drivers/driver-identity\";\nimport type { BatchQuery, QueryExecutionContext } from \"@drivers/types\";\nimport type { Sql } from \"@sql\";\nimport type { UnitContext, UnitKind, UnitOutcome } from \"./contract\";\nimport { callOf } from \"./origin\";\n\nexport type { UnitKind } from \"./contract\";\nexport type Unit = UnitContext;\nexport type UnitEnd = UnitOutcome;\ntype CommitCertainty = \"committed\" | \"may-have-committed\";\n\n/**\n * One handler around a unit. `next()` lets the unit run; the child starts\n * only then, at most once, and must be called. What the handler throws, or a\n * promise it returns that rejects, fails the call; the child's own failure\n * fails it first.\n */\nexport type UnitHandler = (\n unit: Unit,\n next: (sql?: Sql) => Promise<UnitEnd>\n) => unknown;\n\n/** Runs one statement in the transaction a unit opened, and gives its rows. */\nexport type TransactionStatementRunner = (\n statement: Sql\n) => Promise<readonly Record<string, unknown>[]>;\n\n/**\n * The producer's record of one unit: references it already held, never a\n * fact computed for a reader that may not come.\n */\nexport interface UnitSource {\n readonly kind: UnitKind;\n readonly operation?: string | undefined;\n readonly model?: string | undefined;\n /**\n * The trusted execution context: the chain, correlation, a recovered read.\n * An operation unit's is its call's own (`CallOrigin.of`), how a `run`\n * finds it.\n */\n readonly context?: QueryExecutionContext | undefined;\n /** The driver doing the work, read only by `driver(unit)`. */\n readonly driver?: DriverIdentitySource | undefined;\n /** operation: the SQL name of the model. */\n readonly table?: string | undefined;\n /** statement: the rendered text sent, a native batch's texts joined. */\n readonly sql?: string | undefined;\n /** statement: the parameters sent, as the driver detached them. */\n readonly params?: readonly unknown[] | undefined;\n /**\n * statement: the diagnostic snapshot of `params` the driver took (its\n * empty constant when it took none): what `parameters(u)` reads.\n */\n readonly shown?: readonly unknown[] | undefined;\n /** statement: a native batch's members, in order. */\n readonly batch?: readonly BatchQuery[] | undefined;\n /**\n * A logical statement under rewriting units: the statement as the earlier\n * ones left it (what `next(sql)` hands on replaces it).\n */\n statement?: Sql | undefined;\n /** How sure the child's commit is, read once it settled. */\n readonly certainty?: (() => CommitCertainty | undefined) | undefined;\n /** What extensions noted on the unit (`note`), in order. */\n notes?: unknown[];\n /**\n * transaction: called by the producer once the transaction is open, with\n * what runs a statement in it; the body waits for what it returns.\n */\n opened?: (run: TransactionStatementRunner) => Promise<void> | undefined;\n /** transaction: `run(unit, sql)`, set by the runner. */\n run?: TransactionStatementRunner;\n /** Set by the runner once the child settled. */\n failed?: boolean;\n failure?: unknown;\n /**\n * The instant the child settled, read by the innermost layer's end: an\n * outer layer's end comes after the inner handlers continued, and still\n * reports the child's instant.\n */\n settledAt?: number;\n}\n\n/** The unit a handler receives: its producer's record is its own field. */\nclass ProducedUnit implements Unit {\n readonly kind: UnitKind;\n readonly model: string | undefined;\n readonly operation: string | undefined;\n readonly #source: UnitSource;\n constructor(source: UnitSource) {\n this.kind = source.kind;\n this.model = source.model;\n // A driver's unit names its operation through its context alone.\n this.operation = Object.hasOwn(source, \"operation\")\n ? source.operation\n : source.context?.operation;\n this.#source = source;\n }\n static sourceOf(unit: object): UnitSource | undefined {\n return #source in unit ? unit.#source : undefined;\n }\n}\n\n/**\n * A running operation unit, by its execution context: one per operation,\n * the same its call carries, so a call's `run` and the cache, which holds\n * the context, find the same unit.\n */\nconst operations = new WeakMap<object, UnitSource>();\n\n/** The producer's record of `unit`, or `undefined` for a unit it did not make. */\nexport const sourceOf = (unit: object): UnitSource | undefined =>\n ProducedUnit.sourceOf(unit);\n\n/** The unit a handler receives for `source`. */\nexport function unitOf(source: UnitSource): Unit {\n const unit = new ProducedUnit(source);\n source.notes ??= [];\n if (source.kind === \"operation\" && source.context !== undefined)\n operations.set(source.context, source);\n return unit;\n}\n\n/**\n * The unit `origin` stands for: a unit a handler received or `work` made, the\n * operation unit of a call's `run`, or that of an execution context.\n */\nexport function originOf(origin: object): UnitSource | undefined {\n const context = callOf(origin)?.of?.context;\n return (\n sourceOf(origin) ??\n (context === undefined ? operations.get(origin) : operations.get(context))\n );\n}\n","/**\n * The one generation of unit handlers: what runs a unit under a chain's\n * `unit` parts, and `work`, by which an extension emits a unit of its own.\n */\nimport {\n getExecutionExtensionChain,\n isRecoverableExecution,\n trustedExecutionContext,\n} from \"@drivers/execution-context\";\nimport { QueryError } from \"@errors\";\nimport { createOperationExecutionContext } from \"@query-engine/execution-context\";\nimport { Sql } from \"@sql\";\nimport type { ExtensionPart } from \"./chain\";\nimport { coordinate, UNITS } from \"./coordination\";\nimport { scopeOf } from \"./origin\";\nimport { collect } from \"./query\";\nimport {\n originOf,\n type TransactionStatementRunner,\n type Unit,\n type UnitEnd,\n type UnitHandler,\n type UnitKind,\n type UnitSource,\n unitOf,\n} from \"./unit-source\";\n\n/**\n * What a unit runs at its core, once every handler called `next()`: given\n * the statement a logical statement's rewriting units handed on.\n */\nexport type Child<Result> = (statement?: Sql) => Promise<Result>;\n\n/** One `unit` part of a chain: its extension, its handler, its kinds. */\ninterface UnitLayer {\n readonly extension: string;\n readonly handler: UnitHandler;\n /** The kinds it runs around; every kind when absent. */\n readonly kinds?: readonly UnitKind[] | undefined;\n}\n\nconst nothing = (): undefined => undefined;\n\n/**\n * Runs one unit under `handlers`, the first one outermost. Each handler is a\n * plain wrapper: the next one, and at the end the child, starts only when it\n * calls `next()`, and the host waits for the promise it returns. The child's\n * failure fails the unit; once the child succeeded, what a handler throws\n * does. `next()` is called once: never calling it, or calling it again,\n * fails the unit. The host contains nothing a handler does.\n */\nexport function runUnit<Result>(\n handlers: readonly UnitLayer[],\n source: UnitSource,\n child: Child<Result>,\n reached?: () => void\n): Promise<Result> {\n const unit = unitOf(source);\n let core: Promise<Result> | undefined;\n const startCore = (): Promise<Result> => {\n core ??= attempt(() => child(source.statement));\n return core;\n };\n const transaction =\n source.kind === \"transaction\"\n ? openTransaction(source, startCore)\n : undefined;\n const enter = (index: number): Promise<Result> => {\n const resolved = handlers[index];\n // A layer that names other kinds is not around this unit at all.\n if (resolved?.kinds?.includes(source.kind) === false)\n return enter(index + 1);\n if (resolved === undefined) {\n reached?.();\n transaction?.enter();\n return startCore();\n }\n return around(resolved, unit, source, () => enter(index + 1));\n };\n const result = enter(0);\n return transaction === undefined ? result : result.catch(transaction.fail);\n}\n\nfunction attempt<Result>(child: () => Promise<Result>): Promise<Result> {\n try {\n return child();\n } catch (failure) {\n return Promise.reject(failure);\n }\n}\n\n/** One handler around the rest of the unit. */\nasync function around<Result>(\n resolved: UnitLayer,\n unit: Unit,\n source: UnitSource,\n rest: () => Promise<Result>\n): Promise<Result> {\n let started: Promise<Result> | undefined;\n let misuse: QueryError | undefined;\n // `next(sql)` hands on another statement to a logical statement's rest.\n const next = (statement?: Sql): Promise<UnitEnd> => {\n if (started !== undefined) {\n misuse ??= unitError(resolved, unit, \"called next() more than once\");\n return Promise.reject(misuse);\n }\n const at = Date.now();\n const handed = statement !== undefined && source.statement !== undefined;\n // The statement is rendered after every rewrite: refused here, it is\n // refused in the extension's name, not as the renderer's TypeError.\n if (handed && !(statement instanceof Sql))\n started = Promise.reject(\n unitError(resolved, unit, \"handed next() something not a statement\")\n );\n else {\n if (handed) source.statement = statement;\n started = rest();\n }\n return started.then(\n () => settle(source, at, false, undefined),\n (failure: unknown) => settle(source, at, true, failure)\n );\n };\n let handlerFailure: { readonly failure: unknown } | undefined;\n try {\n await resolved.handler(unit, next);\n } catch (failure) {\n handlerFailure = { failure };\n }\n if (started === undefined)\n throw (\n handlerFailure?.failure ??\n unitError(resolved, unit, \"settled without calling next()\")\n );\n const value = await started;\n if (handlerFailure !== undefined) throw handlerFailure.failure;\n if (misuse !== undefined) throw misuse;\n return value;\n}\n\nfunction settle(\n source: UnitSource,\n at: number,\n failed: boolean,\n failure: unknown\n): UnitEnd {\n source.failed = failed;\n source.failure = failure;\n source.settledAt ??= Date.now();\n const certainty = source.certainty?.();\n return {\n status: failed ? \"failure\" : \"success\",\n duration: Math.max(0, source.settledAt - at),\n ...(certainty === undefined ? {} : { certainty }),\n ...(failed && isRecoverableExecution(source.context)\n ? { recovered: true as const }\n : {}),\n };\n}\n\nfunction unitError(\n resolved: UnitLayer,\n unit: Unit,\n failure: string\n): QueryError {\n return new QueryError(\n `Extension \"${resolved.extension}\" unit() for ${unit.kind} ${failure}.`,\n { meta: { method: \"unit\", operation: unit.operation, model: unit.model } }\n );\n}\n\n/**\n * A transaction unit's `run(unit, sql)`: it opens the transaction if no\n * `next()` has yet, and runs the statement there before the body. The body\n * then waits for the innermost `next()`; a unit that fails before it rolls\n * back the transaction `run` opened (`fail`).\n */\nfunction openTransaction<Result>(\n source: UnitSource,\n startCore: () => Promise<Result>\n) {\n let runner: TransactionStatementRunner | undefined;\n let ready: (() => void) | undefined;\n let refuse: ((failure: unknown) => void) | undefined;\n let aborted: { readonly failure: unknown } | undefined;\n let bodyEntered = false;\n // The transaction `run` opened before the body was let run.\n let opening: Promise<Result> | undefined;\n let announce: ((run: TransactionStatementRunner) => void) | undefined;\n const opened = new Promise<TransactionStatementRunner>((resolve) => {\n announce = resolve;\n });\n const openedWith = (run: TransactionStatementRunner) => {\n runner = run;\n announce?.(run);\n if (aborted !== undefined) return Promise.reject(aborted.failure);\n if (bodyEntered) return undefined;\n return new Promise<void>((resolve, reject) => {\n ready = resolve;\n refuse = reject;\n });\n };\n // Named first, then stored: a function literal assigned to a property is\n // allocated outside the young generation and keeps the unit alive.\n source.opened = openedWith;\n const runIn = (statement: Sql) => {\n if (runner !== undefined) return runner(statement);\n opening ??= startCore();\n return Promise.race([\n opened,\n opening.then(() => {\n throw new QueryError(\"run() was called on a transaction that ended.\");\n }),\n ]).then((run) => run(statement));\n };\n source.run = runIn;\n return {\n enter: () => {\n bodyEntered = true;\n ready?.();\n },\n fail: (failure: unknown): Promise<never> => {\n // Thrown, not returned rejected: workerd reports a rejection that the\n // promise taking it holds only a microtask later.\n if (opening === undefined || bodyEntered) throw failure;\n aborted = { failure };\n refuse?.(failure);\n return opening.catch(nothing).then(() => {\n throw failure;\n });\n },\n };\n}\n\n/** What runs a unit under a chain's handlers. */\nexport interface Observation {\n readonly handlers: readonly UnitLayer[];\n readonly run: <Result>(\n source: UnitSource,\n child: Child<Result>\n ) => Promise<Result>;\n /**\n * The members of `$transaction([...])`, or of a batch of logical\n * statements: every member's unit is entered (a member without one is\n * skipped), and this resolves once each reached its child, with the units\n * and what settles once every unit did (and fails as the first that\n * failed). The array waits for it before it prepares any member: a handler\n * that waits (for a tracer to load) does so before the array's work, and\n * each member's work runs inside its unit.\n */\n readonly members: (\n members: readonly (readonly [UnitSource, Child<unknown>] | undefined)[]\n ) => Promise<{\n readonly done: Promise<unknown>;\n readonly units: readonly (\n | { readonly done: Promise<unknown> }\n | undefined\n )[];\n }>;\n /**\n * For a chain's rewriting units (`unit(fn, kinds, { rewrites: true })`):\n * the members of one batch, each its own logical statement: every member\n * is rewritten before `send` sends any (it receives each member's final\n * statement, `undefined` for a member with no unit), and each member's\n * unit then ends as the batch does. A member whose unit fails before its\n * `next()` refuses the batch: `refuse(index, failure)` is thrown.\n */\n readonly together: <Result>(\n sources: readonly (UnitSource | undefined)[],\n send: (statements: readonly (Sql | undefined)[]) => Promise<Result>,\n refuse: (index: number, failure: unknown) => unknown\n ) => Promise<Result>;\n}\n\nexport function observationOf(handlers: readonly UnitLayer[]): Observation {\n const enter = <Result>(source: UnitSource, child: Child<Result>) => {\n let reach: (() => void) | undefined;\n const reached = new Promise<void>((resolve) => {\n reach = resolve;\n });\n const done = runUnit(handlers, source, child, reach);\n done.then(reach, reach);\n return { done, reached };\n };\n const members: Observation[\"members\"] = async (members) => {\n const units = members.map((member) =>\n member === undefined ? undefined : enter(member[0], member[1])\n );\n await Promise.all(units.map((unit) => unit?.reached));\n const done = Promise.all(units.map((unit) => unit?.done));\n done.catch(() => undefined);\n return { done, units };\n };\n return {\n handlers,\n run: (source, child) => runUnit(handlers, source, child),\n members,\n together: async (sources, send, refuse) => {\n const statements: (Sql | undefined)[] = [];\n let settle!: (outcome: Promise<unknown>) => void;\n const outcome = new Promise<unknown>((resolve) => {\n settle = resolve;\n });\n const { done, units } = await members(\n sources.map((source, index) =>\n source === undefined\n ? undefined\n : [\n source,\n (statement) => {\n statements[index] = statement;\n return outcome;\n },\n ]\n )\n );\n // A member's unit reached its child where the child kept its\n // statement.\n const refused = units.findIndex(\n (unit, index) => unit !== undefined && !(index in statements)\n );\n if (refused >= 0) {\n // An unreached unit's end is its failure.\n const failure = await units[refused]?.done.catch(\n (error: unknown) => error\n );\n settle(Promise.reject(failure));\n await done.catch(() => undefined);\n throw refuse(refused, failure);\n }\n const sent = send(statements);\n settle(sent);\n // The send's failure is the call's, through `sent`; the units that\n // wait on `outcome` see it too, and where none started, nothing\n // else does.\n outcome.catch(() => undefined);\n try {\n const value = await sent;\n await done;\n return value;\n } finally {\n await done.catch(() => undefined);\n }\n },\n };\n}\n\n/**\n * The part one `unit(handler, kinds)` builds: it adds a layer to the\n * chain's units, the first extension outermost. It brings nothing of the\n * array barrier of `$transaction([...])`: the array starts every member's\n * unit, and waits until each reached its child, before it prepares any\n * member.\n */\nexport function unitLayerPart(\n handler: UnitHandler,\n kinds: readonly UnitKind[] | undefined\n): ExtensionPart {\n return {\n join({ next, owner }) {\n next.observation = observationOf([\n ...(next.observation?.handlers ?? []),\n { extension: owner.name, handler, kinds },\n ]);\n coordinate(next, UNITS, collect);\n },\n };\n}\n\n/**\n * Run `fn` as a unit of the extension's own (`kind` is any string), under\n * every `unit` part of the chain `origin` belongs to: `origin` is a call's\n * context or `run`, a unit a handler received, one `work` made, or a\n * method's scope. Without a chain that observes units, `fn` runs alone.\n * `fn` receives the unit, to `note` on it.\n */\nexport function work<Result>(\n origin: object,\n unit: {\n readonly kind: UnitKind;\n readonly operation: string;\n readonly model?: string;\n /** A first fact, noted before any handler sees the unit. */\n readonly note?: unknown;\n },\n fn: (unit: Unit) => Promise<Result>\n): Promise<Result> {\n const scope = scopeOf(origin);\n const context =\n originOf(origin)?.context ??\n trustedExecutionContext(origin) ??\n // A method works outside any call: its unit is an execution of its own,\n // with its own correlation.\n (scope &&\n createOperationExecutionContext(\n unit.model ?? scope.extension,\n unit.operation,\n scope.engine.extensionChain\n ));\n const observation = getExecutionExtensionChain(context)?.observation;\n const source: UnitSource = {\n kind: unit.kind,\n operation: unit.operation,\n model: unit.model,\n context,\n notes: unit.note === undefined ? [] : [unit.note],\n };\n // `fn` gets a unit of the same record: what it notes, handlers read.\n return observation === undefined\n ? fn(unitOf(source))\n : observation.run(source, () => fn(unitOf(source)));\n}\n","import type { Dialect } from \"./types\";\n\n/**\n * The configuration facts that name one driver in presented telemetry. No\n * package entry exports this module.\n *\n * `namespace` is the adapter's one normalized SQL qualifier and is absent when\n * the adapter is unqualified. `adapter.namespace` is installed non-writable,\n * so a snapshot taken once (the cached read's, at `$withCache`) cannot go\n * stale. This is the one reader of that property for presentation.\n */\nexport interface DriverIdentity {\n readonly dialect: Dialect;\n readonly driverName: string;\n readonly namespace?: string;\n}\n\n/** The public readonly driver fields an identity is read from. */\nexport interface DriverIdentitySource {\n readonly dialect: Dialect;\n readonly driverName: string;\n readonly adapter: { readonly namespace?: string };\n}\n\n/**\n * Read one driver's identity from its public readonly configuration, or\n * `undefined` when that read throws (a custom adapter's `namespace` getter):\n * every presenter then omits the driver attributes and presents the rest.\n */\nexport function readDriverIdentity(\n driver: DriverIdentitySource\n): DriverIdentity | undefined {\n try {\n const namespace = driver.adapter.namespace;\n return Object.freeze({\n dialect: driver.dialect,\n driverName: driver.driverName,\n ...(namespace === undefined ? {} : { namespace }),\n });\n } catch {\n // The operation's facts, its spans and a cached read's revalidation\n // identity survive a driver that cannot name itself.\n return undefined;\n }\n}\n","/**\n * The words a `unit` handler reads of its unit, each a top-level function\n * that reads what the unit's producer already holds, when it is called: a\n * fact nobody reads is never computed, and a word a program does not import\n * is not in its bundle.\n */\nimport {\n BATCH_DIAGNOSTIC_PARAMS,\n EMPTY_DIAGNOSTIC_PARAMS,\n snapshotDiagnosticParameters,\n} from \"@drivers/driver-diagnostics\";\nimport {\n type DriverIdentity,\n readDriverIdentity,\n} from \"@drivers/driver-identity\";\nimport { QueryError } from \"@errors\";\nimport type { Sql } from \"@sql\";\nimport { errorOrigin } from \"../errors/logged-errors\";\nimport type { StatementUnit, UnitContext } from \"./contract\";\nimport { originOf, sourceOf } from \"./unit-source\";\n\n/**\n * The text a `statement` unit sends, as rendered for its driver; a native\n * batch's texts joined by `\"; \"`. The text of a verbatim unsafe raw query\n * too: it is never rewritten, but it is observed.\n */\nexport const text = (u: UnitContext): string | undefined => sourceOf(u)?.sql;\n\n/**\n * The snapshot the driver took for its diagnostics, or the one taken here at\n * the first read and kept where the driver keeps its own (`key` of `of`): a\n * caller's parameter is read once however many read it.\n */\nfunction shownOf(\n of: object,\n key: PropertyKey,\n params: readonly unknown[] | undefined\n): readonly unknown[] {\n const taken: unknown = Reflect.get(of, key);\n if (Array.isArray(taken) && taken !== EMPTY_DIAGNOSTIC_PARAMS) return taken;\n // Every statement the package sends states its parameters, a raw one `[]`.\n const shown = snapshotDiagnosticParameters(params!);\n Reflect.set(of, key, shown);\n return shown;\n}\n\n/**\n * A bounded snapshot of the parameters a `statement` unit sends; for a\n * native batch, one list per member. Read it before `next()`: a provider may\n * change what it was handed.\n */\nexport function parameters(u: UnitContext): readonly unknown[] | undefined {\n const source = sourceOf(u);\n if (source?.batch !== undefined)\n return source.batch.map((member) =>\n shownOf(member, BATCH_DIAGNOSTIC_PARAMS, member.params)\n );\n return source?.params === undefined\n ? undefined\n : shownOf(source, \"shown\", source.params);\n}\n\n/**\n * The dialect, name and SQL namespace of the driver doing a unit's work;\n * `undefined` for a unit with no driver, or when a custom adapter's\n * `namespace` getter throws.\n */\nexport function driver(u: UnitContext): DriverIdentity | undefined {\n const source = sourceOf(u)?.driver;\n return source === undefined ? undefined : readDriverIdentity(source);\n}\n\n/** What a unit's child failed with, once `next()` settled; else `undefined`. */\nexport const failure = (u: UnitContext): unknown => sourceOf(u)?.failure;\n\n/** The identity of the logical call a unit belongs to. */\nexport const correlation = (u: UnitContext): string | undefined =>\n sourceOf(u)?.context?.correlationId;\n\n/** The SQL name of the model an `operation` unit addresses. */\nexport const table = (u: UnitContext): string | undefined => sourceOf(u)?.table;\n\n/** One member of a native batch, as `statements(u)` gives it. */\nexport interface BatchMember {\n readonly sql: string;\n readonly parameters: readonly unknown[];\n readonly model?: string;\n readonly operation?: string;\n readonly correlation?: string;\n}\n\n/**\n * The members of a `statement` unit that sends a native batch, in order;\n * `undefined` for a unit that sends one statement. A failure that names a\n * member carries its index (`meta.statementIndex`).\n */\nexport function statements(u: UnitContext): readonly BatchMember[] | undefined {\n return sourceOf(u)?.batch?.map((member) => ({\n sql: member.sql,\n // A snapshot only when read, as `parameters(u)` takes one.\n get parameters() {\n return shownOf(member, BATCH_DIAGNOSTIC_PARAMS, member.params);\n },\n // Every member the package sends carries the context of its call.\n model: member.context?.model,\n operation: member.context?.operation,\n correlation: member.context?.correlationId,\n }));\n}\n\n/**\n * The first error of a line of successors the package made from it (a clone\n * that adds execution context or commit certainty); the error itself when it\n * has none. Two units that fail with errors of one origin failed once.\n */\nexport function origin(error: Error): Error;\nexport function origin(error: unknown): unknown;\nexport function origin(error: unknown): unknown {\n return errorOrigin(error);\n}\n\n/**\n * For a unit that rewrites statements: the statement before its rewrite, to\n * hand on, changed or not, to `next(sql)`. Always there in a part that\n * rewrites.\n */\nexport function statement(u: StatementUnit): Sql;\nexport function statement(u: UnitContext): Sql | undefined;\nexport function statement(u: UnitContext): Sql | undefined {\n return sourceOf(u)?.statement;\n}\n\n/**\n * For a `transaction` unit: runs `sql` in the transaction and gives its\n * rows. Called before `next()`, it opens the transaction and runs before\n * anything else does; the transaction's body waits for the innermost\n * `next()`. A savepoint is no transaction.\n */\nexport function run(\n u: UnitContext,\n sql: Sql\n): Promise<readonly Record<string, unknown>[]> {\n const send = sourceOf(u)?.run;\n return send === undefined\n ? Promise.reject(\n new QueryError(\"run() needs the transaction unit a unit() received.\")\n )\n : send(sql);\n}\n\n/**\n * Attach a fact to a unit that is still running: `target` is a unit (one a\n * handler received, or `work` made), or a call's `run`, which notes on the\n * call's `operation` unit. `false` when there is no such unit, or it has\n * settled (where no handler runs around a unit, nothing would read it).\n */\nexport function note(target: object, fact: unknown): boolean {\n const source = originOf(target);\n if (source === undefined || source.failed !== undefined) return false;\n source.notes?.push(fact);\n return true;\n}\n\n/** The facts noted on a unit, in order. */\nexport const notes = (u: UnitContext): readonly unknown[] =>\n sourceOf(u)?.notes ?? [];\n"],"mappings":"yYA2FA,IAAM,aAAN,KAAmC,CACjC,KACA,MACA,UACA,GACA,YAAY,EAAoB,CAC9B,KAAK,KAAO,EAAO,KACnB,KAAK,MAAQ,EAAO,MAEpB,KAAK,UAAY,OAAO,OAAO,EAAQ,YAAY,CAC/C,EAAO,UACP,EAAO,SAAS,UACpB,MAAA,EAAe,EAEjB,OAAO,SAAS,EAAsC,CACpD,MAAO,MAAW,EAAO,GAAA,EAAe,IAAA,KAS5C,MAAM,EAAa,IAAI,QAGV,SAAY,GACvB,aAAa,SAAS,EAAK,CAG7B,SAAgB,OAAO,EAA0B,CAC/C,IAAM,EAAO,IAAI,aAAa,EAAO,CAIrC,MAHA,GAAO,QAAU,EAAE,CACf,EAAO,OAAS,aAAe,EAAO,UAAY,IAAA,IACpD,EAAW,IAAI,EAAO,QAAS,EAAO,CACjC,EAOT,SAAgB,SAAS,EAAwC,CAC/D,IAAM,EAAU,EAAOC,EAAO,EAAE,IAAI,QACpC,OACE,SAASA,EAAO,GACf,IAAY,IAAA,GAAY,EAAW,IAAIA,EAAO,CAAG,EAAW,IAAI,EAAQ,ECjG7E,MAAM,YAA2B,IAAA,GAUjC,SAAgB,QACd,EACA,EACA,EACA,EACiB,CACjB,IAAM,EAAO,OAAO,EAAO,CACvB,E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CAC3D,IAAM,EAAS,SAAS,EAAO,CAG/B,OAFI,IAAW,IAAA,IAAa,EAAO,SAAW,IAAA,GAAkB,IAChE,EAAO,OAAO,KAAK,EAAK,CACjB,IAIT,MAAa,MAAS,GACpB,SAAS,EAAE,EAAE,OAAS,EAAE"}
|
|
1
|
+
{"version":3,"file":"unit-words-BXpLpyr2.mjs","names":["#source","origin","failure","statement","run","members","statements","settle","origin","driver"],"sources":["../src/extensions/unit-source.ts","../src/extensions/observation.ts","../src/drivers/driver-identity.ts","../src/extensions/unit-words.ts"],"sourcesContent":["/**\n * A unit of real work, as a handler receives it, and what its producer\n * already holds about it. The runner keeps the producer's record beside the\n * unit; each unit word (`text`, `parameters`, `driver`, …) reads that record\n * when it is called. A fact nobody reads is never computed, and a program\n * that imports no word carries none of their code.\n */\nimport type { DriverIdentitySource } from \"@drivers/driver-identity\";\nimport type { BatchQuery, QueryExecutionContext } from \"@drivers/types\";\nimport type { Sql } from \"@sql\";\nimport type { UnitContext, UnitKind, UnitOutcome } from \"./contract\";\nimport { callOf } from \"./origin\";\n\nexport type { UnitKind } from \"./contract\";\nexport type Unit = UnitContext;\nexport type UnitEnd = UnitOutcome;\ntype CommitCertainty = \"committed\" | \"may-have-committed\";\n\n/**\n * One handler around a unit. `next()` lets the unit run; the child starts\n * only then, at most once, and must be called. What the handler throws, or a\n * promise it returns that rejects, fails the call; the child's own failure\n * fails it first.\n */\nexport type UnitHandler = (\n unit: Unit,\n next: (sql?: Sql) => Promise<UnitEnd>\n) => unknown;\n\n/** Runs one statement in the transaction a unit opened, and gives its rows. */\nexport type TransactionStatementRunner = (\n statement: Sql\n) => Promise<readonly Record<string, unknown>[]>;\n\n/**\n * The producer's record of one unit: references it already held, never a\n * fact computed for a reader that may not come.\n */\nexport interface UnitSource {\n readonly kind: UnitKind;\n readonly operation?: string | undefined;\n readonly model?: string | undefined;\n /**\n * The trusted execution context: the chain, correlation, a recovered read.\n * An operation unit's is its call's own (`CallOrigin.of`), how a `run`\n * finds it.\n */\n readonly context?: QueryExecutionContext | undefined;\n /** The driver doing the work, read only by `driver(unit)`. */\n readonly driver?: DriverIdentitySource | undefined;\n /** operation: the SQL name of the model. */\n readonly table?: string | undefined;\n /** statement: the rendered text sent, a native batch's texts joined. */\n readonly sql?: string | undefined;\n /** statement: the parameters sent, as the driver detached them. */\n readonly params?: readonly unknown[] | undefined;\n /**\n * statement: the diagnostic snapshot of `params` the driver took (its\n * empty constant when it took none): what `parameters(u)` reads.\n */\n readonly shown?: readonly unknown[] | undefined;\n /** statement: a native batch's members, in order. */\n readonly batch?: readonly BatchQuery[] | undefined;\n /**\n * A logical statement under rewriting units: the statement as the earlier\n * ones left it (what `next(sql)` hands on replaces it).\n */\n statement?: Sql | undefined;\n /** How sure the child's commit is, read once it settled. */\n readonly certainty?: (() => CommitCertainty | undefined) | undefined;\n /** What extensions noted on the unit (`note`), in order. */\n notes?: unknown[];\n /**\n * transaction: called by the producer once the transaction is open, with\n * what runs a statement in it; the body waits for what it returns.\n */\n opened?: (run: TransactionStatementRunner) => Promise<void> | undefined;\n /** transaction: `run(unit, sql)`, set by the runner. */\n run?: TransactionStatementRunner;\n /** Set by the runner once the child settled. */\n failed?: boolean;\n failure?: unknown;\n /**\n * The instant the child settled, read by the innermost layer's end: an\n * outer layer's end comes after the inner handlers continued, and still\n * reports the child's instant.\n */\n settledAt?: number;\n}\n\n/** The unit a handler receives: its producer's record is its own field. */\nclass ProducedUnit implements Unit {\n readonly kind: UnitKind;\n readonly model: string | undefined;\n readonly operation: string | undefined;\n readonly #source: UnitSource;\n constructor(source: UnitSource) {\n this.kind = source.kind;\n this.model = source.model;\n // A driver's unit names its operation through its context alone.\n this.operation = Object.hasOwn(source, \"operation\")\n ? source.operation\n : source.context?.operation;\n this.#source = source;\n }\n static sourceOf(unit: object): UnitSource | undefined {\n return #source in unit ? unit.#source : undefined;\n }\n}\n\n/**\n * A running operation unit, by its execution context: one per operation,\n * the same its call carries, so a call's `run` and the cache, which holds\n * the context, find the same unit.\n */\nconst operations = new WeakMap<object, UnitSource>();\n\n/** The producer's record of `unit`, or `undefined` for a unit it did not make. */\nexport const sourceOf = (unit: object): UnitSource | undefined =>\n ProducedUnit.sourceOf(unit);\n\n/** The unit a handler receives for `source`. */\nexport function unitOf(source: UnitSource): Unit {\n const unit = new ProducedUnit(source);\n source.notes ??= [];\n if (source.kind === \"operation\" && source.context !== undefined)\n operations.set(source.context, source);\n return unit;\n}\n\n/**\n * The unit `origin` stands for: a unit a handler received or `work` made, the\n * operation unit of a call's `run`, or that of an execution context.\n */\nexport function originOf(origin: object): UnitSource | undefined {\n const context = callOf(origin)?.of?.context;\n return (\n sourceOf(origin) ??\n (context === undefined ? operations.get(origin) : operations.get(context))\n );\n}\n","/**\n * The one generation of unit handlers: what runs a unit under a chain's\n * `unit` parts, and `work`, by which an extension emits a unit of its own.\n */\nimport {\n getExecutionExtensionChain,\n isRecoverableExecution,\n trustedExecutionContext,\n} from \"@drivers/execution-context\";\nimport { QueryError } from \"@errors\";\nimport { createOperationExecutionContext } from \"@query-engine/execution-context\";\nimport { Sql } from \"@sql\";\nimport type { ExtensionPart } from \"./chain\";\nimport { coordinate, UNITS } from \"./coordination\";\nimport { scopeOf } from \"./origin\";\nimport { collect } from \"./query\";\nimport {\n originOf,\n type TransactionStatementRunner,\n type Unit,\n type UnitEnd,\n type UnitHandler,\n type UnitKind,\n type UnitSource,\n unitOf,\n} from \"./unit-source\";\n\n/**\n * What a unit runs at its core, once every handler called `next()`: given\n * the statement a logical statement's rewriting units handed on.\n */\nexport type Child<Result> = (statement?: Sql) => Promise<Result>;\n\n/** One `unit` part of a chain: its extension, its handler, its kinds. */\ninterface UnitLayer {\n readonly extension: string;\n readonly handler: UnitHandler;\n /** The kinds it runs around; every kind when absent. */\n readonly kinds?: readonly UnitKind[] | undefined;\n}\n\nconst nothing = (): undefined => undefined;\n\n/**\n * Runs one unit under `handlers`, the first one outermost. Each handler is a\n * plain wrapper: the next one, and at the end the child, starts only when it\n * calls `next()`, and the host waits for the promise it returns. The child's\n * failure fails the unit; once the child succeeded, what a handler throws\n * does. `next()` is called once: never calling it, or calling it again,\n * fails the unit. The host contains nothing a handler does.\n */\nexport function runUnit<Result>(\n handlers: readonly UnitLayer[],\n source: UnitSource,\n child: Child<Result>,\n reached?: () => void\n): Promise<Result> {\n const unit = unitOf(source);\n let core: Promise<Result> | undefined;\n const startCore = (): Promise<Result> => {\n core ??= attempt(() => child(source.statement));\n return core;\n };\n const transaction =\n source.kind === \"transaction\"\n ? openTransaction(source, startCore)\n : undefined;\n const enter = (index: number): Promise<Result> => {\n const resolved = handlers[index];\n // A layer that names other kinds is not around this unit at all.\n if (resolved?.kinds?.includes(source.kind) === false)\n return enter(index + 1);\n if (resolved === undefined) {\n reached?.();\n transaction?.enter();\n return startCore();\n }\n return around(resolved, unit, source, () => enter(index + 1));\n };\n const result = enter(0);\n return transaction === undefined ? result : result.catch(transaction.fail);\n}\n\nfunction attempt<Result>(child: () => Promise<Result>): Promise<Result> {\n try {\n return child();\n } catch (failure) {\n return Promise.reject(failure);\n }\n}\n\n/** One handler around the rest of the unit. */\nasync function around<Result>(\n resolved: UnitLayer,\n unit: Unit,\n source: UnitSource,\n rest: () => Promise<Result>\n): Promise<Result> {\n let started: Promise<Result> | undefined;\n let misuse: QueryError | undefined;\n // `next(sql)` hands on another statement to a logical statement's rest.\n const next = (statement?: Sql): Promise<UnitEnd> => {\n if (started !== undefined) {\n misuse ??= unitError(resolved, unit, \"called next() more than once\");\n return Promise.reject(misuse);\n }\n const at = Date.now();\n const handed = statement !== undefined && source.statement !== undefined;\n // The statement is rendered after every rewrite: refused here, it is\n // refused in the extension's name, not as the renderer's TypeError.\n if (handed && !(statement instanceof Sql))\n started = Promise.reject(\n unitError(resolved, unit, \"handed next() something not a statement\")\n );\n else {\n if (handed) source.statement = statement;\n started = rest();\n }\n return started.then(\n () => settle(source, at, false, undefined),\n (failure: unknown) => settle(source, at, true, failure)\n );\n };\n let handlerFailure: { readonly failure: unknown } | undefined;\n try {\n await resolved.handler(unit, next);\n } catch (failure) {\n handlerFailure = { failure };\n }\n if (started === undefined)\n throw (\n handlerFailure?.failure ??\n unitError(resolved, unit, \"settled without calling next()\")\n );\n const value = await started;\n if (handlerFailure !== undefined) throw handlerFailure.failure;\n if (misuse !== undefined) throw misuse;\n return value;\n}\n\nfunction settle(\n source: UnitSource,\n at: number,\n failed: boolean,\n failure: unknown\n): UnitEnd {\n source.failed = failed;\n source.failure = failure;\n source.settledAt ??= Date.now();\n const certainty = source.certainty?.();\n return {\n status: failed ? \"failure\" : \"success\",\n duration: Math.max(0, source.settledAt - at),\n ...(certainty === undefined ? {} : { certainty }),\n ...(failed && isRecoverableExecution(source.context)\n ? { recovered: true as const }\n : {}),\n };\n}\n\nfunction unitError(\n resolved: UnitLayer,\n unit: Unit,\n failure: string\n): QueryError {\n return new QueryError(\n `Extension \"${resolved.extension}\" unit() for ${unit.kind} ${failure}.`,\n { meta: { method: \"unit\", operation: unit.operation, model: unit.model } }\n );\n}\n\n/**\n * A transaction unit's `run(unit, sql)`: it opens the transaction if no\n * `next()` has yet, and runs the statement there before the body. The body\n * then waits for the innermost `next()`; a unit that fails before it rolls\n * back the transaction `run` opened (`fail`).\n */\nfunction openTransaction<Result>(\n source: UnitSource,\n startCore: () => Promise<Result>\n) {\n let runner: TransactionStatementRunner | undefined;\n let ready: (() => void) | undefined;\n let refuse: ((failure: unknown) => void) | undefined;\n let aborted: { readonly failure: unknown } | undefined;\n let bodyEntered = false;\n // The transaction `run` opened before the body was let run.\n let opening: Promise<Result> | undefined;\n let announce: ((run: TransactionStatementRunner) => void) | undefined;\n const opened = new Promise<TransactionStatementRunner>((resolve) => {\n announce = resolve;\n });\n const openedWith = (run: TransactionStatementRunner) => {\n runner = run;\n announce?.(run);\n if (aborted !== undefined) return Promise.reject(aborted.failure);\n if (bodyEntered) return undefined;\n return new Promise<void>((resolve, reject) => {\n ready = resolve;\n refuse = reject;\n });\n };\n // Named first, then stored: a function literal assigned to a property is\n // allocated outside the young generation and keeps the unit alive.\n source.opened = openedWith;\n const runIn = (statement: Sql) => {\n if (runner !== undefined) return runner(statement);\n opening ??= startCore();\n return Promise.race([\n opened,\n opening.then(() => {\n throw new QueryError(\"run() was called on a transaction that ended.\");\n }),\n ]).then((run) => run(statement));\n };\n source.run = runIn;\n return {\n enter: () => {\n bodyEntered = true;\n ready?.();\n },\n fail: (failure: unknown): Promise<never> => {\n // Thrown, not returned rejected: workerd reports a rejection that the\n // promise taking it holds only a microtask later.\n if (opening === undefined || bodyEntered) throw failure;\n aborted = { failure };\n refuse?.(failure);\n return opening.catch(nothing).then(() => {\n throw failure;\n });\n },\n };\n}\n\n/** What runs a unit under a chain's handlers. */\nexport interface Observation {\n readonly handlers: readonly UnitLayer[];\n readonly run: <Result>(\n source: UnitSource,\n child: Child<Result>\n ) => Promise<Result>;\n /**\n * The members of `$transaction([...])`, or of a batch of logical\n * statements: every member's unit is entered (a member without one is\n * skipped), and this resolves once each reached its child, with the units\n * and what settles once every unit did (and fails as the first that\n * failed). The array waits for it before it prepares any member: a handler\n * that waits (for a tracer to load) does so before the array's work, and\n * each member's work runs inside its unit.\n */\n readonly members: (\n members: readonly (readonly [UnitSource, Child<unknown>] | undefined)[]\n ) => Promise<{\n readonly done: Promise<unknown>;\n readonly units: readonly (\n | { readonly done: Promise<unknown> }\n | undefined\n )[];\n }>;\n /**\n * For a chain's rewriting units (`unit(fn, kinds, { rewrites: true })`):\n * the members of one batch, each its own logical statement: every member\n * is rewritten before `send` sends any (it receives each member's final\n * statement, `undefined` for a member with no unit), and each member's\n * unit then ends as the batch does. A member whose unit fails before its\n * `next()` refuses the batch: `refuse(index, failure)` is thrown.\n */\n readonly together: <Result>(\n sources: readonly (UnitSource | undefined)[],\n send: (statements: readonly (Sql | undefined)[]) => Promise<Result>,\n refuse: (index: number, failure: unknown) => unknown\n ) => Promise<Result>;\n}\n\nexport function observationOf(handlers: readonly UnitLayer[]): Observation {\n const enter = <Result>(source: UnitSource, child: Child<Result>) => {\n let reach: (() => void) | undefined;\n const reached = new Promise<void>((resolve) => {\n reach = resolve;\n });\n const done = runUnit(handlers, source, child, reach);\n done.then(reach, reach);\n return { done, reached };\n };\n const members: Observation[\"members\"] = async (members) => {\n const units = members.map((member) =>\n member === undefined ? undefined : enter(member[0], member[1])\n );\n await Promise.all(units.map((unit) => unit?.reached));\n const done = Promise.all(units.map((unit) => unit?.done));\n done.catch(() => undefined);\n return { done, units };\n };\n return {\n handlers,\n run: (source, child) => runUnit(handlers, source, child),\n members,\n together: async (sources, send, refuse) => {\n const statements: (Sql | undefined)[] = [];\n let settle!: (outcome: Promise<unknown>) => void;\n const outcome = new Promise<unknown>((resolve) => {\n settle = resolve;\n });\n const { done, units } = await members(\n sources.map((source, index) =>\n source === undefined\n ? undefined\n : [\n source,\n (statement) => {\n statements[index] = statement;\n return outcome;\n },\n ]\n )\n );\n // A member's unit reached its child where the child kept its\n // statement.\n const refused = units.findIndex(\n (unit, index) => unit !== undefined && !(index in statements)\n );\n if (refused >= 0) {\n // An unreached unit's end is its failure.\n const failure = await units[refused]?.done.catch(\n (error: unknown) => error\n );\n settle(Promise.reject(failure));\n await done.catch(() => undefined);\n throw refuse(refused, failure);\n }\n const sent = send(statements);\n settle(sent);\n // The send's failure is the call's, through `sent`; the units that\n // wait on `outcome` see it too, and where none started, nothing\n // else does.\n outcome.catch(() => undefined);\n try {\n const value = await sent;\n await done;\n return value;\n } finally {\n await done.catch(() => undefined);\n }\n },\n };\n}\n\n/**\n * The part one `unit(handler, kinds)` builds: it adds a layer to the\n * chain's units, the first extension outermost. It brings nothing of the\n * array barrier of `$transaction([...])`: the array starts every member's\n * unit, and waits until each reached its child, before it prepares any\n * member.\n */\nexport function unitLayerPart(\n handler: UnitHandler,\n kinds: readonly UnitKind[] | undefined\n): ExtensionPart {\n return {\n join({ next, owner }) {\n next.observation = observationOf([\n ...(next.observation?.handlers ?? []),\n { extension: owner.name, handler, kinds },\n ]);\n coordinate(next, UNITS, collect);\n },\n };\n}\n\n/**\n * Run `fn` as a unit of the extension's own (`kind` is any string), under\n * every `unit` part of the chain `origin` belongs to: `origin` is a call's\n * context or `run`, a unit a handler received, one `work` made, or a\n * method's scope. Without a chain that observes units, `fn` runs alone.\n * `fn` receives the unit, to `note` on it.\n */\nexport function work<Result>(\n origin: object,\n unit: {\n readonly kind: UnitKind;\n readonly operation: string;\n readonly model?: string;\n /** A first fact, noted before any handler sees the unit. */\n readonly note?: unknown;\n },\n fn: (unit: Unit) => Promise<Result>\n): Promise<Result> {\n const scope = scopeOf(origin);\n const context =\n originOf(origin)?.context ??\n trustedExecutionContext(origin) ??\n // A method works outside any call: its unit is an execution of its own,\n // with its own correlation.\n (scope &&\n createOperationExecutionContext(\n unit.model ?? scope.extension,\n unit.operation,\n scope.engine.extensionChain\n ));\n const observation = getExecutionExtensionChain(context)?.observation;\n const source: UnitSource = {\n kind: unit.kind,\n operation: unit.operation,\n model: unit.model,\n context,\n notes: unit.note === undefined ? [] : [unit.note],\n };\n // `fn` gets a unit of the same record: what it notes, handlers read.\n return observation === undefined\n ? fn(unitOf(source))\n : observation.run(source, () => fn(unitOf(source)));\n}\n","import type { Dialect } from \"./types\";\n\n/**\n * The configuration facts that name one driver in presented telemetry. No\n * package entry exports this module.\n *\n * `namespace` is the adapter's one normalized SQL qualifier and is absent when\n * the adapter is unqualified. `adapter.namespace` is installed non-writable,\n * so a snapshot taken once (the cached read's, at `$withCache`) cannot go\n * stale. This is the one reader of that property for presentation.\n */\nexport interface DriverIdentity {\n readonly dialect: Dialect;\n readonly driverName: string;\n readonly namespace?: string;\n}\n\n/** The public readonly driver fields an identity is read from. */\nexport interface DriverIdentitySource {\n readonly dialect: Dialect;\n readonly driverName: string;\n readonly adapter: { readonly namespace?: string };\n}\n\n/**\n * Read one driver's identity from its public readonly configuration, or\n * `undefined` when that read throws (a custom adapter's `namespace` getter):\n * every presenter then omits the driver attributes and presents the rest.\n */\nexport function readDriverIdentity(\n driver: DriverIdentitySource\n): DriverIdentity | undefined {\n try {\n const namespace = driver.adapter.namespace;\n return Object.freeze({\n dialect: driver.dialect,\n driverName: driver.driverName,\n ...(namespace === undefined ? {} : { namespace }),\n });\n } catch {\n // The operation's facts, its spans and a cached read's revalidation\n // identity survive a driver that cannot name itself.\n return undefined;\n }\n}\n","/**\n * The words a `unit` handler reads of its unit, each a top-level function\n * that reads what the unit's producer already holds, when it is called: a\n * fact nobody reads is never computed, and a word a program does not import\n * is not in its bundle.\n */\nimport {\n BATCH_DIAGNOSTIC_PARAMS,\n EMPTY_DIAGNOSTIC_PARAMS,\n snapshotDiagnosticParameters,\n} from \"@drivers/driver-diagnostics\";\nimport {\n type DriverIdentity,\n readDriverIdentity,\n} from \"@drivers/driver-identity\";\nimport { QueryError } from \"@errors\";\nimport type { Sql } from \"@sql\";\nimport { errorOrigin } from \"../errors/logged-errors\";\nimport type { StatementUnit, UnitContext } from \"./contract\";\nimport { originOf, sourceOf } from \"./unit-source\";\n\n/**\n * The text a `statement` unit sends, as rendered for its driver; a native\n * batch's texts joined by `\"; \"`. The text of a verbatim unsafe raw query\n * too: it is never rewritten, but it is observed.\n */\nexport const text = (u: UnitContext): string | undefined => sourceOf(u)?.sql;\n\n/**\n * The snapshot the driver took for its diagnostics, or the one taken here at\n * the first read and kept where the driver keeps its own (`key` of `of`): a\n * caller's parameter is read once however many read it.\n */\nfunction shownOf(\n of: object,\n key: PropertyKey,\n params: readonly unknown[] | undefined\n): readonly unknown[] {\n const taken: unknown = Reflect.get(of, key);\n if (Array.isArray(taken) && taken !== EMPTY_DIAGNOSTIC_PARAMS) return taken;\n // Every statement the package sends states its parameters, a raw one `[]`.\n const shown = snapshotDiagnosticParameters(params!);\n Reflect.set(of, key, shown);\n return shown;\n}\n\n/**\n * A bounded snapshot of the parameters a `statement` unit sends; for a\n * native batch, one list per member. Read it before `next()`: a provider may\n * change what it was handed.\n */\nexport function parameters(u: UnitContext): readonly unknown[] | undefined {\n const source = sourceOf(u);\n if (source?.batch !== undefined)\n return source.batch.map((member) =>\n shownOf(member, BATCH_DIAGNOSTIC_PARAMS, member.params)\n );\n return source?.params === undefined\n ? undefined\n : shownOf(source, \"shown\", source.params);\n}\n\n/**\n * The dialect, name and SQL namespace of the driver doing a unit's work;\n * `undefined` for a unit with no driver, or when a custom adapter's\n * `namespace` getter throws.\n */\nexport function driver(u: UnitContext): DriverIdentity | undefined {\n const source = sourceOf(u)?.driver;\n return source === undefined ? undefined : readDriverIdentity(source);\n}\n\n/** What a unit's child failed with, once `next()` settled; else `undefined`. */\nexport const failure = (u: UnitContext): unknown => sourceOf(u)?.failure;\n\n/** The identity of the logical call a unit belongs to. */\nexport const correlation = (u: UnitContext): string | undefined =>\n sourceOf(u)?.context?.correlationId;\n\n/** The SQL name of the model an `operation` unit addresses. */\nexport const table = (u: UnitContext): string | undefined => sourceOf(u)?.table;\n\n/** One member of a native batch, as `statements(u)` gives it. */\nexport interface BatchMember {\n readonly sql: string;\n readonly parameters: readonly unknown[];\n readonly model?: string;\n readonly operation?: string;\n readonly correlation?: string;\n}\n\n/**\n * The members of a `statement` unit that sends a native batch, in order;\n * `undefined` for a unit that sends one statement. A failure that names a\n * member carries its index (`meta.statementIndex`).\n */\nexport function statements(u: UnitContext): readonly BatchMember[] | undefined {\n return sourceOf(u)?.batch?.map((member) => ({\n sql: member.sql,\n // A snapshot only when read, as `parameters(u)` takes one.\n get parameters() {\n return shownOf(member, BATCH_DIAGNOSTIC_PARAMS, member.params);\n },\n // Every member the package sends carries the context of its call.\n model: member.context?.model,\n operation: member.context?.operation,\n correlation: member.context?.correlationId,\n }));\n}\n\n/**\n * The first error of a line of successors the package made from it (a clone\n * that adds execution context or commit certainty); the error itself when it\n * has none. Two units that fail with errors of one origin failed once.\n */\nexport function origin(error: Error): Error;\nexport function origin(error: unknown): unknown;\nexport function origin(error: unknown): unknown {\n return errorOrigin(error);\n}\n\n/**\n * For a unit that rewrites statements: the statement before its rewrite, to\n * hand on, changed or not, to `next(sql)`. Always there in a part that\n * rewrites.\n */\nexport function statement(u: StatementUnit): Sql;\nexport function statement(u: UnitContext): Sql | undefined;\nexport function statement(u: UnitContext): Sql | undefined {\n return sourceOf(u)?.statement;\n}\n\n/**\n * For a `transaction` unit: runs `sql` in the transaction and gives its\n * rows. Called before `next()`, it opens the transaction and runs before\n * anything else does; the transaction's body waits for the innermost\n * `next()`. A savepoint is no transaction.\n */\nexport function run(\n u: UnitContext,\n sql: Sql\n): Promise<readonly Record<string, unknown>[]> {\n const send = sourceOf(u)?.run;\n return send === undefined\n ? Promise.reject(\n new QueryError(\"run() needs the transaction unit a unit() received.\")\n )\n : send(sql);\n}\n\n/**\n * Attach a fact to a unit that is still running: `target` is a unit (one a\n * handler received, or `work` made), or a call's `run`, which notes on the\n * call's `operation` unit. `false` when there is no such unit, or it has\n * settled (where no handler runs around a unit, nothing would read it).\n */\nexport function note(target: object, fact: unknown): boolean {\n const source = originOf(target);\n if (source === undefined || source.failed !== undefined) return false;\n source.notes?.push(fact);\n return true;\n}\n\n/** The facts noted on a unit, in order. */\nexport const notes = (u: UnitContext): readonly unknown[] =>\n sourceOf(u)?.notes ?? [];\n"],"mappings":"gWA2FA,IAAM,EAAN,KAAmC,CACjC,KACA,MACA,UACA,GACA,YAAY,EAAoB,CAC9B,KAAK,KAAO,EAAO,KACnB,KAAK,MAAQ,EAAO,MAEpB,KAAK,UAAY,OAAO,OAAO,EAAQ,YAAY,CAC/C,EAAO,UACP,EAAO,SAAS,UACpB,MAAA,EAAe,EAEjB,OAAO,SAAS,EAAsC,CACpD,MAAO,MAAW,EAAO,GAAA,EAAe,IAAA,KAS5C,MAAM,EAAa,IAAI,QAGV,EAAY,GACvB,EAAa,SAAS,EAAK,CAG7B,SAAgB,EAAO,EAA0B,CAC/C,IAAM,EAAO,IAAI,EAAa,EAAO,CAIrC,MAHA,GAAO,QAAU,EAAE,CACf,EAAO,OAAS,aAAe,EAAO,UAAY,IAAA,IACpD,EAAW,IAAI,EAAO,QAAS,EAA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,CAU3B,SAAgB,EAAU,EAAiC,CACzD,OAAO,EAAS,EAAE,EAAE,UAStB,SAAgB,EACd,EACA,EAC6C,CAC7C,IAAM,EAAO,EAAS,EAAE,EAAE,IAC1B,OAAO,IAAS,IAAA,GACZ,QAAQ,OACN,IAAI,EAAW,sDAAsD,CACtE,CACD,EAAK,EAAI,CASf,SAAgB,EAAK,EAAgB,EAAwB,CAC3D,IAAM,EAAS,EAAS,EAAO,CAG/B,OAFI,IAAW,IAAA,IAAa,EAAO,SAAW,IAAA,GAAkB,IAChE,EAAO,OAAO,KAAK,EAAK,CACjB,IAIT,MAAa,EAAS,GACpB,EAAS,EAAE,EAAE,OAAS,EAAE"}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import{a as e}from"./base-17NSFtrA.mjs";import{n as t}from"./suppressed-failure-CFUDJrUw.mjs";import{a as n}from"./validator-DMzH5Tz0.mjs";import{existsSync as r}from"node:fs";import{resolve as i}from"node:path";import{loadEnvFile as a}from"node:process";import{createJiti as o}from"jiti";const s=[`viborm.config.ts`,`viborm.config.mts`,`viborm.config.js`,`viborm.config.mjs`];function c(e,t){for(let n of t){let t=i(e,n);if(r(t))return t}return null}function l(t,n=!1){let r=e(t),i=t instanceof Error?t.message:typeof t==`string`?t:`CLI operation failed`,a=r?t.code:void 0,o=a?.startsWith(`V11`)?Number(a.slice(1))-11e3+10:r?2:1;process.stderr.write(n?`${JSON.stringify({error:r?t.toJSON():{name:t instanceof Error?t.name:`Error`,message:i},exitCode:o})}\n`:`${a?`[${a}] `:``}${i}\n`),process.exit(o)}async function u(e,n,r=!1){let i=n;try{await e?.$disconnect()}catch(e){i={value:n?t(n.value,e):e}}i&&(r?l(i.value,!0):l(i.value))}async function d(e,t,n){let r,i;try{let t=await p(e);r=t.client,await n(t)}catch(e){i={value:e}}finally{await u(r,i,t)}}function f(e,t){if(t){process.stdout.write(`${JSON.stringify(e,null,2)}\n`);return}let n=[],r=(e,t=``)=>{if(Array.isArray(e)){for(let i of e)n.push(`${t}-`),r(i,`${t} `);e.length===0&&n.push(`${t}(none)`)}else if(typeof e==`object`&&e)for(let[i,a]of Object.entries(e))typeof a==`object`&&a?(n.push(`${t}${i}:`),r(a,`${t} `)):n.push(`${t}${i}: ${String(a)}`);else n.push(`${t}${String(e)}`)};r(e),process.stdout.write(`${n.join(`
|
|
2
|
+
`)}\n`)}async function p(e={}){let t=process.cwd(),o=i(t,`.env`);r(o)&&a(o);let l=e.config?i(t,e.config):c(t,s);if(!(l&&r(l))){let t=e.config?[e.config]:s;throw Error(`Could not find VibORM configuration file.
|
|
3
|
+
|
|
4
|
+
Searched for:\n${t.map(e=>` - ${e}`).join(`
|
|
5
|
+
`)}\n\nCreate a viborm.config.ts file:
|
|
6
|
+
|
|
7
|
+
import { defineConfig } from "viborm/config";\n import { client } from "./src/db";\n\n export default defineConfig({
|
|
8
|
+
client,
|
|
9
|
+
});
|
|
10
|
+
`)}let u=await(e.importer??m)(l),d=Object.hasOwn(u,`default`)&&u.default||u.config||u;if(!d.client)throw Error(`Missing "client" in ${l}.\n\nYour config should include a VibORM client:
|
|
11
|
+
|
|
12
|
+
import { createClient } from "viborm";\n const client = createClient({ driver, schema });
|
|
13
|
+
|
|
14
|
+
export default defineConfig({
|
|
15
|
+
client,
|
|
16
|
+
});
|
|
17
|
+
`);if(!_(d.client))throw Error(`Invalid "client" in ${l}.\n\nThe client must be created with createClient().
|
|
18
|
+
`);let f=d.client.$driver,p=d.client.$schema,g=h(p);if(Object.keys(g).length===0)throw Error(`No models found in client schema from ${l}.\n\nMake sure your client was created with schema models:
|
|
19
|
+
|
|
20
|
+
// src/schema.ts
|
|
21
|
+
import { s } from "viborm";\n\n export const user = s.model({
|
|
22
|
+
id: s.string().id(),
|
|
23
|
+
name: s.string(),
|
|
24
|
+
});
|
|
25
|
+
`);return e.skipValidation||n(g),{client:d.client,driver:f,models:g,migrations:d.migrations}}function m(e){return o(e,{tsconfigPaths:!0,interopDefault:!0}).import(e)}function h(e){let t={};for(let[n,r]of Object.entries(e))g(r)&&(t[n]=r);return t}function g(e){if(typeof e!=`object`||!e)return!1;let t=Reflect.get(e,`~`);if(typeof t!=`object`||!t)return!1;let n=Reflect.get(t,`state`);return typeof n==`object`&&!!n&&`scalars`in n}function _(e){return e===null||typeof e!=`object`&&typeof e!=`function`?!1:Reflect.get(e,`$driver`)!==void 0&&Reflect.get(e,`$schema`)!==void 0}function v(e){return e}export{d as a,f as i,l as n,m as r,v as t};
|
|
26
|
+
//# sourceMappingURL=utils-BHkJsduV.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"utils-CpAojrCj.mjs","names":[],"sources":["../src/cli/utils.ts"],"sourcesContent":["/**\n * CLI Utilities\n *\n * Configuration loading and other CLI utilities.\n *\n * Config file pattern similar to:\n * - drizzle.config.ts\n * - prisma (uses schema.prisma but we use TS)\n */\n\nimport { existsSync } from \"node:fs\";\nimport { resolve } from \"node:path\";\nimport { loadEnvFile } from \"node:process\";\nimport { createJiti } from \"jiti\";\nimport type { AnyDriver } from \"../drivers/driver\";\nimport { withSuppressedFailure } from \"../drivers/shared/suppressed-failure\";\nimport { isVibORMError } from \"../errors\";\nimport type { MigrationClient } from \"../migrations/push/planner\";\nimport type { MigrationStorageWriter } from \"../migrations/storage/contract\";\nimport type { ResolveCallback } from \"../migrations/types\";\nimport type { AnyModel } from \"../schema/model\";\nimport { validateSchemaOrThrow } from \"../schema/validation\";\n\n// =============================================================================\n// CONFIG TYPES\n// =============================================================================\n\n/**\n * Migration configuration options.\n */\nexport interface MigrationConfig {\n /** Estate directory (default: \"./migrations\") */\n dir?: string;\n /** Immutable exact physical table scope; include junctions and rename destinations. */\n tables?: readonly string[];\n /** Explicit rename, destructive-change and enum-value decisions for CLI planning. */\n resolve?: ResolveCallback;\n /**\n * Estate storage writer. Defaults to filesystem storage at `dir`.\n *\n * @example\n * ```ts\n * import { createFsStorageWriter } from \"viborm/migrations/storage/fs\";\n *\n * migrations: {\n * storage: createFsStorageWriter(\"./migrations\"),\n * }\n * ```\n */\n storage?: MigrationStorageWriter;\n}\n\n/**\n * VibORM configuration file format.\n *\n * Example viborm.config.ts:\n * ```ts\n * import { defineConfig } from \"viborm/config\";\n * import { client } from \"./src/db\";\n *\n * export default defineConfig({\n * client,\n * });\n * ```\n */\nexport interface VibORMConfig {\n /** VibORM client instance */\n client: MigrationClient & { $disconnect(): Promise<void> };\n /** Optional: Migration configuration */\n migrations?: MigrationConfig;\n}\n\nexport interface LoadConfigOptions {\n /** Path to config file (default: ./viborm.config.ts) */\n config?: string;\n /** Leave validation to the caller (`viborm check` reports every issue). */\n skipValidation?: boolean;\n /** How the config module is imported; jiti unless a runtime imports TypeScript itself. */\n importer?: (path: string) => Promise<unknown>;\n}\n\nexport interface LoadedConfig {\n client: VibORMConfig[\"client\"];\n driver: AnyDriver;\n models: Record<string, AnyModel>;\n migrations?: MigrationConfig;\n}\n\n// =============================================================================\n// CONFIG FILE DISCOVERY\n// =============================================================================\n\nconst CONFIG_FILES = [\n \"viborm.config.ts\",\n \"viborm.config.mts\",\n \"viborm.config.js\",\n \"viborm.config.mjs\",\n];\n\n/**\n * Finds the first existing file from a list of candidates.\n */\nfunction findFile(cwd: string, candidates: string[]): string | null {\n for (const candidate of candidates) {\n const fullPath = resolve(cwd, candidate);\n if (existsSync(fullPath)) {\n return fullPath;\n }\n }\n return null;\n}\n\n// =============================================================================\n// CONFIG LOADING\n// =============================================================================\n\n/**\n * Loads VibORM configuration from viborm.config.ts file.\n *\n * The config file should export a default configuration object with:\n * - client: VibORM client instance created with createClient()\n */\nexport function failCli(error: unknown, json = false): never {\n const trusted = isVibORMError(error);\n const message =\n error instanceof Error\n ? error.message\n : typeof error === \"string\"\n ? error\n : \"CLI operation failed\";\n const code = trusted ? error.code : undefined;\n const exitCode = code?.startsWith(\"V11\")\n ? Number(code.slice(1)) - 11_000 + 10\n : trusted\n ? 2\n : 1;\n process.stderr.write(\n json\n ? `${JSON.stringify({ error: trusted ? error.toJSON() : { name: error instanceof Error ? error.name : \"Error\", message }, exitCode })}\\n`\n : `${code ? `[${code}] ` : \"\"}${message}\\n`\n );\n process.exit(exitCode);\n}\n\n/** Await owned CLI cleanup before reporting either the primary or cleanup failure. */\nexport async function finishCli(\n client: { $disconnect(): Promise<void> } | undefined,\n failure: { value: unknown } | undefined,\n json = false\n): Promise<void> {\n let outcome = failure;\n try {\n await client?.$disconnect();\n } catch (cleanup) {\n outcome = {\n value: failure ? withSuppressedFailure(failure.value, cleanup) : cleanup,\n };\n }\n if (outcome) {\n if (json) failCli(outcome.value, true);\n else failCli(outcome.value);\n }\n}\n\n/** Every command's frame: load the config, own its client, report through {@link finishCli}. */\nexport async function runCli(\n load: LoadConfigOptions,\n json: boolean | undefined,\n body: (config: LoadedConfig) => Promise<void>\n): Promise<void> {\n let client: { $disconnect(): Promise<void> } | undefined;\n let failure: { value: unknown } | undefined;\n try {\n const config = await loadConfig(load);\n client = config.client;\n await body(config);\n } catch (error) {\n failure = { value: error };\n } finally {\n await finishCli(client, failure, json);\n }\n}\n\n/** JSON for `--json`, else an indented outline of the same value. */\nexport function printJson(value: unknown, json: boolean): void {\n if (json) {\n process.stdout.write(`${JSON.stringify(value, null, 2)}\\n`);\n return;\n }\n const lines: string[] = [];\n const render = (item: unknown, indent = \"\") => {\n if (Array.isArray(item)) {\n for (const entry of item) {\n lines.push(`${indent}-`);\n render(entry, `${indent} `);\n }\n if (item.length === 0) lines.push(`${indent}(none)`);\n } else if (item !== null && typeof item === \"object\") {\n for (const [key, entry] of Object.entries(item)) {\n if (entry !== null && typeof entry === \"object\") {\n lines.push(`${indent}${key}:`);\n render(entry, `${indent} `);\n } else lines.push(`${indent}${key}: ${String(entry)}`);\n }\n } else lines.push(`${indent}${String(item)}`);\n };\n render(value);\n process.stdout.write(`${lines.join(\"\\n\")}\\n`);\n}\n\nexport async function loadConfig(\n options: LoadConfigOptions = {}\n): Promise<LoadedConfig> {\n const cwd = process.cwd();\n const envPath = resolve(cwd, \".env\");\n if (existsSync(envPath)) loadEnvFile(envPath);\n\n // Find config file\n const configPath = options.config\n ? resolve(cwd, options.config)\n : findFile(cwd, CONFIG_FILES);\n\n if (!(configPath && existsSync(configPath))) {\n const searchedPaths = options.config ? [options.config] : CONFIG_FILES;\n\n throw new Error(\n \"Could not find VibORM configuration file.\\n\\n\" +\n `Searched for:\\n${searchedPaths.map((f) => ` - ${f}`).join(\"\\n\")}\\n\\n` +\n \"Create a viborm.config.ts file:\\n\\n\" +\n ` import { defineConfig } from \"viborm/config\";\\n` +\n ` import { client } from \"./src/db\";\\n\\n` +\n \" export default defineConfig({\\n\" +\n \" client,\\n\" +\n \" });\\n\"\n );\n }\n\n // Load the config file\n const configModule = (await (options.importer ?? loadCliModule)(\n configPath\n )) as VibORMConfig & { default?: VibORMConfig; config?: VibORMConfig };\n\n // Extract config (handle both default export and named export)\n const config: VibORMConfig =\n (Object.hasOwn(configModule, \"default\") && configModule.default) ||\n configModule.config ||\n configModule;\n\n // Validate client\n if (!config.client) {\n throw new Error(\n `Missing \"client\" in ${configPath}.\\n\\n` +\n \"Your config should include a VibORM client:\\n\\n\" +\n ` import { createClient } from \"viborm\";\\n` +\n \" const client = createClient({ driver, schema });\\n\\n\" +\n \" export default defineConfig({\\n\" +\n \" client,\\n\" +\n \" });\\n\"\n );\n }\n\n if (!isValidClient(config.client)) {\n throw new Error(\n `Invalid \"client\" in ${configPath}.\\n\\n` +\n \"The client must be created with createClient().\\n\"\n );\n }\n\n // Extract driver and schema from client\n const driver = config.client.$driver;\n const schemaInput = config.client.$schema;\n\n // Extract models from schema (filter out non-model exports)\n const models = extractModels(schemaInput);\n\n if (Object.keys(models).length === 0) {\n throw new Error(\n `No models found in client schema from ${configPath}.\\n\\n` +\n \"Make sure your client was created with schema models:\\n\\n\" +\n \" // src/schema.ts\\n\" +\n ` import { s } from \"viborm\";\\n\\n` +\n \" export const user = s.model({\\n\" +\n \" id: s.string().id(),\\n\" +\n \" name: s.string(),\\n\" +\n \" });\\n\"\n );\n }\n\n // Validate schema before proceeding\n if (!options.skipValidation) validateSchemaOrThrow(models);\n\n return {\n client: config.client,\n driver,\n models,\n migrations: config.migrations,\n };\n}\n\n/**\n * Dynamically imports a TypeScript/JavaScript module.\n */\nexport function loadCliModule<T>(filePath: string): Promise<T> {\n // Dependency imports need CJS interop; consumers select only authored defaults.\n return createJiti(filePath, {\n tsconfigPaths: true,\n interopDefault: true,\n }).import<T>(filePath);\n}\n\n/**\n * Extracts model objects from a module by checking for Model instances.\n */\nfunction extractModels(\n schema: Record<string, unknown>\n): Record<string, AnyModel> {\n const models: Record<string, AnyModel> = {};\n\n for (const [key, value] of Object.entries(schema)) {\n if (isModel(value)) {\n models[key] = value;\n }\n }\n\n return models;\n}\n\n/**\n * Checks if a value is a VibORM Model instance.\n */\nfunction isModel(value: unknown): value is AnyModel {\n if (value === null || typeof value !== \"object\") return false;\n const metadata = Reflect.get(value, \"~\");\n if (metadata === null || typeof metadata !== \"object\") return false;\n const state = Reflect.get(metadata, \"state\");\n // Model state exposes `scalars`/`relations` (never `fields`); the rest of\n // the codebase discriminates models the same way (see serializer).\n return state !== null && typeof state === \"object\" && \"scalars\" in state;\n}\n\n/**\n * Checks if a value is a valid VibORM client instance.\n */\nfunction isValidClient(value: unknown): boolean {\n // The client is a Proxy whose only trap is `get`, so `\"$driver\" in value`\n // (which triggers the `has` trap / falls back to the bare target) is always\n // false. Probe via property access instead.\n // `typeof null === \"object\"`, so null has to be refused here: Reflect.get\n // throws on it rather than answering undefined.\n if (\n value === null ||\n (typeof value !== \"object\" && typeof value !== \"function\")\n ) {\n return false;\n }\n return (\n Reflect.get(value, \"$driver\") !== undefined &&\n Reflect.get(value, \"$schema\") !== undefined\n );\n}\n\n// =============================================================================\n// DEFINE CONFIG HELPER\n// =============================================================================\n\n/**\n * Helper function for defining VibORM configuration with type safety.\n *\n * @example\n * ```ts\n * // viborm.config.ts\n * import { defineConfig } from \"viborm/config\";\n * import { client } from \"./src/db\";\n *\n * export default defineConfig({\n * client,\n * });\n * ```\n */\nexport function defineConfig<const C extends VibORMConfig>(\n config: C &\n Record<Exclude<keyof C, keyof VibORMConfig>, never> &\n (C extends { migrations: infer M }\n ? {\n migrations: M &\n Record<Exclude<keyof M, keyof MigrationConfig>, never>;\n }\n : unknown)\n): C {\n return config;\n}\n"],"mappings":"qUA4FA,MAAM,EAAe,CACnB,mBACA,oBACA,mBACA,oBACD,CAKD,SAAS,SAAS,EAAa,EAAqC,CAClE,IAAK,IAAM,KAAa,EAAY,CAClC,IAAM,EAAW,EAAQ,EAAK,EAAU,CACxC,GAAI,EAAW,EAAS,CACtB,OAAO,EAGX,OAAO,KAaT,SAAgB,QAAQ,EAAgB,EAAO,GAAc,CAC3D,IAAM,EAAU,EAAc,EAAM,CAC9B,EACJ,aAAiB,MACb,EAAM,QACN,OAAO,GAAU,SACf,EACA,uBACF,EAAO,EAAU,EAAM,KAAO,IAAA,GAC9B,EAAW,GAAM,WAAW,MAAM,CACpC,OAAO,EAAK,MAAM,EAAE,CAAC,CAAG,KAAS,GACjC,EACE,EACA,EACN,QAAQ,OAAO,MACb,EACI,GAAG,KAAK,UAAU,CAAE,MAAO,EAAU,EAAM,QAAQ,CAAG,CAAE,KAAM,aAAiB,MAAQ,EAAM,KAAO,QAAS,UAAS,CAAE,WAAU,CAAC,CAAC,IACpI,GAAG,EAAO,IAAI,EAAK,IAAM,KAAK,EAAQ,IAC3C,CACD,QAAQ,KAAK,EAAS,CAIxB,eAAsB,UACpB,EACA,EACA,EAAO,GACQ,CACf,IAAI,EAAU,EACd,GAAI,CACF,MAAM,GAAQ,aAAa,OACpB,EAAS,CAChB,EAAU,CACR,MAAO,EAAU,EAAsB,EAAQ,MAAO,EAAQ,CAAG,EAClE,CAEC,IACE,EAAM,QAAQ,EAAQ,MAAO,GAAK,CACjC,QAAQ,EAAQ,MAAM,EAK/B,eAAsB,OACpB,EACA,EACA,EACe,CACf,IAAI,EACA,EACJ,GAAI,CACF,IAAM,EAAS,MAAM,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AO,UAAU,GAAK,IAAA,IAClC,QAAQ,IAAI,EAAO,UAAU,GAAK,IAAA,GAsBtC,SAAgB,aACd,EAQG,CACH,OAAO"}
|
|
1
|
+
{"version":3,"file":"utils-BHkJsduV.mjs","names":[],"sources":["../src/cli/utils.ts"],"sourcesContent":["/**\n * CLI Utilities\n *\n * Configuration loading and other CLI utilities.\n *\n * Config file pattern similar to:\n * - drizzle.config.ts\n * - prisma (uses schema.prisma but we use TS)\n */\n\nimport { existsSync } from \"node:fs\";\nimport { resolve } from \"node:path\";\nimport { loadEnvFile } from \"node:process\";\nimport { createJiti } from \"jiti\";\nimport type { AnyDriver } from \"../drivers/driver\";\nimport { withSuppressedFailure } from \"../drivers/shared/suppressed-failure\";\nimport { isVibORMError } from \"../errors\";\nimport type { MigrationClient } from \"../migrations/push/planner\";\nimport type { MigrationStorageWriter } from \"../migrations/storage/contract\";\nimport type { ResolveCallback } from \"../migrations/types\";\nimport type { AnyModel } from \"../schema/model\";\nimport { validateSchemaOrThrow } from \"../schema/validation\";\n\n// =============================================================================\n// CONFIG TYPES\n// =============================================================================\n\n/**\n * Migration configuration options.\n */\nexport interface MigrationConfig {\n /** Estate directory (default: \"./migrations\") */\n dir?: string;\n /** Immutable exact physical table scope; include junctions and rename destinations. */\n tables?: readonly string[];\n /** Explicit rename, destructive-change and enum-value decisions for CLI planning. */\n resolve?: ResolveCallback;\n /**\n * Estate storage writer. Defaults to filesystem storage at `dir`.\n *\n * @example\n * ```ts\n * import { createFsStorageWriter } from \"viborm/migrations/storage/fs\";\n *\n * migrations: {\n * storage: createFsStorageWriter(\"./migrations\"),\n * }\n * ```\n */\n storage?: MigrationStorageWriter;\n}\n\n/**\n * VibORM configuration file format.\n *\n * Example viborm.config.ts:\n * ```ts\n * import { defineConfig } from \"viborm/config\";\n * import { client } from \"./src/db\";\n *\n * export default defineConfig({\n * client,\n * });\n * ```\n */\nexport interface VibORMConfig {\n /** VibORM client instance */\n client: MigrationClient & { $disconnect(): Promise<void> };\n /** Optional: Migration configuration */\n migrations?: MigrationConfig;\n}\n\nexport interface LoadConfigOptions {\n /** Path to config file (default: ./viborm.config.ts) */\n config?: string;\n /** Leave validation to the caller (`viborm check` reports every issue). */\n skipValidation?: boolean;\n /** How the config module is imported; jiti unless a runtime imports TypeScript itself. */\n importer?: (path: string) => Promise<unknown>;\n}\n\nexport interface LoadedConfig {\n client: VibORMConfig[\"client\"];\n driver: AnyDriver;\n models: Record<string, AnyModel>;\n migrations?: MigrationConfig;\n}\n\n// =============================================================================\n// CONFIG FILE DISCOVERY\n// =============================================================================\n\nconst CONFIG_FILES = [\n \"viborm.config.ts\",\n \"viborm.config.mts\",\n \"viborm.config.js\",\n \"viborm.config.mjs\",\n];\n\n/**\n * Finds the first existing file from a list of candidates.\n */\nfunction findFile(cwd: string, candidates: string[]): string | null {\n for (const candidate of candidates) {\n const fullPath = resolve(cwd, candidate);\n if (existsSync(fullPath)) {\n return fullPath;\n }\n }\n return null;\n}\n\n// =============================================================================\n// CONFIG LOADING\n// =============================================================================\n\n/**\n * Loads VibORM configuration from viborm.config.ts file.\n *\n * The config file should export a default configuration object with:\n * - client: VibORM client instance created with createClient()\n */\nexport function failCli(error: unknown, json = false): never {\n const trusted = isVibORMError(error);\n const message =\n error instanceof Error\n ? error.message\n : typeof error === \"string\"\n ? error\n : \"CLI operation failed\";\n const code = trusted ? error.code : undefined;\n const exitCode = code?.startsWith(\"V11\")\n ? Number(code.slice(1)) - 11_000 + 10\n : trusted\n ? 2\n : 1;\n process.stderr.write(\n json\n ? `${JSON.stringify({ error: trusted ? error.toJSON() : { name: error instanceof Error ? error.name : \"Error\", message }, exitCode })}\\n`\n : `${code ? `[${code}] ` : \"\"}${message}\\n`\n );\n process.exit(exitCode);\n}\n\n/** Await owned CLI cleanup before reporting either the primary or cleanup failure. */\nexport async function finishCli(\n client: { $disconnect(): Promise<void> } | undefined,\n failure: { value: unknown } | undefined,\n json = false\n): Promise<void> {\n let outcome = failure;\n try {\n await client?.$disconnect();\n } catch (cleanup) {\n outcome = {\n value: failure ? withSuppressedFailure(failure.value, cleanup) : cleanup,\n };\n }\n if (outcome) {\n if (json) failCli(outcome.value, true);\n else failCli(outcome.value);\n }\n}\n\n/** Every command's frame: load the config, own its client, report through {@link finishCli}. */\nexport async function runCli(\n load: LoadConfigOptions,\n json: boolean | undefined,\n body: (config: LoadedConfig) => Promise<void>\n): Promise<void> {\n let client: { $disconnect(): Promise<void> } | undefined;\n let failure: { value: unknown } | undefined;\n try {\n const config = await loadConfig(load);\n client = config.client;\n await body(config);\n } catch (error) {\n failure = { value: error };\n } finally {\n await finishCli(client, failure, json);\n }\n}\n\n/** JSON for `--json`, else an indented outline of the same value. */\nexport function printJson(value: unknown, json: boolean): void {\n if (json) {\n process.stdout.write(`${JSON.stringify(value, null, 2)}\\n`);\n return;\n }\n const lines: string[] = [];\n const render = (item: unknown, indent = \"\") => {\n if (Array.isArray(item)) {\n for (const entry of item) {\n lines.push(`${indent}-`);\n render(entry, `${indent} `);\n }\n if (item.length === 0) lines.push(`${indent}(none)`);\n } else if (item !== null && typeof item === \"object\") {\n for (const [key, entry] of Object.entries(item)) {\n if (entry !== null && typeof entry === \"object\") {\n lines.push(`${indent}${key}:`);\n render(entry, `${indent} `);\n } else lines.push(`${indent}${key}: ${String(entry)}`);\n }\n } else lines.push(`${indent}${String(item)}`);\n };\n render(value);\n process.stdout.write(`${lines.join(\"\\n\")}\\n`);\n}\n\nexport async function loadConfig(\n options: LoadConfigOptions = {}\n): Promise<LoadedConfig> {\n const cwd = process.cwd();\n const envPath = resolve(cwd, \".env\");\n if (existsSync(envPath)) loadEnvFile(envPath);\n\n // Find config file\n const configPath = options.config\n ? resolve(cwd, options.config)\n : findFile(cwd, CONFIG_FILES);\n\n if (!(configPath && existsSync(configPath))) {\n const searchedPaths = options.config ? [options.config] : CONFIG_FILES;\n\n throw new Error(\n \"Could not find VibORM configuration file.\\n\\n\" +\n `Searched for:\\n${searchedPaths.map((f) => ` - ${f}`).join(\"\\n\")}\\n\\n` +\n \"Create a viborm.config.ts file:\\n\\n\" +\n ` import { defineConfig } from \"viborm/config\";\\n` +\n ` import { client } from \"./src/db\";\\n\\n` +\n \" export default defineConfig({\\n\" +\n \" client,\\n\" +\n \" });\\n\"\n );\n }\n\n // Load the config file\n const configModule = (await (options.importer ?? loadCliModule)(\n configPath\n )) as VibORMConfig & { default?: VibORMConfig; config?: VibORMConfig };\n\n // Extract config (handle both default export and named export)\n const config: VibORMConfig =\n (Object.hasOwn(configModule, \"default\") && configModule.default) ||\n configModule.config ||\n configModule;\n\n // Validate client\n if (!config.client) {\n throw new Error(\n `Missing \"client\" in ${configPath}.\\n\\n` +\n \"Your config should include a VibORM client:\\n\\n\" +\n ` import { createClient } from \"viborm\";\\n` +\n \" const client = createClient({ driver, schema });\\n\\n\" +\n \" export default defineConfig({\\n\" +\n \" client,\\n\" +\n \" });\\n\"\n );\n }\n\n if (!isValidClient(config.client)) {\n throw new Error(\n `Invalid \"client\" in ${configPath}.\\n\\n` +\n \"The client must be created with createClient().\\n\"\n );\n }\n\n // Extract driver and schema from client\n const driver = config.client.$driver;\n const schemaInput = config.client.$schema;\n\n // Extract models from schema (filter out non-model exports)\n const models = extractModels(schemaInput);\n\n if (Object.keys(models).length === 0) {\n throw new Error(\n `No models found in client schema from ${configPath}.\\n\\n` +\n \"Make sure your client was created with schema models:\\n\\n\" +\n \" // src/schema.ts\\n\" +\n ` import { s } from \"viborm\";\\n\\n` +\n \" export const user = s.model({\\n\" +\n \" id: s.string().id(),\\n\" +\n \" name: s.string(),\\n\" +\n \" });\\n\"\n );\n }\n\n // Validate schema before proceeding\n if (!options.skipValidation) validateSchemaOrThrow(models);\n\n return {\n client: config.client,\n driver,\n models,\n migrations: config.migrations,\n };\n}\n\n/**\n * Dynamically imports a TypeScript/JavaScript module.\n */\nexport function loadCliModule<T>(filePath: string): Promise<T> {\n // Dependency imports need CJS interop; consumers select only authored defaults.\n return createJiti(filePath, {\n tsconfigPaths: true,\n interopDefault: true,\n }).import<T>(filePath);\n}\n\n/**\n * Extracts model objects from a module by checking for Model instances.\n */\nfunction extractModels(\n schema: Record<string, unknown>\n): Record<string, AnyModel> {\n const models: Record<string, AnyModel> = {};\n\n for (const [key, value] of Object.entries(schema)) {\n if (isModel(value)) {\n models[key] = value;\n }\n }\n\n return models;\n}\n\n/**\n * Checks if a value is a VibORM Model instance.\n */\nfunction isModel(value: unknown): value is AnyModel {\n if (value === null || typeof value !== \"object\") return false;\n const metadata = Reflect.get(value, \"~\");\n if (metadata === null || typeof metadata !== \"object\") return false;\n const state = Reflect.get(metadata, \"state\");\n // Model state exposes `scalars`/`relations` (never `fields`); the rest of\n // the codebase discriminates models the same way (see serializer).\n return state !== null && typeof state === \"object\" && \"scalars\" in state;\n}\n\n/**\n * Checks if a value is a valid VibORM client instance.\n */\nfunction isValidClient(value: unknown): boolean {\n // The client is a Proxy whose only trap is `get`, so `\"$driver\" in value`\n // (which triggers the `has` trap / falls back to the bare target) is always\n // false. Probe via property access instead.\n // `typeof null === \"object\"`, so null has to be refused here: Reflect.get\n // throws on it rather than answering undefined.\n if (\n value === null ||\n (typeof value !== \"object\" && typeof value !== \"function\")\n ) {\n return false;\n }\n return (\n Reflect.get(value, \"$driver\") !== undefined &&\n Reflect.get(value, \"$schema\") !== undefined\n );\n}\n\n// =============================================================================\n// DEFINE CONFIG HELPER\n// =============================================================================\n\n/**\n * Helper function for defining VibORM configuration with type safety.\n *\n * @example\n * ```ts\n * // viborm.config.ts\n * import { defineConfig } from \"viborm/config\";\n * import { client } from \"./src/db\";\n *\n * export default defineConfig({\n * client,\n * });\n * ```\n */\nexport function defineConfig<const C extends VibORMConfig>(\n config: C &\n Record<Exclude<keyof C, keyof VibORMConfig>, never> &\n (C extends { migrations: infer M }\n ? {\n migrations: M &\n Record<Exclude<keyof M, keyof MigrationConfig>, never>;\n }\n : unknown)\n): C {\n return config;\n}\n"],"mappings":"iSA4FA,MAAM,EAAe,CACnB,mBACA,oBACA,mBACA,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extEncoder;function s(e){return o.encode(l(e))}function c(e){return l(e)}function l(e){if(e===null)return`null`;if(e===!0)return`true`;if(e===!1)return`false`;if(typeof e==`string`)return JSON.stringify(e);if(typeof e==`number`)return u(e);if(Array.isArray(e)){let t=Array(e.length);for(let n=0;n<e.length;n++)t[n]=l(e[n]);return`[${t.join(`,`)}]`}if(i(e)){let t=Object.keys(e).sort(d),n=Array(t.length);for(let r=0;r<t.length;r++){let i=t[r];n[r]=`${JSON.stringify(i)}:${l(e[i])}`}return`{${n.join(`,`)}}`}throw new t(`Canonical JSON refuses undefined, bigint, function, symbol, and boxed values`,`V11012`)}function u(e){if(!Number.isFinite(e))throw new t(`Canonical JSON refuses NaN and Infinity`,`V11012`);return Object.is(e,-0)?`0`:JSON.stringify(e)}function d(e,t){return e===t?0:e<t?-1:1}function f(e,n,r){if(!m(e,s(n)))throw new t(`${r} is not canonical RFC 8785 JSON`,`V11012`)}function p(n,r){if(n.length>=3&&n[0]===239&&n[1]===187&&n[2]===191)throw new t(`${r} must be UTF-8 without a BOM`,`V11012`);try{return JSON.parse(new TextDecoder(`utf-8`,{fatal:!0}).decode(n))}catch(n){throw new t(`${r} is not valid UTF-8 JSON`,`V11012`,{cause:e(n)})}}function m(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}function h(e){throw new t(e,`V11012`)}function g(e){throw new t(e,`V11022`)}const _=e=>e.split(` `);function v(e,t,n,r){i(e)||h(`${r} must be an object`);for(let n of Object.keys(e))t.includes(n)||h(`${r} unknown key ${n}`);for(let t of n)t in e||h(`${r} missing ${t}`);return e}function y(e,t,n){return v(e,t,t,n)}function b(e,t,n){return D(e[t],`${n}.${t}`)}function x(e,t,n){return j(e[t],`${n}.${t}`)}function S(e,t,n){return e===null?null:t(e,n)}function C(e,t){return e!==`1`&&h(`${t} format must be "1"`),`1`}function w(e,t){return n(e)&&Number.isSafeInteger(e)||h(`${t} must be a safe integer`),e}function T(e,t){return r(e)||h(`${t} must be boolean`),e}function E(e,t){return a(e)||h(`${t} must be a string`),e}function D(e,t){return(!a(e)||e.length===0)&&h(`${t} must be non-empty string`),e}function O(e,t,n){return Array.isArray(e)||h(`${t} must be an array`),I(e,t,n)}function k(e,t,n){return(!Array.isArray(e)||e.length===0)&&h(`${t} must be non-empty array`),I(e,t,n)}function A(e,t){return O(e,t,E)}function j(e,t){return O(e,t,D)}function M(e,t,n){let r=t.find(t=>t===e);return r===void 0&&h(n),r}const N=[!0,1,1n,`1`,`t`,`true`],P=[!1,0,0n,`0`,`f`,`false`];function F(e){return N.includes(e)?!0:P.includes(e)?!1:void 0}function I(e,t,n){return e.map((e,r)=>n(e,`${t}[${r}]`))}export{c as C,s as S,h as _,S as a,f as b,w as c,M as d,k as f,F as g,A as h,_ as i,C as l,E as m,y as n,O as o,D as p,v as r,T as s,g as t,I as u,x as v,p as w,m as x,b as y};
|
|
2
|
+
//# sourceMappingURL=v1-parse-shared-cJ-uD14P.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"v1-parse-shared-cJ-uD14P.mjs","names":[],"sources":["../src/migrations/canonical-json.ts","../src/migrations/v1-parse-shared.ts"],"sourcesContent":["import { errorCause } from \"../errors/diagnostic-safety\";\n/**\n * RFC 8785 JSON Canonicalization Scheme (JCS).\n *\n * Hash identity is these exact UTF-8 bytes. No locale, insertion order,\n * platform line ending, or display formatter participates.\n */\n\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\nimport { isRecord } from \"../validation/value-guards\";\n\nconst UTF8 = new TextEncoder();\n\nexport function canonicalizeJson(value: unknown): Uint8Array {\n return UTF8.encode(serializeJcs(value));\n}\n\nexport function canonicalizeJsonText(value: unknown): string {\n return serializeJcs(value);\n}\n\nfunction serializeJcs(value: unknown): string {\n if (value === null) return \"null\";\n if (value === true) return \"true\";\n if (value === false) return \"false\";\n if (typeof value === \"string\") return JSON.stringify(value);\n if (typeof value === \"number\") return serializeNumber(value);\n if (Array.isArray(value)) {\n const parts = new Array<string>(value.length);\n for (let i = 0; i < value.length; i++) {\n parts[i] = serializeJcs(value[i]);\n }\n return `[${parts.join(\",\")}]`;\n }\n if (isRecord(value)) {\n const keys = Object.keys(value).sort(compareUtf16);\n const parts = new Array<string>(keys.length);\n for (let i = 0; i < keys.length; i++) {\n const key = keys[i]!;\n parts[i] = `${JSON.stringify(key)}:${serializeJcs(value[key])}`;\n }\n return `{${parts.join(\",\")}}`;\n }\n throw new MigrationError(\n \"Canonical JSON refuses undefined, bigint, function, symbol, and boxed values\",\n VibORMErrorCode.MIGRATION_INVALID_ESTATE\n );\n}\n\nfunction serializeNumber(value: number): string {\n if (!Number.isFinite(value)) {\n throw new MigrationError(\n \"Canonical JSON refuses NaN and Infinity\",\n VibORMErrorCode.MIGRATION_INVALID_ESTATE\n );\n }\n if (Object.is(value, -0)) return \"0\";\n return JSON.stringify(value);\n}\n\nfunction compareUtf16(a: string, b: string): number {\n if (a === b) return 0;\n return a < b ? -1 : 1;\n}\n\nexport function assertCanonicalBytes(\n bytes: Uint8Array,\n reconstructed: unknown,\n label: string\n): void {\n if (!bytesEqual(bytes, canonicalizeJson(reconstructed))) {\n throw new MigrationError(\n `${label} is not canonical RFC 8785 JSON`,\n VibORMErrorCode.MIGRATION_INVALID_ESTATE\n );\n }\n}\n\nexport function parseJsonBytes(bytes: Uint8Array, label: string): unknown {\n if (\n bytes.length >= 3 &&\n bytes[0] === 0xef &&\n bytes[1] === 0xbb &&\n bytes[2] === 0xbf\n ) {\n throw new MigrationError(\n `${label} must be UTF-8 without a BOM`,\n VibORMErrorCode.MIGRATION_INVALID_ESTATE\n );\n }\n try {\n return JSON.parse(new TextDecoder(\"utf-8\", { fatal: true }).decode(bytes));\n } catch (cause) {\n throw new MigrationError(\n `${label} is not valid UTF-8 JSON`,\n VibORMErrorCode.MIGRATION_INVALID_ESTATE,\n { cause: errorCause(cause) }\n );\n }\n}\n\nexport function bytesEqual(left: Uint8Array, right: Uint8Array): boolean {\n if (left.length !== right.length) return false;\n for (let i = 0; i < left.length; i++) {\n if (left[i] !== right[i]) return false;\n }\n return true;\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 {\n isBoolean,\n isNumber,\n isRecord,\n isString,\n} from \"../validation/value-guards\";\n\nexport function refuse(message: string): never {\n throw new MigrationError(message, VibORMErrorCode.MIGRATION_INVALID_ESTATE);\n}\n\nexport function corrupt(message: string): never {\n throw new MigrationError(message, VibORMErrorCode.MIGRATION_CORRUPTION);\n}\n\nexport const ks = (keys: string): readonly string[] => keys.split(\" \");\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} unknown key ${key}`);\n }\n for (const key of required) {\n if (!(key in value)) refuse(`${label} missing ${key}`);\n }\n return value;\n}\n\nexport function exactKeys(\n value: unknown,\n keys: readonly string[],\n label: string\n): Record<string, unknown> {\n return exactObject(value, keys, keys, label);\n}\n\nexport function reqStr(\n record: Record<string, unknown>,\n key: string,\n label: string\n): string {\n return parseRequiredString(record[key], `${label}.${key}`);\n}\n\nexport function reqIds(\n record: Record<string, unknown>,\n key: string,\n label: string\n): string[] {\n return parseIdentifierArray(record[key], `${label}.${key}`);\n}\n\nexport function nullableField<T>(\n value: unknown,\n parse: (v: unknown, label: string) => T,\n label: string\n): T | null {\n return value === null ? null : parse(value, label);\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 (!(isNumber(value) && Number.isSafeInteger(value)))\n refuse(`${label} must be a safe integer`);\n return value;\n}\n\nexport function parseBoolean(value: unknown, label: string): boolean {\n if (!isBoolean(value)) refuse(`${label} must be boolean`);\n return value;\n}\n\nexport function parseString(value: unknown, label: string): string {\n if (!isString(value)) refuse(`${label} must be a string`);\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 non-empty string`);\n return value;\n}\n\nexport function parseArray<T>(\n value: unknown,\n label: string,\n parse: (item: unknown, itemLabel: string) => T\n): T[] {\n if (!Array.isArray(value)) refuse(`${label} must be an array`);\n return parseItems(value, label, parse);\n}\n\nexport function parseNonEmptyArray<T>(\n value: unknown,\n label: string,\n parse: (item: unknown, itemLabel: string) => T\n): T[] {\n if (!Array.isArray(value) || value.length === 0)\n refuse(`${label} must be non-empty array`);\n return parseItems(value, label, parse);\n}\n\nexport function parseStringArray(value: unknown, label: string): string[] {\n return parseArray(value, label, parseString);\n}\n\nexport function parseIdentifierArray(value: unknown, label: string): string[] {\n return parseArray(value, label, parseRequiredString);\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/** Parse an already-admitted array with the artifact's indexed diagnostic path. */\nexport function parseItems<T>(\n items: readonly unknown[],\n label: string,\n parse: (value: unknown, label: string) => T\n): T[] {\n return items.map((value, index) => parse(value, `${label}[${index}]`));\n}\n"],"mappings":"sJAWA,MAAM,EAAO,IAAI,YAEjB,SAAgB,EAAiB,EAA4B,CAC3D,OAAO,EAAK,OA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,EAAkC,CAAC,GAAO,EAAG,GAAI,IAAK,IAAK,QAAQ,CAGzE,SAAgB,EAAS,EAAqC,CAE5D,OADI,EAAW,SAAS,EAAM,CAAS,GAChC,EAAY,SAAS,EAAM,CAAG,GAAQ,IAAA,GAI/C,SAAgB,EACd,EACA,EACA,EACK,CACL,OAAO,EAAM,KAAK,EAAO,IAAU,EAAM,EAAO,GAAG,EAAM,GAAG,EAAM,GAAG,CAAC"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{r as e,t}from"./base-17NSFtrA.mjs";var n=class extends e(`ConnectionError`,`V1001`,!0){static get name(){return`ConnectionError`}},r=class extends e(`ClientInitializationError`,`V1004`){static get name(){return`ClientInitializationError`}};function i(e){return e instanceof r}var a=class extends e(`QueryError`,`V2001`,!0){static get name(){return`QueryError`}},o=class extends t{static get name(){return`NotFoundError`}static diagnosticName=`NotFoundError`;constructor(e,t,n){super(`No ${e} record found for ${t}`,`V6001`,{meta:{...n?.meta,model:e,operation:t}})}},s=class extends t{static get name(){return`ForbiddenError`}static diagnosticName=`ForbiddenError`;constructor(e,t,n){super(`The ${t} on ${e} is not permitted${n?.reason?`: ${n.reason}`:``}`,`V13001`,{meta:{...n?.meta,model:e,operation:t},cause:n?.cause})}},c=class extends t{static get name(){return`NestedWriteError`}static diagnosticName=`NestedWriteError`;constructor(e,t,n){super(e,n?.code??`V7001`,{cause:n?.cause,diagnostics:n?.diagnostics,meta:{...n?.meta,relation:t}})}};const l=`Nested write assertion failed: batch precondition did not hold.`;var u=class extends e(`NestedWriteAssertionError`,`V7006`){static get name(){return`NestedWriteAssertionError`}},d=class extends t{static get name(){return`FeatureNotSupportedError`}static diagnosticName=`FeatureNotSupportedError`;constructor(e,t,n){let r=n?`${e}.${t} is not supported. ${n}`:`${e}.${t} is not supported by this driver.`;super(r,`V8001`,{meta:{feature:e,method:t}})}},f=class extends t{static get name(){return`PendingOperationError`}static diagnosticName=`PendingOperationError`;constructor(e,t,n){super(e,t,n)}static alreadyExecutedWithDriver(e,t){return p(e,t,`V12001`,`Cannot await ${e}.${t}(): already executed with executeWith().`)}static alreadyExecutedDefault(e,t){return p(e,t,`V12002`,`Cannot executeWith() ${e}.${t}(): already awaited.`)}static differentDriverConflict(e,t){return p(e,t,`V12002`,`Cannot executeWith() ${e}.${t}() on a different driver.`)}static clientMismatch(e,t){return p(e,t,`V12003`,`${e}.${t}() belongs to a different client.`)}static scopeMismatch(e,t){return p(e,t,`V12004`,`${e}.${t}() belongs to another transaction scope.`)}};function p(e,t,n,r){return new f(r,n,{meta:{model:e,operation:t}})}function m(e){return e instanceof f}var h=class extends t{static get name(){return`QueryEngineError`}static diagnosticName=`QueryEngineError`;constructor(e,t){super(e,t?.code??`V9001`,t)}},g=class extends h{static get name(){return`UnsupportedOperationError`}static diagnosticName=`UnsupportedOperationError`;constructor(e,t){super(e,{...t,code:`V8003`})}};function _(e){return e instanceof g}function v(e){return e instanceof o}function y(e,t,n=`Query and write-outcome publication failed.`){let r=t instanceof AggregateError?[...t.errors]:[t];return AggregateError([e,...r],n,{cause:e})}const b=e=>()=>{throw new d(`vector`,e,`Load the pgvector extension.`)},x={literal:b(`literal`),l2:b(`l2`),cosine:b(`cosine`)},S={createManyAndReturn:`createMany`,updateManyAndReturn:`updateMany`,deleteManyAndReturn:`deleteMany`};function C(e){return S[e]??e}var w=class extends t{static get name(){return`ValidationError`}static diagnosticName=`ValidationError`;issues;source;operation;constructor(e,t,n){let r=t.length===1?[t[0].path,t[0].message].filter(Boolean).join(`: `):`${t.length} validation errors`,i=T(e,n?.meta),a=i.kind===`operation`?i.operation:void 0,o=E(i);super(`Validation failed for ${o}: ${r}`,a?`V4001`:`V4002`,{cause:n?.cause,diagnostics:n?.diagnostics,validation:{source:i,issues:t},meta:a?{...n?.meta,operation:a}:{...n?.meta}}),this.issues=t,this.source=i,this.operation=a}};function T(e,t){if(typeof e==`string`){let n=typeof t?.model==`string`?t.model:void 0;return Object.freeze({kind:`operation`,operation:C(e),...n?{model:n}:{}})}return e.kind===`operation`?Object.freeze({...e,operation:C(e.operation)}):Object.freeze({...e})}function E(e){return e.kind===`operation`?e.model?`${e.model}.${e.operation}`:e.operation:e.kind===`registry`?`schema registry`:e.kind===`schema-builder`?e.builder:`JSON Schema`}function D(e){return e instanceof w}export{m as _,d as a,x as b,u as c,f as d,h as f,v as g,i as h,n as i,c as l,g as m,D as n,s as o,a as p,r,l as s,w as t,o as u,_ as v,y};
|
|
2
|
+
//# sourceMappingURL=validation-ATmgN5RE.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"validation-ATmgN5RE.mjs","names":[],"sources":["../src/errors/query.ts","../src/errors/validation.ts"],"sourcesContent":["import {\n coded,\n VibORMError,\n VibORMErrorCode,\n type VibORMErrorMeta,\n type VibORMErrorOptions,\n} from \"./base\";\n\n/**\n * Every code {@link ConnectionError} can carry. `CLIENT_INITIALIZATION` is NOT here — it has\n * its own class ({@link ClientInitializationError}).\n */\nexport type ConnectionErrorCode =\n | typeof VibORMErrorCode.CONNECTION_FAILED\n | typeof VibORMErrorCode.CONNECTION_TIMEOUT\n | typeof VibORMErrorCode.CONNECTION_CLOSED\n | typeof VibORMErrorCode.CONNECTION_CAPACITY;\n\n/**\n * Connection-related errors\n */\nexport class ConnectionError extends coded<\n ConnectionErrorCode,\n VibORMErrorOptions & { code?: ConnectionErrorCode | undefined }\n>(\"ConnectionError\", VibORMErrorCode.CONNECTION_FAILED, true) {}\n\n/**\n * Client construction failures (Prisma P1012)\n *\n * Raised while a client is being built or while its schema-shaped surface is being resolved:\n * a missing driver, a schema that fails name hydration, or an access to a model the schema\n * does not define. These are configuration faults, not query faults — nothing has reached the\n * database yet.\n *\n * Prisma raises `PrismaClientInitializationError` for the same category and exposes its code\n * on `errorCode`; P1012 is Prisma's \"Schema validation error\", the closest documented code for\n * a client that cannot be constructed from the given schema and configuration. VibORM\n * publishes it through the shared `prismaCode` getter.\n */\nexport class ClientInitializationError extends coded<\n typeof VibORMErrorCode.CLIENT_INITIALIZATION\n>(\"ClientInitializationError\", VibORMErrorCode.CLIENT_INITIALIZATION) {}\n\n/**\n * Type guard for client initialization errors\n */\nexport function isClientInitializationError(\n error: unknown\n): error is ClientInitializationError {\n return error instanceof ClientInitializationError;\n}\n\n/**\n * Every code {@link QueryError} can carry.\n *\n * The `V2xxx` query family plus `INVALID_INPUT`, which the raw-SQL helpers raise through this\n * class when a caller hands `$queryRaw` something that is neither a tagged template nor an\n * `Sql` fragment, or a raw/provider parameter boundary refuses an invalid\n * `Date` (`client/raw.ts`, `drivers/provider-parameter-snapshot.ts`) — measured\n * at the construction sites, not assumed.\n */\nexport type QueryErrorCode =\n | typeof VibORMErrorCode.QUERY_FAILED\n | typeof VibORMErrorCode.QUERY_TIMEOUT\n | typeof VibORMErrorCode.QUERY_SYNTAX\n | typeof VibORMErrorCode.QUERY_SCHEMA_MISMATCH\n | typeof VibORMErrorCode.QUERY_OUT_OF_RANGE\n | typeof VibORMErrorCode.QUERY_RESULT_INVALID\n | typeof VibORMErrorCode.INVALID_INPUT;\n\n/**\n * Query execution errors\n */\nexport class QueryError extends coded<\n QueryErrorCode,\n VibORMErrorOptions & { code?: QueryErrorCode | undefined }\n>(\"QueryError\", VibORMErrorCode.QUERY_FAILED, true) {}\n\n/**\n * Record not found (for OrThrow operations)\n */\nexport class NotFoundError extends VibORMError {\n static override readonly diagnosticName = \"NotFoundError\";\n\n /** Literal discriminant: this class always carries `RECORD_NOT_FOUND`. */\n declare readonly code: typeof VibORMErrorCode.RECORD_NOT_FOUND;\n\n constructor(\n model: string,\n operation: string,\n options?: { meta?: VibORMErrorMeta }\n ) {\n super(\n `No ${model} record found for ${operation}`,\n VibORMErrorCode.RECORD_NOT_FOUND,\n {\n meta: { ...options?.meta, model, operation },\n }\n );\n }\n}\n\n/**\n * A policy refused the operation: the row a write would produce, or an explicit `assert`, is\n * not permitted to the caller. Like {@link NotFoundError}, it never says whether the row was\n * hidden or visible and not permitted, nor whether a referenced row is hidden or missing.\n */\nexport class ForbiddenError extends VibORMError {\n static override readonly diagnosticName = \"ForbiddenError\";\n\n /** Literal discriminant: this class always carries `FORBIDDEN`. */\n declare readonly code: typeof VibORMErrorCode.FORBIDDEN;\n\n /**\n * `reason` names what refused the operation where the operation alone does\n * not say it, e.g. a field an update writes through a nested write;\n * `cause`, the failure it explains (an upsert's unique violation).\n */\n constructor(\n model: string,\n operation: string,\n options?: { meta?: VibORMErrorMeta; reason?: string; cause?: Error }\n ) {\n super(\n `The ${operation} on ${model} is not permitted${options?.reason ? `: ${options.reason}` : \"\"}`,\n VibORMErrorCode.FORBIDDEN,\n {\n meta: { ...options?.meta, model, operation },\n cause: options?.cause,\n }\n );\n }\n}\n\n/**\n * Every code {@link NestedWriteError} can carry.\n *\n * `NESTED_WRITE_ASSERTION_FAILED` is in the union even though\n * {@link NestedWriteAssertionError} owns that code as a class: the un-attributable batch floor\n * (`OperationExecutor.attributeGuardFailure`, `query-engine/batch-error-attribution.ts`)\n * deliberately re-raises the V7006 floor as a `NestedWriteError` so the surfaced error carries\n * the assertion code without claiming the driver-mapped class. Measured at the construction\n * sites; the two are told apart by class, not by code.\n */\nexport type NestedWriteErrorCode =\n | typeof VibORMErrorCode.NESTED_WRITE_FAILED\n | typeof VibORMErrorCode.NESTED_CREATE_FAILED\n | typeof VibORMErrorCode.NESTED_UPDATE_FAILED\n | typeof VibORMErrorCode.NESTED_DELETE_FAILED\n | typeof VibORMErrorCode.NESTED_CONNECT_FAILED\n | typeof VibORMErrorCode.NESTED_WRITE_ASSERTION_FAILED;\n\n/**\n * Nested write operation errors\n */\nexport class NestedWriteError extends VibORMError {\n static override readonly diagnosticName = \"NestedWriteError\";\n\n /** Discriminant: one of {@link NestedWriteErrorCode}, never a code outside the family. */\n declare readonly code: NestedWriteErrorCode;\n\n constructor(\n message: string,\n relation: string,\n options?: VibORMErrorOptions & { code?: NestedWriteErrorCode | undefined }\n ) {\n super(message, options?.code ?? VibORMErrorCode.NESTED_WRITE_FAILED, {\n cause: options?.cause,\n diagnostics: options?.diagnostics,\n meta: { ...options?.meta, relation },\n });\n }\n}\n\n/**\n * The batch assertion-abort floor sentence — one home for the three layers that\n * say it: the executor's guard-free-ladder floor, merged-batch attribution's\n * un-attributable floor, and driver error mapping's assertion translation.\n * The wording matches V1's frozen runtime verbatim; edit it nowhere else.\n */\nexport const NESTED_WRITE_ASSERTION_FLOOR_MESSAGE =\n \"Nested write assertion failed: batch precondition did not hold.\";\n\n/**\n * Batch-plan nested-write assertion failures\n *\n * Atomic batch plans encode preconditions (connect/disconnect targets must\n * exist, correlation checks) as SQL statements that error on purpose when the\n * precondition fails (adapter.assertions). Each dialect surfaces a different\n * raw error (PG: division by zero, MySQL/SQLite: invalid JSON); the driver\n * error mapping normalizes all of them to this type.\n */\nexport class NestedWriteAssertionError extends coded<\n typeof VibORMErrorCode.NESTED_WRITE_ASSERTION_FAILED\n>(\"NestedWriteAssertionError\", VibORMErrorCode.NESTED_WRITE_ASSERTION_FAILED) {}\n\n/**\n * Feature not supported errors\n */\nexport class FeatureNotSupportedError extends VibORMError {\n static override readonly diagnosticName = \"FeatureNotSupportedError\";\n\n /** Literal discriminant: this class always carries `FEATURE_NOT_SUPPORTED`. */\n declare readonly code: typeof VibORMErrorCode.FEATURE_NOT_SUPPORTED;\n\n constructor(feature: string, method: string, suggestion?: string) {\n const message = suggestion\n ? `${feature}.${method} is not supported. ${suggestion}`\n : `${feature}.${method} is not supported by this driver.`;\n super(message, VibORMErrorCode.FEATURE_NOT_SUPPORTED, {\n meta: { feature, method },\n });\n }\n}\n\n/**\n * Pending operation execution errors\n *\n * Thrown when attempting to execute a PendingOperation in an invalid way,\n * such as awaiting after executeWith() or calling executeWith() after await.\n */\n/** Every code {@link PendingOperationError} can carry. */\nexport type PendingOperationErrorCode =\n | typeof VibORMErrorCode.OPERATION_ALREADY_EXECUTED\n | typeof VibORMErrorCode.OPERATION_EXECUTION_CONFLICT\n | typeof VibORMErrorCode.OPERATION_CLIENT_MISMATCH\n | typeof VibORMErrorCode.OPERATION_SCOPE_MISMATCH;\n\nexport class PendingOperationError extends VibORMError {\n static override readonly diagnosticName = \"PendingOperationError\";\n\n /** Discriminant: one of {@link PendingOperationErrorCode}, never a code outside the family. */\n declare readonly code: PendingOperationErrorCode;\n\n // biome-ignore lint/complexity/noUselessConstructor: not a forwarder — it narrows the public signature, restricting `code` to PendingOperationErrorCode and `options` to `{ meta }`; deleting it would widen the constructor back to the base's VibORMErrorCode plus `cause`/`diagnostics`.\n constructor(\n message: string,\n code: PendingOperationErrorCode,\n options?: { meta?: VibORMErrorMeta }\n ) {\n super(message, code, options);\n }\n\n static alreadyExecutedWithDriver(\n model: string,\n operation: string\n ): PendingOperationError {\n return pendingOpError(\n model,\n operation,\n VibORMErrorCode.OPERATION_ALREADY_EXECUTED,\n `Cannot await ${model}.${operation}(): already executed with executeWith().`\n );\n }\n\n static alreadyExecutedDefault(\n model: string,\n operation: string\n ): PendingOperationError {\n return pendingOpError(\n model,\n operation,\n VibORMErrorCode.OPERATION_EXECUTION_CONFLICT,\n `Cannot executeWith() ${model}.${operation}(): already awaited.`\n );\n }\n\n static differentDriverConflict(\n model: string,\n operation: string\n ): PendingOperationError {\n return pendingOpError(\n model,\n operation,\n VibORMErrorCode.OPERATION_EXECUTION_CONFLICT,\n `Cannot executeWith() ${model}.${operation}() on a different driver.`\n );\n }\n\n static clientMismatch(\n model: string,\n operation: string\n ): PendingOperationError {\n return pendingOpError(\n model,\n operation,\n VibORMErrorCode.OPERATION_CLIENT_MISMATCH,\n `${model}.${operation}() belongs to a different client.`\n );\n }\n\n static scopeMismatch(\n model: string,\n operation: string\n ): PendingOperationError {\n return pendingOpError(\n model,\n operation,\n VibORMErrorCode.OPERATION_SCOPE_MISMATCH,\n `${model}.${operation}() belongs to another transaction scope.`\n );\n }\n}\n\nfunction pendingOpError(\n model: string,\n operation: string,\n code: PendingOperationErrorCode,\n message: string\n): PendingOperationError {\n return new PendingOperationError(message, code, {\n meta: { model, operation },\n });\n}\n\n/**\n * Type guard for pending operation errors\n */\nexport function isPendingOperationError(\n error: unknown\n): error is PendingOperationError {\n return error instanceof PendingOperationError;\n}\n\n/**\n * Internal query engine error\n */\n/**\n * Every code a {@link QueryEngineError} can carry — its own `INTERNAL_ERROR`, plus the\n * `UNSUPPORTED_OPERATION` its {@link UnsupportedOperationError} subclass narrows to. A wider\n * type here would be a lie about the class; a narrower one would make the subclass's `code`\n * an illegal override.\n */\nexport type QueryEngineErrorCode =\n | typeof VibORMErrorCode.INTERNAL_ERROR\n | typeof VibORMErrorCode.UNSUPPORTED_OPERATION;\n\nexport class QueryEngineError extends VibORMError {\n // Annotated `string` (not the literal) so a subclass may narrow it — the\n // pattern VibORMError itself uses for its subclasses.\n static override readonly diagnosticName: string = \"QueryEngineError\";\n\n /**\n * Discriminant. `INTERNAL_ERROR` for a bare engine error; the\n * {@link UnsupportedOperationError} subclass narrows it to `UNSUPPORTED_OPERATION`, which is\n * why this is the family and not a single literal — a code check alone cannot separate the\n * two, so {@link classifyFailure} separates them by class.\n */\n declare readonly code: QueryEngineErrorCode;\n\n constructor(\n message: string,\n options?: {\n cause?: Error | undefined;\n meta?: VibORMErrorMeta | undefined;\n /** Subclass seam: a distinct taxonomy code (default INTERNAL_ERROR). */\n code?: QueryEngineErrorCode | undefined;\n }\n ) {\n super(message, options?.code ?? VibORMErrorCode.INTERNAL_ERROR, options);\n }\n}\n\n/**\n * A payload SHAPE the query engine deliberately does not express — a documented\n * capability boundary (a compound key or non-literal fold past a proven surface,\n * an inexpressible sub-shape, a parity refusal), NOT an engine crash. Distinct\n * from {@link FeatureNotSupportedError} (a dialect/driver capability gap): this\n * is shape-capability. It extends {@link QueryEngineError} so pre-existing\n * `instanceof QueryEngineError` handling keeps working, but carries its own\n * name and code (`V8003 UNSUPPORTED_OPERATION`) so a deliberate refusal is\n * distinguishable from `V9001 INTERNAL_ERROR` programmatically and in logs.\n * Users can `instanceof UnsupportedOperationError` (exported from the package\n * root) to branch on it.\n */\nexport class UnsupportedOperationError extends QueryEngineError {\n static override readonly diagnosticName = \"UnsupportedOperationError\";\n\n /** Literal discriminant: this class always carries `UNSUPPORTED_OPERATION`. */\n declare readonly code: typeof VibORMErrorCode.UNSUPPORTED_OPERATION;\n\n constructor(\n message: string,\n options?: {\n cause?: Error | undefined;\n meta?: VibORMErrorMeta | undefined;\n }\n ) {\n super(message, {\n ...options,\n code: VibORMErrorCode.UNSUPPORTED_OPERATION,\n });\n }\n}\n\n/**\n * Type guard for unsupported-operation (shape-capability) refusals\n */\nexport function isUnsupportedOperationError(\n error: unknown\n): error is UnsupportedOperationError {\n return error instanceof UnsupportedOperationError;\n}\n\n/**\n * Type guard for not found errors\n */\nexport function isNotFoundError(error: unknown): error is NotFoundError {\n return error instanceof NotFoundError;\n}\n\n/**\n * Keep the execution failure primary while retaining every listener failure.\n *\n * ONE composition for the whole estate, stated at the boundary all three of its\n * consumers already depend on: the client (`client.ts`, `raw.ts`,\n * `array-transaction.ts`), the query engine's deferred operation\n * (`pending-operation.ts`) and the candidate engine's operation context. It is\n * pure — a primary, the listener failures flattened out of the publication\n * owner's aggregate, and the primary again as `cause` — so it belongs beside the\n * query failures it composes rather than inside the extension publication owner\n * that raises one half of it. The candidate engine takes no `@extensions`\n * import anywhere today, and importing that owner would add\n * `src/extensions/query.ts` and `src/query-engine/routed-operations.ts` to\n * `raptor3/shared/operation-context.ts`'s runtime closure (181 → 183). A\n * directory cycle is not what this placement avoids: the engine→extensions\n * runtime edge already exists — `query-engine/pending-operation.ts` holds it\n * for the shipped path — and is pre-existing. A second restatement inside the\n * engine was the duplication FC-05 deleted.\n */\nexport function retainWriteOutcomeFailure(\n primary: unknown,\n outcomeFailure: unknown,\n message = \"Query and write-outcome publication failed.\"\n): AggregateError {\n const suppressed =\n outcomeFailure instanceof AggregateError\n ? [...outcomeFailure.errors]\n : [outcomeFailure];\n return new AggregateError([primary, ...suppressed], message, {\n cause: primary,\n });\n}\n\nconst noVector = (method: string) => (): never => {\n throw new FeatureNotSupportedError(\n \"vector\",\n method,\n \"Load the pgvector extension.\"\n );\n};\n\n/**\n * Unsupported vector operations\n *\n * Use this to override adapter.vector when pgvector is not available.\n */\nexport const unsupportedVector = {\n literal: noVector(\"literal\"),\n l2: noVector(\"l2\"),\n cosine: noVector(\"cosine\"),\n};\n","import type { Operation } from \"../query-engine/types\";\nimport {\n VibORMError,\n VibORMErrorCode,\n type VibORMErrorMeta,\n type VibORMErrorOptions,\n} from \"./base\";\n\n/**\n * Validation issue details\n */\nexport interface ValidationIssue {\n path: string;\n message: string;\n}\n\n/** The boundary that rejected a value. */\nexport type ValidationErrorSource =\n | {\n readonly kind: \"operation\";\n readonly operation: Operation;\n readonly model?: string | undefined;\n }\n | {\n readonly kind: \"registry\";\n readonly model?: string | undefined;\n readonly property?: string | undefined;\n }\n | {\n readonly kind: \"schema-builder\";\n readonly builder: string;\n readonly path: string;\n }\n | {\n readonly kind: \"json-schema\";\n readonly target?: string | undefined;\n readonly schemaType?: string | undefined;\n };\n\n/**\n * The INTERNAL operation names that have no client spelling, mapped to the name\n * a caller can actually type.\n *\n * `createManyAndReturn` / `updateManyAndReturn` / `deleteManyAndReturn` name the\n * row-returning ARM of a bulk write inside the engine (maintainer decision D-1:\n * the public surface is `createMany` / `updateMany` / `deleteMany` with a\n * `select`). The client refuses those names outright — `pending-operation.ts`\n * answers `Unknown operation 'createManyAndReturn'` — so an error that named one\n * would send a caller to fix an operation the same client says does not exist.\n * Every user-facing name goes through {@link publicOperationName}; anything not\n * in this map is already its own public spelling.\n */\nconst PUBLIC_OPERATION_NAME: Readonly<Partial<Record<Operation, Operation>>> = {\n createManyAndReturn: \"createMany\",\n updateManyAndReturn: \"updateMany\",\n deleteManyAndReturn: \"deleteMany\",\n};\n\n/**\n * The client spelling of an operation — identity for every name a caller can\n * type, and the public family name for the three internal row-returning arms.\n */\nexport function publicOperationName(operation: Operation): Operation {\n return PUBLIC_OPERATION_NAME[operation] ?? operation;\n}\n\n/**\n * Input validation errors\n */\nexport class ValidationError extends VibORMError {\n static override readonly diagnosticName = \"ValidationError\";\n\n /** Operation failures use V4001; other validation boundaries use V4002. */\n declare readonly code:\n | typeof VibORMErrorCode.VALIDATION_FAILED\n | typeof VibORMErrorCode.INVALID_INPUT;\n\n /** Validation issues */\n readonly issues: ValidationIssue[];\n /** Boundary that rejected the value. */\n readonly source: ValidationErrorSource;\n /**\n * Operation that failed validation, in its CLIENT spelling — a bulk write\n * validated through its internal row-returning arm still reports the family\n * name the caller used (see {@link publicOperationName}).\n */\n readonly operation?: Operation | undefined;\n\n constructor(\n sourceOrOperation: Operation | ValidationErrorSource,\n issues: ValidationIssue[],\n options?: VibORMErrorOptions\n ) {\n const issuesSummary =\n issues.length === 1\n ? [issues[0]!.path, issues[0]!.message].filter(Boolean).join(\": \")\n : `${issues.length} validation errors`;\n const source = normalizeSource(sourceOrOperation, options?.meta);\n const operation =\n source.kind === \"operation\" ? source.operation : undefined;\n const subject = validationSubject(source);\n super(\n `Validation failed for ${subject}: ${issuesSummary}`,\n operation\n ? VibORMErrorCode.VALIDATION_FAILED\n : VibORMErrorCode.INVALID_INPUT,\n {\n cause: options?.cause,\n diagnostics: options?.diagnostics,\n validation: { source, issues },\n meta: operation\n ? { ...options?.meta, operation }\n : { ...options?.meta },\n }\n );\n this.issues = issues;\n this.source = source;\n this.operation = operation;\n }\n}\n\nfunction normalizeSource(\n sourceOrOperation: Operation | ValidationErrorSource,\n meta: VibORMErrorMeta | undefined\n): ValidationErrorSource {\n if (typeof sourceOrOperation === \"string\") {\n const model = typeof meta?.model === \"string\" ? meta.model : undefined;\n return Object.freeze({\n kind: \"operation\",\n operation: publicOperationName(sourceOrOperation),\n ...(model ? { model } : {}),\n });\n }\n\n if (sourceOrOperation.kind === \"operation\") {\n return Object.freeze({\n ...sourceOrOperation,\n operation: publicOperationName(sourceOrOperation.operation),\n });\n }\n\n return Object.freeze({ ...sourceOrOperation });\n}\n\nfunction validationSubject(source: ValidationErrorSource): string {\n if (source.kind === \"operation\")\n return source.model\n ? `${source.model}.${source.operation}`\n : source.operation;\n if (source.kind === \"registry\") return \"schema registry\";\n if (source.kind === \"schema-builder\") return source.builder;\n return \"JSON Schema\";\n}\n\n/**\n * Type guard for validation errors\n */\nexport function isValidationError(error: unknown): error is ValidationError {\n return error instanceof ValidationError;\n}\n"],"mappings":"0CAqBA,IAAa,EAAb,cAAqC,EAGnC,kBAAmB,QAAA,GAAA,AAAe,CAAC,WAAA,MAAA,CAAA,MAAA,oBAexB,EAAb,cAA+C,EAE7C,4BAA6B,QAAA,AAAA,CAAA,WAAA,MAAA,CAAA,MAAA,8BAK/B,SAAgB,EACd,EACoC,CACpC,OAAO,aAAiB,EAwB1B,IAAa,EAAb,cAAgC,EAG9B,aAAc,QAAA,GAAA,AAAe,CAAC,WAAA,MAAA,CAAA,MAAA,eAKnB,EAAb,cAAmC,CAAY,CAAA,WAAA,MAAA,CAAA,MAAA,gBAC7C,OAAyB,eAAiB,gBAK1C,YACE,EACA,EACA,EACA,CACA,MACE,MAAM,EAAM,oBAAoB,IAChC,QACA,CACE,KAAM,CAAE,GAAG,GAAS,KAAM,QAAO,YAAW,CAC9C,CACD,GASQ,EAAb,cAAoC,CAAY,CAAA,WAAA,MAAA,CAAA,MAAA,iBAC9C,OAAyB,eAAiB,iBAU1C,YACE,EACA,EACA,EACA,CACA,MACE,OAAO,EAAU,MAAM,EAAM,mBAAmB,GAAS,OAAS,KAAK,EAAQ,SAAW,KAC1F,SACA,CACE,KAAM,CAAE,GAAG,GAAS,KAAM,QAAO,YAAW,CAC5C,MAAO,GAAS,MAClB,CACD,GAyBQ,EAAb,cAAsC,CAAY,CAAA,WAAA,MAAA,CAAA,MAAA,mBAChD,OAAyB,eAAiB,mBAK1C,YACE,EACA,EACA,EACA,CACA,MAAM,EAAS,GAAS,MAAQ,QAAA,CAC9B,MAAO,GAAS,MAChB,YAAa,GAAS,YACtB,KAAM,CAAE,GAAG,GAAS,KAAM,WAAU,CACrC,CA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