Skip to content

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

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

import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
import * as fs from 'node:fs';
import * as os from 'node:os';
import * as path from 'node:path';
import {spawnSync} from 'node:child_process';
import {createHash} from 'node:crypto';
import {
  integrationPackCheck,
  normalizeThemeVerifyForCompare,
  parseNpmPackOutput,
} from './pack-check.mjs';
import {normalizeThemeBuildForCompare} from '../theme/build/build.mjs';
import {released065Ocean} from './__fixtures__/released-0.6.5-ocean.mjs';
import {
  integrationAddComponent,
  integrationAddTemplate,
} from './add-contribution.mjs';
import {formatCliCommand} from '../../foundation/env/package-manager.mjs';
import {REPO_ROOT} from '../../test-utils/repo-root.mjs';

let tmpDir;

beforeEach(() => {
  tmpDir = fs.mkdtempSync(path.join(REPO_ROOT, '.astryx-pack-check-'));
});

afterEach(() => {
  fs.rmSync(tmpDir, {recursive: true, force: true});
});

function generatedCssArtifact({
  source = 'themes/ocean/oceanTheme.ts',
  cli = '0.6.6',
  core = '0.6.6',
  body = ':root { color: red; }',
} = {}) {
  return `/*
 * @generated by \`astryx theme build\` — do not edit manually.
 * Source: ${source}
 * Command: astryx theme build ${source}
 * CLI: @astryxdesign/cli@${cli}
 * Core: @astryxdesign/core@${core}
 */

${body}
`;
}

function generatedJsArtifact({
  source = 'themes/ocean/oceanTheme.ts',
  cli = '0.6.6',
  core = '0.6.6',
  body = "export const oceanTheme = {name: 'ocean'};",
} = {}) {
  return `/**
 * @generated by \`astryx theme build\` — do not edit manually.
 * Source: ${source}
 * CLI: @astryxdesign/cli@${cli}
 * Core: @astryxdesign/core@${core}
 */

${body}
`;
}

describe('verify-only built-by command normalization', () => {
  /** A built module as `theme build` writes it, by one package manager. */
  const builtModule = (/** @type {string} */ command, slug = 'terminal') =>
    generatedJsArtifact({
      source: `themes/${slug}/${slug}Theme.ts`,
      body: `/**
 * ${slug} theme — built by \`${command} theme build\`
 * Import the CSS file alongside this module:
 */
export const ${slug}Theme = {name: '${slug}'};`,
    });

  // Two published theme packages, "terminal" and "xtra-professional", were
  // built with yarn; verify under pnpm rebuilt each byte for byte except this
  // line and reported theme_module_stale.
  it.each(['terminal', 'xtra-professional'])(
    'treats the %s module built by yarn as the module built by pnpm',
    slug => {
      expect(
        normalizeThemeVerifyForCompare(builtModule('yarn astryx', slug)),
      ).toBe(
        normalizeThemeVerifyForCompare(builtModule('pnpm exec astryx', slug)),
      );
      expect(
        normalizeThemeVerifyForCompare(builtModule('npx astryx', slug)),
      ).toBe(
        normalizeThemeVerifyForCompare(builtModule('acme astryx', slug)),
      );
      expect(
        normalizeThemeBuildForCompare(builtModule('yarn astryx', slug)),
      ).not.toBe(
        normalizeThemeBuildForCompare(builtModule('pnpm exec astryx', slug)),
      );
    },
  );

  it.each([
    [
      'theme name on the built-by line',
      source => source.replace('terminal theme — built', 'reef theme — built'),
    ],
    [
      'second built-by line',
      source =>
        source.replace(
          ' * Import the CSS',
          ' * terminal theme — built by `npm astryx theme build`\n * Import the CSS',
        ),
    ],
    [
      'built-by line without the generated header',
      source => source.replace('@generated by', '@generated with'),
    ],
  ])('keeps a %s significant', (_label, mutate) => {
    const yarn = builtModule('yarn astryx');
    const pnpm = builtModule('pnpm exec astryx');
    expect(normalizeThemeVerifyForCompare(mutate(yarn))).not.toBe(
      normalizeThemeVerifyForCompare(pnpm),
    );
  });
});

describe('verify-only generated CSS header normalization', () => {
  it('ignores one source path and exact version pair but leaves build --check strict', () => {
    const current = generatedCssArtifact();
    const released = generatedCssArtifact({
      source: 'oceanTheme.ts',
      cli: '0.6.5',
      core: '0.6.5',
    });

    expect(normalizeThemeVerifyForCompare(released)).toBe(
      normalizeThemeVerifyForCompare(current),
    );
    expect(normalizeThemeBuildForCompare(released)).not.toBe(
      normalizeThemeBuildForCompare(current),
    );
    expect(released).not.toBe(current);
  });

  it.each([
    ['body change', source => source.replace('color: red', 'color: blue')],
    [
      'Source text in the CSS body',
      source =>
        source.replace(
          ':root { color: red; }',
          ':root { color: red; }\n * Source: body.css',
        ),
    ],
    [
      'header reordering',
      source =>
        source.replace(
          ' * CLI: @astryxdesign/[email protected]\n * Core: @astryxdesign/[email protected]',
          ' * Core: @astryxdesign/[email protected]\n * CLI: @astryxdesign/[email protected]',
        ),
    ],
    [
      'other header change',
      source => source.replace('@generated by', '@generated with'),
    ],
    [
      'missing version line',
      source => source.replace(' * CLI: @astryxdesign/[email protected]\n', ''),
    ],
    [
      'duplicate version line',
      source =>
        source.replace(
          ' * CLI: @astryxdesign/[email protected]\n',
          ' * CLI: @astryxdesign/[email protected]\n * CLI: @astryxdesign/[email protected]\n',
        ),
    ],
    [
      'malformed version line',
      source =>
        source.replace(
          'CLI: @astryxdesign/[email protected]',
          'CLI: malformed-version-header',
        ),
    ],
    [
      'missing Source line',
      source => source.replace(' * Source: themes/ocean/oceanTheme.ts\n', ''),
    ],
    [
      'duplicate Source line',
      source =>
        source.replace(
          ' * Source: themes/ocean/oceanTheme.ts\n',
          ' * Source: themes/ocean/oceanTheme.ts\n * Source: oceanTheme.ts\n',
        ),
    ],
    [
      'malformed Source line',
      source =>
        source.replace(' * Source: themes/ocean/oceanTheme.ts', ' * Source: '),
    ],
  ])('keeps a %s significant', (_label, mutate) => {
    const current = generatedCssArtifact();
    expect(normalizeThemeVerifyForCompare(mutate(current))).not.toBe(
      normalizeThemeVerifyForCompare(current),
    );
  });

  it('normalizes one generated JavaScript header source and version pair', () => {
    const current = generatedJsArtifact();
    const fromThemeDir = generatedJsArtifact({
      source: 'oceanTheme.ts',
      cli: '0.6.5',
      core: '0.6.5',
    });
    expect(normalizeThemeVerifyForCompare(fromThemeDir)).toBe(
      normalizeThemeVerifyForCompare(current),
    );
    expect(normalizeThemeBuildForCompare(fromThemeDir)).not.toBe(
      normalizeThemeBuildForCompare(current),
    );
  });

  it.each([
    [
      'JavaScript body change',
      source => source.replace("name: 'ocean'", "name: 'reef'"),
    ],
    [
      'Source text in the JavaScript body',
      source =>
        source.replace(
          "export const oceanTheme = {name: 'ocean'};",
          "export const oceanTheme = {name: 'ocean'};\n * Source: body.js",
        ),
    ],
    [
      'missing JavaScript Source line',
      source => source.replace(' * Source: themes/ocean/oceanTheme.ts\n', ''),
    ],
    [
      'duplicate JavaScript Source line',
      source =>
        source.replace(
          ' * Source: themes/ocean/oceanTheme.ts\n',
          ' * Source: themes/ocean/oceanTheme.ts\n * Source: oceanTheme.ts\n',
        ),
    ],
    [
      'malformed JavaScript Source line',
      source =>
        source.replace(' * Source: themes/ocean/oceanTheme.ts', ' * Source: '),
    ],
  ])('keeps a %s significant', (_label, mutate) => {
    const current = generatedJsArtifact();
    expect(normalizeThemeVerifyForCompare(mutate(current))).not.toBe(
      normalizeThemeVerifyForCompare(current),
    );
  });
});

/**
 * The files `theme build` writes for the ocean fixture, by name. The build
 * writes the same bytes in any folder, so the file builds once and each
 * fixture gets a copy.
 * @type {Map<string, Buffer> | null}
 */
let builtOcean = null;

/**
 * Put the ocean theme's built files beside its source in `oceanDir`.
 * @param {string} oceanDir
 */
function writeBuiltOcean(oceanDir) {
  if (builtOcean != null) {
    for (const [file, bytes] of builtOcean) {
      fs.writeFileSync(path.join(oceanDir, file), bytes);
    }
    return;
  }
  const sources = new Set(fs.readdirSync(oceanDir));
  const built = spawnSync(
    process.execPath,
    [
      path.join(process.cwd(), 'packages/cli/clients/cli/bin/astryx.mjs'),
      'theme',
      'build',
      'themes/ocean/oceanTheme.ts',
    ],
    {cwd: tmpDir, encoding: 'utf-8', timeout: 30_000},
  );
  if (built.status !== 0) {
    throw new Error(
      `Could not build the theme fixture: ${built.stderr || built.stdout}`,
    );
  }
  builtOcean = new Map(
    fs
      .readdirSync(oceanDir)
      .filter(file => !sources.has(file))
      .map(file => [file, fs.readFileSync(path.join(oceanDir, file))]),
  );
}

/**
 * Write a minimal integration package into tmpDir.
 * Returns the package directory.
 */
function writePackage({
  name = '@acme/widgets',
  version = '1.0.0',
  files,
  manifest = "export default {themes: './themes'};\n",
  themes = true,
  themeExports = false,
  npmignore,
  components = false,
  templates = false,
  scripts,
} = {}) {
  const pkg = {name, version};
  // A theme needs a CLI that reads typed theme descriptors.
  if (themes) pkg.peerDependencies = {'@astryxdesign/cli': '>=0.6.4'};
  if (files !== undefined) pkg.files = files;
  if (scripts !== undefined) pkg.scripts = scripts;
  if (themes && themeExports) {
    pkg.exports = {
      './themes/ocean': './themes/ocean/ocean.js',
      './themes/ocean.css': './themes/ocean/ocean.css',
    };
  }
  fs.writeFileSync(
    path.join(tmpDir, 'package.json'),
    JSON.stringify(pkg, null, 2) + '\n',
  );
  if (manifest != null) {
    fs.writeFileSync(path.join(tmpDir, 'astryx.integration.mjs'), manifest);
  }
  if (themes) {
    const root = path.join(tmpDir, 'themes');
    fs.mkdirSync(path.join(root, 'ocean'), {recursive: true});
    fs.writeFileSync(
      path.join(root, 'ocean', 'oceanTheme.ts'),
      "import {defineTheme} from '@astryxdesign/core/theme';\n\nexport const oceanTheme = defineTheme({name: 'ocean'});\n",
    );
    fs.writeFileSync(
      path.join(root, 'ocean', 'oceanTheme.doc.mjs'),
      `/** @type {import('@astryxdesign/cli/authoring').ThemeDoc} */
export default {type: 'theme', name: 'ocean', displayName: 'Ocean', description: 'Ocean theme.', maintained: true};
`,
    );
    if (themeExports) {
      writeBuiltOcean(path.join(root, 'ocean'));
    }
  }
  if (components) {
    const root = path.join(tmpDir, 'components');
    fs.mkdirSync(root, {recursive: true});
    fs.writeFileSync(
      path.join(root, 'Card.tsx'),
      'export default function Card() { return null; }\n',
    );
  }
  if (templates) {
    const root = path.join(tmpDir, 'templates');
    fs.mkdirSync(root, {recursive: true});
    fs.writeFileSync(
      path.join(root, 'stray.tsx'),
      'export default function Stray() { return null; }\n',
    );
  }
  if (npmignore) {
    fs.writeFileSync(path.join(tmpDir, '.npmignore'), npmignore);
  }
  return tmpDir;
}

function setThemeExports(exportsMap) {
  const packageFile = path.join(tmpDir, 'package.json');
  const pkg = JSON.parse(fs.readFileSync(packageFile, 'utf-8'));
  pkg.exports = exportsMap;
  fs.writeFileSync(packageFile, `${JSON.stringify(pkg, null, 2)}\n`);
}

function runCliVerify() {
  const run = spawnSync(
    process.execPath,
    [
      path.join(process.cwd(), 'packages/cli/clients/cli/bin/astryx.mjs'),
      'integration',
      'verify',
      '--json',
    ],
    {cwd: tmpDir, encoding: 'utf-8', timeout: 30_000},
  );
  return {
    status: run.status,
    stderr: run.stderr,
    receipt: run.stdout ? JSON.parse(run.stdout) : null,
  };
}

/**
 * Give the built ocean theme a font stylesheet and an entry module that loads
 * the theme's own styles, and export them the way such a package does.
 * @param {string} entry
 * @param {string} [file] the entry's file name in `entries/`
 */
function writeOwnStylesEntry(entry, file = 'ocean.mjs') {
  fs.writeFileSync(
    path.join(tmpDir, 'themes', 'ocean', 'ocean.fonts.css'),
    "@font-face { font-family: 'Ocean Sans'; src: local('Ocean Sans'); }\n",
  );
  fs.mkdirSync(path.join(tmpDir, 'entries'), {recursive: true});
  fs.writeFileSync(path.join(tmpDir, 'entries', file), entry);
  const packageFile = path.join(tmpDir, 'package.json');
  const pkg = JSON.parse(fs.readFileSync(packageFile, 'utf-8'));
  pkg.files = ['astryx.integration.mjs', 'themes', 'entries'];
  pkg.exports = {
    './themes/ocean': `./entries/${file}`,
    './themes/ocean.css': './themes/ocean/ocean.css',
    './themes/ocean.fonts.css': './themes/ocean/ocean.fonts.css',
  };
  fs.writeFileSync(packageFile, `${JSON.stringify(pkg, null, 2)}\n`);
}

/**
 * Rename the ocean theme to deep-sea, keeping its `ocean` slug, and build it,
 * so its outputs are named after the theme: `deep-sea.css` and `deep-sea.js`,
 * which exports `deepSeaTheme`.
 */
function writeRenamedOcean() {
  writePackage({files: ['astryx.integration.mjs', 'themes', 'entries']});
  fs.writeFileSync(
    path.join(tmpDir, 'themes', 'ocean', 'oceanTheme.ts'),
    "import {defineTheme} from '@astryxdesign/core/theme';\n\nexport const oceanTheme = defineTheme({name: 'deep-sea'});\n",
  );
  const built = spawnSync(
    process.execPath,
    [
      path.join(process.cwd(), 'packages/cli/clients/cli/bin/astryx.mjs'),
      'theme',
      'build',
      'themes/ocean/oceanTheme.ts',
    ],
    {cwd: tmpDir, encoding: 'utf-8', timeout: 30_000},
  );
  if (built.status !== 0) {
    throw new Error(`Could not build the theme fixture: ${built.stderr}`);
  }
}

/**
 * Give the ocean theme an icon registry and build it, so its built module
 * also exports `oceanIcons`.
 */
function writeOceanWithIcons() {
  writePackage({files: ['astryx.integration.mjs', 'themes', 'entries']});
  const themeDir = path.join(tmpDir, 'themes', 'ocean');
  fs.writeFileSync(
    path.join(themeDir, 'icons.js'),
    'export const oceanIcons = {};\n',
  );
  fs.writeFileSync(
    path.join(themeDir, 'oceanTheme.ts'),
    "import {defineTheme} from '@astryxdesign/core/theme';\nimport {oceanIcons} from './icons';\n\nexport const oceanTheme = defineTheme({name: 'ocean', icons: oceanIcons});\n",
  );
  const built = spawnSync(
    process.execPath,
    [
      path.join(process.cwd(), 'packages/cli/clients/cli/bin/astryx.mjs'),
      'theme',
      'build',
      'themes/ocean/oceanTheme.ts',
    ],
    {cwd: tmpDir, encoding: 'utf-8', timeout: 30_000},
  );
  if (built.status !== 0) {
    throw new Error(`Could not build the theme fixture: ${built.stderr}`);
  }
}

// An entry like one whose import is the whole integration: it loads the
// theme's fonts and stylesheet, by relative path and through the package's
// own exports, and re-exports the built theme.
const OWN_STYLES_ENTRY = `// Copyright (c) Acme.

import '../themes/ocean/ocean.fonts.css';
import '@acme/widgets/themes/ocean.css';

export {oceanTheme} from '../themes/ocean/ocean.js';
`;

describe('a theme module that loads its own styles', () => {
  it('passes an entry that imports the theme stylesheet and fonts and re-exports the built module', async () => {
    writePackage({themeExports: true});
    writeOwnStylesEntry(OWN_STYLES_ENTRY);

    const result = await integrationPackCheck({cwd: tmpDir});

    expect(result.data.issues).toEqual([]);
    expect(result.data.packable).toBe(true);
    const cli = runCliVerify();
    expect(cli.status, cli.stderr).toBe(0);
    expect(cli.receipt?.data.issues).toEqual([]);
  });

  it('passes an entry that imports its fonts through the package exports and re-exports everything', async () => {
    writePackage({themeExports: true});
    writeOwnStylesEntry(
      "import '@acme/widgets/themes/ocean.fonts.css';\nimport '../themes/ocean/ocean.css';\nexport * from '../themes/ocean/ocean.js';\n",
    );

    const result = await integrationPackCheck({cwd: tmpDir});

    expect(result.data.issues).toEqual([]);
    expect(result.data.packable).toBe(true);
  });

  it.each([
    [
      'also imports another stylesheet',
      `${OWN_STYLES_ENTRY}import './other.css';\n`,
      "./other.css is not the theme's own stylesheet or font stylesheet",
    ],
    [
      'also imports a script',
      `import './setup.mjs';\n${OWN_STYLES_ENTRY}`,
      "./setup.mjs is not the theme's own stylesheet or font stylesheet",
    ],
    [
      'runs code',
      `${OWN_STYLES_ENTRY}console.log('ocean');\n`,
      'line 7 is neither a stylesheet import nor the re-export',
    ],
    [
      'exports another value',
      `${OWN_STYLES_ENTRY}export const extra = 1;\n`,
      'line 7 is neither a stylesheet import nor the re-export',
    ],
    [
      'renames the theme it re-exports',
      "import '../themes/ocean/ocean.css';\nexport {oceanTheme, oceanTheme as theme} from '../themes/ocean/ocean.js';\n",
      'it re-exports names other than oceanTheme',
    ],
    [
      'binds the stylesheet it imports',
      "import styles from '../themes/ocean/ocean.css';\nexport {oceanTheme} from '../themes/ocean/ocean.js';\n",
      'its import of ../themes/ocean/ocean.css is not a side-effect import',
    ],
    [
      'imports the stylesheet as a CSS module script',
      "import '../themes/ocean/ocean.css' with {type: 'css'};\nexport {oceanTheme} from '../themes/ocean/ocean.js';\n",
      'its import of ../themes/ocean/ocean.css is not a side-effect import',
    ],
    [
      're-exports another name',
      "import '../themes/ocean/ocean.css';\nexport {oceanTheme, missing} from '../themes/ocean/ocean.js';\n",
      'it re-exports names other than oceanTheme',
    ],
    [
      're-exports a copy that is not a .js module',
      "import '../themes/ocean/ocean.css';\nexport {oceanTheme} from './copy.cjs';\n",
      'its re-export from ./copy.cjs does not name a .js module',
    ],
    [
      'has a directive',
      `'use client';\n${OWN_STYLES_ENTRY}`,
      'it has a directive',
    ],
    [
      're-exports twice',
      `${OWN_STYLES_ENTRY}export * from '../themes/ocean/ocean.js';\n`,
      'it has more than one re-export',
    ],
  ])('fails an entry that %s', async (_label, entry, reason) => {
    writePackage({themeExports: true});
    writeOwnStylesEntry(entry);
    fs.writeFileSync(path.join(tmpDir, 'entries', 'other.css'), '.x {}\n');
    fs.writeFileSync(path.join(tmpDir, 'entries', 'setup.mjs'), 'export {};\n');
    fs.copyFileSync(
      path.join(tmpDir, 'themes', 'ocean', 'ocean.js'),
      path.join(tmpDir, 'entries', 'copy.cjs'),
    );

    const result = await integrationPackCheck({cwd: tmpDir});

    expect(result.data.packable).toBe(false);
    expect(result.data.issues).toEqual([
      {
        code: 'theme_module_stale',
        severity: 'error',
        message: `Theme "ocean" module is not the module \`${formatCliCommand('theme build themes/ocean/oceanTheme.ts', tmpDir)}\` writes and does not only wrap it: ${reason}. A module that wraps the built module may only import the theme's own stylesheet and font stylesheet for their side effects and re-export from the built module either everything or only its theme, as oceanTheme.`,
      },
    ]);
  });

  it('fails an entry whose re-exported module drifts from source', async () => {
    writePackage({themeExports: true});
    writeOwnStylesEntry(OWN_STYLES_ENTRY);
    fs.appendFileSync(
      path.join(tmpDir, 'themes', 'ocean', 'ocean.js'),
      '// stale module\n',
    );

    const result = await integrationPackCheck({cwd: tmpDir});

    expect(result.data.packable).toBe(false);
    expect(result.data.issues).toEqual([
      {
        code: 'theme_module_stale',
        severity: 'error',
        message: `Theme "ocean" module re-exports ../themes/ocean/ocean.js, which does not match themes/ocean/oceanTheme.ts. Run \`${formatCliCommand('theme build themes/ocean/oceanTheme.ts', tmpDir)}\` before packing.`,
      },
    ]);
  });

  it('does not accept a TypeScript entry', async () => {
    writePackage({themeExports: true});
    writeOwnStylesEntry(OWN_STYLES_ENTRY, 'ocean.ts');

    const result = await integrationPackCheck({cwd: tmpDir});

    expect(result.data.packable).toBe(false);
    expect(result.data.issues).toEqual([
      {
        code: 'theme_module_stale',
        severity: 'error',
        message: `Theme "ocean" module does not match themes/ocean/oceanTheme.ts. Run \`${formatCliCommand('theme build themes/ocean/oceanTheme.ts', tmpDir)}\` before packing.`,
      },
    ]);
  });

  it('does not accept an entry that re-exports itself', async () => {
    writePackage({themeExports: true});
    writeOwnStylesEntry(
      "import '../themes/ocean/ocean.css';\nexport * from './ocean.js';\n",
      'ocean.js',
    );

    const result = await integrationPackCheck({cwd: tmpDir});

    expect(result.data.packable).toBe(false);
    expect(result.data.issues).toContainEqual(
      expect.objectContaining({
        code: 'theme_import_unresolvable',
        message: expect.stringContaining('does not export "oceanTheme"'),
      }),
    );
  });

  it('passes an entry for a theme whose own name differs from its slug', async () => {
    writeRenamedOcean();
    writeOwnStylesEntry(
      "import '../themes/ocean/deep-sea.css';\nexport {deepSeaTheme as oceanTheme} from '../themes/ocean/deep-sea.js';\n",
    );
    setThemeExports({
      './themes/ocean': './entries/ocean.mjs',
      './themes/ocean.css': './themes/ocean/deep-sea.css',
    });

    const result = await integrationPackCheck({cwd: tmpDir});

    expect(result.data.issues).toEqual([]);
    expect(result.data.packable).toBe(true);
    const cli = runCliVerify();
    expect(cli.status, cli.stderr).toBe(0);
  });

  it('says a rebuild cannot fix exports that name the theme after its folder once its source renames it', async () => {
    writePackage({
      files: ['astryx.integration.mjs', 'themes'],
      themeExports: true,
    });
    fs.writeFileSync(
      path.join(tmpDir, 'themes', 'ocean', 'oceanTheme.ts'),
      "import {defineTheme} from '@astryxdesign/core/theme';\n\nexport const oceanTheme = defineTheme({name: 'sea'});\n",
    );

    const result = await integrationPackCheck({cwd: tmpDir});

    expect(result.data.issues.map(issue => issue.message)).toEqual([
      `Theme "ocean" module is themes/ocean/ocean.js, but oceanTheme.ts calls defineTheme with name: 'sea', so \`${formatCliCommand('theme build themes/ocean/oceanTheme.ts', tmpDir)}\` writes themes/ocean/sea.js instead and rebuilding never updates ocean.js. Fix: point the package export that serves it at themes/ocean/sea.js after building, or set name: 'ocean' in oceanTheme.ts and rebuild.`,
      `Theme "ocean" stylesheet is themes/ocean/ocean.css, but oceanTheme.ts calls defineTheme with name: 'sea', so \`${formatCliCommand('theme build themes/ocean/oceanTheme.ts', tmpDir)}\` writes themes/ocean/sea.css instead and rebuilding never updates ocean.css. Fix: point the package export that serves it at themes/ocean/sea.css after building, or set name: 'ocean' in oceanTheme.ts and rebuild.`,
    ]);
  });

  it('compares a partial export set with the module named after the theme', async () => {
    writeRenamedOcean();
    setThemeExports({'./themes/ocean': './themes/ocean/deep-sea.js'});

    const result = await integrationPackCheck({cwd: tmpDir});

    expect(result.data.packable).toBe(true);
    expect(result.data.issues.map(issue => issue.code)).toEqual([
      'theme_exports_incomplete',
    ]);
  });

  it('passes an entry that re-exports only the theme from a built module that also exports its icons', async () => {
    writeOceanWithIcons();
    writeOwnStylesEntry(OWN_STYLES_ENTRY);

    const result = await integrationPackCheck({cwd: tmpDir});

    expect(result.data.issues).toEqual([]);
    expect(result.data.packable).toBe(true);
  });

  it('fails an entry that gives the built icons the theme export name', async () => {
    writeOceanWithIcons();
    writeOwnStylesEntry(
      "import '../themes/ocean/ocean.css';\nexport {oceanIcons as oceanTheme} from '../themes/ocean/ocean.js';\n",
    );

    const result = await integrationPackCheck({cwd: tmpDir});

    expect(result.data.packable).toBe(false);
    expect(result.data.issues).toEqual([
      expect.objectContaining({
        code: 'theme_module_stale',
        message: expect.stringContaining(
          'it re-exports oceanIcons, which is not the built theme',
        ),
      }),
    ]);
  });

  it('fails when packing changes the module an entry re-exports', async () => {
    const prepack = [
      "const fs=require('fs')",
      "fs.copyFileSync('themes/ocean/ocean.js','.ocean.js.orig')",
      "fs.appendFileSync('themes/ocean/ocean.js','// packed\\n')",
    ].join(';');
    const postpack =
      "require('fs').renameSync('.ocean.js.orig','themes/ocean/ocean.js')";
    writePackage({
      themeExports: true,
      scripts: {
        prepack: `node -e "${prepack}"`,
        postpack: `node -e "${postpack}"`,
      },
    });
    writeOwnStylesEntry(OWN_STYLES_ENTRY);

    const result = await integrationPackCheck({cwd: tmpDir});

    expect(result.data.packable).toBe(false);
    expect(result.data.issues).toEqual([
      {
        code: 'packed_theme_module_changed',
        severity: 'error',
        message:
          'Theme "ocean" module changed during packing. Keep the built output unchanged in the tarball.',
      },
    ]);
  });
});

describe('integrationPackCheck', () => {
  it('returns packable:true for a valid integration with themes', async () => {
    writePackage({files: ['astryx.integration.mjs', 'themes']});
    const result = await integrationPackCheck({cwd: tmpDir});

    expect(result.type).toBe('integration.pack-check');
    expect(
      result.data.packable,
      JSON.stringify(result.data.issues, null, 2),
    ).toBe(true);
    expect(result.data.name).toBe('@acme/widgets');
    expect(result.data.tarball).not.toBeNull();
    expect(result.data.inventory.manifest).toBe('astryx.integration.mjs');
    expect(result.data.contributions.local?.themes).toEqual([
      {slug: 'ocean', exportName: 'oceanTheme'},
    ]);
    expect(result.data.contributions.packed).toEqual(
      result.data.contributions.local,
    );
    expect(result.data.issues.filter(i => i.severity === 'error')).toHaveLength(
      0,
    );
  });

  it('warns but remains packable when a theme declares no built exports', async () => {
    writePackage({files: ['astryx.integration.mjs', 'themes']});

    const result = await integrationPackCheck({cwd: tmpDir});

    expect(result.data.packable).toBe(true);
    expect(result.data.issues).toEqual([
      {
        code: 'theme_exports_missing',
        severity: 'warning',
        message: `Theme "ocean" has no declared built exports. The package remains source-compatible. To make it importable, run \`${formatCliCommand('theme build themes/ocean/oceanTheme.ts', tmpDir)}\` and export "./themes/ocean" plus "./themes/ocean.css" from package.json; \`${formatCliCommand('integration add theme ocean', tmpDir)}\` creates those exports for a new theme.`,
      },
    ]);
    const cli = runCliVerify();
    expect(cli.status, cli.stderr).toBe(0);
    expect(cli.receipt?.data.packable).toBe(true);
    expect(cli.receipt?.data.issues).toEqual(result.data.issues);
  });

  it('fails a package that ships a theme on a CLI range that cannot read it', async () => {
    writePackage({files: ['astryx.integration.mjs', 'themes']});
    const pkgFile = path.join(tmpDir, 'package.json');
    const pkg = JSON.parse(fs.readFileSync(pkgFile, 'utf-8'));
    delete pkg.peerDependencies;
    fs.writeFileSync(pkgFile, `${JSON.stringify(pkg, null, 2)}\n`);

    const missing = await integrationPackCheck({cwd: tmpDir});
    expect(missing.data.packable).toBe(false);
    expect(missing.data.issues).toContainEqual(
      expect.objectContaining({
        code: 'themes_need_cli',
        message: expect.stringContaining('ships a theme'),
      }),
    );

    pkg.peerDependencies = {'@astryxdesign/cli': '^0.6.3'};
    fs.writeFileSync(pkgFile, `${JSON.stringify(pkg, null, 2)}\n`);
    const old = await integrationPackCheck({cwd: tmpDir});
    expect(old.data.issues).toContainEqual(
      expect.objectContaining({code: 'themes_need_cli'}),
    );

    // Published 0.6.4 reads typed theme descriptors.
    pkg.peerDependencies = {'@astryxdesign/cli': '>=0.6.4'};
    fs.writeFileSync(pkgFile, `${JSON.stringify(pkg, null, 2)}\n`);
    const current = await integrationPackCheck({cwd: tmpDir});
    expect(current.data.issues).not.toContainEqual(
      expect.objectContaining({code: 'themes_need_cli'}),
    );
  });

  it('fails when a declared theme export does not resolve', async () => {
    writePackage({
      files: ['astryx.integration.mjs', 'themes'],
      themeExports: true,
    });
    fs.rmSync(path.join(tmpDir, 'themes', 'ocean', 'ocean.css'));

    const result = await integrationPackCheck({cwd: tmpDir});

    expect(result.data.packable).toBe(false);
    expect(result.data.issues).toContainEqual(
      expect.objectContaining({
        code: 'theme_import_unresolvable',
        message: expect.stringContaining('stylesheet export'),
      }),
    );
  });

  it.each([
    {
      label: 'module only',
      exportsMap: {'./built': './themes/ocean/ocean.js'},
      specifiers: ['@acme/widgets/built'],
    },
    {
      label: 'stylesheet only',
      exportsMap: {'./theme.css': './themes/ocean/ocean.css'},
      specifiers: ['@acme/widgets/theme.css'],
    },
    {
      label: 'font stylesheet only',
      exportsMap: {'./fonts.css': './themes/ocean/ocean.fonts.css'},
      specifiers: ['@acme/widgets/fonts.css'],
      fonts: true,
    },
    {
      label: 'module and font stylesheet',
      exportsMap: {
        './built': './themes/ocean/ocean.js',
        './fonts.css': './themes/ocean/ocean.fonts.css',
      },
      specifiers: ['@acme/widgets/built', '@acme/widgets/fonts.css'],
      fonts: true,
    },
    {
      label: 'stylesheet and font stylesheet',
      exportsMap: {
        './theme.css': './themes/ocean/ocean.css',
        './fonts.css': './themes/ocean/ocean.fonts.css',
      },
      specifiers: ['@acme/widgets/theme.css', '@acme/widgets/fonts.css'],
      fonts: true,
    },
  ])(
    'warns and exits zero for an incomplete $label export set',
    async ({exportsMap, specifiers, fonts}) => {
      writePackage({
        files: ['astryx.integration.mjs', 'themes'],
        themeExports: true,
      });
      if (fonts) {
        fs.writeFileSync(
          path.join(tmpDir, 'themes', 'ocean', 'ocean.fonts.css'),
          '@font-face { font-family: Ocean; src: url(./ocean.woff2); }\n',
        );
      }
      setThemeExports(exportsMap);
      const message = `Theme "ocean" exports ${specifiers.join(', ')} without a complete built module and stylesheet pair. Missing partner exports alone do not block packing; add the matching export when the theme should be importable. Every declared export must resolve. Staleness is a warning until the complete importable pair is declared.`;

      const result = await integrationPackCheck({cwd: tmpDir});

      expect(result.data.packable).toBe(true);
      expect(result.data.issues).toEqual([
        {code: 'theme_exports_incomplete', severity: 'warning', message},
      ]);
      const cli = runCliVerify();
      expect(cli.status, cli.stderr).toBe(0);
      expect(cli.receipt?.data.packable).toBe(true);
      expect(cli.receipt?.data.issues).toEqual(result.data.issues);
    },
  );

  it('keeps a published 0.6.5 stylesheet-only package packable', async () => {
    writePackage({
      files: ['astryx.integration.mjs', 'themes'],
      themeExports: true,
    });
    setThemeExports({'./theme.css': './themes/ocean/ocean.css'});
    const provenance = released065Ocean;
    const released = Buffer.from(provenance.base64, 'base64');
    expect(createHash('sha256').update(released).digest('hex')).toBe(
      provenance.sha256,
    );
    expect(provenance).toMatchObject({
      artifact: 'released-0.6.5-ocean.css',
      package: '@astryxdesign/[email protected]',
      source: 'npm',
      command: 'astryx theme build oceanTheme.ts',
      workingDirectory: 'themes/ocean',
      inputSha256:
        '05ac5f9fc3eb71a0096e4fd6dcecfb0d508e403a564be49bf5c535b3c5080245',
      sha256:
        'd48aa16f5a87dcaa0d851928a4be735f80c29e462d3dd223cfc38570495f6fbd',
    });
    const source = fs.readFileSync(
      path.join(tmpDir, 'themes', 'ocean', 'oceanTheme.ts'),
    );
    expect(createHash('sha256').update(source).digest('hex')).toBe(
      provenance.inputSha256,
    );
    fs.writeFileSync(
      path.join(tmpDir, 'themes', 'ocean', 'ocean.css'),
      released,
    );

    const result = await integrationPackCheck({cwd: tmpDir});

    expect(result.data.packable).toBe(true);
    expect(result.data.issues).toEqual([
      {
        code: 'theme_exports_incomplete',
        severity: 'warning',
        message:
          'Theme "ocean" exports @acme/widgets/theme.css without a complete built module and stylesheet pair. Missing partner exports alone do not block packing; add the matching export when the theme should be importable. Every declared export must resolve. Staleness is a warning until the complete importable pair is declared.',
      },
      // A 0.6.5-built stylesheet still carries the root data-color defaults
      // that theme output no longer emits, so it no longer matches its source.
      {
        code: 'theme_stylesheet_stale',
        severity: 'warning',
        message: `Theme "ocean" stylesheet does not match themes/ocean/oceanTheme.ts. This incomplete export remains packable, but run \`${formatCliCommand('theme build themes/ocean/oceanTheme.ts', tmpDir)}\` before adding its matching export.`,
      },
    ]);
    const cli = runCliVerify();
    expect(cli.status, cli.stderr).toBe(0);
    expect(cli.receipt?.data.packable).toBe(true);
    expect(cli.receipt?.data.issues).toEqual(result.data.issues);
  });

  it('warns and exits zero for stale content in an incomplete export set', async () => {
    writePackage({
      files: ['astryx.integration.mjs', 'themes'],
      themeExports: true,
    });
    setThemeExports({'./theme.css': './themes/ocean/ocean.css'});
    fs.appendFileSync(
      path.join(tmpDir, 'themes', 'ocean', 'ocean.css'),
      '/* stale stylesheet body */\n',
    );

    const result = await integrationPackCheck({cwd: tmpDir});

    expect(result.data.packable).toBe(true);
    expect(result.data.issues).toEqual([
      {
        code: 'theme_exports_incomplete',
        severity: 'warning',
        message:
          'Theme "ocean" exports @acme/widgets/theme.css without a complete built module and stylesheet pair. Missing partner exports alone do not block packing; add the matching export when the theme should be importable. Every declared export must resolve. Staleness is a warning until the complete importable pair is declared.',
      },
      {
        code: 'theme_stylesheet_stale',
        severity: 'warning',
        message: `Theme "ocean" stylesheet does not match themes/ocean/oceanTheme.ts. This incomplete export remains packable, but run \`${formatCliCommand('theme build themes/ocean/oceanTheme.ts', tmpDir)}\` before adding its matching export.`,
      },
    ]);
    const cli = runCliVerify();
    expect(cli.status, cli.stderr).toBe(0);
    expect(cli.receipt?.data.packable).toBe(true);
    expect(cli.receipt?.data.issues).toEqual(result.data.issues);
  });

  it('passes a complete pair generated by the current CLI', async () => {
    writePackage({
      files: ['astryx.integration.mjs', 'themes'],
      themeExports: true,
    });

    const result = await integrationPackCheck({cwd: tmpDir});

    expect(result.data.packable).toBe(true);
    expect(result.data.issues).toEqual([]);
    const cli = runCliVerify();
    expect(cli.status, cli.stderr).toBe(0);
    expect(cli.receipt?.data.packable).toBe(true);
    expect(cli.receipt?.data.issues).toEqual([]);
  });

  it('passes a complete pair built from inside the theme directory', async () => {
    writePackage({
      files: ['astryx.integration.mjs', 'themes'],
      themeExports: true,
    });
    const themeDir = path.join(tmpDir, 'themes', 'ocean');
    const built = spawnSync(
      process.execPath,
      [
        path.join(process.cwd(), 'packages/cli/clients/cli/bin/astryx.mjs'),
        'theme',
        'build',
        'oceanTheme.ts',
      ],
      {cwd: themeDir, encoding: 'utf-8', timeout: 30_000},
    );
    expect(built.status, built.stderr).toBe(0);

    const result = await integrationPackCheck({cwd: tmpDir});

    expect(result.data.packable).toBe(true);
    expect(result.data.issues).toEqual([]);
    const cli = runCliVerify();
    expect(cli.status, cli.stderr).toBe(0);
    expect(cli.receipt?.data.issues).toEqual([]);
  });

  it('fails when a complete pair drifts from source', async () => {
    writePackage({
      files: ['astryx.integration.mjs', 'themes'],
      themeExports: true,
    });
    fs.appendFileSync(
      path.join(tmpDir, 'themes', 'ocean', 'ocean.js'),
      '// stale module\n',
    );
    fs.appendFileSync(
      path.join(tmpDir, 'themes', 'ocean', 'ocean.css'),
      '/* stale stylesheet */\n',
    );

    const result = await integrationPackCheck({cwd: tmpDir});

    expect(result.data.packable).toBe(false);
    expect(result.data.issues).toEqual([
      {
        code: 'theme_module_stale',
        severity: 'error',
        message: `Theme "ocean" module does not match themes/ocean/oceanTheme.ts. Run \`${formatCliCommand('theme build themes/ocean/oceanTheme.ts', tmpDir)}\` before packing.`,
      },
      {
        code: 'theme_stylesheet_stale',
        severity: 'error',
        message: `Theme "ocean" stylesheet does not match themes/ocean/oceanTheme.ts. Run \`${formatCliCommand('theme build themes/ocean/oceanTheme.ts', tmpDir)}\` before packing.`,
      },
    ]);
    const cli = runCliVerify();
    expect(cli.status).toBe(1);
    expect(cli.receipt?.data.packable).toBe(false);
    expect(cli.receipt?.data.issues).toEqual(result.data.issues);
  });

  it('fails when a built module omits the descriptor export', async () => {
    writePackage({
      files: ['astryx.integration.mjs', 'themes'],
      themeExports: true,
    });
    const built = path.join(tmpDir, 'themes', 'ocean', 'ocean.js');
    fs.writeFileSync(
      built,
      fs
        .readFileSync(built, 'utf-8')
        .replace('export const oceanTheme', 'export const otherTheme'),
    );

    const result = await integrationPackCheck({cwd: tmpDir});

    expect(result.data.packable).toBe(false);
    expect(result.data.issues).toContainEqual(
      expect.objectContaining({
        code: 'theme_import_unresolvable',
        message: expect.stringContaining('does not export "oceanTheme"'),
      }),
    );
  });

  it('fails when an exported font stylesheet is absent from the tarball', async () => {
    writePackage({npmignore: '**/*.fonts.css\n', themeExports: true});
    const packageFile = path.join(tmpDir, 'package.json');
    const pkg = JSON.parse(fs.readFileSync(packageFile, 'utf-8'));
    pkg.exports['./themes/ocean.fonts.css'] = './themes/ocean/ocean.fonts.css';
    fs.writeFileSync(packageFile, `${JSON.stringify(pkg, null, 2)}\n`);
    fs.writeFileSync(
      path.join(tmpDir, 'themes', 'ocean', 'ocean.fonts.css'),
      '@import url("https://example.com/fonts.css");\n',
    );

    const result = await integrationPackCheck({cwd: tmpDir});

    expect(result.data.packable).toBe(false);
    expect(result.data.issues).toContainEqual(
      expect.objectContaining({
        code: 'theme_import_unresolvable',
        message: expect.stringContaining('font stylesheet does not resolve'),
      }),
    );
  });

  it('fails when a theme entry omits its inferred runtime export', async () => {
    writePackage({files: ['astryx.integration.mjs', 'themes']});
    fs.writeFileSync(
      path.join(tmpDir, 'themes', 'ocean', 'oceanTheme.ts'),
      'export const anotherTheme = {};\n',
    );

    const result = await integrationPackCheck({cwd: tmpDir});

    expect(result.data.packable).toBe(false);
    expect(result.data.issues).toContainEqual(
      expect.objectContaining({
        code: 'invalid_theme',
        message: expect.stringContaining(
          'entry "oceanTheme.ts" does not export "oceanTheme"',
        ),
      }),
    );
  });

  it('fails when a theme imports a missing local file', async () => {
    writePackage({files: ['astryx.integration.mjs', 'themes']});
    fs.writeFileSync(
      path.join(tmpDir, 'themes', 'ocean', 'oceanTheme.ts'),
      "import {oceanPalette} from './tokens/ocean.palette';\nexport const oceanTheme = {oceanPalette};\n",
    );

    const result = await integrationPackCheck({cwd: tmpDir});

    expect(result.data.packable).toBe(false);
    expect(result.data.issues).toContainEqual(
      expect.objectContaining({
        code: 'invalid_theme',
        message: expect.stringContaining(
          'must resolve to a file inside the theme directory',
        ),
      }),
    );
  });

  it('fails when a discovered component is not exported to consumers', async () => {
    writePackage({
      manifest: "export default {components: './components'};\n",
      files: ['astryx.integration.mjs', 'components', 'index.mjs'],
      themes: false,
    });
    const pkgFile = path.join(tmpDir, 'package.json');
    const pkg = JSON.parse(fs.readFileSync(pkgFile, 'utf-8'));
    pkg.exports = {'.': './index.mjs'};
    fs.writeFileSync(pkgFile, `${JSON.stringify(pkg, null, 2)}\n`);
    fs.writeFileSync(
      path.join(tmpDir, 'index.mjs'),
      'export const existing = 1;\n',
    );
    fs.mkdirSync(path.join(tmpDir, 'components'));
    fs.writeFileSync(
      path.join(tmpDir, 'components', 'AcmeWidget.doc.mjs'),
      "export default {type: 'component', name: 'AcmeWidget', description: 'Widget.', props: []};\n",
    );
    fs.writeFileSync(
      path.join(tmpDir, 'components', 'AcmeWidget.tsx'),
      'export function AcmeWidget() { return null; }\n',
    );

    const result = await integrationPackCheck({cwd: tmpDir});

    expect(result.data.packable).toBe(false);
    expect(result.data.issues).toContainEqual(
      expect.objectContaining({
        code: 'component_export_missing',
        message: expect.stringContaining('AcmeWidget'),
      }),
    );
  });

  it('checks the export a component doc names when its file is named otherwise', async () => {
    fs.writeFileSync(
      path.join(tmpDir, 'package.json'),
      `${JSON.stringify({
        name: '@acme/widgets',
        version: '1.0.0',
        files: ['astryx.integration.mjs', 'components'],
        exports: {'./components/Slides': './components/Slides.tsx'},
      })}\n`,
    );
    fs.writeFileSync(
      path.join(tmpDir, 'astryx.integration.mjs'),
      "export default {components: './components'};\n",
    );
    fs.mkdirSync(path.join(tmpDir, 'components'));
    // Slides.tsx exports AcmeCarousel and nothing named Slides.
    fs.writeFileSync(
      path.join(tmpDir, 'components', 'Slides.tsx'),
      'export function AcmeCarousel() { return null; }\n',
    );
    fs.writeFileSync(
      path.join(tmpDir, 'components', 'Slides.doc.mjs'),
      "export default {type: 'component', name: 'AcmeCarousel', import: '@acme/widgets/components/Slides', description: 'x', props: []};\n",
    );

    const result = await integrationPackCheck({cwd: tmpDir});
    expect(result.data.packable).toBe(true);
    expect(result.data.contributions.packed.components).toEqual([
      'AcmeCarousel',
    ]);
  });

  it('checks each family member against the module its family doc imports', async () => {
    fs.writeFileSync(
      path.join(tmpDir, 'package.json'),
      `${JSON.stringify({
        name: '@acme/widgets',
        version: '1.0.0',
        files: ['astryx.integration.mjs', 'components'],
        exports: {'./tabs': './components/tabs/index.ts'},
      })}\n`,
    );
    fs.writeFileSync(
      path.join(tmpDir, 'astryx.integration.mjs'),
      "export default {components: './components'};\n",
    );
    const dir = path.join(tmpDir, 'components', 'tabs');
    fs.mkdirSync(dir, {recursive: true});
    fs.writeFileSync(
      path.join(dir, 'AcmeTabs.tsx'),
      'export function AcmeTabs() { return null; }\nexport function AcmeTabsLegacy() { return null; }\n',
    );
    fs.writeFileSync(
      path.join(dir, 'tab.tsx'),
      'export function AcmeTab() { return null; }\n',
    );
    // The module apps import exports AcmeTabs and AcmeTab, not AcmeTabsLegacy.
    fs.writeFileSync(
      path.join(dir, 'index.ts'),
      "export {AcmeTabs} from './AcmeTabs';\nexport {AcmeTab} from './tab';\n",
    );
    fs.writeFileSync(
      path.join(dir, 'AcmeTabs.doc.mjs'),
      "export default {type: 'component', name: 'AcmeTabs', import: '@acme/widgets/tabs', description: 'x', components: [{name: 'AcmeTabs', description: 'x', props: []}, {name: 'AcmeTab', description: 'x', props: []}, {name: 'AcmeTabsLegacy', description: 'x', props: []}]};\n",
    );

    const result = await integrationPackCheck({cwd: tmpDir});

    expect(result.data.issues).toEqual([]);
    expect(result.data.packable).toBe(true);
    expect(result.data.contributions.packed.components).toEqual([
      'AcmeTab',
      'AcmeTabs',
    ]);
  });

  it.each([
    'a clean checkout',
    'a stale build',
    'a stale build that exports more',
  ])(
    'reads members a family imports from output its pack lifecycle builds, from %s',
    async start => {
      fs.writeFileSync(
        path.join(tmpDir, 'package.json'),
        `${JSON.stringify({
          name: '@acme/widgets',
          version: '1.0.0',
          files: ['astryx.integration.mjs', 'components', 'dist'],
          exports: {'./tabs': './dist/tabs/index.mjs'},
          scripts: {prepack: 'node build.mjs'},
        })}\n`,
      );
      fs.writeFileSync(
        path.join(tmpDir, 'astryx.integration.mjs'),
        "export default {components: './components'};\n",
      );
      // The build writes the module the family imports; a clean checkout has none.
      fs.writeFileSync(
        path.join(tmpDir, 'build.mjs'),
        "import fs from 'node:fs';\nfs.mkdirSync('dist/tabs', {recursive: true});\nfs.writeFileSync('dist/tabs/index.mjs', \"export {AcmeTabs, AcmeTab} from '../../components/tabs/AcmeTabs.tsx';\\n\");\n",
      );
      const dir = path.join(tmpDir, 'components', 'tabs');
      fs.mkdirSync(dir, {recursive: true});
      fs.writeFileSync(
        path.join(dir, 'AcmeTabs.tsx'),
        'export function AcmeTabs() { return null; }\nexport function AcmeTab() { return null; }\nexport function AcmeTabLegacy() { return null; }\n',
      );
      fs.writeFileSync(
        path.join(dir, 'AcmeTabs.doc.mjs'),
        "export default {type: 'component', name: 'AcmeTabs', import: '@acme/widgets/tabs', description: 'x', components: [{name: 'AcmeTabs', description: 'x', props: []}, {name: 'AcmeTab', description: 'x', props: []}, {name: 'AcmeTabLegacy', description: 'x', props: []}]};\n",
      );

      if (start !== 'a clean checkout') {
        // An earlier build: before AcmeTab was exported, or while AcmeTabLegacy
        // still was.
        const names =
          start === 'a stale build'
            ? 'AcmeTabs'
            : 'AcmeTabs, AcmeTab, AcmeTabLegacy';
        fs.mkdirSync(path.join(tmpDir, 'dist', 'tabs'), {recursive: true});
        fs.writeFileSync(
          path.join(tmpDir, 'dist', 'tabs', 'index.mjs'),
          `export {${names}} from '../../components/tabs/AcmeTabs.tsx';\n`,
        );
      }

      const result = await integrationPackCheck({cwd: tmpDir});

      expect(result.data.issues).toEqual([]);
      expect(result.data.packable).toBe(true);
      expect(result.data.contributions.local.components).toEqual(
        result.data.contributions.packed.components,
      );
    },
  );

  it.each(['a clean checkout', 'an incremental build'])(
    'reads members built output re-exports from compiled files, from %s',
    async start => {
      fs.writeFileSync(
        path.join(tmpDir, 'package.json'),
        `${JSON.stringify({
          name: '@acme/widgets',
          version: '1.0.0',
          files: ['astryx.integration.mjs', 'components', 'dist'],
          exports: {'./tabs': './dist/tabs/index.mjs'},
          scripts: {prepack: 'node build.mjs'},
        })}\n`,
      );
      fs.writeFileSync(
        path.join(tmpDir, 'astryx.integration.mjs'),
        "export default {components: './components'};\n",
      );
      // The build compiles each source to its own file and, like an
      // incremental build, rewrites only the files whose output changed.
      const output = {
        'index.mjs':
          "export {AcmeTabs} from './tabs.mjs';\nexport * from './tab.mjs';\n",
        'tabs.mjs': 'export function AcmeTabs() { return null; }\n',
        'tab.mjs': 'export function AcmeTab() { return null; }\n',
      };
      fs.writeFileSync(
        path.join(tmpDir, 'build.mjs'),
        `import fs from 'node:fs';\nconst output = ${JSON.stringify(output)};\nfs.mkdirSync('dist/tabs', {recursive: true});\nfor (const [file, text] of Object.entries(output)) {\n  const target = 'dist/tabs/' + file;\n  if (!fs.existsSync(target) || fs.readFileSync(target, 'utf-8') !== text) fs.writeFileSync(target, text);\n}\n`,
      );
      const dir = path.join(tmpDir, 'components', 'tabs');
      fs.mkdirSync(dir, {recursive: true});
      fs.writeFileSync(
        path.join(dir, 'AcmeTabs.tsx'),
        'export function AcmeTabs() { return null; }\n',
      );
      fs.writeFileSync(
        path.join(dir, 'AcmeTab.tsx'),
        'export function AcmeTab() { return null; }\n',
      );
      fs.writeFileSync(
        path.join(dir, 'AcmeTabs.doc.mjs'),
        "export default {type: 'component', name: 'AcmeTabs', import: '@acme/widgets/tabs', description: 'x', components: [{name: 'AcmeTabs', description: 'x', props: []}, {name: 'AcmeTab', description: 'x', props: []}]};\n",
      );
      if (start === 'an incremental build') {
        // An earlier build from before AcmeTab existed: the file the import
        // names is already current, so the build leaves it untouched.
        fs.mkdirSync(path.join(tmpDir, 'dist', 'tabs'), {recursive: true});
        for (const [file, text] of Object.entries({...output, 'tab.mjs': ''})) {
          fs.writeFileSync(path.join(tmpDir, 'dist', 'tabs', file), text);
        }
      }

      const result = await integrationPackCheck({cwd: tmpDir});

      expect(result.data.issues).toEqual([]);
      expect(result.data.packable).toBe(true);
      expect(result.data.contributions.packed.components).toEqual([
        'AcmeTab',
        'AcmeTabs',
      ]);
      expect(result.data.contributions.local.components).toEqual(
        result.data.contributions.packed.components,
      );
    },
  );

  it('passes a member another folder declares, which has no source', async () => {
    fs.writeFileSync(
      path.join(tmpDir, 'package.json'),
      `${JSON.stringify({
        name: '@acme/widgets',
        version: '1.0.0',
        files: ['astryx.integration.mjs', 'components'],
        exports: {'./menu': './components/menu/index.ts'},
      })}\n`,
    );
    fs.writeFileSync(
      path.join(tmpDir, 'astryx.integration.mjs'),
      "export default {components: './components'};\n",
    );
    const menu = path.join(tmpDir, 'components', 'menu');
    const shared = path.join(tmpDir, 'components', 'shared');
    fs.mkdirSync(menu, {recursive: true});
    fs.mkdirSync(shared, {recursive: true});
    fs.writeFileSync(
      path.join(menu, 'AcmeMenu.doc.mjs'),
      "export default {type: 'component', name: 'AcmeMenu', import: '@acme/widgets/menu', description: 'x', components: [{name: 'AcmeMenuItem', description: 'x', props: []}]};\n",
    );
    fs.writeFileSync(
      path.join(menu, 'AcmeMenu.tsx'),
      'export function AcmeMenu() { return null; }\n',
    );
    fs.writeFileSync(
      path.join(menu, 'index.ts'),
      "export {AcmeMenu} from './AcmeMenu';\nexport {AcmeMenuItem} from '../shared/AcmeMenuItem';\n",
    );
    fs.writeFileSync(
      path.join(shared, 'AcmeMenuItem.tsx'),
      'export function AcmeMenuItem() { return null; }\n',
    );

    const result = await integrationPackCheck({cwd: tmpDir});

    expect(result.data.issues).toEqual([]);
    expect(result.data.packable).toBe(true);
    expect(result.data.contributions.packed.components).toEqual([
      'AcmeMenu',
      'AcmeMenuItem',
    ]);
  });

  it('reports a family doc the loader rejects once, not once per member', async () => {
    fs.writeFileSync(
      path.join(tmpDir, 'package.json'),
      `${JSON.stringify({
        name: '@acme/widgets',
        version: '1.0.0',
        files: ['astryx.integration.mjs', 'components'],
      })}\n`,
    );
    fs.writeFileSync(
      path.join(tmpDir, 'astryx.integration.mjs'),
      "export default {components: './components'};\n",
    );
    fs.mkdirSync(path.join(tmpDir, 'components'));
    fs.writeFileSync(
      path.join(tmpDir, 'components', 'AcmeTabs.tsx'),
      'export function AcmeTabs() { return null; }\nexport function AcmeTab() { return null; }\nexport function AcmeTabPanel() { return null; }\n',
    );
    // A displayName that is not a string makes the loader reject the doc.
    fs.writeFileSync(
      path.join(tmpDir, 'components', 'AcmeTabs.doc.mjs'),
      "export default {type: 'component', name: 'AcmeTabs', displayName: 1, description: 'x', components: [{name: 'AcmeTab', description: 'x', props: []}, {name: 'AcmeTabPanel', description: 'x', props: []}]};\n",
    );

    const result = await integrationPackCheck({cwd: tmpDir});
    const codes = result.data.issues.map(issue => issue.code);

    expect(codes).toContain('component_doc_unloadable');
    expect(codes.length).toBe(new Set(codes).size);
  });

  it('passes a generated component through its exact packed export', async () => {
    fs.writeFileSync(
      path.join(tmpDir, 'package.json'),
      `${JSON.stringify({
        name: '@acme/widgets',
        version: '1.0.0',
        files: ['index.mjs'],
        exports: {'.': './index.mjs'},
      })}\n`,
    );
    fs.writeFileSync(
      path.join(tmpDir, 'index.mjs'),
      'export const existing = 1;\n',
    );
    await integrationAddComponent('AcmeWidget', {cwd: tmpDir});

    const result = await integrationPackCheck({cwd: tmpDir});

    expect(result.data.packable).toBe(true);
    expect(result.data.issues).not.toContainEqual(
      expect.objectContaining({code: 'component_export_missing'}),
    );
  });

  it('resolves public imports in the packed package, not the source', async () => {
    // The root export's target is left out of `files`: the source package
    // resolves it, but an app that installs the tarball cannot.
    fs.writeFileSync(
      path.join(tmpDir, 'package.json'),
      `${JSON.stringify({
        name: '@acme/widgets',
        version: '1.0.0',
        files: ['astryx.integration.mjs'],
        exports: {'.': './index.mjs'},
      })}\n`,
    );
    fs.writeFileSync(
      path.join(tmpDir, 'index.mjs'),
      "export {AcmeWidget} from './components/AcmeWidget.tsx';\n",
    );
    await integrationAddComponent('AcmeWidget', {cwd: tmpDir});
    const docFile = path.join(tmpDir, 'components', 'AcmeWidget.doc.mjs');
    const doc = fs.readFileSync(docFile, 'utf-8');
    expect(doc).toContain('@acme/widgets/components/AcmeWidget');
    fs.writeFileSync(
      docFile,
      doc.replace('@acme/widgets/components/AcmeWidget', '@acme/widgets'),
    );

    const result = await integrationPackCheck({cwd: tmpDir});

    expect(result.data.packable).toBe(false);
    expect(result.data.issues).toContainEqual(
      expect.objectContaining({code: 'component_export_missing'}),
    );
  });

  it('does not count a type-only re-export as the component', async () => {
    fs.writeFileSync(
      path.join(tmpDir, 'package.json'),
      `${JSON.stringify({
        name: '@acme/widgets',
        version: '1.0.0',
        files: ['astryx.integration.mjs', 'src'],
        exports: {'.': './src/index.ts'},
      })}\n`,
    );
    fs.writeFileSync(
      path.join(tmpDir, 'astryx.integration.mjs'),
      "export default {components: './src'};\n",
    );
    fs.mkdirSync(path.join(tmpDir, 'src'));
    fs.writeFileSync(
      path.join(tmpDir, 'src', 'index.ts'),
      "export type {AcmeWidget} from './AcmeWidget';\n",
    );
    fs.writeFileSync(
      path.join(tmpDir, 'src', 'AcmeWidget.tsx'),
      'export function AcmeWidget() { return null; }\n',
    );
    fs.writeFileSync(
      path.join(tmpDir, 'src', 'AcmeWidget.doc.mjs'),
      "export default {type: 'component', name: 'AcmeWidget', import: '@acme/widgets', description: 'Widget.', props: []};\n",
    );

    const result = await integrationPackCheck({cwd: tmpDir});

    expect(result.data.issues).toContainEqual(
      expect.objectContaining({code: 'component_export_missing'}),
    );
  });

  it('follows a re-export of a folder to its index file', async () => {
    // `./primitives` names a folder: TypeScript and bundlers load its index file.
    fs.writeFileSync(
      path.join(tmpDir, 'package.json'),
      `${JSON.stringify({
        name: '@acme/widgets',
        version: '1.0.0',
        files: ['astryx.integration.mjs', 'src'],
        exports: {'.': './src/index.ts'},
      })}\n`,
    );
    fs.writeFileSync(
      path.join(tmpDir, 'astryx.integration.mjs'),
      "export default {components: './src'};\n",
    );
    const primitives = path.join(tmpDir, 'src', 'primitives');
    fs.mkdirSync(primitives, {recursive: true});
    fs.writeFileSync(
      path.join(tmpDir, 'src', 'index.ts'),
      "export * from './primitives';\n",
    );
    fs.writeFileSync(
      path.join(primitives, 'index.ts'),
      "export * from './AcmeWidget';\n",
    );
    fs.writeFileSync(
      path.join(primitives, 'AcmeWidget.tsx'),
      'export function AcmeWidget() { return null; }\n',
    );
    fs.writeFileSync(
      path.join(primitives, 'AcmeWidget.doc.mjs'),
      "export default {type: 'component', name: 'AcmeWidget', import: '@acme/widgets', description: 'Widget.', props: []};\n",
    );

    const result = await integrationPackCheck({cwd: tmpDir});

    expect(result.data.issues).not.toContainEqual(
      expect.objectContaining({code: 'component_export_missing'}),
    );
    expect(
      result.data.packable,
      JSON.stringify(result.data.issues, null, 2),
    ).toBe(true);
  });

  it('fails when packed template source is hidden by package exports', async () => {
    writePackage({
      manifest: "export default {templates: './templates'};\n",
      files: ['astryx.integration.mjs', 'templates', 'index.mjs'],
      themes: false,
    });
    const pkgFile = path.join(tmpDir, 'package.json');
    const pkg = JSON.parse(fs.readFileSync(pkgFile, 'utf-8'));
    pkg.exports = {'.': './index.mjs'};
    fs.writeFileSync(pkgFile, `${JSON.stringify(pkg, null, 2)}\n`);
    fs.writeFileSync(
      path.join(tmpDir, 'index.mjs'),
      'export const existing = 1;\n',
    );
    fs.mkdirSync(path.join(tmpDir, 'templates'));
    fs.writeFileSync(
      path.join(tmpDir, 'templates', 'account-page.doc.mjs'),
      "export default {type: 'page', name: 'Account page', description: 'Account page.'};\n",
    );
    fs.writeFileSync(
      path.join(tmpDir, 'templates', 'account-page.tsx'),
      'export default function AccountPage() { return null; }\n',
    );

    const result = await integrationPackCheck({cwd: tmpDir});

    expect(result.data.packable).toBe(false);
    expect(result.data.issues).toContainEqual(
      expect.objectContaining({
        code: 'template_import_unresolvable',
        message: expect.stringContaining('account-page'),
      }),
    );
  });

  it('passes generated component and template source through exact packed exports', async () => {
    fs.writeFileSync(
      path.join(tmpDir, 'package.json'),
      `${JSON.stringify({
        name: '@acme/widgets',
        version: '1.0.0',
        files: ['index.mjs'],
        exports: {'.': './index.mjs'},
      })}\n`,
    );
    fs.writeFileSync(
      path.join(tmpDir, 'index.mjs'),
      'export const existing = 1;\n',
    );
    await integrationAddComponent('AcmeWidget', {cwd: tmpDir});
    await integrationAddTemplate('account-page', {cwd: tmpDir, type: 'page'});

    const result = await integrationPackCheck({cwd: tmpDir});

    expect(result.data.packable).toBe(true);
    expect(result.data.issues).not.toContainEqual(
      expect.objectContaining({code: 'component_export_missing'}),
    );
    expect(result.data.issues).not.toContainEqual(
      expect.objectContaining({code: 'template_import_unresolvable'}),
    );
  });

  it('errors when a root directory is excluded from files[]', async () => {
    // Include manifest but NOT themes
    writePackage({files: ['astryx.integration.mjs']});
    const result = await integrationPackCheck({cwd: tmpDir});

    expect(result.data.packable).toBe(false);
    const rootError = result.data.issues.find(
      i => i.code === 'root_not_packed',
    );
    expect(rootError).toBeDefined();
    expect(rootError.message).toContain('themes');
  });

  it('errors when .npmignore excludes a contribution', async () => {
    writePackage({npmignore: 'themes/\n'});
    const result = await integrationPackCheck({cwd: tmpDir});

    expect(result.data.packable).toBe(false);
    const fileErrors = result.data.issues.filter(
      i => i.code === 'root_not_packed' || i.code === 'file_not_packed',
    );
    expect(fileErrors.length).toBeGreaterThan(0);
  });

  it('fails a package that ships a namespace doc on a CLI range that cannot read it', async () => {
    writePackage({
      manifest: "export default {docs: './docs'};\n",
      themes: false,
    });
    fs.mkdirSync(path.join(tmpDir, 'docs'), {recursive: true});
    fs.writeFileSync(
      path.join(tmpDir, 'docs', 'acme.doc.mjs'),
      "export default {type: 'namespace', name: 'acme', title: 'Acme', summary: 'Acme guides.', slots: {guides: {title: 'Guides', accepts: {kinds: ['generic']}}}};\n",
    );
    fs.writeFileSync(
      path.join(tmpDir, 'docs', 'deploying.doc.mjs'),
      "export default {type: 'generic', name: 'deploying', title: 'Deploying', description: 'Ship it.', placement: {parent: 'namespace:acme', slot: 'guides'}, sections: [{title: 'Overview', content: [{type: 'prose', text: 'Ship it.'}]}]};\n",
    );
    const file = path.join(tmpDir, 'package.json');
    const peer = (/** @type {string | undefined} */ range) => {
      const pkg = JSON.parse(fs.readFileSync(file, 'utf-8'));
      if (range == null) delete pkg.peerDependencies;
      else pkg.peerDependencies = {'@astryxdesign/cli': range};
      fs.writeFileSync(file, `${JSON.stringify(pkg, null, 2)}\n`);
    };
    const codes = async () =>
      (await integrationPackCheck({cwd: tmpDir})).data.issues.map(
        (/** @type {{code: string}} */ issue) => issue.code,
      );

    peer(undefined);
    expect(await codes()).toContain('docs_tree_needs_cli');
    peer('^0.6.0 || >=0.7.0');
    expect(await codes()).toContain('docs_tree_needs_cli');
    peer('>=0.6.3');
    expect(await codes()).toContain('docs_tree_needs_cli');
    // Published 0.6.4 reads the docs tree.
    peer('>=0.6.4');
    expect(await codes()).not.toContain('docs_tree_needs_cli');
  }, 120_000);

  it('fails a package with only a placed guide on a CLI range that cannot read the docs tree, and passes flat topics', async () => {
    writePackage({
      manifest: "export default {docs: './docs'};\n",
      themes: false,
    });
    fs.mkdirSync(path.join(tmpDir, 'docs'), {recursive: true});
    fs.writeFileSync(
      path.join(tmpDir, 'docs', 'notes.doc.mjs'),
      "export default {type: 'generic', name: 'notes', title: 'Notes', description: 'Notes.', sections: [{title: 'Overview', content: [{type: 'prose', text: 'Notes.'}]}]};\n",
    );
    const codes = async () =>
      (await integrationPackCheck({cwd: tmpDir})).data.issues.map(
        (/** @type {{code: string}} */ issue) => issue.code,
      );
    // Flat topics alone need no CLI peer.
    expect(await codes()).not.toContain('docs_tree_needs_cli');
    fs.writeFileSync(
      path.join(tmpDir, 'docs', 'setup.doc.mjs'),
      "export default {type: 'generic', name: 'setup', title: 'Setup', description: 'Set up.', placement: {parent: 'namespace:acme', slot: 'guides'}, sections: [{title: 'Overview', content: [{type: 'prose', text: 'Set up.'}]}]};\n",
    );
    expect(await codes()).toContain('docs_tree_needs_cli');
    const file = path.join(tmpDir, 'package.json');
    const pkg = JSON.parse(fs.readFileSync(file, 'utf-8'));
    pkg.peerDependencies = {'@astryxdesign/cli': '>=0.7.0'};
    fs.writeFileSync(file, `${JSON.stringify(pkg, null, 2)}\n`);
    expect(await codes()).not.toContain('docs_tree_needs_cli');
  }, 120_000);

  it('fails a package whose doc section sets id on a CLI range that rejects the field', async () => {
    writePackage({
      manifest: "export default {docs: './docs'};\n",
      themes: false,
    });
    fs.mkdirSync(path.join(tmpDir, 'docs'), {recursive: true});
    const topic = (/** @type {string} */ section) =>
      `export default {type: 'generic', name: 'notes', title: 'Notes', description: 'Notes.', sections: [${section}]};\n`;
    const file = path.join(tmpDir, 'docs', 'notes.doc.mjs');
    const codes = async () =>
      (await integrationPackCheck({cwd: tmpDir})).data.issues.map(
        (/** @type {{code: string}} */ issue) => issue.code,
      );
    fs.writeFileSync(
      file,
      topic(
        "{title: 'Take notes', content: [{type: 'prose', text: 'Notes.'}]}",
      ),
    );
    expect(await codes()).not.toContain('section_ids_need_cli');
    // A fresh file name: the module loader caches a path once it is imported.
    fs.rmSync(file);
    fs.writeFileSync(
      path.join(tmpDir, 'docs', 'notes-with-ids.doc.mjs'),
      topic(
        "{id: 'take-notes', title: 'Take notes', content: [{type: 'prose', text: 'Notes.'}]}",
      ),
    );
    expect(await codes()).toContain('section_ids_need_cli');
    const pkgFile = path.join(tmpDir, 'package.json');
    const pkg = JSON.parse(fs.readFileSync(pkgFile, 'utf-8'));
    pkg.peerDependencies = {'@astryxdesign/cli': '^0.6.3'};
    fs.writeFileSync(pkgFile, `${JSON.stringify(pkg, null, 2)}\n`);
    expect(await codes()).toContain('section_ids_need_cli');
    // Published 0.6.4 reads a section id.
    pkg.peerDependencies = {'@astryxdesign/cli': '>=0.6.4'};
    fs.writeFileSync(pkgFile, `${JSON.stringify(pkg, null, 2)}\n`);
    expect(await codes()).not.toContain('section_ids_need_cli');
  }, 120_000);

  it('warns, without failing, when a doc section sets before or after on a CLI range that rejects them', async () => {
    writePackage({
      manifest: "export default {docs: './docs'};\n",
      themes: false,
    });
    fs.mkdirSync(path.join(tmpDir, 'docs'), {recursive: true});
    const pkgFile = path.join(tmpDir, 'package.json');
    const pkg = JSON.parse(fs.readFileSync(pkgFile, 'utf-8'));
    pkg.peerDependencies = {'@astryxdesign/cli': '>=0.7.0'};
    fs.writeFileSync(pkgFile, `${JSON.stringify(pkg, null, 2)}\n`);
    const issues = async () =>
      (await integrationPackCheck({cwd: tmpDir})).data.issues.filter(
        (/** @type {{code: string}} */ issue) =>
          issue.code === 'section_position_needs_cli',
      );
    // A placed guide's section counts too: an older CLI rejects the field in
    // any doc and hides the package's topics.
    fs.writeFileSync(
      path.join(tmpDir, 'docs', 'acme.doc.mjs'),
      "export default {type: 'namespace', name: 'acme', title: 'Acme', summary: 'Acme.', slots: {guides: {title: 'Guides', accepts: {kinds: ['generic']}}}};\n",
    );
    fs.writeFileSync(
      path.join(tmpDir, 'docs', 'setup.doc.mjs'),
      "export default {type: 'generic', name: 'setup', title: 'Setup', description: 'Set up.', placement: {parent: 'namespace:acme', slot: 'guides'}, sections: [{id: 'overview', title: 'Overview', after: 'nothing', content: [{type: 'prose', text: 'Set up.'}]}]};\n",
    );
    expect(await issues()).toEqual([
      expect.objectContaining({severity: 'warning'}),
    ]);
    pkg.peerDependencies = {'@astryxdesign/cli': '>=0.7.4'};
    fs.writeFileSync(pkgFile, `${JSON.stringify(pkg, null, 2)}\n`);
    expect(await issues()).toEqual([]);
  }, 120_000);

  it('warns when a package whose docs write doc tokens has a CLI range that prints them raw', async () => {
    writePackage({
      manifest: "export default {docs: './docs'};\n",
      themes: false,
    });
    fs.mkdirSync(path.join(tmpDir, 'docs'), {recursive: true});
    const write = (/** @type {string} */ name, /** @type {string} */ text) =>
      fs.writeFileSync(
        path.join(tmpDir, 'docs', `${name}.doc.mjs`),
        `export default {type: 'generic', name: '${name}', title: 'Notes', description: 'Notes.', sections: [{title: 'Run', content: [{type: 'prose', text: ${JSON.stringify(text)}}]}]};\n`,
      );
    const found = async () =>
      (await integrationPackCheck({cwd: tmpDir})).data.issues.filter(
        (/** @type {{code: string}} */ issue) => issue.code === 'doc_tokens_need_cli',
      );
    // An escaped token is shown as written by every release.
    write('escaped', 'Write {@@pm install x} for an install.');
    expect(await found()).toEqual([]);
    write('tokens', 'Run {@command doctor} first.');
    expect((await found()).map((/** @type {any} */ issue) => issue.severity)).toEqual(['warning']);
    const pkgFile = path.join(tmpDir, 'package.json');
    const pkg = JSON.parse(fs.readFileSync(pkgFile, 'utf-8'));
    pkg.peerDependencies = {'@astryxdesign/cli': '>=0.7.3'};
    fs.writeFileSync(pkgFile, `${JSON.stringify(pkg, null, 2)}\n`);
    expect(await found()).toHaveLength(1);
    pkg.peerDependencies = {'@astryxdesign/cli': '>=0.7.4'};
    fs.writeFileSync(pkgFile, `${JSON.stringify(pkg, null, 2)}\n`);
    expect(await found()).toEqual([]);
  }, 120_000);

  it('fails a package with a template that sets replaces on a CLI range that rejects the field', async () => {
    writePackage({
      manifest: "export default {templates: './templates'};\n",
      themes: false,
    });
    fs.mkdirSync(path.join(tmpDir, 'templates'), {recursive: true});
    fs.writeFileSync(
      path.join(tmpDir, 'templates', 'acme-shell.doc.mjs'),
      "export default {type: 'page', name: 'acme-shell', description: 'Acme shell.', replaces: 'shell-side-nav'};\n",
    );
    fs.writeFileSync(
      path.join(tmpDir, 'templates', 'acme-shell.tsx'),
      'export default function AcmeShell() { return null; }\n',
    );
    const file = path.join(tmpDir, 'package.json');
    const peer = (/** @type {string | undefined} */ range) => {
      const pkg = JSON.parse(fs.readFileSync(file, 'utf-8'));
      if (range == null) delete pkg.peerDependencies;
      else pkg.peerDependencies = {'@astryxdesign/cli': range};
      fs.writeFileSync(file, `${JSON.stringify(pkg, null, 2)}\n`);
    };
    const codes = async () =>
      (await integrationPackCheck({cwd: tmpDir})).data.issues.map(
        (/** @type {{code: string}} */ issue) => issue.code,
      );

    peer(undefined);
    expect(await codes()).toContain('replaces_needs_cli');
    peer('^0.6.0');
    expect(await codes()).toContain('replaces_needs_cli');
    // Published 0.6.3 rejects `replaces`; published 0.6.4 applies it.
    peer('>=0.6.3');
    expect(await codes()).toContain('replaces_needs_cli');
    peer('>=0.6.4');
    expect(await codes()).not.toContain('replaces_needs_cli');
    peer('>=0.7.0');
    expect(await codes()).not.toContain('replaces_needs_cli');
  }, 120_000);

  it('fails a package with a template that sets keywords on a CLI range that rejects the field', async () => {
    writePackage({
      manifest: "export default {templates: './templates'};\n",
      themes: false,
    });
    fs.mkdirSync(path.join(tmpDir, 'templates'), {recursive: true});
    fs.writeFileSync(
      path.join(tmpDir, 'templates', 'acme-health.doc.mjs'),
      "export default {type: 'page', name: 'acme-health', description: 'Status tiles.', keywords: ['uptime']};\n",
    );
    fs.writeFileSync(
      path.join(tmpDir, 'templates', 'acme-health.tsx'),
      'export default function AcmeHealth() { return null; }\n',
    );
    const file = path.join(tmpDir, 'package.json');
    const peer = (/** @type {string | undefined} */ range) => {
      const pkg = JSON.parse(fs.readFileSync(file, 'utf-8'));
      if (range == null) delete pkg.peerDependencies;
      else pkg.peerDependencies = {'@astryxdesign/cli': range};
      fs.writeFileSync(file, `${JSON.stringify(pkg, null, 2)}\n`);
    };
    const codes = async () =>
      (await integrationPackCheck({cwd: tmpDir})).data.issues.map(
        (/** @type {{code: string}} */ issue) => issue.code,
      );

    peer(undefined);
    expect(await codes()).toContain('keywords_needs_cli');
    peer('^0.6.0');
    expect(await codes()).toContain('keywords_needs_cli');
    // Published 0.6.4 and 0.6.5 drop a template that sets `keywords`;
    // published 0.6.6 reads it.
    peer('>=0.6.5');
    expect(await codes()).toContain('keywords_needs_cli');
    peer('>=0.6.6');
    expect(await codes()).not.toContain('keywords_needs_cli');
    peer('>=0.7.0');
    expect(await codes()).not.toContain('keywords_needs_cli');
  }, 120_000);

  it('passes when package.json has no files field', async () => {
    writePackage({files: undefined});
    const result = await integrationPackCheck({cwd: tmpDir});

    // No files field → npm includes everything
    expect(result.data.packable).toBe(true);
  });

  it('detects a lifecycle script that changes packed template replacements', async () => {
    const script = [
      "const fs=require('fs')",
      "const p='templates/acme-shell.template.mjs'",
      "const s=fs.readFileSync(p,'utf8')",
      "fs.writeFileSync(p,s.replace('shell-side-nav','shell-top-nav'))",
    ].join(';');
    writePackage({
      manifest: "export default {templates: './templates'};\n",
      files: ['astryx.integration.mjs', 'templates'],
      themes: false,
      scripts: {prepack: `node -e "${script}"`},
    });
    fs.mkdirSync(path.join(tmpDir, 'templates'));
    fs.writeFileSync(
      path.join(tmpDir, 'templates', 'acme-shell.template.mjs'),
      "export default {type: 'page', name: 'Acme shell', description: 'Fixture.', replaces: 'shell-side-nav'};\n",
    );
    fs.writeFileSync(
      path.join(tmpDir, 'templates', 'acme-shell.tsx'),
      'export default function AcmeShell() { return null; }\n',
    );

    const result = await integrationPackCheck({cwd: tmpDir});

    expect(result.data.packable).toBe(false);
    expect(result.data.issues).toContainEqual(
      expect.objectContaining({
        code: 'identity_mismatch',
        message: expect.stringContaining('acme-shell'),
      }),
    );
  });

  it('detects a lifecycle script that changes the packed identity', async () => {
    const script = [
      "const fs=require('fs')",
      "fs.renameSync('themes/ocean','themes/storm')",
      "const p='themes/storm/oceanTheme.doc.mjs'",
      "let x=fs.readFileSync(p,'utf8')",
      "x=x.replace(/name: 'ocean'/, 'name: '+String.fromCharCode(39)+'storm'+String.fromCharCode(39))",
      'fs.writeFileSync(p,x)',
    ].join(';');
    writePackage({
      files: ['astryx.integration.mjs', 'themes'],
      scripts: {prepack: `node -e "${script}"`},
    });

    const result = await integrationPackCheck({cwd: tmpDir});

    expect(result.data.packable).toBe(false);
    expect(
      result.data.issues.find(issue => issue.code === 'identity_not_packed')
        ?.message,
    ).toContain('ocean');
    expect(
      result.data.issues.find(
        issue => issue.code === 'packed_identity_unexpected',
      )?.message,
    ).toContain('storm');
  });

  it('rejects a declared root with no contribution files', async () => {
    writePackage({
      manifest: "export default {docs: './docs'};\n",
      files: ['astryx.integration.mjs', 'docs'],
      themes: false,
    });
    fs.mkdirSync(path.join(tmpDir, 'docs'));

    const result = await integrationPackCheck({cwd: tmpDir});

    expect(result.data.packable).toBe(false);
    expect(
      result.data.issues.some(
        issue => issue.code === 'empty_contribution_root',
      ),
    ).toBe(true);
  });

  it('handles scoped package extraction correctly', async () => {
    writePackage({
      name: '@my-org/deep-integration',
      files: ['astryx.integration.mjs', 'themes'],
    });
    const result = await integrationPackCheck({cwd: tmpDir});

    expect(result.data.name).toBe('@my-org/deep-integration');
    expect(result.data.packable).toBe(true);
  });

  it('reports source-only component candidates as warnings', async () => {
    writePackage({
      manifest:
        "export default {themes: './themes', components: './components'};\n",
      files: ['astryx.integration.mjs', 'themes', 'components'],
      components: true,
    });
    const result = await integrationPackCheck({cwd: tmpDir});

    const sourceWarnings = result.data.issues.filter(
      issue => issue.code === 'source_without_component_doc',
    );
    // Card.tsx is PascalCase but has no doc metadata → warning
    expect(sourceWarnings.length).toBeGreaterThanOrEqual(1);
    expect(sourceWarnings[0].severity).toBe('warning');
    expect(sourceWarnings[0].message).toContain('Card.tsx');
  });

  it('reports template sources without metadata as warnings', async () => {
    writePackage({
      manifest:
        "export default {themes: './themes', templates: './templates'};\n",
      files: ['astryx.integration.mjs', 'themes', 'templates'],
      templates: true,
    });
    const result = await integrationPackCheck({cwd: tmpDir});

    const sourceWarnings = result.data.issues.filter(
      issue => issue.code === 'source_without_template_doc',
    );
    expect(sourceWarnings).toHaveLength(1);
    expect(sourceWarnings[0].severity).toBe('warning');
    expect(sourceWarnings[0].message).toContain('stray.tsx');
  });

  it('says npm pack skips a symlinked root instead of asking for a "files" entry', async () => {
    writePackage({
      manifest:
        "export default {themes: './themes', components: './components'};\n",
    });
    const real = path.join(tmpDir, 'real-components');
    fs.mkdirSync(real, {recursive: true});
    fs.writeFileSync(
      path.join(real, 'Card.doc.mjs'),
      "export default {type: 'component', name: 'Card', displayName: 'Card', usage: {description: 'Card.'}, props: []};\n",
    );
    fs.writeFileSync(
      path.join(real, 'Card.tsx'),
      'export function Card() { return null; }\n',
    );
    fs.symlinkSync('real-components', path.join(tmpDir, 'components'));

    const result = await integrationPackCheck({cwd: tmpDir});
    const codes = result.data.issues.map(issue => issue.code);
    expect(codes).toContain('symlinked_root');
    const notPacked = result.data.issues.find(
      issue => issue.code === 'root_not_packed',
    );
    expect(notPacked?.message).toBe(
      'Declared components root "components" has 0 of 2 expected files in the pack list. It is reached through the symlink "components", and npm pack does not follow a symlinked folder. Fix: replace the link with the folder itself, or point "components" at the folder it links to.',
    );
  });

  it('names packed files by their path in the package, never the scratch copy', async () => {
    writePackage({
      manifest:
        "export default {themes: './themes', docs: './docs/a.doc.mjs'};\n",
    });
    fs.mkdirSync(path.join(tmpDir, 'docs'), {recursive: true});
    fs.writeFileSync(path.join(tmpDir, 'docs', 'a.doc.mjs'), '');

    const result = await integrationPackCheck({cwd: tmpDir});
    const messages = result.data.issues.map(issue => issue.message);
    expect(messages.join('\n')).not.toContain(
      path.join(tmpDir, '.astryx-pack-check-'),
    );
    expect(messages).toContain(
      'Packed: Declared docs root is a file, not a folder: docs/a.doc.mjs. Fix: point "docs" in the manifest at the folder that holds them.',
    );
    // The root's own issue covers it: no empty-root error, no raw errno.
    const codes = result.data.issues.map(issue => issue.code);
    expect(codes).not.toContain('empty_contribution_root');
    expect(codes).not.toContain('local_discovery_failed');
    expect(codes).not.toContain('packed_discovery_failed');
  });

  it('fails on a package.json npm cannot pack, which validate only warns about', async () => {
    writePackage({files: ['astryx.integration.mjs', 'themes']});
    const packageFile = path.join(tmpDir, 'package.json');
    const pkg = JSON.parse(fs.readFileSync(packageFile, 'utf-8'));
    delete pkg.name;
    fs.writeFileSync(packageFile, `${JSON.stringify(pkg, null, 2)}\n`);

    const result = await integrationPackCheck({cwd: tmpDir});

    expect(result.data.packable).toBe(false);
    expect(
      result.data.issues.map(issue => [issue.code, issue.severity]),
    ).toEqual([
      ['invalid_package_json', 'error'],
      ['pack_failed', 'error'],
    ]);
  });

  it('cleans up its scratch consumer when npm pack fails', async () => {
    writePackage({
      files: ['astryx.integration.mjs', 'themes'],
      scripts: {prepack: 'node -e "process.exit(17)"'},
    });

    const result = await integrationPackCheck({cwd: tmpDir});

    expect(result.data.packable).toBe(false);
    expect(result.data.issues.some(issue => issue.code === 'pack_failed')).toBe(
      true,
    );
    expect(
      fs
        .readdirSync(tmpDir)
        .filter(name => name.startsWith('.astryx-pack-check-')),
    ).toEqual([]);
  });

  it('cleans up its scratch consumer after a successful check', async () => {
    writePackage({files: ['astryx.integration.mjs', 'themes']});

    const result = await integrationPackCheck({cwd: tmpDir});

    expect(result.data.packable).toBe(true);
    expect(
      fs
        .readdirSync(tmpDir)
        .filter(name => name.startsWith('.astryx-pack-check-')),
    ).toEqual([]);
  });

  it("reads npm 8's scoped tarball name as the file npm writes", () => {
    const entry = {entryCount: 1, size: 1, unpackedSize: 1, files: []};
    expect(
      parseNpmPackOutput(
        JSON.stringify([{...entry, filename: '@acme/kit-1.0.0.tgz'}]),
      ).filename,
    ).toBe('acme-kit-1.0.0.tgz');
    expect(
      parseNpmPackOutput(
        JSON.stringify([{...entry, filename: 'acme-kit-1.0.0.tgz'}]),
      ).filename,
    ).toBe('acme-kit-1.0.0.tgz');
  });

  it('rejects malformed npm pack output without a raw TypeError', () => {
    expect(() =>
      parseNpmPackOutput(
        JSON.stringify([
          {filename: 'pkg.tgz', entryCount: 1, size: 1, unpackedSize: 1},
        ]),
      ),
    ).toThrow(/without a files array/);
  });

  it('reports pack_failed when no npm can be found', async () => {
    writePackage({files: ['astryx.integration.mjs', 'themes']});
    const originalPath = process.env.PATH;
    const originalExecPath = process.execPath;
    process.env.PATH = '';
    // A Node with no npm beside it, and no npm on the PATH.
    process.execPath = path.join(tmpDir, 'no-npm', 'bin', 'node');
    try {
      const result = await integrationPackCheck({cwd: tmpDir});
      expect(result.data.packable).toBe(false);
      expect(result.data.issues).toContainEqual(
        expect.objectContaining({
          code: 'pack_failed',
          message: expect.stringContaining('Could not start npm pack'),
        }),
      );
    } finally {
      process.env.PATH = originalPath;
      process.execPath = originalExecPath;
    }
  });

  it('does not execute shell metacharacters embedded in the cwd', async () => {
    const marker = path.join(process.cwd(), 'astryx-pack-check-injected');
    fs.rmSync(marker, {force: true});
    const weirdDir = fs.mkdtempSync(
      path.join(REPO_ROOT, '.astryx-;touch astryx-pack-check-injected;#-'),
    );
    try {
      const pkg = {name: 'safe-pkg', version: '1.0.0'};
      fs.writeFileSync(
        path.join(weirdDir, 'package.json'),
        JSON.stringify(pkg),
      );
      fs.writeFileSync(
        path.join(weirdDir, 'astryx.integration.mjs'),
        'export default {};\n',
      );
      const result = await integrationPackCheck({cwd: weirdDir});
      expect(result.type).toBe('integration.pack-check');
      expect(fs.existsSync(marker)).toBe(false);
    } finally {
      fs.rmSync(weirdDir, {recursive: true, force: true});
      fs.rmSync(marker, {force: true});
    }
  });

  it('returns early with issues for a directory without package.json', async () => {
    const emptyDir = fs.mkdtempSync(
      path.join(os.tmpdir(), 'astryx-pack-check-empty-'),
    );
    try {
      const result = await integrationPackCheck({cwd: emptyDir});
      expect(result.data.packable).toBe(false);
      expect(result.data.issues.some(i => i.code === 'no_package')).toBe(true);
    } finally {
      fs.rmSync(emptyDir, {recursive: true, force: true});
    }
  });

  it('reports malformed package.json instead of treating it as missing', async () => {
    fs.writeFileSync(path.join(tmpDir, 'package.json'), '{bad-json');
    fs.writeFileSync(
      path.join(tmpDir, 'astryx.integration.mjs'),
      'export default {};\n',
    );

    const result = await integrationPackCheck({cwd: tmpDir});

    expect(result.data.packable).toBe(false);
    expect(result.data.issues).toContainEqual(
      expect.objectContaining({code: 'invalid_package_json'}),
    );
  });

  it('returns early with issues for a package without a manifest', async () => {
    fs.writeFileSync(
      path.join(tmpDir, 'package.json'),
      '{"name":"bare-pkg","version":"1.0.0"}\n',
    );
    const result = await integrationPackCheck({cwd: tmpDir});

    expect(result.data.packable).toBe(false);
    expect(result.data.issues.some(i => i.code === 'missing_manifest')).toBe(
      true,
    );
  });
});

describe('pack-check mutation tests', () => {
  it('detects when a theme source is deleted after initial authoring', async () => {
    writePackage({files: ['astryx.integration.mjs', 'themes']});
    fs.rmSync(path.join(tmpDir, 'themes', 'ocean', 'oceanTheme.ts'));

    const result = await integrationPackCheck({cwd: tmpDir});
    expect(result.data.packable).toBe(false);
    expect(result.data.issues).toContainEqual(
      expect.objectContaining({code: 'invalid_theme'}),
    );
  });

  it('detects when files[] is narrowed after add removes themes', async () => {
    // First: valid package
    writePackage({files: ['astryx.integration.mjs', 'themes']});

    // Narrow files to exclude themes
    const pkg = JSON.parse(
      fs.readFileSync(path.join(tmpDir, 'package.json'), 'utf-8'),
    );
    pkg.files = ['astryx.integration.mjs'];
    fs.writeFileSync(
      path.join(tmpDir, 'package.json'),
      JSON.stringify(pkg, null, 2) + '\n',
    );

    const result = await integrationPackCheck({cwd: tmpDir});
    expect(result.data.packable).toBe(false);
    expect(result.data.issues.some(i => i.code === 'root_not_packed')).toBe(
      true,
    );
  });

  it('correctly counts packed vs expected files in inventory', async () => {
    writePackage({files: ['astryx.integration.mjs', 'themes']});
    const result = await integrationPackCheck({cwd: tmpDir});

    expect(result.data.inventory.expectedFiles).toBeGreaterThan(0);
    expect(result.data.inventory.packedFiles).toBe(
      result.data.inventory.expectedFiles,
    );
    for (const root of result.data.inventory.roots) {
      expect(root.complete).toBe(true);
      expect(root.missingFiles).toEqual([]);
    }
  });
});

describe('extensionless subpath resolution', () => {
  it('rejects .tsx public specifiers before publishing', async () => {
    // Manually construct a package with OLD-style .tsx exports keys
    writePackage({
      manifest: "export default {components: './components'};\n",
      files: ['astryx.integration.mjs', 'components', 'index.mjs'],
      themes: false,
    });
    const pkgFile = path.join(tmpDir, 'package.json');
    const pkg = JSON.parse(fs.readFileSync(pkgFile, 'utf-8'));
    pkg.exports = {
      '.': './index.mjs',
      './components/AcmeWidget.tsx': './components/AcmeWidget.tsx',
    };
    fs.writeFileSync(pkgFile, `${JSON.stringify(pkg, null, 2)}\n`);
    fs.writeFileSync(
      path.join(tmpDir, 'index.mjs'),
      'export const existing = 1;\n',
    );
    fs.mkdirSync(path.join(tmpDir, 'components'));
    fs.writeFileSync(
      path.join(tmpDir, 'components', 'AcmeWidget.doc.mjs'),
      `export default {type: 'component', name: 'AcmeWidget', import: '@acme/widgets/components/AcmeWidget.tsx', description: 'Widget.', props: []};\n`,
    );
    fs.writeFileSync(
      path.join(tmpDir, 'components', 'AcmeWidget.tsx'),
      'export function AcmeWidget() { return null; }\n',
    );

    const result = await integrationPackCheck({cwd: tmpDir});

    // The .tsx extension in the specifier must be caught
    expect(result.data.packable).toBe(false);
    expect(result.data.issues).toContainEqual(
      expect.objectContaining({
        code: 'typescript_extension_in_specifier',
        message: expect.stringContaining('.tsx'),
      }),
    );
  });

  it('generated extensionless component specifier resolves through exports map', async () => {
    fs.writeFileSync(
      path.join(tmpDir, 'package.json'),
      `${JSON.stringify({
        name: '@acme/widgets',
        version: '1.0.0',
        files: ['index.mjs'],
        exports: {'.': './index.mjs'},
      })}\n`,
    );
    fs.writeFileSync(
      path.join(tmpDir, 'index.mjs'),
      'export const existing = 1;\n',
    );
    await integrationAddComponent('AcmeWidget', {cwd: tmpDir});

    // Verify the exports map has extensionless key → .tsx target
    const pkg = JSON.parse(
      fs.readFileSync(path.join(tmpDir, 'package.json'), 'utf-8'),
    );
    expect(pkg.exports['./components/AcmeWidget']).toBe(
      './components/AcmeWidget.tsx',
    );
    expect(pkg.exports['./components/AcmeWidget.tsx']).toBeUndefined();

    const result = await integrationPackCheck({cwd: tmpDir});

    expect(result.data.packable).toBe(true);
    expect(result.data.issues).not.toContainEqual(
      expect.objectContaining({code: 'typescript_extension_in_specifier'}),
    );
    expect(result.data.issues).not.toContainEqual(
      expect.objectContaining({code: 'component_import_unresolvable'}),
    );
  });

  it('validates generated imports without project-local TypeScript', async () => {
    fs.rmSync(tmpDir, {recursive: true, force: true});
    tmpDir = fs.mkdtempSync(
      path.join(os.tmpdir(), 'astryx-pack-check-no-typescript-'),
    );
    fs.writeFileSync(
      path.join(tmpDir, 'package.json'),
      `${JSON.stringify({
        name: '@acme/widgets',
        version: '1.0.0',
        files: ['index.mjs'],
        exports: {'.': './index.mjs'},
      })}\n`,
    );
    fs.writeFileSync(
      path.join(tmpDir, 'index.mjs'),
      'export const existing = 1;\n',
    );
    await integrationAddComponent('AcmeWidget', {cwd: tmpDir});

    const result = await integrationPackCheck({cwd: tmpDir});

    expect(result.data.packable).toBe(true);
    expect(result.data.issues).not.toContainEqual(
      expect.objectContaining({code: 'component_import_unresolvable'}),
    );
  });

  it('generated extensionless template specifiers resolve for page and block types', async () => {
    fs.writeFileSync(
      path.join(tmpDir, 'package.json'),
      `${JSON.stringify({
        name: '@acme/widgets',
        version: '1.0.0',
        files: ['index.mjs'],
        exports: {'.': './index.mjs'},
      })}\n`,
    );
    fs.writeFileSync(
      path.join(tmpDir, 'index.mjs'),
      'export const existing = 1;\n',
    );
    await integrationAddTemplate('account-page', {cwd: tmpDir, type: 'page'});
    await integrationAddTemplate('info-card', {cwd: tmpDir, type: 'block'});

    const pkg = JSON.parse(
      fs.readFileSync(path.join(tmpDir, 'package.json'), 'utf-8'),
    );
    expect(pkg.exports['./templates/account-page']).toBe(
      './templates/account-page.tsx',
    );
    expect(pkg.exports['./templates/info-card']).toBe(
      './templates/info-card.tsx',
    );

    const result = await integrationPackCheck({cwd: tmpDir});

    expect(result.data.packable).toBe(true);
    expect(result.data.issues).not.toContainEqual(
      expect.objectContaining({code: 'template_import_unresolvable'}),
    );
    expect(result.data.issues).not.toContainEqual(
      expect.objectContaining({code: 'typescript_extension_in_specifier'}),
    );
  });

  it('preserves condition-style exports sugar without creating a map', async () => {
    // Package with condition-only exports (sugar, no subpaths)
    fs.writeFileSync(
      path.join(tmpDir, 'package.json'),
      `${JSON.stringify({
        name: '@acme/widgets',
        version: '1.0.0',
        files: ['index.mjs'],
        exports: {import: './index.mjs', require: './index.cjs'},
      })}\n`,
    );
    fs.writeFileSync(
      path.join(tmpDir, 'index.mjs'),
      'export const existing = 1;\n',
    );
    fs.writeFileSync(path.join(tmpDir, 'index.cjs'), 'exports.existing = 1;\n');
    fs.writeFileSync(
      path.join(tmpDir, 'astryx.integration.mjs'),
      'export default {};\n',
    );

    await integrationAddComponent('AcmeWidget', {cwd: tmpDir});

    const pkg = JSON.parse(
      fs.readFileSync(path.join(tmpDir, 'package.json'), 'utf-8'),
    );
    // Condition sugar wrapped into subpath map with the component added
    expect(pkg.exports['.']).toEqual({
      import: './index.mjs',
      require: './index.cjs',
    });
    expect(pkg.exports['./components/AcmeWidget']).toBe(
      './components/AcmeWidget.tsx',
    );
  });

  it('no-map: pack-check fails when generated component has no exports map', async () => {
    fs.writeFileSync(
      path.join(tmpDir, 'package.json'),
      `${JSON.stringify({
        name: '@acme/widgets',
        version: '1.0.0',
        files: ['dist'],
      })}\n`,
    );
    fs.writeFileSync(
      path.join(tmpDir, 'astryx.integration.mjs'),
      'export default {};\n',
    );

    await integrationAddComponent('AcmeWidget', {cwd: tmpDir});
    await integrationAddTemplate('hero-page', {cwd: tmpDir, type: 'page'});

    const pkg = JSON.parse(
      fs.readFileSync(path.join(tmpDir, 'package.json'), 'utf-8'),
    );
    // No exports map created
    expect(pkg.exports).toBeUndefined();

    const result = await integrationPackCheck({cwd: tmpDir});

    // The extensionless import cannot resolve without an exports map —
    // pack-check must fail closed, not false-green.
    expect(result.data.packable).toBe(false);
    expect(result.data.issues).toContainEqual(
      expect.objectContaining({
        severity: 'error',
        message: expect.stringContaining('AcmeWidget'),
      }),
    );
  });

  it('idempotent when extensionless export already exists', async () => {
    fs.writeFileSync(
      path.join(tmpDir, 'package.json'),
      `${JSON.stringify({
        name: '@acme/widgets',
        version: '1.0.0',
        files: ['index.mjs'],
        exports: {
          '.': './index.mjs',
          './components/AcmeWidget': './components/AcmeWidget.tsx',
        },
      })}\n`,
    );
    fs.writeFileSync(
      path.join(tmpDir, 'index.mjs'),
      'export const existing = 1;\n',
    );
    fs.writeFileSync(
      path.join(tmpDir, 'astryx.integration.mjs'),
      'export default {};\n',
    );

    await integrationAddComponent('AcmeWidget', {cwd: tmpDir});

    const pkg = JSON.parse(
      fs.readFileSync(path.join(tmpDir, 'package.json'), 'utf-8'),
    );
    // Export preserved, no duplicate
    expect(
      Object.keys(pkg.exports).filter(k => k.includes('AcmeWidget')),
    ).toEqual(['./components/AcmeWidget']);
  });
});