template.js
This file
Path
lib/methods/template.js
182 lines · 6.6 KiB · JavaScript
Last changed by
Fix template strings, `parseCommandString()` and `execaNode()` edge casesSindre Sorhusbefore adoptionfb92da1
History of this fileTake it
The walk stopped after 200 commits: lines older than 63de206 point at it.
Improve examples used in types (#1000)ehmickybefore adoption63de206
lines 1–2why, one step back1import {ChildProcess} from 'node:child_process';2import isPlainObject from 'is-plain-obj';Fix template string tokenization of escape sequencesSindre Sorhusbefore adoptionb67f199
line 3why, one step back3import {ASTRAL_START} from '../arguments/escape.js';Improve examples used in types (#1000)ehmickybefore adoption63de206
line 4why, one step back4import {isUint8Array, uint8ArrayToString} from '../utils/uint-array.js';Fix template strings, `parseCommandString()` and `execaNode()` edge casesSindre Sorhusbefore adoptionfb92da1
line 5why, one step back5import {isExecaError} from '../return/final-error.js';Improve examples used in types (#1000)ehmickybefore adoption63de206
lines 6–12why, one step back67// Check whether the template string syntax is being used8export const isTemplateString = templates => Array.isArray(templates) && Array.isArray(templates.raw);910// Convert execa`file ...commandArguments` to execa(file, commandArguments)11export const parseTemplates = (templates, expressions) => {12 let tokens = [];Fix template strings, `parseCommandString()` and `execaNode()` edge casesSindre Sorhusbefore adoptionfb92da1
lines 13–14why, one step back13 // Whether whitespaces separate the last token from the next one14 let isSeparated = false;Improve examples used in types (#1000)ehmickybefore adoption63de206
lines 15–16why, one step back1516 for (const [index, template] of templates.entries()) {Fix template strings, `parseCommandString()` and `execaNode()` edge casesSindre Sorhusbefore adoptionfb92da1
line 17why, one step back17 ({tokens, isSeparated} = parseTemplate({Improve examples used in types (#1000)ehmickybefore adoption63de206
lines 18–20why, one step back18 templates,19 expressions,20 tokens,Fix template strings, `parseCommandString()` and `execaNode()` edge casesSindre Sorhusbefore adoptionfb92da1
line 21why, one step back21 isSeparated,Improve examples used in types (#1000)ehmickybefore adoption63de206
lines 22–23why, one step back22 index,23 template,Fix template strings, `parseCommandString()` and `execaNode()` edge casesSindre Sorhusbefore adoptionfb92da1
line 24why, one step back24 }));Improve examples used in types (#1000)ehmickybefore adoption63de206
lines 25–34why, one step back25 }2627 if (tokens.length === 0) {28 throw new TypeError('Template script must not be empty');29 }3031 const [file, ...commandArguments] = tokens;32 return [file, commandArguments, {}];33};34Fix template strings, `parseCommandString()` and `execaNode()` edge casesSindre Sorhusbefore adoptionfb92da1
line 35why, one step back35const parseTemplate = ({templates, expressions, tokens, isSeparated, index, template}) => {Improve examples used in types (#1000)ehmickybefore adoption63de206
lines 36–40why, one step back36 if (template === undefined) {37 throw new TypeError(`Invalid backslash sequence: ${templates.raw[index]}`);38 }3940 const {nextTokens, leadingWhitespaces, trailingWhitespaces} = splitByWhitespaces(template, templates.raw[index]);Fix template strings, `parseCommandString()` and `execaNode()` edge casesSindre Sorhusbefore adoptionfb92da1
lines 41–43why, one step back41 const newTokens = concatTokens(tokens, nextTokens, isSeparated || leadingWhitespaces);42 // When the template has no tokens, the whitespaces before it still separate the next token, e.g. after an empty array expression43 const isTemplateSeparated = trailingWhitespaces || (nextTokens.length === 0 && isSeparated);Improve examples used in types (#1000)ehmickybefore adoption63de206
lines 44–45why, one step back4445 if (index === expressions.length) {Fix template strings, `parseCommandString()` and `execaNode()` edge casesSindre Sorhusbefore adoptionfb92da1
line 46why, one step back46 return {tokens: newTokens, isSeparated: isTemplateSeparated};Improve examples used in types (#1000)ehmickybefore adoption63de206
lines 47–52why, one step back47 }4849 const expression = expressions[index];50 const expressionTokens = Array.isArray(expression)51 ? expression.map(expression => parseExpression(expression))52 : [parseExpression(expression)];Fix template strings, `parseCommandString()` and `execaNode()` edge casesSindre Sorhusbefore adoptionfb92da1
lines 53–56why, one step back53 return {54 tokens: concatTokens(newTokens, expressionTokens, isTemplateSeparated),55 isSeparated: expressionTokens.length === 0 && isTemplateSeparated,56 };Improve examples used in types (#1000)ehmickybefore adoption63de206
lines 57–65why, one step back57};5859// Like `string.split(/[ \t\r\n]+/)` except newlines and tabs are:60// - ignored when input as a backslash sequence like: `echo foo\n bar`61// - not ignored when input directly62// The only way to distinguish those in JavaScript is to use a tagged template and compare:63// - the first array argument, which does not escape backslash sequences64// - its `raw` property, which escapes them65const splitByWhitespaces = (template, rawTemplate) => {Fix template string tokenization of escape sequencesSindre Sorhusbefore adoptionb67f199
lines 66–68why, one step back66 // The template is empty either between two `${expression}`, or when it only contains escaped newlines.67 // Neither holds any whitespace, so neither separates tokens.68 if (template.length === 0) {Improve examples used in types (#1000)ehmickybefore adoption63de206
lines 69–73why, one step back69 return {nextTokens: [], leadingWhitespaces: false, trailingWhitespaces: false};70 }7172 const nextTokens = [];73 let templateStart = 0;Fix template string tokenization of escape sequencesSindre Sorhusbefore adoptionb67f199
line 74why, one step back74 let isLeadingWhitespaces = false;Improve examples used in types (#1000)ehmickybefore adoption63de206
lines 75–82why, one step back7576 for (77 let templateIndex = 0, rawIndex = 0;78 templateIndex < template.length;79 templateIndex += 1, rawIndex += 180 ) {81 const rawCharacter = rawTemplate[rawIndex];82 if (DELIMITERS.has(rawCharacter)) {Fix template string tokenization of escape sequencesSindre Sorhusbefore adoptionb67f199
lines 83–87why, one step back83 // Escaped newlines are ignored, so a whitespace after them is still a leading one84 if (templateIndex === 0) {85 isLeadingWhitespaces = true;86 }87Improve examples used in types (#1000)ehmickybefore adoption63de206
lines 88–94why, one step back88 if (templateStart !== templateIndex) {89 nextTokens.push(template.slice(templateStart, templateIndex));90 }9192 templateStart = templateIndex + 1;93 } else if (rawCharacter === '\\') {94 const nextRawCharacter = rawTemplate[rawIndex + 1];Fixes argument parsing for escaped newlines (#1176)Aaron Dandybefore adoption2aa3b0c
lines 95–99why, one step back95 if (nextRawCharacter === '\n') {96 // Handles escaped newlines in templates97 templateIndex -= 1;98 rawIndex += 1;99 } else if (nextRawCharacter === 'u' && rawTemplate[rawIndex + 2] === '{') {Fix template string tokenization of escape sequencesSindre Sorhusbefore adoptionb67f199
lines 100–106why, one step back100 const closingBraceIndex = rawTemplate.indexOf('}', rawIndex + 3);101 // A code point above the BMP is a surrogate pair, i.e. two characters, in the template string102 if (isAstralEscape(rawTemplate.slice(rawIndex + 3, closingBraceIndex))) {103 templateIndex += 1;104 }105106 rawIndex = closingBraceIndex;Improve examples used in types (#1000)ehmickybefore adoption63de206
lines 107–112why, one step back107 } else {108 rawIndex += ESCAPE_LENGTH[nextRawCharacter] ?? 1;109 }110 }111 }112Update dev dependencies (#1257)Sindre Sorhusbefore adoption5944b2d
lines 113–114why, one step back113 const isTrailingWhitespaces = templateStart === template.length;114 if (!isTrailingWhitespaces) {Improve examples used in types (#1000)ehmickybefore adoption63de206
lines 115–117why, one step back115 nextTokens.push(template.slice(templateStart));116 }117Update dev dependencies (#1257)Sindre Sorhusbefore adoption5944b2d
line 118why, one step back118 return {nextTokens, leadingWhitespaces: isLeadingWhitespaces, trailingWhitespaces: isTrailingWhitespaces};Improve examples used in types (#1000)ehmickybefore adoption63de206
line 119why, one step back119};Fix template string tokenization of escape sequencesSindre Sorhusbefore adoptionb67f199
lines 120–121why, one step back120121const isAstralEscape = codePointHex => Number.parseInt(codePointHex, 16) > ASTRAL_START;Improve examples used in types (#1000)ehmickybefore adoption63de206
lines 122–151why, one step back122123const DELIMITERS = new Set([' ', '\t', '\r', '\n']);124125// Number of characters in backslash escape sequences: \0 \xXX or \uXXXX126// \cX is allowed in RegExps but not in strings127// Octal sequences are not allowed in strict mode128const ESCAPE_LENGTH = {x: 3, u: 5};129130const concatTokens = (tokens, nextTokens, isSeparated) => isSeparated131 || tokens.length === 0132 || nextTokens.length === 0133 ? [...tokens, ...nextTokens]134 : [135 ...tokens.slice(0, -1),136 `${tokens.at(-1)}${nextTokens[0]}`,137 ...nextTokens.slice(1),138 ];139140// Handle `${expression}` inside the template string syntax141const parseExpression = expression => {142 const typeOfExpression = typeof expression;143144 if (typeOfExpression === 'string') {145 return expression;146 }147148 if (typeOfExpression === 'number') {149 return String(expression);150 }151Fix template strings, `parseCommandString()` and `execaNode()` edge casesSindre Sorhusbefore adoptionfb92da1
lines 152–154why, one step back152 // Only own properties are checked: a polluted `Object.prototype.stdout` must not turn any plain object into a subprocess result.153 // A failed subprocess result is an error instance instead.154 if ((isPlainObject(expression) || isExecaError(expression)) && (Object.hasOwn(expression, 'stdout') || Object.hasOwn(expression, 'isMaxBuffer'))) {Improve examples used in types (#1000)ehmickybefore adoption63de206
lines 155–165why, one step back155 return getSubprocessResult(expression);156 }157158 if (expression instanceof ChildProcess || Object.prototype.toString.call(expression) === '[object Promise]') {159 // eslint-disable-next-line no-template-curly-in-string160 throw new TypeError('Unexpected subprocess in template expression. Please use ${await subprocess} instead of ${subprocess}.');161 }162163 throw new TypeError(`Unexpected "${typeOfExpression}" in template expression`);164};165Harden some thingsSindre Sorhusbefore adoption4a0a121
lines 166–168why, one step back166const getSubprocessResult = result => {167 // Read the own property only: results with `stdout: 'ignore'` have no `stdout` property, which must not be read from a polluted prototype168 const stdout = Object.hasOwn(result, 'stdout') ? result.stdout : undefined;Improve examples used in types (#1000)ehmickybefore adoption63de206
lines 169–182why, one step back169 if (typeof stdout === 'string') {170 return stdout;171 }172173 if (isUint8Array(stdout)) {174 return uint8ArrayToString(stdout);175 }176177 if (stdout === undefined) {178 throw new TypeError('Missing result.stdout in template expression. This is probably due to the previous subprocess\' "stdout" option.');179 }180181 throw new TypeError(`Unexpected "${typeof stdout}" stdout in template expression`);182};