script.js
This file
Path
lib/script.js
206 lines · 6.2 KiB · JavaScript
Last changed by
Fix errors thrown by `.pipe()` (#854)ehmickybefore adoption46ba4b4
History of this fileTake it
Improve input validation (#838)ehmickybefore adoption8ee137c
line 1why, one step back1import isPlainObject from 'is-plain-obj';Fix errors thrown by `.pipe()` (#854)ehmickybefore adoption46ba4b4
line 2why, one step back2import {isBinary, binaryToString, isChildProcess} from './utils.js';Split files (#837)ehmickybefore adoption672c2d7
lines 3–4why, one step back3import {execa} from './async.js';4import {execaSync} from './sync.js';Fix errors thrown by `.pipe()` (#854)ehmickybefore adoption46ba4b4
line 5why, one step back5import {PROCESS_OPTIONS} from './pipe/validate.js';Split files (#791)ehmickybefore adoption932fb26
line 6why, one step back6Split files (#837)ehmickybefore adoption672c2d7
lines 7–8why, one step back7const create$ = options => {8 function $(templatesOrOptions, ...expressions) {Improve input validation (#838)ehmickybefore adoption8ee137c
line 9why, one step back9 if (isPlainObject(templatesOrOptions)) {Split files (#837)ehmickybefore adoption672c2d7
lines 10–11why, one step back10 return create$({...options, ...templatesOrOptions});11 }Split files (#791)ehmickybefore adoption932fb26
line 12why, one step back12Improve input validation (#838)ehmickybefore adoption8ee137c
lines 13–16why, one step back13 if (!Array.isArray(templatesOrOptions)) {14 throw new TypeError('Please use either $(option) or $`command`.');15 }16Split files (#837)ehmickybefore adoption672c2d7
line 17why, one step back17 const [file, ...args] = parseTemplates(templatesOrOptions, expressions);`.pipe()` shortcut for `$` (#840)ehmickybefore adoption316f562
line 18why, one step back18 const childProcess = execa(file, args, normalizeScriptOptions(options));Fix calling script `.pipe` multiple times (#846)ehmickybefore adoptionbd547e4
line 19why, one step back19 return scriptWithPipe(childProcess);Split files (#791)ehmickybefore adoption932fb26
lines 20–21why, one step back20 }21Split files (#837)ehmickybefore adoption672c2d7
line 22why, one step back22 $.sync = (templates, ...expressions) => {Improve input validation (#838)ehmickybefore adoption8ee137c
line 23why, one step back23 if (isPlainObject(templates)) {Split files (#837)ehmickybefore adoption672c2d7
line 24why, one step back24 throw new TypeError('Please use $(options).sync`command` instead of $.sync(options)`command`.');Improve input validation (#838)ehmickybefore adoption8ee137c
lines 25–28why, one step back25 }2627 if (!Array.isArray(templates)) {28 throw new TypeError('A template string must be used: $.sync`command`.');Split files (#791)ehmickybefore adoption932fb26
lines 29–30why, one step back29 }30Split files (#837)ehmickybefore adoption672c2d7
lines 31–33why, one step back31 const [file, ...args] = parseTemplates(templates, expressions);32 return execaSync(file, args, normalizeScriptOptions(options));33 };Split files (#791)ehmickybefore adoption932fb26
line 34why, one step back34Split files (#837)ehmickybefore adoption672c2d7
line 35why, one step back35 $.s = $.sync;Split files (#791)ehmickybefore adoption932fb26
line 36why, one step back36Split files (#837)ehmickybefore adoption672c2d7
line 37why, one step back37 return $;Split files (#791)ehmickybefore adoption932fb26
lines 38–39why, one step back38};39Split files (#837)ehmickybefore adoption672c2d7
line 40why, one step back40export const $ = create$();Split files (#791)ehmickybefore adoption932fb26
line 41why, one step back41Fix calling script `.pipe` multiple times (#846)ehmickybefore adoptionbd547e4
lines 42–49why, one step back42const scriptWithPipe = returnValue => {43 const originalPipe = returnValue.pipe.bind(returnValue);44 const pipeMethod = (...args) => scriptWithPipe(originalPipe(...args));45 returnValue.pipe = scriptPipe.bind(undefined, pipeMethod, {});46 return returnValue;47};4849const scriptPipe = (pipeMethod, options, firstArgument, ...args) => {Fix errors thrown by `.pipe()` (#854)ehmickybefore adoption46ba4b4
line 50why, one step back50 if (PROCESS_OPTIONS.has(firstArgument)) {`.pipe()` shortcut for `$` (#840)ehmickybefore adoption316f562
lines 51–54why, one step back51 if (Object.keys(options).length > 0) {52 throw new TypeError('Please use .pipe(options)`command` or .pipe($(options)`command`) instead of .pipe(options)($`command`).');53 }54Fix calling script `.pipe` multiple times (#846)ehmickybefore adoptionbd547e4
line 55why, one step back55 return pipeMethod(firstArgument, ...args);`.pipe()` shortcut for `$` (#840)ehmickybefore adoption316f562
lines 56–58why, one step back56 }5758 if (isPlainObject(firstArgument)) {Fix calling script `.pipe` multiple times (#846)ehmickybefore adoptionbd547e4
line 59why, one step back59 return scriptPipe.bind(undefined, pipeMethod, {...options, ...firstArgument});`.pipe()` shortcut for `$` (#840)ehmickybefore adoption316f562
lines 60–66why, one step back60 }6162 if (!Array.isArray(firstArgument)) {63 throw new TypeError('The first argument must be a template string, an options object, or an Execa child process.');64 }6566 const childProcess = create$({...options, stdin: 'pipe'})(firstArgument, ...args);Fix calling script `.pipe` multiple times (#846)ehmickybefore adoptionbd547e4
line 67why, one step back67 return pipeMethod(childProcess, options);`.pipe()` shortcut for `$` (#840)ehmickybefore adoption316f562
lines 68–69why, one step back68};69Split files (#837)ehmickybefore adoption672c2d7
lines 70–71why, one step back70const parseTemplates = (templates, expressions) => {71 let tokens = [];Split files (#791)ehmickybefore adoption932fb26
line 72why, one step back72Split files (#837)ehmickybefore adoption672c2d7
lines 73–76why, one step back73 for (const [index, template] of templates.entries()) {74 tokens = parseTemplate({templates, expressions, tokens, index, template});75 }76Allow newlines in `$` (#843)ehmickybefore adoption1315486
lines 77–80why, one step back77 if (tokens.length === 0) {78 throw new TypeError('Template script must not be empty');79 }80Split files (#837)ehmickybefore adoption672c2d7
lines 81–83why, one step back81 return tokens;82};83Split files (#791)ehmickybefore adoption932fb26
line 84why, one step back84const parseTemplate = ({templates, expressions, tokens, index, template}) => {Allow newlines in `$` (#843)ehmickybefore adoption1315486
lines 85–87why, one step back85 if (template === undefined) {86 throw new TypeError(`Invalid backslash sequence: ${templates.raw[index]}`);87 }Split files (#791)ehmickybefore adoption932fb26
line 88why, one step back88Allow newlines in `$` (#843)ehmickybefore adoption1315486
lines 89–91why, one step back89 const {nextTokens, leadingWhitespaces, trailingWhitespaces} = splitByWhitespaces(template, templates.raw[index]);90 const newTokens = concatTokens(tokens, nextTokens, leadingWhitespaces);91Split files (#791)ehmickybefore adoption932fb26
lines 92–99why, one step back92 if (index === expressions.length) {93 return newTokens;94 }9596 const expression = expressions[index];97 const expressionTokens = Array.isArray(expression)98 ? expression.map(expression => parseExpression(expression))99 : [parseExpression(expression)];Allow newlines in `$` (#843)ehmickybefore adoption1315486
line 100why, one step back100 return concatTokens(newTokens, expressionTokens, trailingWhitespaces);Split files (#791)ehmickybefore adoption932fb26
lines 101–102why, one step back101};102Allow newlines in `$` (#843)ehmickybefore adoption1315486
lines 103–112why, one step back103// Like `string.split(/[ \t\r\n]+/)` except newlines and tabs are:104// - ignored when input as a backslash sequence like: `echo foo\n bar`105// - not ignored when input directly106// The only way to distinguish those in JavaScript is to use a tagged template and compare:107// - the first array argument, which does not escape backslash sequences108// - its `raw` property, which escapes them109const splitByWhitespaces = (template, rawTemplate) => {110 if (rawTemplate.length === 0) {111 return {nextTokens: [], leadingWhitespaces: false, trailingWhitespaces: false};112 }Split files (#791)ehmickybefore adoption932fb26
line 113why, one step back113Allow newlines in `$` (#843)ehmickybefore adoption1315486
lines 114–157why, one step back114 const nextTokens = [];115 let templateStart = 0;116 const leadingWhitespaces = DELIMITERS.has(rawTemplate[0]);117118 for (119 let templateIndex = 0, rawIndex = 0;120 templateIndex < template.length;121 templateIndex += 1, rawIndex += 1122 ) {123 const rawCharacter = rawTemplate[rawIndex];124 if (DELIMITERS.has(rawCharacter)) {125 if (templateStart !== templateIndex) {126 nextTokens.push(template.slice(templateStart, templateIndex));127 }128129 templateStart = templateIndex + 1;130 } else if (rawCharacter === '\\') {131 const nextRawCharacter = rawTemplate[rawIndex + 1];132 if (nextRawCharacter === 'u' && rawTemplate[rawIndex + 2] === '{') {133 rawIndex = rawTemplate.indexOf('}', rawIndex + 3);134 } else {135 rawIndex += ESCAPE_LENGTH[nextRawCharacter] ?? 1;136 }137 }138 }139140 const trailingWhitespaces = templateStart === template.length;141 if (!trailingWhitespaces) {142 nextTokens.push(template.slice(templateStart));143 }144145 return {nextTokens, leadingWhitespaces, trailingWhitespaces};146};147148const DELIMITERS = new Set([' ', '\t', '\r', '\n']);149150// Number of characters in backslash escape sequences: \0 \xXX or \uXXXX151// \cX is allowed in RegExps but not in strings152// Octal sequences are not allowed in strict mode153const ESCAPE_LENGTH = {x: 3, u: 5};154155const concatTokens = (tokens, nextTokens, isSeparated) => isSeparated156 || tokens.length === 0157 || nextTokens.length === 0Split files (#837)ehmickybefore adoption672c2d7
lines 158–169why, one step back158 ? [...tokens, ...nextTokens]159 : [160 ...tokens.slice(0, -1),161 `${tokens.at(-1)}${nextTokens[0]}`,162 ...nextTokens.slice(1),163 ];164165const parseExpression = expression => {166 const typeOfExpression = typeof expression;167168 if (typeOfExpression === 'string') {169 return expression;Split files (#791)ehmickybefore adoption932fb26
lines 170–171why, one step back170 }171Split files (#837)ehmickybefore adoption672c2d7
lines 172–178why, one step back172 if (typeOfExpression === 'number') {173 return String(expression);174 }175176 if (177 typeOfExpression === 'object'178 && expression !== null`.pipe()` shortcut for `$` (#840)ehmickybefore adoption316f562
line 179why, one step back179 && !isChildProcess(expression)Split files (#837)ehmickybefore adoption672c2d7
lines 180–195why, one step back180 && 'stdout' in expression181 ) {182 const typeOfStdout = typeof expression.stdout;183184 if (typeOfStdout === 'string') {185 return expression.stdout;186 }187188 if (isBinary(expression.stdout)) {189 return binaryToString(expression.stdout);190 }191192 throw new TypeError(`Unexpected "${typeOfStdout}" stdout in template expression`);193 }194195 throw new TypeError(`Unexpected "${typeOfExpression}" in template expression`);Split files (#791)ehmickybefore adoption932fb26
lines 196–197why, one step back196};197Split files (#837)ehmickybefore adoption672c2d7
lines 198–206why, one step back198const normalizeScriptOptions = (options = {}) => ({199 preferLocal: true,200 ...normalizeScriptStdin(options),201 ...options,202});203204const normalizeScriptStdin = ({input, inputFile, stdio}) => input === undefined && inputFile === undefined && stdio === undefined205 ? {stdin: 'inherit'}206 : {};