Skip to content
Myr

Fix the `encoding` option and line splitting in transforms

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

authored by Sindre Sorhus · committed by Sindre Sorhus · parent 4a0a121 · Browse files · 14 files+394 added−40 removed
This commit

State

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

Diff stats

14 files+394 added−40 removed

  • tests:+301 added−12 removed
  • other:+93 added−28 removed

14 files+394 added−40 removed

modified:docs/api.md+2 added
986 unmodified lines
987- [`'hex'`](https://en.wikipedia.org/wiki/Hexadecimal), [`'base64'`](https://en.wikipedia.org/wiki/Base64), [`'base64url'`](https://en.wikipedia.org/wiki/Base64#RFC_4648), [`'latin1'`](https://nodejs.org/api/buffer.html#buffers-and-character-encodings) or [`'ascii'`](https://nodejs.org/api/buffer.html#buffers-and-character-encodings): encodes the binary output as a string.988989The output is available with [`result.stdout`](#resultstdout), [`result.stderr`](#resultstderr) and [`result.stdio`](#resultstdio).990991String input passed with the [`input`](#optionsinput) or [`stdin`](#optionsstdin) option is always encoded with UTF-8, whatever this option is. With a text encoding, [`stdin` transforms](transform.md) also decode their input with UTF-8.992993[More info.](binary.md)994995### options.lines996
367 unmodified lines
modified:docs/binary.md+3 added
modified:lib/arguments/encoding-option.js+10 added
modified:lib/io/input-sync.js+5 added-3 removed
modified:lib/stdio/handle-async.js+6 added
1import {createReadStream, createWriteStream} from 'node:fs';2import {Buffer} from 'node:buffer';3import {Readable, Writable, Duplex} from 'node:stream';4import {generatorToStream} from '../transform/generator.js';5import {getInputEncoding} from '../arguments/encoding-option.js';6import {handleStdio} from './handle.js';7import {TYPE_TO_MESSAGE} from './type.js';89// Handle `input`, `inputFile`, `stdin`, `stdout` and `stderr` options, before spawning, in async mode
18 unmodified lines
28 duplex: ({value: {transform}}) => ({stream: transform}),29 native() {},30};3132// Input transforms use UTF-8 with text encodings, since those only apply to the output33const generatorToInputStream = (stdioItem, {encoding}) => generatorToStream(stdioItem, {encoding: getInputEncoding(encoding)});3435const addPropertiesAsync = {36 input: {37 ...addProperties,38 generator: generatorToInputStream,39 asyncGenerator: generatorToInputStream,40 fileUrl: ({value}) => ({stream: createReadStream(value)}),41 filePath: ({value: {file}}) => ({stream: createReadStream(file)}),42 webStream: ({value}) => ({stream: Readable.fromWeb(value)}),43 iterable: ({value}) => ({stream: Readable.from(value)}),
15 unmodified lines
modified:lib/transform/encoding-transform.js+15 added
1import {Buffer} from 'node:buffer';2import {StringDecoder} from 'node:string_decoder';3import {getStringEncoding} from '../arguments/encoding-option.js';4import {isUint8Array, bufferToUint8Array} from '../utils/uint-array.js';56/*7When using binary encodings, add an internal generator that converts chunks from `Buffer` to `string` or `Uint8Array`.
41 unmodified lines
49 if (lastChunk !== '') {50 yield lastChunk;51 }52};5354/*55Once the user's transform has run, its string chunks are converted to bytes: by `Transform.push()` with the asynchronous methods, and by `joinToString()` with the synchronous ones. Both use UTF-8, yet the result is then decoded with the `encoding` option, which would corrupt the text when that option is a different text encoding.56Therefore, those chunks are converted using the `encoding` option beforehand.57With the `binary` transform option, they are converted with UTF-8 even when the `encoding` option is another text encoding. Otherwise, with synchronous methods, the next transform would receive the string itself, while with asynchronous methods it receives those UTF-8 bytes decoded with the `encoding` option.58When the `encoding` option is UTF-8, strings round-trip unchanged, so there is nothing to do.59*/60export const getStringToBytesGenerator = (binary, encoding, skipped) => skipped || encoding === 'utf8'61 ? undefined62 : {transform: stringToBytesGenerator.bind(undefined, getStringEncoding(binary, encoding))};6364const stringToBytesGenerator = function * (stringEncoding, chunk) {65 yield typeof chunk === 'string' ? bufferToUint8Array(Buffer.from(chunk, stringEncoding)) : chunk;66};
modified:lib/transform/generator.js+13 added-2 removed
1import {Transform, getDefaultHighWaterMark} from 'node:stream';2import {getStringEncoding} from '../arguments/encoding-option.js';3import {isAsyncGenerator} from '../stdio/type.js';4import {getSplitLinesGenerator, getAppendNewlineGenerator} from './split.js';5import {getValidateTransformInput, getValidateTransformReturn} from './validate.js';5import {getEncodingTransformGenerator} from './encoding-transform.js';6import {getEncodingTransformGenerator, getStringToBytesGenerator} from './encoding-transform.js';7import {8 pushChunks,9 transformChunk,10 finalChunks,
26 unmodified lines
37`Duplex.from(generator)` cannot be used because it does not allow setting the `objectMode` and `highWaterMark`.38*/39export const generatorToStream = ({40 value,40 value: {transform, final, writableObjectMode, readableObjectMode},41 value: {42 transform,43 final,44 binary,45 writableObjectMode,46 readableObjectMode,47 },48 optionName,49}, {encoding}) => {50 const state = {};51 const generators = addInternalGenerators(value, encoding, optionName);
14 unmodified lines
66 writableObjectMode,67 writableHighWaterMark: getDefaultHighWaterMark(writableObjectMode),68 readableObjectMode,69 readableHighWaterMark: getDefaultHighWaterMark(readableObjectMode),70 // A string written to the stream is converted to bytes with this encoding, which `getEncodingTransformGenerator()` then decodes with the `encoding` option71 defaultEncoding: getStringEncoding(binary, encoding),72 transform(chunk, encoding, done) {73 transformMethod([chunk, generators, 0], this, done);74 },75 flush(done) {
34 unmodified lines
110 binary,111 preserveNewlines,112 readableObjectMode,113 state,114 encoding,115 }),116 getStringToBytesGenerator(binary, encoding, readableObjectMode),117 ].filter(Boolean);118};
modified:lib/transform/split.js+37 added-23 removed
1import {getStringEncoding} from '../arguments/encoding-option.js';23// Split chunks line-wise for generators passed to the `std*` options4export const getSplitLinesGenerator = (binary, preserveNewlines, skipped, state) => binary || skipped5 ? undefined6 : initializeSplitLines(preserveNewlines, state);
30 unmodified lines
37 if (chunk[end] !== '\n') {38 continue;39 }4039 const newlineLength = getNewlineLength(chunk, end, preserveNewlines, state);40 let line = chunk.slice(start + 1, end + 1 - newlineLength);41 // The `\r` of a `\r\n` sequence is stripped further below, once `previousChunks` has been prepended.42 // Otherwise, a `\r\n` sequence split across two chunks would not be detected.43 let line = chunk.slice(start + 1, preserveNewlines ? end + 1 : end);4445 if (previousChunks.length > 0) {46 line = concatString(previousChunks, line);47 previousChunks = '';48 }4947 yield line;50 yield preserveNewlines ? line : stripCarriageReturn(line, state);51 start = end;52 }5354 if (start !== chunk.length - 1) {
2 unmodified lines
5758 state.previousChunks = previousChunks;59};6058const getNewlineLength = (chunk, end, preserveNewlines, state) => {59 if (preserveNewlines) {60 return 0;61 }6263 state.isWindowsNewline = end !== 0 && chunk[end - 1] === '\r';64 return state.isWindowsNewline ? 2 : 1;61const stripCarriageReturn = (line, state) => {62 state.isWindowsNewline = line.endsWith('\r');63 return state.isWindowsNewline ? line.slice(0, -1) : line;64};6566const linesFinal = function * ({previousChunks}) {67 if (previousChunks.length > 0) {
2 unmodified lines
70};7172// Unless `preserveNewlines: true` is used, we strip the newline of each line.73// This re-adds them after the user `transform` code has run.74// The re-added newline must be encoded with the `encoding` option when the chunk is bytes: a UTF-8 newline would misalign `utf16le` bytes.75export const getAppendNewlineGenerator = ({binary, preserveNewlines, readableObjectMode, state}) => binary || preserveNewlines || readableObjectMode75export const getAppendNewlineGenerator = ({binary, preserveNewlines, readableObjectMode, state, encoding}) => binary || preserveNewlines || readableObjectMode76 ? undefined77 : {transform: appendNewlineGenerator.bind(undefined, state)};77 : {transform: appendNewlineGenerator.bind(undefined, state, getStringEncoding(binary, encoding))};7879const appendNewlineGenerator = function * ({isWindowsNewline = false}, chunk) {80 const {unixNewline, windowsNewline, LF, concatBytes} = typeof chunk === 'string' ? linesStringInfo : linesUint8ArrayInfo;79const appendNewlineGenerator = function * ({isWindowsNewline = false}, stringEncoding, chunk) {80 const {unixNewline, windowsNewline, concat} = typeof chunk === 'string'81 ? linesStringInfo82 : LINES_BYTES_INFO[stringEncoding];8382 if (chunk.at(-1) === LF) {84 if (endsWithNewline(chunk, unixNewline)) {85 yield chunk;86 return;87 }8889 const newline = isWindowsNewline ? windowsNewline : unixNewline;88 yield concatBytes(chunk, newline);90 yield concat(chunk, newline);91};9293const endsWithNewline = (chunk, unixNewline) => typeof chunk === 'string'94 ? chunk.endsWith(unixNewline)95 : chunk.length >= unixNewline.length96 && chunk.subarray(-unixNewline.length).every((byte, index) => byte === unixNewline[index]);9798const concatString = (firstChunk, secondChunk) => `${firstChunk}${secondChunk}`;99100const linesStringInfo = {101 windowsNewline: '\r\n',102 unixNewline: '\n',96 LF: '\n',97 concatBytes: concatString,103 concat: concatString,104};105106const concatUint8Array = (firstChunk, secondChunk) => {107 const chunk = new Uint8Array(firstChunk.length + secondChunk.length);
1 unmodified line
109 chunk.set(secondChunk, firstChunk.length);110 return chunk;111};112107const linesUint8ArrayInfo = {108 windowsNewline: new Uint8Array([0x0D, 0x0A]),109 unixNewline: new Uint8Array([0x0A]),110 LF: 0x0A,111 concatBytes: concatUint8Array,113// Only indexed with text encodings, since the `binary` option and binary encodings disable this generator114const LINES_BYTES_INFO = {115 __proto__: null,116 utf8: {117 windowsNewline: new Uint8Array([0x0D, 0x0A]),118 unixNewline: new Uint8Array([0x0A]),119 concat: concatUint8Array,120 },121 utf16le: {122 windowsNewline: new Uint8Array([0x0D, 0x00, 0x0A, 0x00]),123 unixNewline: new Uint8Array([0x0A, 0x00]),124 concat: concatUint8Array,125 },126};
modified:test/helpers/lines.js-2 removed
18 unmodified lines
19export const simpleFullUtf16Inverted = simpleFullBuffer.toString('utf16le');20const simpleFullUtf16Buffer = Buffer.from(simpleFull, 'utf16le');21export const simpleFullUtf16Uint8Array = new Uint8Array(simpleFullUtf16Buffer);22export const simpleFullEnd = `${simpleFull}\n`;23const simpleFullEndBuffer = Buffer.from(simpleFullEnd);23export const simpleFullEndChunks = [simpleFullEnd];25export const simpleFullEndUtf16Inverted = simpleFullEndBuffer.toString('utf16le');24export const simpleLines = ['aaa\n', 'bbb\n', 'ccc'];25export const simpleFullEndLines = ['aaa\n', 'bbb\n', 'ccc\n'];26export const noNewlinesFull = 'aaabbbccc';27export const noNewlinesChunks = ['aaa', 'bbb', 'ccc'];
16 unmodified lines
modified:test/io/input-option.js+57 added
1import {Buffer} from 'node:buffer';2import {Writable} from 'node:stream';3import test from 'ava';4import {execa, execaSync} from '../../index.js';5import {setFixtureDirectory} from '../helpers/fixtures-directory.js';
10 unmodified lines
16 foobarArrayBuffer,17 foobarUint16Array,18 foobarDataView,19} from '../helpers/input.js';20import {noopGenerator} from '../helpers/generator.js';2122setFixtureDirectory();2324const testInput = async (t, input, execaMethod) => {
43 unmodified lines
68test('input option cannot be 0 - sync', testInvalidInput, 0, execaSync);69test('input option cannot be false - sync', testInvalidInput, false, execaSync);70test('input option cannot be null - sync', testInvalidInput, null, execaSync);71test('input option cannot be a non-Readable stream - sync', testInvalidInput, new Writable(), execaSync);7273/*74String input is encoded with the `encoding` option, so it round-trips with subprocesses echoing it back.75This must not depend on whether a `stdin` transform happens to be present.76*/77const nonAsciiString = '🦄🦄';7879const testStringEncoding = async (t, options, execaMethod) => {80 const {stdout} = await execaMethod('stdin.js', {...options, input: nonAsciiString, encoding: 'utf16le'});81 t.is(stdout, nonAsciiString);82};8384test('input option string is encoded with encoding "utf16le" without transforms', testStringEncoding, {}, execa);85test('input option string is encoded with encoding "utf16le" without transforms - sync', testStringEncoding, {}, execaSync);86test('input option string is encoded with encoding "utf16le" with transforms', testStringEncoding, {stdin: noopGenerator()}, execa);87test('input option string is encoded with encoding "utf16le" with transforms - sync', testStringEncoding, {stdin: noopGenerator()}, execaSync);8889/*90Sources other than the `input` option also pass strings to the subprocess, which must be encoded with the `encoding` option too.91*/92const testIterableInputEncoding = async (t, execaMethod) => {93 const {stdout} = await execaMethod('stdin.js', {94 stdin: [[`${nonAsciiString}aaa\n`], [`${nonAsciiString}bbb\n`]],95 encoding: 'utf16le',96 stripFinalNewline: false,97 });98 t.is(stdout, `${nonAsciiString}aaa\n${nonAsciiString}bbb\n`);99};100101test('Iterable string input is encoded with encoding "utf16le"', testIterableInputEncoding, execa);102test('Iterable string input is encoded with encoding "utf16le" - sync', testIterableInputEncoding, execaSync);103104const testAsyncIterableInputEncoding = async t => {105 const chunks = async function * () {106 yield nonAsciiString;107 };108109 const {stdout} = await execa('stdin.js', {stdin: [chunks()], encoding: 'utf16le'});110 t.is(stdout, nonAsciiString);111};112113test('Async iterable string input is encoded with encoding "utf16le"', testAsyncIterableInputEncoding);114115/*116The `encoding` option does not change how string input is encoded when it is a binary encoding: those describe how output bytes are serialized, so input keeps using UTF-8.117*/118const testBinaryEncodingInput = async (t, encoding, execaMethod) => {119 const {stdout} = await execaMethod('stdin.js', {input: nonAsciiString, encoding});120 t.is(stdout, Buffer.from(nonAsciiString).toString(encoding));121};122123test('String input stays UTF-8 with encoding "latin1"', testBinaryEncodingInput, 'latin1', execa);124test('String input stays UTF-8 with encoding "latin1" - sync', testBinaryEncodingInput, 'latin1', execaSync);125test('String input stays UTF-8 with encoding "hex"', testBinaryEncodingInput, 'hex', execa);126test('String input stays UTF-8 with encoding "hex" - sync', testBinaryEncodingInput, 'hex', execaSync);
modified:test/transform/encoding-transform.js+132 added-1 removed
5 unmodified lines
6import {7 foobarString,8 foobarUint8Array,9 foobarBuffer,10 foobarUtf16Uint8Array,11 foobarObject,12} from '../helpers/input.js';12import {noopGenerator, getOutputGenerator} from '../helpers/generator.js';13import {noopGenerator, getOutputGenerator, uppercaseGenerator} from '../helpers/generator.js';1415setFixtureDirectory();1617const getTypeofGenerator = lines => (objectMode, binary) => ({
74 unmodified lines
92test('First generator argument can be objects with objectMode, sync', testGeneratorFirstEncodingSync, foobarObject, 'utf8', 'Object', true, undefined);93test('First generator argument can be objects with objectMode, "binary: false", sync', testGeneratorFirstEncodingSync, foobarObject, 'utf8', 'Object', true, false);94test('First generator argument can be objects with objectMode, "binary: true", sync', testGeneratorFirstEncodingSync, foobarObject, 'utf8', 'Object', true, true);9596/*97The `encoding` option also determines how binary `stdin` input is decoded before being passed to a transform.98Unlike the tests above, this checks the chunk's value, not only its type.99This must be the same with both asynchronous and synchronous methods.100*/101const getChunkGenerator = chunks => ({102 * transform(chunk) {103 chunks.push(chunk);104 yield chunk;105 },106});107108const testStdinEncodingValue = async (t, encoding) => {109 const chunks = [];110 const subprocess = execa('stdin.js', {stdin: getChunkGenerator(chunks), encoding});111 subprocess.stdin.end(foobarUtf16Uint8Array);112 await subprocess;113 t.deepEqual(chunks, [Buffer.from(foobarUtf16Uint8Array).toString(encoding)]);114};115116test('First generator argument is decoded with encoding "utf8"', testStdinEncodingValue, 'utf8');117test('First generator argument is decoded with encoding "utf16le"', testStdinEncodingValue, 'utf16le');118119const testStdinEncodingValueSync = (t, encoding) => {120 const chunks = [];121 execaSync('stdin.js', {stdin: [[foobarUtf16Uint8Array], getChunkGenerator(chunks)], encoding});122 t.deepEqual(chunks, [Buffer.from(foobarUtf16Uint8Array).toString(encoding)]);123};124125test('First generator argument is decoded with encoding "utf8", sync', testStdinEncodingValueSync, 'utf8');126test('First generator argument is decoded with encoding "utf16le", sync', testStdinEncodingValueSync, 'utf16le');127128const testEncodingIgnored = async (t, encoding) => {129 const input = Buffer.from(foobarString).toString(encoding);130 const subprocess = execa('stdin.js', {stdin: noopGenerator(true)});131 subprocess.stdin.end(input, encoding);
75 unmodified lines
207test('The first generator with result.stdio[*] does not receive an object argument even in objectMode', testFirstOutputGeneratorArgument, 3, execa);208test('The first generator with result.stdout does not receive an object argument even in objectMode, sync', testFirstOutputGeneratorArgument, 1, execaSync);209test('The first generator with result.stderr does not receive an object argument even in objectMode, sync', testFirstOutputGeneratorArgument, 2, execaSync);210test('The first generator with result.stdio[*] does not receive an object argument even in objectMode, sync', testFirstOutputGeneratorArgument, 3, execaSync);211212// When the `encoding` option is binary, the whole pipeline is byte-oriented: a transform yielding a213// string has it encoded as UTF-8, then those bytes are serialized using the `encoding` option.214// This is the only coherent rule, since a yielded string like 'foobar' is neither valid hex nor valid base64.215// A non-ASCII string is used, so UTF-8 and the binary encoding differ.216const nonAsciiString = 'ré😀';217const nonAsciiBuffer = Buffer.from(nonAsciiString, 'utf8');218219const testYieldStringBinaryEncoding = async (t, encoding, execaMethod) => {220 const {stdout} = await execaMethod('noop.js', {221 stdout: getOutputGenerator(nonAsciiString)(false, true),222 encoding,223 });224 t.is(stdout, nonAsciiBuffer.toString(encoding));225};226227test('Transforms yielding a string are UTF-8 encoded, latin1', testYieldStringBinaryEncoding, 'latin1', execa);228test('Transforms yielding a string are UTF-8 encoded, latin1, sync', testYieldStringBinaryEncoding, 'latin1', execaSync);229test('Transforms yielding a string are UTF-8 encoded, hex', testYieldStringBinaryEncoding, 'hex', execa);230test('Transforms yielding a string are UTF-8 encoded, hex, sync', testYieldStringBinaryEncoding, 'hex', execaSync);231test('Transforms yielding a string are UTF-8 encoded, base64', testYieldStringBinaryEncoding, 'base64', execa);232test('Transforms yielding a string are UTF-8 encoded, base64, sync', testYieldStringBinaryEncoding, 'base64', execaSync);233234// A transform yielding the bytes it received must round-trip them unchanged235const testYieldBytesBinaryEncoding = async (t, execaMethod) => {236 const {stdout} = await execaMethod('noop-fd.js', ['1', nonAsciiString], {237 stdout: noopGenerator(false, true),238 encoding: 'latin1',239 });240 t.is(stdout, nonAsciiBuffer.toString('latin1'));241};242243test('Transforms yielding Uint8Array keep the bytes unchanged', testYieldBytesBinaryEncoding, execa);244test('Transforms yielding Uint8Array keep the bytes unchanged, sync', testYieldBytesBinaryEncoding, execaSync);245246/*247With a text encoding, a transform receives text decoded with it, so a string it yields must be encoded back with it.248Otherwise that string would be encoded as UTF-8, then decoded with the `encoding` option, which corrupts it.249*/250const nonAsciiUtf16Uint8Array = new Uint8Array(Buffer.from(nonAsciiString, 'utf16le'));251252const testYieldStringTextEncoding = async (t, transform, expectedOutput, execaMethod) => {253 const {stdout} = await execaMethod('noop.js', {254 stdout: [getOutputGenerator(nonAsciiUtf16Uint8Array)(false, true), transform],255 encoding: 'utf16le',256 });257 t.is(stdout, expectedOutput);258};259260test('Transforms yielding a string are encoded with encoding "utf16le"', testYieldStringTextEncoding, noopGenerator(), nonAsciiString, execa);261test('Transforms yielding a string are encoded with encoding "utf16le", sync', testYieldStringTextEncoding, noopGenerator(), nonAsciiString, execaSync);262test('Transforms modifying a string are encoded with encoding "utf16le"', testYieldStringTextEncoding, uppercaseGenerator(), nonAsciiString.toUpperCase(), execa);263test('Transforms modifying a string are encoded with encoding "utf16le", sync', testYieldStringTextEncoding, uppercaseGenerator(), nonAsciiString.toUpperCase(), execaSync);264test('Transforms yielding a Uint8Array keep the bytes unchanged with encoding "utf16le"', testYieldStringTextEncoding, getOutputGenerator(nonAsciiUtf16Uint8Array)(false, true), nonAsciiString, execa);265test('Transforms yielding a Uint8Array keep the bytes unchanged with encoding "utf16le", sync', testYieldStringTextEncoding, getOutputGenerator(nonAsciiUtf16Uint8Array)(false, true), nonAsciiString, execaSync);266267// A `stdin` transform also receives text decoded with the `encoding` option, so the same applies in that direction268const testYieldStringTextEncodingInput = async (t, execaMethod) => {269 const {stdout} = await execaMethod('stdin.js', {270 stdin: [[nonAsciiUtf16Uint8Array], noopGenerator()],271 encoding: 'utf16le',272 });273 t.is(stdout, nonAsciiString);274};275276test('Transforms yielding a string are encoded with encoding "utf16le", stdin', testYieldStringTextEncodingInput, execa);277test('Transforms yielding a string are encoded with encoding "utf16le", stdin, sync', testYieldStringTextEncodingInput, execaSync);278279// When the `stdin` value is a string, the transform receives it as text, so it must not be encoded as UTF-8 either280const testStringInputTextEncoding = async (t, execaMethod) => {281 const {stdout} = await execaMethod('stdin.js', {282 stdin: [[nonAsciiString], noopGenerator()],283 encoding: 'utf16le',284 });285 t.is(stdout, nonAsciiString);286};287288test('String input is encoded with encoding "utf16le", stdin', testStringInputTextEncoding, execa);289test('String input is encoded with encoding "utf16le", stdin, sync', testStringInputTextEncoding, execaSync);290291// A transform may also yield `Uint8Array`s with a text encoding. The newline re-added after each stripped line must then be encoded with that same encoding, otherwise the bytes become misaligned.292const utf16leYieldGenerator = {293 * transform(line) {294 yield Buffer.from(line, 'utf16le');295 },296};297298const testYieldUtf16LeLines = async (t, execaMethod) => {299 const {stdout} = await execaMethod('stdin.js', {300 stdin: [['aaa\nbbb\nccc\n'], utf16leYieldGenerator],301 encoding: 'utf16le',302 stripFinalNewline: false,303 });304 t.is(stdout, 'aaa\nbbb\nccc\n');305};306307test('Transforms yielding Uint8Array re-add newlines with encoding "utf16le"', testYieldUtf16LeLines, execa);308test('Transforms yielding Uint8Array re-add newlines with encoding "utf16le", sync', testYieldUtf16LeLines, execaSync);
modified:test/transform/split-binary.js+8 added-9 removed
8 unmodified lines
9 simpleFullUtf16Inverted,10 simpleFullUtf16Uint8Array,11 simpleChunksUint8Array,12 simpleFullEnd,13 simpleFullEndUtf16Inverted,13 simpleFullHex,14 simpleLines,15 noNewlinesChunks,16} from '../helpers/lines.js';
18 unmodified lines
35test('Does not split lines when "binary" is true', testBinaryOption, true, simpleChunks, simpleChunksUint8Array, simpleFull, false, true, 'utf8', execa);36test('Splits lines when "binary" is false', testBinaryOption, false, simpleChunks, simpleLines, simpleFull, false, true, 'utf8', execa);37test('Splits lines when "binary" is undefined', testBinaryOption, undefined, simpleChunks, simpleLines, simpleFull, false, true, 'utf8', execa);38test('Does not split lines when "binary" is true, encoding "utf16le"', testBinaryOption, true, simpleChunks, simpleChunksUint8Array, simpleFullUtf16Inverted, false, true, 'utf16le', execa);40test('Splits lines when "binary" is false, encoding "utf16le"', testBinaryOption, false, [simpleFullUtf16Uint8Array], simpleLines, simpleFullUtf16Inverted, false, true, 'utf16le', execa);41test('Splits lines when "binary" is undefined, encoding "utf16le"', testBinaryOption, undefined, [simpleFullUtf16Uint8Array], simpleLines, simpleFullUtf16Inverted, false, true, 'utf16le', execa);39test('Splits lines when "binary" is false, encoding "utf16le"', testBinaryOption, false, [simpleFullUtf16Uint8Array], simpleLines, simpleFull, false, true, 'utf16le', execa);40test('Splits lines when "binary" is undefined, encoding "utf16le"', testBinaryOption, undefined, [simpleFullUtf16Uint8Array], simpleLines, simpleFull, false, true, 'utf16le', execa);41test('Does not split lines when "binary" is true, encoding "buffer"', testBinaryOption, true, simpleChunks, simpleChunksUint8Array, simpleFullUint8Array, false, true, 'buffer', execa);42test('Does not split lines when "binary" is undefined, encoding "buffer"', testBinaryOption, undefined, simpleChunks, simpleChunksUint8Array, simpleFullUint8Array, false, true, 'buffer', execa);43test('Does not split lines when "binary" is false, encoding "buffer"', testBinaryOption, false, simpleChunks, simpleChunksUint8Array, simpleFullUint8Array, false, true, 'buffer', execa);44test('Does not split lines when "binary" is true, encoding "hex"', testBinaryOption, true, simpleChunks, simpleChunksUint8Array, simpleFullHex, false, true, 'hex', execa);
5 unmodified lines
50test('Does not split lines when "binary" is true, preserveNewlines', testBinaryOption, true, simpleChunks, simpleChunksUint8Array, simpleFull, false, false, 'utf8', execa);51test('Splits lines when "binary" is false, preserveNewlines', testBinaryOption, false, simpleChunks, noNewlinesChunks, simpleFullEnd, false, false, 'utf8', execa);52test('Splits lines when "binary" is undefined, preserveNewlines', testBinaryOption, undefined, simpleChunks, noNewlinesChunks, simpleFullEnd, false, false, 'utf8', execa);53test('Does not split lines when "binary" is true, preserveNewlines, encoding "utf16le"', testBinaryOption, true, simpleChunks, simpleChunksUint8Array, simpleFullUtf16Inverted, false, false, 'utf16le', execa);55test('Splits lines when "binary" is false, preserveNewlines, encoding "utf16le"', testBinaryOption, false, [simpleFullUtf16Uint8Array], noNewlinesChunks, simpleFullEndUtf16Inverted, false, false, 'utf16le', execa);56test('Splits lines when "binary" is undefined, preserveNewlines, encoding "utf16le"', testBinaryOption, undefined, [simpleFullUtf16Uint8Array], noNewlinesChunks, simpleFullEndUtf16Inverted, false, false, 'utf16le', execa);54test('Splits lines when "binary" is false, preserveNewlines, encoding "utf16le"', testBinaryOption, false, [simpleFullUtf16Uint8Array], noNewlinesChunks, simpleFullEnd, false, false, 'utf16le', execa);55test('Splits lines when "binary" is undefined, preserveNewlines, encoding "utf16le"', testBinaryOption, undefined, [simpleFullUtf16Uint8Array], noNewlinesChunks, simpleFullEnd, false, false, 'utf16le', execa);56test('Does not split lines when "binary" is true, encoding "buffer", preserveNewlines', testBinaryOption, true, simpleChunks, simpleChunksUint8Array, simpleFullUint8Array, false, false, 'buffer', execa);57test('Does not split lines when "binary" is undefined, encoding "buffer", preserveNewlines', testBinaryOption, undefined, simpleChunks, simpleChunksUint8Array, simpleFullUint8Array, false, false, 'buffer', execa);58test('Does not split lines when "binary" is false, encoding "buffer", preserveNewlines', testBinaryOption, false, simpleChunks, simpleChunksUint8Array, simpleFullUint8Array, false, false, 'buffer', execa);59test('Does not split lines when "binary" is true, objectMode, preserveNewlines', testBinaryOption, true, simpleChunks, simpleChunksUint8Array, simpleChunksUint8Array, true, false, 'utf8', execa);
5 unmodified lines
65test('Does not split lines when "binary" is true, sync', testBinaryOption, true, simpleChunks, simpleChunksUint8Array, simpleFull, false, true, 'utf8', execaSync);66test('Splits lines when "binary" is false, sync', testBinaryOption, false, simpleChunks, simpleLines, simpleFull, false, true, 'utf8', execaSync);67test('Splits lines when "binary" is undefined, sync', testBinaryOption, undefined, simpleChunks, simpleLines, simpleFull, false, true, 'utf8', execaSync);68test('Does not split lines when "binary" is true, encoding "utf16le", sync', testBinaryOption, true, simpleChunks, simpleChunksUint8Array, simpleFullUtf16Inverted, false, true, 'utf16le', execaSync);70test('Splits lines when "binary" is false, encoding "utf16le", sync', testBinaryOption, false, [simpleFullUtf16Uint8Array], simpleLines, simpleFullUtf16Inverted, false, true, 'utf16le', execaSync);71test('Splits lines when "binary" is undefined, encoding "utf16le", sync', testBinaryOption, undefined, [simpleFullUtf16Uint8Array], simpleLines, simpleFullUtf16Inverted, false, true, 'utf16le', execaSync);69test('Splits lines when "binary" is false, encoding "utf16le", sync', testBinaryOption, false, [simpleFullUtf16Uint8Array], simpleLines, simpleFull, false, true, 'utf16le', execaSync);70test('Splits lines when "binary" is undefined, encoding "utf16le", sync', testBinaryOption, undefined, [simpleFullUtf16Uint8Array], simpleLines, simpleFull, false, true, 'utf16le', execaSync);71test('Does not split lines when "binary" is true, encoding "buffer", sync', testBinaryOption, true, simpleChunks, simpleChunksUint8Array, simpleFullUint8Array, false, true, 'buffer', execaSync);72test('Does not split lines when "binary" is undefined, encoding "buffer", sync', testBinaryOption, undefined, simpleChunks, simpleChunksUint8Array, simpleFullUint8Array, false, true, 'buffer', execaSync);73test('Does not split lines when "binary" is false, encoding "buffer", sync', testBinaryOption, false, simpleChunks, simpleChunksUint8Array, simpleFullUint8Array, false, true, 'buffer', execaSync);74test('Does not split lines when "binary" is true, encoding "hex", sync', testBinaryOption, true, simpleChunks, simpleChunksUint8Array, simpleFullHex, false, true, 'hex', execaSync);
5 unmodified lines
80test('Does not split lines when "binary" is true, preserveNewlines, sync', testBinaryOption, true, simpleChunks, simpleChunksUint8Array, simpleFull, false, false, 'utf8', execaSync);81test('Splits lines when "binary" is false, preserveNewlines, sync', testBinaryOption, false, simpleChunks, noNewlinesChunks, simpleFullEnd, false, false, 'utf8', execaSync);82test('Splits lines when "binary" is undefined, preserveNewlines, sync', testBinaryOption, undefined, simpleChunks, noNewlinesChunks, simpleFullEnd, false, false, 'utf8', execaSync);83test('Does not split lines when "binary" is true, preserveNewlines, encoding "utf16le", sync', testBinaryOption, true, simpleChunks, simpleChunksUint8Array, simpleFullUtf16Inverted, false, false, 'utf16le', execaSync);85test('Splits lines when "binary" is false, preserveNewlines, encoding "utf16le", sync', testBinaryOption, false, [simpleFullUtf16Uint8Array], noNewlinesChunks, simpleFullEndUtf16Inverted, false, false, 'utf16le', execaSync);86test('Splits lines when "binary" is undefined, preserveNewlines, encoding "utf16le", sync', testBinaryOption, undefined, [simpleFullUtf16Uint8Array], noNewlinesChunks, simpleFullEndUtf16Inverted, false, false, 'utf16le', execaSync);84test('Splits lines when "binary" is false, preserveNewlines, encoding "utf16le", sync', testBinaryOption, false, [simpleFullUtf16Uint8Array], noNewlinesChunks, simpleFullEnd, false, false, 'utf16le', execaSync);85test('Splits lines when "binary" is undefined, preserveNewlines, encoding "utf16le", sync', testBinaryOption, undefined, [simpleFullUtf16Uint8Array], noNewlinesChunks, simpleFullEnd, false, false, 'utf16le', execaSync);86test('Does not split lines when "binary" is true, encoding "buffer", preserveNewlines, sync', testBinaryOption, true, simpleChunks, simpleChunksUint8Array, simpleFullUint8Array, false, false, 'buffer', execaSync);87test('Does not split lines when "binary" is undefined, encoding "buffer", preserveNewlines, sync', testBinaryOption, undefined, simpleChunks, simpleChunksUint8Array, simpleFullUint8Array, false, false, 'buffer', execaSync);88test('Does not split lines when "binary" is false, encoding "buffer", preserveNewlines, sync', testBinaryOption, false, simpleChunks, simpleChunksUint8Array, simpleFullUint8Array, false, false, 'buffer', execaSync);89test('Does not split lines when "binary" is true, objectMode, preserveNewlines, sync', testBinaryOption, true, simpleChunks, simpleChunksUint8Array, simpleChunksUint8Array, true, false, 'utf8', execaSync);
5 unmodified lines
modified:test/transform/split-newline.js+104 added
1import process from 'node:process';2import {Buffer} from 'node:buffer';3import test from 'ava';4import {execa, execaSync} from '../../index.js';5import {setFixtureDirectory} from '../helpers/fixtures-directory.js';6import {getOutputsGenerator, noopGenerator, noopAsyncGenerator} from '../helpers/generator.js';
29 unmodified lines
3637test('Can mix Unix and Windows newlines', testMixNewlines, noopGenerator, execa);38test('Can mix Unix and Windows newlines, sync', testMixNewlines, noopGenerator, execaSync);39test('Can mix Unix and Windows newlines, async', testMixNewlines, noopAsyncGenerator, execa);4041// A `\r\n` sequence can be split across two chunks, since chunk boundaries are arbitrary.42// `noop-progressive.js` writes each character as a separate chunk, then a final newline.43test('Detects Windows newlines split across chunks', async t => {44 const {stdout} = await execa('noop-progressive.js', ['aaa\r'], {lines: true});45 t.deepEqual(stdout, ['aaa']);46});4748test('Keeps Windows newlines split across chunks', async t => {49 const {stdout} = await execa('noop-progressive.js', ['aaa\r'], {lines: true, stripFinalNewline: false});50 t.deepEqual(stdout, ['aaa\r\n']);51});5253test('Detects multiple Windows newlines split across chunks', async t => {54 const {stdout} = await execa('noop-progressive.js', ['aaa\r\nbbb\r'], {lines: true});55 t.deepEqual(stdout, ['aaa', 'bbb']);56});5758test('Keeps lone carriage returns split across chunks', async t => {59 const {stdout} = await execa('noop-progressive.js', ['aaa\rbbb'], {lines: true});60 t.deepEqual(stdout, ['aaa\rbbb']);61});6263/*64The newline re-added after each stripped line must be encoded with the `encoding` option when the transform yields bytes, both for `\n` and `\r\n`, and whether the input comes from the subprocess or from the `stdin` option.65*/66const utf16Input = 'aaa\nbbb\nccc\n';67const utf16WindowsInput = 'aaa\r\nbbb\r\n';6869const utf16YieldGenerator = {70 * transform(line) {71 yield Buffer.from(line, 'utf16le');72 },73};7475// The transform yields bytes which already end with a newline: it must not be appended twice76const utf16YieldNewlineGenerator = {77 * transform(line) {78 yield Buffer.from(`${line}\n`, 'utf16le');79 },80};8182const testUtf16LeInputNewlines = async (t, input, generator, execaMethod) => {83 const {stdout} = await execaMethod('stdin.js', {84 stdin: [[input], generator],85 encoding: 'utf16le',86 stripFinalNewline: false,87 });88 t.is(stdout, input);89};9091test('Newlines re-added to bytes use encoding "utf16le"', testUtf16LeInputNewlines, utf16Input, utf16YieldGenerator, execa);92test('Newlines re-added to bytes use encoding "utf16le", sync', testUtf16LeInputNewlines, utf16Input, utf16YieldGenerator, execaSync);93test('Windows newlines re-added to bytes use encoding "utf16le"', testUtf16LeInputNewlines, utf16WindowsInput, utf16YieldGenerator, execa);94test('Windows newlines re-added to bytes use encoding "utf16le", sync', testUtf16LeInputNewlines, utf16WindowsInput, utf16YieldGenerator, execaSync);95test('Bytes already ending with a newline are not appended to, utf16le', testUtf16LeInputNewlines, utf16Input, utf16YieldNewlineGenerator, execa);96test('Bytes already ending with a newline are not appended to, utf16le, sync', testUtf16LeInputNewlines, utf16Input, utf16YieldNewlineGenerator, execaSync);9798// The subprocess' own output goes through the same newline re-adding logic99const testUtf16LeOutputNewlines = async (t, execaMethod) => {100 const {stdout} = await execaMethod(process.execPath, ['-e', `process.stdout.write(${JSON.stringify(utf16Input)}, 'utf16le')`], {101 stdout: utf16YieldGenerator,102 encoding: 'utf16le',103 stripFinalNewline: false,104 });105 t.is(stdout, utf16Input);106};107108test('Newlines re-added to bytes use encoding "utf16le", subprocess output', testUtf16LeOutputNewlines, execa);109test('Newlines re-added to bytes use encoding "utf16le", subprocess output, sync', testUtf16LeOutputNewlines, execaSync);110111// Control: UTF-8 bytes keep using UTF-8 newlines112const utf8YieldGenerator = {113 * transform(line) {114 yield Buffer.from(line, 'utf8');115 },116};117118const testUtf8InputNewlines = async (t, execaMethod) => {119 const {stdout} = await execaMethod('stdin.js', {120 stdin: [[utf16Input], utf8YieldGenerator],121 stripFinalNewline: false,122 });123 t.is(stdout, utf16Input);124};125126test('Newlines re-added to bytes use UTF-8 by default', testUtf8InputNewlines, execa);127test('Newlines re-added to bytes use UTF-8 by default, sync', testUtf8InputNewlines, execaSync);128129// With the `binary` transform option, the transform deals with raw bytes: they are left untouched130const testBinaryUtf16Le = async (t, execaMethod) => {131 const bytes = new Uint8Array(Buffer.from(utf16Input, 'utf16le'));132 const {stdout} = await execaMethod('stdin.js', {133 stdin: [[bytes], noopGenerator(false, true)],134 encoding: 'utf16le',135 stripFinalNewline: false,136 });137 t.is(stdout, utf16Input);138};139140test('"binary: true" leaves utf16le bytes untouched', testBinaryUtf16Le, execa);141test('"binary: true" leaves utf16le bytes untouched, sync', testBinaryUtf16Le, execaSync);
modified:types/arguments/options.d.ts+2 added
157 unmodified lines
158 - [`'hex'`](https://en.wikipedia.org/wiki/Hexadecimal), [`'base64'`](https://en.wikipedia.org/wiki/Base64), [`'base64url'`](https://en.wikipedia.org/wiki/Base64#RFC_4648), [`'latin1'`](https://nodejs.org/api/buffer.html#buffers-and-character-encodings) or [`'ascii'`](https://nodejs.org/api/buffer.html#buffers-and-character-encodings): encodes the binary output as a string.159160 The output is available with `result.stdout`, `result.stderr` and `result.stdio`.161162 String input passed with the `input` or `stdin` option is always encoded with UTF-8, whatever this option is. With a text encoding, `stdin` transforms also decode their input with UTF-8.163164 @default 'utf8'165 */166 readonly encoding?: Encoding;167
260 unmodified lines