Add TypeScript definition (#188)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Dimitri Benin · committed by Sindre Sorhus · parent f24e7c7 · Browse files · 4 files·+669 added−7 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
4 files+669 added−7 removed
- other:+669 added−7 removed
Provenance
- Commit
3db7d2c- Tree
b9e6a01- Author
Dimitri Benin <BendingBender@users.noreply.github.com>- Committer
Sindre Sorhus <sindresorhus@gmail.com>- Parent
f24e7c7
4 files changed+669 added−7 removed
added:index.d.ts+494 added
1+/// <reference types="node"/>2+import {ChildProcess} from 'child_process';3+import {Stream, Readable as ReadableStream} from 'stream';4+5+export type StdioOption =6+ | 'pipe'7+ | 'ipc'8+ | 'ignore'9+ | 'inherit'10+ | Stream11+ | number12+ | null13+ | undefined;14+15+export interface CommonOptions<EncodingType> {16+ /**17+ Current working directory of the child process.18+19+ @default process.cwd()20+ */21+ readonly cwd?: string;22+23+ /**24+ Environment key-value pairs. Extends automatically from `process.env`. Set `extendEnv` to `false` if you don't want this.25+26+ @default process.env27+ */28+ readonly env?: NodeJS.ProcessEnv;29+30+ /**31+ Set to `false` if you don't want to extend the environment variables when providing the `env` property.32+33+ @default true34+ */35+ readonly extendEnv?: boolean;36+37+ /**38+ Explicitly set the value of `argv[0]` sent to the child process. This will be set to `command` or `file` if not specified.39+ */40+ readonly argv0?: string;41+42+ /**43+ Child's [stdio](https://nodejs.org/api/child_process.html#child_process_options_stdio) configuration.44+45+ @default 'pipe'46+ */47+ readonly stdio?: 'pipe' | 'ignore' | 'inherit' | ReadonlyArray<StdioOption>;48+49+ /**50+ Prepare child to run independently of its parent process. Specific behavior [depends on the platform](https://nodejs.org/api/child_process.html#child_process_options_detached).51+52+ @default false53+ */54+ readonly detached?: boolean;55+56+ /**57+ Sets the user identity of the process.58+ */59+ readonly uid?: number;60+61+ /**62+ Sets the group identity of the process.63+ */64+ readonly gid?: number;65+66+ /**67+ If `true`, runs `command` inside of a shell. Uses `/bin/sh` on UNIX and `cmd.exe` on Windows. A different shell can be specified as a string. The shell should understand the `-c` switch on UNIX or `/d /s /c` on Windows.68+69+ @default false70+ */71+ readonly shell?: boolean | string;72+73+ /**74+ Strip the final [newline character](https://en.wikipedia.org/wiki/Newline) from the output.75+76+ @default true77+ */78+ readonly stripFinalNewline?: boolean;79+80+ /**81+ Prefer locally installed binaries when looking for a binary to execute.82+83+ If you `$ npm install foo`, you can then `execa('foo')`.84+85+ @default true86+ */87+ readonly preferLocal?: boolean;88+89+ /**90+ Preferred path to find locally installed binaries in (use with `preferLocal`).91+92+ @default process.cwd()93+ */94+ readonly localDir?: string;95+96+ /**97+ Setting this to `false` resolves the promise with the error instead of rejecting it.98+99+ @default true100+ */101+ readonly reject?: boolean;102+103+ /**104+ Keep track of the spawned process and `kill` it when the parent process exits.105+106+ @default true107+ */108+ readonly cleanup?: boolean;109+110+ /**111+ Specify the character encoding used to decode the `stdout` and `stderr` output. If set to `null`, then `stdout` and `stderr` will be a `Buffer` instead of a string.112+113+ @default 'utf8'114+ */115+ readonly encoding?: EncodingType;116+117+ /**118+ If `timeout` is greater than `0`, the parent will send the signal identified by the `killSignal` property (the default is `SIGTERM`) if the child runs longer than `timeout` milliseconds.119+120+ @default 0121+ */122+ readonly timeout?: number;123+124+ /**125+ Buffer the output from the spawned process. When buffering is disabled you must consume the output of the `stdout` and `stderr` streams because the promise will not be resolved/rejected until they have completed.126+127+ @default true128+ */129+ readonly buffer?: boolean;130+131+ /**132+ Largest amount of data in bytes allowed on `stdout` or `stderr`. Default: 10MB.133+134+ @default 10000000135+ */136+ readonly maxBuffer?: number;137+138+ /**139+ Signal value to be used when the spawned process will be killed.140+141+ @default 'SIGTERM'142+ */143+ readonly killSignal?: string | number;144+145+ /**146+ Same options as [`stdio`](https://nodejs.org/dist/latest-v6.x/docs/api/child_process.html#child_process_options_stdio).147+148+ @default 'pipe'149+ */150+ readonly stdin?: StdioOption;151+152+ /**153+ Same options as [`stdio`](https://nodejs.org/dist/latest-v6.x/docs/api/child_process.html#child_process_options_stdio).154+155+ @default 'pipe'156+ */157+ readonly stdout?: StdioOption;158+159+ /**160+ Same options as [`stdio`](https://nodejs.org/dist/latest-v6.x/docs/api/child_process.html#child_process_options_stdio).161+162+ @default 'pipe'163+ */164+ readonly stderr?: StdioOption;165+166+ /**167+ If `true`, no quoting or escaping of arguments is done on Windows. Ignored on other platforms. This is set to `true` automatically when the `shell` option is `true`.168+169+ @default false170+ */171+ readonly windowsVerbatimArguments?: boolean;172+}173+174+export interface Options<EncodingType = string>175+ extends CommonOptions<EncodingType> {176+ /**177+ Write some input to the `stdin` of your binary.178+ */179+ readonly input?: string | Buffer | ReadableStream;180+}181+182+export interface SyncOptions<EncodingType = string>183+ extends CommonOptions<EncodingType> {184+ /**185+ Write some input to the `stdin` of your binary.186+ */187+ readonly input?: string | Buffer;188+}189+190+export interface ExecaReturnBase<StdoutStderrType> {191+ /**192+ The numeric exit code of the process that was run.193+ */194+ exitCode: number;195+196+ /**197+ The textual exit code of the process that was run.198+ */199+ exitCodeName: string;200+201+ /**202+ The output of the process on stdout.203+ */204+ stdout: StdoutStderrType;205+206+ /**207+ The output of the process on stderr.208+ */209+ stderr: StdoutStderrType;210+211+ /**212+ Whether the process failed to run.213+ */214+ failed: boolean;215+216+ /**217+ The signal that was used to terminate the process.218+ */219+ signal?: string;220+221+ /**222+ The command that was run.223+ */224+ cmd: string;225+226+ /**227+ Whether the process timed out.228+ */229+ timedOut: boolean;230+231+ /**232+ Whether the process was killed.233+ */234+ killed: boolean;235+}236+237+export interface ExecaSyncReturnValue<StdOutErrType = string>238+ extends ExecaReturnBase<StdOutErrType> {239+ /**240+ The exit code of the process that was run.241+ */242+ code: number;243+}244+245+export interface ExecaReturnValue<StdOutErrType = string>246+ extends ExecaSyncReturnValue<StdOutErrType> {247+ /**248+ The output of the process with `stdout` and `stderr` interleaved.249+ */250+ all: StdOutErrType;251+252+ /**253+ Whether the process was canceled.254+ */255+ isCanceled: boolean;256+}257+258+export interface ExecaSyncError<StdOutErrType = string>259+ extends Error,260+ ExecaReturnBase<StdOutErrType> {261+ /**262+ The error message.263+ */264+ message: string;265+266+ /**267+ The exit code (either numeric or textual) of the process that was run.268+ */269+ code: number | string;270+}271+272+export interface ExecaError<StdOutErrType = string>273+ extends ExecaSyncError<StdOutErrType> {274+ /**275+ The output of the process with `stdout` and `stderr` interleaved.276+ */277+ all: StdOutErrType;278+279+ /**280+ Whether the process was canceled.281+ */282+ isCanceled: boolean;283+}284+285+export interface ExecaChildPromise<StdOutErrType> {286+ catch<ResultType = never>(287+ onRejected?:288+ | ((289+ reason: ExecaError<StdOutErrType>290+ ) => ResultType | PromiseLike<ResultType>)291+ | null292+ ): Promise<ExecaReturnValue<StdOutErrType> | ResultType>;293+294+ /**295+ Cancel the subprocess.296+297+ Causes the promise to reject an error with a `.isCanceled = true` property, provided the process gets canceled. The process will not be canceled if it has already exited.298+ */299+ cancel(): void;300+}301+302+export type ExecaChildProcess<StdOutErrType = string> = ChildProcess &303+ ExecaChildPromise<StdOutErrType> &304+ Promise<ExecaReturnValue<StdOutErrType>>;305+306+declare const execa: {307+ /**308+ Execute a file.309+310+ Think of this as a mix of `child_process.execFile` and `child_process.spawn`.311+312+ @param file - The program/script to execute.313+ @param arguments - Arguments to pass to `file` on execution.314+ @returns A [`child_process` instance](https://nodejs.org/api/child_process.html#child_process_class_childprocess), which is enhanced to also be a `Promise` for a result `Object` with `stdout` and `stderr` properties.315+316+ @example317+ ```318+ import execa from 'execa';319+320+ (async () => {321+ const {stdout} = await execa('echo', ['unicorns']);322+ console.log(stdout);323+ //=> 'unicorns'324+325+ // Cancelling a spawned process326+ const subprocess = execa('node');327+ setTimeout(() => { spawned.cancel() }, 1000);328+ try {329+ await subprocess;330+ } catch (error) {331+ console.log(subprocess.killed); // true332+ console.log(error.isCanceled); // true333+ }334+ })();335+336+ // Pipe the child process stdout to the current stdout337+ execa('echo', ['unicorns']).stdout.pipe(process.stdout);338+ ```339+ */340+ (341+ file: string,342+ arguments?: ReadonlyArray<string>,343+ options?: Options344+ ): ExecaChildProcess;345+ (346+ file: string,347+ arguments?: ReadonlyArray<string>,348+ options?: Options<null>349+ ): ExecaChildProcess<Buffer>;350+ (file: string, options?: Options): ExecaChildProcess;351+ (file: string, options?: Options<null>): ExecaChildProcess<Buffer>;352+353+ /**354+ Same as `execa()`, but returns only `stdout`.355+356+ @param file - The program/script to execute.357+ @param arguments - Arguments to pass to `file` on execution.358+ @returns The contents of the executed process' `stdout`.359+ */360+ stdout(361+ file: string,362+ arguments?: ReadonlyArray<string>,363+ options?: Options364+ ): Promise<string>;365+ stdout(366+ file: string,367+ arguments?: ReadonlyArray<string>,368+ options?: Options<null>369+ ): Promise<Buffer>;370+ stdout(file: string, options?: Options): Promise<string>;371+ stdout(file: string, options?: Options<null>): Promise<Buffer>;372+373+ /**374+ Same as `execa()`, but returns only `stderr`.375+376+ @param file - The program/script to execute.377+ @param arguments - Arguments to pass to `file` on execution.378+ @returns The contents of the executed process' `stderr`.379+ */380+ stderr(381+ file: string,382+ arguments?: ReadonlyArray<string>,383+ options?: Options384+ ): Promise<string>;385+ stderr(386+ file: string,387+ arguments?: ReadonlyArray<string>,388+ options?: Options<null>389+ ): Promise<Buffer>;390+ stderr(file: string, options?: Options): Promise<string>;391+ stderr(file: string, options?: Options<null>): Promise<Buffer>;392+393+ /**394+ Execute a command through the system shell.395+396+ Prefer `execa()` whenever possible, as it's both faster and safer.397+398+ @param command - The command to execute.399+ @returns A [`child_process` instance](https://nodejs.org/api/child_process.html#child_process_class_childprocess).400+401+ @example402+ ```403+ import execa from 'execa';404+405+ (async => {406+ // Run a shell command407+ const {stdout} = await execa.shell('echo unicorns');408+ //=> 'unicorns'409+410+ // Catching an error411+ try {412+ await execa.shell('exit 3');413+ } catch (error) {414+ console.log(error);415+ //{416+ // message: 'Command failed with exit code 3 (ESRCH): exit 3',417+ // code: 3,418+ // exitCode: 3,419+ // exitCodeName: 'ESRCH',420+ // stdout: '',421+ // stderr: '',422+ // all: '',423+ // failed: true,424+ // cmd: 'exit 3',425+ // timedOut: false,426+ // killed: false427+ //}428+ }429+ })();430+ ```431+ */432+ shell(command: string, options?: Options): ExecaChildProcess;433+ shell(command: string, options?: Options<null>): ExecaChildProcess<Buffer>;434+435+ /**436+ Execute a file synchronously.437+438+ This method throws an `Error` if the command fails.439+440+ @param file - The program/script to execute.441+ @param arguments - Arguments to pass to `file` on execution.442+ @returns The same result object as [`child_process.spawnSync`](https://nodejs.org/api/child_process.html#child_process_child_process_spawnsync_command_args_options).443+ */444+ sync(445+ file: string,446+ arguments?: ReadonlyArray<string>,447+ options?: SyncOptions448+ ): ExecaSyncReturnValue;449+ sync(450+ file: string,451+ arguments?: ReadonlyArray<string>,452+ options?: SyncOptions<null>453+ ): ExecaSyncReturnValue<Buffer>;454+ sync(file: string, options?: SyncOptions): ExecaSyncReturnValue;455+ sync(file: string, options?: SyncOptions<null>): ExecaSyncReturnValue<Buffer>;456+457+ /**458+ Execute a command synchronously through the system shell.459+460+ This method throws an `Error` if the command fails.461+462+ @param command - The command to execute.463+ @returns The same result object as [`child_process.spawnSync`](https://nodejs.org/api/child_process.html#child_process_child_process_spawnsync_command_args_options).464+465+ @example466+ ```467+ import execa from 'execa';468+469+ try {470+ execa.shellSync('exit 3');471+ } catch (error) {472+ console.log(error);473+ //{474+ // message: 'Command failed with exit code 3 (ESRCH): exit 3',475+ // code: 3,476+ // exitCode: 3,477+ // exitCodeName: 'ESRCH',478+ // stdout: '',479+ // stderr: '',480+ // failed: true,481+ // cmd: 'exit 3',482+ // timedOut: false483+ //}484+ }485+ ```486+ */487+ shellSync(command: string, options?: Options): ExecaSyncReturnValue;488+ shellSync(489+ command: string,490+ options?: Options<null>491+ ): ExecaSyncReturnValue<Buffer>;492+};493+494+export default execa;modified:index.js+8 added-5 removed
223 unmodified lines224 225 return joinedCommand;226 }227 228-module.exports = (command, args, options) => {228+const execa = (command, args, options) => {229 const parsed = handleArgs(command, args, options);230 const {encoding, buffer, maxBuffer} = parsed.options;231 const joinedCommand = joinCommand(command, args);232 140 unmodified lines373 374 return spawned;375 };376 377+module.exports = execa;378+module.exports.default = execa;379+380 // TODO: set `stderr: 'ignore'` when that option is implemented381 module.exports.stdout = async (...args) => {379- const {stdout} = await module.exports(...args);382+ const {stdout} = await execa(...args);383 return stdout;384 };385 386 // TODO: set `stdout: 'ignore'` when that option is implemented387 module.exports.stderr = async (...args) => {385- const {stderr} = await module.exports(...args);388+ const {stderr} = await execa(...args);389 return stderr;390 };391 389-module.exports.shell = (command, options) => handleShell(module.exports, command, options);392+module.exports.shell = (command, options) => handleShell(execa, command, options);393 394 module.exports.sync = (command, args, options) => {395 const parsed = handleArgs(command, args, options);396 const joinedCommand = joinCommand(command, args);29 unmodified lines426 timedOut: false427 };428 };429 427-module.exports.shellSync = (command, options) => handleShell(module.exports.sync, command, options);430+module.exports.shellSync = (command, options) => handleShell(execa.sync, command, options);added:index.test-d.ts+162 added
1+import {expectType, expectError} from 'tsd';2+import execa, {3+ ExecaReturnValue,4+ ExecaChildProcess,5+ ExecaError,6+ ExecaSyncReturnValue,7+ ExecaSyncError8+} from '.';9+10+try {11+ const execaPromise = execa('unicorns');12+ execaPromise.cancel();13+14+ const unicornsResult = await execaPromise;15+ expectType<string>(unicornsResult.cmd);16+ expectType<string | number>(unicornsResult.code);17+ expectType<boolean>(unicornsResult.failed);18+ expectType<boolean>(unicornsResult.killed);19+ expectType<string | undefined>(unicornsResult.signal);20+ expectType<string>(unicornsResult.stderr);21+ expectType<string>(unicornsResult.stdout);22+ expectType<string>(unicornsResult.all);23+ expectType<boolean>(unicornsResult.timedOut);24+ expectType<boolean>(unicornsResult.isCanceled);25+} catch (error) {26+ const execaError: ExecaError = error;27+28+ expectType<string>(execaError.message);29+ expectType<number | string>(execaError.code);30+ expectType<string>(execaError.all);31+ expectType<boolean>(execaError.isCanceled);32+}33+34+try {35+ const unicornsResult = execa.sync('unicorns');36+ expectType<string>(unicornsResult.cmd);37+ expectType<string | number>(unicornsResult.code);38+ expectType<boolean>(unicornsResult.failed);39+ expectType<boolean>(unicornsResult.killed);40+ expectType<string | undefined>(unicornsResult.signal);41+ expectType<string>(unicornsResult.stderr);42+ expectType<string>(unicornsResult.stdout);43+ expectType<boolean>(unicornsResult.timedOut);44+ expectError(unicornsResult.all);45+ expectError(unicornsResult.isCanceled);46+} catch (error) {47+ const execaError: ExecaSyncError = error;48+49+ expectType<string>(execaError.message);50+ expectType<number | string>(execaError.code);51+ expectError(execaError.all);52+ expectError(execaError.isCanceled);53+}54+55+execa('unicorns', {cwd: '.'});56+execa('unicorns', {env: {PATH: ''}});57+execa('unicorns', {extendEnv: false});58+execa('unicorns', {argv0: ''});59+execa('unicorns', {stdio: 'pipe'});60+execa('unicorns', {stdio: 'ignore'});61+execa('unicorns', {stdio: 'inherit'});62+execa('unicorns', {63+ stdio: ['pipe', 'ipc', 'ignore', 'inherit', process.stdin, 1, null, undefined]64+});65+execa('unicorns', {detached: true});66+execa('unicorns', {uid: 0});67+execa('unicorns', {gid: 0});68+execa('unicorns', {shell: true});69+execa('unicorns', {shell: '/bin/sh'});70+execa('unicorns', {stripFinalNewline: false});71+execa('unicorns', {preferLocal: false});72+execa('unicorns', {localDir: '.'});73+execa('unicorns', {reject: false});74+execa('unicorns', {cleanup: false});75+execa('unicorns', {timeout: 1000});76+execa('unicorns', {buffer: false});77+execa('unicorns', {maxBuffer: 1000});78+execa('unicorns', {killSignal: 'SIGTERM'});79+execa('unicorns', {killSignal: 9});80+execa('unicorns', {stdin: 'pipe'});81+execa('unicorns', {stdin: 'ipc'});82+execa('unicorns', {stdin: 'ignore'});83+execa('unicorns', {stdin: 'inherit'});84+execa('unicorns', {stdin: process.stdin});85+execa('unicorns', {stdin: 1});86+execa('unicorns', {stdin: null});87+execa('unicorns', {stdin: undefined});88+execa('unicorns', {stderr: 'pipe'});89+execa('unicorns', {stderr: 'ipc'});90+execa('unicorns', {stderr: 'ignore'});91+execa('unicorns', {stderr: 'inherit'});92+execa('unicorns', {stderr: process.stderr});93+execa('unicorns', {stderr: 1});94+execa('unicorns', {stderr: null});95+execa('unicorns', {stderr: undefined});96+execa('unicorns', {stdout: 'pipe'});97+execa('unicorns', {stdout: 'ipc'});98+execa('unicorns', {stdout: 'ignore'});99+execa('unicorns', {stdout: 'inherit'});100+execa('unicorns', {stdout: process.stdout});101+execa('unicorns', {stdout: 1});102+execa('unicorns', {stdout: null});103+execa('unicorns', {stdout: undefined});104+execa('unicorns', {windowsVerbatimArguments: true});105+106+expectType<ExecaChildProcess<string>>(execa('unicorns'));107+expectType<ExecaReturnValue<string>>(await execa('unicorns'));108+expectType<ExecaReturnValue<string>>(109+ await execa('unicorns', {encoding: 'utf8'})110+);111+expectType<ExecaReturnValue<Buffer>>(await execa('unicorns', {encoding: null}));112+expectType<ExecaReturnValue<string>>(113+ await execa('unicorns', ['foo'], {encoding: 'utf8'})114+);115+expectType<ExecaReturnValue<Buffer>>(116+ await execa('unicorns', ['foo'], {encoding: null})117+);118+119+expectType<Promise<string>>(execa.stdout('unicorns'));120+expectType<string>(await execa.stdout('unicorns'));121+expectType<string>(await execa.stdout('unicorns', {encoding: 'utf8'}));122+expectType<Buffer>(await execa.stdout('unicorns', {encoding: null}));123+expectType<string>(await execa.stdout('unicorns', ['foo'], {encoding: 'utf8'}));124+expectType<Buffer>(await execa.stdout('unicorns', ['foo'], {encoding: null}));125+126+expectType<Promise<string>>(execa.stderr('unicorns'));127+expectType<string>(await execa.stderr('unicorns'));128+expectType<string>(await execa.stderr('unicorns', {encoding: 'utf8'}));129+expectType<Buffer>(await execa.stderr('unicorns', {encoding: null}));130+expectType<string>(await execa.stderr('unicorns', ['foo'], {encoding: 'utf8'}));131+expectType<Buffer>(await execa.stderr('unicorns', ['foo'], {encoding: null}));132+133+expectType<ExecaChildProcess<string>>(execa.shell('unicorns'));134+expectType<ExecaReturnValue<string>>(await execa.shell('unicorns'));135+expectType<ExecaReturnValue<string>>(136+ await execa.shell('unicorns', {encoding: 'utf8'})137+);138+expectType<ExecaReturnValue<Buffer>>(139+ await execa.shell('unicorns', {encoding: null})140+);141+142+expectType<ExecaSyncReturnValue<string>>(execa.sync('unicorns'));143+expectType<ExecaSyncReturnValue<string>>(144+ execa.sync('unicorns', {encoding: 'utf8'})145+);146+expectType<ExecaSyncReturnValue<Buffer>>(147+ execa.sync('unicorns', {encoding: null})148+);149+expectType<ExecaSyncReturnValue<string>>(150+ execa.sync('unicorns', ['foo'], {encoding: 'utf8'})151+);152+expectType<ExecaSyncReturnValue<Buffer>>(153+ execa.sync('unicorns', ['foo'], {encoding: null})154+);155+156+expectType<ExecaSyncReturnValue<string>>(execa.shellSync('unicorns'));157+expectType<ExecaSyncReturnValue<string>>(158+ execa.shellSync('unicorns', {encoding: 'utf8'})159+);160+expectType<ExecaSyncReturnValue<Buffer>>(161+ execa.shellSync('unicorns', {encoding: null})162+);modified:package.json+5 added-2 removed
11 unmodified lines121314151616171819202122232415 unmodified lines404142434344454647484950515253545556575859606162636 unmodified lines11 unmodified lines "engines": { "node": ">=8" }, "scripts": { "test": "xo && nyc ava" "test": "xo && nyc ava && tsd" }, "files": [ "index.js", "index.d.ts", "lib" ], "keywords": [ "exec",15 unmodified lines "dependencies": { "cross-spawn": "^6.0.0", "get-stream": "^4.0.0", "is-stream": "^1.1.0", "merge-stream": "1.0.1", "merge-stream": "^1.0.1", "npm-run-path": "^2.0.0", "p-finally": "^1.0.0", "signal-exit": "^3.0.0", "strip-final-newline": "^2.0.0" }, "devDependencies": { "@types/node": "^11.11.4", "ava": "^1.3.1", "cat-names": "^2.0.0", "coveralls": "^3.0.3", "delay": "^4.1.0", "is-running": "^2.0.0", "nyc": "^13.3.0", "tempfile": "^2.0.0", "tsd": "^0.7.0", "xo": "^0.24.0" }, "nyc": { "exclude": [6 unmodified lines