All files / utils/expressions formula.js

99.09% Statements 328/331
97.6% Branches 245/251
100% Functions 42/42
99.66% Lines 302/303

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 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702                          24x 24x 24x                 36x 36x 36x                       24x 24x     111x 111x 111x 966x 966x 212x 212x   754x 754x 200x 181x 5x 6x   181x 181x   573x 34x 34x 34x 113x 113x 113x   34x 1x 33x 33x 33x   539x 105x 105x 104x 104x 103x 103x 103x   434x 391x 78x 78x   356x 356x 8x 8x 8x   348x 345x 345x 345x   3x   105x 105x                 115x 3x   112x 1x             111x 105x 105x   7050x 744x 3989x 617x     568x 568x 1x           567x       65x 65x 1x         204x 199x 1x 1x   199x       205x 200x 4x 4x   200x       213x 4x 4x   209x       209x 204x 44x 44x   204x       253x 248x 5x 5x   248x       258x 256x 114x 114x   253x       372x 368x 13x 13x   368x       389x 4x 4x   385x       385x 385x   178x   33x   102x   69x 4x             65x 1x           64x 64x 64x 57x 57x 41x 41x     64x 64x     2x 1x 1x     1x   1x       105x 100x 1x   99x                             115x           31x   43x   8x     19x   9x     2x   3x             24x                                                                             345x   103x   97x 97x 3x   94x 94x 1x           93x     7x 7x 7x 5x     76x   62x               246x 13x       76x 73x 73x     5x 4x 3x           23x 22x 22x   5x 4x 3x     15x 14x 13x     25x 24x 24x         62x 62x 1x   61x 61x 61x 2x           59x 91x 90x 90x 89x   57x     9x 9x 9x 7x             24x     183x                 120x 116x       16x 16x 15x       6x       4x 2x       20x 20x                         262x   77x   70x 70x     5x 4x     60x   50x         60x 2x       58x 1x         57x 53x 53x   2x   12x   2x   7x   1x   5x     6x 3x     18x           56x       14x 12x       16x 16x 16x   3x   4x   7x   2x           50x 2x 2x   48x 3x 4x 4x   1x     45x 43x   65x 40x   2x 2x     1x   1x   1x   1x   1x   1x   1x   1x   4x   2x 2x     1x 1x     3x   2x   3x   3x   3x   4x   1x   2x   1x     1x         3x 3x 3x 4x   1x                   16x 16x 66x 66x 66x 18x 18x   66x   16x 16x     24x                        
// @implements UC-WORKFLOW-007.1
/**
 * Excel-like formula language used in automatic workflow transition
 * conditions (see docs/architecture/AUTOMATION.md "Formulas").
 *
 * Formulas are user-written, so they are never run as code: this module
 * tokenizes and parses them into an AST, type-checks the AST against the
 * entity's fields when the entity is saved, and evaluates it with its own
 * interpreter. No `eval`, no `Function`, no loops, no regular expressions —
 * evaluation time is bounded by the AST size, itself bounded by the limits
 * below.
 */
 
const MAX_FORMULA_LENGTH = 1000
const MAX_FORMULA_NODES = 200
const MAX_TEXT_LENGTH = 10000
 
class FormulaError extends Error {
  /**
   * @param {string} code - Stable error code, returned to the client
   * @param {string} message - Developer-facing explanation
   * @param {number} [position] - Character offset in the formula text
   */
  constructor(code, message, position) {
    super(message)
    this.code = code
    this.position = position
  }
}
 
// Raised during evaluation only (empty operand, division by zero, ...): the
// condition leaf holding the formula then simply reads as false.
class EvaluationError extends Error {}
 
// ---------------------------------------------------------------------------
// Tokenizer
// ---------------------------------------------------------------------------
 
const TWO_CHAR_OPERATORS = ['<=', '>=', '<>', '!=']
const ONE_CHAR_OPERATORS = ['+', '-', '*', '/', '%', '&', '=', '<', '>', '(', ')', ',']
 
function tokenize(text) {
  const tokens = []
  let i = 0
  while (i < text.length) {
    const ch = text[i]
    if (/\s/.test(ch)) {
      i++
      continue
    }
    const start = i
    if (/[0-9]/.test(ch) || (ch === '.' && /[0-9]/.test(text[i + 1] || ''))) {
      while (i < text.length && /[0-9]/.test(text[i])) i++
      if (text[i] === '.') {
        i++
        while (i < text.length && /[0-9]/.test(text[i])) i++
      }
      tokens.push({ type: 'number', value: Number(text.slice(start, i)), pos: start })
      continue
    }
    if (ch === '"') {
      let value = ''
      i++
      while (i < text.length && text[i] !== '"') {
        if (text[i] === '\\' && i + 1 < text.length) i++
        value += text[i]
        i++
      }
      if (i >= text.length)
        throw new FormulaError('UNTERMINATED_STRING', 'Missing closing "', start)
      i++
      tokens.push({ type: 'string', value, pos: start })
      continue
    }
    if (ch === '{') {
      const end = text.indexOf('}', i)
      if (end === -1) throw new FormulaError('UNTERMINATED_FIELD', 'Missing closing }', start)
      const fieldId = text.slice(i + 1, end).trim()
      if (!fieldId) throw new FormulaError('EMPTY_FIELD_REFERENCE', 'Empty {} reference', start)
      tokens.push({ type: 'field', value: fieldId, pos: start })
      i = end + 1
      continue
    }
    if (/[A-Za-z_]/.test(ch)) {
      while (i < text.length && /[A-Za-z0-9_]/.test(text[i])) i++
      tokens.push({ type: 'ident', value: text.slice(start, i).toUpperCase(), pos: start })
      continue
    }
    const two = text.slice(i, i + 2)
    if (TWO_CHAR_OPERATORS.includes(two)) {
      tokens.push({ type: 'op', value: two === '<>' ? '!=' : two, pos: start })
      i += 2
      continue
    }
    if (ONE_CHAR_OPERATORS.includes(ch)) {
      tokens.push({ type: 'op', value: ch, pos: start })
      i++
      continue
    }
    throw new FormulaError('UNEXPECTED_CHARACTER', `Unexpected character "${ch}"`, start)
  }
  tokens.push({ type: 'end', pos: text.length })
  return tokens
}
 
// ---------------------------------------------------------------------------
// Parser — precedence climbing, lowest first:
//   OR < AND < NOT < comparison < & < + - < * / % < unary - < primary
// ---------------------------------------------------------------------------
 
function parse(text) {
  if (typeof text !== 'string' || text.trim() === '') {
    throw new FormulaError('EMPTY_FORMULA', 'The formula is empty', 0)
  }
  if (text.length > MAX_FORMULA_LENGTH) {
    throw new FormulaError(
      'FORMULA_TOO_LONG',
      `A formula is limited to ${MAX_FORMULA_LENGTH} characters`,
      MAX_FORMULA_LENGTH
    )
  }
 
  const tokens = tokenize(text)
  let index = 0
  let nodeCount = 0
 
  const peek = () => tokens[index]
  const next = () => tokens[index++]
  const isOp = (value) => peek().type === 'op' && peek().value === value
  const isKeyword = (value) => peek().type === 'ident' && peek().value === value
 
  function node(fields) {
    nodeCount++
    if (nodeCount > MAX_FORMULA_NODES) {
      throw new FormulaError(
        'FORMULA_TOO_COMPLEX',
        `A formula is limited to ${MAX_FORMULA_NODES} elements`,
        fields.pos
      )
    }
    return fields
  }
 
  function expect(value) {
    const token = next()
    if (token.type !== 'op' || token.value !== value) {
      throw new FormulaError('UNEXPECTED_TOKEN', `Expected "${value}"`, token.pos)
    }
  }
 
  function parseOr() {
    let left = parseAnd()
    while (isKeyword('OR')) {
      const { pos } = next()
      left = node({ kind: 'binary', op: 'OR', left, right: parseAnd(), pos })
    }
    return left
  }
 
  function parseAnd() {
    let left = parseNot()
    while (isKeyword('AND')) {
      const { pos } = next()
      left = node({ kind: 'binary', op: 'AND', left, right: parseNot(), pos })
    }
    return left
  }
 
  function parseNot() {
    if (isKeyword('NOT')) {
      const { pos } = next()
      return node({ kind: 'unary', op: 'NOT', operand: parseNot(), pos })
    }
    return parseComparison()
  }
 
  function parseComparison() {
    let left = parseConcat()
    while (['=', '!=', '<', '<=', '>', '>='].some(isOp)) {
      const { value, pos } = next()
      left = node({ kind: 'binary', op: value, left, right: parseConcat(), pos })
    }
    return left
  }
 
  function parseConcat() {
    let left = parseAdditive()
    while (isOp('&')) {
      const { pos } = next()
      left = node({ kind: 'binary', op: '&', left, right: parseAdditive(), pos })
    }
    return left
  }
 
  function parseAdditive() {
    let left = parseMultiplicative()
    while (isOp('+') || isOp('-')) {
      const { value, pos } = next()
      left = node({ kind: 'binary', op: value, left, right: parseMultiplicative(), pos })
    }
    return left
  }
 
  function parseMultiplicative() {
    let left = parseUnary()
    while (isOp('*') || isOp('/') || isOp('%')) {
      const { value, pos } = next()
      left = node({ kind: 'binary', op: value, left, right: parseUnary(), pos })
    }
    return left
  }
 
  function parseUnary() {
    if (isOp('-')) {
      const { pos } = next()
      return node({ kind: 'unary', op: '-', operand: parseUnary(), pos })
    }
    return parsePrimary()
  }
 
  function parsePrimary() {
    const token = next()
    switch (token.type) {
      case 'number':
        return node({ kind: 'literal', valueType: 'number', value: token.value, pos: token.pos })
      case 'string':
        return node({ kind: 'literal', valueType: 'text', value: token.value, pos: token.pos })
      case 'field':
        return node({ kind: 'field', fieldId: token.value, pos: token.pos })
      case 'ident': {
        if (token.value === 'TRUE' || token.value === 'FALSE') {
          return node({
            kind: 'literal',
            valueType: 'boolean',
            value: token.value === 'TRUE',
            pos: token.pos
          })
        }
        if (!isOp('(')) {
          throw new FormulaError(
            'UNEXPECTED_TOKEN',
            `"${token.value}" must be followed by "(" — fields are written {fieldId}`,
            token.pos
          )
        }
        next()
        const args = []
        if (!isOp(')')) {
          args.push(parseOr())
          while (isOp(',')) {
            next()
            args.push(parseOr())
          }
        }
        expect(')')
        return node({ kind: 'call', name: token.value, args, pos: token.pos })
      }
      case 'op':
        if (token.value === '(') {
          const inner = parseOr()
          expect(')')
          return inner
        }
        throw new FormulaError('UNEXPECTED_TOKEN', `Unexpected "${token.value}"`, token.pos)
      default:
        throw new FormulaError('UNEXPECTED_END', 'The formula ends too early', token.pos)
    }
  }
 
  const ast = parseOr()
  if (peek().type !== 'end') {
    throw new FormulaError('UNEXPECTED_TOKEN', 'Unexpected text after the formula', peek().pos)
  }
  return ast
}
 
// ---------------------------------------------------------------------------
// Types
// ---------------------------------------------------------------------------
 
/**
 * The formula type of an entity field, or null when the field can't be used
 * in a formula (images, files, geo locations, ...).
 *
 * @param {object} field - Entity field definition
 * @returns {'text' | 'number' | 'boolean' | 'date' | 'list' | null}
 */
function formulaTypeOfField(field) {
  switch (field?.type) {
    case 'text':
    case 'textarea':
    case 'email':
    case 'select':
    case 'workflow':
      return 'text'
    case 'number':
      return 'number'
    case 'boolean':
      return 'boolean'
    case 'date':
    case 'datetime':
      return 'date'
    case 'multiselect':
      return 'list'
    case 'user':
    case 'entity_ref':
      return field.reference?.multiple ? 'list' : 'text'
    default:
      return null
  }
}
 
// Function catalog: `args` lists the accepted types of each argument
// ('any' accepts every type); `variadic` repeats the last argument type.
// `returns` is a type, or 'same' for the (common) type of args from index 1.
const FUNCTIONS = {
  ROUND: { args: [['number'], ['number']], minArgs: 1, returns: 'number' },
  MIN: { args: [['number']], variadic: true, minArgs: 1, returns: 'number' },
  MAX: { args: [['number']], variadic: true, minArgs: 1, returns: 'number' },
  ABS: { args: [['number']], returns: 'number' },
  FLOOR: { args: [['number']], returns: 'number' },
  CEIL: { args: [['number']], returns: 'number' },
  UPPER: { args: [['text']], returns: 'text' },
  LOWER: { args: [['text']], returns: 'text' },
  TRIM: { args: [['text']], returns: 'text' },
  LEFT: { args: [['text'], ['number']], returns: 'text' },
  RIGHT: { args: [['text'], ['number']], returns: 'text' },
  MID: { args: [['text'], ['number'], ['number']], returns: 'text' },
  LEN: { args: [['text', 'list']], returns: 'number' },
  REPLACE: { args: [['text'], ['text'], ['text']], returns: 'text' },
  CONTAINS: { args: [['text', 'list'], ['text']], returns: 'boolean' },
  IF: { args: [['boolean'], ['any'], ['any']], returns: 'same' },
  ISEMPTY: { args: [['any']], returns: 'boolean' },
  COALESCE: { args: [['any']], variadic: true, minArgs: 1, returns: 'same', sameFrom: 0 },
  DATE: { args: [['text']], returns: 'date' },
  DAYS_BETWEEN: { args: [['date'], ['date']], returns: 'number' },
  ADD_DAYS: { args: [['date'], ['number']], returns: 'date' },
  YEAR: { args: [['date']], returns: 'number' },
  MONTH: { args: [['date']], returns: 'number' },
  DAY: { args: [['date']], returns: 'number' },
  // Evaluated when the item is saved or a timer fires (UC-WORKFLOW-009.1)
  TODAY: { args: [], returns: 'date' },
  NOW: { args: [], returns: 'date' }
}
 
/**
 * Type-checks a parsed formula against the entity's fields.
 *
 * @param {object} ast - Output of parse()
 * @param {Map<string, object>} fieldsById - Entity fields keyed by fieldId
 * @returns {'text' | 'number' | 'boolean' | 'date' | 'list'} the formula's result type
 * @throws {FormulaError}
 */
function typeCheck(ast, fieldsById) {
  switch (ast.kind) {
    case 'literal':
      return ast.valueType
    case 'field': {
      const field = fieldsById.get(ast.fieldId)
      if (!field) {
        throw new FormulaError('UNKNOWN_FIELD', `Unknown field {${ast.fieldId}}`, ast.pos)
      }
      const type = formulaTypeOfField(field)
      if (!type) {
        throw new FormulaError(
          'UNSUPPORTED_FIELD_TYPE',
          `A ${field.type} field can't be used in a formula`,
          ast.pos
        )
      }
      return type
    }
    case 'unary': {
      const type = typeCheck(ast.operand, fieldsById)
      const expected = ast.op === 'NOT' ? 'boolean' : 'number'
      expectType(type, [expected], ast.operand.pos)
      return expected
    }
    case 'binary':
      return typeCheckBinary(ast, fieldsById)
    case 'call':
      return typeCheckCall(ast, fieldsById)
    /* istanbul ignore next -- parse() only produces the kinds above */
    default:
      throw new FormulaError('INVALID_FORMULA', 'Invalid formula', ast.pos)
  }
}
 
function expectType(actual, accepted, pos) {
  if (accepted.includes('any') || accepted.includes(actual)) return
  throw new FormulaError('TYPE_MISMATCH', `Expected ${accepted.join(' or ')}, got ${actual}`, pos)
}
 
function typeCheckBinary(ast, fieldsById) {
  const left = typeCheck(ast.left, fieldsById)
  const right = typeCheck(ast.right, fieldsById)
  switch (ast.op) {
    case 'AND':
    case 'OR':
      expectType(left, ['boolean'], ast.left.pos)
      expectType(right, ['boolean'], ast.right.pos)
      return 'boolean'
    case '+':
    case '-':
    case '*':
    case '/':
    case '%':
      expectType(left, ['number'], ast.left.pos)
      expectType(right, ['number'], ast.right.pos)
      return 'number'
    case '&':
      expectType(left, ['text', 'number', 'boolean', 'date'], ast.left.pos)
      expectType(right, ['text', 'number', 'boolean', 'date'], ast.right.pos)
      return 'text'
    case '=':
    case '!=':
      expectType(left, ['text', 'number', 'boolean', 'date'], ast.left.pos)
      expectType(right, [left], ast.right.pos)
      return 'boolean'
    default:
      // < <= > >=
      expectType(left, ['text', 'number', 'date'], ast.left.pos)
      expectType(right, [left], ast.right.pos)
      return 'boolean'
  }
}
 
function typeCheckCall(ast, fieldsById) {
  const spec = FUNCTIONS[ast.name]
  if (!spec) {
    throw new FormulaError('UNKNOWN_FUNCTION', `Unknown function ${ast.name}`, ast.pos)
  }
  const minArgs = spec.minArgs ?? spec.args.length
  const maxArgs = spec.variadic ? Infinity : spec.args.length
  if (ast.args.length < minArgs || ast.args.length > maxArgs) {
    throw new FormulaError(
      'WRONG_ARGUMENT_COUNT',
      `${ast.name} takes ${minArgs === maxArgs ? minArgs : `${minArgs} or more`} argument(s)`,
      ast.pos
    )
  }
  const types = ast.args.map((arg, i) => {
    const type = typeCheck(arg, fieldsById)
    const accepted = spec.args[Math.min(i, spec.args.length - 1)]
    expectType(type, accepted, arg.pos)
    return type
  })
  if (spec.returns !== 'same') return spec.returns
 
  // IF's two branches, or every COALESCE argument, must share one type
  const sameFrom = spec.sameFrom ?? 1
  const [first, ...rest] = types.slice(sameFrom)
  rest.forEach((type, i) => expectType(type, [first], ast.args[sameFrom + 1 + i].pos))
  return first
}
 
// ---------------------------------------------------------------------------
// Evaluation
// ---------------------------------------------------------------------------
 
const MS_PER_DAY = 24 * 60 * 60 * 1000
 
function isEmpty(value) {
  return (
    value === undefined ||
    value === null ||
    value === '' ||
    (Array.isArray(value) && value.length === 0)
  )
}
 
function required(value) {
  if (isEmpty(value)) throw new EvaluationError('Empty operand')
  return value
}
 
function toDateMs(value) {
  const ms = Date.parse(required(value))
  if (Number.isNaN(ms)) throw new EvaluationError('Invalid date')
  return ms
}
 
function fromDateMs(ms) {
  return new Date(ms).toISOString().slice(0, 10)
}
 
function capText(text) {
  if (text.length > MAX_TEXT_LENGTH) throw new EvaluationError('Text too long')
  return text
}
 
function toText(value) {
  Iif (isEmpty(value)) return ''
  return String(value)
}
 
/**
 * Evaluates a type-checked formula.
 *
 * @param {object} ast - Output of parse(), already type-checked
 * @param {(fieldId: string) => unknown} getValue - Reads one field of the item
 * @param {number} [now] - The clock, in ms, for TODAY() / NOW()
 * @returns {unknown} The formula's value
 * @throws {EvaluationError} On an empty operand, a division by zero, an invalid date, ...
 */
function evaluate(ast, getValue, now = Date.now()) {
  switch (ast.kind) {
    case 'literal':
      return ast.value
    case 'field': {
      const value = getValue(ast.fieldId)
      return value === undefined ? null : value
    }
    case 'unary': {
      const value = required(evaluate(ast.operand, getValue, now))
      return ast.op === 'NOT' ? !value : -value
    }
    case 'binary':
      return evaluateBinary(ast, getValue, now)
    default:
      return evaluateCall(ast, getValue, now)
  }
}
 
function evaluateBinary(ast, getValue, now = Date.now()) {
  if (ast.op === 'AND') {
    return (
      required(evaluate(ast.left, getValue, now)) && required(evaluate(ast.right, getValue, now))
    )
  }
  if (ast.op === 'OR') {
    return (
      required(evaluate(ast.left, getValue, now)) || required(evaluate(ast.right, getValue, now))
    )
  }
 
  const left = evaluate(ast.left, getValue, now)
  const right = evaluate(ast.right, getValue, now)
  switch (ast.op) {
    case '&':
      return capText(toText(left) + toText(right))
    case '=':
      return equals(left, right)
    case '!=':
      return !equals(left, right)
    case '+':
      return required(left) + required(right)
    case '-':
      return required(left) - required(right)
    case '*':
      return required(left) * required(right)
    case '/':
    case '%': {
      if (required(right) === 0) throw new EvaluationError('Division by zero')
      return ast.op === '/' ? required(left) / right : required(left) % right
    }
    default:
      return compare(ast.op, required(left), required(right))
  }
}
 
// Text comparisons ignore case, like the condition builder's operators
function normalizeForComparison(value) {
  return typeof value === 'string' ? value.toLowerCase() : value
}
 
function equals(left, right) {
  if (isEmpty(left) || isEmpty(right)) return isEmpty(left) && isEmpty(right)
  return normalizeForComparison(left) === normalizeForComparison(right)
}
 
function compare(op, left, right) {
  const a = normalizeForComparison(left)
  const b = normalizeForComparison(right)
  switch (op) {
    case '<':
      return a < b
    case '<=':
      return a <= b
    case '>':
      return a > b
    default:
      return a >= b
  }
}
 
function evaluateCall(ast, getValue, now = Date.now()) {
  // IF and COALESCE only evaluate what they need
  if (ast.name === 'IF') {
    const condition = required(evaluate(ast.args[0], getValue, now))
    return evaluate(condition ? ast.args[1] : ast.args[2], getValue, now)
  }
  if (ast.name === 'COALESCE') {
    for (const arg of ast.args) {
      const value = evaluate(arg, getValue, now)
      if (!isEmpty(value)) return value
    }
    return null
  }
 
  if (ast.name === 'TODAY') return fromDateMs(now)
  if (ast.name === 'NOW') return new Date(now).toISOString()
 
  const args = ast.args.map((arg) => evaluate(arg, getValue, now))
  switch (ast.name) {
    case 'ROUND': {
      const factor = 10 ** (args.length > 1 ? required(args[1]) : 0)
      return Math.round(required(args[0]) * factor) / factor
    }
    case 'MIN':
      return Math.min(...args.map(required))
    case 'MAX':
      return Math.max(...args.map(required))
    case 'ABS':
      return Math.abs(required(args[0]))
    case 'FLOOR':
      return Math.floor(required(args[0]))
    case 'CEIL':
      return Math.ceil(required(args[0]))
    case 'UPPER':
      return toText(args[0]).toUpperCase()
    case 'LOWER':
      return toText(args[0]).toLowerCase()
    case 'TRIM':
      return toText(args[0]).trim()
    case 'LEFT':
      return toText(args[0]).slice(0, Math.max(0, required(args[1])))
    case 'RIGHT': {
      const count = Math.max(0, required(args[1]))
      return count === 0 ? '' : toText(args[0]).slice(-count)
    }
    case 'MID': {
      const start = Math.max(1, required(args[1])) - 1
      return toText(args[0]).slice(start, start + Math.max(0, required(args[2])))
    }
    case 'LEN':
      return isEmpty(args[0]) ? 0 : args[0].length
    case 'REPLACE':
      return capText(toText(args[0]).split(required(args[1])).join(toText(args[2])))
    case 'CONTAINS':
      return contains(args[0], toText(args[1]))
    case 'ISEMPTY':
      return isEmpty(args[0])
    case 'DATE':
      return fromDateMs(toDateMs(args[0]))
    case 'DAYS_BETWEEN':
      return Math.round((toDateMs(args[1]) - toDateMs(args[0])) / MS_PER_DAY)
    case 'ADD_DAYS':
      return fromDateMs(toDateMs(args[0]) + required(args[1]) * MS_PER_DAY)
    case 'YEAR':
      return new Date(toDateMs(args[0])).getUTCFullYear()
    case 'MONTH':
      return new Date(toDateMs(args[0])).getUTCMonth() + 1
    default:
      // DAY — every other name is rejected by typeCheck()
      return new Date(toDateMs(args[0])).getUTCDate()
  }
}
 
function contains(haystack, needle) {
  Iif (isEmpty(haystack)) return false
  const target = needle.toLowerCase()
  if (Array.isArray(haystack)) {
    return haystack.some((entry) => String(entry).toLowerCase() === target)
  }
  return String(haystack).toLowerCase().includes(target)
}
 
/**
 * The fieldIds a formula reads, in order of first appearance.
 *
 * @param {object} ast - Output of parse()
 * @returns {string[]}
 */
function referencedFields(ast) {
  const ids = new Set()
  const visit = (node) => {
    if (node.kind === 'field') ids.add(node.fieldId)
    if (node.kind === 'unary') visit(node.operand)
    if (node.kind === 'binary') {
      visit(node.left)
      visit(node.right)
    }
    if (node.kind === 'call') node.args.forEach(visit)
  }
  visit(ast)
  return [...ids]
}
 
module.exports = {
  MAX_FORMULA_LENGTH,
  MAX_FORMULA_NODES,
  FUNCTIONS,
  FormulaError,
  EvaluationError,
  parse,
  typeCheck,
  evaluate,
  referencedFields,
  formulaTypeOfField
}