viborm 1.7.0 → 1.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (159) hide show
  1. package/dist/adapters.d.mts +1 -1
  2. package/dist/adapters.mjs +1 -1
  3. package/dist/{batch-refs-DWMYN0fw.mjs → batch-refs-ZHBzfoBC.mjs} +2 -2
  4. package/dist/{batch-refs-DWMYN0fw.mjs.map → batch-refs-ZHBzfoBC.mjs.map} +1 -1
  5. package/dist/{builder-B4n-7I7Q.mjs → builder-Ct1qPFc8.mjs} +2 -2
  6. package/dist/{builder-B4n-7I7Q.mjs.map → builder-Ct1qPFc8.mjs.map} +1 -1
  7. package/dist/bun-sql.d.mts +1 -1
  8. package/dist/bun-sql.mjs +1 -1
  9. package/dist/bun-sqlite.d.mts +1 -1
  10. package/dist/bun-sqlite.mjs +1 -1
  11. package/dist/cache/cloudflare-kv.d.mts +1 -1
  12. package/dist/cache/cloudflare-kv.mjs +1 -1
  13. package/dist/cache/memory.d.mts +1 -1
  14. package/dist/cache/memory.mjs +1 -1
  15. package/dist/cache.d.mts +1 -1
  16. package/dist/cache.mjs +1 -1
  17. package/dist/{chain-DVuRxjPO.mjs → chain--uZ0O7_Y.mjs} +2 -2
  18. package/dist/{chain-DVuRxjPO.mjs.map → chain--uZ0O7_Y.mjs.map} +1 -1
  19. package/dist/cli.mjs +1 -1
  20. package/dist/client-BAxU6jnw.mjs +2 -0
  21. package/dist/client-BAxU6jnw.mjs.map +1 -0
  22. package/dist/{client-7ApJka0M.d.mts → client-DP6gM_tf.d.mts} +2 -2
  23. package/dist/{client-l7dSOul5.mjs → client-mQcOvDdK.mjs} +3 -3
  24. package/dist/client-mQcOvDdK.mjs.map +1 -0
  25. package/dist/client.d.mts +1 -1
  26. package/dist/client.mjs +1 -1
  27. package/dist/config.d.mts +1 -1
  28. package/dist/config.mjs +1 -1
  29. package/dist/d1.d.mts +1 -1
  30. package/dist/d1.mjs +1 -1
  31. package/dist/{driver-DaBNytbz.mjs → driver-NtekjA3W.mjs} +2 -2
  32. package/dist/{driver-DaBNytbz.mjs.map → driver-NtekjA3W.mjs.map} +1 -1
  33. package/dist/{driver-CK_IKqDa.mjs → driver-XlmOJFRH.mjs} +2 -2
  34. package/dist/{driver-CK_IKqDa.mjs.map → driver-XlmOJFRH.mjs.map} +1 -1
  35. package/dist/driver.d.mts +1 -1
  36. package/dist/driver.mjs +1 -1
  37. package/dist/every-Xql4tHDz.mjs +2 -0
  38. package/dist/{every-6VrIclsx.mjs.map → every-Xql4tHDz.mjs.map} +1 -1
  39. package/dist/{hydration-BUBkHlCK.mjs → hydration-BNEFeV5v.mjs} +2 -2
  40. package/dist/{hydration-BUBkHlCK.mjs.map → hydration-BNEFeV5v.mjs.map} +1 -1
  41. package/dist/{identifier-conversion-BXrBYgAq.mjs → identifier-conversion-C_XCo9es.mjs} +2 -2
  42. package/dist/{identifier-conversion-BXrBYgAq.mjs.map → identifier-conversion-C_XCo9es.mjs.map} +1 -1
  43. package/dist/{index-CsO6vG2h.d.mts → index-DBhpNR0X.d.mts} +70 -8
  44. package/dist/index.d.mts +3 -3
  45. package/dist/index.mjs +1 -1
  46. package/dist/instrumentation.d.mts +1 -1
  47. package/dist/instrumentation.mjs +1 -1
  48. package/dist/{key-Cz83fdLO.mjs → key-QgLg2Kve.mjs} +2 -2
  49. package/dist/{key-Cz83fdLO.mjs.map → key-QgLg2Kve.mjs.map} +1 -1
  50. package/dist/{keys-EP1Eq2eD.mjs → keys-D5hv9EaJ.mjs} +2 -2
  51. package/dist/{keys-EP1Eq2eD.mjs.map → keys-D5hv9EaJ.mjs.map} +1 -1
  52. package/dist/{libsql-ClGi2zY2.mjs → libsql-BsJdPDES.mjs} +2 -2
  53. package/dist/{libsql-ClGi2zY2.mjs.map → libsql-BsJdPDES.mjs.map} +1 -1
  54. package/dist/libsql.d.mts +1 -1
  55. package/dist/libsql.mjs +1 -1
  56. package/dist/{memory-B1GnzgZr.mjs → memory-BEaJ0-FU.mjs} +2 -2
  57. package/dist/{memory-B1GnzgZr.mjs.map → memory-BEaJ0-FU.mjs.map} +1 -1
  58. package/dist/migrations/mysql.d.mts +4 -4
  59. package/dist/migrations/mysql.mjs +1 -1
  60. package/dist/migrations/postgres.d.mts +4 -4
  61. package/dist/migrations/postgres.mjs +1 -1
  62. package/dist/migrations/sqlite.d.mts +4 -4
  63. package/dist/migrations/sqlite.mjs +1 -1
  64. package/dist/migrations/tenant.d.mts +2 -2
  65. package/dist/migrations/tenant.mjs +1 -1
  66. package/dist/migrations.d.mts +4 -4
  67. package/dist/migrations.mjs +1 -1
  68. package/dist/{model-DsXZ_pHE.mjs → model-D94xU8jq.mjs} +2 -2
  69. package/dist/{model-DsXZ_pHE.mjs.map → model-D94xU8jq.mjs.map} +1 -1
  70. package/dist/{mysql-hoo290Dd.mjs → mysql-DT_dTWDi.mjs} +2 -2
  71. package/dist/{mysql-hoo290Dd.mjs.map → mysql-DT_dTWDi.mjs.map} +1 -1
  72. package/dist/{mysql-adapter-D-Dq2FN9.mjs → mysql-adapter-BUwzKlbt.mjs} +2 -2
  73. package/dist/{mysql-adapter-D-Dq2FN9.mjs.map → mysql-adapter-BUwzKlbt.mjs.map} +1 -1
  74. package/dist/mysql2.d.mts +1 -1
  75. package/dist/mysql2.mjs +1 -1
  76. package/dist/neon-http.d.mts +1 -1
  77. package/dist/neon-http.mjs +1 -1
  78. package/dist/{normalized-result-23DWxZVY.mjs → normalized-result-ByvlIQqa.mjs} +2 -2
  79. package/dist/{normalized-result-23DWxZVY.mjs.map → normalized-result-ByvlIQqa.mjs.map} +1 -1
  80. package/dist/{object-store-9VfS-3sY.d.mts → object-store-35LjwOS-.d.mts} +3 -3
  81. package/dist/on.d.mts +1 -1
  82. package/dist/ordering.d.mts +41 -19
  83. package/dist/ordering.mjs +8 -8
  84. package/dist/ordering.mjs.map +1 -1
  85. package/dist/permissions.d.mts +1 -1
  86. package/dist/permissions.mjs +1 -1
  87. package/dist/pg.d.mts +1 -1
  88. package/dist/pg.mjs +1 -1
  89. package/dist/pglite.d.mts +1 -1
  90. package/dist/pglite.mjs +1 -1
  91. package/dist/planetscale.d.mts +1 -1
  92. package/dist/planetscale.mjs +1 -1
  93. package/dist/{planner-Cc3ABIUU.d.mts → planner-CmDw5jPb.d.mts} +1 -1
  94. package/dist/{postgres-CqcP_qv-.mjs → postgres-Do0nq95P.mjs} +2 -2
  95. package/dist/{postgres-CqcP_qv-.mjs.map → postgres-Do0nq95P.mjs.map} +1 -1
  96. package/dist/{postgres-adapter-_o6EWuxW.mjs → postgres-adapter-DFzjbAP7.mjs} +2 -2
  97. package/dist/{postgres-adapter-_o6EWuxW.mjs.map → postgres-adapter-DFzjbAP7.mjs.map} +1 -1
  98. package/dist/{postgres-adapter-CYZAL2uo.mjs → postgres-adapter-Dvt16rbl.mjs} +2 -2
  99. package/dist/{postgres-adapter-CYZAL2uo.mjs.map → postgres-adapter-Dvt16rbl.mjs.map} +1 -1
  100. package/dist/{postgres-result-D94PyZ78.mjs → postgres-result-ehQiy2H-.mjs} +2 -2
  101. package/dist/{postgres-result-D94PyZ78.mjs.map → postgres-result-ehQiy2H-.mjs.map} +1 -1
  102. package/dist/postgres.d.mts +1 -1
  103. package/dist/postgres.mjs +1 -1
  104. package/dist/{result-shape-uaCsF_SZ.mjs → result-shape-DwoSyWnq.mjs} +2 -2
  105. package/dist/{result-shape-uaCsF_SZ.mjs.map → result-shape-DwoSyWnq.mjs.map} +1 -1
  106. package/dist/{rows-AtX0guAb.mjs → rows-ig1gjVRb.mjs} +2 -2
  107. package/dist/{rows-AtX0guAb.mjs.map → rows-ig1gjVRb.mjs.map} +1 -1
  108. package/dist/rows-of-Djavcb19.mjs +2 -0
  109. package/dist/rows-of-Djavcb19.mjs.map +1 -0
  110. package/dist/{scalar-CZ_q89Hc.mjs → scalar-BgxfbRLw.mjs} +2 -2
  111. package/dist/{scalar-CZ_q89Hc.mjs.map → scalar-BgxfbRLw.mjs.map} +1 -1
  112. package/dist/schema/json.d.mts +1 -1
  113. package/dist/schema/json.mjs +1 -1
  114. package/dist/schema-CT57uls5.mjs +2 -0
  115. package/dist/{schema-CZTCxG2p.mjs.map → schema-CT57uls5.mjs.map} +1 -1
  116. package/dist/{schema-introspection-DoZHc1o7.mjs → schema-introspection-BFDAX5Ol.mjs} +2 -2
  117. package/dist/{schema-introspection-DoZHc1o7.mjs.map → schema-introspection-BFDAX5Ol.mjs.map} +1 -1
  118. package/dist/schema.d.mts +1 -1
  119. package/dist/schema.mjs +1 -1
  120. package/dist/{select-assembly-BtNtBsUh.mjs → select-assembly-Dcaqm09G.mjs} +2 -2
  121. package/dist/{select-assembly-BtNtBsUh.mjs.map → select-assembly-Dcaqm09G.mjs.map} +1 -1
  122. package/dist/soft-delete.d.mts +116 -14
  123. package/dist/soft-delete.mjs +1 -1
  124. package/dist/soft-delete.mjs.map +1 -1
  125. package/dist/sql-BsBoKwaf.mjs +2 -0
  126. package/dist/sql-BsBoKwaf.mjs.map +1 -0
  127. package/dist/{sql-BnXk8adi.d.mts → sql-D7JnXgUh.d.mts} +5 -0
  128. package/dist/sql.d.mts +1 -1
  129. package/dist/sql.mjs +1 -1
  130. package/dist/{sqlite-adapter-CnAwmszh.mjs → sqlite-adapter-eGsbASDR.mjs} +2 -2
  131. package/dist/{sqlite-adapter-CnAwmszh.mjs.map → sqlite-adapter-eGsbASDR.mjs.map} +1 -1
  132. package/dist/sqlite3.d.mts +1 -1
  133. package/dist/sqlite3.mjs +1 -1
  134. package/dist/{standard-sql-Ci8ROrql.mjs → standard-sql-BtzSzrof.mjs} +2 -2
  135. package/dist/standard-sql-BtzSzrof.mjs.map +1 -0
  136. package/dist/{to-many-BtLpp5cW.mjs → to-many-CJ-8_caR.mjs} +2 -2
  137. package/dist/{to-many-BtLpp5cW.mjs.map → to-many-CJ-8_caR.mjs.map} +1 -1
  138. package/dist/{utils-CAACs9Jw.mjs → utils-DYz-Xm59.mjs} +2 -2
  139. package/dist/{utils-CAACs9Jw.mjs.map → utils-DYz-Xm59.mjs.map} +1 -1
  140. package/dist/{v-Pb_jJOjC.mjs → v-C2XN11Gy.mjs} +2 -2
  141. package/dist/{v-Pb_jJOjC.mjs.map → v-C2XN11Gy.mjs.map} +1 -1
  142. package/dist/validation.d.mts +1 -1
  143. package/dist/validation.mjs +1 -1
  144. package/dist/{validator-Dthaj1Hz.mjs → validator-DqI5RlVU.mjs} +2 -2
  145. package/dist/{validator-Dthaj1Hz.mjs.map → validator-DqI5RlVU.mjs.map} +1 -1
  146. package/dist/version-DyH_HopX.mjs +2 -0
  147. package/dist/{version-DvynkoaW.mjs.map → version-DyH_HopX.mjs.map} +1 -1
  148. package/package.json +21 -21
  149. package/dist/client-Yqn0LqmI.mjs +0 -2
  150. package/dist/client-Yqn0LqmI.mjs.map +0 -1
  151. package/dist/client-l7dSOul5.mjs.map +0 -1
  152. package/dist/every-6VrIclsx.mjs +0 -2
  153. package/dist/insert-value-Cbp_bNxj.mjs +0 -2
  154. package/dist/insert-value-Cbp_bNxj.mjs.map +0 -1
  155. package/dist/schema-CZTCxG2p.mjs +0 -2
  156. package/dist/sql-DGtEeP8z.mjs +0 -2
  157. package/dist/sql-DGtEeP8z.mjs.map +0 -1
  158. package/dist/standard-sql-Ci8ROrql.mjs.map +0 -1
  159. package/dist/version-DvynkoaW.mjs +0 -2
@@ -1 +1 @@
1
- {"version":3,"file":"model-DsXZ_pHE.mjs","names":["#state","#internal","#state","#internal","#withForeignKeyAction","#localFields","v","#state","#internal","model","#names","#nameRegistry","#scalarFieldNames","#relationNames"],"sources":["../src/schema/record.ts","../src/schema/relation/polymorphic.ts","../src/schema/relation/to-one.ts","../src/schema/model/helper.ts","../src/schema/model/model.ts"],"sourcesContent":["// Records keyed by DATA.\n//\n// A schema is built from maps whose keys come from somewhere else: a model\n// shape's field key, a document's model/field/variant key, an enum reference, a\n// default's own object keys. `record[key] = value` is not a safe way to build\n// such a map, because `__proto__` is an accessor on `Object.prototype`:\n// assigning through it sets a prototype and creates NO own key. The entry\n// disappears, and what is left is a well-formed object, so nothing downstream\n// can notice the loss.\n//\n// Reading has the mirror problem: `record[key]` resolves inherited members, so\n// a data key of `__proto__`, `constructor` or `toString` answers something the\n// map never held.\n//\n// One owner for both, used everywhere a key comes from data — the JSON\n// document's maps and `s.model(...)`'s classified member maps alike. It carries\n// no refusal: whether a key is a legal identifier is `isValidSchemaIdentifier`'s\n// question, asked at hydration and by the document reader, and the answer is the\n// same whichever way the key was written. The document READER needs neither\n// helper, because it asks that question before anything is written.\n\n/** A map with no inherited members, so a data key can only find what was put. */\nexport function emptyRecord<T>(): Record<string, T> {\n return Object.create(null);\n}\n\n/** Write one own key, whatever it is called. */\nexport function put<T>(target: Record<string, T>, key: string, value: T): void {\n Object.defineProperty(target, key, {\n value,\n enumerable: true,\n writable: true,\n configurable: true,\n });\n}\n\n/** Read one own key, or nothing. */\nexport function own<T>(\n source: Record<string, T> | undefined,\n key: string\n): T | undefined {\n if (source === undefined || !Object.hasOwn(source, key)) return;\n return source[key];\n}\n","// Variant target domains: the normalization owner and the two variant terminals.\n//\n// \"Polymorphic\" is not a relation family. It is the derived observation that a\n// declaration's TARGET DOMAIN holds named variants instead of one model, which\n// is why the two variant terminals are reached through the same `s.toOne` /\n// `s.toMany` factories as the model-target ones. What is irreducibly different\n// is the legal local configuration: a row-held variant to-one may be\n// `.optional()` and owns no public foreign key, and a member-junction variant\n// to-many names one junction per variant through an exact `.through(...)` map.\n\nimport type { Model } from \"@schema/model\";\nimport type { Scalar } from \"@schema/scalars/base\";\nimport { isValidSchemaIdentifier } from \"../identifier\";\nimport {\n createTargetSettlement,\n declaredKeys,\n hasExactKeys,\n isPlainRecord,\n normalizeRelationName,\n type RelationBuilder,\n readCallerProperty,\n refuseRelationInput,\n} from \"./terminal\";\nimport type {\n AnyRelation,\n Getter,\n RelationInternal,\n Replace,\n VariantEntry,\n VariantJunctionOverride,\n VariantManyEntry,\n VariantToManyState,\n VariantToOneState,\n} from \"./types\";\n\n/**\n * The stored-discriminator grammar. A stored value is written to a physical\n * column and read back by migrations and predicates, so it admits namespaced\n * and versioned spellings the public variant key does not.\n */\nconst STORED_VALUE = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,190}$/;\n\nconst THROUGH_ENTRY_KEYS = [\"table\", \"source\", \"target\"] as const;\n\n// =============================================================================\n// FACTORY-LEVEL TYPES\n// =============================================================================\n\nexport type VariantGetterMap = Readonly<Record<string, Getter>>;\n\n/**\n * The map overload's phantom refusal.\n *\n * It is NOT redundant with {@link GetterOnly}. With the map overload first and\n * an unconstrained getter overload second, a structurally-map argument that\n * fails this guard would otherwise fall through to the getter overload, whose\n * conditional return answers `never` — and `never` is assignable to a model\n * shape, so the refusal would disappear entirely. This guard uniquely owns\n * \"structurally a map, but not a legal variant map\"; `GetterOnly` uniquely owns\n * \"not a map at all and not a getter\".\n */\nexport type VariantMapGuard<Entries> = string extends keyof Entries\n ? {\n readonly \"a variant map needs literal keys, not a string index signature\": never;\n }\n : [keyof Entries] extends [never]\n ? { readonly \"a variant map needs at least one variant\": never }\n : unknown;\n\nexport type VariantOptions<Entries> = {\n readonly values: { readonly [Key in keyof Entries]: string };\n};\n\n/**\n * The whole options bag is exact, not only `values`: a NON-FRESH bag with a\n * sibling key beside `values` sails through excess-property checking, so the\n * unknown keys are refused structurally.\n */\nexport type ExactVariantOptions<Options, Entries> = Options extends undefined\n ? unknown\n : Record<Exclude<keyof Options, \"values\">, never> & {\n readonly values: Record<\n Exclude<\n keyof (Options extends { readonly values: infer Values }\n ? Values\n : never),\n keyof Entries\n >,\n never\n >;\n };\n\n/**\n * Normalized entries carry the getter's exact type and a plain `string` stored\n * value: the stored discriminator is runtime storage, never a public result\n * discriminator, so carrying its literal would be a public type parameter no\n * consumer reads.\n */\nexport type NormalizedOneEntries<Entries> = {\n readonly [Key in keyof Entries]: {\n readonly getter: Entries[Key];\n readonly storedValue: string;\n };\n};\n\nexport type NormalizedManyEntries<Entries> = {\n readonly [Key in keyof Entries]: {\n readonly getter: Entries[Key];\n readonly storedValue: string;\n readonly junction?: VariantJunctionOverride;\n };\n};\n\ntype VariantEntriesOfState<State> = State extends {\n readonly target: { readonly entries: infer Entries };\n}\n ? Entries\n : never;\n\ntype VariantThroughMap<Entries> = {\n readonly [Key in keyof Entries]: VariantJunctionOverride;\n};\n\ntype ExactVariantThroughMap<Given, Entries> = Record<\n Exclude<keyof Given, keyof Entries>,\n never\n> & {\n readonly [Key in keyof Given]: Record<\n Exclude<keyof Given[Key], keyof VariantJunctionOverride>,\n never\n >;\n};\n\n// =============================================================================\n// TERMINAL CAPABILITY SURFACES\n// =============================================================================\n\n/** A slot that holds at most one membership across its variants. */\nexport type VariantToOneRelation<State> = {\n readonly \"~\": RelationInternal<State>;\n name<const Name extends string>(\n name: Name\n ): VariantToOneRelation<Replace<State, { readonly name: Name }>>;\n optional(): VariantToOneRelation<Replace<State, { readonly optional: true }>>;\n};\n\n/**\n * A slot that holds a collection across its variants. No `.optional()`: an\n * empty collection is already the empty case.\n */\nexport type VariantToManyRelation<State> = {\n readonly \"~\": RelationInternal<State>;\n name<const Name extends string>(\n name: Name\n ): VariantToManyRelation<Replace<State, { readonly name: Name }>>;\n through<\n const ThroughMap extends VariantThroughMap<VariantEntriesOfState<State>>,\n >(\n map: ThroughMap &\n ExactVariantThroughMap<ThroughMap, VariantEntriesOfState<State>>\n ): VariantToManyRelation<State>;\n};\n\n// =============================================================================\n// NORMALIZATION\n// =============================================================================\n\n/**\n * Read the target map and its options ONCE, judge every structurally knowable\n * fact, and build the single normalized entry map. There is no separately\n * stored `targets`, `values` or `through` map to keep in sync.\n *\n * Every own property at both map levels is read exactly once here and pinned as\n * a plain value: a live accessor could otherwise answer validation with one\n * value and the storage builder with another. Reading a property's value does\n * not invoke a target thunk; getters are stored as functions and stay lazy.\n */\nexport function normalizeVariantEntries(\n builder: RelationBuilder,\n variants: unknown,\n options: unknown\n): Readonly<Record<string, VariantEntry>> {\n if (!isPlainRecord(variants)) {\n refuseRelationInput(\n builder,\n \"target\",\n \"A relation target is either `() => model` or a plain map of named `() => model` getters\"\n );\n }\n const variantKeys = declaredKeys(variants);\n if (variantKeys.length === 0) {\n refuseRelationInput(\n builder,\n \"target\",\n \"A variant map needs at least one variant\"\n );\n }\n const storedValues = readStoredValues(builder, variantKeys, options);\n const entries: Record<string, VariantEntry> = {};\n for (const variantKey of variantKeys) {\n if (!isValidSchemaIdentifier(variantKey)) {\n refuseRelationInput(\n builder,\n `target.${variantKey}`,\n `Variant key '${variantKey}' is not a valid schema identifier`\n );\n }\n const getter = readCallerProperty(\n builder,\n variants,\n variantKey,\n `target.${variantKey}`\n );\n if (typeof getter !== \"function\") {\n refuseRelationInput(\n builder,\n `target.${variantKey}`,\n `Variant '${variantKey}' must be a lazy getter; write \\`() => model\\` rather than the model itself`\n );\n }\n entries[variantKey] = Object.freeze({\n getter,\n storedValue: storedValues[variantKey] ?? variantKey,\n });\n }\n return Object.freeze(entries);\n}\n\n/**\n * The stored discriminator per variant: each public key by default, or the\n * exact `values` bag when one is supplied. An explicit `undefined` is\n * equivalent to omission; `{}` is not, because it declares an options bag\n * without the one option it may carry.\n */\nfunction readStoredValues(\n builder: RelationBuilder,\n variantKeys: readonly string[],\n options: unknown\n): Record<string, string> {\n if (options === undefined) return {};\n if (!isPlainRecord(options)) {\n refuseRelationInput(\n builder,\n \"options\",\n \"Relation options must be a plain `{ values }` record; omit the argument to use each variant key as its stored value\"\n );\n }\n if (!hasExactKeys(declaredKeys(options), [\"values\"])) {\n refuseRelationInput(\n builder,\n \"options\",\n \"Relation options carry exactly one key, `values`; omit the argument to use each variant key as its stored value\"\n );\n }\n const values = readCallerProperty(\n builder,\n options,\n \"values\",\n \"options.values\"\n );\n if (!isPlainRecord(values)) {\n refuseRelationInput(\n builder,\n \"options.values\",\n \"`values` must be a plain record keyed by every variant\"\n );\n }\n const valueKeys = declaredKeys(values);\n if (!hasExactKeys(valueKeys, variantKeys)) {\n refuseRelationInput(\n builder,\n \"options.values\",\n `\\`values\\` must be exact over the variant keys ${renderKeys(variantKeys)}; it declares ${renderKeys(valueKeys)}`\n );\n }\n const storedValues: Record<string, string> = {};\n const claimed = new Set<string>();\n for (const variantKey of variantKeys) {\n const storedValue = readCallerProperty(\n builder,\n values,\n variantKey,\n `options.values.${variantKey}`\n );\n if (typeof storedValue !== \"string\" || !STORED_VALUE.test(storedValue)) {\n refuseRelationInput(\n builder,\n `options.values.${variantKey}`,\n `Stored value for variant '${variantKey}' must match the stored-discriminator grammar`\n );\n }\n if (claimed.has(storedValue)) {\n refuseRelationInput(\n builder,\n `options.values.${variantKey}`,\n `Stored value '${storedValue}' is declared for more than one variant`\n );\n }\n claimed.add(storedValue);\n storedValues[variantKey] = storedValue;\n }\n return storedValues;\n}\n\nfunction renderKeys(keys: readonly string[]): string {\n return `[${keys.map((key) => `'${key}'`).join(\", \")}]`;\n}\n\n/**\n * Fold one member-junction override into each normalized entry. The outer map\n * is exact over the variants and every inner value is exact — the runtime\n * mirror of the `.through()` type contract, and the reason there is no second\n * `through` map to keep in sync with the entries.\n */\nfunction foldMemberJunctions(\n entries: Readonly<Record<string, VariantEntry>>,\n through: unknown\n): Readonly<Record<string, VariantManyEntry>> {\n const variantKeys = Object.keys(entries);\n if (!isPlainRecord(through)) {\n refuseRelationInput(\n \"s.toMany\",\n \"through\",\n \"`.through()` takes a plain map keyed by every variant\"\n );\n }\n if (!hasExactKeys(declaredKeys(through), variantKeys)) {\n refuseRelationInput(\n \"s.toMany\",\n \"through\",\n `\\`.through()\\` must be exact over the variant keys ${renderKeys(variantKeys)}`\n );\n }\n const folded: Record<string, VariantManyEntry> = {};\n for (const [variantKey, entry] of Object.entries(entries)) {\n const override = readCallerProperty(\n \"s.toMany\",\n through,\n variantKey,\n `through.${variantKey}`\n );\n folded[variantKey] = Object.freeze({\n ...entry,\n junction: readJunctionOverride(variantKey, override),\n });\n }\n return Object.freeze(folded);\n}\n\nfunction readJunctionOverride(\n variantKey: string,\n override: unknown\n): VariantJunctionOverride {\n const path = `through.${variantKey}`;\n if (!isPlainRecord(override)) {\n refuseRelationInput(\n \"s.toMany\",\n path,\n `Member junction '${variantKey}' must be a plain \\`{ table, source, target }\\` record`\n );\n }\n const table = readCallerProperty(\n \"s.toMany\",\n override,\n \"table\",\n `${path}.table`\n );\n const source = readCallerProperty(\n \"s.toMany\",\n override,\n \"source\",\n `${path}.source`\n );\n const target = readCallerProperty(\n \"s.toMany\",\n override,\n \"target\",\n `${path}.target`\n );\n if (\n !hasExactKeys(declaredKeys(override), THROUGH_ENTRY_KEYS) ||\n typeof table !== \"string\" ||\n typeof source !== \"string\" ||\n typeof target !== \"string\"\n ) {\n refuseRelationInput(\n \"s.toMany\",\n path,\n `Member junction '${variantKey}' declares exactly \\`table\\`, \\`source\\` and \\`target\\`, all strings`\n );\n }\n return Object.freeze({ table, source, target });\n}\n\n// =============================================================================\n// TERMINALS\n// =============================================================================\n\n/**\n * Private terminal machinery. None of the four terminal classes is exported\n * from its module, let alone from the package: callers see only the\n * capabilities the two factories return. The two constructor helpers below are\n * the whole cross-module surface.\n */\nclass VariantToOne {\n readonly #state: VariantToOneState;\n readonly #internal: RelationInternal<VariantToOneState>;\n\n constructor(state: VariantToOneState) {\n this.#state = Object.freeze(state);\n this.#internal = Object.freeze({\n state: this.#state,\n settleTarget: createTargetSettlement((variantKey) =>\n readVariantGetter(this.#state, variantKey)\n ),\n });\n }\n\n name(name: string): VariantToOne {\n return new VariantToOne({\n ...this.#state,\n name: normalizeRelationName(\"s.toOne\", name),\n });\n }\n\n optional(): VariantToOne {\n return new VariantToOne({ ...this.#state, optional: true });\n }\n\n get \"~\"(): RelationInternal<VariantToOneState> {\n return this.#internal;\n }\n}\n\nclass VariantToMany {\n readonly #state: VariantToManyState;\n readonly #internal: RelationInternal<VariantToManyState>;\n\n constructor(state: VariantToManyState) {\n this.#state = Object.freeze(state);\n this.#internal = Object.freeze({\n state: this.#state,\n settleTarget: createTargetSettlement((variantKey) =>\n readVariantGetter(this.#state, variantKey)\n ),\n });\n }\n\n name(name: string): VariantToMany {\n return new VariantToMany({\n ...this.#state,\n name: normalizeRelationName(\"s.toMany\", name),\n });\n }\n\n through(map: unknown): VariantToMany {\n return new VariantToMany({\n ...this.#state,\n target: {\n kind: \"variants\",\n entries: foldMemberJunctions(this.#state.target.entries, map),\n },\n });\n }\n\n get \"~\"(): RelationInternal<VariantToManyState> {\n return this.#internal;\n }\n}\n\n/** Construct the row-held variant terminal for `s.toOne`. */\nexport function variantToOneTerminal(state: VariantToOneState): AnyRelation {\n return new VariantToOne(state);\n}\n\n/** Construct the member-junction variant terminal for `s.toMany`. */\nexport function variantToManyTerminal(state: VariantToManyState): AnyRelation {\n return new VariantToMany(state);\n}\n\nfunction readVariantGetter(\n state: VariantToOneState | VariantToManyState,\n variantKey: string | undefined\n): unknown {\n if (variantKey === undefined) return undefined;\n const entry = state.target.entries[variantKey];\n return entry === undefined ? undefined : entry.getter;\n}\n\n// =============================================================================\n// RESOLVED VARIANT STORAGE COLUMN\n// =============================================================================\n// Resolution OUTPUT, not declaration state: one private column the variant\n// row-storage owner derives, carried on the resolved edge and read by the\n// serializer and the engine. The descriptors that used to sit beside it are\n// gone — the resolved edge IS the topology, and a second copy of it on the\n// model was a second answer to every question the edge already answers.\n\nexport interface PolymorphicStorageColumn {\n readonly name: string;\n readonly scalar: Scalar;\n readonly nullable: boolean;\n /**\n * The KEY this private column stands in for, when it stands in for one.\n *\n * A row carrier's id column holds every variant's primary key, and what\n * those keys hold — an identifier domain above all — may be DERIVED rather\n * than declared: the ordinary one-to-one child whose primary key IS its\n * parent foreign key declares nothing and still holds uuids. The scalar\n * alone cannot answer that (derivation is keyed by model and field, never by\n * a scalar instance two models may share), so the column carries the pair\n * the one lookup takes. Every variant's key agrees on the answer or the\n * carrier does not exist — that agreement is what the identifier-domain\n * derivation refuses when it fails — so the FIRST member's key is the\n * carrier's key.\n *\n * The type discriminator column stands in for no key and carries none.\n */\n readonly reference?: {\n readonly model: Model<any>;\n readonly field: string;\n };\n}\n","// `s.toOne` — one of the two relation factories.\n//\n// The factory states the SLOT CARDINALITY (one) and its argument states the\n// TARGET DOMAIN (one model, or named variants). Which endpoint owns a foreign\n// key, whether the pair is one-to-one or many-to-one, and whether a model-target\n// slot may be empty are DERIVED later by the full-schema topology owner.\n\nimport {\n type ExactVariantOptions,\n type NormalizedOneEntries,\n normalizeVariantEntries,\n type VariantGetterMap,\n type VariantMapGuard,\n type VariantOptions,\n type VariantToOneRelation,\n variantToOneTerminal,\n} from \"./polymorphic\";\nimport {\n createTargetSettlement,\n normalizeFieldTuple,\n normalizeReferentialAction,\n normalizeRelationName,\n refuseRelationInput,\n} from \"./terminal\";\nimport type {\n AnyRelation,\n ForeignKeyDeclaration,\n Getter,\n GetterOnly,\n ModelToOneState,\n NonEmptyFieldTuple,\n ReferentialAction,\n RelationInternal,\n Replace,\n} from \"./types\";\n\n// =============================================================================\n// TERMINAL CAPABILITY SURFACE\n// =============================================================================\n\n/**\n * Referential actions exist only once a complete reference exists — they act on\n * a foreign key, and there is no foreign key to act on before\n * `.references(...)` completes the pair.\n */\ntype ForeignKeyActions<State> = {\n onDelete<const Action extends ReferentialAction>(\n action: Action\n ): ModelToOneRelation<\n State extends { readonly foreignKey: infer FK }\n ? Replace<\n State,\n { readonly foreignKey: Replace<FK, { onDelete: Action }> }\n >\n : State\n >;\n onUpdate<const Action extends ReferentialAction>(\n action: Action\n ): ModelToOneRelation<\n State extends { readonly foreignKey: infer FK }\n ? Replace<\n State,\n { readonly foreignKey: Replace<FK, { onUpdate: Action }> }\n >\n : State\n >;\n};\n\ntype ModelToOneCapabilities<State> = {\n readonly \"~\": RelationInternal<State>;\n name<const Name extends string>(\n name: Name\n ): ModelToOneRelation<Replace<State, { readonly name: Name }>>;\n fields<const Fields extends NonEmptyFieldTuple>(\n ...fields: Fields\n ): ReferencesStage<State, Fields>;\n};\n\n/**\n * A model-target singular slot. It exposes no `.optional()`: emptiness follows\n * from the nullability of a complete local foreign-key tuple, and a non-owning\n * singular view is derived nullable.\n */\nexport type ModelToOneRelation<State> = ModelToOneCapabilities<State> &\n (State extends { readonly foreignKey: ForeignKeyDeclaration }\n ? ForeignKeyActions<State>\n : unknown);\n\n/**\n * The transient value `.fields(...)` returns.\n *\n * It carries NO relation brand, so neither `ModelShape` nor any downstream\n * relation consumer can mistake an incomplete foreign key for trusted schema\n * state, and `s.model(...)` refuses it outright. It exposes only\n * `.references(...)` and `.name(...)`: a name must not be able to turn an\n * incomplete pair into schema truth.\n */\nexport type ReferencesStage<State, Fields extends NonEmptyFieldTuple> = {\n references<\n const References extends NonEmptyFieldTuple & {\n readonly length: Fields[\"length\"];\n },\n >(\n ...references: References\n ): ModelToOneRelation<\n Replace<\n State,\n {\n readonly foreignKey: Replace<\n State extends { readonly foreignKey: infer FK } ? FK : unknown,\n { readonly fields: Fields; readonly references: References }\n >;\n }\n >\n >;\n name<const Name extends string>(\n name: Name\n ): ReferencesStage<Replace<State, { readonly name: Name }>, Fields>;\n};\n\n// =============================================================================\n// PRIVATE TERMINALS\n// =============================================================================\n\nclass ModelToOne {\n readonly #state: ModelToOneState;\n readonly #internal: RelationInternal<ModelToOneState>;\n\n constructor(state: ModelToOneState) {\n this.#state = Object.freeze(state);\n this.#internal = Object.freeze({\n state: this.#state,\n settleTarget: createTargetSettlement(() => this.#state.target.getter),\n });\n }\n\n name(name: string): ModelToOne {\n return new ModelToOne({\n ...this.#state,\n name: normalizeRelationName(\"s.toOne\", name),\n });\n }\n\n fields(...fields: string[]): PendingReferences {\n return new PendingReferences(\n this.#state,\n normalizeFieldTuple(\"s.toOne\", \"fields\", fields)\n );\n }\n\n onDelete(action: ReferentialAction): ModelToOne {\n return this.#withForeignKeyAction(\"onDelete\", action);\n }\n\n onUpdate(action: ReferentialAction): ModelToOne {\n return this.#withForeignKeyAction(\"onUpdate\", action);\n }\n\n /**\n * The type surface hides both action setters until `.references(...)` has\n * completed a foreign key. This refusal covers the route a type pin cannot:\n * a JavaScript caller placing a referential action on a slot that owns no\n * foreign key, where the action would otherwise have nowhere to be stored and\n * would be silently dropped.\n */\n #withForeignKeyAction(\n action: \"onDelete\" | \"onUpdate\",\n value: ReferentialAction\n ): ModelToOne {\n const foreignKey = this.#state.foreignKey;\n if (foreignKey === undefined) {\n refuseRelationInput(\n \"s.toOne\",\n action,\n `'${action}' is available only after \\`.fields(...).references(...)\\` declares a foreign key`\n );\n }\n return new ModelToOne({\n ...this.#state,\n foreignKey: Object.freeze({\n ...foreignKey,\n [action]: normalizeReferentialAction(action, value),\n }),\n });\n }\n\n get \"~\"(): RelationInternal<ModelToOneState> {\n return this.#internal;\n }\n}\n\n/**\n * The transient references stage. It has no `\"~\"` accessor by design: that\n * absence is what makes an incomplete chain unusable as a model member.\n */\nclass PendingReferences {\n readonly #state: ModelToOneState;\n readonly #localFields: NonEmptyFieldTuple;\n\n constructor(state: ModelToOneState, localFields: NonEmptyFieldTuple) {\n this.#state = state;\n this.#localFields = localFields;\n }\n\n name(name: string): PendingReferences {\n return new PendingReferences(\n { ...this.#state, name: normalizeRelationName(\"s.toOne\", name) },\n this.#localFields\n );\n }\n\n references(...references: string[]): ModelToOne {\n const referenced = normalizeFieldTuple(\"s.toOne\", \"references\", references);\n if (referenced.length !== this.#localFields.length)\n refuseReferenceArity(referenced.length, this.#localFields.length);\n // Completing a second stage replaces the pair atomically and preserves the\n // endpoint's name and referential actions; the prior terminal is untouched.\n const prior = this.#state.foreignKey;\n const foreignKey: ForeignKeyDeclaration = {\n fields: this.#localFields,\n references: referenced,\n ...(prior?.onDelete === undefined ? {} : { onDelete: prior.onDelete }),\n ...(prior?.onUpdate === undefined ? {} : { onUpdate: prior.onUpdate }),\n };\n return new ModelToOne({\n ...this.#state,\n foreignKey: Object.freeze(foreignKey),\n });\n }\n}\n\n/**\n * Is this model member a transient references stage?\n *\n * Deliberately nominal: a stage is only ever produced by `.fields(...)`, so an\n * `instanceof` test cannot be spoofed by a look-alike record, and the\n * `s.model(...)` boundary can refuse the one member shape that would otherwise\n * be silently dropped.\n */\nexport function isReferencesStage(value: unknown): boolean {\n return value instanceof PendingReferences;\n}\n\n// =============================================================================\n// FACTORY\n// =============================================================================\n\n/**\n * Declare a slot that holds AT MOST ONE membership.\n *\n * The map overload is declared first so a variant map is never swallowed by the\n * broad getter overload. Dispatch examines only the argument representation and\n * never invokes a getter.\n */\nexport function toOne<\n const Entries extends VariantGetterMap,\n const Options extends VariantOptions<Entries> | undefined = undefined,\n>(\n variants: Entries & VariantMapGuard<Entries>,\n options?: Options & ExactVariantOptions<Options, Entries>\n): VariantToOneRelation<{\n readonly kind: \"relation\";\n readonly cardinality: \"one\";\n readonly target: {\n readonly kind: \"variants\";\n readonly entries: NormalizedOneEntries<Entries>;\n };\n}>;\nexport function toOne<const G>(getter: G & GetterOnly<G>): G extends Getter\n ? ModelToOneRelation<{\n readonly kind: \"relation\";\n readonly cardinality: \"one\";\n readonly target: { readonly kind: \"model\"; readonly getter: G };\n }>\n : never;\nexport function toOne(target: unknown, options?: unknown): AnyRelation {\n if (typeof target === \"function\") {\n // biome-ignore lint/complexity/noArguments: distinguishes omission from explicit undefined without changing the factory's public arity\n if (arguments.length > 1) {\n refuseRelationInput(\n \"s.toOne\",\n \"options\",\n \"A model-target relation takes exactly one argument\"\n );\n }\n return new ModelToOne({\n kind: \"relation\",\n cardinality: \"one\",\n target: { kind: \"model\", getter: target },\n });\n }\n return variantToOneTerminal({\n kind: \"relation\",\n cardinality: \"one\",\n target: {\n kind: \"variants\",\n entries: normalizeVariantEntries(\"s.toOne\", target, options),\n },\n });\n}\n\nfunction refuseReferenceArity(referenced: number, local: number): never {\n return refuseRelationInput(\n \"s.toOne\",\n \"references\",\n `\\`.references(...)\\` declares ${referenced} field(s) against ${local} local field(s); a foreign key pairs them positionally`\n );\n}\n","import { emptyRecord } from \"@schema/record\";\nimport type { AnyRelation } from \"@schema/relation\";\nimport { refuseRelationInput } from \"@schema/relation/terminal\";\n// Deep import: the references-stage predicate is the `s.model(...)` boundary's\n// own instrument and is deliberately not part of the relation package surface.\nimport { isReferencesStage } from \"@schema/relation/to-one\";\nimport type { Scalar } from \"@schema/scalars/base\";\n\n/**\n * Record of model fields - the canonical type for scalar and relation definitions.\n * A model field is either a scalar or a relation; ONE relation map holds both\n * target domains.\n */\nexport type AnyModelField = Scalar | AnyRelation;\nexport type ModelShape = Record<string, AnyModelField>;\n\n/**\n * The shape `s.model(...)` and `.extends(...)` accept: a model shape with no\n * member named `_count` or `_distance`, the names a selection's own outputs\n * reserve (relation counts, a distance). This is the compile-time spelling of\n * rule F010 for TypeScript callers; F010 (`memberNamesAreNotReserved`) stays\n * the contract for every caller. It constrains keys only and never reads a\n * member's type, so it cannot change what a shape infers. Each key's type is\n * its reason spelled as a string literal, so the diagnostic a caller reads\n * names it: no model member is a string, so nothing a shape can hold\n * satisfies it.\n */\nexport type DeclaredModelShape = ModelShape & {\n readonly _count?: \"`_count` is reserved for relation counts (F010)\";\n readonly _distance?: \"`_distance` is reserved for distance results (F010)\";\n};\n\nexport type NameFromKeys<\n TFields extends string[],\n TName extends string = \"\",\n> = TFields extends readonly [\n infer F extends string,\n ...infer R extends string[],\n]\n ? R extends []\n ? `${TName}_${F}`\n : NameFromKeys<R, TName extends \"\" ? F : `${TName}_${F}`>\n : never;\n\nexport interface CompoundConstraint<\n TFields extends string[],\n TName extends string | undefined = undefined,\n> {\n fields: TFields;\n name: TName extends undefined ? NameFromKeys<TFields> : TName;\n}\n\n/** Any compound constraint (for loose typing) */\nexport type AnyCompoundConstraint = CompoundConstraint<string[]>;\n\nexport type ToString<T> = T extends\n | string\n | number\n | bigint\n | boolean\n | null\n | undefined\n ? `${T}`\n : never;\n\nexport type StringKeyOf<T extends Record<string, any>> = {\n [K in keyof T]: K extends string ? K : never;\n}[keyof T];\n\nexport type ScalarKeys<T extends ModelShape> = {\n [K in keyof T]: T[K] extends Scalar ? ToString<K> : never;\n}[keyof T];\n\n/** Fixed-decimal list keys, which have value semantics but no key semantics. */\nexport type DecimalListScalarKeys<T extends ModelShape> = {\n [K in keyof T]: T[K] extends Scalar\n ? T[K][\"~\"][\"state\"] extends { type: \"decimal\"; array: true }\n ? ToString<K>\n : never\n : never;\n}[keyof T];\n\n/** GeoPoint keys have value semantics but no portable key/order semantics. */\nexport type PointScalarKeys<T extends ModelShape> = {\n [K in keyof T]: T[K] extends Scalar\n ? T[K][\"~\"][\"state\"][\"type\"] extends \"point\"\n ? ToString<K>\n : never\n : never;\n}[keyof T];\n\nexport type NonNullablePointScalarKeys<T extends ModelShape> = {\n [K in keyof T]: T[K] extends Scalar\n ? T[K][\"~\"][\"state\"][\"type\"] extends \"point\"\n ? T[K][\"~\"][\"state\"][\"nullable\"] extends true\n ? never\n : ToString<K>\n : never\n : never;\n}[keyof T];\n\nexport type NonPointScalarKeys<T extends ModelShape> = Exclude<\n ScalarKeys<T>,\n string extends keyof T ? never : PointScalarKeys<T>\n>;\n\n/** Scalar keys except fixed-decimal lists, which cannot be physical keys. */\nexport type NonDecimalListScalarKeys<T extends ModelShape> = Exclude<\n ScalarKeys<T>,\n string extends keyof T ? never : DecimalListScalarKeys<T>\n>;\n\n/** Scalar keys admitted in IDs, unique constraints, and foreign-key identity. */\nexport type PortableKeyScalarKeys<T extends ModelShape> = Exclude<\n NonDecimalListScalarKeys<T>,\n string extends keyof T ? never : PointScalarKeys<T>\n>;\n\n/** Extract relation keys from ModelState */\nexport type RelationKeys<T extends ModelShape> = {\n [K in keyof T]: T[K] extends AnyRelation ? ToString<K> : never;\n}[keyof T];\n\nexport type RequiredScalarKeys<T extends ModelShape> = {\n [K in keyof T]: T[K] extends Scalar\n ? T[K][\"~\"][\"state\"][\"optional\"] extends true\n ? never\n : ToString<K>\n : never;\n}[keyof T];\n\nexport type UniqueScalarKeys<T extends ModelShape> = {\n [K in keyof T]: T[K] extends Scalar\n ? T[K][\"~\"][\"state\"][\"isId\"] extends true\n ? ToString<K>\n : T[K][\"~\"][\"state\"][\"isUnique\"] extends true\n ? ToString<K>\n : never\n : never;\n}[keyof T];\n\n/** Numeric scalar types for aggregations (avg, sum) */\nexport type NumericScalarType = \"int\" | \"number\" | \"decimal\" | \"bigint\";\n\n/** Extract keys of numeric scalars from a ModelShape */\nexport type NumericScalarKeys<T extends ModelShape> = {\n [K in keyof T]: T[K] extends Scalar\n ? T[K][\"~\"][\"state\"][\"array\"] extends true\n ? never\n : T[K][\"~\"][\"state\"][\"type\"] extends NumericScalarType\n ? ToString<K>\n : never\n : never;\n}[keyof T];\n\nexport type ScalarMap<T extends ModelShape> = {\n [K in ScalarKeys<T>]: T[K] extends Scalar ? T[K] : never;\n};\n\nexport type RelationMap<T extends ModelShape> = {\n [K in RelationKeys<T>]: T[K] extends AnyRelation ? T[K] : never;\n};\n\nexport type UniqueScalarMap<T extends ModelShape> = {\n [K in UniqueScalarKeys<T>]: T[K] extends Scalar ? T[K] : never;\n};\n\n/**\n * ONE relation boundary, keyed on the internal brand.\n *\n * Trusted relation state originates only in `s.toOne` / `s.toMany`, and both\n * target domains carry `kind: \"relation\"` — so a model has one relation map and\n * no consumer has to ask which family a member belongs to. Scalars keep\n * `state.type`, so the two brands cannot collide.\n */\nfunction isRelation(value: unknown): value is AnyRelation {\n if (\n (typeof value !== \"object\" || value === null) &&\n typeof value !== \"function\"\n ) {\n return false;\n }\n const internal = Reflect.get(value, \"~\");\n if (typeof internal !== \"object\" || internal === null) return false;\n const state = Reflect.get(internal, \"state\");\n return (\n typeof state === \"object\" &&\n state !== null &&\n Reflect.get(state, \"kind\") === \"relation\"\n );\n}\n\nconst SCALAR_TYPES = new Set<string>([\n \"string\",\n \"int\",\n \"number\",\n \"decimal\",\n \"boolean\",\n \"datetime\",\n \"date\",\n \"time\",\n \"bigint\",\n \"json\",\n \"blob\",\n \"vector\",\n \"point\",\n \"enum\",\n]);\n\nfunction isScalar(value: unknown): value is Scalar {\n if (\n (typeof value !== \"object\" || value === null) &&\n typeof value !== \"function\"\n ) {\n return false;\n }\n const internal = Reflect.get(value, \"~\");\n if (typeof internal !== \"object\" || internal === null) return false;\n const state = Reflect.get(internal, \"state\");\n if (typeof state !== \"object\" || state === null) return false;\n const type = Reflect.get(state, \"type\");\n return typeof type === \"string\" && SCALAR_TYPES.has(type);\n}\n\n/**\n * The classified member maps are a PROJECTION of the shape: every member an\n * extractor recognizes appears in the map that claims it, under the key the\n * shape gave it. A shape key comes from the caller — a hand-written literal, a\n * generated schema, a JSON document's field name — so it can be any string, and\n * assigning into an ordinary object would lose a `__proto__` member to\n * `Object.prototype`'s setter. These maps come from `emptyRecord` and stay\n * private until complete: their null prototype makes every assignment an own\n * data entry, including `__proto__`, without defining a descriptor per member.\n *\n * Whether such a key is a LEGAL identifier is a separate question with a\n * separate owner (`isValidSchemaIdentifier`, enforced at hydration and by the\n * document reader). Keeping the member is what lets that owner name it.\n */\nexport const extractScalarMap = <T extends ModelShape>(fields: T) => {\n const scalars = emptyRecord<Scalar>();\n for (const [key, value] of Object.entries(fields)) {\n if (isScalar(value)) {\n scalars[key] = value;\n }\n }\n return scalars as ScalarMap<T>;\n};\n\n/**\n * The `s.model(...)` member-classification boundary for relations.\n *\n * It gains exactly ONE refusal: a transient references stage — a chain that\n * started `.fields(...)` and never received `.references(...)` — is rejected\n * loudly rather than silently dropped, because that member declares a foreign\n * key the schema would then never have. Every other unrecognized member keeps\n * its existing silent-drop behavior; widening that is a separate decision.\n */\nexport const extractRelationMap = <T extends ModelShape>(fields: T) => {\n const relations = emptyRecord<AnyRelation>();\n for (const [key, value] of Object.entries(fields)) {\n if (isRelation(value)) {\n relations[key] = value;\n } else if (isReferencesStage(value)) {\n refuseRelationInput(\n \"s.model\",\n key,\n `Relation '${key}' started \\`.fields(...)\\` without \\`.references(...)\\`; complete the foreign key before using it as a model field`\n );\n }\n }\n return relations as RelationMap<T>;\n};\n\nexport const extractUniqueScalarMap = <T extends ModelShape>(fields: T) => {\n const uniques = emptyRecord<Scalar>();\n for (const [key, value] of Object.entries(fields)) {\n if (\n isScalar(value) &&\n (value[\"~\"].state.isUnique || value[\"~\"].state.isId)\n ) {\n uniques[key] = value;\n }\n }\n return uniques as UniqueScalarMap<T>;\n};\n\nexport const getNameFromKeys = <\n Name extends string | undefined,\n TFields extends any[],\n>(\n name: Name,\n fields: TFields\n) => {\n return (\n name ??\n (fields.join(\"_\") as Name extends undefined ? NameFromKeys<TFields> : Name)\n );\n};\n","// Model Class Implementation\n// Defines database models with scalars and relations\n\nimport type { ObjectSchema, VibSchema } from \"@validation\";\nimport v from \"@validation/primitives/v\";\nimport { emptyRecord, put } from \"../record\";\nimport type { AnyRelation } from \"../relation\";\nimport type { Scalar } from \"../scalars/base\";\nimport type { HydratedSchemaNames, SchemaNames } from \"../scalars/common\";\nimport {\n type DeclaredModelShape,\n extractRelationMap,\n extractScalarMap,\n extractUniqueScalarMap,\n getNameFromKeys,\n type ModelShape,\n type NameFromKeys,\n type NonNullablePointScalarKeys,\n type PortableKeyScalarKeys,\n type RelationMap,\n type ScalarMap,\n type StringKeyOf,\n type UniqueScalarMap,\n} from \"./helper\";\n// Re-export types from helpers for external use\n\n// =============================================================================\n// TYPE INFERENCE HELPER\n// =============================================================================\n\nexport interface ModelState {\n shape: ModelShape;\n compoundId:\n | Record<string, ObjectSchema<Record<string, VibSchema>>>\n | undefined;\n compoundUniques:\n | Record<string, ObjectSchema<Record<string, VibSchema>>>\n | undefined;\n tableName: string | undefined;\n indexes: IndexDefinition[];\n omit: Record<string, true> | undefined;\n scalars: Record<string, Scalar>;\n /** ONE canonical relation map, holding both target domains in shape order. */\n relations: Record<string, AnyRelation>;\n uniques: Record<string, Scalar>;\n}\n\n/** Initial model projections stay named when a consumer emits recursive graphs. */\nexport interface InitialModelState<Shape extends ModelShape>\n extends ModelState {\n shape: Shape;\n scalars: ScalarMap<Shape>;\n relations: RelationMap<Shape>;\n uniques: UniqueScalarMap<Shape>;\n omit: undefined;\n}\n\n/**\n * Internal accessor return type for Model[\"~\"]\n * Explicit type annotation to avoid TS7056 (type too complex to serialize)\n */\nexport interface ModelInternal<T extends ModelState> {\n state: T;\n names: SchemaNames;\n nameRegistry: {\n fields: Map<string, SchemaNames>;\n };\n getFieldName: (key: string) => HydratedSchemaNames;\n /** Cached scalar field names (computed once on first access) */\n scalarFieldNames: string[];\n /** Cached relation names (computed once on first access) */\n relationNames: string[];\n}\n\n/**\n * The index kinds a schema may declare. The union is the whole of what any\n * dialect accepts, not what all of them accept — `validateIndexType` in\n * `migrations/drivers/base.ts` refuses each one on the dialects whose\n * `supportsIndexTypes` does not list it, by name, at push time.\n *\n * `fulltext` and `spatial` are here because MySQL's whole round trip already\n * exists and only this union could not spell it: the emitter writes the\n * `FULLTEXT`/`SPATIAL` prefix and refuses to combine either with `UNIQUE`\n * (`mysql/index.ts`), the introspection reads them back and normalizes MySQL's\n * `RTREE` to `spatial` (`mysql/introspect.ts`), the migration snapshot's\n * `IndexDef` already carries both (`migrations/types.ts`), and the capability\n * list already declares them. See Phase 10 item 6 in\n * `docs/architecture/query-performance-plan.md`.\n */\nexport type IndexType =\n | \"btree\"\n | \"hash\"\n | \"gin\"\n | \"gist\"\n | \"fulltext\"\n | \"spatial\";\n\nexport interface IndexOptions {\n name?: string;\n unique?: boolean;\n type?: IndexType;\n where?: string; // For partial indexes (PostgreSQL)\n}\n\ntype OrdinaryIndexOptions = Omit<IndexOptions, \"type\"> & {\n type?: Exclude<IndexType, \"spatial\">;\n};\n\ntype GeoPointSpatialIndexOptions = {\n name?: string;\n type: \"spatial\";\n unique?: never;\n where?: never;\n};\n\nexport interface IndexDefinition<\n Keys extends string[] = string[],\n O extends IndexOptions = IndexOptions,\n> {\n fields: Keys;\n options: O;\n}\n\n/** A partial index cannot constrain rows excluded by its predicate. */\nexport function isTotalIndex(options: Pick<IndexOptions, \"where\">): boolean {\n return !options.where;\n}\n\nexport type UpdateIndexDefinition<\n State extends ModelState,\n Index extends IndexDefinition,\n> = [...State[\"indexes\"], Index];\n\n/** The name a compound `.id()` / `.unique()` constraint may be given. */\nexport interface CompoundKeyOptions {\n name?: string;\n}\n\n/**\n * An options bag that carries the surface's own keys and NOTHING else.\n *\n * A generic `O extends Options` is no guard on its own: when inference produces\n * a bag the constraint would reject, TypeScript CLAMPS `O` to the constraint and\n * only excess-property checking is left to catch the stray key — and that needs\n * a fresh object literal, so `.index([\"a\"], sharedIndexOptions)` sails through\n * with `uniqu: true` recorded as nothing at all. Demanding `never` for the\n * unknown keys refuses structurally instead, whatever the argument's freshness.\n * Same instrument as `UnknownOmitKeys` below.\n */\ntype ExactOptions<Given, Allowed> = Given &\n Record<Exclude<keyof Given, keyof Allowed>, never>;\n\n/**\n * The constraint name: the caller's `name` when they gave one, otherwise the\n * underscore-joined field names. Read off the options bag rather than a separate\n * inferred parameter so that ONE type parameter carries the whole literal — the\n * parameter `ExactOptions` needs in order to see the unknown keys.\n */\ntype CompoundKeyName<\n Keys extends string[],\n O extends CompoundKeyOptions,\n> = O extends { name: infer N extends string } ? N : NameFromKeys<Keys>;\n\nexport const mergeIndexDefinitions = <\n State extends ModelState,\n Index extends IndexDefinition,\n>(\n state: State,\n index: Index\n): UpdateIndexDefinition<State, Index> => {\n return [...state.indexes, index] as UpdateIndexDefinition<State, Index>;\n};\n\n// Publish the same completed state as fluent returns so a legacy explicit\n// Model<UpdateState<...>> annotation retains exact relation-link identity.\nexport type UpdateState<\n State extends ModelState,\n Update extends Partial<ModelState>,\n> = {\n [P in keyof (Omit<State, keyof Update> & Update)]: (Omit<\n State,\n keyof Update\n > &\n Update)[P];\n};\n\n/**\n * The keys a proposed `.omit()` names that this model does NOT have as a\n * scalar: the typos and the relation names.\n *\n * `Hidden` is inferred from the argument's own keys and is deliberately NOT\n * constrained to the scalar names. A constrained type parameter is no guard\n * here: when inference produces something the constraint rejects, TypeScript\n * silently CLAMPS the parameter to the constraint and only excess-property\n * checking — which needs a fresh object literal — is left to catch the bad\n * key. Anything non-fresh (`as const`, a spread, an annotated variable, a\n * widened `Record<string, true>`) then sails through and records a\n * hidden-column claim nobody wrote. Excluding the unknown keys and demanding\n * `never` for them refuses structurally instead, whatever the argument's\n * freshness, and a `never` the caller cannot produce is a compile error at the\n * offending key.\n *\n * Relations are absent from the accepted set because `State[\"scalars\"]` is the\n * scalar half of the shape (`ScalarMap`), the same source `.index()` /\n * `.id()` / `.unique()` key off. Reading it never touches a relation's\n * `getter`, the member that must not be resolved while two model consts still\n * refer to each other (see `RelationState.getter`).\n */\ntype UnknownOmitKeys<Hidden extends string, State extends ModelState> = Exclude<\n Hidden,\n StringKeyOf<State[\"scalars\"]>\n>;\n\n/**\n * This model's scalar names, each optionally flagged `true`.\n *\n * It carries NO refusal — `UnknownOmitKeys` does that — and it adds no\n * requirement, every key being optional. It is in the parameter for one\n * reason: an editor offers the keys of a CONCRETE contextual type, and\n * `Record<Hidden, true>` is not concrete until `Hidden` has been inferred from\n * the very literal being typed. Without this member `.omit({ ` autocompletes\n * the global scope; with it, the model's scalars.\n */\nexport type ModelOmitInput<State extends ModelState> = Partial<\n Record<StringKeyOf<State[\"scalars\"]>, true>\n>;\n\n/**\n * Merge a new compound constraint into the existing record so repeated\n * .id()/.unique() calls accumulate instead of replacing each other.\n * Resolves to just `Added` when nothing was set yet.\n */\ntype MergeCompound<Existing, Added> = Added &\n (Existing extends Record<string, ObjectSchema<Record<string, VibSchema>>>\n ? Existing\n : unknown);\n\n/**\n * Resolve compound-key members to their base schemas, refusing any name that\n * is not a scalar of the model AT THE DECLARING SITE. The typed surface\n * already refuses these names; this throw is the runtime backstop for\n * untyped callers and JSON documents (the document interpreter relocates it\n * onto the `ids[]`/`uniques[]` node that wrote it), and it must fire on the\n * rule-free paths (`serializeModels`, `generate`,\n * `push({ skipValidation: true })`) that never run the advisory rules. I003\n * keeps its own coverage: post-construction shape drift (`.extends()`\n * shadowing a key member) is invisible to this constructor.\n *\n * A module function rather than a `Model` method: adding members to the class\n * perturbs how TS compares mutually-recursive model instantiations.\n */\nfunction compoundMembers(\n state: ModelState,\n fields: readonly string[],\n label: string\n): Record<string, VibSchema> {\n refuseDuplicateModelKeyMembers(fields, label);\n const members = emptyRecord<VibSchema>();\n for (const fieldName of fields) {\n // `in` is exact here: both maps come from the extractors, which build\n // prototype-free records, so no key can resolve an inherited member.\n const scalar =\n fieldName in state.scalars ? state.scalars[fieldName] : undefined;\n if (!scalar) {\n throw new Error(\n fieldName in state.relations\n ? `${label} field '${fieldName}' is a relation and cannot be a key member`\n : `${label} field '${fieldName}' does not exist`\n );\n }\n put(members, fieldName, scalar[\"~\"].state.base);\n }\n return members;\n}\n\n/**\n * One compound ID or unique, written into its own slot. The first tuple of a\n * name is preserved before Record storage could overwrite it.\n */\nfunction withCompound(\n state: ModelState,\n slot: \"compoundId\" | \"compoundUniques\",\n label: \"Compound ID\" | \"Compound unique\",\n fields: readonly string[],\n options: CompoundKeyOptions | undefined\n): Model<any> {\n const storedFields = snapshotModelKeyMembers(fields, label);\n const name = getNameFromKeys(options?.name, storedFields);\n if (Object.hasOwn(state[slot] ?? {}, name)) {\n throw new Error(\n `${label} name '${name}' is already used by another compound key; give this tuple a distinct name`\n );\n }\n const fieldsRecord = compoundMembers(state, storedFields, label);\n return new Model({\n ...state,\n [slot]: {\n ...state[slot],\n [name]: v.object(fieldsRecord, { partial: false }),\n },\n });\n}\n\n/** Snapshot one declaration tuple without consulting caller iteration hooks. */\nfunction snapshotModelKeyMembers(fields: unknown, label: string): string[] {\n if (!Array.isArray(fields)) {\n throw new Error(`${label} fields must be a dense array of strings`);\n }\n const memberCount = fields.length;\n const members = new Array<string>(memberCount);\n for (let position = 0; position < memberCount; position++) {\n if (!Object.hasOwn(fields, position)) {\n throw new Error(`${label} fields must be a dense array of strings`);\n }\n const member: unknown = fields[position];\n if (typeof member !== \"string\") {\n throw new Error(`${label} fields must be a dense array of strings`);\n }\n members[position] = member;\n }\n return members;\n}\n\n/** Snapshot the four public index options, including inherited accessors. */\nfunction snapshotIndexOptions(options: IndexOptions): IndexOptions {\n const name = options.name;\n const unique = options.unique;\n const type = options.type;\n const where = options.where;\n return {\n ...(name === undefined ? {} : { name }),\n ...(unique === undefined ? {} : { unique }),\n ...(type === undefined ? {} : { type }),\n ...(where === undefined ? {} : { where }),\n };\n}\n\n/** One physical key/index tuple cannot name the same column twice. */\nfunction refuseDuplicateModelKeyMembers(\n fields: readonly string[],\n label: string\n): void {\n if (new Set(fields).size !== fields.length) {\n throw new Error(`${label} cannot repeat a field in one tuple`);\n }\n}\n\n/**\n * Name registry for scalars and relations.\n * Maps scalar/relation keys to their resolved names (ts and sql).\n * This is populated during hydration.\n */\nexport interface NameRegistry {\n /** Scalar names: key -> {ts, sql} */\n fields: Map<string, SchemaNames>;\n}\n\nexport class Model<State extends ModelState> {\n // biome-ignore lint/style/useReadonlyClassProperties: <it is reassigned when hydrating schemas>\n #names: SchemaNames = {};\n // biome-ignore lint/style/useReadonlyClassProperties: <it is reassigned when hydrating schemas>\n #nameRegistry: NameRegistry = {\n fields: new Map(),\n };\n readonly #state: State;\n\n // Cached field metadata (lazily computed on first access)\n #scalarFieldNames: string[] | undefined;\n #relationNames: string[] | undefined;\n #internal: ModelInternal<State> | undefined;\n\n constructor(state: State) {\n this.#state = state;\n }\n\n // Materialize each completed modifier state inline before a recursive getter\n // captures it. A helper alias retains the whole prior modifier chain.\n /**\n * Maps the model to a specific database table name\n */\n map<Name extends string>(tableName: Name) {\n return new Model({ ...this.#state, tableName }) as unknown as Model<{\n [KState in keyof UpdateState<State, { tableName: Name }>]: UpdateState<\n State,\n { tableName: Name }\n >[KState];\n }>;\n }\n\n /**\n * Hide scalars from every result of this model — the schema-level exclusion.\n *\n * Keyed to the model's own SCALARS, so a typo or a relation name is a\n * compile error instead of an `omit` that quietly hides nothing. That\n * matters more here than anywhere else the builder takes field names: this\n * is the spelling used for secrets, and a silently-ignored key is a leaked\n * column. The refusal is per KEY, not per call: `{ secret: true, tokne:\n * true }` fails on `tokne` even though `secret` is real — two secrets with\n * one misspelled is the realistic case, and it is exactly the case an\n * excess-property-only refusal would wave through (see `UnknownOmitKeys`).\n *\n * Every value must be `true`. `false` has no meaning here (model-level omit\n * only ever hides) and a flag that may be `undefined` hides nothing at\n * runtime — `projectableScalarNames` compares against `true` — so\n * `Record<Hidden, true>` refuses both rather than recording a claim the\n * runtime would not honor.\n *\n * The literal survives the round trip — `.omit({ secret: true })` carries\n * exactly `{ secret: true }` into the state, not a widened record — which is\n * what every downstream `keyof State[\"omit\"]` reads. `Hidden` defaults to\n * `never` for the one call with nothing to infer from, `.omit({})`: a bare\n * `extends string` would fall back to `string` there and hand the state a\n * record keyed by every conceivable name.\n */\n omit<Hidden extends string = never>(\n items: Record<Hidden, true> &\n Record<UnknownOmitKeys<Hidden, State>, never> &\n ModelOmitInput<State>\n ) {\n return new Model({\n ...this.#state,\n omit: items,\n }) as unknown as Model<{\n [KState in keyof UpdateState<\n State,\n { omit: Record<Hidden, true> }\n >]: UpdateState<State, { omit: Record<Hidden, true> }>[KState];\n }>;\n }\n\n index<\n const Keys extends PortableKeyScalarKeys<State[\"scalars\"]>[],\n O extends OrdinaryIndexOptions = OrdinaryIndexOptions,\n >(\n fields: Keys,\n options?: ExactOptions<O, OrdinaryIndexOptions>\n ): Model<{\n [KState in keyof UpdateState<\n State,\n { indexes: UpdateIndexDefinition<State, { fields: Keys; options: O }> }\n >]: UpdateState<\n State,\n { indexes: UpdateIndexDefinition<State, { fields: Keys; options: O }> }\n >[KState];\n }>;\n index<\n const Key extends NonNullablePointScalarKeys<State[\"scalars\"]>,\n const O extends GeoPointSpatialIndexOptions,\n >(\n fields: [Key],\n options: ExactOptions<O, GeoPointSpatialIndexOptions>\n ): Model<{\n [KState in keyof UpdateState<\n State,\n { indexes: UpdateIndexDefinition<State, { fields: [Key]; options: O }> }\n >]: UpdateState<\n State,\n { indexes: UpdateIndexDefinition<State, { fields: [Key]; options: O }> }\n >[KState];\n }>;\n index(fields: string[], options: IndexOptions = {}): Model<any> {\n const storedFields = snapshotModelKeyMembers(fields, \"Index\");\n refuseDuplicateModelKeyMembers(storedFields, \"Index\");\n const storedOptions = snapshotIndexOptions(options);\n return new Model({\n ...this.#state,\n indexes: mergeIndexDefinitions(this.#state, {\n fields: storedFields,\n options: storedOptions,\n }),\n });\n }\n\n id<\n const Keys extends PortableKeyScalarKeys<State[\"scalars\"]>[],\n const O extends CompoundKeyOptions = Record<never, never>,\n >(fields: Keys, options?: ExactOptions<O, CompoundKeyOptions>) {\n return withCompound(\n this.#state,\n \"compoundId\",\n \"Compound ID\",\n fields,\n options\n ) as unknown as Model<{\n [KState in keyof UpdateState<\n State,\n {\n compoundId: MergeCompound<\n State[\"compoundId\"],\n {\n [K in CompoundKeyName<Keys, O>]: ObjectSchema<{\n [K2 in Keys[number]]: State[\"scalars\"][K2][\"~\"][\"state\"][\"base\"];\n }>;\n }\n >;\n }\n >]: UpdateState<\n State,\n {\n compoundId: MergeCompound<\n State[\"compoundId\"],\n {\n [K in CompoundKeyName<Keys, O>]: ObjectSchema<{\n [K2 in Keys[number]]: State[\"scalars\"][K2][\"~\"][\"state\"][\"base\"];\n }>;\n }\n >;\n }\n >[KState];\n }>;\n }\n\n unique<\n const Keys extends PortableKeyScalarKeys<State[\"scalars\"]>[],\n const O extends CompoundKeyOptions = Record<never, never>,\n >(fields: Keys, options?: ExactOptions<O, CompoundKeyOptions>) {\n return withCompound(\n this.#state,\n \"compoundUniques\",\n \"Compound unique\",\n fields,\n options\n ) as unknown as Model<{\n [KState in keyof UpdateState<\n State,\n {\n compoundUniques: MergeCompound<\n State[\"compoundUniques\"],\n {\n [K in CompoundKeyName<Keys, O>]: ObjectSchema<{\n [K2 in Keys[number]]: State[\"scalars\"][K2][\"~\"][\"state\"][\"base\"];\n }>;\n }\n >;\n }\n >]: UpdateState<\n State,\n {\n compoundUniques: MergeCompound<\n State[\"compoundUniques\"],\n {\n [K in CompoundKeyName<Keys, O>]: ObjectSchema<{\n [K2 in Keys[number]]: State[\"scalars\"][K2][\"~\"][\"state\"][\"base\"];\n }>;\n }\n >;\n }\n >[KState];\n }>;\n }\n\n extends<ETShape extends DeclaredModelShape>(shape: ETShape) {\n const newShape = { ...this.#state.shape, ...shape } as State[\"shape\"] &\n ETShape;\n return new Model({\n ...this.#state,\n shape: newShape,\n scalars: extractScalarMap(newShape),\n relations: extractRelationMap(newShape),\n uniques: extractUniqueScalarMap(newShape),\n }) as unknown as Model<\n UpdateState<\n State,\n {\n shape: State[\"shape\"] & ETShape;\n scalars: ScalarMap<State[\"shape\"] & ETShape>;\n relations: RelationMap<State[\"shape\"] & ETShape>;\n uniques: UniqueScalarMap<State[\"shape\"] & ETShape>;\n }\n >\n >;\n }\n\n get \"~\"(): ModelInternal<State> {\n if (this.#internal) {\n return this.#internal;\n }\n // Capture model instance for use in getters\n const model = this;\n\n this.#internal = {\n state: this.#state,\n // getters so hydration after first access is still observed\n get names() {\n return model.#names;\n },\n get nameRegistry() {\n return model.#nameRegistry;\n },\n /**\n * Get the resolved names for a field.\n * Throws if the schema has not been hydrated.\n */\n getFieldName: (key: string): HydratedSchemaNames => {\n const registered = model.#nameRegistry.fields.get(key);\n if (registered) {\n return registered as HydratedSchemaNames;\n }\n throw new Error(`Scalar \"${key}\" not found in nameRegistry`);\n },\n /** Cached scalar field names (computed once on first access) */\n get scalarFieldNames(): string[] {\n return (model.#scalarFieldNames ??= Object.keys(model.#state.scalars));\n },\n /** Cached relation names (computed once on first access) */\n get relationNames(): string[] {\n return (model.#relationNames ??= Object.keys(model.#state.relations));\n },\n };\n return this.#internal;\n }\n}\n\nexport const model = <TShape extends DeclaredModelShape>(\n shape: TShape\n): Model<InitialModelState<TShape>> =>\n new Model({\n compoundId: undefined,\n compoundUniques: undefined,\n tableName: undefined,\n indexes: [],\n omit: undefined,\n shape,\n scalars: extractScalarMap(shape),\n relations: extractRelationMap(shape),\n uniques: extractUniqueScalarMap(shape),\n });\n\nexport type AnyModel = Model<any>;\n\n/**\n * SQL table name for a model: hydrated name, then .map() tableName, then\n * the given fallback.\n */\nexport function getTableName(model: AnyModel, fallback = \"unknown\"): string {\n return model[\"~\"].names.sql ?? model[\"~\"].state.tableName ?? fallback;\n}\n\n/**\n * SQL column name for a field, resolved through the model's nameRegistry\n * (supports field reuse across models) with .map() and field-name fallbacks.\n */\nexport function getColumnName(model: AnyModel, fieldName: string): string {\n return model[\"~\"].getFieldName(fieldName).sql;\n}\n"],"mappings":"iMAsBA,SAAgB,aAAoC,CAClD,OAAO,OAAO,OAAO,KAAK,CAI5B,SAAgB,IAAO,EAA2B,EAAa,EAAgB,CAC7E,OAAO,eAAe,EAAQ,EAAK,CACjC,QACA,WAAY,GACZ,SAAU,GACV,aAAc,GACf,CAAC,CAIJ,SAAgB,IACd,EACA,EACe,CACX,SAAW,IAAA,IAAa,CAAC,OAAO,OAAO,EAAQ,EAAI,EACvD,OAAO,EAAO,GCFhB,MAAM,EAAe,sCAEf,EAAqB,CAAC,QAAS,SAAU,SAAS,CAuIxD,SAAgB,wBACd,EACA,EACA,EACwC,CACnC,EAAc,EAAS,EAC1B,EACE,EACA,SACA,0FACD,CAEH,IAAM,EAAc,EAAa,EAAS,CACtC,EAAY,SAAW,GACzB,EACE,EACA,SACA,2CACD,CAEH,IAAM,EAAe,iBAAiB,EAAS,EAAa,EAAQ,CAC9D,EAAwC,EAAE,CAChD,IAAK,IAAM,KAAc,EAAa,CAC/B,EAAwB,EAAW,EACtC,EACE,EACA,UAAU,IACV,gBAAgB,EAAW,oCAC5B,CAEH,IAAM,EAAS,EACb,EACA,EACA,EACA,UAAU,IACX,CACG,OAAO,GAAW,YACpB,EACE,EACA,UAAU,IACV,YAAY,EAAW,6EACxB,CAEH,EAAQ,GAAc,OAAO,OAAO,CAClC,SACA,YAAa,EAAa,IAAe,EAC1C,CAAC,CAEJ,OAAO,OAAO,OAAO,EAAQ,CAS/B,SAAS,iBACP,EACA,EACA,EACwB,CACxB,GAAI,IAAY,IAAA,GAAW,MAAO,EAAE,CAC/B,EAAc,EAAQ,EACzB,EACE,EACA,UACA,sHACD,CAEE,EAAa,EAAa,EAAQ,CAAE,CAAC,SAAS,CAAC,EAClD,EACE,EACA,UACA,kHACD,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C,EAAgB,CAC1D,IAAM,EAAW,CAAE,GAAG,MAAA,EAAY,MAAO,GAAG,EAAO,CAEnD,OAAO,IAAI,MAAM,CACf,GAAG,MAAA,EACH,MAAO,EACP,QAAS,iBAAiB,EAAS,CACnC,UAAW,mBAAmB,EAAS,CACvC,QAAS,uBAAuB,EAAS,CAC1C,CAAC,CAaJ,GAAI,KAA4B,CAC9B,GAAI,MAAA,EACF,OAAO,MAAA,EAGT,IAAMG,EAAQ,KA+Bd,MA7BA,OAAA,EAAiB,CACf,MAAO,MAAA,EAEP,IAAI,OAAQ,CACV,OAAOA,GAAAA,GAET,IAAI,cAAe,CACjB,OAAOA,GAAAA,GAMT,aAAe,GAAqC,CAClD,IAAM,EAAaA,GAAAA,EAAoB,OAAO,IAAI,EAAI,CACtD,GAAI,EACF,OAAO,EAET,MAAU,MAAM,WAAW,EAAI,6BAA6B,EAG9D,IAAI,kBAA6B,CAC/B,MAAQ,IAAA,IAA4B,OAAO,KAAKA,GAAAA,EAAa,QAAQ,EAGvE,IAAI,eAA0B,CAC5B,MAAQ,IAAA,IAAyB,OAAO,KAAKA,GAAAA,EAAa,UAAU,EAEvE,CACM,MAAA,IAIX,MAAa,MACX,GAEA,IAAI,EAAM,CACR,WAAY,IAAA,GACZ,gBAAiB,IAAA,GACjB,UAAW,IAAA,GACX,QAAS,EAAE,CACX,KAAM,IAAA,GACN,QACA,QAAS,iBAAiB,EAAM,CAChC,UAAW,mBAAmB,EAAM,CACpC,QAAS,uBAAuB,EAAM,CACvC,CAAC,CAQJ,SAAgB,aAAa,EAAiB,EAAW,UAAmB,CAC1E,OAAOA,EAAM,KAAK,MAAM,KAAOA,EAAM,KAAK,MAAM,WAAa,EAO/D,SAAgB,cAAc,EAAiB,EAA2B,CACxE,OAAOA,EAAM,KAAK,aAAa,EAAU,CAAC"}
1
+ {"version":3,"file":"model-D94xU8jq.mjs","names":["#state","#internal","#state","#internal","#withForeignKeyAction","#localFields","v","#state","#internal","model","#names","#nameRegistry","#scalarFieldNames","#relationNames"],"sources":["../src/schema/record.ts","../src/schema/relation/polymorphic.ts","../src/schema/relation/to-one.ts","../src/schema/model/helper.ts","../src/schema/model/model.ts"],"sourcesContent":["// Records keyed by DATA.\n//\n// A schema is built from maps whose keys come from somewhere else: a model\n// shape's field key, a document's model/field/variant key, an enum reference, a\n// default's own object keys. `record[key] = value` is not a safe way to build\n// such a map, because `__proto__` is an accessor on `Object.prototype`:\n// assigning through it sets a prototype and creates NO own key. The entry\n// disappears, and what is left is a well-formed object, so nothing downstream\n// can notice the loss.\n//\n// Reading has the mirror problem: `record[key]` resolves inherited members, so\n// a data key of `__proto__`, `constructor` or `toString` answers something the\n// map never held.\n//\n// One owner for both, used everywhere a key comes from data — the JSON\n// document's maps and `s.model(...)`'s classified member maps alike. It carries\n// no refusal: whether a key is a legal identifier is `isValidSchemaIdentifier`'s\n// question, asked at hydration and by the document reader, and the answer is the\n// same whichever way the key was written. The document READER needs neither\n// helper, because it asks that question before anything is written.\n\n/** A map with no inherited members, so a data key can only find what was put. */\nexport function emptyRecord<T>(): Record<string, T> {\n return Object.create(null);\n}\n\n/** Write one own key, whatever it is called. */\nexport function put<T>(target: Record<string, T>, key: string, value: T): void {\n Object.defineProperty(target, key, {\n value,\n enumerable: true,\n writable: true,\n configurable: true,\n });\n}\n\n/** Read one own key, or nothing. */\nexport function own<T>(\n source: Record<string, T> | undefined,\n key: string\n): T | undefined {\n if (source === undefined || !Object.hasOwn(source, key)) return;\n return source[key];\n}\n","// Variant target domains: the normalization owner and the two variant terminals.\n//\n// \"Polymorphic\" is not a relation family. It is the derived observation that a\n// declaration's TARGET DOMAIN holds named variants instead of one model, which\n// is why the two variant terminals are reached through the same `s.toOne` /\n// `s.toMany` factories as the model-target ones. What is irreducibly different\n// is the legal local configuration: a row-held variant to-one may be\n// `.optional()` and owns no public foreign key, and a member-junction variant\n// to-many names one junction per variant through an exact `.through(...)` map.\n\nimport type { Model } from \"@schema/model\";\nimport type { Scalar } from \"@schema/scalars/base\";\nimport { isValidSchemaIdentifier } from \"../identifier\";\nimport {\n createTargetSettlement,\n declaredKeys,\n hasExactKeys,\n isPlainRecord,\n normalizeRelationName,\n type RelationBuilder,\n readCallerProperty,\n refuseRelationInput,\n} from \"./terminal\";\nimport type {\n AnyRelation,\n Getter,\n RelationInternal,\n Replace,\n VariantEntry,\n VariantJunctionOverride,\n VariantManyEntry,\n VariantToManyState,\n VariantToOneState,\n} from \"./types\";\n\n/**\n * The stored-discriminator grammar. A stored value is written to a physical\n * column and read back by migrations and predicates, so it admits namespaced\n * and versioned spellings the public variant key does not.\n */\nconst STORED_VALUE = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,190}$/;\n\nconst THROUGH_ENTRY_KEYS = [\"table\", \"source\", \"target\"] as const;\n\n// =============================================================================\n// FACTORY-LEVEL TYPES\n// =============================================================================\n\nexport type VariantGetterMap = Readonly<Record<string, Getter>>;\n\n/**\n * The map overload's phantom refusal.\n *\n * It is NOT redundant with {@link GetterOnly}. With the map overload first and\n * an unconstrained getter overload second, a structurally-map argument that\n * fails this guard would otherwise fall through to the getter overload, whose\n * conditional return answers `never` — and `never` is assignable to a model\n * shape, so the refusal would disappear entirely. This guard uniquely owns\n * \"structurally a map, but not a legal variant map\"; `GetterOnly` uniquely owns\n * \"not a map at all and not a getter\".\n */\nexport type VariantMapGuard<Entries> = string extends keyof Entries\n ? {\n readonly \"a variant map needs literal keys, not a string index signature\": never;\n }\n : [keyof Entries] extends [never]\n ? { readonly \"a variant map needs at least one variant\": never }\n : unknown;\n\nexport type VariantOptions<Entries> = {\n readonly values: { readonly [Key in keyof Entries]: string };\n};\n\n/**\n * The whole options bag is exact, not only `values`: a NON-FRESH bag with a\n * sibling key beside `values` sails through excess-property checking, so the\n * unknown keys are refused structurally.\n */\nexport type ExactVariantOptions<Options, Entries> = Options extends undefined\n ? unknown\n : Record<Exclude<keyof Options, \"values\">, never> & {\n readonly values: Record<\n Exclude<\n keyof (Options extends { readonly values: infer Values }\n ? Values\n : never),\n keyof Entries\n >,\n never\n >;\n };\n\n/**\n * Normalized entries carry the getter's exact type and a plain `string` stored\n * value: the stored discriminator is runtime storage, never a public result\n * discriminator, so carrying its literal would be a public type parameter no\n * consumer reads.\n */\nexport type NormalizedOneEntries<Entries> = {\n readonly [Key in keyof Entries]: {\n readonly getter: Entries[Key];\n readonly storedValue: string;\n };\n};\n\nexport type NormalizedManyEntries<Entries> = {\n readonly [Key in keyof Entries]: {\n readonly getter: Entries[Key];\n readonly storedValue: string;\n readonly junction?: VariantJunctionOverride;\n };\n};\n\ntype VariantEntriesOfState<State> = State extends {\n readonly target: { readonly entries: infer Entries };\n}\n ? Entries\n : never;\n\ntype VariantThroughMap<Entries> = {\n readonly [Key in keyof Entries]: VariantJunctionOverride;\n};\n\ntype ExactVariantThroughMap<Given, Entries> = Record<\n Exclude<keyof Given, keyof Entries>,\n never\n> & {\n readonly [Key in keyof Given]: Record<\n Exclude<keyof Given[Key], keyof VariantJunctionOverride>,\n never\n >;\n};\n\n// =============================================================================\n// TERMINAL CAPABILITY SURFACES\n// =============================================================================\n\n/** A slot that holds at most one membership across its variants. */\nexport type VariantToOneRelation<State> = {\n readonly \"~\": RelationInternal<State>;\n name<const Name extends string>(\n name: Name\n ): VariantToOneRelation<Replace<State, { readonly name: Name }>>;\n optional(): VariantToOneRelation<Replace<State, { readonly optional: true }>>;\n};\n\n/**\n * A slot that holds a collection across its variants. No `.optional()`: an\n * empty collection is already the empty case.\n */\nexport type VariantToManyRelation<State> = {\n readonly \"~\": RelationInternal<State>;\n name<const Name extends string>(\n name: Name\n ): VariantToManyRelation<Replace<State, { readonly name: Name }>>;\n through<\n const ThroughMap extends VariantThroughMap<VariantEntriesOfState<State>>,\n >(\n map: ThroughMap &\n ExactVariantThroughMap<ThroughMap, VariantEntriesOfState<State>>\n ): VariantToManyRelation<State>;\n};\n\n// =============================================================================\n// NORMALIZATION\n// =============================================================================\n\n/**\n * Read the target map and its options ONCE, judge every structurally knowable\n * fact, and build the single normalized entry map. There is no separately\n * stored `targets`, `values` or `through` map to keep in sync.\n *\n * Every own property at both map levels is read exactly once here and pinned as\n * a plain value: a live accessor could otherwise answer validation with one\n * value and the storage builder with another. Reading a property's value does\n * not invoke a target thunk; getters are stored as functions and stay lazy.\n */\nexport function normalizeVariantEntries(\n builder: RelationBuilder,\n variants: unknown,\n options: unknown\n): Readonly<Record<string, VariantEntry>> {\n if (!isPlainRecord(variants)) {\n refuseRelationInput(\n builder,\n \"target\",\n \"A relation target is either `() => model` or a plain map of named `() => model` getters\"\n );\n }\n const variantKeys = declaredKeys(variants);\n if (variantKeys.length === 0) {\n refuseRelationInput(\n builder,\n \"target\",\n \"A variant map needs at least one variant\"\n );\n }\n const storedValues = readStoredValues(builder, variantKeys, options);\n const entries: Record<string, VariantEntry> = {};\n for (const variantKey of variantKeys) {\n if (!isValidSchemaIdentifier(variantKey)) {\n refuseRelationInput(\n builder,\n `target.${variantKey}`,\n `Variant key '${variantKey}' is not a valid schema identifier`\n );\n }\n const getter = readCallerProperty(\n builder,\n variants,\n variantKey,\n `target.${variantKey}`\n );\n if (typeof getter !== \"function\") {\n refuseRelationInput(\n builder,\n `target.${variantKey}`,\n `Variant '${variantKey}' must be a lazy getter; write \\`() => model\\` rather than the model itself`\n );\n }\n entries[variantKey] = Object.freeze({\n getter,\n storedValue: storedValues[variantKey] ?? variantKey,\n });\n }\n return Object.freeze(entries);\n}\n\n/**\n * The stored discriminator per variant: each public key by default, or the\n * exact `values` bag when one is supplied. An explicit `undefined` is\n * equivalent to omission; `{}` is not, because it declares an options bag\n * without the one option it may carry.\n */\nfunction readStoredValues(\n builder: RelationBuilder,\n variantKeys: readonly string[],\n options: unknown\n): Record<string, string> {\n if (options === undefined) return {};\n if (!isPlainRecord(options)) {\n refuseRelationInput(\n builder,\n \"options\",\n \"Relation options must be a plain `{ values }` record; omit the argument to use each variant key as its stored value\"\n );\n }\n if (!hasExactKeys(declaredKeys(options), [\"values\"])) {\n refuseRelationInput(\n builder,\n \"options\",\n \"Relation options carry exactly one key, `values`; omit the argument to use each variant key as its stored value\"\n );\n }\n const values = readCallerProperty(\n builder,\n options,\n \"values\",\n \"options.values\"\n );\n if (!isPlainRecord(values)) {\n refuseRelationInput(\n builder,\n \"options.values\",\n \"`values` must be a plain record keyed by every variant\"\n );\n }\n const valueKeys = declaredKeys(values);\n if (!hasExactKeys(valueKeys, variantKeys)) {\n refuseRelationInput(\n builder,\n \"options.values\",\n `\\`values\\` must be exact over the variant keys ${renderKeys(variantKeys)}; it declares ${renderKeys(valueKeys)}`\n );\n }\n const storedValues: Record<string, string> = {};\n const claimed = new Set<string>();\n for (const variantKey of variantKeys) {\n const storedValue = readCallerProperty(\n builder,\n values,\n variantKey,\n `options.values.${variantKey}`\n );\n if (typeof storedValue !== \"string\" || !STORED_VALUE.test(storedValue)) {\n refuseRelationInput(\n builder,\n `options.values.${variantKey}`,\n `Stored value for variant '${variantKey}' must match the stored-discriminator grammar`\n );\n }\n if (claimed.has(storedValue)) {\n refuseRelationInput(\n builder,\n `options.values.${variantKey}`,\n `Stored value '${storedValue}' is declared for more than one variant`\n );\n }\n claimed.add(storedValue);\n storedValues[variantKey] = storedValue;\n }\n return storedValues;\n}\n\nfunction renderKeys(keys: readonly string[]): string {\n return `[${keys.map((key) => `'${key}'`).join(\", \")}]`;\n}\n\n/**\n * Fold one member-junction override into each normalized entry. The outer map\n * is exact over the variants and every inner value is exact — the runtime\n * mirror of the `.through()` type contract, and the reason there is no second\n * `through` map to keep in sync with the entries.\n */\nfunction foldMemberJunctions(\n entries: Readonly<Record<string, VariantEntry>>,\n through: unknown\n): Readonly<Record<string, VariantManyEntry>> {\n const variantKeys = Object.keys(entries);\n if (!isPlainRecord(through)) {\n refuseRelationInput(\n \"s.toMany\",\n \"through\",\n \"`.through()` takes a plain map keyed by every variant\"\n );\n }\n if (!hasExactKeys(declaredKeys(through), variantKeys)) {\n refuseRelationInput(\n \"s.toMany\",\n \"through\",\n `\\`.through()\\` must be exact over the variant keys ${renderKeys(variantKeys)}`\n );\n }\n const folded: Record<string, VariantManyEntry> = {};\n for (const [variantKey, entry] of Object.entries(entries)) {\n const override = readCallerProperty(\n \"s.toMany\",\n through,\n variantKey,\n `through.${variantKey}`\n );\n folded[variantKey] = Object.freeze({\n ...entry,\n junction: readJunctionOverride(variantKey, override),\n });\n }\n return Object.freeze(folded);\n}\n\nfunction readJunctionOverride(\n variantKey: string,\n override: unknown\n): VariantJunctionOverride {\n const path = `through.${variantKey}`;\n if (!isPlainRecord(override)) {\n refuseRelationInput(\n \"s.toMany\",\n path,\n `Member junction '${variantKey}' must be a plain \\`{ table, source, target }\\` record`\n );\n }\n const table = readCallerProperty(\n \"s.toMany\",\n override,\n \"table\",\n `${path}.table`\n );\n const source = readCallerProperty(\n \"s.toMany\",\n override,\n \"source\",\n `${path}.source`\n );\n const target = readCallerProperty(\n \"s.toMany\",\n override,\n \"target\",\n `${path}.target`\n );\n if (\n !hasExactKeys(declaredKeys(override), THROUGH_ENTRY_KEYS) ||\n typeof table !== \"string\" ||\n typeof source !== \"string\" ||\n typeof target !== \"string\"\n ) {\n refuseRelationInput(\n \"s.toMany\",\n path,\n `Member junction '${variantKey}' declares exactly \\`table\\`, \\`source\\` and \\`target\\`, all strings`\n );\n }\n return Object.freeze({ table, source, target });\n}\n\n// =============================================================================\n// TERMINALS\n// =============================================================================\n\n/**\n * Private terminal machinery. None of the four terminal classes is exported\n * from its module, let alone from the package: callers see only the\n * capabilities the two factories return. The two constructor helpers below are\n * the whole cross-module surface.\n */\nclass VariantToOne {\n readonly #state: VariantToOneState;\n readonly #internal: RelationInternal<VariantToOneState>;\n\n constructor(state: VariantToOneState) {\n this.#state = Object.freeze(state);\n this.#internal = Object.freeze({\n state: this.#state,\n settleTarget: createTargetSettlement((variantKey) =>\n readVariantGetter(this.#state, variantKey)\n ),\n });\n }\n\n name(name: string): VariantToOne {\n return new VariantToOne({\n ...this.#state,\n name: normalizeRelationName(\"s.toOne\", name),\n });\n }\n\n optional(): VariantToOne {\n return new VariantToOne({ ...this.#state, optional: true });\n }\n\n get \"~\"(): RelationInternal<VariantToOneState> {\n return this.#internal;\n }\n}\n\nclass VariantToMany {\n readonly #state: VariantToManyState;\n readonly #internal: RelationInternal<VariantToManyState>;\n\n constructor(state: VariantToManyState) {\n this.#state = Object.freeze(state);\n this.#internal = Object.freeze({\n state: this.#state,\n settleTarget: createTargetSettlement((variantKey) =>\n readVariantGetter(this.#state, variantKey)\n ),\n });\n }\n\n name(name: string): VariantToMany {\n return new VariantToMany({\n ...this.#state,\n name: normalizeRelationName(\"s.toMany\", name),\n });\n }\n\n through(map: unknown): VariantToMany {\n return new VariantToMany({\n ...this.#state,\n target: {\n kind: \"variants\",\n entries: foldMemberJunctions(this.#state.target.entries, map),\n },\n });\n }\n\n get \"~\"(): RelationInternal<VariantToManyState> {\n return this.#internal;\n }\n}\n\n/** Construct the row-held variant terminal for `s.toOne`. */\nexport function variantToOneTerminal(state: VariantToOneState): AnyRelation {\n return new VariantToOne(state);\n}\n\n/** Construct the member-junction variant terminal for `s.toMany`. */\nexport function variantToManyTerminal(state: VariantToManyState): AnyRelation {\n return new VariantToMany(state);\n}\n\nfunction readVariantGetter(\n state: VariantToOneState | VariantToManyState,\n variantKey: string | undefined\n): unknown {\n if (variantKey === undefined) return undefined;\n const entry = state.target.entries[variantKey];\n return entry === undefined ? undefined : entry.getter;\n}\n\n// =============================================================================\n// RESOLVED VARIANT STORAGE COLUMN\n// =============================================================================\n// Resolution OUTPUT, not declaration state: one private column the variant\n// row-storage owner derives, carried on the resolved edge and read by the\n// serializer and the engine. The descriptors that used to sit beside it are\n// gone — the resolved edge IS the topology, and a second copy of it on the\n// model was a second answer to every question the edge already answers.\n\nexport interface PolymorphicStorageColumn {\n readonly name: string;\n readonly scalar: Scalar;\n readonly nullable: boolean;\n /**\n * The KEY this private column stands in for, when it stands in for one.\n *\n * A row carrier's id column holds every variant's primary key, and what\n * those keys hold — an identifier domain above all — may be DERIVED rather\n * than declared: the ordinary one-to-one child whose primary key IS its\n * parent foreign key declares nothing and still holds uuids. The scalar\n * alone cannot answer that (derivation is keyed by model and field, never by\n * a scalar instance two models may share), so the column carries the pair\n * the one lookup takes. Every variant's key agrees on the answer or the\n * carrier does not exist — that agreement is what the identifier-domain\n * derivation refuses when it fails — so the FIRST member's key is the\n * carrier's key.\n *\n * The type discriminator column stands in for no key and carries none.\n */\n readonly reference?: {\n readonly model: Model<any>;\n readonly field: string;\n };\n}\n","// `s.toOne` — one of the two relation factories.\n//\n// The factory states the SLOT CARDINALITY (one) and its argument states the\n// TARGET DOMAIN (one model, or named variants). Which endpoint owns a foreign\n// key, whether the pair is one-to-one or many-to-one, and whether a model-target\n// slot may be empty are DERIVED later by the full-schema topology owner.\n\nimport {\n type ExactVariantOptions,\n type NormalizedOneEntries,\n normalizeVariantEntries,\n type VariantGetterMap,\n type VariantMapGuard,\n type VariantOptions,\n type VariantToOneRelation,\n variantToOneTerminal,\n} from \"./polymorphic\";\nimport {\n createTargetSettlement,\n normalizeFieldTuple,\n normalizeReferentialAction,\n normalizeRelationName,\n refuseRelationInput,\n} from \"./terminal\";\nimport type {\n AnyRelation,\n ForeignKeyDeclaration,\n Getter,\n GetterOnly,\n ModelToOneState,\n NonEmptyFieldTuple,\n ReferentialAction,\n RelationInternal,\n Replace,\n} from \"./types\";\n\n// =============================================================================\n// TERMINAL CAPABILITY SURFACE\n// =============================================================================\n\n/**\n * Referential actions exist only once a complete reference exists — they act on\n * a foreign key, and there is no foreign key to act on before\n * `.references(...)` completes the pair.\n */\ntype ForeignKeyActions<State> = {\n onDelete<const Action extends ReferentialAction>(\n action: Action\n ): ModelToOneRelation<\n State extends { readonly foreignKey: infer FK }\n ? Replace<\n State,\n { readonly foreignKey: Replace<FK, { onDelete: Action }> }\n >\n : State\n >;\n onUpdate<const Action extends ReferentialAction>(\n action: Action\n ): ModelToOneRelation<\n State extends { readonly foreignKey: infer FK }\n ? Replace<\n State,\n { readonly foreignKey: Replace<FK, { onUpdate: Action }> }\n >\n : State\n >;\n};\n\ntype ModelToOneCapabilities<State> = {\n readonly \"~\": RelationInternal<State>;\n name<const Name extends string>(\n name: Name\n ): ModelToOneRelation<Replace<State, { readonly name: Name }>>;\n fields<const Fields extends NonEmptyFieldTuple>(\n ...fields: Fields\n ): ReferencesStage<State, Fields>;\n};\n\n/**\n * A model-target singular slot. It exposes no `.optional()`: emptiness follows\n * from the nullability of a complete local foreign-key tuple, and a non-owning\n * singular view is derived nullable.\n */\nexport type ModelToOneRelation<State> = ModelToOneCapabilities<State> &\n (State extends { readonly foreignKey: ForeignKeyDeclaration }\n ? ForeignKeyActions<State>\n : unknown);\n\n/**\n * The transient value `.fields(...)` returns.\n *\n * It carries NO relation brand, so neither `ModelShape` nor any downstream\n * relation consumer can mistake an incomplete foreign key for trusted schema\n * state, and `s.model(...)` refuses it outright. It exposes only\n * `.references(...)` and `.name(...)`: a name must not be able to turn an\n * incomplete pair into schema truth.\n */\nexport type ReferencesStage<State, Fields extends NonEmptyFieldTuple> = {\n references<\n const References extends NonEmptyFieldTuple & {\n readonly length: Fields[\"length\"];\n },\n >(\n ...references: References\n ): ModelToOneRelation<\n Replace<\n State,\n {\n readonly foreignKey: Replace<\n State extends { readonly foreignKey: infer FK } ? FK : unknown,\n { readonly fields: Fields; readonly references: References }\n >;\n }\n >\n >;\n name<const Name extends string>(\n name: Name\n ): ReferencesStage<Replace<State, { readonly name: Name }>, Fields>;\n};\n\n// =============================================================================\n// PRIVATE TERMINALS\n// =============================================================================\n\nclass ModelToOne {\n readonly #state: ModelToOneState;\n readonly #internal: RelationInternal<ModelToOneState>;\n\n constructor(state: ModelToOneState) {\n this.#state = Object.freeze(state);\n this.#internal = Object.freeze({\n state: this.#state,\n settleTarget: createTargetSettlement(() => this.#state.target.getter),\n });\n }\n\n name(name: string): ModelToOne {\n return new ModelToOne({\n ...this.#state,\n name: normalizeRelationName(\"s.toOne\", name),\n });\n }\n\n fields(...fields: string[]): PendingReferences {\n return new PendingReferences(\n this.#state,\n normalizeFieldTuple(\"s.toOne\", \"fields\", fields)\n );\n }\n\n onDelete(action: ReferentialAction): ModelToOne {\n return this.#withForeignKeyAction(\"onDelete\", action);\n }\n\n onUpdate(action: ReferentialAction): ModelToOne {\n return this.#withForeignKeyAction(\"onUpdate\", action);\n }\n\n /**\n * The type surface hides both action setters until `.references(...)` has\n * completed a foreign key. This refusal covers the route a type pin cannot:\n * a JavaScript caller placing a referential action on a slot that owns no\n * foreign key, where the action would otherwise have nowhere to be stored and\n * would be silently dropped.\n */\n #withForeignKeyAction(\n action: \"onDelete\" | \"onUpdate\",\n value: ReferentialAction\n ): ModelToOne {\n const foreignKey = this.#state.foreignKey;\n if (foreignKey === undefined) {\n refuseRelationInput(\n \"s.toOne\",\n action,\n `'${action}' is available only after \\`.fields(...).references(...)\\` declares a foreign key`\n );\n }\n return new ModelToOne({\n ...this.#state,\n foreignKey: Object.freeze({\n ...foreignKey,\n [action]: normalizeReferentialAction(action, value),\n }),\n });\n }\n\n get \"~\"(): RelationInternal<ModelToOneState> {\n return this.#internal;\n }\n}\n\n/**\n * The transient references stage. It has no `\"~\"` accessor by design: that\n * absence is what makes an incomplete chain unusable as a model member.\n */\nclass PendingReferences {\n readonly #state: ModelToOneState;\n readonly #localFields: NonEmptyFieldTuple;\n\n constructor(state: ModelToOneState, localFields: NonEmptyFieldTuple) {\n this.#state = state;\n this.#localFields = localFields;\n }\n\n name(name: string): PendingReferences {\n return new PendingReferences(\n { ...this.#state, name: normalizeRelationName(\"s.toOne\", name) },\n this.#localFields\n );\n }\n\n references(...references: string[]): ModelToOne {\n const referenced = normalizeFieldTuple(\"s.toOne\", \"references\", references);\n if (referenced.length !== this.#localFields.length)\n refuseReferenceArity(referenced.length, this.#localFields.length);\n // Completing a second stage replaces the pair atomically and preserves the\n // endpoint's name and referential actions; the prior terminal is untouched.\n const prior = this.#state.foreignKey;\n const foreignKey: ForeignKeyDeclaration = {\n fields: this.#localFields,\n references: referenced,\n ...(prior?.onDelete === undefined ? {} : { onDelete: prior.onDelete }),\n ...(prior?.onUpdate === undefined ? {} : { onUpdate: prior.onUpdate }),\n };\n return new ModelToOne({\n ...this.#state,\n foreignKey: Object.freeze(foreignKey),\n });\n }\n}\n\n/**\n * Is this model member a transient references stage?\n *\n * Deliberately nominal: a stage is only ever produced by `.fields(...)`, so an\n * `instanceof` test cannot be spoofed by a look-alike record, and the\n * `s.model(...)` boundary can refuse the one member shape that would otherwise\n * be silently dropped.\n */\nexport function isReferencesStage(value: unknown): boolean {\n return value instanceof PendingReferences;\n}\n\n// =============================================================================\n// FACTORY\n// =============================================================================\n\n/**\n * Declare a slot that holds AT MOST ONE membership.\n *\n * The map overload is declared first so a variant map is never swallowed by the\n * broad getter overload. Dispatch examines only the argument representation and\n * never invokes a getter.\n */\nexport function toOne<\n const Entries extends VariantGetterMap,\n const Options extends VariantOptions<Entries> | undefined = undefined,\n>(\n variants: Entries & VariantMapGuard<Entries>,\n options?: Options & ExactVariantOptions<Options, Entries>\n): VariantToOneRelation<{\n readonly kind: \"relation\";\n readonly cardinality: \"one\";\n readonly target: {\n readonly kind: \"variants\";\n readonly entries: NormalizedOneEntries<Entries>;\n };\n}>;\nexport function toOne<const G>(getter: G & GetterOnly<G>): G extends Getter\n ? ModelToOneRelation<{\n readonly kind: \"relation\";\n readonly cardinality: \"one\";\n readonly target: { readonly kind: \"model\"; readonly getter: G };\n }>\n : never;\nexport function toOne(target: unknown, options?: unknown): AnyRelation {\n if (typeof target === \"function\") {\n // biome-ignore lint/complexity/noArguments: distinguishes omission from explicit undefined without changing the factory's public arity\n if (arguments.length > 1) {\n refuseRelationInput(\n \"s.toOne\",\n \"options\",\n \"A model-target relation takes exactly one argument\"\n );\n }\n return new ModelToOne({\n kind: \"relation\",\n cardinality: \"one\",\n target: { kind: \"model\", getter: target },\n });\n }\n return variantToOneTerminal({\n kind: \"relation\",\n cardinality: \"one\",\n target: {\n kind: \"variants\",\n entries: normalizeVariantEntries(\"s.toOne\", target, options),\n },\n });\n}\n\nfunction refuseReferenceArity(referenced: number, local: number): never {\n return refuseRelationInput(\n \"s.toOne\",\n \"references\",\n `\\`.references(...)\\` declares ${referenced} field(s) against ${local} local field(s); a foreign key pairs them positionally`\n );\n}\n","import { emptyRecord } from \"@schema/record\";\nimport type { AnyRelation } from \"@schema/relation\";\nimport { refuseRelationInput } from \"@schema/relation/terminal\";\n// Deep import: the references-stage predicate is the `s.model(...)` boundary's\n// own instrument and is deliberately not part of the relation package surface.\nimport { isReferencesStage } from \"@schema/relation/to-one\";\nimport type { Scalar } from \"@schema/scalars/base\";\n\n/**\n * Record of model fields - the canonical type for scalar and relation definitions.\n * A model field is either a scalar or a relation; ONE relation map holds both\n * target domains.\n */\nexport type AnyModelField = Scalar | AnyRelation;\nexport type ModelShape = Record<string, AnyModelField>;\n\n/**\n * The shape `s.model(...)` and `.extends(...)` accept: a model shape with no\n * member named `_count` or `_distance`, the names a selection's own outputs\n * reserve (relation counts, a distance). This is the compile-time spelling of\n * rule F010 for TypeScript callers; F010 (`memberNamesAreNotReserved`) stays\n * the contract for every caller. It constrains keys only and never reads a\n * member's type, so it cannot change what a shape infers. Each key's type is\n * its reason spelled as a string literal, so the diagnostic a caller reads\n * names it: no model member is a string, so nothing a shape can hold\n * satisfies it.\n */\nexport type DeclaredModelShape = ModelShape & {\n readonly _count?: \"`_count` is reserved for relation counts (F010)\";\n readonly _distance?: \"`_distance` is reserved for distance results (F010)\";\n};\n\nexport type NameFromKeys<\n TFields extends string[],\n TName extends string = \"\",\n> = TFields extends readonly [\n infer F extends string,\n ...infer R extends string[],\n]\n ? R extends []\n ? `${TName}_${F}`\n : NameFromKeys<R, TName extends \"\" ? F : `${TName}_${F}`>\n : never;\n\nexport interface CompoundConstraint<\n TFields extends string[],\n TName extends string | undefined = undefined,\n> {\n fields: TFields;\n name: TName extends undefined ? NameFromKeys<TFields> : TName;\n}\n\n/** Any compound constraint (for loose typing) */\nexport type AnyCompoundConstraint = CompoundConstraint<string[]>;\n\nexport type ToString<T> = T extends\n | string\n | number\n | bigint\n | boolean\n | null\n | undefined\n ? `${T}`\n : never;\n\nexport type StringKeyOf<T extends Record<string, any>> = {\n [K in keyof T]: K extends string ? K : never;\n}[keyof T];\n\nexport type ScalarKeys<T extends ModelShape> = {\n [K in keyof T]: T[K] extends Scalar ? ToString<K> : never;\n}[keyof T];\n\n/** Fixed-decimal list keys, which have value semantics but no key semantics. */\nexport type DecimalListScalarKeys<T extends ModelShape> = {\n [K in keyof T]: T[K] extends Scalar\n ? T[K][\"~\"][\"state\"] extends { type: \"decimal\"; array: true }\n ? ToString<K>\n : never\n : never;\n}[keyof T];\n\n/** GeoPoint keys have value semantics but no portable key/order semantics. */\nexport type PointScalarKeys<T extends ModelShape> = {\n [K in keyof T]: T[K] extends Scalar\n ? T[K][\"~\"][\"state\"][\"type\"] extends \"point\"\n ? ToString<K>\n : never\n : never;\n}[keyof T];\n\nexport type NonNullablePointScalarKeys<T extends ModelShape> = {\n [K in keyof T]: T[K] extends Scalar\n ? T[K][\"~\"][\"state\"][\"type\"] extends \"point\"\n ? T[K][\"~\"][\"state\"][\"nullable\"] extends true\n ? never\n : ToString<K>\n : never\n : never;\n}[keyof T];\n\nexport type NonPointScalarKeys<T extends ModelShape> = Exclude<\n ScalarKeys<T>,\n string extends keyof T ? never : PointScalarKeys<T>\n>;\n\n/** Scalar keys except fixed-decimal lists, which cannot be physical keys. */\nexport type NonDecimalListScalarKeys<T extends ModelShape> = Exclude<\n ScalarKeys<T>,\n string extends keyof T ? never : DecimalListScalarKeys<T>\n>;\n\n/** Scalar keys admitted in IDs, unique constraints, and foreign-key identity. */\nexport type PortableKeyScalarKeys<T extends ModelShape> = Exclude<\n NonDecimalListScalarKeys<T>,\n string extends keyof T ? never : PointScalarKeys<T>\n>;\n\n/** Extract relation keys from ModelState */\nexport type RelationKeys<T extends ModelShape> = {\n [K in keyof T]: T[K] extends AnyRelation ? ToString<K> : never;\n}[keyof T];\n\nexport type RequiredScalarKeys<T extends ModelShape> = {\n [K in keyof T]: T[K] extends Scalar\n ? T[K][\"~\"][\"state\"][\"optional\"] extends true\n ? never\n : ToString<K>\n : never;\n}[keyof T];\n\nexport type UniqueScalarKeys<T extends ModelShape> = {\n [K in keyof T]: T[K] extends Scalar\n ? T[K][\"~\"][\"state\"][\"isId\"] extends true\n ? ToString<K>\n : T[K][\"~\"][\"state\"][\"isUnique\"] extends true\n ? ToString<K>\n : never\n : never;\n}[keyof T];\n\n/** Numeric scalar types for aggregations (avg, sum) */\nexport type NumericScalarType = \"int\" | \"number\" | \"decimal\" | \"bigint\";\n\n/** Extract keys of numeric scalars from a ModelShape */\nexport type NumericScalarKeys<T extends ModelShape> = {\n [K in keyof T]: T[K] extends Scalar\n ? T[K][\"~\"][\"state\"][\"array\"] extends true\n ? never\n : T[K][\"~\"][\"state\"][\"type\"] extends NumericScalarType\n ? ToString<K>\n : never\n : never;\n}[keyof T];\n\nexport type ScalarMap<T extends ModelShape> = {\n [K in ScalarKeys<T>]: T[K] extends Scalar ? T[K] : never;\n};\n\nexport type RelationMap<T extends ModelShape> = {\n [K in RelationKeys<T>]: T[K] extends AnyRelation ? T[K] : never;\n};\n\nexport type UniqueScalarMap<T extends ModelShape> = {\n [K in UniqueScalarKeys<T>]: T[K] extends Scalar ? T[K] : never;\n};\n\n/**\n * ONE relation boundary, keyed on the internal brand.\n *\n * Trusted relation state originates only in `s.toOne` / `s.toMany`, and both\n * target domains carry `kind: \"relation\"` — so a model has one relation map and\n * no consumer has to ask which family a member belongs to. Scalars keep\n * `state.type`, so the two brands cannot collide.\n */\nfunction isRelation(value: unknown): value is AnyRelation {\n if (\n (typeof value !== \"object\" || value === null) &&\n typeof value !== \"function\"\n ) {\n return false;\n }\n const internal = Reflect.get(value, \"~\");\n if (typeof internal !== \"object\" || internal === null) return false;\n const state = Reflect.get(internal, \"state\");\n return (\n typeof state === \"object\" &&\n state !== null &&\n Reflect.get(state, \"kind\") === \"relation\"\n );\n}\n\nconst SCALAR_TYPES = new Set<string>([\n \"string\",\n \"int\",\n \"number\",\n \"decimal\",\n \"boolean\",\n \"datetime\",\n \"date\",\n \"time\",\n \"bigint\",\n \"json\",\n \"blob\",\n \"vector\",\n \"point\",\n \"enum\",\n]);\n\nfunction isScalar(value: unknown): value is Scalar {\n if (\n (typeof value !== \"object\" || value === null) &&\n typeof value !== \"function\"\n ) {\n return false;\n }\n const internal = Reflect.get(value, \"~\");\n if (typeof internal !== \"object\" || internal === null) return false;\n const state = Reflect.get(internal, \"state\");\n if (typeof state !== \"object\" || state === null) return false;\n const type = Reflect.get(state, \"type\");\n return typeof type === \"string\" && SCALAR_TYPES.has(type);\n}\n\n/**\n * The classified member maps are a PROJECTION of the shape: every member an\n * extractor recognizes appears in the map that claims it, under the key the\n * shape gave it. A shape key comes from the caller — a hand-written literal, a\n * generated schema, a JSON document's field name — so it can be any string, and\n * assigning into an ordinary object would lose a `__proto__` member to\n * `Object.prototype`'s setter. These maps come from `emptyRecord` and stay\n * private until complete: their null prototype makes every assignment an own\n * data entry, including `__proto__`, without defining a descriptor per member.\n *\n * Whether such a key is a LEGAL identifier is a separate question with a\n * separate owner (`isValidSchemaIdentifier`, enforced at hydration and by the\n * document reader). Keeping the member is what lets that owner name it.\n */\nexport const extractScalarMap = <T extends ModelShape>(fields: T) => {\n const scalars = emptyRecord<Scalar>();\n for (const [key, value] of Object.entries(fields)) {\n if (isScalar(value)) {\n scalars[key] = value;\n }\n }\n return scalars as ScalarMap<T>;\n};\n\n/**\n * The `s.model(...)` member-classification boundary for relations.\n *\n * It gains exactly ONE refusal: a transient references stage — a chain that\n * started `.fields(...)` and never received `.references(...)` — is rejected\n * loudly rather than silently dropped, because that member declares a foreign\n * key the schema would then never have. Every other unrecognized member keeps\n * its existing silent-drop behavior; widening that is a separate decision.\n */\nexport const extractRelationMap = <T extends ModelShape>(fields: T) => {\n const relations = emptyRecord<AnyRelation>();\n for (const [key, value] of Object.entries(fields)) {\n if (isRelation(value)) {\n relations[key] = value;\n } else if (isReferencesStage(value)) {\n refuseRelationInput(\n \"s.model\",\n key,\n `Relation '${key}' started \\`.fields(...)\\` without \\`.references(...)\\`; complete the foreign key before using it as a model field`\n );\n }\n }\n return relations as RelationMap<T>;\n};\n\nexport const extractUniqueScalarMap = <T extends ModelShape>(fields: T) => {\n const uniques = emptyRecord<Scalar>();\n for (const [key, value] of Object.entries(fields)) {\n if (\n isScalar(value) &&\n (value[\"~\"].state.isUnique || value[\"~\"].state.isId)\n ) {\n uniques[key] = value;\n }\n }\n return uniques as UniqueScalarMap<T>;\n};\n\nexport const getNameFromKeys = <\n Name extends string | undefined,\n TFields extends any[],\n>(\n name: Name,\n fields: TFields\n) => {\n return (\n name ??\n (fields.join(\"_\") as Name extends undefined ? NameFromKeys<TFields> : Name)\n );\n};\n","// Model Class Implementation\n// Defines database models with scalars and relations\n\nimport type { ObjectSchema, VibSchema } from \"@validation\";\nimport v from \"@validation/primitives/v\";\nimport { emptyRecord, put } from \"../record\";\nimport type { AnyRelation } from \"../relation\";\nimport type { Scalar } from \"../scalars/base\";\nimport type { HydratedSchemaNames, SchemaNames } from \"../scalars/common\";\nimport {\n type DeclaredModelShape,\n extractRelationMap,\n extractScalarMap,\n extractUniqueScalarMap,\n getNameFromKeys,\n type ModelShape,\n type NameFromKeys,\n type NonNullablePointScalarKeys,\n type PortableKeyScalarKeys,\n type RelationMap,\n type ScalarMap,\n type StringKeyOf,\n type UniqueScalarMap,\n} from \"./helper\";\n// Re-export types from helpers for external use\n\n// =============================================================================\n// TYPE INFERENCE HELPER\n// =============================================================================\n\nexport interface ModelState {\n shape: ModelShape;\n compoundId:\n | Record<string, ObjectSchema<Record<string, VibSchema>>>\n | undefined;\n compoundUniques:\n | Record<string, ObjectSchema<Record<string, VibSchema>>>\n | undefined;\n tableName: string | undefined;\n indexes: IndexDefinition[];\n omit: Record<string, true> | undefined;\n scalars: Record<string, Scalar>;\n /** ONE canonical relation map, holding both target domains in shape order. */\n relations: Record<string, AnyRelation>;\n uniques: Record<string, Scalar>;\n}\n\n/** Initial model projections stay named when a consumer emits recursive graphs. */\nexport interface InitialModelState<Shape extends ModelShape>\n extends ModelState {\n shape: Shape;\n scalars: ScalarMap<Shape>;\n relations: RelationMap<Shape>;\n uniques: UniqueScalarMap<Shape>;\n omit: undefined;\n}\n\n/**\n * Internal accessor return type for Model[\"~\"]\n * Explicit type annotation to avoid TS7056 (type too complex to serialize)\n */\nexport interface ModelInternal<T extends ModelState> {\n state: T;\n names: SchemaNames;\n nameRegistry: {\n fields: Map<string, SchemaNames>;\n };\n getFieldName: (key: string) => HydratedSchemaNames;\n /** Cached scalar field names (computed once on first access) */\n scalarFieldNames: string[];\n /** Cached relation names (computed once on first access) */\n relationNames: string[];\n}\n\n/**\n * The index kinds a schema may declare. The union is the whole of what any\n * dialect accepts, not what all of them accept — `validateIndexType` in\n * `migrations/drivers/base.ts` refuses each one on the dialects whose\n * `supportsIndexTypes` does not list it, by name, at push time.\n *\n * `fulltext` and `spatial` are here because MySQL's whole round trip already\n * exists and only this union could not spell it: the emitter writes the\n * `FULLTEXT`/`SPATIAL` prefix and refuses to combine either with `UNIQUE`\n * (`mysql/index.ts`), the introspection reads them back and normalizes MySQL's\n * `RTREE` to `spatial` (`mysql/introspect.ts`), the migration snapshot's\n * `IndexDef` already carries both (`migrations/types.ts`), and the capability\n * list already declares them. See Phase 10 item 6 in\n * `docs/architecture/query-performance-plan.md`.\n */\nexport type IndexType =\n | \"btree\"\n | \"hash\"\n | \"gin\"\n | \"gist\"\n | \"fulltext\"\n | \"spatial\";\n\nexport interface IndexOptions {\n name?: string;\n unique?: boolean;\n type?: IndexType;\n where?: string; // For partial indexes (PostgreSQL)\n}\n\ntype OrdinaryIndexOptions = Omit<IndexOptions, \"type\"> & {\n type?: Exclude<IndexType, \"spatial\">;\n};\n\ntype GeoPointSpatialIndexOptions = {\n name?: string;\n type: \"spatial\";\n unique?: never;\n where?: never;\n};\n\nexport interface IndexDefinition<\n Keys extends string[] = string[],\n O extends IndexOptions = IndexOptions,\n> {\n fields: Keys;\n options: O;\n}\n\n/** A partial index cannot constrain rows excluded by its predicate. */\nexport function isTotalIndex(options: Pick<IndexOptions, \"where\">): boolean {\n return !options.where;\n}\n\nexport type UpdateIndexDefinition<\n State extends ModelState,\n Index extends IndexDefinition,\n> = [...State[\"indexes\"], Index];\n\n/** The name a compound `.id()` / `.unique()` constraint may be given. */\nexport interface CompoundKeyOptions {\n name?: string;\n}\n\n/**\n * An options bag that carries the surface's own keys and NOTHING else.\n *\n * A generic `O extends Options` is no guard on its own: when inference produces\n * a bag the constraint would reject, TypeScript CLAMPS `O` to the constraint and\n * only excess-property checking is left to catch the stray key — and that needs\n * a fresh object literal, so `.index([\"a\"], sharedIndexOptions)` sails through\n * with `uniqu: true` recorded as nothing at all. Demanding `never` for the\n * unknown keys refuses structurally instead, whatever the argument's freshness.\n * Same instrument as `UnknownOmitKeys` below.\n */\ntype ExactOptions<Given, Allowed> = Given &\n Record<Exclude<keyof Given, keyof Allowed>, never>;\n\n/**\n * The constraint name: the caller's `name` when they gave one, otherwise the\n * underscore-joined field names. Read off the options bag rather than a separate\n * inferred parameter so that ONE type parameter carries the whole literal — the\n * parameter `ExactOptions` needs in order to see the unknown keys.\n */\ntype CompoundKeyName<\n Keys extends string[],\n O extends CompoundKeyOptions,\n> = O extends { name: infer N extends string } ? N : NameFromKeys<Keys>;\n\nexport const mergeIndexDefinitions = <\n State extends ModelState,\n Index extends IndexDefinition,\n>(\n state: State,\n index: Index\n): UpdateIndexDefinition<State, Index> => {\n return [...state.indexes, index] as UpdateIndexDefinition<State, Index>;\n};\n\n// Publish the same completed state as fluent returns so a legacy explicit\n// Model<UpdateState<...>> annotation retains exact relation-link identity.\nexport type UpdateState<\n State extends ModelState,\n Update extends Partial<ModelState>,\n> = {\n [P in keyof (Omit<State, keyof Update> & Update)]: (Omit<\n State,\n keyof Update\n > &\n Update)[P];\n};\n\n/**\n * The keys a proposed `.omit()` names that this model does NOT have as a\n * scalar: the typos and the relation names.\n *\n * `Hidden` is inferred from the argument's own keys and is deliberately NOT\n * constrained to the scalar names. A constrained type parameter is no guard\n * here: when inference produces something the constraint rejects, TypeScript\n * silently CLAMPS the parameter to the constraint and only excess-property\n * checking — which needs a fresh object literal — is left to catch the bad\n * key. Anything non-fresh (`as const`, a spread, an annotated variable, a\n * widened `Record<string, true>`) then sails through and records a\n * hidden-column claim nobody wrote. Excluding the unknown keys and demanding\n * `never` for them refuses structurally instead, whatever the argument's\n * freshness, and a `never` the caller cannot produce is a compile error at the\n * offending key.\n *\n * Relations are absent from the accepted set because `State[\"scalars\"]` is the\n * scalar half of the shape (`ScalarMap`), the same source `.index()` /\n * `.id()` / `.unique()` key off. Reading it never touches a relation's\n * `getter`, the member that must not be resolved while two model consts still\n * refer to each other (see `RelationState.getter`).\n */\ntype UnknownOmitKeys<Hidden extends string, State extends ModelState> = Exclude<\n Hidden,\n StringKeyOf<State[\"scalars\"]>\n>;\n\n/**\n * This model's scalar names, each optionally flagged `true`.\n *\n * It carries NO refusal — `UnknownOmitKeys` does that — and it adds no\n * requirement, every key being optional. It is in the parameter for one\n * reason: an editor offers the keys of a CONCRETE contextual type, and\n * `Record<Hidden, true>` is not concrete until `Hidden` has been inferred from\n * the very literal being typed. Without this member `.omit({ ` autocompletes\n * the global scope; with it, the model's scalars.\n */\nexport type ModelOmitInput<State extends ModelState> = Partial<\n Record<StringKeyOf<State[\"scalars\"]>, true>\n>;\n\n/**\n * Merge a new compound constraint into the existing record so repeated\n * .id()/.unique() calls accumulate instead of replacing each other.\n * Resolves to just `Added` when nothing was set yet.\n */\ntype MergeCompound<Existing, Added> = Added &\n (Existing extends Record<string, ObjectSchema<Record<string, VibSchema>>>\n ? Existing\n : unknown);\n\n/**\n * Resolve compound-key members to their base schemas, refusing any name that\n * is not a scalar of the model AT THE DECLARING SITE. The typed surface\n * already refuses these names; this throw is the runtime backstop for\n * untyped callers and JSON documents (the document interpreter relocates it\n * onto the `ids[]`/`uniques[]` node that wrote it), and it must fire on the\n * rule-free paths (`serializeModels`, `generate`,\n * `push({ skipValidation: true })`) that never run the advisory rules. I003\n * keeps its own coverage: post-construction shape drift (`.extends()`\n * shadowing a key member) is invisible to this constructor.\n *\n * A module function rather than a `Model` method: adding members to the class\n * perturbs how TS compares mutually-recursive model instantiations.\n */\nfunction compoundMembers(\n state: ModelState,\n fields: readonly string[],\n label: string\n): Record<string, VibSchema> {\n refuseDuplicateModelKeyMembers(fields, label);\n const members = emptyRecord<VibSchema>();\n for (const fieldName of fields) {\n // `in` is exact here: both maps come from the extractors, which build\n // prototype-free records, so no key can resolve an inherited member.\n const scalar =\n fieldName in state.scalars ? state.scalars[fieldName] : undefined;\n if (!scalar) {\n throw new Error(\n fieldName in state.relations\n ? `${label} field '${fieldName}' is a relation and cannot be a key member`\n : `${label} field '${fieldName}' does not exist`\n );\n }\n put(members, fieldName, scalar[\"~\"].state.base);\n }\n return members;\n}\n\n/**\n * One compound ID or unique, written into its own slot. The first tuple of a\n * name is preserved before Record storage could overwrite it.\n */\nfunction withCompound(\n state: ModelState,\n slot: \"compoundId\" | \"compoundUniques\",\n label: \"Compound ID\" | \"Compound unique\",\n fields: readonly string[],\n options: CompoundKeyOptions | undefined\n): Model<any> {\n const storedFields = snapshotModelKeyMembers(fields, label);\n const name = getNameFromKeys(options?.name, storedFields);\n if (Object.hasOwn(state[slot] ?? {}, name)) {\n throw new Error(\n `${label} name '${name}' is already used by another compound key; give this tuple a distinct name`\n );\n }\n const fieldsRecord = compoundMembers(state, storedFields, label);\n return new Model({\n ...state,\n [slot]: {\n ...state[slot],\n [name]: v.object(fieldsRecord, { partial: false }),\n },\n });\n}\n\n/** Snapshot one declaration tuple without consulting caller iteration hooks. */\nfunction snapshotModelKeyMembers(fields: unknown, label: string): string[] {\n if (!Array.isArray(fields)) {\n throw new Error(`${label} fields must be a dense array of strings`);\n }\n const memberCount = fields.length;\n const members = new Array<string>(memberCount);\n for (let position = 0; position < memberCount; position++) {\n if (!Object.hasOwn(fields, position)) {\n throw new Error(`${label} fields must be a dense array of strings`);\n }\n const member: unknown = fields[position];\n if (typeof member !== \"string\") {\n throw new Error(`${label} fields must be a dense array of strings`);\n }\n members[position] = member;\n }\n return members;\n}\n\n/** Snapshot the four public index options, including inherited accessors. */\nfunction snapshotIndexOptions(options: IndexOptions): IndexOptions {\n const name = options.name;\n const unique = options.unique;\n const type = options.type;\n const where = options.where;\n return {\n ...(name === undefined ? {} : { name }),\n ...(unique === undefined ? {} : { unique }),\n ...(type === undefined ? {} : { type }),\n ...(where === undefined ? {} : { where }),\n };\n}\n\n/** One physical key/index tuple cannot name the same column twice. */\nfunction refuseDuplicateModelKeyMembers(\n fields: readonly string[],\n label: string\n): void {\n if (new Set(fields).size !== fields.length) {\n throw new Error(`${label} cannot repeat a field in one tuple`);\n }\n}\n\n/**\n * Name registry for scalars and relations.\n * Maps scalar/relation keys to their resolved names (ts and sql).\n * This is populated during hydration.\n */\nexport interface NameRegistry {\n /** Scalar names: key -> {ts, sql} */\n fields: Map<string, SchemaNames>;\n}\n\nexport class Model<State extends ModelState> {\n // biome-ignore lint/style/useReadonlyClassProperties: <it is reassigned when hydrating schemas>\n #names: SchemaNames = {};\n // biome-ignore lint/style/useReadonlyClassProperties: <it is reassigned when hydrating schemas>\n #nameRegistry: NameRegistry = {\n fields: new Map(),\n };\n readonly #state: State;\n\n // Cached field metadata (lazily computed on first access)\n #scalarFieldNames: string[] | undefined;\n #relationNames: string[] | undefined;\n #internal: ModelInternal<State> | undefined;\n\n constructor(state: State) {\n this.#state = state;\n }\n\n // Materialize each completed modifier state inline before a recursive getter\n // captures it. A helper alias retains the whole prior modifier chain.\n /**\n * Maps the model to a specific database table name\n */\n map<Name extends string>(tableName: Name) {\n return new Model({ ...this.#state, tableName }) as unknown as Model<{\n [KState in keyof UpdateState<State, { tableName: Name }>]: UpdateState<\n State,\n { tableName: Name }\n >[KState];\n }>;\n }\n\n /**\n * Hide scalars from every result of this model — the schema-level exclusion.\n *\n * Keyed to the model's own SCALARS, so a typo or a relation name is a\n * compile error instead of an `omit` that quietly hides nothing. That\n * matters more here than anywhere else the builder takes field names: this\n * is the spelling used for secrets, and a silently-ignored key is a leaked\n * column. The refusal is per KEY, not per call: `{ secret: true, tokne:\n * true }` fails on `tokne` even though `secret` is real — two secrets with\n * one misspelled is the realistic case, and it is exactly the case an\n * excess-property-only refusal would wave through (see `UnknownOmitKeys`).\n *\n * Every value must be `true`. `false` has no meaning here (model-level omit\n * only ever hides) and a flag that may be `undefined` hides nothing at\n * runtime — `projectableScalarNames` compares against `true` — so\n * `Record<Hidden, true>` refuses both rather than recording a claim the\n * runtime would not honor.\n *\n * The literal survives the round trip — `.omit({ secret: true })` carries\n * exactly `{ secret: true }` into the state, not a widened record — which is\n * what every downstream `keyof State[\"omit\"]` reads. `Hidden` defaults to\n * `never` for the one call with nothing to infer from, `.omit({})`: a bare\n * `extends string` would fall back to `string` there and hand the state a\n * record keyed by every conceivable name.\n */\n omit<Hidden extends string = never>(\n items: Record<Hidden, true> &\n Record<UnknownOmitKeys<Hidden, State>, never> &\n ModelOmitInput<State>\n ) {\n return new Model({\n ...this.#state,\n omit: items,\n }) as unknown as Model<{\n [KState in keyof UpdateState<\n State,\n { omit: Record<Hidden, true> }\n >]: UpdateState<State, { omit: Record<Hidden, true> }>[KState];\n }>;\n }\n\n index<\n const Keys extends PortableKeyScalarKeys<State[\"scalars\"]>[],\n O extends OrdinaryIndexOptions = OrdinaryIndexOptions,\n >(\n fields: Keys,\n options?: ExactOptions<O, OrdinaryIndexOptions>\n ): Model<{\n [KState in keyof UpdateState<\n State,\n { indexes: UpdateIndexDefinition<State, { fields: Keys; options: O }> }\n >]: UpdateState<\n State,\n { indexes: UpdateIndexDefinition<State, { fields: Keys; options: O }> }\n >[KState];\n }>;\n index<\n const Key extends NonNullablePointScalarKeys<State[\"scalars\"]>,\n const O extends GeoPointSpatialIndexOptions,\n >(\n fields: [Key],\n options: ExactOptions<O, GeoPointSpatialIndexOptions>\n ): Model<{\n [KState in keyof UpdateState<\n State,\n { indexes: UpdateIndexDefinition<State, { fields: [Key]; options: O }> }\n >]: UpdateState<\n State,\n { indexes: UpdateIndexDefinition<State, { fields: [Key]; options: O }> }\n >[KState];\n }>;\n index(fields: string[], options: IndexOptions = {}): Model<any> {\n const storedFields = snapshotModelKeyMembers(fields, \"Index\");\n refuseDuplicateModelKeyMembers(storedFields, \"Index\");\n const storedOptions = snapshotIndexOptions(options);\n return new Model({\n ...this.#state,\n indexes: mergeIndexDefinitions(this.#state, {\n fields: storedFields,\n options: storedOptions,\n }),\n });\n }\n\n id<\n const Keys extends PortableKeyScalarKeys<State[\"scalars\"]>[],\n const O extends CompoundKeyOptions = Record<never, never>,\n >(fields: Keys, options?: ExactOptions<O, CompoundKeyOptions>) {\n return withCompound(\n this.#state,\n \"compoundId\",\n \"Compound ID\",\n fields,\n options\n ) as unknown as Model<{\n [KState in keyof UpdateState<\n State,\n {\n compoundId: MergeCompound<\n State[\"compoundId\"],\n {\n [K in CompoundKeyName<Keys, O>]: ObjectSchema<{\n [K2 in Keys[number]]: State[\"scalars\"][K2][\"~\"][\"state\"][\"base\"];\n }>;\n }\n >;\n }\n >]: UpdateState<\n State,\n {\n compoundId: MergeCompound<\n State[\"compoundId\"],\n {\n [K in CompoundKeyName<Keys, O>]: ObjectSchema<{\n [K2 in Keys[number]]: State[\"scalars\"][K2][\"~\"][\"state\"][\"base\"];\n }>;\n }\n >;\n }\n >[KState];\n }>;\n }\n\n unique<\n const Keys extends PortableKeyScalarKeys<State[\"scalars\"]>[],\n const O extends CompoundKeyOptions = Record<never, never>,\n >(fields: Keys, options?: ExactOptions<O, CompoundKeyOptions>) {\n return withCompound(\n this.#state,\n \"compoundUniques\",\n \"Compound unique\",\n fields,\n options\n ) as unknown as Model<{\n [KState in keyof UpdateState<\n State,\n {\n compoundUniques: MergeCompound<\n State[\"compoundUniques\"],\n {\n [K in CompoundKeyName<Keys, O>]: ObjectSchema<{\n [K2 in Keys[number]]: State[\"scalars\"][K2][\"~\"][\"state\"][\"base\"];\n }>;\n }\n >;\n }\n >]: UpdateState<\n State,\n {\n compoundUniques: MergeCompound<\n State[\"compoundUniques\"],\n {\n [K in CompoundKeyName<Keys, O>]: ObjectSchema<{\n [K2 in Keys[number]]: State[\"scalars\"][K2][\"~\"][\"state\"][\"base\"];\n }>;\n }\n >;\n }\n >[KState];\n }>;\n }\n\n extends<ETShape extends DeclaredModelShape>(shape: ETShape) {\n const newShape = { ...this.#state.shape, ...shape } as State[\"shape\"] &\n ETShape;\n return new Model({\n ...this.#state,\n shape: newShape,\n scalars: extractScalarMap(newShape),\n relations: extractRelationMap(newShape),\n uniques: extractUniqueScalarMap(newShape),\n }) as unknown as Model<\n UpdateState<\n State,\n {\n shape: State[\"shape\"] & ETShape;\n scalars: ScalarMap<State[\"shape\"] & ETShape>;\n relations: RelationMap<State[\"shape\"] & ETShape>;\n uniques: UniqueScalarMap<State[\"shape\"] & ETShape>;\n }\n >\n >;\n }\n\n get \"~\"(): ModelInternal<State> {\n if (this.#internal) {\n return this.#internal;\n }\n // Capture model instance for use in getters\n const model = this;\n\n this.#internal = {\n state: this.#state,\n // getters so hydration after first access is still observed\n get names() {\n return model.#names;\n },\n get nameRegistry() {\n return model.#nameRegistry;\n },\n /**\n * Get the resolved names for a field.\n * Throws if the schema has not been hydrated.\n */\n getFieldName: (key: string): HydratedSchemaNames => {\n const registered = model.#nameRegistry.fields.get(key);\n if (registered) {\n return registered as HydratedSchemaNames;\n }\n throw new Error(`Scalar \"${key}\" not found in nameRegistry`);\n },\n /** Cached scalar field names (computed once on first access) */\n get scalarFieldNames(): string[] {\n return (model.#scalarFieldNames ??= Object.keys(model.#state.scalars));\n },\n /** Cached relation names (computed once on first access) */\n get relationNames(): string[] {\n return (model.#relationNames ??= Object.keys(model.#state.relations));\n },\n };\n return this.#internal;\n }\n}\n\nexport const model = <TShape extends DeclaredModelShape>(\n shape: TShape\n): Model<InitialModelState<TShape>> =>\n new Model({\n compoundId: undefined,\n compoundUniques: undefined,\n tableName: undefined,\n indexes: [],\n omit: undefined,\n shape,\n scalars: extractScalarMap(shape),\n relations: extractRelationMap(shape),\n uniques: extractUniqueScalarMap(shape),\n });\n\nexport type AnyModel = Model<any>;\n\n/**\n * SQL table name for a model: hydrated name, then .map() tableName, then\n * the given fallback.\n */\nexport function getTableName(model: AnyModel, fallback = \"unknown\"): string {\n return model[\"~\"].names.sql ?? model[\"~\"].state.tableName ?? fallback;\n}\n\n/**\n * SQL column name for a field, resolved through the model's nameRegistry\n * (supports field reuse across models) with .map() and field-name fallbacks.\n */\nexport function getColumnName(model: AnyModel, fieldName: string): string {\n return model[\"~\"].getFieldName(fieldName).sql;\n}\n"],"mappings":"iMAsBA,SAAgB,aAAoC,CAClD,OAAO,OAAO,OAAO,KAAK,CAI5B,SAAgB,IAAO,EAA2B,EAAa,EAAgB,CAC7E,OAAO,eAAe,EAAQ,EAAK,CACjC,QACA,WAAY,GACZ,SAAU,GACV,aAAc,GACf,CAAC,CAIJ,SAAgB,IACd,EACA,EACe,CACX,SAAW,IAAA,IAAa,CAAC,OAAO,OAAO,EAAQ,EAAI,EACvD,OAAO,EAAO,GCFhB,MAAM,EAAe,sCAEf,EAAqB,CAAC,QAAS,SAAU,SAAS,CAuIxD,SAAgB,wBACd,EACA,EACA,EACwC,CACnC,EAAc,EAAS,EAC1B,EACE,EACA,SACA,0FACD,CAEH,IAAM,EAAc,EAAa,EAAS,CACtC,EAAY,SAAW,GACzB,EACE,EACA,SACA,2CACD,CAEH,IAAM,EAAe,iBAAiB,EAAS,EAAa,EAAQ,CAC9D,EAAwC,EAAE,CAChD,IAAK,IAAM,KAAc,EAAa,CAC/B,EAAwB,EAAW,EACtC,EACE,EACA,UAAU,IACV,gBAAgB,EAAW,oCAC5B,CAEH,IAAM,EAAS,EACb,EACA,EACA,EACA,UAAU,IACX,CACG,OAAO,GAAW,YACpB,EACE,EACA,UAAU,IACV,YAAY,EAAW,6EACxB,CAEH,EAAQ,GA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AC,CAQJ,SAAgB,aAAa,EAAiB,EAAW,UAAmB,CAC1E,OAAOA,EAAM,KAAK,MAAM,KAAOA,EAAM,KAAK,MAAM,WAAa,EAO/D,SAAgB,cAAc,EAAiB,EAA2B,CACxE,OAAOA,EAAM,KAAK,aAAa,EAAU,CAAC"}
@@ -1,4 +1,4 @@
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{E as r,N as i}from"./geo-point-codec-CIZxuIvE.mjs";import{o as a}from"./native-types-CQH05hcr.mjs";import{a as o}from"./physical-t_gDjUCD.mjs";import{r as s}from"./datetime-physical-codec-DTdvABny.mjs";import{A as c,B as l,G as u,H as d,I as f,K as p,L as m,N as h,R as g,U as _,V as v,W as y,Y as b,j as x,m as S,q as C,z as w}from"./client-l7dSOul5.mjs";import{r as T}from"./identity-BtuwgqhS.mjs";import{P as E}from"./standard-sql-Ci8ROrql.mjs";import{a as D,i as O,o as k}from"./identifier-conversion-BXrBYgAq.mjs";const namespaceMeta=e=>({dialect:`mysql`,namespace:e});async function resolveCatalogNamespace(e,r){if(r===void 0)throw new n(`This MySQL client's adapter declares no database, so there is no catalog to read. MySQL migration artifacts are database-relative on purpose: supply the live destination explicitly, in the connection URL, or through the driver's database option.`,t.MIGRATION_INVALID_STATE,{meta:{dialect:`mysql`,type:`unbound-database`}});let{rows:i}=await e(`
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{E as r,N as i}from"./geo-point-codec-CIZxuIvE.mjs";import{o as a}from"./native-types-CQH05hcr.mjs";import{a as o}from"./physical-t_gDjUCD.mjs";import{r as s}from"./datetime-physical-codec-DTdvABny.mjs";import{A as c,B as l,G as u,H as d,I as f,K as p,L as m,N as h,R as g,U as _,V as v,W as y,Y as b,j as x,m as S,q as C,z as w}from"./client-mQcOvDdK.mjs";import{r as T}from"./identity-BtuwgqhS.mjs";import{P as E}from"./standard-sql-BtzSzrof.mjs";import{a as D,i as O,o as k}from"./identifier-conversion-C_XCo9es.mjs";const namespaceMeta=e=>({dialect:`mysql`,namespace:e});async function resolveCatalogNamespace(e,r){if(r===void 0)throw new n(`This MySQL client's adapter declares no database, so there is no catalog to read. MySQL migration artifacts are database-relative on purpose: supply the live destination explicitly, in the connection URL, or through the driver's database option.`,t.MIGRATION_INVALID_STATE,{meta:{dialect:`mysql`,type:`unbound-database`}});let{rows:i}=await e(`
2
2
  SELECT SCHEMA_NAME
3
3
  FROM information_schema.SCHEMATA
4
4
  WHERE LOWER(SCHEMA_NAME) = LOWER(?)
@@ -96,4 +96,4 @@ WHERE tc.CONSTRAINT_TYPE = 'FOREIGN KEY'
96
96
  ORDER BY tc.TABLE_NAME, tc.CONSTRAINT_NAME, kcu.ORDINAL_POSITION
97
97
  `,[a,a]);admitContainedForeignKeys(d.rows,a,i);let p=O(c.rows,e=>e.TABLE_NAME),m=O(l.rows,e=>e.TABLE_NAME),h=D(u.rows,e=>e.TABLE_NAME,e=>e.INDEX_NAME),_=D(d.rows.filter(e=>e.TABLE_SCHEMA===a),e=>e.TABLE_NAME,e=>e.CONSTRAINT_NAME),v=[],y=new Set,b=[];for(let e of s.rows){let r=e.TABLE_NAME,a=[];for(let e of p.get(r)||[]){if((i===void 0||i.includes(r))&&(e.EXTRA.toUpperCase().includes(`VIRTUAL GENERATED`)||e.EXTRA.toUpperCase().includes(`STORED GENERATED`)))throw new n(`MySQL column "${r}.${e.COLUMN_NAME}" is generated. Synchronization refuses before effects because its expression cannot be represented.`,t.MIGRATION_INVALID_STATE,{meta:{table:r,column:e.COLUMN_NAME,feature:`generated column`}});if(e.DATA_TYPE===`enum`){let t=g(e.COLUMN_TYPE),n=t&&f(t);t&&n&&!y.has(n)&&(v.push({name:n,values:t}),y.add(n))}let o=i===void 0||i.includes(r),s=o?readDecimalDomain(e):void 0;a.push({name:e.COLUMN_NAME,type:o?formatColumnType(e):e.COLUMN_TYPE,nullable:e.IS_NULLABLE===`YES`,default:o?cleanDefault(e):void 0,autoIncrement:isAutoIncrement(e.EXTRA),decimal:s})}let o,s=m.get(r);if(s&&s.length>0){s.sort((e,t)=>e.ORDINAL_POSITION-t.ORDINAL_POSITION);let e=s[0];e&&(o={columns:s.map(e=>e.COLUMN_NAME),name:e.CONSTRAINT_NAME})}let c=[],l=h.get(r),u=new Set(_.get(r)?.keys()??[]);if(l)for(let[e,t]of l){if(u.has(e))continue;t.sort((e,t)=>e.SEQ_IN_INDEX-t.SEQ_IN_INDEX);let n=t[0];if(n){let r=n.INDEX_TYPE.toLowerCase(),i=r===`rtree`?`spatial`:r;c.push({name:e,columns:t.map(e=>e.COLUMN_NAME),unique:n.NON_UNIQUE===0,type:i===`btree`||i===`hash`||i===`fulltext`||i===`spatial`?i:void 0})}}let d=[],x=_.get(r);if(x)for(let[e,t]of x){t.sort((e,t)=>e.ORDINAL_POSITION-t.ORDINAL_POSITION);let n=t[0];n&&d.push({name:e,columns:t.map(e=>e.COLUMN_NAME),referencedTable:n.REFERENCED_TABLE_NAME,referencedColumns:t.map(e=>e.REFERENCED_COLUMN_NAME),onDelete:k(n.DELETE_RULE),onUpdate:k(n.UPDATE_RULE)})}b.push({name:r,columns:a,primaryKey:o,indexes:c,foreignKeys:d,uniqueConstraints:[]})}return{tables:b,enums:v.length>0?v:void 0}}const R=/[^a-z0-9_]/g;function hashLockScope(e){let t=2166136261;for(let n=0;n<e.length;n+=1)t^=e.charCodeAt(n),t=Math.imul(t,16777619);return(t>>>0).toString(16).padStart(8,`0`)}function mysqlMigrationLockName(e){let t=e.toLowerCase();return`viborm_migration_${t.replace(R,`_`).slice(0,38)}_${hashLockScope(t)}`}function mysqlAcquireLockStatement(e,t,n){return`SELECT GET_LOCK(${n(mysqlMigrationLockName(e))}, ${t}) AS acquired`}function mysqlReleaseLockStatement(e,t){return`SELECT RELEASE_LOCK(${t(mysqlMigrationLockName(e))}) AS released`}function mysqlLockAnswer(e,t){if(e.length!==1)return!1;let n=e[0];if(typeof n!=`object`||!n)return!1;let r=Reflect.get(n,t);return typeof r==`number`?r===1:typeof r==`string`?Number(r)===1:!1}function mysqlSelectTargetStatement(e,t){return`USE ${t(e)}`}const z=/^(\d+)\.(\d+)\.(\d+)/;async function proveMySQLExactValueSession(e,r){let{rows:i}=await e(`SELECT @@SESSION.sql_mode AS sql_mode, VERSION() AS server_version`),a=i[0],o=typeof a==`object`&&a?Reflect.get(a,`sql_mode`):void 0,s=typeof o==`string`?o:``,c=typeof a==`object`&&a?Reflect.get(a,`server_version`):void 0,l=typeof c==`string`?c:`<unreported>`;if(!supportsEnforcedMySQLChecks(l))throw new n(`This MySQL migration session reports version "${l}". Fixed-decimal conversions require MySQL 8.0.16 or later, where CHECK constraints are enforced; the command is refused before any migration effect.`,t.DRIVER_NOT_SUPPORTED,{meta:{dialect:`mysql`,type:`unenforced-check-constraints`,target:r}});if(!s.split(`,`).some(e=>{let t=e.trim();return t===`STRICT_TRANS_TABLES`||t===`STRICT_ALL_TABLES`}))throw new n(`This MySQL session runs in sql_mode "${s}", which has neither STRICT_TRANS_TABLES nor STRICT_ALL_TABLES. Effectful migration work is refused: without a strict mode MySQL answers an out-of-range DECIMAL with a warning and stores the clamped value, so an exact fixed-decimal column would silently stop holding what it was given. Enable a strict mode on the server or on this connection and run the command again.`,t.DRIVER_NOT_SUPPORTED,{meta:{dialect:`mysql`,type:`non-strict-sql-mode`,target:r}})}function supportsEnforcedMySQLChecks(e){if(e.toLowerCase().includes(`mariadb`))return!1;let t=z.exec(e);if(t===null)return!1;let n=Number(t[1]),r=Number(t[2]),i=Number(t[3]);return n>8||n===8&&(r>0||i>=16)}const B=[/^GEOMETRY\b/,/^POINT\b/,/^LINESTRING\b/,/^POLYGON\b/,/^MULTIPOINT\b/,/^MULTILINESTRING\b/,/^MULTIPOLYGON\b/,/^GEOMETRYCOLLECTION\b/],V=/^(?:(?:TINY|MEDIUM|LONG)?(?:TEXT|BLOB)|JSON|GEOMETRY|POINT|LINESTRING|POLYGON|MULTI(?:POINT|LINESTRING|POLYGON)|GEOMETRYCOLLECTION)\b/i,H=/[\s(]/;function classifyDecimalListDescriptorChange(e,t){return e.scale===t.scale?e.precision<t.precision?`widening`:e.precision>t.precision?`narrowing`:`same`:`rescaling`}const U=x.point.indexOf(` `),W=x.point.slice(0,U),G=x.point.slice(U+1);function mysqlRefusesLiteralDefault(e){let t=e.toUpperCase();return t.includes(`TEXT`)||t.includes(`BLOB`)||t.includes(`JSON`)||B.some(e=>e.test(t))}const K=/^(?:DATETIME|TIMESTAMP)\s*(?:\((\d+)\))?$/i;function mysqlNowExpression(e){let t=K.exec(e.trim());if(t!==null)return t[1]===void 0?`CURRENT_TIMESTAMP`:`CURRENT_TIMESTAMP(${t[1]})`}function finalizeMySQLColumn(e,t){let n=e.type.toUpperCase()===`TEXT`&&t?`VARCHAR(191)`:e.type,r=e.default!==void 0&&mysqlRefusesLiteralDefault(n)?`(${e.default})`:e.default;return n===e.type&&r===e.default?e:{...e,type:n,default:r}}function isMySQLExactIntegerType(e){let t=e.trim().toUpperCase().split(H,1)[0];return t===`INT`||t===`INTEGER`||t===`BIGINT`}const q=new class MySQLMigrationDriver extends S{dialect=`mysql`;driverName=`mysql`;capabilities={supportsNativeEnums:!0,supportsAddEnumValueInTransaction:!1,supportsIndexTypes:[`btree`,`fulltext`,`spatial`],supportsNativeArrays:!1,supportsAddForeignKeyViaAlter:!0,introspectionReadsConstraintNames:!0};getIrreversibleRollbackReason(e){if(e.type!==`alterColumn`)return;let t=e.from.decimal,n=e.to.decimal;if(!(t===void 0||n===void 0||C(e.from)!==`list`||C(e.to)!==`list`||classifyDecimalListDescriptorChange(t,n)!==`narrowing`))return`MySQL cannot automatically roll back the decimal-list widening of "${e.tableName}"."${e.columnName}": the inverse narrows ${r(t)} to ${r(n)}, and its implicit DDL commits cannot make the stricter proof, descriptor-marker change, and cleanup indivisible.`}async preflightSchemaRequirements(e,r){let i=new Set(e.flatMap(e=>e.tables.map(e=>e.name)));if(i.size===0)return!1;let a=await resolveCatalogNamespace(r,this.namespace),o=(await r(`SELECT TABLE_NAME FROM information_schema.VIEWS WHERE TABLE_SCHEMA = ?`,[a])).rows.find(e=>i.has(e.TABLE_NAME));if(o)throw new n(`MySQL relation "${o.TABLE_NAME}" is a view, but this schema declares a table. Synchronization refuses before effects and preserves the view.`,t.MIGRATION_INVALID_STATE,{meta:{table:o.TABLE_NAME,feature:`view`,namespace:a}});return!1}introspect(e){return introspect(e,this.namespace,this.target?.tables)}escapeValue(e){return e==null?`NULL`:m(String(e))}escapeIdentifier(e){if(e==null)throw new n(`Cannot escape null or undefined identifier`,t.INVALID_INPUT);return`\`${String(e).replace(/`/g,"``")}\``}tableRef(e,t){return E(e=>this.escapeIdentifier(e),t===`live`?this.namespace:void 0,e)}mapScalarType(e,t,n){let r=e[`~`].nativeType,i=n===void 0||t.array===!0?void 0:o(n,r,`mysql`);if(i)return i.columnType;let s=a(r,`mysql`);return s&&!t.array?s.type:h({type:t.type,array:t.array,decimal:t.decimal})}getDefaultExpression(e,t){let n=t.type===`datetime`&&!t.array&&t.hasDefault&&!t.autoGenerate?this.literalDefaultValue(t):void 0;if(t.type===`datetime`&&!t.array&&t.hasDefault&&!t.autoGenerate&&typeof n==`string`)return this.escapeValue(s(n));if(!(t.hasDefault&&t.default===null))return t.autoGenerate?.kind===`now`?mysqlNowExpression(this.mapScalarType(e,t)):super.getDefaultExpression(e,t)}finalizeTable(e){let r=new Set([...e.primaryKey?.columns??[],...e.uniqueConstraints.flatMap(e=>e.columns),...e.indexes.flatMap(e=>e.columns),...e.foreignKeys.flatMap(e=>e.columns)]),i=new Set(e.indexes.map(e=>e.name)),a=e.uniqueConstraints.filter(e=>!i.has(e.name)).map(e=>({name:e.name,columns:e.columns,unique:!0})),o={...e,primaryKey:e.primaryKey?{...e.primaryKey,name:`PRIMARY`}:void 0,columns:e.columns.map(e=>finalizeMySQLColumn(e,r.has(e.name))),indexes:[...e.indexes,...a],uniqueConstraints:[]},s=o.indexes.filter(e=>!e.type||e.type===`btree`),c=[{name:`PRIMARY`,columns:o.primaryKey?.columns??[]},...s.map(e=>({name:e.name,columns:e.columns})),...o.foreignKeys.map(e=>({name:e.name,columns:e.columns}))];for(let{name:r,columns:i}of c)for(let a of i){let i=o.columns.find(e=>e.name===a);if(i&&V.test(i.type))throw new n(`MySQL key "${e.name}.${r}" cannot directly index ${i.type} column "${i.name}". Use an indexable native type such as VARCHAR, or manage a reviewed prefix/expression index outside this declaration.`,t.FEATURE_NOT_SUPPORTED,{meta:{table:e.name,column:i.name}})}let l=o.columns.filter(e=>e.autoIncrement);if(l.length>1||l.some(e=>o.primaryKey?.columns[0]!==e.name&&!s.some(t=>t.columns[0]===e.name&&!t.where)&&!o.foreignKeys.some(t=>t.columns[0]===e.name)))throw new n(`MySQL table "${e.name}" requires at most one AUTO_INCREMENT column, first in an ordinary key. Declare its primary key or leading index explicitly.`,t.INVALID_INPUT,{meta:{table:e.name}});return o}formatBooleanDefault(e){return e?`1`:`0`}getEnumColumnType(e,t,n){return f(n)}static AUTO_INCREMENT_TYPES=new Set([`tinyint`,`smallint`,`mediumint`,`int`,`integer`,`bigint`]);validateAutoIncrementType(e){let r=e.type.toLowerCase().split(H)[0];if(!MySQLMigrationDriver.AUTO_INCREMENT_TYPES.has(r))throw new n(`MySQL AUTO_INCREMENT requires an integer type (TINYINT, SMALLINT, MEDIUMINT, INT, INTEGER, BIGINT). Column "${e.name}" has type "${e.type}" which is not compatible with AUTO_INCREMENT.`,t.INVALID_INPUT,{meta:{column:e.name,type:e.type,autoIncrement:!0}})}generateColumnDef(e,t){let n=[this.escapeIdentifier(e.name)],r=e.type.toUpperCase()===x.point;return e.autoIncrement?(this.validateAutoIncrementType(e),n.push(e.type),n.push(`AUTO_INCREMENT`)):n.push(r?W:e.type),e.nullable||n.push(`NOT NULL`),r&&n.push(G),e.default!==void 0&&!e.autoIncrement&&n.push(`DEFAULT ${e.default}`),e.decimal&&C(e)===`list`&&n.push(`COMMENT ${this.escapeValue(p(e.decimal))}`),n.join(` `)}generateCreateTable(e,t){let{table:n}=e,r=n.columns.map(e=>this.generateColumnDef(e,t)),i=n.columns.find(e=>e.autoIncrement),a=i&&n.primaryKey?.columns[0]!==i.name?n.indexes.find(e=>(!e.type||e.type===`btree`)&&!e.where&&e.columns[0]===i.name):void 0;if(a&&r.push(`${a.unique?`UNIQUE `:``}KEY ${this.escapeIdentifier(a.name)} (${a.columns.map(e=>this.escapeIdentifier(e)).join(`, `)})`),n.primaryKey){let e=n.primaryKey.columns.map(e=>this.escapeIdentifier(e)).join(`, `);r.push(`PRIMARY KEY (${e})`)}for(let e of n.uniqueConstraints){let t=e.columns.map(e=>this.escapeIdentifier(e)).join(`, `);r.push(`CONSTRAINT ${this.escapeIdentifier(e.name)} UNIQUE (${t})`)}for(let e of n.foreignKeys)r.push(this.foreignKeyClause(e,t));let o=[`CREATE TABLE ${this.tableRef(n.name,t.destination)} (\n ${r.join(`,
98
98
  `)}\n) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_bin`];for(let e of n.indexes)e!==a&&o.push(this.generateCreateIndex({type:`createIndex`,tableName:n.name,index:e},t));return o}generateDropTable(e,t){return`DROP TABLE IF EXISTS ${this.tableRef(e.tableName,t.destination)}`}generateRenameTable(e,t){return`RENAME TABLE ${this.tableRef(e.from,t.destination)} TO ${this.tableRef(e.to,t.destination)}`}renameDerivedNames(e,t,n,r){let i=[...t].map(([e,{to:t}])=>{let i=n.foreignKeys.find(t=>t.name===e);return i?`DROP FOREIGN KEY ${this.escapeIdentifier(e)}, ADD ${this.foreignKeyClause({...i,name:t},r)}`:`RENAME INDEX ${this.escapeIdentifier(e)} TO ${this.escapeIdentifier(t)}`});return[`ALTER TABLE ${this.tableRef(e,r.destination)} ${i.join(`, `)}`]}generateAddColumn(e,t){let n=this.generateColumnDef(e.column,t);return`ALTER TABLE ${this.tableRef(e.tableName,t.destination)} ADD COLUMN ${n}`}generateDropColumn(e,t){return`ALTER TABLE ${this.tableRef(e.tableName,t.destination)} DROP COLUMN ${this.escapeIdentifier(e.columnName)}`}generateRenameColumn(e,t){return`ALTER TABLE ${this.tableRef(e.tableName,t.destination)} RENAME COLUMN ${this.escapeIdentifier(e.from)} TO ${this.escapeIdentifier(e.to)}`}generateAlterColumn(e,t){let{tableName:n,columnName:r,to:i}=e,a=this.tableRef(n,t.destination),o=this.generateColumnDef(i,t),s=r===i.name?`ALTER TABLE ${a} MODIFY COLUMN ${o}`:`ALTER TABLE ${a} CHANGE COLUMN ${this.escapeIdentifier(r)} ${o}`,c=this.decimalConversionBracket(e,a,t);return c===null?[s]:[c.validate,s,c.release]}decimalConversionBracket(e,i,a){let{from:o,to:s}=e,c=o.decimal,u=s.decimal;if(u===void 0||!l(o,s))return null;if(e.columnName!==s.name)throw new n(`The MySQL decimal conversion for "${e.tableName}"."${e.columnName}" also renames the column to "${s.name}". Run the rename as a separate migration step before changing the decimal descriptor; an interrupted CHECK proof must keep one stable column identity across MySQL's implicit DDL commits.`,t.MIGRATION_INVALID_STATE,{meta:{dialect:`mysql`,table:e.tableName,column:e.columnName,type:`decimal-conversion-with-rename`}});let d=C(s);if(c===void 0)return(d!==`scalar`||!isMySQLExactIntegerType(o.type))&&this.refuseDecimalAdoption(e,a,d),this.decimalScalarConversionBracket(e,i,s.type,u);let f=C(o);if((d===void 0||f!==d)&&this.refuseDecimalConversion(e,a,`moves it from ${v(f)} to ${v(d)} storage, which`),d===`list`){let t=classifyDecimalListDescriptorChange(c,u);return t===`rescaling`&&this.refuseDecimalConversion(e,a,`moves its JSON list from ${r(c)} to ${r(u)}, which rescales every member and so`),t===`narrowing`&&this.refuseDecimalConversion(e,a,`narrows its JSON list from ${r(c)} to ${r(u)}, which`),this.decimalListConversionBracket(e,i,c)}return this.decimalScalarConversionBracket(e,i,s.type,u)}decimalListConversionBracket(e,t,n){let r=this.escapeIdentifier(w(`list`,n));return{validate:`ALTER TABLE ${t} ADD CONSTRAINT ${r} CHECK (${u(this.escapeIdentifier(e.columnName),n)})`,release:`ALTER TABLE ${t} DROP CHECK ${r}`}}decimalScalarConversionBracket(e,t,n,r){let i=this.escapeIdentifier(w(`scalar`,r));return{validate:`ALTER TABLE ${t} ADD CONSTRAINT ${i} CHECK (${_(this.escapeIdentifier(e.columnName),n)})`,release:`ALTER TABLE ${t} DROP CHECK ${i}`}}refuseDecimalAdoption(e,r,i){throw new n(`The declared change to "${e.tableName}"."${e.columnName}" would adopt unmarked ${e.from.type} storage as a fixed-decimal ${v(i)}. Only INT and BIGINT have one exact descriptor-free meaning that a transient target-domain CHECK can prove. Approximate, text, native-decimal-without-descriptor, and unmarked JSON storage could already contain rounded values or members at an unknown scale. The change is refused before any statement runs, so MySQL cannot implicitly round or reinterpret the stored data. Use an explicit migration that validates and rewrites the source values.`,t.FEATURE_NOT_SUPPORTED,{meta:{table:e.tableName,column:e.columnName,feature:`decimal storage adoption`,dialect:`mysql`,target:r.destination}})}refuseDecimalConversion(e,r,i){throw new n(`The declared change to "${e.tableName}"."${e.columnName}" ${i} would rewrite every stored value, and MySQL commits each DDL statement implicitly. There is no boundary that could make the member rewrite and its descriptor-marker change indivisible. The change is refused before any statement runs, so the schema and its data are unchanged. Only same-scale precision widening is applied automatically; narrowing or a scale change needs an explicit migration that validates and moves the values itself.`,t.FEATURE_NOT_SUPPORTED,{meta:{table:e.tableName,column:e.columnName,feature:`decimal descriptor conversion`,dialect:`mysql`,target:r.destination}})}generateCreateIndex(e,r){let{tableName:i,index:a}=e;if(this.validateIndexType(a.type,a.name),a.where)throw new n(`Index "${a.name}" declares a partial index predicate (where: "${a.where}"). MySQL does not support partial indexes. Either remove 'where' from the index definition, or move the predicate into a generated column and index that.`,t.FEATURE_NOT_SUPPORTED,{meta:{indexName:a.name,indexWhere:a.where}});let o=a.columns.map(e=>this.escapeIdentifier(e)).join(`, `),s=``;if(a.type===`fulltext`?s=`FULLTEXT `:a.type===`spatial`&&(s=`SPATIAL `),a.unique&&s)throw new n(`Cannot combine UNIQUE with ${a.type?.toUpperCase()} index "${a.name}". MySQL does not support UNIQUE ${a.type?.toUpperCase()} indexes. Either remove 'unique: true' from the index definition, or create a separate unique index.`,t.MIGRATION_FAILED,{meta:{indexName:a.name,indexType:a.type}});return`CREATE ${a.unique?`UNIQUE `:``}${s}INDEX ${this.escapeIdentifier(a.name)} ON ${this.tableRef(i,r.destination)} (${o})`}generateDropIndex(e,t){return`DROP INDEX ${this.escapeIdentifier(e.indexName)} ON ${this.tableRef(e.tableName,t.destination)}`}generateAddForeignKey(e,t){return`ALTER TABLE ${this.tableRef(e.tableName,t.destination)} ADD ${this.foreignKeyClause(e.fk,t)}`}foreignKeyClause(e,t){let n=e.columns.map(e=>this.escapeIdentifier(e)).join(`, `),r=e.referencedColumns.map(e=>this.escapeIdentifier(e)).join(`, `),i=`CONSTRAINT ${this.escapeIdentifier(e.name)} `;return i+=`FOREIGN KEY (${n}) `,i+=`REFERENCES ${this.tableRef(e.referencedTable,t.destination)} (${r})`,e.onDelete&&e.onDelete!==`noAction`&&(i+=` ON DELETE ${this.formatReferentialAction(e.onDelete)}`),e.onUpdate&&e.onUpdate!==`noAction`&&(i+=` ON UPDATE ${this.formatReferentialAction(e.onUpdate)}`),i}generateDropForeignKey(e,t){return`ALTER TABLE ${this.tableRef(e.tableName,t.destination)} DROP FOREIGN KEY ${this.escapeIdentifier(e.fkName)}`}generateAddUniqueConstraint(e,t){let{tableName:n,constraint:r}=e,i=r.columns.map(e=>this.escapeIdentifier(e)).join(`, `);return`ALTER TABLE ${this.tableRef(n,t.destination)} ADD CONSTRAINT ${this.escapeIdentifier(r.name)} UNIQUE (${i})`}generateDropUniqueConstraint(e,t){return`ALTER TABLE ${this.tableRef(e.tableName,t.destination)} DROP INDEX ${this.escapeIdentifier(e.constraintName)}`}generateAddPrimaryKey(e,t){let{tableName:n,primaryKey:r}=e,i=r.columns.map(e=>this.escapeIdentifier(e)).join(`, `);return`ALTER TABLE ${this.tableRef(n,t.destination)} ADD PRIMARY KEY (${i})`}generateDropPrimaryKey(e,t){return`ALTER TABLE ${this.tableRef(e.tableName,t.destination)} DROP PRIMARY KEY`}generateCreateEnum(e,t){return`-- MySQL: ENUM type is part of column definition`}generateDropEnum(e,t){return`-- MySQL: ENUM type is part of column definition`}generateAlterEnum(e,t){let{enumName:n,newValues:r,dependentColumns:i}=e;if(!r||r.length===0)return[`-- MySQL: no new values provided for enum "${n}"`];if(!i||i.length===0)return[`-- MySQL: no dependent columns found for enum "${n}"`];let a=[],o=this.getEnumColumnType(``,``,r);a.push(...this.buildEnumReplacementUpdates(e,t));for(let e of i){let n=(t.currentSchema?.tables.find(t=>t.name===e.tableName))?.columns.find(t=>t.name===e.columnName);if(!n){a.push(`-- MySQL: column "${e.columnName}" not found in table "${e.tableName}"`);continue}let r=this.tableRef(e.tableName,t.destination),i=this.escapeIdentifier(e.columnName),s=n.nullable?``:` NOT NULL`,c=n.default===void 0?``:` DEFAULT ${n.default}`;a.push(`ALTER TABLE ${r} MODIFY COLUMN ${i} ${o}${s}${c}`)}return a}async proveNamespaceExists(e){await this.resolveCommandNamespace(e)}async resolveCommandNamespace(e){return await resolveCatalogNamespace(e,this.namespace)}generateAcquireLock(e){return mysqlAcquireLockStatement(this.requireLockScope(),30,e=>this.escapeValue(e))}generateReleaseLock(e){return mysqlReleaseLockStatement(this.requireLockScope(),e=>this.escapeValue(e))}provesLockAcquired(e){return mysqlLockAnswer(e,`acquired`)}provesLockReleased(e){return mysqlLockAnswer(e,`released`)}generateSelectTarget(){return this.namespace===void 0?null:mysqlSelectTargetStatement(this.namespace,e=>this.escapeIdentifier(e))}async proveSession(e){await proveMySQLExactValueSession(e,`database "${this.namespace??`(unbound)`}"`);let t=this.requireLockScope(),n=!1,r,i=Object.create(this);return Object.defineProperty(i,`programPreamble`,{value:async e=>{if(n)return[];if(r!==void 0)return await r,[];r=planInterruptedMySQLDecimalRecovery((t,n)=>e._executeRaw(t,n),t,e=>this.escapeIdentifier(e));try{let e=await r;return n=!0,e}catch(e){throw r=void 0,e}}}),Object.freeze(i),i}programPreamble(){return Promise.reject(new n(`This MySQL sequential migration program is not bound to its locked command's decimal-recovery scope.`,t.MIGRATION_INVALID_STATE,{meta:{dialect:`mysql`,type:`unbound-migration-command`}}))}requireLockScope(){if(this.namespace===void 0)throw new n(`This MySQL migration driver is not bound to a database, so there is no lock scope to name. A MySQL named lock is server-wide, and VibORM will not take one that covers every database on the instance. Supply the live destination explicitly, in the connection URL, or through the driver's database option.`,t.MIGRATION_INVALID_STATE,{meta:{dialect:`mysql`,type:`unbound-database`}});return this.namespace}generateInventoryTables(){if(this.namespace===void 0)throw new n(`This MySQL migration driver is not bound to a database, so there is no table inventory to read. VibORM will not fall back to the connection's ambient default database here: a reset inventory decides what gets DROPPED. Supply the live destination explicitly, in the connection URL, or through the driver's database option.`,t.MIGRATION_INVALID_STATE,{meta:{dialect:`mysql`,type:`unbound-database`}});return{sql:`SELECT TABLE_NAME AS name FROM information_schema.TABLES WHERE TABLE_SCHEMA = ? AND TABLE_TYPE = 'BASE TABLE' ORDER BY TABLE_NAME`,params:[this.namespace]}}generateInventoryEnums(){return null}};export{q as t};
99
- //# sourceMappingURL=mysql-hoo290Dd.mjs.map
99
+ //# sourceMappingURL=mysql-DT_dTWDi.mjs.map