'use strict';

var require$$9 = require('../external/@socketsecurity/registry/lib/debug');
var spawn = require('../external/@socketsecurity/registry/lib/spawn');
var constants = require('./constants.js');
var utils = require('./utils.js');
var shadowPnpmBin = require('./shadow-pnpm-bin2.js');
var shadowNpmBin = require('./shadow-npm-bin2.js');

const DLX_COMMANDS = new Set(['dlx']);
const INSTALL_COMMANDS = new Set(['add', 'install', 'up', 'upgrade', 'upgrade-interactive']);
async function shadowYarnBin(args = process.argv.slice(2), options, extra) {
  const opts = {
    __proto__: null,
    ...options
  };
  const {
    env: spawnEnv,
    ipc,
    ...spawnOpts
  } = opts;
  const {
    spinner
  } = opts;
  const wasSpinning = !!spinner?.isSpinning;
  spinner?.start();
  const terminatorPos = args.indexOf('--');
  const rawYarnArgs = terminatorPos === -1 ? args : args.slice(0, terminatorPos);
  const otherArgs = terminatorPos === -1 ? [] : args.slice(terminatorPos);

  // Check for package scanning.
  const command = rawYarnArgs[0];
  const scanResult = await shadowPnpmBin.scanPackagesAndLogAlerts({
    acceptRisks: !!constants.default.ENV.SOCKET_CLI_ACCEPT_RISKS,
    command,
    cwd: process.cwd(),
    dlxCommands: DLX_COMMANDS,
    installCommands: INSTALL_COMMANDS,
    managerName: 'yarn',
    rawArgs: rawYarnArgs,
    spinner,
    viewAllRisks: !!constants.default.ENV.SOCKET_CLI_VIEW_ALL_RISKS
  });
  if (scanResult.shouldExit) {
    // eslint-disable-next-line n/no-process-exit
    process.exit(1);
    // This line is never reached in production, but helps tests.
    throw new Error('process.exit called');
  }
  const realYarnPath = await utils.installYarnLinks(constants.default.shadowBinPath);
  spinner?.stop();
  const suffixArgs = [...rawYarnArgs, ...otherArgs];
  require$$9.debugFn('notice', `spawn: ${constants.YARN} shadow bin ${realYarnPath} ${utils.cmdFlagsToString(suffixArgs)}`);
  if (wasSpinning) {
    spinner?.start();
  }

  // Set up stdio with IPC channel.
  const stdio = shadowNpmBin.ensureIpcInStdio(spawnOpts.stdio);
  const spawnPromise = spawn.spawn(realYarnPath, suffixArgs, {
    ...spawnOpts,
    env: {
      ...process.env,
      ...spawnEnv
    },
    stdio,
    // On Windows, yarn is often a .cmd file that requires shell execution.
    // The spawn function from @socketsecurity/registry will handle this properly
    // when shell is true.
    shell: constants.default.WIN32
  }, extra);

  // Send IPC handshake.
  spawnPromise.process.send({
    [constants.default.SOCKET_IPC_HANDSHAKE]: {
      [constants.default.SOCKET_CLI_SHADOW_API_TOKEN]: utils.getPublicApiToken(),
      [constants.default.SOCKET_CLI_SHADOW_BIN]: constants.YARN,
      [constants.default.SOCKET_CLI_SHADOW_PROGRESS]: true,
      ...ipc
    }
  });
  return {
    spawnPromise
  };
}

module.exports = shadowYarnBin;
//# debugId=ff4ce2bd-18b1-4eb9-93cf-526f617702d4
//# sourceMappingURL=shadow-yarn-bin.js.map
