viborm 1.5.0 → 1.5.1
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-internals-Cy2QEBnH.mjs → adapter-internals-Dagucesf.mjs} +1 -1
- package/dist/{adapter-internals-Cy2QEBnH.mjs.map → adapter-internals-Dagucesf.mjs.map} +1 -1
- package/dist/{adapter-namespace-NnXlXR8c.mjs → adapter-namespace-DuugUuQa.mjs} +2 -2
- package/dist/{adapter-namespace-NnXlXR8c.mjs.map → adapter-namespace-DuugUuQa.mjs.map} +1 -1
- package/dist/{adapter-result-parser-D6lluSMi.mjs → adapter-result-parser-B63ouFIz.mjs} +1 -1
- package/dist/{adapter-result-parser-D6lluSMi.mjs.map → adapter-result-parser-B63ouFIz.mjs.map} +1 -1
- package/dist/adapters.mjs +1 -1
- package/dist/{array-literal-BsbbSLw3.mjs → array-literal-BU1R9byi.mjs} +1 -1
- package/dist/{array-literal-BsbbSLw3.mjs.map → array-literal-BU1R9byi.mjs.map} +1 -1
- package/dist/base-wlv81COV.mjs +2 -0
- package/dist/base-wlv81COV.mjs.map +1 -0
- package/dist/{batch-refs-BYCu1JnQ.mjs → batch-refs-C3MTcVre.mjs} +2 -2
- package/dist/{batch-refs-BYCu1JnQ.mjs.map → batch-refs-C3MTcVre.mjs.map} +1 -1
- package/dist/{bind-parameter-capacity-D6p9HrbB.mjs → bind-parameter-capacity-faPOSaLz.mjs} +2 -2
- package/dist/{bind-parameter-capacity-D6p9HrbB.mjs.map → bind-parameter-capacity-faPOSaLz.mjs.map} +1 -1
- package/dist/{builder-BxCr9ANq.mjs → builder-ClblW6Lj.mjs} +2 -2
- package/dist/{builder-BxCr9ANq.mjs.map → builder-ClblW6Lj.mjs.map} +1 -1
- package/dist/bun-sql.mjs +1 -1
- package/dist/bun-sqlite.mjs +1 -1
- package/dist/cache/cloudflare-kv.mjs +1 -1
- package/dist/cache/memory.mjs +1 -1
- package/dist/cache/memory.mjs.map +1 -1
- package/dist/cache.mjs +1 -1
- package/dist/cache.mjs.map +1 -1
- package/dist/{canonical-json-acY4dQNQ.mjs → canonical-json-JLUMrnoq.mjs} +2 -2
- package/dist/{canonical-json-acY4dQNQ.mjs.map → canonical-json-JLUMrnoq.mjs.map} +1 -1
- package/dist/{chain-C4EUyLzF.mjs → chain-C1VPkUpC.mjs} +2 -2
- package/dist/{chain-C4EUyLzF.mjs.map → chain-C1VPkUpC.mjs.map} +1 -1
- package/dist/cli.mjs +1 -1
- package/dist/client-C1MxqFtt.mjs +49 -0
- package/dist/client-C1MxqFtt.mjs.map +1 -0
- package/dist/client-DHf2ZfRe.mjs +2 -0
- package/dist/{client-DACEO6tS.mjs.map → client-DHf2ZfRe.mjs.map} +1 -1
- package/dist/{client-D-XiaClb.d.mts → client-DyIsSin0.d.mts} +1 -1
- package/dist/client.mjs +1 -1
- package/dist/{clock-CJotKAxc.mjs → clock-CK41KO7t.mjs} +1 -1
- package/dist/{clock-CJotKAxc.mjs.map → clock-CK41KO7t.mjs.map} +1 -1
- package/dist/config.d.mts +1 -1
- package/dist/config.mjs +1 -1
- package/dist/{current-C2fZL9Ln.mjs → current-CKQ4EgeM.mjs} +1 -1
- package/dist/{current-C2fZL9Ln.mjs.map → current-CKQ4EgeM.mjs.map} +1 -1
- package/dist/d1.mjs +1 -1
- package/dist/{datetime-physical-codec-CFoeuitT.mjs → datetime-physical-codec-DfVmz14E.mjs} +2 -2
- package/dist/{datetime-physical-codec-CFoeuitT.mjs.map → datetime-physical-codec-DfVmz14E.mjs.map} +1 -1
- package/dist/driver-DpQbSOUD.mjs +2 -0
- package/dist/{driver-BqD-3_jO.mjs.map → driver-DpQbSOUD.mjs.map} +1 -1
- package/dist/{driver-DseQwbsu.mjs → driver-aqfbJdZC.mjs} +2 -2
- package/dist/{driver-DseQwbsu.mjs.map → driver-aqfbJdZC.mjs.map} +1 -1
- package/dist/driver.mjs +1 -1
- package/dist/error-mapping-Zett_Pnt.mjs +2 -0
- package/dist/error-mapping-Zett_Pnt.mjs.map +1 -0
- package/dist/every-BUf842ai.mjs +2 -0
- package/dist/{every-CqR4_Xsx.mjs.map → every-BUf842ai.mjs.map} +1 -1
- package/dist/execution-context-_oajgBi4.mjs +2 -0
- package/dist/execution-context-_oajgBi4.mjs.map +1 -0
- package/dist/{fs-estate-N_F2YqYa.mjs → fs-estate-BXNX7l62.mjs} +2 -2
- package/dist/{fs-estate-N_F2YqYa.mjs.map → fs-estate-BXNX7l62.mjs.map} +1 -1
- package/dist/{geo-area-codec-4W5b7whM.mjs → geo-area-codec-DQpSEgSD.mjs} +2 -2
- package/dist/{geo-area-codec-4W5b7whM.mjs.map → geo-area-codec-DQpSEgSD.mjs.map} +1 -1
- package/dist/{geo-point-codec-pAWYj5ZZ.mjs → geo-point-codec-DcUTvoEg.mjs} +2 -2
- package/dist/{geo-point-codec-pAWYj5ZZ.mjs.map → geo-point-codec-DcUTvoEg.mjs.map} +1 -1
- package/dist/{hydration-Az2rjp5a.mjs → hydration-BK6vRndL.mjs} +2 -2
- package/dist/{hydration-Az2rjp5a.mjs.map → hydration-BK6vRndL.mjs.map} +1 -1
- package/dist/{identifier-conversion-ufaCNi9E.mjs → identifier-conversion-8ldidfgu.mjs} +2 -2
- package/dist/{identifier-conversion-ufaCNi9E.mjs.map → identifier-conversion-8ldidfgu.mjs.map} +1 -1
- package/dist/{identity-CmRos0Yf.mjs → identity-Bu6jbgym.mjs} +2 -2
- package/dist/{identity-CmRos0Yf.mjs.map → identity-Bu6jbgym.mjs.map} +1 -1
- package/dist/index.mjs +1 -1
- package/dist/index.mjs.map +1 -1
- package/dist/instrumentation.mjs +1 -1
- package/dist/{invariant-D_fIjY_z.mjs → invariant-BnLYqsHO.mjs} +1 -1
- package/dist/{invariant-D_fIjY_z.mjs.map → invariant-BnLYqsHO.mjs.map} +1 -1
- package/dist/{json-number-CGXpPu4D.mjs → json-number-CAfNAqDB.mjs} +1 -1
- package/dist/{json-number-CGXpPu4D.mjs.map → json-number-CAfNAqDB.mjs.map} +1 -1
- package/dist/key-DJXcPZR_.mjs +2 -0
- package/dist/{key-CyLRw0ne.mjs.map → key-DJXcPZR_.mjs.map} +1 -1
- package/dist/{libsql-DnbEwMY5.mjs → libsql-Dmtj0O4E.mjs} +2 -2
- package/dist/{libsql-DnbEwMY5.mjs.map → libsql-Dmtj0O4E.mjs.map} +1 -1
- package/dist/libsql.mjs +1 -1
- package/dist/libsql.mjs.map +1 -1
- package/dist/{memory-CJ7m33Gi.mjs → memory-b-dafk9S.mjs} +2 -2
- package/dist/{memory-CJ7m33Gi.mjs.map → memory-b-dafk9S.mjs.map} +1 -1
- package/dist/migrations/mysql.d.mts +3 -3
- package/dist/migrations/mysql.mjs +1 -1
- package/dist/migrations/postgres.d.mts +3 -3
- package/dist/migrations/postgres.mjs +1 -1
- package/dist/migrations/sqlite.d.mts +3 -3
- package/dist/migrations/sqlite.mjs +1 -1
- package/dist/migrations/storage/durable-object.mjs +1 -1
- package/dist/migrations/storage/fs.mjs +1 -1
- package/dist/migrations/storage/r2.mjs +1 -1
- package/dist/migrations/tenant.d.mts +2 -2
- package/dist/migrations/tenant.mjs +1 -1
- package/dist/migrations-OE5D32qo.mjs +2 -0
- package/dist/migrations-OE5D32qo.mjs.map +1 -0
- package/dist/migrations.d.mts +3 -3
- package/dist/migrations.mjs +1 -1
- package/dist/{mysql-9C0lSVzX.mjs → mysql-DAaUSeBw.mjs} +2 -2
- package/dist/{mysql-9C0lSVzX.mjs.map → mysql-DAaUSeBw.mjs.map} +1 -1
- package/dist/{mysql-adapter-B1U35CJn.mjs → mysql-adapter-BrkDrfin.mjs} +2 -2
- package/dist/{mysql-adapter-B1U35CJn.mjs.map → mysql-adapter-BrkDrfin.mjs.map} +1 -1
- package/dist/mysql2.mjs +1 -1
- package/dist/mysql2.mjs.map +1 -1
- package/dist/{native-types-asNCr26n.mjs → native-types-BbKWN3JV.mjs} +1 -1
- package/dist/{native-types-asNCr26n.mjs.map → native-types-BbKWN3JV.mjs.map} +1 -1
- package/dist/neon-http.mjs +1 -1
- package/dist/{normalized-result-BF7gr4_b.mjs → normalized-result-VunNi4ID.mjs} +2 -2
- package/dist/{normalized-result-BF7gr4_b.mjs.map → normalized-result-VunNi4ID.mjs.map} +1 -1
- package/dist/{object-store-H7fJwgPR.d.mts → object-store-BHyP-LEI.d.mts} +2 -2
- package/dist/{object-store-WjVilDvN.mjs → object-store-I1MyfM72.mjs} +2 -2
- package/dist/{object-store-WjVilDvN.mjs.map → object-store-I1MyfM72.mjs.map} +1 -1
- package/dist/observation-BcT8Cs3d.mjs +2 -0
- package/dist/observation-BcT8Cs3d.mjs.map +1 -0
- package/dist/permissions.mjs +1 -1
- package/dist/pg.mjs +1 -1
- package/dist/pg.mjs.map +1 -1
- package/dist/pglite.mjs +1 -1
- package/dist/{physical-C4D-979R.mjs → physical-CAZ_LauY.mjs} +2 -2
- package/dist/{physical-C4D-979R.mjs.map → physical-CAZ_LauY.mjs.map} +1 -1
- package/dist/{pinned-session-FYOFV_gB.mjs → pinned-session-D8bM5obl.mjs} +2 -2
- package/dist/{pinned-session-FYOFV_gB.mjs.map → pinned-session-D8bM5obl.mjs.map} +1 -1
- package/dist/planetscale.mjs +1 -1
- package/dist/{planner-CUcPdJwD.d.mts → planner-BDLdDieE.d.mts} +11 -2
- package/dist/{postgres-BPeNXAZR.mjs → postgres-HaFcFACt.mjs} +3 -3
- package/dist/{postgres-BPeNXAZR.mjs.map → postgres-HaFcFACt.mjs.map} +1 -1
- package/dist/{postgres-adapter-CJmoxTW7.mjs → postgres-adapter-BhNE_3b-.mjs} +2 -2
- package/dist/{postgres-adapter-CJmoxTW7.mjs.map → postgres-adapter-BhNE_3b-.mjs.map} +1 -1
- package/dist/{postgres-adapter-B7hzWhky.mjs → postgres-adapter-CnZjhvG1.mjs} +2 -2
- package/dist/{postgres-adapter-B7hzWhky.mjs.map → postgres-adapter-CnZjhvG1.mjs.map} +1 -1
- package/dist/{postgres-result-BCUQf8b_.mjs → postgres-result-D4_yZqO8.mjs} +2 -2
- package/dist/{postgres-result-BCUQf8b_.mjs.map → postgres-result-D4_yZqO8.mjs.map} +1 -1
- package/dist/postgres.mjs +1 -1
- package/dist/postgres.mjs.map +1 -1
- package/dist/{provider-limits-D0ECF7_Q.mjs → provider-limits-CpitUqW6.mjs} +2 -2
- package/dist/{provider-limits-D0ECF7_Q.mjs.map → provider-limits-CpitUqW6.mjs.map} +1 -1
- package/dist/{relation-bound-BrZLsSke.mjs → relation-bound-5ChGF3n5.mjs} +1 -1
- package/dist/{relation-bound-BrZLsSke.mjs.map → relation-bound-5ChGF3n5.mjs.map} +1 -1
- package/dist/{result-parsing-CQf_eCl8.mjs → result-parsing-BX3_3Q15.mjs} +1 -1
- package/dist/{result-parsing-CQf_eCl8.mjs.map → result-parsing-BX3_3Q15.mjs.map} +1 -1
- package/dist/result-shape-BuGfArOr.mjs +2 -0
- package/dist/{result-shape-ic2j3Tze.mjs.map → result-shape-BuGfArOr.mjs.map} +1 -1
- package/dist/{rows-YyvK9MDz.mjs → rows-BlONp14o.mjs} +2 -2
- package/dist/{rows-YyvK9MDz.mjs.map → rows-BlONp14o.mjs.map} +1 -1
- package/dist/{scalar-Dyns7kc7.mjs → scalar-B3WLZzJj.mjs} +2 -2
- package/dist/{scalar-Dyns7kc7.mjs.map → scalar-B3WLZzJj.mjs.map} +1 -1
- package/dist/schema/json.mjs +1 -1
- package/dist/{schema-CUm_yh6L.mjs → schema-B_Bc7TQ2.mjs} +2 -2
- package/dist/{schema-CUm_yh6L.mjs.map → schema-B_Bc7TQ2.mjs.map} +1 -1
- package/dist/{schema-introspection-LpRNeSG2.mjs → schema-introspection-BqN7d_sA.mjs} +2 -2
- package/dist/{schema-introspection-LpRNeSG2.mjs.map → schema-introspection-BqN7d_sA.mjs.map} +1 -1
- package/dist/schema.mjs +1 -1
- package/dist/{select-assembly-BjT_fDbu.mjs → select-assembly-BP8c4O-0.mjs} +2 -2
- package/dist/{select-assembly-BjT_fDbu.mjs.map → select-assembly-BP8c4O-0.mjs.map} +1 -1
- package/dist/{settle-C4w1GfTU.mjs → settle-B9Vg1FnP.mjs} +2 -2
- package/dist/{settle-C4w1GfTU.mjs.map → settle-B9Vg1FnP.mjs.map} +1 -1
- package/dist/{sha256-_Nu4s32f.mjs → sha256-DDEbgnTU.mjs} +1 -1
- package/dist/{sha256-_Nu4s32f.mjs.map → sha256-DDEbgnTU.mjs.map} +1 -1
- package/dist/{sql-BvHwL73I.mjs → sql-BR8ZzKn8.mjs} +1 -1
- package/dist/{sql-BvHwL73I.mjs.map → sql-BR8ZzKn8.mjs.map} +1 -1
- package/dist/{sql-statement-tokens-4J5l5Lyt.mjs → sql-statement-tokens-BBcoGmJb.mjs} +1 -1
- package/dist/{sql-statement-tokens-4J5l5Lyt.mjs.map → sql-statement-tokens-BBcoGmJb.mjs.map} +1 -1
- package/dist/sql.mjs +1 -1
- package/dist/{sqlite-adapter-CLWY4B8w.mjs → sqlite-adapter-CF-m7LIP.mjs} +2 -2
- package/dist/{sqlite-adapter-CLWY4B8w.mjs.map → sqlite-adapter-CF-m7LIP.mjs.map} +1 -1
- package/dist/{sqlite-utils-C5_KQPZn.mjs → sqlite-utils-CFInz2yY.mjs} +2 -2
- package/dist/{sqlite-utils-C5_KQPZn.mjs.map → sqlite-utils-CFInz2yY.mjs.map} +1 -1
- package/dist/sqlite3.mjs +1 -1
- package/dist/{standard-sql-DmKF8msN.mjs → standard-sql-wRMNi-Yg.mjs} +2 -2
- package/dist/{standard-sql-DmKF8msN.mjs.map → standard-sql-wRMNi-Yg.mjs.map} +1 -1
- package/dist/{to-many-DxQuOBuq.mjs → to-many-CUBK3CTd.mjs} +2 -2
- package/dist/{to-many-DxQuOBuq.mjs.map → to-many-CUBK3CTd.mjs.map} +1 -1
- package/dist/{transaction-4dfqals6.mjs → transaction-D5LHYn-r.mjs} +2 -2
- package/dist/{transaction-4dfqals6.mjs.map → transaction-D5LHYn-r.mjs.map} +1 -1
- package/dist/{transaction-operation-CU1zlxiG.mjs → transaction-operation-C3Jbblbl.mjs} +2 -2
- package/dist/{transaction-operation-CU1zlxiG.mjs.map → transaction-operation-C3Jbblbl.mjs.map} +1 -1
- package/dist/{types-C5Oxz9yp.mjs → types-BNR3u6hH.mjs} +1 -1
- package/dist/{types-C5Oxz9yp.mjs.map → types-BNR3u6hH.mjs.map} +1 -1
- package/dist/{utils-CQ2nQwwO.mjs → utils-Be91XL14.mjs} +2 -2
- package/dist/{utils-CQ2nQwwO.mjs.map → utils-Be91XL14.mjs.map} +1 -1
- package/dist/{v-BcroBusN.mjs → v-lthABIXD.mjs} +2 -2
- package/dist/{v-BcroBusN.mjs.map → v-lthABIXD.mjs.map} +1 -1
- package/dist/{validation-CjWRiLWU.mjs → validation-BfJaNYMf.mjs} +2 -2
- package/dist/{validation-CjWRiLWU.mjs.map → validation-BfJaNYMf.mjs.map} +1 -1
- package/dist/{validation-gwZYm3Yn.mjs → validation-DN1N2OdK.mjs} +2 -2
- package/dist/{validation-gwZYm3Yn.mjs.map → validation-DN1N2OdK.mjs.map} +1 -1
- package/dist/validation.mjs +1 -1
- package/dist/{validator-yrGnrsAo.mjs → validator-BJhI364k.mjs} +2 -2
- package/dist/{validator-yrGnrsAo.mjs.map → validator-BJhI364k.mjs.map} +1 -1
- package/dist/version-DAFcmokN.mjs +2 -0
- package/dist/{version-Dt62tqkV.mjs.map → version-DAFcmokN.mjs.map} +1 -1
- package/package.json +11 -11
- package/dist/base-D3m1S7Uc.mjs +0 -2
- package/dist/base-D3m1S7Uc.mjs.map +0 -1
- package/dist/cache-CIPRF-pz.mjs +0 -2
- package/dist/cache-CIPRF-pz.mjs.map +0 -1
- package/dist/client-CnXO0M-E.mjs +0 -49
- package/dist/client-CnXO0M-E.mjs.map +0 -1
- package/dist/client-DACEO6tS.mjs +0 -2
- package/dist/driver-BqD-3_jO.mjs +0 -2
- package/dist/error-mapping-6op318w6.mjs +0 -2
- package/dist/error-mapping-6op318w6.mjs.map +0 -1
- package/dist/every-CqR4_Xsx.mjs +0 -2
- package/dist/execution-context-asSCmyas.mjs +0 -2
- package/dist/execution-context-asSCmyas.mjs.map +0 -1
- package/dist/key-CyLRw0ne.mjs +0 -2
- package/dist/migrations-Bn1SatyB.mjs +0 -2
- package/dist/migrations-Bn1SatyB.mjs.map +0 -1
- package/dist/observation-Co72iCd1.mjs +0 -2
- package/dist/observation-Co72iCd1.mjs.map +0 -1
- package/dist/result-shape-ic2j3Tze.mjs +0 -2
- package/dist/version-Dt62tqkV.mjs +0 -2
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"native-types-asNCr26n.mjs","names":[],"sources":["../src/schema/scalars/native-types.ts"],"sourcesContent":["// Native Database Type Overrides\n// Provides typed constants for database-specific column types\n\n// =============================================================================\n// NATIVE TYPE INTERFACE\n// =============================================================================\n\nexport interface NativeType {\n readonly db: \"pg\" | \"mysql\" | \"sqlite\";\n readonly type: string;\n}\n\n/** The three dialects a native type can name. */\nexport type NativeDialect = NativeType[\"db\"];\n\n/**\n * A native type of ONE dialect — what every `PG` / `MYSQL` / `SQLITE` constant\n * is, parameterized ones included, so `PG.STRING.VARCHAR(80)` can fill a `pg`\n * entry of a {@link NativeTypeMap} and cannot fill a `mysql` one.\n */\nexport interface DialectNativeType<Dialect extends NativeDialect>\n extends NativeType {\n readonly db: Dialect;\n}\n\n/**\n * One scalar's native type on each dialect it names:\n * `s.string({ pg: PG.STRING.CITEXT, mysql: MYSQL.STRING.LONGTEXT })`.\n *\n * A dialect the map leaves out keeps that scalar's automatic column, exactly\n * as a tagged {@link NativeType} leaves every OTHER dialect's column alone.\n */\nexport interface NativeTypeMap {\n readonly pg?: DialectNativeType<\"pg\">;\n readonly mysql?: DialectNativeType<\"mysql\">;\n readonly sqlite?: DialectNativeType<\"sqlite\">;\n}\n\n/**\n * What a scalar factory's native-type argument declares: the tagged shorthand\n * (one dialect) or a {@link NativeTypeMap} (several). Scalars store the\n * declaration in the form it was written, so a schema document restates it\n * faithfully; every PHYSICAL reader asks {@link nativeTypeFor} instead of\n * inspecting the form.\n */\nexport type NativeTypeDeclaration = NativeType | NativeTypeMap;\n\n/** Every dialect, in the order a per-dialect question visits them. */\nexport const NATIVE_DIALECTS: readonly NativeDialect[] = [\n \"pg\",\n \"mysql\",\n \"sqlite\",\n];\n\n/** Whether a declaration is the tagged shorthand rather than a map. */\nexport const isTaggedNativeType = (\n declaration: NativeTypeDeclaration\n): declaration is NativeType => \"db\" in declaration;\n\n/**\n * The native type a declaration selects on one dialect, or `undefined` for the\n * dialect's automatic column.\n *\n * The ONE bound-dialect resolver. A migration driver, an adapter and the\n * identifier storage owner each know which dialect they speak and ask this;\n * none of them reads the declaration's form. A tagged shorthand for another\n * dialect is that dialect's automatic column, as it always was.\n */\nexport function nativeTypeFor(\n declaration: NativeTypeDeclaration | undefined,\n dialect: NativeDialect\n): NativeType | undefined {\n if (declaration === undefined) return undefined;\n if (isTaggedNativeType(declaration)) {\n return declaration.db === dialect ? declaration : undefined;\n }\n return declaration[dialect];\n}\n\n/**\n * A scalar factory's native-type argument: the tagged shorthand of dialect\n * `Db`, or the map `Given`, which the factory bounds by\n * {@link ExactNativeTypeMap}.\n *\n * The tagged shorthand keeps its historical shape: a `NativeType`, a union of\n * them, a generic `T extends NativeType`, a custom `type`, or one with unrelated\n * extra keys held in a variable all still compile, a fresh literal with an extra\n * key is still an excess-property error, and a value missing `db` or `type` is\n * still refused — except that a dialect key BESIDE its `db` is refused, since\n * that object would be two declarations at once.\n *\n * `Db` is inferred from a tagged value's `db` only so that TypeScript counts the\n * value as matched by this first member and keeps it out of `Given`: an\n * argument reaches `Given` only when it is not tagged, and `Given` is naked so\n * a union-typed argument (`NativeType | NativeTypeMap`) reaches it whole.\n */\nexport type NativeTypeArgument<Db extends NativeDialect, Given> =\n | (DialectNativeType<Db> & Partial<Record<NativeDialect, never>>)\n | Given;\n\n/**\n * The bound of a factory's `Given`: every key a dialect, each entry a native\n * type of its own key's dialect, and at least one dialect key. `{ type: \"text\" }`,\n * `{ postgres: … }`, `{}` and a `Date` are refused; an unknown key is refused\n * beside a real one, fresh and held in a variable. An argument that fails the\n * bound is refused against the bound itself, which is TypeScript's fallback.\n *\n * The exactness is a homomorphic mapped type, so it judges each member of a\n * union-typed map on its own. Measured traps (TS 7.0.2) that shaped it: a\n * generic CONSTRAINED to the weak `NativeTypeMap` falls back to that weak type\n * and admitted `{ foo: 1 }` and a `Date`; a parameter spelled `Given & NoInfer<…>`\n * makes TypeScript infer one member of a union argument; and a bound that is a\n * conditional type distributing over `Given` is a circular constraint (TS2313).\n * The at-least-one test is therefore not distributive: a union of maps with no\n * dialect key in COMMON is refused — annotate such a variable `NativeTypeMap`.\n */\nexport type ExactNativeTypeMap<Given> = {\n [Key in keyof Given]: Key extends NativeDialect\n ? DialectNativeType<Key>\n : never;\n} & ([keyof Given & NativeDialect] extends [never] ? never : unknown);\n\n// =============================================================================\n// CONSTANT BUILDERS\n// =============================================================================\n\n/** A fixed native type: its `db` and `type` keep their literal types. */\nconst fixed =\n <const Db extends NativeDialect>(db: Db) =>\n <const Type extends string>(type: Type) =>\n ({ db, type }) as const;\n\nconst pg = fixed(\"pg\");\nconst mysql = fixed(\"mysql\");\nconst sqlite = fixed(\"sqlite\");\n\n/** A type that takes one required size: `varchar(80)`. */\nconst sized =\n <Db extends NativeDialect>(db: Db, name: string) =>\n (n: number): DialectNativeType<Db> => ({ db, type: `${name}(${n})` });\n\n/** A type whose precision is optional: `timestamp` or `timestamp(3)`. */\nconst opt =\n <Db extends NativeDialect>(db: Db, name: string) =>\n (precision?: number): DialectNativeType<Db> => ({\n db,\n type: precision !== undefined ? `${name}(${precision})` : name,\n });\n\n// =============================================================================\n// POSTGRESQL NATIVE TYPES\n// https://www.prisma.io/docs/orm/reference/prisma-schema-reference#postgresql\n// =============================================================================\n\nexport const PG = {\n // String types\n STRING: {\n TEXT: pg(\"text\"),\n VARCHAR: sized(\"pg\", \"varchar\"),\n CHAR: sized(\"pg\", \"char\"),\n CITEXT: pg(\"citext\"),\n UUID: pg(\"uuid\"),\n BIT: sized(\"pg\", \"bit\"),\n // By hand: a zero size is the bare type here, not `varbit(0)`.\n VARBIT: (n?: number): DialectNativeType<\"pg\"> => ({\n db: \"pg\",\n type: n ? `varbit(${n})` : \"varbit\",\n }),\n XML: pg(\"xml\"),\n INET: pg(\"inet\"),\n CIDR: pg(\"cidr\"),\n MACADDR: pg(\"macaddr\"),\n MACADDR8: pg(\"macaddr8\"),\n TSVECTOR: pg(\"tsvector\"),\n TSQUERY: pg(\"tsquery\"),\n },\n\n // Integer types\n INT: {\n SMALLINT: pg(\"smallint\"),\n INTEGER: pg(\"integer\"),\n OID: pg(\"oid\"),\n },\n\n // BigInt types\n BIGINT: {\n BIGINT: pg(\"bigint\"),\n },\n\n // Float types\n FLOAT: {\n REAL: pg(\"real\"),\n DOUBLE_PRECISION: pg(\"double precision\"),\n },\n\n // Boolean types\n BOOLEAN: {\n BOOLEAN: pg(\"boolean\"),\n },\n\n // DateTime types\n DATETIME: {\n TIMESTAMP: opt(\"pg\", \"timestamp\"),\n TIMESTAMPTZ: opt(\"pg\", \"timestamptz\"),\n DATE: pg(\"date\"),\n TIME: opt(\"pg\", \"time\"),\n TIMETZ: opt(\"pg\", \"timetz\"),\n },\n\n // JSON types\n JSON: {\n JSON: pg(\"json\"),\n JSONB: pg(\"jsonb\"),\n },\n\n // Binary types\n BLOB: {\n BYTEA: pg(\"bytea\"),\n },\n} as const;\n\n// =============================================================================\n// MYSQL NATIVE TYPES\n// https://www.prisma.io/docs/orm/reference/prisma-schema-reference#mysql\n// =============================================================================\n\nexport const MYSQL = {\n // String types\n STRING: {\n VARCHAR: sized(\"mysql\", \"VARCHAR\"),\n CHAR: sized(\"mysql\", \"CHAR\"),\n TEXT: mysql(\"TEXT\"),\n TINYTEXT: mysql(\"TINYTEXT\"),\n MEDIUMTEXT: mysql(\"MEDIUMTEXT\"),\n LONGTEXT: mysql(\"LONGTEXT\"),\n BIT: sized(\"mysql\", \"BIT\"),\n },\n\n // Integer types\n INT: {\n TINYINT: mysql(\"TINYINT\"),\n TINYINT_UNSIGNED: mysql(\"TINYINT UNSIGNED\"),\n SMALLINT: mysql(\"SMALLINT\"),\n SMALLINT_UNSIGNED: mysql(\"SMALLINT UNSIGNED\"),\n MEDIUMINT: mysql(\"MEDIUMINT\"),\n MEDIUMINT_UNSIGNED: mysql(\"MEDIUMINT UNSIGNED\"),\n INT: mysql(\"INT\"),\n INT_UNSIGNED: mysql(\"INT UNSIGNED\"),\n YEAR: mysql(\"YEAR\"),\n },\n\n // BigInt types\n BIGINT: {\n BIGINT: mysql(\"BIGINT\"),\n BIGINT_UNSIGNED: mysql(\"BIGINT UNSIGNED\"),\n },\n\n // Float types\n FLOAT: {\n FLOAT: mysql(\"FLOAT\"),\n DOUBLE: mysql(\"DOUBLE\"),\n },\n\n // Boolean types (MySQL uses TINYINT(1))\n BOOLEAN: {\n TINYINT: mysql(\"TINYINT(1)\"),\n },\n\n // DateTime types\n DATETIME: {\n DATETIME: opt(\"mysql\", \"DATETIME\"),\n TIMESTAMP: opt(\"mysql\", \"TIMESTAMP\"),\n DATE: mysql(\"DATE\"),\n TIME: opt(\"mysql\", \"TIME\"),\n },\n\n // JSON types\n JSON: {\n JSON: mysql(\"JSON\"),\n },\n\n // Binary types\n BLOB: {\n BLOB: mysql(\"BLOB\"),\n TINYBLOB: mysql(\"TINYBLOB\"),\n MEDIUMBLOB: mysql(\"MEDIUMBLOB\"),\n LONGBLOB: mysql(\"LONGBLOB\"),\n BINARY: sized(\"mysql\", \"BINARY\"),\n VARBINARY: sized(\"mysql\", \"VARBINARY\"),\n },\n} as const;\n\n// =============================================================================\n// SQLITE NATIVE TYPES\n// https://www.prisma.io/docs/orm/reference/prisma-schema-reference#sqlite\n// SQLite has limited type affinity, but we expose common mappings\n// =============================================================================\n\nexport const SQLITE = {\n // String types (all map to TEXT)\n STRING: {\n TEXT: sqlite(\"TEXT\"),\n },\n\n // Integer types\n INT: {\n INTEGER: sqlite(\"INTEGER\"),\n },\n\n // BigInt types (same as INTEGER in SQLite)\n BIGINT: {\n INTEGER: sqlite(\"INTEGER\"),\n },\n\n // Float types\n FLOAT: {\n REAL: sqlite(\"REAL\"),\n },\n\n // Boolean types (stored as INTEGER 0/1)\n BOOLEAN: {\n INTEGER: sqlite(\"INTEGER\"),\n },\n\n // DateTime types (stored as TEXT, REAL, or INTEGER)\n DATETIME: {\n TEXT: sqlite(\"TEXT\"),\n REAL: sqlite(\"REAL\"),\n INTEGER: sqlite(\"INTEGER\"),\n },\n\n // JSON types (stored as TEXT)\n JSON: {\n TEXT: sqlite(\"TEXT\"),\n },\n\n // Binary types\n BLOB: {\n BLOB: sqlite(\"BLOB\"),\n },\n} as const;\n"],"mappings":"yCAgDA,MAAa,EAA4C,CACvD,KACA,QACA,SACD,CAGY,mBACX,GAC8B,OAAQ,EAWxC,SAAgB,cACd,EACA,EACwB,CACpB,OAAgB,IAAA,GAIpB,OAHI,mBAAmB,EAAY,CAC1B,EAAY,KAAO,EAAU,EAAc,IAAA,GAE7C,EAAY,GAmDrB,MAAM,MAC6B,GACL,IACzB,CAAE,KAAI,OAAM,EAEX,EAAK,MAAM,KAAK,CAChB,EAAQ,MAAM,QAAQ,CACtB,EAAS,MAAM,SAAS,CAGxB,OACuB,EAAQ,IAClC,IAAsC,CAAE,KAAI,KAAM,GAAG,EAAK,GAAG,EAAE,GAAI,EAGhE,KACuB,EAAQ,IAClC,IAA+C,CAC9C,KACA,KAAM,IAAc,IAAA,GAAsC,EAA1B,GAAG,EAAK,GAAG,EAAU,GACtD,EAOU,EAAK,CAEhB,OAAQ,CACN,KAAM,EAAG,OAAO,CAChB,QAAS,MAAM,KAAM,UAAU,CAC/B,KAAM,MAAM,KAAM,OAAO,CACzB,OAAQ,EAAG,SAAS,CACpB,KAAM,EAAG,OAAO,CAChB,IAAK,MAAM,KAAM,MAAM,CAEvB,OAAS,IAAyC,CAChD,GAAI,KACJ,KAAM,EAAI,UAAU,EAAE,GAAK,SA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M,kBAAkB,CAC1C,CAGD,MAAO,CACL,MAAO,EAAM,QAAQ,CACrB,OAAQ,EAAM,SAAS,CACxB,CAGD,QAAS,CACP,QAAS,EAAM,aAAa,CAC7B,CAGD,SAAU,CACR,SAAU,IAAI,QAAS,WAAW,CAClC,UAAW,IAAI,QAAS,YAAY,CACpC,KAAM,EAAM,OAAO,CACnB,KAAM,IAAI,QAAS,OAAO,CAC3B,CAGD,KAAM,CACJ,KAAM,EAAM,OAAO,CACpB,CAGD,KAAM,CACJ,KAAM,EAAM,OAAO,CACnB,SAAU,EAAM,WAAW,CAC3B,WAAY,EAAM,aAAa,CAC/B,SAAU,EAAM,WAAW,CAC3B,OAAQ,MAAM,QAAS,SAAS,CAChC,UAAW,MAAM,QAAS,YAAY,CACvC,CACF,CAQY,EAAS,CAEpB,OAAQ,CACN,KAAM,EAAO,OAAO,CACrB,CAGD,IAAK,CACH,QAAS,EAAO,UAAU,CAC3B,CAGD,OAAQ,CACN,QAAS,EAAO,UAAU,CAC3B,CAGD,MAAO,CACL,KAAM,EAAO,OAAO,CACrB,CAGD,QAAS,CACP,QAAS,EAAO,UAAU,CAC3B,CAGD,SAAU,CACR,KAAM,EAAO,OAAO,CACpB,KAAM,EAAO,OAAO,CACpB,QAAS,EAAO,UAAU,CAC3B,CAGD,KAAM,CACJ,KAAM,EAAO,OAAO,CACrB,CAGD,KAAM,CACJ,KAAM,EAAO,OAAO,CACrB,CACF"}
|
|
1
|
+
{"version":3,"file":"native-types-BbKWN3JV.mjs","names":[],"sources":["../src/schema/scalars/native-types.ts"],"sourcesContent":["// Native Database Type Overrides\n// Provides typed constants for database-specific column types\n\n// =============================================================================\n// NATIVE TYPE INTERFACE\n// =============================================================================\n\nexport interface NativeType {\n readonly db: \"pg\" | \"mysql\" | \"sqlite\";\n readonly type: string;\n}\n\n/** The three dialects a native type can name. */\nexport type NativeDialect = NativeType[\"db\"];\n\n/**\n * A native type of ONE dialect — what every `PG` / `MYSQL` / `SQLITE` constant\n * is, parameterized ones included, so `PG.STRING.VARCHAR(80)` can fill a `pg`\n * entry of a {@link NativeTypeMap} and cannot fill a `mysql` one.\n */\nexport interface DialectNativeType<Dialect extends NativeDialect>\n extends NativeType {\n readonly db: Dialect;\n}\n\n/**\n * One scalar's native type on each dialect it names:\n * `s.string({ pg: PG.STRING.CITEXT, mysql: MYSQL.STRING.LONGTEXT })`.\n *\n * A dialect the map leaves out keeps that scalar's automatic column, exactly\n * as a tagged {@link NativeType} leaves every OTHER dialect's column alone.\n */\nexport interface NativeTypeMap {\n readonly pg?: DialectNativeType<\"pg\">;\n readonly mysql?: DialectNativeType<\"mysql\">;\n readonly sqlite?: DialectNativeType<\"sqlite\">;\n}\n\n/**\n * What a scalar factory's native-type argument declares: the tagged shorthand\n * (one dialect) or a {@link NativeTypeMap} (several). Scalars store the\n * declaration in the form it was written, so a schema document restates it\n * faithfully; every PHYSICAL reader asks {@link nativeTypeFor} instead of\n * inspecting the form.\n */\nexport type NativeTypeDeclaration = NativeType | NativeTypeMap;\n\n/** Every dialect, in the order a per-dialect question visits them. */\nexport const NATIVE_DIALECTS: readonly NativeDialect[] = [\n \"pg\",\n \"mysql\",\n \"sqlite\",\n];\n\n/** Whether a declaration is the tagged shorthand rather than a map. */\nexport const isTaggedNativeType = (\n declaration: NativeTypeDeclaration\n): declaration is NativeType => \"db\" in declaration;\n\n/**\n * The native type a declaration selects on one dialect, or `undefined` for the\n * dialect's automatic column.\n *\n * The ONE bound-dialect resolver. A migration driver, an adapter and the\n * identifier storage owner each know which dialect they speak and ask this;\n * none of them reads the declaration's form. A tagged shorthand for another\n * dialect is that dialect's automatic column, as it always was.\n */\nexport function nativeTypeFor(\n declaration: NativeTypeDeclaration | undefined,\n dialect: NativeDialect\n): NativeType | undefined {\n if (declaration === undefined) return undefined;\n if (isTaggedNativeType(declaration)) {\n return declaration.db === dialect ? declaration : undefined;\n }\n return declaration[dialect];\n}\n\n/**\n * A scalar factory's native-type argument: the tagged shorthand of dialect\n * `Db`, or the map `Given`, which the factory bounds by\n * {@link ExactNativeTypeMap}.\n *\n * The tagged shorthand keeps its historical shape: a `NativeType`, a union of\n * them, a generic `T extends NativeType`, a custom `type`, or one with unrelated\n * extra keys held in a variable all still compile, a fresh literal with an extra\n * key is still an excess-property error, and a value missing `db` or `type` is\n * still refused — except that a dialect key BESIDE its `db` is refused, since\n * that object would be two declarations at once.\n *\n * `Db` is inferred from a tagged value's `db` only so that TypeScript counts the\n * value as matched by this first member and keeps it out of `Given`: an\n * argument reaches `Given` only when it is not tagged, and `Given` is naked so\n * a union-typed argument (`NativeType | NativeTypeMap`) reaches it whole.\n */\nexport type NativeTypeArgument<Db extends NativeDialect, Given> =\n | (DialectNativeType<Db> & Partial<Record<NativeDialect, never>>)\n | Given;\n\n/**\n * The bound of a factory's `Given`: every key a dialect, each entry a native\n * type of its own key's dialect, and at least one dialect key. `{ type: \"text\" }`,\n * `{ postgres: … }`, `{}` and a `Date` are refused; an unknown key is refused\n * beside a real one, fresh and held in a variable. An argument that fails the\n * bound is refused against the bound itself, which is TypeScript's fallback.\n *\n * The exactness is a homomorphic mapped type, so it judges each member of a\n * union-typed map on its own. Measured traps (TS 7.0.2) that shaped it: a\n * generic CONSTRAINED to the weak `NativeTypeMap` falls back to that weak type\n * and admitted `{ foo: 1 }` and a `Date`; a parameter spelled `Given & NoInfer<…>`\n * makes TypeScript infer one member of a union argument; and a bound that is a\n * conditional type distributing over `Given` is a circular constraint (TS2313).\n * The at-least-one test is therefore not distributive: a union of maps with no\n * dialect key in COMMON is refused — annotate such a variable `NativeTypeMap`.\n */\nexport type ExactNativeTypeMap<Given> = {\n [Key in keyof Given]: Key extends NativeDialect\n ? DialectNativeType<Key>\n : never;\n} & ([keyof Given & NativeDialect] extends [never] ? never : unknown);\n\n// =============================================================================\n// CONSTANT BUILDERS\n// =============================================================================\n\n/** A fixed native type: its `db` and `type` keep their literal types. */\nconst fixed =\n <const Db extends NativeDialect>(db: Db) =>\n <const Type extends string>(type: Type) =>\n ({ db, type }) as const;\n\nconst pg = fixed(\"pg\");\nconst mysql = fixed(\"mysql\");\nconst sqlite = fixed(\"sqlite\");\n\n/** A type that takes one required size: `varchar(80)`. */\nconst sized =\n <Db extends NativeDialect>(db: Db, name: string) =>\n (n: number): DialectNativeType<Db> => ({ db, type: `${name}(${n})` });\n\n/** A type whose precision is optional: `timestamp` or `timestamp(3)`. */\nconst opt =\n <Db extends NativeDialect>(db: Db, name: string) =>\n (precision?: number): DialectNativeType<Db> => ({\n db,\n type: precision !== undefined ? `${name}(${precision})` : name,\n });\n\n// =============================================================================\n// POSTGRESQL NATIVE TYPES\n// https://www.prisma.io/docs/orm/reference/prisma-schema-reference#postgresql\n// =============================================================================\n\nexport const PG = {\n // String types\n STRING: {\n TEXT: pg(\"text\"),\n VARCHAR: sized(\"pg\", \"varchar\"),\n CHAR: sized(\"pg\", \"char\"),\n CITEXT: pg(\"citext\"),\n UUID: pg(\"uuid\"),\n BIT: sized(\"pg\", \"bit\"),\n // By hand: a zero size is the bare type here, not `varbit(0)`.\n VARBIT: (n?: number): DialectNativeType<\"pg\"> => ({\n db: \"pg\",\n type: n ? `varbit(${n})` : \"varbit\",\n }),\n XML: pg(\"xml\"),\n INET: pg(\"inet\"),\n CIDR: pg(\"cidr\"),\n MACADDR: pg(\"macaddr\"),\n MACADDR8: pg(\"macaddr8\"),\n TSVECTOR: pg(\"tsvector\"),\n TSQUERY: pg(\"tsquery\"),\n },\n\n // Integer types\n INT: {\n SMALLINT: pg(\"smallint\"),\n INTEGER: pg(\"integer\"),\n OID: pg(\"oid\"),\n },\n\n // BigInt types\n BIGINT: {\n BIGINT: pg(\"bigint\"),\n },\n\n // Float types\n FLOAT: {\n REAL: pg(\"real\"),\n DOUBLE_PRECISION: pg(\"double precision\"),\n },\n\n // Boolean types\n BOOLEAN: {\n BOOLEAN: pg(\"boolean\"),\n },\n\n // DateTime types\n DATETIME: {\n TIMESTAMP: opt(\"pg\", \"timestamp\"),\n TIMESTAMPTZ: opt(\"pg\", \"timestamptz\"),\n DATE: pg(\"date\"),\n TIME: opt(\"pg\", \"time\"),\n TIMETZ: opt(\"pg\", \"timetz\"),\n },\n\n // JSON types\n JSON: {\n JSON: pg(\"json\"),\n JSONB: pg(\"jsonb\"),\n },\n\n // Binary types\n BLOB: {\n BYTEA: pg(\"bytea\"),\n },\n} as const;\n\n// =============================================================================\n// MYSQL NATIVE TYPES\n// https://www.prisma.io/docs/orm/reference/prisma-schema-reference#mysql\n// =============================================================================\n\nexport const MYSQL = {\n // String types\n STRING: {\n VARCHAR: sized(\"mysql\", \"VARCHAR\"),\n CHAR: sized(\"mysql\", \"CHAR\"),\n TEXT: mysql(\"TEXT\"),\n TINYTEXT: mysql(\"TINYTEXT\"),\n MEDIUMTEXT: mysql(\"MEDIUMTEXT\"),\n LONGTEXT: mysql(\"LONGTEXT\"),\n BIT: sized(\"mysql\", \"BIT\"),\n },\n\n // Integer types\n INT: {\n TINYINT: mysql(\"TINYINT\"),\n TINYINT_UNSIGNED: mysql(\"TINYINT UNSIGNED\"),\n SMALLINT: mysql(\"SMALLINT\"),\n SMALLINT_UNSIGNED: mysql(\"SMALLINT UNSIGNED\"),\n MEDIUMINT: mysql(\"MEDIUMINT\"),\n MEDIUMINT_UNSIGNED: mysql(\"MEDIUMINT UNSIGNED\"),\n INT: mysql(\"INT\"),\n INT_UNSIGNED: mysql(\"INT UNSIGNED\"),\n YEAR: mysql(\"YEAR\"),\n },\n\n // BigInt types\n BIGINT: {\n BIGINT: mysql(\"BIGINT\"),\n BIGINT_UNSIGNED: mysql(\"BIGINT UNSIGNED\"),\n },\n\n // Float types\n FLOAT: {\n FLOAT: mysql(\"FLOAT\"),\n DOUBLE: mysql(\"DOUBLE\"),\n },\n\n // Boolean types (MySQL uses TINYINT(1))\n BOOLEAN: {\n TINYINT: mysql(\"TINYINT(1)\"),\n },\n\n // DateTime types\n DATETIME: {\n DATETIME: opt(\"mysql\", \"DATETIME\"),\n TIMESTAMP: opt(\"mysql\", \"TIMESTAMP\"),\n DATE: mysql(\"DATE\"),\n TIME: opt(\"mysql\", \"TIME\"),\n },\n\n // JSON types\n JSON: {\n JSON: mysql(\"JSON\"),\n },\n\n // Binary types\n BLOB: {\n BLOB: mysql(\"BLOB\"),\n TINYBLOB: mysql(\"TINYBLOB\"),\n MEDIUMBLOB: mysql(\"MEDIUMBLOB\"),\n LONGBLOB: mysql(\"LONGBLOB\"),\n BINARY: sized(\"mysql\", \"BINARY\"),\n VARBINARY: sized(\"mysql\", \"VARBINARY\"),\n },\n} as const;\n\n// =============================================================================\n// SQLITE NATIVE TYPES\n// https://www.prisma.io/docs/orm/reference/prisma-schema-reference#sqlite\n// SQLite has limited type affinity, but we expose common mappings\n// =============================================================================\n\nexport const SQLITE = {\n // String types (all map to TEXT)\n STRING: {\n TEXT: sqlite(\"TEXT\"),\n },\n\n // Integer types\n INT: {\n INTEGER: sqlite(\"INTEGER\"),\n },\n\n // BigInt types (same as INTEGER in SQLite)\n BIGINT: {\n INTEGER: sqlite(\"INTEGER\"),\n },\n\n // Float types\n FLOAT: {\n REAL: sqlite(\"REAL\"),\n },\n\n // Boolean types (stored as INTEGER 0/1)\n BOOLEAN: {\n INTEGER: sqlite(\"INTEGER\"),\n },\n\n // DateTime types (stored as TEXT, REAL, or INTEGER)\n DATETIME: {\n TEXT: sqlite(\"TEXT\"),\n REAL: sqlite(\"REAL\"),\n INTEGER: sqlite(\"INTEGER\"),\n },\n\n // JSON types (stored as TEXT)\n JSON: {\n TEXT: sqlite(\"TEXT\"),\n },\n\n // Binary types\n BLOB: {\n BLOB: sqlite(\"BLOB\"),\n },\n} as const;\n"],"mappings":"yCAgDA,MAAa,EAA4C,CACvD,KACA,QACA,SACD,CAGY,mBACX,GAC8B,OAAQ,EAWxC,SAAgB,cACd,EACA,EACwB,CACpB,OAAgB,IAAA,GAIpB,OAHI,mBAAmB,EAAY,CAC1B,EAAY,KAAO,EAAU,EAAc,IAAA,GAE7C,EAAY,GAmDrB,MAAM,MAC6B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AS,CACP,QAAS,EAAO,UAAU,CAC3B,CAGD,SAAU,CACR,KAAM,EAAO,OAAO,CACpB,KAAM,EAAO,OAAO,CACpB,QAAS,EAAO,UAAU,CAC3B,CAGD,KAAM,CACJ,KAAM,EAAO,OAAO,CACrB,CAGD,KAAM,CACJ,KAAM,EAAO,OAAO,CACrB,CACF"}
|
package/dist/neon-http.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{n as e}from"./chunk-BuuaeEvq.mjs";import{i as t}from"./normalized-result-
|
|
1
|
+
import{n as e}from"./chunk-BuuaeEvq.mjs";import{i as t}from"./normalized-result-VunNi4ID.mjs";import{h as n}from"./error-mapping-Zett_Pnt.mjs";import{p as r,r as i}from"./validation-DN1N2OdK.mjs";import{n as a}from"./client-DHf2ZfRe.mjs";import{c as o,d as s,t as c}from"./driver-aqfbJdZC.mjs";import{t as l}from"./postgres-result-D4_yZqO8.mjs";import{t as u}from"./postgres-adapter-CnZjhvG1.mjs";const d={databaseUrl:!0,options:!0,pgvector:!0,postgis:!0,sharedRelationBodies:!0,relationsPerStatement:!0,namespace:!0};function malformedNeonResult(e,t){let n=e.operation??`execute`;return new r(`Driver "neon-http" returned a malformed result payload for operation "${n}": ${t}.`,{meta:{driver:`neon-http`,...e,operation:n}})}function assertNeonFullResult(e,n){if(!(t(e)&&Array.isArray(e.fields))||typeof e.command!=`string`||!Object.hasOwn(e,`rowCount`)||e.rowCount!==null&&(typeof e.rowCount!=`number`||!Number.isFinite(e.rowCount)||!Number.isSafeInteger(e.rowCount)||e.rowCount<0)||!Array.isArray(e.rows)||!e.rows.every(t)||e.rowAsArray!==!1)throw malformedNeonResult(n,`expected fullResults object with object rows and explicit rowCount`)}var NeonHTTPDriver=class extends c{maxBindParametersPerStatement=65535;supportsTransactions=!1;supportsBatch=!0;supportsOrderedCommittedSegments=!0;driverOptions;queryTypes;constructor(e={}){super(`postgresql`,`neon-http`);let t=s(e);this.driverOptions=e,u(this,t,e)}async initClient(){let{neon:e,types:t}=await import(`@neondatabase/serverless`);if(!this.driverOptions.databaseUrl)throw new i(`Neon HTTP driver requires a databaseUrl`,{meta:{driver:this.driverName}});let identityParser=e=>e,getTypeParser=((e,n)=>[1082,1114,1184,1115,1182,1185].includes(e)&&n!==`binary`?identityParser:t.getTypeParser(e,n));return this.queryTypes={getTypeParser},e(this.driverOptions.databaseUrl,{fetchOptions:this.driverOptions.options?.fetchOptions,authToken:this.driverOptions.options?.authToken,fullResults:!0,arrayMode:!1})}async closeClient(e){}async execute(e,t,n,r){return this.executeQuery(e,t,n,r,`execute`)}async executeQuery(e,t,n,r,i){let a=r??{operation:i},o=await e.query(t,n,{arrayMode:!1,fullResults:!0,types:this.queryTypes});return this.parseResult(o,a)}async executeRaw(e,t,n,r){return this.executeQuery(e,t,n??[],r,`executeRaw`)}transactionOptionSupport(){return{isolationLevel:`provider`,timeout:!1,timeoutReason:`Neon HTTP runs a batch as one provider call with no interactive body to interrupt`,maxWait:`unsupported`,maxWaitReason:`Neon HTTP submits the batch immediately with no connection to acquire`}}transaction(e,t){return Promise.reject(n(this.driverName))}async executeBatch(e,t,n,r,i){let a=n??{operation:`executeBatch`},o=await e.transaction(t.map(t=>{let n=t.context??a;try{return e.query(t.sql,t.params??[],{types:this.queryTypes})}catch(e){throw this.normalizeStatementFailure(e,t.sql,this.getBatchDiagnosticParameters(t),n,!0)}}),{isolationLevel:i?.isolationLevel,arrayMode:!1,fullResults:!0});if(await r?.(),!Array.isArray(o)||o.length!==t.length){let e=Array.isArray(o)?o.length:0;throw malformedNeonResult(a,`expected ${t.length} statement results but received ${e}`)}return o.map((e,n)=>this.parseResult(e,t[n]?.context??a))}parseResult(e,t){let n=t.operation??`execute`;return assertNeonFullResult(e,t),{rows:e.rows,rowCount:l(e.rowCount,e.command,e.rows,{provider:`neon-http`,operation:n,model:t.model,correlationId:t.correlationId})}}};function createClient(e){o(e,`neon-http`,d);let{databaseUrl:t,options:n,pgvector:r,postgis:i}=e,c=s(e);return a(e,new NeonHTTPDriver({databaseUrl:t,options:n,pgvector:r,postgis:i,sharedRelationBodies:e.sharedRelationBodies,relationsPerStatement:e.relationsPerStatement,namespace:c}))}export{NeonHTTPDriver,createClient};
|
|
2
2
|
//# sourceMappingURL=neon-http.mjs.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{n as e}from"./chunk-BuuaeEvq.mjs";import{r as t}from"./value-guards-CK9guf2Z.mjs";import{n}from"./base-
|
|
2
|
-
//# sourceMappingURL=normalized-result-
|
|
1
|
+
import{n as e}from"./chunk-BuuaeEvq.mjs";import{r as t}from"./value-guards-CK9guf2Z.mjs";import{n}from"./base-wlv81COV.mjs";import{p as r}from"./validation-DN1N2OdK.mjs";import{t as i}from"./sql-BR8ZzKn8.mjs";const a=typeof Symbol.asyncDispose==`symbol`?Symbol.asyncDispose:void 0,o=Symbol(`viborm.verbatimBatchQuery`);function markVerbatimBatchQuery(e){return Object.defineProperty(e,o,{configurable:!1,enumerable:!1,value:!0,writable:!1}),e}function isVerbatimBatchQuery(e){return Reflect.get(e,o)===!0}const s=new WeakMap;function registerPreparedStatement(e,t){s.set(e,t)}function transferPreparedStatement(e,t){let n=s.get(e);return n!==void 0&&s.set(t,n),t}function snapshotPreparedStatement(e,t,n){let r=s.get(e);return r!==void 0&&s.set(t,new i([...r.strings],[...n])),t}function readPreparedStatement(e){return s.get(e)}const c=/^(?:0|[1-9]\d*)$/;function captureBuiltinPrototype(e){let t=[];for(let n of Reflect.ownKeys(e)){let r=Object.getOwnPropertyDescriptor(e,n);r&&t.push({descriptor:r,key:n})}return Object.freeze(t)}const l=captureBuiltinPrototype(Object.prototype),u=captureBuiltinPrototype(Array.prototype);function isArrayIndex(e){if(typeof e!=`string`||!c.test(e))return!1;let t=Number(e);return t<=4294967294&&String(t)===e}function functionSource(e){if(typeof e==`function`)try{return Function.prototype.toString.call(e)}catch{return}}function sameInertRecord(e,t){if(e===null||t===null||typeof e!=`object`||typeof t!=`object`)return Object.is(e,t);try{if(Object.getPrototypeOf(e)!==null||Object.getPrototypeOf(t)!==null)return!1;let n=Reflect.ownKeys(e),r=Reflect.ownKeys(t);if(n.length!==r.length)return!1;for(let i=0;i<r.length;i+=1){let a=n[i],o=r[i];if(a!==o||o===void 0)return!1;let s=Object.getOwnPropertyDescriptor(e,o),c=Object.getOwnPropertyDescriptor(t,o);if(s===void 0||c===void 0||!(`value`in s)||!(`value`in c)||s.configurable!==c.configurable||s.enumerable!==c.enumerable||s.writable!==c.writable||!Object.is(s.value,c.value))return!1}return!0}catch{return!1}}function sameBuiltinDescriptor(e,t){if(e.configurable!==t.configurable||e.enumerable!==t.enumerable||`value`in e!=`value`in t)return!1;if(`value`in e&&`value`in t){if(e.writable!==t.writable)return!1;let n=functionSource(t.value);return n===void 0?sameInertRecord(e.value,t.value):functionSource(e.value)===n}return functionSource(e.get)===functionSource(t.get)&&functionSource(e.set)===functionSource(t.set)}function hasBuiltinPrototypeShape(e,t){try{let n=Reflect.ownKeys(e);if(n.length!==t.length)return!1;for(let r=0;r<t.length;r+=1){let i=t[r];if(i===void 0||n[r]!==i.key)return!1;let a=Object.getOwnPropertyDescriptor(e,i.key);if(a===void 0||!sameBuiltinDescriptor(a,i.descriptor))return!1}return!0}catch{return!1}}function isObjectPrototype(e){try{return Object.getPrototypeOf(e)===null&&hasBuiltinPrototypeShape(e,l)}catch{return!1}}function isArrayPrototype(e){try{let t=Object.getPrototypeOf(e);return t!==null&&isObjectPrototype(t)&&hasBuiltinPrototypeShape(e,u)}catch{return!1}}function rawParameterNodeShape(e){let t=!1;try{t=Array.isArray(e);let n=Object.getPrototypeOf(e);if(t&&n!==null&&!isArrayPrototype(n)||!t&&n!==null&&!isObjectPrototype(n))return{kind:t?`unsupported-array`:`opaque`};let r=[],i=[];for(let n of Reflect.ownKeys(e)){let a=Object.getOwnPropertyDescriptor(e,n);if(a!==void 0&&(i.push({descriptor:a,key:n}),t?isArrayIndex(n):a.enumerable&&typeof n==`string`)){if(!(`value`in a))return{kind:t?`unsupported-array`:`opaque`};r.push({descriptor:a,key:n,value:a.value})}}let a=i.find(e=>e.key===`toJSON`);return a&&(!(`value`in a.descriptor)||typeof a.descriptor.value==`function`)?{kind:t?`unsupported-array`:`opaque`}:{kind:`node`,shape:{edges:r,isArray:t,properties:i,prototype:n}}}catch{return{kind:t?`unsupported-array`:`opaque`}}}function rawDateTime(e,n,r){if(!t(e))return;let i=Date.prototype.getTime.call(e);if(Number.isNaN(i))throw r(n);return i}function analyzeRawParameterGraph(e,t){let n=new WeakMap,r=new WeakMap,i=[],a=Array(e.length),discover=(e,a)=>{let o=rawDateTime(e,a,t.invalidDate);if(o!==void 0&&typeof e==`object`&&e){r.set(e,o);return}if(typeof e!=`object`||!e)return;let s=n.get(e);if(s)return s;let c=rawParameterNodeShape(e);if(c.kind===`unsupported-array`)throw t.unsupportedArray(a);if(c.kind===`opaque`)return;let l={...c.shape,source:e};return n.set(e,l),i.push(l),l};for(let n=0;n<e.length;n++){if(!Object.hasOwn(e,n))continue;let o=e[n];a[n]=o;let s=rawDateTime(o,n,t.invalidDate);if(s!==void 0&&typeof o==`object`&&o){r.set(o,s);continue}let c=discover(o,n);if(!c)continue;let l=[c],u=0;for(;u<l.length;){let e=l[u];if(u+=1,e)for(let t of e.edges){let e=i.length,r=discover(t.value,n);r&&i.length>e&&l.push(r)}}}return{dateTimes:r,nodes:i,roots:a}}function validateRawParameters(e,t){analyzeRawParameterGraph(e,t)}function snapshotRawParameterGraph(e,t){let n=analyzeRawParameterGraph(e,t),r=new WeakMap,i=new WeakMap;for(let e of n.nodes){let t=e.isArray?[]:{};e.prototype===null&&Object.setPrototypeOf(t,null),r.set(e.source,t)}let copiedValue=e=>{if(typeof e!=`object`||!e)return e;let t=n.dateTimes.get(e);if(t!==void 0){let n=i.get(e);if(n)return n;let r=new Date(t);return i.set(e,r),r}return r.get(e)??e};for(let e of n.nodes){let t=r.get(e.source);if(t){for(let n of e.properties){if(e.isArray&&n.key===`length`)continue;let r=n.descriptor;Object.defineProperty(t,n.key,`value`in r&&(e.isArray?isArrayIndex(n.key):r.enumerable&&typeof n.key==`string`)?{...r,value:copiedValue(r.value)}:r)}if(e.isArray){let n=e.properties.find(e=>e.key===`length`);n&&Object.defineProperty(t,`length`,n.descriptor)}}}let a=Array(n.roots.length);for(let e=0;e<n.roots.length;e++)Object.hasOwn(n.roots,e)&&(a[e]=copiedValue(n.roots[e]));return a}function invalidProviderDateError(e,t){return new r(`Operation "${e.operation??`statement`}" received an invalid Date as bound parameter ${t}. An invalid Date names no instant, so a provider either refuses the statement after dispatch or binds it as null.`,{code:n.INVALID_INPUT,meta:{parameterIndex:t,model:e.model,operation:e.operation,correlationId:e.correlationId}})}function unsupportedProviderArrayError(e,t){return new r(`Operation "${e.operation??`statement`}" received raw array parameter ${t} with custom inherited or accessor behavior. VibORM cannot validate that behavior without invoking caller code before dispatch.`,{code:n.INVALID_INPUT,meta:{parameterIndex:t,model:e.model,operation:e.operation,correlationId:e.correlationId}})}function snapshotProviderParameters(e,t){return t.model===`$raw`?snapshotRawParameterGraph(e,{invalidDate:e=>invalidProviderDateError(t,e),unsupportedArray:e=>unsupportedProviderArrayError(t,e)}):[...e]}function createNormalizedResultMeta(e){return{driver:e.provider,operation:e.operation,...e.model?{model:e.model}:{},...e.correlationId?{correlationId:e.correlationId}:{}}}const d=/^(?:0|[1-9]\d*)$/;function normalizeProviderRowCount(e,t,n){let i=e===null?n?.nullValue:e;if(n?.allowDecimalString===!0&&typeof i==`string`&&d.test(i)&&(i=Number(i)),typeof i!=`number`||!Number.isSafeInteger(i)||i<0)throw new r(`Driver "${t.provider}" returned a malformed row count for operation "${t.operation}".`,{meta:createNormalizedResultMeta(t)});return i}function normalizeProviderInsertId(e,t,n){if(typeof e==`string`){if(!d.test(e))throw malformedInsertId(t);return e===`0`?void 0:BigInt(e)}if(n?.allowNumber===!0&&typeof e==`number`){if(!Number.isSafeInteger(e)||e<0)throw malformedInsertId(t);return e===0?void 0:e}throw malformedInsertId(t)}function malformedInsertId(e){return new r(`Driver "${e.provider}" returned a malformed insert id for operation "${e.operation}".`,{meta:createNormalizedResultMeta(e)})}function malformedNormalizedResult(e,t){let n=t===void 0?``:` at batch result index ${t}`;return new r(`Driver "${e.provider}" returned a malformed normalized result for operation "${e.operation}"${n}; expected { rows: object[], rowCount: safe non-negative integer }.`,{meta:{...createNormalizedResultMeta(e),...t===void 0?{}:{resultIndex:t}}})}function isNormalizedResultRow(e){return typeof e==`object`&&!!e&&Object.prototype.toString.call(e)===`[object Object]`}function hasNormalizedRows(e){if(!Array.isArray(e))return!1;for(let t=0;t<e.length;t+=1)if(!(Object.hasOwn(e,t)&&isNormalizedResultRow(e[t])))return!1;return!0}function assertNormalizedQueryResult(e,t,n){let r=e?.insertId===void 0||typeof e.insertId==`bigint`&&e.insertId>=0n||typeof e.insertId==`number`&&Number.isFinite(e.insertId)&&Number.isSafeInteger(e.insertId)&&e.insertId>=0;if(!(isNormalizedResultRow(e)&&hasNormalizedRows(e.rows))||typeof e.rowCount!=`number`||!Number.isFinite(e.rowCount)||!Number.isSafeInteger(e.rowCount)||e.rowCount<0||!r)throw malformedNormalizedResult(t,n)}function assertNormalizedBatchResults(e,t,n){if(!Array.isArray(e)||e.length!==t){let i=Array.isArray(e)?e.length:0;throw new r(`Driver "${n.provider}" returned ${i} results for operation "${n.operation}"; expected ${t}, one per statement.`,{meta:{...createNormalizedResultMeta(n),expectedStatementCount:t,actualResultCount:i}})}for(let t=0;t<e.length;t+=1)assertNormalizedQueryResult(e[t],n,t)}export{normalizeProviderInsertId as a,validateRawParameters as c,snapshotPreparedStatement as d,transferPreparedStatement as f,a as h,isNormalizedResultRow as i,readPreparedStatement as l,markVerbatimBatchQuery as m,assertNormalizedQueryResult as n,normalizeProviderRowCount as o,isVerbatimBatchQuery as p,createNormalizedResultMeta as r,snapshotProviderParameters as s,assertNormalizedBatchResults as t,registerPreparedStatement as u};
|
|
2
|
+
//# sourceMappingURL=normalized-result-VunNi4ID.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"normalized-result-BF7gr4_b.mjs","names":[],"sources":["../src/drivers/async-dispose.ts","../src/drivers/driver-batch-query-kind.ts","../src/drivers/prepared-statement-provenance.ts","../src/drivers/provider-parameter-snapshot.ts","../src/drivers/normalized-result.ts"],"sourcesContent":["/**\n * The platform's async-disposal protocol — as much of it as the runtime and the\n * consumer's type declarations actually provide.\n *\n * `Symbol.asyncDispose` (explicit resource management, TypeScript 5.2+) can be\n * missing in two independent ways, and each one is handled here so that no\n * caller has to think about it:\n *\n * 1. **The runtime symbol** is absent on engines that predate the proposal.\n * {@link ASYNC_DISPOSE} resolves it once; every definition site guards on it\n * rather than writing a bare `[Symbol.asyncDispose]` computed key, which\n * would otherwise install a method under the string key `\"undefined\"`.\n *\n * 2. **The type declaration** is absent from a consumer's `lib` / `@types`.\n * That is why the disposal member is carried by {@link AsyncDisposeMember}\n * instead of being written literally: a consumer who never writes\n * `await using` must not be forced to widen `lib` just to compile the\n * published `.d.mts`. See `docs/architecture/typed-kernel-without-effect-plan.md`\n * (Phase T6) and the consumer-floor probe in\n * `scripts/consumer-type-floor.mjs` for the measured floor.\n */\n\n/**\n * The runtime's async-disposal key, or `undefined` on engines that predate\n * explicit resource management.\n */\nexport const ASYNC_DISPOSE: typeof Symbol.asyncDispose | undefined =\n typeof Symbol.asyncDispose === \"symbol\" ? Symbol.asyncDispose : undefined;\n\n/**\n * `Symbol.asyncDispose`'s type where the ambient declarations define it, and\n * `never` where they do not.\n *\n * `never` is the load-bearing half: it turns {@link AsyncDisposeMember} into the\n * empty object, so the member simply is not there for a consumer whose `lib`\n * and `@types` never declared the symbol in the first place.\n */\nexport type AsyncDisposeKey = SymbolConstructor extends {\n readonly asyncDispose: infer Key extends symbol;\n}\n ? Key\n : never;\n\n/**\n * `{ [Symbol.asyncDispose](): Promise<void> }` where the symbol is typed, and\n * `{}` where it is not — the graceful-degradation carrier for every viborm type\n * that participates in `await using`.\n */\nexport type AsyncDisposeMember = {\n [Key in AsyncDisposeKey]: () => Promise<void>;\n};\n","/** Internal execution-kind metadata for prepared batch queries. */\n\nconst VERBATIM_BATCH_QUERY = Symbol(\"viborm.verbatimBatchQuery\");\n\n/** Mark a prepared raw statement that must retain verbatim driver semantics. */\nexport function markVerbatimBatchQuery<T extends object>(query: T): T {\n Object.defineProperty(query, VERBATIM_BATCH_QUERY, {\n configurable: false,\n enumerable: false,\n value: true,\n writable: false,\n });\n return query;\n}\n\n/** Whether a prepared statement came from an unsafe or legacy raw call. */\nexport function isVerbatimBatchQuery(query: object): boolean {\n return Reflect.get(query, VERBATIM_BATCH_QUERY) === true;\n}\n","import { Sql } from \"@sql\";\n\nconst preparedStatements = new WeakMap<object, Sql>();\n\n/** Retain the typed Sql behind a rendered batch query without publishing it. */\nexport function registerPreparedStatement(query: object, statement: Sql): void {\n preparedStatements.set(query, statement);\n}\n\n/** Preserve private provenance when an internal owner snapshots a batch query. */\nexport function transferPreparedStatement<Output extends object>(\n source: object,\n output: Output\n): Output {\n const statement = preparedStatements.get(source);\n if (statement !== undefined) preparedStatements.set(output, statement);\n return output;\n}\n\n/** Preserve provenance with the exact detached values a batch will execute. */\nexport function snapshotPreparedStatement<Output extends object>(\n source: object,\n output: Output,\n values: readonly unknown[]\n): Output {\n const statement = preparedStatements.get(source);\n if (statement !== undefined) {\n preparedStatements.set(\n output,\n new Sql([...statement.strings], [...values])\n );\n }\n return output;\n}\n\n/** Read provenance only at the trusted typed-statement execution boundary. */\nexport function readPreparedStatement(query: object): Sql | undefined {\n return preparedStatements.get(query);\n}\n","import { QueryError, VibORMErrorCode } from \"@errors\";\nimport { isDate } from \"@validation/value-guards\";\nimport type { QueryExecutionContext } from \"./types\";\n\ntype InvalidRawDateError = (parameterIndex: number) => Error;\ntype UnsupportedRawArrayError = (parameterIndex: number) => Error;\n\ninterface RawParameterErrors {\n readonly invalidDate: InvalidRawDateError;\n readonly unsupportedArray: UnsupportedRawArrayError;\n}\n\ninterface RawParameterEdge {\n readonly descriptor: PropertyDescriptor;\n readonly key: PropertyKey;\n readonly value: unknown;\n}\n\ninterface RawParameterNode {\n readonly edges: readonly RawParameterEdge[];\n readonly isArray: boolean;\n readonly properties: readonly RawParameterProperty[];\n readonly prototype: object | null;\n readonly source: object;\n}\n\ninterface RawParameterProperty {\n readonly descriptor: PropertyDescriptor;\n readonly key: PropertyKey;\n}\n\ninterface RawParameterGraph {\n readonly dateTimes: WeakMap<object, number>;\n readonly nodes: readonly RawParameterNode[];\n readonly roots: readonly unknown[];\n}\n\ntype RawParameterNodeAnalysis =\n | { readonly kind: \"node\"; readonly shape: Omit<RawParameterNode, \"source\"> }\n | { readonly kind: \"opaque\" }\n | { readonly kind: \"unsupported-array\" };\n\nconst arrayIndex = /^(?:0|[1-9]\\d*)$/;\nconst maximumArrayIndex = 4_294_967_294;\n\ninterface BuiltinPrototypeProperty {\n readonly descriptor: PropertyDescriptor;\n readonly key: PropertyKey;\n}\n\nfunction captureBuiltinPrototype(\n prototype: object\n): readonly BuiltinPrototypeProperty[] {\n const properties: BuiltinPrototypeProperty[] = [];\n for (const key of Reflect.ownKeys(prototype)) {\n const descriptor = Object.getOwnPropertyDescriptor(prototype, key);\n if (descriptor) properties.push({ descriptor, key });\n }\n return Object.freeze(properties);\n}\n\nconst objectPrototypeShape = captureBuiltinPrototype(Object.prototype);\nconst arrayPrototypeShape = captureBuiltinPrototype(Array.prototype);\n\nfunction isArrayIndex(key: PropertyKey): boolean {\n if (typeof key !== \"string\" || !arrayIndex.test(key)) return false;\n const index = Number(key);\n return index <= maximumArrayIndex && String(index) === key;\n}\n\nfunction functionSource(value: unknown): string | undefined {\n if (typeof value !== \"function\") return;\n try {\n return Function.prototype.toString.call(value);\n } catch {\n return;\n }\n}\n\nfunction sameInertRecord(left: unknown, right: unknown): boolean {\n if (\n left === null ||\n right === null ||\n typeof left !== \"object\" ||\n typeof right !== \"object\"\n ) {\n return Object.is(left, right);\n }\n try {\n if (\n Object.getPrototypeOf(left) !== null ||\n Object.getPrototypeOf(right) !== null\n ) {\n return false;\n }\n const leftKeys = Reflect.ownKeys(left);\n const rightKeys = Reflect.ownKeys(right);\n if (leftKeys.length !== rightKeys.length) return false;\n for (let index = 0; index < rightKeys.length; index += 1) {\n const leftKey = leftKeys[index];\n const rightKey = rightKeys[index];\n if (leftKey !== rightKey || rightKey === undefined) return false;\n const leftDescriptor = Object.getOwnPropertyDescriptor(left, rightKey);\n const rightDescriptor = Object.getOwnPropertyDescriptor(right, rightKey);\n if (\n leftDescriptor === undefined ||\n rightDescriptor === undefined ||\n !(\"value\" in leftDescriptor) ||\n !(\"value\" in rightDescriptor) ||\n leftDescriptor.configurable !== rightDescriptor.configurable ||\n leftDescriptor.enumerable !== rightDescriptor.enumerable ||\n leftDescriptor.writable !== rightDescriptor.writable ||\n !Object.is(leftDescriptor.value, rightDescriptor.value)\n ) {\n return false;\n }\n }\n return true;\n } catch {\n return false;\n }\n}\n\nfunction sameBuiltinDescriptor(\n actual: PropertyDescriptor,\n expected: PropertyDescriptor\n): boolean {\n if (\n actual.configurable !== expected.configurable ||\n actual.enumerable !== expected.enumerable ||\n \"value\" in actual !== \"value\" in expected\n ) {\n return false;\n }\n if (\"value\" in actual && \"value\" in expected) {\n if (actual.writable !== expected.writable) return false;\n const expectedSource = functionSource(expected.value);\n if (expectedSource !== undefined) {\n return functionSource(actual.value) === expectedSource;\n }\n return sameInertRecord(actual.value, expected.value);\n }\n return (\n functionSource(actual.get) === functionSource(expected.get) &&\n functionSource(actual.set) === functionSource(expected.set)\n );\n}\n\nfunction hasBuiltinPrototypeShape(\n prototype: object,\n shape: readonly BuiltinPrototypeProperty[]\n): boolean {\n try {\n const keys = Reflect.ownKeys(prototype);\n if (keys.length !== shape.length) return false;\n for (let index = 0; index < shape.length; index += 1) {\n const expected = shape[index];\n if (expected === undefined || keys[index] !== expected.key) return false;\n const actual = Object.getOwnPropertyDescriptor(prototype, expected.key);\n if (\n actual === undefined ||\n !sameBuiltinDescriptor(actual, expected.descriptor)\n ) {\n return false;\n }\n }\n return true;\n } catch {\n return false;\n }\n}\n\nfunction isObjectPrototype(prototype: object): boolean {\n try {\n return (\n Object.getPrototypeOf(prototype) === null &&\n hasBuiltinPrototypeShape(prototype, objectPrototypeShape)\n );\n } catch {\n return false;\n }\n}\n\nfunction isArrayPrototype(prototype: object): boolean {\n try {\n const parent = Object.getPrototypeOf(prototype);\n return (\n parent !== null &&\n isObjectPrototype(parent) &&\n hasBuiltinPrototypeShape(prototype, arrayPrototypeShape)\n );\n } catch {\n return false;\n }\n}\n\n/** Only arrays and records with inert inherited behavior are interpreted. */\nfunction rawParameterNodeShape(value: object): RawParameterNodeAnalysis {\n let isArray = false;\n try {\n isArray = Array.isArray(value);\n const prototype = Object.getPrototypeOf(value);\n if (\n (isArray && prototype !== null && !isArrayPrototype(prototype)) ||\n (!isArray && prototype !== null && !isObjectPrototype(prototype))\n ) {\n return { kind: isArray ? \"unsupported-array\" : \"opaque\" };\n }\n\n const edges: RawParameterEdge[] = [];\n const properties: RawParameterProperty[] = [];\n for (const key of Reflect.ownKeys(value)) {\n const descriptor = Object.getOwnPropertyDescriptor(value, key);\n if (descriptor === undefined) continue;\n properties.push({ descriptor, key });\n const isProviderVisible = isArray\n ? isArrayIndex(key)\n : descriptor.enumerable && typeof key === \"string\";\n if (!isProviderVisible) continue;\n if (!(\"value\" in descriptor)) {\n return { kind: isArray ? \"unsupported-array\" : \"opaque\" };\n }\n edges.push({ descriptor, key, value: descriptor.value });\n }\n const toJSON = properties.find((property) => property.key === \"toJSON\");\n if (\n toJSON &&\n (!(\"value\" in toJSON.descriptor) ||\n typeof toJSON.descriptor.value === \"function\")\n ) {\n return { kind: isArray ? \"unsupported-array\" : \"opaque\" };\n }\n return {\n kind: \"node\",\n shape: { edges, isArray, properties, prototype },\n };\n } catch {\n // An exotic record owns its traversal semantics. If reflection refuses an\n // array shape, it cannot safely reach provider array semantics.\n return { kind: isArray ? \"unsupported-array\" : \"opaque\" };\n }\n}\n\nfunction rawDateTime(\n value: unknown,\n parameterIndex: number,\n invalidDateError: InvalidRawDateError\n): number | undefined {\n if (!isDate(value)) return;\n const time = Date.prototype.getTime.call(value);\n if (Number.isNaN(time)) throw invalidDateError(parameterIndex);\n return time;\n}\n\nfunction analyzeRawParameterGraph(\n params: readonly unknown[],\n errors: RawParameterErrors\n): RawParameterGraph {\n const nodesBySource = new WeakMap<object, RawParameterNode>();\n const dateTimes = new WeakMap<object, number>();\n const nodes: RawParameterNode[] = [];\n const roots = new Array<unknown>(params.length);\n\n const discover = (\n value: unknown,\n parameterIndex: number\n ): RawParameterNode | undefined => {\n const time = rawDateTime(value, parameterIndex, errors.invalidDate);\n if (time !== undefined && typeof value === \"object\" && value !== null) {\n dateTimes.set(value, time);\n return;\n }\n if (typeof value !== \"object\" || value === null) return;\n\n const known = nodesBySource.get(value);\n if (known) return known;\n const analysis = rawParameterNodeShape(value);\n if (analysis.kind === \"unsupported-array\") {\n throw errors.unsupportedArray(parameterIndex);\n }\n if (analysis.kind === \"opaque\") return;\n const node: RawParameterNode = {\n ...analysis.shape,\n source: value,\n };\n nodesBySource.set(value, node);\n nodes.push(node);\n return node;\n };\n\n for (\n let parameterIndex = 0;\n parameterIndex < params.length;\n parameterIndex++\n ) {\n if (!Object.hasOwn(params, parameterIndex)) continue;\n const root = params[parameterIndex];\n roots[parameterIndex] = root;\n const rootTime = rawDateTime(root, parameterIndex, errors.invalidDate);\n if (rootTime !== undefined && typeof root === \"object\" && root !== null) {\n dateTimes.set(root, rootTime);\n continue;\n }\n const rootNode = discover(root, parameterIndex);\n if (!rootNode) continue;\n\n const pending = [rootNode];\n let cursor = 0;\n while (cursor < pending.length) {\n const node = pending[cursor];\n cursor += 1;\n if (!node) continue;\n for (const edge of node.edges) {\n const before = nodes.length;\n const child = discover(edge.value, parameterIndex);\n if (child && nodes.length > before) pending.push(child);\n }\n }\n }\n\n return { dateTimes, nodes, roots };\n}\n\n/** Validate every interpreted raw parameter before query interception. */\nexport function validateRawParameters(\n params: readonly unknown[],\n errors: RawParameterErrors\n): void {\n analyzeRawParameterGraph(params, errors);\n}\n\n/**\n * Snapshot every admitted data-descriptor JSON container, preserving aliases,\n * cycles, and property descriptors. Foreign built-in containers normalize to\n * local prototypes. Custom record carriers and provider-native objects remain\n * opaque; arrays with custom provider-visible behavior are refused. A Proxy\n * can run reflection traps while presenting an admitted container shape; the\n * captured descriptor view, never the later mutable Proxy, reaches dispatch.\n */\nfunction snapshotRawParameterGraph(\n params: readonly unknown[],\n errors: RawParameterErrors\n): unknown[] {\n const graph = analyzeRawParameterGraph(params, errors);\n const copies = new WeakMap<object, object>();\n const copiedDates = new WeakMap<object, Date>();\n\n for (const node of graph.nodes) {\n const copy: object = node.isArray ? [] : {};\n if (node.prototype === null) Object.setPrototypeOf(copy, null);\n copies.set(node.source, copy);\n }\n\n const copiedValue = (value: unknown): unknown => {\n if (typeof value !== \"object\" || value === null) return value;\n const time = graph.dateTimes.get(value);\n if (time !== undefined) {\n const known = copiedDates.get(value);\n if (known) return known;\n const copy = new Date(time);\n copiedDates.set(value, copy);\n return copy;\n }\n return copies.get(value) ?? value;\n };\n\n for (const node of graph.nodes) {\n const copy = copies.get(node.source);\n if (!copy) continue;\n for (const property of node.properties) {\n if (node.isArray && property.key === \"length\") continue;\n const descriptor = property.descriptor;\n Object.defineProperty(\n copy,\n property.key,\n \"value\" in descriptor &&\n (node.isArray\n ? isArrayIndex(property.key)\n : descriptor.enumerable && typeof property.key === \"string\")\n ? { ...descriptor, value: copiedValue(descriptor.value) }\n : descriptor\n );\n }\n if (node.isArray) {\n const length = node.properties.find(\n (property) => property.key === \"length\"\n );\n if (length) Object.defineProperty(copy, \"length\", length.descriptor);\n }\n }\n\n const snapshot = new Array<unknown>(graph.roots.length);\n for (let index = 0; index < graph.roots.length; index++) {\n if (!Object.hasOwn(graph.roots, index)) continue;\n snapshot[index] = copiedValue(graph.roots[index]);\n }\n return snapshot;\n}\n\nfunction invalidProviderDateError(\n context: QueryExecutionContext,\n parameterIndex: number\n): QueryError {\n return new QueryError(\n `Operation \"${context.operation ?? \"statement\"}\" received an invalid Date as bound parameter ${parameterIndex}. An invalid Date names no instant, so a provider either refuses the statement after dispatch or binds it as null.`,\n {\n code: VibORMErrorCode.INVALID_INPUT,\n meta: {\n parameterIndex,\n model: context.model,\n operation: context.operation,\n correlationId: context.correlationId,\n },\n }\n );\n}\n\nfunction unsupportedProviderArrayError(\n context: QueryExecutionContext,\n parameterIndex: number\n): QueryError {\n return new QueryError(\n `Operation \"${context.operation ?? \"statement\"}\" received raw array parameter ${parameterIndex} with custom inherited or accessor behavior. VibORM cannot validate that behavior without invoking caller code before dispatch.`,\n {\n code: VibORMErrorCode.INVALID_INPUT,\n meta: {\n parameterIndex,\n model: context.model,\n operation: context.operation,\n correlationId: context.correlationId,\n },\n }\n );\n}\n\n/**\n * Preserve the raw Date admission invariant after the last trusted statement\n * transform. Non-raw statements keep the old shallow-copy path: their typed\n * inputs were validated upstream, and statement transforms are trusted. Raw\n * Date leaves are revalidated and every admitted data-descriptor array or\n * ordinary JSON record is detached. Reflection does not invoke accessors,\n * iterators, or `toJSON`; a Proxy may run its reflection traps, so its captured\n * descriptor view is the stable provider value. Arrays with custom inherited\n * or accessor behavior are refused. Custom record and provider-native carriers\n * remain opaque and are not traversed.\n */\nexport function snapshotProviderParameters(\n params: readonly unknown[],\n context: QueryExecutionContext\n): unknown[] {\n if (context.model !== \"$raw\") return [...params];\n return snapshotRawParameterGraph(params, {\n invalidDate: (parameterIndex) =>\n invalidProviderDateError(context, parameterIndex),\n unsupportedArray: (parameterIndex) =>\n unsupportedProviderArrayError(context, parameterIndex),\n });\n}\n","import { QueryError } from \"@errors\";\nimport type { QueryResult } from \"./types\";\n\nexport interface NormalizedResultContext {\n provider: string;\n operation: string;\n model?: string;\n correlationId?: string;\n}\n\nexport function createNormalizedResultMeta(\n context: NormalizedResultContext\n): Record<string, unknown> {\n return {\n driver: context.provider,\n operation: context.operation,\n ...(context.model ? { model: context.model } : {}),\n ...(context.correlationId ? { correlationId: context.correlationId } : {}),\n };\n}\n\nconst NON_NEGATIVE_DECIMAL_REGEX = /^(?:0|[1-9]\\d*)$/;\n\nexport function normalizeProviderRowCount(\n value: unknown,\n context: NormalizedResultContext,\n options?: { allowDecimalString?: boolean; nullValue?: number }\n): number {\n let normalized = value === null ? options?.nullValue : value;\n if (\n options?.allowDecimalString === true &&\n typeof normalized === \"string\" &&\n NON_NEGATIVE_DECIMAL_REGEX.test(normalized)\n ) {\n normalized = Number(normalized);\n }\n if (\n typeof normalized !== \"number\" ||\n !Number.isSafeInteger(normalized) ||\n normalized < 0\n ) {\n throw new QueryError(\n `Driver \"${context.provider}\" returned a malformed row count for operation \"${context.operation}\".`,\n {\n meta: createNormalizedResultMeta(context),\n }\n );\n }\n return normalized;\n}\n\nexport function normalizeProviderInsertId(\n value: unknown,\n context: NormalizedResultContext,\n options?: { allowNumber?: boolean }\n): number | bigint | undefined {\n if (typeof value === \"string\") {\n if (!NON_NEGATIVE_DECIMAL_REGEX.test(value)) {\n throw malformedInsertId(context);\n }\n return value === \"0\" ? undefined : BigInt(value);\n }\n if (options?.allowNumber === true && typeof value === \"number\") {\n if (!Number.isSafeInteger(value) || value < 0) {\n throw malformedInsertId(context);\n }\n return value === 0 ? undefined : value;\n }\n throw malformedInsertId(context);\n}\n\nfunction malformedInsertId(context: NormalizedResultContext): QueryError {\n return new QueryError(\n `Driver \"${context.provider}\" returned a malformed insert id for operation \"${context.operation}\".`,\n {\n meta: createNormalizedResultMeta(context),\n }\n );\n}\n\nfunction malformedNormalizedResult(\n context: NormalizedResultContext,\n resultIndex?: number\n): QueryError {\n const position =\n resultIndex === undefined ? \"\" : ` at batch result index ${resultIndex}`;\n return new QueryError(\n `Driver \"${context.provider}\" returned a malformed normalized result for operation \"${context.operation}\"${position}; expected { rows: object[], rowCount: safe non-negative integer }.`,\n {\n meta: {\n ...createNormalizedResultMeta(context),\n ...(resultIndex === undefined ? {} : { resultIndex }),\n },\n }\n );\n}\n\nexport function isNormalizedResultRow(\n value: unknown\n): value is Record<string, unknown> {\n return (\n typeof value === \"object\" &&\n value !== null &&\n Object.prototype.toString.call(value) === \"[object Object]\"\n );\n}\n\nfunction hasNormalizedRows(value: unknown): value is Record<string, unknown>[] {\n if (!Array.isArray(value)) return false;\n for (let index = 0; index < value.length; index += 1) {\n if (!(Object.hasOwn(value, index) && isNormalizedResultRow(value[index]))) {\n return false;\n }\n }\n return true;\n}\n\n/**\n * Assert the single cross-driver success contract. Empty row arrays and a\n * rowCount of zero are valid; missing fields, non-record rows, and invented\n * counts are not.\n */\nexport function assertNormalizedQueryResult(\n result: QueryResult<unknown> | undefined,\n context: NormalizedResultContext,\n resultIndex?: number\n): void {\n const hasValidInsertId =\n result?.insertId === undefined ||\n (typeof result.insertId === \"bigint\" && result.insertId >= 0n) ||\n (typeof result.insertId === \"number\" &&\n Number.isFinite(result.insertId) &&\n Number.isSafeInteger(result.insertId) &&\n result.insertId >= 0);\n if (\n !(isNormalizedResultRow(result) && hasNormalizedRows(result.rows)) ||\n typeof result.rowCount !== \"number\" ||\n !Number.isFinite(result.rowCount) ||\n !Number.isSafeInteger(result.rowCount) ||\n result.rowCount < 0 ||\n !hasValidInsertId\n ) {\n throw malformedNormalizedResult(context, resultIndex);\n }\n}\n\n/**\n * Native and planned batches must return one normalized result for each\n * submitted statement, in the same order.\n */\nexport function assertNormalizedBatchResults(\n results: readonly QueryResult<unknown>[],\n expectedStatementCount: number,\n context: NormalizedResultContext\n): void {\n if (!Array.isArray(results) || results.length !== expectedStatementCount) {\n const actualResultCount = Array.isArray(results) ? results.length : 0;\n throw new QueryError(\n `Driver \"${context.provider}\" returned ${actualResultCount} results for operation \"${context.operation}\"; expected ${expectedStatementCount}, one per statement.`,\n {\n meta: {\n ...createNormalizedResultMeta(context),\n expectedStatementCount,\n actualResultCount,\n },\n }\n );\n }\n\n for (let resultIndex = 0; resultIndex < results.length; resultIndex += 1) {\n assertNormalizedQueryResult(results[resultI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,EAAS,EAAY,CAQzD,SAAgB,6BACd,EACA,EACA,EACM,CACN,GAAI,CAAC,MAAM,QAAQ,EAAQ,EAAI,EAAQ,SAAW,EAAwB,CACxE,IAAM,EAAoB,MAAM,QAAQ,EAAQ,CAAG,EAAQ,OAAS,EACpE,MAAM,IAAI,EACR,WAAW,EAAQ,SAAS,aAAa,EAAkB,0BAA0B,EAAQ,UAAU,cAAc,EAAuB,sBAC5I,CACE,KAAM,CACJ,GAAG,2BAA2B,EAAQ,CACtC,yBACA,oBACD,CACF,CACF,CAGH,IAAK,IAAI,EAAc,EAAG,EAAc,EAAQ,OAAQ,GAAe,EACrE,4BAA4B,EAAQ,GAAc,EAAS,EAAY"}
|
|
1
|
+
{"version":3,"file":"normalized-result-VunNi4ID.mjs","names":[],"sources":["../src/drivers/async-dispose.ts","../src/drivers/driver-batch-query-kind.ts","../src/drivers/prepared-statement-provenance.ts","../src/drivers/provider-parameter-snapshot.ts","../src/drivers/normalized-result.ts"],"sourcesContent":["/**\n * The platform's async-disposal protocol — as much of it as the runtime and the\n * consumer's type declarations actually provide.\n *\n * `Symbol.asyncDispose` (explicit resource management, TypeScript 5.2+) can be\n * missing in two independent ways, and each one is handled here so that no\n * caller has to think about it:\n *\n * 1. **The runtime symbol** is absent on engines that predate the proposal.\n * {@link ASYNC_DISPOSE} resolves it once; every definition site guards on it\n * rather than writing a bare `[Symbol.asyncDispose]` computed key, which\n * would otherwise install a method under the string key `\"undefined\"`.\n *\n * 2. **The type declaration** is absent from a consumer's `lib` / `@types`.\n * That is why the disposal member is carried by {@link AsyncDisposeMember}\n * instead of being written literally: a consumer who never writes\n * `await using` must not be forced to widen `lib` just to compile the\n * published `.d.mts`. See `docs/architecture/typed-kernel-without-effect-plan.md`\n * (Phase T6) and the consumer-floor probe in\n * `scripts/consumer-type-floor.mjs` for the measured floor.\n */\n\n/**\n * The runtime's async-disposal key, or `undefined` on engines that predate\n * explicit resource management.\n */\nexport const ASYNC_DISPOSE: typeof Symbol.asyncDispose | undefined =\n typeof Symbol.asyncDispose === \"symbol\" ? Symbol.asyncDispose : undefined;\n\n/**\n * `Symbol.asyncDispose`'s type where the ambient declarations define it, and\n * `never` where they do not.\n *\n * `never` is the load-bearing half: it turns {@link AsyncDisposeMember} into the\n * empty object, so the member simply is not there for a consumer whose `lib`\n * and `@types` never declared the symbol in the first place.\n */\nexport type AsyncDisposeKey = SymbolConstructor extends {\n readonly asyncDispose: infer Key extends symbol;\n}\n ? Key\n : never;\n\n/**\n * `{ [Symbol.asyncDispose](): Promise<void> }` where the symbol is typed, and\n * `{}` where it is not — the graceful-degradation carrier for every viborm type\n * that participates in `await using`.\n */\nexport type AsyncDisposeMember = {\n [Key in AsyncDisposeKey]: () => Promise<void>;\n};\n","/** Internal execution-kind metadata for prepared batch queries. */\n\nconst VERBATIM_BATCH_QUERY = Symbol(\"viborm.verbatimBatchQuery\");\n\n/** Mark a prepared raw statement that must retain verbatim driver semantics. */\nexport function markVerbatimBatchQuery<T extends object>(query: T): T {\n Object.defineProperty(query, VERBATIM_BATCH_QUERY, {\n configurable: false,\n enumerable: false,\n value: true,\n writable: false,\n });\n return query;\n}\n\n/** Whether a prepared statement came from an unsafe or legacy raw call. */\nexport function isVerbatimBatchQuery(query: object): boolean {\n return Reflect.get(query, VERBATIM_BATCH_QUERY) === true;\n}\n","import { Sql } from \"@sql\";\n\nconst preparedStatements = new WeakMap<object, Sql>();\n\n/** Retain the typed Sql behind a rendered batch query without publishing it. */\nexport function registerPreparedStatement(query: object, statement: Sql): void {\n preparedStatements.set(query, statement);\n}\n\n/** Preserve private provenance when an internal owner snapshots a batch query. */\nexport function transferPreparedStatement<Output extends object>(\n source: object,\n output: Output\n): Output {\n const statement = preparedStatements.get(source);\n if (statement !== undefined) preparedStatements.set(output, statement);\n return output;\n}\n\n/** Preserve provenance with the exact detached values a batch will execute. */\nexport function snapshotPreparedStatement<Output extends object>(\n source: object,\n output: Output,\n values: readonly unknown[]\n): Output {\n const statement = preparedStatements.get(source);\n if (statement !== undefined) {\n preparedStatements.set(\n output,\n new Sql([...statement.strings], [...values])\n );\n }\n return output;\n}\n\n/** Read provenance only at the trusted typed-statement execution boundary. */\nexport function readPreparedStatement(query: object): Sql | undefined {\n return preparedStatements.get(query);\n}\n","import { QueryError, VibORMErrorCode } from \"@errors\";\nimport { isDate } from \"@validation/value-guards\";\nimport type { QueryExecutionContext } from \"./types\";\n\ntype InvalidRawDateError = (parameterIndex: number) => Error;\ntype UnsupportedRawArrayError = (parameterIndex: number) => Error;\n\ninterface RawParameterErrors {\n readonly invalidDate: InvalidRawDateError;\n readonly unsupportedArray: UnsupportedRawArrayError;\n}\n\ninterface RawParameterEdge {\n readonly descriptor: PropertyDescriptor;\n readonly key: PropertyKey;\n readonly value: unknown;\n}\n\ninterface RawParameterNode {\n readonly edges: readonly RawParameterEdge[];\n readonly isArray: boolean;\n readonly properties: readonly RawParameterProperty[];\n readonly prototype: object | null;\n readonly source: object;\n}\n\ninterface RawParameterProperty {\n readonly descriptor: PropertyDescriptor;\n readonly key: PropertyKey;\n}\n\ninterface RawParameterGraph {\n readonly dateTimes: WeakMap<object, number>;\n readonly nodes: readonly RawParameterNode[];\n readonly roots: readonly unknown[];\n}\n\ntype RawParameterNodeAnalysis =\n | { readonly kind: \"node\"; readonly shape: Omit<RawParameterNode, \"source\"> }\n | { readonly kind: \"opaque\" }\n | { readonly kind: \"unsupported-array\" };\n\nconst arrayIndex = /^(?:0|[1-9]\\d*)$/;\nconst maximumArrayIndex = 4_294_967_294;\n\ninterface BuiltinPrototypeProperty {\n readonly descriptor: PropertyDescriptor;\n readonly key: PropertyKey;\n}\n\nfunction captureBuiltinPrototype(\n prototype: object\n): readonly BuiltinPrototypeProperty[] {\n const properties: BuiltinPrototypeProperty[] = [];\n for (const key of Reflect.ownKeys(prototype)) {\n const descriptor = Object.getOwnPropertyDescriptor(prototype, key);\n if (descriptor) properties.push({ descriptor, key });\n }\n return Object.freeze(properties);\n}\n\nconst objectPrototypeShape = captureBuiltinPrototype(Object.prototype);\nconst arrayPrototypeShape = captureBuiltinPrototype(Array.prototype);\n\nfunction isArrayIndex(key: PropertyKey): boolean {\n if (typeof key !== \"string\" || !arrayIndex.test(key)) return false;\n const index = Number(key);\n return index <= maximumArrayIndex && String(index) === key;\n}\n\nfunction functionSource(value: unknown): string | undefined {\n if (typeof value !== \"function\") return;\n try {\n return Function.prototype.toString.call(value);\n } catch {\n return;\n }\n}\n\nfunction sameInertRecord(left: unknown, right: unknown): boolean {\n if (\n left === null ||\n right === null ||\n typeof left !== \"object\" ||\n typeof right !== \"object\"\n ) {\n return Object.is(left, right);\n }\n try {\n if (\n Object.getPrototypeOf(left) !== null ||\n Object.getPrototypeOf(right) !== null\n ) {\n return false;\n }\n const leftKeys = Reflect.ownKeys(left);\n const rightKeys = Reflect.ownKeys(right);\n if (leftKeys.length !== rightKeys.length) return false;\n for (let index = 0; index < rightKeys.length; index += 1) {\n const leftKey = leftKeys[index];\n const rightKey = rightKeys[index];\n if (leftKey !== rightKey || rightKey === undefined) return false;\n const leftDescriptor = Object.getOwnPropertyDescriptor(left, rightKey);\n const rightDescriptor = Object.getOwnPropertyDescriptor(right, rightKey);\n if (\n leftDescriptor === undefined ||\n rightDescriptor === undefined ||\n !(\"value\" in leftDescriptor) ||\n !(\"value\" in rightDescriptor) ||\n leftDescriptor.configurable !== rightDescriptor.configurable ||\n leftDescriptor.enumerable !== rightDescriptor.enumerable ||\n leftDescriptor.writable !== rightDescriptor.writable ||\n !Object.is(leftDescriptor.value, rightDescriptor.value)\n ) {\n return false;\n }\n }\n return true;\n } catch {\n return false;\n }\n}\n\nfunction sameBuiltinDescriptor(\n actual: PropertyDescriptor,\n expected: PropertyDescriptor\n): boolean {\n if (\n actual.configurable !== expected.configurable ||\n actual.enumerable !== expected.enumerable ||\n \"value\" in actual !== \"value\" in expected\n ) {\n return false;\n }\n if (\"value\" in actual && \"value\" in expected) {\n if (actual.writable !== expected.writable) return false;\n const expectedSource = functionSource(expected.value);\n if (expectedSource !== undefined) {\n return functionSource(actual.value) === expectedSource;\n }\n return sameInertRecord(actual.value, expected.value);\n }\n return (\n functionSource(actual.get) === functionSource(expected.get) &&\n functionSource(actual.set) === functionSource(expected.set)\n );\n}\n\nfunction hasBuiltinPrototypeShape(\n prototype: object,\n shape: readonly BuiltinPrototypeProperty[]\n): boolean {\n try {\n const keys = Reflect.ownKeys(prototype);\n if (keys.length !== shape.length) return false;\n for (let index = 0; index < shape.length; index += 1) {\n const expected = shape[index];\n if (expected === undefined || keys[index] !== expected.key) return false;\n const actual = Object.getOwnPropertyDescriptor(prototype, expected.key);\n if (\n actual === undefined ||\n !sameBuiltinDescriptor(actual, expected.descriptor)\n ) {\n return false;\n }\n }\n return true;\n } catch {\n return false;\n }\n}\n\nfunction isObjectPrototype(prototype: object): boolean {\n try {\n return (\n Object.getPrototypeOf(prototype) === null &&\n hasBuiltinPrototypeShape(prototype, objectPrototypeShape)\n );\n } catch {\n return false;\n }\n}\n\nfunction isArrayPrototype(prototype: object): boolean {\n try {\n const parent = Object.getPrototypeOf(prototype);\n return (\n parent !== null &&\n isObjectPrototype(parent) &&\n hasBuiltinPrototypeShape(prototype, arrayPrototypeShape)\n );\n } catch {\n return false;\n }\n}\n\n/** Only arrays and records with inert inherited behavior are interpreted. */\nfunction rawParameterNodeShape(value: object): RawParameterNodeAnalysis {\n let isArray = false;\n try {\n isArray = Array.isArray(value);\n const prototype = Object.getPrototypeOf(value);\n if (\n (isArray && prototype !== null && !isArrayPrototype(prototype)) ||\n (!isArray && prototype !== null && !isObjectPrototype(prototype))\n ) {\n return { kind: isArray ? \"unsupported-array\" : \"opaque\" };\n }\n\n const edges: RawParameterEdge[] = [];\n const properties: RawParameterProperty[] = [];\n for (const key of Reflect.ownKeys(value)) {\n const descriptor = Object.getOwnPropertyDescriptor(value, key);\n if (descriptor === undefined) continue;\n properties.push({ descriptor, key });\n const isProviderVisible = isArray\n ? isArrayIndex(key)\n : descriptor.enumerable && typeof key === \"string\";\n if (!isProviderVisible) continue;\n if (!(\"value\" in descriptor)) {\n return { kind: isArray ? \"unsupported-array\" : \"opaque\" };\n }\n edges.push({ descriptor, key, value: descriptor.value });\n }\n const toJSON = properties.find((property) => property.key === \"toJSON\");\n if (\n toJSON &&\n (!(\"value\" in toJSON.descriptor) ||\n typeof toJSON.descriptor.value === \"function\")\n ) {\n return { kind: isArray ? \"unsupported-array\" : \"opaque\" };\n }\n return {\n kind: \"node\",\n shape: { edges, isArray, properties, prototype },\n };\n } catch {\n // An exotic record owns its traversal semantics. If reflection refuses an\n // array shape, it cannot safely reach provider array semantics.\n return { kind: isArray ? \"unsupported-array\" : \"opaque\" };\n }\n}\n\nfunction rawDateTime(\n value: unknown,\n parameterIndex: number,\n invalidDateError: InvalidRawDateError\n): number | undefined {\n if (!isDate(value)) return;\n const time = Date.prototype.getTime.call(value);\n if (Number.isNaN(time)) throw invalidDateError(parameterIndex);\n return time;\n}\n\nfunction analyzeRawParameterGraph(\n params: readonly unknown[],\n errors: RawParameterErrors\n): RawParameterGraph {\n const nodesBySource = new WeakMap<object, RawParameterNode>();\n const dateTimes = new WeakMap<object, number>();\n const nodes: RawParameterNode[] = [];\n const roots = new Array<unknown>(params.length);\n\n const discover = (\n value: unknown,\n parameterIndex: number\n ): RawParameterNode | undefined => {\n const time = rawDateTime(value, parameterIndex, errors.invalidDate);\n if (time !== undefined && typeof value === \"object\" && value !== null) {\n dateTimes.set(value, time);\n return;\n }\n if (typeof value !== \"object\" || value === null) return;\n\n const known = nodesBySource.get(value);\n if (known) return known;\n const analysis = rawParameterNodeShape(value);\n if (analysis.kind === \"unsupported-array\") {\n throw errors.unsupportedArray(parameterIndex);\n }\n if (analysis.kind === \"opaque\") return;\n const node: RawParameterNode = {\n ...analysis.shape,\n source: value,\n };\n nodesBySource.set(value, node);\n nodes.push(node);\n return node;\n };\n\n for (\n let parameterIndex = 0;\n parameterIndex < params.length;\n parameterIndex++\n ) {\n if (!Object.hasOwn(params, parameterIndex)) continue;\n const root = params[parameterIndex];\n roots[parameterIndex] = root;\n const rootTime = rawDateTime(root, parameterIndex, errors.invalidDate);\n if (rootTime !== undefined && typeof root === \"object\" && root !== null) {\n dateTimes.set(root, rootTime);\n continue;\n }\n const rootNode = discover(root, parameterIndex);\n if (!rootNode) continue;\n\n const pending = [rootNode];\n let cursor = 0;\n while (cursor < pending.length) {\n const node = pending[cursor];\n cursor += 1;\n if (!node) continue;\n for (const edge of node.edges) {\n const before = nodes.length;\n const child = discover(edge.value, parameterIndex);\n if (child && nodes.length > before) pending.push(child);\n }\n }\n }\n\n return { dateTimes, nodes, roots };\n}\n\n/** Validate every interpreted raw parameter before query interception. */\nexport function validateRawParameters(\n params: readonly unknown[],\n errors: RawParameterErrors\n): void {\n analyzeRawParameterGraph(params, errors);\n}\n\n/**\n * Snapshot every admitted data-descriptor JSON container, preserving aliases,\n * cycles, and property descriptors. Foreign built-in containers normalize to\n * local prototypes. Custom record carriers and provider-native objects remain\n * opaque; arrays with custom provider-visible behavior are refused. A Proxy\n * can run reflection traps while presenting an admitted container shape; the\n * captured descriptor view, never the later mutable Proxy, reaches dispatch.\n */\nfunction snapshotRawParameterGraph(\n params: readonly unknown[],\n errors: RawParameterErrors\n): unknown[] {\n const graph = analyzeRawParameterGraph(params, errors);\n const copies = new WeakMap<object, object>();\n const copiedDates = new WeakMap<object, Date>();\n\n for (const node of graph.nodes) {\n const copy: object = node.isArray ? [] : {};\n if (node.prototype === null) Object.setPrototypeOf(copy, null);\n copies.set(node.source, copy);\n }\n\n const copiedValue = (value: unknown): unknown => {\n if (typeof value !== \"object\" || value === null) return value;\n const time = graph.dateTimes.get(value);\n if (time !== undefined) {\n const known = copiedDates.get(value);\n if (known) return known;\n const copy = new Date(time);\n copiedDates.set(value, copy);\n return copy;\n }\n return copies.get(value) ?? value;\n };\n\n for (const node of graph.nodes) {\n const copy = copies.get(node.source);\n if (!copy) continue;\n for (const property of node.properties) {\n if (node.isArray && property.key === \"length\") continue;\n const descriptor = property.descriptor;\n Object.defineProperty(\n copy,\n property.key,\n \"value\" in descriptor &&\n (node.isArray\n ? isArrayIndex(property.key)\n : descriptor.enumerable && typeof property.key === \"string\")\n ? { ...descriptor, value: copiedValue(descriptor.value) }\n : descriptor\n );\n }\n if (node.isArray) {\n const length = node.properties.find(\n (property) => property.key === \"length\"\n );\n if (length) Object.defineProperty(copy, \"length\", length.descriptor);\n }\n }\n\n const snapshot = new Array<unknown>(graph.roots.length);\n for (let index = 0; index < graph.roots.length; index++) {\n if (!Object.hasOwn(graph.roots, index)) continue;\n snapshot[index] = copiedValue(graph.roots[index]);\n }\n return snapshot;\n}\n\nfunction invalidProviderDateError(\n context: QueryExecutionContext,\n parameterIndex: number\n): QueryError {\n return new QueryError(\n `Operation \"${context.operation ?? \"statement\"}\" received an invalid Date as bound parameter ${parameterIndex}. An invalid Date names no instant, so a provider either refuses the statement after dispatch or binds it as null.`,\n {\n code: VibORMErrorCode.INVALID_INPUT,\n meta: {\n parameterIndex,\n model: context.model,\n operation: context.operation,\n correlationId: context.correlationId,\n },\n }\n );\n}\n\nfunction unsupportedProviderArrayError(\n context: QueryExecutionContext,\n parameterIndex: number\n): QueryError {\n return new QueryError(\n `Operation \"${context.operation ?? \"statement\"}\" received raw array parameter ${parameterIndex} with custom inherited or accessor behavior. VibORM cannot validate that behavior without invoking caller code before dispatch.`,\n {\n code: VibORMErrorCode.INVALID_INPUT,\n meta: {\n parameterIndex,\n model: context.model,\n operation: context.operation,\n correlationId: context.correlationId,\n },\n }\n );\n}\n\n/**\n * Preserve the raw Date admission invariant after the last trusted statement\n * transform. Non-raw statements keep the old shallow-copy path: their typed\n * inputs were validated upstream, and statement transforms are trusted. Raw\n * Date leaves are revalidated and every admitted data-descriptor array or\n * ordinary JSON record is detached. Reflection does not invoke accessors,\n * iterators, or `toJSON`; a Proxy may run its reflection traps, so its captured\n * descriptor view is the stable provider value. Arrays with custom inherited\n * or accessor behavior are refused. Custom record and provider-native carriers\n * remain opaque and are not traversed.\n */\nexport function snapshotProviderParameters(\n params: readonly unknown[],\n context: QueryExecutionContext\n): unknown[] {\n if (context.model !== \"$raw\") return [...params];\n return snapshotRawParameterGraph(params, {\n invalidDate: (parameterIndex) =>\n invalidProviderDateError(context, parameterIndex),\n unsupportedArray: (parameterIndex) =>\n unsupportedProviderArrayError(context, parameterIndex),\n });\n}\n","import { QueryError } from \"@errors\";\nimport type { QueryResult } from \"./types\";\n\nexport interface NormalizedResultContext {\n provider: string;\n operation: string;\n model?: string;\n correlationId?: string;\n}\n\nexport function createNormalizedResultMeta(\n context: NormalizedResultContext\n): Record<string, unknown> {\n return {\n driver: context.provider,\n operation: context.operation,\n ...(context.model ? { model: context.model } : {}),\n ...(context.correlationId ? { correlationId: context.correlationId } : {}),\n };\n}\n\nconst NON_NEGATIVE_DECIMAL_REGEX = /^(?:0|[1-9]\\d*)$/;\n\nexport function normalizeProviderRowCount(\n value: unknown,\n context: NormalizedResultContext,\n options?: { allowDecimalString?: boolean; nullValue?: number }\n): number {\n let normalized = value === null ? options?.nullValue : value;\n if (\n options?.allowDecimalString === true &&\n typeof normalized === \"string\" &&\n NON_NEGATIVE_DECIMAL_REGEX.test(normalized)\n ) {\n normalized = Number(normalized);\n }\n if (\n typeof normalized !== \"number\" ||\n !Number.isSafeInteger(normalized) ||\n normalized < 0\n ) {\n throw new QueryError(\n `Driver \"${context.provider}\" returned a malformed row count for operation \"${context.operation}\".`,\n {\n meta: createNormalizedResultMeta(context),\n }\n );\n }\n return normalized;\n}\n\nexport function normalizeProviderInsertId(\n value: unknown,\n context: NormalizedResultContext,\n options?: { allowNumber?: boolean }\n): number | bigint | undefined {\n if (typeof value === \"string\") {\n if (!NON_NEGATIVE_DECIMAL_REGEX.test(value)) {\n throw malformedInsertId(context);\n }\n return value === \"0\" ? undefined : BigInt(value);\n }\n if (options?.allowNumber === true && typeof value === \"number\") {\n if (!Number.isSafeInteger(value) || value < 0) {\n throw malformedInsertId(context);\n }\n return value === 0 ? undefined : value;\n }\n throw malformedInsertId(context);\n}\n\nfunction malformedInsertId(context: NormalizedResultContext): QueryError {\n return new QueryError(\n `Driver \"${context.provider}\" returned a malformed insert id for operation \"${context.operation}\".`,\n {\n meta: createNormalizedResultMeta(context),\n }\n );\n}\n\nfunction malformedNormalizedResult(\n context: NormalizedResultContext,\n resultIndex?: number\n): QueryError {\n const position =\n resultIndex === undefined ? \"\" : ` at batch result index ${resultIndex}`;\n return new QueryError(\n `Driver \"${context.provider}\" returned a malformed normalized result for operation \"${context.operation}\"${position}; expected { rows: object[], rowCount: safe non-negative integer }.`,\n {\n meta: {\n ...createNormalizedResultMeta(context),\n ...(resultIndex === undefined ? {} : { resultIndex }),\n },\n }\n );\n}\n\nexport function isNormalizedResultRow(\n value: unknown\n): value is Record<string, unknown> {\n return (\n typeof value === \"object\" &&\n value !== null &&\n Object.prototype.toString.call(value) === \"[object Object]\"\n );\n}\n\nfunction hasNormalizedRows(value: unknown): value is Record<string, unknown>[] {\n if (!Array.isArray(value)) return false;\n for (let index = 0; index < value.length; index += 1) {\n if (!(Object.hasOwn(value, index) && isNormalizedResultRow(value[index]))) {\n return false;\n }\n }\n return true;\n}\n\n/**\n * Assert the single cross-driver success contract. Empty row arrays and a\n * rowCount of zero are valid; missing fields, non-record rows, and invented\n * counts are not.\n */\nexport function assertNormalizedQueryResult(\n result: QueryResult<unknown> | undefined,\n context: NormalizedResultContext,\n resultIndex?: number\n): void {\n const hasValidInsertId =\n result?.insertId === undefined ||\n (typeof result.insertId === \"bigint\" && result.insertId >= 0n) ||\n (typeof result.insertId === \"number\" &&\n Number.isFinite(result.insertId) &&\n Number.isSafeInteger(result.insertId) &&\n result.insertId >= 0);\n if (\n !(isNormalizedResultRow(result) && hasNormalizedRows(result.rows)) ||\n typeof result.rowCount !== \"number\" ||\n !Number.isFinite(result.rowCount) ||\n !Number.isSafeInteger(result.rowCount) ||\n result.rowCount < 0 ||\n !hasValidInsertId\n ) {\n throw malformedNormalizedResult(context, resultIndex);\n }\n}\n\n/**\n * Native and planned batches must return one normalized result for each\n * submitted statement, in the same order.\n */\nexport function assertNormalizedBatchResults(\n results: readonly QueryResult<unknown>[],\n expectedStatementCount: number,\n context: NormalizedResultContext\n): void {\n if (!Array.isArray(results) || results.length !== expectedStatementCount) {\n const actualResultCount = Array.isArray(results) ? results.length : 0;\n throw new QueryError(\n `Driver \"${context.provider}\" returned ${actualResultCount} results for operation \"${context.operation}\"; expected ${expectedStatementCount}, one per statement.`,\n {\n meta: {\n ...createNormalizedResultMeta(context),\n expectedStatementCount,\n actualResultCount,\n },\n }\n );\n }\n\n for (let resultIndex = 0; resultIndex < results.length; resultIndex += 1) {\n assertNormalizedQueryResult(results[resultIndex], context, resultIndex);\n }\n}\n"],"mappings":"iNA0BA,MAAa,EACX,OAAO,OAAO,cAAiB,SAAW,OAAO,aAAe,IAAA,GCzB5D,EAAuB,OAAO,4BAA4B,CAGhE,SAAgB,uBAAyC,EAAa,CAOpE,OANA,OAAO,eAAe,EAAO,EAAsB,CACjD,aAAc,GACd,WAAY,GACZ,MAAO,GACP,SAAU,GACX,CAAC,CACK,EAIT,SAAgB,qBAAqB,EAAwB,CAC3D,OAAO,QAAQ,IAAI,EAAO,EAAqB,GAAK,GCftD,MAAM,EAAqB,IAAI,QAG/B,SAAgB,0BAA0B,EAAe,EAAsB,CAC7E,EAAmB,IAAI,EAAO,EAAU,CAI1C,SAAgB,0BACd,EACA,EACQ,CACR,IAAM,EAAY,EAAmB,IAAI,EAAO,CAEhD,OADI,IAAc,IAAA,IAAW,EAAmB,IAAI,EAAQ,EAAU,CAC/D,EAIT,SAAgB,0BACd,EACA,EACA,EACQ,CACR,IAAM,EAAY,EAAmB,IAAI,EAAO,CAOhD,OANI,IAAc,IAAA,IAChB,EAAmB,IACjB,EACA,IAAI,EAAI,CAAC,GAAG,EAAU,QAAQ,CAAE,CAAC,GAAG,EAAO,CAAC,CAC7C,CAEI,EAIT,SAAgB,sBAAsB,EAAgC,CACpE,OAAO,EAAmB,IAAI,EAAM,CC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QT,SAAgB,4BACd,EACA,EACA,EACM,CACN,IAAM,EACJ,GAAQ,WAAa,IAAA,IACpB,OAAO,EAAO,UAAa,UAAY,EAAO,UAAY,IAC1D,OAAO,EAAO,UAAa,UAC1B,OAAO,SAAS,EAAO,SAAS,EAChC,OAAO,cAAc,EAAO,SAAS,EACrC,EAAO,UAAY,EACvB,GACE,EAAE,sBAAsB,EAAO,EAAI,kBAAkB,EAAO,KAAK,GACjE,OAAO,EAAO,UAAa,UAC3B,CAAC,OAAO,SAAS,EAAO,SAAS,EACjC,CAAC,OAAO,cAAc,EAAO,SAAS,EACtC,EAAO,SAAW,GAClB,CAAC,EAED,MAAM,0BAA0B,EAAS,EAAY,CAQzD,SAAgB,6BACd,EACA,EACA,EACM,CACN,GAAI,CAAC,MAAM,QAAQ,EAAQ,EAAI,EAAQ,SAAW,EAAwB,CACxE,IAAM,EAAoB,MAAM,QAAQ,EAAQ,CAAG,EAAQ,OAAS,EACpE,MAAM,IAAI,EACR,WAAW,EAAQ,SAAS,aAAa,EAAkB,0BAA0B,EAAQ,UAAU,cAAc,EAAuB,sBAC5I,CACE,KAAM,CACJ,GAAG,2BAA2B,EAAQ,CACtC,yBACA,oBACD,CACF,CACF,CAGH,IAAK,IAAI,EAAc,EAAG,EAAc,EAAQ,OAAQ,GAAe,EACrE,4BAA4B,EAAQ,GAAc,EAAS,EAAY"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { Mn as Dialect, Un as AnyModel } from "./index-Ci8b13Lm.mjs";
|
|
2
|
-
import { i as ResolveCallback, t as MigrationClient } from "./planner-
|
|
2
|
+
import { i as ResolveCallback, t as MigrationClient } from "./planner-BDLdDieE.mjs";
|
|
3
3
|
import { i as Sha256, n as MigrationStorageWriter, r as PublishResult } from "./contract-Dw0FR78e.mjs";
|
|
4
|
-
import { B as MigrationCheckInput, V as MigrationDecisionV1 } from "./client-
|
|
4
|
+
import { B as MigrationCheckInput, V as MigrationDecisionV1 } from "./client-DyIsSin0.mjs";
|
|
5
5
|
|
|
6
6
|
//#region src/adapters/databases/sqlite/storage/datetime.d.ts
|
|
7
7
|
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{n as e}from"./chunk-BuuaeEvq.mjs";import{n as t}from"./base-
|
|
2
|
-
//# sourceMappingURL=object-store-
|
|
1
|
+
import{n as e}from"./chunk-BuuaeEvq.mjs";import{n as t}from"./base-wlv81COV.mjs";import{t as n}from"./migrations-OE5D32qo.mjs";import{n as r}from"./canonical-json-JLUMrnoq.mjs";import{a as i}from"./identity-Bu6jbgym.mjs";function refuseWorkersKvWritable(){throw new n(`Workers KV cannot be a V1 estate writer: listing is eventually consistent and puts are not conditional`,t.MIGRATION_UNSUPPORTED_PROVIDER)}var ObjectStoreEstateStorage=class{store;constructor(e){this.store=e}async readEstate(){return this.store.get(`estate.json`)}async listStates(){return this.listHex(`states/`,`.json`)}async listSnapshots(){return this.listHex(`snapshots/`,`.json`)}async listSql(){return this.listHex(`sql/`,`.sql`)}async readState(e){return this.store.get(`states/${e}.json`)}async readSnapshot(e){return this.store.get(`snapshots/${e}.json`)}async readSql(e){return this.store.get(`sql/${e}.sql`)}async publishEstate(e){return this.publish(`estate.json`,e)}async publishSnapshot(e,t){return this.publish(`snapshots/${e}.json`,t)}async publishSql(e,t){return this.publish(`sql/${e}.sql`,t)}async publishState(e,r){if(!i(e))throw new n(`State id is not a SHA-256 digest`,t.MIGRATION_INVALID_ESTATE);return this.publish(`states/${e}.json`,r)}async publish(e,i){if(await this.store.putIfAbsent(e,i)===`created`)return{outcome:`created`};let a=await this.store.get(e);if(!(a&&r(a,i)))throw new n(`Object-store key ${e} already holds different bytes`,t.MIGRATION_CORRUPTION);return{outcome:`identical`}}async listHex(e,t){let n=await this.store.list(e),r=[];for(let a of n){let n=a.slice(e.length);if(!n.endsWith(t))continue;let o=n.slice(0,-t.length);i(o)&&r.push(o)}return r.sort()}},MemoryConditionalObjectStore=class{objects=new Map;async putIfAbsent(e,t){return this.objects.has(e)?`exists`:(this.objects.set(e,t.slice()),`created`)}async get(e){let t=this.objects.get(e);return t?t.slice():null}async list(e){return[...this.objects.keys()].filter(t=>t.startsWith(e)).sort()}};export{ObjectStoreEstateStorage as n,refuseWorkersKvWritable as r,MemoryConditionalObjectStore as t};
|
|
2
|
+
//# sourceMappingURL=object-store-I1MyfM72.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"object-store-
|
|
1
|
+
{"version":3,"file":"object-store-I1MyfM72.mjs","names":[],"sources":["../src/migrations/storage/object-store.ts"],"sourcesContent":["/**\n * Strong object-store publication contract.\n * A writable driver that cannot do conditional create is not a V1 estate owner.\n * Workers KV is refused here: it has no compare-and-swap publication.\n */\n\nimport { MigrationError, VibORMErrorCode } from \"../../errors\";\nimport { bytesEqual } from \"../canonical-json\";\nimport { isSha256, type Sha256 } from \"../identity\";\nimport type { MigrationStorageWriter, PublishResult } from \"./contract\";\n\nexport function refuseWorkersKvWritable(): never {\n throw new MigrationError(\n \"Workers KV cannot be a V1 estate writer: listing is eventually consistent and puts are not conditional\",\n VibORMErrorCode.MIGRATION_UNSUPPORTED_PROVIDER\n );\n}\n\nexport interface ObjectStoreConditionalPut {\n putIfAbsent(key: string, bytes: Uint8Array): Promise<\"created\" | \"exists\">;\n get(key: string): Promise<Uint8Array | null>;\n list(prefix: string): Promise<readonly string[]>;\n}\n\n/**\n * Estate writer over a strongly consistent object store with if-none-match\n * publication. Manifests become visible only after referenced bytes exist.\n */\nexport class ObjectStoreEstateStorage implements MigrationStorageWriter {\n private readonly store: ObjectStoreConditionalPut;\n\n constructor(store: ObjectStoreConditionalPut) {\n this.store = store;\n }\n\n async readEstate(): Promise<Uint8Array | null> {\n return this.store.get(\"estate.json\");\n }\n\n async listStates(): Promise<readonly Sha256[]> {\n return this.listHex(\"states/\", \".json\");\n }\n\n async listSnapshots(): Promise<readonly Sha256[]> {\n return this.listHex(\"snapshots/\", \".json\");\n }\n\n async listSql(): Promise<readonly Sha256[]> {\n return this.listHex(\"sql/\", \".sql\");\n }\n\n async readState(id: Sha256): Promise<Uint8Array | null> {\n return this.store.get(`states/${id}.json`);\n }\n\n async readSnapshot(hash: Sha256): Promise<Uint8Array | null> {\n return this.store.get(`snapshots/${hash}.json`);\n }\n\n async readSql(hash: Sha256): Promise<Uint8Array | null> {\n return this.store.get(`sql/${hash}.sql`);\n }\n\n async publishEstate(bytes: Uint8Array): Promise<PublishResult> {\n return this.publish(\"estate.json\", bytes);\n }\n\n async publishSnapshot(\n hash: Sha256,\n bytes: Uint8Array\n ): Promise<PublishResult> {\n return this.publish(`snapshots/${hash}.json`, bytes);\n }\n\n async publishSql(hash: Sha256, bytes: Uint8Array): Promise<PublishResult> {\n return this.publish(`sql/${hash}.sql`, bytes);\n }\n\n async publishState(id: Sha256, bytes: Uint8Array): Promise<PublishResult> {\n if (!isSha256(id)) {\n throw new MigrationError(\n \"State id is not a SHA-256 digest\",\n VibORMErrorCode.MIGRATION_INVALID_ESTATE\n );\n }\n return this.publish(`states/${id}.json`, bytes);\n }\n\n private async publish(\n key: string,\n bytes: Uint8Array\n ): Promise<PublishResult> {\n const result = await this.store.putIfAbsent(key, bytes);\n if (result === \"created\") return { outcome: \"created\" };\n const existing = await this.store.get(key);\n if (!(existing && bytesEqual(existing, bytes))) {\n throw new MigrationError(\n `Object-store key ${key} already holds different bytes`,\n VibORMErrorCode.MIGRATION_CORRUPTION\n );\n }\n return { outcome: \"identical\" };\n }\n\n private async listHex(prefix: string, suffix: string): Promise<Sha256[]> {\n const keys = await this.store.list(prefix);\n const hashes: Sha256[] = [];\n for (const key of keys) {\n const name = key.slice(prefix.length);\n if (!name.endsWith(suffix)) continue;\n const hex = name.slice(0, -suffix.length);\n if (isSha256(hex)) hashes.push(hex);\n }\n return hashes.sort();\n }\n}\n\n/** In-memory strong object store for the conformance fixture. */\nexport class MemoryConditionalObjectStore implements ObjectStoreConditionalPut {\n private readonly objects = new Map<string, Uint8Array>();\n\n async putIfAbsent(\n key: string,\n bytes: Uint8Array\n ): Promise<\"created\" | \"exists\"> {\n if (this.objects.has(key)) return \"exists\";\n this.objects.set(key, bytes.slice());\n return \"created\";\n }\n\n async get(key: string): Promise<Uint8Array | null> {\n const bytes = this.objects.get(key);\n return bytes ? bytes.slice() : null;\n }\n\n async list(prefix: string): Promise<readonly string[]> {\n return [...this.objects.keys()]\n .filter((key) => key.startsWith(prefix))\n .sort();\n }\n}\n"],"mappings":"6NAWA,SAAgB,yBAAiC,CAC/C,MAAM,IAAI,EACR,yGACA,EAAgB,+BACjB,CAaH,IAAa,yBAAb,KAAwE,CACtE,MAEA,YAAY,EAAkC,CAC5C,KAAK,MAAQ,EAGf,MAAM,YAAyC,CAC7C,OAAO,KAAK,MAAM,IAAI,cAAc,CAGtC,MAAM,YAAyC,CAC7C,OAAO,KAAK,QAAQ,UAAW,QAAQ,CAGzC,MAAM,eAA4C,CAChD,OAAO,KAAK,QAAQ,aAAc,QAAQ,CAG5C,MAAM,SAAsC,CAC1C,OAAO,KAAK,QAAQ,OAAQ,OAAO,CAGrC,MAAM,UAAU,EAAwC,CACtD,OAAO,KAAK,MAAM,IAAI,UAAU,EAAG,OAAO,CAG5C,MAAM,aAAa,EAA0C,CAC3D,OAAO,KAAK,MAAM,IAAI,aAAa,EAAK,OAAO,CAGjD,MAAM,QAAQ,EAA0C,CACtD,OAAO,KAAK,MAAM,IAAI,OAAO,EAAK,MAAM,CAG1C,MAAM,cAAc,EAA2C,CAC7D,OAAO,KAAK,QAAQ,cAAe,EAAM,CAG3C,MAAM,gBACJ,EACA,EACwB,CACxB,OAAO,KAAK,QAAQ,aAAa,EAAK,OAAQ,EAAM,CAGtD,MAAM,WAAW,EAAc,EAA2C,CACxE,OAAO,KAAK,QAAQ,OAAO,EAAK,MAAO,EAAM,CAG/C,MAAM,aAAa,EAAY,EAA2C,CACxE,GAAI,CAAC,EAAS,EAAG,CACf,MAAM,IAAI,EACR,mCACA,EAAgB,yBACjB,CAEH,OAAO,KAAK,QAAQ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LError=class extends a{static diagnosticName=`CacheInvalidTTLError`;constructor(e,t){super(e,i.CACHE_INVALID_TTL,t)}},CacheInvalidKeyError=class extends a{static diagnosticName=`CacheInvalidKeyError`;constructor(e,t){super(e,i.CACHE_INVALID_KEY,t)}},CacheOperationNotCacheableError=class extends a{static diagnosticName=`CacheOperationNotCacheableError`;constructor(e,t,n){super(`Operation "${e}" is not cacheable. Only read operations can be cached: ${t.join(`, `)}`,i.CACHE_OPERATION_NOT_CACHEABLE,{meta:{...n?.meta,operation:e}})}},CacheConfigurationError=class extends a{static diagnosticName=`CacheConfigurationError`;constructor(e,t){super(e,i.CACHE_CONFIGURATION,t)}};const o=new WeakMap,s=new WeakMap,c=new WeakMap,settleObserverReturn=()=>void 0;function getOfficialInstrumentationChainCapability(e){return e===void 0?void 0:c.get(e)}function registerOfficialInstrumentationChain(e,t){c.set(e,t)}function registerTrustedProtectedObserver(e,t,n){o.set(e,{capability:t,observer:n})}function getTrustedProtectedObserverCapability(e){return t(e)?o.get(e)?.capability:void 0}function selectTrustedObservers(e){let t=e?.find(({handler:e})=>o.has(e));return t===void 0?void 0:[t]}function prewarmProtectedObservers(e){if(!(e===void 0||e.length===0))for(let t of e){let e=o.get(t.handler);if(e===void 0)continue;let n=prewarmTrustedObserver(e.capability);if(n!==void 0)return n}}function readProtectedLifecycleFacts(e){return s.get(e)?.facts}function readProtectedLifecycleCompletionFacts(e){return s.get(e)?.completion}function runProtectedObservers(e,t,n,r,i){if(t===void 0||t.length===0)return n();let a=Date.now(),c=freezeLifecycleUnit(e),l=-1,u;for(let[e,n]of t.entries()){let t=o.get(n.handler);if(t!==void 0){l=e,u=t;break}}let d,f,p,m=u===void 0?void 0:new Promise(e=>{p=e}),h,g=u===void 0,_,v=!1,resolveOuterWhenReady=()=>{g&&h!==void 0&&p?.(h)},settleCompletion=(e,t)=>{let n=Math.max(0,Date.now()-a),i;try{i=r?.()?.commitCertainty}catch{i=void 0}let o=createCompletion(e,n,i,t);h=o;let l=s.get(c);if(l!==void 0)try{l.completion=l.facts.complete({status:e,durationMs:n,...e===`failure`?{failure:t}:{}})}catch{l.completion=void 0}d?.(o),resolveOuterWhenReady()},observeApplicationCompletion=()=>{v||f===void 0||_===void 0||(v=!0,_.then(()=>settleCompletion(`success`),e=>settleCompletion(`failure`,e)))},readCompletionPromise=()=>(f===void 0&&(f=new Promise(e=>{d=e})),observeApplicationCompletion(),f),startChild=()=>{let e;try{e=n()}catch(t){e=Promise.reject(t)}return _=e,observeApplicationCompletion(),e},startObserver=e=>{let n=t[e];if(n===void 0)return startChild();let r=o.get(n.handler);if(r!==void 0){if(i!==void 0)try{let e=i();e!==void 0&&s.set(c,{facts:e})}catch{}let t,n,a=new Promise((e,r)=>{t=e,n=r}),o=!1,startNext=()=>(o||(o=!0,startObserver(e+1).then(e=>t(e),e=>n(e))),readCompletionPromise()),l;try{l=r.observer(c,startNext)}catch{return startNext(),g=!0,resolveOuterWhenReady(),a}return Promise.resolve(l).then(()=>{o||startNext(),g=!0,resolveOuterWhenReady()},()=>{o||startNext(),g=!0,resolveOuterWhenReady()}),a}let a,startNextApplication=()=>(a===void 0&&(a=startObserver(e+1)),a),proceed=()=>(startNextApplication(),m!==void 0&&e<l?m:readCompletionPromise()),u;try{u=Reflect.apply(n.handler,void 0,[c,proceed])}catch{u=void 0}let d=startNextApplication();return consumeObserverReturn(u),d},y=i===void 0||u===void 0?void 0:prewarmTrustedObserver(u.capability);if(y===void 0)return startObserver(0);let b,x,S=new Promise((e,t)=>{b=e,x=t}),startAfterPrewarm=()=>{startObserver(0).then(e=>b(e),e=>x(e))};return y.then(startAfterPrewarm),S}function observeOperation(e,t,n,r,i,a){return runProtectedObservers({kind:`operation`,operation:t,...n===void 0?{}:{model:n}},e,r,i,a)}function observeStatement(e,t,n,r,i,a){return runProtectedObservers({kind:`statement`,...t===void 0?{}:{operation:t},...n===void 0||n===`$raw`?{}:{model:n}},e,r,i,a)}function observeDriverLifecycle(e,t,n,r,i,a){return runProtectedObservers({kind:e,...n===void 0?{}:{operation:n}},t,r,i,a)}function prewarmTrustedObserver(e){let t=e.prewarm;if(t===void 0)return;let n;try{n=t()}catch{return}if(n!==void 0)return Promise.resolve(n).then(()=>void 0,()=>void 0)}function freezeLifecycleUnit(e){return Object.freeze(e)}function consumeObserverReturn(e){if(!(e===null||typeof e!=`object`&&typeof e!=`function`))try{let n=Reflect.get(e,`then`);if(!t(n))return;Reflect.apply(n,e,[settleObserverReturn,settleObserverReturn])}catch{}}function createCompletion(e,t,n,r){let i=e===`failure`?summarizeFailure(r):void 0;return Object.freeze({status:e,durationMs:t,...i===void 0?{}:{error:i},...n===void 0?{}:{commitCertainty:n}})}function summarizeFailure(e){let t=r(n(e)?e:Error(`Application rejected with a non-Error value`)),i=Object.getOwnPropertyDescriptor(t,`code`)?.value;return Object.freeze({name:t.name,message:t.message,...typeof i==`string`?{code:i}:{}})}export{observeStatement as a,readProtectedLifecycleFacts as c,runProtectedObservers as d,selectTrustedObservers as f,CacheOperationNotCacheableError as g,CacheInvalidTTLError as h,observeOperation as i,registerOfficialInstrumentationChain as l,CacheInvalidKeyError as m,getTrustedProtectedObserverCapability as n,prewarmProtectedObservers as o,CacheConfigurationError as p,observeDriverLifecycle as r,readProtectedLifecycleCompletionFacts as s,getOfficialInstrumentationChainCapability as t,registerTrustedProtectedObserver as u};
|
|
2
|
+
//# sourceMappingURL=observation-BcT8Cs3d.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"observation-BcT8Cs3d.mjs","names":["resolveApplication","rejectApplication","applicationBridge"],"sources":["../src/errors/cache.ts","../src/extensions/observation.ts"],"sourcesContent":["import { VibORMError, VibORMErrorCode, type VibORMErrorMeta } from \"./base\";\n\n/**\n * Invalid TTL format or value\n */\nexport class CacheInvalidTTLError extends VibORMError {\n static override readonly diagnosticName = \"CacheInvalidTTLError\";\n\n /** Literal discriminant: this class always carries `CACHE_INVALID_TTL`. */\n declare readonly code: typeof VibORMErrorCode.CACHE_INVALID_TTL;\n\n constructor(message: string, options?: { meta?: VibORMErrorMeta }) {\n super(message, VibORMErrorCode.CACHE_INVALID_TTL, options);\n }\n}\n\n/**\n * Invalid cache key (circular reference, uncacheable type)\n */\nexport class CacheInvalidKeyError extends VibORMError {\n static override readonly diagnosticName = \"CacheInvalidKeyError\";\n\n /** Literal discriminant: this class always carries `CACHE_INVALID_KEY`. */\n declare readonly code: typeof VibORMErrorCode.CACHE_INVALID_KEY;\n\n constructor(message: string, options?: { meta?: VibORMErrorMeta }) {\n super(message, VibORMErrorCode.CACHE_INVALID_KEY, options);\n }\n}\n\n/**\n * Operation cannot be cached (e.g., mutation operations)\n */\nexport class CacheOperationNotCacheableError extends VibORMError {\n static override readonly diagnosticName = \"CacheOperationNotCacheableError\";\n\n /** Literal discriminant: this class always carries `CACHE_OPERATION_NOT_CACHEABLE`. */\n declare readonly code: typeof VibORMErrorCode.CACHE_OPERATION_NOT_CACHEABLE;\n\n constructor(\n operation: string,\n cacheableOperations: string[],\n options?: { meta?: VibORMErrorMeta }\n ) {\n super(\n `Operation \"${operation}\" is not cacheable. Only read operations can be cached: ${cacheableOperations.join(\", \")}`,\n VibORMErrorCode.CACHE_OPERATION_NOT_CACHEABLE,\n {\n meta: { ...options?.meta, operation },\n }\n );\n }\n}\n\n/**\n * Invalid or missing cache configuration (options or driver)\n */\nexport class CacheConfigurationError extends VibORMError {\n static override readonly diagnosticName = \"CacheConfigurationError\";\n\n /** Literal discriminant: this class always carries `CACHE_CONFIGURATION`. */\n declare readonly code: typeof VibORMErrorCode.CACHE_CONFIGURATION;\n\n constructor(\n message: string,\n options?: { cause?: Error | undefined; meta?: VibORMErrorMeta }\n ) {\n super(message, VibORMErrorCode.CACHE_CONFIGURATION, options);\n }\n}\n","import { sanitizeErrorForLogging } from \"@errors\";\nimport { isFunction } from \"@validation/value-guards\";\nimport { isError } from \"../errors/diagnostic-safety\";\nimport type { ResolvedExtensionChain, ResolvedExtensionHandler } from \"./chain\";\nimport type {\n OfficialLifecycleCompletionFacts,\n OfficialLifecycleFacts,\n OfficialLifecycleFactsReader,\n OfficialObservationCapability,\n} from \"./official-facts\";\n\n/** The exact public facts carried by each protected lifecycle boundary. */\nexport type LifecycleUnit =\n | Readonly<{\n kind: \"operation\";\n operation: string;\n model?: string;\n }>\n | Readonly<{\n kind: \"statement\";\n operation?: string;\n model?: string;\n }>\n | Readonly<{\n kind: \"batch\";\n operation: string;\n }>\n | Readonly<{\n kind: \"transaction\";\n operation?: string;\n }>\n | Readonly<{\n kind: \"savepoint\";\n operation?: string;\n }>\n | Readonly<{\n kind: \"connection\";\n operation?: string;\n }>\n | Readonly<{\n kind: \"cache\";\n operation: \"get\" | \"set\" | \"revalidate\" | \"invalidate\";\n }>;\n\nexport type LifecycleUnitKind = LifecycleUnit[\"kind\"];\n\nexport type CommitCertainty = \"committed\" | \"may-have-committed\";\n\nexport interface ObservationErrorSummary {\n readonly name: string;\n readonly message: string;\n readonly code?: string;\n}\n\nexport interface ObservationCompletion {\n readonly status: \"success\" | \"failure\";\n readonly durationMs: number;\n readonly error?: ObservationErrorSummary;\n readonly commitCertainty?: CommitCertainty;\n}\n\nexport interface ObservationCompletionFacts {\n readonly commitCertainty?: CommitCertainty;\n}\n\nexport type ObservationCompletionFactsReader = () =>\n | ObservationCompletionFacts\n | undefined;\n\nexport type ObservationUnit = LifecycleUnit;\n\nexport type ObserveHandler = (\n unit: ObservationUnit,\n proceed: () => Promise<ObservationCompletion>\n) => unknown;\n\ntype TrustedProtectedObserver = (\n unit: LifecycleUnit,\n proceed: () => Promise<ObservationCompletion>\n) => unknown;\n\ninterface TrustedProtectedObserverRegistration {\n readonly capability: OfficialObservationCapability;\n readonly observer: TrustedProtectedObserver;\n}\n\ninterface ProtectedLifecycleFactsState {\n readonly facts: OfficialLifecycleFacts;\n completion?: OfficialLifecycleCompletionFacts;\n}\n\nconst trustedObservers = new WeakMap<\n CallableFunction,\n TrustedProtectedObserverRegistration\n>();\nconst lifecycleFacts = new WeakMap<\n LifecycleUnit,\n ProtectedLifecycleFactsState\n>();\nconst officialCapabilitiesByChain = new WeakMap<\n ResolvedExtensionChain,\n OfficialObservationCapability\n>();\nconst settleObserverReturn = (): undefined => undefined;\n\n/** The one official capability registered for this exact chain, if any. */\nexport function getOfficialInstrumentationChainCapability(\n chain: ResolvedExtensionChain | undefined\n): OfficialObservationCapability | undefined {\n return chain === undefined\n ? undefined\n : officialCapabilitiesByChain.get(chain);\n}\n\n/** Bind the admitted official capability to one exact resolved chain. */\nexport function registerOfficialInstrumentationChain(\n chain: ResolvedExtensionChain,\n capability: OfficialObservationCapability\n): void {\n officialCapabilitiesByChain.set(chain, capability);\n}\n\n/** Register one package-owned observer identity without publishing a marker. */\nexport function registerTrustedProtectedObserver(\n handler: CallableFunction,\n capability: OfficialObservationCapability,\n observer: TrustedProtectedObserver\n): void {\n trustedObservers.set(handler, { capability, observer });\n}\n\n/** Recognize the exact package-owned handler identity and nothing else. */\nexport function getTrustedProtectedObserverCapability(\n handler: unknown\n): OfficialObservationCapability | undefined {\n return isFunction(handler)\n ? trustedObservers.get(handler)?.capability\n : undefined;\n}\n\n/**\n * The exact chain's one trusted observer, alone, or `undefined`. Dispatch\n * through it reaches no ordinary observer: cache backend delete/clear, which\n * have no public unit, run through the one runner this way.\n */\nexport function selectTrustedObservers(\n observers: readonly ResolvedExtensionHandler[] | undefined\n): readonly ResolvedExtensionHandler[] | undefined {\n const trusted = observers?.find(({ handler }) =>\n trustedObservers.has(handler)\n );\n return trusted === undefined ? undefined : [trusted];\n}\n\n/** Resolve the one trusted readiness once before a coordinated array starts. */\nexport function prewarmProtectedObservers(\n observers: readonly ResolvedExtensionHandler[] | undefined\n): void | Promise<void> {\n if (observers === undefined || observers.length === 0) return;\n for (const observer of observers) {\n const registration = trustedObservers.get(observer.handler);\n if (registration === undefined) continue;\n const readiness = prewarmTrustedObserver(registration.capability);\n if (readiness !== undefined) return readiness;\n }\n}\n\n/** Read facts only for the exact frozen unit created by this runner. */\nexport function readProtectedLifecycleFacts(\n unit: LifecycleUnit\n): OfficialLifecycleFacts | undefined {\n return lifecycleFacts.get(unit)?.facts;\n}\n\n/** Read completion facts projected by core after the child settled. */\nexport function readProtectedLifecycleCompletionFacts(\n unit: LifecycleUnit\n): OfficialLifecycleCompletionFacts | undefined {\n return lifecycleFacts.get(unit)?.completion;\n}\n\n/**\n * Runs completion-only observers without giving their onion authority over the\n * application promise.\n */\nexport function runProtectedObservers<Result>(\n unit: LifecycleUnit,\n observers: readonly ResolvedExtensionHandler[] | undefined,\n child: () => Promise<Result>,\n readCompletionFacts?: ObservationCompletionFactsReader,\n readInstrumentationFacts?: OfficialLifecycleFactsReader\n): Promise<Result> {\n if (observers === undefined || observers.length === 0) return child();\n\n const startedAt = Date.now();\n const immutableUnit = freezeLifecycleUnit(unit);\n let trustedIndex = -1;\n let trustedRegistration: TrustedProtectedObserverRegistration | undefined;\n for (const [index, observer] of observers.entries()) {\n const registration = trustedObservers.get(observer.handler);\n if (registration !== undefined) {\n trustedIndex = index;\n trustedRegistration = registration;\n break;\n }\n }\n let resolveCompletion:\n | ((completion: ObservationCompletion) => void)\n | undefined;\n let completionPromise: Promise<ObservationCompletion> | undefined;\n let resolveOuterCompletion:\n | ((completion: ObservationCompletion) => void)\n | undefined;\n const outerCompletionPromise =\n trustedRegistration === undefined\n ? undefined\n : new Promise<ObservationCompletion>((resolve) => {\n resolveOuterCompletion = resolve;\n });\n let settledCompletion: ObservationCompletion | undefined;\n let trustedSetupSettled = trustedRegistration === undefined;\n let applicationPromise: Promise<Result> | undefined;\n let observesApplicationCompletion = false;\n\n const resolveOuterWhenReady = (): void => {\n if (trustedSetupSettled && settledCompletion !== undefined) {\n resolveOuterCompletion?.(settledCompletion);\n }\n };\n\n const settleCompletion = (\n status: ObservationCompletion[\"status\"],\n failure?: unknown\n ): void => {\n const durationMs = Math.max(0, Date.now() - startedAt);\n let commitCertainty: CommitCertainty | undefined;\n try {\n commitCertainty = readCompletionFacts?.()?.commitCertainty;\n } catch {\n commitCertainty = undefined;\n }\n const completion = createCompletion(\n status,\n durationMs,\n commitCertainty,\n failure\n );\n settledCompletion = completion;\n const factsState = lifecycleFacts.get(immutableUnit);\n if (factsState !== undefined) {\n try {\n factsState.completion = factsState.facts.complete({\n status,\n durationMs,\n ...(status === \"failure\" ? { failure } : {}),\n });\n } catch {\n factsState.completion = undefined;\n }\n }\n resolveCompletion?.(completion);\n resolveOuterWhenReady();\n };\n\n const observeApplicationCompletion = (): void => {\n if (\n observesApplicationCompletion ||\n completionPromise === undefined ||\n applicationPromise === undefined\n ) {\n return;\n }\n observesApplicationCompletion = true;\n applicationPromise.then(\n () => settleCompletion(\"success\"),\n (failure: unknown) => settleCompletion(\"failure\", failure)\n );\n };\n\n const readCompletionPromise = (): Promise<ObservationCompletion> => {\n if (completionPromise === undefined) {\n completionPromise = new Promise<ObservationCompletion>((resolve) => {\n resolveCompletion = resolve;\n });\n }\n observeApplicationCompletion();\n return completionPromise;\n };\n\n const startChild = (): Promise<Result> => {\n let started: Promise<Result>;\n try {\n started = child();\n } catch (failure) {\n started = Promise.reject(failure);\n }\n applicationPromise = started;\n observeApplicationCompletion();\n return started;\n };\n\n const startObserver = (index: number): Promise<Result> => {\n const observer = observers[index];\n if (observer === undefined) return startChild();\n\n const trustedObserver = trustedObservers.get(observer.handler);\n if (trustedObserver !== undefined) {\n if (readInstrumentationFacts !== undefined) {\n try {\n const facts = readInstrumentationFacts();\n if (facts !== undefined) lifecycleFacts.set(immutableUnit, { facts });\n } catch {\n // Instrumentation fact production cannot stop the application.\n }\n }\n // Promise executors run synchronously; TypeScript does not model that guarantee.\n let resolveApplication!: (value: Result | PromiseLike<Result>) => void;\n let rejectApplication!: (reason?: unknown) => void;\n const applicationBridge = new Promise<Result>((resolve, reject) => {\n resolveApplication = resolve;\n rejectApplication = reject;\n });\n let proceeded = false;\n const startNext = (): Promise<ObservationCompletion> => {\n if (!proceeded) {\n proceeded = true;\n startObserver(index + 1).then(\n (value) => resolveApplication(value),\n (failure: unknown) => rejectApplication(failure)\n );\n }\n return readCompletionPromise();\n };\n let setup: unknown;\n try {\n setup = trustedObserver.observer(immutableUnit, startNext);\n } catch {\n startNext();\n trustedSetupSettled = true;\n resolveOuterWhenReady();\n return applicationBridge;\n }\n Promise.resolve(setup).then(\n () => {\n if (!proceeded) startNext();\n trustedSetupSettled = true;\n resolveOuterWhenReady();\n },\n () => {\n if (!proceeded) startNext();\n trustedSetupSettled = true;\n resolveOuterWhenReady();\n }\n );\n return applicationBridge;\n }\n\n let nextApplicationPromise: Promise<Result> | undefined;\n const startNextApplication = (): Promise<Result> => {\n if (nextApplicationPromise === undefined) {\n nextApplicationPromise = startObserver(index + 1);\n }\n return nextApplicationPromise;\n };\n const proceed = (): Promise<ObservationCompletion> => {\n startNextApplication();\n return outerCompletionPromise !== undefined && index < trustedIndex\n ? outerCompletionPromise\n : readCompletionPromise();\n };\n\n let returned: unknown;\n try {\n returned = Reflect.apply(observer.handler, undefined, [\n immutableUnit,\n proceed,\n ]);\n } catch {\n returned = undefined;\n }\n const nextApplication = startNextApplication();\n consumeObserverReturn(returned);\n return nextApplication;\n };\n\n const readiness =\n readInstrumentationFacts === undefined || trustedRegistration === undefined\n ? undefined\n : prewarmTrustedObserver(trustedRegistration.capability);\n if (readiness === undefined) return startObserver(0);\n\n // Promise executors run synchronously; TypeScript does not model that guarantee.\n let resolveApplication!: (value: Result | PromiseLike<Result>) => void;\n let rejectApplication!: (reason?: unknown) => void;\n const applicationBridge = new Promise<Result>((resolve, reject) => {\n resolveApplication = resolve;\n rejectApplication = reject;\n });\n const startAfterPrewarm = (): void => {\n startObserver(0).then(\n (value) => resolveApplication(value),\n (failure: unknown) => rejectApplication(failure)\n );\n };\n readiness.then(startAfterPrewarm);\n return applicationBridge;\n}\n\n/** Observe one logical operation without duplicating its completion protocol. */\nexport function observeOperation<Result>(\n observers: readonly ResolvedExtensionHandler[],\n operation: string,\n model: string | undefined,\n child: () => Promise<Result>,\n readCompletionFacts?: ObservationCompletionFactsReader,\n readInstrumentationFacts?: OfficialLifecycleFactsReader\n): Promise<Result> {\n return runProtectedObservers(\n {\n kind: \"operation\",\n operation,\n ...(model === undefined ? {} : { model }),\n },\n observers,\n child,\n readCompletionFacts,\n readInstrumentationFacts\n );\n}\n\n/** Observe one driver-owned physical statement boundary. */\nexport function observeStatement<Result>(\n observers: readonly ResolvedExtensionHandler[],\n operation: string | undefined,\n model: string | undefined,\n child: () => Promise<Result>,\n readCompletionFacts?: ObservationCompletionFactsReader,\n readInstrumentationFacts?: OfficialLifecycleFactsReader\n): Promise<Result> {\n return runProtectedObservers(\n {\n kind: \"statement\",\n ...(operation === undefined ? {} : { operation }),\n ...(model === undefined || model === \"$raw\" ? {} : { model }),\n },\n observers,\n child,\n readCompletionFacts,\n readInstrumentationFacts\n );\n}\n\n/** Observe one driver-owned connection, transaction, or savepoint boundary. */\nexport function observeDriverLifecycle<Result>(\n kind: Extract<LifecycleUnitKind, \"connection\" | \"savepoint\" | \"transaction\">,\n observers: readonly ResolvedExtensionHandler[],\n operation: string | undefined,\n child: () => Promise<Result>,\n readCompletionFacts?: ObservationCompletionFactsReader,\n readInstrumentationFacts?: OfficialLifecycleFactsReader\n): Promise<Result> {\n return runProtectedObservers(\n {\n kind,\n ...(operation === undefined ? {} : { operation }),\n },\n observers,\n child,\n readCompletionFacts,\n readInstrumentationFacts\n );\n}\n\nfunction prewarmTrustedObserver(\n capability: OfficialObservationCapability\n): void | Promise<void> {\n const prewarm = capability.prewarm;\n if (prewarm === undefined) return;\n let readiness: void | Promise<void>;\n try {\n readiness = prewarm();\n } catch {\n return;\n }\n if (readiness === undefined) return;\n return Promise.resolve(readiness).then(\n () => undefined,\n () => undefined\n );\n}\n\nfunction freezeLifecycleUnit(unit: LifecycleUnit): LifecycleUnit {\n return Object.freeze(unit);\n}\n\nfunction consumeObserverReturn(returned: unknown): void {\n if (\n returned === null ||\n (typeof returned !== \"object\" && typeof returned !== \"function\")\n ) {\n return;\n }\n try {\n const then = Reflect.get(returned, \"then\");\n if (!isFunction(then)) return;\n Reflect.apply(then, returned, [settleObserverReturn, settleObserverReturn]);\n } catch {\n // Observer returns cannot affect the application.\n }\n}\n\nfunction createCompletion(\n status: ObservationCompletion[\"status\"],\n durationMs: number,\n commitCertainty: CommitCertainty | undefined,\n failure: unknown\n): ObservationCompletion {\n const error = status === \"failure\" ? summarizeFailure(failure) : undefined;\n return Object.freeze({\n status,\n durationMs,\n ...(error === undefined ? {} : { error }),\n ...(commitCertainty === undefined ? {} : { commitCertainty }),\n });\n}\n\nfunction summarizeFailure(failure: unknown): ObservationErrorSummary {\n const normalized = isError(failure)\n ? failure\n : new Error(\"Application rejected with a non-Error value\");\n const sanitized = sanitizeErrorForLogging(normalized);\n const code = Object.getOwnPropertyDescriptor(sanitized, \"code\")?.value;\n return Object.freeze({\n name: sanitized.name,\n message: sanitized.message,\n ...(typeof code === \"string\" ? { code } : {}),\n });\n}\n"],"mappings":"sJAKA,IAAa,qBAAb,cAA0C,CAAY,CACpD,OAAyB,eAAiB,uBAK1C,YAAY,EAAiB,EAAsC,CACjE,MAAM,EAAS,EAAgB,kBAAmB,EAAQ,GAOjD,qBAAb,cAA0C,CAAY,CACpD,OAAyB,eAAiB,uBAK1C,YAAY,EAAiB,EAAsC,CACjE,MAAM,EAAS,EAAgB,kBAAmB,EAAQ,GAOjD,gCAAb,cAAqD,CAAY,CAC/D,OAAyB,eAAiB,kCAK1C,YACE,EACA,EACA,EACA,CACA,MACE,cAAc,EAAU,0DAA0D,EAAoB,KAAK,KAAK,GAChH,EAAgB,8BAChB,CACE,KAAM,CAAE,GAAG,GAAS,KAAM,YAAW,CACtC,CACF,GAOQ,wBAAb,cAA6C,CAAY,CACvD,OAAyB,eAAiB,0BAK1C,YACE,EACA,EACA,CACA,MAAM,EAAS,EAAgB,oBAAqB,EAAQ,GCwBhE,MAAM,EAAmB,IAAI,QAIvB,EAAiB,IAAI,QAIrB,EAA8B,IAAI,QAIlC,yBAAwC,IA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