vendor-index.fbec8a81.mjs 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071
  1. import { Buffer } from 'buffer';
  2. import path from 'path';
  3. import childProcess from 'child_process';
  4. import process$1 from 'process';
  5. import { m as mergeStream, g as getStream, c as crossSpawn } from './vendor-index.2ae8040a.mjs';
  6. import url from 'url';
  7. import require$$0, { constants } from 'os';
  8. import { s as signalExit } from './vendor-index.29636037.mjs';
  9. function stripFinalNewline(input) {
  10. const LF = typeof input === 'string' ? '\n' : '\n'.charCodeAt();
  11. const CR = typeof input === 'string' ? '\r' : '\r'.charCodeAt();
  12. if (input[input.length - 1] === LF) {
  13. input = input.slice(0, -1);
  14. }
  15. if (input[input.length - 1] === CR) {
  16. input = input.slice(0, -1);
  17. }
  18. return input;
  19. }
  20. function pathKey(options = {}) {
  21. const {
  22. env = process.env,
  23. platform = process.platform
  24. } = options;
  25. if (platform !== 'win32') {
  26. return 'PATH';
  27. }
  28. return Object.keys(env).reverse().find(key => key.toUpperCase() === 'PATH') || 'Path';
  29. }
  30. function npmRunPath(options = {}) {
  31. const {
  32. cwd = process$1.cwd(),
  33. path: path_ = process$1.env[pathKey()],
  34. execPath = process$1.execPath,
  35. } = options;
  36. let previous;
  37. const cwdString = cwd instanceof URL ? url.fileURLToPath(cwd) : cwd;
  38. let cwdPath = path.resolve(cwdString);
  39. const result = [];
  40. while (previous !== cwdPath) {
  41. result.push(path.join(cwdPath, 'node_modules/.bin'));
  42. previous = cwdPath;
  43. cwdPath = path.resolve(cwdPath, '..');
  44. }
  45. // Ensure the running `node` binary is used.
  46. result.push(path.resolve(cwdString, execPath, '..'));
  47. return [...result, path_].join(path.delimiter);
  48. }
  49. function npmRunPathEnv({env = process$1.env, ...options} = {}) {
  50. env = {...env};
  51. const path = pathKey({env});
  52. options.path = env[path];
  53. env[path] = npmRunPath(options);
  54. return env;
  55. }
  56. const copyProperty = (to, from, property, ignoreNonConfigurable) => {
  57. // `Function#length` should reflect the parameters of `to` not `from` since we keep its body.
  58. // `Function#prototype` is non-writable and non-configurable so can never be modified.
  59. if (property === 'length' || property === 'prototype') {
  60. return;
  61. }
  62. // `Function#arguments` and `Function#caller` should not be copied. They were reported to be present in `Reflect.ownKeys` for some devices in React Native (#41), so we explicitly ignore them here.
  63. if (property === 'arguments' || property === 'caller') {
  64. return;
  65. }
  66. const toDescriptor = Object.getOwnPropertyDescriptor(to, property);
  67. const fromDescriptor = Object.getOwnPropertyDescriptor(from, property);
  68. if (!canCopyProperty(toDescriptor, fromDescriptor) && ignoreNonConfigurable) {
  69. return;
  70. }
  71. Object.defineProperty(to, property, fromDescriptor);
  72. };
  73. // `Object.defineProperty()` throws if the property exists, is not configurable and either:
  74. // - one its descriptors is changed
  75. // - it is non-writable and its value is changed
  76. const canCopyProperty = function (toDescriptor, fromDescriptor) {
  77. return toDescriptor === undefined || toDescriptor.configurable || (
  78. toDescriptor.writable === fromDescriptor.writable &&
  79. toDescriptor.enumerable === fromDescriptor.enumerable &&
  80. toDescriptor.configurable === fromDescriptor.configurable &&
  81. (toDescriptor.writable || toDescriptor.value === fromDescriptor.value)
  82. );
  83. };
  84. const changePrototype = (to, from) => {
  85. const fromPrototype = Object.getPrototypeOf(from);
  86. if (fromPrototype === Object.getPrototypeOf(to)) {
  87. return;
  88. }
  89. Object.setPrototypeOf(to, fromPrototype);
  90. };
  91. const wrappedToString = (withName, fromBody) => `/* Wrapped ${withName}*/\n${fromBody}`;
  92. const toStringDescriptor = Object.getOwnPropertyDescriptor(Function.prototype, 'toString');
  93. const toStringName = Object.getOwnPropertyDescriptor(Function.prototype.toString, 'name');
  94. // We call `from.toString()` early (not lazily) to ensure `from` can be garbage collected.
  95. // We use `bind()` instead of a closure for the same reason.
  96. // Calling `from.toString()` early also allows caching it in case `to.toString()` is called several times.
  97. const changeToString = (to, from, name) => {
  98. const withName = name === '' ? '' : `with ${name.trim()}() `;
  99. const newToString = wrappedToString.bind(null, withName, from.toString());
  100. // Ensure `to.toString.toString` is non-enumerable and has the same `same`
  101. Object.defineProperty(newToString, 'name', toStringName);
  102. Object.defineProperty(to, 'toString', {...toStringDescriptor, value: newToString});
  103. };
  104. function mimicFunction(to, from, {ignoreNonConfigurable = false} = {}) {
  105. const {name} = to;
  106. for (const property of Reflect.ownKeys(from)) {
  107. copyProperty(to, from, property, ignoreNonConfigurable);
  108. }
  109. changePrototype(to, from);
  110. changeToString(to, from, name);
  111. return to;
  112. }
  113. const calledFunctions = new WeakMap();
  114. const onetime = (function_, options = {}) => {
  115. if (typeof function_ !== 'function') {
  116. throw new TypeError('Expected a function');
  117. }
  118. let returnValue;
  119. let callCount = 0;
  120. const functionName = function_.displayName || function_.name || '<anonymous>';
  121. const onetime = function (...arguments_) {
  122. calledFunctions.set(onetime, ++callCount);
  123. if (callCount === 1) {
  124. returnValue = function_.apply(this, arguments_);
  125. function_ = null;
  126. } else if (options.throw === true) {
  127. throw new Error(`Function \`${functionName}\` can only be called once`);
  128. }
  129. return returnValue;
  130. };
  131. mimicFunction(onetime, function_);
  132. calledFunctions.set(onetime, callCount);
  133. return onetime;
  134. };
  135. onetime.callCount = function_ => {
  136. if (!calledFunctions.has(function_)) {
  137. throw new Error(`The given function \`${function_.name}\` is not wrapped by the \`onetime\` package`);
  138. }
  139. return calledFunctions.get(function_);
  140. };
  141. const getRealtimeSignals=function(){
  142. const length=SIGRTMAX-SIGRTMIN+1;
  143. return Array.from({length},getRealtimeSignal);
  144. };
  145. const getRealtimeSignal=function(value,index){
  146. return {
  147. name:`SIGRT${index+1}`,
  148. number:SIGRTMIN+index,
  149. action:"terminate",
  150. description:"Application-specific signal (realtime)",
  151. standard:"posix"};
  152. };
  153. const SIGRTMIN=34;
  154. const SIGRTMAX=64;
  155. const SIGNALS=[
  156. {
  157. name:"SIGHUP",
  158. number:1,
  159. action:"terminate",
  160. description:"Terminal closed",
  161. standard:"posix"},
  162. {
  163. name:"SIGINT",
  164. number:2,
  165. action:"terminate",
  166. description:"User interruption with CTRL-C",
  167. standard:"ansi"},
  168. {
  169. name:"SIGQUIT",
  170. number:3,
  171. action:"core",
  172. description:"User interruption with CTRL-\\",
  173. standard:"posix"},
  174. {
  175. name:"SIGILL",
  176. number:4,
  177. action:"core",
  178. description:"Invalid machine instruction",
  179. standard:"ansi"},
  180. {
  181. name:"SIGTRAP",
  182. number:5,
  183. action:"core",
  184. description:"Debugger breakpoint",
  185. standard:"posix"},
  186. {
  187. name:"SIGABRT",
  188. number:6,
  189. action:"core",
  190. description:"Aborted",
  191. standard:"ansi"},
  192. {
  193. name:"SIGIOT",
  194. number:6,
  195. action:"core",
  196. description:"Aborted",
  197. standard:"bsd"},
  198. {
  199. name:"SIGBUS",
  200. number:7,
  201. action:"core",
  202. description:
  203. "Bus error due to misaligned, non-existing address or paging error",
  204. standard:"bsd"},
  205. {
  206. name:"SIGEMT",
  207. number:7,
  208. action:"terminate",
  209. description:"Command should be emulated but is not implemented",
  210. standard:"other"},
  211. {
  212. name:"SIGFPE",
  213. number:8,
  214. action:"core",
  215. description:"Floating point arithmetic error",
  216. standard:"ansi"},
  217. {
  218. name:"SIGKILL",
  219. number:9,
  220. action:"terminate",
  221. description:"Forced termination",
  222. standard:"posix",
  223. forced:true},
  224. {
  225. name:"SIGUSR1",
  226. number:10,
  227. action:"terminate",
  228. description:"Application-specific signal",
  229. standard:"posix"},
  230. {
  231. name:"SIGSEGV",
  232. number:11,
  233. action:"core",
  234. description:"Segmentation fault",
  235. standard:"ansi"},
  236. {
  237. name:"SIGUSR2",
  238. number:12,
  239. action:"terminate",
  240. description:"Application-specific signal",
  241. standard:"posix"},
  242. {
  243. name:"SIGPIPE",
  244. number:13,
  245. action:"terminate",
  246. description:"Broken pipe or socket",
  247. standard:"posix"},
  248. {
  249. name:"SIGALRM",
  250. number:14,
  251. action:"terminate",
  252. description:"Timeout or timer",
  253. standard:"posix"},
  254. {
  255. name:"SIGTERM",
  256. number:15,
  257. action:"terminate",
  258. description:"Termination",
  259. standard:"ansi"},
  260. {
  261. name:"SIGSTKFLT",
  262. number:16,
  263. action:"terminate",
  264. description:"Stack is empty or overflowed",
  265. standard:"other"},
  266. {
  267. name:"SIGCHLD",
  268. number:17,
  269. action:"ignore",
  270. description:"Child process terminated, paused or unpaused",
  271. standard:"posix"},
  272. {
  273. name:"SIGCLD",
  274. number:17,
  275. action:"ignore",
  276. description:"Child process terminated, paused or unpaused",
  277. standard:"other"},
  278. {
  279. name:"SIGCONT",
  280. number:18,
  281. action:"unpause",
  282. description:"Unpaused",
  283. standard:"posix",
  284. forced:true},
  285. {
  286. name:"SIGSTOP",
  287. number:19,
  288. action:"pause",
  289. description:"Paused",
  290. standard:"posix",
  291. forced:true},
  292. {
  293. name:"SIGTSTP",
  294. number:20,
  295. action:"pause",
  296. description:"Paused using CTRL-Z or \"suspend\"",
  297. standard:"posix"},
  298. {
  299. name:"SIGTTIN",
  300. number:21,
  301. action:"pause",
  302. description:"Background process cannot read terminal input",
  303. standard:"posix"},
  304. {
  305. name:"SIGBREAK",
  306. number:21,
  307. action:"terminate",
  308. description:"User interruption with CTRL-BREAK",
  309. standard:"other"},
  310. {
  311. name:"SIGTTOU",
  312. number:22,
  313. action:"pause",
  314. description:"Background process cannot write to terminal output",
  315. standard:"posix"},
  316. {
  317. name:"SIGURG",
  318. number:23,
  319. action:"ignore",
  320. description:"Socket received out-of-band data",
  321. standard:"bsd"},
  322. {
  323. name:"SIGXCPU",
  324. number:24,
  325. action:"core",
  326. description:"Process timed out",
  327. standard:"bsd"},
  328. {
  329. name:"SIGXFSZ",
  330. number:25,
  331. action:"core",
  332. description:"File too big",
  333. standard:"bsd"},
  334. {
  335. name:"SIGVTALRM",
  336. number:26,
  337. action:"terminate",
  338. description:"Timeout or timer",
  339. standard:"bsd"},
  340. {
  341. name:"SIGPROF",
  342. number:27,
  343. action:"terminate",
  344. description:"Timeout or timer",
  345. standard:"bsd"},
  346. {
  347. name:"SIGWINCH",
  348. number:28,
  349. action:"ignore",
  350. description:"Terminal window size changed",
  351. standard:"bsd"},
  352. {
  353. name:"SIGIO",
  354. number:29,
  355. action:"terminate",
  356. description:"I/O is available",
  357. standard:"other"},
  358. {
  359. name:"SIGPOLL",
  360. number:29,
  361. action:"terminate",
  362. description:"Watched event",
  363. standard:"other"},
  364. {
  365. name:"SIGINFO",
  366. number:29,
  367. action:"ignore",
  368. description:"Request for process information",
  369. standard:"other"},
  370. {
  371. name:"SIGPWR",
  372. number:30,
  373. action:"terminate",
  374. description:"Device running out of power",
  375. standard:"systemv"},
  376. {
  377. name:"SIGSYS",
  378. number:31,
  379. action:"core",
  380. description:"Invalid system call",
  381. standard:"other"},
  382. {
  383. name:"SIGUNUSED",
  384. number:31,
  385. action:"terminate",
  386. description:"Invalid system call",
  387. standard:"other"}];
  388. const getSignals=function(){
  389. const realtimeSignals=getRealtimeSignals();
  390. const signals=[...SIGNALS,...realtimeSignals].map(normalizeSignal);
  391. return signals;
  392. };
  393. const normalizeSignal=function({
  394. name,
  395. number:defaultNumber,
  396. description,
  397. action,
  398. forced=false,
  399. standard})
  400. {
  401. const{
  402. signals:{[name]:constantSignal}}=
  403. constants;
  404. const supported=constantSignal!==undefined;
  405. const number=supported?constantSignal:defaultNumber;
  406. return {name,number,description,supported,action,forced,standard};
  407. };
  408. const getSignalsByName=function(){
  409. const signals=getSignals();
  410. return signals.reduce(getSignalByName,{});
  411. };
  412. const getSignalByName=function(
  413. signalByNameMemo,
  414. {name,number,description,supported,action,forced,standard})
  415. {
  416. return {
  417. ...signalByNameMemo,
  418. [name]:{name,number,description,supported,action,forced,standard}};
  419. };
  420. const signalsByName=getSignalsByName();
  421. const getSignalsByNumber=function(){
  422. const signals=getSignals();
  423. const length=SIGRTMAX+1;
  424. const signalsA=Array.from({length},(value,number)=>
  425. getSignalByNumber(number,signals));
  426. return Object.assign({},...signalsA);
  427. };
  428. const getSignalByNumber=function(number,signals){
  429. const signal=findSignalByNumber(number,signals);
  430. if(signal===undefined){
  431. return {};
  432. }
  433. const{name,description,supported,action,forced,standard}=signal;
  434. return {
  435. [number]:{
  436. name,
  437. number,
  438. description,
  439. supported,
  440. action,
  441. forced,
  442. standard}};
  443. };
  444. const findSignalByNumber=function(number,signals){
  445. const signal=signals.find(({name})=>constants.signals[name]===number);
  446. if(signal!==undefined){
  447. return signal;
  448. }
  449. return signals.find((signalA)=>signalA.number===number);
  450. };
  451. getSignalsByNumber();
  452. const getErrorPrefix = ({timedOut, timeout, errorCode, signal, signalDescription, exitCode, isCanceled}) => {
  453. if (timedOut) {
  454. return `timed out after ${timeout} milliseconds`;
  455. }
  456. if (isCanceled) {
  457. return 'was canceled';
  458. }
  459. if (errorCode !== undefined) {
  460. return `failed with ${errorCode}`;
  461. }
  462. if (signal !== undefined) {
  463. return `was killed with ${signal} (${signalDescription})`;
  464. }
  465. if (exitCode !== undefined) {
  466. return `failed with exit code ${exitCode}`;
  467. }
  468. return 'failed';
  469. };
  470. const makeError = ({
  471. stdout,
  472. stderr,
  473. all,
  474. error,
  475. signal,
  476. exitCode,
  477. command,
  478. escapedCommand,
  479. timedOut,
  480. isCanceled,
  481. killed,
  482. parsed: {options: {timeout}},
  483. }) => {
  484. // `signal` and `exitCode` emitted on `spawned.on('exit')` event can be `null`.
  485. // We normalize them to `undefined`
  486. exitCode = exitCode === null ? undefined : exitCode;
  487. signal = signal === null ? undefined : signal;
  488. const signalDescription = signal === undefined ? undefined : signalsByName[signal].description;
  489. const errorCode = error && error.code;
  490. const prefix = getErrorPrefix({timedOut, timeout, errorCode, signal, signalDescription, exitCode, isCanceled});
  491. const execaMessage = `Command ${prefix}: ${command}`;
  492. const isError = Object.prototype.toString.call(error) === '[object Error]';
  493. const shortMessage = isError ? `${execaMessage}\n${error.message}` : execaMessage;
  494. const message = [shortMessage, stderr, stdout].filter(Boolean).join('\n');
  495. if (isError) {
  496. error.originalMessage = error.message;
  497. error.message = message;
  498. } else {
  499. error = new Error(message);
  500. }
  501. error.shortMessage = shortMessage;
  502. error.command = command;
  503. error.escapedCommand = escapedCommand;
  504. error.exitCode = exitCode;
  505. error.signal = signal;
  506. error.signalDescription = signalDescription;
  507. error.stdout = stdout;
  508. error.stderr = stderr;
  509. if (all !== undefined) {
  510. error.all = all;
  511. }
  512. if ('bufferedData' in error) {
  513. delete error.bufferedData;
  514. }
  515. error.failed = true;
  516. error.timedOut = Boolean(timedOut);
  517. error.isCanceled = isCanceled;
  518. error.killed = killed && !timedOut;
  519. return error;
  520. };
  521. const aliases = ['stdin', 'stdout', 'stderr'];
  522. const hasAlias = options => aliases.some(alias => options[alias] !== undefined);
  523. const normalizeStdio = options => {
  524. if (!options) {
  525. return;
  526. }
  527. const {stdio} = options;
  528. if (stdio === undefined) {
  529. return aliases.map(alias => options[alias]);
  530. }
  531. if (hasAlias(options)) {
  532. throw new Error(`It's not possible to provide \`stdio\` in combination with one of ${aliases.map(alias => `\`${alias}\``).join(', ')}`);
  533. }
  534. if (typeof stdio === 'string') {
  535. return stdio;
  536. }
  537. if (!Array.isArray(stdio)) {
  538. throw new TypeError(`Expected \`stdio\` to be of type \`string\` or \`Array\`, got \`${typeof stdio}\``);
  539. }
  540. const length = Math.max(stdio.length, aliases.length);
  541. return Array.from({length}, (value, index) => stdio[index]);
  542. };
  543. const DEFAULT_FORCE_KILL_TIMEOUT = 1000 * 5;
  544. // Monkey-patches `childProcess.kill()` to add `forceKillAfterTimeout` behavior
  545. const spawnedKill = (kill, signal = 'SIGTERM', options = {}) => {
  546. const killResult = kill(signal);
  547. setKillTimeout(kill, signal, options, killResult);
  548. return killResult;
  549. };
  550. const setKillTimeout = (kill, signal, options, killResult) => {
  551. if (!shouldForceKill(signal, options, killResult)) {
  552. return;
  553. }
  554. const timeout = getForceKillAfterTimeout(options);
  555. const t = setTimeout(() => {
  556. kill('SIGKILL');
  557. }, timeout);
  558. // Guarded because there's no `.unref()` when `execa` is used in the renderer
  559. // process in Electron. This cannot be tested since we don't run tests in
  560. // Electron.
  561. // istanbul ignore else
  562. if (t.unref) {
  563. t.unref();
  564. }
  565. };
  566. const shouldForceKill = (signal, {forceKillAfterTimeout}, killResult) => isSigterm(signal) && forceKillAfterTimeout !== false && killResult;
  567. const isSigterm = signal => signal === require$$0.constants.signals.SIGTERM
  568. || (typeof signal === 'string' && signal.toUpperCase() === 'SIGTERM');
  569. const getForceKillAfterTimeout = ({forceKillAfterTimeout = true}) => {
  570. if (forceKillAfterTimeout === true) {
  571. return DEFAULT_FORCE_KILL_TIMEOUT;
  572. }
  573. if (!Number.isFinite(forceKillAfterTimeout) || forceKillAfterTimeout < 0) {
  574. throw new TypeError(`Expected the \`forceKillAfterTimeout\` option to be a non-negative integer, got \`${forceKillAfterTimeout}\` (${typeof forceKillAfterTimeout})`);
  575. }
  576. return forceKillAfterTimeout;
  577. };
  578. // `childProcess.cancel()`
  579. const spawnedCancel = (spawned, context) => {
  580. const killResult = spawned.kill();
  581. if (killResult) {
  582. context.isCanceled = true;
  583. }
  584. };
  585. const timeoutKill = (spawned, signal, reject) => {
  586. spawned.kill(signal);
  587. reject(Object.assign(new Error('Timed out'), {timedOut: true, signal}));
  588. };
  589. // `timeout` option handling
  590. const setupTimeout = (spawned, {timeout, killSignal = 'SIGTERM'}, spawnedPromise) => {
  591. if (timeout === 0 || timeout === undefined) {
  592. return spawnedPromise;
  593. }
  594. let timeoutId;
  595. const timeoutPromise = new Promise((resolve, reject) => {
  596. timeoutId = setTimeout(() => {
  597. timeoutKill(spawned, killSignal, reject);
  598. }, timeout);
  599. });
  600. const safeSpawnedPromise = spawnedPromise.finally(() => {
  601. clearTimeout(timeoutId);
  602. });
  603. return Promise.race([timeoutPromise, safeSpawnedPromise]);
  604. };
  605. const validateTimeout = ({timeout}) => {
  606. if (timeout !== undefined && (!Number.isFinite(timeout) || timeout < 0)) {
  607. throw new TypeError(`Expected the \`timeout\` option to be a non-negative integer, got \`${timeout}\` (${typeof timeout})`);
  608. }
  609. };
  610. // `cleanup` option handling
  611. const setExitHandler = async (spawned, {cleanup, detached}, timedPromise) => {
  612. if (!cleanup || detached) {
  613. return timedPromise;
  614. }
  615. const removeExitHandler = signalExit.exports(() => {
  616. spawned.kill();
  617. });
  618. return timedPromise.finally(() => {
  619. removeExitHandler();
  620. });
  621. };
  622. function isStream(stream) {
  623. return stream !== null
  624. && typeof stream === 'object'
  625. && typeof stream.pipe === 'function';
  626. }
  627. // `input` option
  628. const handleInput = (spawned, input) => {
  629. // Checking for stdin is workaround for https://github.com/nodejs/node/issues/26852
  630. // @todo remove `|| spawned.stdin === undefined` once we drop support for Node.js <=12.2.0
  631. if (input === undefined || spawned.stdin === undefined) {
  632. return;
  633. }
  634. if (isStream(input)) {
  635. input.pipe(spawned.stdin);
  636. } else {
  637. spawned.stdin.end(input);
  638. }
  639. };
  640. // `all` interleaves `stdout` and `stderr`
  641. const makeAllStream = (spawned, {all}) => {
  642. if (!all || (!spawned.stdout && !spawned.stderr)) {
  643. return;
  644. }
  645. const mixed = mergeStream();
  646. if (spawned.stdout) {
  647. mixed.add(spawned.stdout);
  648. }
  649. if (spawned.stderr) {
  650. mixed.add(spawned.stderr);
  651. }
  652. return mixed;
  653. };
  654. // On failure, `result.stdout|stderr|all` should contain the currently buffered stream
  655. const getBufferedData = async (stream, streamPromise) => {
  656. if (!stream) {
  657. return;
  658. }
  659. stream.destroy();
  660. try {
  661. return await streamPromise;
  662. } catch (error) {
  663. return error.bufferedData;
  664. }
  665. };
  666. const getStreamPromise = (stream, {encoding, buffer, maxBuffer}) => {
  667. if (!stream || !buffer) {
  668. return;
  669. }
  670. if (encoding) {
  671. return getStream.exports(stream, {encoding, maxBuffer});
  672. }
  673. return getStream.exports.buffer(stream, {maxBuffer});
  674. };
  675. // Retrieve result of child process: exit code, signal, error, streams (stdout/stderr/all)
  676. const getSpawnedResult = async ({stdout, stderr, all}, {encoding, buffer, maxBuffer}, processDone) => {
  677. const stdoutPromise = getStreamPromise(stdout, {encoding, buffer, maxBuffer});
  678. const stderrPromise = getStreamPromise(stderr, {encoding, buffer, maxBuffer});
  679. const allPromise = getStreamPromise(all, {encoding, buffer, maxBuffer: maxBuffer * 2});
  680. try {
  681. return await Promise.all([processDone, stdoutPromise, stderrPromise, allPromise]);
  682. } catch (error) {
  683. return Promise.all([
  684. {error, signal: error.signal, timedOut: error.timedOut},
  685. getBufferedData(stdout, stdoutPromise),
  686. getBufferedData(stderr, stderrPromise),
  687. getBufferedData(all, allPromise),
  688. ]);
  689. }
  690. };
  691. const nativePromisePrototype = (async () => {})().constructor.prototype;
  692. const descriptors = ['then', 'catch', 'finally'].map(property => [
  693. property,
  694. Reflect.getOwnPropertyDescriptor(nativePromisePrototype, property),
  695. ]);
  696. // The return value is a mixin of `childProcess` and `Promise`
  697. const mergePromise = (spawned, promise) => {
  698. for (const [property, descriptor] of descriptors) {
  699. // Starting the main `promise` is deferred to avoid consuming streams
  700. const value = typeof promise === 'function'
  701. ? (...args) => Reflect.apply(descriptor.value, promise(), args)
  702. : descriptor.value.bind(promise);
  703. Reflect.defineProperty(spawned, property, {...descriptor, value});
  704. }
  705. return spawned;
  706. };
  707. // Use promises instead of `child_process` events
  708. const getSpawnedPromise = spawned => new Promise((resolve, reject) => {
  709. spawned.on('exit', (exitCode, signal) => {
  710. resolve({exitCode, signal});
  711. });
  712. spawned.on('error', error => {
  713. reject(error);
  714. });
  715. if (spawned.stdin) {
  716. spawned.stdin.on('error', error => {
  717. reject(error);
  718. });
  719. }
  720. });
  721. const normalizeArgs = (file, args = []) => {
  722. if (!Array.isArray(args)) {
  723. return [file];
  724. }
  725. return [file, ...args];
  726. };
  727. const NO_ESCAPE_REGEXP = /^[\w.-]+$/;
  728. const DOUBLE_QUOTES_REGEXP = /"/g;
  729. const escapeArg = arg => {
  730. if (typeof arg !== 'string' || NO_ESCAPE_REGEXP.test(arg)) {
  731. return arg;
  732. }
  733. return `"${arg.replace(DOUBLE_QUOTES_REGEXP, '\\"')}"`;
  734. };
  735. const joinCommand = (file, args) => normalizeArgs(file, args).join(' ');
  736. const getEscapedCommand = (file, args) => normalizeArgs(file, args).map(arg => escapeArg(arg)).join(' ');
  737. const DEFAULT_MAX_BUFFER = 1000 * 1000 * 100;
  738. const getEnv = ({env: envOption, extendEnv, preferLocal, localDir, execPath}) => {
  739. const env = extendEnv ? {...process$1.env, ...envOption} : envOption;
  740. if (preferLocal) {
  741. return npmRunPathEnv({env, cwd: localDir, execPath});
  742. }
  743. return env;
  744. };
  745. const handleArguments = (file, args, options = {}) => {
  746. const parsed = crossSpawn.exports._parse(file, args, options);
  747. file = parsed.command;
  748. args = parsed.args;
  749. options = parsed.options;
  750. options = {
  751. maxBuffer: DEFAULT_MAX_BUFFER,
  752. buffer: true,
  753. stripFinalNewline: true,
  754. extendEnv: true,
  755. preferLocal: false,
  756. localDir: options.cwd || process$1.cwd(),
  757. execPath: process$1.execPath,
  758. encoding: 'utf8',
  759. reject: true,
  760. cleanup: true,
  761. all: false,
  762. windowsHide: true,
  763. ...options,
  764. };
  765. options.env = getEnv(options);
  766. options.stdio = normalizeStdio(options);
  767. if (process$1.platform === 'win32' && path.basename(file, '.exe') === 'cmd') {
  768. // #116
  769. args.unshift('/q');
  770. }
  771. return {file, args, options, parsed};
  772. };
  773. const handleOutput = (options, value, error) => {
  774. if (typeof value !== 'string' && !Buffer.isBuffer(value)) {
  775. // When `execaSync()` errors, we normalize it to '' to mimic `execa()`
  776. return error === undefined ? undefined : '';
  777. }
  778. if (options.stripFinalNewline) {
  779. return stripFinalNewline(value);
  780. }
  781. return value;
  782. };
  783. function execa(file, args, options) {
  784. const parsed = handleArguments(file, args, options);
  785. const command = joinCommand(file, args);
  786. const escapedCommand = getEscapedCommand(file, args);
  787. validateTimeout(parsed.options);
  788. let spawned;
  789. try {
  790. spawned = childProcess.spawn(parsed.file, parsed.args, parsed.options);
  791. } catch (error) {
  792. // Ensure the returned error is always both a promise and a child process
  793. const dummySpawned = new childProcess.ChildProcess();
  794. const errorPromise = Promise.reject(makeError({
  795. error,
  796. stdout: '',
  797. stderr: '',
  798. all: '',
  799. command,
  800. escapedCommand,
  801. parsed,
  802. timedOut: false,
  803. isCanceled: false,
  804. killed: false,
  805. }));
  806. return mergePromise(dummySpawned, errorPromise);
  807. }
  808. const spawnedPromise = getSpawnedPromise(spawned);
  809. const timedPromise = setupTimeout(spawned, parsed.options, spawnedPromise);
  810. const processDone = setExitHandler(spawned, parsed.options, timedPromise);
  811. const context = {isCanceled: false};
  812. spawned.kill = spawnedKill.bind(null, spawned.kill.bind(spawned));
  813. spawned.cancel = spawnedCancel.bind(null, spawned, context);
  814. const handlePromise = async () => {
  815. const [{error, exitCode, signal, timedOut}, stdoutResult, stderrResult, allResult] = await getSpawnedResult(spawned, parsed.options, processDone);
  816. const stdout = handleOutput(parsed.options, stdoutResult);
  817. const stderr = handleOutput(parsed.options, stderrResult);
  818. const all = handleOutput(parsed.options, allResult);
  819. if (error || exitCode !== 0 || signal !== null) {
  820. const returnedError = makeError({
  821. error,
  822. exitCode,
  823. signal,
  824. stdout,
  825. stderr,
  826. all,
  827. command,
  828. escapedCommand,
  829. parsed,
  830. timedOut,
  831. isCanceled: context.isCanceled || (parsed.options.signal ? parsed.options.signal.aborted : false),
  832. killed: spawned.killed,
  833. });
  834. if (!parsed.options.reject) {
  835. return returnedError;
  836. }
  837. throw returnedError;
  838. }
  839. return {
  840. command,
  841. escapedCommand,
  842. exitCode: 0,
  843. stdout,
  844. stderr,
  845. all,
  846. failed: false,
  847. timedOut: false,
  848. isCanceled: false,
  849. killed: false,
  850. };
  851. };
  852. const handlePromiseOnce = onetime(handlePromise);
  853. handleInput(spawned, parsed.options.input);
  854. spawned.all = makeAllStream(spawned, parsed.options);
  855. return mergePromise(spawned, handlePromiseOnce);
  856. }
  857. export { execa as e };