{"version":3,"file":"utils.mjs","names":["collectAsync","SelectAstCtor"],"sources":["../../../1-core/contract/src/ir/storage-entry-schemas.ts","../../../1-core/contract/src/ir/sql-node.ts","../../../1-core/contract/src/ir/check-constraint.ts","../../../1-core/contract/src/ir/foreign-key-reference.ts","../../../1-core/contract/src/ir/foreign-key.ts","../../../1-core/contract/src/ir/primary-key.ts","../../../1-core/contract/src/ir/sql-index.ts","../../../1-core/contract/src/ir/storage-column.ts","../../../1-core/contract/src/ir/unique-constraint.ts","../../../1-core/contract/src/ir/storage-table.ts","../../../1-core/contract/src/ir/storage-value-set.ts","../../../1-core/contract/src/entity-kinds.ts","../../../1-core/contract/src/ir/sql-storage.ts","../../../1-core/contract/test/test-support.ts","../../test/test-codec.ts","../../test/utils.ts"],"sourcesContent":["import { type Type, type } from 'arktype';\nimport type { ForeignKeyInput, ReferentialAction } from './foreign-key';\nimport type { ForeignKeyReferenceInput } from './foreign-key-reference';\nimport type { PrimaryKeyInput } from './primary-key';\nimport type { UniqueConstraintInput } from './unique-constraint';\n\ntype ColumnDefaultLiteral = {\n  readonly kind: 'literal';\n  readonly value: string | number | boolean | Record<string, unknown> | unknown[] | null;\n};\ntype ColumnDefaultFunction = { readonly kind: 'function'; readonly expression: string };\n\nconst literalKindSchema = type(\"'literal'\");\nconst functionKindSchema = type(\"'function'\");\nconst ControlPolicySchema = type(\"'managed' | 'tolerated' | 'external' | 'observed'\");\n\nexport const ColumnDefaultLiteralSchema = type.declare<ColumnDefaultLiteral>().type({\n  kind: literalKindSchema,\n  value: 'string | number | boolean | null | unknown[] | Record<string, unknown>',\n});\n\nexport const ColumnDefaultFunctionSchema = type.declare<ColumnDefaultFunction>().type({\n  kind: functionKindSchema,\n  expression: 'string',\n});\n\nexport const ColumnDefaultSchema = ColumnDefaultLiteralSchema.or(ColumnDefaultFunctionSchema);\n\nconst StorageValueSetRefSchema = type({\n  plane: \"'storage'\",\n  namespaceId: 'string',\n  entityKind: \"'valueSet'\",\n  entityName: 'string',\n  'spaceId?': 'string',\n});\n\nconst StorageColumnSchema = type({\n  '+': 'reject',\n  nativeType: 'string',\n  codecId: 'string',\n  nullable: 'boolean',\n  'many?': 'boolean',\n  'typeParams?': 'Record<string, unknown>',\n  'typeRef?': 'string',\n  'default?': ColumnDefaultSchema,\n  'control?': ControlPolicySchema,\n  'valueSet?': StorageValueSetRefSchema,\n}).narrow((col, ctx) => {\n  if (col.typeParams !== undefined && col.typeRef !== undefined) {\n    return ctx.mustBe('a column with either typeParams or typeRef, not both');\n  }\n  return true;\n});\n\n/**\n * Storage value-set entry under `storage.namespaces[id].entries.valueSet[name]`.\n * Carries a `kind: 'valueSet'` discriminator (enumerable, survives JSON) and an\n * ordered `values` array of codec-encoded permitted values.\n */\nexport const StorageValueSetSchema = type({\n  kind: \"'valueSet'\",\n  values: type('string | number | boolean | null | unknown[] | Record<string, unknown>')\n    .array()\n    .readonly(),\n});\n\nconst PrimaryKeySchema = type.declare<PrimaryKeyInput>().type({\n  columns: type.string.array().readonly(),\n  'name?': 'string',\n});\n\nconst UniqueConstraintSchema = type.declare<UniqueConstraintInput>().type({\n  columns: type.string.array().readonly(),\n  'name?': 'string',\n});\n\nexport const IndexSchema = type({\n  columns: type.string.array().readonly(),\n  'name?': 'string',\n  'type?': 'string',\n  'options?': 'Record<string, unknown>',\n});\n\nexport const ForeignKeyReferenceSchema = type({\n  '+': 'reject',\n  namespaceId: 'string',\n  tableName: 'string',\n  columns: type.string.array().readonly(),\n  'spaceId?': 'string',\n}) satisfies Type<ForeignKeyReferenceInput>;\n\nexport const ForeignKeySourceSchema = type({\n  '+': 'reject',\n  namespaceId: 'string',\n  tableName: 'string',\n  columns: type.string.array().readonly(),\n}) satisfies Type<ForeignKeyReferenceInput>;\n\nexport const ReferentialActionSchema = type\n  .declare<ReferentialAction>()\n  .type(\"'noAction' | 'restrict' | 'cascade' | 'setNull' | 'setDefault'\");\n\nexport const ForeignKeySchema = type.declare<ForeignKeyInput>().type({\n  source: ForeignKeySourceSchema,\n  target: ForeignKeyReferenceSchema,\n  'name?': 'string',\n  'onDelete?': ReferentialActionSchema,\n  'onUpdate?': ReferentialActionSchema,\n});\n\nexport const CheckConstraintSchema = type({\n  '+': 'reject',\n  name: 'string',\n  column: 'string',\n  valueSet: StorageValueSetRefSchema,\n});\n\nexport const StorageTableSchema = type({\n  '+': 'reject',\n  columns: type({ '[string]': StorageColumnSchema }),\n  'primaryKey?': PrimaryKeySchema,\n  uniques: UniqueConstraintSchema.array().readonly(),\n  indexes: IndexSchema.array().readonly(),\n  foreignKeys: ForeignKeySchema.array().readonly(),\n  'control?': ControlPolicySchema,\n  'checks?': CheckConstraintSchema.array().readonly(),\n});\n","import { IRNodeBase } from '@prisma-next/framework-components/ir';\n\n/**\n * SQL family IR node base. Carries the family-level `kind` discriminator\n * `'sql'` and inherits the framework's `freezeNode` affordance.\n *\n * Single family-level discriminator (not per-leaf) reflects the fact that\n * SQL IR has no polymorphic dispatch today — verifiers and serializers\n * walk by structural position (`storage.tables[name].columns[name]`),\n * not by inspecting `kind`. The abstract bar for per-leaf discriminators\n * isn't earned until a future polymorphic consumer arrives.\n *\n * `kind` is installed as a non-enumerable own property on every instance,\n * which keeps three things clean simultaneously:\n *\n * - `JSON.stringify(node)` produces the canonical pre-lift JSON envelope\n *   shape (no `kind` field), so emitted contract.json files and the\n *   `validateSqlContractFully` arktype schemas stay unchanged.\n * - Test assertions that use `toEqual({...})` against the pre-lift flat\n *   shape continue to pass — only enumerable own properties are\n *   compared.\n * - Direct access (`node.kind`) and runtime narrowing\n *   (`if (node.kind === 'sql')`) still work, so future polymorphic\n *   dispatch can begin reading `kind` without a runtime change.\n *\n * Future per-leaf overrides land cleanly: a class that gains a\n * polymorphic-dispatch consumer (e.g. an enum type instance walked\n * alongside other types) overrides `kind` with its narrower literal\n * at that leaf level. Per-leaf overrides will use enumerable kind\n * (matching the Mongo per-class-discriminator precedent) because they\n * encode dispatch-relevant information that callers need to see in\n * JSON envelopes; the family-level `'sql'` is uniform across all SQL\n * IR and carries no dispatch-relevant information.\n */\nexport abstract class SqlNode extends IRNodeBase {\n  readonly kind?: string;\n\n  constructor() {\n    super();\n    Object.defineProperty(this, 'kind', {\n      value: 'sql',\n      writable: false,\n      enumerable: false,\n      // configurable so per-leaf subclasses (e.g. StorageValueSet)\n      // can override `kind` with their narrower\n      // enumerable literal via a class-field initializer. SqlNode\n      // itself never needs to mutate the property again, so\n      // configurability has no surface impact at this layer.\n      configurable: true,\n    });\n  }\n}\n","import type { ValueSetRef } from '@prisma-next/contract/types';\nimport { freezeNode } from '@prisma-next/framework-components/ir';\nimport { SqlNode } from './sql-node';\n\n/**\n * Hydration / construction input shape for {@link CheckConstraint}.\n * Mirrors the on-disk storage JSON envelope so the serializer hydration\n * walker can hand a validated literal straight to `new`.\n */\nexport interface CheckConstraintInput {\n  readonly name: string;\n  readonly column: string;\n  readonly valueSet: ValueSetRef;\n}\n\n/**\n * SQL Contract IR node for a table-level check constraint that restricts\n * a column to the permitted values of a value-set.\n *\n * The constraint is **structured** (names a column and a value-set\n * reference), not a raw SQL expression. Each target renders its own DDL\n * from the structured form, keeping the contract target-agnostic.\n *\n * Construction is idempotent: passing an existing `CheckConstraint`\n * instance as input produces a new instance with identical fields.\n * The constructor does not use `instanceof` for input discrimination —\n * it reads plain named properties, which is sufficient since\n * `CheckConstraintInput` is a structural type.\n */\nexport class CheckConstraint extends SqlNode {\n  readonly name: string;\n  readonly column: string;\n  readonly valueSet: ValueSetRef;\n\n  constructor(input: CheckConstraintInput) {\n    super();\n    this.name = input.name;\n    this.column = input.column;\n    this.valueSet = input.valueSet;\n    freezeNode(this);\n  }\n}\n","import { asNamespaceId, type NamespaceId } from '@prisma-next/contract/types';\nimport { freezeNode } from '@prisma-next/framework-components/ir';\nimport { SqlNode } from './sql-node';\n\n/**\n * Input for a foreign-key reference (one side of a foreign-key declaration).\n *\n * When `spaceId` is absent the reference is local — the referenced table lives\n * in the same contract-space. When `spaceId` is present the reference is\n * cross-space — the referenced table lives in a different contract-space\n * identified by `spaceId`.\n *\n * Presence-based discrimination keeps local FK JSON byte-identical to\n * contracts authored before cross-space support was added.\n */\nexport interface ForeignKeyReferenceInput {\n  readonly namespaceId: string;\n  readonly tableName: string;\n  readonly columns: readonly string[];\n  readonly spaceId?: string;\n}\n\n/**\n * SQL Contract IR node for one side (source or target) of a foreign-key\n * declaration. Carries the full coordinate: namespace, table, and columns.\n *\n * Cross-space discrimination is based on `spaceId` presence: absent means\n * local (same contract-space); present means cross-space (the referenced\n * table lives in the contract-space identified by `spaceId`).\n *\n * For local references `spaceId` is absent from JSON, keeping the serialized\n * shape byte-identical to contracts authored before cross-space support was\n * added. For cross-space references `spaceId` appears in JSON so round-trips\n * are lossless.\n *\n * Use `UNBOUND_NAMESPACE_ID` from `@prisma-next/framework-components/ir`\n * as the sentinel `namespaceId` for single-namespace (unbound) references.\n */\nexport class ForeignKeyReference extends SqlNode {\n  readonly namespaceId: NamespaceId;\n  readonly tableName: string;\n  readonly columns: readonly string[];\n  declare readonly spaceId?: string;\n\n  constructor(input: ForeignKeyReferenceInput) {\n    super();\n    this.namespaceId = asNamespaceId(input.namespaceId);\n    this.tableName = input.tableName;\n    this.columns = input.columns;\n    if (input.spaceId !== undefined) this.spaceId = input.spaceId;\n    freezeNode(this);\n  }\n}\n","import { freezeNode } from '@prisma-next/framework-components/ir';\nimport { ForeignKeyReference, type ForeignKeyReferenceInput } from './foreign-key-reference';\nimport { SqlNode } from './sql-node';\n\nexport type ReferentialAction = 'noAction' | 'restrict' | 'cascade' | 'setNull' | 'setDefault';\n\nexport interface ForeignKeyInput {\n  readonly source: ForeignKeyReference | ForeignKeyReferenceInput;\n  readonly target: ForeignKeyReference | ForeignKeyReferenceInput;\n  readonly name?: string;\n  readonly onDelete?: ReferentialAction;\n  readonly onUpdate?: ReferentialAction;\n}\n\n/**\n * SQL Contract IR node for a table-level foreign-key declaration — the\n * referential constraint only (source, target, `onDelete`/`onUpdate`).\n *\n * A persisted `foreignKeys[]` entry always denotes a real constraint: whether\n * to emit the constraint at all, and whether to back it with an index, are\n * authoring-time decisions (PSL `@relation(index:)`, TS `fk({ constraint,\n * index })`) resolved once at `contract emit` — a `constraint: false` FK\n * simply has no entry here, and a backing index (if any) is its own discrete,\n * named entry in the table's `indexes[]`.\n *\n * Each FK carries explicit `source` and `target` {@link ForeignKeyReference}\n * coordinates (namespace, table, columns). For single-namespace contracts the\n * sentinel `UNBOUND_NAMESPACE_ID` appears on both sides.\n *\n * The nested references are normalised to {@link ForeignKeyReference}\n * instances inside the constructor so downstream walks see a uniform AST\n * regardless of whether the input was a JSON literal or an already-constructed\n * class instance.\n */\nexport class ForeignKey extends SqlNode {\n  readonly source: ForeignKeyReference;\n  readonly target: ForeignKeyReference;\n  declare readonly name?: string;\n  declare readonly onDelete?: ReferentialAction;\n  declare readonly onUpdate?: ReferentialAction;\n\n  constructor(input: ForeignKeyInput) {\n    super();\n    this.source =\n      input.source instanceof ForeignKeyReference\n        ? input.source\n        : new ForeignKeyReference(input.source);\n    this.target =\n      input.target instanceof ForeignKeyReference\n        ? input.target\n        : new ForeignKeyReference(input.target);\n    if (input.name !== undefined) this.name = input.name;\n    if (input.onDelete !== undefined) this.onDelete = input.onDelete;\n    if (input.onUpdate !== undefined) this.onUpdate = input.onUpdate;\n    freezeNode(this);\n  }\n}\n","import { freezeNode } from '@prisma-next/framework-components/ir';\nimport { SqlNode } from './sql-node';\n\nexport interface PrimaryKeyInput {\n  readonly columns: readonly string[];\n  readonly name?: string;\n}\n\n/**\n * SQL Contract IR node for a table's primary-key constraint.\n */\nexport class PrimaryKey extends SqlNode {\n  readonly columns: readonly string[];\n  declare readonly name?: string;\n\n  constructor(input: PrimaryKeyInput) {\n    super();\n    this.columns = input.columns;\n    if (input.name !== undefined) this.name = input.name;\n    freezeNode(this);\n  }\n}\n","import { freezeNode } from '@prisma-next/framework-components/ir';\nimport { SqlNode } from './sql-node';\n\nexport interface IndexInput {\n  readonly columns: readonly string[];\n  readonly name?: string;\n  readonly type?: string;\n  readonly options?: Record<string, unknown>;\n}\n\n/**\n * SQL Contract IR node for a table-level secondary index.\n *\n * Note that this class shadows the global TypeScript `Index` lib type\n * at the family-shared name; consumer files that need both should\n * alias one (e.g.\n * `import { Index as SqlIndexNode } from '@prisma-next/sql-contract/types'`).\n */\nexport class Index extends SqlNode {\n  readonly columns: readonly string[];\n  declare readonly name?: string;\n  declare readonly type?: string;\n  declare readonly options?: Record<string, unknown>;\n\n  constructor(input: IndexInput) {\n    super();\n    this.columns = input.columns;\n    if (input.name !== undefined) this.name = input.name;\n    if (input.type !== undefined) this.type = input.type;\n    if (input.options !== undefined) this.options = input.options;\n    freezeNode(this);\n  }\n}\n","import type { ColumnDefault, ControlPolicy, ValueSetRef } from '@prisma-next/contract/types';\nimport { freezeNode } from '@prisma-next/framework-components/ir';\nimport { SqlNode } from './sql-node';\n\n/**\n * Hydration / construction input shape for {@link StorageColumn}. Mirrors\n * the on-disk storage JSON envelope exactly so the family-base\n * serializer's hydration walker can hand an arktype-validated literal\n * straight to `new`.\n *\n * `typeParams` and `typeRef` remain mutually exclusive (one or the\n * other, not both); the constructor preserves whichever caller-side\n * choice the input encodes.\n */\nexport interface StorageColumnInput {\n  readonly nativeType: string;\n  readonly codecId: string;\n  readonly nullable: boolean;\n  readonly many?: boolean;\n  readonly typeParams?: Record<string, unknown>;\n  readonly typeRef?: string;\n  readonly default?: ColumnDefault;\n  readonly control?: ControlPolicy;\n  readonly valueSet?: ValueSetRef;\n}\n\n/**\n * SQL Contract IR node for a single column entry in `StorageTable.columns`.\n *\n * Single concrete family-shared class — every SQL target reads the\n * same column shape today, so there is no per-target subclass. The\n * class type accepts any caller that constructs via\n * `new StorageColumn(input)`; literal construction sites must pass\n * through the constructor or the family-base hydration walker.\n *\n * The column's `name` is not on the class — columns are keyed by name\n * in the parent `StorageTable.columns: Record<string, StorageColumn>`\n * map, so a `name` field would be redundant with the key.\n */\nexport class StorageColumn extends SqlNode {\n  readonly nativeType: string;\n  readonly codecId: string;\n  readonly nullable: boolean;\n  declare readonly many?: boolean;\n  declare readonly typeParams?: Record<string, unknown>;\n  declare readonly typeRef?: string;\n  declare readonly default?: ColumnDefault;\n  declare readonly control?: ControlPolicy;\n  declare readonly valueSet?: ValueSetRef;\n\n  constructor(input: StorageColumnInput) {\n    super();\n    this.nativeType = input.nativeType;\n    this.codecId = input.codecId;\n    this.nullable = input.nullable;\n    if (input.many !== undefined) this.many = input.many;\n    if (input.typeParams !== undefined) this.typeParams = input.typeParams;\n    if (input.typeRef !== undefined) this.typeRef = input.typeRef;\n    if (input.default !== undefined) this.default = input.default;\n    if (input.control !== undefined) this.control = input.control;\n    if (input.valueSet !== undefined) this.valueSet = input.valueSet;\n    freezeNode(this);\n  }\n}\n","import { freezeNode } from '@prisma-next/framework-components/ir';\nimport { SqlNode } from './sql-node';\n\nexport interface UniqueConstraintInput {\n  readonly columns: readonly string[];\n  readonly name?: string;\n}\n\n/**\n * SQL Contract IR node for a table-level unique constraint.\n */\nexport class UniqueConstraint extends SqlNode {\n  readonly columns: readonly string[];\n  declare readonly name?: string;\n\n  constructor(input: UniqueConstraintInput) {\n    super();\n    this.columns = input.columns;\n    if (input.name !== undefined) this.name = input.name;\n    freezeNode(this);\n  }\n}\n","import type { ControlPolicy } from '@prisma-next/contract/types';\nimport { freezeNode } from '@prisma-next/framework-components/ir';\nimport { CheckConstraint, type CheckConstraintInput } from './check-constraint';\nimport { ForeignKey, type ForeignKeyInput } from './foreign-key';\nimport { PrimaryKey, type PrimaryKeyInput } from './primary-key';\nimport { Index, type IndexInput } from './sql-index';\nimport { SqlNode } from './sql-node';\nimport { StorageColumn, type StorageColumnInput } from './storage-column';\nimport { UniqueConstraint, type UniqueConstraintInput } from './unique-constraint';\n\nexport interface StorageTableInput {\n  readonly columns: Record<string, StorageColumn | StorageColumnInput>;\n  readonly primaryKey?: PrimaryKey | PrimaryKeyInput;\n  readonly uniques: ReadonlyArray<UniqueConstraint | UniqueConstraintInput>;\n  readonly indexes: ReadonlyArray<Index | IndexInput>;\n  readonly foreignKeys: ReadonlyArray<ForeignKey | ForeignKeyInput>;\n  readonly control?: ControlPolicy;\n  readonly checks?: ReadonlyArray<CheckConstraint | CheckConstraintInput>;\n}\n\n/**\n * SQL Contract IR node for a single table entry in a namespace's\n * `tables` map.\n *\n * The constructor normalises nested IR-class fields (columns, primary\n * key, uniques, indexes, foreign keys) into the appropriate class\n * instances so downstream walks see a uniform AST regardless of whether\n * the input was a JSON literal or an already-constructed class.\n *\n * The table's `name` is not on the class — tables are keyed by name in\n * the parent namespace's `tables: Record<string, StorageTable>` map.\n */\nexport class StorageTable extends SqlNode {\n  readonly columns: Readonly<Record<string, StorageColumn>>;\n  readonly uniques: ReadonlyArray<UniqueConstraint>;\n  readonly indexes: ReadonlyArray<Index>;\n  readonly foreignKeys: ReadonlyArray<ForeignKey>;\n  declare readonly primaryKey?: PrimaryKey;\n  declare readonly control?: ControlPolicy;\n  declare readonly checks?: ReadonlyArray<CheckConstraint>;\n\n  constructor(input: StorageTableInput) {\n    super();\n    this.columns = Object.freeze(\n      Object.fromEntries(\n        Object.entries(input.columns).map(([name, col]) => [\n          name,\n          col instanceof StorageColumn ? col : new StorageColumn(col),\n        ]),\n      ),\n    );\n    if (input.primaryKey !== undefined) {\n      this.primaryKey =\n        input.primaryKey instanceof PrimaryKey\n          ? input.primaryKey\n          : new PrimaryKey(input.primaryKey);\n    }\n    this.uniques = Object.freeze(\n      input.uniques.map((u) => (u instanceof UniqueConstraint ? u : new UniqueConstraint(u))),\n    );\n    this.indexes = Object.freeze(input.indexes.map((i) => (i instanceof Index ? i : new Index(i))));\n    this.foreignKeys = Object.freeze(\n      input.foreignKeys.map((fk) => (fk instanceof ForeignKey ? fk : new ForeignKey(fk))),\n    );\n    if (input.control !== undefined) this.control = input.control;\n    if (input.checks !== undefined && input.checks.length > 0) {\n      this.checks = Object.freeze(input.checks.map((cc) => new CheckConstraint(cc)));\n    }\n    freezeNode(this);\n  }\n\n  /**\n   * Runtime guard that a namespace `table` entry is really a `StorageTable`.\n   * The compiler already types the entry as `StorageTable`, but a\n   * freshly-deserialized contract may carry plain JSON at that slot until\n   * hydration; this duck-types the structural shape. Accepts `undefined` so\n   * optional-chained entry lookups pass straight through.\n   */\n  static is(value: StorageTable | undefined): value is StorageTable {\n    if (typeof value !== 'object' || value === null) return false;\n    return 'columns' in value && 'uniques' in value && 'indexes' in value && 'foreignKeys' in value;\n  }\n\n  static assert(\n    value: StorageTable | undefined,\n    coordinate: string,\n  ): asserts value is StorageTable {\n    if (!StorageTable.is(value)) {\n      throw new Error(`Expected a StorageTable at ${coordinate}`);\n    }\n  }\n}\n","import type { JsonValue } from '@prisma-next/contract/types';\nimport { freezeNode } from '@prisma-next/framework-components/ir';\nimport { SqlNode } from './sql-node';\n\n/**\n * Hydration / construction input shape for {@link StorageValueSet}.\n * Mirrors the on-disk storage JSON envelope so the serializer hydration\n * walker can hand a validated literal straight to `new`.\n */\nexport interface StorageValueSetInput {\n  readonly kind: 'valueSet';\n  /** Ordered permitted values, codec-encoded. Declaration order is preserved. */\n  readonly values: readonly JsonValue[];\n}\n\n/**\n * SQL Contract IR node for a value-set entry in a namespace's `valueSet`\n * map (`SqlNamespace.entries.valueSet`).\n *\n * A value-set records the ordered set of permitted codec-encoded values for\n * an enum-like column restriction. It does not carry a `codecId` — the\n * column that references it already holds the codec; the value-set holds\n * only the permitted values.\n *\n * The node's `kind` is enumerable (`'valueSet'`) so the JSON envelope\n * carries the discriminator and the serializer hydration walker can\n * dispatch on it. This follows the per-leaf enumerable-kind convention\n * established in the SQL-node comment (future polymorphic dispatch on\n * namespace entries needs the discriminator in JSON).\n *\n * The entry's name is not on the class — value-sets are keyed by name in\n * the parent namespace's `valueSet: Record<string, StorageValueSet>` map.\n */\nexport class StorageValueSet extends SqlNode {\n  override readonly kind = 'valueSet' as const;\n  readonly values: readonly JsonValue[];\n\n  constructor(input: StorageValueSetInput) {\n    super();\n    this.values = Object.freeze([...input.values]);\n    freezeNode(this);\n  }\n}\n\nexport function isStorageValueSet(value: unknown): value is StorageValueSet {\n  if (typeof value !== 'object' || value === null) return false;\n  return 'kind' in value && value.kind === 'valueSet' && 'values' in value;\n}\n","import type {\n  AnyEntityKindDescriptor,\n  EntityKindDescriptor,\n} from '@prisma-next/framework-components/ir';\nimport { StorageTableSchema, StorageValueSetSchema } from './ir/storage-entry-schemas';\nimport { StorageTable, type StorageTableInput } from './ir/storage-table';\nimport { StorageValueSet, type StorageValueSetInput } from './ir/storage-value-set';\n\nexport const tableEntityKind: EntityKindDescriptor<StorageTableInput, StorageTable> = {\n  kind: 'table',\n  schema: StorageTableSchema,\n  construct: (input) => new StorageTable(input),\n};\n\nexport const valueSetEntityKind: EntityKindDescriptor<StorageValueSetInput, StorageValueSet> = {\n  kind: 'valueSet',\n  schema: StorageValueSetSchema,\n  construct: (input) => new StorageValueSet(input),\n};\n\n/**\n * Assembles the `kind → descriptor` registry for SQL namespaces: the built-in\n * `table` and `valueSet` kinds plus any target `packKinds`. This builds the\n * lookup table — it does not touch contract data. `hydrateNamespaceEntities`\n * later consumes this registry to turn a namespace's raw entries into IR\n * instances, and `createSqlContractSchema` derives validation from the same\n * registry. Throws on a duplicate kind.\n */\nexport function composeSqlEntityKinds(\n  packKinds: readonly AnyEntityKindDescriptor[] = [],\n): ReadonlyMap<string, AnyEntityKindDescriptor> {\n  const kinds = new Map<string, AnyEntityKindDescriptor>([\n    ['table', tableEntityKind],\n    ['valueSet', valueSetEntityKind],\n  ]);\n  for (const descriptor of packKinds) {\n    if (kinds.has(descriptor.kind)) {\n      throw new Error(\n        `composeSqlEntityKinds: duplicate entity kind \"${descriptor.kind}\" — each kind may be registered only once`,\n      );\n    }\n    kinds.set(descriptor.kind, descriptor);\n  }\n  return kinds;\n}\n","import type { StorageHashBase } from '@prisma-next/contract/types';\nimport type { AuthoringContributions } from '@prisma-next/framework-components/authoring';\nimport {\n  freezeNode,\n  isPlainRecord,\n  type Namespace,\n  NamespaceBase,\n  type Storage,\n} from '@prisma-next/framework-components/ir';\nimport { SqlNode } from './sql-node';\nimport type { StorageTable } from './storage-table';\nimport {\n  isStorageTypeInstance,\n  type StorageTypeInstance,\n  type StorageTypeInstanceInput,\n  toStorageTypeInstance,\n} from './storage-type-instance';\nimport type { StorageValueSet } from './storage-value-set';\n\n/**\n * Polymorphic value type for document-scoped `SqlStorage.types` entries\n * (codec aliases / parameterised native type registrations).\n *\n * Postgres native enum registrations live under the postgres-specific\n * `entries.type` slot on `PostgresSchema` (target layer), not here.\n */\nexport type SqlStorageTypeEntry = StorageTypeInstance | StorageTypeInstanceInput;\n\nexport interface SqlNamespaceInput {\n  readonly id: string;\n  readonly entries: Readonly<Record<string, Readonly<Record<string, unknown>>>>;\n}\n\n/**\n * Target-supplied factory that materializes a `Namespace` from a SQL\n * `SqlNamespaceInput` (used to populate `SqlStorage.namespaces`).\n */\nexport type SqlNamespaceFactory = (input: SqlNamespaceInput) => Namespace;\n\n/**\n * SQL-family extension of the framework `AuthoringContributions`. SQL target\n * packs add a `createNamespace` factory so the PSL/TS authoring paths can\n * materialize namespaces (and merge lowered extension-block entities) without\n * each consumer re-specifying it. The factory is SQL-specific, so it lives here\n * rather than on the framework `AuthoringContributions` base.\n */\nexport interface SqlAuthoringContributions extends AuthoringContributions {\n  readonly createNamespace?: SqlNamespaceFactory;\n}\n\n/**\n * Narrows framework `AuthoringContributions` to the SQL-family shape by testing\n * for the SQL-specific `createNamespace` capability.\n */\nexport function isSqlAuthoringContributions(\n  authoring: AuthoringContributions | undefined,\n): authoring is SqlAuthoringContributions {\n  if (authoring === undefined || !Object.hasOwn(authoring, 'createNamespace')) {\n    return false;\n  }\n  return typeof Reflect.get(authoring, 'createNamespace') === 'function';\n}\n\nexport interface SqlStorageInput<THash extends string = string> {\n  readonly storageHash: StorageHashBase<THash>;\n  readonly types?: Record<string, SqlStorageTypeEntry>;\n  readonly namespaces: Readonly<Record<string, SqlNamespaceBase>>;\n}\n\n/**\n * SQL Contract IR root node for the `storage` field.\n *\n * Single concrete family-shared class — both Postgres and SQLite\n * consume this class today. Per-target storage subclasses are\n * introduced when each target's namespace shape earns its\n * target-specific concretion (target-specific derived fields,\n * target-specific storage extensions).\n *\n * Honours the framework `Storage` interface: every SQL IR carries a\n * `namespaces` map keyed by namespace id. Callers must supply fully\n * constructed `Namespace` instances — construction discipline lives\n * in the authoring builders and deserializer hydration paths.\n *\n * The constructor normalises optional `types` into class instances.\n * `types` is polymorphic per Decision 18 Option B: codec-triple inputs\n * are stamped with `kind: 'codec-instance'`; hydration of raw JSON\n * class-instance entries (carrying their narrower `kind` literal) is\n * the per-target serializer's responsibility (so the family base does\n * not import target-specific subclasses).\n */\n/**\n * The typed `entries` shape for SQL family namespaces. The open dictionary\n * is intersected with optional known-kind maps so that `ns.entries.table`\n * and `ns.entries.valueSet` resolve without a cast, while unknown pack-\n * contributed kinds remain valid (the `Record` part allows any string key).\n */\nexport type SqlNamespaceEntries = Readonly<Record<string, Readonly<Record<string, unknown>>>> & {\n  readonly table?: Readonly<Record<string, StorageTable>>;\n  readonly valueSet?: Readonly<Record<string, StorageValueSet>>;\n};\n\n/**\n * Structural interface for SQL family namespaces. Generated `.d.ts` contract\n * types satisfy this structurally (no prototype methods). The runtime\n * abstract class `SqlNamespaceBase` extends this.\n *\n * `qualifyTable` and `isUnbound` are optional so JSON-shaped contract types\n * (which carry no methods) are accepted where `SqlNamespace` is required.\n * Hydrated `SqlNamespaceBase` instances always have both.\n */\nexport interface SqlNamespace {\n  readonly kind: string;\n  readonly id: string;\n  readonly entries: SqlNamespaceEntries;\n  readonly isUnbound?: boolean;\n  qualifyTable?(tableName: string): string;\n}\n\n/**\n * Abstract SQL family namespace base class. Target concretions (`PostgresSchema`,\n * `SqliteDatabase`, …) extend this — it is never instantiated directly.\n * `entries` is the open ADR 224 dictionary: `entries[entityKind][entityName]`\n * addresses any entity.\n */\nexport abstract class SqlNamespaceBase extends NamespaceBase implements SqlNamespace {\n  abstract override readonly id: string;\n  abstract override readonly entries: SqlNamespaceEntries;\n\n  abstract qualifyTable(tableName: string): string;\n}\n\n/**\n * Realm-safe guard for hydrated `SqlNamespaceBase` concretions. Checks\n * `qualifyTable` structurally instead of `instanceof NamespaceBase`, so it\n * survives duplicate-module boundaries (e.g. dist e2e where the target and\n * the family carry separate copies of `@prisma-next/framework-components`).\n *\n * Every concrete `SqlNamespaceBase` subclass (`PostgresSchema`, `SqliteDatabase`,\n * `TestSqlNamespace`, …) implements `qualifyTable`. Raw `SqlNamespaceInput`\n * objects (`{ id, entries }`) do not.\n */\nexport function isMaterializedSqlNamespace(x: unknown): x is SqlNamespaceBase {\n  if (typeof x !== 'object' || x === null || !('qualifyTable' in x)) return false;\n  return typeof x.qualifyTable === 'function';\n}\n\nexport class SqlStorage<THash extends string = string> extends SqlNode implements Storage {\n  readonly storageHash: StorageHashBase<THash>;\n  readonly namespaces: Readonly<Record<string, SqlNamespace>>;\n  declare readonly types?: Readonly<Record<string, StorageTypeInstance>>;\n\n  constructor(input: SqlStorageInput<THash>) {\n    super();\n    this.storageHash = input.storageHash;\n    this.namespaces = Object.freeze(input.namespaces);\n    if (input.types !== undefined) {\n      this.types = Object.freeze(\n        Object.fromEntries(\n          Object.entries(input.types).map(([name, ti]) => [name, normaliseTypeEntry(name, ti)]),\n        ),\n      );\n    }\n    freezeNode(this);\n  }\n}\n\n/**\n * Strict polymorphic-slot dispatch for `SqlStorage.types` entries.\n * Every entry must carry a `kind: 'codec-instance'` discriminator or\n * be an already-constructed `StorageTypeInstance`. Untagged or\n * unrecognised inputs throw a diagnostic naming the entry and its\n * `kind`, so format drift surfaces loudly at the deserializer\n * boundary instead of slipping past the seam and corrupting\n * downstream IR walks.\n *\n * Codec-triple authors that have an untagged shape on hand can call\n * `toStorageTypeInstance(...)` (which stamps the `'codec-instance'`\n * discriminator) before constructing `SqlStorage`. On-disk reads\n * cross `familyInstance.deserializeContract` first; the structural\n * arktype schema rejects untagged entries earlier, so this throw\n * only fires for in-memory authoring bugs.\n */\nfunction normaliseTypeEntry(name: string, entry: SqlStorageTypeEntry): StorageTypeInstance {\n  if (isStorageTypeInstance(entry)) {\n    // Normalise on-disk objects that omit `typeParams` (the canonical on-disk\n    // form strips empty typeParams to keep JSON compact). The in-memory invariant\n    // is always `typeParams: {}` when empty — never `undefined`. Only create a\n    // new object when necessary to preserve identity-equality for callers that\n    // hold a reference to an already-correct in-memory entry.\n    if ('typeParams' in entry) {\n      return entry;\n    }\n    return toStorageTypeInstance(entry);\n  }\n  const rawKind = isPlainRecord(entry) ? entry['kind'] : undefined;\n  const kindDescription =\n    rawKind === undefined\n      ? 'missing `kind` discriminator'\n      : `unrecognised \\`kind\\` discriminator ${JSON.stringify(rawKind)}`;\n  throw new Error(\n    `storage.types[${JSON.stringify(name)}] has ${kindDescription}; expected ${JSON.stringify('codec-instance')}. Untagged codec triples should be wrapped with toStorageTypeInstance(...) before construction.`,\n  );\n}\n","import {\n  freezeNode,\n  hydrateNamespaceEntities,\n  UNBOUND_NAMESPACE_ID,\n} from '@prisma-next/framework-components/ir';\nimport { blindCast } from '@prisma-next/utils/casts';\nimport { composeSqlEntityKinds } from '../src/entity-kinds';\nimport {\n  SqlNamespaceBase,\n  type SqlNamespaceEntries,\n  type SqlNamespaceInput,\n} from '../src/ir/sql-storage';\nimport type { StorageTable } from '../src/ir/storage-table';\nimport type { StorageValueSet } from '../src/ir/storage-value-set';\n\n/**\n * Minimal concrete `SqlNamespaceBase` for use in `packages/2-sql/**` unit tests.\n *\n * This is a legitimate target concretion — not a materialised family\n * namespace.  Production code never constructs one; the target-specific\n * concretions (`PostgresSchema`, `SqliteDatabase`) are used in production.\n */\nexport class TestSqlNamespace extends SqlNamespaceBase {\n  declare readonly kind: 'test-sql-namespace';\n  readonly id: string;\n  readonly entries: SqlNamespaceEntries;\n\n  constructor(input: SqlNamespaceInput) {\n    super();\n    this.id = input.id;\n    const dispatched = hydrateNamespaceEntities(input.entries, composeSqlEntityKinds(), 'carry');\n    this.entries = Object.freeze(\n      blindCast<\n        SqlNamespaceEntries,\n        'composeSqlEntityKinds() supplies table→StorageTable and valueSet→StorageValueSet descriptors'\n      >(dispatched),\n    );\n    Object.defineProperty(this, 'kind', {\n      value: 'test-sql-namespace',\n      writable: false,\n      enumerable: false,\n      configurable: true,\n    });\n    freezeNode(this);\n  }\n\n  get table(): Readonly<Record<string, StorageTable>> {\n    return this.entries.table ?? Object.freeze({});\n  }\n\n  get valueSet(): Readonly<Record<string, StorageValueSet>> | undefined {\n    return this.entries.valueSet;\n  }\n\n  qualifyTable(tableName: string): string {\n    if (this.id === UNBOUND_NAMESPACE_ID) {\n      return `\"${tableName}\"`;\n    }\n    return `\"${this.id}\".\"${tableName}\"`;\n  }\n}\n\nexport function createTestSqlNamespace(input: SqlNamespaceInput): TestSqlNamespace {\n  return new TestSqlNamespace(input);\n}\n","/**\n * Test-only helper that constructs a SQL-family `Codec` instance from author-side encode/decode functions. Replaces the legacy public `mkCodec()` factory (deleted under TML-2357); tests that need a stub codec for behavioural assertions instantiate one through this helper rather than going through `descriptor.factory(...)`.\n *\n * The body is identical in spirit to the retired `mkCodec`: promise-lift sync author functions onto the framework-required `Promise<…>` boundary, default `encodeJson`/`decodeJson` to identity when `TInput` is JSON-safe, fail loudly otherwise.\n */\nimport type { JsonValue } from '@prisma-next/contract/types';\nimport type { CodecTrait } from '@prisma-next/framework-components/codec';\nimport type { Codec, SqlCodecCallContext } from '@prisma-next/sql-relational-core/ast';\n\ntype JsonRoundTripConfig<TInput> = [TInput] extends [JsonValue]\n  ? {\n      encodeJson?: (value: TInput) => JsonValue;\n      decodeJson?: (json: JsonValue) => TInput;\n    }\n  : {\n      encodeJson: (value: TInput) => JsonValue;\n      decodeJson: (json: JsonValue) => TInput;\n    };\n\nexport function defineTestCodec<\n  Id extends string,\n  const TTraits extends readonly CodecTrait[] = readonly [],\n  TWire = unknown,\n  TInput = unknown,\n>(\n  config: {\n    typeId: Id;\n    targetTypes?: readonly string[];\n    encode: (value: TInput, ctx: SqlCodecCallContext) => TWire | Promise<TWire>;\n    decode: (wire: TWire, ctx: SqlCodecCallContext) => TInput | Promise<TInput>;\n    traits?: TTraits;\n  } & JsonRoundTripConfig<TInput>,\n): Codec<Id, TTraits, TWire, TInput> {\n  const identity = (v: unknown) => v;\n  const userEncode = config.encode;\n  const userDecode = config.decode;\n  const widenedConfig = config as {\n    encodeJson?: (value: TInput) => JsonValue;\n    decodeJson?: (json: JsonValue) => TInput;\n  };\n  return {\n    id: config.typeId,\n    encode: (value, ctx) => {\n      try {\n        return Promise.resolve(userEncode(value, ctx));\n      } catch (error) {\n        return Promise.reject(error);\n      }\n    },\n    decode: (wire, ctx) => {\n      try {\n        return Promise.resolve(userDecode(wire, ctx));\n      } catch (error) {\n        return Promise.reject(error);\n      }\n    },\n    encodeJson: (widenedConfig.encodeJson ?? identity) as (value: TInput) => JsonValue,\n    decodeJson: (widenedConfig.decodeJson ?? identity) as (json: JsonValue) => TInput,\n  } as Codec<Id, TTraits, TWire, TInput>;\n}\n","import {\n  type Contract,\n  type ContractModelBase,\n  coreHash,\n  profileHash,\n} from '@prisma-next/contract/types';\nimport type {\n  CodecDescriptor,\n  CodecMeta,\n  CodecTrait,\n} from '@prisma-next/framework-components/codec';\nimport { APP_SPACE_ID } from '@prisma-next/framework-components/control';\nimport {\n  instantiateExecutionStack,\n  type RuntimeDriverDescriptor,\n} from '@prisma-next/framework-components/execution';\nimport { UNBOUND_NAMESPACE_ID } from '@prisma-next/framework-components/ir';\nimport type { ResultType } from '@prisma-next/framework-components/runtime';\nimport { runtimeError } from '@prisma-next/framework-components/runtime';\nimport { canonicalizeJson } from '@prisma-next/framework-components/utils';\nimport { builtinGeneratorIds } from '@prisma-next/ids';\nimport { generateId } from '@prisma-next/ids/runtime';\nimport {\n  SqlStorage,\n  type SqlStorageInput,\n  type StorageTableInput,\n} from '@prisma-next/sql-contract/types';\nimport type {\n  Adapter,\n  AnyQueryAst,\n  Codec,\n  ContractCodecRegistry,\n  LoweredStatement,\n  SelectAst,\n} from '@prisma-next/sql-relational-core/ast';\nimport { SelectAst as SelectAstCtor, TableSource } from '@prisma-next/sql-relational-core/ast';\nimport type { SqlExecutionPlan, SqlQueryPlan } from '@prisma-next/sql-relational-core/plan';\nimport { applicationDomainOf, collectAsync, drainAsyncIterable } from '@prisma-next/test-utils';\nimport { ifDefined } from '@prisma-next/utils/defined';\nimport type { Client } from 'pg';\nimport { createTestSqlNamespace } from '../../1-core/contract/test/test-support';\nimport { createExecutionContext, createSqlExecutionStack } from '../src/exports';\nimport type {\n  ExecutionContext,\n  SqlRuntimeAdapterDescriptor,\n  SqlRuntimeAdapterInstance,\n  SqlRuntimeDriverInstance,\n  SqlRuntimeExtensionDescriptor,\n  SqlRuntimeTargetDescriptor,\n} from '../src/sql-context';\nimport { type Runtime, type RuntimeOptions, SqlRuntimeBase } from '../src/sql-runtime';\nimport { defineTestCodec } from './test-codec';\n\nfunction createTestMutationDefaultGenerators() {\n  return builtinGeneratorIds.map((id) => ({\n    id,\n    generate: (params?: Record<string, unknown>) => generateId(params ? { id, params } : { id }),\n    stability: 'field' as const,\n  }));\n}\n\nclass TestSqlRuntime extends SqlRuntimeBase {}\n\ntype CreateTestRuntimeOptions<TContract extends Contract<SqlStorage>> = Omit<\n  RuntimeOptions<TContract>,\n  'adapter'\n> & {\n  readonly stackInstance: { readonly adapter: RuntimeOptions<TContract>['adapter'] };\n};\n\n/**\n * Test-only concrete runtime. Unpacks `stackInstance.adapter` and forwards\n * the rest into `TestSqlRuntime`, a trivial concrete leaf of the abstract\n * `SqlRuntimeBase`.\n */\nexport function createTestRuntime<TContract extends Contract<SqlStorage>>(\n  options: CreateTestRuntimeOptions<TContract>,\n): Runtime {\n  const { stackInstance, context, driver, verifyMarker, middleware, mode, log } = options;\n  return new TestSqlRuntime({\n    context,\n    adapter: stackInstance.adapter,\n    driver,\n    ...ifDefined('verifyMarker', verifyMarker),\n    ...ifDefined('middleware', middleware),\n    ...ifDefined('mode', mode),\n    ...ifDefined('log', log),\n  });\n}\n\n/**\n * Executes a plan and collects all results into an array. This helper DRYs up the common pattern of executing plans in tests. The return type is inferred from the plan's type parameter.\n */\nexport async function executePlanAndCollect<\n  P extends SqlExecutionPlan<ResultType<P>> | SqlQueryPlan<ResultType<P>>,\n>(runtime: Runtime, plan: P): Promise<ResultType<P>[]> {\n  type Row = ResultType<P>;\n  return collectAsync<Row>(runtime.execute<Row>(plan));\n}\n\n/**\n * Drains a plan execution, consuming all results without collecting them. Useful for testing side effects without memory overhead.\n */\nexport async function drainPlanExecution(\n  runtime: Runtime,\n  plan: SqlExecutionPlan | SqlQueryPlan<unknown>,\n): Promise<void> {\n  return drainAsyncIterable(runtime.execute(plan));\n}\n\n/**\n * Sets up database schema and data, then writes the contract marker. This helper DRYs up the common pattern of database setup in tests.\n *\n * Callers must supply `bootstrapMarkerTables` (typically\n * `bootstrapPostgresSignMarkerTables` from integration `postgres-bootstrap.ts`)\n * so this package does not depend on the postgres adapter/target packs.\n */\nexport async function setupTestDatabase(\n  client: Client,\n  contract: Contract<SqlStorage>,\n  setupFn: (client: Client) => Promise<void>,\n  bootstrapMarkerTables: (client: Client) => Promise<void>,\n): Promise<void> {\n  await client.query('drop schema if exists prisma_contract cascade');\n  await client.query('create schema if not exists public');\n\n  await setupFn(client);\n\n  await bootstrapMarkerTables(client);\n  await writeTestContractMarker(client, contract);\n}\n\nexport interface SeedMarkerInput {\n  /** Logical space for the marker row; defaults to {@link APP_SPACE_ID}. */\n  readonly space?: string;\n  readonly storageHash: string;\n  readonly profileHash: string;\n  readonly contractJson?: unknown;\n  readonly canonicalVersion?: number;\n  readonly invariants?: readonly string[];\n}\n\n/**\n * Seeds a contract marker row directly via raw SQL. Test-only: the production\n * write path goes through the control adapter SPI (`initMarker`/`updateMarker`),\n * which needs a `ControlDriverInstance`; these fixtures hold a raw `pg.Client`,\n * so they perform a minimal `INSERT` over the columns the runtime reads back.\n */\nexport async function seedTestMarker(client: Client, input: SeedMarkerInput): Promise<void> {\n  await client.query(\n    `insert into prisma_contract.marker\n       (space, core_hash, profile_hash, contract_json, canonical_version, invariants, updated_at)\n     values ($1, $2, $3, $4::jsonb, $5, $6::text[], now())`,\n    [\n      input.space ?? APP_SPACE_ID,\n      input.storageHash,\n      input.profileHash,\n      input.contractJson === undefined ? null : JSON.stringify(input.contractJson),\n      input.canonicalVersion ?? null,\n      input.invariants ?? [],\n    ],\n  );\n}\n\n/**\n * Seeds the app-space marker for a contract. Thin wrapper over\n * {@link seedTestMarker} for the common \"write the marker for this contract\" case.\n */\nexport async function writeTestContractMarker(\n  client: Client,\n  contract: Contract<SqlStorage>,\n): Promise<void> {\n  await seedTestMarker(client, {\n    storageHash: contract.storage.storageHash,\n    profileHash: contract.profileHash,\n    contractJson: contract,\n    canonicalVersion: 1,\n  });\n}\n\n/**\n * Creates a test adapter descriptor from a raw adapter. Wraps the adapter in an SqlRuntimeAdapterDescriptor with static contributions derived from the adapter's codec registry.\n */\n/**\n * Build a {@link ContractCodecRegistry} from a codec array for tests that exercise `encodeParam(s)` / `decodeRow` in isolation. The production runtime builds `ContractCodecRegistry` from contract walk + descriptor list and never goes through this helper; tests use it to wire a hand-built codec set into the surface those functions consume in production.\n */\nexport function buildTestContractCodecs(\n  codecs: ReadonlyArray<Codec<string>>,\n): ContractCodecRegistry {\n  const byId = new Map<string, Codec<string>>();\n  for (const codec of codecs) {\n    byId.set(codec.id, codec);\n  }\n  // Canonical-key cache: production `forCodecRef` memoizes per `(codecId, canonicalize(typeParams))`. Tests resolve by codecId, but key the cache on the canonical pair so callers passing distinct typeParams get distinct (still codec-id-templated) entries — and so this helper cannot silently coalesce them.\n  const byCanonicalKey = new Map<string, Codec<string>>();\n  return {\n    forColumn: () => undefined,\n    forCodecRef: (ref) => {\n      const canonicalKey = canonicalizeJson({\n        codecId: ref.codecId,\n        ...(ref.typeParams !== undefined ? { typeParams: ref.typeParams } : {}),\n      });\n      const cached = byCanonicalKey.get(canonicalKey);\n      if (cached) return cached;\n      const template = byId.get(ref.codecId);\n      if (!template) {\n        throw runtimeError(\n          'RUNTIME.CODEC_DESCRIPTOR_MISSING',\n          `Test ContractCodecRegistry has no codec for codecId '${ref.codecId}'.`,\n          {\n            codecId: ref.codecId,\n            ...(ref.typeParams !== undefined ? { typeParams: ref.typeParams } : {}),\n          },\n        );\n      }\n      byCanonicalKey.set(canonicalKey, template);\n      return template;\n    },\n  };\n}\n\n/**\n * Synthesize `CodecDescriptor`s from a codec array of non-parameterized codec instances. Test-only: the production synthesis bridge was retired under TML-2357. Lets the existing `createTestAdapterDescriptor` pattern keep wrapping a stub `Adapter` (whose `__codecs` slot still exposes the codec set) into the descriptor-list shape that `SqlStaticContributions.codecs:` now expects. The `Codec` instances carry\n * `traits`/`targetTypes`/`meta` via the SQL family extension; the structural narrow reads those fields directly.\n */\nexport function descriptorsFromCodecs(\n  codecs: ReadonlyArray<Codec<string>>,\n): ReadonlyArray<CodecDescriptor> {\n  // Permissive paramsSchema for synthesized test descriptors: accepts any\n  // shape (incl. undefined) and passes it through. Stubs do not encode\n  // parameterization, so marking them `isParameterized: true` with this\n  // schema lets the runtime integrity check tolerate columns that legitimately\n  // carry typeParams (e.g. `sql/char@1` length=36) without re-introducing\n  // the legacy \"non-parameterized + typeParams\" silent skip.\n  // Permissive schema for synthesized test descriptors. `validate()` always\n  // succeeds and discards input, narrowed to `void` to match the\n  // `paramsSchema: StandardSchemaV1<void, void>` slot on the descriptor.\n  // The factory ignores typeParams, so typing the validated output as `void`\n  // is honest about what the stub does with the value.\n  const acceptAnyParamsSchema = {\n    '~standard': {\n      version: 1 as const,\n      vendor: 'sql-runtime/test-utils',\n      validate: (_value: unknown) => ({ value: undefined }),\n    },\n  };\n  const descriptors: CodecDescriptor[] = [];\n  for (const instance of codecs) {\n    const legacy = instance as {\n      readonly traits?: readonly CodecTrait[];\n      readonly targetTypes?: readonly string[];\n      readonly meta?: CodecMeta;\n    };\n    descriptors.push({\n      codecId: instance.id,\n      traits: legacy.traits ?? [],\n      targetTypes: legacy.targetTypes ?? [],\n      paramsSchema: acceptAnyParamsSchema,\n      isParameterized: true,\n      factory: () => () => instance,\n      ...(legacy.meta !== undefined ? { meta: legacy.meta } : {}),\n    });\n  }\n  return descriptors;\n}\n\nexport function createTestAdapterDescriptor(\n  adapter: StubAdapter,\n): SqlRuntimeAdapterDescriptor<'postgres'> {\n  const descriptors = descriptorsFromCodecs(adapter.__codecs);\n  return {\n    kind: 'adapter' as const,\n    rawCodecInferer: { inferCodec: () => 'pg/text' },\n    id: 'test-adapter',\n    version: '0.0.1',\n    familyId: 'sql' as const,\n    targetId: 'postgres' as const,\n    codecs: () => descriptors,\n    mutationDefaultGenerators: createTestMutationDefaultGenerators,\n    create(_stack): SqlRuntimeAdapterInstance<'postgres'> {\n      return Object.assign({ familyId: 'sql' as const, targetId: 'postgres' as const }, adapter);\n    },\n  };\n}\n\n/**\n * Creates a test target descriptor with empty static contributions.\n */\nexport function createTestTargetDescriptor(): SqlRuntimeTargetDescriptor<'postgres'> {\n  return {\n    kind: 'target' as const,\n    id: 'postgres',\n    version: '0.0.1',\n    familyId: 'sql' as const,\n    targetId: 'postgres' as const,\n    codecs: () => [],\n    create() {\n      return { familyId: 'sql' as const, targetId: 'postgres' as const };\n    },\n  };\n}\n\n/**\n * Creates an ExecutionContext for testing. This helper DRYs up the common pattern of context creation in tests.\n *\n * Accepts a raw adapter and optional extension descriptors, wrapping the adapter in a descriptor internally for descriptor-first context creation.\n */\nexport function createTestContext<TContract extends Contract<SqlStorage>>(\n  contract: TContract,\n  adapter: StubAdapter,\n  options?: {\n    extensionPacks?: ReadonlyArray<SqlRuntimeExtensionDescriptor<'postgres'>>;\n  },\n): ExecutionContext<TContract> {\n  return createExecutionContext({\n    contract,\n    stack: {\n      target: createTestTargetDescriptor(),\n      adapter: createTestAdapterDescriptor(adapter),\n      extensionPacks: options?.extensionPacks ?? [],\n    },\n  });\n}\n\nexport function createTestStackInstance(options?: {\n  extensionPacks?: ReadonlyArray<SqlRuntimeExtensionDescriptor<'postgres'>>;\n  driver?: RuntimeDriverDescriptor<\n    'sql',\n    'postgres',\n    unknown,\n    SqlRuntimeDriverInstance<'postgres'>\n  >;\n}) {\n  const stack = createSqlExecutionStack({\n    target: createTestTargetDescriptor(),\n    adapter: createTestAdapterDescriptor(createStubAdapter()),\n    driver: options?.driver,\n    extensionPacks: options?.extensionPacks ?? [],\n  });\n\n  return instantiateExecutionStack(stack);\n}\n\n/**\n * Stub-adapter type augments the public {@link Adapter} surface with a `__codecs` slot that exposes the test stub's runtime codec set to descriptor-shaping helpers (`createTestAdapterDescriptor`). Production adapters do not declare this slot — runtime codecs flow through the descriptor list from `SqlRuntimeAdapterDescriptor.codecs()` — so the augmentation is intentionally test-only.\n */\nexport type StubAdapter = Adapter<SelectAst, Contract<SqlStorage>, LoweredStatement> & {\n  readonly __codecs: ReadonlyArray<Codec<string>>;\n};\n\n/**\n * Creates a stub adapter for testing. This helper DRYs up the common pattern of adapter creation in tests.\n *\n * The stub adapter includes simple codecs for common test types (pg/int4@1, pg/text@1, pg/timestamptz@1) to enable type inference in tests without requiring the postgres adapter package.\n */\nexport function createStubAdapter(): StubAdapter {\n  // Stub codecs for codec IDs that test contracts may reference. The set must\n  // be complete enough to satisfy `assertColumnCodecIntegrity` against any\n  // emitted test contract; the encode/decode bodies are passthrough since\n  // the stub adapter never executes against a real driver.\n  // The encode/decode bodies pass through; widen TInput to a JSON-safe type\n  // so `defineTestCodec` does not require explicit JSON round-trip helpers.\n  const passthroughCodec = (typeId: string, targetType: string): Codec<string> =>\n    defineTestCodec({\n      typeId,\n      targetTypes: [targetType],\n      encode: (value: string | number | boolean | null) => value,\n      decode: (wire: string | number | boolean | null) => wire,\n    });\n  const codecs: ReadonlyArray<Codec<string>> = [\n    passthroughCodec('pg/bit@1', 'bit'),\n    passthroughCodec('pg/bool@1', 'bool'),\n    passthroughCodec('pg/bytea@1', 'bytea'),\n    passthroughCodec('pg/float4@1', 'float4'),\n    passthroughCodec('pg/float8@1', 'float8'),\n    passthroughCodec('pg/int2@1', 'int2'),\n    defineTestCodec({\n      typeId: 'pg/int4@1',\n      targetTypes: ['int4'],\n      encode: (value: number) => value,\n      decode: (wire: number) => wire,\n    }),\n    passthroughCodec('pg/int8@1', 'int8'),\n    passthroughCodec('pg/interval@1', 'interval'),\n    passthroughCodec('pg/json@1', 'json'),\n    passthroughCodec('pg/jsonb@1', 'jsonb'),\n    passthroughCodec('pg/numeric@1', 'numeric'),\n    defineTestCodec({\n      typeId: 'pg/text@1',\n      targetTypes: ['text'],\n      encode: (value: string) => value,\n      decode: (wire: string) => wire,\n    }),\n    passthroughCodec('pg/time@1', 'time'),\n    defineTestCodec({\n      typeId: 'pg/timestamp@1',\n      targetTypes: ['timestamp'],\n      encode: (value: Date) => value,\n      decode: (wire: Date) => wire,\n      encodeJson: (value: Date) => value.toISOString(),\n      decodeJson: (json) => {\n        if (typeof json !== 'string') throw new Error('expected ISO date string');\n        return new Date(json);\n      },\n    }),\n    defineTestCodec({\n      typeId: 'pg/timestamptz@1',\n      targetTypes: ['timestamptz'],\n      encode: (value: Date) => value,\n      decode: (wire: Date) => wire,\n      // Date is not assignable to JsonValue, so the JSON round-trip pair must be supplied explicitly.\n      encodeJson: (value: Date) => value.toISOString(),\n      decodeJson: (json) => {\n        if (typeof json !== 'string') throw new Error('expected ISO date string');\n        return new Date(json);\n      },\n    }),\n    passthroughCodec('pg/timetz@1', 'timetz'),\n    passthroughCodec('pg/varbit@1', 'varbit'),\n    passthroughCodec('pg/uuid@1', 'uuid'),\n    passthroughCodec('sql/char@1', 'char'),\n    passthroughCodec('sql/varchar@1', 'varchar'),\n  ];\n\n  return {\n    __codecs: codecs,\n    profile: {\n      id: 'stub-profile',\n      target: 'postgres',\n      capabilities: {},\n      readMarker: async () => ({ kind: 'absent' as const }),\n    },\n    lower(ast: SelectAst, _ctx: { contract: Contract<SqlStorage>; params?: readonly unknown[] }) {\n      const sqlText = JSON.stringify(ast);\n      const refs = ast.collectParamRefs();\n      const params = refs.map((ref) =>\n        ref.kind === 'prepared-param-ref'\n          ? ({ kind: 'bind' as const, name: ref.name } as const)\n          : ({ kind: 'literal' as const, value: ref.value } as const),\n      );\n      return Object.freeze({ sql: sqlText, params });\n    },\n  };\n}\n\nexport function unboundNamespaceWithTables(\n  tables: Record<string, StorageTableInput>,\n): ReturnType<typeof createTestSqlNamespace> {\n  return createTestSqlNamespace({ id: UNBOUND_NAMESPACE_ID, entries: { table: tables } });\n}\n\nexport function emptySqlTestDomain() {\n  return applicationDomainOf({ models: {} });\n}\n\nexport function createTestContract(\n  contract: Partial<Omit<Contract<SqlStorage>, 'profileHash' | 'storage' | 'domain'>> & {\n    storageHash?: string;\n    profileHash?: string;\n    models?: Record<string, ContractModelBase>;\n    domain?: Contract<SqlStorage>['domain'];\n    storage?: Partial<Omit<SqlStorageInput, 'storageHash'>>;\n  },\n): Contract<SqlStorage> {\n  const { execution, ...rest } = contract;\n  const storageHashValue = coreHash(rest['storageHash'] ?? 'sha256:testcore');\n\n  return {\n    target: rest['target'] ?? 'postgres',\n    targetFamily: rest['targetFamily'] ?? 'sql',\n    storage: rest['storage']\n      ? new SqlStorage({\n          ...rest['storage'],\n          storageHash: storageHashValue,\n          namespaces: rest['storage'].namespaces ?? {\n            __unbound__: createTestSqlNamespace({ id: '__unbound__', entries: { table: {} } }),\n          },\n        })\n      : new SqlStorage({\n          storageHash: storageHashValue,\n          namespaces: {\n            __unbound__: createTestSqlNamespace({ id: '__unbound__', entries: { table: {} } }),\n          },\n        }),\n    domain: rest['domain'] ?? applicationDomainOf({ models: rest['models'] ?? {} }),\n    roots: rest['roots'] ?? {},\n    capabilities: rest['capabilities'] ?? {},\n    extensionPacks: rest['extensionPacks'] ?? {},\n    meta: rest['meta'] ?? {},\n    ...(execution ? { execution } : {}),\n    profileHash: profileHash(rest['profileHash'] ?? 'sha256:testprofile'),\n  };\n}\n\nexport function stubAst(): AnyQueryAst {\n  return SelectAstCtor.from(TableSource.named('stub'));\n}\n\n// Re-export generic utilities from test-utils\nexport {\n  collectAsync,\n  createDevDatabase,\n  type DevDatabase,\n  teardownTestDatabase,\n  withClient,\n} from '@prisma-next/test-utils';\n\n// Re-export decode helpers so cross-package tests can exercise the row-decode\n// path (e.g. RUNTIME.DECODE_FAILED for a malformed many-element) without going\n// through the full query round-trip.\nexport { buildDecodeContext, decodeRow } from '../src/codecs/decoding';\n"],"mappings":";;;;;;;;;;;;;;;;AAYA,MAAM,oBAAoB,KAAK,WAAW;AAC1C,MAAM,qBAAqB,KAAK,YAAY;AAC5C,MAAM,sBAAsB,KAAK,mDAAmD;AAEpF,MAAa,6BAA6B,KAAK,QAA8B,CAAC,CAAC,KAAK;CAClF,MAAM;CACN,OAAO;AACT,CAAC;AAED,MAAa,8BAA8B,KAAK,QAA+B,CAAC,CAAC,KAAK;CACpF,MAAM;CACN,YAAY;AACd,CAAC;AAED,MAAa,sBAAsB,2BAA2B,GAAG,2BAA2B;AAE5F,MAAM,2BAA2B,KAAK;CACpC,OAAO;CACP,aAAa;CACb,YAAY;CACZ,YAAY;CACZ,YAAY;AACd,CAAC;AAED,MAAM,sBAAsB,KAAK;CAC/B,KAAK;CACL,YAAY;CACZ,SAAS;CACT,UAAU;CACV,SAAS;CACT,eAAe;CACf,YAAY;CACZ,YAAY;CACZ,YAAY;CACZ,aAAa;AACf,CAAC,CAAC,CAAC,QAAQ,KAAK,QAAQ;CACtB,IAAI,IAAI,eAAe,KAAA,KAAa,IAAI,YAAY,KAAA,GAClD,OAAO,IAAI,OAAO,sDAAsD;CAE1E,OAAO;AACT,CAAC;;;;;;AAOD,MAAa,wBAAwB,KAAK;CACxC,MAAM;CACN,QAAQ,KAAK,wEAAwE,CAAC,CACnF,MAAM,CAAC,CACP,SAAS;AACd,CAAC;AAED,MAAM,mBAAmB,KAAK,QAAyB,CAAC,CAAC,KAAK;CAC5D,SAAS,KAAK,OAAO,MAAM,CAAC,CAAC,SAAS;CACtC,SAAS;AACX,CAAC;AAED,MAAM,yBAAyB,KAAK,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