import type { EntityMutationTriggerConfiguration } from '../EntityMutationTriggerConfiguration.ts'; import type { ReadonlyEntity } from '../ReadonlyEntity.ts'; import type { ViewerContext } from '../ViewerContext.ts'; function nonNullish(value: TValue | null | undefined): value is NonNullable { return value !== null && value !== undefined; } export function mergeEntityMutationTriggerConfigurations< TFields extends Record, TIDField extends keyof NonNullable>, TViewerContext extends ViewerContext, TEntity extends ReadonlyEntity, TSelectedFields extends keyof TFields, >( ...mutationTriggerConfigurations: EntityMutationTriggerConfiguration< TFields, TIDField, TViewerContext, TEntity, TSelectedFields >[] ): EntityMutationTriggerConfiguration { const merged = { beforeCreate: mutationTriggerConfigurations.flatMap((c) => c.beforeCreate).filter(nonNullish), afterCreate: mutationTriggerConfigurations.flatMap((c) => c.afterCreate).filter(nonNullish), beforeUpdate: mutationTriggerConfigurations.flatMap((c) => c.beforeUpdate).filter(nonNullish), afterUpdate: mutationTriggerConfigurations.flatMap((c) => c.afterUpdate).filter(nonNullish), beforeDelete: mutationTriggerConfigurations.flatMap((c) => c.beforeDelete).filter(nonNullish), afterDelete: mutationTriggerConfigurations.flatMap((c) => c.afterDelete).filter(nonNullish), beforeAll: mutationTriggerConfigurations.flatMap((c) => c.beforeAll).filter(nonNullish), afterAll: mutationTriggerConfigurations.flatMap((c) => c.afterAll).filter(nonNullish), afterCommit: mutationTriggerConfigurations.flatMap((c) => c.afterCommit).filter(nonNullish), }; /** Remove any trigger that is an empty array */ for (const key of Object.keys(merged) as (keyof typeof merged)[]) { if (merged[key].length === 0) { delete merged[key]; } } return merged; }