import { AlgebraicType } from '../lib/algebraic_type.ts'; import { FunctionVisibility, type Lifecycle } from '../lib/autogen/types.ts'; import type { ParamsObj, Reducer } from '../lib/reducers.ts'; import { type UntypedSchemaDef } from '../lib/schema.ts'; import { deepEqual } from '../lib/util.ts'; import { t } from '../lib/type_builders.ts'; import type { OutboxMetadata, ScheduleTableForParams, UntypedTableSchema, } from '../lib/table_schema.ts'; import { RowBuilder, type RowObj } from '../lib/type_builders.ts'; import { toPascalCase } from '../lib/util.ts'; import { exportContext, registerExport, type ModuleExport, type SchemaInner, } from './schema.ts'; export interface ReducerExport< S extends UntypedSchemaDef, Params extends ParamsObj, > extends Reducer, ModuleExport {} export interface ReducerOpts { name: string; onSchedule?: ScheduleTableForParams; onResult?: UntypedTableSchema & { readonly outbox: OutboxMetadata }; } export type ReducerOptsWithOptionalName = Omit, 'name'> & { name?: string }; export function makeReducerExport< S extends UntypedSchemaDef, Params extends ParamsObj, >( ctx: SchemaInner, opts: ReducerOptsWithOptionalName | undefined, params: RowObj | RowBuilder, fn: Reducer, lifecycle?: Lifecycle ): ReducerExport { const reducerExport: ReducerExport = (...args) => fn(...args); reducerExport[exportContext] = ctx; reducerExport[registerExport] = (ctx, exportName) => { registerReducer(ctx, exportName, params, fn, opts, lifecycle); ctx.functionExports.set( reducerExport as ReducerExport, exportName ); if (opts?.onResult !== undefined) { ctx.pendingOutboxCallbacks.push({ table: opts.onResult, functionName: exportName, }); } if (opts?.onSchedule !== undefined) { ctx.pendingSchedules.push({ table: opts.onSchedule, functionName: exportName, }); } }; return reducerExport; } /** * internal: pushReducer() helper used by reducer() and lifecycle wrappers * * @param name - The name of the reducer. * @param params - The parameters for the reducer. * @param fn - The reducer function. * @param lifecycle - Optional lifecycle hooks for the reducer. */ export function registerReducer( ctx: SchemaInner, exportName: string, params: RowObj | RowBuilder, fn: Reducer, opts?: ReducerOptsWithOptionalName, lifecycle?: Lifecycle ): void { ctx.defineFunction(exportName); if (!(params instanceof RowBuilder)) { params = new RowBuilder(params); } if (opts?.onResult) { if (opts.onSchedule) { throw new TypeError('A reducer cannot use both onSchedule and onResult'); } if (lifecycle) { throw new TypeError('A lifecycle reducer cannot use onResult'); } const target = opts.onResult; const fields = Object.values(params.row); if ( fields.length !== 2 || fields[0].typeBuilder !== target.rowType || !deepEqual( fields[1].typeBuilder.algebraicType, t.result(t.unit(), t.string()).algebraicType ) ) { throw new TypeError( 'onResult requires the outbox row followed by Result' ); } } if (params.typeName === undefined) { params.typeName = toPascalCase(exportName); } const ref = ctx.registerTypesRecursively(params); const paramsType = ctx.resolveType(ref).value; const isLifecycle = lifecycle != null; ctx.moduleDef.reducers.push({ sourceName: exportName, params: paramsType, //ModuleDef validation code is responsible to mark private reducers visibility: FunctionVisibility.ClientCallable, //Hardcoded for now - reducers do not return values yet okReturnType: AlgebraicType.Product({ elements: [] }), errReturnType: AlgebraicType.String, }); if (opts?.name != null) { ctx.moduleDef.explicitNames.entries.push({ tag: 'Function', value: { sourceName: exportName, canonicalName: opts.name, }, }); } if (isLifecycle) { ctx.moduleDef.lifeCycleReducers.push({ lifecycleSpec: lifecycle, functionName: exportName, }); } // If the function isn't named (e.g. `function foobar() {}`), give it the same // name as the reducer so that it's clear what it is in in backtraces. if (!fn.name) { Object.defineProperty(fn, 'name', { value: exportName, writable: false }); } ctx.reducers.push(fn); } export type Reducers = Reducer[];