File size: 1,741 Bytes
6a2bc3b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
import { spawnSync } from 'node:child_process';
import { readFileSync } from 'node:fs';
import { dirname, resolve } from 'node:path';
import { createRequire } from 'node:module';

const require = createRequire(import.meta.url);

export function resolveLocalCli(packageName, executableName) {
  let packageJsonPath;
  try {
    packageJsonPath = require.resolve(`${packageName}/package.json`);
  } catch (error) {
    throw new Error(
      `Local CLI dependency ${packageName} is not installed. Run pnpm install; runtime CLI downloads are disabled.`,
      { cause: error },
    );
  }

  const manifest = JSON.parse(readFileSync(packageJsonPath, 'utf8'));
  const relativeBin = typeof manifest.bin === 'string' ? manifest.bin : manifest.bin?.[executableName];
  if (typeof relativeBin !== 'string') {
    throw new Error(`${packageName} does not declare the expected "${executableName}" binary.`);
  }
  return resolve(dirname(packageJsonPath), relativeBin);
}

export function runLocalCli(packageName, executableName, args, options = {}) {
  const cliPath = resolveLocalCli(packageName, executableName);
  const result = spawnSync(process.execPath, [cliPath, ...args], {
    cwd: options.cwd,
    env: options.env ?? process.env,
    encoding: options.encoding,
    stdio: options.stdio ?? 'inherit',
  });
  if (result.error !== undefined) {
    throw new Error(`Unable to start local ${executableName}: ${result.error.message}`, {
      cause: result.error,
    });
  }
  if (result.status !== 0) {
    const output = [result.stdout, result.stderr].filter(Boolean).join('');
    throw new Error(
      `Local ${executableName} exited with code ${result.status ?? 'unknown'}${output ? `:\n${output}` : ''}`,
    );
  }
  return result;
}