Allow template strings with all methods (#933)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by ehmicky · committed by GitHub · parent a480e1d · Browse files · 25 files·+1651 added−1083 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
25 files+1651 added−1083 removed
- tests:+754 added−469 removed
- other:+897 added−614 removed
Provenance
- Commit
8074d85- Tree
f9546ff- Author
ehmicky <ehmicky@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent
a480e1d
25 files changed+1651 added−1083 removed
modified:docs/scripts.md+16 added-1 removed
26 unmodified lines27 const dirName = 'foo bar';28 await $`mkdir /tmp/${dirName}`;29 ```30 31+## Template string syntax32+33+The examples below use the [template string syntax](../readme.md#template-string-syntax). However, the other syntax using [an array of arguments](../readme.md#execafile-arguments-options) is also available as `$(file, arguments?, options?)`.34+35+Also, the template string syntax can be used outside of script files: `$` is not required to use that syntax. For example, `execa` can use it too.36+37+The only difference between `$` and `execa` is that the former includes [script-friendly default options](../readme.md#file-arguments-options).38+39+```js40+import {execa, $} from 'execa';41+42+const branch = await execa`git branch --show-current`;43+await $('dep', ['deploy', `--branch=${branch}`]);44+```45+46 ## Examples47 48 ### Main binary49 768 unmodified lines818 If you really need a shell though, the [`shell` option](../readme.md#shell) can be used.819 820 ### Simplicity821 807-Execa's scripting API mostly consists of only two methods: [`` $`command` ``](../readme.md#command) and [`$(options)`](../readme.md#options).822+Execa's scripting API mostly consists of only two methods: [`` $`command` ``](../readme.md#file-arguments-options) and [`$(options)`](../readme.md#execaoptions).823 824 [No special binary](#main-binary) is recommended, no [global variable](#global-variables) is injected: scripts are regular Node.js files.825 826 Execa is a thin wrapper around the core Node.js [`child_process` module](https://nodejs.org/api/child_process.html). Unlike zx, it lets you use [any of its native features](#background-subprocesses): [`pid`](#pid), [IPC](https://nodejs.org/api/child_process.html#subprocesssendmessage-sendhandle-options-callback), [`unref()`](https://nodejs.org/api/child_process.html#subprocessunref), [`detached`](https://nodejs.org/api/child_process.html#child_processspawncommand-args-options), [`uid`](https://nodejs.org/api/child_process.html#child_processspawncommand-args-options), [`gid`](https://nodejs.org/api/child_process.html#child_processspawncommand-args-options), [`cancelSignal`](https://nodejs.org/api/child_process.html#child_processspawncommand-args-options), etc.20 unmodified linesadded:lib/arguments/create.js+42 added
123456789101112131415161718192021222324252627282930313233343536373839404142import isPlainObject from 'is-plain-obj';import {execaCoreAsync} from '../async.js';import {execaCoreSync} from '../sync.js';import {normalizeArguments} from './normalize.js';import {isTemplateString, parseTemplates} from './template.js';
export const createExeca = (mapArguments, boundOptions, deepOptions, setBoundExeca) => { const createNested = (mapArguments, boundOptions, setBoundExeca) => createExeca(mapArguments, boundOptions, deepOptions, setBoundExeca); const boundExeca = (...args) => callBoundExeca({mapArguments, deepOptions, boundOptions, setBoundExeca, createNested}, ...args);
if (setBoundExeca !== undefined) { setBoundExeca(boundExeca, createNested, boundOptions); }
return boundExeca;};
const callBoundExeca = ({mapArguments, deepOptions = {}, boundOptions = {}, setBoundExeca, createNested}, firstArgument, ...nextArguments) => { if (isPlainObject(firstArgument)) { return createNested(mapArguments, {...boundOptions, ...firstArgument}, setBoundExeca); }
const {file, args, options, isSync} = parseArguments({mapArguments, firstArgument, nextArguments, deepOptions, boundOptions}); return isSync ? execaCoreSync(file, args, options) : execaCoreAsync(file, args, options, createNested);};
const parseArguments = ({mapArguments, firstArgument, nextArguments, deepOptions, boundOptions}) => { const callArguments = isTemplateString(firstArgument) ? parseTemplates(firstArgument, nextArguments) : [firstArgument, ...nextArguments]; const [rawFile, rawArgs, rawOptions] = normalizeArguments(...callArguments); const mergedOptions = {...deepOptions, ...boundOptions, ...rawOptions}; const { file = rawFile, args = rawArgs, options = mergedOptions, isSync = false, } = mapArguments({file: rawFile, args: rawArgs, options: mergedOptions}); return {file, args, options, isSync};};modified:lib/arguments/node.js+3 added-7 removed
12343478956789141510111213141527 unmodified linesimport {execPath, execArgv} from 'node:process';import {basename, resolve} from 'node:path';import {execa} from '../async.js';import {normalizeArguments} from './options.js';import {safeNormalizeFileUrl} from './cwd.js';
export function execaNode(file, args, options) { [file, args, options] = normalizeArguments(file, args, options);
export const mapNode = ({options}) => { if (options.node === false) { throw new TypeError('The "node" option cannot be false with `execaNode()`.'); }
return execa(file, args, {...options, node: true});} return {options: {...options, node: true}};};
export const handleNodeOption = (file, args, { node: shouldHandleNode = false, nodePath = execPath,27 unmodified linesadded:lib/arguments/normalize.js+29 added
1234567891011121314151617181920212223242526272829import isPlainObject from 'is-plain-obj';import {safeNormalizeFileUrl} from './cwd.js';
export const normalizeArguments = (rawFile, rawArgs = [], rawOptions = {}) => { const filePath = safeNormalizeFileUrl(rawFile, 'First argument'); const [args, options] = isPlainObject(rawArgs) ? [[], rawArgs] : [rawArgs, rawOptions];
if (!Array.isArray(args)) { throw new TypeError(`Second argument must be either an array of arguments or an options object: ${args}`); }
if (args.some(arg => typeof arg === 'object' && arg !== null)) { throw new TypeError(`Second argument must be an array of strings: ${args}`); }
const normalizedArgs = args.map(String); const nullByteArg = normalizedArgs.find(arg => arg.includes('\0')); if (nullByteArg !== undefined) { throw new TypeError(`Arguments cannot contain null bytes ("\\0"): ${nullByteArg}`); }
if (!isPlainObject(options)) { throw new TypeError(`Last argument must be an options object: ${options}`); }
return [filePath, normalizedArgs, options];};modified:lib/arguments/options.js+2 added-30 removed
1234556789101112141314161718192021222324252627282930313233343536373839404142151617181920212251232425262768 unmodified linesimport {basename} from 'node:path';import process from 'node:process';import crossSpawn from 'cross-spawn';import {npmRunPathEnv} from 'npm-run-path';import isPlainObject from 'is-plain-obj';import {normalizeForceKillAfterDelay} from '../exit/kill.js';import {validateTimeout} from '../exit/timeout.js';import {logCommand} from '../verbose/start.js';import {getVerboseInfo} from '../verbose/info.js';import {getStartTime} from '../return/duration.js';import {validateEncoding, BINARY_ENCODINGS} from './encoding.js';import {handleNodeOption} from './node.js';import {joinCommand} from './escape.js';import {normalizeCwd, safeNormalizeFileUrl, normalizeFileUrl} from './cwd.js';import {normalizeCwd, normalizeFileUrl} from './cwd.js';
export const normalizeArguments = (rawFile, rawArgs = [], rawOptions = {}) => { const filePath = safeNormalizeFileUrl(rawFile, 'First argument'); const [args, options] = isPlainObject(rawArgs) ? [[], rawArgs] : [rawArgs, rawOptions];
if (!Array.isArray(args)) { throw new TypeError(`Second argument must be either an array of arguments or an options object: ${args}`); }
if (args.some(arg => typeof arg === 'object' && arg !== null)) { throw new TypeError(`Second argument must be an array of strings: ${args}`); }
const normalizedArgs = args.map(String); const nullByteArg = normalizedArgs.find(arg => arg.includes('\0')); if (nullByteArg !== undefined) { throw new TypeError(`Arguments cannot contain null bytes ("\\0"): ${nullByteArg}`); }
if (!isPlainObject(options)) { throw new TypeError(`Last argument must be an options object: ${options}`); }
return [filePath, normalizedArgs, options];};
export const handleCommand = (filePath, rawArgs, rawOptions) => { const startTime = getStartTime(); const {command, escapedCommand} = joinCommand(filePath, rawArgs); const verboseInfo = getVerboseInfo(rawOptions); logCommand(escapedCommand, verboseInfo, rawOptions); return {command, escapedCommand, startTime, verboseInfo};};
export const handleArguments = (filePath, rawArgs, rawOptions) => {export const handleOptions = (filePath, rawArgs, rawOptions) => { rawOptions.cwd = normalizeCwd(rawOptions.cwd); const [processedFile, processedArgs, processedOptions] = handleNodeOption(filePath, rawArgs, rawOptions);
const {command: file, args, options: initialOptions} = crossSpawn._parse(processedFile, processedArgs, processedOptions);68 unmodified linesadded:lib/arguments/template.js+132 added
1+import {isUint8Array, uint8ArrayToString, isSubprocess} from '../utils.js';2+3+export const isTemplateString = templates => Array.isArray(templates) && Array.isArray(templates.raw);4+5+export const parseTemplates = (templates, expressions) => {6+ let tokens = [];7+8+ for (const [index, template] of templates.entries()) {9+ tokens = parseTemplate({templates, expressions, tokens, index, template});10+ }11+12+ if (tokens.length === 0) {13+ throw new TypeError('Template script must not be empty');14+ }15+16+ const [file, ...args] = tokens;17+ return [file, args, {}];18+};19+20+const parseTemplate = ({templates, expressions, tokens, index, template}) => {21+ if (template === undefined) {22+ throw new TypeError(`Invalid backslash sequence: ${templates.raw[index]}`);23+ }24+25+ const {nextTokens, leadingWhitespaces, trailingWhitespaces} = splitByWhitespaces(template, templates.raw[index]);26+ const newTokens = concatTokens(tokens, nextTokens, leadingWhitespaces);27+28+ if (index === expressions.length) {29+ return newTokens;30+ }31+32+ const expression = expressions[index];33+ const expressionTokens = Array.isArray(expression)34+ ? expression.map(expression => parseExpression(expression))35+ : [parseExpression(expression)];36+ return concatTokens(newTokens, expressionTokens, trailingWhitespaces);37+};38+39+// Like `string.split(/[ \t\r\n]+/)` except newlines and tabs are:40+// - ignored when input as a backslash sequence like: `echo foo\n bar`41+// - not ignored when input directly42+// The only way to distinguish those in JavaScript is to use a tagged template and compare:43+// - the first array argument, which does not escape backslash sequences44+// - its `raw` property, which escapes them45+const splitByWhitespaces = (template, rawTemplate) => {46+ if (rawTemplate.length === 0) {47+ return {nextTokens: [], leadingWhitespaces: false, trailingWhitespaces: false};48+ }49+50+ const nextTokens = [];51+ let templateStart = 0;52+ const leadingWhitespaces = DELIMITERS.has(rawTemplate[0]);53+54+ for (55+ let templateIndex = 0, rawIndex = 0;56+ templateIndex < template.length;57+ templateIndex += 1, rawIndex += 158+ ) {59+ const rawCharacter = rawTemplate[rawIndex];60+ if (DELIMITERS.has(rawCharacter)) {61+ if (templateStart !== templateIndex) {62+ nextTokens.push(template.slice(templateStart, templateIndex));63+ }64+65+ templateStart = templateIndex + 1;66+ } else if (rawCharacter === '\\') {67+ const nextRawCharacter = rawTemplate[rawIndex + 1];68+ if (nextRawCharacter === 'u' && rawTemplate[rawIndex + 2] === '{') {69+ rawIndex = rawTemplate.indexOf('}', rawIndex + 3);70+ } else {71+ rawIndex += ESCAPE_LENGTH[nextRawCharacter] ?? 1;72+ }73+ }74+ }75+76+ const trailingWhitespaces = templateStart === template.length;77+ if (!trailingWhitespaces) {78+ nextTokens.push(template.slice(templateStart));79+ }80+81+ return {nextTokens, leadingWhitespaces, trailingWhitespaces};82+};83+84+const DELIMITERS = new Set([' ', '\t', '\r', '\n']);85+86+// Number of characters in backslash escape sequences: \0 \xXX or \uXXXX87+// \cX is allowed in RegExps but not in strings88+// Octal sequences are not allowed in strict mode89+const ESCAPE_LENGTH = {x: 3, u: 5};90+91+const concatTokens = (tokens, nextTokens, isSeparated) => isSeparated92+ || tokens.length === 093+ || nextTokens.length === 094+ ? [...tokens, ...nextTokens]95+ : [96+ ...tokens.slice(0, -1),97+ `${tokens.at(-1)}${nextTokens[0]}`,98+ ...nextTokens.slice(1),99+ ];100+101+const parseExpression = expression => {102+ const typeOfExpression = typeof expression;103+104+ if (typeOfExpression === 'string') {105+ return expression;106+ }107+108+ if (typeOfExpression === 'number') {109+ return String(expression);110+ }111+112+ if (113+ typeOfExpression === 'object'114+ && expression !== null115+ && !isSubprocess(expression)116+ && 'stdout' in expression117+ ) {118+ const typeOfStdout = typeof expression.stdout;119+120+ if (typeOfStdout === 'string') {121+ return expression.stdout;122+ }123+124+ if (isUint8Array(expression.stdout)) {125+ return uint8ArrayToString(expression.stdout);126+ }127+128+ throw new TypeError(`Unexpected "${typeOfStdout}" stdout in template expression`);129+ }130+131+ throw new TypeError(`Unexpected "${typeOfExpression}" in template expression`);132+};modified:lib/pipe/validate.js+9 added-11 removed
1-import {execa} from '../async.js';2-import {create$} from '../script.js';3-import {normalizeArguments} from '../arguments/options.js';1+import {normalizeArguments} from '../arguments/normalize.js';2 import {STANDARD_STREAMS_ALIASES} from '../utils.js';3 import {getStartTime} from '../return/duration.js';4 7-export const normalizePipeArguments = ({source, sourcePromise, boundOptions}, ...args) => {5+export const normalizePipeArguments = ({source, sourcePromise, boundOptions, createNested}, ...args) => {6 const startTime = getStartTime();7 const {8 destination,9 destinationStream,10 destinationError,11 from,12 unpipeSignal,15- } = getDestinationStream(boundOptions, args);13+ } = getDestinationStream(boundOptions, createNested, args);14 const {sourceStream, sourceError} = getSourceStream(source, from);15 const {options: sourceOptions, fileDescriptors} = SUBPROCESS_OPTIONS.get(source);16 return {17 sourcePromise,8 unmodified lines26 startTime,27 };28 };29 32-const getDestinationStream = (boundOptions, args) => {30+const getDestinationStream = (boundOptions, createNested, args) => {31 try {32 const {33 destination,34 pipeOptions: {from, to, unpipeSignal} = {},37- } = getDestination(boundOptions, ...args);35+ } = getDestination(boundOptions, createNested, ...args);36 const destinationStream = getWritable(destination, to);37 return {destination, destinationStream, from, unpipeSignal};38 } catch (error) {39 return {destinationError: error};40 }41 };42 45-const getDestination = (boundOptions, firstArgument, ...args) => {43+const getDestination = (boundOptions, createNested, firstArgument, ...args) => {44 if (Array.isArray(firstArgument)) {47- const destination = create$({...boundOptions, ...PIPED_SUBPROCESS_OPTIONS})(firstArgument, ...args);45+ const destination = createNested(mapDestinationArguments, boundOptions)(firstArgument, ...args);46 return {destination, pipeOptions: boundOptions};47 }48 49 if (typeof firstArgument === 'string' || firstArgument instanceof URL) {1 unmodified line51 throw new TypeError('Please use .pipe("file", ..., options) or .pipe(execa("file", ..., options)) instead of .pipe(options)("file", ...).');52 }53 54 const [rawFile, rawArgs, rawOptions] = normalizeArguments(firstArgument, ...args);57- const destination = execa(rawFile, rawArgs, {...rawOptions, ...PIPED_SUBPROCESS_OPTIONS});55+ const destination = createNested(mapDestinationArguments)(rawFile, rawArgs, rawOptions);56 return {destination, pipeOptions: rawOptions};57 }58 59 if (SUBPROCESS_OPTIONS.has(firstArgument)) {6 unmodified lines66 67 throw new TypeError(`The first argument must be a template string, an options object, or an Execa subprocess: ${firstArgument}`);68 };69 72-const PIPED_SUBPROCESS_OPTIONS = {stdin: 'pipe', piped: true};70+const mapDestinationArguments = ({options}) => ({options: {...options, stdin: 'pipe', piped: true}});71 72 export const SUBPROCESS_OPTIONS = new WeakMap();73 74 export const getWritable = (destination, to = 'stdin') => {120 unmodified linesmodified:lib/async.js+4 added-5 removed
1 import {setMaxListeners} from 'node:events';2 import {spawn} from 'node:child_process';3-import {normalizeArguments, handleCommand, handleArguments} from './arguments/options.js';3+import {handleCommand, handleOptions} from './arguments/options.js';4 import {makeError, makeSuccessResult} from './return/error.js';5 import {handleOutput, handleResult} from './return/output.js';6 import {handleEarlyError} from './return/early-error.js';7 import {handleInputAsync, pipeOutputAsync} from './stdio/async.js';6 unmodified lines14 import {addConvertedStreams} from './convert/add.js';15 import {getSubprocessResult} from './stream/resolve.js';16 import {mergePromise} from './promise.js';17 18-export const execa = (rawFile, rawArgs, rawOptions) => {18+export const execaCoreAsync = (rawFile, rawArgs, rawOptions, createNested) => {19 const {file, args, command, escapedCommand, startTime, verboseInfo, options, fileDescriptors, stdioState} = handleAsyncArguments(rawFile, rawArgs, rawOptions);20 const {subprocess, promise} = spawnSubprocessAsync({file, args, options, startTime, verboseInfo, command, escapedCommand, fileDescriptors, stdioState});21- subprocess.pipe = pipeToSubprocess.bind(undefined, {source: subprocess, sourcePromise: promise, boundOptions: {}});21+ subprocess.pipe = pipeToSubprocess.bind(undefined, {source: subprocess, sourcePromise: promise, boundOptions: {}, createNested});22 mergePromise(subprocess, promise);23 SUBPROCESS_OPTIONS.set(subprocess, {options, fileDescriptors});24 return subprocess;25 };26 27 const handleAsyncArguments = (rawFile, rawArgs, rawOptions) => {28- [rawFile, rawArgs, rawOptions] = normalizeArguments(rawFile, rawArgs, rawOptions);28 const {command, escapedCommand, startTime, verboseInfo} = handleCommand(rawFile, rawArgs, rawOptions);29 30 try {32- const {file, args, options: normalizedOptions} = handleArguments(rawFile, rawArgs, rawOptions);31+ const {file, args, options: normalizedOptions} = handleOptions(rawFile, rawArgs, rawOptions);32 const options = handleAsyncOptions(normalizedOptions);33 const {fileDescriptors, stdioState} = handleInputAsync(options, verboseInfo);34 return {file, args, command, escapedCommand, startTime, verboseInfo, options, fileDescriptors, stdioState};35 } catch (error) {70 unmodified linesmodified:lib/command.js+7 added-21 removed
1-import isPlainObj from 'is-plain-obj';2-import {execa} from './async.js';3-import {execaSync} from './sync.js';1+export const mapCommandAsync = ({file, args}) => parseCommand(file, args);2+export const mapCommandSync = ({file, args}) => ({...parseCommand(file, args), isSync: true});3 5-export function execaCommand(command, options) {6- const [file, ...args] = parseCommand(command, options);7- return execa(file, args, options);8-}9-10-export function execaCommandSync(command, options) {11- const [file, ...args] = parseCommand(command, options);12- return execaSync(file, args, options);13-}14-15-const parseCommand = (command, options) => {16- if (typeof command !== 'string') {17- throw new TypeError(`First argument must be a string: ${command}.`);4+const parseCommand = (command, unusedArgs) => {5+ if (unusedArgs.length > 0) {6+ throw new TypeError(`The command and its arguments must be passed as a single string: ${command} ${unusedArgs}.`);7 }8 20- if (options !== undefined && !isPlainObj(options)) {21- throw new TypeError(`The command and its arguments must be passed as a single string: ${command} ${options}.`);22- }23-9 const tokens = [];10 for (const token of command.trim().split(SPACES_REGEXP)) {11 // Allow spaces to be escaped by a backslash if not meant as a delimiter12 const previousToken = tokens.at(-1);4 unmodified lines17 tokens.push(token);18 }19 }20 36- return tokens;21+ const [file, ...args] = tokens;22+ return {file, args};23 };24 25 const SPACES_REGEXP = / +/g;modified:lib/script.js+9 added-170 removed
1-import isPlainObject from 'is-plain-obj';2-import {isUint8Array, uint8ArrayToString, isSubprocess} from './utils.js';3-import {execa} from './async.js';4-import {execaSync} from './sync.js';5-6-export const create$ = options => {7- function $(templatesOrOptions, ...expressions) {8- if (isPlainObject(templatesOrOptions)) {9- return create$({...options, ...templatesOrOptions});10- }11-12- if (!Array.isArray(templatesOrOptions)) {13- throw new TypeError('Please use either $(option) or $`command`.');14- }15-16- const [file, ...args] = parseTemplates(templatesOrOptions, expressions);17- return execa(file, args, normalizeScriptOptions(options));18- }19-20- $.sync = (templates, ...expressions) => {21- if (isPlainObject(templates)) {22- throw new TypeError('Please use $(options).sync`command` instead of $.sync(options)`command`.');23- }24-25- if (!Array.isArray(templates)) {26- throw new TypeError('A template string must be used: $.sync`command`.');27- }28-29- const [file, ...args] = parseTemplates(templates, expressions);30- return execaSync(file, args, normalizeScriptOptions(options));31- };32-33- $.s = $.sync;34-35- return $;1+export const setScriptSync = (boundExeca, createNested, boundOptions) => {2+ boundExeca.sync = createNested(mapScriptSync, boundOptions);3+ boundExeca.s = boundExeca.sync;4 };5 38-export const $ = create$();6+export const mapScriptAsync = ({options}) => getScriptOptions(options);7+const mapScriptSync = ({options}) => ({...getScriptOptions(options), isSync: true});8 40-const parseTemplates = (templates, expressions) => {41- let tokens = [];9+const getScriptOptions = options => ({options: {...getScriptStdinOption(options), ...options}});10 43- for (const [index, template] of templates.entries()) {44- tokens = parseTemplate({templates, expressions, tokens, index, template});45- }46-47- if (tokens.length === 0) {48- throw new TypeError('Template script must not be empty');49- }50-51- return tokens;52-};53-54-const parseTemplate = ({templates, expressions, tokens, index, template}) => {55- if (template === undefined) {56- throw new TypeError(`Invalid backslash sequence: ${templates.raw[index]}`);57- }58-59- const {nextTokens, leadingWhitespaces, trailingWhitespaces} = splitByWhitespaces(template, templates.raw[index]);60- const newTokens = concatTokens(tokens, nextTokens, leadingWhitespaces);61-62- if (index === expressions.length) {63- return newTokens;64- }65-66- const expression = expressions[index];67- const expressionTokens = Array.isArray(expression)68- ? expression.map(expression => parseExpression(expression))69- : [parseExpression(expression)];70- return concatTokens(newTokens, expressionTokens, trailingWhitespaces);71-};72-73-// Like `string.split(/[ \t\r\n]+/)` except newlines and tabs are:74-// - ignored when input as a backslash sequence like: `echo foo\n bar`75-// - not ignored when input directly76-// The only way to distinguish those in JavaScript is to use a tagged template and compare:77-// - the first array argument, which does not escape backslash sequences78-// - its `raw` property, which escapes them79-const splitByWhitespaces = (template, rawTemplate) => {80- if (rawTemplate.length === 0) {81- return {nextTokens: [], leadingWhitespaces: false, trailingWhitespaces: false};82- }83-84- const nextTokens = [];85- let templateStart = 0;86- const leadingWhitespaces = DELIMITERS.has(rawTemplate[0]);87-88- for (89- let templateIndex = 0, rawIndex = 0;90- templateIndex < template.length;91- templateIndex += 1, rawIndex += 192- ) {93- const rawCharacter = rawTemplate[rawIndex];94- if (DELIMITERS.has(rawCharacter)) {95- if (templateStart !== templateIndex) {96- nextTokens.push(template.slice(templateStart, templateIndex));97- }98-99- templateStart = templateIndex + 1;100- } else if (rawCharacter === '\\') {101- const nextRawCharacter = rawTemplate[rawIndex + 1];102- if (nextRawCharacter === 'u' && rawTemplate[rawIndex + 2] === '{') {103- rawIndex = rawTemplate.indexOf('}', rawIndex + 3);104- } else {105- rawIndex += ESCAPE_LENGTH[nextRawCharacter] ?? 1;106- }107- }108- }109-110- const trailingWhitespaces = templateStart === template.length;111- if (!trailingWhitespaces) {112- nextTokens.push(template.slice(templateStart));113- }114-115- return {nextTokens, leadingWhitespaces, trailingWhitespaces};116-};117-118-const DELIMITERS = new Set([' ', '\t', '\r', '\n']);119-120-// Number of characters in backslash escape sequences: \0 \xXX or \uXXXX121-// \cX is allowed in RegExps but not in strings122-// Octal sequences are not allowed in strict mode123-const ESCAPE_LENGTH = {x: 3, u: 5};124-125-const concatTokens = (tokens, nextTokens, isSeparated) => isSeparated126- || tokens.length === 0127- || nextTokens.length === 0128- ? [...tokens, ...nextTokens]129- : [130- ...tokens.slice(0, -1),131- `${tokens.at(-1)}${nextTokens[0]}`,132- ...nextTokens.slice(1),133- ];134-135-const parseExpression = expression => {136- const typeOfExpression = typeof expression;137-138- if (typeOfExpression === 'string') {139- return expression;140- }141-142- if (typeOfExpression === 'number') {143- return String(expression);144- }145-146- if (147- typeOfExpression === 'object'148- && expression !== null149- && !isSubprocess(expression)150- && 'stdout' in expression151- ) {152- const typeOfStdout = typeof expression.stdout;153-154- if (typeOfStdout === 'string') {155- return expression.stdout;156- }157-158- if (isUint8Array(expression.stdout)) {159- return uint8ArrayToString(expression.stdout);160- }161-162- throw new TypeError(`Unexpected "${typeOfStdout}" stdout in template expression`);163- }164-165- throw new TypeError(`Unexpected "${typeOfExpression}" in template expression`);166-};167-168-const normalizeScriptOptions = (options = {}) => ({169- preferLocal: true,170- ...normalizeScriptStdin(options),171- ...options,172-});173-174-const normalizeScriptStdin = ({input, inputFile, stdio}) => input === undefined && inputFile === undefined && stdio === undefined11+const getScriptStdinOption = ({input, inputFile, stdio}) => input === undefined && inputFile === undefined && stdio === undefined12 ? {stdin: 'inherit'}13 : {};14+15+export const deepScriptOptions = {preferLocal: true};modified:lib/sync.js+3 added-4 removed
1 import {spawnSync} from 'node:child_process';2-import {normalizeArguments, handleCommand, handleArguments} from './arguments/options.js';2+import {handleCommand, handleOptions} from './arguments/options.js';3 import {makeError, makeEarlyError, makeSuccessResult} from './return/error.js';4 import {handleOutput, handleResult} from './return/output.js';5 import {handleInputSync, pipeOutputSync} from './stdio/sync.js';6 import {logEarlyResult} from './verbose/complete.js';7 import {getSyncExitResult} from './exit/code.js';8 9-export const execaSync = (rawFile, rawArgs, rawOptions) => {9+export const execaCoreSync = (rawFile, rawArgs, rawOptions) => {10 const {file, args, command, escapedCommand, startTime, verboseInfo, options, fileDescriptors} = handleSyncArguments(rawFile, rawArgs, rawOptions);11 const result = spawnSubprocessSync({file, args, options, command, escapedCommand, fileDescriptors, startTime});12 return handleResult(result, verboseInfo, options);13 };14 15 const handleSyncArguments = (rawFile, rawArgs, rawOptions) => {16- [rawFile, rawArgs, rawOptions] = normalizeArguments(rawFile, rawArgs, rawOptions);16 const {command, escapedCommand, startTime, verboseInfo} = handleCommand(rawFile, rawArgs, rawOptions);17 18 try {19 const syncOptions = normalizeSyncOptions(rawOptions);21- const {file, args, options} = handleArguments(rawFile, rawArgs, syncOptions);20+ const {file, args, options} = handleOptions(rawFile, rawArgs, syncOptions);21 validateSyncOptions(options);22 const fileDescriptors = handleInputSync(options, verboseInfo);23 return {file, args, command, escapedCommand, startTime, verboseInfo, options, fileDescriptors};24 } catch (error) {44 unmodified linesadded:test/arguments/create.js+85 added
1+import {join} from 'node:path';2+import test from 'ava';3+import {execa, execaSync, execaNode, $} from '../../index.js';4+import {foobarString, foobarArray} from '../helpers/input.js';5+import {setFixtureDir, FIXTURES_DIR} from '../helpers/fixtures-dir.js';6+7+setFixtureDir();8+const NOOP_PATH = join(FIXTURES_DIR, 'noop.js');9+10+const testTemplate = async (t, execaMethod) => {11+ const {stdout} = await execaMethod`${NOOP_PATH} ${foobarString}`;12+ t.is(stdout, foobarString);13+};14+15+test('execa() can use template strings', testTemplate, execa);16+test('execaNode() can use template strings', testTemplate, execaNode);17+test('$ can use template strings', testTemplate, $);18+19+const testTemplateSync = (t, execaMethod) => {20+ const {stdout} = execaMethod`${NOOP_PATH} ${foobarString}`;21+ t.is(stdout, foobarString);22+};23+24+test('execaSync() can use template strings', testTemplateSync, execaSync);25+test('$.sync can use template strings', testTemplateSync, $.sync);26+27+const testTemplateOptions = async (t, execaMethod) => {28+ const {stdout} = await execaMethod({stripFinalNewline: false})`${NOOP_PATH} ${foobarString}`;29+ t.is(stdout, `${foobarString}\n`);30+};31+32+test('execa() can use template strings with options', testTemplateOptions, execa);33+test('execaNode() can use template strings with options', testTemplateOptions, execaNode);34+test('$ can use template strings with options', testTemplateOptions, $);35+36+const testTemplateOptionsSync = (t, execaMethod) => {37+ const {stdout} = execaMethod({stripFinalNewline: false})`${NOOP_PATH} ${foobarString}`;38+ t.is(stdout, `${foobarString}\n`);39+};40+41+test('execaSync() can use template strings with options', testTemplateOptionsSync, execaSync);42+test('$.sync can use template strings with options', testTemplateOptionsSync, $.sync);43+44+const testBindOptions = async (t, execaMethod) => {45+ const {stdout} = await execaMethod({stripFinalNewline: false})(NOOP_PATH, [foobarString]);46+ t.is(stdout, `${foobarString}\n`);47+};48+49+test('execa() can bind options', testBindOptions, execa);50+test('execaNode() can bind options', testBindOptions, execaNode);51+test('$ can bind options', testBindOptions, $);52+53+const testBindOptionsSync = (t, execaMethod) => {54+ const {stdout} = execaMethod({stripFinalNewline: false})(NOOP_PATH, [foobarString]);55+ t.is(stdout, `${foobarString}\n`);56+};57+58+test('execaSync() can bind options', testBindOptionsSync, execaSync);59+test('$.sync can bind options', testBindOptionsSync, $.sync);60+61+const testBindPriority = async (t, execaMethod) => {62+ const {stdout} = await execaMethod({stripFinalNewline: false})(NOOP_PATH, [foobarString], {stripFinalNewline: true});63+ t.is(stdout, foobarString);64+};65+66+test('execa() bound options have lower priority', testBindPriority, execa);67+test('execaSync() bound options have lower priority', testBindPriority, execaSync);68+test('execaNode() bound options have lower priority', testBindPriority, execaNode);69+test('$ bound options have lower priority', testBindPriority, $);70+test('$.sync bound options have lower priority', testBindPriority, $.sync);71+72+const testSpacedCommand = async (t, args, execaMethod) => {73+ const {stdout} = await execaMethod('command with space.js', args);74+ const expectedStdout = args === undefined ? '' : args.join('\n');75+ t.is(stdout, expectedStdout);76+};77+78+test('allow commands with spaces and no array arguments', testSpacedCommand, undefined, execa);79+test('allow commands with spaces and array arguments', testSpacedCommand, foobarArray, execa);80+test('allow commands with spaces and no array arguments, execaSync', testSpacedCommand, undefined, execaSync);81+test('allow commands with spaces and array arguments, execaSync', testSpacedCommand, foobarArray, execaSync);82+test('allow commands with spaces and no array arguments, $', testSpacedCommand, undefined, $);83+test('allow commands with spaces and array arguments, $', testSpacedCommand, foobarArray, $);84+test('allow commands with spaces and no array arguments, $.sync', testSpacedCommand, undefined, $.sync);85+test('allow commands with spaces and array arguments, $.sync', testSpacedCommand, foobarArray, $.sync);modified:test/arguments/escape.js-10 removed
96 unmodified lines97 test('result.escapedCommand - \\uE000', testEscapedCommand, ['\uE000'], '\'\\ue000\'', '"\\ue000"');98 test('result.escapedCommand - \\U1D172', testEscapedCommand, ['\u{1D172}'], '\'\u{1D172}\'', '"\u{1D172}"');99 test('result.escapedCommand - \\U1D173', testEscapedCommand, ['\u{1D173}'], '\'\\U1d173\'', '"\\U1d173"');100 test('result.escapedCommand - \\U10FFFD', testEscapedCommand, ['\u{10FFFD}'], '\'\\U10fffd\'', '"\\U10fffd"');101-102-test('allow commands with spaces and no array arguments', async t => {103- const {stdout} = await execa('command with space.js');104- t.is(stdout, '');105-});106-107-test('allow commands with spaces and array arguments', async t => {108- const {stdout} = await execa('command with space.js', ['foo', 'bar']);109- t.is(stdout, 'foo\nbar');110-});modified:test/arguments/node.js+28 added-1 removed
1 import {once} from 'node:events';2 import {dirname, relative} from 'node:path';3-import process from 'node:process';3+import process, {version} from 'node:process';4 import {pathToFileURL} from 'node:url';5 import test from 'ava';6 import getNode from 'get-node';7 import {pEvent} from 'p-event';21 unmodified lines29 test('execaNode() succeeds', testNodeSuccess, execaNode);30 test('The "node" option succeeds', testNodeSuccess, runWithNodeOption);31 test('The "node" option succeeds - sync', testNodeSuccess, runWithNodeOptionSync);32 33+test('execaNode(options) succeeds', async t => {34+ const {stdout} = await execaNode({stripFinalNewline: false})('noop.js', [foobarString]);35+ t.is(stdout, `${foobarString}\n`);36+});37+38+test('execaNode`...` succeeds', async t => {39+ const {stdout} = await execaNode`noop.js ${foobarString}`;40+ t.is(stdout, foobarString);41+});42+43+test('execaNode().pipe(execaNode()) succeeds', async t => {44+ const {stdout} = await execaNode('noop.js').pipe(execaNode('--version'));45+ t.is(stdout, version);46+});47+48+test('execaNode().pipe(execa()) requires using "node"', async t => {49+ await t.throwsAsync(execaNode('noop.js').pipe(execa('--version')));50+});51+52+test('execaNode().pipe(...) requires using "node"', async t => {53+ await t.throwsAsync(execaNode('noop.js').pipe('--version'));54+});55+56+test('execaNode().pipe`...` requires using "node"', async t => {57+ await t.throwsAsync(execaNode('noop.js').pipe`--version`);58+});59+60 test('execaNode() cannot set the "node" option to false', t => {61 t.throws(() => {62 execaNode('empty.js', {node: false});63 }, {message: /The "node" option cannot be false/});242 unmodified linesadded:test/arguments/normalize.js+183 added
1+import {join, basename} from 'node:path';2+import {fileURLToPath} from 'node:url';3+import test from 'ava';4+import {execa, execaSync, execaCommand, execaCommandSync, execaNode, $} from '../../index.js';5+import {setFixtureDir, FIXTURES_DIR, FIXTURES_DIR_URL} from '../helpers/fixtures-dir.js';6+import {foobarString} from '../helpers/input.js';7+8+setFixtureDir();9+const NOOP_PATH = join(FIXTURES_DIR, 'noop.js');10+11+const testFileUrl = async (t, execaMethod) => {12+ const command = new URL('noop.js', FIXTURES_DIR_URL);13+ const {stdout} = await execaMethod(command);14+ t.is(stdout, foobarString);15+};16+17+test('execa()\'s command argument can be a file URL', testFileUrl, execa);18+test('execaSync()\'s command argument can be a file URL', testFileUrl, execaSync);19+test('execaCommand()\'s command argument can be a file URL', testFileUrl, execaCommand);20+test('execaCommandSync()\'s command argument can be a file URL', testFileUrl, execaCommandSync);21+test('execaNode()\'s command argument can be a file URL', testFileUrl, execaNode);22+test('$\'s command argument can be a file URL', testFileUrl, $);23+test('$.sync\'s command argument can be a file URL', testFileUrl, $.sync);24+25+const testInvalidFileUrl = async (t, execaMethod) => {26+ const invalidUrl = new URL('https://invalid.com');27+ t.throws(() => {28+ execaMethod(invalidUrl);29+ }, {code: 'ERR_INVALID_URL_SCHEME'});30+};31+32+test('execa()\'s command argument cannot be a non-file URL', testInvalidFileUrl, execa);33+test('execaSync()\'s command argument cannot be a non-file URL', testInvalidFileUrl, execaSync);34+test('execaCommand()\'s command argument cannot be a non-file URL', testInvalidFileUrl, execaCommand);35+test('execaCommandSync()\'s command argument cannot be a non-file URL', testInvalidFileUrl, execaCommandSync);36+test('execaNode()\'s command argument cannot be a non-file URL', testInvalidFileUrl, execaNode);37+test('$\'s command argument cannot be a non-file URL', testInvalidFileUrl, $);38+test('$.sync\'s command argument cannot be a non-file URL', testInvalidFileUrl, $.sync);39+40+const testInvalidCommand = async (t, arg, execaMethod) => {41+ t.throws(() => {42+ execaMethod(arg);43+ }, {message: /First argument must be a string or a file URL/});44+};45+46+test('execa()\'s first argument must be defined', testInvalidCommand, undefined, execa);47+test('execaSync()\'s first argument must be defined', testInvalidCommand, undefined, execaSync);48+test('execaCommand()\'s first argument must be defined', testInvalidCommand, undefined, execaCommand);49+test('execaCommandSync()\'s first argument must be defined', testInvalidCommand, undefined, execaCommandSync);50+test('execaNode()\'s first argument must be defined', testInvalidCommand, undefined, execaNode);51+test('$\'s first argument must be defined', testInvalidCommand, undefined, $);52+test('$.sync\'s first argument must be defined', testInvalidCommand, undefined, $.sync);53+test('execa()\'s first argument must be valid', testInvalidCommand, true, execa);54+test('execaSync()\'s first argument must be valid', testInvalidCommand, true, execaSync);55+test('execaCommand()\'s first argument must be valid', testInvalidCommand, true, execaCommand);56+test('execaCommandSync()\'s first argument must be valid', testInvalidCommand, true, execaCommandSync);57+test('execaNode()\'s first argument must be valid', testInvalidCommand, true, execaNode);58+test('$\'s first argument must be valid', testInvalidCommand, true, $);59+test('$.sync\'s first argument must be valid', testInvalidCommand, true, $.sync);60+test('execa()\'s command argument must be a string or file URL', testInvalidCommand, ['command', 'arg'], execa);61+test('execaSync()\'s command argument must be a string or file URL', testInvalidCommand, ['command', 'arg'], execaSync);62+test('execaCommand()\'s command argument must be a string or file URL', testInvalidCommand, ['command', 'arg'], execaCommand);63+test('execaCommandSync()\'s command argument must be a string or file URL', testInvalidCommand, ['command', 'arg'], execaCommandSync);64+test('execaNode()\'s command argument must be a string or file URL', testInvalidCommand, ['command', 'arg'], execaNode);65+test('$\'s command argument must be a string or file URL', testInvalidCommand, ['command', 'arg'], $);66+test('$.sync\'s command argument must be a string or file URL', testInvalidCommand, ['command', 'arg'], $.sync);67+68+const testInvalidArgs = async (t, execaMethod) => {69+ t.throws(() => {70+ execaMethod('echo', true);71+ }, {message: /Second argument must be either/});72+};73+74+test('execa()\'s second argument must be valid', testInvalidArgs, execa);75+test('execaSync()\'s second argument must be valid', testInvalidArgs, execaSync);76+test('execaCommand()\'s second argument must be valid', testInvalidArgs, execaCommand);77+test('execaCommandSync()\'s second argument must be valid', testInvalidArgs, execaCommandSync);78+test('execaNode()\'s second argument must be valid', testInvalidArgs, execaNode);79+test('$\'s second argument must be valid', testInvalidArgs, $);80+test('$.sync\'s second argument must be valid', testInvalidArgs, $.sync);81+82+const testInvalidArgsItems = async (t, execaMethod) => {83+ t.throws(() => {84+ execaMethod('echo', [{}]);85+ }, {message: 'Second argument must be an array of strings: [object Object]'});86+};87+88+test('execa()\'s second argument must not be objects', testInvalidArgsItems, execa);89+test('execaSync()\'s second argument must not be objects', testInvalidArgsItems, execaSync);90+test('execaCommand()\'s second argument must not be objects', testInvalidArgsItems, execaCommand);91+test('execaCommandSync()\'s second argument must not be objects', testInvalidArgsItems, execaCommandSync);92+test('execaNode()\'s second argument must not be objects', testInvalidArgsItems, execaNode);93+test('$\'s second argument must not be objects', testInvalidArgsItems, $);94+test('$.sync\'s second argument must not be objects', testInvalidArgsItems, $.sync);95+96+const testNullByteArg = async (t, execaMethod) => {97+ t.throws(() => {98+ execaMethod('echo', ['a\0b']);99+ }, {message: /null bytes/});100+};101+102+test('execa()\'s second argument must not include \\0', testNullByteArg, execa);103+test('execaSync()\'s second argument must not include \\0', testNullByteArg, execaSync);104+test('execaCommand()\'s second argument must not include \\0', testNullByteArg, execaCommand);105+test('execaCommandSync()\'s second argument must not include \\0', testNullByteArg, execaCommandSync);106+test('execaNode()\'s second argument must not include \\0', testNullByteArg, execaNode);107+test('$\'s second argument must not include \\0', testNullByteArg, $);108+test('$.sync\'s second argument must not include \\0', testNullByteArg, $.sync);109+110+const testSerializeArg = async (t, arg, execaMethod) => {111+ const {stdout} = await execaMethod(NOOP_PATH, [arg]);112+ t.is(stdout, String(arg));113+};114+115+test('execa()\'s arguments can be numbers', testSerializeArg, 1, execa);116+test('execa()\'s arguments can be booleans', testSerializeArg, true, execa);117+test('execa()\'s arguments can be NaN', testSerializeArg, Number.NaN, execa);118+test('execa()\'s arguments can be Infinity', testSerializeArg, Number.POSITIVE_INFINITY, execa);119+test('execa()\'s arguments can be null', testSerializeArg, null, execa);120+test('execa()\'s arguments can be undefined', testSerializeArg, undefined, execa);121+test('execa()\'s arguments can be bigints', testSerializeArg, 1n, execa);122+test('execa()\'s arguments can be symbols', testSerializeArg, Symbol('test'), execa);123+test('execaSync()\'s arguments can be numbers', testSerializeArg, 1, execaSync);124+test('execaSync()\'s arguments can be booleans', testSerializeArg, true, execaSync);125+test('execaSync()\'s arguments can be NaN', testSerializeArg, Number.NaN, execaSync);126+test('execaSync()\'s arguments can be Infinity', testSerializeArg, Number.POSITIVE_INFINITY, execaSync);127+test('execaSync()\'s arguments can be null', testSerializeArg, null, execaSync);128+test('execaSync()\'s arguments can be undefined', testSerializeArg, undefined, execaSync);129+test('execaSync()\'s arguments can be bigints', testSerializeArg, 1n, execaSync);130+test('execaSync()\'s arguments can be symbols', testSerializeArg, Symbol('test'), execaSync);131+test('execaNode()\'s arguments can be numbers', testSerializeArg, 1, execaNode);132+test('execaNode()\'s arguments can be booleans', testSerializeArg, true, execaNode);133+test('execaNode()\'s arguments can be NaN', testSerializeArg, Number.NaN, execaNode);134+test('execaNode()\'s arguments can be Infinity', testSerializeArg, Number.POSITIVE_INFINITY, execaNode);135+test('execaNode()\'s arguments can be null', testSerializeArg, null, execaNode);136+test('execaNode()\'s arguments can be undefined', testSerializeArg, undefined, execaNode);137+test('execaNode()\'s arguments can be bigints', testSerializeArg, 1n, execaNode);138+test('execaNode()\'s arguments can be symbols', testSerializeArg, Symbol('test'), execaNode);139+test('$\'s arguments can be numbers', testSerializeArg, 1, $);140+test('$\'s arguments can be booleans', testSerializeArg, true, $);141+test('$\'s arguments can be NaN', testSerializeArg, Number.NaN, $);142+test('$\'s arguments can be Infinity', testSerializeArg, Number.POSITIVE_INFINITY, $);143+test('$\'s arguments can be null', testSerializeArg, null, $);144+test('$\'s arguments can be undefined', testSerializeArg, undefined, $);145+test('$\'s arguments can be bigints', testSerializeArg, 1n, $);146+test('$\'s arguments can be symbols', testSerializeArg, Symbol('test'), $);147+test('$.sync\'s arguments can be numbers', testSerializeArg, 1, $.sync);148+test('$.sync\'s arguments can be booleans', testSerializeArg, true, $.sync);149+test('$.sync\'s arguments can be NaN', testSerializeArg, Number.NaN, $.sync);150+test('$.sync\'s arguments can be Infinity', testSerializeArg, Number.POSITIVE_INFINITY, $.sync);151+test('$.sync\'s arguments can be null', testSerializeArg, null, $.sync);152+test('$.sync\'s arguments can be undefined', testSerializeArg, undefined, $.sync);153+test('$.sync\'s arguments can be bigints', testSerializeArg, 1n, $.sync);154+test('$.sync\'s arguments can be symbols', testSerializeArg, Symbol('test'), $.sync);155+156+const testInvalidOptions = async (t, execaMethod) => {157+ t.throws(() => {158+ execaMethod('echo', [], new Map());159+ }, {message: /Last argument must be an options object/});160+};161+162+test('execa()\'s third argument must be a plain object', testInvalidOptions, execa);163+test('execaSync()\'s third argument must be a plain object', testInvalidOptions, execaSync);164+test('execaCommand()\'s third argument must be a plain object', testInvalidOptions, execaCommand);165+test('execaCommandSync()\'s third argument must be a plain object', testInvalidOptions, execaCommandSync);166+test('execaNode()\'s third argument must be a plain object', testInvalidOptions, execaNode);167+test('$\'s third argument must be a plain object', testInvalidOptions, $);168+test('$.sync\'s third argument must be a plain object', testInvalidOptions, $.sync);169+170+const testRelativePath = async (t, execaMethod) => {171+ const rootDir = basename(fileURLToPath(new URL('../..', import.meta.url)));172+ const pathViaParentDir = join('..', rootDir, 'test', 'fixtures', 'noop.js');173+ const {stdout} = await execaMethod(pathViaParentDir);174+ t.is(stdout, foobarString);175+};176+177+test('execa() use relative path with \'..\' chars', testRelativePath, execa);178+test('execaSync() use relative path with \'..\' chars', testRelativePath, execaSync);179+test('execaCommand() use relative path with \'..\' chars', testRelativePath, execaCommand);180+test('execaCommandSync() use relative path with \'..\' chars', testRelativePath, execaCommandSync);181+test('execaNode() use relative path with \'..\' chars', testRelativePath, execaNode);182+test('$ use relative path with \'..\' chars', testRelativePath, $);183+test('$.sync use relative path with \'..\' chars', testRelativePath, $.sync);modified:test/arguments/options.js+27 added-100 removed
1-import {delimiter, join, basename} from 'node:path';1+import {delimiter} from 'node:path';2 import process from 'node:process';3-import {pathToFileURL, fileURLToPath} from 'node:url';3+import {pathToFileURL} from 'node:url';4 import test from 'ava';5 import which from 'which';6-import {execa, $, execaSync, execaNode} from '../../index.js';7-import {setFixtureDir, FIXTURES_DIR_URL, PATH_KEY} from '../helpers/fixtures-dir.js';6+import {execa, $} from '../../index.js';7+import {setFixtureDir, PATH_KEY} from '../helpers/fixtures-dir.js';8 import {identity} from '../helpers/stdio.js';9 10 setFixtureDir();11 process.env.FOO = 'foo';7 unmodified lines19 };20 21 const BIN_DIR_REGEXP = /node_modules[\\/]\.bin/;22 23+const pathWitoutLocalDir = getPathWithoutLocalDir();24+25 test('preferLocal: true', async t => {24- await t.notThrowsAsync(execa('ava', ['--version'], {preferLocal: true, env: getPathWithoutLocalDir()}));26+ await t.notThrowsAsync(execa('ava', ['--version'], {preferLocal: true, env: pathWitoutLocalDir}));27 });28 29 test('preferLocal: false', async t => {28- await t.throwsAsync(execa('ava', ['--version'], {preferLocal: false, env: getPathWithoutLocalDir()}), {message: ENOENT_REGEXP});30+ await t.throwsAsync(execa('ava', ['--version'], {preferLocal: false, env: pathWitoutLocalDir}), {message: ENOENT_REGEXP});31 });32 33 test('preferLocal: undefined', async t => {32- await t.throwsAsync(execa('ava', ['--version'], {env: getPathWithoutLocalDir()}), {message: ENOENT_REGEXP});34+ await t.throwsAsync(execa('ava', ['--version'], {env: pathWitoutLocalDir}), {message: ENOENT_REGEXP});35 });36 37 test('preferLocal: undefined with $', async t => {36- await t.notThrowsAsync($({env: getPathWithoutLocalDir()})`ava --version`);38+ await t.notThrowsAsync($('ava', ['--version'], {env: pathWitoutLocalDir}));39 });40 41 test('preferLocal: undefined with $.sync', t => {40- t.notThrows(() => $({env: getPathWithoutLocalDir()}).sync`ava --version`);42+ t.notThrows(() => $.sync('ava', ['--version'], {env: pathWitoutLocalDir}));43 });44 45+test('preferLocal: undefined with execa.pipe`...`', async t => {46+ await t.throwsAsync(() => execa('node', ['--version']).pipe({env: pathWitoutLocalDir})`ava --version`);47+});48+49+test('preferLocal: undefined with $.pipe`...`', async t => {50+ await t.notThrows(() => $('node', ['--version']).pipe({env: pathWitoutLocalDir})`ava --version`);51+});52+53+test('preferLocal: undefined with execa.pipe()', async t => {54+ await t.throwsAsync(() => execa('node', ['--version']).pipe('ava', ['--version'], {env: pathWitoutLocalDir}));55+});56+57+test('preferLocal: undefined with $.pipe()', async t => {58+ await t.notThrows(() => $('node', ['--version']).pipe('ava', ['--version'], {env: pathWitoutLocalDir}));59+});60+61 test('localDir option', async t => {62 const command = isWindows ? 'echo %PATH%' : 'echo $PATH';63 const {stdout} = await execa(command, {shell: true, preferLocal: true, localDir: '/test'});64 const envPaths = stdout.split(delimiter);43 unmodified lines108 };109 110 test('can use `options.shell: string`', testShellPath, identity);111 test('can use `options.shell: file URL`', testShellPath, pathToFileURL);94-95-const testFileUrl = async (t, execaMethod) => {96- const command = new URL('noop.js', FIXTURES_DIR_URL);97- const {stdout} = await execaMethod(command, ['foobar']);98- t.is(stdout, 'foobar');99-};100-101-test('execa()\'s command argument can be a file URL', testFileUrl, execa);102-test('execaSync()\'s command argument can be a file URL', testFileUrl, execaSync);103-test('execaNode()\'s command argument can be a file URL', testFileUrl, execaNode);104-105-const testInvalidFileUrl = async (t, execaMethod) => {106- const invalidUrl = new URL('https://invalid.com');107- t.throws(() => {108- execaMethod(invalidUrl);109- }, {code: 'ERR_INVALID_URL_SCHEME'});110-};111-112-test('execa()\'s command argument cannot be a non-file URL', testInvalidFileUrl, execa);113-test('execaSync()\'s command argument cannot be a non-file URL', testInvalidFileUrl, execaSync);114-test('execaNode()\'s command argument cannot be a non-file URL', testInvalidFileUrl, execaNode);115-116-const testInvalidCommand = async (t, execaMethod) => {117- t.throws(() => {118- execaMethod(['command', 'arg']);119- }, {message: /First argument must be a string or a file URL/});120-};121-122-test('execa()\'s command argument must be a string or file URL', testInvalidCommand, execa);123-test('execaSync()\'s command argument must be a string or file URL', testInvalidCommand, execaSync);124-test('execaNode()\'s command argument must be a string or file URL', testInvalidCommand, execaNode);125-126-const testInvalidArgs = async (t, execaMethod) => {127- t.throws(() => {128- execaMethod('echo', true);129- }, {message: /Second argument must be either/});130-};131-132-test('execa()\'s second argument must be an array', testInvalidArgs, execa);133-test('execaSync()\'s second argument must be an array', testInvalidArgs, execaSync);134-test('execaNode()\'s second argument must be an array', testInvalidArgs, execaNode);135-136-const testInvalidArgsItems = async (t, execaMethod) => {137- t.throws(() => {138- execaMethod('echo', [{}]);139- }, {message: 'Second argument must be an array of strings: [object Object]'});140-};141-142-test('execa()\'s second argument must not be objects', testInvalidArgsItems, execa);143-test('execaSync()\'s second argument must not be objects', testInvalidArgsItems, execaSync);144-test('execaNode()\'s second argument must not be objects', testInvalidArgsItems, execaNode);145-146-const testNullByteArg = async (t, execaMethod) => {147- t.throws(() => {148- execaMethod('echo', ['a\0b']);149- }, {message: /null bytes/});150-};151-152-test('execa()\'s second argument must not include \\0', testNullByteArg, execa);153-test('execaSync()\'s second argument must not include \\0', testNullByteArg, execaSync);154-test('execaNode()\'s second argument must not include \\0', testNullByteArg, execaNode);155-156-const testSerializeArg = async (t, arg) => {157- const {stdout} = await execa('noop.js', [arg]);158- t.is(stdout, String(arg));159-};160-161-test('execa()\'s arguments can be numbers', testSerializeArg, 1);162-test('execa()\'s arguments can be booleans', testSerializeArg, true);163-test('execa()\'s arguments can be NaN', testSerializeArg, Number.NaN);164-test('execa()\'s arguments can be Infinity', testSerializeArg, Number.POSITIVE_INFINITY);165-test('execa()\'s arguments can be null', testSerializeArg, null);166-test('execa()\'s arguments can be undefined', testSerializeArg, undefined);167-test('execa()\'s arguments can be bigints', testSerializeArg, 1n);168-test('execa()\'s arguments can be symbols', testSerializeArg, Symbol('test'));169-170-const testInvalidOptions = async (t, execaMethod) => {171- t.throws(() => {172- execaMethod('echo', [], new Map());173- }, {message: /Last argument must be an options object/});174-};175-176-test('execa()\'s third argument must be a plain object', testInvalidOptions, execa);177-test('execaSync()\'s third argument must be a plain object', testInvalidOptions, execaSync);178-test('execaNode()\'s third argument must be a plain object', testInvalidOptions, execaNode);179-180-test('use relative path with \'..\' chars', async t => {181- const pathViaParentDir = join('..', basename(fileURLToPath(new URL('../..', import.meta.url))), 'test', 'fixtures', 'noop.js');182- const {stdout} = await execa(pathViaParentDir, ['foo']);183- t.is(stdout, 'foo');184-});added:test/arguments/template.js+329 added
1+import test from 'ava';2+import {$} from '../../index.js';3+import {setFixtureDir} from '../helpers/fixtures-dir.js';4+5+setFixtureDir();6+7+// Workaround since some text editors or IDEs do not allow inputting \r directly8+const escapedCall = string => {9+ const templates = [string];10+ templates.raw = [string];11+ return $(templates);12+};13+14+const testScriptStdout = async (t, getSubprocess, expectedStdout) => {15+ const {stdout} = await getSubprocess();16+ t.is(stdout, expectedStdout);17+};18+19+test('$ allows number interpolation', testScriptStdout, () => $`echo.js 1 ${2}`, '1\n2');20+test('$ can concatenate multiple tokens', testScriptStdout, () => $`echo.js ${'foo'}bar${'foo'}`, 'foobarfoo');21+test('$ can use newlines and tab indentations', testScriptStdout, () => $`echo.js foo22+ bar`, 'foo\nbar');23+test('$ can use newlines and space indentations', testScriptStdout, () => $`echo.js foo24+ bar`, 'foo\nbar');25+test('$ can use Windows newlines and tab indentations', testScriptStdout, () => escapedCall('echo.js foo\r\n\tbar'), 'foo\nbar');26+test('$ can use Windows newlines and space indentations', testScriptStdout, () => escapedCall('echo.js foo\r\n bar'), 'foo\nbar');27+test('$ does not ignore comments in expressions', testScriptStdout, () => $`echo.js foo28+ ${/* This is a comment */''}29+ bar30+ ${/* This is another comment */''}31+ baz32+`, 'foo\n\nbar\n\nbaz');33+test('$ allows escaping spaces with interpolation', testScriptStdout, () => $`echo.js ${'foo bar'}`, 'foo bar');34+test('$ allows escaping spaces in commands with interpolation', testScriptStdout, () => $`${'command with space.js'} foo bar`, 'foo\nbar');35+test('$ trims', testScriptStdout, () => $` echo.js foo bar `, 'foo\nbar');36+test('$ allows array interpolation', testScriptStdout, () => $`echo.js ${['foo', 'bar']}`, 'foo\nbar');37+test('$ allows empty array interpolation', testScriptStdout, () => $`echo.js foo ${[]} bar`, 'foo\nbar');38+test('$ allows space escaped values in array interpolation', testScriptStdout, () => $`echo.js ${['foo', 'bar baz']}`, 'foo\nbar baz');39+test('$ can concatenate at the end of tokens followed by an array', testScriptStdout, () => $`echo.js foo${['bar', 'foo']}`, 'foobar\nfoo');40+test('$ can concatenate at the start of tokens followed by an array', testScriptStdout, () => $`echo.js ${['foo', 'bar']}foo`, 'foo\nbarfoo');41+test('$ can concatenate at the start and end of tokens followed by an array', testScriptStdout, () => $`echo.js foo${['bar', 'foo']}bar`, 'foobar\nfoobar');42+test('$ handles escaped newlines', testScriptStdout, () => $`echo.js a\43+b`, 'ab');44+test('$ handles backslashes at end of lines', testScriptStdout, () => $`echo.js a\\45+ b`, 'a\\\nb');46+test('$ handles double backslashes at end of lines', testScriptStdout, () => $`echo.js a\\\\47+ b`, 'a\\\\\nb');48+test('$ handles tokens - a', testScriptStdout, () => $`echo.js a`, 'a');49+test('$ handles expressions - a', testScriptStdout, () => $`echo.js ${'a'}`, 'a');50+test('$ handles tokens - abc', testScriptStdout, () => $`echo.js abc`, 'abc');51+test('$ handles expressions - abc', testScriptStdout, () => $`echo.js ${'abc'}`, 'abc');52+test('$ handles tokens - ""', testScriptStdout, () => $`echo.js`, '');53+test('$ handles expressions - ""', testScriptStdout, () => $`echo.js a ${''} b`, 'a\n\nb');54+test('$ splits tokens - ""', testScriptStdout, () => $`echo.js ab`, 'ab');55+test('$ splits expressions - ""', testScriptStdout, () => $`echo.js ${'a'}${'b'}`, 'ab');56+test('$ concatenates expressions - ""', testScriptStdout, () => $`echo.js a${'b'}c`, 'abc');57+test('$ handles tokens - " "', testScriptStdout, () => $`echo.js `, '');58+test('$ handles expressions - " "', testScriptStdout, () => $`echo.js ${' '}`, ' ');59+test('$ splits tokens - " "', testScriptStdout, () => $`echo.js a b`, 'a\nb');60+test('$ splits expressions - " "', testScriptStdout, () => $`echo.js ${'a'} ${'b'}`, 'a\nb');61+test('$ concatenates tokens - " "', testScriptStdout, () => $`echo.js a `, 'a');62+test('$ concatenates expressions - " "', testScriptStdout, () => $`echo.js ${'a'} `, 'a');63+test('$ handles tokens - " " (2 spaces)', testScriptStdout, () => $`echo.js `, '');64+test('$ handles expressions - " " (2 spaces)', testScriptStdout, () => $`echo.js ${' '}`, ' ');65+test('$ splits tokens - " " (2 spaces)', testScriptStdout, () => $`echo.js a b`, 'a\nb');66+test('$ splits expressions - " " (2 spaces)', testScriptStdout, () => $`echo.js ${'a'} ${'b'}`, 'a\nb');67+test('$ concatenates tokens - " " (2 spaces)', testScriptStdout, () => $`echo.js a `, 'a');68+test('$ concatenates expressions - " " (2 spaces)', testScriptStdout, () => $`echo.js ${'a'} `, 'a');69+test('$ handles tokens - " " (3 spaces)', testScriptStdout, () => $`echo.js `, '');70+test('$ handles expressions - " " (3 spaces)', testScriptStdout, () => $`echo.js ${' '}`, ' ');71+test('$ splits tokens - " " (3 spaces)', testScriptStdout, () => $`echo.js a b`, 'a\nb');72+test('$ splits expressions - " " (3 spaces)', testScriptStdout, () => $`echo.js ${'a'} ${'b'}`, 'a\nb');73+test('$ concatenates tokens - " " (3 spaces)', testScriptStdout, () => $`echo.js a `, 'a');74+test('$ concatenates expressions - " " (3 spaces)', testScriptStdout, () => $`echo.js ${'a'} `, 'a');75+test('$ handles tokens - \\t (no escape)', testScriptStdout, () => $`echo.js `, '');76+test('$ handles expressions - \\t (no escape)', testScriptStdout, () => $`echo.js ${' '}`, '\t');77+test('$ splits tokens - \\t (no escape)', testScriptStdout, () => $`echo.js a b`, 'a\nb');78+test('$ splits expressions - \\t (no escape)', testScriptStdout, () => $`echo.js ${'a'} ${'b'}`, 'a\nb');79+test('$ concatenates tokens - \\t (no escape)', testScriptStdout, () => $`echo.js a b`, 'a\nb');80+test('$ concatenates expressions - \\t (no escape)', testScriptStdout, () => $`echo.js ${'a'} b`, 'a\nb');81+test('$ handles tokens - \\t (escape)', testScriptStdout, () => $`echo.js \t`, '\t');82+test('$ handles expressions - \\t (escape)', testScriptStdout, () => $`echo.js ${'\t'}`, '\t');83+test('$ splits tokens - \\t (escape)', testScriptStdout, () => $`echo.js a\tb`, 'a\tb');84+test('$ splits expressions - \\t (escape)', testScriptStdout, () => $`echo.js ${'a'}\t${'b'}`, 'a\tb');85+test('$ concatenates tokens - \\t (escape)', testScriptStdout, () => $`echo.js \ta\t b`, '\ta\t\nb');86+test('$ concatenates expressions - \\t (escape)', testScriptStdout, () => $`echo.js \t${'a'}\t b`, '\ta\t\nb');87+test('$ handles tokens - \\n (no escape)', testScriptStdout, () => $`echo.js88+ `, '');89+test('$ handles expressions - \\n (no escape)', testScriptStdout, () => $`echo.js ${`90+`} `, '\n');91+test('$ splits tokens - \\n (no escape)', testScriptStdout, () => $`echo.js a92+ b`, 'a\nb');93+test('$ splits expressions - \\n (no escape)', testScriptStdout, () => $`echo.js ${'a'}94+ ${'b'}`, 'a\nb');95+test('$ concatenates tokens - \\n (no escape)', testScriptStdout, () => $`echo.js96+a97+ b`, 'a\nb');98+test('$ concatenates expressions - \\n (no escape)', testScriptStdout, () => $`echo.js99+${'a'}100+ b`, 'a\nb');101+test('$ handles tokens - \\n (escape)', testScriptStdout, () => $`echo.js \n `, '\n');102+test('$ handles expressions - \\n (escape)', testScriptStdout, () => $`echo.js ${'\n'} `, '\n');103+test('$ splits tokens - \\n (escape)', testScriptStdout, () => $`echo.js a\n b`, 'a\n\nb');104+test('$ splits expressions - \\n (escape)', testScriptStdout, () => $`echo.js ${'a'}\n ${'b'}`, 'a\n\nb');105+test('$ concatenates tokens - \\n (escape)', testScriptStdout, () => $`echo.js \na\n b`, '\na\n\nb');106+test('$ concatenates expressions - \\n (escape)', testScriptStdout, () => $`echo.js \n${'a'}\n b`, '\na\n\nb');107+test('$ handles tokens - \\r (no escape)', testScriptStdout, () => escapedCall('echo.js \r '), '');108+test('$ splits tokens - \\r (no escape)', testScriptStdout, () => escapedCall('echo.js a\rb'), 'a\nb');109+test('$ splits expressions - \\r (no escape)', testScriptStdout, () => escapedCall(`echo.js ${'a'}\r${'b'}`), 'a\nb');110+test('$ concatenates tokens - \\r (no escape)', testScriptStdout, () => escapedCall('echo.js \ra\r b'), 'a\nb');111+test('$ concatenates expressions - \\r (no escape)', testScriptStdout, () => escapedCall(`echo.js \r${'a'}\r b`), 'a\nb');112+test('$ splits tokens - \\r (escape)', testScriptStdout, () => $`echo.js a\r b`, 'a\r\nb');113+test('$ splits expressions - \\r (escape)', testScriptStdout, () => $`echo.js ${'a'}\r ${'b'}`, 'a\r\nb');114+test('$ concatenates tokens - \\r (escape)', testScriptStdout, () => $`echo.js \ra\r b`, '\ra\r\nb');115+test('$ concatenates expressions - \\r (escape)', testScriptStdout, () => $`echo.js \r${'a'}\r b`, '\ra\r\nb');116+test('$ handles tokens - \\r\\n (no escape)', testScriptStdout, () => escapedCall('echo.js \r\n '), '');117+test('$ splits tokens - \\r\\n (no escape)', testScriptStdout, () => escapedCall('echo.js a\r\nb'), 'a\nb');118+test('$ splits expressions - \\r\\n (no escape)', testScriptStdout, () => escapedCall(`echo.js ${'a'}\r\n${'b'}`), 'a\nb');119+test('$ concatenates tokens - \\r\\n (no escape)', testScriptStdout, () => escapedCall('echo.js \r\na\r\n b'), 'a\nb');120+test('$ concatenates expressions - \\r\\n (no escape)', testScriptStdout, () => escapedCall(`echo.js \r\n${'a'}\r\n b`), 'a\nb');121+test('$ handles tokens - \\r\\n (escape)', testScriptStdout, () => $`echo.js \r\n `, '\r\n');122+test('$ handles expressions - \\r\\n (escape)', testScriptStdout, () => $`echo.js ${'\r\n'} `, '\r\n');123+test('$ splits tokens - \\r\\n (escape)', testScriptStdout, () => $`echo.js a\r\n b`, 'a\r\n\nb');124+test('$ splits expressions - \\r\\n (escape)', testScriptStdout, () => $`echo.js ${'a'}\r\n ${'b'}`, 'a\r\n\nb');125+test('$ concatenates tokens - \\r\\n (escape)', testScriptStdout, () => $`echo.js \r\na\r\n b`, '\r\na\r\n\nb');126+test('$ concatenates expressions - \\r\\n (escape)', testScriptStdout, () => $`echo.js \r\n${'a'}\r\n b`, '\r\na\r\n\nb');127+/* eslint-disable no-irregular-whitespace */128+test('$ handles expressions - \\f (no escape)', testScriptStdout, () => $`echo.js ${''}`, '\f');129+test('$ splits tokens - \\f (no escape)', testScriptStdout, () => $`echo.js ab`, 'a\fb');130+test('$ splits expressions - \\f (no escape)', testScriptStdout, () => $`echo.js ${'a'}${'b'}`, 'a\fb');131+test('$ concatenates tokens - \\f (no escape)', testScriptStdout, () => $`echo.js a b`, '\fa\f\nb');132+test('$ concatenates expressions - \\f (no escape)', testScriptStdout, () => $`echo.js ${'a'} b`, '\fa\f\nb');133+/* eslint-enable no-irregular-whitespace */134+test('$ handles tokens - \\f (escape)', testScriptStdout, () => $`echo.js \f`, '\f');135+test('$ handles expressions - \\f (escape)', testScriptStdout, () => $`echo.js ${'\f'}`, '\f');136+test('$ splits tokens - \\f (escape)', testScriptStdout, () => $`echo.js a\fb`, 'a\fb');137+test('$ splits expressions - \\f (escape)', testScriptStdout, () => $`echo.js ${'a'}\f${'b'}`, 'a\fb');138+test('$ concatenates tokens - \\f (escape)', testScriptStdout, () => $`echo.js \fa\f b`, '\fa\f\nb');139+test('$ concatenates expressions - \\f (escape)', testScriptStdout, () => $`echo.js \f${'a'}\f b`, '\fa\f\nb');140+test('$ handles tokens - \\', testScriptStdout, () => $`echo.js \\`, '\\');141+test('$ handles expressions - \\', testScriptStdout, () => $`echo.js ${'\\'}`, '\\');142+test('$ splits tokens - \\', testScriptStdout, () => $`echo.js a\\b`, 'a\\b');143+test('$ splits expressions - \\', testScriptStdout, () => $`echo.js ${'a'}\\${'b'}`, 'a\\b');144+test('$ concatenates tokens - \\', testScriptStdout, () => $`echo.js \\a\\ b`, '\\a\\\nb');145+test('$ concatenates expressions - \\', testScriptStdout, () => $`echo.js \\${'a'}\\ b`, '\\a\\\nb');146+test('$ handles tokens - \\\\', testScriptStdout, () => $`echo.js \\\\`, '\\\\');147+test('$ handles expressions - \\\\', testScriptStdout, () => $`echo.js ${'\\\\'}`, '\\\\');148+test('$ splits tokens - \\\\', testScriptStdout, () => $`echo.js a\\\\b`, 'a\\\\b');149+test('$ splits expressions - \\\\', testScriptStdout, () => $`echo.js ${'a'}\\\\${'b'}`, 'a\\\\b');150+test('$ concatenates tokens - \\\\', testScriptStdout, () => $`echo.js \\\\a\\\\ b`, '\\\\a\\\\\nb');151+test('$ concatenates expressions - \\\\', testScriptStdout, () => $`echo.js \\\\${'a'}\\\\ b`, '\\\\a\\\\\nb');152+test('$ handles tokens - `', testScriptStdout, () => $`echo.js \``, '`');153+test('$ handles expressions - `', testScriptStdout, () => $`echo.js ${'`'}`, '`');154+test('$ splits tokens - `', testScriptStdout, () => $`echo.js a\`b`, 'a`b');155+test('$ splits expressions - `', testScriptStdout, () => $`echo.js ${'a'}\`${'b'}`, 'a`b');156+test('$ concatenates tokens - `', testScriptStdout, () => $`echo.js \`a\` b`, '`a`\nb');157+test('$ concatenates expressions - `', testScriptStdout, () => $`echo.js \`${'a'}\` b`, '`a`\nb');158+test('$ handles tokens - \\v', testScriptStdout, () => $`echo.js \v`, '\v');159+test('$ handles expressions - \\v', testScriptStdout, () => $`echo.js ${'\v'}`, '\v');160+test('$ splits tokens - \\v', testScriptStdout, () => $`echo.js a\vb`, 'a\vb');161+test('$ splits expressions - \\v', testScriptStdout, () => $`echo.js ${'a'}\v${'b'}`, 'a\vb');162+test('$ concatenates tokens - \\v', testScriptStdout, () => $`echo.js \va\v b`, '\va\v\nb');163+test('$ concatenates expressions - \\v', testScriptStdout, () => $`echo.js \v${'a'}\v b`, '\va\v\nb');164+test('$ handles tokens - \\u2028', testScriptStdout, () => $`echo.js \u2028`, '\u2028');165+test('$ handles expressions - \\u2028', testScriptStdout, () => $`echo.js ${'\u2028'}`, '\u2028');166+test('$ splits tokens - \\u2028', testScriptStdout, () => $`echo.js a\u2028b`, 'a\u2028b');167+test('$ splits expressions - \\u2028', testScriptStdout, () => $`echo.js ${'a'}\u2028${'b'}`, 'a\u2028b');168+test('$ concatenates tokens - \\u2028', testScriptStdout, () => $`echo.js \u2028a\u2028 b`, '\u2028a\u2028\nb');169+test('$ concatenates expressions - \\u2028', testScriptStdout, () => $`echo.js \u2028${'a'}\u2028 b`, '\u2028a\u2028\nb');170+test('$ handles tokens - \\a', testScriptStdout, () => $`echo.js \a`, 'a');171+test('$ splits tokens - \\a', testScriptStdout, () => $`echo.js a\ab`, 'aab');172+test('$ splits expressions - \\a', testScriptStdout, () => $`echo.js ${'a'}\a${'b'}`, 'aab');173+test('$ concatenates tokens - \\a', testScriptStdout, () => $`echo.js \aa\a b`, 'aaa\nb');174+test('$ concatenates expressions - \\a', testScriptStdout, () => $`echo.js \a${'a'}\a b`, 'aaa\nb');175+test('$ handles tokens - \\cJ', testScriptStdout, () => $`echo.js \cJ`, 'cJ');176+test('$ splits tokens - \\cJ', testScriptStdout, () => $`echo.js a\cJb`, 'acJb');177+test('$ splits expressions - \\cJ', testScriptStdout, () => $`echo.js ${'a'}\cJ${'b'}`, 'acJb');178+test('$ concatenates tokens - \\cJ', testScriptStdout, () => $`echo.js \cJa\cJ b`, 'cJacJ\nb');179+test('$ concatenates expressions - \\cJ', testScriptStdout, () => $`echo.js \cJ${'a'}\cJ b`, 'cJacJ\nb');180+test('$ handles tokens - \\.', testScriptStdout, () => $`echo.js \.`, '.');181+test('$ splits tokens - \\.', testScriptStdout, () => $`echo.js a\.b`, 'a.b');182+test('$ splits expressions - \\.', testScriptStdout, () => $`echo.js ${'a'}\.${'b'}`, 'a.b');183+test('$ concatenates tokens - \\.', testScriptStdout, () => $`echo.js \.a\. b`, '.a.\nb');184+test('$ concatenates expressions - \\.', testScriptStdout, () => $`echo.js \.${'a'}\. b`, '.a.\nb');185+/* eslint-disable unicorn/no-hex-escape */186+test('$ handles tokens - \\x63', testScriptStdout, () => $`echo.js \x63`, 'c');187+test('$ splits tokens - \\x63', testScriptStdout, () => $`echo.js a\x63b`, 'acb');188+test('$ splits expressions - \\x63', testScriptStdout, () => $`echo.js ${'a'}\x63${'b'}`, 'acb');189+test('$ concatenates tokens - \\x63', testScriptStdout, () => $`echo.js \x63a\x63 b`, 'cac\nb');190+test('$ concatenates expressions - \\x63', testScriptStdout, () => $`echo.js \x63${'a'}\x63 b`, 'cac\nb');191+/* eslint-enable unicorn/no-hex-escape */192+test('$ handles tokens - \\u0063', testScriptStdout, () => $`echo.js \u0063`, 'c');193+test('$ splits tokens - \\u0063', testScriptStdout, () => $`echo.js a\u0063b`, 'acb');194+test('$ splits expressions - \\u0063', testScriptStdout, () => $`echo.js ${'a'}\u0063${'b'}`, 'acb');195+test('$ concatenates tokens - \\u0063', testScriptStdout, () => $`echo.js \u0063a\u0063 b`, 'cac\nb');196+test('$ concatenates expressions - \\u0063', testScriptStdout, () => $`echo.js \u0063${'a'}\u0063 b`, 'cac\nb');197+test('$ handles tokens - \\u{1}', testScriptStdout, () => $`echo.js \u{1}`, '\u0001');198+test('$ splits tokens - \\u{1}', testScriptStdout, () => $`echo.js a\u{1}b`, 'a\u0001b');199+test('$ splits expressions - \\u{1}', testScriptStdout, () => $`echo.js ${'a'}\u{1}${'b'}`, 'a\u0001b');200+test('$ concatenates tokens - \\u{1}', testScriptStdout, () => $`echo.js \u{1}a\u{1} b`, '\u0001a\u0001\nb');201+test('$ concatenates expressions - \\u{1}', testScriptStdout, () => $`echo.js \u{1}${'a'}\u{1} b`, '\u0001a\u0001\nb');202+test('$ handles tokens - \\u{63}', testScriptStdout, () => $`echo.js \u{63}`, 'c');203+test('$ splits tokens - \\u{63}', testScriptStdout, () => $`echo.js a\u{63}b`, 'acb');204+test('$ splits expressions - \\u{63}', testScriptStdout, () => $`echo.js ${'a'}\u{63}${'b'}`, 'acb');205+test('$ concatenates tokens - \\u{63}', testScriptStdout, () => $`echo.js \u{63}a\u{63} b`, 'cac\nb');206+test('$ concatenates expressions - \\u{63}', testScriptStdout, () => $`echo.js \u{63}${'a'}\u{63} b`, 'cac\nb');207+test('$ handles tokens - \\u{063}', testScriptStdout, () => $`echo.js \u{063}`, 'c');208+test('$ splits tokens - \\u{063}', testScriptStdout, () => $`echo.js a\u{063}b`, 'acb');209+test('$ splits expressions - \\u{063}', testScriptStdout, () => $`echo.js ${'a'}\u{063}${'b'}`, 'acb');210+test('$ concatenates tokens - \\u{063}', testScriptStdout, () => $`echo.js \u{063}a\u{063} b`, 'cac\nb');211+test('$ concatenates expressions - \\u{063}', testScriptStdout, () => $`echo.js \u{063}${'a'}\u{063} b`, 'cac\nb');212+test('$ handles tokens - \\u{0063}', testScriptStdout, () => $`echo.js \u{0063}`, 'c');213+test('$ splits tokens - \\u{0063}', testScriptStdout, () => $`echo.js a\u{0063}b`, 'acb');214+test('$ splits expressions - \\u{0063}', testScriptStdout, () => $`echo.js ${'a'}\u{0063}${'b'}`, 'acb');215+test('$ concatenates tokens - \\u{0063}', testScriptStdout, () => $`echo.js \u{0063}a\u{0063} b`, 'cac\nb');216+test('$ concatenates expressions - \\u{0063}', testScriptStdout, () => $`echo.js \u{0063}${'a'}\u{0063} b`, 'cac\nb');217+test('$ handles tokens - \\u{00063}', testScriptStdout, () => $`echo.js \u{00063}`, 'c');218+test('$ splits tokens - \\u{00063}', testScriptStdout, () => $`echo.js a\u{00063}b`, 'acb');219+test('$ splits expressions - \\u{00063}', testScriptStdout, () => $`echo.js ${'a'}\u{00063}${'b'}`, 'acb');220+test('$ concatenates tokens - \\u{00063}', testScriptStdout, () => $`echo.js \u{00063}a\u{00063} b`, 'cac\nb');221+test('$ concatenates expressions - \\u{00063}', testScriptStdout, () => $`echo.js \u{00063}${'a'}\u{00063} b`, 'cac\nb');222+test('$ handles tokens - \\u{000063}', testScriptStdout, () => $`echo.js \u{000063}`, 'c');223+test('$ splits tokens - \\u{000063}', testScriptStdout, () => $`echo.js a\u{000063}b`, 'acb');224+test('$ splits expressions - \\u{000063}', testScriptStdout, () => $`echo.js ${'a'}\u{000063}${'b'}`, 'acb');225+test('$ concatenates tokens - \\u{000063}', testScriptStdout, () => $`echo.js \u{000063}a\u{000063} b`, 'cac\nb');226+test('$ concatenates expressions - \\u{000063}', testScriptStdout, () => $`echo.js \u{000063}${'a'}\u{000063} b`, 'cac\nb');227+test('$ handles tokens - \\u{0000063}', testScriptStdout, () => $`echo.js \u{0000063}`, 'c');228+test('$ splits tokens - \\u{0000063}', testScriptStdout, () => $`echo.js a\u{0000063}b`, 'acb');229+test('$ splits expressions - \\u{0000063}', testScriptStdout, () => $`echo.js ${'a'}\u{0000063}${'b'}`, 'acb');230+test('$ concatenates tokens - \\u{0000063}', testScriptStdout, () => $`echo.js \u{0000063}a\u{0000063} b`, 'cac\nb');231+test('$ concatenates expressions - \\u{0000063}', testScriptStdout, () => $`echo.js \u{0000063}${'a'}\u{0000063} b`, 'cac\nb');232+test('$ handles tokens - \\u{0063}}', testScriptStdout, () => $`echo.js \u{0063}}`, 'c}');233+test('$ splits tokens - \\u{0063}}', testScriptStdout, () => $`echo.js a\u{0063}}b`, 'ac}b');234+test('$ splits expressions - \\u{0063}}', testScriptStdout, () => $`echo.js ${'a'}\u{0063}}${'b'}`, 'ac}b');235+test('$ concatenates tokens - \\u{0063}}', testScriptStdout, () => $`echo.js \u{0063}}a\u{0063}} b`, 'c}ac}\nb');236+test('$ concatenates expressions - \\u{0063}}', testScriptStdout, () => $`echo.js \u{0063}}${'a'}\u{0063}} b`, 'c}ac}\nb');237+238+const testScriptErrorStdout = async (t, getSubprocess) => {239+ t.throws(getSubprocess, {message: /null bytes/});240+};241+242+test('$ handles tokens - \\0', testScriptErrorStdout, () => $`echo.js \0`);243+test('$ splits tokens - \\0', testScriptErrorStdout, () => $`echo.js a\0b`);244+test('$ splits expressions - \\0', testScriptErrorStdout, () => $`echo.js ${'a'}\0${'b'}`);245+test('$ concatenates tokens - \\0', testScriptErrorStdout, () => $`echo.js \0a\0 b`);246+test('$ concatenates expressions - \\0', testScriptErrorStdout, () => $`echo.js \0${'a'}\0 b`);247+248+const testReturnInterpolate = async (t, getSubprocess, expectedStdout, options = {}) => {249+ const foo = await $(options)`echo.js foo`;250+ const {stdout} = await getSubprocess(foo);251+ t.is(stdout, expectedStdout);252+};253+254+test('$ allows execa return value interpolation', testReturnInterpolate, foo => $`echo.js ${foo} bar`, 'foo\nbar');255+test('$ allows execa return value buffer interpolation', testReturnInterpolate, foo => $`echo.js ${foo} bar`, 'foo\nbar', {encoding: 'buffer'});256+test('$ allows execa return value array interpolation', testReturnInterpolate, foo => $`echo.js ${[foo, 'bar']}`, 'foo\nbar');257+test('$ allows execa return value buffer array interpolation', testReturnInterpolate, foo => $`echo.js ${[foo, 'bar']}`, 'foo\nbar', {encoding: 'buffer'});258+259+const testReturnInterpolateSync = (t, getSubprocess, expectedStdout, options = {}) => {260+ const foo = $(options).sync`echo.js foo`;261+ const {stdout} = getSubprocess(foo);262+ t.is(stdout, expectedStdout);263+};264+265+test('$.sync allows execa return value interpolation', testReturnInterpolateSync, foo => $.sync`echo.js ${foo} bar`, 'foo\nbar');266+test('$.sync allows execa return value buffer interpolation', testReturnInterpolateSync, foo => $.sync`echo.js ${foo} bar`, 'foo\nbar', {encoding: 'buffer'});267+test('$.sync allows execa return value array interpolation', testReturnInterpolateSync, foo => $.sync`echo.js ${[foo, 'bar']}`, 'foo\nbar');268+test('$.sync allows execa return value buffer array interpolation', testReturnInterpolateSync, foo => $.sync`echo.js ${[foo, 'bar']}`, 'foo\nbar', {encoding: 'buffer'});269+270+const testInvalidSequence = (t, getSubprocess) => {271+ t.throws(getSubprocess, {message: /Invalid backslash sequence/});272+};273+274+test('$ handles invalid escape sequence - \\1', testInvalidSequence, () => $`echo.js \1`);275+test('$ handles invalid escape sequence - \\u', testInvalidSequence, () => $`echo.js \u`);276+test('$ handles invalid escape sequence - \\u0', testInvalidSequence, () => $`echo.js \u0`);277+test('$ handles invalid escape sequence - \\u00', testInvalidSequence, () => $`echo.js \u00`);278+test('$ handles invalid escape sequence - \\u000', testInvalidSequence, () => $`echo.js \u000`);279+test('$ handles invalid escape sequence - \\ug', testInvalidSequence, () => $`echo.js \ug`);280+test('$ handles invalid escape sequence - \\u{', testInvalidSequence, () => $`echo.js \u{`);281+test('$ handles invalid escape sequence - \\u{0000', testInvalidSequence, () => $`echo.js \u{0000`);282+test('$ handles invalid escape sequence - \\u{g}', testInvalidSequence, () => $`echo.js \u{g}`);283+/* eslint-disable unicorn/no-hex-escape */284+test('$ handles invalid escape sequence - \\x', testInvalidSequence, () => $`echo.js \x`);285+test('$ handles invalid escape sequence - \\x0', testInvalidSequence, () => $`echo.js \x0`);286+test('$ handles invalid escape sequence - \\xgg', testInvalidSequence, () => $`echo.js \xgg`);287+/* eslint-enable unicorn/no-hex-escape */288+289+const testEmptyScript = (t, getSubprocess) => {290+ t.throws(getSubprocess, {message: /Template script must not be empty/});291+};292+293+test('$``', testEmptyScript, () => $``);294+test('$` `', testEmptyScript, () => $` `);295+test('$` ` (2 spaces)', testEmptyScript, () => $` `);296+test('$`\\t`', testEmptyScript, () => $` `);297+test('$`\\n`', testEmptyScript, () => $`298+`);299+300+const testInvalidExpression = (t, invalidExpression, execaMethod) => {301+ const expression = typeof invalidExpression === 'function' ? invalidExpression() : invalidExpression;302+ t.throws(303+ () => execaMethod`echo.js ${expression}`,304+ {message: /in template expression/},305+ );306+};307+308+test('$ throws on invalid expression - undefined', testInvalidExpression, undefined, $);309+test('$ throws on invalid expression - null', testInvalidExpression, null, $);310+test('$ throws on invalid expression - true', testInvalidExpression, true, $);311+test('$ throws on invalid expression - {}', testInvalidExpression, {}, $);312+test('$ throws on invalid expression - {foo: "bar"}', testInvalidExpression, {foo: 'bar'}, $);313+test('$ throws on invalid expression - {stdout: undefined}', testInvalidExpression, {stdout: undefined}, $);314+test('$ throws on invalid expression - {stdout: 1}', testInvalidExpression, {stdout: 1}, $);315+test('$ throws on invalid expression - Promise.resolve()', testInvalidExpression, Promise.resolve(), $);316+test('$ throws on invalid expression - Promise.resolve({stdout: "foo"})', testInvalidExpression, Promise.resolve({foo: 'bar'}), $);317+test('$ throws on invalid expression - $', testInvalidExpression, () => $`noop.js`, $);318+test('$ throws on invalid expression - $(options).sync', testInvalidExpression, () => $({stdio: 'ignore'}).sync`noop.js`, $);319+test('$ throws on invalid expression - [undefined]', testInvalidExpression, [undefined], $);320+test('$ throws on invalid expression - [null]', testInvalidExpression, [null], $);321+test('$ throws on invalid expression - [true]', testInvalidExpression, [true], $);322+test('$ throws on invalid expression - [{}]', testInvalidExpression, [{}], $);323+test('$ throws on invalid expression - [{foo: "bar"}]', testInvalidExpression, [{foo: 'bar'}], $);324+test('$ throws on invalid expression - [{stdout: undefined}]', testInvalidExpression, [{stdout: undefined}], $);325+test('$ throws on invalid expression - [{stdout: 1}]', testInvalidExpression, [{stdout: 1}], $);326+test('$ throws on invalid expression - [Promise.resolve()]', testInvalidExpression, [Promise.resolve()], $);327+test('$ throws on invalid expression - [Promise.resolve({stdout: "foo"})]', testInvalidExpression, [Promise.resolve({stdout: 'foo'})], $);328+test('$ throws on invalid expression - [$]', testInvalidExpression, () => [$`noop.js`], $);329+test('$ throws on invalid expression - [$(options).sync]', testInvalidExpression, () => [$({stdio: 'ignore'}).sync`noop.js`], $);modified:test/fixtures/noop.js+2 added-1 removed
1 #!/usr/bin/env node2 import process from 'node:process';3+import {foobarString} from '../helpers/input.js';4 4-const bytes = process.argv[2];5+const bytes = process.argv[2] || foobarString;6 console.log(bytes);modified:test/helpers/input.js+1 added
3 unmodified lines4 5 export const bufferToUint8Array = buffer => new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength);6 7 export const foobarString = 'foobar';8+export const foobarArray = ['foo', 'bar'];9 export const foobarUint8Array = textEncoder.encode('foobar');10 export const foobarArrayBuffer = foobarUint8Array.buffer;11 export const foobarUint16Array = new Uint16Array(foobarArrayBuffer);12 export const foobarBuffer = Buffer.from(foobarString);5 unmodified linesmodified:test/command.js+69 added-19 removed
1+import {join} from 'node:path';2 import test from 'ava';3 import {execaCommand, execaCommandSync} from '../index.js';3-import {setFixtureDir} from './helpers/fixtures-dir.js';4+import {setFixtureDir, FIXTURES_DIR} from './helpers/fixtures-dir.js';5+import {QUOTE} from './helpers/verbose.js';6 7 setFixtureDir();8+const STDIN_FIXTURE = join(FIXTURES_DIR, 'stdin.js');9 10 test('execaCommand()', async t => {11 const {stdout} = await execaCommand('echo.js foo bar');12 t.is(stdout, 'foo\nbar');13 });14 15+test('execaCommandSync()', t => {16+ const {stdout} = execaCommandSync('echo.js foo bar');17+ t.is(stdout, 'foo\nbar');18+});19+20+test('execaCommand`...`', async t => {21+ const {stdout} = await execaCommand`${'echo.js foo bar'}`;22+ t.is(stdout, 'foo\nbar');23+});24+25+test('execaCommandSync`...`', t => {26+ const {stdout} = execaCommandSync`${'echo.js foo bar'}`;27+ t.is(stdout, 'foo\nbar');28+});29+30+test('execaCommand(options)`...`', async t => {31+ const {stdout} = await execaCommand({stripFinalNewline: false})`${'echo.js foo bar'}`;32+ t.is(stdout, 'foo\nbar\n');33+});34+35+test('execaCommandSync(options)`...`', t => {36+ const {stdout} = execaCommandSync({stripFinalNewline: false})`${'echo.js foo bar'}`;37+ t.is(stdout, 'foo\nbar\n');38+});39+40+test('execaCommand(options)()', async t => {41+ const {stdout} = await execaCommand({stripFinalNewline: false})('echo.js foo bar');42+ t.is(stdout, 'foo\nbar\n');43+});44+45+test('execaCommandSync(options)()', t => {46+ const {stdout} = execaCommandSync({stripFinalNewline: false})('echo.js foo bar');47+ t.is(stdout, 'foo\nbar\n');48+});49+50+test('execaCommand().pipe(execaCommand())', async t => {51+ const {stdout} = await execaCommand('echo.js foo bar').pipe(execaCommand(`node ${STDIN_FIXTURE}`));52+ t.is(stdout, 'foo\nbar');53+});54+55+test('execaCommand().pipe(...) does not use execaCommand', async t => {56+ const {escapedCommand} = await execaCommand('echo.js foo bar').pipe(`node ${STDIN_FIXTURE}`, {reject: false});57+ t.true(escapedCommand.startsWith(`${QUOTE}node `));58+});59+60+test('execaCommand() bound options have lower priority', async t => {61+ const {stdout} = await execaCommand({stripFinalNewline: false})('echo.js foo bar', {stripFinalNewline: true});62+ t.is(stdout, 'foo\nbar');63+});64+65+test('execaCommandSync() bound options have lower priority', t => {66+ const {stdout} = execaCommandSync({stripFinalNewline: false})('echo.js foo bar', {stripFinalNewline: true});67+ t.is(stdout, 'foo\nbar');68+});69+70 test('execaCommand() ignores consecutive spaces', async t => {71 const {stdout} = await execaCommand('echo.js foo bar');72 t.is(stdout, 'foo\nbar');73 });17 unmodified lines91 const {stdout} = await execaCommand(' echo.js foo bar ');92 t.is(stdout, 'foo\nbar');93 });94 37-test('execaCommandSync()', t => {38- const {stdout} = execaCommandSync('echo.js foo bar');39- t.is(stdout, 'foo\nbar');40-});41-42-const testInvalidCommand = (t, execaCommand, invalidArgument) => {95+const testInvalidArgsArray = (t, execaMethod) => {96 t.throws(() => {44- execaCommand(invalidArgument);45- }, {message: /First argument must be a string/});97+ execaMethod('echo', ['foo']);98+ }, {message: /The command and its arguments must be passed as a single string/});99 };100 48-test('execaCommand() must use a string', testInvalidCommand, execaCommand, true);49-test('execaCommandSync() must use a string', testInvalidCommand, execaCommandSync, true);50-test('execaCommand() must have an argument', testInvalidCommand, execaCommand, undefined);51-test('execaCommandSync() must have an argument', testInvalidCommand, execaCommandSync, undefined);101+test('execaCommand() must not pass an array of arguments', testInvalidArgsArray, execaCommand);102+test('execaCommandSync() must not pass an array of arguments', testInvalidArgsArray, execaCommandSync);103 53-const testInvalidArgs = (t, secondArgument, execaCommand) => {104+const testInvalidArgsTemplate = (t, execaMethod) => {105 t.throws(() => {55- execaCommand('echo', secondArgument);106+ // eslint-disable-next-line no-unused-expressions107+ execaMethod`echo foo`;108 }, {message: /The command and its arguments must be passed as a single string/});109 };110 59-test('execaCommand() must not pass an array of arguments', testInvalidArgs, [''], execaCommand);60-test('execaCommandSync() must not pass an array of arguments', testInvalidArgs, [''], execaCommandSync);61-test('execaCommand() must not pass non-options as second argument', testInvalidArgs, '', execaCommand);62-test('execaCommandSync() must not pass non-options as second argument', testInvalidArgs, '', execaCommandSync);111+test('execaCommand() must not pass an array of arguments with a template string', testInvalidArgsTemplate, execaCommand);112+test('execaCommandSync() must not pass an array of arguments with a template string', testInvalidArgsTemplate, execaCommandSync);modified:test/script.js+30 added-338 removed
1 import test from 'ava';2 import {isStream} from 'is-stream';3 import {$} from '../index.js';4 import {setFixtureDir} from './helpers/fixtures-dir.js';5+import {foobarString} from './helpers/input.js';6 7 setFixtureDir();8 8-// Workaround since some text editors or IDEs do not allow inputting \r directly9-const escapedCall = string => {10- const templates = [string];11- templates.raw = [string];12- return $(templates);13-};14-15-const testScriptStdout = async (t, getSubprocess, expectedStdout) => {16- const {stdout} = await getSubprocess();17- t.is(stdout, expectedStdout);18-};19-20-test('$ executes command', testScriptStdout, () => $`echo.js foo bar`, 'foo\nbar');21-test('$ accepts options', testScriptStdout, () => $({stripFinalNewline: true})`noop.js foo`, 'foo');22-test('$ allows number interpolation', testScriptStdout, () => $`echo.js 1 ${2}`, '1\n2');23-test('$ can concatenate multiple tokens', testScriptStdout, () => $`echo.js ${'foo'}bar${'foo'}`, 'foobarfoo');24-test('$ can use newlines and tab indentations', testScriptStdout, () => $`echo.js foo25- bar`, 'foo\nbar');26-test('$ can use newlines and space indentations', testScriptStdout, () => $`echo.js foo27- bar`, 'foo\nbar');28-test('$ can use Windows newlines and tab indentations', testScriptStdout, () => escapedCall('echo.js foo\r\n\tbar'), 'foo\nbar');29-test('$ can use Windows newlines and space indentations', testScriptStdout, () => escapedCall('echo.js foo\r\n bar'), 'foo\nbar');30-test('$ does not ignore comments in expressions', testScriptStdout, () => $`echo.js foo31- ${/* This is a comment */''}32- bar33- ${/* This is another comment */''}34- baz35-`, 'foo\n\nbar\n\nbaz');36-test('$ allows escaping spaces with interpolation', testScriptStdout, () => $`echo.js ${'foo bar'}`, 'foo bar');37-test('$ allows escaping spaces in commands with interpolation', testScriptStdout, () => $`${'command with space.js'} foo bar`, 'foo\nbar');38-test('$ trims', testScriptStdout, () => $` echo.js foo bar `, 'foo\nbar');39-test('$ allows array interpolation', testScriptStdout, () => $`echo.js ${['foo', 'bar']}`, 'foo\nbar');40-test('$ allows empty array interpolation', testScriptStdout, () => $`echo.js foo ${[]} bar`, 'foo\nbar');41-test('$ allows space escaped values in array interpolation', testScriptStdout, () => $`echo.js ${['foo', 'bar baz']}`, 'foo\nbar baz');42-test('$ can concatenate at the end of tokens followed by an array', testScriptStdout, () => $`echo.js foo${['bar', 'foo']}`, 'foobar\nfoo');43-test('$ can concatenate at the start of tokens followed by an array', testScriptStdout, () => $`echo.js ${['foo', 'bar']}foo`, 'foo\nbarfoo');44-test('$ can concatenate at the start and end of tokens followed by an array', testScriptStdout, () => $`echo.js foo${['bar', 'foo']}bar`, 'foobar\nfoobar');45-test('$ handles escaped newlines', testScriptStdout, () => $`echo.js a\46-b`, 'ab');47-test('$ handles backslashes at end of lines', testScriptStdout, () => $`echo.js a\\48- b`, 'a\\\nb');49-test('$ handles double backslashes at end of lines', testScriptStdout, () => $`echo.js a\\\\50- b`, 'a\\\\\nb');51-test('$ handles tokens - a', testScriptStdout, () => $`echo.js a`, 'a');52-test('$ handles expressions - a', testScriptStdout, () => $`echo.js ${'a'}`, 'a');53-test('$ handles tokens - abc', testScriptStdout, () => $`echo.js abc`, 'abc');54-test('$ handles expressions - abc', testScriptStdout, () => $`echo.js ${'abc'}`, 'abc');55-test('$ handles tokens - ""', testScriptStdout, () => $`echo.js`, '');56-test('$ handles expressions - ""', testScriptStdout, () => $`echo.js a ${''} b`, 'a\n\nb');57-test('$ splits tokens - ""', testScriptStdout, () => $`echo.js ab`, 'ab');58-test('$ splits expressions - ""', testScriptStdout, () => $`echo.js ${'a'}${'b'}`, 'ab');59-test('$ concatenates expressions - ""', testScriptStdout, () => $`echo.js a${'b'}c`, 'abc');60-test('$ handles tokens - " "', testScriptStdout, () => $`echo.js `, '');61-test('$ handles expressions - " "', testScriptStdout, () => $`echo.js ${' '}`, ' ');62-test('$ splits tokens - " "', testScriptStdout, () => $`echo.js a b`, 'a\nb');63-test('$ splits expressions - " "', testScriptStdout, () => $`echo.js ${'a'} ${'b'}`, 'a\nb');64-test('$ concatenates tokens - " "', testScriptStdout, () => $`echo.js a `, 'a');65-test('$ concatenates expressions - " "', testScriptStdout, () => $`echo.js ${'a'} `, 'a');66-test('$ handles tokens - " " (2 spaces)', testScriptStdout, () => $`echo.js `, '');67-test('$ handles expressions - " " (2 spaces)', testScriptStdout, () => $`echo.js ${' '}`, ' ');68-test('$ splits tokens - " " (2 spaces)', testScriptStdout, () => $`echo.js a b`, 'a\nb');69-test('$ splits expressions - " " (2 spaces)', testScriptStdout, () => $`echo.js ${'a'} ${'b'}`, 'a\nb');70-test('$ concatenates tokens - " " (2 spaces)', testScriptStdout, () => $`echo.js a `, 'a');71-test('$ concatenates expressions - " " (2 spaces)', testScriptStdout, () => $`echo.js ${'a'} `, 'a');72-test('$ handles tokens - " " (3 spaces)', testScriptStdout, () => $`echo.js `, '');73-test('$ handles expressions - " " (3 spaces)', testScriptStdout, () => $`echo.js ${' '}`, ' ');74-test('$ splits tokens - " " (3 spaces)', testScriptStdout, () => $`echo.js a b`, 'a\nb');75-test('$ splits expressions - " " (3 spaces)', testScriptStdout, () => $`echo.js ${'a'} ${'b'}`, 'a\nb');76-test('$ concatenates tokens - " " (3 spaces)', testScriptStdout, () => $`echo.js a `, 'a');77-test('$ concatenates expressions - " " (3 spaces)', testScriptStdout, () => $`echo.js ${'a'} `, 'a');78-test('$ handles tokens - \\t (no escape)', testScriptStdout, () => $`echo.js `, '');79-test('$ handles expressions - \\t (no escape)', testScriptStdout, () => $`echo.js ${' '}`, '\t');80-test('$ splits tokens - \\t (no escape)', testScriptStdout, () => $`echo.js a b`, 'a\nb');81-test('$ splits expressions - \\t (no escape)', testScriptStdout, () => $`echo.js ${'a'} ${'b'}`, 'a\nb');82-test('$ concatenates tokens - \\t (no escape)', testScriptStdout, () => $`echo.js a b`, 'a\nb');83-test('$ concatenates expressions - \\t (no escape)', testScriptStdout, () => $`echo.js ${'a'} b`, 'a\nb');84-test('$ handles tokens - \\t (escape)', testScriptStdout, () => $`echo.js \t`, '\t');85-test('$ handles expressions - \\t (escape)', testScriptStdout, () => $`echo.js ${'\t'}`, '\t');86-test('$ splits tokens - \\t (escape)', testScriptStdout, () => $`echo.js a\tb`, 'a\tb');87-test('$ splits expressions - \\t (escape)', testScriptStdout, () => $`echo.js ${'a'}\t${'b'}`, 'a\tb');88-test('$ concatenates tokens - \\t (escape)', testScriptStdout, () => $`echo.js \ta\t b`, '\ta\t\nb');89-test('$ concatenates expressions - \\t (escape)', testScriptStdout, () => $`echo.js \t${'a'}\t b`, '\ta\t\nb');90-test('$ handles tokens - \\n (no escape)', testScriptStdout, () => $`echo.js91- `, '');92-test('$ handles expressions - \\n (no escape)', testScriptStdout, () => $`echo.js ${`93-`} `, '\n');94-test('$ splits tokens - \\n (no escape)', testScriptStdout, () => $`echo.js a95- b`, 'a\nb');96-test('$ splits expressions - \\n (no escape)', testScriptStdout, () => $`echo.js ${'a'}97- ${'b'}`, 'a\nb');98-test('$ concatenates tokens - \\n (no escape)', testScriptStdout, () => $`echo.js99-a100- b`, 'a\nb');101-test('$ concatenates expressions - \\n (no escape)', testScriptStdout, () => $`echo.js102-${'a'}103- b`, 'a\nb');104-test('$ handles tokens - \\n (escape)', testScriptStdout, () => $`echo.js \n `, '\n');105-test('$ handles expressions - \\n (escape)', testScriptStdout, () => $`echo.js ${'\n'} `, '\n');106-test('$ splits tokens - \\n (escape)', testScriptStdout, () => $`echo.js a\n b`, 'a\n\nb');107-test('$ splits expressions - \\n (escape)', testScriptStdout, () => $`echo.js ${'a'}\n ${'b'}`, 'a\n\nb');108-test('$ concatenates tokens - \\n (escape)', testScriptStdout, () => $`echo.js \na\n b`, '\na\n\nb');109-test('$ concatenates expressions - \\n (escape)', testScriptStdout, () => $`echo.js \n${'a'}\n b`, '\na\n\nb');110-test('$ handles tokens - \\r (no escape)', testScriptStdout, () => escapedCall('echo.js \r '), '');111-test('$ splits tokens - \\r (no escape)', testScriptStdout, () => escapedCall('echo.js a\rb'), 'a\nb');112-test('$ splits expressions - \\r (no escape)', testScriptStdout, () => escapedCall(`echo.js ${'a'}\r${'b'}`), 'a\nb');113-test('$ concatenates tokens - \\r (no escape)', testScriptStdout, () => escapedCall('echo.js \ra\r b'), 'a\nb');114-test('$ concatenates expressions - \\r (no escape)', testScriptStdout, () => escapedCall(`echo.js \r${'a'}\r b`), 'a\nb');115-test('$ splits tokens - \\r (escape)', testScriptStdout, () => $`echo.js a\r b`, 'a\r\nb');116-test('$ splits expressions - \\r (escape)', testScriptStdout, () => $`echo.js ${'a'}\r ${'b'}`, 'a\r\nb');117-test('$ concatenates tokens - \\r (escape)', testScriptStdout, () => $`echo.js \ra\r b`, '\ra\r\nb');118-test('$ concatenates expressions - \\r (escape)', testScriptStdout, () => $`echo.js \r${'a'}\r b`, '\ra\r\nb');119-test('$ handles tokens - \\r\\n (no escape)', testScriptStdout, () => escapedCall('echo.js \r\n '), '');120-test('$ splits tokens - \\r\\n (no escape)', testScriptStdout, () => escapedCall('echo.js a\r\nb'), 'a\nb');121-test('$ splits expressions - \\r\\n (no escape)', testScriptStdout, () => escapedCall(`echo.js ${'a'}\r\n${'b'}`), 'a\nb');122-test('$ concatenates tokens - \\r\\n (no escape)', testScriptStdout, () => escapedCall('echo.js \r\na\r\n b'), 'a\nb');123-test('$ concatenates expressions - \\r\\n (no escape)', testScriptStdout, () => escapedCall(`echo.js \r\n${'a'}\r\n b`), 'a\nb');124-test('$ handles tokens - \\r\\n (escape)', testScriptStdout, () => $`echo.js \r\n `, '\r\n');125-test('$ handles expressions - \\r\\n (escape)', testScriptStdout, () => $`echo.js ${'\r\n'} `, '\r\n');126-test('$ splits tokens - \\r\\n (escape)', testScriptStdout, () => $`echo.js a\r\n b`, 'a\r\n\nb');127-test('$ splits expressions - \\r\\n (escape)', testScriptStdout, () => $`echo.js ${'a'}\r\n ${'b'}`, 'a\r\n\nb');128-test('$ concatenates tokens - \\r\\n (escape)', testScriptStdout, () => $`echo.js \r\na\r\n b`, '\r\na\r\n\nb');129-test('$ concatenates expressions - \\r\\n (escape)', testScriptStdout, () => $`echo.js \r\n${'a'}\r\n b`, '\r\na\r\n\nb');130-/* eslint-disable no-irregular-whitespace */131-test('$ handles expressions - \\f (no escape)', testScriptStdout, () => $`echo.js ${''}`, '\f');132-test('$ splits tokens - \\f (no escape)', testScriptStdout, () => $`echo.js ab`, 'a\fb');133-test('$ splits expressions - \\f (no escape)', testScriptStdout, () => $`echo.js ${'a'}${'b'}`, 'a\fb');134-test('$ concatenates tokens - \\f (no escape)', testScriptStdout, () => $`echo.js a b`, '\fa\f\nb');135-test('$ concatenates expressions - \\f (no escape)', testScriptStdout, () => $`echo.js ${'a'} b`, '\fa\f\nb');136-/* eslint-enable no-irregular-whitespace */137-test('$ handles tokens - \\f (escape)', testScriptStdout, () => $`echo.js \f`, '\f');138-test('$ handles expressions - \\f (escape)', testScriptStdout, () => $`echo.js ${'\f'}`, '\f');139-test('$ splits tokens - \\f (escape)', testScriptStdout, () => $`echo.js a\fb`, 'a\fb');140-test('$ splits expressions - \\f (escape)', testScriptStdout, () => $`echo.js ${'a'}\f${'b'}`, 'a\fb');141-test('$ concatenates tokens - \\f (escape)', testScriptStdout, () => $`echo.js \fa\f b`, '\fa\f\nb');142-test('$ concatenates expressions - \\f (escape)', testScriptStdout, () => $`echo.js \f${'a'}\f b`, '\fa\f\nb');143-test('$ handles tokens - \\', testScriptStdout, () => $`echo.js \\`, '\\');144-test('$ handles expressions - \\', testScriptStdout, () => $`echo.js ${'\\'}`, '\\');145-test('$ splits tokens - \\', testScriptStdout, () => $`echo.js a\\b`, 'a\\b');146-test('$ splits expressions - \\', testScriptStdout, () => $`echo.js ${'a'}\\${'b'}`, 'a\\b');147-test('$ concatenates tokens - \\', testScriptStdout, () => $`echo.js \\a\\ b`, '\\a\\\nb');148-test('$ concatenates expressions - \\', testScriptStdout, () => $`echo.js \\${'a'}\\ b`, '\\a\\\nb');149-test('$ handles tokens - \\\\', testScriptStdout, () => $`echo.js \\\\`, '\\\\');150-test('$ handles expressions - \\\\', testScriptStdout, () => $`echo.js ${'\\\\'}`, '\\\\');151-test('$ splits tokens - \\\\', testScriptStdout, () => $`echo.js a\\\\b`, 'a\\\\b');152-test('$ splits expressions - \\\\', testScriptStdout, () => $`echo.js ${'a'}\\\\${'b'}`, 'a\\\\b');153-test('$ concatenates tokens - \\\\', testScriptStdout, () => $`echo.js \\\\a\\\\ b`, '\\\\a\\\\\nb');154-test('$ concatenates expressions - \\\\', testScriptStdout, () => $`echo.js \\\\${'a'}\\\\ b`, '\\\\a\\\\\nb');155-test('$ handles tokens - `', testScriptStdout, () => $`echo.js \``, '`');156-test('$ handles expressions - `', testScriptStdout, () => $`echo.js ${'`'}`, '`');157-test('$ splits tokens - `', testScriptStdout, () => $`echo.js a\`b`, 'a`b');158-test('$ splits expressions - `', testScriptStdout, () => $`echo.js ${'a'}\`${'b'}`, 'a`b');159-test('$ concatenates tokens - `', testScriptStdout, () => $`echo.js \`a\` b`, '`a`\nb');160-test('$ concatenates expressions - `', testScriptStdout, () => $`echo.js \`${'a'}\` b`, '`a`\nb');161-test('$ handles tokens - \\v', testScriptStdout, () => $`echo.js \v`, '\v');162-test('$ handles expressions - \\v', testScriptStdout, () => $`echo.js ${'\v'}`, '\v');163-test('$ splits tokens - \\v', testScriptStdout, () => $`echo.js a\vb`, 'a\vb');164-test('$ splits expressions - \\v', testScriptStdout, () => $`echo.js ${'a'}\v${'b'}`, 'a\vb');165-test('$ concatenates tokens - \\v', testScriptStdout, () => $`echo.js \va\v b`, '\va\v\nb');166-test('$ concatenates expressions - \\v', testScriptStdout, () => $`echo.js \v${'a'}\v b`, '\va\v\nb');167-test('$ handles tokens - \\u2028', testScriptStdout, () => $`echo.js \u2028`, '\u2028');168-test('$ handles expressions - \\u2028', testScriptStdout, () => $`echo.js ${'\u2028'}`, '\u2028');169-test('$ splits tokens - \\u2028', testScriptStdout, () => $`echo.js a\u2028b`, 'a\u2028b');170-test('$ splits expressions - \\u2028', testScriptStdout, () => $`echo.js ${'a'}\u2028${'b'}`, 'a\u2028b');171-test('$ concatenates tokens - \\u2028', testScriptStdout, () => $`echo.js \u2028a\u2028 b`, '\u2028a\u2028\nb');172-test('$ concatenates expressions - \\u2028', testScriptStdout, () => $`echo.js \u2028${'a'}\u2028 b`, '\u2028a\u2028\nb');173-test('$ handles tokens - \\a', testScriptStdout, () => $`echo.js \a`, 'a');174-test('$ splits tokens - \\a', testScriptStdout, () => $`echo.js a\ab`, 'aab');175-test('$ splits expressions - \\a', testScriptStdout, () => $`echo.js ${'a'}\a${'b'}`, 'aab');176-test('$ concatenates tokens - \\a', testScriptStdout, () => $`echo.js \aa\a b`, 'aaa\nb');177-test('$ concatenates expressions - \\a', testScriptStdout, () => $`echo.js \a${'a'}\a b`, 'aaa\nb');178-test('$ handles tokens - \\cJ', testScriptStdout, () => $`echo.js \cJ`, 'cJ');179-test('$ splits tokens - \\cJ', testScriptStdout, () => $`echo.js a\cJb`, 'acJb');180-test('$ splits expressions - \\cJ', testScriptStdout, () => $`echo.js ${'a'}\cJ${'b'}`, 'acJb');181-test('$ concatenates tokens - \\cJ', testScriptStdout, () => $`echo.js \cJa\cJ b`, 'cJacJ\nb');182-test('$ concatenates expressions - \\cJ', testScriptStdout, () => $`echo.js \cJ${'a'}\cJ b`, 'cJacJ\nb');183-test('$ handles tokens - \\.', testScriptStdout, () => $`echo.js \.`, '.');184-test('$ splits tokens - \\.', testScriptStdout, () => $`echo.js a\.b`, 'a.b');185-test('$ splits expressions - \\.', testScriptStdout, () => $`echo.js ${'a'}\.${'b'}`, 'a.b');186-test('$ concatenates tokens - \\.', testScriptStdout, () => $`echo.js \.a\. b`, '.a.\nb');187-test('$ concatenates expressions - \\.', testScriptStdout, () => $`echo.js \.${'a'}\. b`, '.a.\nb');188-/* eslint-disable unicorn/no-hex-escape */189-test('$ handles tokens - \\x63', testScriptStdout, () => $`echo.js \x63`, 'c');190-test('$ splits tokens - \\x63', testScriptStdout, () => $`echo.js a\x63b`, 'acb');191-test('$ splits expressions - \\x63', testScriptStdout, () => $`echo.js ${'a'}\x63${'b'}`, 'acb');192-test('$ concatenates tokens - \\x63', testScriptStdout, () => $`echo.js \x63a\x63 b`, 'cac\nb');193-test('$ concatenates expressions - \\x63', testScriptStdout, () => $`echo.js \x63${'a'}\x63 b`, 'cac\nb');194-/* eslint-enable unicorn/no-hex-escape */195-test('$ handles tokens - \\u0063', testScriptStdout, () => $`echo.js \u0063`, 'c');196-test('$ splits tokens - \\u0063', testScriptStdout, () => $`echo.js a\u0063b`, 'acb');197-test('$ splits expressions - \\u0063', testScriptStdout, () => $`echo.js ${'a'}\u0063${'b'}`, 'acb');198-test('$ concatenates tokens - \\u0063', testScriptStdout, () => $`echo.js \u0063a\u0063 b`, 'cac\nb');199-test('$ concatenates expressions - \\u0063', testScriptStdout, () => $`echo.js \u0063${'a'}\u0063 b`, 'cac\nb');200-test('$ handles tokens - \\u{1}', testScriptStdout, () => $`echo.js \u{1}`, '\u0001');201-test('$ splits tokens - \\u{1}', testScriptStdout, () => $`echo.js a\u{1}b`, 'a\u0001b');202-test('$ splits expressions - \\u{1}', testScriptStdout, () => $`echo.js ${'a'}\u{1}${'b'}`, 'a\u0001b');203-test('$ concatenates tokens - \\u{1}', testScriptStdout, () => $`echo.js \u{1}a\u{1} b`, '\u0001a\u0001\nb');204-test('$ concatenates expressions - \\u{1}', testScriptStdout, () => $`echo.js \u{1}${'a'}\u{1} b`, '\u0001a\u0001\nb');205-test('$ handles tokens - \\u{63}', testScriptStdout, () => $`echo.js \u{63}`, 'c');206-test('$ splits tokens - \\u{63}', testScriptStdout, () => $`echo.js a\u{63}b`, 'acb');207-test('$ splits expressions - \\u{63}', testScriptStdout, () => $`echo.js ${'a'}\u{63}${'b'}`, 'acb');208-test('$ concatenates tokens - \\u{63}', testScriptStdout, () => $`echo.js \u{63}a\u{63} b`, 'cac\nb');209-test('$ concatenates expressions - \\u{63}', testScriptStdout, () => $`echo.js \u{63}${'a'}\u{63} b`, 'cac\nb');210-test('$ handles tokens - \\u{063}', testScriptStdout, () => $`echo.js \u{063}`, 'c');211-test('$ splits tokens - \\u{063}', testScriptStdout, () => $`echo.js a\u{063}b`, 'acb');212-test('$ splits expressions - \\u{063}', testScriptStdout, () => $`echo.js ${'a'}\u{063}${'b'}`, 'acb');213-test('$ concatenates tokens - \\u{063}', testScriptStdout, () => $`echo.js \u{063}a\u{063} b`, 'cac\nb');214-test('$ concatenates expressions - \\u{063}', testScriptStdout, () => $`echo.js \u{063}${'a'}\u{063} b`, 'cac\nb');215-test('$ handles tokens - \\u{0063}', testScriptStdout, () => $`echo.js \u{0063}`, 'c');216-test('$ splits tokens - \\u{0063}', testScriptStdout, () => $`echo.js a\u{0063}b`, 'acb');217-test('$ splits expressions - \\u{0063}', testScriptStdout, () => $`echo.js ${'a'}\u{0063}${'b'}`, 'acb');218-test('$ concatenates tokens - \\u{0063}', testScriptStdout, () => $`echo.js \u{0063}a\u{0063} b`, 'cac\nb');219-test('$ concatenates expressions - \\u{0063}', testScriptStdout, () => $`echo.js \u{0063}${'a'}\u{0063} b`, 'cac\nb');220-test('$ handles tokens - \\u{00063}', testScriptStdout, () => $`echo.js \u{00063}`, 'c');221-test('$ splits tokens - \\u{00063}', testScriptStdout, () => $`echo.js a\u{00063}b`, 'acb');222-test('$ splits expressions - \\u{00063}', testScriptStdout, () => $`echo.js ${'a'}\u{00063}${'b'}`, 'acb');223-test('$ concatenates tokens - \\u{00063}', testScriptStdout, () => $`echo.js \u{00063}a\u{00063} b`, 'cac\nb');224-test('$ concatenates expressions - \\u{00063}', testScriptStdout, () => $`echo.js \u{00063}${'a'}\u{00063} b`, 'cac\nb');225-test('$ handles tokens - \\u{000063}', testScriptStdout, () => $`echo.js \u{000063}`, 'c');226-test('$ splits tokens - \\u{000063}', testScriptStdout, () => $`echo.js a\u{000063}b`, 'acb');227-test('$ splits expressions - \\u{000063}', testScriptStdout, () => $`echo.js ${'a'}\u{000063}${'b'}`, 'acb');228-test('$ concatenates tokens - \\u{000063}', testScriptStdout, () => $`echo.js \u{000063}a\u{000063} b`, 'cac\nb');229-test('$ concatenates expressions - \\u{000063}', testScriptStdout, () => $`echo.js \u{000063}${'a'}\u{000063} b`, 'cac\nb');230-test('$ handles tokens - \\u{0000063}', testScriptStdout, () => $`echo.js \u{0000063}`, 'c');231-test('$ splits tokens - \\u{0000063}', testScriptStdout, () => $`echo.js a\u{0000063}b`, 'acb');232-test('$ splits expressions - \\u{0000063}', testScriptStdout, () => $`echo.js ${'a'}\u{0000063}${'b'}`, 'acb');233-test('$ concatenates tokens - \\u{0000063}', testScriptStdout, () => $`echo.js \u{0000063}a\u{0000063} b`, 'cac\nb');234-test('$ concatenates expressions - \\u{0000063}', testScriptStdout, () => $`echo.js \u{0000063}${'a'}\u{0000063} b`, 'cac\nb');235-test('$ handles tokens - \\u{0063}}', testScriptStdout, () => $`echo.js \u{0063}}`, 'c}');236-test('$ splits tokens - \\u{0063}}', testScriptStdout, () => $`echo.js a\u{0063}}b`, 'ac}b');237-test('$ splits expressions - \\u{0063}}', testScriptStdout, () => $`echo.js ${'a'}\u{0063}}${'b'}`, 'ac}b');238-test('$ concatenates tokens - \\u{0063}}', testScriptStdout, () => $`echo.js \u{0063}}a\u{0063}} b`, 'c}ac}\nb');239-test('$ concatenates expressions - \\u{0063}}', testScriptStdout, () => $`echo.js \u{0063}}${'a'}\u{0063}} b`, 'c}ac}\nb');240-241-const testScriptErrorStdout = async (t, getSubprocess) => {242- t.throws(getSubprocess, {message: /null bytes/});243-};244-245-test('$ handles tokens - \\0', testScriptErrorStdout, () => $`echo.js \0`);246-test('$ splits tokens - \\0', testScriptErrorStdout, () => $`echo.js a\0b`);247-test('$ splits expressions - \\0', testScriptErrorStdout, () => $`echo.js ${'a'}\0${'b'}`);248-test('$ concatenates tokens - \\0', testScriptErrorStdout, () => $`echo.js \0a\0 b`);249-test('$ concatenates expressions - \\0', testScriptErrorStdout, () => $`echo.js \0${'a'}\0 b`);250-9 const testScriptStdoutSync = (t, getSubprocess, expectedStdout) => {10 const {stdout} = getSubprocess();11 t.is(stdout, expectedStdout);12 };13 256-test('$.sync', testScriptStdoutSync, () => $.sync`echo.js foo bar`, 'foo\nbar');257-test('$.sync can be called $.s', testScriptStdoutSync, () => $.s`echo.js foo bar`, 'foo\nbar');258-test('$.sync accepts options', testScriptStdoutSync, () => $({stripFinalNewline: true}).sync`noop.js foo`, 'foo');14+test('$.sync`...`', testScriptStdoutSync, () => $.sync`echo.js foo bar`, 'foo\nbar');15+test('$.s`...`', testScriptStdoutSync, () => $.s`echo.js foo bar`, 'foo\nbar');16+test('$(options).sync`...`', testScriptStdoutSync, () => $({stripFinalNewline: false}).sync`echo.js ${foobarString}`, `${foobarString}\n`);17+test('$.sync(options)`...`', testScriptStdoutSync, () => $.sync({stripFinalNewline: false})`echo.js ${foobarString}`, `${foobarString}\n`);18 260-const testReturnInterpolate = async (t, getSubprocess, expectedStdout, options = {}) => {261- const foo = await $(options)`echo.js foo`;262- const {stdout} = await getSubprocess(foo);263- t.is(stdout, expectedStdout);264-};19+test('Cannot call $.sync.sync', t => {20+ t.false('sync' in $.sync);21+});22 266-test('$ allows execa return value interpolation', testReturnInterpolate, foo => $`echo.js ${foo} bar`, 'foo\nbar');267-test('$ allows execa return value buffer interpolation', testReturnInterpolate, foo => $`echo.js ${foo} bar`, 'foo\nbar', {encoding: 'buffer'});268-test('$ allows execa return value array interpolation', testReturnInterpolate, foo => $`echo.js ${[foo, 'bar']}`, 'foo\nbar');269-test('$ allows execa return value buffer array interpolation', testReturnInterpolate, foo => $`echo.js ${[foo, 'bar']}`, 'foo\nbar', {encoding: 'buffer'});23+test('Cannot call $.sync(options).sync', t => {24+ t.false('sync' in $.sync({}));25+});26 271-const testReturnInterpolateSync = (t, getSubprocess, expectedStdout, options = {}) => {272- const foo = $(options).sync`echo.js foo`;273- const {stdout} = getSubprocess(foo);274- t.is(stdout, expectedStdout);275-};27+test('$(options)() stdin defaults to "inherit"', async t => {28+ const {stdout} = await $({input: foobarString})('stdin-script.js');29+ t.is(stdout, foobarString);30+});31 277-test('$.sync allows execa return value interpolation', testReturnInterpolateSync, foo => $.sync`echo.js ${foo} bar`, 'foo\nbar');278-test('$.sync allows execa return value buffer interpolation', testReturnInterpolateSync, foo => $.sync`echo.js ${foo} bar`, 'foo\nbar', {encoding: 'buffer'});279-test('$.sync allows execa return value array interpolation', testReturnInterpolateSync, foo => $.sync`echo.js ${[foo, 'bar']}`, 'foo\nbar');280-test('$.sync allows execa return value buffer array interpolation', testReturnInterpolateSync, foo => $.sync`echo.js ${[foo, 'bar']}`, 'foo\nbar', {encoding: 'buffer'});281-282-const testInvalidSequence = (t, getSubprocess) => {283- t.throws(getSubprocess, {message: /Invalid backslash sequence/});284-};285-286-test('$ handles invalid escape sequence - \\1', testInvalidSequence, () => $`echo.js \1`);287-test('$ handles invalid escape sequence - \\u', testInvalidSequence, () => $`echo.js \u`);288-test('$ handles invalid escape sequence - \\u0', testInvalidSequence, () => $`echo.js \u0`);289-test('$ handles invalid escape sequence - \\u00', testInvalidSequence, () => $`echo.js \u00`);290-test('$ handles invalid escape sequence - \\u000', testInvalidSequence, () => $`echo.js \u000`);291-test('$ handles invalid escape sequence - \\ug', testInvalidSequence, () => $`echo.js \ug`);292-test('$ handles invalid escape sequence - \\u{', testInvalidSequence, () => $`echo.js \u{`);293-test('$ handles invalid escape sequence - \\u{0000', testInvalidSequence, () => $`echo.js \u{0000`);294-test('$ handles invalid escape sequence - \\u{g}', testInvalidSequence, () => $`echo.js \u{g}`);295-/* eslint-disable unicorn/no-hex-escape */296-test('$ handles invalid escape sequence - \\x', testInvalidSequence, () => $`echo.js \x`);297-test('$ handles invalid escape sequence - \\x0', testInvalidSequence, () => $`echo.js \x0`);298-test('$ handles invalid escape sequence - \\xgg', testInvalidSequence, () => $`echo.js \xgg`);299-/* eslint-enable unicorn/no-hex-escape */300-301-const testEmptyScript = (t, getSubprocess) => {302- t.throws(getSubprocess, {message: /Template script must not be empty/});303-};304-305-test('$``', testEmptyScript, () => $``);306-test('$` `', testEmptyScript, () => $` `);307-test('$` ` (2 spaces)', testEmptyScript, () => $` `);308-test('$`\\t`', testEmptyScript, () => $` `);309-test('$`\\n`', testEmptyScript, () => $`310-`);311-312-test('$.sync must be used after options binding, not before', t => {313- t.throws(() => $.sync({})`noop.js`, {message: /Please use/});32+test('$.sync(options)() stdin defaults to "inherit"', t => {33+ const {stdout} = $.sync({input: foobarString})('stdin-script.js');34+ t.is(stdout, foobarString);35 });36 316-test('$ must only use options or templates', t => {317- t.throws(() => $(true)`noop.js`, {message: /Please use either/});37+test('$(options).sync() stdin defaults to "inherit"', t => {38+ const {stdout} = $({input: foobarString}).sync('stdin-script.js');39+ t.is(stdout, foobarString);40 });41 320-test('$.sync must only templates', t => {321- t.throws(() => $.sync(true)`noop.js`, {message: /A template string must be used/});42+test('$(options)`...` stdin defaults to "inherit"', async t => {43+ const {stdout} = await $({input: foobarString})`stdin-script.js`;44+ t.is(stdout, foobarString);45 });46 324-const testInvalidExpression = (t, invalidExpression, execaMethod) => {325- const expression = typeof invalidExpression === 'function' ? invalidExpression() : invalidExpression;326- t.throws(327- () => execaMethod`echo.js ${expression}`,328- {message: /in template expression/},329- );330-};331-332-test('$ throws on invalid expression - undefined', testInvalidExpression, undefined, $);333-test('$ throws on invalid expression - null', testInvalidExpression, null, $);334-test('$ throws on invalid expression - true', testInvalidExpression, true, $);335-test('$ throws on invalid expression - {}', testInvalidExpression, {}, $);336-test('$ throws on invalid expression - {foo: "bar"}', testInvalidExpression, {foo: 'bar'}, $);337-test('$ throws on invalid expression - {stdout: undefined}', testInvalidExpression, {stdout: undefined}, $);338-test('$ throws on invalid expression - {stdout: 1}', testInvalidExpression, {stdout: 1}, $);339-test('$ throws on invalid expression - Promise.resolve()', testInvalidExpression, Promise.resolve(), $);340-test('$ throws on invalid expression - Promise.resolve({stdout: "foo"})', testInvalidExpression, Promise.resolve({foo: 'bar'}), $);341-test('$ throws on invalid expression - $', testInvalidExpression, () => $`noop.js`, $);342-test('$ throws on invalid expression - $(options).sync', testInvalidExpression, () => $({stdio: 'ignore'}).sync`noop.js`, $);343-test('$ throws on invalid expression - [undefined]', testInvalidExpression, [undefined], $);344-test('$ throws on invalid expression - [null]', testInvalidExpression, [null], $);345-test('$ throws on invalid expression - [true]', testInvalidExpression, [true], $);346-test('$ throws on invalid expression - [{}]', testInvalidExpression, [{}], $);347-test('$ throws on invalid expression - [{foo: "bar"}]', testInvalidExpression, [{foo: 'bar'}], $);348-test('$ throws on invalid expression - [{stdout: undefined}]', testInvalidExpression, [{stdout: undefined}], $);349-test('$ throws on invalid expression - [{stdout: 1}]', testInvalidExpression, [{stdout: 1}], $);350-test('$ throws on invalid expression - [Promise.resolve()]', testInvalidExpression, [Promise.resolve()], $);351-test('$ throws on invalid expression - [Promise.resolve({stdout: "foo"})]', testInvalidExpression, [Promise.resolve({stdout: 'foo'})], $);352-test('$ throws on invalid expression - [$]', testInvalidExpression, () => [$`noop.js`], $);353-test('$ throws on invalid expression - [$(options).sync]', testInvalidExpression, () => [$({stdio: 'ignore'}).sync`noop.js`], $);354-355-test('$ stdin defaults to "inherit"', async t => {356- const {stdout} = await $({input: 'foo'})`stdin-script.js`;357- t.is(stdout, 'foo');47+test('$.sync(options)`...` stdin defaults to "inherit"', t => {48+ const {stdout} = $.sync({input: foobarString})`stdin-script.js`;49+ t.is(stdout, foobarString);50 });51 360-test('$.sync stdin defaults to "inherit"', t => {361- const {stdout} = $({input: 'foo'}).sync`stdin-script.js`;362- t.is(stdout, 'foo');52+test('$(options).sync`...` stdin defaults to "inherit"', t => {53+ const {stdout} = $({input: foobarString}).sync`stdin-script.js`;54+ t.is(stdout, foobarString);55 });56 57 test('$ stdin has no default value when stdio is set', t => {58 t.true(isStream($({stdio: 'pipe'})`noop.js`.stdin));1 unmodified linemodified:index.d.ts+209 added-213 removed
950 unmodified lines951 952 This can be called multiple times to chain a series of subprocesses.953 954 Multiple subprocesses can be piped to the same subprocess. Conversely, the same subprocess can be piped to multiple other subprocesses.955-956- This is usually the preferred method to pipe subprocesses.955 */956 pipe<OptionsType extends Options & PipeOptions = {}>(957 file: string | URL,958 arguments?: readonly string[],5 unmodified lines964 ): Promise<ExecaResult<OptionsType>> & PipableSubprocess;965 966 /**967 Like `.pipe(file, arguments?, options?)` but using a `command` template string instead. This follows the same syntax as `$`.970-971- This is the preferred method to pipe subprocesses when using `$`.968 */969 pipe(templates: TemplateStringsArray, ...expressions: readonly TemplateExpression[]):970 Promise<ExecaResult<{}>> & PipableSubprocess;971 pipe<OptionsType extends Options & PipeOptions = {}>(options: OptionsType):135 unmodified lines1107 export type ExecaSubprocess<OptionsType extends Options = Options> = ChildProcess &1108 ExecaResultPromise<OptionsType> &1109 Promise<ExecaResult<OptionsType>>;1110 1111+type TemplateExpression = string | number | CommonResultInstance1112+| Array<string | number | CommonResultInstance>;1113+1114+type TemplateString = [TemplateStringsArray, ...readonly TemplateExpression[]];1115+type SimpleTemplateString = [TemplateStringsArray, string?];1116+1117+type Execa<OptionsType extends Options> = {1118+ <NewOptionsType extends Options = {}>(options: NewOptionsType): Execa<OptionsType & NewOptionsType>;1119+1120+ (...templateString: TemplateString): ExecaSubprocess<OptionsType>;1121+1122+ <NewOptionsType extends Options = {}>(1123+ file: string | URL,1124+ arguments?: readonly string[],1125+ options?: NewOptionsType,1126+ ): ExecaSubprocess<OptionsType & NewOptionsType>;1127+1128+ <NewOptionsType extends Options = {}>(1129+ file: string | URL,1130+ options?: NewOptionsType,1131+ ): ExecaSubprocess<OptionsType & NewOptionsType>;1132+};1133+1134 /**1135 Executes a command using `file ...arguments`.1136 1118-Arguments are automatically escaped. They can contain any character, including spaces.1137+Arguments are automatically escaped. They can contain any character, including spaces, tabs and newlines.1138 1120-This is the preferred method when executing single commands.1139+When `command` is a template string, it includes both the `file` and its `arguments`.1140 1141+The `command` template string can inject any `${value}` with the following types: string, number, `subprocess` or an array of those types. For example: `` execa`echo one ${'two'} ${3} ${['four', 'five']}` ``. For `${subprocess}`, the subprocess's `stdout` is used.1142+1143+When `command` is a template string, arguments can contain any character, but spaces, tabs and newlines must use `${}` like `` execa`echo ${'has space'}` ``.1144+1145+The `command` template string can use multiple lines and indentation.1146+1147+`execa(options)` can be used to return a new instance of Execa but with different default `options`. Consecutive calls are merged to previous ones. This allows setting global options or sharing options between multiple commands.1148+1149 @param file - The program/script to execute, as a string or file URL1150 @param arguments - Arguments to pass to `file` on execution.1151 @returns An `ExecaSubprocess` that is both:1152 - a `Promise` resolving or rejecting with a `subprocessResult`.8 unmodified lines1161 console.log(stdout);1162 //=> 'unicorns'1163 ```1164 1165+@example <caption>Global/shared options</caption>1166+```1167+import {execa as execa_} from 'execa';1168+1169+const execa = execa_({verbose: 'full'});1170+1171+await execa('echo', ['unicorns']);1172+//=> 'unicorns'1173+```1174+1175+@example <caption>Template string interface</caption>1176+1177+```1178+import {execa} from 'execa';1179+1180+const arg = 'unicorns'1181+const {stdout} = await execa`echo ${arg} & rainbows!`;1182+console.log(stdout);1183+//=> 'unicorns & rainbows!'1184+```1185+1186+@example <caption>Template string multiple arguments</caption>1187+1188+```1189+import {execa} from 'execa';1190+1191+const args = ['unicorns', '&', 'rainbows!'];1192+const {stdout} = await execa`echo ${args}`;1193+console.log(stdout);1194+//=> 'unicorns & rainbows!'1195+```1196+1197+@example <caption>Template string with options</caption>1198+1199+```1200+import {execa} from 'execa';1201+1202+await execa({verbose: 'full'})`echo unicorns`;1203+//=> 'unicorns'1204+```1205+1206 @example <caption>Redirect output to a file</caption>1207 ```1208 import {execa} from 'execa';1209 36 unmodified lines1246 console.log(stdout);1247 //=> 'unicorns'1248 ```1249 1250+@example <caption>Pipe with template strings</caption>1251+```1252+import {execa} from 'execa';1253+1254+await execa`npm run build`1255+ .pipe`sort`1256+ .pipe`head -n2`;1257+```1258+1259+@example <caption>Iterate over output lines</caption>1260+```1261+import {execa} from 'execa';1262+1263+for await (const line of execa`npm run build`)) {1264+ if (line.includes('ERROR')) {1265+ console.log(line);1266+ }1267+}1268+```1269+1270 @example <caption>Handling errors</caption>1271 ```1272 import {execa} from 'execa';1273 35 unmodified lines1309 \*\/1310 }1311 ```1312 */1225-export function execa<OptionsType extends Options = {}>(1226- file: string | URL,1227- arguments?: readonly string[],1228- options?: OptionsType,1229-): ExecaSubprocess<OptionsType>;1230-export function execa<OptionsType extends Options = {}>(1231- file: string | URL,1232- options?: OptionsType,1233-): ExecaSubprocess<OptionsType>;1313+declare const execa: Execa<{}>;1314 1315+type ExecaSync<OptionsType extends SyncOptions> = {1316+ <NewOptionsType extends SyncOptions = {}>(options: NewOptionsType): ExecaSync<OptionsType & NewOptionsType>;1317+1318+ (...templateString: TemplateString): ExecaSyncResult<OptionsType>;1319+1320+ <NewOptionsType extends SyncOptions = {}>(1321+ file: string | URL,1322+ arguments?: readonly string[],1323+ options?: NewOptionsType,1324+ ): ExecaSyncResult<OptionsType & NewOptionsType>;1325+1326+ <NewOptionsType extends SyncOptions = {}>(1327+ file: string | URL,1328+ options?: NewOptionsType,1329+ ): ExecaSyncResult<OptionsType & NewOptionsType>;1330+};1331+1332 /**1333 Same as `execa()` but synchronous.1334 1238-Cannot use the following options: `all`, `cleanup`, `buffer`, `detached`, `ipc`, `serialization`, `cancelSignal`, `lines` and `verbose: 'full'`. Also, the `stdin`, `stdout`, `stderr`, `stdio` and `input` options cannot be an array, an iterable, a transform or a web stream. Node.js streams must have a file descriptor unless the `input` option is used.1239-1335 Returns or throws a `subprocessResult`. The `subprocess` is not returned: its methods and properties are not available. This includes [`.kill()`](https://nodejs.org/api/child_process.html#subprocesskillsignal), [`.pid`](https://nodejs.org/api/child_process.html#subprocesspid), `.pipe()` and the [`.stdin`/`.stdout`/`.stderr`](https://nodejs.org/api/child_process.html#subprocessstdout) streams.1336 1337+Cannot use the following options: `all`, `cleanup`, `buffer`, `detached`, `ipc`, `serialization`, `cancelSignal`, `lines` and `verbose: 'full'`. Also, the `stdin`, `stdout`, `stderr`, `stdio` and `input` options cannot be an array, an iterable, a transform or a web stream. Node.js streams must have a file descriptor unless the `input` option is used.1338+1339 @param file - The program/script to execute, as a string or file URL1340 @param arguments - Arguments to pass to `file` on execution.1341 @returns A `subprocessResult` object1342 @throws A `subprocessResult` error49 unmodified lines1392 \*\/1393 }1394 ```1395 */1299-export function execaSync<OptionsType extends SyncOptions = {}>(1300- file: string | URL,1301- arguments?: readonly string[],1302- options?: OptionsType,1303-): ExecaSyncResult<OptionsType>;1304-export function execaSync<OptionsType extends SyncOptions = {}>(1305- file: string | URL,1306- options?: OptionsType,1307-): ExecaSyncResult<OptionsType>;1396+declare const execaSync: ExecaSync<{}>;1397 1398+type ExecaCommand<OptionsType extends Options> = {1399+ <NewOptionsType extends Options = {}>(options: NewOptionsType): ExecaCommand<OptionsType & NewOptionsType>;1400+1401+ (...templateString: SimpleTemplateString): ExecaSubprocess<OptionsType>;1402+1403+ <NewOptionsType extends Options = {}>(1404+ command: string,1405+ options?: NewOptionsType,1406+ ): ExecaSubprocess<OptionsType & NewOptionsType>;1407+};1408+1409 /**1310-Executes a command. The `command` string includes both the `file` and its `arguments`.1410+`execa` with the template string syntax allows the `file` or the `arguments` to be user-defined (by injecting them with `${}`). However, if _both_ the `file` and the `arguments` are user-defined, _and_ those are supplied as a single string, then `execaCommand(command)` must be used instead.1411 1312-Arguments are automatically escaped. They can contain any character, but spaces must be escaped with a backslash like `execaCommand('echo has\\ space')`.1412+This is only intended for very specific cases, such as a REPL. This should be avoided otherwise.1413 1314-This is the preferred method when executing a user-supplied `command` string, such as in a REPL.1414+Just like `execa()`, this can bind options. It can also be run synchronously using `execaCommandSync()`.1415 1416+Arguments are automatically escaped. They can contain any character, but spaces must be escaped with a backslash like `execaCommand('echo has\\ space')`.1417+1418 @param command - The program/script to execute and its arguments.1419 @returns An `ExecaSubprocess` that is both:1420 - a `Promise` resolving or rejecting with a `subprocessResult`.1421 - a [`child_process` instance](https://nodejs.org/api/child_process.html#child_process_class_childprocess) with some additional methods and properties.7 unmodified lines1429 console.log(stdout);1430 //=> 'unicorns'1431 ```1432 */1331-export function execaCommand<OptionsType extends Options = {}>(1332- command: string,1333- options?: OptionsType1334-): ExecaSubprocess<OptionsType>;1433+declare const execaCommand: ExecaCommand<{}>;1434 1435+type ExecaCommandSync<OptionsType extends SyncOptions> = {1436+ <NewOptionsType extends SyncOptions = {}>(options: NewOptionsType): ExecaCommandSync<OptionsType & NewOptionsType>;1437+1438+ (...templateString: SimpleTemplateString): ExecaSyncResult<OptionsType>;1439+1440+ <NewOptionsType extends SyncOptions = {}>(1441+ command: string,1442+ options?: NewOptionsType,1443+ ): ExecaSyncResult<OptionsType & NewOptionsType>;1444+};1445+1446 /**1447 Same as `execaCommand()` but synchronous.1448 1339-Cannot use the following options: `all`, `cleanup`, `buffer`, `detached`, `ipc`, `serialization`, `cancelSignal`, `lines` and `verbose: 'full'`. Also, the `stdin`, `stdout`, `stderr`, `stdio` and `input` options cannot be an array, an iterable, a transform or a web stream. Node.js streams must have a file descriptor unless the `input` option is used.1340-1449 Returns or throws a `subprocessResult`. The `subprocess` is not returned: its methods and properties are not available. This includes [`.kill()`](https://nodejs.org/api/child_process.html#subprocesskillsignal), [`.pid`](https://nodejs.org/api/child_process.html#subprocesspid), `.pipe()` and the [`.stdin`/`.stdout`/`.stderr`](https://nodejs.org/api/child_process.html#subprocessstdout) streams.1450 1451+Cannot use the following options: `all`, `cleanup`, `buffer`, `detached`, `ipc`, `serialization`, `cancelSignal`, `lines` and `verbose: 'full'`. Also, the `stdin`, `stdout`, `stderr`, `stdio` and `input` options cannot be an array, an iterable, a transform or a web stream. Node.js streams must have a file descriptor unless the `input` option is used.1452+1453 @param command - The program/script to execute and its arguments.1454 @returns A `subprocessResult` object1455 @throws A `subprocessResult` error1456 5 unmodified lines1462 console.log(stdout);1463 //=> 'unicorns'1464 ```1465 */1356-export function execaCommandSync<OptionsType extends SyncOptions = {}>(1357- command: string,1358- options?: OptionsType1359-): ExecaSyncResult<OptionsType>;1466+declare const execaCommandSync: ExecaCommandSync<{}>;1467 1361-type TemplateExpression = string | number | CommonResultInstance1362-| Array<string | number | CommonResultInstance>;1468+type ExecaScriptCommon<OptionsType extends CommonOptions> = {1469+ <NewOptionsType extends CommonOptions = {}>(options: NewOptionsType): ExecaScript<OptionsType & NewOptionsType>;1470 1364-type Execa$<OptionsType extends CommonOptions = {}> = {1365- /**1366- Returns a new instance of `$` but with different default `options`. Consecutive calls are merged to previous ones.1471+ (...templateString: TemplateString): ExecaSubprocess<StricterOptions<OptionsType, Options>>;1472 1368- This can be used to either:1369- - Set options for a specific command: `` $(options)`command` ``1370- - Share options for multiple commands: `` const $$ = $(options); $$`command`; $$`otherCommand` ``1473+ <NewOptionsType extends Options = {}>(1474+ file: string | URL,1475+ arguments?: readonly string[],1476+ options?: NewOptionsType,1477+ ): ExecaSubprocess<OptionsType & NewOptionsType>;1478 1372- @param options - Options to set1373- @returns A new instance of `$` with those `options` set1479+ <NewOptionsType extends Options = {}>(1480+ file: string | URL,1481+ options?: NewOptionsType,1482+ ): ExecaSubprocess<OptionsType & NewOptionsType>;1483+};1484 1375- @example1376- ```1377- import {$} from 'execa';1485+type ExecaScriptSync<OptionsType extends CommonOptions> = {1486+ <NewOptionsType extends SyncOptions = {}>(options: NewOptionsType): ExecaScriptSync<OptionsType & NewOptionsType>;1487 1379- const $$ = $({stdio: 'inherit'});1488+ (...templateString: TemplateString): ExecaSyncResult<StricterOptions<OptionsType, SyncOptions>>;1489 1381- await $$`echo unicorns`;1382- //=> 'unicorns'1490+ <NewOptionsType extends SyncOptions = {}>(1491+ file: string | URL,1492+ arguments?: readonly string[],1493+ options?: NewOptionsType,1494+ ): ExecaSyncResult<OptionsType & NewOptionsType>;1495 1384- await $$`echo rainbows`;1385- //=> 'rainbows'1386- ```1387- */1388- <NewOptionsType extends CommonOptions = {}>1389- (options: NewOptionsType): Execa$<OptionsType & NewOptionsType>;1390-1391- (templates: TemplateStringsArray, ...expressions: readonly TemplateExpression[]):1392- ExecaSubprocess<StricterOptions<OptionsType, Options>> & PipableSubprocess;1393-1394- /**1395- Same as $\`command\` but synchronous.1396-1397- Cannot use the following options: `all`, `cleanup`, `buffer`, `detached`, `ipc`, `serialization`, `cancelSignal`, `lines` and `verbose: 'full'`. Also, the `stdin`, `stdout`, `stderr`, `stdio` and `input` options cannot be an array, an iterable, a transform or a web stream. Node.js streams must have a file descriptor unless the `input` option is used.1398-1399- Returns or throws a `subprocessResult`. The `subprocess` is not returned: its methods and properties are not available. This includes [`.kill()`](https://nodejs.org/api/child_process.html#subprocesskillsignal), [`.pid`](https://nodejs.org/api/child_process.html#subprocesspid), `.pipe()` and the [`.stdin`/`.stdout`/`.stderr`](https://nodejs.org/api/child_process.html#subprocessstdout) streams.1400-1401- @returns A `subprocessResult` object1402- @throws A `subprocessResult` error1403-1404- @example <caption>Basic</caption>1405- ```1406- import {$} from 'execa';1407-1408- const branch = $.sync`git branch --show-current`;1409- $.sync`dep deploy --branch=${branch}`;1410- ```1411-1412- @example <caption>Multiple arguments</caption>1413- ```1414- import {$} from 'execa';1415-1416- const args = ['unicorns', '&', 'rainbows!'];1417- const {stdout} = $.sync`echo ${args}`;1418- console.log(stdout);1419- //=> 'unicorns & rainbows!'1420- ```1421-1422- @example <caption>With options</caption>1423- ```1424- import {$} from 'execa';1425-1426- $.sync({stdio: 'inherit'})`echo unicorns`;1427- //=> 'unicorns'1428- ```1429-1430- @example <caption>Shared options</caption>1431- ```1432- import {$} from 'execa';1433-1434- const $$ = $({stdio: 'inherit'});1435-1436- $$.sync`echo unicorns`;1437- //=> 'unicorns'1438-1439- $$.sync`echo rainbows`;1440- //=> 'rainbows'1441- ```1442- */1443- sync(1444- templates: TemplateStringsArray,1445- ...expressions: readonly TemplateExpression[]1446- ): ExecaSyncResult<StricterOptions<OptionsType, SyncOptions>>;1447-1448- /**1449- Same as $\`command\` but synchronous.1450-1451- Cannot use the following options: `all`, `cleanup`, `buffer`, `detached`, `ipc`, `serialization`, `cancelSignal`, `lines` and `verbose: 'full'`. Also, the `stdin`, `stdout`, `stderr`, `stdio` and `input` options cannot be an array, an iterable, a transform or a web stream. Node.js streams must have a file descriptor unless the `input` option is used.1452-1453- Returns or throws a `subprocessResult`. The `subprocess` is not returned: its methods and properties are not available. This includes [`.kill()`](https://nodejs.org/api/child_process.html#subprocesskillsignal), [`.pid`](https://nodejs.org/api/child_process.html#subprocesspid), `.pipe()` and the [`.stdin`/`.stdout`/`.stderr`](https://nodejs.org/api/child_process.html#subprocessstdout) streams.1454-1455- @returns A `subprocessResult` object1456- @throws A `subprocessResult` error1457-1458- @example <caption>Basic</caption>1459- ```1460- import {$} from 'execa';1461-1462- const branch = $.s`git branch --show-current`;1463- $.s`dep deploy --branch=${branch}`;1464- ```1465-1466- @example <caption>Multiple arguments</caption>1467- ```1468- import {$} from 'execa';1469-1470- const args = ['unicorns', '&', 'rainbows!'];1471- const {stdout} = $.s`echo ${args}`;1472- console.log(stdout);1473- //=> 'unicorns & rainbows!'1474- ```1475-1476- @example <caption>With options</caption>1477- ```1478- import {$} from 'execa';1479-1480- $.s({stdio: 'inherit'})`echo unicorns`;1481- //=> 'unicorns'1482- ```1483-1484- @example <caption>Shared options</caption>1485- ```1486- import {$} from 'execa';1487-1488- const $$ = $({stdio: 'inherit'});1489-1490- $$.s`echo unicorns`;1491- //=> 'unicorns'1492-1493- $$.s`echo rainbows`;1494- //=> 'rainbows'1495- ```1496- */1497- s(1498- templates: TemplateStringsArray,1499- ...expressions: readonly TemplateExpression[]1500- ): ExecaSyncResult<StricterOptions<OptionsType, SyncOptions>>;1496+ <NewOptionsType extends SyncOptions = {}>(1497+ file: string | URL,1498+ options?: NewOptionsType,1499+ ): ExecaSyncResult<OptionsType & NewOptionsType>;1500 };1501 1502+type ExecaScript<OptionsType extends CommonOptions> = {1503+ sync: ExecaScriptSync<OptionsType>;1504+ s: ExecaScriptSync<OptionsType>;1505+} & ExecaScriptCommon<OptionsType>;1506+1507 /**1504-Executes a command. The `command` string includes both the `file` and its `arguments`.1508+Same as `execa()` but using the `stdin: 'inherit'` and `preferLocal: true` options.1509 1506-Arguments are automatically escaped. They can contain any character, but spaces, tabs and newlines must use `${}` like `` $`echo ${'has space'}` ``.1510+Just like `execa()`, this can use the template string syntax or bind options. It can also be run synchronously using `$.sync()` or `$.s()`.1511 1512 This is the preferred method when executing multiple commands in a script file.1513 1510-The `command` string can inject any `${value}` with the following types: string, number, `subprocess` or an array of those types. For example: `` $`echo one ${'two'} ${3} ${['four', 'five']}` ``. For `${subprocess}`, the subprocess's `stdout` is used.1511-1514 @returns An `ExecaSubprocess` that is both:1515 - a `Promise` resolving or rejecting with a `subprocessResult`.1516 - a [`child_process` instance](https://nodejs.org/api/child_process.html#child_process_class_childprocess) with some additional methods and properties.1517 @throws A `subprocessResult` error5 unmodified lines1523 const branch = await $`git branch --show-current`;1524 await $`dep deploy --branch=${branch}`;1525 ```1526 1525-@example <caption>Multiple arguments</caption>1527+@example <caption>Verbose mode</caption>1528 ```1527-import {$} from 'execa';1529+> node file.js1530+unicorns1531+rainbows1532 1529-const args = ['unicorns', '&', 'rainbows!'];1530-const {stdout} = await $`echo ${args}`;1531-console.log(stdout);1532-//=> 'unicorns & rainbows!'1533+> NODE_DEBUG=execa node file.js1534+[19:49:00.360] [0] $ echo unicorns1535+unicorns1536+[19:49:00.383] [0] √ (done in 23ms)1537+[19:49:00.383] [1] $ echo rainbows1538+rainbows1539+[19:49:00.404] [1] √ (done in 21ms)1540 ```1541+*/1542+export const $: ExecaScript<{}>;1543 1535-@example <caption>With options</caption>1536-```1537-import {$} from 'execa';1544+type ExecaNode<OptionsType extends Options> = {1545+ <NewOptionsType extends Options = {}>(options: NewOptionsType): ExecaNode<OptionsType & NewOptionsType>;1546 1539-await $({stdio: 'inherit'})`echo unicorns`;1540-//=> 'unicorns'1541-```1547+ (...templateString: TemplateString): ExecaSubprocess<OptionsType>;1548 1543-@example <caption>Shared options</caption>1544-```1545-import {$} from 'execa';1549+ <NewOptionsType extends Options = {}>(1550+ scriptPath: string | URL,1551+ arguments?: readonly string[],1552+ options?: NewOptionsType,1553+ ): ExecaSubprocess<OptionsType & NewOptionsType>;1554 1547-const $$ = $({stdio: 'inherit'});1555+ <NewOptionsType extends Options = {}>(1556+ scriptPath: string | URL,1557+ options?: NewOptionsType,1558+ ): ExecaSubprocess<OptionsType & NewOptionsType>;1559+};1560 1549-await $$`echo unicorns`;1550-//=> 'unicorns'1551-1552-await $$`echo rainbows`;1553-//=> 'rainbows'1554-```1555-*/1556-export const $: Execa$;1557-1561 /**1559-Same as `execa()` but using the `node` option.1560-1562+Same as `execa()` but using the `node: true` option.1563 Executes a Node.js file using `node scriptPath ...arguments`.1564 1565+Just like `execa()`, this can use the template string syntax or bind options.1566+1567 This is the preferred method when executing Node.js files.1568 1569 @param scriptPath - Node.js script to execute, as a string or file URL1570 @param arguments - Arguments to pass to `scriptPath` on execution.3 unmodified lines1574 @throws A `subprocessResult` error1575 1576 @example1577 ```1574-import {execa} from 'execa';1578+import {execaNode} from 'execa';1579 1580 await execaNode('scriptPath', ['argument']);1581 ```1582 */1579-export function execaNode<OptionsType extends Options = {}>(1580- scriptPath: string | URL,1581- arguments?: readonly string[],1582- options?: OptionsType1583-): ExecaSubprocess<OptionsType>;1584-export function execaNode<OptionsType extends Options = {}>(1585- scriptPath: string | URL,1586- options?: OptionsType1587-): ExecaSubprocess<OptionsType>;1583+export const execaNode: ExecaNode<{}>;modified:index.js+12 added-5 removed
1-export {execa} from './lib/async.js';2-export {execaSync} from './lib/sync.js';3-export {execaCommand, execaCommandSync} from './lib/command.js';4-export {execaNode} from './lib/arguments/node.js';5-export {$} from './lib/script.js';1+import {createExeca} from './lib/arguments/create.js';2+import {mapCommandAsync, mapCommandSync} from './lib/command.js';3+import {mapNode} from './lib/arguments/node.js';4+import {mapScriptAsync, setScriptSync, deepScriptOptions} from './lib/script.js';5+6 export {ExecaError, ExecaSyncError} from './lib/return/cause.js';7+8+export const execa = createExeca(() => ({}));9+export const execaSync = createExeca(() => ({isSync: true}));10+export const execaCommand = createExeca(mapCommandAsync);11+export const execaCommandSync = createExeca(mapCommandSync);12+export const execaNode = createExeca(mapNode);13+export const $ = createExeca(mapScriptAsync, {}, deepScriptOptions, setScriptSync);modified:index.test-d.ts+332 added-68 removed
1693 unmodified lines1694 expectError(execa('unicorns').kill(undefined, {}));1695 expectError(execa('unicorns').kill('SIGKILL', {}));1696 expectError(execa('unicorns').kill(null, new Error('test')));1697 1698+expectError(execa());1699+expectError(execa(true));1700 expectError(execa(['unicorns', 'arg']));1701 expectAssignable<ExecaSubprocess>(execa('unicorns'));1702 expectAssignable<ExecaSubprocess>(execa(fileUrl));1703+expectAssignable<ExecaSubprocess>(execa('unicorns', []));1704+expectAssignable<ExecaSubprocess>(execa('unicorns', ['foo']));1705+expectAssignable<ExecaSubprocess>(execa('unicorns', {}));1706+expectAssignable<ExecaSubprocess>(execa('unicorns', [], {}));1707+expectError(execa('unicorns', 'foo'));1708+expectError(execa('unicorns', [true]));1709+expectError(execa('unicorns', [], []));1710+expectError(execa('unicorns', {other: true}));1711+expectAssignable<ExecaSubprocess>(execa`unicorns`);1712+expectAssignable<typeof execa>(execa({}));1713+expectAssignable<ExecaSubprocess>(execa({})('unicorns'));1714+expectAssignable<ExecaSubprocess>(execa({})`unicorns`);1701-expectType<ExecaResult>(await execa('unicorns'));1715+expectType<ExecaResult<{}>>(await execa('unicorns'));1716+expectType<ExecaResult<{}>>(await execa`unicorns`);1717 expectAssignable<{stdout: string}>(await execa('unicorns'));1718 expectAssignable<{stdout: Uint8Array}>(await execa('unicorns', {encoding: 'buffer'}));1719 expectAssignable<{stdout: string}>(await execa('unicorns', ['foo']));1720 expectAssignable<{stdout: Uint8Array}>(await execa('unicorns', ['foo'], {encoding: 'buffer'}));1721+expectAssignable<{stdout: string}>(await execa({})('unicorns'));1722+expectAssignable<{stdout: Uint8Array}>(await execa({encoding: 'buffer'})('unicorns'));1723+expectAssignable<{stdout: Uint8Array}>(await execa({})({encoding: 'buffer'})('unicorns'));1724+expectAssignable<{stdout: Uint8Array}>(await execa({encoding: 'buffer'})({})('unicorns'));1725+expectAssignable<{stdout: string}>(await execa({})`unicorns`);1726+expectAssignable<{stdout: Uint8Array}>(await execa({encoding: 'buffer'})`unicorns`);1727+expectAssignable<{stdout: Uint8Array}>(await execa({})({encoding: 'buffer'})`unicorns`);1728+expectAssignable<{stdout: Uint8Array}>(await execa({encoding: 'buffer'})({})`unicorns`);1729+expectType<ExecaResult<{}>>(await execa`${'unicorns'}`);1730+expectType<ExecaResult<{}>>(await execa`unicorns ${'foo'}`);1731+expectType<ExecaResult<{}>>(await execa`unicorns ${'foo'} ${'bar'}`);1732+expectType<ExecaResult<{}>>(await execa`unicorns ${1}`);1733+expectType<ExecaResult<{}>>(await execa`unicorns ${['foo', 'bar']}`);1734+expectType<ExecaResult<{}>>(await execa`unicorns ${[1, 2]}`);1735+expectType<ExecaResult<{}>>(await execa`unicorns ${await execa`echo foo`}`);1736+expectError(await execa`unicorns ${execa`echo foo`}`);1737+expectType<ExecaResult<{}>>(await execa`unicorns ${[await execa`echo foo`, 'bar']}`);1738+expectError(await execa`unicorns ${[execa`echo foo`, 'bar']}`);1739+expectType<ExecaResult<{}>>(await execa`unicorns ${true.toString()}`);1740+expectError(await execa`unicorns ${true}`);1741 1742+expectError(execaSync());1743+expectError(execaSync(true));1744 expectError(execaSync(['unicorns', 'arg']));1708-expectAssignable<ExecaSyncResult>(execaSync('unicorns'));1709-expectAssignable<ExecaSyncResult>(execaSync(fileUrl));1745+expectType<ExecaSyncResult<{}>>(execaSync('unicorns'));1746+expectType<ExecaSyncResult<{}>>(execaSync(fileUrl));1747+expectType<ExecaSyncResult<{}>>(execaSync('unicorns', []));1748+expectType<ExecaSyncResult<{}>>(execaSync('unicorns', ['foo']));1749+expectType<ExecaSyncResult<{}>>(execaSync('unicorns', {}));1750+expectType<ExecaSyncResult<{}>>(execaSync('unicorns', [], {}));1751+expectError(execaSync('unicorns', 'foo'));1752+expectError(execaSync('unicorns', [true]));1753+expectError(execaSync('unicorns', [], []));1754+expectError(execaSync('unicorns', {other: true}));1755+expectType<ExecaSyncResult<{}>>(execaSync`unicorns`);1756+expectAssignable<typeof execaSync>(execaSync({}));1757+expectType<ExecaSyncResult<{}>>(execaSync({})('unicorns'));1758+expectType<ExecaSyncResult<{}>>(execaSync({})`unicorns`);1759+expectType<ExecaSyncResult<{}>>(execaSync('unicorns'));1760+expectType<ExecaSyncResult<{}>>(execaSync`unicorns`);1761 expectAssignable<{stdout: string}>(execaSync('unicorns'));1762 expectAssignable<{stdout: Uint8Array}>(execaSync('unicorns', {encoding: 'buffer'}));1763 expectAssignable<{stdout: string}>(execaSync('unicorns', ['foo']));1764 expectAssignable<{stdout: Uint8Array}>(execaSync('unicorns', ['foo'], {encoding: 'buffer'}));1765+expectAssignable<{stdout: string}>(execaSync({})('unicorns'));1766+expectAssignable<{stdout: Uint8Array}>(execaSync({encoding: 'buffer'})('unicorns'));1767+expectAssignable<{stdout: Uint8Array}>(execaSync({})({encoding: 'buffer'})('unicorns'));1768+expectAssignable<{stdout: Uint8Array}>(execaSync({encoding: 'buffer'})({})('unicorns'));1769+expectAssignable<{stdout: string}>(execaSync({})`unicorns`);1770+expectAssignable<{stdout: Uint8Array}>(execaSync({encoding: 'buffer'})`unicorns`);1771+expectAssignable<{stdout: Uint8Array}>(execaSync({})({encoding: 'buffer'})`unicorns`);1772+expectAssignable<{stdout: Uint8Array}>(execaSync({encoding: 'buffer'})({})`unicorns`);1773+expectType<ExecaSyncResult<{}>>(execaSync`${'unicorns'}`);1774+expectType<ExecaSyncResult<{}>>(execaSync`unicorns ${'foo'}`);1775+expectType<ExecaSyncResult<{}>>(execaSync`unicorns ${'foo'} ${'bar'}`);1776+expectType<ExecaSyncResult<{}>>(execaSync`unicorns ${1}`);1777+expectType<ExecaSyncResult<{}>>(execaSync`unicorns ${['foo', 'bar']}`);1778+expectType<ExecaSyncResult<{}>>(execaSync`unicorns ${[1, 2]}`);1779+expectType<ExecaSyncResult<{}>>(execaSync`unicorns ${execaSync`echo foo`}`);1780+expectType<ExecaSyncResult<{}>>(execaSync`unicorns ${[execaSync`echo foo`, 'bar']}`);1781+expectType<ExecaSyncResult<{}>>(execaSync`unicorns ${false.toString()}`);1782+expectError(execaSync`unicorns ${false}`);1783 1784+expectError(execaCommand());1785+expectError(execaCommand(true));1786+expectError(execaCommand(['unicorns', 'arg']));1787 expectAssignable<ExecaSubprocess>(execaCommand('unicorns'));1788+expectError(execaCommand(fileUrl));1789+expectError(execaCommand('unicorns', []));1790+expectError(execaCommand('unicorns', ['foo']));1791+expectAssignable<ExecaSubprocess>(execaCommand('unicorns', {}));1792+expectError(execaCommand('unicorns', [], {}));1793+expectError(execaCommand('unicorns', 'foo'));1794+expectError(execaCommand('unicorns', [true]));1795+expectError(execaCommand('unicorns', [], []));1796+expectError(execaCommand('unicorns', {other: true}));1797+expectAssignable<ExecaSubprocess>(execaCommand`unicorns`);1798+expectAssignable<typeof execaCommand>(execaCommand({}));1799+expectAssignable<ExecaSubprocess>(execaCommand({})('unicorns'));1800+expectAssignable<ExecaSubprocess>(execaCommand({})`unicorns`);1716-expectType<ExecaResult>(await execaCommand('unicorns'));1801+expectType<ExecaResult<{}>>(await execaCommand('unicorns'));1802+expectType<ExecaResult<{}>>(await execaCommand`unicorns`);1803 expectAssignable<{stdout: string}>(await execaCommand('unicorns'));1804 expectAssignable<{stdout: Uint8Array}>(await execaCommand('unicorns', {encoding: 'buffer'}));1719-expectAssignable<{stdout: string}>(await execaCommand('unicorns foo'));1720-expectAssignable<{stdout: Uint8Array}>(await execaCommand('unicorns foo', {encoding: 'buffer'}));1805+expectAssignable<{stdout: string}>(await execaCommand({})('unicorns'));1806+expectAssignable<{stdout: Uint8Array}>(await execaCommand({encoding: 'buffer'})('unicorns'));1807+expectAssignable<{stdout: Uint8Array}>(await execaCommand({})({encoding: 'buffer'})('unicorns'));1808+expectAssignable<{stdout: Uint8Array}>(await execaCommand({encoding: 'buffer'})({})('unicorns'));1809+expectAssignable<{stdout: string}>(await execaCommand({})`unicorns`);1810+expectAssignable<{stdout: Uint8Array}>(await execaCommand({encoding: 'buffer'})`unicorns`);1811+expectAssignable<{stdout: Uint8Array}>(await execaCommand({})({encoding: 'buffer'})`unicorns`);1812+expectAssignable<{stdout: Uint8Array}>(await execaCommand({encoding: 'buffer'})({})`unicorns`);1813+expectType<ExecaResult<{}>>(await execaCommand`${'unicorns'}`);1814+expectType<ExecaResult<{}>>(await execaCommand`unicorns ${'foo'}`);1815+expectError(await execaCommand`unicorns ${'foo'} ${'bar'}`);1816+expectError(await execaCommand`unicorns ${1}`);1817+expectError(await execaCommand`unicorns ${['foo', 'bar']}`);1818+expectError(await execaCommand`unicorns ${[1, 2]}`);1819+expectError(await execaCommand`unicorns ${await execaCommand`echo foo`}`);1820+expectError(await execaCommand`unicorns ${execaCommand`echo foo`}`);1821+expectError(await execaCommand`unicorns ${[await execaCommand`echo foo`, 'bar']}`);1822+expectError(await execaCommand`unicorns ${[execaCommand`echo foo`, 'bar']}`);1823+expectType<ExecaResult<{}>>(await execaCommand`unicorns ${true.toString()}`);1824+expectError(await execaCommand`unicorns ${true}`);1825 1722-expectAssignable<ExecaSyncResult>(execaCommandSync('unicorns'));1826+expectError(execaCommandSync());1827+expectError(execaCommandSync(true));1828+expectError(execaCommandSync(['unicorns', 'arg']));1829+expectType<ExecaSyncResult<{}>>(execaCommandSync('unicorns'));1830+expectError(execaCommandSync(fileUrl));1831+expectError(execaCommandSync('unicorns', []));1832+expectError(execaCommandSync('unicorns', ['foo']));1833+expectType<ExecaSyncResult<{}>>(execaCommandSync('unicorns', {}));1834+expectError(execaCommandSync('unicorns', [], {}));1835+expectError(execaCommandSync('unicorns', 'foo'));1836+expectError(execaCommandSync('unicorns', [true]));1837+expectError(execaCommandSync('unicorns', [], []));1838+expectError(execaCommandSync('unicorns', {other: true}));1839+expectType<ExecaSyncResult<{}>>(execaCommandSync`unicorns`);1840+expectAssignable<typeof execaCommandSync>(execaCommandSync({}));1841+expectType<ExecaSyncResult<{}>>(execaCommandSync({})('unicorns'));1842+expectType<ExecaSyncResult<{}>>(execaCommandSync({})`unicorns`);1843+expectType<ExecaSyncResult<{}>>(execaCommandSync('unicorns'));1844+expectType<ExecaSyncResult<{}>>(execaCommandSync`unicorns`);1845 expectAssignable<{stdout: string}>(execaCommandSync('unicorns'));1846 expectAssignable<{stdout: Uint8Array}>(execaCommandSync('unicorns', {encoding: 'buffer'}));1725-expectAssignable<{stdout: string}>(execaCommandSync('unicorns foo'));1726-expectAssignable<{stdout: Uint8Array}>(execaCommandSync('unicorns foo', {encoding: 'buffer'}));1847+expectAssignable<{stdout: string}>(execaCommandSync({})('unicorns'));1848+expectAssignable<{stdout: Uint8Array}>(execaCommandSync({encoding: 'buffer'})('unicorns'));1849+expectAssignable<{stdout: Uint8Array}>(execaCommandSync({})({encoding: 'buffer'})('unicorns'));1850+expectAssignable<{stdout: Uint8Array}>(execaCommandSync({encoding: 'buffer'})({})('unicorns'));1851+expectAssignable<{stdout: string}>(execaCommandSync({})`unicorns`);1852+expectAssignable<{stdout: Uint8Array}>(execaCommandSync({encoding: 'buffer'})`unicorns`);1853+expectAssignable<{stdout: Uint8Array}>(execaCommandSync({})({encoding: 'buffer'})`unicorns`);1854+expectAssignable<{stdout: Uint8Array}>(execaCommandSync({encoding: 'buffer'})({})`unicorns`);1855+expectType<ExecaSyncResult<{}>>(execaCommandSync`${'unicorns'}`);1856+expectType<ExecaSyncResult<{}>>(execaCommandSync`unicorns ${'foo'}`);1857+expectError(execaCommandSync`unicorns ${'foo'} ${'bar'}`);1858+expectError(execaCommandSync`unicorns ${1}`);1859+expectError(execaCommandSync`unicorns ${['foo', 'bar']}`);1860+expectError(execaCommandSync`unicorns ${[1, 2]}`);1861+expectError(execaCommandSync`unicorns ${execaCommandSync`echo foo`}`);1862+expectError(execaCommandSync`unicorns ${[execaCommandSync`echo foo`, 'bar']}`);1863+expectType<ExecaSyncResult<{}>>(execaCommandSync`unicorns ${false.toString()}`);1864+expectError(execaCommandSync`unicorns ${false}`);1865 1866+expectError($());1867+expectError($(true));1868+expectError($(['unicorns', 'arg']));1869+expectAssignable<ExecaSubprocess>($('unicorns'));1870+expectAssignable<ExecaSubprocess>($(fileUrl));1871+expectAssignable<ExecaSubprocess>($('unicorns', []));1872+expectAssignable<ExecaSubprocess>($('unicorns', ['foo']));1873+expectAssignable<ExecaSubprocess>($('unicorns', {}));1874+expectAssignable<ExecaSubprocess>($('unicorns', [], {}));1875+expectError($('unicorns', 'foo'));1876+expectError($('unicorns', [true]));1877+expectError($('unicorns', [], []));1878+expectError($('unicorns', {other: true}));1879+expectAssignable<ExecaSubprocess>($`unicorns`);1880+expectAssignable<typeof $>($({}));1881+expectAssignable<ExecaSubprocess>($({})('unicorns'));1882+expectAssignable<ExecaSubprocess>($({})`unicorns`);1883+expectType<ExecaResult<{}>>(await $('unicorns'));1884+expectType<ExecaResult<{}>>(await $`unicorns`);1885+expectAssignable<{stdout: string}>(await $('unicorns'));1886+expectAssignable<{stdout: Uint8Array}>(await $('unicorns', {encoding: 'buffer'}));1887+expectAssignable<{stdout: string}>(await $('unicorns', ['foo']));1888+expectAssignable<{stdout: Uint8Array}>(await $('unicorns', ['foo'], {encoding: 'buffer'}));1889+expectAssignable<{stdout: string}>(await $({})('unicorns'));1890+expectAssignable<{stdout: Uint8Array}>(await $({encoding: 'buffer'})('unicorns'));1891+expectAssignable<{stdout: Uint8Array}>(await $({})({encoding: 'buffer'})('unicorns'));1892+expectAssignable<{stdout: Uint8Array}>(await $({encoding: 'buffer'})({})('unicorns'));1893+expectAssignable<{stdout: string}>(await $({})`unicorns`);1894+expectAssignable<{stdout: Uint8Array}>(await $({encoding: 'buffer'})`unicorns`);1895+expectAssignable<{stdout: Uint8Array}>(await $({})({encoding: 'buffer'})`unicorns`);1896+expectAssignable<{stdout: Uint8Array}>(await $({encoding: 'buffer'})({})`unicorns`);1897+expectType<ExecaResult<{}>>(await $`${'unicorns'}`);1898+expectType<ExecaResult<{}>>(await $`unicorns ${'foo'}`);1899+expectType<ExecaResult<{}>>(await $`unicorns ${'foo'} ${'bar'}`);1900+expectType<ExecaResult<{}>>(await $`unicorns ${1}`);1901+expectType<ExecaResult<{}>>(await $`unicorns ${['foo', 'bar']}`);1902+expectType<ExecaResult<{}>>(await $`unicorns ${[1, 2]}`);1903+expectType<ExecaResult<{}>>(await $`unicorns ${await $`echo foo`}`);1904+expectError(await $`unicorns ${$`echo foo`}`);1905+expectType<ExecaResult<{}>>(await $`unicorns ${[await $`echo foo`, 'bar']}`);1906+expectError(await $`unicorns ${[$`echo foo`, 'bar']}`);1907+expectType<ExecaResult<{}>>(await $`unicorns ${true.toString()}`);1908+expectError(await $`unicorns ${true}`);1909+1910+expectError($.sync());1911+expectError($.sync(true));1912+expectError($.sync(['unicorns', 'arg']));1913+expectType<ExecaSyncResult<{}>>($.sync('unicorns'));1914+expectType<ExecaSyncResult<{}>>($.sync(fileUrl));1915+expectType<ExecaSyncResult<{}>>($.sync('unicorns', []));1916+expectType<ExecaSyncResult<{}>>($.sync('unicorns', ['foo']));1917+expectType<ExecaSyncResult<{}>>($.sync('unicorns', {}));1918+expectType<ExecaSyncResult<{}>>($.sync('unicorns', [], {}));1919+expectError($.sync('unicorns', 'foo'));1920+expectError($.sync('unicorns', [true]));1921+expectError($.sync('unicorns', [], []));1922+expectError($.sync('unicorns', {other: true}));1923+expectType<ExecaSyncResult<{}>>($.sync`unicorns`);1924+expectAssignable<typeof $.sync>($.sync({}));1925+expectType<ExecaSyncResult<{}>>($.sync({})('unicorns'));1926+expectType<ExecaSyncResult<{}>>($({}).sync('unicorns'));1927+expectType<ExecaSyncResult<{}>>($.sync({})`unicorns`);1928+expectType<ExecaSyncResult<{}>>($({}).sync`unicorns`);1929+expectType<ExecaSyncResult<{}>>($.sync('unicorns'));1930+expectType<ExecaSyncResult<{}>>($.sync`unicorns`);1931+expectAssignable<{stdout: string}>($.sync('unicorns'));1932+expectAssignable<{stdout: Uint8Array}>($.sync('unicorns', {encoding: 'buffer'}));1933+expectAssignable<{stdout: string}>($.sync('unicorns', ['foo']));1934+expectAssignable<{stdout: Uint8Array}>($.sync('unicorns', ['foo'], {encoding: 'buffer'}));1935+expectAssignable<{stdout: string}>($.sync({})('unicorns'));1936+expectAssignable<{stdout: string}>($({}).sync('unicorns'));1937+expectAssignable<{stdout: Uint8Array}>($.sync({encoding: 'buffer'})('unicorns'));1938+expectAssignable<{stdout: Uint8Array}>($({encoding: 'buffer'}).sync('unicorns'));1939+expectAssignable<{stdout: Uint8Array}>($.sync({})({encoding: 'buffer'})('unicorns'));1940+expectAssignable<{stdout: Uint8Array}>($({})({encoding: 'buffer'}).sync('unicorns'));1941+expectAssignable<{stdout: Uint8Array}>($.sync({encoding: 'buffer'})({})('unicorns'));1942+expectAssignable<{stdout: Uint8Array}>($({encoding: 'buffer'}).sync({})('unicorns'));1943+expectAssignable<{stdout: string}>($.sync({})`unicorns`);1944+expectAssignable<{stdout: string}>($({}).sync`unicorns`);1945+expectAssignable<{stdout: Uint8Array}>($.sync({encoding: 'buffer'})`unicorns`);1946+expectAssignable<{stdout: Uint8Array}>($({encoding: 'buffer'}).sync`unicorns`);1947+expectAssignable<{stdout: Uint8Array}>($.sync({})({encoding: 'buffer'})`unicorns`);1948+expectAssignable<{stdout: Uint8Array}>($({})({encoding: 'buffer'}).sync`unicorns`);1949+expectAssignable<{stdout: Uint8Array}>($.sync({encoding: 'buffer'})({})`unicorns`);1950+expectAssignable<{stdout: Uint8Array}>($({encoding: 'buffer'}).sync({})`unicorns`);1951+expectType<ExecaSyncResult<{}>>($.sync`${'unicorns'}`);1952+expectType<ExecaSyncResult<{}>>($.sync`unicorns ${'foo'}`);1953+expectType<ExecaSyncResult<{}>>($.sync`unicorns ${'foo'} ${'bar'}`);1954+expectType<ExecaSyncResult<{}>>($.sync`unicorns ${1}`);1955+expectType<ExecaSyncResult<{}>>($.sync`unicorns ${['foo', 'bar']}`);1956+expectType<ExecaSyncResult<{}>>($.sync`unicorns ${[1, 2]}`);1957+expectType<ExecaSyncResult<{}>>($.sync`unicorns ${$.sync`echo foo`}`);1958+expectType<ExecaSyncResult<{}>>($.sync`unicorns ${[$.sync`echo foo`, 'bar']}`);1959+expectType<ExecaSyncResult<{}>>($.sync`unicorns ${false.toString()}`);1960+expectError($.sync`unicorns ${false}`);1961+1962+expectError($.s());1963+expectError($.s(true));1964+expectError($.s(['unicorns', 'arg']));1965+expectType<ExecaSyncResult<{}>>($.s('unicorns'));1966+expectType<ExecaSyncResult<{}>>($.s(fileUrl));1967+expectType<ExecaSyncResult<{}>>($.s('unicorns', []));1968+expectType<ExecaSyncResult<{}>>($.s('unicorns', ['foo']));1969+expectType<ExecaSyncResult<{}>>($.s('unicorns', {}));1970+expectType<ExecaSyncResult<{}>>($.s('unicorns', [], {}));1971+expectError($.s('unicorns', 'foo'));1972+expectError($.s('unicorns', [true]));1973+expectError($.s('unicorns', [], []));1974+expectError($.s('unicorns', {other: true}));1975+expectType<ExecaSyncResult<{}>>($.s`unicorns`);1976+expectAssignable<typeof $.s>($.s({}));1977+expectType<ExecaSyncResult<{}>>($.s({})('unicorns'));1978+expectType<ExecaSyncResult<{}>>($({}).s('unicorns'));1979+expectType<ExecaSyncResult<{}>>($.s({})`unicorns`);1980+expectType<ExecaSyncResult<{}>>($({}).s`unicorns`);1981+expectType<ExecaSyncResult<{}>>($.s('unicorns'));1982+expectType<ExecaSyncResult<{}>>($.s`unicorns`);1983+expectAssignable<{stdout: string}>($.s('unicorns'));1984+expectAssignable<{stdout: Uint8Array}>($.s('unicorns', {encoding: 'buffer'}));1985+expectAssignable<{stdout: string}>($.s('unicorns', ['foo']));1986+expectAssignable<{stdout: Uint8Array}>($.s('unicorns', ['foo'], {encoding: 'buffer'}));1987+expectAssignable<{stdout: string}>($.s({})('unicorns'));1988+expectAssignable<{stdout: string}>($({}).s('unicorns'));1989+expectAssignable<{stdout: Uint8Array}>($.s({encoding: 'buffer'})('unicorns'));1990+expectAssignable<{stdout: Uint8Array}>($({encoding: 'buffer'}).s('unicorns'));1991+expectAssignable<{stdout: Uint8Array}>($.s({})({encoding: 'buffer'})('unicorns'));1992+expectAssignable<{stdout: Uint8Array}>($({})({encoding: 'buffer'}).s('unicorns'));1993+expectAssignable<{stdout: Uint8Array}>($.s({encoding: 'buffer'})({})('unicorns'));1994+expectAssignable<{stdout: Uint8Array}>($({encoding: 'buffer'}).s({})('unicorns'));1995+expectAssignable<{stdout: string}>($.s({})`unicorns`);1996+expectAssignable<{stdout: string}>($({}).s`unicorns`);1997+expectAssignable<{stdout: Uint8Array}>($.s({encoding: 'buffer'})`unicorns`);1998+expectAssignable<{stdout: Uint8Array}>($({encoding: 'buffer'}).s`unicorns`);1999+expectAssignable<{stdout: Uint8Array}>($.s({})({encoding: 'buffer'})`unicorns`);2000+expectAssignable<{stdout: Uint8Array}>($({})({encoding: 'buffer'}).s`unicorns`);2001+expectAssignable<{stdout: Uint8Array}>($.s({encoding: 'buffer'})({})`unicorns`);2002+expectAssignable<{stdout: Uint8Array}>($({encoding: 'buffer'}).s({})`unicorns`);2003+expectType<ExecaSyncResult<{}>>($.s`${'unicorns'}`);2004+expectType<ExecaSyncResult<{}>>($.s`unicorns ${'foo'}`);2005+expectType<ExecaSyncResult<{}>>($.s`unicorns ${'foo'} ${'bar'}`);2006+expectType<ExecaSyncResult<{}>>($.s`unicorns ${1}`);2007+expectType<ExecaSyncResult<{}>>($.s`unicorns ${['foo', 'bar']}`);2008+expectType<ExecaSyncResult<{}>>($.s`unicorns ${[1, 2]}`);2009+expectType<ExecaSyncResult<{}>>($.s`unicorns ${$.s`echo foo`}`);2010+expectType<ExecaSyncResult<{}>>($.s`unicorns ${[$.s`echo foo`, 'bar']}`);2011+expectType<ExecaSyncResult<{}>>($.s`unicorns ${false.toString()}`);2012+expectError($.s`unicorns ${false}`);2013+2014+expectError(execaNode());2015+expectError(execaNode(true));2016 expectError(execaNode(['unicorns', 'arg']));2017 expectAssignable<ExecaSubprocess>(execaNode('unicorns'));2018+expectAssignable<ExecaSubprocess>(execaNode(fileUrl));2019+expectAssignable<ExecaSubprocess>(execaNode('unicorns', []));2020+expectAssignable<ExecaSubprocess>(execaNode('unicorns', ['foo']));2021+expectAssignable<ExecaSubprocess>(execaNode('unicorns', {}));2022+expectAssignable<ExecaSubprocess>(execaNode('unicorns', [], {}));2023+expectError(execaNode('unicorns', 'foo'));2024+expectError(execaNode('unicorns', [true]));2025+expectError(execaNode('unicorns', [], []));2026+expectError(execaNode('unicorns', {other: true}));2027+expectAssignable<ExecaSubprocess>(execaNode`unicorns`);2028+expectAssignable<typeof execaNode>(execaNode({}));2029+expectAssignable<ExecaSubprocess>(execaNode({})('unicorns'));2030+expectAssignable<ExecaSubprocess>(execaNode({})`unicorns`);1730-expectType<ExecaResult>(await execaNode('unicorns'));1731-expectType<ExecaResult>(await execaNode(fileUrl));2031+expectType<ExecaResult<{}>>(await execaNode('unicorns'));2032+expectType<ExecaResult<{}>>(await execaNode`unicorns`);2033 expectAssignable<{stdout: string}>(await execaNode('unicorns'));2034 expectAssignable<{stdout: Uint8Array}>(await execaNode('unicorns', {encoding: 'buffer'}));2035 expectAssignable<{stdout: string}>(await execaNode('unicorns', ['foo']));2036 expectAssignable<{stdout: Uint8Array}>(await execaNode('unicorns', ['foo'], {encoding: 'buffer'}));2037+expectAssignable<{stdout: string}>(await execaNode({})('unicorns'));2038+expectAssignable<{stdout: Uint8Array}>(await execaNode({encoding: 'buffer'})('unicorns'));2039+expectAssignable<{stdout: Uint8Array}>(await execaNode({})({encoding: 'buffer'})('unicorns'));2040+expectAssignable<{stdout: Uint8Array}>(await execaNode({encoding: 'buffer'})({})('unicorns'));2041+expectAssignable<{stdout: string}>(await execaNode({})`unicorns`);2042+expectAssignable<{stdout: Uint8Array}>(await execaNode({encoding: 'buffer'})`unicorns`);2043+expectAssignable<{stdout: Uint8Array}>(await execaNode({})({encoding: 'buffer'})`unicorns`);2044+expectAssignable<{stdout: Uint8Array}>(await execaNode({encoding: 'buffer'})({})`unicorns`);2045+expectType<ExecaResult<{}>>(await execaNode`${'unicorns'}`);2046+expectType<ExecaResult<{}>>(await execaNode`unicorns ${'foo'}`);2047+expectType<ExecaResult<{}>>(await execaNode`unicorns ${'foo'} ${'bar'}`);2048+expectType<ExecaResult<{}>>(await execaNode`unicorns ${1}`);2049+expectType<ExecaResult<{}>>(await execaNode`unicorns ${['foo', 'bar']}`);2050+expectType<ExecaResult<{}>>(await execaNode`unicorns ${[1, 2]}`);2051+expectType<ExecaResult<{}>>(await execaNode`unicorns ${await execaNode`echo foo`}`);2052+expectError(await execaNode`unicorns ${execaNode`echo foo`}`);2053+expectType<ExecaResult<{}>>(await execaNode`unicorns ${[await execaNode`echo foo`, 'bar']}`);2054+expectError(await execaNode`unicorns ${[execaNode`echo foo`, 'bar']}`);2055+expectType<ExecaResult<{}>>(await execaNode`unicorns ${true.toString()}`);2056+expectError(await execaNode`unicorns ${true}`);2057 2058 expectAssignable<ExecaSubprocess>(execaNode('unicorns', {nodePath: './node'}));2059 expectAssignable<ExecaSubprocess>(execaNode('unicorns', {nodePath: fileUrl}));1739-2060 expectAssignable<{stdout: string}>(await execaNode('unicorns', {nodeOptions: ['--async-stack-traces']}));2061 expectAssignable<{stdout: Uint8Array}>(await execaNode('unicorns', {nodeOptions: ['--async-stack-traces'], encoding: 'buffer'}));2062 expectAssignable<{stdout: string}>(await execaNode('unicorns', ['foo'], {nodeOptions: ['--async-stack-traces']}));2063 expectAssignable<{stdout: Uint8Array}>(await execaNode('unicorns', ['foo'], {nodeOptions: ['--async-stack-traces'], encoding: 'buffer'}));1744-1745-expectAssignable<ExecaSubprocess>($`unicorns`);1746-expectAssignable<ExecaResult>(await $`unicorns`);1747-expectAssignable<ExecaSyncResult>($.sync`unicorns`);1748-expectAssignable<ExecaSyncResult>($.s`unicorns`);1749-1750-expectAssignable<ExecaSubprocess>($({})`unicorns`);1751-expectAssignable<{stdout: string}>(await $({})`unicorns`);1752-expectAssignable<{stdout: string}>($({}).sync`unicorns`);1753-1754-expectAssignable<ExecaSubprocess>($({})`unicorns foo`);1755-expectAssignable<{stdout: string}>(await $({})`unicorns foo`);1756-expectAssignable<{stdout: string}>($({}).sync`unicorns foo`);1757-1758-expectAssignable<ExecaSubprocess>($({encoding: 'buffer'})`unicorns`);1759-expectAssignable<{stdout: Uint8Array}>(await $({encoding: 'buffer'})`unicorns`);1760-expectAssignable<{stdout: Uint8Array}>($({encoding: 'buffer'}).sync`unicorns`);1761-1762-expectAssignable<ExecaSubprocess>($({encoding: 'buffer'})`unicorns foo`);1763-expectAssignable<{stdout: Uint8Array}>(await $({encoding: 'buffer'})`unicorns foo`);1764-expectAssignable<{stdout: Uint8Array}>($({encoding: 'buffer'}).sync`unicorns foo`);1765-1766-expectAssignable<ExecaSubprocess>($({encoding: 'buffer'})({})`unicorns`);1767-expectAssignable<{stdout: Uint8Array}>(await $({encoding: 'buffer'})({})`unicorns`);1768-expectAssignable<{stdout: Uint8Array}>($({encoding: 'buffer'})({}).sync`unicorns`);1769-1770-expectAssignable<ExecaSubprocess>($({encoding: 'buffer'})({})`unicorns foo`);1771-expectAssignable<{stdout: Uint8Array}>(await $({encoding: 'buffer'})({})`unicorns foo`);1772-expectAssignable<{stdout: Uint8Array}>($({encoding: 'buffer'})({}).sync`unicorns foo`);1773-1774-expectAssignable<ExecaSubprocess>($({})({encoding: 'buffer'})`unicorns`);1775-expectAssignable<{stdout: Uint8Array}>(await $({})({encoding: 'buffer'})`unicorns`);1776-expectAssignable<{stdout: Uint8Array}>($({})({encoding: 'buffer'}).sync`unicorns`);1777-1778-expectAssignable<ExecaSubprocess>($({})({encoding: 'buffer'})`unicorns foo`);1779-expectAssignable<{stdout: Uint8Array}>(await $({})({encoding: 'buffer'})`unicorns foo`);1780-expectAssignable<{stdout: Uint8Array}>($({})({encoding: 'buffer'}).sync`unicorns foo`);1781-1782-expectAssignable<ExecaResult>(await $`unicorns ${'foo'}`);1783-expectAssignable<ExecaSyncResult>($.sync`unicorns ${'foo'}`);1784-expectAssignable<ExecaResult>(await $`unicorns ${1}`);1785-expectAssignable<ExecaSyncResult>($.sync`unicorns ${1}`);1786-expectAssignable<ExecaResult>(await $`unicorns ${['foo', 'bar']}`);1787-expectAssignable<ExecaSyncResult>($.sync`unicorns ${['foo', 'bar']}`);1788-expectAssignable<ExecaResult>(await $`unicorns ${[1, 2]}`);1789-expectAssignable<ExecaSyncResult>($.sync`unicorns ${[1, 2]}`);1790-expectAssignable<ExecaResult>(await $`unicorns ${await $`echo foo`}`);1791-expectError<ExecaResult>(await $`unicorns ${$`echo foo`}`);1792-expectAssignable<ExecaSyncResult>($.sync`unicorns ${$.sync`echo foo`}`);1793-expectAssignable<ExecaResult>(await $`unicorns ${[await $`echo foo`, 'bar']}`);1794-expectError<ExecaResult>(await $`unicorns ${[$`echo foo`, 'bar']}`);1795-expectAssignable<ExecaSyncResult>($.sync`unicorns ${[$.sync`echo foo`, 'bar']}`);1796-expectAssignable<ExecaResult>(await $`unicorns ${true.toString()}`);1797-expectAssignable<ExecaSyncResult>($.sync`unicorns ${false.toString()}`);1798-expectError<ExecaResult>(await $`unicorns ${true}`);1799-expectError<ExecaSyncResult>($.sync`unicorns ${false}`);modified:readme.md+88 added-79 removed
45 unmodified lines46 ## Why47 48 This package improves [`child_process`](https://nodejs.org/api/child_process.html) methods with:49 50-- [Promise interface](#execacommandcommand-options).51-- [Scripts interface](#scripts-interface), like `zx`.50+- [Promise interface](#execafile-arguments-options).51+- [Script interface](docs/scripts.md) and [template strings](#template-string-syntax), like `zx`.52 - Improved [Windows support](https://github.com/IndigoUnited/node-cross-spawn#why), including [shebang](https://en.wikipedia.org/wiki/Shebang_(Unix)) binaries.53 - Executes [locally installed binaries](#preferlocal) without `npx`.54 - [Cleans up](#cleanup) subprocesses when the current process ends.55 - Redirect [`stdin`](#stdin)/[`stdout`](#stdout-1)/[`stderr`](#stderr-1) from/to files, streams, iterables, strings, `Uint8Array` or [objects](docs/transform.md#object-mode).2 unmodified lines58 - [Fail-safe subprocess termination](#forcekillafterdelay).59 - Get [interleaved output](#all) from `stdout` and `stderr` similar to what is printed on the terminal.60 - [Strips the final newline](#stripfinalnewline) from the output so you don't have to do `stdout.trim()`.61 - Convenience methods to pipe subprocesses' [input](#input) and [output](#redirect-output-to-a-file).62-- Can specify file and arguments [as a single string](#execacommandcommand-options) without a shell.62 - [Verbose mode](#verbose-mode) for debugging.63 - More descriptive errors.64 - Higher max buffer: 100 MB instead of 1 MB.65 14 unmodified lines80 console.log(stdout);81 //=> 'unicorns'82 ```83 85-### Scripts interface84+#### Global/shared options85 87-For more information about Execa scripts, please see [this page](docs/scripts.md).86+```js87+import {execa as execa_} from 'execa';88 89+const execa = execa_({verbose: 'full'});90+91+await execa('echo', ['unicorns']);92+//=> 'unicorns'93+```94+95+### Template string syntax96+97 #### Basic98 99 ```js92-import {$} from 'execa';100+import {execa} from 'execa';101 94-const branch = await $`git branch --show-current`;95-await $`dep deploy --branch=${branch}`;102+const arg = 'unicorns'103+const {stdout} = await execa`echo ${arg} & rainbows!`;104+console.log(stdout);105+//=> 'unicorns & rainbows!'106 ```107 108 #### Multiple arguments109 110 ```js101-import {$} from 'execa';111+import {execa} from 'execa';112 113 const args = ['unicorns', '&', 'rainbows!'];104-const {stdout} = await $`echo ${args}`;114+const {stdout} = await execa`echo ${args}`;115 console.log(stdout);116 //=> 'unicorns & rainbows!'117 ```118 119 #### With options120 121 ```js112-import {$} from 'execa';122+import {execa} from 'execa';123 114-await $({stdio: 'inherit'})`echo unicorns`;124+await execa({verbose: 'full'})`echo unicorns`;125 //=> 'unicorns'126 ```127 118-#### Global/shared options128+### Scripts129 120-```js121-import {$ as $_} from 'execa';130+For more information about Execa scripts, please see [this page](docs/scripts.md).131 123-const $ = $_({stdio: 'inherit'});132+#### Basic133 125-await $`echo unicorns`;126-//=> 'unicorns'127-128-await $`echo rainbows`;129-//=> 'rainbows'130-```131-132-#### Piping133-134 ```js135 import {$} from 'execa';136 137-await $`npm run build`138- .pipe`sort`139- .pipe`head -n2`;137+const branch = await $`git branch --show-current`;138+await $`dep deploy --branch=${branch}`;139 ```140 141 #### Verbose mode142 63 unmodified lines206 console.log(pipedFrom[0]); // Result of `sort`207 console.log(pipedFrom[0].pipedFrom[0]); // Result of `npm run build`208 ```209 210+#### Pipe with template strings211+212+```js213+import {execa} from 'execa';214+215+await execa`npm run build`216+ .pipe`sort`217+ .pipe`head -n2`;218+```219+220 #### Iterate over output lines221 222 ```js223 import {execa} from 'execa';224 216-for await (const line of execa('npm', ['run', 'build'])) {225+for await (const line of execa`npm run build`)) {226 if (line.includes('ERROR')) {227 console.log(line);228 }229 }50 unmodified lines280 #### execa(file, arguments?, options?)281 282 `file`: `string | URL`\283 `arguments`: `string[]`\275-`options`: [`Options`](#options-1)\284+`options`: [`Options`](#options)\285 _Returns_: [`Subprocess`](#subprocess)286 287 Executes a command using `file ...arguments`.288 280-Arguments are [automatically escaped](#shell-syntax). They can contain any character, including spaces.289+Arguments are [automatically escaped](#shell-syntax). They can contain any character, including spaces, tabs and newlines.290 282-This is the preferred method when executing single commands.291+#### execa\`command\`292+#### execa(options)\`command\`293 284-#### $\`command\`285-#### $(options)\`command\`286-294 `command`: `string`\288-`options`: [`Options`](#options-1)\295+`options`: [`Options`](#options)\296 _Returns_: [`Subprocess`](#subprocess)297 291-Executes a command. The `command` string includes both the `file` and its `arguments`.298+Executes a command. `command` is a [template string](#template-string-syntax) and includes both the `file` and its `arguments`.299 293-Arguments are [automatically escaped](#shell-syntax). They can contain any character, but spaces, tabs and newlines must use `${}` like `` $`echo ${'has space'}` ``.300+The `command` template string can inject any `${value}` with the following types: string, number, [`subprocess`](#subprocess) or an array of those types. For example: `` execa`echo one ${'two'} ${3} ${['four', 'five']}` ``. For `${subprocess}`, the subprocess's [`stdout`](#stdout) is used.301 295-This is the preferred method when executing multiple commands in a script file.302+Arguments are [automatically escaped](#shell-syntax). They can contain any character, but spaces, tabs and newlines must use `${}` like `` execa`echo ${'has space'}` ``.303 297-The `command` string can inject any `${value}` with the following types: string, number, [`subprocess`](#subprocess) or an array of those types. For example: `` $`echo one ${'two'} ${3} ${['four', 'five']}` ``. For `${subprocess}`, the subprocess's `stdout` is used.304+The `command` template string can use [multiple lines and indentation](docs/scripts.md#multiline-commands).305 299-The `command` string can use [multiple lines and indentation](docs/scripts.md#multiline-commands).306+#### execa(options)307 301-For more information, please see [this section](#scripts-interface) and [this page](docs/scripts.md).308+`options`: [`Options`](#options)\309+_Returns_: [`execa`](#execafile-arguments-options)310 303-#### $(options)311+Returns a new instance of Execa but with different default [`options`](#options). Consecutive calls are merged to previous ones.312 305-`options`: [`Options`](#options-1)\306-_Returns_: [`$`](#command)313+This allows setting global options or [sharing options](#globalshared-options) between multiple commands.314 308-Returns a new instance of [`$`](#command) but with different default [`options`](#options-1). Consecutive calls are merged to previous ones.315+#### execaSync(file, arguments?, options?)316+#### execaSync\`command\`317 310-This can be used to either:311-- Set options for a specific command: `` $(options)`command` ``312-- Share options for multiple commands: `` const $$ = $(options); $$`command`; $$`otherCommand`; ``318+Same as [`execa()`](#execafile-arguments-options) but synchronous.319 314-#### execaCommand(command, options?)320+Returns or throws a [`subprocessResult`](#subprocessResult). The [`subprocess`](#subprocess) is not returned: its methods and properties are not available. This includes [`.kill()`](https://nodejs.org/api/child_process.html#subprocesskillsignal), [`.pid`](https://nodejs.org/api/child_process.html#subprocesspid), [`.pipe()`](#pipefile-arguments-options) and the [`.stdin`/`.stdout`/`.stderr`](https://nodejs.org/api/child_process.html#subprocessstdout) streams.321 322+Cannot use the following options: [`all`](#all-2), [`cleanup`](#cleanup), [`buffer`](#buffer), [`detached`](#detached), [`ipc`](#ipc), [`serialization`](#serialization), [`cancelSignal`](#cancelsignal), [`lines`](#lines) and [`verbose: 'full'`](#verbose). Also, the [`stdin`](#stdin), [`stdout`](#stdout-1), [`stderr`](#stderr-1), [`stdio`](#stdio-1) and [`input`](#input) options cannot be an array, an iterable, a [transform](docs/transform.md) or a web stream. Node.js streams [must have a file descriptor](#redirect-a-nodejs-stream-fromto-stdinstdoutstderr) unless the `input` option is used.323+324+#### $(file, arguments?, options?)325+326+`file`: `string | URL`\316-`command`: `string`\317-`options`: [`Options`](#options-1)\327+`arguments`: `string[]`\328+`options`: [`Options`](#options)\329 _Returns_: [`Subprocess`](#subprocess)330 320-Executes a command. The `command` string includes both the `file` and its `arguments`.331+Same as [`execa()`](#execafile-arguments-options) but using the [`stdin: 'inherit'`](#stdin) and [`preferLocal: true`](#preferlocal) options.332 322-Arguments are [automatically escaped](#shell-syntax). They can contain any character, but spaces must be escaped with a backslash like `execaCommand('echo has\\ space')`.333+Just like `execa()`, this can use the [template string syntax](#execacommand) or [bind options](#execaoptions). It can also be [run synchronously](#execasyncfile-arguments-options) using `$.sync()` or `$.s()`.334 324-This is the preferred method when executing a user-supplied `command` string, such as in a REPL.335+This is the preferred method when executing multiple commands in a script file. For more information, please see [this page](docs/scripts.md).336 337 #### execaNode(scriptPath, arguments?, options?)338 328-`file`: `string | URL`\339+`scriptPath`: `string | URL`\340 `arguments`: `string[]`\330-`options`: [`Options`](#options-1)\341+`options`: [`Options`](#options)\342 _Returns_: [`Subprocess`](#subprocess)343 333-Same as [`execa()`](#execacommandcommand-options) but using the [`node`](#node) option.334-344+Same as [`execa()`](#execafile-arguments-options) but using the [`node: true`](#node) option.345 Executes a Node.js file using `node scriptPath ...arguments`.346 347+Just like `execa()`, this can use the [template string syntax](#execacommand) or [bind options](#execaoptions).348+349 This is the preferred method when executing Node.js files.350 339-#### execaSync(file, arguments?, options?)340-#### execaCommandSync(command, options?)341-#### $.sync\`command\`342-#### $.s\`command\`343-#### $.sync(options)\`command\`344-#### $.s(options)\`command\`351+#### execaCommand(command, options?)352 346-Same as [`execa()`](#execacommandcommand-options), [`execaCommand()`](#execacommand-command-options), [$\`command\`](#command) but synchronous.353+`command`: `string`\354+`options`: [`Options`](#options)\355+_Returns_: [`Subprocess`](#subprocess)356 348-Cannot use the following options: [`all`](#all-2), [`cleanup`](#cleanup), [`buffer`](#buffer), [`detached`](#detached), [`ipc`](#ipc), [`serialization`](#serialization), [`cancelSignal`](#cancelsignal), [`lines`](#lines) and [`verbose: 'full'`](#verbose). Also, the [`stdin`](#stdin), [`stdout`](#stdout-1), [`stderr`](#stderr-1), [`stdio`](#stdio-1) and [`input`](#input) options cannot be an array, an iterable, a [transform](docs/transform.md) or a web stream. Node.js streams [must have a file descriptor](#redirect-a-nodejs-stream-fromto-stdinstdoutstderr) unless the `input` option is used.357+[`execa`](#execafile-arguments-options) with the [template string syntax](#execacommand) allows the `file` or the `arguments` to be user-defined (by injecting them with `${}`). However, if _both_ the `file` and the `arguments` are user-defined, _and_ those are supplied as a single string, then `execaCommand(command)` must be used instead.358 350-Returns or throws a [`subprocessResult`](#subprocessResult). The [`subprocess`](#subprocess) is not returned: its methods and properties are not available. This includes [`.kill()`](https://nodejs.org/api/child_process.html#subprocesskillsignal), [`.pid`](https://nodejs.org/api/child_process.html#subprocesspid), [`.pipe()`](#pipefile-arguments-options) and the [`.stdin`/`.stdout`/`.stderr`](https://nodejs.org/api/child_process.html#subprocessstdout) streams.359+This is only intended for very specific cases, such as a REPL. This should be avoided otherwise.360 361+Just like `execa()`, this can [bind options](#execaoptions). It can also be [run synchronously](#execasyncfile-arguments-options) using `execaCommandSync()`.362+363+Arguments are [automatically escaped](#shell-syntax). They can contain any character, but spaces must be escaped with a backslash like `execaCommand('echo has\\ space')`.364+365 ### Shell syntax366 367 For all the [methods above](#methods), no shell interpreter (Bash, cmd.exe, etc.) is used unless the [`shell` option](#shell) is set. This means shell-specific characters and expressions (`$variable`, `&&`, `||`, `;`, `|`, etc.) have no special meaning and do not need to be escaped.368 16 unmodified lines385 #### pipe(file, arguments?, options?)386 387 `file`: `string | URL`\388 `arguments`: `string[]`\376-`options`: [`Options`](#options-1) and [`PipeOptions`](#pipeoptions)\389+`options`: [`Options`](#options) and [`PipeOptions`](#pipeoptions)\390 _Returns_: [`Promise<SubprocessResult>`](#subprocessresult)391 392 [Pipe](https://nodejs.org/api/stream.html#readablepipedestination-options) the subprocess' `stdout` to a second Execa subprocess' `stdin`. This resolves with that second subprocess' [result](#subprocessresult). If either subprocess is rejected, this is rejected with that subprocess' [error](#execaerror) instead.393 381-This follows the same syntax as [`execa(file, arguments?, options?)`](#execafile-arguments-options) except both [regular options](#options-1) and [pipe-specific options](#pipeoptions) can be specified.394+This follows the same syntax as [`execa(file, arguments?, options?)`](#execafile-arguments-options) except both [regular options](#options) and [pipe-specific options](#pipeoptions) can be specified.395 396 This can be called multiple times to chain a series of subprocesses.397 398 Multiple subprocesses can be piped to the same subprocess. Conversely, the same subprocess can be piped to multiple other subprocesses.399 387-This is usually the preferred method to pipe subprocesses.388-400 #### pipe\`command\`401 #### pipe(options)\`command\`402 403 `command`: `string`\393-`options`: [`Options`](#options-1) and [`PipeOptions`](#pipeoptions)\404+`options`: [`Options`](#options) and [`PipeOptions`](#pipeoptions)\405 _Returns_: [`Promise<SubprocessResult>`](#subprocessresult)406 396-Like [`.pipe(file, arguments?, options?)`](#pipefile-arguments-options) but using a [`command` template string](docs/scripts.md#piping-stdout-to-another-command) instead. This follows the same syntax as [`$`](#command).407+Like [`.pipe(file, arguments?, options?)`](#pipefile-arguments-options) but using a [`command` template string](docs/scripts.md#piping-stdout-to-another-command) instead. This follows the same syntax as `execa` [template strings](#execacommand).408 398-This is the preferred method to pipe subprocesses when using [`$`](#command).399-409 #### pipe(secondSubprocess, pipeOptions?)410 411 `secondSubprocess`: [`execa()` return value](#subprocess)\412 `pipeOptions`: [`PipeOptions`](#pipeoptions)\155 unmodified lines568 #### escapedCommand569 570 Type: `string`571 563-Same as [`command`](#command-1) but escaped.572+Same as [`command`](#command) but escaped.573 574 Unlike `command`, control characters are escaped, which makes it safe to print in a terminal.575 576 This can also be copied and pasted into a shell, for debugging purposes.210 unmodified lines787 788 #### preferLocal789 790 Type: `boolean`\782-Default: `true` with [`$`](#command), `false` otherwise791+Default: `true` with [`$`](#file-arguments-options), `false` otherwise792 793 Prefer locally installed binaries when looking for a binary to execute.\794 If you `$ npm install foo`, you can then `execa('foo')`.795 74 unmodified lines870 871 #### stdin872 873 Type: `string | number | stream.Readable | ReadableStream | URL | Uint8Array | Iterable<string> | Iterable<Uint8Array> | Iterable<unknown> | AsyncIterable<string> | AsyncIterable<Uint8Array> | AsyncIterable<unknown> | GeneratorFunction<string> | GeneratorFunction<Uint8Array> | GeneratorFunction<unknown>| AsyncGeneratorFunction<string> | AsyncGeneratorFunction<Uint8Array> | AsyncGeneratorFunction<unknown>` (or a tuple of those types)\865-Default: `inherit` with [`$`](#command), `pipe` otherwise874+Default: `inherit` with [`$`](#file-arguments-options), `pipe` otherwise875 876 [How to setup](https://nodejs.org/api/child_process.html#child_process_options_stdio) the subprocess' standard input. This can be:877 - `'pipe'`: Sets [`subprocess.stdin`](https://nodejs.org/api/child_process.html#subprocessstdin) stream.878 - `'overlapped'`: Like `'pipe'` but asynchronous on Windows.347 unmodified lines