Skip to content

An open source design system that's fully customizable and agent ready

TypeScript
32.2 KB
Raw Blame
// Copyright (c) Meta Platforms, Inc. and affiliates.

import {describe, it, expect, afterEach, beforeAll, vi} from 'vitest';
import {spawnSync} from 'node:child_process';
import * as fs from 'node:fs';
import * as path from 'node:path';
import * as os from 'node:os';
import {
  detectPackageManager,
  explainPackageManager,
  getDlxPrefix,
  isCliOneOff,
  cliBinResolves,
  getCliInvocation,
  guessCliInvocation,
  formatCliCommand,
  prefixCliCommands,
  quoteCommandArgument,
  commandInFolder,
} from './package-manager.mjs';
import {recordDeclaredCliCommands, runWithCliDoor} from './cli-command.mjs';
import {CLI_VERSION} from '../../test-utils/release-fixtures.mjs';

let tmpDir;
const ORIGINAL_ARGV1 = process.argv[1];

/** Prints, as JSON, the folder a command ran in and the arguments it got. */
const PRINT_RUN =
  'process.stdout.write(JSON.stringify({cwd: process.cwd(), argv: process.argv.slice(1)}))';

/** PowerShell, when it is on the PATH: printed commands target it on Windows. */
const PWSH = (process.env.PATH ?? '')
  .split(path.delimiter)
  .flatMap(dir => ['pwsh', 'pwsh.exe'].map(name => path.join(dir, name)))
  .find(file => isFile(file));

/** @param {string} file */
function isFile(file) {
  try {
    return fs.statSync(file).isFile();
  } catch {
    return false;
  }
}

afterEach(() => {
  if (tmpDir) {
    fs.rmSync(tmpDir, {recursive: true, force: true});
    tmpDir = null;
  }
  vi.restoreAllMocks();
  delete process.env.npm_config_user_agent;
  process.argv[1] = ORIGINAL_ARGV1;
});

function makeTmpDir() {
  tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-pm-test-'));
  return tmpDir;
}

/** Install the CLI's bin link in `dir`, the way a package manager does. */
function linkCliBin(dir, name = 'astryx') {
  const binDir = path.join(dir, 'node_modules', '.bin');
  fs.mkdirSync(binDir, {recursive: true});
  fs.writeFileSync(path.join(binDir, name), '');
  // The installed package the bin belongs to: this copy, so the project's own
  // CLI is the one answering (spec AST-081 FR5's run-prefix case).
  const pkg = path.join(dir, 'node_modules', '@astryxdesign', 'cli');
  fs.mkdirSync(path.dirname(pkg), {recursive: true});
  if (!fs.existsSync(pkg)) fs.symlinkSync(THIS_CLI, pkg, 'dir');
}

/** This CLI package's folder. */
const THIS_CLI = path.resolve(import.meta.dirname, '..', '..');

/** The header a classic Yarn (1.x) lockfile starts with. */
const YARN_V1_LOCK =
  '# THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY.\n# yarn lockfile v1\n\n';

/** The header a Berry (Yarn 2+) lockfile starts with. */
const YARN_BERRY_LOCK =
  '# This file is generated by running "yarn install" inside your project.\n# Manual changes might be lost - proceed with caution!\n\n__metadata:\n  version: 8\n';

/** An installed CLI's entry, outside any runner cache (a global or workspace install). */
const INSTALLED_ENTRY =
  '/usr/local/lib/node_modules/@astryxdesign/cli/clients/cli/bin/astryx.mjs';

describe('detectPackageManager', () => {
  it('detects yarn from yarn.lock', () => {
    const dir = makeTmpDir();
    fs.writeFileSync(path.join(dir, 'yarn.lock'), '');
    expect(detectPackageManager(dir)).toBe('yarn');
  });

  it('detects pnpm from pnpm-lock.yaml', () => {
    const dir = makeTmpDir();
    fs.writeFileSync(path.join(dir, 'pnpm-lock.yaml'), '');
    expect(detectPackageManager(dir)).toBe('pnpm');
  });

  it('detects npm from package-lock.json', () => {
    const dir = makeTmpDir();
    fs.writeFileSync(path.join(dir, 'package-lock.json'), '{}');
    expect(detectPackageManager(dir)).toBe('npm');
  });

  it('detects bun from bun.lockb', () => {
    const dir = makeTmpDir();
    fs.writeFileSync(path.join(dir, 'bun.lockb'), '');
    expect(detectPackageManager(dir)).toBe('bun');
  });

  it('refuses to let the runner break a multi-lockfile tie', () => {
    // One `yarn install` inside a pnpm project leaves a yarn.lock next to the
    // committed pnpm-lock.yaml. Nothing the project owns picks between them, so
    // there is no honest answer to give — only the neutral one.
    const dir = makeTmpDir();
    fs.writeFileSync(path.join(dir, 'pnpm-lock.yaml'), '');
    fs.writeFileSync(path.join(dir, 'yarn.lock'), '');
    process.env.npm_config_user_agent = 'pnpm/11.10.0 npm/? node/v22.0.0';
    expect(detectPackageManager(dir)).toBe('npx');
    expect(explainPackageManager(dir)).toMatchObject({
      ambiguous: true,
      candidates: ['yarn', 'pnpm'],
    });
  });

  it('does not reproduce a wrong `yarn astryx` line it was invoked through', () => {
    // The regression: an agent handed the wrong `yarn astryx` line runs the CLI
    // THROUGH yarn, so npm_config_user_agent says yarn. A runner tiebreak then
    // agrees with the mistake, and regenerating agent docs writes it again —
    // the wrong line reproduces itself forever. Project evidence only.
    const dir = makeTmpDir();
    fs.writeFileSync(path.join(dir, 'pnpm-lock.yaml'), '');
    fs.writeFileSync(path.join(dir, 'yarn.lock'), '');
    linkCliBin(dir);
    process.env.npm_config_user_agent = 'yarn/1.22.21 npm/? node/v22.0.0';
    expect(detectPackageManager(dir)).not.toBe('yarn');
    expect(getCliInvocation(dir)).toBe('npx astryx');
  });

  it('does not reproduce it for a directly invoked installed binary either', () => {
    const dir = makeTmpDir();
    const entry = process.argv[1];
    try {
      fs.writeFileSync(path.join(dir, 'pnpm-lock.yaml'), '');
      fs.writeFileSync(path.join(dir, 'yarn.lock'), '');
      linkCliBin(dir);
      process.env.npm_config_user_agent = 'yarn/1.22.21 npm/? node/v22.0.0';
      process.argv[1] = path.join(dir, 'node_modules/.bin/astryx');
      expect(getCliInvocation(dir)).toBe('npx astryx');
    } finally {
      process.argv[1] = entry;
    }
  });

  it('breaks the tie from a committed pnpm-workspace.yaml', () => {
    const dir = makeTmpDir();
    fs.writeFileSync(path.join(dir, 'pnpm-lock.yaml'), '');
    fs.writeFileSync(path.join(dir, 'yarn.lock'), '');
    fs.writeFileSync(path.join(dir, 'pnpm-workspace.yaml'), 'packages: []\n');
    process.env.npm_config_user_agent = 'yarn/1.22.21 npm/? node/v22.0.0';
    expect(detectPackageManager(dir)).toBe('pnpm');
  });

  it('breaks the tie from a committed .yarnrc.yml', () => {
    const dir = makeTmpDir();
    fs.writeFileSync(path.join(dir, 'pnpm-lock.yaml'), '');
    fs.writeFileSync(path.join(dir, 'yarn.lock'), '');
    fs.writeFileSync(
      path.join(dir, '.yarnrc.yml'),
      'nodeLinker: node-modules\n',
    );
    expect(detectPackageManager(dir)).toBe('yarn');
  });

  it('stays ambiguous when the project owns evidence for both', () => {
    const dir = makeTmpDir();
    fs.writeFileSync(path.join(dir, 'pnpm-lock.yaml'), '');
    fs.writeFileSync(path.join(dir, 'yarn.lock'), '');
    fs.writeFileSync(path.join(dir, 'pnpm-workspace.yaml'), 'packages: []\n');
    fs.writeFileSync(path.join(dir, '.yarnrc.yml'), '');
    expect(explainPackageManager(dir).ambiguous).toBe(true);
  });

  it('lets the packageManager field break a multi-lockfile tie', () => {
    const dir = makeTmpDir();
    fs.writeFileSync(path.join(dir, 'yarn.lock'), '');
    fs.writeFileSync(path.join(dir, 'pnpm-lock.yaml'), '');
    fs.writeFileSync(
      path.join(dir, 'package.json'),
      JSON.stringify({packageManager: '[email protected]'}),
    );
    expect(detectPackageManager(dir)).toBe('pnpm');
  });

  it('follows the declared packageManager even when no lockfile matches it', () => {
    // The declaration is the project speaking. Two lockfiles that disagree
    // with it are two traces that are both wrong, not a tie to resolve.
    const dir = makeTmpDir();
    fs.writeFileSync(path.join(dir, 'yarn.lock'), '');
    fs.writeFileSync(path.join(dir, 'package-lock.json'), '{}');
    fs.writeFileSync(
      path.join(dir, 'package.json'),
      JSON.stringify({packageManager: '[email protected]'}),
    );
    expect(explainPackageManager(dir)).toMatchObject({
      pm: 'pnpm',
      ambiguous: false,
      declared: 'pnpm',
      source: 'declared',
    });
  });

  it('ignores a runner that has no lockfile in the directory', () => {
    const dir = makeTmpDir();
    fs.writeFileSync(path.join(dir, 'pnpm-lock.yaml'), '');
    process.env.npm_config_user_agent = 'yarn/1.22.21 npm/? node/v22.0.0';
    expect(detectPackageManager(dir)).toBe('pnpm');
  });

  it('detects from packageManager field in package.json (no lockfile)', () => {
    const dir = makeTmpDir();
    fs.writeFileSync(
      path.join(dir, 'package.json'),
      JSON.stringify({packageManager: '[email protected]'}),
    );
    expect(detectPackageManager(dir)).toBe('yarn');
  });

  it('detects pnpm from packageManager field', () => {
    const dir = makeTmpDir();
    fs.writeFileSync(
      path.join(dir, 'package.json'),
      JSON.stringify({packageManager: '[email protected]'}),
    );
    expect(detectPackageManager(dir)).toBe('pnpm');
  });

  it('ignores unknown packageManager values', () => {
    const dir = makeTmpDir();
    fs.writeFileSync(
      path.join(dir, 'package.json'),
      JSON.stringify({packageManager: '[email protected]'}),
    );
    expect(detectPackageManager(dir)).toBe('npx');
  });

  it('declared packageManager outranks a single stray lockfile', () => {
    // The regression: one `yarn install` inside a pnpm project leaves a
    // yarn.lock forever, and a single lockfile used to outrank the field. The
    // CLI then printed `yarn astryx` for a pnpm project — and wrote that line
    // into the agent docs, where agents copy it.
    const dir = makeTmpDir();
    fs.writeFileSync(path.join(dir, 'yarn.lock'), '');
    fs.writeFileSync(
      path.join(dir, 'package.json'),
      JSON.stringify({packageManager: '[email protected]'}),
    );
    linkCliBin(dir);
    expect(detectPackageManager(dir)).toBe('pnpm');
    expect(getCliInvocation(dir)).toBe('pnpm exec astryx');
  });

  it('reports the stray lockfile it ignored, so doctor can name it', () => {
    const dir = makeTmpDir();
    fs.writeFileSync(path.join(dir, 'yarn.lock'), '');
    fs.writeFileSync(path.join(dir, 'pnpm-lock.yaml'), '');
    fs.writeFileSync(
      path.join(dir, 'package.json'),
      JSON.stringify({packageManager: '[email protected]'}),
    );
    expect(explainPackageManager(dir)).toMatchObject({
      pm: 'pnpm',
      declared: 'pnpm',
      source: 'declared',
      strayLockfiles: [{pm: 'yarn', file: 'yarn.lock'}],
    });
  });

  it('reports no stray when the lockfile agrees with the declaration', () => {
    const dir = makeTmpDir();
    fs.writeFileSync(path.join(dir, 'pnpm-lock.yaml'), '');
    fs.writeFileSync(
      path.join(dir, 'package.json'),
      JSON.stringify({packageManager: '[email protected]'}),
    );
    expect(explainPackageManager(dir)).toMatchObject({
      pm: 'pnpm',
      declared: 'pnpm',
      strayLockfiles: [],
    });
  });

  it('keeps the lockfile fallback when nothing is declared', () => {
    // The documented fallback: with no declaration, one lockfile still decides.
    const dir = makeTmpDir();
    fs.writeFileSync(path.join(dir, 'yarn.lock'), '');
    fs.writeFileSync(path.join(dir, 'package.json'), JSON.stringify({}));
    expect(explainPackageManager(dir)).toMatchObject({
      pm: 'yarn',
      declared: null,
      source: 'lockfile',
    });
  });

  it('ignores an unknown packageManager value and falls back to the lockfile', () => {
    const dir = makeTmpDir();
    fs.writeFileSync(path.join(dir, 'yarn.lock'), '');
    fs.writeFileSync(
      path.join(dir, 'package.json'),
      JSON.stringify({packageManager: '[email protected]'}),
    );
    expect(detectPackageManager(dir)).toBe('yarn');
  });

  it('lets a nearer directory answer before an outer declaration', () => {
    // Unchanged walk-up behaviour: the first directory that answers wins, so a
    // workspace root's declaration does not reach past a package that has its
    // own lockfile.
    const dir = makeTmpDir();
    const inner = path.join(dir, 'packages', 'app');
    fs.mkdirSync(inner, {recursive: true});
    fs.writeFileSync(
      path.join(dir, 'package.json'),
      JSON.stringify({packageManager: '[email protected]'}),
    );
    fs.writeFileSync(path.join(inner, 'package-lock.json'), '{}');
    expect(detectPackageManager(inner)).toBe('npm');
    expect(detectPackageManager(dir)).toBe('pnpm');
  });

  it('detects from npm_config_user_agent env var', () => {
    const dir = makeTmpDir();
    process.env.npm_config_user_agent = 'yarn/1.22.22 node/v20.0.0';
    expect(detectPackageManager(dir)).toBe('yarn');
  });

  it('detects pnpm from npm_config_user_agent env var', () => {
    const dir = makeTmpDir();
    process.env.npm_config_user_agent = 'pnpm/8.15.0 node/v20.0.0';
    expect(detectPackageManager(dir)).toBe('pnpm');
  });

  it('falls back to npx when no signals present', () => {
    const dir = makeTmpDir();
    expect(detectPackageManager(dir)).toBe('npx');
  });

  it('packageManager field takes priority over npm_config_user_agent', () => {
    const dir = makeTmpDir();
    fs.writeFileSync(
      path.join(dir, 'package.json'),
      JSON.stringify({packageManager: '[email protected]'}),
    );
    process.env.npm_config_user_agent = 'npm/10.0.0 node/v20.0.0';
    expect(detectPackageManager(dir)).toBe('bun');
  });
});

describe('getDlxPrefix', () => {
  it('returns "pnpm dlx" for pnpm projects', () => {
    const dir = makeTmpDir();
    fs.writeFileSync(path.join(dir, 'pnpm-lock.yaml'), '');
    expect(getDlxPrefix(dir)).toBe('pnpm dlx');
  });

  it('returns "yarn dlx" for yarn projects', () => {
    const dir = makeTmpDir();
    fs.writeFileSync(path.join(dir, 'yarn.lock'), '');
    expect(getDlxPrefix(dir)).toBe('yarn dlx');
  });

  // Classic Yarn (1.x) has no `dlx`; `yarn dlx …` fails there, so its one-off
  // form is `npx`. Berry (2+) keeps `yarn dlx`.
  it('returns "npx" for a classic Yarn lockfile', () => {
    const dir = makeTmpDir();
    fs.writeFileSync(path.join(dir, 'yarn.lock'), YARN_V1_LOCK);
    expect(getDlxPrefix(dir)).toBe('npx');
  });

  it('returns "yarn dlx" for a Berry lockfile', () => {
    const dir = makeTmpDir();
    fs.writeFileSync(path.join(dir, 'yarn.lock'), YARN_BERRY_LOCK);
    expect(getDlxPrefix(dir)).toBe('yarn dlx');
  });

  it('reads the declared packageManager version first', () => {
    const classic = makeTmpDir();
    fs.writeFileSync(
      path.join(classic, 'package.json'),
      JSON.stringify({packageManager: '[email protected]'}),
    );
    // A Berry-looking lockfile does not outrank the declaration.
    fs.writeFileSync(path.join(classic, 'yarn.lock'), YARN_BERRY_LOCK);
    expect(getDlxPrefix(classic)).toBe('npx');
    fs.rmSync(classic, {recursive: true, force: true});

    const berry = makeTmpDir();
    fs.writeFileSync(
      path.join(berry, 'package.json'),
      JSON.stringify({packageManager: '[email protected]'}),
    );
    fs.writeFileSync(path.join(berry, 'yarn.lock'), YARN_V1_LOCK);
    expect(getDlxPrefix(berry)).toBe('yarn dlx');
  });

  it('reads a bare major version in the declaration', () => {
    const classic = makeTmpDir();
    fs.writeFileSync(
      path.join(classic, 'package.json'),
      JSON.stringify({packageManager: 'yarn@1'}),
    );
    expect(getDlxPrefix(classic)).toBe('npx');
    fs.rmSync(classic, {recursive: true, force: true});

    const berry = makeTmpDir();
    fs.writeFileSync(
      path.join(berry, 'package.json'),
      JSON.stringify({packageManager: 'yarn@4'}),
    );
    expect(getDlxPrefix(berry)).toBe('yarn dlx');
  });

  it('reads a committed Yarn config when the lockfile has no header', () => {
    const classic = makeTmpDir();
    fs.writeFileSync(path.join(classic, 'yarn.lock'), '');
    fs.writeFileSync(path.join(classic, '.yarnrc'), '');
    expect(getDlxPrefix(classic)).toBe('npx');
    fs.rmSync(classic, {recursive: true, force: true});

    const berry = makeTmpDir();
    fs.writeFileSync(path.join(berry, 'yarn.lock'), '');
    fs.writeFileSync(path.join(berry, '.yarnrc.yml'), '');
    expect(getDlxPrefix(berry)).toBe('yarn dlx');
  });

  it('reads the runner version when nothing on disk names Yarn', () => {
    makeTmpDir();
    process.env.npm_config_user_agent = 'yarn/1.22.21 npm/? node/v22.0.0';
    expect(getDlxPrefix(tmpDir)).toBe('npx');
    process.env.npm_config_user_agent = 'yarn/4.5.0 npm/? node/v22.0.0';
    expect(getDlxPrefix(tmpDir)).toBe('yarn dlx');
  });

  it('returns "bunx" for bun projects', () => {
    const dir = makeTmpDir();
    fs.writeFileSync(path.join(dir, 'bun.lockb'), '');
    expect(getDlxPrefix(dir)).toBe('bunx');
  });

  it('falls back to "npx" with no signals', () => {
    const dir = makeTmpDir();
    delete process.env.npm_config_user_agent;
    expect(getDlxPrefix(dir)).toBe('npx');
  });
});

describe('isCliOneOff', () => {
  it('detects an npm npx cache entry', () => {
    process.argv[1] = '/home/u/.npm/_npx/a1b2/node_modules/.bin/astryx';
    expect(isCliOneOff()).toBe(true);
  });

  it('detects a pnpm dlx cache entry', () => {
    process.argv[1] =
      '/home/u/.cache/pnpm/dlx/9f/node_modules/@astryxdesign/cli/bin/astryx.mjs';
    expect(isCliOneOff()).toBe(true);
  });

  it('detects a bunx cache entry', () => {
    process.argv[1] =
      '/home/u/.bun/install/cache/@astryxdesign/cli/bin/astryx.mjs';
    expect(isCliOneOff()).toBe(true);
  });

  it('is false for an installed node_modules entry', () => {
    process.argv[1] = '/proj/node_modules/@astryxdesign/cli/bin/astryx.mjs';
    expect(isCliOneOff()).toBe(false);
  });

  it('is false for a source checkout (dev) entry', () => {
    process.argv[1] = '/repo/packages/cli/bin/astryx.mjs';
    expect(isCliOneOff()).toBe(false);
  });
});

describe('cliBinResolves', () => {
  it('finds the bin link in the project', () => {
    const dir = makeTmpDir();
    linkCliBin(dir);
    expect(cliBinResolves(dir)).toBe(true);
  });

  it('finds it in a folder above the project (a workspace root)', () => {
    const root = makeTmpDir();
    linkCliBin(root);
    const pkg = path.join(root, 'packages', 'app');
    fs.mkdirSync(pkg, {recursive: true});
    expect(cliBinResolves(pkg)).toBe(true);
  });

  it('finds a Windows shim', () => {
    const dir = makeTmpDir();
    linkCliBin(dir, 'astryx.cmd');
    expect(cliBinResolves(dir)).toBe(true);
  });

  it('is false when no bin link exists up the tree', () => {
    const dir = makeTmpDir();
    fs.mkdirSync(path.join(dir, 'node_modules', '.bin'), {recursive: true});
    expect(cliBinResolves(dir)).toBe(false);
  });
});

describe('getCliInvocation', () => {
  it('uses the run-prefix + bare bin when the bin resolves from the project', () => {
    process.argv[1] = '/proj/node_modules/@astryxdesign/cli/bin/astryx.mjs';
    const dir = makeTmpDir();
    fs.writeFileSync(path.join(dir, 'pnpm-lock.yaml'), '');
    linkCliBin(dir);
    expect(getCliInvocation(dir)).toBe('pnpm exec astryx');
  });

  it('keeps `npx astryx` for a project with a local CLI', () => {
    process.argv[1] = INSTALLED_ENTRY;
    const dir = makeTmpDir();
    fs.writeFileSync(path.join(dir, 'package-lock.json'), '{}');
    linkCliBin(dir);
    expect(getCliInvocation(dir)).toBe('npx astryx');
  });

  it('keeps the installed form in a workspace package when the root has the bin', () => {
    process.argv[1] = INSTALLED_ENTRY;
    const root = makeTmpDir();
    fs.writeFileSync(path.join(root, 'pnpm-lock.yaml'), '');
    linkCliBin(root);
    const pkg = path.join(root, 'packages', 'app');
    fs.mkdirSync(pkg, {recursive: true});
    fs.writeFileSync(path.join(pkg, 'package.json'), '{"name":"app"}');
    expect(getCliInvocation(pkg)).toBe('pnpm exec astryx');
  });

  // The hazard: the npm package named `astryx` is not this CLI. Launched from
  // an installed path (a global install, or a workspace install running in a
  // fresh package), the CLI used to print `npx astryx` for a project where that
  // bin does not resolve, so following the hint fetched someone else's package.
  it.each([
    ['package-lock.json', '{}', `npx @astryxdesign/cli@${CLI_VERSION}`],
    ['pnpm-lock.yaml', '', `pnpm dlx @astryxdesign/cli@${CLI_VERSION}`],
    ['yarn.lock', YARN_BERRY_LOCK, `yarn dlx @astryxdesign/cli@${CLI_VERSION}`],
    ['yarn.lock', YARN_V1_LOCK, `npx @astryxdesign/cli@${CLI_VERSION}`],
    ['bun.lockb', '', `bunx @astryxdesign/cli@${CLI_VERSION}`],
  ])(
    'prints the scoped package for a project with no local CLI (%s), launched from an installed path',
    (lockfile, contents, expected) => {
      process.argv[1] = INSTALLED_ENTRY;
      const dir = makeTmpDir();
      fs.writeFileSync(path.join(dir, lockfile), contents);
      expect(isCliOneOff()).toBe(false);
      expect(getCliInvocation(dir)).toBe(expected);
    },
  );

  it('prints the scoped package for a fresh package with no lockfile or install', () => {
    process.argv[1] = INSTALLED_ENTRY;
    const dir = makeTmpDir();
    delete process.env.npm_config_user_agent;
    fs.writeFileSync(path.join(dir, 'package.json'), '{"name":"fresh"}');
    expect(getCliInvocation(dir)).toBe(`npx @astryxdesign/cli@${CLI_VERSION}`);
  });

  it('uses the dlx runner + scoped package when run one-off', () => {
    process.argv[1] = '/home/u/.npm/_npx/a1b2/node_modules/.bin/astryx';
    const dir = makeTmpDir();
    delete process.env.npm_config_user_agent;
    expect(getCliInvocation(dir)).toBe(`npx @astryxdesign/cli@${CLI_VERSION}`);
  });

  it('pairs the dlx runner with the scoped package for pnpm one-off', () => {
    process.argv[1] =
      '/home/u/.cache/pnpm/dlx/9f/node_modules/@astryxdesign/cli/bin/astryx.mjs';
    const dir = makeTmpDir();
    fs.writeFileSync(path.join(dir, 'pnpm-lock.yaml'), '');
    expect(getCliInvocation(dir)).toBe(
      `pnpm dlx @astryxdesign/cli@${CLI_VERSION}`,
    );
  });
});

describe('formatCliCommand', () => {
  it('strips a leading "astryx" token and prepends the invocation stem', () => {
    process.argv[1] = '/proj/node_modules/@astryxdesign/cli/bin/astryx.mjs';
    const dir = makeTmpDir();
    fs.writeFileSync(path.join(dir, 'pnpm-lock.yaml'), '');
    linkCliBin(dir);
    expect(formatCliCommand('astryx component Button', dir)).toBe(
      'pnpm exec astryx component Button',
    );
  });

  it('accepts a bare subcommand (no leading astryx)', () => {
    process.argv[1] = '/proj/node_modules/@astryxdesign/cli/bin/astryx.mjs';
    const dir = makeTmpDir();
    fs.writeFileSync(path.join(dir, 'package-lock.json'), '{}');
    linkCliBin(dir);
    expect(formatCliCommand('docs tokens', dir)).toBe('npx astryx docs tokens');
  });

  it('rewrites to the scoped package for one-off invocations', () => {
    process.argv[1] = '/home/u/.npm/_npx/a1b2/node_modules/.bin/astryx';
    const dir = makeTmpDir();
    fs.writeFileSync(path.join(dir, 'package-lock.json'), '{}');
    expect(formatCliCommand('astryx component Button', dir)).toBe(
      `npx @astryxdesign/cli@${CLI_VERSION} component Button`,
    );
  });
});

describe('the picker: declared cliCommand, then the door, then the guess', () => {
  /** A pnpm project with the CLI installed: the guess is `pnpm exec astryx`. */
  function pnpmProject() {
    process.argv[1] = INSTALLED_ENTRY;
    const dir = makeTmpDir();
    fs.writeFileSync(path.join(dir, 'package.json'), '{"name":"app"}');
    fs.writeFileSync(path.join(dir, 'pnpm-lock.yaml'), '');
    linkCliBin(dir);
    return dir;
  }

  it('guesses when nothing is declared', () => {
    const dir = pnpmProject();
    recordDeclaredCliCommands(dir, [{name: '@acme/a'}]);
    expect(getCliInvocation(dir)).toBe('pnpm exec astryx');
  });

  it("uses an integration's cliCommand over the guess", () => {
    const dir = pnpmProject();
    recordDeclaredCliCommands(dir, [
      {name: '@acme/a', cliCommand: 'acme astryx'},
      {name: '@acme/b', cliCommand: 'acme astryx'},
    ]);
    expect(getCliInvocation(dir)).toBe('acme astryx');
    expect(formatCliCommand('astryx docs tokens', dir)).toBe(
      'acme astryx docs tokens',
    );
    expect(guessCliInvocation(dir)).toBe('pnpm exec astryx');
  });

  it('falls back to the guess when integrations declare different commands', () => {
    const dir = pnpmProject();
    recordDeclaredCliCommands(dir, [
      {name: '@acme/a', cliCommand: 'acme astryx'},
      {name: '@acme/b', cliCommand: 'other astryx'},
    ]);
    expect(getCliInvocation(dir)).toBe('pnpm exec astryx');
  });

  it("puts a declared command ahead of a host's door", () => {
    const dir = pnpmProject();
    recordDeclaredCliCommands(dir, [
      {name: '@acme/a', cliCommand: 'acme astryx'},
    ]);
    expect(runWithCliDoor('astryx', () => getCliInvocation(dir))).toBe(
      'acme astryx',
    );
  });

  it("uses a host's door when nothing is declared", () => {
    const dir = pnpmProject();
    recordDeclaredCliCommands(dir, []);
    expect(runWithCliDoor('astryx', () => getCliInvocation(dir))).toBe(
      'astryx',
    );
  });

  it('guesses on a conflict even when a host set a door', () => {
    const dir = pnpmProject();
    recordDeclaredCliCommands(dir, [
      {name: '@acme/a', cliCommand: 'acme astryx'},
      {name: '@acme/b', cliCommand: 'other astryx'},
    ]);
    expect(runWithCliDoor('astryx', () => getCliInvocation(dir))).toBe(
      'pnpm exec astryx',
    );
  });
});

describe('prefixCliCommands', () => {
  /** @param {string} text @param {string | null} [lang] */
  const shown = (text, lang) => prefixCliCommands(text, 'acme astryx', lang);

  it('prefixes inline code spans that run the CLI', () => {
    expect(
      shown('Run `astryx docs theme`, then `astryx`. Not `astryx.config.ts`.'),
    ).toBe(
      'Run `acme astryx docs theme`, then `acme astryx`. Not `astryx.config.ts`.',
    );
  });

  it('prefixes commands in shell fences and leaves code fences alone', () => {
    const text = [
      '```bash',
      '# astryx in a comment stays',
      'astryx doctor && astryx integration verify',
      '$ astryx docs',
      'npm install @astryxdesign/cli',
      '```',
      '```tsx',
      'astryx docs',
      '```',
    ].join('\n');
    expect(shown(text).split('\n')).toEqual([
      '```bash',
      '# astryx in a comment stays',
      'acme astryx doctor && acme astryx integration verify',
      '$ acme astryx docs',
      'npm install @astryxdesign/cli',
      '```',
      '```tsx',
      'astryx docs',
      '```',
    ]);
  });

  it("follows one code block's language", () => {
    expect(shown('astryx docs', 'bash')).toBe('acme astryx docs');
    expect(shown('1. Read `astryx docs cli`.', 'text')).toBe(
      '1. Read `acme astryx docs cli`.',
    );
    expect(shown("const run = 'astryx docs';", 'ts')).toBe(
      "const run = 'astryx docs';",
    );
  });

  it('leaves plain prose alone', () => {
    expect(shown('Astryx and astryx themes')).toBe('Astryx and astryx themes');
  });

  it('changes nothing when the stem is the bare bin', () => {
    expect(prefixCliCommands('`astryx docs`', 'astryx')).toBe('`astryx docs`');
  });
});

describe('quoteCommandArgument', () => {
  it('leaves a plain value bare', () => {
    for (const platform of ['linux', 'darwin', 'win32']) {
      expect(quoteCommandArgument('0.7.1', platform)).toBe('0.7.1');
      expect(quoteCommandArgument('@acme/widgets', platform)).toBe(
        '@acme/widgets',
      );
      expect(quoteCommandArgument('/home/me/app/src', platform)).toBe(
        '/home/me/app/src',
      );
    }
  });

  it('single-quotes for a POSIX shell, so $, backticks and double quotes stay literal', () => {
    expect(quoteCommandArgument('/tmp/my app/src', 'linux')).toBe(
      "'/tmp/my app/src'",
    );
    expect(quoteCommandArgument('/tmp/cost $5/src', 'darwin')).toBe(
      "'/tmp/cost $5/src'",
    );
    expect(quoteCommandArgument('a`id`"b"!', 'linux')).toBe('\'a`id`"b"!\'');
    expect(quoteCommandArgument("it's", 'linux')).toBe("'it'\\''s'");
    expect(quoteCommandArgument('C:\\app', 'linux')).toBe("'C:\\app'");
    expect(quoteCommandArgument('', 'linux')).toBe("''");
  });

  it('keeps a Windows drive path bare', () => {
    expect(quoteCommandArgument('C:\\Users\\me\\app\\src', 'win32')).toBe(
      'C:\\Users\\me\\app\\src',
    );
  });

  // Windows output targets PowerShell, not cmd.exe: PowerShell reads a
  // single-quoted value literally, `$`, backticks, `%` and `!` included.
  it('single-quotes for PowerShell on Windows, doubling an embedded quote', () => {
    expect(quoteCommandArgument('C:\\Users\\Jo Smith\\app\\src', 'win32')).toBe(
      "'C:\\Users\\Jo Smith\\app\\src'",
    );
    expect(quoteCommandArgument('C:\\cost $5 %x% !y\\src', 'win32')).toBe(
      "'C:\\cost $5 %x% !y\\src'",
    );
    expect(quoteCommandArgument('C:\\it\'s `x` "q"', 'win32')).toBe(
      "'C:\\it''s `x` \"q\"'",
    );
    // PowerShell also ends a single-quoted string at ‘ ’ ‚ and ‛.
    expect(
      quoteCommandArgument('C:\\Users\\jo\\OneDrive - Macy’s\\app', 'win32'),
    ).toBe("'C:\\Users\\jo\\OneDrive - Macy’’s\\app'");
    expect(quoteCommandArgument('‘a’ ‚b‛', 'win32')).toBe("'‘‘a’’ ‚‚b‛‛'");
    // A POSIX shell reads them literally inside single quotes.
    expect(quoteCommandArgument('/home/jo/Macy’s app', 'linux')).toBe(
      "'/home/jo/Macy’s app'",
    );
  });
});

describe('commandInFolder', () => {
  it('enters the folder, then runs the command only if that worked, in a POSIX shell', () => {
    expect(commandInFolder('/tmp/my app', 'npx x', 'linux')).toBe(
      "cd '/tmp/my app' && npx x",
    );
    expect(commandInFolder('/srv/app', 'npx x', 'darwin')).toBe(
      'cd /srv/app && npx x',
    );
  });

  it('enters the folder literally and stops if it cannot, in PowerShell', () => {
    expect(commandInFolder('C:\\a[1] b', 'npx x', 'win32')).toBe(
      "cd -LiteralPath 'C:\\a[1] b' -ErrorAction Stop; npx x",
    );
  });

  it.skipIf(process.platform === 'win32')(
    'runs in the folder with every argument unchanged, pasted into /bin/sh elsewhere',
    () => {
      const root = makeTmpDir();
      const project = path.join(root, 'it\'s Macy’s ‘q’ $5 %x% !y `z` "q" [1]');
      fs.mkdirSync(project);
      const args = [path.join(project, 'src'), 'a$b c', "it's", '@scope/pkg@1'];
      const command = commandInFolder(
        project,
        ['npx', ...args.map(arg => quoteCommandArgument(arg, 'linux'))].join(
          ' ',
        ),
        'linux',
      );
      const ran = spawnSync(
        '/bin/sh',
        [
          '-c',
          `npx() { "$0" -e '${PRINT_RUN}' -- "$@"; }; ${command}`,
          process.execPath,
        ],
        {cwd: root, encoding: 'utf8'},
      );

      expect(ran.status, ran.stderr).toBe(0);
      expect(JSON.parse(ran.stdout)).toEqual({
        cwd: fs.realpathSync(project),
        argv: args,
      });
    },
  );

  describe.runIf(PWSH)('in PowerShell, where it is installed', () => {
    // The first `pwsh` a job starts pays PowerShell's cold start, which on a
    // busy runner has outlasted a test's 30 s. `spawnSync` blocks, so that
    // start landed on the first test's clock. Starting it once here, on the
    // hook's own timeout, leaves each test's clock to its command.
    beforeAll(() => {
      const warm = spawnSync(
        /** @type {string} */ (PWSH),
        ['-NoProfile', '-NonInteractive', '-Command', 'exit 0'],
        {encoding: 'utf8'},
      );
      expect(warm.status, warm.stderr).toBe(0);
    }, 120_000);

    it('runs in the folder with every argument unchanged', () => {
      const root = makeTmpDir();
      const project = path.join(root, 'it\'s Macy’s ‘q’ $5 %x% !y `z` "q" [1]');
      fs.mkdirSync(project);
      const args = [path.join(project, 'src'), 'a$b c', "it's", '@scope/pkg@1'];
      const command = commandInFolder(
        project,
        ['npx', ...args.map(arg => quoteCommandArgument(arg, 'win32'))].join(
          ' ',
        ),
        'win32',
      );
      const npx = `function npx { & ${quoteCommandArgument(process.execPath, 'win32')} -e '${PRINT_RUN}' -- @args }`;
      const ran = spawnSync(
        /** @type {string} */ (PWSH),
        ['-NoProfile', '-NonInteractive', '-Command', `${npx}; ${command}`],
        {cwd: root, encoding: 'utf8'},
      );

      expect(ran.status, ran.stderr).toBe(0);
      expect(JSON.parse(ran.stdout)).toEqual({
        cwd: fs.realpathSync(project),
        argv: args,
      });
    });

    it('stops when the folder cannot be entered', () => {
      const root = makeTmpDir();
      const command = commandInFolder(
        path.join(root, 'missing'),
        'npx',
        'win32',
      );
      const ran = spawnSync(
        /** @type {string} */ (PWSH),
        [
          '-NoProfile',
          '-NonInteractive',
          '-Command',
          `function npx { 'RAN' }; ${command}`,
        ],
        {cwd: root, encoding: 'utf8'},
      );

      expect(ran.stdout).not.toContain('RAN');
    });
  });
});