#!/usr/bin/env node
/**
 * check-pack-hygiene.js — guard the npm tarball contents.
 *
 * Runs `npm pack --dry-run --json` and fails if the would-be tarball contains
 * any runtime/local/test path that must never be published. `.openlife/method/**`
 * is allowed (intentionally bundled). Uses execFileSync (no shell).
 *
 * Usage: node scripts/check-pack-hygiene.js
 * Success line: PACK_HYGIENE_OK <fileCount> <unpackedSize>
 */
'use strict';

const { execFileSync } = require('child_process');

// Predicates for forbidden tarball entries.
const FORBIDDEN = [
  (p) => p.startsWith('.artifacts/'),
  (p) => p.startsWith('.sessions/'),
  (p) => p.startsWith('.temp_audio/'),
  (p) => p.startsWith('.temp_images/'),
  (p) => p.startsWith('.audit-runs/'),
  (p) => p === 'connections.json',
  (p) => p === '.openlife/benchmark-run.json',
  (p) => p === '.openlife/world-bootstrap.json',
  (p) => p.startsWith('.openlife/promoted-assets/'),
  (p) => /^src\/test_.*\.ts$/.test(p),
];

const npmBin = process.platform === 'win32' ? 'npm.cmd' : 'npm';
const raw = execFileSync(npmBin, ['pack', '--dry-run', '--json'], {
  encoding: 'utf8',
  maxBuffer: 64 * 1024 * 1024,
});

let report;
try {
  report = JSON.parse(raw);
} catch (err) {
  console.error('PACK_HYGIENE_FAIL — could not parse npm pack JSON:', err.message);
  process.exitCode = 1;
  return;
}

const pack = Array.isArray(report) ? report[0] : report;
const files = (pack && pack.files ? pack.files : []).map((f) => f.path);

const bad = files.filter((p) => FORBIDDEN.some((pred) => pred(p)));

if (bad.length) {
  console.error('PACK_HYGIENE_FAIL — forbidden files in tarball:');
  for (const p of bad) console.error(`  ${p}`);
  process.exitCode = 1;
} else {
  console.log(`PACK_HYGIENE_OK ${files.length} ${pack ? pack.unpackedSize : 'unknown'}`);
}
