toon-format/toon · error · SyntaxError

Invalid escape sequence: backslash at end of string

Error message

Invalid escape sequence: backslash at end of string

What it means

unescapeString processes backslash escapes in parsed TOON string literals. If the input ends with a bare backslash, there is no following character to complete an escape sequence, so the parser throws a SyntaxError rather than silently dropping or keeping the backslash.

Source

Thrown at packages/toon/src/shared/string-utils.ts:55

    .replace(/\t/g, `${BACKSLASH}t`)
    // eslint-disable-next-line no-control-regex
    .replace(/[\u0000-\u001F]/g, c => `${BACKSLASH}u${c.charCodeAt(0).toString(16).padStart(4, '0')}`)
}

/**
 * Unescapes a string by processing escape sequences.
 *
 * @remarks
 * Lone surrogates in `\uXXXX` escapes are rejected.
 */
export function unescapeString(value: string): string {
  let unescaped = ''
  let i = 0

  while (i < value.length) {
    if (value[i] === BACKSLASH) {
      if (i + 1 >= value.length) {
        throw new SyntaxError('Invalid escape sequence: backslash at end of string')
      }

      const next = value[i + 1]
      if (next === 'n') {
        unescaped += NEWLINE
        i += 2
        continue
      }
      if (next === 't') {
        unescaped += TAB
        i += 2
        continue
      }
      if (next === 'r') {
        unescaped += CARRIAGE_RETURN
        i += 2
        continue
      }

View on GitHub (pinned to 604eac266e)

Solutions

  1. Double the trailing backslash so it is a valid escaped backslash (\\)
  2. Remove the dangling backslash if it was unintended
  3. Check the source file for truncation and regenerate it from the encoder

Example fix

// before (in TOON input)
path: "C:\\Users\\"
// after
path: "C:\\Users\\\\"
Defensive patterns

Strategy: try-catch

Validate before calling

function hasTrailingBackslash(s: string): boolean {
  const m = s.match(/\\\\$/)
  return m !== null && (m.index === 0 || (s.slice(0, m.index).match(/\\\\*$/)?.[0].length ?? 0) % 2 === 1)
}

Try / catch

try {
  const value = decode(input)
} catch (e) {
  if (e instanceof SyntaxError && e.message.includes('backslash at end of string')) {
    // repair: double the trailing backslash and retry once
  }
  throw e
}

Prevention

When it happens

Trigger: Parsing TOON input (via parseStringLiteral or key parsing) where a quoted string literal ends with `"...\\"` — a backslash as the last character before the closing quote.

Common situations: Hand-edited TOON files with Windows-style paths like "C:\\dir\\" mis-escaped; truncated files or strings clipped mid-escape by text processing or templating tools.

Related errors


AI-assisted analysis of toon-format/toon@604eac266e (2026-08-31). Data as JSON: /api/errors/c8aabb7f235a9135. Report an issue: GitHub.