import { type Contract, coreHash, executionHash, profileHash } from '@internal/contract/types'; import { SqlStorage } from '@internal/sql-contract/types'; import type { SqlOperationDescriptors } from '@internal/sql-operations'; import type { Codec } from '@internal/sql-relational-core/ast'; import type { CollectionMethodContribution } from '@internal/sql-relational-core/collection-methods'; import { applicationDomainOf } from '@repo/test-utils'; import { describe, expect, it } from 'vitest'; import { createTestSqlNamespace } from '../../1-core/contract/test/test-support'; import { createExecutionContext, type SqlExecutionStack, type SqlRuntimeAdapterDescriptor, type SqlRuntimeExtensionDescriptor, type SqlRuntimeTargetDescriptor, } from '../src/sql-context'; import { defineTestCodec } from './test-codec'; import { createStubAdapter, createTestAdapterDescriptor, createTestTargetDescriptor, descriptorsFromCodecs, } from './utils'; const testContract: Contract = { targetFamily: 'sql', target: 'postgres', profileHash: profileHash('test'), domain: applicationDomainOf({ models: {} }), roots: {}, storage: new SqlStorage({ storageHash: coreHash('test'), namespaces: { __unbound__: createTestSqlNamespace({ id: '__unbound__', entries: { table: {} } }), }, }), extensions: {}, capabilities: {}, meta: {}, }; function createTestExtensionDescriptor(options?: { hasCodecs?: boolean; hasOperations?: boolean; }): SqlRuntimeExtensionDescriptor<'postgres'> { const { hasCodecs = false, hasOperations = false } = options ?? {}; const codecRegistry: ReadonlyArray> = hasCodecs ? [ defineTestCodec({ typeId: 'test/ext@1', toWire: (v: string) => v, fromWire: (w: string) => w, }), ] : []; const operations: SqlOperationDescriptors = hasOperations ? { testOp: { self: { codecId: 'test/ext@1' }, impl: () => undefined as never, }, } : {}; return { kind: 'extension' as const, id: 'test-extension', version: '0.0.1', familyId: 'sql' as const, targetId: 'postgres' as const, codecs: () => descriptorsFromCodecs(codecRegistry), queryOperations: () => operations, create() { return { familyId: 'sql' as const, targetId: 'postgres' as const, }; }, }; } function createStack(options?: { extensions?: ReadonlyArray>; }): SqlExecutionStack<'postgres'> { return { target: createTestTargetDescriptor(), adapter: createTestAdapterDescriptor(createStubAdapter()), extensions: options?.extensions ?? [], }; } describe('createExecutionContext', () => { it('creates context with adapter codecs from descriptor', () => { const context = createExecutionContext({ contract: testContract, stack: createStack(), }); expect(context.contract).toEqual(testContract); expect(context.codecDescriptors.descriptorFor('pg/int4@1')).toBeDefined(); expect(context.queryOperations).toBeDefined(); }); it('creates context with empty extension packs', () => { const context = createExecutionContext({ contract: testContract, stack: createStack({ extensions: [] }), }); expect(context.codecDescriptors.descriptorFor('pg/int4@1')).toBeDefined(); expect(context.codecDescriptors.descriptorFor('test/ext@1')).toBeUndefined(); }); it('registers extension codecs from descriptors', () => { const context = createExecutionContext({ contract: testContract, stack: createStack({ extensions: [createTestExtensionDescriptor({ hasCodecs: true })], }), }); expect(context.codecDescriptors.descriptorFor('pg/int4@1')).toBeDefined(); expect(context.codecDescriptors.descriptorFor('test/ext@1')).toBeDefined(); }); it('registers extension operations from descriptors', () => { const context = createExecutionContext({ contract: testContract, stack: createStack({ extensions: [createTestExtensionDescriptor({ hasOperations: true })], }), }); const entries = context.queryOperations.entries(); expect(entries['testOp']).toBeDefined(); }); it('collects the collection methods the target and extensions contribute, in stack order', () => { const method = (id: string): CollectionMethodContribution => ({ id, methodsFor: () => ({}), }); const extension = (id: string): SqlRuntimeExtensionDescriptor<'postgres'> => ({ ...createTestExtensionDescriptor({ hasCodecs: false, hasOperations: false }), id, collectionMethods: () => [method(`${id}/method`)], }); const context = createExecutionContext({ contract: testContract, stack: { ...createStack({ extensions: [extension('first'), extension('second')] }), target: { ...createTestTargetDescriptor(), collectionMethods: () => [method('target')] }, }, }); expect(context.collectionMethods?.map(({ id }) => id)).toEqual([ 'target', 'first/method', 'second/method', ]); }); it('handles extension with no contributions', () => { const context = createExecutionContext({ contract: testContract, stack: createStack({ extensions: [createTestExtensionDescriptor({ hasCodecs: false, hasOperations: false })], }), }); expect(context.codecDescriptors.descriptorFor('pg/int4@1')).toBeDefined(); expect(context.codecDescriptors.descriptorFor('test/ext@1')).toBeUndefined(); }); }); describe('comprehensive descriptor-based derivation', () => { it('includes all expected codec IDs and operations from target, adapter, and extensions', () => { const targetCodecRegistry: ReadonlyArray> = [ defineTestCodec({ typeId: 'target/special@1', toWire: (v: string) => v, fromWire: (w: string) => w, }), ]; const targetOps: SqlOperationDescriptors = { targetOp: { self: { codecId: 'target/special@1' }, impl: () => undefined as never, }, }; const target: SqlRuntimeTargetDescriptor<'postgres'> = { kind: 'target' as const, id: 'postgres', version: '0.0.1', familyId: 'sql' as const, targetId: 'postgres' as const, codecs: () => descriptorsFromCodecs(targetCodecRegistry), queryOperations: () => targetOps, create() { return { familyId: 'sql' as const, targetId: 'postgres' as const }; }, }; const stack: SqlExecutionStack<'postgres'> = { target, adapter: createTestAdapterDescriptor(createStubAdapter()), extensions: [createTestExtensionDescriptor({ hasCodecs: true, hasOperations: true })], }; const context = createExecutionContext({ contract: testContract, stack }); expect(context.codecDescriptors.descriptorFor('target/special@1')).toBeDefined(); expect(context.codecDescriptors.descriptorFor('pg/int4@1')).toBeDefined(); expect(context.codecDescriptors.descriptorFor('test/ext@1')).toBeDefined(); const entries = context.queryOperations.entries(); expect(entries['targetOp']).toBeDefined(); expect(entries['testOp']).toBeDefined(); }); }); describe('the execution context', () => { it('carries no type helpers', () => { const context = createExecutionContext({ contract: testContract, stack: createStack(), }); expect(Object.hasOwn(context, 'types')).toBe(false); }); }); describe('contract/stack validation errors', () => { it('throws RUNTIME.CONTRACT_FAMILY_MISMATCH when contract targetFamily differs from stack', () => { const mismatchedFamilyContract = { ...testContract, targetFamily: 'document', } as unknown as Contract; expect(() => createExecutionContext({ contract: mismatchedFamilyContract, stack: createStack() }), ).toThrow( expect.objectContaining({ code: 'RUNTIME.CONTRACT_FAMILY_MISMATCH', category: 'RUNTIME', severity: 'error', details: { actual: 'document', expected: 'sql', }, }), ); }); it('throws RUNTIME.CONTRACT_TARGET_MISMATCH when contract target differs from stack', () => { const mismatchedContract: Contract = { ...testContract, target: 'mysql', }; expect(() => createExecutionContext({ contract: mismatchedContract, stack: createStack() }), ).toThrow( expect.objectContaining({ code: 'RUNTIME.CONTRACT_TARGET_MISMATCH', category: 'RUNTIME', severity: 'error', details: { actual: 'mysql', expected: 'postgres', }, }), ); }); it('throws RUNTIME.MISSING_EXTENSION_PACK when contract requires extension not in stack', () => { const contractWithExtension: Contract = { ...testContract, extensions: { 'required-extension': { id: 'required-extension', version: '1.0.0', capabilities: {} }, }, }; expect(() => createExecutionContext({ contract: contractWithExtension, stack: createStack() }), ).toThrow( expect.objectContaining({ code: 'RUNTIME.MISSING_EXTENSION_PACK', category: 'RUNTIME', severity: 'error', details: { packIds: ['required-extension'], }, }), ); }); it('lists all missing extension packs in a single error', () => { const contractWithExtensions: Contract = { ...testContract, extensions: { 'ext-a': { id: 'ext-a', version: '1.0.0', capabilities: {} }, 'ext-b': { id: 'ext-b', version: '1.0.0', capabilities: {} }, }, }; expect(() => createExecutionContext({ contract: contractWithExtensions, stack: createStack() }), ).toThrow( expect.objectContaining({ code: 'RUNTIME.MISSING_EXTENSION_PACK', details: { packIds: expect.arrayContaining(['ext-a', 'ext-b']), }, }), ); }); it('throws RUNTIME.MUTATION_DEFAULT_GENERATOR_MISSING when contract references a generator the stack does not provide', () => { const contractWithUnknownGenerator: Contract = { ...testContract, storage: new SqlStorage({ storageHash: coreHash('test'), namespaces: { __unbound__: createTestSqlNamespace({ id: '__unbound__', entries: { table: { user: { columns: { id: { dataType: 'pg/text', codecId: 'pg/text@1', nullable: false }, }, uniques: [], indexes: [], foreignKeys: [], }, }, }, }), }, }), execution: { executionHash: executionHash('test'), mutations: { defaults: [ { ref: { namespace: '__unbound__', entry: 'user', field: 'id' }, onCreate: { kind: 'generator', id: 'unregistered' }, }, ], }, }, }; expect(() => createExecutionContext({ contract: contractWithUnknownGenerator, stack: createStack() }), ).toThrow( expect.objectContaining({ code: 'RUNTIME.MUTATION_DEFAULT_GENERATOR_MISSING', category: 'RUNTIME', severity: 'error', message: expect.stringContaining( "Contract requires mutation default generator 'unregistered' for user.id, but no runtime component in the execution stack provides it.", ), details: expect.objectContaining({ ids: ['unregistered'], fields: ['user.id'], }), }), ); }); it('checks column codecs before mutation default generators', () => { const contractWithBothProblems: Contract = { ...testContract, storage: new SqlStorage({ storageHash: coreHash('test'), namespaces: { __unbound__: createTestSqlNamespace({ id: '__unbound__', entries: { table: { user: { columns: { id: { dataType: 'test/unregistered', codecId: 'test/unregistered@1', nullable: false, }, }, uniques: [], indexes: [], foreignKeys: [], }, }, }, }), }, }), execution: { executionHash: executionHash('test'), mutations: { defaults: [ { ref: { namespace: '__unbound__', entry: 'user', field: 'id' }, onCreate: { kind: 'generator', id: 'unregistered' }, }, ], }, }, }; expect(() => createExecutionContext({ contract: contractWithBothProblems, stack: createStack() }), ).toThrow(expect.objectContaining({ code: 'RUNTIME.CODEC_DESCRIPTOR_MISSING' })); }); }); describe('context.applyMutationDefaults', () => { const contractWithDefaults: Contract = { ...testContract, storage: new SqlStorage({ storageHash: coreHash('test'), namespaces: { __unbound__: createTestSqlNamespace({ id: '__unbound__', entries: { table: { user: { columns: { id: { dataType: 'pg/text', codecId: 'pg/text@1', nullable: false }, slug: { dataType: 'pg/text', codecId: 'pg/text@1', nullable: false }, email: { dataType: 'pg/text', codecId: 'pg/text@1', nullable: false }, }, uniques: [], indexes: [], foreignKeys: [], }, }, }, }), }, }), execution: { executionHash: executionHash('test'), mutations: { defaults: [ { ref: { namespace: '__unbound__', entry: 'user', field: 'id' }, onCreate: { kind: 'generator', id: 'nanoid', params: { size: 8 } }, }, { ref: { namespace: '__unbound__', entry: 'user', field: 'slug' }, onUpdate: { kind: 'generator', id: 'nanoid', params: { size: 6 } }, }, ], }, }, }; it('applies create defaults with the generators the stack contributes', () => { const context = createExecutionContext({ contract: contractWithDefaults, stack: createStack(), }); const applied = context.applyMutationDefaults({ op: 'create', entry: 'user', namespace: '__unbound__', values: {}, }); expect(applied).toEqual([ { field: 'id', value: expect.any(String), }, ]); expect((applied[0]!.value as string).length).toBe(8); }); }); describe("the contract's capabilities", () => { function targetWithCapabilities( capabilities: Record>, ): SqlRuntimeTargetDescriptor<'postgres'> { return { ...createTestTargetDescriptor(), capabilities }; } function adapterWithCapabilities( capabilities: Record>, ): SqlRuntimeAdapterDescriptor<'postgres'> { return { ...createTestAdapterDescriptor(createStubAdapter()), capabilities }; } function extensionWithCapabilities( capabilities: Record>, ): SqlRuntimeExtensionDescriptor<'postgres'> { return { ...createTestExtensionDescriptor(), capabilities }; } it('are the list the contract states: the target, adapter and extensions add nothing', () => { const contract: Contract = { ...testContract, capabilities: { sql: { lateral: true } }, }; const context = createExecutionContext({ contract, stack: { target: targetWithCapabilities({ sql: { returning: true } }), adapter: adapterWithCapabilities({ sql: { defaultInInsert: true, lateral: false } }), extensions: [extensionWithCapabilities({ postgres: { distinctOn: true } })], }, }); expect(context.contract.capabilities).toEqual({ sql: { lateral: true } }); }); it('stay empty for a contract that lists none, whatever the stack declares', () => { const context = createExecutionContext({ contract: testContract, stack: { target: createTestTargetDescriptor(), adapter: adapterWithCapabilities({ sql: { returning: true } }), extensions: [], }, }); expect(context.contract.capabilities).toEqual({}); }); });