function findNodeInASTRecursive()

in src/asl-utils/utils/jsonata/jsonata.ts [46:115]


function findNodeInASTRecursive(
  ast: ExprNode | ExprNode[],
  parent: ExprNode | null,
  position: number,
  depth = 0,
): JSONataASTResult | null {
  if (depth > MAX_AST_DEPTH) {
    return null
  }

  // Some AST children are arrays, so we should iterate through each of the children
  if (Array.isArray(ast)) {
    let currentNode: ExprNode | null = null
    for (const node of ast) {
      const currentPosition = node.position || node.error?.position
      if (!currentPosition) {
        const found = findNodeInASTRecursive(node, parent, position, depth + 1)
        if (found) {
          return found
        }

        continue
      }

      if (currentPosition > position) {
        continue
      }

      if (currentPosition === position) {
        return {
          node: node,
          parent,
        }
      }

      if (!currentNode?.position || (currentPosition < position && currentNode.position < currentPosition)) {
        currentNode = node
      }
    }

    if (!currentNode) {
      return null
    }

    return findNodeInASTRecursive(currentNode, parent, position, depth + 1)
  }

  if (ast.position && ast.position > position) {
    return null
  }

  if (ast.position === position) {
    return {
      node: ast,
      parent,
    }
  }

  for (const key of exprPropertiesToRecurse) {
    const value = ast[key]
    if (value) {
      const found = findNodeInASTRecursive(value, ast, position, depth + 1)
      if (found) {
        return found
      }
    }
  }

  return null
}