script.js
This file
Path
lib/script.js
80 lines · 2.0 KiB · JavaScript
Last changed by
Split files (#791)ehmickybefore adoption932fb26
History of this fileTake it
Split files (#791)ehmickybefore adoption932fb26
lines 1–80why, one step back1import {ChildProcess} from 'node:child_process';2import {isBinary, binaryToString} from './stdio/utils.js';34const parseExpression = expression => {5 const typeOfExpression = typeof expression;67 if (typeOfExpression === 'string') {8 return expression;9 }1011 if (typeOfExpression === 'number') {12 return String(expression);13 }1415 if (16 typeOfExpression === 'object'17 && expression !== null18 && !(expression instanceof ChildProcess)19 && 'stdout' in expression20 ) {21 const typeOfStdout = typeof expression.stdout;2223 if (typeOfStdout === 'string') {24 return expression.stdout;25 }2627 if (isBinary(expression.stdout)) {28 return binaryToString(expression.stdout);29 }3031 throw new TypeError(`Unexpected "${typeOfStdout}" stdout in template expression`);32 }3334 throw new TypeError(`Unexpected "${typeOfExpression}" in template expression`);35};3637const concatTokens = (tokens, nextTokens, isNew) => isNew || tokens.length === 0 || nextTokens.length === 038 ? [...tokens, ...nextTokens]39 : [40 ...tokens.slice(0, -1),41 `${tokens.at(-1)}${nextTokens[0]}`,42 ...nextTokens.slice(1),43 ];4445const SPACES_REGEXP = / +/g;4647const parseTemplate = ({templates, expressions, tokens, index, template}) => {48 const templateString = template ?? templates.raw[index];49 const templateTokens = templateString.split(SPACES_REGEXP).filter(Boolean);50 const newTokens = concatTokens(51 tokens,52 templateTokens,53 templateString.startsWith(' '),54 );5556 if (index === expressions.length) {57 return newTokens;58 }5960 const expression = expressions[index];61 const expressionTokens = Array.isArray(expression)62 ? expression.map(expression => parseExpression(expression))63 : [parseExpression(expression)];64 return concatTokens(65 newTokens,66 expressionTokens,67 templateString.endsWith(' '),68 );69};7071export const parseTemplates = (templates, expressions) => {72 let tokens = [];7374 for (const [index, template] of templates.entries()) {75 tokens = parseTemplate({templates, expressions, tokens, index, template});76 }7778 return tokens;79};80