Skip to content
Myr

Fix template string tokenization of escape sequences

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Sindre Sorhus · committed by Sindre Sorhus · parent 7c1a631 · Browse files · 5 files+86 added−5 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

5 files+86 added−5 removed

  • tests:+65 added−0 removed
  • other:+21 added−5 removed

5 files+86 added−5 removed

modified:lib/arguments/escape.js+2 added-2 removed
modified:lib/methods/template.js+19 added-3 removed
1import {ChildProcess} from 'node:child_process';2import isPlainObject from 'is-plain-obj';3import {ASTRAL_START} from '../arguments/escape.js';4import {isUint8Array, uint8ArrayToString} from '../utils/uint-array.js';56// Check whether the template string syntax is being used7export const isTemplateString = templates => Array.isArray(templates) && Array.isArray(templates.raw);
45 unmodified lines
53// The only way to distinguish those in JavaScript is to use a tagged template and compare:54// - the first array argument, which does not escape backslash sequences55// - its `raw` property, which escapes them56const splitByWhitespaces = (template, rawTemplate) => {57 // The template is empty either between two `${expression}`, or when it only contains escaped newlines.58 // Neither holds any whitespace, so neither separates tokens.56 if (rawTemplate.length === 0) {59 if (template.length === 0) {60 return {nextTokens: [], leadingWhitespaces: false, trailingWhitespaces: false};61 }6263 const nextTokens = [];64 let templateStart = 0;62 const isLeadingWhitespaces = DELIMITERS.has(rawTemplate[0]);65 let isLeadingWhitespaces = false;6667 for (68 let templateIndex = 0, rawIndex = 0;69 templateIndex < template.length;70 templateIndex += 1, rawIndex += 171 ) {72 const rawCharacter = rawTemplate[rawIndex];73 if (DELIMITERS.has(rawCharacter)) {74 // Escaped newlines are ignored, so a whitespace after them is still a leading one75 if (templateIndex === 0) {76 isLeadingWhitespaces = true;77 }7879 if (templateStart !== templateIndex) {80 nextTokens.push(template.slice(templateStart, templateIndex));81 }82
4 unmodified lines
87 // Handles escaped newlines in templates88 templateIndex -= 1;89 rawIndex += 1;90 } else if (nextRawCharacter === 'u' && rawTemplate[rawIndex + 2] === '{') {83 rawIndex = rawTemplate.indexOf('}', rawIndex + 3);91 const closingBraceIndex = rawTemplate.indexOf('}', rawIndex + 3);92 // A code point above the BMP is a surrogate pair, i.e. two characters, in the template string93 if (isAstralEscape(rawTemplate.slice(rawIndex + 3, closingBraceIndex))) {94 templateIndex += 1;95 }9697 rawIndex = closingBraceIndex;98 } else {99 rawIndex += ESCAPE_LENGTH[nextRawCharacter] ?? 1;100 }101 }
6 unmodified lines
108109 return {nextTokens, leadingWhitespaces: isLeadingWhitespaces, trailingWhitespaces: isTrailingWhitespaces};110};111112const isAstralEscape = codePointHex => Number.parseInt(codePointHex, 16) > ASTRAL_START;113114const DELIMITERS = new Set([' ', '\t', '\r', '\n']);115116// Number of characters in backslash escape sequences: \0 \xXX or \uXXXX117// \cX is allowed in RegExps but not in strings
55 unmodified lines
modified:test/arguments/escape.js+29 added
100 unmodified lines
101test('result.escapedCommand - \\uE000', testEscapedCommand, ['\u{E000}'], '\'\\ue000\'', '"\\ue000"', '\'\u{E000}\'', '"\u{E000}"');102test('result.escapedCommand - \\U1D172', testEscapedCommand, ['\u{1D172}'], '\'\u{1D172}\'', '"\u{1D172}"');103test('result.escapedCommand - \\U1D173', testEscapedCommand, ['\u{1D173}'], '\'\\U1d173\'', '"\\U1d173"', '\'\u{1D173}\'', '"\u{1D173}"');104test('result.escapedCommand - \\U10FFFD', testEscapedCommand, ['\u{10FFFD}'], '\'\\U10fffd\'', '"\\U10fffd"', '\'\u{10FFFD}\'', '"\u{10FFFD}"');105106/*107`result.escapedCommand` is documented as safe to copy and paste in a terminal, so a shell must parse it back to the exact same arguments.108Control characters are excluded, since those are intentionally escaped with a Bash-specific notation instead.109*/110if (!isWindows) {111 const testShellRoundTrip = async (t, commandArguments) => {112 const {escapedCommand} = await execa('print-arguments.js', commandArguments);113 const {stdout} = await execa('/bin/sh', ['-c', escapedCommand]);114 t.deepEqual(JSON.parse(stdout), commandArguments);115 };116117 testShellRoundTrip.title = (message, commandArguments) => `result.escapedCommand can be pasted in a shell: ${JSON.stringify(commandArguments)}`;118119 test(testShellRoundTrip, ['foo', 'bar']);120 test(testShellRoundTrip, ['foo bar']);121 test(testShellRoundTrip, ['\'foo\'', '"bar"']);122 test(testShellRoundTrip, ['it\'s', 'a\'\'b']);123 test(testShellRoundTrip, ['foo\\bar', '\\', '\\\\']);124 // eslint-disable-next-line no-template-curly-in-string125 test(testShellRoundTrip, ['$FOO', '${FOO}', '$(echo foo)']);126 test(testShellRoundTrip, ['`echo foo`']);127 test(testShellRoundTrip, ['foo;bar', 'foo&&bar', 'foo|bar', 'foo>bar']);128 test(testShellRoundTrip, ['*', '?', '[a-z]', '{a,b}']);129 test(testShellRoundTrip, ['~', '#foo', '!foo', '-foo', '--foo=bar']);130 test(testShellRoundTrip, ['', 'foo']);131 test(testShellRoundTrip, ['ã', '😀']);132 test(testShellRoundTrip, ['\'"`$\\!*&;| ']);133}
added:test/fixtures/print-arguments.js+4 added
modified:test/methods/template.js+32 added
28 unmodified lines
29test('$ can use escaped newlines and character escaped tab indentations', testScriptStdout, () => $`echo.js foo\30\tbar`, 'foo\tbar');31test('$ can use escaped newlines and character escaped newlines', testScriptStdout, () => $`echo.js foo\32\n\nbar`, 'foo\n\nbar');33// An escaped newline is ignored, so it must not separate tokens, nor hide the whitespaces following it.34// This must behave the same whether the tokens around it are expressions or not.35test('$ can use escaped newlines between tokens', testScriptStdout, () => $`echo.js foo\36bar`, 'foobar');37test('$ can use escaped newlines between expressions', testScriptStdout, () => $`echo.js ${'foo'}\38${'bar'}`, 'foobar');39test('$ can use multiple escaped newlines between expressions', testScriptStdout, () => $`echo.js ${'foo'}\40\41${'bar'}`, 'foobar');42test('$ can use escaped newlines and space indentations between expressions', testScriptStdout, () => $`echo.js ${'foo'}\43 ${'bar'}`, 'foo\nbar');44test('$ can use escaped newlines and tab indentations between expressions', testScriptStdout, () => $`echo.js ${'foo'}\45 ${'bar'}`, 'foo\nbar');46test('$ can use escaped newlines and space indentations after an expression', testScriptStdout, () => $`echo.js ${'foo'}\47 bar`, 'foo\nbar');48test('$ can use escaped newlines and tab indentations after an expression', testScriptStdout, () => $`echo.js ${'foo'}\49 bar`, 'foo\nbar');50test('$ can use escaped newlines before an expression', testScriptStdout, () => $`echo.js foo\51${'bar'}`, 'foobar');52test('$ can use Windows newlines and tab indentations', testScriptStdout, () => escapedCall('echo.js foo\r\n\tbar'), 'foo\nbar');53test('$ can use Windows newlines and space indentations', testScriptStdout, () => escapedCall('echo.js foo\r\n bar'), 'foo\nbar');54test('$ does not ignore comments in expressions', testScriptStdout, () => $`echo.js foo55 ${/* This is a comment */''}
200 unmodified lines
256test('$ splits tokens - \\u{0000063}', testScriptStdout, () => $`echo.js a\u{0000063}b`, 'acb');257test('$ splits expressions - \\u{0000063}', testScriptStdout, () => $`echo.js ${'a'}\u{0000063}${'b'}`, 'acb');258test('$ concatenates tokens - \\u{0000063}', testScriptStdout, () => $`echo.js \u{0000063}a\u{0000063} b`, 'cac\nb');259test('$ concatenates expressions - \\u{0000063}', testScriptStdout, () => $`echo.js \u{0000063}${'a'}\u{0000063} b`, 'cac\nb');260261// Code points above the BMP are a surrogate pair, i.e. two characters, in the template string but not in its raw version.262// Miscounting them shifts every following character, which splits tokens at the wrong place and breaks the surrogate pair.263test('$ handles tokens - \\u{1F600}', testScriptStdout, () => $`echo.js \u{1F600}`, '\u{1F600}');264test('$ splits tokens - \\u{1F600}', testScriptStdout, () => $`echo.js a\u{1F600}b`, 'a\u{1F600}b');265test('$ splits expressions - \\u{1F600}', testScriptStdout, () => $`echo.js ${'a'}\u{1F600}${'b'}`, 'a\u{1F600}b');266test('$ concatenates tokens - \\u{1F600}', testScriptStdout, () => $`echo.js \u{1F600}a\u{1F600} b`, '\u{1F600}a\u{1F600}\nb');267test('$ concatenates expressions - \\u{1F600}', testScriptStdout, () => $`echo.js \u{1F600}${'a'}\u{1F600} b`, '\u{1F600}a\u{1F600}\nb');268test('$ handles multiple tokens - \\u{1F600}', testScriptStdout, () => $`echo.js \u{1F600}\u{1F600} b c`, '\u{1F600}\u{1F600}\nb\nc');269test('$ handles the highest code point - \\u{10FFFF}', testScriptStdout, () => $`echo.js \u{10FFFF} b`, '\u{10FFFF}\nb');270// The BMP boundary is the exact point where the character count changes271test('$ handles the last BMP code point - \\u{FFFF}', testScriptStdout, () => $`echo.js \u{FFFF} b`, '\u{FFFF}\nb');272test('$ handles the first astral code point - \\u{10000}', testScriptStdout, () => $`echo.js \u{10000} b`, '\u{10000}\nb');273test('$ handles tokens - \\u{0063}}', testScriptStdout, () => $`echo.js \u{0063}}`, 'c}');274test('$ splits tokens - \\u{0063}}', testScriptStdout, () => $`echo.js a\u{0063}}b`, 'ac}b');275test('$ splits expressions - \\u{0063}}', testScriptStdout, () => $`echo.js ${'a'}\u{0063}}${'b'}`, 'ac}b');276test('$ concatenates tokens - \\u{0063}}', testScriptStdout, () => $`echo.js \u{0063}}a\u{0063}} b`, 'c}ac}\nb');
108 unmodified lines