{"version":3,"sources":["../../../../../../../../../../../execroot/_main/bazel-out/k8-fastbuild/bin/core/player/src/index.ts","../../../../../../../../../../../execroot/_main/bazel-out/k8-fastbuild/bin/core/player/src/binding/index.ts","../../../../../../../../../../../execroot/_main/bazel-out/k8-fastbuild/bin/core/player/src/binding-grammar/ast.ts","../../../../../../../../../../../execroot/_main/bazel-out/k8-fastbuild/bin/core/player/src/binding-grammar/custom/index.ts","../../../../../../../../../../../execroot/_main/bazel-out/k8-fastbuild/bin/core/player/src/binding/utils.ts","../../../../../../../../../../../execroot/_main/bazel-out/k8-fastbuild/bin/core/player/src/binding/binding.ts","../../../../../../../../../../../execroot/_main/bazel-out/k8-fastbuild/bin/core/player/src/binding/resolver.ts","../../../../../../../../../../../execroot/_main/bazel-out/k8-fastbuild/bin/core/player/src/data/dependency-tracker.ts","../../../../../../../../../../../execroot/_main/bazel-out/k8-fastbuild/bin/core/player/src/data/model.ts","../../../../../../../../../../../execroot/_main/bazel-out/k8-fastbuild/bin/core/player/src/data/noop-model.ts","../../../../../../../../../../../execroot/_main/bazel-out/k8-fastbuild/bin/core/player/src/data/local-model.ts","../../../../../../../../../../../execroot/_main/bazel-out/k8-fastbuild/bin/core/player/src/expressions/evaluator.ts","../../../../../../../../../../../execroot/_main/bazel-out/k8-fastbuild/bin/core/player/src/expressions/types.ts","../../../../../../../../../../../execroot/_main/bazel-out/k8-fastbuild/bin/core/player/src/expressions/parser.ts","../../../../../../../../../../../execroot/_main/bazel-out/k8-fastbuild/bin/core/player/src/expressions/evaluator-functions.ts","../../../../../../../../../../../execroot/_main/bazel-out/k8-fastbuild/bin/core/player/src/expressions/async.ts","../../../../../../../../../../../execroot/_main/bazel-out/k8-fastbuild/bin/core/player/src/expressions/utils.ts","../../../../../../../../../../../execroot/_main/bazel-out/k8-fastbuild/bin/core/player/src/logger/types.ts","../../../../../../../../../../../execroot/_main/bazel-out/k8-fastbuild/bin/core/player/src/logger/consoleLogger.ts","../../../../../../../../../../../execroot/_main/bazel-out/k8-fastbuild/bin/core/player/src/logger/noopLogger.ts","../../../../../../../../../../../execroot/_main/bazel-out/k8-fastbuild/bin/core/player/src/logger/tapableLogger.ts","../../../../../../../../../../../execroot/_main/bazel-out/k8-fastbuild/bin/core/player/src/logger/proxyLogger.ts","../../../../../../../../../../../execroot/_main/bazel-out/k8-fastbuild/bin/core/player/src/schema/schema.ts","../../../../../../../../../../../execroot/_main/bazel-out/k8-fastbuild/bin/core/player/src/string-resolver/index.ts","../../../../../../../../../../../execroot/_main/bazel-out/k8-fastbuild/bin/core/player/src/validator/validation-middleware.ts","../../../../../../../../../../../execroot/_main/bazel-out/k8-fastbuild/bin/core/player/src/validator/binding-map-splice.ts","../../../../../../../../../../../execroot/_main/bazel-out/k8-fastbuild/bin/core/player/src/validator/registry.ts","../../../../../../../../../../../execroot/_main/bazel-out/k8-fastbuild/bin/core/player/src/view/view.ts","../../../../../../../../../../../execroot/_main/bazel-out/k8-fastbuild/bin/core/player/src/view/resolver/index.ts","../../../../../../../../../../../execroot/_main/bazel-out/k8-fastbuild/bin/core/player/src/view/parser/index.ts","../../../../../../../../../../../execroot/_main/bazel-out/k8-fastbuild/bin/core/player/src/view/parser/types.ts","../../../../../../../../../../../execroot/_main/bazel-out/k8-fastbuild/bin/core/player/src/view/parser/utils.ts","../../../../../../../../../../../execroot/_main/bazel-out/k8-fastbuild/bin/core/player/src/view/resolver/utils.ts","../../../../../../../../../../../execroot/_main/bazel-out/k8-fastbuild/bin/core/player/src/view/builder/index.ts","../../../../../../../../../../../execroot/_main/bazel-out/k8-fastbuild/bin/core/player/src/view/plugins/template.ts","../../../../../../../../../../../execroot/_main/bazel-out/k8-fastbuild/bin/core/player/src/view/plugins/string-resolver.ts","../../../../../../../../../../../execroot/_main/bazel-out/k8-fastbuild/bin/core/player/src/view/plugins/applicability.ts","../../../../../../../../../../../execroot/_main/bazel-out/k8-fastbuild/bin/core/player/src/view/plugins/switch.ts","../../../../../../../../../../../execroot/_main/bazel-out/k8-fastbuild/bin/core/player/src/view/plugins/multi-node.ts","../../../../../../../../../../../execroot/_main/bazel-out/k8-fastbuild/bin/core/player/src/view/plugins/asset.ts","../../../../../../../../../../../execroot/_main/bazel-out/k8-fastbuild/bin/core/player/src/controllers/view/store.ts","../../../../../../../../../../../execroot/_main/bazel-out/k8-fastbuild/bin/core/player/src/view/plugins/asset-transform.ts","../../../../../../../../../../../execroot/_main/bazel-out/k8-fastbuild/bin/core/player/src/player.ts","../../../../../../../../../../../execroot/_main/bazel-out/k8-fastbuild/bin/core/player/src/controllers/flow/flow.ts","../../../../../../../../../../../execroot/_main/bazel-out/k8-fastbuild/bin/core/player/src/controllers/flow/controller.ts","../../../../../../../../../../../execroot/_main/bazel-out/k8-fastbuild/bin/core/player/src/controllers/validation/controller.ts","../../../../../../../../../../../execroot/_main/bazel-out/k8-fastbuild/bin/core/player/src/utils/replaceParams.ts","../../../../../../../../../../../execroot/_main/bazel-out/k8-fastbuild/bin/core/player/src/controllers/validation/binding-tracker.ts","../../../../../../../../../../../execroot/_main/bazel-out/k8-fastbuild/bin/core/player/src/controllers/view/controller.ts","../../../../../../../../../../../execroot/_main/bazel-out/k8-fastbuild/bin/core/player/src/controllers/data/controller.ts","../../../../../../../../../../../execroot/_main/bazel-out/k8-fastbuild/bin/core/player/src/controllers/data/utils.ts","../../../../../../../../../../../execroot/_main/bazel-out/k8-fastbuild/bin/core/player/src/controllers/constants/utils.ts","../../../../../../../../../../../execroot/_main/bazel-out/k8-fastbuild/bin/core/player/src/controllers/constants/index.ts","../../../../../../../../../../../execroot/_main/bazel-out/k8-fastbuild/bin/core/player/src/plugins/flow-exp-plugin.ts","../../../../../../../../../../../execroot/_main/bazel-out/k8-fastbuild/bin/core/player/src/plugins/default-exp-plugin.ts","../../../../../../../../../../../execroot/_main/bazel-out/k8-fastbuild/bin/core/player/src/types.ts"],"sourcesContent":["// Add the types export first so it's naming takes precedence\nexport * from \"@player-ui/types\";\nexport * from \"./binding/index\";\nexport * from \"./data/index\";\nexport * from \"./expressions/index\";\nexport * from \"./logger/index\";\nexport * from \"./schema/index\";\nexport * from \"./string-resolver/index\";\nexport * from \"./validator/index\";\nexport * from \"./view/index\";\n\nexport * from \"./player\";\nexport * from \"./controllers/index\";\nexport * from \"./types\";\nexport * from \"./plugins/flow-exp-plugin\";\n","import { SyncBailHook, SyncWaterfallHook } from \"tapable-ts\";\nimport { NestedError } from \"ts-nested-error\";\nimport type { ParserResult, AnyNode } from \"../binding-grammar/index\";\nimport {\n  // We can swap this with whichever parser we want to use\n  parseCustom as parseBinding,\n} from \"../binding-grammar\";\nimport type { BindingParserOptions, BindingLike } from \"./binding\";\nimport { BindingInstance } from \"./binding\";\nimport { isBinding } from \"./utils\";\nimport type { NormalizedResult, ResolveBindingASTOptions } from \"./resolver\";\nimport { resolveBindingAST } from \"./resolver\";\n\nexport * from \"./utils\";\nexport * from \"./binding\";\n\nexport const SIMPLE_BINDING_REGEX = /^[\\w\\-@]+(\\.[\\w\\-@]+)*$/;\nexport const BINDING_BRACKETS_REGEX = /[\\s()*=`{}'\"[\\]]/;\nconst LAZY_BINDING_REGEX = /^[^.]+(\\..+)*$/;\n\nconst DEFAULT_OPTIONS: BindingParserOptions = {\n  get: () => {\n    throw new Error(\"Not Implemented\");\n  },\n  set: () => {\n    throw new Error(\"Not Implemented\");\n  },\n  evaluate: () => {\n    throw new Error(\"Not Implemented\");\n  },\n};\n\ntype BeforeResolveNodeContext = Required<NormalizedResult> &\n  ResolveBindingASTOptions;\n\n/** A parser for creating bindings from a string */\nexport class BindingParser {\n  private cache: Record<string, BindingInstance>;\n  private parseCache: Record<string, ParserResult>;\n  private parserOptions: BindingParserOptions;\n\n  public hooks = {\n    skipOptimization: new SyncBailHook<[string], boolean>(),\n    beforeResolveNode: new SyncWaterfallHook<\n      [AnyNode, BeforeResolveNodeContext]\n    >(),\n  };\n\n  constructor(options?: Partial<BindingParserOptions>) {\n    this.parserOptions = { ...DEFAULT_OPTIONS, ...options };\n    this.cache = {};\n    this.parseCache = {};\n    this.parse = this.parse.bind(this);\n  }\n\n  /**\n   * Takes a binding path, parses it, and returns an equivalent, normalized\n   * representation of that path.\n   */\n  private normalizePath(\n    path: string,\n    resolveOptions: ResolveBindingASTOptions,\n  ) {\n    /**\n     * Ensure no binding characters exist in path and the characters remaining\n     * look like a binding format.\n     */\n    if (\n      !BINDING_BRACKETS_REGEX.test(path) &&\n      LAZY_BINDING_REGEX.test(path) &&\n      this.hooks.skipOptimization.call(path) !== true\n    ) {\n      return { path: path.split(\".\"), updates: undefined } as NormalizedResult;\n    }\n\n    const ast = this.parseCache[path] ?? parseBinding(path);\n    this.parseCache[path] = ast;\n\n    if (typeof ast !== \"object\" || !ast?.status) {\n      throw new TypeError(\n        `Cannot normalize path \"${path}\": ${ast?.error ?? \"Unknown Error.\"}`,\n      );\n    }\n\n    try {\n      return resolveBindingAST(ast.path, resolveOptions, this.hooks);\n    } catch (e: any) {\n      throw new NestedError(`Cannot resolve binding: ${path}`, e);\n    }\n  }\n\n  private getBindingForNormalizedResult(\n    normalized: NormalizedResult,\n  ): BindingInstance {\n    const normalizedStr = normalized.path.join(\".\");\n\n    if (this.cache[normalizedStr]) {\n      return this.cache[normalizedStr];\n    }\n\n    const created = new BindingInstance(\n      normalizedStr === \"\" ? [] : normalized.path,\n      this.parse,\n    );\n    this.cache[normalizedStr] = created;\n\n    return created;\n  }\n\n  public parse(\n    rawBinding: BindingLike,\n    overrides: Partial<BindingParserOptions> = {},\n  ): BindingInstance {\n    if (isBinding(rawBinding)) {\n      return rawBinding;\n    }\n\n    const options = {\n      ...this.parserOptions,\n      ...overrides,\n    };\n\n    let updates: Record<string, any> = {};\n\n    const joined = Array.isArray(rawBinding)\n      ? rawBinding.join(\".\")\n      : String(rawBinding);\n\n    const normalizeConfig: ResolveBindingASTOptions = {\n      getValue: (path: Array<string | number>) => {\n        const normalized = this.normalizePath(path.join(\".\"), normalizeConfig);\n\n        return options.get(this.getBindingForNormalizedResult(normalized));\n      },\n      evaluate: (exp) => {\n        return options.evaluate(exp);\n      },\n      convertToPath: (path: any) => {\n        if (path === undefined) {\n          throw new Error(\n            \"Attempted to convert undefined value to binding path\",\n          );\n        }\n\n        if (\n          typeof path !== \"string\" &&\n          typeof path !== \"number\" &&\n          typeof path !== \"boolean\"\n        ) {\n          throw new Error(\n            `Attempting to convert ${typeof path} to a binding path.`,\n          );\n        }\n\n        const normalized = this.normalizePath(String(path), normalizeConfig);\n\n        if (normalized.updates) {\n          updates = {\n            ...updates,\n            ...normalized.updates,\n          };\n        }\n\n        const joinedNormalizedPath = normalized.path.join(\".\");\n\n        if (joinedNormalizedPath === \"\") {\n          throw new Error(\"Nested path resolved to an empty path\");\n        }\n\n        return joinedNormalizedPath;\n      },\n    };\n\n    const normalized = this.normalizePath(joined, normalizeConfig);\n\n    if (normalized.updates) {\n      updates = {\n        ...updates,\n        ...normalized.updates,\n      };\n    }\n\n    const updateKeys = Object.keys(updates);\n\n    if (!options.readOnly && updateKeys.length > 0) {\n      const updateTransaction = updateKeys.map<[BindingInstance, any]>(\n        (updatedBinding) => [\n          this.parse(updatedBinding),\n          updates[updatedBinding],\n        ],\n      );\n\n      options.set(updateTransaction);\n    }\n\n    return this.getBindingForNormalizedResult(normalized);\n  }\n}\n","export interface Node<T extends string> {\n  /** The basic node type */\n  name: T;\n}\n\n/**\n * An AST node that represents a nested path in the model\n * foo.{{bar}}.baz (this is {{bar}})\n */\nexport interface PathNode extends Node<\"PathNode\"> {\n  /** The path in the model that this node represents */\n  path: Array<AnyNode>;\n}\n\n/**\n * A segment representing a query\n * [foo=bar]\n */\nexport interface QueryNode extends Node<\"Query\"> {\n  /** The key to query */\n  key: AnyNode;\n\n  /** The target value */\n  value?: AnyNode;\n}\n\n/** A simple segment */\nexport interface ValueNode extends Node<\"Value\"> {\n  /** The segment value */\n  value: string | number | boolean;\n}\n\n/** A nested expression */\nexport interface ExpressionNode extends Node<\"Expression\"> {\n  /** The expression */\n  value: string;\n}\n\n/** Helper to create a value node */\nexport const toValue = (value: string | number | boolean): ValueNode => ({\n  name: \"Value\",\n  value,\n});\n\n/** Helper to create an expression node */\nexport const toExpression = (value: string): ExpressionNode => ({\n  name: \"Expression\",\n  value,\n});\n\n/** Helper to create a nested path node */\nexport const toPath = (path: Array<AnyNode>): PathNode => ({\n  name: \"PathNode\",\n  path,\n});\n\n/** Helper to create a query node */\nexport const toQuery = (key: AnyNode, value?: AnyNode): QueryNode => ({\n  name: \"Query\",\n  key,\n  value,\n});\n\n/** Create a concat node */\nexport const toConcatenatedNode = (\n  values: Array<PathNode | ValueNode | ExpressionNode>,\n): PathNode | ValueNode | ConcatenatedNode | ExpressionNode => {\n  if (values.length === 1) {\n    return values[0];\n  }\n\n  return {\n    name: \"Concatenated\",\n    value: values,\n  };\n};\n\n/**\n * A binding segment that's multiple smaller ones\n * {{foo}}_bar_{{baz}}\n */\nexport interface ConcatenatedNode extends Node<\"Concatenated\"> {\n  /** A list of nested paths, or value nodes to concat together to form a segment */\n  value: Array<PathNode | ValueNode | ExpressionNode>;\n}\n\nexport type AnyNode =\n  | PathNode\n  | QueryNode\n  | ValueNode\n  | ConcatenatedNode\n  | ExpressionNode;\nexport type Path = Array<AnyNode>;\n\nexport interface ParserSuccessResult {\n  /** A successful parse result */\n  status: true;\n\n  /** The path the binding represents */\n  path: PathNode;\n}\n\nexport interface ParserFailureResult {\n  /** A failed parse result */\n  status: false;\n\n  /** The message representing the reason the parse result failed */\n  error: string;\n}\n\nexport type ParserResult = ParserSuccessResult | ParserFailureResult;\n\nexport type Parser = (raw: string) => ParserResult;\n","import type {\n  Parser,\n  AnyNode,\n  PathNode,\n  ConcatenatedNode,\n  ValueNode,\n  QueryNode,\n  ExpressionNode,\n} from \"../ast\";\nimport {\n  toValue,\n  toPath,\n  toConcatenatedNode,\n  toQuery,\n  toExpression,\n} from \"../ast\";\n\nconst SEGMENT_SEPARATOR = \".\";\nconst OPEN_CURL = \"{\";\nconst CLOSE_CURL = \"}\";\nconst OPEN_BRACKET = \"[\";\nconst CLOSE_BRACKET = \"]\";\nconst EQUALS = \"=\";\nconst SINGLE_QUOTE = \"'\";\nconst DOUBLE_QUOTE = '\"';\nconst BACK_TICK = \"`\";\n// const IDENTIFIER_REGEX = /[\\w\\-@]+/;\n\n/** A _faster_ way to match chars instead of a regex. */\nconst isIdentifierChar = (char?: string): boolean => {\n  if (!char) {\n    return false;\n  }\n\n  const charCode = char.charCodeAt(0);\n\n  const matches =\n    charCode === 32 || // ' '\n    charCode === 34 || // \"\n    charCode === 39 || // '\n    charCode === 40 || // (\n    charCode === 41 || // )\n    charCode === 42 || // *\n    charCode === 46 || // .\n    charCode === 61 || // =\n    charCode === 91 || // [\n    charCode === 93 || // ]\n    charCode === 96 || // `\n    charCode === 123 || // {\n    charCode === 125; // }\n\n  return !matches;\n};\n\n/** Parse out a binding AST from a path */\nexport const parse: Parser = (path) => {\n  let index = 1;\n  let ch = path.charAt(0);\n\n  /** get the next char in the string */\n  const next = (expected?: string) => {\n    if (expected && ch !== expected) {\n      throw new Error(`Expected char: ${expected} but got: ${ch}`);\n    }\n\n    ch = path.charAt(index);\n    index += 1;\n    return ch;\n  };\n\n  /** gobble all whitespace */\n  const whitespace = () => {\n    while (ch === \" \") {\n      next();\n    }\n  };\n\n  /** get an identifier if you can */\n  const identifier = (allowBoolValue = false): ValueNode | undefined => {\n    if (!isIdentifierChar(ch)) {\n      return;\n    }\n\n    let value: string | number = ch;\n\n    while (next()) {\n      if (!isIdentifierChar(ch)) {\n        break;\n      }\n\n      value += ch;\n    }\n\n    if (allowBoolValue) {\n      if (value === \"true\") {\n        return toValue(true);\n      }\n      if (value === \"false\") {\n        return toValue(false);\n      }\n    }\n\n    if (value) {\n      const maybeNumber = Number(value);\n      value = isNaN(maybeNumber) ? value : maybeNumber;\n      return toValue(value);\n    }\n  };\n\n  /** get an expression node if you can */\n  const expression = (): ExpressionNode | undefined => {\n    if (ch === BACK_TICK) {\n      next(BACK_TICK);\n\n      let exp = ch;\n\n      while (next()) {\n        if (ch === BACK_TICK) {\n          break;\n        }\n\n        exp += ch;\n      }\n\n      next(BACK_TICK);\n\n      if (exp) {\n        return toExpression(exp);\n      }\n    }\n  };\n\n  /** Grab a value using a regex */\n  const regex = (match: RegExp): ValueNode | undefined => {\n    if (!ch?.match(match)) {\n      return;\n    }\n\n    let value = ch;\n\n    while (next()) {\n      if (!ch?.match(match)) {\n        break;\n      }\n\n      value += ch;\n    }\n\n    if (value) {\n      return toValue(value);\n    }\n  };\n\n  /** parse out a nestedPath if you can */\n  const nestedPath = (): PathNode | undefined => {\n    if (ch === OPEN_CURL) {\n      next(OPEN_CURL);\n      next(OPEN_CURL);\n\n      const modelRef = parsePath();\n      next(CLOSE_CURL);\n      next(CLOSE_CURL);\n      return modelRef;\n    }\n  };\n\n  /** get a simple segment node */\n  const simpleSegment = (allowBoolValue = false) =>\n    nestedPath() ?? expression() ?? identifier(allowBoolValue);\n\n  /** Parse a segment */\n  const segment = ():\n    | ConcatenatedNode\n    | PathNode\n    | ValueNode\n    | ExpressionNode\n    | undefined => {\n    // Either a string, modelRef, or concatenated version (both)\n    const segments: Array<ValueNode | PathNode | ExpressionNode> = [];\n    let nextSegment = simpleSegment();\n\n    while (nextSegment !== undefined) {\n      segments.push(nextSegment);\n      nextSegment = simpleSegment();\n    }\n\n    if (segments.length === 0) {\n      return undefined;\n    }\n\n    return toConcatenatedNode(segments);\n  };\n\n  /** get an optionally quoted block */\n  const optionallyQuotedSegment = (\n    allowBoolValue = false,\n  ): ValueNode | PathNode | ExpressionNode | undefined => {\n    whitespace();\n\n    // see if we have a quote\n\n    if (ch === SINGLE_QUOTE || ch === DOUBLE_QUOTE) {\n      const singleQuote = ch === SINGLE_QUOTE;\n      next(singleQuote ? SINGLE_QUOTE : DOUBLE_QUOTE);\n      const id = regex(/[^'\"]+/);\n      next(singleQuote ? SINGLE_QUOTE : DOUBLE_QUOTE);\n      return id;\n    }\n\n    return simpleSegment(allowBoolValue);\n  };\n\n  /** eat equals signs */\n  const equals = (): boolean => {\n    if (ch !== EQUALS) {\n      return false;\n    }\n\n    while (ch === EQUALS) {\n      next();\n    }\n\n    return true;\n  };\n\n  /** Parse out a bracket */\n  const parseBracket = ():\n    | ValueNode\n    | QueryNode\n    | PathNode\n    | ExpressionNode\n    | undefined => {\n    if (ch === OPEN_BRACKET) {\n      next(OPEN_BRACKET);\n      whitespace();\n      let value: ValueNode | QueryNode | PathNode | ExpressionNode | undefined =\n        optionallyQuotedSegment();\n      if (value) {\n        whitespace();\n        if (equals()) {\n          whitespace();\n          const second = optionallyQuotedSegment(true);\n          value = toQuery(value, second);\n          whitespace();\n        }\n      } else {\n        throw new Error(`Expected identifier`);\n      }\n\n      if (value) {\n        next(CLOSE_BRACKET);\n      }\n\n      return value;\n    }\n  };\n\n  /** Parse a segment and any number of brackets following it */\n  const parseSegmentAndBrackets = (): Array<AnyNode> => {\n    // try to parse a segment first\n\n    const parsed: Array<AnyNode> = [];\n\n    const firstSegment = segment();\n\n    if (firstSegment) {\n      parsed.push(firstSegment);\n\n      let bracketSegment = parseBracket();\n\n      if (bracketSegment?.name === \"Value\") {\n        const maybeNumber = Number(bracketSegment.value);\n        bracketSegment.value =\n          isNaN(maybeNumber) || String(maybeNumber) !== bracketSegment.value\n            ? bracketSegment.value\n            : maybeNumber;\n      }\n\n      while (bracketSegment !== undefined) {\n        parsed.push(bracketSegment);\n        bracketSegment = parseBracket();\n      }\n    }\n\n    return parsed;\n  };\n\n  /** Parse out a path segment */\n  const parsePath = (): PathNode => {\n    const parts: AnyNode[] = [];\n\n    let nextSegment = parseSegmentAndBrackets();\n\n    while (nextSegment !== undefined) {\n      parts.push(...nextSegment);\n\n      if (!ch || ch === CLOSE_CURL) {\n        break;\n      }\n\n      if (nextSegment.length === 0 && ch) {\n        throw new Error(`Unexpected character: ${ch}`);\n      }\n\n      next(SEGMENT_SEPARATOR);\n      nextSegment = parseSegmentAndBrackets();\n    }\n\n    return toPath(parts);\n  };\n\n  try {\n    const result = parsePath();\n\n    return {\n      status: true,\n      path: result,\n    };\n  } catch (e: any) {\n    return {\n      status: false,\n      error: e.message,\n    };\n  }\n};\n","import type { BindingLike, BindingInstance } from \"./binding\";\n\n/** Check if the parameter representing a binding is already of the Binding class */\nexport function isBinding(binding: BindingLike): binding is BindingInstance {\n  return !(typeof binding === \"string\" || Array.isArray(binding));\n}\n\n/** Convert the string to an int if you can, otherwise just return the original string */\nexport function maybeConvertToNum(i: string): string | number {\n  const asInt = parseInt(i, 10);\n\n  if (isNaN(asInt)) {\n    return i;\n  }\n\n  return asInt;\n}\n\n/**\n * utility to convert binding into binding segments.\n */\nexport function getBindingSegments(\n  binding: BindingLike,\n): Array<string | number> {\n  if (Array.isArray(binding)) {\n    return binding;\n  }\n\n  if (typeof binding === \"string\") {\n    return binding.split(\".\");\n  }\n\n  return binding.asArray();\n}\n\n/** Like _.findIndex, but ignores types */\nexport function findInArray<T extends Record<string | number, object>>(\n  array: Array<T>,\n  key: string | number,\n  value: T,\n): number | undefined {\n  return array.findIndex((obj) => {\n    if (obj && typeof obj === \"object\") {\n      // Intentional double-equals because we want '4' to be coerced to 4\n      return obj[key] == value;\n    }\n\n    return false;\n  });\n}\n","import { getBindingSegments } from \"./utils\";\n\nexport interface BindingParserOptions {\n  /** Get the value for a specific binding */\n  get: (binding: BindingInstance) => any;\n\n  /**\n   * Set the values for bindings.\n   * This is used when the query syntax needs to modify an object\n   */\n  set: (transaction: Array<[BindingInstance, any]>) => void;\n\n  /**\n   * Get the result of evaluating an expression\n   */\n  evaluate: (exp: string) => any;\n\n  /**\n   * Without readOnly, if a binding such as this is used: arr[key='does not exist'],\n   * then an object with that key will be created.\n   * This is done to make assignment such as arr[key='abc'].val = 'foo' work smoothly.\n   * Setting readOnly to true will prevent this behavior, avoiding unintended data changes.\n   */\n  readOnly?: boolean;\n}\n\nexport type Getter = (path: BindingInstance) => any;\n\nexport type RawBindingSegment = number | string;\nexport type RawBinding = string | RawBindingSegment[];\nexport type BindingLike = RawBinding | BindingInstance;\nexport type BindingFactory = (\n  raw: RawBinding,\n  options?: Partial<BindingParserOptions>,\n) => BindingInstance;\n\n/**\n * A path in the data model\n */\nexport class BindingInstance {\n  private split: RawBindingSegment[];\n  private joined: string;\n  private factory: BindingFactory;\n\n  constructor(\n    raw: RawBinding,\n    factory = (rawBinding: RawBinding) => new BindingInstance(rawBinding),\n  ) {\n    const split = Array.isArray(raw) ? raw : raw.split(\".\");\n    this.split = split.map((segment) => {\n      if (typeof segment === \"number\") {\n        return segment;\n      }\n\n      const tryNum = Number(segment);\n      // test to make sure turning a numerical string to a number doesn't change\n      // the actual value of the string by getting rid of a leading zero\n      return isNaN(tryNum) || String(tryNum) !== segment ? segment : tryNum;\n    });\n    Object.freeze(this.split);\n    this.joined = this.split.join(\".\");\n    this.factory = factory;\n  }\n\n  asArray(): RawBindingSegment[] {\n    return this.split;\n  }\n\n  asString(): string {\n    return this.joined;\n  }\n\n  /**\n   * Check to see if the given binding is a sub-path of the current one\n   */\n  contains(binding: BindingInstance): boolean {\n    // need to account for partial key matches\n    // [foo, bar] !== [foo, ba]\n    const bindingAsArray = binding.asArray();\n\n    if (bindingAsArray.length < this.split.length) {\n      return false;\n    }\n\n    // Check every overlapping index to make sure they're the same\n    // Intentionally use a for loop for speeeed\n    for (let i = 0; i < this.split.length; i++) {\n      if (this.split[i] !== bindingAsArray[i]) {\n        return false;\n      }\n    }\n\n    return true;\n  }\n\n  relative(binding: BindingInstance): RawBindingSegment[] {\n    return this.asArray().slice(binding.asArray().length);\n  }\n\n  parent(): BindingInstance {\n    return this.factory(this.split.slice(0, -1));\n  }\n\n  key(): RawBindingSegment {\n    return this.split[this.split.length - 1];\n  }\n\n  /**\n   * This is a utility method to get a binding that is a descendent of this binding\n   *\n   * @param relative - The relative path to descend to\n   */\n  descendent(relative: BindingLike): BindingInstance {\n    const descendentSegments = getBindingSegments(relative);\n\n    return this.factory(this.split.concat(descendentSegments));\n  }\n}\n","import { NestedError } from \"ts-nested-error\";\nimport type { SyncWaterfallHook } from \"tapable-ts\";\nimport type { PathNode, AnyNode } from \"../binding-grammar\";\nimport { findInArray, maybeConvertToNum } from \"./utils\";\n\nexport interface NormalizedResult {\n  /** The normalized path */\n  path: Array<string | number>;\n\n  /** Any new updates that need to happen for this binding to be resolved */\n  updates?: Record<string, any>;\n}\n\nexport interface ResolveBindingASTOptions {\n  /** Get the value of the model at the given path */\n  getValue: (path: Array<string | number>) => any;\n\n  /** Convert the value into valid path segments */\n  convertToPath: (value: any) => string;\n\n  /** Convert the value into valid path segments */\n  evaluate: (exp: string) => any;\n}\n\nexport interface ResolveBindingASTHooks {\n  /** A hook for transforming a node before fully resolving it */\n  beforeResolveNode: SyncWaterfallHook<\n    [AnyNode, Required<NormalizedResult> & ResolveBindingASTOptions]\n  >;\n}\n\n/** Given a binding AST, resolve it */\nexport function resolveBindingAST(\n  bindingPathNode: PathNode,\n  options: ResolveBindingASTOptions,\n  hooks?: ResolveBindingASTHooks,\n): NormalizedResult {\n  const context: Required<NormalizedResult> = {\n    updates: {},\n    path: [],\n  };\n\n  // let updates: Record<string, any> = {};\n  // const path: Array<string | number> = [];\n\n  /** Get the value for any child node */\n  function getValueForNode(node: AnyNode): any {\n    if (node.name === \"Value\") {\n      return node.value;\n    }\n\n    if (node.name === \"PathNode\") {\n      const nestedResolvedValue = resolveBindingAST(node, options);\n\n      if (nestedResolvedValue.updates) {\n        context.updates = {\n          ...context.updates,\n          ...nestedResolvedValue.updates,\n        };\n      }\n\n      try {\n        return options.convertToPath(\n          options.getValue(nestedResolvedValue.path),\n        );\n      } catch (e: any) {\n        throw new NestedError(\n          `Unable to resolve path segment: ${nestedResolvedValue.path}`,\n          e,\n        );\n      }\n    }\n\n    if (node.name === \"Expression\") {\n      try {\n        const actualValue = options.evaluate(node.value);\n\n        return options.convertToPath(actualValue);\n      } catch (e: any) {\n        throw new NestedError(`Unable to resolve path: ${node.value}`, e);\n      }\n    }\n\n    throw new Error(`Unable to resolve value for node: ${node.name}`);\n  }\n\n  /** Handle when path segments are binding paths (foo.bar) or single segments (foo) */\n  function appendPathSegments(segment: string | number) {\n    if (typeof segment === \"string\" && segment.indexOf(\".\") > -1) {\n      segment.split(\".\").forEach((i) => {\n        context.path.push(maybeConvertToNum(i));\n      });\n    } else {\n      context.path.push(segment);\n    }\n  }\n\n  /** Compute the _actual_ binding val from the AST */\n  function resolveNode(_node: AnyNode) {\n    const resolvedNode =\n      hooks?.beforeResolveNode.call(_node, { ...context, ...options }) ?? _node;\n\n    switch (resolvedNode.name) {\n      case \"Expression\":\n      case \"PathNode\":\n        appendPathSegments(getValueForNode(resolvedNode));\n        break;\n\n      case \"Value\":\n        appendPathSegments(\n          typeof resolvedNode.value === \"boolean\"\n            ? String(resolvedNode.value)\n            : resolvedNode.value,\n        );\n        break;\n\n      case \"Query\": {\n        // Look for an object at the path with the given key/val criteria\n        const objToQuery: Record<string, any>[] =\n          options.getValue(context.path) ?? [];\n\n        const { key, value } = resolvedNode;\n\n        const resolvedKey = getValueForNode(key);\n        const resolvedValue = value && getValueForNode(value);\n\n        const index = findInArray(objToQuery, resolvedKey, resolvedValue);\n\n        if (index === undefined || index === -1) {\n          context.updates[\n            [...context.path, objToQuery.length, resolvedKey].join(\".\")\n          ] = resolvedValue;\n          context.path.push(objToQuery.length);\n        } else {\n          context.path.push(index);\n        }\n\n        break;\n      }\n\n      case \"Concatenated\":\n        context.path.push(resolvedNode.value.map(getValueForNode).join(\"\"));\n        break;\n\n      default:\n        throw new Error(`Unsupported node type: ${(resolvedNode as any).name}`);\n    }\n  }\n\n  bindingPathNode.path.forEach(resolveNode);\n\n  return {\n    path: context.path,\n    updates:\n      Object.keys(context.updates ?? {}).length > 0\n        ? context.updates\n        : undefined,\n  };\n}\n","import type { BindingInstance } from \"../binding\";\nimport type {\n  BatchSetTransaction,\n  DataModelImpl,\n  DataModelMiddleware,\n  DataModelOptions,\n  Updates,\n} from \"./model\";\n\nexport type DependencySets = \"core\" | \"children\";\n\n/** A class to track usage of read/writes to/from a data model */\nexport class DependencyTracker {\n  protected readDeps: Set<BindingInstance>;\n  protected writeDeps: Set<BindingInstance>;\n  protected namedSet: DependencySets;\n\n  private namedDependencySets: Partial<\n    Record<\n      DependencySets,\n      {\n        /** readDeps */\n        readDeps: Set<BindingInstance>;\n        /** writeDeps */\n        writeDeps: Set<BindingInstance>;\n      }\n    >\n  >;\n\n  constructor() {\n    this.readDeps = new Set();\n    this.writeDeps = new Set();\n    this.namedDependencySets = {};\n    this.namedSet = \"core\";\n\n    this.createSubset(\"core\");\n    this.createSubset(\"children\");\n  }\n\n  protected createSubset(name: DependencySets, force = false): void {\n    if (force || !this.namedDependencySets[name]) {\n      this.namedDependencySets[name] = {\n        readDeps: new Set(),\n        writeDeps: new Set(),\n      };\n    }\n  }\n\n  /** Grab all of the bindings that this depended on */\n  public getDependencies(name?: DependencySets): Set<BindingInstance> {\n    if (name !== undefined) {\n      return this.namedDependencySets?.[name]?.readDeps ?? new Set();\n    }\n\n    return this.readDeps;\n  }\n\n  public trackSubset(name: DependencySets) {\n    this.createSubset(name);\n    this.namedSet = name;\n  }\n\n  public trackDefault() {\n    this.namedSet = \"core\";\n  }\n\n  /** Grab all of the bindings this wrote to */\n  public getModified(name?: DependencySets): Set<BindingInstance> {\n    if (name !== undefined) {\n      return this.namedDependencySets?.[name]?.writeDeps ?? new Set();\n    }\n\n    return this.writeDeps;\n  }\n\n  /**\n   * Check to see if the dataModel has read the value at the given binding\n   *\n   * @param binding - The binding you want to check for\n   */\n  public readsBinding(binding: BindingInstance): boolean {\n    return this.readDeps.has(binding);\n  }\n\n  /**\n   * Check to see if the dataModel has written to the binding\n   */\n  public writesBinding(binding: BindingInstance): boolean {\n    return this.writeDeps.has(binding);\n  }\n\n  /** Reset all tracking of dependencies */\n  public reset() {\n    this.readDeps = new Set();\n    this.writeDeps = new Set();\n    this.namedDependencySets = {};\n    this.namedSet = \"core\";\n\n    this.createSubset(\"core\", true);\n    this.createSubset(\"children\", true);\n  }\n\n  protected addReadDep(\n    binding: BindingInstance,\n    namedSet = this.namedSet,\n  ): void {\n    if (namedSet) {\n      this.namedDependencySets?.[namedSet]?.readDeps.add(binding);\n    }\n\n    this.readDeps.add(binding);\n  }\n\n  protected addWriteDep(\n    binding: BindingInstance,\n    namedSet = this.namedSet,\n  ): void {\n    if (namedSet) {\n      this.namedDependencySets?.[namedSet]?.writeDeps.add(binding);\n    }\n\n    this.writeDeps.add(binding);\n  }\n\n  public addChildReadDep(binding: BindingInstance): void {\n    this.addReadDep(binding, \"children\");\n  }\n}\n\n/** Middleware that tracks dependencies of read/written data */\nexport class DependencyMiddleware\n  extends DependencyTracker\n  implements DataModelMiddleware\n{\n  constructor() {\n    super();\n    this.get = this.get.bind(this);\n    this.set = this.set.bind(this);\n  }\n\n  public set(\n    transaction: BatchSetTransaction,\n    options?: DataModelOptions,\n    next?: DataModelImpl | undefined,\n  ): Updates {\n    transaction.forEach(([binding]) => this.addWriteDep(binding));\n\n    return next?.set(transaction, options) ?? [];\n  }\n\n  public get(\n    binding: BindingInstance,\n    options?: DataModelOptions,\n    next?: DataModelImpl | undefined,\n  ) {\n    this.addReadDep(binding);\n\n    return next?.get(binding, options);\n  }\n\n  public delete(\n    binding: BindingInstance,\n    options?: DataModelOptions,\n    next?: DataModelImpl | undefined,\n  ) {\n    this.addWriteDep(binding);\n    return next?.delete(binding, options);\n  }\n}\n\n/** A data-model that tracks dependencies of read/written data */\nexport class DependencyModel<Options = DataModelOptions>\n  extends DependencyTracker\n  implements DataModelImpl<Options>\n{\n  private readonly rootModel: DataModelImpl<Options>;\n\n  constructor(rootModel: DataModelImpl<Options>) {\n    super();\n    this.rootModel = rootModel;\n    this.set = this.set.bind(this);\n    this.get = this.get.bind(this);\n  }\n\n  public set(transaction: BatchSetTransaction, options?: Options): Updates {\n    transaction.forEach(([binding]) => this.addWriteDep(binding));\n\n    return this.rootModel.set(transaction, options);\n  }\n\n  public get(binding: BindingInstance, options?: Options) {\n    this.addReadDep(binding);\n\n    return this.rootModel.get(binding, options);\n  }\n\n  public delete(binding: BindingInstance, options?: Options) {\n    this.addWriteDep(binding);\n    return this.rootModel.delete(binding, options);\n  }\n}\n","import { SyncHook } from \"tapable-ts\";\nimport type { BindingLike, BindingFactory } from \"../binding\";\nimport { BindingInstance, isBinding } from \"../binding\";\nimport { NOOP_MODEL } from \"./noop-model\";\n\nexport const ROOT_BINDING = new BindingInstance([]);\nexport type BatchSetTransaction = [BindingInstance, any][];\n\nexport type Updates = Array<{\n  /** The updated binding */\n  binding: BindingInstance;\n\n  /** The old value */\n  oldValue: any;\n\n  /** The new value */\n  newValue: any;\n\n  /** Force the Update to be included even if no data changed */\n  force?: boolean;\n}>;\n\n/** Options to use when getting or setting data */\nexport interface DataModelOptions {\n  /**\n   * The data (either to set or get) should represent a formatted value\n   * For setting data, the data will be de-formatted before continuing in the pipeline\n   * For getting data, the data will be formatted before returning\n   */\n  formatted?: boolean;\n\n  /**\n   * By default, fetching data will ignore any invalid data.\n   * You can choose to grab the queued invalid data if you'd like\n   * This is usually the case for user-inputs\n   */\n  includeInvalid?: boolean;\n\n  /**\n   * A flag to set to ignore any default value in the schema, and just use the raw value\n   */\n  ignoreDefaultValue?: boolean;\n\n  /**\n   * A flag to indicate that this update should happen silently\n   */\n  silent?: boolean;\n\n  /** Other context associated with this request */\n  context?: {\n    /** The data model to use when getting other data from the context of this request */\n    model: DataModelWithParser;\n  };\n}\n\nexport interface DataModelWithParser<Options = DataModelOptions> {\n  get(binding: BindingLike, options?: Options): any;\n  set(transaction: [BindingLike, any][], options?: Options): Updates;\n  delete(binding: BindingLike, options?: Options): void;\n}\n\nexport interface DataModelImpl<Options = DataModelOptions> {\n  get(binding: BindingInstance, options?: Options): any;\n  set(transaction: BatchSetTransaction, options?: Options): Updates;\n  delete(binding: BindingInstance, options?: Options): void;\n}\n\nexport interface DataModelMiddleware {\n  /** The name of the middleware */\n  name?: string;\n\n  set(\n    transaction: BatchSetTransaction,\n    options?: DataModelOptions,\n    next?: DataModelImpl,\n  ): Updates;\n\n  get(\n    binding: BindingInstance,\n    options?: DataModelOptions,\n    next?: DataModelImpl,\n  ): any;\n\n  delete?(\n    binding: BindingInstance,\n    options?: DataModelOptions,\n    next?: DataModelImpl,\n  ): void;\n\n  reset?(): void;\n}\n\n/** Wrap the inputs of the DataModel with calls to parse raw binding inputs */\nexport function withParser<Options = unknown>(\n  model: DataModelImpl<Options>,\n  parseBinding: BindingFactory,\n): DataModelWithParser<Options> {\n  /** Parse something into a binding if it requires it */\n  function maybeParse(\n    binding: BindingLike,\n    readOnly: boolean,\n  ): BindingInstance {\n    const parsed = isBinding(binding)\n      ? binding\n      : parseBinding(binding, {\n          get: model.get,\n          set: model.set,\n          readOnly,\n        });\n\n    if (!parsed) {\n      throw new Error(\"Unable to parse binding\");\n    }\n\n    return parsed;\n  }\n\n  return {\n    get(binding, options?: Options) {\n      return model.get(maybeParse(binding, true), options);\n    },\n    set(transaction, options?: Options) {\n      return model.set(\n        transaction.map(([key, val]) => [maybeParse(key, false), val]),\n        options,\n      );\n    },\n    delete(binding, options?: Options) {\n      return model.delete(maybeParse(binding, false), options);\n    },\n  };\n}\n\n/** Wrap a middleware instance in a DataModel compliant API */\nexport function toModel(\n  middleware: DataModelMiddleware,\n  defaultOptions?: DataModelOptions,\n  next?: DataModelImpl,\n): DataModelImpl {\n  if (!next) {\n    return middleware as DataModelImpl;\n  }\n\n  return {\n    get: (binding: BindingInstance, options?: DataModelOptions) => {\n      const resolvedOptions = options ?? defaultOptions;\n\n      if (middleware.get) {\n        return middleware.get(binding, resolvedOptions, next);\n      }\n\n      return next?.get(binding, resolvedOptions);\n    },\n    set: (transaction: BatchSetTransaction, options?: DataModelOptions) => {\n      const resolvedOptions = options ?? defaultOptions;\n\n      if (middleware.set) {\n        return middleware.set(transaction, resolvedOptions, next);\n      }\n\n      return next?.set(transaction, resolvedOptions);\n    },\n    delete: (binding: BindingInstance, options?: DataModelOptions) => {\n      const resolvedOptions = options ?? defaultOptions;\n\n      if (middleware.delete) {\n        return middleware.delete(binding, resolvedOptions, next);\n      }\n\n      return next?.delete(binding, resolvedOptions);\n    },\n  };\n}\n\nexport type DataPipeline = Array<DataModelMiddleware | DataModelImpl>;\n\n/**\n * Given a set of steps in a pipeline, create the effective data-model\n */\nexport function constructModelForPipeline(\n  pipeline: DataPipeline,\n): DataModelImpl {\n  if (pipeline.length === 0) {\n    return NOOP_MODEL;\n  }\n\n  if (pipeline.length === 1) {\n    return toModel(pipeline[0]);\n  }\n\n  /** Default and propagate the options into the nested calls */\n  function createModelWithOptions(options?: DataModelOptions) {\n    const model: DataModelImpl =\n      pipeline.reduce<DataModelImpl | undefined>(\n        (nextModel, middleware) => toModel(middleware, options, nextModel),\n        undefined,\n      ) ?? NOOP_MODEL;\n\n    return model;\n  }\n\n  return {\n    get: (binding: BindingInstance, options?: DataModelOptions) => {\n      return createModelWithOptions(options)?.get(binding, options);\n    },\n    set: (transaction, options) => {\n      return createModelWithOptions(options)?.set(transaction, options);\n    },\n    delete: (binding, options) => {\n      return createModelWithOptions(options)?.delete(binding, options);\n    },\n  };\n}\n\n/** A DataModel that manages middleware data handlers  */\nexport class PipelinedDataModel implements DataModelImpl {\n  private pipeline: DataPipeline;\n  private effectiveDataModel: DataModelImpl;\n\n  public readonly hooks = {\n    onSet: new SyncHook<[BatchSetTransaction]>(),\n  };\n\n  constructor(pipeline: DataPipeline = []) {\n    this.pipeline = pipeline;\n    this.effectiveDataModel = constructModelForPipeline(this.pipeline);\n  }\n\n  public setMiddleware(handlers: DataPipeline) {\n    this.pipeline = handlers;\n    this.effectiveDataModel = constructModelForPipeline(handlers);\n  }\n\n  public addMiddleware(handler: DataModelMiddleware) {\n    this.pipeline = [...this.pipeline, handler];\n    this.effectiveDataModel = constructModelForPipeline(this.pipeline);\n  }\n\n  public reset(model = {}) {\n    this.pipeline.forEach((middleware) => {\n      if (\"reset\" in middleware) {\n        middleware.reset?.();\n      }\n    });\n\n    this.set([[ROOT_BINDING, model]]);\n  }\n\n  public set(\n    transaction: BatchSetTransaction,\n    options?: DataModelOptions,\n  ): Updates {\n    const appliedTransaction = this.effectiveDataModel.set(\n      transaction,\n      options,\n    );\n    this.hooks.onSet.call(transaction);\n    return appliedTransaction;\n  }\n\n  public get(binding: BindingInstance, options?: DataModelOptions): any {\n    return this.effectiveDataModel.get(binding, options);\n  }\n\n  public delete(binding: BindingInstance, options?: DataModelOptions): void {\n    return this.effectiveDataModel.delete(binding, options);\n  }\n}\n","import type { DataModelImpl } from \"./model\";\n\n/**\n * A model that does nothing\n * Helpful for testing and other default DataModel applications\n */\nexport class NOOPDataModel implements DataModelImpl {\n  get() {\n    return undefined;\n  }\n\n  set() {\n    return [];\n  }\n\n  delete() {}\n}\n\n/** You only really need 1 instance of the NOOP model */\nexport const NOOP_MODEL = new NOOPDataModel();\n","import get from \"dlv\";\nimport { setIn, omit, removeAt } from \"timm\";\nimport type { BindingInstance } from \"../binding\";\nimport type { BatchSetTransaction, DataModelImpl, Updates } from \"./model\";\n\n/**\n * A data model that stores data in an in-memory JS object\n */\nexport class LocalModel implements DataModelImpl {\n  public model: {\n    [key: string]: any;\n  };\n\n  constructor(model = {}) {\n    this.model = model;\n    this.get = this.get.bind(this);\n    this.set = this.set.bind(this);\n  }\n\n  public reset(model = {}) {\n    this.model = model;\n  }\n\n  public get(binding?: BindingInstance) {\n    if (!binding || !binding.asString()) {\n      return this.model;\n    }\n\n    return get(this.model, binding.asArray() as string[]);\n  }\n\n  public set(transaction: BatchSetTransaction) {\n    const effectiveOperations: Updates = [];\n    transaction.forEach(([binding, value]) => {\n      const oldValue = this.get(binding);\n      this.model = setIn(this.model, binding.asArray(), value) as any;\n      effectiveOperations.push({ binding, oldValue, newValue: value });\n    });\n    return effectiveOperations;\n  }\n\n  public delete(binding: BindingInstance) {\n    const parentBinding = binding.parent();\n\n    if (parentBinding) {\n      const parentValue = this.get(parentBinding);\n\n      if (parentValue !== undefined) {\n        if (Array.isArray(parentValue)) {\n          this.model = setIn(\n            this.model,\n            parentBinding.asArray(),\n            removeAt(parentValue, binding.key() as number),\n          ) as any;\n        } else {\n          this.model = setIn(\n            this.model,\n            parentBinding.asArray(),\n            omit(parentValue, binding.key() as string),\n          ) as any;\n        }\n      }\n    }\n  }\n}\n","import { SyncWaterfallHook, SyncBailHook } from \"tapable-ts\";\nimport { NestedError } from \"ts-nested-error\";\nimport { parseExpression } from \"./parser\";\nimport * as DEFAULT_EXPRESSION_HANDLERS from \"./evaluator-functions\";\nimport { collateAwaitable, isAwaitable, isPromiseLike } from \"./async\";\nimport { isExpressionNode } from \"./types\";\nimport { isObjectExpression } from \"./utils\";\nimport type {\n  ExpressionNode,\n  BinaryOperator,\n  UnaryOperator,\n  ExpressionType,\n  ExpressionContext,\n  ExpressionHandler,\n} from \"./types\";\n\n/** a && b -- but handles short cutting if the first value is false */\nconst andandOperator: BinaryOperator = (ctx, a, b, async) => {\n  return LogicalOperators.and(ctx, a, b, async);\n};\nandandOperator.resolveParams = false;\n\n/** a || b -- but with short cutting if first value is true */\nconst ororOperator: BinaryOperator = (ctx, a, b, async) => {\n  return LogicalOperators.or(ctx, a, b, async);\n};\nororOperator.resolveParams = false;\n\nconst DEFAULT_BINARY_OPERATORS: Record<string, BinaryOperator> = {\n  // TODO: A lot of these functions used to do type coercion. Not sure if we want to keep that behavior or not.\n  \"+\": (a: any, b: any) => a + b,\n  \"-\": (a: any, b: any) => a - b,\n  \"*\": (a: any, b: any) => a * b,\n  \"/\": (a: any, b: any) => a / b,\n  \"%\": (a: any, b: any) => a % b,\n\n  // Promise-aware comparison operators\n  // eslint-disable-next-line\n  \"==\": makePromiseAwareBinaryOp((a: any, b: any) => a == b),\n  // eslint-disable-next-line\n  \"!=\": makePromiseAwareBinaryOp((a: any, b: any) => a != b),\n  \">\": makePromiseAwareBinaryOp((a: any, b: any) => a > b),\n  \">=\": makePromiseAwareBinaryOp((a: any, b: any) => a >= b),\n  \"<\": makePromiseAwareBinaryOp((a: any, b: any) => a < b),\n  \"<=\": makePromiseAwareBinaryOp((a: any, b: any) => a <= b),\n  \"!==\": makePromiseAwareBinaryOp((a: any, b: any) => a !== b),\n  \"===\": makePromiseAwareBinaryOp((a: any, b: any) => a === b),\n\n  \"&&\": andandOperator,\n  \"||\": ororOperator,\n\n  // eslint-disable-next-line\n  \"|\": (a: any, b: any) => a | b,\n\n  // eslint-disable-next-line\n  \"&\": (a: any, b: any) => a & b,\n  \"+=\": (a: any, b: any) => a + b,\n  \"-=\": (a: any, b: any) => a - b,\n\n  // eslint-disable-next-line\n  \"&=\": (a: any, b: any) => a & b,\n\n  // eslint-disable-next-line\n  \"|=\": (a: any, b: any) => a | b,\n};\n\nconst DEFAULT_UNARY_OPERATORS: Record<string, UnaryOperator> = {\n  \"-\": (a: any) => -a,\n  \"+\": (a: any) => Number(a),\n  \"!\": makePromiseAwareUnaryOp((a: any) => !a),\n};\n\n/**\n * Higher-order function that makes any binary operation Promise-aware\n */\nfunction makePromiseAwareBinaryOp<T>(\n  operation: (a: any, b: any) => T,\n): (a: any, b: any, async: boolean) => T | Promise<T> {\n  return (a: any, b: any, async: boolean) => {\n    //async handler\n    if (async && (isAwaitable(a) || isAwaitable(b))) {\n      return collateAwaitable([\n        Promise.resolve(a),\n        Promise.resolve(b),\n      ]).awaitableThen(([resolvedA, resolvedB]) =>\n        operation(resolvedA, resolvedB),\n      );\n    }\n    //sync handler\n    return operation(a, b);\n  };\n}\n\n/**\n * Higher-order function that makes any unary operation Promise-aware\n */\nfunction makePromiseAwareUnaryOp<T>(\n  operation: (a: any) => T,\n): (a: any, async: boolean) => T | Promise<T> {\n  return (a: any, async: boolean) => {\n    //async handler\n    if (async && isAwaitable(a)) {\n      return a.awaitableThen((resolved: any) => operation(resolved));\n    }\n    //sync handler\n    return operation(a);\n  };\n}\n\n/**\n * Utility for handling conditional branching with Promises\n */\nfunction handleConditionalBranching(\n  testValue: any,\n  getTrueBranch: () => any,\n  getFalseBranch: () => any,\n  resolveNode: (node: any) => any,\n  async: boolean,\n): any {\n  //async handler\n  if (async && isAwaitable(testValue)) {\n    return testValue.awaitableThen((resolved: boolean) => {\n      const branch = resolved ? getTrueBranch() : getFalseBranch();\n      const branchResult = resolveNode(branch);\n      return isAwaitable(branchResult)\n        ? Promise.resolve(branchResult)\n        : branchResult;\n    });\n  }\n\n  // sync handler\n  const branch = testValue ? getTrueBranch() : getFalseBranch();\n  return resolveNode(branch);\n}\n\n/**\n * Utility for handling collections (arrays/objects) with potential Promises\n */\nconst PromiseCollectionHandler = {\n  /**\n   * Handle array with potential Promise elements\n   */\n  handleArray<T>(items: T[], async: boolean): T[] | Promise<T[]> {\n    if (!async) {\n      return items;\n    }\n    const hasPromises = items.some((item) => isAwaitable(item));\n    return hasPromises ? collateAwaitable(items) : items;\n  },\n\n  /**\n   * Handle object with potential Promise keys/values\n   */\n  handleObject(\n    attributes: Array<{ key: any; value: any }>,\n    resolveNode: (node: any) => any,\n    async: boolean,\n  ): Record<string, any> | Promise<Record<string, any>> {\n    const resolvedAttributes: Record<string, any> = {};\n    const promises: Promise<void>[] = [];\n    let hasPromises = false;\n\n    attributes.forEach((attr) => {\n      const key = resolveNode(attr.key);\n      const value = resolveNode(attr.value);\n\n      //async handler\n      if (async && (isAwaitable(key) || isAwaitable(value))) {\n        hasPromises = true;\n        const keyPromise = Promise.resolve(key);\n        const valuePromise = Promise.resolve(value);\n\n        promises.push(\n          collateAwaitable([keyPromise, valuePromise]).awaitableThen(\n            ([resolvedKey, resolvedValue]) => {\n              resolvedAttributes[resolvedKey] = resolvedValue;\n            },\n          ),\n        );\n      } else {\n        resolvedAttributes[key] = value;\n      }\n    });\n\n    return hasPromises\n      ? collateAwaitable(promises).awaitableThen(() => resolvedAttributes)\n      : resolvedAttributes;\n  },\n};\n\n/**\n * Smart logical operators that handle short-circuiting with Promises\n */\nconst LogicalOperators = {\n  and: (ctx: any, leftNode: any, rightNode: any, async: boolean) => {\n    const leftResult = ctx.evaluate(leftNode);\n\n    if (async && isAwaitable(leftResult)) {\n      return leftResult.awaitableThen((awaitedLeft: any) => {\n        if (!awaitedLeft) return awaitedLeft; // Short circuit\n        const rightResult = ctx.evaluate(rightNode);\n        return isAwaitable(rightResult)\n          ? rightResult\n          : Promise.resolve(rightResult);\n      });\n    }\n\n    // Sync short-circuiting\n    return leftResult && ctx.evaluate(rightNode);\n  },\n\n  or: (ctx: any, leftNode: any, rightNode: any, async: boolean) => {\n    const leftResult = ctx.evaluate(leftNode);\n\n    if (async && isAwaitable(leftResult)) {\n      return leftResult.awaitableThen((awaitedLeft: any) => {\n        if (awaitedLeft) return awaitedLeft; // Short circuit\n        const rightResult = ctx.evaluate(rightNode);\n        return isAwaitable(rightResult)\n          ? rightResult\n          : Promise.resolve(rightResult);\n      });\n    }\n\n    // Sync short-circuiting\n    return leftResult || ctx.evaluate(rightNode);\n  },\n};\n\nexport interface HookOptions extends ExpressionContext {\n  /** Given an expression node  */\n  resolveNode: (node: ExpressionNode) => any;\n\n  /** Enabling this flag skips calling the onError hook, and just throws errors back to the caller.\n   * The caller is responsible for handling the error.\n   */\n  throwErrors?: boolean;\n\n  /** Whether expressions should be parsed strictly or not */\n  strict?: boolean;\n\n  /** Whether the expression should be evaluated asynchronously */\n  async?: boolean;\n}\n\nexport type ExpressionEvaluatorOptions = Omit<\n  HookOptions,\n  \"resolveNode\" | \"evaluate\"\n>;\n\nexport type ExpressionEvaluatorFunction = (\n  exp: ExpressionType,\n  options?: ExpressionEvaluatorOptions,\n) => any;\n\n/**\n * The expression evaluator is responsible for parsing and executing anything in the custom expression language\n * */\nexport class ExpressionEvaluator {\n  private readonly vars: Record<string, any> = {};\n  public readonly hooks: {\n    resolve: SyncWaterfallHook<[any, ExpressionNode, HookOptions]>;\n    resolveOptions: SyncWaterfallHook<[HookOptions]>;\n    beforeEvaluate: SyncWaterfallHook<[ExpressionType, HookOptions]>;\n    onError: SyncBailHook<[Error], true>;\n  } = {\n    /** Resolve an AST node for an expression to a value */\n    resolve: new SyncWaterfallHook<[any, ExpressionNode, HookOptions]>(),\n    /** Gets the options that will be passed in calls to the resolve hook */\n    resolveOptions: new SyncWaterfallHook<[HookOptions]>(),\n    /** Allows users to change the expression to be evaluated before processing */\n    beforeEvaluate: new SyncWaterfallHook<[ExpressionType, HookOptions]>(),\n    /**\n     * An optional means of handling an error in the expression execution\n     * Return true if handled, to stop propagation of the error\n     */\n    onError: new SyncBailHook<[Error], true>(),\n  };\n\n  private readonly expressionsCache: Map<string, ExpressionNode> = new Map();\n\n  private readonly defaultHookOptions: HookOptions;\n\n  public readonly operators: {\n    binary: Map<string, BinaryOperator>;\n    unary: Map<string, UnaryOperator>;\n    expressions: Map<string, ExpressionHandler<any, any>>;\n  } = {\n    binary: new Map<string, BinaryOperator>(\n      Object.entries(DEFAULT_BINARY_OPERATORS),\n    ),\n    unary: new Map<string, UnaryOperator>(\n      Object.entries(DEFAULT_UNARY_OPERATORS),\n    ),\n    expressions: new Map<string, ExpressionHandler<any, any>>([\n      ...Object.entries(DEFAULT_EXPRESSION_HANDLERS),\n      [\"await\", DEFAULT_EXPRESSION_HANDLERS.waitFor],\n    ]),\n  };\n\n  public reset(): void {\n    this.expressionsCache.clear();\n  }\n\n  constructor(defaultOptions: ExpressionEvaluatorOptions) {\n    this.defaultHookOptions = {\n      ...defaultOptions,\n      evaluate: (expr) => this.evaluate(expr, this.defaultHookOptions),\n      resolveNode: (node: ExpressionNode) =>\n        this._execAST(node, this.defaultHookOptions),\n    };\n\n    this.hooks.resolve.tap(\"ExpressionEvaluator\", (result, node, options) => {\n      return this._resolveNode(result, node, options);\n    });\n    this.evaluate = this.evaluate.bind(this);\n  }\n\n  public evaluate(\n    expr: ExpressionType,\n    options?: ExpressionEvaluatorOptions,\n  ): any {\n    const resolvedOpts = this.hooks.resolveOptions.call({\n      ...this.defaultHookOptions,\n      ...options,\n      resolveNode: (node: ExpressionNode) => this._execAST(node, resolvedOpts),\n    });\n\n    let expression = this.hooks.beforeEvaluate.call(expr, resolvedOpts) ?? expr;\n\n    // Unwrap any returned expression type\n    // Since this could also be an object type, we need to recurse through it until we find the end\n    while (isObjectExpression(expression)) {\n      expression = expression.value;\n    }\n\n    // Check for literals\n    if (\n      typeof expression === \"number\" ||\n      typeof expression === \"boolean\" ||\n      expression === undefined ||\n      expression === null\n    ) {\n      return expression;\n    }\n\n    // Skip doing anything with objects that are _actually_ just parsed expression nodes\n    if (isExpressionNode(expression)) {\n      return this._execAST(expression, resolvedOpts);\n    }\n\n    if (Array.isArray(expression)) {\n      return expression.reduce(\n        (_nothing, exp) => this.evaluate(exp, options),\n        null,\n      );\n    }\n\n    return this._execString(String(expression), resolvedOpts);\n  }\n\n  /**\n   * Evaluate functions in an async context\n   * @experimental These Player APIs are in active development and may change. Use with caution\n   */\n  public evaluateAsync(\n    expr: ExpressionType,\n    options?: ExpressionEvaluatorOptions,\n  ): Promise<any> {\n    // handle async expression block\n    if (Array.isArray(expr)) {\n      return collateAwaitable(\n        expr.map(async (exp) =>\n          this.evaluate(exp, { ...options, async: true } as any),\n        ),\n      ).awaitableThen((values) => {\n        return values.pop();\n      });\n    } else {\n      return this.evaluate(expr, { ...options, async: true } as any);\n    }\n  }\n\n  public addExpressionFunction<T extends readonly unknown[], R>(\n    name: string,\n    handler: ExpressionHandler<T, R>,\n  ): void {\n    this.operators.expressions.set(name, handler);\n  }\n\n  public addBinaryOperator(operator: string, handler: BinaryOperator): void {\n    this.operators.binary.set(operator, handler);\n  }\n\n  public addUnaryOperator(operator: string, handler: UnaryOperator): void {\n    this.operators.unary.set(operator, handler);\n  }\n\n  public setExpressionVariable(name: string, value: unknown): void {\n    this.vars[name] = value;\n  }\n\n  public getExpressionVariable(name: string): unknown {\n    return this.vars[name];\n  }\n\n  private _execAST(node: ExpressionNode, options: HookOptions): any {\n    return this.hooks.resolve.call(undefined, node, options);\n  }\n\n  private _execString(exp: string, options: HookOptions) {\n    if (exp === \"\") {\n      return exp;\n    }\n\n    const matches = exp.match(/^@\\[(.*)\\]@$/);\n    let matchedExp = exp;\n    if (matches) {\n      const [, matched] = Array.from(matches); // In case the expression was surrounded by @[ ]@\n      if (matched) {\n        matchedExp = matched;\n      }\n    }\n\n    let storedAST: ExpressionNode;\n\n    try {\n      storedAST =\n        this.expressionsCache.get(matchedExp) ??\n        parseExpression(matchedExp, { strict: options.strict });\n      this.expressionsCache.set(matchedExp, storedAST);\n    } catch (e: any) {\n      if (options.throwErrors || !this.hooks.onError.call(e)) {\n        // Only throw the error if it's not handled by the hook, or throwErrors is true\n        throw new NestedError(`Error parsing expression: ${exp}`, e);\n      }\n\n      return;\n    }\n\n    try {\n      return this._execAST(storedAST, options);\n    } catch (e: any) {\n      if (options.throwErrors || !this.hooks.onError.call(e)) {\n        // Only throw the error if it's not handled by the hook, or throwErrors is true\n        throw new NestedError(`Error evaluating expression: ${exp}`, e);\n      }\n    }\n  }\n\n  private _resolveNode(\n    _currentValue: any,\n    node: ExpressionNode,\n    options: HookOptions,\n  ): unknown {\n    const { resolveNode, model } = options;\n    const isAsync = options.async ?? false;\n\n    const expressionContext: ExpressionContext = {\n      ...options,\n      evaluate: (expr) => this.evaluate(expr, options),\n    };\n\n    if (node.type === \"Literal\") {\n      return node.value;\n    }\n\n    if (node.type === \"Identifier\") {\n      return this.vars[node.name];\n    }\n\n    if (node.type === \"Compound\" || node.type === \"ThisExpression\") {\n      throw new Error(`Expression type: ${node.type} is not supported`);\n    }\n\n    if (node.type === \"BinaryExpression\" || node.type === \"LogicalExpression\") {\n      const operator = this.operators.binary.get(node.operator);\n\n      if (operator) {\n        if (\"resolveParams\" in operator) {\n          if (operator.resolveParams === false) {\n            return operator(expressionContext, node.left, node.right, isAsync);\n          }\n\n          const left = resolveNode(node.left);\n          const right = resolveNode(node.right);\n\n          // Handle promises in binary operations\n          if (options.async && (isAwaitable(left) || isAwaitable(right))) {\n            return collateAwaitable([left, right]).awaitableThen(\n              ([leftVal, rightVal]) =>\n                operator(expressionContext, leftVal, rightVal, isAsync),\n            );\n          }\n\n          return operator(expressionContext, left, right, isAsync);\n        }\n\n        const left = resolveNode(node.left);\n        const right = resolveNode(node.right);\n\n        if (options.async && (isAwaitable(left) || isAwaitable(right))) {\n          return collateAwaitable([left, right]).awaitableThen(\n            ([leftVal, rightVal]) => operator(leftVal, rightVal, isAsync),\n          );\n        }\n\n        return operator(left, right, isAsync);\n      }\n\n      return;\n    }\n\n    if (node.type === \"UnaryExpression\") {\n      const operator = this.operators.unary.get(node.operator);\n\n      if (operator) {\n        if (\"resolveParams\" in operator) {\n          if (operator.resolveParams === false) {\n            return operator(expressionContext, node.argument, isAsync);\n          }\n\n          const arg = resolveNode(node.argument);\n\n          if (options.async && isAwaitable(arg)) {\n            return arg.awaitableThen((argVal) =>\n              operator(expressionContext, argVal, isAsync),\n            );\n          }\n\n          return operator(expressionContext, arg, isAsync);\n        }\n\n        const arg = resolveNode(node.argument);\n\n        if (options.async && isAwaitable(arg)) {\n          return arg.awaitableThen((argVal) => operator(argVal, isAsync));\n        }\n\n        return operator(arg, isAsync);\n      }\n\n      return;\n    }\n\n    if (node.type === \"Object\") {\n      return PromiseCollectionHandler.handleObject(\n        node.attributes,\n        resolveNode,\n        options.async || false,\n      );\n    }\n\n    if (node.type === \"CallExpression\") {\n      const expressionName = node.callTarget.name;\n\n      const operator = this.operators.expressions.get(expressionName);\n\n      if (!operator) {\n        throw new Error(`Unknown expression function: ${expressionName}`);\n      }\n\n      if (\n        operator.name === DEFAULT_EXPRESSION_HANDLERS.waitFor.name &&\n        !options.async\n      ) {\n        throw new Error(\"Usage of await outside of async context\");\n      }\n\n      if (\"resolveParams\" in operator && operator.resolveParams === false) {\n        return operator(expressionContext, ...node.args);\n      }\n\n      const args = node.args.map((n) => resolveNode(n));\n\n      // Check if any arguments are promises\n      if (options.async) {\n        const hasPromises = args.some(isAwaitable);\n\n        if (hasPromises) {\n          return collateAwaitable(args).awaitableThen((resolvedArgs) =>\n            operator(expressionContext, ...resolvedArgs),\n          );\n        }\n      }\n\n      return operator(expressionContext, ...args);\n    }\n\n    if (node.type === \"ModelRef\") {\n      return model.get(node.ref, { context: { model: options.model } });\n    }\n\n    if (node.type === \"MemberExpression\") {\n      const obj = resolveNode(node.object);\n      const prop = resolveNode(node.property);\n\n      if (options.async && (isAwaitable(obj) || isAwaitable(prop))) {\n        return collateAwaitable([obj, prop]).awaitableThen(\n          ([objVal, propVal]) => objVal[propVal],\n        );\n      }\n\n      return obj[prop];\n    }\n\n    if (node.type === \"Assignment\") {\n      if (node.left.type === \"ModelRef\") {\n        const value = resolveNode(node.right);\n\n        if (isPromiseLike(value)) {\n          if (options.async && isAwaitable(value)) {\n            return value.awaitableThen((resolvedValue) => {\n              model.set([[(node.left as any).ref, resolvedValue]]);\n              return resolvedValue;\n            });\n          } else {\n            options.logger?.warn(\n              \"Unawaited promise written to mode, this behavior is undefined and may change in future releases\",\n            );\n          }\n        }\n\n        model.set([[(node.left as any).ref, value]]);\n        return value;\n      }\n\n      if (node.left.type === \"Identifier\") {\n        const value = resolveNode(node.right);\n\n        if (options.async && isAwaitable(value)) {\n          return value.awaitableThen((resolvedValue) => {\n            this.vars[(node.left as any).name] = resolvedValue;\n            return resolvedValue;\n          });\n        }\n\n        this.vars[(node.left as any).name] = value;\n        return value;\n      }\n\n      return;\n    }\n\n    if (node.type === \"ConditionalExpression\") {\n      const testResult = resolveNode(node.test);\n\n      return handleConditionalBranching(\n        testResult,\n        () => node.consequent,\n        () => node.alternate,\n        resolveNode,\n        isAsync,\n      );\n    }\n\n    if (node.type === \"ArrayExpression\") {\n      const results = node.elements.map((ele) => resolveNode(ele));\n      return PromiseCollectionHandler.handleArray(results, isAsync);\n    }\n\n    if (node.type === \"Modification\") {\n      const operation = this.operators.binary.get(node.operator);\n\n      if (operation) {\n        let newValue;\n\n        if (\"resolveParams\" in operation) {\n          if (operation.resolveParams === false) {\n            newValue = operation(\n              expressionContext,\n              node.left,\n              node.right,\n              isAsync,\n            );\n          } else {\n            const left = resolveNode(node.left);\n            const right = resolveNode(node.right);\n\n            if (options.async && (isAwaitable(left) || isAwaitable(right))) {\n              newValue = collateAwaitable([left, right]).awaitableThen(\n                ([leftVal, rightVal]) =>\n                  operation(expressionContext, leftVal, rightVal, isAsync),\n              );\n            } else {\n              newValue = operation(expressionContext, left, right, isAsync);\n            }\n          }\n        } else {\n          const left = resolveNode(node.left);\n          const right = resolveNode(node.right);\n\n          if (options.async && (isAwaitable(left) || isAwaitable(right))) {\n            newValue = collateAwaitable([left, right]).awaitableThen(\n              ([leftVal, rightVal]) => operation(leftVal, rightVal, isAsync),\n            );\n          } else {\n            newValue = operation(left, right, isAsync);\n          }\n        }\n\n        if (node.left.type === \"ModelRef\") {\n          if (options.async && isAwaitable(newValue)) {\n            return newValue.awaitableThen((resolvedValue) => {\n              model.set([[(node.left as any).ref, resolvedValue]]);\n              return resolvedValue;\n            });\n          }\n          model.set([[(node.left as any).ref, newValue]]);\n        } else if (node.left.type === \"Identifier\") {\n          if (options.async && isAwaitable(newValue)) {\n            return newValue.awaitableThen((resolvedValue) => {\n              this.vars[(node.left as any).name] = resolvedValue;\n              return resolvedValue;\n            });\n          }\n          this.vars[(node.left as any).name] = newValue;\n        }\n\n        return newValue;\n      }\n\n      return resolveNode(node.left);\n    }\n  }\n}\n","import type { DataModelWithParser } from \"../data\";\nimport type { Logger } from \"../logger\";\n\nexport type ExpressionObjectType = {\n  /** The expression to eval */\n  value: BasicExpressionTypes;\n};\n\nexport type ExpressionLiteralType =\n  | string\n  | number\n  | boolean\n  | undefined\n  | null;\n\nexport type BasicExpressionTypes =\n  | ExpressionLiteralType\n  | ExpressionObjectType\n  | Array<ExpressionLiteralType | ExpressionObjectType>;\n\nexport type ExpressionType = BasicExpressionTypes | ExpressionNode;\n\nexport interface OperatorProcessingOptions {\n  /**\n   * When set to a falsy value, the arguments passed to the handler will be raw AST Nodes\n   * This enables lazy evaluation of arguments\n   */\n  resolveParams: boolean;\n\n  /**\n   * Whether the expression should be allowed to be evaluated asynchronously\n   */\n  async?: boolean;\n}\n\nexport type BinaryOperatorBasic = (\n  left: any,\n  right: any,\n  async: boolean,\n) => unknown;\nexport type BinaryOperatorAdvanced = OperatorProcessingOptions &\n  ((ctx: ExpressionContext, left: any, right: any, async: boolean) => unknown);\n\nexport type BinaryOperator = BinaryOperatorAdvanced | BinaryOperatorBasic;\n\nexport type UnaryOperator =\n  | ((arg: any, async: boolean) => unknown)\n  | (((ctx: ExpressionContext, arg: any, async: boolean) => unknown) &\n      OperatorProcessingOptions);\n\nexport interface ExpressionContext {\n  /** A means of executing an expression */\n  evaluate: (expr: ExpressionType) => unknown;\n\n  /** The data model that expression handlers can use when fetching data */\n  model: DataModelWithParser;\n\n  /** A logger to use */\n  logger?: Logger;\n}\n\nexport type ExpressionHandler<\n  T extends readonly unknown[] = unknown[],\n  R = void,\n> = ((context: ExpressionContext, ...args: T) => R) &\n  Partial<OperatorProcessingOptions>;\n\nexport const ExpNodeOpaqueIdentifier: unique symbol =\n  Symbol(\"Expression Node ID\");\n\n/** Checks if the input is an already processed Expression node */\nexport function isExpressionNode(x: any): x is ExpressionNode {\n  return (\n    typeof x === \"object\" &&\n    x !== null &&\n    !Array.isArray(x) &&\n    x.__id === ExpNodeOpaqueIdentifier\n  );\n}\n\nexport interface NodePosition {\n  /** The character location */\n  character: number;\n}\n\nexport interface NodeLocation {\n  // We only care about the character offset, not the line/column for now\n  // But making these objects allows us to add more (like line number) later\n\n  /** The start of the node */\n  start: NodePosition;\n\n  /** The end of the node */\n  end: NodePosition;\n}\n\nexport interface BaseNode<T> {\n  /** The thing to discriminate the AST type on */\n  type: T;\n\n  /** How to tell this apart from other objects */\n  __id: typeof ExpNodeOpaqueIdentifier;\n\n  /** The location of the node in the source expression string */\n  location?: NodeLocation;\n\n  /**\n   * The error that occurred while parsing this node\n   * This is only set if the parsing mode is set to non-strict\n   */\n  error?: Error;\n}\n\n/** A helper interface for nodes that container left and right children */\nexport interface DirectionalNode {\n  /** The left node. Often for the left hand side of an expression */\n  left: ExpressionNode;\n\n  /** The right child. Often for the right hand side of an expression */\n  right: ExpressionNode;\n}\n\nexport interface LiteralNode extends BaseNode<\"Literal\"> {\n  /** A node that holds a literal value */\n  value: string | number;\n\n  /** The unprocessed value */\n  raw?: any;\n}\n\nexport interface BinaryNode\n  extends BaseNode<\"BinaryExpression\">,\n    DirectionalNode {\n  /** The operation to perform on the nodes */\n  operator: string;\n}\n\nexport interface LogicalNode\n  extends BaseNode<\"LogicalExpression\">,\n    DirectionalNode {\n  /** The logical operation to perform on the nodes */\n  operator: string;\n}\n\nexport interface UnaryNode extends BaseNode<\"UnaryExpression\"> {\n  /** The operation to perform on the node */\n  operator: string;\n\n  /** The single argument that the operation should be performed on */\n  argument: ExpressionNode;\n}\n\nexport type ThisNode = BaseNode<\"ThisExpression\">;\n\nexport interface ModelRefNode extends BaseNode<\"ModelRef\"> {\n  /** The binding that the model reference points to */\n  ref: string;\n}\n\nexport interface ObjectNode extends BaseNode<\"Object\"> {\n  /**  */\n  attributes: Array<{\n    /** The property name of the object */\n    key: ExpressionNode;\n\n    /** the associated value */\n    value: ExpressionNode;\n  }>;\n}\n\nexport interface MemberExpressionNode extends BaseNode<\"MemberExpression\"> {\n  /** The object to be introspected */\n  object: ExpressionNode;\n\n  /** If the property uses . or open-bracket */\n  computed: boolean;\n\n  /** The property to access on the object */\n  property: ExpressionNode;\n}\n\nexport interface ConditionalExpressionNode\n  extends BaseNode<\"ConditionalExpression\"> {\n  /** The test for the ternary */\n  test: ExpressionNode;\n\n  /** The truthy case for the ternary */\n  consequent: ExpressionNode;\n\n  /** The falsy case for the ternary */\n  alternate: ExpressionNode;\n}\n\nexport interface CompoundNode extends BaseNode<\"Compound\"> {\n  /** The contents of the compound expression */\n  body: ExpressionNode[];\n}\n\nexport interface CallExpressionNode extends BaseNode<\"CallExpression\"> {\n  /** The arguments to the function */\n  args: ExpressionNode[];\n\n  /** The function name */\n  callTarget: IdentifierNode;\n}\n\nexport interface ArrayExpressionNode extends BaseNode<\"ArrayExpression\"> {\n  /** The items in an array */\n  elements: ExpressionNode[];\n}\n\nexport interface IdentifierNode extends BaseNode<\"Identifier\"> {\n  /** The variable name */\n  name: string;\n}\n\nexport type AssignmentNode = BaseNode<\"Assignment\"> & DirectionalNode;\n\nexport interface ModificationNode\n  extends BaseNode<\"Modification\">,\n    DirectionalNode {\n  /** The operator for the modification */\n  operator: string;\n}\n\nexport type ExpressionNode =\n  | LiteralNode\n  | BinaryNode\n  | LogicalNode\n  | UnaryNode\n  | ThisNode\n  | ModelRefNode\n  | MemberExpressionNode\n  | ConditionalExpressionNode\n  | CompoundNode\n  | CallExpressionNode\n  | ArrayExpressionNode\n  | IdentifierNode\n  | AssignmentNode\n  | ModificationNode\n  | ObjectNode;\n\nexport type ExpressionNodeType = ExpressionNode[\"type\"];\n\nexport interface ErrorWithLocation extends Error {\n  /** The place in the string where the error occurs */\n  index: number;\n\n  /** a helpful description */\n  description: string;\n}\n","/**\n * An expression to AST parser based on JSEP: http://jsep.from.so/\n */\nimport type {\n  ErrorWithLocation,\n  ExpressionNode,\n  ExpressionNodeType,\n  NodeLocation,\n} from \"./types\";\nimport { ExpNodeOpaqueIdentifier } from \"./types\";\n\nconst PERIOD_CODE = 46; // '.'\nconst COMMA_CODE = 44; // ','\nconst SQUOTE_CODE = 39; // Single quote\nconst DQUOTE_CODE = 34; // Double quotes\nconst OPAREN_CODE = 40; // (\nconst CPAREN_CODE = 41; // )\nconst OBRACK_CODE = 91; // [\nconst CBRACK_CODE = 93; // ]\nconst QUMARK_CODE = 63; // ?\nconst SEMCOL_CODE = 59; // ;\nconst COLON_CODE = 58; // :\nconst OCURL_CODE = 123; // {\nconst CCURL_CODE = 125; // }\n\n// Operations\n// ----------\n\n// Set `t` to `true` to save space (when minified, not gzipped)\nconst t = true;\n\n// Use a quickly-accessible map to store all of the unary operators\n// Values are set to `true` (it really doesn't matter)\nconst unaryOps = { \"-\": t, \"!\": t, \"~\": t, \"+\": t };\n\n// Also use a map for the binary operations but set their values to their\n// binary precedence for quick reference:\n// see [Operator precedence](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence)\nconst binaryOps: Record<string, number> = {\n  \"=\": 3,\n  \"+=\": 3,\n  \"-=\": 3,\n  \"&=\": 3,\n  \"|=\": 3,\n  // Conditional: 4,\n  \"||\": 5,\n  \"&&\": 6,\n  \"|\": 7,\n  \"^\": 8,\n  \"&\": 9,\n  \"==\": 10,\n  \"!=\": 10,\n  \"===\": 10,\n  \"!==\": 10,\n  \"<\": 11,\n  \">\": 11,\n  \"<=\": 11,\n  \">=\": 11,\n  \"<<\": 12,\n  \">>\": 12,\n  \">>>\": 12,\n  \"+\": 13,\n  \"-\": 13,\n  \"*\": 14,\n  \"/\": 14,\n  \"%\": 14,\n};\n\n/** Wrap the message and index in an error and throw it */\nfunction throwError(message: string, index: number): ErrorWithLocation {\n  const err = new Error(`${message} at character ${index}`);\n\n  (err as ErrorWithLocation).index = index;\n  (err as ErrorWithLocation).description = message;\n\n  throw err;\n}\n\n/** Create a new location marker that spans both nodes */\nfunction createSpanningLocation(start?: NodeLocation, end?: NodeLocation) {\n  if (!start || !end) {\n    return;\n  }\n\n  return {\n    start: start.start,\n    end: end.end,\n  };\n}\n\n/** Get return the longest key length of any object */\nfunction getMaxKeyLen(obj: object): number {\n  let maxLen = 0;\n\n  Object.keys(obj).forEach((key) => {\n    if (key.length > maxLen && Object.prototype.hasOwnProperty.call(obj, key)) {\n      maxLen = key.length;\n    }\n  });\n\n  return maxLen;\n}\n\nconst maxUnopLen = getMaxKeyLen(unaryOps);\nconst maxBinopLen = getMaxKeyLen(binaryOps);\n\n// Literals\n// ----------\n// Store the values to return for the various literals we may encounter\nconst literals = {\n  true: true,\n  false: false,\n  null: null,\n  undefined,\n} as const;\n\n// Except for `this`, which is special. This could be changed to something like `'self'` as well\nconst thisStr = \"this\";\n\n/** Returns the precedence of a binary operator or `0` if it isn't a binary operator */\nfunction binaryPrecedence(opVal: string): number {\n  return binaryOps[opVal] || 0;\n}\n\n/**\n * Utility function (gets called from multiple places)\n * Also note that `a && b` and `a || b` are *logical* expressions, not binary expressions\n */\nfunction createBinaryExpression(\n  operator: string | boolean,\n  left: string,\n  right: string,\n  location?: NodeLocation,\n) {\n  let type: ExpressionNodeType;\n\n  if (operator === \"||\" || operator === \"&&\") {\n    type = \"LogicalExpression\";\n  } else if (operator === \"=\") {\n    type = \"Assignment\";\n  } else if (\n    operator === \"+=\" ||\n    operator === \"-=\" ||\n    operator === \"&=\" ||\n    operator === \"|=\"\n  ) {\n    type = \"Modification\";\n  } else {\n    type = \"BinaryExpression\";\n  }\n\n  return {\n    __id: ExpNodeOpaqueIdentifier,\n    type,\n    operator,\n    left,\n    right,\n    location,\n  };\n}\n\n/** `ch` is a character code in the next three functions */\nfunction isDecimalDigit(ch: number) {\n  return ch >= 48 && ch <= 57; // 0...9\n}\n\n/** Check if the char is the character code for the start of an identifier */\nfunction isIdentifierStart(ch: number) {\n  return (\n    ch === 36 ||\n    ch === 95 || // `$` and `_`\n    (ch >= 65 && ch <= 90) || // A...Z\n    (ch >= 97 && ch <= 122)\n  ); // A...z\n}\n\n/** Check if the char code is still a valid identifier portion */\nfunction isIdentifierPart(ch: number) {\n  return (\n    ch === 36 ||\n    ch === 95 || // `$` and `_`\n    (ch >= 65 && ch <= 90) || // A...Z\n    (ch >= 97 && ch <= 122) || // A...z\n    (ch >= 48 && ch <= 57)\n  ); // 0...9\n}\n\n/** Check if the 2 chars are the start of a model reference */\nfunction isModelRefStart(ch0: number, ch1: number) {\n  return ch0 === OCURL_CODE && ch1 === OCURL_CODE; // '{{'\n}\n\n/** Parse out an expression from the string */\nexport function parseExpression(\n  expr: string,\n  options?: {\n    /** If true (the default), will throw on invalid expressions */\n    strict?: boolean;\n  },\n): ExpressionNode {\n  const strictMode = options?.strict ?? true;\n\n  // `index` stores the character number we are currently at while `length` is a constant\n  // All of the gobbles below will modify `index` as we move along\n  const charAtFunc = expr.charAt;\n  const charCodeAtFunc = expr.charCodeAt;\n  const { length } = expr;\n\n  let index = 0;\n\n  /** Create a location object  */\n  const getLocation = (startChar: number) => {\n    return {\n      start: {\n        character: startChar,\n      },\n      end: {\n        character: index,\n      },\n    };\n  };\n\n  /** Grab the char at the index from the expression */\n  function exprI(i: number) {\n    return charAtFunc.call(expr, i);\n  }\n\n  /** Grab the unicode char at the index in the expression */\n  function exprICode(i: number) {\n    return charCodeAtFunc.call(expr, i);\n  }\n\n  /**\n   * Gobble an object and store the object in an attributes array\n   */\n  function gobbleObjects() {\n    const attributes: Array<{\n      /** The property name of the object */\n      key: any;\n\n      /** the associated value */\n      value: any;\n    }> = [];\n    let closed = false;\n\n    let shouldDefineKey = true;\n    let key;\n    let value;\n    let chCode;\n    const startCharIndex = index;\n\n    // get rid of OCURL_CODE\n    ++index;\n\n    while (index < length) {\n      gobbleSpaces();\n      chCode = exprICode(index);\n      // check for end\n      if (chCode === CCURL_CODE) {\n        // if we are at the end but a key was defined\n        if (key) {\n          throwError(\"A key was defined but a value was not\", index);\n        }\n\n        index++;\n        closed = true;\n        break;\n      } else if (shouldDefineKey) {\n        // check for key\n        if (chCode !== SQUOTE_CODE && chCode !== DQUOTE_CODE) {\n          throwError(\"An object must start wtih a key\", index);\n        }\n\n        // get key\n        key = gobbleStringLiteral();\n        // remove spaces\n        gobbleSpaces();\n        // remove colon\n        if (exprICode(index) === COLON_CODE) {\n          index++;\n          shouldDefineKey = false;\n        } else {\n          throwError(\"A colon must follow an object key\", index);\n        }\n      } else {\n        value = gobbleExpression();\n\n        attributes.push({ key, value });\n        gobbleSpaces();\n        chCode = exprICode(index);\n        if (chCode === COMMA_CODE) {\n          index++;\n        } else if (chCode !== CCURL_CODE) {\n          throwError(\"Please add a comma to add another key\", index);\n        }\n\n        shouldDefineKey = true;\n        key = undefined;\n        value = undefined;\n      }\n\n      chCode = exprICode(index);\n    }\n\n    // throw error if object is not closed\n    if (!closed) {\n      throwError(`Unclosed brace in object`, index);\n    }\n\n    return {\n      __id: ExpNodeOpaqueIdentifier,\n      type: \"Object\",\n      attributes,\n      location: getLocation(startCharIndex),\n    };\n  }\n\n  /**\n   * Push `index` up to the next non-space character\n   */\n  function gobbleSpaces() {\n    let ch = exprICode(index);\n    // Space or tab\n    while (ch === 32 || ch === 9) {\n      ch = exprICode(++index);\n    }\n  }\n\n  /**\n   * The main parsing function. Much of this code is dedicated to ternary expressions\n   */\n  function gobbleExpression(): ExpressionNode {\n    const test = gobbleBinaryExpression();\n    gobbleSpaces();\n    const startCharIndex = index;\n\n    if (index < length && exprICode(index) === QUMARK_CODE) {\n      // Ternary expression: test ? consequent : alternate\n      index++;\n      const consequent = gobbleExpression();\n\n      if (!consequent) {\n        throwError(\"Expected expression\", index);\n      }\n\n      gobbleSpaces();\n\n      if (exprICode(index) === COLON_CODE) {\n        index++;\n        const alternate = gobbleExpression();\n\n        if (!alternate) {\n          throwError(\"Expected expression\", index);\n        }\n\n        return {\n          __id: ExpNodeOpaqueIdentifier,\n          type: \"ConditionalExpression\",\n          test,\n          consequent,\n          alternate,\n          location: getLocation(startCharIndex),\n        };\n      }\n\n      throwError(\"Expected :\", index);\n    }\n\n    return test;\n  }\n\n  /**\n   * Search for the operation portion of the string (e.g. `+`, `===`)\n   * Start by taking the longest possible binary operations (3 characters: `===`, `!==`, `>>>`)\n   * and move down from 3 to 2 to 1 character until a matching binary operation is found\n   * then, return that binary operation\n   */\n  function gobbleBinaryOp() {\n    gobbleSpaces();\n\n    let toCheck = expr.substr(index, maxBinopLen);\n    let tcLen = toCheck.length;\n\n    while (tcLen > 0) {\n      if (Object.prototype.hasOwnProperty.call(binaryOps, toCheck)) {\n        index += tcLen;\n        return toCheck;\n      }\n\n      toCheck = toCheck.substr(0, --tcLen);\n    }\n\n    return false;\n  }\n\n  /**\n   * This function is responsible for gobbling an individual expression,\n   * e.g. `1`, `1+2`, `a+(b*2)-Math.sqrt(2)`\n   */\n  function gobbleBinaryExpression() {\n    let node;\n    let prec;\n    let i;\n\n    // First, try to get the leftmost thing\n    // Then, check to see if there's a binary operator operating on that leftmost thing\n    let left = gobbleToken();\n    let biop = gobbleBinaryOp();\n\n    // If there wasn't a binary operator, just return the leftmost node\n    if (!biop) {\n      return left;\n    }\n\n    // Otherwise, we need to start a stack to properly place the binary operations in their\n    // precedence structure\n    let biopInfo = { value: biop, prec: binaryPrecedence(biop) };\n    let right = gobbleToken();\n\n    if (!right) {\n      throwError(`Expected expression after ${biop}`, index);\n    }\n\n    const stack = [left, biopInfo, right];\n\n    // Properly deal with precedence using [recursive descent](http://www.engr.mun.ca/~theo/Misc/exp_parsing.htm)\n    biop = gobbleBinaryOp();\n    while (biop) {\n      prec = binaryPrecedence(biop);\n\n      if (prec === 0) {\n        break;\n      }\n\n      biopInfo = { value: biop, prec };\n\n      // Reduce: make a binary expression from the three topmost entries.\n      while (stack.length > 2 && prec <= stack[stack.length - 2].prec) {\n        right = stack.pop();\n        biop = stack.pop().value;\n        left = stack.pop();\n        node = createBinaryExpression(\n          biop,\n          left,\n          right,\n          createSpanningLocation(left.location, right.location),\n        );\n        stack.push(node);\n      }\n\n      node = gobbleToken();\n\n      if (!node) {\n        throwError(`Expected expression after ${biop}`, index);\n      }\n\n      stack.push(biopInfo, node);\n      biop = gobbleBinaryOp();\n    }\n\n    i = stack.length - 1;\n    node = stack[i];\n\n    while (i > 1) {\n      node = createBinaryExpression(\n        stack[i - 1].value,\n        stack[i - 2],\n        node,\n        createSpanningLocation(stack[i - 2].location, node.location),\n      );\n      i -= 2;\n    }\n\n    return node;\n  }\n\n  /**\n   * An individual part of a binary expression:\n   * e.g. `foo.bar(baz)`, `1`, `\"abc\"`, `(a % 2)` (because it's in parenthesis)\n   */\n  function gobbleToken(): any {\n    gobbleSpaces();\n    const ch = exprICode(index);\n    const startCharIndex = index;\n\n    if (isDecimalDigit(ch) || ch === PERIOD_CODE) {\n      // Char code 46 is a dot `.` which can start off a numeric literal\n      return gobbleNumericLiteral();\n    }\n\n    if (ch === SQUOTE_CODE || ch === DQUOTE_CODE) {\n      // Single or double quotes\n      return gobbleStringLiteral();\n    }\n\n    if (isIdentifierStart(ch) || ch === OPAREN_CODE) {\n      // Open parenthesis\n      // `foo`, `bar.baz`\n      return gobbleVariable();\n    }\n\n    if (ch === OBRACK_CODE) {\n      return gobbleArray();\n    }\n\n    if (isModelRefStart(ch, exprICode(index + 1))) {\n      return gobbleModelRef();\n    }\n\n    // not a double bracket: {{}} but if its a single {}\n    if (ch === OCURL_CODE) {\n      return gobbleObjects();\n    }\n\n    let toCheck = expr.substr(index, maxUnopLen);\n    let tcLen = toCheck.length;\n\n    while (tcLen > 0) {\n      if (Object.prototype.hasOwnProperty.call(unaryOps, toCheck)) {\n        index += tcLen;\n        return {\n          __id: ExpNodeOpaqueIdentifier,\n          type: \"UnaryExpression\",\n          operator: toCheck,\n          argument: gobbleToken(),\n          prefix: true,\n          location: getLocation(startCharIndex),\n        };\n      }\n\n      toCheck = toCheck.substr(0, --tcLen);\n    }\n\n    return false;\n  }\n\n  /**\n   * Parse simple numeric literals: `12`, `3.4`, `.5`. Do this by using a string to\n   * keep track of everything in the numeric literal and then calling `parseFloat` on that string\n   */\n  function gobbleNumericLiteral() {\n    let num = \"\";\n    const startCharIndex = index;\n\n    while (isDecimalDigit(exprICode(index))) {\n      num += exprI(index++);\n    }\n\n    if (exprICode(index) === PERIOD_CODE) {\n      // Can start with a decimal marker\n      num += exprI(index++);\n\n      while (isDecimalDigit(exprICode(index))) {\n        num += exprI(index++);\n      }\n    }\n\n    let ch = exprI(index);\n    if (ch === \"e\" || ch === \"E\") {\n      // Exponent marker\n      num += exprI(index++);\n      ch = exprI(index);\n\n      if (ch === \"+\" || ch === \"-\") {\n        // Exponent sign\n        num += exprI(index++);\n      }\n\n      while (isDecimalDigit(exprICode(index))) {\n        // Exponent itself\n        num += exprI(index++);\n      }\n\n      if (!isDecimalDigit(exprICode(index - 1))) {\n        throwError(`Expected exponent (${num}${exprI(index)})`, index);\n      }\n    }\n\n    const chCode = exprICode(index);\n    // Check to make sure this isn't a variable name that start with a number (123abc)\n    if (isIdentifierStart(chCode)) {\n      throwError(\n        `Variable names cannot start with a number (${num}${exprI(index)})`,\n        index,\n      );\n    } else if (chCode === PERIOD_CODE) {\n      throwError(\"Unexpected period\", index);\n    }\n\n    return {\n      __id: ExpNodeOpaqueIdentifier,\n      type: \"Literal\",\n      value: parseFloat(num),\n      raw: num,\n      location: getLocation(startCharIndex),\n    };\n  }\n\n  /**\n   * Parses a string literal, staring with single or double quotes with basic support for escape codes\n   * e.g. `\"hello world\"`, `'this is\\nJSEP'`\n   */\n  function gobbleStringLiteral() {\n    const quote = exprI(index++);\n    let str = \"\";\n    let closed = false;\n    const startCharIndex = index;\n\n    while (index < length) {\n      let ch = exprI(index++);\n\n      if (ch === quote) {\n        closed = true;\n        break;\n      }\n\n      if (ch !== \"\\\\\") {\n        str += ch;\n        continue;\n      }\n\n      // Check for all of the common escape codes\n      ch = exprI(index++);\n\n      switch (ch) {\n        case \"n\":\n          str += \"\\n\";\n          break;\n        case \"r\":\n          str += \"\\r\";\n          break;\n        case \"t\":\n          str += \"\\t\";\n          break;\n        case \"b\":\n          str += \"\\b\";\n          break;\n        case \"f\":\n          str += \"\\f\";\n          break;\n        case \"v\":\n          str += \"\\u000B\";\n          break;\n        default:\n      }\n    }\n\n    if (!closed) {\n      throwError(`Unclosed quote after \"${str}\"`, index);\n    }\n\n    return {\n      __id: ExpNodeOpaqueIdentifier,\n      type: \"Literal\",\n      value: str,\n      raw: `${quote}${str}${quote}`,\n      location: getLocation(startCharIndex),\n    };\n  }\n\n  /**\n   * Model refs are bindings wrapped in 2 sets of double curlys\n   * e.g. {{foo.bar.ref}}\n   */\n  function gobbleModelRef() {\n    let str = \"\";\n    let closed = false;\n    let openBraceCount = 1;\n    const startCharIndex = index;\n\n    index += 2; // Skip the {{\n    while (index < length) {\n      const ch = exprI(index++);\n\n      if (ch === \"}\" && exprICode(index) === CCURL_CODE) {\n        index++;\n        openBraceCount--;\n\n        if (openBraceCount === 0) {\n          closed = true;\n          break;\n        }\n\n        str += \"}}\";\n      } else if (ch === \"{\" && exprICode(index) === OCURL_CODE) {\n        openBraceCount++;\n        str += \"{{\";\n        index++;\n      } else {\n        str += ch;\n      }\n    }\n\n    if (!closed) {\n      throwError(`Unclosed brace after \"${str}\"`, index);\n    }\n\n    return {\n      __id: ExpNodeOpaqueIdentifier,\n      type: \"ModelRef\",\n      ref: str,\n      location: getLocation(startCharIndex),\n    };\n  }\n\n  /**\n   * Gobbles only identifiers\n   * e.g.: `foo`, `_value`, `$x1`\n   * Also, this function checks if that identifier is a literal:\n   * (e.g. `true`, `false`, `null`) or `this`\n   */\n  function gobbleIdentifier() {\n    const start = index;\n    let ch = exprICode(start);\n\n    if (isIdentifierStart(ch)) {\n      index++;\n    } else {\n      throwError(`Unexpected ${exprI(index)}`, index);\n    }\n\n    while (index < length) {\n      ch = exprICode(index);\n      if (isIdentifierPart(ch)) {\n        index++;\n      } else {\n        break;\n      }\n    }\n\n    const identifier = expr.slice(start, index);\n\n    if (Object.prototype.hasOwnProperty.call(literals, identifier)) {\n      return {\n        __id: ExpNodeOpaqueIdentifier,\n        type: \"Literal\",\n        value: (literals as any)[identifier],\n        raw: identifier,\n        location: getLocation(start),\n      };\n    }\n\n    if (identifier === thisStr) {\n      return {\n        __id: ExpNodeOpaqueIdentifier,\n        type: \"ThisExpression\",\n        location: getLocation(start),\n      };\n    }\n\n    return {\n      __id: ExpNodeOpaqueIdentifier,\n      type: \"Identifier\",\n      name: identifier,\n      location: getLocation(start),\n    };\n  }\n\n  /**\n   * Gobbles a list of arguments within the context of a function call\n   * or array literal. This function also assumes that the opening character\n   * `(` or `[` has already been gobbled, and gobbles expressions and commas\n   * until the terminator character `)` or `]` is encountered.\n   * e.g. `foo(bar, baz)`, `my_func()`, or `[bar, baz]`\n   */\n  function gobbleArguments(termination: number) {\n    const args = [];\n    let charIndex;\n    let node;\n\n    while (index < length) {\n      gobbleSpaces();\n      charIndex = exprICode(index);\n\n      if (charIndex === termination) {\n        // Done parsing\n        index++;\n        break;\n      }\n\n      if (charIndex === COMMA_CODE) {\n        // Between expressions\n        index++;\n        continue;\n      }\n\n      node = gobbleExpression();\n\n      if (!node || node.type === \"Compound\") {\n        throwError(\"Expected comma\", index);\n      }\n\n      args.push(node);\n    }\n\n    if (strictMode && charIndex !== termination) {\n      throwError(`Expected ${String.fromCharCode(termination)}`, index);\n    }\n\n    return args;\n  }\n\n  /**\n   * Gobble a non-literal variable name. This variable name may include properties\n   * e.g. `foo`, `bar.baz`, `foo['bar'].baz`\n   * It also gobbles function calls:\n   * e.g. `Math.acos(obj.angle)`\n   */\n  function gobbleVariable(): ExpressionNode {\n    let charIndex = exprICode(index);\n    let node: any =\n      charIndex === OPAREN_CODE ? gobbleGroup() : gobbleIdentifier();\n    const startCharIndex = index;\n    gobbleSpaces();\n    charIndex = exprICode(index);\n\n    while (\n      charIndex === PERIOD_CODE ||\n      charIndex === OBRACK_CODE ||\n      charIndex === OPAREN_CODE\n    ) {\n      index++;\n\n      if (charIndex === PERIOD_CODE) {\n        gobbleSpaces();\n\n        node = {\n          __id: ExpNodeOpaqueIdentifier,\n          type: \"MemberExpression\",\n          computed: false,\n          object: node,\n          property: gobbleIdentifier(),\n          location: getLocation(startCharIndex),\n        };\n      } else if (charIndex === OBRACK_CODE) {\n        node = {\n          __id: ExpNodeOpaqueIdentifier,\n          type: \"MemberExpression\",\n          computed: true,\n          object: node,\n          property: gobbleExpression(),\n          location: getLocation(startCharIndex),\n        };\n\n        gobbleSpaces();\n        charIndex = exprICode(index);\n\n        if (charIndex !== CBRACK_CODE) {\n          throwError(\"Unclosed [\", index);\n        }\n\n        index++;\n      } else if (charIndex === OPAREN_CODE) {\n        // A function call is being made; gobble all the arguments\n        node = {\n          __id: ExpNodeOpaqueIdentifier,\n          type: \"CallExpression\",\n          args: gobbleArguments(CPAREN_CODE),\n          callTarget: node,\n          location: getLocation(startCharIndex),\n        };\n      }\n\n      gobbleSpaces();\n      charIndex = exprICode(index);\n    }\n\n    return node;\n  }\n\n  /**\n   * Responsible for parsing a group of things within parentheses `()`\n   * This function assumes that it needs to gobble the opening parenthesis\n   * and then tries to gobble everything within that parenthesis, assuming\n   * that the next thing it should see is the close parenthesis. If not,\n   * then the expression probably doesn't have a `)`\n   */\n  function gobbleGroup() {\n    index++;\n    const node = gobbleExpression();\n    gobbleSpaces();\n\n    if (exprICode(index) === CPAREN_CODE) {\n      index++;\n      return node;\n    }\n\n    throwError(\"Unclosed (\", index);\n  }\n\n  /**\n   * Responsible for parsing Array literals `[1, 2, 3]`\n   * This function assumes that it needs to gobble the opening bracket\n   * and then tries to gobble the expressions as arguments.\n   */\n  function gobbleArray() {\n    const startCharIndex = index;\n    index++;\n\n    return {\n      __id: ExpNodeOpaqueIdentifier,\n      type: \"ArrayExpression\",\n      elements: gobbleArguments(CBRACK_CODE),\n      location: getLocation(startCharIndex),\n    };\n  }\n\n  const nodes = [];\n\n  try {\n    while (index < length) {\n      const chIndex = exprICode(index);\n\n      // Expressions can be separated by semicolons, commas, or just inferred without any\n      // separators\n      if (chIndex === SEMCOL_CODE || chIndex === COMMA_CODE) {\n        index++; // ignore separators\n        continue;\n      }\n\n      const node = gobbleExpression();\n\n      // Try to gobble each expression individually\n      if (node) {\n        nodes.push(node);\n        // If we weren't able to find a binary expression and are out of room, then\n        // the expression passed in probably has too much\n      } else if (strictMode && index < length) {\n        throwError(`Unexpected \"${exprI(index)}\"`, index);\n      }\n    }\n\n    // If there's only one expression just try returning the expression\n    if (nodes.length === 1) {\n      return nodes[0];\n    }\n\n    return {\n      __id: ExpNodeOpaqueIdentifier,\n      type: \"Compound\",\n      body: nodes,\n      location: getLocation(0),\n    };\n  } catch (e) {\n    if (strictMode || !(e instanceof Error)) {\n      throw e;\n    }\n\n    return {\n      __id: ExpNodeOpaqueIdentifier,\n      type: \"Compound\",\n      body: nodes,\n      location: getLocation(0),\n      error: e,\n    };\n  }\n}\n","import type { Binding } from \"@player-ui/types\";\n\nimport type { BindingLike } from \"../binding\";\nimport type {\n  ExpressionHandler,\n  ExpressionContext,\n  ExpressionNode,\n} from \"./types\";\nimport { Awaitable, isAwaitable, makeAwaitable } from \"./async\";\n\n/** Sets a value to the data-model */\nexport const setDataVal: ExpressionHandler<[Binding, any], any> = (\n  _context: ExpressionContext,\n  binding,\n  value,\n) => {\n  _context.model.set([[binding as BindingLike, value]]);\n};\n\n/** Fetches a valid from the data-model */\nexport const getDataVal: ExpressionHandler<[Binding], unknown> = (\n  _context: ExpressionContext,\n  binding,\n) => {\n  return _context.model.get(binding as BindingLike);\n};\n\n/** Deletes a value from the model */\nexport const deleteDataVal: ExpressionHandler<[Binding], void> = (\n  _context: ExpressionContext,\n  binding,\n) => {\n  return _context.model.delete(binding);\n};\n\n/** Conditional expression handler */\nexport const conditional: ExpressionHandler<\n  [ExpressionNode, ExpressionNode, ExpressionNode?]\n> = (ctx, condition, ifTrue, ifFalse) => {\n  const testResult = ctx.evaluate(condition);\n\n  // Handle Promise case automatically (same pattern as ternary operator)\n  if (isAwaitable(testResult)) {\n    return testResult.awaitableThen((resolvedTest: any) => {\n      if (resolvedTest) {\n        return ctx.evaluate(ifTrue);\n      }\n      if (ifFalse) {\n        return ctx.evaluate(ifFalse);\n      }\n      return null;\n    });\n  }\n\n  // Handle sync case\n  if (testResult) {\n    return ctx.evaluate(ifTrue);\n  }\n  if (ifFalse) {\n    return ctx.evaluate(ifFalse);\n  }\n  return null;\n};\n\nconditional.resolveParams = false;\n\n/**\n * Internal await function\n * This is technically registered as `await` but can't be called that due to conflicting with the keyword\n */\nexport const waitFor: ExpressionHandler<[Promise<any>], Awaitable<any>> = (\n  ctx,\n  promise,\n) => {\n  return makeAwaitable(promise);\n};\n","/**\n * Promise detection that handles various Promise implementations\n * and reduces false positives from objects with coincidental 'then' methods\n */\nexport function isPromiseLike(value: any): value is Promise<any> {\n  return (\n    value != null &&\n    typeof value === \"object\" &&\n    typeof value.then === \"function\" &&\n    // Additional safeguards against false positives\n    (value instanceof Promise ||\n      // Check for standard Promise constructor name\n      value.constructor?.name === \"Promise\" ||\n      // Verify it has other Promise-like methods to reduce false positives\n      (typeof value.catch === \"function\" &&\n        typeof value.finally === \"function\"))\n  );\n}\n\n/** Unique private symbol to indicate async functions wrapped in Player's await function */\nexport const AwaitableSymbol: unique symbol = Symbol(\"Awaitable\");\n\n/**\n * Wrapper for Promises that are generated from the `await` function with a unique symbol so we can\n * determine when a promise should be awaited by us (as its returned by await) or a promise thats\n * generated from any async function\n */\nexport interface Awaitable<T> extends Promise<T> {\n  /** Prevent unwrapped then from being exposed from underlying promise */\n  then: never;\n  /** Internalally awaitable wrapper around underlying then function */\n  awaitableThen<TResult1 = T, TResult2 = never>(\n    onfulfilled?:\n      | ((value: T) => TResult1 | PromiseLike<TResult1>)\n      | undefined\n      | null,\n    onrejected?:\n      | ((reason: any) => TResult2 | PromiseLike<TResult2>)\n      | undefined\n      | null,\n  ): Promise<TResult1 | TResult2>;\n  /** Symbol to identify this as something returned by await */\n  [AwaitableSymbol]: symbol;\n}\n\n/** Typeguard for AwaitableResult */\nexport function isAwaitable(val: unknown): val is Awaitable<any> {\n  return (\n    isPromiseLike(val) && (val as Awaitable<any>)[AwaitableSymbol] !== undefined\n  );\n}\n\n/**\n * Wraps Promise.all in AwaitableResult wrapper to allow internal functions to await internally produced promises\n */\nexport function collateAwaitable<T extends readonly unknown[] | []>(\n  promises: T,\n): Awaitable<any> {\n  const result = Promise.all(promises) as Promise<any>;\n  return makeAwaitable(result);\n}\n\n/**\n * Add AwaitableSymbol to base promise and promise returned by then() function\n */\nexport function makeAwaitable(promise: Promise<any>): Awaitable<any> {\n  (promise as Awaitable<any>)[AwaitableSymbol] = AwaitableSymbol;\n  (promise as any).awaitableThen = (arg: any) => {\n    return makeAwaitable(promise.then(arg));\n  };\n  return promise as Awaitable<any>;\n}\n","import { isExpressionNode } from \"./types\";\nimport type {\n  ErrorWithLocation,\n  ExpressionHandler,\n  ExpressionNode,\n  ExpressionObjectType,\n  ExpressionType,\n  NodeLocation,\n  NodePosition,\n} from \"./types\";\n\n/** Generates a function by removing the first context argument */\nexport function withoutContext<T extends unknown[], Return>(\n  fn: (...args: T) => Return,\n): ExpressionHandler<T, Return> {\n  return (_context, ...args) => fn(...args);\n}\n\n/** Checks if the location includes the target position  */\nfunction isInRange(position: NodePosition, location: NodeLocation) {\n  return (\n    position.character >= location.start.character &&\n    position.character <= location.end.character\n  );\n}\n\n/** Get the node in the expression that's closest to the desired position */\nexport function findClosestNodeAtPosition(\n  node: ExpressionNode,\n  position: NodePosition,\n): ExpressionNode | undefined {\n  // This is just mapping recursively over nodes in the tree\n\n  switch (node.type) {\n    case \"Modification\":\n    case \"Assignment\":\n    case \"LogicalExpression\":\n    case \"BinaryExpression\": {\n      const check =\n        findClosestNodeAtPosition(node.left, position) ??\n        findClosestNodeAtPosition(node.right, position);\n      if (check) {\n        return check;\n      }\n\n      break;\n    }\n\n    case \"UnaryExpression\": {\n      const checkArg = findClosestNodeAtPosition(node.argument, position);\n      if (checkArg) {\n        return checkArg;\n      }\n\n      break;\n    }\n\n    case \"MemberExpression\": {\n      const checkObject =\n        findClosestNodeAtPosition(node.object, position) ??\n        findClosestNodeAtPosition(node.property, position);\n      if (checkObject) {\n        return checkObject;\n      }\n\n      break;\n    }\n\n    case \"ConditionalExpression\": {\n      const checkObject =\n        findClosestNodeAtPosition(node.test, position) ??\n        findClosestNodeAtPosition(node.consequent, position) ??\n        findClosestNodeAtPosition(node.alternate, position);\n      if (checkObject) {\n        return checkObject;\n      }\n\n      break;\n    }\n\n    case \"ArrayExpression\":\n    case \"Compound\": {\n      const elements =\n        node.type === \"ArrayExpression\" ? node.elements : node.body;\n\n      const anyElements = elements.find((e) =>\n        findClosestNodeAtPosition(e, position),\n      );\n\n      if (anyElements) {\n        return anyElements;\n      }\n\n      break;\n    }\n\n    case \"Object\": {\n      const checkObject = node.attributes.reduce<ExpressionNode | undefined>(\n        (found, next) => {\n          return (\n            found ??\n            findClosestNodeAtPosition(next.key, position) ??\n            findClosestNodeAtPosition(next.value, position)\n          );\n        },\n        undefined,\n      );\n\n      if (checkObject) {\n        return checkObject;\n      }\n\n      break;\n    }\n\n    case \"CallExpression\": {\n      const anyArgs =\n        node.args.find((arg) => {\n          return findClosestNodeAtPosition(arg, position);\n        }) ?? findClosestNodeAtPosition(node.callTarget, position);\n\n      if (anyArgs) {\n        return anyArgs;\n      }\n\n      break;\n    }\n  }\n\n  // Lastly check for yourself\n  if (node.location && isInRange(position, node.location)) {\n    return node;\n  }\n}\n\n/** Checks if the expression is a simple type */\nexport function isObjectExpression(\n  expr: ExpressionType,\n): expr is ExpressionObjectType {\n  if (isExpressionNode(expr)) {\n    return false;\n  }\n\n  return (\n    typeof expr === \"object\" &&\n    expr !== null &&\n    !Array.isArray(expr) &&\n    \"value\" in expr\n  );\n}\n\n/**\n * Type guard for ErrorWithLocation\n */\nexport function isErrorWithLocation(error: Error): error is ErrorWithLocation {\n  return (\n    (error as ErrorWithLocation).index !== undefined &&\n    (error as ErrorWithLocation).description !== undefined\n  );\n}\n","export type LogFn = (...args: Array<any>) => void;\n\nexport const severities = [\"trace\", \"debug\", \"info\", \"warn\", \"error\"] as const;\nexport type Severity = (typeof severities)[number];\nexport type Logger = Record<Severity, LogFn>;\nexport type LoggerProvider = () => Logger | undefined;\n","import type { Logger, Severity } from \"./types\";\nimport { severities } from \"./types\";\n\nexport type ConsoleHandler = Pick<typeof console, \"log\" | \"warn\" | \"error\">;\n\n/** A Logger implementation that uses console */\nexport class ConsoleLogger implements Logger {\n  private severity: Severity;\n  private _console: ConsoleHandler;\n\n  constructor(severity: Severity = \"warn\", _console: ConsoleHandler = console) {\n    this.severity = severity;\n    this._console = _console;\n  }\n\n  public setSeverity(severity: Severity) {\n    this.severity = severity;\n  }\n\n  private getConsoleFn(severity: Severity) {\n    switch (severities.indexOf(severity)) {\n      case 0:\n      case 1:\n      case 2:\n        return this._console.log;\n      case 3:\n        return this._console.warn;\n      default:\n        return this._console.error;\n    }\n  }\n\n  private createHandler(severity: Severity): (...args: any[]) => void {\n    return (...args: any[]) => {\n      const sevIndex = severities.indexOf(severity);\n      const sevConf = severities.indexOf(this.severity);\n\n      if (sevIndex >= sevConf) {\n        this.getConsoleFn(severity)(`player - ${severity} -`, ...args);\n      }\n    };\n  }\n\n  public readonly trace = this.createHandler(\"trace\");\n  public readonly debug = this.createHandler(\"debug\");\n  public readonly info = this.createHandler(\"info\");\n  public readonly warn = this.createHandler(\"warn\");\n  public readonly error = this.createHandler(\"error\");\n}\n","import type { Logger } from \"./types\";\n\n/** An empty function so the logger ignore everything */\nconst noop = () => {};\n\n/** A logger implementation that goes nowhere */\nexport class NoopLogger implements Logger {\n  public readonly trace = noop;\n  public readonly debug = noop;\n  public readonly info = noop;\n  public readonly warn = noop;\n  public readonly error = noop;\n}\n","import { SyncHook } from \"tapable-ts\";\nimport type { Logger, Severity } from \"./types\";\n\n/** A logger that has a tapable subscriptions to callbacks */\nexport class TapableLogger implements Logger {\n  public readonly hooks = {\n    trace: new SyncHook<[Array<any>]>(),\n    debug: new SyncHook<[Array<any>]>(),\n    info: new SyncHook<[Array<any>]>(),\n    warn: new SyncHook<[Array<any>]>(),\n    error: new SyncHook<[Array<any>]>(),\n    log: new SyncHook<[Severity, Array<any>]>(),\n  };\n\n  private logHandlers: Set<Logger> = new Set();\n\n  private createHandler(severity: Severity): (...args: any[]) => void {\n    return (...args: any[]) => {\n      this.hooks[severity].call(args);\n      this.hooks.log.call(severity, args);\n      this.logHandlers.forEach((logger) => logger[severity](...args));\n    };\n  }\n\n  public addHandler(logHandler: Logger) {\n    this.logHandlers.add(logHandler);\n  }\n\n  public removeHandler(logHandler: Logger) {\n    this.logHandlers.delete(logHandler);\n  }\n\n  public readonly trace = this.createHandler(\"trace\");\n  public readonly debug = this.createHandler(\"debug\");\n  public readonly info = this.createHandler(\"info\");\n  public readonly warn = this.createHandler(\"warn\");\n  public readonly error = this.createHandler(\"error\");\n}\n","import type { Logger, Severity, LoggerProvider } from \"./types\";\n\n/**\n * The ProxyLogger allows a user to log to another Logger instance that may not exist yet\n */\nexport class ProxyLogger implements Logger {\n  private proxiedLoggerProvider: LoggerProvider;\n\n  constructor(loggerProvider: LoggerProvider) {\n    this.proxiedLoggerProvider = loggerProvider;\n  }\n\n  private createHandler(severity: Severity): (...args: any[]) => void {\n    return (...args: any[]) => {\n      const logger = this.proxiedLoggerProvider();\n      logger?.[severity](...args);\n    };\n  }\n\n  public readonly trace = this.createHandler(\"trace\");\n  public readonly debug = this.createHandler(\"debug\");\n  public readonly info = this.createHandler(\"info\");\n  public readonly warn = this.createHandler(\"warn\");\n  public readonly error = this.createHandler(\"error\");\n}\n","import { SyncWaterfallHook } from \"tapable-ts\";\nimport type { Schema as SchemaType, Formatting } from \"@player-ui/types\";\n\nimport type { BindingInstance } from \"../binding\";\nimport type { ValidationProvider, ValidationObject } from \"../validator\";\nimport type { FormatDefinition, FormatOptions, FormatType } from \"./types\";\n\n/** A function that returns itself */\nconst identify = (val: any) => val;\n\n/** Expand the authored schema into a set of paths -> DataTypes */\nexport function parse(\n  schema: SchemaType.Schema,\n): Map<string, SchemaType.DataTypes> {\n  const expandedPaths = new Map<string, SchemaType.DataTypes>();\n\n  if (!schema.ROOT) {\n    return expandedPaths;\n  }\n\n  const parseQueue: Array<{\n    /** The node to process */\n    node: SchemaType.Node;\n\n    /** The path in the data-model this node represents */\n    path: Array<string>;\n\n    /** A set of visited DataTypes to prevent loops */\n    visited: Set<string>;\n  }> = [{ node: schema.ROOT, path: [], visited: new Set() }];\n\n  while (parseQueue.length > 0) {\n    const next = parseQueue.shift();\n\n    if (!next) {\n      break;\n    }\n\n    const { node, path, visited } = next;\n\n    Object.entries(node).forEach(([prop, type]) => {\n      const nestedPath = [...path, prop];\n\n      const nestedPathStr = nestedPath.join(\".\");\n\n      if (expandedPaths.has(nestedPathStr)) {\n        // We've gone in a loop. Panic\n        throw new Error(\n          \"Path has already been processed. There's either a loop somewhere or a bug\",\n        );\n      }\n\n      if (visited.has(type.type)) {\n        throw new Error(\n          `Path already contained type: ${type.type}. This likely indicates a loop in the schema`,\n        );\n      }\n\n      expandedPaths.set(nestedPathStr, type);\n\n      if (type.isArray) {\n        nestedPath.push(\"[]\");\n      }\n\n      if (type.isRecord) {\n        nestedPath.push(\"{}\");\n      }\n\n      if (type.type && schema[type.type]) {\n        parseQueue.push({\n          path: nestedPath,\n          node: schema[type.type],\n          visited: new Set([...visited, type.type]),\n        });\n      }\n    });\n  }\n\n  return expandedPaths;\n}\n\n/**\n * The Schema is the central hub for all data invariants, and metaData associated with the data-model itself\n * Outside of the types defined in the JSON payload, it doesn't manage or keep any state.\n * It simply servers as an orchestrator for other modules to interface w/ the schema.\n */\nexport class SchemaController implements ValidationProvider {\n  private formatters: Map<string, FormatType<any, any, FormatOptions>> =\n    new Map();\n\n  private types: Map<string, SchemaType.DataType<any>> = new Map();\n  public readonly schema: Map<string, SchemaType.DataTypes> = new Map();\n\n  private bindingSchemaNormalizedCache: Map<BindingInstance, string> =\n    new Map();\n\n  public readonly hooks = {\n    resolveTypeForBinding: new SyncWaterfallHook<\n      [SchemaType.DataTypes | undefined, BindingInstance]\n    >(),\n  };\n\n  constructor(schema?: SchemaType.Schema) {\n    this.schema = schema ? parse(schema) : new Map();\n  }\n\n  public addFormatters(fns: Array<FormatType<any, any, FormatOptions>>) {\n    fns.forEach((def) => {\n      this.formatters.set(def.name, def);\n    });\n  }\n\n  public addDataTypes(types: Array<SchemaType.DataType<any>>) {\n    types.forEach((t) => {\n      this.types.set(t.type, t);\n    });\n  }\n\n  getValidationsForBinding(\n    binding: BindingInstance,\n  ): Array<ValidationObject> | undefined {\n    const typeDef = this.getApparentType(binding);\n\n    if (!typeDef?.validation?.length) {\n      return undefined;\n    }\n\n    // Set the defaults for schema-level validations\n    return typeDef.validation.map((vRef) => ({\n      severity: \"error\",\n      trigger: \"change\",\n      ...vRef,\n    }));\n  }\n\n  private normalizeBinding(binding: BindingInstance): string {\n    const cached = this.bindingSchemaNormalizedCache.get(binding);\n    if (cached) {\n      return cached;\n    }\n\n    let bindingArray = binding.asArray();\n    let normalized = bindingArray\n      .map((p) => (typeof p === \"number\" ? \"[]\" : p))\n      .join(\".\");\n\n    if (normalized) {\n      this.bindingSchemaNormalizedCache.set(binding, normalized);\n      bindingArray = normalized.split(\".\");\n    }\n\n    bindingArray.forEach((item) => {\n      const recordBinding = bindingArray\n        .map((p) => (p === item ? \"{}\" : p))\n        .join(\".\");\n\n      if (this.schema.get(recordBinding)) {\n        this.bindingSchemaNormalizedCache.set(binding, recordBinding);\n        bindingArray = recordBinding.split(\".\");\n        normalized = recordBinding;\n      }\n    });\n\n    return normalized;\n  }\n\n  public getType(binding: BindingInstance): SchemaType.DataTypes | undefined {\n    return this.hooks.resolveTypeForBinding.call(\n      this.schema.get(this.normalizeBinding(binding)),\n      binding,\n    );\n  }\n\n  public getApparentType(\n    binding: BindingInstance,\n  ): SchemaType.DataTypes | undefined {\n    const schemaType = this.getType(binding);\n\n    if (schemaType === undefined) {\n      return undefined;\n    }\n\n    const baseType = this.getTypeDefinition(schemaType?.type);\n\n    if (baseType === undefined) {\n      return schemaType;\n    }\n\n    return {\n      ...baseType,\n      ...schemaType,\n      validation: [\n        ...(schemaType.validation ?? []),\n        ...(baseType.validation ?? []),\n      ],\n    };\n  }\n\n  public getTypeDefinition(dataType: string) {\n    return this.types.get(dataType);\n  }\n\n  public getFormatterForType(\n    formatReference: Formatting.Reference,\n  ): FormatDefinition<unknown, unknown> | undefined {\n    const { type: formatType, ...options } = formatReference;\n\n    const formatter = this.formatters.get(formatType);\n\n    if (!formatter) {\n      return;\n    }\n\n    return {\n      format: formatter.format\n        ? (val) => formatter.format?.(val, options)\n        : identify,\n      deformat: formatter.deformat\n        ? (val) => formatter.deformat?.(val, options)\n        : identify,\n    };\n  }\n\n  /**\n   * Given a binding, fetch a function that's responsible for formatting, and/or de-formatting the data\n   * If no formatter is registered, it will return undefined\n   */\n  public getFormatter(\n    binding: BindingInstance,\n  ): FormatDefinition<unknown, unknown> | undefined {\n    const type = this.getApparentType(binding);\n\n    if (!type?.format) {\n      return undefined;\n    }\n\n    return this.getFormatterForType(type.format);\n  }\n}\n","import { setIn } from \"timm\";\nimport type { Expression } from \"@player-ui/types\";\nimport type { DataModelWithParser } from \"../data\";\n\nconst DOUBLE_OPEN_CURLY = \"{{\";\nconst DOUBLE_CLOSE_CURLY = \"}}\";\n\nexport interface Options {\n  /**\n   * The model to use when resolving refs\n   * Passing `false` will skip trying to resolve any direct model refs ({{foo}})\n   */\n  model: false | DataModelWithParser;\n\n  /**\n   * A function to evaluate an expression\n   * Passing `false` will skip trying to evaluate any expressions (@[ foo() ]@)\n   */\n  evaluate: false | ((exp: Expression) => any);\n\n  /**\n   * Optionaly resolve binding without formatting in case Type format applies\n   */\n  formatted?: boolean;\n}\n\n/** Search the given string for the coordinates of the next expression to resolve */\nexport function findNextExp(str: string) {\n  const expStart = str.indexOf(DOUBLE_OPEN_CURLY);\n\n  if (expStart === -1) {\n    return undefined;\n  }\n\n  let count = 1;\n  let offset = expStart + DOUBLE_OPEN_CURLY.length;\n  let workingString = str.substring(expStart + DOUBLE_OPEN_CURLY.length);\n\n  while (count > 0 && workingString.length > 0) {\n    // Find the next open or close curly\n    const nextCloseCurly = workingString.indexOf(DOUBLE_CLOSE_CURLY);\n\n    // We can't close anything, so there's no point in going on with life.\n    if (nextCloseCurly === -1) {\n      break;\n    }\n\n    const nextOpenCurly = workingString.indexOf(DOUBLE_OPEN_CURLY);\n\n    if (nextOpenCurly !== -1 && nextOpenCurly < nextCloseCurly) {\n      // We've hit another open bracket before closing out the one we want\n      // Move everything over and bump our close count by 1\n      count++;\n      workingString = workingString.substring(\n        nextOpenCurly + DOUBLE_OPEN_CURLY.length,\n      );\n      offset += nextOpenCurly + DOUBLE_OPEN_CURLY.length;\n    } else {\n      // We've hit another closing bracket\n      // Decrement our count and updates offsets\n      count--;\n      workingString = workingString.substring(\n        nextCloseCurly + DOUBLE_CLOSE_CURLY.length,\n      );\n      offset += nextCloseCurly + DOUBLE_CLOSE_CURLY.length;\n    }\n  }\n\n  if (count !== 0) {\n    throw new Error(`Unbalanced {{ and }} in exp: ${str}`);\n  }\n\n  return {\n    start: expStart,\n    end: offset,\n  };\n}\n\n/** Finds any subset of the string wrapped in @[]@ and evaluates it as an expression */\nexport function resolveExpressionsInString(\n  val: string,\n  { evaluate }: Options,\n): string {\n  if (!evaluate) {\n    return val;\n  }\n\n  const expMatch = /@\\[.*?\\]@/;\n  let newVal = val;\n  let match = newVal.match(expMatch);\n\n  while (match !== null) {\n    const expStrWithBrackets = match[0];\n    const matchStart = newVal.indexOf(expStrWithBrackets);\n\n    const expString = expStrWithBrackets.substr(\n      \"@[\".length,\n      expStrWithBrackets.length - \"@[\".length - \"]@\".length,\n    );\n    const expValue = evaluate(expString);\n\n    // The string is only the expression, return the raw value.\n    if (\n      matchStart === 0 &&\n      expStrWithBrackets === val &&\n      typeof expValue !== \"string\"\n    ) {\n      return expValue;\n    }\n\n    newVal =\n      newVal.substr(0, matchStart) +\n      expValue +\n      newVal.substr(matchStart + expStrWithBrackets.length);\n    // remove the surrounding @[]@ to get the expression\n    match = newVal.match(expMatch);\n  }\n\n  return newVal;\n}\n\n/** Return a string with all data model references resolved */\nexport function resolveDataRefsInString(val: string, options: Options): string {\n  const { model, formatted = true } = options;\n  let workingString = resolveExpressionsInString(val, options);\n\n  if (\n    !model ||\n    typeof workingString !== \"string\" ||\n    workingString.indexOf(DOUBLE_OPEN_CURLY) === -1\n  ) {\n    return workingString;\n  }\n\n  while (workingString.indexOf(DOUBLE_OPEN_CURLY) !== -1) {\n    const expLocation = findNextExp(workingString);\n\n    if (!expLocation) {\n      return workingString;\n    }\n\n    const { start, end } = expLocation;\n\n    // Strip out the wrapping curlies from {{binding}} before passing to the model\n    const binding = workingString\n      .substring(\n        start + DOUBLE_OPEN_CURLY.length,\n        end - DOUBLE_OPEN_CURLY.length,\n      )\n      .trim();\n\n    const evaledVal = model.get(binding, { formatted });\n\n    // Exit early if the string is _just_ a model lookup\n    // If the result is a string, we may need further processing for nested bindings\n    if (\n      start === 0 &&\n      end === workingString.length &&\n      typeof evaledVal !== \"string\"\n    ) {\n      return evaledVal;\n    }\n\n    workingString =\n      workingString.substr(0, start) + evaledVal + workingString.substr(end);\n  }\n\n  return workingString;\n}\n\n/** Traverse the thing and replace any model refs */\nfunction traverseObject<T>(val: T, options: Options): T {\n  switch (typeof val) {\n    case \"string\": {\n      return resolveDataRefsInString(val as string, options) as unknown as T;\n    }\n\n    case \"object\": {\n      if (!val) return val;\n      // TODO: Do we care refs in keys?\n      const keys = Object.keys(val);\n      let newVal = val;\n\n      if (keys.length > 0) {\n        keys.forEach((key) => {\n          newVal = setIn(\n            newVal as any,\n            [key],\n            traverseObject((val as any)[key], options),\n          ) as any;\n        });\n      }\n\n      return newVal;\n    }\n\n    default:\n      return val;\n  }\n}\n\n/** Recursively resolve all model refs in whatever you pass in */\nexport function resolveDataRefs<T>(val: T, options: Options): T {\n  return traverseObject(val, options);\n}\n","import { setIn } from \"timm\";\nimport type { BindingInstance } from \"../binding\";\nimport type {\n  BatchSetTransaction,\n  DataModelImpl,\n  DataModelOptions,\n  DataModelMiddleware,\n  Updates,\n} from \"../data\";\nimport { toModel } from \"../data\";\nimport type { Logger } from \"../logger\";\n\nimport type { ValidationResponse } from \"./types\";\nimport { removeBindingAndChildrenFromMap } from \"./binding-map-splice\";\n\n/**\n * A BindingInstance with an indicator of whether or not it's a strong binding\n */\nexport type StrongOrWeakBinding = {\n  /** BindingInstance in question */\n  binding: BindingInstance;\n  /** Boolean indicating whether the relevant BindingInstance is a strong binding */\n  isStrong: boolean;\n};\n\n/**\n * Returns a validation object if the data is invalid or an set of BindingsInstances if the binding itself is a weak ref of another invalid validation\n */\nexport type MiddlewareChecker = (\n  binding: BindingInstance,\n  model: DataModelImpl,\n) => ValidationResponse | Set<StrongOrWeakBinding> | undefined;\n\n/**\n * Middleware for the data-model that caches the results of invalid data\n */\nexport class ValidationMiddleware implements DataModelMiddleware {\n  public validator: MiddlewareChecker;\n  public shadowModelPaths: Map<BindingInstance, any>;\n  private logger?: Logger;\n  private shouldIncludeInvalid?: (options?: DataModelOptions) => boolean;\n\n  constructor(\n    validator: MiddlewareChecker,\n    options?: {\n      /** A logger instance */\n      logger?: Logger;\n      /** Optional function to include data staged in shadowModel */\n      shouldIncludeInvalid?: (options?: DataModelOptions) => boolean;\n    },\n  ) {\n    this.validator = validator;\n    this.shadowModelPaths = new Map();\n    this.logger = options?.logger;\n    this.shouldIncludeInvalid = options?.shouldIncludeInvalid;\n  }\n\n  public set(\n    transaction: BatchSetTransaction,\n    options?: DataModelOptions,\n    next?: DataModelImpl,\n  ): Updates {\n    const asModel = toModel(this, { ...options, includeInvalid: true }, next);\n    const nextTransaction: BatchSetTransaction = [];\n\n    const includedBindings = new Set<BindingInstance>();\n\n    transaction.forEach(([binding, value]) => {\n      this.shadowModelPaths.set(binding, value);\n      includedBindings.add(binding);\n    });\n\n    const invalidBindings: Array<BindingInstance> = [];\n\n    this.shadowModelPaths.forEach((value, binding) => {\n      const validations = this.validator(binding, asModel);\n\n      if (validations === undefined) {\n        nextTransaction.push([binding, value]);\n      } else if (validations instanceof Set) {\n        validations.forEach((validation) => {\n          invalidBindings.push(validation.binding);\n          if (\n            !validation.isStrong &&\n            validation.binding.asString() === binding.asString()\n          ) {\n            nextTransaction.push([validation.binding, value]);\n          }\n        });\n      } else if (includedBindings.has(binding)) {\n        invalidBindings.push(binding);\n        this.logger?.debug(\n          `Invalid value for path: ${binding.asString()} - ${\n            validations.severity\n          } - ${validations.message}`,\n        );\n      }\n    });\n\n    let validResults: Updates = [];\n\n    if (next && nextTransaction.length > 0) {\n      // defer clearing the shadow model to prevent validations that are run twice due to weak binding refs still needing the data\n      nextTransaction.forEach(([binding]) =>\n        this.shadowModelPaths.delete(binding),\n      );\n      const result = next.set(nextTransaction, options);\n      if (invalidBindings.length === 0) {\n        return result;\n      }\n\n      validResults = result;\n    }\n\n    const invalidResults = invalidBindings.map((binding) => {\n      return {\n        binding,\n        oldValue: asModel.get(binding),\n        newValue: asModel.get(binding),\n        force: true,\n      };\n    });\n\n    return [...validResults, ...invalidResults];\n  }\n\n  public get(\n    binding: BindingInstance,\n    options?: DataModelOptions,\n    next?: DataModelImpl,\n  ) {\n    let val = next?.get(binding, options);\n\n    if (\n      this.shouldIncludeInvalid?.(options) ??\n      options?.includeInvalid === true\n    ) {\n      this.shadowModelPaths.forEach((shadowValue, shadowBinding) => {\n        if (shadowBinding === binding) {\n          val = shadowValue;\n\n          return;\n        }\n\n        if (binding.contains(shadowBinding)) {\n          val = setIn(val, shadowBinding.relative(binding), shadowValue);\n        }\n      });\n    }\n\n    return val;\n  }\n\n  public delete(\n    binding: BindingInstance,\n    options?: DataModelOptions,\n    next?: DataModelImpl,\n  ) {\n    this.shadowModelPaths = removeBindingAndChildrenFromMap(\n      this.shadowModelPaths,\n      binding,\n    );\n\n    return next?.delete(binding, options);\n  }\n}\n","import type { BindingInstance } from \"../binding\";\n\n/**\n * Remove a binding, and any children from from the map\n * If the binding is an array-item, then it will be spliced from the array and the others will be shifted down\n *\n * @param sourceMap - A map of bindings to values\n * @param binding - The binding to remove from the map\n */\nexport function removeBindingAndChildrenFromMap<T>(\n  sourceMap: Map<BindingInstance, T>,\n  binding: BindingInstance,\n): Map<BindingInstance, T> {\n  const targetMap = new Map(sourceMap);\n\n  const parentBinding = binding.parent();\n  const property = binding.key();\n\n  // Clear out any that are sub-bindings of this binding\n\n  targetMap.forEach((_value, trackedBinding) => {\n    if (binding === trackedBinding || binding.contains(trackedBinding)) {\n      targetMap.delete(trackedBinding);\n    }\n  });\n\n  if (typeof property === \"number\") {\n    // Splice out this index from the rest\n\n    // Order matters here b/c we are shifting items in the array\n    // Start with the smallest index and work our way down\n    const bindingsToRewrite = Array.from(sourceMap.keys())\n      .filter((b) => {\n        if (parentBinding.contains(b)) {\n          const [childIndex] = b.relative(parentBinding);\n          return typeof childIndex === \"number\" && childIndex > property;\n        }\n\n        return false;\n      })\n      .sort();\n\n    bindingsToRewrite.forEach((trackedBinding) => {\n      // If the tracked binding is a sub-binding of the parent binding, then we need to\n      // update the path to reflect the new index\n\n      const [childIndex, ...childPath] = trackedBinding.relative(parentBinding);\n\n      if (typeof childIndex === \"number\") {\n        const newSegments = [childIndex - 1, ...childPath];\n        const newChildBinding = parentBinding.descendent(newSegments);\n        targetMap.set(newChildBinding, targetMap.get(trackedBinding) as T);\n        targetMap.delete(trackedBinding);\n      }\n    });\n  }\n\n  return targetMap;\n}\n","import type { ValidatorFunction } from \"./types\";\n\n/** A registry that tracks validators  */\nexport class ValidatorRegistry {\n  private registry: Map<string, ValidatorFunction<any>>;\n\n  constructor() {\n    this.registry = new Map();\n  }\n\n  /** Use the given validator name to fetch the handler */\n  public get(name: string): ValidatorFunction | undefined {\n    return this.registry.get(name);\n  }\n\n  /** Register a new validator */\n  public register<T>(name: string, handler: ValidatorFunction<T>) {\n    this.registry.set(name, handler);\n  }\n}\n","import { SyncHook } from \"tapable-ts\";\nimport type { View as ViewType } from \"@player-ui/types\";\nimport type { BindingInstance, BindingFactory } from \"../binding\";\nimport type { ValidationProvider, ValidationObject } from \"../validator\";\nimport type { Logger } from \"../logger\";\nimport type { Resolve } from \"./resolver\";\nimport { Resolver } from \"./resolver\";\nimport type { Node } from \"./parser\";\nimport { Parser } from \"./parser\";\nimport { TemplatePlugin } from \"./plugins\";\n\n/**\n * Manages the view level validations\n */\nclass CrossfieldProvider implements ValidationProvider {\n  private allValidations = new Set<ValidationObject>();\n  private byBinding = new Map<BindingInstance, Array<ValidationObject>>();\n  private logger?: Logger;\n\n  constructor(initialView: ViewType, parser: BindingFactory, logger?: Logger) {\n    this.logger = logger;\n    this.parse(initialView, parser);\n  }\n\n  private parse(contentView: ViewType, parser: BindingFactory) {\n    const xfieldRefs = contentView.validation;\n\n    if (xfieldRefs === undefined) {\n      return;\n    }\n\n    if (!Array.isArray(xfieldRefs)) {\n      this.logger?.warn(\n        `Unable to register view validations for id: ${contentView.id}. 'validation' property must be an Array.`,\n      );\n\n      return;\n    }\n\n    // Grab the validations from the view (as authored) and parse out the ones that have a _ref_ (to a binding)\n    // Group them all by binding to make it easier to return than later\n\n    xfieldRefs.forEach((vRef) => {\n      // x-field validations by default are triggered by navigating away from the page\n      // the reference can also override that _or_ the severity\n      const withDefaults: ValidationObject = {\n        trigger: \"navigation\",\n        severity: \"error\",\n        ...vRef,\n      };\n\n      this.allValidations.add(withDefaults);\n\n      // The validation reference contains a _ref_ (a binding)\n      const { ref } = vRef;\n\n      if (ref) {\n        /** Group together validations by binding */\n        const parsed = parser(ref);\n\n        if (this.byBinding.has(parsed)) {\n          this.byBinding.get(parsed)?.push(withDefaults);\n        } else {\n          this.byBinding.set(parsed, [withDefaults]);\n        }\n      }\n    });\n  }\n\n  getValidationsForBinding(binding: BindingInstance) {\n    return this.byBinding.get(binding);\n  }\n}\n\nexport type ViewHooks = {\n  /** Hook every time there is an update to this view instance */\n  onUpdate: SyncHook<[ViewType]>;\n  /** Hook to retrieve the parser used for this view */\n  parser: SyncHook<[Parser]>;\n  /** Hook to retrieve the resolver used for this view */\n  resolver: SyncHook<[Resolver]>;\n  /** Hook to retrieve the template plugin used for this view */\n  templatePlugin: SyncHook<[TemplatePlugin]>;\n};\n\n/** A stateful view instance from an content */\nexport class ViewInstance implements ValidationProvider {\n  public hooks: ViewHooks = {\n    onUpdate: new SyncHook(),\n    parser: new SyncHook(),\n    resolver: new SyncHook(),\n    templatePlugin: new SyncHook(),\n  };\n\n  private resolver?: Resolver;\n  public readonly initialView: ViewType;\n  public readonly resolverOptions: Resolve.ResolverOptions;\n  private rootNode?: Node.Node;\n\n  private validationProvider?: CrossfieldProvider;\n\n  private templatePlugin: TemplatePlugin | undefined;\n\n  // TODO might want to add a version/timestamp to this to compare updates\n  public lastUpdate: Record<string, any> | undefined;\n\n  constructor(initialView: ViewType, resolverOptions: Resolve.ResolverOptions) {\n    this.initialView = initialView;\n    this.resolverOptions = resolverOptions;\n  }\n\n  /** @deprecated use ViewController.updateViewAST */\n  public updateAsync(asyncNode: string): void {\n    const update = this.resolver?.update();\n    this.lastUpdate = update;\n    this.hooks.onUpdate.call(update);\n  }\n\n  public update(\n    changes?: Set<BindingInstance>,\n    nodeChanges?: Set<Node.Node>,\n  ): any {\n    if (this.rootNode === undefined) {\n      /** On initialization of the view, also create a validation parser */\n      this.validationProvider = new CrossfieldProvider(\n        this.initialView,\n        this.resolverOptions.parseBinding,\n        this.resolverOptions.logger,\n      );\n\n      if (this.templatePlugin) {\n        this.hooks.templatePlugin.call(this.templatePlugin);\n      } else {\n        this.resolverOptions.logger?.warn(\n          \"templatePlugin not set for View, legacy templates may not work\",\n        );\n      }\n\n      const parser = new Parser();\n      this.hooks.parser.call(parser);\n      this.rootNode = parser.parseView(this.initialView);\n\n      this.resolver = new Resolver(this.rootNode, {\n        ...this.resolverOptions,\n        parseNode: parser.parseObject.bind(parser),\n      });\n      this.hooks.resolver.call(this.resolver);\n    }\n\n    const update = this.resolver?.update(changes, nodeChanges);\n\n    if (this.lastUpdate === update) {\n      return this.lastUpdate;\n    }\n\n    this.lastUpdate = update;\n    this.hooks.onUpdate.call(update);\n\n    return update;\n  }\n\n  getValidationsForBinding(\n    binding: BindingInstance,\n  ): Array<ValidationObject> | undefined {\n    return this.validationProvider?.getValidationsForBinding(binding);\n  }\n\n  public setTemplatePlugin(plugin: TemplatePlugin): void {\n    this.templatePlugin = plugin;\n  }\n}\n\n/** A plugin for a view */\nexport interface ViewPlugin {\n  /** Called with a view instance */\n  apply(view: ViewInstance): void;\n}\n","import { SyncHook, SyncWaterfallHook } from \"tapable-ts\";\nimport { addLast, clone, setIn } from \"timm\";\nimport dlv from \"dlv\";\nimport { dequal } from \"dequal\";\nimport type { BindingInstance, BindingLike } from \"../../binding\";\nimport type {\n  DataModelOptions,\n  DataModelWithParser,\n  Updates,\n} from \"../../data\";\nimport { DependencyModel, withParser } from \"../../data\";\nimport type { Logger } from \"../../logger\";\nimport { Node, NodeType } from \"../parser\";\nimport { caresAboutDataChanges, toNodeResolveOptions } from \"./utils\";\nimport type { Resolve } from \"./types\";\nimport { getNodeID } from \"../parser/utils\";\n\nexport * from \"./types\";\nexport * from \"./utils\";\n\ninterface NodeUpdate extends Resolve.ResolvedNode {\n  /** A flag to track if a node has changed since the last resolution */\n  updated: boolean;\n}\n\n/** Add model context to the data model */\nconst withContext = (model: DataModelWithParser): DataModelWithParser => {\n  return {\n    get: (binding: BindingLike, options?: DataModelOptions): any => {\n      return model.get(binding, {\n        context: { model },\n        ...options,\n      });\n    },\n\n    set: (\n      transaction: [BindingLike, any][],\n      options?: DataModelOptions,\n    ): Updates => {\n      return model.set(transaction, {\n        context: { model },\n        ...options,\n      });\n    },\n\n    delete: (binding: BindingLike, options?: DataModelOptions): void => {\n      return model.delete(binding, {\n        context: { model },\n        ...options,\n      });\n    },\n  };\n};\n\nexport type ResolverHooks = {\n  /** A hook to allow skipping of the resolution tree for a specific node */\n  skipResolve: SyncWaterfallHook<\n    [boolean, Node.Node, Resolve.NodeResolveOptions]\n  >;\n\n  /** An event emitted before calculating the next update */\n  beforeUpdate: SyncHook<[Set<BindingInstance> | undefined]>;\n\n  /** An event emitted after calculating the next update */\n  afterUpdate: SyncHook<[any]>;\n\n  /** The options passed to a node to resolve it to an object */\n  resolveOptions: SyncWaterfallHook<[Resolve.NodeResolveOptions, Node.Node]>;\n\n  /** A hook to transform the AST node into a new AST node before resolving it */\n  beforeResolve: SyncWaterfallHook<\n    [Node.Node | null, Resolve.NodeResolveOptions]\n  >;\n\n  /**\n   * A hook to transform an AST node into it's resolved value.\n   * This runs _before_ any children are resolved\n   */\n  resolve: SyncWaterfallHook<[any, Node.Node, Resolve.NodeResolveOptions]>;\n\n  /**\n   * A hook to transform the resolved value of an AST node.\n   * This runs _after_ all children nodes are resolved\n   */\n  afterResolve: SyncWaterfallHook<[any, Node.Node, Resolve.NodeResolveOptions]>;\n\n  /** Called at the very end of a node's tree being updated */\n  afterNodeUpdate: SyncHook<[Node.Node, Node.Node | undefined, NodeUpdate]>;\n};\n\n/**\n * The Resolver is the way to take a parsed AST graph of a view and resolve it to a concrete representation of the current user state\n * It combines the ability to mutate ast nodes before resolving, as well as the mutating the resolved objects while parsing\n */\nexport class Resolver {\n  public readonly hooks: ResolverHooks = {\n    skipResolve: new SyncWaterfallHook(),\n    beforeUpdate: new SyncHook(),\n    afterUpdate: new SyncHook(),\n    resolveOptions: new SyncWaterfallHook(),\n    beforeResolve: new SyncWaterfallHook(),\n    resolve: new SyncWaterfallHook(),\n    afterResolve: new SyncWaterfallHook(),\n    afterNodeUpdate: new SyncHook(),\n  };\n\n  /**\n   * The AST tree after beforeResolve is ran mapped to the AST before beforeResolve is ran\n   */\n  private readonly ASTMap: Map<Node.Node, Node.Node>;\n  /**\n   * The root node in the AST tree we want to resolve\n   */\n  public readonly root: Node.Node;\n\n  /**\n   * The cache of the last resolved values when walking the tree.\n   * This gets recycled every update to avoid stale data if a node is unused in an update\n   */\n  private resolveCache: Map<Node.Node, Resolve.ResolvedNode>;\n\n  /**\n   * Cache of node IDs that have been processed to track if nodes have duplicate IDs\n   */\n  private idCache: Set<string>;\n\n  /**\n   * The parameters required to resolve AST nodes\n   */\n  private readonly options: Resolve.ResolverOptions;\n\n  /**\n   * Tapable logger for logging errors encountered during view resolution\n   */\n  private logger?: Logger;\n\n  constructor(root: Node.Node, options: Resolve.ResolverOptions) {\n    this.root = root;\n    this.options = options;\n    this.resolveCache = new Map();\n    this.ASTMap = new Map();\n    this.logger = options.logger;\n    this.idCache = new Set();\n  }\n\n  public getSourceNode(convertedAST: Node.Node): Node.Node | undefined {\n    return this.ASTMap.get(convertedAST);\n  }\n\n  public update(\n    dataChanges?: Set<BindingInstance>,\n    nodeChanges?: Set<Node.Node>,\n  ): any {\n    this.hooks.beforeUpdate.call(dataChanges);\n    const resolveCache = new Map<Node.Node, Resolve.ResolvedNode>();\n    this.idCache.clear();\n    const prevASTMap = new Map(this.ASTMap);\n    this.ASTMap.clear();\n\n    // Optimization: Prefill node changes with parents to reduce time spent evaluating the cache validity in computeTree\n    const realNodeChanges = new Set<Node.Node>();\n    for (const node of nodeChanges?.values() ?? []) {\n      let current: Node.Node | undefined = node;\n      while (current) {\n        const original = prevASTMap.get(current) ?? current;\n        // Break early to avoid going up the tree on guaranteed duplicates.\n        if (realNodeChanges.has(original)) {\n          break;\n        }\n\n        realNodeChanges.add(original);\n        current = current.parent;\n      }\n    }\n\n    const updated = this.computeTree(\n      this.root,\n      undefined,\n      dataChanges,\n      resolveCache,\n      toNodeResolveOptions(this.options),\n      undefined,\n      prevASTMap,\n      realNodeChanges,\n    );\n    this.resolveCache = resolveCache;\n    this.hooks.afterUpdate.call(updated.value);\n    return updated.value;\n  }\n\n  public getResolveCache(): Map<Node.Node, Resolve.ResolvedNode> {\n    return new Map(this.resolveCache);\n  }\n\n  private getPreviousResult(node: Node.Node): Resolve.ResolvedNode | undefined {\n    if (!node) {\n      return;\n    }\n\n    const isFirstUpdate = this.resolveCache.size === 0;\n    const id = getNodeID(node);\n\n    if (id) {\n      if (this.idCache.has(id)) {\n        // Only log this conflict once to cut down on noise\n        // May want to swap this to logging when we first see the id -- which may not be the first render\n        if (isFirstUpdate) {\n          if (node.type === NodeType.Asset || node.type === NodeType.View) {\n            this.logger?.error(\n              `Cache conflict: Found Asset/View nodes that have conflicting ids: ${id}, may cause cache issues.`,\n            );\n          } else if (node.type === NodeType.Value) {\n            this.logger?.info(\n              `Cache conflict: Found Value nodes that have conflicting ids: ${id}, may cause cache issues. To improve performance make value node IDs globally unique.`,\n            );\n          }\n        }\n\n        // Don't use anything from a prev result if there's a duplicate id detected\n        return;\n      }\n\n      this.idCache.add(id);\n    }\n\n    return this.resolveCache.get(node);\n  }\n\n  private cloneNode(node: any) {\n    const clonedNode = clone(node);\n\n    Object.keys(clonedNode).forEach((key) => {\n      if (key === \"parent\") return;\n\n      const value = clonedNode[key];\n      if (typeof value === \"object\" && value !== null) {\n        clonedNode[key] = Array.isArray(value) ? [...value] : { ...value };\n      }\n    });\n\n    return clonedNode;\n  }\n\n  private computeTree(\n    node: Node.Node,\n    rawParent: Node.Node | undefined,\n    dataChanges: Set<BindingInstance> | undefined,\n    cacheUpdate: Map<Node.Node, Resolve.ResolvedNode>,\n    options: Resolve.NodeResolveOptions,\n    partiallyResolvedParent: Node.Node | undefined,\n    prevASTMap: Map<Node.Node, Node.Node>,\n    nodeChanges: Set<Node.Node>,\n  ): NodeUpdate {\n    const dependencyModel = new DependencyModel(options.data.model);\n\n    dependencyModel.trackSubset(\"core\");\n    const depModelWithParser = withContext(\n      withParser(dependencyModel, this.options.parseBinding),\n    );\n\n    const resolveOptions = this.hooks.resolveOptions.call(\n      {\n        ...options,\n        data: {\n          ...options.data,\n          model: depModelWithParser,\n        },\n        evaluate: (exp) =>\n          this.options.evaluator.evaluate(exp, { model: depModelWithParser }),\n        node,\n      },\n      node,\n    );\n\n    const previousResult = this.getPreviousResult(node);\n    const previousDeps = previousResult?.dependencies;\n\n    const isChanged = nodeChanges.has(node);\n    const dataChanged = caresAboutDataChanges(dataChanges, previousDeps);\n    const shouldUseLastValue = this.hooks.skipResolve.call(\n      !dataChanged && !isChanged,\n      node,\n      resolveOptions,\n    );\n\n    if (previousResult && shouldUseLastValue) {\n      const update = {\n        ...previousResult,\n        updated: false,\n      };\n\n      /** Recursively repopulate the AST map given some AST Node and it's resolved AST representation */\n      const repopulateASTMapFromCache = (\n        resolvedNode: Resolve.ResolvedNode,\n        AST: Node.Node,\n        ASTParent: Node.Node | undefined,\n      ) => {\n        const { node: resolvedASTLocal } = resolvedNode;\n        this.ASTMap.set(resolvedASTLocal, AST);\n        const resolvedUpdate = {\n          ...resolvedNode,\n          updated: false,\n        };\n        cacheUpdate.set(AST, resolvedUpdate);\n\n        /** Helper function for recursing over child node */\n        const handleChildNode = (childNode: Node.Node) => {\n          // In order to get the correct results, we need to use the node references from the last update.\n          const originalChildNode = prevASTMap.get(childNode) ?? childNode;\n          const previousChildResult = this.getPreviousResult(originalChildNode);\n          if (!previousChildResult) return;\n\n          repopulateASTMapFromCache(\n            previousChildResult,\n            originalChildNode,\n            AST,\n          );\n        };\n\n        if (\"children\" in resolvedASTLocal) {\n          resolvedASTLocal.children?.forEach(({ value: childAST }) =>\n            handleChildNode(childAST),\n          );\n        } else if (resolvedASTLocal.type === NodeType.MultiNode) {\n          resolvedASTLocal.values.forEach(handleChildNode);\n        }\n\n        this.hooks.afterNodeUpdate.call(AST, ASTParent, resolvedUpdate);\n      };\n\n      // Point the root of the cached node to the new resolved node.\n      previousResult.node.parent = partiallyResolvedParent;\n\n      repopulateASTMapFromCache(previousResult, node, rawParent);\n\n      return update;\n    }\n\n    // Shallow clone the node so that changes to it during the resolve steps don't impact the original.\n    // We are trusting that this becomes a deep clone once the whole node tree has been traversed.\n    const clonedNode: Node.Node = {\n      ...this.cloneNode(node),\n      parent: partiallyResolvedParent,\n    };\n    const resolvedAST = this.hooks.beforeResolve.call(\n      clonedNode,\n      resolveOptions,\n    ) ?? {\n      type: NodeType.Empty,\n    };\n\n    resolvedAST.parent = partiallyResolvedParent;\n\n    resolveOptions.node = resolvedAST;\n\n    this.ASTMap.set(resolvedAST, node);\n\n    let resolved = this.hooks.resolve.call(\n      undefined,\n      resolvedAST,\n      resolveOptions,\n    );\n\n    let updated = !dequal(previousResult?.value, resolved);\n\n    if (previousResult && !updated) {\n      resolved = previousResult?.value;\n    }\n\n    const childDependencies = new Set<BindingInstance>();\n    dependencyModel.trackSubset(\"children\");\n\n    if (\"children\" in resolvedAST) {\n      const newChildren = resolvedAST.children?.map((child) => {\n        const computedChildTree = this.computeTree(\n          child.value,\n          node,\n          dataChanges,\n          cacheUpdate,\n          resolveOptions,\n          resolvedAST,\n          prevASTMap,\n          nodeChanges,\n        );\n        const {\n          dependencies: childTreeDeps,\n          node: childNode,\n          updated: childUpdated,\n          value: childValue,\n        } = computedChildTree;\n\n        childTreeDeps.forEach((binding) => childDependencies.add(binding));\n\n        if (childValue) {\n          if (childNode.type === NodeType.MultiNode && !childNode.override) {\n            const arr = addLast(\n              dlv(resolved, child.path as any[], []),\n              childValue,\n            );\n            resolved = setIn(resolved, child.path, arr);\n          } else {\n            resolved = setIn(resolved, child.path, childValue);\n          }\n        }\n\n        updated = updated || childUpdated;\n\n        return { ...child, value: childNode };\n      });\n\n      resolvedAST.children = newChildren;\n    } else if (resolvedAST.type === NodeType.MultiNode) {\n      const childValue: any = [];\n      const rawParentToPassIn = node;\n\n      resolvedAST.values = resolvedAST.values.map((mValue) => {\n        const mTree = this.computeTree(\n          mValue,\n          rawParentToPassIn,\n          dataChanges,\n          cacheUpdate,\n          resolveOptions,\n          resolvedAST,\n          prevASTMap,\n          nodeChanges,\n        );\n\n        if (mTree.value !== undefined && mTree.value !== null) {\n          mTree.dependencies.forEach((bindingDep) =>\n            childDependencies.add(bindingDep),\n          );\n\n          updated = updated || mTree.updated;\n          childValue.push(mTree.value);\n        }\n\n        return mTree.node;\n      });\n\n      resolved = childValue;\n    }\n\n    childDependencies.forEach((bindingDep) =>\n      dependencyModel.addChildReadDep(bindingDep),\n    );\n\n    dependencyModel.trackSubset(\"core\");\n    if (previousResult && !updated) {\n      resolved = previousResult?.value;\n    }\n\n    resolved = this.hooks.afterResolve.call(resolved, resolvedAST, {\n      ...resolveOptions,\n      getDependencies: (scope?: \"core\" | \"children\") =>\n        dependencyModel.getDependencies(scope),\n    });\n\n    const update: NodeUpdate = {\n      node: resolvedAST,\n      updated,\n      value: resolved,\n      dependencies: new Set([\n        ...dependencyModel.getDependencies(),\n        ...childDependencies,\n      ]),\n    };\n\n    this.hooks.afterNodeUpdate.call(node, rawParent, update);\n    cacheUpdate.set(node, update);\n\n    return update;\n  }\n}\n","import { setIn } from \"timm\";\nimport { SyncBailHook, SyncWaterfallHook } from \"tapable-ts\";\nimport type { AnyAssetType, Node } from \"./types\";\nimport { NodeType } from \"./types\";\n\nexport * from \"./types\";\nexport * from \"./utils\";\n\nexport const EMPTY_NODE: Node.Empty = {\n  type: NodeType.Empty,\n};\n\nexport interface ParseObjectOptions {\n  /** how nested the templated is */\n  templateDepth?: number;\n}\n\nexport interface ParseObjectChildOptions {\n  key: string;\n  path: Node.PathSegment[];\n  parentObj: object;\n}\n\nexport type ParserHooks = {\n  /**\n   * A hook to interact with an object _before_ parsing it into an AST\n   *\n   * @param value - The object we're are about to parse\n   * @returns - A new value to parse.\n   *  If undefined, the original value is used.\n   *  If null, we stop parsing this node.\n   */\n  onParseObject: SyncWaterfallHook<[object, NodeType]>;\n  /**\n   * A callback to interact with an AST _after_ we parse it into the AST\n   *\n   * @param value - The object we parsed\n   * @param node - The AST node we generated\n   * @returns - A new AST node to use\n   *   If undefined, the original value is used.\n   *   If null, we ignore this node all together\n   */\n  onCreateASTNode: SyncWaterfallHook<[Node.Node | undefined | null, object]>;\n  /** A hook to call when parsing an object into an AST node\n   *\n   * @param obj - The object we're are about to parse\n   * @param nodeType - The type of node we're parsing\n   * @param parseOptions - Additional options when parsing\n   * @param childOptions - Additional options that are populated when the node being parsed is a child of another node\n   * @returns - A new AST node to use\n   *   If undefined, the original value is used.\n   *   If null, we ignore this node all together\n   */\n  parseNode: SyncBailHook<\n    [\n      obj: object,\n      nodeType: Node.ChildrenTypes,\n      parseOptions: ParseObjectOptions,\n      childOptions?: ParseObjectChildOptions,\n    ],\n    Node.Node | Node.Child[]\n  >;\n};\n\ninterface NestedObj {\n  /** The values of a nested local object */\n  children: Node.Child[];\n\n  value: any;\n}\n/**\n * The Parser is the way to take an incoming view from the user and parse it into an AST.\n * It provides a few ways to interact with the parsing, including mutating an object before and after creation of an AST node\n */\nexport class Parser {\n  public readonly hooks: ParserHooks = {\n    onParseObject: new SyncWaterfallHook(),\n    onCreateASTNode: new SyncWaterfallHook(),\n    parseNode: new SyncBailHook(),\n  };\n\n  public parseView(value: AnyAssetType): Node.View {\n    const viewNode = this.parseObject(value, NodeType.View);\n\n    if (!viewNode) {\n      throw new Error(\"Unable to parse object into a view\");\n    }\n\n    return viewNode as Node.View;\n  }\n\n  public createASTNode(node: Node.Node | null, value: any): Node.Node | null {\n    const tapped = this.hooks.onCreateASTNode.call(node, value);\n\n    if (tapped === undefined) {\n      return node;\n    }\n\n    return tapped;\n  }\n\n  public parseObject(\n    obj: object,\n    type: Node.ChildrenTypes = NodeType.Value,\n    options: ParseObjectOptions = { templateDepth: 0 },\n  ): Node.Node | null {\n    const parsedNode = this.hooks.parseNode.call(\n      obj,\n      type,\n      options,\n    ) as Node.Node | null;\n\n    if (parsedNode || parsedNode === null) {\n      return parsedNode;\n    }\n\n    const parseLocalObject = (\n      currentValue: any,\n      objToParse: unknown,\n      path: string[] = [],\n    ): NestedObj => {\n      if (typeof objToParse !== \"object\" || objToParse === null) {\n        return { value: objToParse, children: [] };\n      }\n\n      const localObj = this.hooks.onParseObject.call(objToParse, type);\n\n      if (!localObj) {\n        return currentValue;\n      }\n\n      const objEntries = Array.isArray(localObj)\n        ? localObj.map((v, i) => [i, v])\n        : [\n            ...Object.entries(localObj),\n            ...Object.getOwnPropertySymbols(localObj).map((s) => [\n              s,\n              (localObj as any)[s],\n            ]),\n          ];\n\n      const defaultValue: NestedObj = {\n        children: [],\n        value: currentValue,\n      };\n\n      const newValue = objEntries.reduce((accumulation, current): NestedObj => {\n        let { value } = accumulation;\n        const { children } = accumulation;\n        const [localKey, localValue] = current;\n\n        const newChildren = this.hooks.parseNode.call(\n          localValue,\n          NodeType.Value,\n          options,\n          {\n            path,\n            key: localKey,\n            parentObj: localObj,\n          },\n        ) as Node.Child[];\n\n        if (newChildren) {\n          children.push(...newChildren);\n        } else if (localValue && typeof localValue === \"object\") {\n          const result = parseLocalObject(accumulation.value, localValue, [\n            ...path,\n            localKey,\n          ]);\n\n          value = result.value;\n          children.push(...result.children);\n        } else {\n          value = setIn(accumulation.value, [...path, localKey], localValue);\n        }\n\n        return {\n          value,\n          children,\n        };\n      }, defaultValue);\n\n      return newValue;\n    };\n\n    const { value, children } = parseLocalObject(undefined, obj);\n\n    const baseAst =\n      value === undefined && !children.length\n        ? undefined\n        : {\n            type,\n            value,\n          };\n\n    if (baseAst && children.length) {\n      const parent: Node.BaseWithChildren<any> = baseAst;\n      parent.children = children;\n      children.forEach((child) => {\n        child.value.parent = parent;\n      });\n    }\n\n    return this.hooks.onCreateASTNode.call(baseAst, obj) ?? null;\n  }\n}\n","import type { Asset as AssetType, Expression, Binding } from \"@player-ui/types\";\n\nexport type AnyAssetType = AssetType<string>;\nexport enum NodeType {\n  Asset = \"asset\",\n  View = \"view\",\n  Applicability = \"applicability\",\n  Template = \"template\",\n  Value = \"value\",\n  MultiNode = \"multi-node\",\n  Switch = \"switch\",\n  Async = \"async\",\n  Unknown = \"unknown\",\n  Empty = \"empty\",\n}\nexport declare namespace Node {\n  export type ChildrenTypes = NodeType.Asset | NodeType.Value | NodeType.View;\n\n  export interface Base<T extends NodeType> {\n    /** Every node contains a type to distinguish it from other nodes */\n    type: T;\n\n    /** Every node (outside of the root) contains a reference to it's parent */\n    parent?: Node;\n  }\n\n  export type PathSegment = string | number;\n\n  export interface Child {\n    /** The path of the child relative to the parent */\n    path: PathSegment[];\n\n    /** If true, the path points to an array, and the value will be appended to it result */\n    array?: boolean;\n\n    /** The child node */\n    value: Node;\n  }\n\n  export interface BaseWithChildren<T extends NodeType> extends Base<T> {\n    /** Any node that contains a list of children underneath it */\n    children?: Child[];\n  }\n\n  export interface Asset<T extends AnyAssetType = AnyAssetType>\n    extends BaseWithChildren<NodeType.Asset>,\n      PluginOptions {\n    /** Any asset nested within a view */\n    value: T;\n  }\n\n  export interface View<T extends AnyAssetType = AnyAssetType>\n    extends BaseWithChildren<NodeType.View>,\n      PluginOptions {\n    /** The root of the parsed view */\n    value: T;\n  }\n\n  export interface Applicability extends Base<NodeType.Applicability> {\n    /** The expression to execute that determines applicability of the target node */\n    expression: Expression;\n\n    /** The node to use if the expression is truthy */\n    value: Node;\n  }\n\n  export interface Template extends Base<NodeType.Template> {\n    /** The location of an array in the model */\n    data: Binding;\n\n    /** The template to use when mapping over the data */\n    template: unknown;\n\n    /** The number of nested templates so far */\n    depth: number;\n\n    /** Should the template recompute when data changes */\n    dynamic?: boolean;\n\n    /** Specifies the template placement in relation to existing elements*/\n    placement?: \"prepend\" | \"append\";\n  }\n\n  export interface Value\n    extends BaseWithChildren<NodeType.Value>,\n      PluginOptions {\n    /** A simple node representing a value */\n    value: any;\n  }\n\n  export interface MultiNode extends Base<NodeType.MultiNode> {\n    /**\n     * Should this list override the target node if they overlap?\n     * If not amend the existing list\n     */\n    override?: boolean;\n\n    /** A list of values that comprise this node */\n    values: Array<Node>;\n  }\n\n  export interface Switch extends Base<NodeType.Switch> {\n    /** Should this list be re-computed when data changes */\n    dynamic?: boolean;\n\n    /** A list of cases to evaluate in order */\n    cases: SwitchCase[];\n  }\n\n  export interface SwitchCase {\n    /** The expression to evaluate for a single case statement */\n    case: Expression | true;\n    /** The value to use if this case is true */\n    value: Value;\n  }\n\n  export interface Async extends Base<NodeType.Async> {\n    /** The unique id of the node */\n    id: string;\n    /** The value representing the node */\n    value: Node;\n    /**\n     * Should the content streamed in be flattened during resolving\n     */\n    flatten?: boolean;\n    /** Function to run against parsed content from the node to manipulate the content before resolving it. */\n    onValueReceived?: (node: Node.Node) => Node.Node;\n  }\n\n  export interface PluginOptions {\n    /** A list of plugins */\n    plugins?: {\n      /** StringResolverPlugin options */\n      stringResolver?: {\n        /**\n         * An optional array of node properties to skip during string resolution\n         * Specified in the AssetTransformPlugin\n         */\n        propertiesToSkip?: string[];\n      };\n    };\n  }\n\n  export type Unknown = Base<NodeType.Unknown>;\n  export type Empty = Base<NodeType.Empty>;\n  export type ViewOrAsset = View | Asset;\n\n  export type Node =\n    | Asset\n    | Applicability\n    | Template\n    | Value\n    | View\n    | MultiNode\n    | Switch\n    | Async\n    | Unknown\n    | Empty;\n}\n","import type { Node } from \"./types\";\n\n/**\n * Checks if there are templated values in the object\n *\n * @param obj - The Parsed Object to check to see if we have a template array type for\n * @param localKey - The key being checked\n */\nexport function hasTemplateValues(obj: any, localKey: string) {\n  return (\n    Object.hasOwnProperty.call(obj, \"template\") &&\n    Array.isArray(obj?.template) &&\n    obj.template.length &&\n    obj.template.find((tmpl: any) => tmpl.output === localKey)\n  );\n}\n\n/** Check to see if the string is a valid switch key */\nexport function hasSwitchKey(localKey: string) {\n  return localKey === \"staticSwitch\" || localKey === \"dynamicSwitch\";\n}\n\n/** Check to see if the string is a valid template key */\nexport function hasTemplateKey(localKey: string) {\n  return localKey === \"template\";\n}\n\n/** Get the ID of the Node if there is one */\nexport function getNodeID(node?: Node.Node | null): string | undefined {\n  if (!node) {\n    return;\n  }\n\n  if (\n    \"value\" in node &&\n    typeof node.value === \"object\" &&\n    typeof node.value?.id === \"string\"\n  ) {\n    return node.value.id;\n  }\n}\n","import type { BindingInstance, BindingLike } from \"../../binding\";\nimport { isBinding } from \"../../binding\";\nimport type { ExpressionType } from \"../../expressions\";\nimport type { Resolve } from \"./types\";\n\n/** Check to see if and of the data-changes affect the given dependencies  */\nexport function caresAboutDataChanges(\n  dataChanges?: Set<BindingInstance>,\n  dependencies?: Set<BindingInstance>,\n) {\n  if (!dataChanges || !dependencies) {\n    return true;\n  }\n\n  const depArray = Array.from(dependencies.values());\n  const dataChangeArray = Array.from(dataChanges.values());\n\n  return (\n    depArray.find(\n      (dep) =>\n        !!dataChangeArray.find(\n          (change) =>\n            change === dep || change.contains(dep) || dep.contains(change),\n        ),\n    ) !== undefined\n  );\n}\n\n/** Convert the options object for a resolver to one for a node */\nexport function toNodeResolveOptions(\n  resolverOptions: Resolve.ResolverOptions,\n): Resolve.NodeResolveOptions {\n  return {\n    ...resolverOptions,\n    data: {\n      model: resolverOptions.model,\n      formatValue: (ref, value) => {\n        if (resolverOptions.formatValue) {\n          return resolverOptions.formatValue(ref, value);\n        }\n\n        return value;\n      },\n      format: (bindingLike: BindingLike, value: any) =>\n        resolverOptions.format\n          ? resolverOptions.format(\n              isBinding(bindingLike)\n                ? bindingLike\n                : resolverOptions.parseBinding(bindingLike),\n              value,\n            )\n          : value,\n    },\n    evaluate: (exp: ExpressionType) =>\n      resolverOptions.evaluator.evaluate(exp, resolverOptions),\n  };\n}\n","import type { Node, AnyAssetType } from \"../parser\";\nimport { NodeType } from \"../parser\";\n\n/**\n * Functions for building AST nodes (relatively) easily\n */\nexport class Builder {\n  /**\n   * Creates an asset node\n   *\n   * @param value - the value to put in the asset node\n   */\n  static asset<T extends AnyAssetType>(value: T): Node.Asset<T> {\n    return {\n      type: NodeType.Asset,\n      value,\n    };\n  }\n\n  static assetWrapper<T extends Node.Node>(value: T): Node.Value {\n    const valueNode = Builder.value();\n    Builder.addChild(valueNode, \"asset\", value);\n    return valueNode;\n  }\n\n  /**\n   * Creates a value node\n   *\n   * @param v - The object to put in the value node\n   */\n  static value(v?: object): Node.Value {\n    return {\n      type: NodeType.Value,\n      value: v,\n    };\n  }\n\n  /**\n   * Creates a multiNode and associates the multiNode as the parent\n   * of all the value nodes\n   *\n   * @param values - the value, applicability or async nodes to put in the multinode\n   */\n  static multiNode(\n    ...values: (Node.Value | Node.Applicability | Node.Async)[]\n  ): Node.MultiNode {\n    const m: Node.MultiNode = {\n      type: NodeType.MultiNode,\n      override: true,\n      values,\n    };\n\n    values.forEach((v) => {\n      v.parent = m;\n    });\n\n    return m;\n  }\n\n  /**\n   * Creates an async node\n   *\n   * @param id - the id of async node. It should be identical for each async node\n   */\n  static asyncNode(\n    id: string,\n    flatten = true,\n    onValueReceived?: (node: Node.Node) => Node.Node,\n  ): Node.Async {\n    return {\n      id,\n      type: NodeType.Async,\n      flatten: flatten,\n      onValueReceived,\n      value: {\n        type: NodeType.Value,\n        value: {\n          id,\n        },\n      },\n    };\n  }\n\n  /**\n   * Adds a child node to a node\n   *\n   * @param node - The node to add a child to\n   * @param path - The path at which to add the child\n   * @param child - The child node\n   */\n  static addChild<N extends Node.BaseWithChildren<NT>, NT extends NodeType>(\n    node: N,\n    path: Node.PathSegment | Node.PathSegment[],\n    child: Node.Node,\n  ): N {\n    child.parent = node as Node.Node;\n\n    const newChild: Node.Child = {\n      path: Array.isArray(path) ? path : [path],\n      value: child,\n    };\n\n    node.children = node.children || [];\n    node.children.push(newChild);\n\n    return node;\n  }\n\n  /**\n   * Updates children of a node of the same path and preserves order\n   *\n   * @param node - The node to update children for\n   * @param pathToMatch - The path to match against child paths\n   * @param mapFn - Function to transform matching children\n   */\n  static updateChildrenByPath<T extends Node.ViewOrAsset | Node.Value>(\n    node: T,\n    pathToMatch: Node.PathSegment[],\n    updateFn: (child: Node.Child) => Node.Node,\n  ): T {\n    if (!node.children) return node;\n\n    // Use map to preserve original order\n    const updatedChildren = node.children.map((child) =>\n      // Check if paths match exactly\n      child.path.join() === pathToMatch.join()\n        ? { ...child, value: updateFn(child) }\n        : child,\n    );\n\n    return {\n      ...node,\n      children: updatedChildren,\n    };\n  }\n}\n","import { SyncWaterfallHook } from \"tapable-ts\";\nimport type { Template } from \"@player-ui/types\";\nimport type {\n  Node,\n  ParseObjectOptions,\n  ParseObjectChildOptions,\n  Parser,\n} from \"../parser\";\nimport { NodeType } from \"../parser\";\nimport { ViewInstance, ViewPlugin } from \"../view\";\nimport type { Options } from \"./options\";\nimport type { Resolver } from \"../resolver\";\nimport { hasTemplateKey } from \"../parser/utils\";\n\nconst templateSymbol = Symbol(\"template\");\n\nexport interface TemplateItemInfo {\n  /** The index of the data for the current iteration of the template */\n  index: number;\n  /** The data for the current iteration of the template */\n  data: any;\n  /** The depth of the template node */\n  depth: number;\n}\n\nexport interface TemplateSubstitution {\n  /** Regular expression to find and replace. The global flag will be always be added to this expression. */\n  expression: string | RegExp;\n  /** The value to replace matches with. */\n  value: string;\n}\n\nexport type TemplateSubstitutionsFunc = (\n  baseSubstitutions: TemplateSubstitution[],\n  templateItemInfo: TemplateItemInfo,\n) => TemplateSubstitution[];\n\n/** A view plugin to resolve/manage templates */\nexport class TemplatePlugin implements ViewPlugin {\n  private readonly options: Options;\n\n  hooks: {\n    resolveTemplateSubstitutions: SyncWaterfallHook<\n      [TemplateSubstitution[], TemplateItemInfo],\n      Record<string, any>\n    >;\n  } = {\n    resolveTemplateSubstitutions: new SyncWaterfallHook<\n      [TemplateSubstitution[], TemplateItemInfo]\n    >(),\n  };\n\n  constructor(options: Options) {\n    this.options = options;\n  }\n\n  private parseTemplate(\n    parseObject: any,\n    node: Node.Template,\n    options: Options,\n  ): Node.Node | null {\n    const { template, depth } = node;\n    const data = options.data.model.get(node.data);\n\n    if (!data) {\n      return null;\n    }\n\n    if (!Array.isArray(data)) {\n      throw new Error(`Template using '${node.data}' but is not an array`);\n    }\n\n    const values: Array<Node.Node> = [];\n\n    data.forEach((dataItem, index) => {\n      const templateSubstitutions =\n        this.hooks.resolveTemplateSubstitutions.call(\n          [\n            {\n              expression: new RegExp(`_index${depth || \"\"}_`),\n              value: String(index),\n            },\n          ],\n          {\n            depth,\n            data: dataItem,\n            index,\n          },\n        );\n      let templateStr = JSON.stringify(template);\n\n      for (const { expression, value } of templateSubstitutions) {\n        let flags = \"g\";\n        if (typeof expression === \"object\") {\n          flags = `${expression.flags}${expression.global ? \"\" : \"g\"}`;\n        }\n\n        templateStr = templateStr.replace(new RegExp(expression, flags), value);\n      }\n\n      const parsed = parseObject(JSON.parse(templateStr), NodeType.Value, {\n        templateDepth: node.depth + 1,\n      });\n\n      if (parsed) {\n        values.push(parsed);\n      }\n    });\n\n    const result: Node.MultiNode = {\n      type: NodeType.MultiNode,\n      override: false,\n      values,\n    };\n\n    // Removes undefined Symbol property\n    if (node.placement !== undefined) {\n      (result as any)[templateSymbol] = node.placement;\n    }\n\n    return result;\n  }\n\n  applyParser(parser: Parser): void {\n    parser.hooks.onCreateASTNode.tap(\"template\", (node) => {\n      if (node && node.type === NodeType.Template && !node.dynamic) {\n        return this.parseTemplate(\n          parser.parseObject.bind(parser),\n          node,\n          this.options,\n        );\n      }\n\n      return node;\n    });\n\n    parser.hooks.onCreateASTNode.tap(\"template\", (node) => {\n      function getTemplateSymbolValue(node: Node.Node): string | undefined {\n        if (node.type === NodeType.MultiNode) {\n          return (node as any)[templateSymbol];\n        } else if (node.type === NodeType.Template) {\n          return node.placement;\n        }\n        return undefined;\n      }\n\n      if (\n        node &&\n        (node.type === NodeType.View || node.type === NodeType.Asset) &&\n        Array.isArray(node.children)\n      ) {\n        node.children = node.children.sort((a, b) => {\n          // compare template output with static values\n          const aPath = a.path.join();\n          const bPath = b.path.join();\n\n          const pathsEqual = aPath === bPath;\n\n          if (pathsEqual) {\n            const aPlacement = getTemplateSymbolValue(a.value);\n            const bPlacement = getTemplateSymbolValue(b.value);\n\n            if (aPlacement !== undefined && bPlacement === undefined) {\n              return aPlacement === \"prepend\" ? -1 : 1;\n            } else if (bPlacement !== undefined && aPlacement === undefined) {\n              return bPlacement === \"prepend\" ? 1 : -1;\n            } else if (aPlacement !== undefined && bPlacement !== undefined) {\n              // Both have placement values\n              if (aPlacement === bPlacement) {\n                return 0; // Same placement, no preference\n              }\n              // \"prepend\" should come before \"append\"\n              return aPlacement === \"prepend\" ? -1 : 1;\n            }\n            return 0;\n          }\n\n          // Trigger more sorting for nested assets\n          return aPath > bPath ? 1 : -1;\n        });\n      }\n\n      return node;\n    });\n\n    parser.hooks.parseNode.tap(\n      \"template\",\n      (\n        obj: any,\n        _nodeType: Node.ChildrenTypes,\n        options: ParseObjectOptions,\n        childOptions?: ParseObjectChildOptions,\n      ) => {\n        if (childOptions && hasTemplateKey(childOptions.key)) {\n          return obj\n            .map((template: Template) => {\n              const templateAST = parser.createASTNode(\n                {\n                  type: NodeType.Template,\n                  depth: options.templateDepth ?? 0,\n                  data: template.data,\n                  template: template.value,\n                  dynamic: template.dynamic ?? false,\n                  placement: template.placement,\n                },\n                template,\n              );\n\n              if (!templateAST) return;\n\n              if (templateAST.type === NodeType.MultiNode) {\n                templateAST.values.forEach((v) => {\n                  v.parent = templateAST;\n                });\n              }\n\n              return {\n                path: [...childOptions.path, template.output],\n                value: templateAST,\n              };\n            })\n            .filter(Boolean);\n        }\n      },\n    );\n  }\n\n  applyResolverHooks(resolver: Resolver): void {\n    // Transform dynamic templates into MultiNodes\n    resolver.hooks.beforeResolve.tap(\"template\", (node, options) => {\n      if (node && node.type === NodeType.Template && node.dynamic) {\n        return this.parseTemplate(options.parseNode, node, options);\n      }\n\n      return node;\n    });\n  }\n\n  apply(view: ViewInstance): void {\n    view.hooks.parser.tap(\"template\", this.applyParser.bind(this));\n    view.hooks.resolver.tap(\"template\", this.applyResolverHooks.bind(this));\n    view.setTemplatePlugin(this);\n  }\n}\n","import { set } from \"timm\";\nimport { resolveDataRefs } from \"../../string-resolver\";\nimport type { Options } from \"./options\";\nimport type { Node } from \"../parser\";\nimport { NodeType } from \"../parser\";\nimport type { Resolver } from \"../resolver\";\nimport { ViewInstance, ViewPlugin } from \"../view\";\n\n/** Create a function that checks for a start/end sequence in a string */\nconst createPatternMatcher = (start: string, end: string) => {\n  return (testStr: string) => {\n    const startLocation = testStr.indexOf(start);\n\n    if (startLocation === -1) {\n      return false;\n    }\n\n    const endLocation = testStr.indexOf(end);\n\n    if (endLocation === -1) {\n      return false;\n    }\n\n    return startLocation < endLocation;\n  };\n};\n\nconst bindingResolveLookup = createPatternMatcher(\"{{\", \"}}\");\nconst expressionResolveLookup = createPatternMatcher(\"@[\", \"]@\");\n\n/** Check to see if a string contains a reference to dynamic content */\nfunction hasSomethingToResolve(str: string) {\n  return bindingResolveLookup(str) || expressionResolveLookup(str);\n}\n\n/** Resolve data refs in a string if necessary. */\nfunction resolveString(str: string, resolveOptions: Options) {\n  return hasSomethingToResolve(str)\n    ? resolveDataRefs(str, {\n        model: resolveOptions.data.model,\n        evaluate: resolveOptions.evaluate,\n      })\n    : str;\n}\n\n/** Recursively resolve all string references in an object or array */\nexport function resolveAllRefs(\n  node: any,\n  resolveOptions: Options,\n  propertiesToSkip: Set<string | number>,\n): any {\n  if (\n    node === null ||\n    node === undefined ||\n    (typeof node !== \"object\" && typeof node !== \"string\")\n  ) {\n    return node;\n  }\n\n  if (typeof node === \"string\") {\n    return resolveString(node, resolveOptions);\n  }\n\n  let newNode = node;\n\n  Object.keys(node).forEach((key: string | number) => {\n    if (propertiesToSkip.has(key)) {\n      return;\n    }\n\n    const val = node[key];\n\n    let newVal = val;\n\n    if (typeof val === \"object\") {\n      newVal = resolveAllRefs(val, resolveOptions, propertiesToSkip);\n    } else if (typeof val === \"string\") {\n      newVal = resolveString(val, resolveOptions);\n    }\n\n    if (newVal !== val) {\n      newNode = set(newNode, key as any, newVal);\n    }\n  });\n\n  return newNode;\n}\n\n/** Traverse up the node tree finding the first available 'path' */\nconst findBasePath = (\n  node: Node.Node,\n  resolver: Resolver,\n): Node.PathSegment[] => {\n  const parentNode = node.parent;\n  if (!parentNode) {\n    return [];\n  }\n\n  if (\"children\" in parentNode) {\n    const original = resolver.getSourceNode(node);\n    return (\n      parentNode.children?.find((child) => child.value === original)?.path ?? []\n    );\n  }\n\n  if (parentNode.type !== NodeType.MultiNode) {\n    return [];\n  }\n\n  return findBasePath(parentNode, resolver);\n};\n\n/** A plugin that resolves all string references for each node */\nexport class StringResolverPlugin implements ViewPlugin {\n  private propertiesToSkipCache: Map<string, Set<string>>;\n\n  constructor() {\n    this.propertiesToSkipCache = new Map();\n  }\n\n  applyResolver(resolver: Resolver) {\n    resolver.hooks.resolve.tap(\"string-resolver\", (value, node, options) => {\n      if (node.type === NodeType.Empty || node.type === NodeType.Unknown) {\n        return null;\n      }\n\n      if (\n        node.type === NodeType.Value ||\n        node.type === NodeType.Asset ||\n        node.type === NodeType.View\n      ) {\n        /** Use specified properties to skip during string resolution, or default */\n        let propsToSkip: Set<string>;\n        if (node.type === NodeType.Asset || node.type === NodeType.View) {\n          propsToSkip = new Set(\n            node.plugins?.stringResolver?.propertiesToSkip ?? [\"exp\"],\n          );\n          if (node.value?.id) {\n            this.propertiesToSkipCache.set(node.value.id, propsToSkip);\n          }\n        } else if (\n          node.parent?.type === NodeType.MultiNode &&\n          (node.parent?.parent?.type === NodeType.Asset ||\n            node.parent?.parent?.type === NodeType.View) &&\n          node.parent.parent.value?.id &&\n          this.propertiesToSkipCache.has(node.parent.parent.value.id)\n        ) {\n          propsToSkip = this.propertiesToSkipCache.get(\n            node.parent.parent.value.id,\n          ) as Set<string>;\n        } else {\n          propsToSkip = new Set([\"exp\"]);\n        }\n\n        const nodePath = findBasePath(node, resolver);\n\n        /** If the path includes something that is supposed to be skipped, this node should be skipped too. */\n        if (\n          nodePath.length > 0 &&\n          nodePath.some((segment) => propsToSkip.has(segment.toString()))\n        ) {\n          return node.value;\n        }\n\n        return resolveAllRefs(node.value, options, propsToSkip);\n      }\n\n      return value;\n    });\n  }\n\n  apply(view: ViewInstance) {\n    view.hooks.resolver.tap(\"string-resolver\", this.applyResolver.bind(this));\n  }\n}\n","import { omit } from \"timm\";\nimport type { Options } from \"./options\";\nimport type { Resolver } from \"../resolver\";\nimport type {\n  Node,\n  ParseObjectOptions,\n  ParseObjectChildOptions,\n  Parser,\n} from \"../parser\";\nimport { NodeType } from \"../parser\";\nimport { ViewInstance, ViewPlugin } from \"../view\";\n\n/** A view plugin to remove inapplicable assets from the tree */\nexport class ApplicabilityPlugin implements ViewPlugin {\n  private isApplicability(obj: any) {\n    return obj && Object.prototype.hasOwnProperty.call(obj, \"applicability\");\n  }\n\n  applyResolver(resolver: Resolver) {\n    resolver.hooks.beforeResolve.tap(\n      \"applicability\",\n      (node: Node.Node | null, options: Options) => {\n        let newNode = node;\n\n        if (node?.type === NodeType.Applicability) {\n          const isApplicable = options.evaluate(node.expression);\n\n          if (isApplicable === false) {\n            return null;\n          }\n\n          newNode = node.value;\n        }\n\n        return newNode;\n      },\n    );\n  }\n\n  applyParser(parser: Parser) {\n    parser.hooks.parseNode.tap(\n      \"applicability\",\n      (\n        obj: any,\n        nodeType: Node.ChildrenTypes,\n        options: ParseObjectOptions,\n        childOptions?: ParseObjectChildOptions,\n      ) => {\n        if (this.isApplicability(obj)) {\n          const parsedApplicability = parser.parseObject(\n            omit(obj, \"applicability\"),\n            nodeType,\n            options,\n          );\n\n          if (!parsedApplicability) {\n            return childOptions ? [] : null;\n          }\n\n          const applicabilityNode = parser.createASTNode(\n            {\n              type: NodeType.Applicability,\n              expression: (obj as any).applicability,\n              value: parsedApplicability,\n            },\n            obj,\n          );\n\n          if (!applicabilityNode) {\n            return childOptions ? [] : null;\n          }\n\n          if (applicabilityNode.type === NodeType.Applicability) {\n            applicabilityNode.value.parent = applicabilityNode;\n          }\n\n          return childOptions\n            ? [\n                {\n                  path: [...childOptions.path, childOptions.key],\n                  value: applicabilityNode,\n                },\n              ]\n            : applicabilityNode;\n        }\n      },\n    );\n  }\n\n  apply(view: ViewInstance) {\n    view.hooks.resolver.tap(\"applicability\", this.applyResolver.bind(this));\n    view.hooks.parser.tap(\"applicability\", this.applyParser.bind(this));\n  }\n}\n","import { ViewInstance, ViewPlugin } from \"../view\";\nimport type { Options } from \"./options\";\nimport type {\n  Parser,\n  Node,\n  ParseObjectOptions,\n  ParseObjectChildOptions,\n} from \"../parser\";\nimport { EMPTY_NODE, NodeType } from \"../parser\";\nimport type { Resolver } from \"../resolver\";\nimport { hasSwitchKey } from \"../parser/utils\";\n\n/** A view plugin to resolve switches */\nexport class SwitchPlugin implements ViewPlugin {\n  private readonly options: Options;\n\n  constructor(options: Options) {\n    this.options = options;\n  }\n\n  private resolveSwitch(node: Node.Switch, options: Options): Node.Node {\n    for (const switchCase of node.cases) {\n      const isApplicable = options.evaluate(switchCase.case);\n      if (isApplicable) {\n        return switchCase.value;\n      }\n    }\n\n    return EMPTY_NODE;\n  }\n\n  private isSwitch(obj: any) {\n    return (\n      obj &&\n      (Object.prototype.hasOwnProperty.call(obj, \"dynamicSwitch\") ||\n        Object.prototype.hasOwnProperty.call(obj, \"staticSwitch\"))\n    );\n  }\n\n  applyParser(parser: Parser) {\n    /** Switches resolved during the parsing phase are static */\n    parser.hooks.onCreateASTNode.tap(\"switch\", (node) => {\n      if (node && node.type === NodeType.Switch && !node.dynamic) {\n        return this.resolveSwitch(node, this.options);\n      }\n\n      return node;\n    });\n\n    parser.hooks.parseNode.tap(\n      \"switch\",\n      (\n        obj: any,\n        _nodeType: Node.ChildrenTypes,\n        options: ParseObjectOptions,\n        childOptions?: ParseObjectChildOptions,\n      ) => {\n        if (\n          this.isSwitch(obj) ||\n          (childOptions && hasSwitchKey(childOptions.key))\n        ) {\n          const objToParse =\n            childOptions && hasSwitchKey(childOptions.key)\n              ? { [childOptions.key]: obj }\n              : obj;\n          const dynamic = \"dynamicSwitch\" in objToParse;\n          const switchContent = dynamic\n            ? objToParse.dynamicSwitch\n            : objToParse.staticSwitch;\n\n          const cases: Node.SwitchCase[] = switchContent\n            .map(\n              (switchCase: {\n                [x: string]: any;\n                /**\n                 *\n                 */\n                case: any;\n              }) => {\n                const { case: switchCaseExpr, ...switchBody } = switchCase;\n                const value = parser.parseObject(\n                  switchBody,\n                  NodeType.Value,\n                  options,\n                );\n\n                if (value) {\n                  return {\n                    case: switchCaseExpr,\n                    value: value as Node.Value,\n                  };\n                }\n\n                return;\n              },\n            )\n            .filter(Boolean);\n\n          const switchAST = parser.createASTNode(\n            {\n              type: NodeType.Switch,\n              dynamic,\n              cases,\n            },\n            objToParse,\n          );\n\n          if (!switchAST || switchAST.type === NodeType.Empty) {\n            return childOptions ? [] : null;\n          }\n\n          if (switchAST.type === NodeType.Switch) {\n            switchAST.cases.forEach((sCase) => {\n              sCase.value.parent = switchAST;\n            });\n          }\n\n          if (childOptions) {\n            let path = [...childOptions.path, childOptions.key];\n            let value: any = switchAST;\n\n            if (\n              switchAST.type === NodeType.Value &&\n              switchAST.children?.length === 1 &&\n              switchAST.value === undefined\n            ) {\n              const firstChild = switchAST.children[0];\n              path = [...path, ...firstChild.path];\n              value = firstChild.value;\n            }\n\n            return [{ path, value }];\n          }\n\n          return switchAST;\n        }\n      },\n    );\n  }\n\n  applyResolver(resolver: Resolver) {\n    /** Switches resolved during the parsing phase are dynamic */\n    resolver.hooks.beforeResolve.tap(\"switch\", (node, options) => {\n      if (node && node.type === NodeType.Switch && node.dynamic) {\n        return this.resolveSwitch(node, options);\n      }\n\n      return node;\n    });\n  }\n\n  apply(view: ViewInstance) {\n    view.hooks.parser.tap(\"switch\", this.applyParser.bind(this));\n    view.hooks.resolver.tap(\"switch\", this.applyResolver.bind(this));\n  }\n}\n","import { ViewInstance, ViewPlugin } from \"../view\";\nimport type {\n  Parser,\n  Node,\n  ParseObjectOptions,\n  ParseObjectChildOptions,\n} from \"../parser\";\nimport { NodeType } from \"../parser\";\nimport { hasTemplateValues, hasTemplateKey } from \"../parser/utils\";\n\n/** A view plugin to resolve multi nodes */\nexport class MultiNodePlugin implements ViewPlugin {\n  applyParser(parser: Parser): void {\n    parser.hooks.parseNode.tap(\n      \"multi-node\",\n      (\n        obj: any,\n        nodeType: Node.ChildrenTypes,\n        options: ParseObjectOptions,\n        childOptions?: ParseObjectChildOptions,\n      ) => {\n        if (\n          (childOptions === undefined || !hasTemplateKey(childOptions.key)) &&\n          Array.isArray(obj)\n        ) {\n          const values = obj\n            .map((childVal) =>\n              parser.parseObject(childVal, NodeType.Value, options),\n            )\n            .filter((child): child is Node.Node => !!child);\n\n          if (!values.length) {\n            return [];\n          }\n\n          const multiNode = parser.createASTNode(\n            {\n              type: NodeType.MultiNode,\n              override:\n                childOptions !== undefined &&\n                !hasTemplateValues(childOptions.parentObj, childOptions.key),\n              values,\n            },\n            obj,\n          );\n\n          if (!multiNode) {\n            return [];\n          }\n\n          if (multiNode.type === NodeType.MultiNode) {\n            multiNode.values.forEach((v) => {\n              v.parent = multiNode;\n            });\n          }\n\n          return childOptions === undefined\n            ? multiNode\n            : [\n                {\n                  path: [...childOptions.path, childOptions.key],\n                  value: multiNode,\n                },\n              ];\n        }\n      },\n    );\n  }\n\n  apply(view: ViewInstance): void {\n    view.hooks.parser.tap(\"multi-node\", this.applyParser.bind(this));\n  }\n}\n","import { ViewInstance, ViewPlugin } from \"../view\";\nimport type {\n  Parser,\n  Node,\n  ParseObjectOptions,\n  ParseObjectChildOptions,\n} from \"../parser\";\nimport { NodeType } from \"../parser\";\n\n/** A view plugin to resolve assets */\nexport class AssetPlugin implements ViewPlugin {\n  applyParser(parser: Parser) {\n    parser.hooks.parseNode.tap(\n      \"asset\",\n      (\n        obj: any,\n        nodeType: Node.ChildrenTypes,\n        options: ParseObjectOptions,\n        childOptions?: ParseObjectChildOptions,\n      ) => {\n        if (childOptions?.key === \"asset\" && typeof obj === \"object\") {\n          const assetAST = parser.parseObject(obj, NodeType.Asset, options);\n\n          if (!assetAST) {\n            return [];\n          }\n\n          return [\n            {\n              path: [...childOptions.path, childOptions.key],\n              value: assetAST,\n            },\n          ];\n        }\n      },\n    );\n  }\n\n  apply(view: ViewInstance) {\n    view.hooks.parser.tap(\"asset\", this.applyParser.bind(this));\n  }\n}\n","export interface Store {\n  useLocalState<T>(initialState: T): readonly [T, (value: T) => void];\n  useSharedState<T>(\n    key: string | symbol,\n  ): (initialState: T) => readonly [T, (value: T) => void];\n}\n\ninterface SharedStore {\n  getLocalStateFunction<T>(\n    key: string | symbol,\n    countKey: symbol,\n  ): (initialState: T) => readonly [T, (value: T) => void];\n  useSharedState<T>(\n    key: string | symbol,\n  ): (initialState: T) => readonly [T, (value: T) => void];\n}\n\n/** A store that holds on to state for a transform */\nexport class LocalStateStore implements SharedStore {\n  private state: Map<string | symbol, any>;\n\n  private updateCallback?: () => void;\n\n  constructor(onUpdate?: () => void) {\n    this.updateCallback = onUpdate;\n\n    this.state = new Map();\n  }\n\n  public removeKey(key: symbol | string) {\n    this.state.delete(key);\n  }\n\n  public reset() {\n    this.state.clear();\n  }\n\n  useSharedState<T>(key: string | symbol) {\n    return (initialState: T) => {\n      if (!this.state.has(key)) {\n        this.state.set(key, initialState);\n      }\n\n      return [\n        this.state.get(key) as T,\n        (newState: T) => {\n          const current = this.state.get(key) as T;\n\n          this.state.set(key, newState);\n\n          if (current !== newState) {\n            this.updateCallback?.();\n          }\n        },\n      ] as const;\n    };\n  }\n\n  getLocalStateFunction<T>(key: symbol, countKey: symbol) {\n    return (initialState: T) => {\n      // initialize if not already created\n      if (!this.state.has(key)) {\n        this.state.set(key, []);\n      }\n\n      if (!this.state.has(countKey)) {\n        this.state.set(countKey, 0);\n      }\n\n      const localState = this.state.get(key);\n      const oldCount = this.state.get(countKey);\n\n      this.state.set(countKey, oldCount + 1);\n\n      if (localState.length <= oldCount) {\n        localState.push(initialState);\n      }\n\n      const value = localState[oldCount] as T;\n\n      return [\n        value,\n        (newState: T) => {\n          const oldValue = localState[oldCount] as T;\n          localState[oldCount] = newState;\n\n          if (oldValue !== newState) {\n            this.updateCallback?.();\n          }\n        },\n      ] as const;\n    };\n  }\n}\n","import type { Node, ViewInstance } from \"..\";\nimport { NodeType } from \"..\";\nimport { LocalStateStore } from \"../../controllers/view/store\";\nimport type { TransformRegistry } from \"../../controllers/view/types\";\n\n/** Traverse up the nodes until the target is found */\nfunction findUp(node: Node.Node, target: Node.Node): boolean {\n  if (node === target) {\n    return true;\n  }\n\n  if (node.parent) {\n    return findUp(node.parent, target);\n  }\n\n  return false;\n}\n\n/**\n * A plugin to register custom transforms on certain asset types\n * This allows users to embed stateful data into transforms.\n */\nexport class AssetTransformCorePlugin {\n  public readonly stateStore: Map<Node.Node, LocalStateStore>;\n  private readonly registry: TransformRegistry;\n  private beforeResolveSymbol: symbol;\n  private resolveSymbol: symbol;\n  private beforeResolveCountSymbol: symbol;\n  private resolveCountSymbol: symbol;\n\n  constructor(registry: TransformRegistry) {\n    this.registry = registry;\n    this.stateStore = new Map();\n    this.beforeResolveSymbol = Symbol(\"before resolve\");\n    this.resolveSymbol = Symbol(\"resolve\");\n    this.beforeResolveCountSymbol = Symbol(\"before resolve count\");\n    this.resolveCountSymbol = Symbol(\"resolve count\");\n  }\n\n  apply(view: ViewInstance) {\n    // Clear out everything when we create a new view\n    this.stateStore.clear();\n\n    view.hooks.resolver.tap(\"asset-transform\", (resolver) => {\n      let lastUpdatedNode: Node.Node | undefined;\n\n      /** A function to update the state and trigger a view re-compute */\n      const updateState = (node: Node.Node) => {\n        lastUpdatedNode = node;\n        view.update(new Set());\n      };\n\n      /** Given a node and a transform step, fetch a local store */\n      const getStore = (node: Node.Node, stepKey: symbol) => {\n        let store: LocalStateStore;\n        const countKey =\n          stepKey === this.resolveSymbol\n            ? this.resolveCountSymbol\n            : this.beforeResolveCountSymbol;\n\n        const storedState = this.stateStore.get(node);\n\n        if (storedState) {\n          store = storedState;\n          store.removeKey(countKey);\n        } else {\n          store = new LocalStateStore(() => {\n            updateState(node);\n          });\n          this.stateStore.set(node, store);\n        }\n\n        return {\n          useSharedState: (\n            key: string | symbol,\n          ): (<T>(initialState: T) => readonly [T, (value: T) => void]) => {\n            return store.useSharedState(key);\n          },\n          useLocalState: <T>(initialState: T) => {\n            return store.getLocalStateFunction<T>(\n              stepKey,\n              countKey,\n            )(initialState);\n          },\n        };\n      };\n\n      resolver.hooks.beforeResolve.tap(\"asset-transform\", (node, options) => {\n        if (node && (node.type === \"asset\" || node.type === \"view\")) {\n          const transform = this.registry.get(node.value);\n\n          if (transform?.beforeResolve) {\n            const store = getStore(\n              options.node ?? node,\n              this.beforeResolveSymbol,\n            );\n\n            return transform.beforeResolve(node, options, store);\n          }\n        }\n\n        return node;\n      });\n\n      resolver.hooks.afterUpdate.tap(\"asset-transform\", () => {\n        lastUpdatedNode = undefined;\n      });\n\n      resolver.hooks.skipResolve.tap(\"asset-transform\", (skip, node) => {\n        if (!skip || !lastUpdatedNode) {\n          return skip;\n        }\n\n        const isParentOfUpdated = findUp(lastUpdatedNode, node);\n        const isChildOfUpdated = findUp(node, lastUpdatedNode);\n\n        return !isParentOfUpdated && !isChildOfUpdated;\n      });\n\n      resolver.hooks.afterResolve.tap(\n        \"asset-transform\",\n        (value, node, options) => {\n          if (node.type !== NodeType.Asset && node.type !== NodeType.View) {\n            return value;\n          }\n\n          const originalNode = resolver.getSourceNode(node);\n\n          if (!originalNode) {\n            return value;\n          }\n\n          const transform = this.registry.get(value);\n\n          if (transform?.resolve) {\n            const store = getStore(originalNode, this.resolveSymbol);\n\n            return transform?.resolve(value, options, store);\n          }\n\n          return value;\n        },\n      );\n    });\n  }\n}\n","import { setIn } from \"timm\";\nimport deferred from \"p-defer\";\nimport type { Flow, FlowResult } from \"@player-ui/types\";\nimport queueMicrotask from \"queue-microtask\";\n\nimport { SyncHook, SyncWaterfallHook } from \"tapable-ts\";\nimport type { Logger } from \"./logger\";\nimport { TapableLogger } from \"./logger\";\nimport type { ExpressionType } from \"./expressions\";\nimport { ExpressionEvaluator, isPromiseLike } from \"./expressions\";\nimport { SchemaController } from \"./schema\";\nimport { BindingParser } from \"./binding\";\nimport type { ViewInstance } from \"./view\";\nimport { resolveDataRefs } from \"./string-resolver\";\nimport type { FlowInstance } from \"./controllers\";\nimport {\n  ConstantsController,\n  ViewController,\n  DataController,\n  ValidationController,\n  FlowController,\n} from \"./controllers\";\nimport { FlowExpPlugin } from \"./plugins/flow-exp-plugin\";\nimport { DefaultExpPlugin } from \"./plugins/default-exp-plugin\";\nimport type {\n  PlayerFlowState,\n  InProgressState,\n  CompletedState,\n  ErrorState,\n  PlayerHooks,\n} from \"./types\";\nimport { NOT_STARTED_STATE } from \"./types\";\n\n/**\nVariables injected at build time\n*/\ndeclare global {\n  const __VERSION__: string;\n  const __GIT_COMMIT__: string;\n}\n\n// Version of Player at buildtime\nconst PLAYER_VERSION: string =\n  typeof __VERSION__ !== \"undefined\" ? __VERSION__ : \"unknown\";\n\n// HEAD commit used to build Player\nconst COMMIT: string =\n  typeof __GIT_COMMIT__ !== \"undefined\" ? __GIT_COMMIT__ : \"unknown\";\n\nexport interface PlayerPlugin {\n  /**\n   * Unique identifier of the plugin.\n   * Enables the plugin to be retrievable from Player.\n   */\n  symbol?: symbol;\n\n  /** The name of the plugin */\n  name: string;\n\n  /**\n   * Use this to tap into Player hooks\n   */\n  apply: (player: Player) => void;\n}\n\n// eslint-disable-next-line @typescript-eslint/no-empty-object-type\nexport interface ExtendedPlayerPlugin<\n  // eslint-disable-next-line @typescript-eslint/no-unused-vars\n  Assets = void,\n  // eslint-disable-next-line @typescript-eslint/no-unused-vars\n  Views = void,\n  // eslint-disable-next-line @typescript-eslint/no-unused-vars\n  Expressions = void,\n  // eslint-disable-next-line @typescript-eslint/no-unused-vars\n  DataTypes = void,\n> {}\n\nexport interface PlayerConfigOptions {\n  /** A set of plugins to load  */\n  plugins?: PlayerPlugin[];\n\n  /** A logger to use */\n  logger?: Logger;\n}\n\nexport interface PlayerInfo {\n  /** Version of the running player */\n  version: typeof PLAYER_VERSION;\n\n  /** Hash of the HEAD commit used to build the current version */\n  commit: typeof COMMIT;\n}\n\n/**\n * This is it.\n */\nexport class Player {\n  public static readonly info: PlayerInfo = {\n    version: PLAYER_VERSION,\n    commit: COMMIT,\n  };\n\n  public readonly logger: TapableLogger = new TapableLogger();\n  public readonly constantsController: ConstantsController =\n    new ConstantsController();\n  private config: PlayerConfigOptions;\n  private state: PlayerFlowState = NOT_STARTED_STATE;\n\n  public readonly hooks: PlayerHooks = {\n    flowController: new SyncHook<[FlowController]>(),\n    viewController: new SyncHook<[ViewController]>(),\n    view: new SyncHook<[ViewInstance]>(),\n    expressionEvaluator: new SyncHook<[ExpressionEvaluator]>(),\n    dataController: new SyncHook<[DataController]>(),\n    schema: new SyncHook<[SchemaController]>(),\n    validationController: new SyncHook<[ValidationController]>(),\n    bindingParser: new SyncHook<[BindingParser]>(),\n    state: new SyncHook<[PlayerFlowState]>(),\n    onStart: new SyncHook<[Flow]>(),\n    onEnd: new SyncHook<[]>(),\n    resolveFlowContent: new SyncWaterfallHook<[Flow]>(),\n  };\n\n  constructor(config?: PlayerConfigOptions) {\n    if (config?.logger) {\n      this.logger.addHandler(config.logger);\n    }\n\n    this.config = config || {};\n    this.config.plugins = [\n      new DefaultExpPlugin(),\n      ...(this.config.plugins || []),\n      new FlowExpPlugin(),\n    ];\n    this.config.plugins?.forEach((plugin) => {\n      plugin.apply(this);\n    });\n  }\n\n  /**  Returns currently registered plugins */\n  public getPlugins(): PlayerPlugin[] {\n    return this.config.plugins ?? [];\n  }\n\n  /** Find instance of [Plugin] that has been registered to Player */\n  public findPlugin<Plugin extends PlayerPlugin>(\n    symbol: symbol,\n  ): Plugin | undefined {\n    return this.config.plugins?.find((el) => el.symbol === symbol) as Plugin;\n  }\n\n  /** Retrieve an instance of [Plugin] and conditionally invoke [apply] if it exists */\n  public applyTo<Plugin extends PlayerPlugin>(\n    symbol: symbol,\n    apply: (plugin: Plugin) => void,\n  ): void {\n    const plugin = this.findPlugin<Plugin>(symbol);\n\n    if (plugin) {\n      apply(plugin);\n    }\n  }\n\n  /** Register and apply [Plugin] if one with the same symbol is not already registered. */\n  public registerPlugin(plugin: PlayerPlugin): void {\n    plugin.apply(this);\n    this.config.plugins?.push(plugin);\n  }\n\n  /** Returns the current version of the running player */\n  public getVersion(): string {\n    return Player.info.version;\n  }\n\n  /** Returns the git commit used to build Player version */\n  public getCommit(): string {\n    return Player.info.commit;\n  }\n\n  /**\n   * Fetch the current state of Player.\n   * It will return either `not-started`, `in-progress`, `completed`\n   * with some extra data in each\n   */\n  public getState(): PlayerFlowState {\n    return this.state;\n  }\n\n  /**\n   * A private means of setting the state of Player\n   * Calls the hooks for subscribers to listen for this event\n   */\n  private setState(state: PlayerFlowState) {\n    this.state = state;\n    this.hooks.state.call(state);\n  }\n\n  /** Start Player with the given flow */\n  private setupFlow(userContent: Flow): {\n    /** a callback to _actually_ start the flow */\n    start: () => void;\n\n    /** the state object to kick if off */\n    state: Omit<InProgressState, \"ref\">;\n  } {\n    const userFlow = this.hooks.resolveFlowContent.call(userContent);\n\n    const flowController = new FlowController(userFlow.navigation, {\n      logger: this.logger,\n    });\n\n    this.hooks.onStart.call(userFlow);\n\n    this.hooks.flowController.call(flowController);\n\n    // eslint-disable-next-line prefer-const\n    let expressionEvaluator: ExpressionEvaluator;\n    // eslint-disable-next-line prefer-const\n    let dataController: DataController;\n\n    const pathResolver = new BindingParser({\n      get: (binding) => {\n        return dataController.get(binding);\n      },\n      set: (transaction) => {\n        return dataController.set(transaction);\n      },\n      evaluate: (expression) => {\n        return expressionEvaluator.evaluate(expression);\n      },\n    });\n\n    this.hooks.bindingParser.call(pathResolver);\n    const parseBinding = pathResolver.parse;\n    const flowResultDeferred = deferred<FlowResult>();\n\n    const schema = new SchemaController(userFlow.schema);\n    this.hooks.schema.call(schema);\n\n    const validationController = new ValidationController(schema);\n\n    this.hooks.validationController.call(validationController);\n\n    dataController = new DataController(userFlow.data, {\n      pathResolver,\n      middleware: validationController.getDataMiddleware(),\n      logger: this.logger,\n    });\n\n    dataController.hooks.format.tap(\"player\", (value, binding) => {\n      const formatter = schema.getFormatter(binding);\n\n      return formatter ? formatter.format(value) : value;\n    });\n\n    dataController.hooks.deformat.tap(\"player\", (value, binding) => {\n      const formatter = schema.getFormatter(binding);\n\n      return formatter ? formatter.deformat(value) : value;\n    });\n\n    dataController.hooks.resolveDefaultValue.tap(\n      \"player\",\n      (binding) => schema.getApparentType(binding)?.default,\n    );\n\n    // eslint-disable-next-line prefer-const\n    let viewController: ViewController;\n\n    expressionEvaluator = new ExpressionEvaluator({\n      model: dataController,\n      logger: this.logger,\n    });\n\n    this.hooks.expressionEvaluator.call(expressionEvaluator);\n\n    expressionEvaluator.hooks.onError.tap(\"player\", (e) => {\n      flowResultDeferred.reject(e);\n\n      return true;\n    });\n\n    /** Resolve any data references in a string */\n    function resolveStrings<T>(val: T, formatted?: boolean) {\n      return resolveDataRefs(val, {\n        model: dataController,\n        evaluate: expressionEvaluator.evaluate,\n        formatted,\n      });\n    }\n\n    flowController.hooks.flow.tap(\"player\", (flow: FlowInstance) => {\n      flow.hooks.beforeTransition.tap(\"player\", (state, transitionVal) => {\n        /** Checks to see if there are any transitions for a specific transition state (i.e. next, back). If not, it will default to * */\n        const computedTransitionVal = state.transitions[transitionVal]\n          ? transitionVal\n          : \"*\";\n        if (state.onEnd && state.transitions[computedTransitionVal]) {\n          if (typeof state.onEnd === \"object\" && \"exp\" in state.onEnd) {\n            expressionEvaluator?.evaluate(state.onEnd.exp);\n          } else {\n            expressionEvaluator?.evaluate(state.onEnd as ExpressionType);\n          }\n        }\n\n        /** If the transition does not exist, then do not resolve any expressions */\n        if (\n          !(\"transitions\" in state) ||\n          !state.transitions[computedTransitionVal]\n        ) {\n          return state;\n        }\n\n        /** resolves and sets the transition to the computed exp */\n        return setIn(\n          state,\n          [\"transitions\", computedTransitionVal],\n          resolveStrings(state.transitions[computedTransitionVal]),\n        ) as any;\n      });\n\n      flow.hooks.skipTransition.tap(\"validation\", (currentState) => {\n        if (currentState?.value.state_type === \"VIEW\") {\n          const { canTransition, validations } =\n            validationController.validateView(\"navigation\");\n\n          if (!canTransition && validations) {\n            const bindings = new Set(validations.keys());\n            viewController?.currentView?.update(bindings);\n\n            return true;\n          }\n        }\n\n        return undefined;\n      });\n\n      flow.hooks.resolveTransitionNode.tap(\"player\", (state) => {\n        let newState = state;\n\n        if (\"ref\" in state) {\n          newState = setIn(state, [\"ref\"], resolveStrings(state.ref)) as any;\n        }\n\n        if (\"param\" in state) {\n          newState = setIn(\n            state,\n            [\"param\"],\n            resolveStrings(state.param, false),\n          ) as any;\n        }\n\n        return newState;\n      });\n\n      flow.hooks.transition.tap(\"player\", (_oldState, newState) => {\n        if (newState.value.state_type !== \"VIEW\") {\n          validationController.reset();\n        }\n      });\n\n      // Tap for action states\n      flow.hooks.afterTransition.tap(\"player-action-states\", (flowInstance) => {\n        const value = flowInstance.currentState?.value;\n        if (value && value.state_type === \"ASYNC_ACTION\") {\n          const { exp } = value;\n          // defer async execution to next tick to allow transition to settle\n          try {\n            const result = expressionEvaluator.evaluateAsync(exp);\n            if (isPromiseLike(result)) {\n              if (value.await) {\n                queueMicrotask(() => {\n                  result\n                    .then((r) => flowController?.transition(String(r)))\n                    .catch(flowResultDeferred.reject);\n                });\n              } else {\n                this.logger.warn(\n                  \"Unawaited promise used as return value in in non-async context, transitioning with '*' value\",\n                );\n                flowController?.transition(String(result));\n              }\n            } else {\n              this.logger.warn(\n                \"Non async expression used in async action node\",\n              );\n              flowController?.transition(String(result));\n            }\n          } catch (e) {\n            flowResultDeferred.reject(e);\n          }\n        } else if (value && value.state_type === \"ACTION\") {\n          // handle sync actions\n          const { exp } = value;\n          const result = expressionEvaluator.evaluate(exp);\n          if (isPromiseLike(result)) {\n            this.logger.warn(\n              \"Async expression used as return value in in non-async context, transitioning with '*' value\",\n            );\n          }\n          flowController?.transition(String(result));\n        }\n\n        expressionEvaluator.reset();\n      });\n    });\n\n    this.hooks.dataController.call(dataController);\n\n    validationController.setOptions({\n      parseBinding,\n      model: dataController,\n      logger: this.logger,\n      evaluate: expressionEvaluator.evaluate,\n      constants: this.constantsController,\n    });\n\n    viewController = new ViewController(userFlow.views || [], {\n      evaluator: expressionEvaluator,\n      parseBinding,\n      transition: flowController.transition,\n      model: dataController,\n      utils: {\n        findPlugin: <Plugin = unknown>(pluginSymbol: symbol) => {\n          return this.findPlugin(pluginSymbol) as unknown as Plugin;\n        },\n      },\n      logger: this.logger,\n      flowController,\n      schema,\n      format: (binding, value) => {\n        const formatter = schema.getFormatter(binding);\n\n        return formatter?.format ? formatter.format(value) : value;\n      },\n      formatValue: (ref, value) => {\n        const formatter = schema.getFormatterForType(ref);\n\n        return formatter?.format ? formatter.format(value) : value;\n      },\n      validation: {\n        ...validationController.forView(parseBinding),\n        type: (b) => schema.getType(parseBinding(b)),\n      },\n      constants: this.constantsController,\n    });\n\n    viewController.hooks.view.tap(\"player\", (view) => {\n      validationController.onView(view);\n      this.hooks.view.call(view);\n    });\n    this.hooks.viewController.call(viewController);\n\n    return {\n      start: () => {\n        flowController\n          .start()\n          .then((endState) => {\n            const flowResult: FlowResult = {\n              endState: resolveStrings(endState, false),\n              data: dataController.serialize(),\n            };\n\n            return flowResult;\n          })\n          .then(flowResultDeferred.resolve)\n          .catch((e) => {\n            this.logger.error(`Something went wrong: ${e.message}`);\n            throw e;\n          })\n          .catch(flowResultDeferred.reject)\n          .finally(() => this.hooks.onEnd.call());\n      },\n      state: {\n        status: \"in-progress\",\n        flowResult: flowResultDeferred.promise,\n        controllers: {\n          data: dataController,\n          view: viewController,\n          flow: flowController,\n          schema,\n          expression: expressionEvaluator,\n          binding: pathResolver,\n          validation: validationController,\n        },\n        fail: flowResultDeferred.reject,\n        flow: userFlow,\n        logger: this.logger,\n      },\n    };\n  }\n\n  public async start(payload: Flow): Promise<CompletedState> {\n    const ref = Symbol(payload?.id ?? \"payload\");\n\n    /** A check to avoid updating the state for a flow that's not the current one */\n    const maybeUpdateState = <T extends PlayerFlowState>(newState: T) => {\n      if (this.state.ref !== ref) {\n        this.logger.warn(\n          `Received update for a flow that's not the current one`,\n        );\n\n        return newState;\n      }\n\n      this.setState(newState);\n\n      return newState;\n    };\n\n    this.setState({\n      status: \"not-started\",\n      ref,\n    });\n\n    try {\n      const { state, start } = this.setupFlow(payload);\n      this.setState({\n        ref,\n        ...state,\n      });\n\n      start();\n\n      // common data for the end state\n      // make sure to use the same ref as the starting one\n      const endProps = {\n        ref,\n        status: \"completed\",\n        flow: state.flow,\n        controllers: {\n          data: state.controllers.data.makeReadOnly(),\n        },\n      } as const;\n\n      return maybeUpdateState({\n        ...(await state.flowResult),\n        ...endProps,\n      });\n    } catch (error: any) {\n      const errorState: ErrorState = {\n        status: \"error\",\n        ref,\n        flow: payload,\n        error,\n      };\n\n      maybeUpdateState(errorState);\n\n      throw error;\n    }\n  }\n}\n","import { SyncBailHook, SyncHook, SyncWaterfallHook } from \"tapable-ts\";\nimport type { DeferredPromise } from \"p-defer\";\nimport defer from \"p-defer\";\nimport type {\n  NavigationFlow,\n  NavigationFlowState,\n  NavigationFlowEndState,\n  NavigationFlowActionState,\n  NavigationFlowAsyncActionState,\n  NavigationFlowExternalState,\n  NavigationFlowFlowState,\n  NavigationFlowViewState,\n} from \"@player-ui/types\";\nimport type { Logger } from \"../../logger\";\n\nexport interface NamedState {\n  /** The name of the navigation node */\n  name: string;\n\n  /** The nav node */\n  value: NavigationFlowState;\n}\n\nexport interface TransitionOptions {\n  /** Ignore any validations or other signals preventing the transition from taking place  */\n  force?: boolean;\n}\nexport type TransitionFunction = (\n  name: string,\n  options?: TransitionOptions,\n) => void;\n\nexport interface FlowInstanceHooks {\n  beforeStart: SyncBailHook<\n    [NavigationFlow],\n    NavigationFlow,\n    Record<string, any>\n  >;\n  /** A callback when the onStart node was present */\n  onStart: SyncHook<[any], Record<string, any>>;\n  /** A callback when the onEnd node was present */\n  onEnd: SyncHook<[any], Record<string, any>>;\n  /** A hook to intercept and block a transition */\n  skipTransition: SyncBailHook<\n    [NamedState | undefined],\n    boolean | undefined,\n    Record<string, any>\n  >;\n  /** A chance to manipulate the flow-node used to calculate the given transition used  */\n  beforeTransition: SyncWaterfallHook<\n    [\n      (\n        | NavigationFlowViewState\n        | NavigationFlowFlowState\n        | NavigationFlowActionState\n        | NavigationFlowAsyncActionState\n        | NavigationFlowExternalState\n      ),\n      string,\n    ],\n    Record<string, any>\n  >;\n  /** A chance to manipulate the flow-node calculated after a transition */\n  resolveTransitionNode: SyncWaterfallHook<\n    [NavigationFlowState],\n    Record<string, any>\n  >;\n  /** A callback when a transition from 1 state to another was made */\n  transition: SyncHook<\n    [NamedState | undefined, NamedState],\n    Record<string, any>\n  >;\n  /** A callback to run actions after a transition occurs */\n  afterTransition: SyncHook<[FlowInstance], Record<string, any>>;\n}\n\n/** The Content navigation state machine */\nexport class FlowInstance {\n  private flow: NavigationFlow;\n  private log?: Logger;\n  private history: string[];\n  private isTransitioning = false;\n  private flowPromise?: DeferredPromise<NavigationFlowEndState>;\n  public readonly id: string;\n  public currentState?: NamedState;\n  public readonly hooks: FlowInstanceHooks = {\n    beforeStart: new SyncBailHook<[NavigationFlow], NavigationFlow>(),\n    onStart: new SyncHook<[any]>(),\n    onEnd: new SyncHook<[any]>(),\n    skipTransition: new SyncBailHook<\n      [NamedState | undefined],\n      boolean | undefined\n    >(),\n    beforeTransition: new SyncWaterfallHook<\n      [Exclude<NavigationFlowState, NavigationFlowEndState>, string]\n    >(),\n    resolveTransitionNode: new SyncWaterfallHook<[NavigationFlowState]>(),\n    transition: new SyncHook<[NamedState | undefined, NamedState]>(),\n    afterTransition: new SyncHook<[FlowInstance]>(),\n  };\n\n  constructor(\n    id: string,\n    flow: NavigationFlow,\n    options?: {\n      /** Logger instance to use */\n      logger?: Logger;\n    },\n  ) {\n    this.id = id;\n    this.flow = flow;\n    this.log = options?.logger;\n    this.history = [];\n\n    this.hooks.transition.tap(\n      \"startPromise\",\n      async (_oldState, nextState: NamedState) => {\n        const newState = nextState.value;\n\n        if (this.flowPromise && newState.state_type === \"END\") {\n          this.flowPromise.resolve(newState);\n        }\n      },\n    );\n  }\n\n  /** Start the state machine */\n  public async start(): Promise<NavigationFlowEndState> {\n    if (this.flowPromise) {\n      this.log?.warn(\"Already called start for flow\");\n\n      return this.flowPromise.promise;\n    }\n\n    this.flow = this.hooks.beforeStart.call(this.flow) || this.flow;\n\n    if (this.flow.onStart) {\n      this.hooks.onStart.call(this.flow.onStart);\n    }\n\n    const initialState = this.flow.startState;\n\n    if (!initialState) {\n      return Promise.reject(new Error(\"No 'startState' defined for flow\"));\n    }\n\n    this.flowPromise = defer();\n    this.pushHistory(initialState);\n\n    return this.flowPromise.promise;\n  }\n\n  public transition(\n    transitionValue: string,\n    options?: TransitionOptions,\n  ): void {\n    if (this.isTransitioning) {\n      throw new Error(\n        `Transitioning while ongoing transition from ${this.currentState?.name} is in progress is not supported`,\n      );\n    }\n\n    if (this.currentState?.value.state_type === \"END\") {\n      this.log?.warn(\n        `Skipping transition using ${transitionValue}. Already at and END state`,\n      );\n\n      return;\n    }\n\n    if (this.currentState === undefined) {\n      throw new Error(\"Cannot transition when there's no current state\");\n    }\n\n    if (options?.force) {\n      this.log?.debug(`Forced transition. Skipping validation checks`);\n    } else {\n      const skipTransition = this.hooks.skipTransition.call(this.currentState);\n\n      if (skipTransition) {\n        this.log?.debug(\n          `Skipping transition from ${this.currentState.name} b/c hook told us to`,\n        );\n        return;\n      }\n    }\n\n    const state = this.hooks.beforeTransition.call(\n      this.currentState.value,\n      transitionValue,\n    );\n\n    if (!(\"transitions\" in state)) {\n      throw new Error(`No transitions defined for ${this.currentState.value}`);\n    }\n\n    const { transitions } = state;\n    const nextState = transitions[transitionValue] || transitions[\"*\"];\n\n    if (nextState === undefined) {\n      this.log?.warn(\n        `No transition from ${this.currentState.name} using ${transitionValue} or *`,\n      );\n\n      return;\n    }\n\n    this.log?.debug(\n      `Transitioning from ${this.currentState.name} to ${nextState} using ${transitionValue} `,\n    );\n\n    return this.pushHistory(nextState, options);\n  }\n\n  private pushHistory(stateName: string, options?: TransitionOptions) {\n    if (!Object.prototype.hasOwnProperty.call(this.flow, stateName)) {\n      throw new Error(`No flow definition for: ${stateName} was found.`);\n    }\n\n    let nextState = this.flow[stateName];\n\n    if (\n      !this.flow[stateName] ||\n      typeof nextState !== \"object\" ||\n      !(\"state_type\" in nextState)\n    ) {\n      this.log?.error(`Flow doesn't contain any states named: ${stateName}`);\n\n      return;\n    }\n\n    const prevState = this.currentState;\n\n    this.isTransitioning = true;\n    nextState = this.hooks.resolveTransitionNode.call(nextState);\n\n    const newCurrentState = {\n      name: stateName,\n      value: nextState,\n    } as NamedState;\n    this.currentState = newCurrentState;\n    this.history.push(stateName);\n\n    // If the new state is an END state call the `onEnd` if it exists\n\n    if (newCurrentState.value.state_type === \"END\" && this.flow.onEnd) {\n      this.hooks.onEnd.call(this.flow.onEnd);\n    }\n\n    this.hooks.transition.call(prevState, {\n      ...newCurrentState,\n    });\n\n    this.isTransitioning = false;\n\n    this.hooks.afterTransition.call(this);\n  }\n}\n","import { SyncHook } from \"tapable-ts\";\nimport type { Navigation, NavigationFlowEndState } from \"@player-ui/types\";\nimport type { Logger } from \"../../logger\";\nimport type { TransitionOptions } from \"./flow\";\nimport { FlowInstance } from \"./flow\";\n\nexport interface FlowControllerHooks {\n  flow: SyncHook<[FlowInstance], Record<string, any>>;\n}\n\n/** A manager for the navigation section of a Content blob */\nexport class FlowController {\n  public readonly hooks: FlowControllerHooks = {\n    flow: new SyncHook<[FlowInstance]>(),\n  };\n\n  private readonly log?: Logger;\n  private navigation: Navigation;\n  private navStack: FlowInstance[];\n  public current?: FlowInstance;\n\n  constructor(\n    navigation: Navigation,\n    options?: {\n      /** A logger instance to use */\n      logger?: Logger;\n    },\n  ) {\n    this.navigation = navigation;\n    this.navStack = [];\n    this.log = options?.logger;\n\n    this.start = this.start.bind(this);\n    this.run = this.run.bind(this);\n    this.transition = this.transition.bind(this);\n    this.addNewFlow = this.addNewFlow.bind(this);\n  }\n\n  /** Navigate to another state in the state-machine */\n  public transition(\n    stateTransition: string,\n    options?: TransitionOptions,\n  ): void {\n    if (this.current === undefined) {\n      throw new Error(\"Not currently in a flow. Cannot transition.\");\n    }\n\n    this.current.transition(stateTransition, options);\n  }\n\n  private addNewFlow(flow: FlowInstance) {\n    this.navStack.push(flow);\n    this.current = flow;\n    this.hooks.flow.call(flow);\n  }\n\n  private async run(startState: string): Promise<NavigationFlowEndState> {\n    if (!Object.prototype.hasOwnProperty.call(this.navigation, startState)) {\n      return Promise.reject(new Error(`No flow defined for: ${startState}`));\n    }\n\n    const startFlow = this.navigation[startState];\n\n    if (startFlow === null || typeof startFlow !== \"object\") {\n      return Promise.reject(\n        new Error(`Flow: ${startState} needs to be an object`),\n      );\n    }\n\n    this.log?.debug(`Starting flow: ${startState}`);\n\n    const flow = new FlowInstance(startState, startFlow, { logger: this.log });\n    this.addNewFlow(flow);\n\n    flow.hooks.afterTransition.tap(\"flow-controller\", (flowInstance) => {\n      if (flowInstance.currentState?.value.state_type === \"FLOW\") {\n        const subflowId = flowInstance.currentState?.value.ref;\n        this.log?.debug(`Loading subflow ${subflowId}`);\n        this.run(subflowId).then((subFlowEndState) => {\n          this.log?.debug(\n            `Subflow ended. Using outcome: ${subFlowEndState.outcome}`,\n          );\n          flowInstance.transition(subFlowEndState?.outcome);\n        });\n      }\n    });\n\n    const end = await flow.start();\n    this.navStack.pop();\n\n    if (this.navStack.length > 0) {\n      const firstItem = 0;\n      this.current = this.navStack[firstItem];\n    }\n\n    return end;\n  }\n\n  public async start(): Promise<NavigationFlowEndState> {\n    if (!this.navigation.BEGIN) {\n      return Promise.reject(new Error(\"Must supply a BEGIN state\"));\n    }\n\n    return this.run(this.navigation.BEGIN);\n  }\n}\n","import type { Validation } from \"@player-ui/types\";\nimport { SyncHook, SyncWaterfallHook } from \"tapable-ts\";\nimport { setIn } from \"timm\";\n\nimport type { BindingInstance, BindingFactory } from \"../../binding\";\nimport { isBinding } from \"../../binding\";\nimport type { DataModelWithParser, DataModelMiddleware } from \"../../data\";\nimport type { SchemaController } from \"../../schema\";\nimport type {\n  ErrorValidationResponse,\n  ValidationObject,\n  ValidationObjectWithHandler,\n  ValidatorContext,\n  ValidationProvider,\n  ValidationResponse,\n  WarningValidationResponse,\n  StrongOrWeakBinding,\n} from \"../../validator\";\nimport {\n  ValidationMiddleware,\n  ValidatorRegistry,\n  removeBindingAndChildrenFromMap,\n} from \"../../validator\";\nimport type { Logger } from \"../../logger\";\nimport { ProxyLogger } from \"../../logger\";\nimport type { Resolve, ViewInstance } from \"../../view\";\nimport { caresAboutDataChanges } from \"../../view\";\nimport { replaceParams } from \"../../utils\";\nimport { resolveDataRefs } from \"../../string-resolver\";\nimport type {\n  ExpressionEvaluatorOptions,\n  ExpressionType,\n} from \"../../expressions\";\nimport type { BindingTracker } from \"./binding-tracker\";\nimport { ValidationBindingTrackerViewPlugin } from \"./binding-tracker\";\n\nexport const SCHEMA_VALIDATION_PROVIDER_NAME = \"schema\";\nexport const VIEW_VALIDATION_PROVIDER_NAME = \"view\";\n\nexport const VALIDATION_PROVIDER_NAME_SYMBOL: unique symbol = Symbol.for(\n  \"validation-provider-name\",\n);\n\nexport type ValidationObjectWithSource = ValidationObjectWithHandler & {\n  /** The name of the validation */\n  [VALIDATION_PROVIDER_NAME_SYMBOL]: string;\n};\n\ntype SimpleValidatorContext = Omit<\n  ValidatorContext,\n  \"validation\" | \"schemaType\"\n>;\n\ninterface BaseActiveValidation<T> {\n  /** The validation is being actively shown */\n  state: \"active\";\n\n  /** The validation response */\n  response: T;\n}\n\ntype ActiveWarning = BaseActiveValidation<WarningValidationResponse> & {\n  /** Warnings track if they can be dismissed automatically (by navigating) */\n  dismissable: boolean;\n};\ntype ActiveError = BaseActiveValidation<ErrorValidationResponse>;\n\n/**\n * warnings that keep track of their active state\n */\ntype StatefulWarning = {\n  /** A common key to differentiate between errors and warnings */\n  type: \"warning\";\n\n  /** The underlying validation this tracks */\n  value: ValidationObjectWithSource;\n\n  /** If this is currently preventing navigation from continuing */\n  isBlockingNavigation: boolean;\n} & (\n  | {\n      /** warnings start with no state, but can active or dismissed */\n      state: \"none\" | \"dismissed\";\n    }\n  | ActiveWarning\n);\n\n/** Errors that keep track of their state */\ntype StatefulError = {\n  /** A common key to differentiate between errors and warnings */\n  type: \"error\";\n\n  /** The underlying validation this tracks */\n  value: ValidationObjectWithSource;\n\n  /** If this is currently preventing navigation from continuing */\n  isBlockingNavigation: boolean;\n} & (\n  | {\n      /** Errors start with no state an can be activated */\n      state: \"none\";\n    }\n  | ActiveError\n);\n\nexport type StatefulValidationObject = StatefulWarning | StatefulError;\n\n/** Helper function to determin if the subset is within the containingSet */\nfunction isSubset<T>(subset: Set<T>, containingSet: Set<T>): boolean {\n  if (subset.size > containingSet.size) return false;\n  for (const entry of subset) if (!containingSet.has(entry)) return false;\n  return true;\n}\n\n/** Helper for initializing a validation object that tracks state */\nfunction createStatefulValidationObject(\n  obj: ValidationObjectWithSource,\n): StatefulValidationObject {\n  return {\n    value: obj,\n    type: obj.severity,\n    state: \"none\",\n    isBlockingNavigation: false,\n  };\n}\n\ntype ValidationRunner = (obj: ValidationObjectWithHandler) =>\n  | {\n      /** A validation message */\n      message: string;\n    }\n  | undefined;\n\n/** A class that manages validating bindings across phases */\nclass ValidatedBinding {\n  public currentPhase?: Validation.Trigger;\n  private applicableValidations: Array<StatefulValidationObject> = [];\n  private validationsByState: Record<\n    Validation.Trigger,\n    Array<StatefulValidationObject>\n  > = {\n    load: [],\n    change: [],\n    navigation: [],\n  };\n\n  public get allValidations(): Array<StatefulValidationObject> {\n    return Object.values(this.validationsByState).flat();\n  }\n\n  public weakBindings: Set<BindingInstance>;\n\n  private onDismiss?: () => void;\n\n  constructor(\n    possibleValidations: Array<ValidationObjectWithSource>,\n    onDismiss?: () => void,\n    log?: Logger,\n    weakBindings?: Set<BindingInstance>,\n  ) {\n    this.onDismiss = onDismiss;\n    possibleValidations.forEach((vObj) => {\n      const { trigger } = vObj;\n\n      if (this.validationsByState[trigger]) {\n        const statefulValidationObject = createStatefulValidationObject(vObj);\n        this.validationsByState[trigger].push(statefulValidationObject);\n      } else {\n        log?.warn(`Unknown validation trigger: ${trigger}`);\n      }\n    });\n    this.weakBindings = weakBindings ?? new Set();\n  }\n\n  private checkIfBlocking(statefulObj: StatefulValidationObject) {\n    if (statefulObj.state === \"active\") {\n      const { isBlockingNavigation } = statefulObj;\n      return isBlockingNavigation;\n    }\n\n    return false;\n  }\n\n  public getAll(): Array<ValidationResponse> {\n    return this.applicableValidations.reduce((all, statefulObj) => {\n      if (statefulObj.state === \"active\" && statefulObj.response) {\n        all.push({\n          ...statefulObj.response,\n          blocking: this.checkIfBlocking(statefulObj),\n        });\n      }\n\n      return all;\n    }, [] as Array<ValidationResponse>);\n  }\n\n  public get(): ValidationResponse | undefined {\n    const firstInvalid = this.applicableValidations.find((statefulObj) => {\n      return statefulObj.state === \"active\" && statefulObj.response;\n    });\n\n    if (firstInvalid?.state === \"active\") {\n      return {\n        ...firstInvalid.response,\n        blocking: this.checkIfBlocking(firstInvalid),\n      };\n    }\n  }\n\n  private runApplicableValidations(\n    runner: ValidationRunner,\n    canDismiss: boolean,\n    phase: Validation.Trigger,\n  ) {\n    // If the currentState is not load, skip those\n    this.applicableValidations = this.applicableValidations.map(\n      (originalValue) => {\n        if (originalValue.state === \"dismissed\") {\n          // Don't rerun any dismissed warnings\n          return originalValue;\n        }\n\n        // treat all warnings the same and block it once (unless blocking is true)\n        const blocking =\n          originalValue.value.blocking ??\n          ((originalValue.value.severity === \"warning\" && \"once\") || true);\n\n        const obj = setIn(\n          originalValue,\n          [\"value\", \"blocking\"],\n          blocking,\n        ) as StatefulValidationObject;\n\n        const isBlockingNavigation =\n          blocking === true || (blocking === \"once\" && !canDismiss);\n\n        if (\n          phase === \"navigation\" &&\n          obj.state === \"active\" &&\n          obj.value.blocking !== true\n        ) {\n          if (obj.value.severity === \"warning\") {\n            const warn = obj as ActiveWarning;\n            if (\n              warn.dismissable &&\n              warn.response.dismiss &&\n              (warn.response.blocking !== \"once\" || !warn.response.blocking)\n            ) {\n              warn.response.dismiss();\n            } else {\n              if (warn?.response.blocking === \"once\") {\n                warn.response.blocking = false;\n              }\n\n              warn.dismissable = true;\n            }\n\n            return warn as StatefulValidationObject;\n          }\n        }\n\n        const response = runner(obj.value);\n\n        const newState = {\n          type: obj.type,\n          value: obj.value,\n          state: response ? \"active\" : \"none\",\n          isBlockingNavigation,\n          dismissable:\n            obj.value.severity === \"warning\" && phase === \"navigation\",\n          response: response\n            ? {\n                ...obj.value,\n                message: response.message ?? \"Something is broken\",\n                severity: obj.value.severity,\n                displayTarget: obj.value.displayTarget ?? \"field\",\n              }\n            : undefined,\n        } as StatefulValidationObject;\n\n        if (newState.state === \"active\" && obj.value.severity === \"warning\") {\n          (newState.response as WarningValidationResponse).dismiss = () => {\n            (newState as StatefulWarning).state = \"dismissed\";\n            this.onDismiss?.();\n          };\n        }\n\n        return newState;\n      },\n    );\n  }\n\n  public update(\n    phase: Validation.Trigger,\n    canDismiss: boolean,\n    runner: ValidationRunner,\n  ) {\n    const newApplicableValidations: StatefulValidationObject[] = [];\n\n    if (phase === \"load\" && this.currentPhase !== undefined) {\n      // Tried to run the 'load' phase twice. Aborting\n      return;\n    }\n\n    if (this.currentPhase === \"navigation\" || phase === this.currentPhase) {\n      // Already added all the types. No need to continue adding new validations\n      this.runApplicableValidations(runner, canDismiss, phase);\n      return;\n    }\n\n    if (phase === \"load\") {\n      this.currentPhase = \"load\";\n      this.applicableValidations = [...this.validationsByState.load];\n    } else if (phase === \"change\" && this.currentPhase === \"load\") {\n      this.currentPhase = \"change\";\n      // The transition to the 'change' type can only come from a 'load' type\n      this.applicableValidations = [\n        ...this.applicableValidations,\n        ...this.validationsByState.change,\n      ];\n    } else if (\n      phase === \"navigation\" &&\n      (this.currentPhase === \"load\" || this.currentPhase === \"change\")\n    ) {\n      // Can transition to a nav state from a change or load\n\n      // if there is an non-blocking error that is active then remove the error from applicable validations so it can no longer be shown\n      // which is needed if there are additional warnings to become active for that binding after the error is shown\n      this.applicableValidations.forEach((element) => {\n        if (\n          !(\n            element.type === \"error\" &&\n            element.state === \"active\" &&\n            element.isBlockingNavigation === false\n          )\n        ) {\n          newApplicableValidations.push(element);\n        }\n      });\n\n      this.applicableValidations = [\n        ...newApplicableValidations,\n        ...this.validationsByState.navigation,\n        ...(this.currentPhase === \"load\" ? this.validationsByState.change : []),\n      ];\n      this.currentPhase = \"navigation\";\n    }\n\n    this.runApplicableValidations(runner, canDismiss, phase);\n  }\n}\n\n/**\n * A controller for orchestrating validation within a running player\n *\n * The current validation flow is as follows:\n *\n *   - When a binding is first seen, gather all of the possible validations for it from the providers\n *     - Schema and Crossfield (view) are both providers of possible validations\n *     - Run all of the applicable validations for that binding for the `load` trigger\n *\n *   - When a change occurs, set the phase of the binding to `change`.\n *     - Run all of the `change` triggered validations for that binding.\n *\n *   - When a navigation event occurs, set the phase of the binding to `navigate`.\n *     - Run all `change` and `navigate` validations for each tracked binding.\n *     - For any warnings, also keep a state of `shown` or `dismissed`.\n *       - Set all non-dismissed warnings to `shown`.\n *       - Set all `shown` warnings to `dismissed`.\n *     - Allow navigation forward if there are no non-dismissed warnings and no valid errors.\n */\nexport class ValidationController implements BindingTracker {\n  public readonly hooks = {\n    /** A hook called to tap into the validator registry for adding more validators */\n    createValidatorRegistry: new SyncHook<[ValidatorRegistry]>(),\n\n    /** A callback/event when a new validation is added to the view */\n    onAddValidation: new SyncWaterfallHook<\n      [ValidationResponse, BindingInstance]\n    >(),\n\n    /** The inverse of onAddValidation, this is called when a validation is removed from the list */\n    onRemoveValidation: new SyncWaterfallHook<\n      [ValidationResponse, BindingInstance]\n    >(),\n\n    resolveValidationProviders: new SyncWaterfallHook<\n      [\n        Array<{\n          /** The name of the provider */\n          source: string;\n          /** The provider itself */\n          provider: ValidationProvider;\n        }>,\n      ],\n      {\n        /** The view this is triggered for  */\n        view?: ViewInstance;\n      }\n    >(),\n\n    /** A hook called when a binding is added to the tracker */\n    onTrackBinding: new SyncHook<[BindingInstance]>(),\n  };\n\n  private tracker: BindingTracker | undefined;\n  private validations = new Map<BindingInstance, ValidatedBinding>();\n  private validatorRegistry?: ValidatorRegistry;\n  private schema: SchemaController;\n\n  private providers:\n    | Array<{\n        /** The name of the provider */\n        source: string;\n        /** The provider itself */\n        provider: ValidationProvider;\n      }>\n    | undefined;\n\n  private viewValidationProvider?: ValidationProvider;\n  private options?: SimpleValidatorContext;\n  private weakBindingTracker = new Set<BindingInstance>();\n\n  constructor(schema: SchemaController, options?: SimpleValidatorContext) {\n    this.schema = schema;\n    this.options = options;\n    this.reset();\n  }\n\n  setOptions(options: SimpleValidatorContext) {\n    this.options = options;\n  }\n\n  /** Return the middleware for the data-model to stop propagation of invalid data */\n  public getDataMiddleware(): Array<DataModelMiddleware> {\n    return [\n      {\n        set: (transaction, options, next) => {\n          return next?.set(transaction, options) ?? [];\n        },\n        get: (binding, options, next) => {\n          return next?.get(binding, options);\n        },\n        delete: (binding, options, next) => {\n          this.validations = removeBindingAndChildrenFromMap(\n            this.validations,\n            binding,\n          );\n\n          return next?.delete(binding, options);\n        },\n      },\n      new ValidationMiddleware(\n        (binding) => {\n          if (!this.options) {\n            return;\n          }\n\n          this.updateValidationsForBinding(binding, \"change\", this.options);\n          const strongValidation = this.getValidationForBinding(binding);\n\n          // return validation issues directly on bindings first\n          if (strongValidation?.get()?.severity === \"error\") {\n            return strongValidation.get();\n          }\n\n          // if none, check to see any validations this binding may be a weak ref of and return\n          const newInvalidBindings: Set<StrongOrWeakBinding> = new Set();\n          this.validations.forEach((weakValidation, strongBinding) => {\n            if (\n              caresAboutDataChanges(\n                new Set([binding]),\n                weakValidation.weakBindings,\n              ) &&\n              weakValidation?.get()?.severity === \"error\"\n            ) {\n              weakValidation?.weakBindings.forEach((weakBinding) => {\n                if (weakBinding === strongBinding) {\n                  newInvalidBindings.add({\n                    binding: weakBinding,\n                    isStrong: true,\n                  });\n                } else {\n                  newInvalidBindings.add({\n                    binding: weakBinding,\n                    isStrong: false,\n                  });\n                }\n              });\n            }\n          });\n\n          if (newInvalidBindings.size > 0) {\n            return newInvalidBindings;\n          }\n        },\n        { logger: new ProxyLogger(() => this.options?.logger) },\n      ),\n    ];\n  }\n\n  private getValidationProviders() {\n    if (this.providers) {\n      return this.providers;\n    }\n\n    this.providers = this.hooks.resolveValidationProviders.call([\n      {\n        source: SCHEMA_VALIDATION_PROVIDER_NAME,\n        provider: this.schema,\n      },\n      {\n        source: VIEW_VALIDATION_PROVIDER_NAME,\n        provider: {\n          getValidationsForBinding: (\n            binding: BindingInstance,\n          ): Array<ValidationObject> | undefined => {\n            return this.viewValidationProvider?.getValidationsForBinding?.(\n              binding,\n            );\n          },\n\n          getValidationsForView: (): Array<ValidationObject> | undefined => {\n            return this.viewValidationProvider?.getValidationsForView?.();\n          },\n        },\n      },\n    ]);\n\n    return this.providers;\n  }\n\n  public reset() {\n    this.validations.clear();\n    this.tracker = undefined;\n  }\n\n  public onView(view: ViewInstance): void {\n    this.validations.clear();\n    if (!this.options) {\n      return;\n    }\n\n    const bindingTrackerPlugin = new ValidationBindingTrackerViewPlugin({\n      ...this.options,\n      callbacks: {\n        onAdd: (binding) => {\n          if (\n            !this.options ||\n            this.getValidationForBinding(binding) !== undefined\n          ) {\n            return;\n          }\n\n          // Set the default value for the binding if we need to\n          const originalValue = this.options.model.get(binding);\n          const withoutDefault = this.options.model.get(binding, {\n            ignoreDefaultValue: true,\n          });\n\n          if (originalValue !== withoutDefault) {\n            // Don't trigger updates when setting the default value\n            this.options.model.set([[binding, originalValue]], {\n              silent: true,\n            });\n          }\n\n          this.updateValidationsForBinding(\n            binding,\n            \"load\",\n            this.options,\n            () => {\n              view.update(new Set([binding]));\n            },\n          );\n\n          this.hooks.onTrackBinding.call(binding);\n        },\n      },\n    });\n\n    this.tracker = bindingTrackerPlugin;\n    this.viewValidationProvider = view;\n\n    bindingTrackerPlugin.apply(view);\n  }\n\n  updateValidationsForBinding(\n    binding: BindingInstance,\n    trigger: Validation.Trigger,\n    validationContext?: SimpleValidatorContext,\n    onDismiss?: () => void,\n  ): void {\n    const context = validationContext ?? this.options;\n\n    if (!context) {\n      throw new Error(`Context is required for executing validations`);\n    }\n\n    if (trigger === \"load\") {\n      // Get all of the validations from each provider\n      const possibleValidations = this.getValidationProviders().reduce<\n        Array<ValidationObjectWithSource>\n      >((vals, provider) => {\n        vals.push(\n          ...(provider.provider\n            .getValidationsForBinding?.(binding)\n            ?.map((valObj) => ({\n              ...valObj,\n              [VALIDATION_PROVIDER_NAME_SYMBOL]: provider.source,\n            })) ?? []),\n        );\n\n        return vals;\n      }, []);\n\n      if (possibleValidations.length === 0) {\n        return;\n      }\n\n      this.validations.set(\n        binding,\n        new ValidatedBinding(\n          possibleValidations,\n          onDismiss,\n          this.options?.logger,\n        ),\n      );\n    }\n\n    const trackedValidations = this.validations.get(binding);\n    trackedValidations?.update(trigger, true, (validationObj) => {\n      const response = this.validationRunner(validationObj, binding, context);\n\n      if (this.weakBindingTracker.size > 0) {\n        const t = this.validations.get(binding) as ValidatedBinding;\n        this.weakBindingTracker.forEach((b) => t.weakBindings.add(b));\n      }\n\n      return response ? { message: response.message } : undefined;\n    });\n\n    // Also run any validations that binding or sub-binding is a weak binding of\n    if (trigger !== \"load\") {\n      this.validations.forEach((validation, vBinding) => {\n        if (\n          vBinding !== binding &&\n          caresAboutDataChanges(new Set([binding]), validation.weakBindings)\n        ) {\n          validation.update(trigger, true, (validationObj) => {\n            const response = this.validationRunner(\n              validationObj,\n              vBinding,\n              context,\n            );\n            return response ? { message: response.message } : undefined;\n          });\n        }\n      });\n    }\n  }\n\n  validationRunner(\n    validationObj: ValidationObjectWithHandler,\n    binding: BindingInstance,\n    context: SimpleValidatorContext | undefined = this.options,\n  ) {\n    if (!context) {\n      throw new Error(\"No context provided to validation runner\");\n    }\n\n    const handler =\n      validationObj.handler ?? this.getValidator(validationObj.type);\n\n    const weakBindings = new Set<BindingInstance>();\n\n    // For any data-gets in the validation runner, default to using the _invalid_ value (since that's what we're testing against)\n    const model: DataModelWithParser = {\n      get(b, options) {\n        weakBindings.add(isBinding(b) ? binding : context.parseBinding(b));\n        return context.model.get(b, { ...options, includeInvalid: true });\n      },\n      set: context.model.set,\n      delete: context.model.delete,\n    };\n\n    const result = handler?.(\n      {\n        ...context,\n        evaluate: (\n          exp: ExpressionType,\n          options: ExpressionEvaluatorOptions = { model },\n        ) => context.evaluate(exp, options),\n        model,\n        validation: validationObj,\n        schemaType: this.schema.getType(binding),\n      },\n      context.model.get(binding, {\n        includeInvalid: true,\n        formatted: validationObj.dataTarget === \"formatted\",\n      }),\n      validationObj,\n    );\n\n    this.weakBindingTracker = weakBindings;\n\n    if (result) {\n      let { message } = result;\n      const { parameters } = result;\n\n      if (validationObj.message) {\n        message = resolveDataRefs(validationObj.message, {\n          model,\n          evaluate: context.evaluate,\n        });\n        if (parameters) {\n          message = replaceParams(message, parameters);\n        }\n      }\n\n      return {\n        message,\n      };\n    }\n  }\n\n  private updateValidationsForView(trigger: Validation.Trigger): void {\n    const isNavigationTrigger = trigger === \"navigation\";\n    const lastActiveBindings = this.activeBindings;\n\n    /** Run validations for all bindings in view */\n    const updateValidations = (dismissValidations: boolean) => {\n      this.getBindings().forEach((binding) => {\n        this.validations\n          .get(binding)\n          ?.update(trigger, dismissValidations, (obj) => {\n            if (!this.options) {\n              return;\n            }\n\n            return this.validationRunner(obj, binding, this.options);\n          });\n      });\n    };\n\n    // Should dismiss for non-navigation triggers.\n    updateValidations(!isNavigationTrigger);\n\n    if (isNavigationTrigger) {\n      // If validations didn't change since last update, dismiss all dismissible validations.\n      const { activeBindings } = this;\n      if (isSubset(activeBindings, lastActiveBindings)) {\n        updateValidations(true);\n      }\n    }\n  }\n\n  private get activeBindings(): Set<BindingInstance> {\n    return new Set(\n      Array.from(this.getBindings()).filter(\n        (b) => this.validations.get(b)?.get() !== undefined,\n      ),\n    );\n  }\n\n  public getValidator(type: string) {\n    if (this.validatorRegistry) {\n      return this.validatorRegistry.get(type);\n    }\n\n    const registry = new ValidatorRegistry();\n    this.hooks.createValidatorRegistry.call(registry);\n    this.validatorRegistry = registry;\n\n    return registry.get(type);\n  }\n\n  getBindings(): Set<BindingInstance> {\n    return this.tracker?.getBindings() ?? new Set();\n  }\n\n  trackBinding(binding: BindingInstance): void {\n    this.tracker?.trackBinding(binding);\n  }\n\n  /** Executes all known validations for the tracked bindings using the given model */\n  validateView(trigger: Validation.Trigger = \"navigation\"): {\n    /** Indicating if the view can proceed without error */\n    canTransition: boolean;\n\n    /** the validations that are preventing the view from continuing */\n    validations?: Map<BindingInstance, ValidationResponse>;\n  } {\n    this.updateValidationsForView(trigger);\n\n    const validations = new Map<BindingInstance, ValidationResponse>();\n\n    let canTransition = true;\n\n    this.getBindings().forEach((b) => {\n      const allValidations = this.getValidationForBinding(b)?.getAll();\n\n      allValidations?.forEach((v) => {\n        if (trigger === \"navigation\" && v.blocking) {\n          this.options?.logger.debug(\n            `Validation on binding: ${b.asString()} is preventing navigation. ${JSON.stringify(\n              v,\n            )}`,\n          );\n\n          canTransition = false;\n        }\n\n        if (!validations.has(b)) {\n          validations.set(b, v);\n        }\n      });\n    });\n\n    return {\n      canTransition,\n      validations: validations.size ? validations : undefined,\n    };\n  }\n\n  /** Get the current tracked validation for the given binding */\n  public getValidationForBinding(\n    binding: BindingInstance,\n  ): ValidatedBinding | undefined {\n    return this.validations.get(binding);\n  }\n\n  forView(parser: BindingFactory): Resolve.Validation {\n    return {\n      _getValidationForBinding: (binding) => {\n        return this.getValidationForBinding(\n          isBinding(binding) ? binding : parser(binding),\n        );\n      },\n      getAll: () => {\n        const bindings = this.getBindings();\n        if (bindings.size === 0) {\n          return undefined;\n        }\n\n        const validationMapping = new Map<\n          BindingInstance,\n          ValidationResponse\n        >();\n\n        bindings.forEach((b) => {\n          const validation = this.getValidationForBinding(b)?.get();\n\n          if (validation) {\n            validationMapping.set(b, validation);\n          }\n        });\n\n        return validationMapping.size === 0 ? undefined : validationMapping;\n      },\n      get() {\n        throw new Error(\"Error Access be provided by the view plugin\");\n      },\n      getValidationsForBinding() {\n        throw new Error(\"Error rollup should be provided by the view plugin\");\n      },\n      getChildren() {\n        throw new Error(\"Error rollup should be provided by the view plugin\");\n      },\n      getValidationsForSection() {\n        throw new Error(\"Error rollup should be provided by the view plugin\");\n      },\n      track: () => {\n        throw new Error(\"Tracking should be provided by the view plugin\");\n      },\n      register: () => {\n        throw new Error(\n          \"Section functionality should be provided by the view plugin\",\n        );\n      },\n      type: (binding) =>\n        this.schema.getType(isBinding(binding) ? binding : parser(binding)),\n    };\n  }\n}\n","const ANY_CHAR_REGEX = /%([a-zA-Z]+)/g;\n\n/**\n * Replaces %num in message with the provided parameters in order.\n *\n * @param message - Parameterized string like \"This is a %1\"\n * @param params - Parameters to replace in message E.g. ['tax2021.amount']\n * @returns A message with the parameters replaced.\n */\nexport function replaceParams(\n  message: string,\n  params: Record<string, any>,\n): string {\n  return message\n    .slice()\n    .replace(ANY_CHAR_REGEX, (keyExpr) => params[keyExpr.slice(1)] || keyExpr);\n}\n","import type { Validation } from \"@player-ui/types\";\nimport type { ViewPlugin, Resolver, Node, ViewInstance } from \"../../view\";\nimport { NodeType } from \"../../view\";\nimport type {\n  BindingInstance,\n  BindingLike,\n  BindingFactory,\n} from \"../../binding\";\nimport { isBinding } from \"../../binding\";\nimport type { ValidationResponse } from \"../../validator\";\n\nconst CONTEXT = \"validation-binding-tracker\";\n\nexport interface BindingTracker {\n  /** Get the bindings currently being tracked for validation */\n  getBindings(): Set<BindingInstance>;\n\n  /** Add a binding to the tracked set */\n  trackBinding(binding: BindingInstance): void;\n}\ninterface Options {\n  /** Parse a binding from a view */\n  parseBinding: BindingFactory;\n\n  /** Callbacks when events happen */\n  callbacks?: {\n    /** Called when a binding is encountered for the first time in a view */\n    onAdd?: (binding: BindingInstance) => void;\n  };\n}\n\n/** A view plugin that manages bindings tracked across updates */\nexport class ValidationBindingTrackerViewPlugin\n  implements ViewPlugin, BindingTracker\n{\n  private options: Options;\n\n  private trackedBindings = new Set<BindingInstance>();\n\n  constructor(options: Options) {\n    this.options = options;\n  }\n\n  /** Fetch the tracked bindings in the current view */\n  getBindings(): Set<BindingInstance> {\n    return this.trackedBindings;\n  }\n\n  /** Add a binding to the tracked set */\n  trackBinding(binding: BindingInstance) {\n    if (this.trackedBindings.has(binding)) {\n      return;\n    }\n\n    this.trackedBindings.add(binding);\n    this.options.callbacks?.onAdd?.(binding);\n  }\n\n  /** Attach hooks to the given resolver */\n  applyResolver(resolver: Resolver) {\n    this.trackedBindings.clear();\n\n    /** Each node maps to a set of bindings that it directly tracks */\n    const tracked = new Map<Node.Node, Set<BindingInstance>>();\n\n    /** Each Node is a registered section or page that maps to a set of nodes in its section */\n    const sections = new Map<Node.Node, Set<Node.Node>>();\n\n    let lastViewUpdateChangeSet: Set<BindingInstance> | undefined;\n\n    /** Map of node to all bindings in children */\n    const lastComputedBindingTree = new Map<Node.Node, Set<BindingInstance>>();\n    let currentBindingTree = new Map<Node.Node, Set<BindingInstance>>();\n\n    /** Map of registered section nodes to bindings */\n    const lastSectionBindingTree = new Map<Node.Node, Set<BindingInstance>>();\n\n    /** Map of resolved nodes to their original nodes. */\n    const resolvedNodeMap: Map<Node.Node, Node.Node> = new Map();\n\n    resolver.hooks.beforeUpdate.tap(CONTEXT, (changes) => {\n      lastViewUpdateChangeSet = changes;\n    });\n\n    resolver.hooks.skipResolve.tap(CONTEXT, (shouldSkip, node) => {\n      const trackedBindingsForNode = lastComputedBindingTree.get(node);\n\n      if (!shouldSkip || !lastViewUpdateChangeSet || !trackedBindingsForNode) {\n        return shouldSkip;\n      }\n\n      const intersection = new Set(\n        [...lastViewUpdateChangeSet].filter((b) =>\n          trackedBindingsForNode.has(b),\n        ),\n      );\n\n      return intersection.size === 0;\n    });\n\n    resolver.hooks.resolveOptions.tap(CONTEXT, (options, node) => {\n      if (options.validation === undefined) {\n        return options;\n      }\n\n      // Clear out any old tracked bindings for this node since we're re-compiling it\n      tracked.delete(node);\n\n      /** Validation callback to track a binding */\n      const track = (binding: BindingLike) => {\n        const parsed = isBinding(binding)\n          ? binding\n          : this.options.parseBinding(binding);\n\n        if (tracked.has(node)) {\n          tracked.get(node)?.add(parsed);\n        } else {\n          tracked.set(node, new Set([parsed]));\n        }\n\n        /** find first parent registered as section and add self to its list */\n        let { parent } = node;\n\n        while (parent) {\n          if (sections.has(parent)) {\n            sections.get(parent)?.add(node);\n            break;\n          } else {\n            parent = parent.parent;\n          }\n        }\n\n        this.trackedBindings.add(parsed);\n        this.options.callbacks?.onAdd?.(parsed);\n      };\n\n      return {\n        ...options,\n        validation: {\n          ...options.validation,\n          get: (binding, getOptions) => {\n            if (getOptions?.track) {\n              track(binding);\n            }\n\n            const eows = options.validation\n              ?._getValidationForBinding(binding)\n              ?.getAll(getOptions);\n\n            const firstFieldEOW = eows?.find(\n              (eow) =>\n                eow.displayTarget === \"field\" ||\n                eow.displayTarget === undefined,\n            );\n\n            return firstFieldEOW;\n          },\n          getValidationsForBinding(binding, getOptions) {\n            if (getOptions?.track) {\n              track(binding);\n            }\n\n            return (\n              options.validation\n                ?._getValidationForBinding(binding)\n                ?.getAll(getOptions) ?? []\n            );\n          },\n          getChildren: (type?: Validation.DisplayTarget) => {\n            const validations = new Array<ValidationResponse>();\n            lastComputedBindingTree.get(node)?.forEach((binding) => {\n              const eow = options.validation\n                ?._getValidationForBinding(binding)\n                ?.get();\n\n              if (eow && (type === undefined || type === eow.displayTarget)) {\n                validations.push(eow);\n              }\n            });\n\n            return validations;\n          },\n          getValidationsForSection: () => {\n            const validations = new Array<ValidationResponse>();\n            lastSectionBindingTree.get(node)?.forEach((binding) => {\n              const eow = options.validation\n                ?._getValidationForBinding(binding)\n                ?.get();\n\n              if (eow && eow.displayTarget === \"section\") {\n                validations.push(eow);\n              }\n            });\n\n            return validations;\n          },\n          register: (registerOptions) => {\n            if (registerOptions?.type === \"section\") {\n              if (!sections.has(node)) {\n                sections.set(node, new Set());\n              }\n            }\n          },\n          track,\n        },\n      };\n    });\n\n    resolver.hooks.afterNodeUpdate.tap(\n      CONTEXT,\n      (originalNode, parent, update) => {\n        // Compute the new tree for this node\n        // If it's not-updated, use the last known value\n\n        const { updated, node: resolvedNode } = update;\n        resolvedNodeMap.set(resolvedNode, originalNode);\n\n        if (updated) {\n          const newlyComputed = new Set(tracked.get(originalNode));\n          if (resolvedNode.type === NodeType.MultiNode) {\n            resolvedNode.values.forEach((value) =>\n              currentBindingTree\n                .get(value)\n                ?.forEach((b) => newlyComputed.add(b)),\n            );\n          }\n\n          if (\"children\" in resolvedNode && resolvedNode.children) {\n            resolvedNode.children.forEach((child) => {\n              currentBindingTree\n                .get(child.value)\n                ?.forEach((b) => newlyComputed.add(b));\n            });\n          }\n\n          currentBindingTree.set(resolvedNode, newlyComputed);\n        } else {\n          currentBindingTree.set(\n            resolvedNode,\n            lastComputedBindingTree.get(originalNode) ?? new Set(),\n          );\n        }\n\n        if (originalNode === resolver.root) {\n          this.trackedBindings = new Set(currentBindingTree.get(resolvedNode));\n          lastComputedBindingTree.clear();\n          currentBindingTree.forEach((value, key) => {\n            const node = resolvedNodeMap.get(key);\n            if (node) {\n              lastComputedBindingTree.set(node, value);\n            }\n          });\n\n          lastSectionBindingTree.clear();\n          sections.forEach((nodeSet, sectionNode) => {\n            const temp = new Set<BindingInstance>();\n            nodeSet.forEach((n) => {\n              tracked.get(n)?.forEach(temp.add, temp);\n            });\n            lastSectionBindingTree.set(sectionNode, temp);\n          });\n\n          tracked.clear();\n          sections.clear();\n          currentBindingTree = new Map();\n        }\n      },\n    );\n  }\n\n  apply(view: ViewInstance) {\n    view.hooks.resolver.tap(CONTEXT, this.applyResolver.bind(this));\n  }\n}\n","import { SyncHook, SyncWaterfallHook } from \"tapable-ts\";\nimport queueMicrotask from \"queue-microtask\";\nimport { Registry } from \"@player-ui/partial-match-registry\";\nimport type { View, NavigationFlowViewState } from \"@player-ui/types\";\n\nimport { resolveDataRefsInString } from \"../../string-resolver\";\nimport type { Resolve, ViewPlugin } from \"../../view\";\nimport {\n  ApplicabilityPlugin,\n  AssetPlugin,\n  AssetTransformCorePlugin,\n  MultiNodePlugin,\n  StringResolverPlugin,\n  SwitchPlugin,\n  TemplatePlugin,\n  toNodeResolveOptions,\n  ViewInstance,\n} from \"../../view\";\nimport type { Logger } from \"../../logger\";\nimport type { FlowInstance, FlowController } from \"../flow\";\nimport type { DataController } from \"../data/controller\";\nimport type { TransformRegistry } from \"./types\";\nimport type { BindingInstance } from \"../../binding\";\nimport type { Node } from \"../../view\";\n\nexport interface ViewControllerOptions {\n  /** Where to get data from */\n  model: DataController;\n\n  /** Where to log data */\n  logger?: Logger;\n\n  /** A flow-controller instance to listen for view changes */\n  flowController: FlowController;\n}\n\nexport type ViewControllerHooks = {\n  /** Do any processing before the `View` instance is created */\n  resolveView: SyncWaterfallHook<\n    [View | undefined, string, NavigationFlowViewState]\n  >;\n\n  /** The hook right before the View starts resolving. Attach anything custom here */\n  view: SyncHook<[ViewInstance]>;\n};\n\n/** Merge two optional sets into a new set. Returns an empty set if both are undefined. */\nconst mergeSets = <T>(setA?: Set<T>, setB?: Set<T>): Set<T> => {\n  return new Set<T>([...(setA?.values() ?? []), ...(setB?.values() ?? [])]);\n};\n\n/** A controller to manage updating/switching views */\nexport class ViewController {\n  public readonly hooks: ViewControllerHooks = {\n    resolveView: new SyncWaterfallHook(),\n    view: new SyncHook(),\n  };\n\n  private readonly viewMap: Record<string, View>;\n  private readonly viewOptions: Resolve.ResolverOptions & ViewControllerOptions;\n  private pendingUpdate?: {\n    /** pending data binding changes */\n    changedBindings?: Set<BindingInstance>;\n    /** pending changes to view nodes */\n    changedNodes?: Set<Node.Node>;\n    /** Whether we have a microtask queued to handle this pending update */\n    scheduled?: boolean;\n  };\n  private readonly viewPlugins: Array<ViewPlugin>;\n\n  public currentView?: ViewInstance;\n  public transformRegistry: TransformRegistry = new Registry();\n  public optimizeUpdates = true;\n\n  constructor(\n    initialViews: View[],\n    options: Resolve.ResolverOptions & ViewControllerOptions,\n  ) {\n    this.viewOptions = options;\n    this.viewMap = initialViews.reduce<Record<string, View>>(\n      (viewMap, view) => {\n        viewMap[view.id] = view;\n        return viewMap;\n      },\n      {},\n    );\n\n    options.flowController.hooks.flow.tap(\n      \"viewController\",\n      (flow: FlowInstance) => {\n        flow.hooks.transition.tap(\"viewController\", (_oldState, newState) => {\n          if (newState.value.state_type === \"VIEW\") {\n            this.onView(newState.value);\n          } else {\n            this.currentView = undefined;\n          }\n        });\n      },\n    );\n\n    /** Trigger a view update */\n    const update = (updates: Set<BindingInstance>, silent = false) => {\n      if (this.currentView) {\n        if (this.optimizeUpdates) {\n          this.queueUpdate(updates, undefined, silent);\n        } else {\n          this.currentView.update();\n        }\n      }\n    };\n\n    options.model.hooks.onUpdate.tap(\n      \"viewController\",\n      (updates, updateOptions) => {\n        update(\n          new Set(updates.map((t) => t.binding)),\n          updateOptions?.silent ?? false,\n        );\n      },\n    );\n\n    options.model.hooks.onDelete.tap(\"viewController\", (binding) => {\n      const parentBinding = binding.parent();\n      const property = binding.key();\n\n      // Deleting an array item will trigger an update for the entire array\n      if (typeof property === \"number\" && parentBinding) {\n        update(new Set([parentBinding]));\n      } else {\n        update(new Set([binding]));\n      }\n    });\n\n    this.viewPlugins = this.createViewPlugins();\n  }\n\n  private queueUpdate(\n    bindings?: Set<BindingInstance>,\n    nodes?: Set<Node.Node>,\n    silent = false,\n  ) {\n    if (!this.pendingUpdate) {\n      this.pendingUpdate = {\n        scheduled: false,\n      };\n    }\n\n    this.pendingUpdate = {\n      ...this.pendingUpdate,\n      changedBindings: mergeSets(this.pendingUpdate.changedBindings, bindings),\n      changedNodes: mergeSets(this.pendingUpdate.changedNodes, nodes),\n    };\n\n    // If there's no pending update, schedule one only if this one isn't silent\n    // otherwise if this is silent, we'll just wait for the next non-silent update and make sure our bindings are included\n    if (!this.pendingUpdate.scheduled && !silent) {\n      this.pendingUpdate.scheduled = true;\n      queueMicrotask(() => {\n        const { changedBindings, changedNodes } = this.pendingUpdate ?? {};\n        this.pendingUpdate = undefined;\n        this.currentView?.update(changedBindings, changedNodes);\n      });\n    }\n  }\n\n  private getViewForRef(viewRef: string): View | undefined {\n    // First look for a 1:1 viewRef -> id mapping (this is most common)\n    if (this.viewMap[viewRef]) {\n      return this.viewMap[viewRef];\n    }\n\n    // The view ids saved may also contain model refs, resolve those and try again\n    const matchingViewId = Object.keys(this.viewMap).find(\n      (possibleViewIdMatch) =>\n        viewRef ===\n        resolveDataRefsInString(possibleViewIdMatch, {\n          model: this.viewOptions.model,\n          evaluate: this.viewOptions.evaluator.evaluate,\n        }),\n    );\n\n    if (matchingViewId && this.viewMap[matchingViewId]) {\n      return this.viewMap[matchingViewId];\n    }\n  }\n\n  public onView(state: NavigationFlowViewState): void {\n    const viewId = state.ref;\n\n    const source = this.hooks.resolveView.call(\n      this.getViewForRef(viewId),\n      viewId,\n      state,\n    );\n\n    if (!source) {\n      throw new Error(`No view with id ${viewId}`);\n    }\n\n    const view = new ViewInstance(source, this.viewOptions);\n    this.currentView = view;\n\n    // Give people a chance to attach their\n    // own listeners to the view before we resolve it\n    this.applyViewPlugins(view);\n    this.hooks.view.call(view);\n    view.update();\n  }\n\n  private applyViewPlugins(view: ViewInstance): void {\n    for (const plugin of this.viewPlugins) {\n      plugin.apply(view);\n    }\n  }\n\n  private createViewPlugins(): Array<ViewPlugin> {\n    const pluginOptions = toNodeResolveOptions(this.viewOptions);\n    return [\n      new AssetPlugin(),\n      new SwitchPlugin(pluginOptions),\n      new ApplicabilityPlugin(),\n      new AssetTransformCorePlugin(this.transformRegistry),\n      new StringResolverPlugin(),\n      new TemplatePlugin(pluginOptions),\n      new MultiNodePlugin(),\n    ];\n  }\n\n  /** Marks all AST nodes in `nodes` as changed, triggering the view to update and re-resolve these nodes. View updates are triggered asynchronously and many calls to this in a short time will batch into a single update.\n   *\n   * NOTE: In most cases view updates are handled automatically by changes to data or any other built-in functionality that would require a view update. Only call this function if absolutely necessary.\n   */\n  public updateViewAST(nodes: Set<Node.Node>): void {\n    this.queueUpdate(undefined, nodes);\n  }\n}\n","import { SyncHook, SyncWaterfallHook, SyncBailHook } from \"tapable-ts\";\nimport { dequal } from \"dequal\";\nimport type { Logger } from \"../../logger\";\nimport type { BindingParser, BindingLike } from \"../../binding\";\nimport { BindingInstance } from \"../../binding\";\nimport type {\n  BatchSetTransaction,\n  Updates,\n  DataModelOptions,\n  DataModelWithParser,\n  DataPipeline,\n  DataModelMiddleware,\n} from \"../../data\";\nimport { PipelinedDataModel, LocalModel } from \"../../data\";\nimport type { RawSetTransaction } from \"../../types\";\nimport { ReadOnlyDataController } from \"./utils\";\n\n/** The orchestrator for player data */\nexport class DataController implements DataModelWithParser<DataModelOptions> {\n  public hooks = {\n    resolve: new SyncWaterfallHook(),\n    resolveDataStages: new SyncWaterfallHook<[DataPipeline]>(),\n\n    // On any set or get of an undefined value, redirect the value to be the default\n    resolveDefaultValue: new SyncBailHook<[BindingInstance], any>(),\n\n    onDelete: new SyncHook<[any]>(),\n\n    onSet: new SyncHook<[BatchSetTransaction]>(),\n\n    onGet: new SyncHook<[any, any]>(),\n\n    onUpdate: new SyncHook<[Updates, DataModelOptions | undefined]>(),\n\n    format: new SyncWaterfallHook<[any, BindingInstance]>(),\n\n    deformat: new SyncWaterfallHook<[any, BindingInstance]>(),\n\n    serialize: new SyncWaterfallHook<[any]>(),\n  };\n\n  private model?: PipelinedDataModel;\n  private trash: Set<BindingInstance>;\n  private pathResolver: BindingParser;\n  private baseMiddleware: Array<DataModelMiddleware>;\n  private logger?: Logger;\n\n  constructor(\n    model: Record<any, unknown> | undefined,\n    options: {\n      /** A means of parsing a raw binding to a Binding object */\n      pathResolver: BindingParser;\n\n      /** middleware to use. typically for validation */\n      middleware?: Array<DataModelMiddleware>;\n\n      /** A logger to use  */\n      logger?: Logger;\n    },\n  ) {\n    this.logger = options.logger;\n    const middleware = options.middleware || [];\n    this.baseMiddleware = [new LocalModel(model), ...middleware];\n\n    this.trash = new Set();\n    this.pathResolver = options.pathResolver;\n  }\n\n  public getModel(): PipelinedDataModel {\n    if (!this.model) {\n      const stages = this.hooks.resolveDataStages.call(this.baseMiddleware);\n      const model = new PipelinedDataModel();\n      model.setMiddleware(stages);\n      this.model = model;\n    }\n\n    return this.model;\n  }\n\n  private resolveDataValue(\n    binding: BindingInstance,\n    value: any,\n    deformat: boolean,\n  ) {\n    if (deformat) {\n      return this.hooks.deformat.call(value, binding);\n    }\n\n    return value;\n  }\n\n  public set(\n    transaction: RawSetTransaction,\n    options?: DataModelOptions,\n  ): Updates {\n    let normalizedTransaction: BatchSetTransaction = [];\n\n    if (Array.isArray(transaction)) {\n      normalizedTransaction = transaction.map(([binding, value]) => {\n        const parsed = this.pathResolver.parse(binding);\n\n        return [\n          parsed,\n          this.resolveDataValue(parsed, value, Boolean(options?.formatted)),\n        ];\n      }) as BatchSetTransaction;\n    } else {\n      normalizedTransaction = Object.keys(transaction).map(\n        (binding: string) => {\n          const parsed = this.pathResolver.parse(binding);\n          const val = transaction[binding];\n\n          return [\n            parsed,\n            this.resolveDataValue(parsed, val, Boolean(options?.formatted)),\n          ];\n        },\n      ) as BatchSetTransaction;\n    }\n\n    // Figure out what the base changes being applied are\n    const setUpdates = normalizedTransaction.reduce<Updates>(\n      (updates, [binding, newVal]) => {\n        const oldVal = this.get(binding, { includeInvalid: true });\n\n        const update = {\n          binding,\n          newValue: newVal,\n          oldValue: oldVal,\n        };\n\n        if (dequal(oldVal, newVal)) {\n          this.logger?.debug(\n            `Skipping update for path: ${binding.asString()}. Value was unchanged: ${oldVal}`,\n          );\n        } else {\n          updates.push(update);\n\n          this.logger?.debug(\n            `Setting path: ${binding.asString()} from: ${oldVal} to: ${newVal}`,\n          );\n        }\n\n        return updates;\n      },\n      [],\n    );\n\n    // Get the applied update\n    const result = this.getModel().set(normalizedTransaction, options);\n\n    // Add any extra bindings that were effected\n    const setUpdateBindings = new Set(setUpdates.map((su) => su.binding));\n    result.forEach((tr) => {\n      if (\n        !setUpdateBindings.has(tr.binding) &&\n        (tr.force === true || !dequal(tr.oldValue, tr.newValue))\n      ) {\n        this.logger?.debug(\n          `Path: ${tr.binding.asString()} was changed from: ${\n            tr.oldValue\n          } to: ${tr.newValue}`,\n        );\n        setUpdates.push(tr);\n      }\n    });\n\n    this.hooks.onSet.call(normalizedTransaction);\n\n    if (setUpdates.length > 0) {\n      this.hooks.onUpdate.call(setUpdates, options);\n    }\n\n    return result;\n  }\n\n  private resolve(binding: BindingLike, readOnly: boolean): BindingInstance {\n    return Array.isArray(binding) || typeof binding === \"string\"\n      ? this.pathResolver.parse(binding, { readOnly })\n      : binding;\n  }\n\n  public get(binding: BindingLike, options?: DataModelOptions) {\n    const resolved =\n      binding instanceof BindingInstance\n        ? binding\n        : this.resolve(binding, true);\n    let result = this.getModel().get(resolved, options);\n\n    if (result === undefined && !options?.ignoreDefaultValue) {\n      const defaultVal = this.hooks.resolveDefaultValue.call(resolved);\n\n      if (defaultVal !== result) {\n        result = defaultVal;\n      }\n    }\n\n    if (options?.formatted) {\n      result = this.hooks.format.call(result, resolved);\n    } else if (options?.formatted === false) {\n      result = this.hooks.deformat.call(result, resolved);\n    }\n\n    this.hooks.onGet.call(binding, result);\n\n    return result;\n  }\n\n  public delete(binding: BindingLike, options?: DataModelOptions) {\n    if (\n      typeof binding !== \"string\" &&\n      !Array.isArray(binding) &&\n      !(binding instanceof BindingInstance)\n    ) {\n      throw new Error(\"Invalid arguments: delete expects a data path (string)\");\n    }\n\n    const resolved =\n      binding instanceof BindingInstance\n        ? binding\n        : this.resolve(binding, false);\n\n    const parentBinding = resolved.parent();\n    const property = resolved.key();\n    const parentValue = this.get(parentBinding);\n\n    const existedBeforeDelete =\n      typeof parentValue === \"object\" &&\n      parentValue !== null &&\n      Object.prototype.hasOwnProperty.call(parentValue, property);\n\n    this.getModel().delete(resolved, options);\n\n    if (existedBeforeDelete && !this.get(resolved)) {\n      this.trash.add(resolved);\n    }\n\n    this.hooks.onDelete.call(resolved);\n  }\n\n  public serialize(): object {\n    return this.hooks.serialize.call(this.get(\"\"));\n  }\n\n  public makeReadOnly(): ReadOnlyDataController {\n    return new ReadOnlyDataController(this, this.logger);\n  }\n}\n","import type { DataController } from \".\";\nimport type { Logger } from \"../../logger\";\nimport type { BindingLike } from \"../../binding\";\nimport type {\n  DataModelWithParser,\n  DataModelOptions,\n  Updates,\n} from \"../../data\";\n\n/** Wrapper for the Data Controller Class that prevents writes */\nexport class ReadOnlyDataController\n  implements DataModelWithParser<DataModelOptions>\n{\n  private controller: DataController;\n  private logger?: Logger;\n\n  constructor(controller: DataController, logger?: Logger) {\n    this.controller = controller;\n    this.logger = logger;\n  }\n\n  get(binding: BindingLike, options?: DataModelOptions | undefined) {\n    return this.controller.get(binding, options);\n  }\n\n  set(\n    transaction: [BindingLike, any][],\n    options?: DataModelOptions | undefined,\n  ): Updates {\n    this.logger?.error(\n      \"Error: Tried to set in a read only instance of the DataController\",\n    );\n    return [];\n  }\n\n  delete(binding: BindingLike, options?: DataModelOptions | undefined): void {\n    this.logger?.error(\n      \"Error: Tried to delete in a read only instance of the DataController\",\n    );\n  }\n}\n","import { BindingInstance } from \"../../binding\";\n\n/** Recursively flattens a nested object to be an object of depth 1 with keys being the full path in the orginal object */\nexport function flatten(obj: any, roots: [string][] = [], sep = \".\"): any {\n  return (\n    Object\n      // find props of given object\n      .keys(obj)\n      // return an object by iterating props\n      .reduce(\n        (memo, prop) => ({\n          // create a new object\n\n          // include previously returned object\n          ...memo,\n          ...(Object.prototype.toString.call(obj[prop]) === \"[object Object]\"\n            ? // keep working if value is an object\n              flatten(obj[prop], roots.concat([prop]))\n            : // include current prop and value and prefix prop with the roots\n              { [roots.concat([prop]).join(sep)]: obj[prop] }),\n        }),\n        {},\n      )\n  );\n}\n\n/** Converts an object into a list of binding/value tuples to use with a LocalModel object */\nexport function objectToBatchSet(obj: any): [BindingInstance, any][] {\n  const flattenedObj = flatten(obj);\n  const batchTxn: [BindingInstance, any][] = [];\n\n  Object.keys(flattenedObj).forEach((key) => {\n    batchTxn.push([new BindingInstance(key), flattenedObj[key]]);\n  });\n\n  return batchTxn;\n}\n","import { LocalModel } from \"../../data\";\nimport { BindingInstance } from \"../../binding\";\nimport { objectToBatchSet } from \"./utils\";\n\nexport interface ConstantsProvider {\n  /**\n   * Function to add constants to the providers store\n   * - @param data values to add to the constants store\n   */\n  addConstants(data: Record<string, any>, namespace: string): void;\n\n  /**\n   * Function to retrieve constants from the providers store\n   *  - @param key Key used for the store access\n   *  - @param namespace namespace values were loaded under (defined in the plugin)\n   *  - @param fallback Optional - if key doesn't exist in namespace what to return (will return unknown if not provided)\n   */\n  getConstants(key: any, namespace: string, fallback?: any): any;\n\n  /**\n   * Function to set values to temporarily override certain keys in the perminant store\n   * - @param data values to override store with\n   * - @param namespace namespace to override\n   */\n  setTemporaryValues(data: any, namespace: string): void;\n\n  /**\n   * Clears any temporary values that were previously set\n   */\n  clearTemporaryValues(): void;\n}\n\n/**\n * Key/Value store for constants and context for Player\n */\nexport class ConstantsController implements ConstantsProvider {\n  /**\n   * Data store is basically a map of namespaces to DataModels to provide some data isolation\n   */\n  private store: Map<string, LocalModel>;\n\n  /**\n   * Separate store for temporary flow specific overrides.\n   * They are kept in a separate data model to make clearing it easier between flows\n   * and so there is no confusion on what is static and what is temporary\n   */\n  private tempStore: Map<string, LocalModel>;\n\n  constructor() {\n    this.store = new Map();\n    this.tempStore = new Map();\n  }\n\n  addConstants(data: any, namespace: string): void {\n    if (this.store.has(namespace)) {\n      this.store.get(namespace)?.set(objectToBatchSet(data));\n    } else {\n      this.store.set(namespace, new LocalModel(data));\n    }\n  }\n\n  getConstants(key: string, namespace: string, fallback?: any): any {\n    const path = new BindingInstance(key);\n\n    return (\n      this.tempStore.get(namespace)?.get(path) ??\n      this.store.get(namespace)?.get(path) ??\n      fallback\n    );\n  }\n\n  setTemporaryValues(data: any, namespace: string): void {\n    if (this.tempStore.has(namespace)) {\n      this.tempStore.get(namespace)?.set(objectToBatchSet(data));\n    } else {\n      this.tempStore.set(namespace, new LocalModel(data));\n    }\n  }\n\n  clearTemporaryValues(namespace?: string): void {\n    if (namespace) {\n      this.tempStore.get(namespace)?.reset();\n    } else {\n      this.tempStore.forEach((value: LocalModel) => {\n        value.reset();\n      });\n    }\n  }\n}\n","import type {\n  Expression,\n  ExpressionObject,\n  NavigationFlowState,\n} from \"@player-ui/types\";\nimport type { ExpressionEvaluator, ExpressionType } from \"../expressions\";\nimport type { FlowInstance } from \"../controllers\";\nimport type { Player, PlayerPlugin } from \"../player\";\n\n/**\n * A plugin that taps into the flow controller to evaluate available expressions\n * Expressions can be exposed via lifecycle \"hooks\" in flow/state nodes\n * e.g: onStart, onEnd\n */\nexport class FlowExpPlugin implements PlayerPlugin {\n  name = \"flow-exp-plugin\";\n\n  apply(player: Player) {\n    let expressionEvaluator: ExpressionEvaluator | undefined;\n\n    /**\n     * Eval Helper\n     *\n     * @param exp - an expression to be evaluated\n     */\n    const handleEval = (exp: Expression | ExpressionObject) => {\n      if (exp) {\n        if (typeof exp === \"object\" && \"exp\" in exp) {\n          expressionEvaluator?.evaluate(exp.exp);\n        } else {\n          expressionEvaluator?.evaluate(exp as ExpressionType);\n        }\n      }\n    };\n\n    player.hooks.expressionEvaluator.tap(this.name, (evaluator) => {\n      expressionEvaluator = evaluator;\n    });\n\n    player.hooks.flowController.tap(this.name, (fc) => {\n      fc.hooks.flow.tap(this.name, (flow: FlowInstance) => {\n        // Eval flow nodes\n        flow.hooks.onStart.tap(this.name, (exp) => handleEval(exp));\n\n        flow.hooks.onEnd.tap(this.name, (exp) => handleEval(exp));\n        // Eval state nodes\n        flow.hooks.resolveTransitionNode.intercept({\n          call: (nextState: NavigationFlowState) => {\n            if (nextState?.onStart) {\n              handleEval(nextState.onStart);\n            }\n          },\n        });\n      });\n    });\n  }\n}\n","import type { ExpressionHandler, ExpressionType } from \"../expressions\";\nimport type { SchemaController } from \"../schema\";\nimport type { Player, PlayerPlugin } from \"../player\";\n\n/** Gets formatter for given formatName and formats value if found, returns value otherwise */\nconst createFormatFunction = (schema: SchemaController) => {\n  /**\n   * The generated handler for the given schema\n   */\n  const handler: ExpressionHandler<[unknown, string], any> = (\n    ctx,\n    value,\n    formatName,\n  ) => {\n    return (\n      schema.getFormatterForType({ type: formatName })?.format(value) ?? value\n    );\n  };\n\n  return handler;\n};\n\n/**\n * A plugin that provides the out-of-the-box expressions for player\n */\nexport class DefaultExpPlugin implements PlayerPlugin {\n  name = \"flow-exp-plugin\";\n\n  apply(player: Player) {\n    let formatFunction: ExpressionHandler<[unknown, string]> | undefined;\n\n    player.hooks.schema.tap(this.name, (schemaController) => {\n      formatFunction = createFormatFunction(schemaController);\n    });\n\n    player.hooks.expressionEvaluator.tap(this.name, (expEvaluator) => {\n      if (formatFunction) {\n        expEvaluator.addExpressionFunction(\"format\", formatFunction);\n      }\n\n      expEvaluator.addExpressionFunction(\"log\", (ctx, ...args) => {\n        player.logger.info(...args);\n      });\n\n      expEvaluator.addExpressionFunction(\"debug\", (ctx, ...args) => {\n        player.logger.debug(...args);\n      });\n\n      expEvaluator.addExpressionFunction(\n        \"eval\",\n        (ctx, ...args: [ExpressionType]) => {\n          return ctx.evaluate(...args);\n        },\n      );\n    });\n  }\n}\n","import type { Asset, Flow, FlowResult } from \"@player-ui/types\";\nimport type { BindingParser, BindingLike } from \"./binding\";\nimport type { SchemaController } from \"./schema\";\nimport type { ExpressionEvaluator } from \"./expressions\";\nimport type { Logger } from \"./logger\";\nimport type {\n  ViewController,\n  DataController,\n  ValidationController,\n  FlowController,\n} from \"./controllers\";\nimport type { ReadOnlyDataController } from \"./controllers/data/utils\";\nimport { SyncHook, SyncWaterfallHook } from \"tapable-ts\";\nimport { ViewInstance } from \"./view\";\n\n/**\n * Public Player Hooks\n */\nexport interface PlayerHooks {\n  /** The hook that fires every time we create a new flowController (a new Content blob is passed in) */\n  flowController: SyncHook<[FlowController], Record<string, any>>;\n  /** The hook that updates/handles views */\n  viewController: SyncHook<[ViewController], Record<string, any>>;\n  /** A hook called every-time there's a new view. This is equivalent to the view hook on the view-controller */\n  view: SyncHook<[ViewInstance], Record<string, any>>;\n  /** Called when an expression evaluator was created */\n  expressionEvaluator: SyncHook<[ExpressionEvaluator], Record<string, any>>;\n  /** The hook that creates and manages data */\n  dataController: SyncHook<[DataController], Record<string, any>>;\n  /** Called after the schema is created for a flow */\n  schema: SyncHook<[SchemaController], Record<string, any>>;\n  /** Manages validations (schema and x-field ) */\n  validationController: SyncHook<[ValidationController], Record<string, any>>;\n  /** Manages parsing binding */\n  bindingParser: SyncHook<[BindingParser], Record<string, any>>;\n  /** A that's called for state changes in the flow execution */\n  state: SyncHook<[PlayerFlowState], Record<string, any>>;\n  /** A hook to access the current flow */\n  onStart: SyncHook<[Flow<Asset<string>>], Record<string, any>>;\n  /** A hook for when the flow ends either in success or failure */\n  onEnd: SyncHook<[], Record<string, any>>;\n  /** Mutate the Content flow before starting */\n  resolveFlowContent: SyncWaterfallHook<\n    [Flow<Asset<string>>],\n    Record<string, any>\n  >;\n}\n\n/** The status for a flow's execution state */\nexport type PlayerFlowStatus =\n  | \"not-started\"\n  | \"in-progress\"\n  | \"completed\"\n  | \"error\";\n\n/** Common interface for the state of Player's flow execution */\nexport interface BaseFlowState<T extends PlayerFlowStatus> {\n  /** A unique reference for the life-cycle of a flow */\n  ref: symbol;\n\n  /** The status of the given flow */\n  status: T;\n}\n\n/** The beginning state of Player, before it's seen a flow  */\nexport type NotStartedState = BaseFlowState<\"not-started\">;\n\nexport const NOT_STARTED_STATE: NotStartedState = {\n  ref: Symbol(\"not-started\"),\n  status: \"not-started\",\n};\n\n/** Shared properties for a flow in any state of execution (in-progress, completed successfully, or errored out) */\nexport interface PlayerFlowExecutionData {\n  /** The currently executing flow */\n  flow: Flow;\n}\n\nexport interface ControllerState {\n  /** The manager for data for a flow */\n  data: DataController;\n\n  /** The view manager for a flow */\n  view: ViewController;\n\n  /** The schema manager for a flow */\n  schema: SchemaController;\n\n  /** The validation manager for a flow */\n  validation: ValidationController;\n\n  /** The expression evaluator for a flow */\n  expression: ExpressionEvaluator;\n\n  /** The manager for parsing and resolving bindings */\n  binding: BindingParser;\n\n  /** the manager for the flow state machine */\n  flow: FlowController;\n}\n\n/** A flow is currently executing */\nexport type InProgressState = BaseFlowState<\"in-progress\"> &\n  PlayerFlowExecutionData & {\n    /** A promise that resolves when the flow is completed */\n    flowResult: Promise<FlowResult>;\n\n    /** The underlying state controllers for the current flow */\n    controllers: ControllerState;\n\n    /** Allow other platforms to abort the current flow with an error  */\n    fail: (error: Error) => void;\n\n    /**\n     * The Logger for the current player instance\n     */\n    logger: Logger;\n  };\n\n/** The flow completed properly */\nexport type CompletedState = BaseFlowState<\"completed\"> &\n  PlayerFlowExecutionData &\n  FlowResult & {\n    /** Readonly Player controllers to provide Player functionality after the flow has ended */\n    controllers: {\n      /** A read only instance of the Data Controller */\n      data: ReadOnlyDataController;\n    };\n  };\n\n/** The flow finished but not successfully */\nexport type ErrorState = BaseFlowState<\"error\"> & {\n  /** The currently executing flow */\n  flow: Flow;\n\n  /** The error associated with the failed flow */\n  error: Error;\n};\n\n/** Any Player state  */\nexport type PlayerFlowState =\n  | NotStartedState\n  | InProgressState\n  | CompletedState\n  | ErrorState;\n\n// Model\n\nexport type RawSetType = [BindingLike, any];\nexport type RawSetTransaction = Record<string, any> | RawSetType[];\n"],"mappings":";;;;;;;AACA,cAAc;;;ACDd,SAAS,cAAc,yBAAyB;AAChD,SAAS,eAAAA,oBAAmB;;;ACsCrB,IAAM,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A,EAEA,MAAa,MAAM,SAAwC;AACzD,UAAM,MAAM,OAAO,SAAS,MAAM,SAAS;AAG3C,UAAM,mBAAmB,CAA4B,aAAgB;AACnE,UAAI,KAAK,MAAM,QAAQ,KAAK;AAC1B,aAAK,OAAO;AAAA,UACV;AAAA,QACF;AAEA,eAAO;AAAA,MACT;AAEA,WAAK,SAAS,QAAQ;AAEtB,aAAO;AAAA,IACT;AAEA,SAAK,SAAS;AAAA,MACZ,QAAQ;AAAA,MACR;AAAA,IACF,CAAC;AAED,QAAI;AACF,YAAM,EAAE,OAAO,MAAM,IAAI,KAAK,UAAU,OAAO;AAC/C,WAAK,SAAS;AAAA,QACZ;AAAA,QACA,GAAG;AAAA,MACL,CAAC;AAED,YAAM;AAIN,YAAM,WAAW;AAAA,QACf;AAAA,QACA,QAAQ;AAAA,QACR,MAAM,MAAM;AAAA,QACZ,aAAa;AAAA,UACX,MAAM,MAAM,YAAY,KAAK,aAAa;AAAA,QAC5C;AAAA,MACF;AAEA,aAAO,iBAAiB;AAAA,QACtB,GAAI,MAAM,MAAM;AAAA,QAChB,GAAG;AAAA,MACL,CAAC;AAAA,IACH,SAAS,OAAY;AACnB,YAAM,aAAyB;AAAA,QAC7B,QAAQ;AAAA,QACR;AAAA,QACA,MAAM;AAAA,QACN;AAAA,MACF;AAEA,uBAAiB,UAAU;AAE3B,YAAM;AAAA,IACR;AAAA,EACF;AACF;AAxca,QACY,OAAmB;AAAA,EACxC,SAAS;AAAA,EACT,QAAQ;AACV;AAJK,IAAM,SAAN;","names":["NestedError","NestedError","normalized","SyncWaterfallHook","SyncBailHook","NestedError","branch","SyncWaterfallHook","SyncBailHook","NestedError","left","right","arg","SyncHook","SyncWaterfallHook","parse","t","setIn","setIn","setIn","SyncHook","SyncHook","SyncWaterfallHook","setIn","setIn","SyncBailHook","SyncWaterfallHook","NodeType","SyncWaterfallHook","SyncBailHook","value","children","setIn","SyncWaterfallHook","SyncHook","update","setIn","SyncHook","flatten","SyncWaterfallHook","SyncWaterfallHook","node","omit","omit","setIn","queueMicrotask","SyncHook","SyncWaterfallHook","SyncBailHook","SyncHook","SyncWaterfallHook","SyncHook","SyncHook","SyncHook","SyncWaterfallHook","setIn","setIn","SyncHook","SyncWaterfallHook","t","SyncHook","SyncWaterfallHook","SyncWaterfallHook","SyncHook","t","SyncHook","SyncWaterfallHook","SyncBailHook","dequal","SyncWaterfallHook","SyncBailHook","SyncHook","dequal","SyncHook","SyncWaterfallHook","setIn","queueMicrotask"]}