export function webextParsePattern()

in js/src/webext-parse.ts [19:55]


export function webextParsePattern(
  msg: Message,
  src: string,
  onError: (error: ParseError) => void
): Pattern {
  const decl = Array.isArray(msg) ? {} : msg.decl
  const pattern: Pattern = []
  const addText = (text: string) => {
    if (typeof pattern.at(-1) == 'string') pattern[pattern.length - 1] += text
    else pattern.push(text)
  }
  let pos = 0
  for (const m of src.matchAll(/\$([a-zA-Z0-9_@]+)\$|(\$[1-9])|\$(\$+)/dg)) {
    if (m.index > pos) addText(src.substring(pos, m.index))
    const matchSrc = m[0]
    pos = m.index + matchSrc.length
    if (m[1]) {
      // Named placeholder
      const name = m[1].toLowerCase()
      const attr = Object.assign(Object.create(null), { source: matchSrc })
      pattern.push({ $: name, attr })
      if (!decl[name]) {
        const error = `webext: Unresolved Variable ${matchSrc}`
        onError(new ParseError(error, m.index, pos))
      }
    } else if (m[2]) {
      // Indexed placeholder
      const attr = Object.assign(Object.create(null), { source: matchSrc })
      pattern.push({ $: `arg${m[2][1]}`, attr })
    } else {
      // Escaped literal dollar sign
      addText(m[3])
    }
  }
  if (pos < src.length) addText(src.substring(pos))
  return pattern
}