|
| 1 | +import { AlgebraicType, ProductType } from '../lib/algebraic_type'; |
| 2 | +import type { ConnectionId } from '../lib/connection_id'; |
| 3 | +import type { Identity } from '../lib/identity'; |
| 4 | +import type { Timestamp } from '../lib/timestamp'; |
| 5 | +import type { ParamsObj } from './reducers'; |
| 6 | +import { |
| 7 | + MODULE_DEF, |
| 8 | + registerTypesRecursively, |
| 9 | + type UntypedSchemaDef, |
| 10 | +} from './schema'; |
| 11 | +import type { Infer, InferTypeOfRow, TypeBuilder } from './type_builders'; |
| 12 | +import { bsatnBaseSize } from './util'; |
| 13 | + |
| 14 | +export type ProcedureFn< |
| 15 | + S extends UntypedSchemaDef, |
| 16 | + Params extends ParamsObj, |
| 17 | + Ret extends TypeBuilder<any, any>, |
| 18 | +> = (ctx: ProcedureCtx<S>, args: InferTypeOfRow<Params>) => Infer<Ret>; |
| 19 | + |
| 20 | +// eslint-disable-next-line @typescript-eslint/no-unused-vars |
| 21 | +export interface ProcedureCtx<S extends UntypedSchemaDef> { |
| 22 | + readonly sender: Identity; |
| 23 | + readonly identity: Identity; |
| 24 | + readonly timestamp: Timestamp; |
| 25 | + readonly connectionId: ConnectionId | null; |
| 26 | +} |
| 27 | + |
| 28 | +export function procedure< |
| 29 | + S extends UntypedSchemaDef, |
| 30 | + Params extends ParamsObj, |
| 31 | + Ret extends TypeBuilder<any, any>, |
| 32 | +>(name: string, params: Params, ret: Ret, fn: ProcedureFn<S, Params, Ret>) { |
| 33 | + const paramsType: ProductType = { |
| 34 | + elements: Object.entries(params).map(([n, c]) => ({ |
| 35 | + name: n, |
| 36 | + algebraicType: |
| 37 | + 'typeBuilder' in c ? c.typeBuilder.algebraicType : c.algebraicType, |
| 38 | + })), |
| 39 | + }; |
| 40 | + const returnType = registerTypesRecursively(ret).algebraicType; |
| 41 | + |
| 42 | + MODULE_DEF.miscExports.push({ |
| 43 | + tag: 'Procedure', |
| 44 | + value: { |
| 45 | + name, |
| 46 | + params: paramsType, |
| 47 | + returnType, |
| 48 | + }, |
| 49 | + }); |
| 50 | + |
| 51 | + PROCEDURES.push({ |
| 52 | + fn, |
| 53 | + paramsType, |
| 54 | + returnType, |
| 55 | + returnTypeBaseSize: bsatnBaseSize(MODULE_DEF.typespace, returnType), |
| 56 | + }); |
| 57 | +} |
| 58 | + |
| 59 | +export const PROCEDURES: Array<{ |
| 60 | + fn: ProcedureFn<any, any, any>; |
| 61 | + paramsType: ProductType; |
| 62 | + returnType: AlgebraicType; |
| 63 | + returnTypeBaseSize: number; |
| 64 | +}> = []; |
0 commit comments