All files / libs/amalia-lang/formula/evaluate/shared/src/functions AmaliaFunction.ts

100% Statements 238/238
100% Branches 9/9
100% Functions 6/6
100% Lines 238/238

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 2391x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 25x 25x 1x 1x 2x 118x 118x 2x 2x 1x 1x 1x 1x 1x 1x 734x 734x 734x 734x 734x 734x 734x 734x 734x 734x 734x 734x 734x 734x 734x 734x 734x 734x 734x 734x 734x 734x 734x 734x 734x 734x 734x 734x 734x 734x 734x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 662x 662x 662x 662x 662x 662x 662x 662x 662x 662x 662x 662x 662x 662x 662x 662x 662x 662x 662x 662x 662x 662x 662x 662x 662x 662x 662x 662x 662x 1x 1x 1x 1x 1x 1x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 1x 1x 1x 1x 1x 1x  
import { uniqBy } from 'lodash-es';
import { type MathNode } from 'mathjs';
 
import {
  type AmaliaFormula,
  type AmaliaFunctionCategory,
  type AmaliaFunctionKeys,
} from '@amalia/amalia-lang/formula/types';
import { type TokenType } from '@amalia/amalia-lang/tokens/types';
import { type FormatsEnum } from '@amalia/data-capture/fields/types';
import { type ComputedFunctionArgs, type ComputeEngineResult } from '@amalia/payout-calculation/types';
 
import { type ParserScope } from '../CalculationParser';
 
export type AmaliaFunctionArgument = {
  name: string;
  description: string;
  defaultValue?: ComputeEngineResult;
  /**
   * Token types that are valid for this argument. If not provided, all token types are valid.
   */
  validTokenTypes?: TokenType[];
 
  /**
   * Token values per token types that are valid for this argument. Useful if you want to restrict the values of a token type.
   * Example: In sum function, second argument can be a function but only `IF` or `DEFAULT` functions are valid.
   */
  validTokenValues?: Partial<Record<TokenType, string[]>>;
 
  /**
   * Formats that are valid for this argument. If not provided, all formats are valid.
   */
  validFormats?: FormatsEnum[];
};
 
type MathjsRawArgsFunctionArguments = [MathNode[], unknown, ParserScope];
 
export interface AmaliaFunctionExec<
  TArgs extends ComputeEngineResult[] | MathjsRawArgsFunctionArguments =
    | ComputeEngineResult[]
    | MathjsRawArgsFunctionArguments,
  TReturnType extends ComputeEngineResult = ComputeEngineResult,
> {
  (...args: TArgs): TReturnType;
  readonly rawArgs?: boolean;
}
 
export interface AmaliaFunctionExecDefault<
  TArgs extends ComputeEngineResult[] = ComputeEngineResult[],
  TReturnType extends ComputeEngineResult = ComputeEngineResult,
> extends AmaliaFunctionExec<TArgs, TReturnType> {
  readonly rawArgs?: false;
}
 
export interface AmaliaFunctionExecRawArgs<
  TReturnType extends ComputeEngineResult = ComputeEngineResult,
> extends AmaliaFunctionExec<MathjsRawArgsFunctionArguments, TReturnType> {
  readonly rawArgs: true;
}
 
export type AmaliaFunctionMetadata<
  TArgs extends ComputeEngineResult[] | MathjsRawArgsFunctionArguments =
    | ComputeEngineResult[]
    | MathjsRawArgsFunctionArguments,
  TReturnType extends ComputeEngineResult = ComputeEngineResult,
  TExecFn extends AmaliaFunctionExec<TArgs, TReturnType> = AmaliaFunctionExec<TArgs, TReturnType>,
> = {
  name: AmaliaFunctionKeys;
  category: AmaliaFunctionCategory;
  exec: TExecFn;
  execMock?: TExecFn;
  nbParamsRequired?: number;
  description?: string[] | string;
  examples: { desc?: string; formula: AmaliaFormula; result?: TReturnType }[];
  params: AmaliaFunctionArgument[];
  hasInfiniteParams?: boolean;
  hiddenFromLibrary?: boolean;
  generateComputedFunctionResult?: (args: MathNode[]) => ComputedFunctionArgs;
  parametersToEscapeOnParse?: number[];
};
 
export abstract class AmaliaFunction<
  TArgs extends ComputeEngineResult[] | MathjsRawArgsFunctionArguments =
    | ComputeEngineResult[]
    | MathjsRawArgsFunctionArguments,
  TReturnType extends ComputeEngineResult = ComputeEngineResult,
  TExecFn extends AmaliaFunctionExec<TArgs, TReturnType> = AmaliaFunctionExec<TArgs, TReturnType>,
> {
  // @ts-expect-error -- Will be filled during initialization.
  private static allFunctions: Record<AmaliaFunctionKeys, AmaliaFunction> = {};
 
  public static getAllFunctions(): Readonly<Record<AmaliaFunctionKeys, AmaliaFunction>> {
    return AmaliaFunction.allFunctions;
  }
 
  public static getFunctionsEnum() {
    return Object.keys(AmaliaFunction.allFunctions).reduce<Record<string, string>>((acc, key) => {
      acc[key] = key;
      return acc;
    }, {});
  }
 
  public static getAllFunctionsArray(): AmaliaFunction[] {
    return uniqBy(Object.values(AmaliaFunction.allFunctions), 'name');
  }
 
  public constructor({
    name,
    category,
    exec,
    params,
    execMock = undefined,
    nbParamsRequired = undefined,
    description = undefined,
    examples,
    hasInfiniteParams = false,
    hiddenFromLibrary = false,
    generateComputedFunctionResult = undefined,
    parametersToEscapeOnParse = undefined,
    nbParamsDeclared,
  }: AmaliaFunctionMetadata<TArgs, TReturnType, TExecFn> & { nbParamsDeclared: number }) {
    this.name = name;
    this.category = category;
    this.exec = exec;
    this.execMock = execMock;
    this.nbParamsRequired = nbParamsRequired;
    this.description = description;
    this.examples = examples;
    this.params = params;
    this.hasInfiniteParams = hasInfiniteParams;
    this.hiddenFromLibrary = hiddenFromLibrary;
    this.generateComputedFunctionResult = generateComputedFunctionResult;
    this.parametersToEscapeOnParse = parametersToEscapeOnParse;
    this.nbParamsDeclared = nbParamsDeclared;
 
    // Register this function into the global enum.
    AmaliaFunction.allFunctions[name] = this as unknown as AmaliaFunction;
  }
 
  public readonly name: AmaliaFunctionKeys;
 
  public readonly category: AmaliaFunctionCategory;
 
  public readonly nbParamsRequired?: number;
 
  public readonly description?: string[] | string;
 
  public readonly examples: { desc?: string; formula: AmaliaFormula; result?: TReturnType }[];
 
  public readonly params: AmaliaFunctionArgument[];
 
  protected readonly nbParamsDeclared: number;
 
  public readonly hasInfiniteParams?: boolean;
 
  public readonly hiddenFromLibrary?: boolean;
 
  // The function to call in order to execute the function.
  public readonly exec: TExecFn;
 
  // Mock the evaluation in formula validation, useful for ComputedFunctionResults for instance.
  public readonly execMock?: TExecFn;
 
  /**
   * Given the args of the current context, generates the ComputedFunctionResult skeleton
   * for this function.
   */
  public readonly generateComputedFunctionResult?: (args: MathNode[]) => ComputedFunctionArgs;
 
  /**
   * For some functions, avoid classic parsing on some parameters by ignoring them.
   *
   * It usually means that they should be parsed in another context (for instance a dataset or a different period).
   */
  public readonly parametersToEscapeOnParse?: number[];
}
 
export class AmaliaFunctionDefault<
  TArgs extends ComputeEngineResult[] = ComputeEngineResult[],
  TReturnType extends ComputeEngineResult = ComputeEngineResult,
> extends AmaliaFunction<TArgs, TReturnType, AmaliaFunctionExecDefault<TArgs, TReturnType>> {
  public constructor({
    exec,
    ...other
  }: AmaliaFunctionMetadata<TArgs, TReturnType, AmaliaFunctionExecDefault<TArgs, TReturnType>>) {
    // const withArgsValidation =
    //   (execFn: typeof exec) =>
    //   (...args: TArgs) => {
    //     if (this.nbParamsRequired !== undefined) {
    //       for (let i = 0; i < this.nbParamsRequired; i++) {
    //         if (args[i] === undefined) {
    //           throw new ConfigurationError(
    //             `${this.name} is missing parameter at position ${i + 1} or its value is undefined`,
    //           );
    //         }
    //       }
    //     }
 
    //     if (!this.hasInfiniteParams && this.params.length && args.length > this.params.length) {
    //       throw new ConfigurationError(`Too many parameters for function ${this.name}`);
    //     }
 
    //     return execFn(...args);
    //   };
 
    super({
      ...other,
      exec,
      nbParamsDeclared: exec.length,
    });
  }
}
 
export class AmaliaFunctionRawArgs<
  TReturnType extends ComputeEngineResult = ComputeEngineResult,
> extends AmaliaFunction<MathjsRawArgsFunctionArguments, TReturnType, AmaliaFunctionExecRawArgs<TReturnType>> {
  public constructor({
    exec,
    execMock,
    ...other
  }: AmaliaFunctionMetadata<
    MathjsRawArgsFunctionArguments,
    TReturnType,
    AmaliaFunctionExec<MathjsRawArgsFunctionArguments, TReturnType>
  >) {
    super({
      ...other,
      exec: Object.assign(exec, { rawArgs: true } as const),
      execMock: execMock ? Object.assign(execMock, { rawArgs: true } as const) : undefined,
      nbParamsDeclared: exec.length,
    });
  }
}
 
/**
 * FIXME: this is a designer specific type, move it near the designer.
 */
export type AmaliaFunctionWithId = Omit<AmaliaFunction, 'nbParamsDeclared'> & { id: string | undefined };