|
| 1 | +import child_process from 'node:child_process' |
| 2 | +import { mkdtemp, readFile } from 'node:fs/promises' |
| 3 | +import { tmpdir } from 'node:os' |
| 4 | +import path from 'node:path' |
| 5 | +import process from 'node:process' |
| 6 | +import { promisify } from 'node:util' |
| 7 | +import { blue, dim } from 'ansis' |
| 8 | +import Debug from 'debug' |
| 9 | +import { fsRemove } from '../utils/fs' |
| 10 | +import { logger } from '../utils/logger' |
| 11 | +import type { ResolvedOptions } from '../options' |
| 12 | + |
| 13 | +const debug = Debug('tsdown:attw') |
| 14 | +const exec = promisify(child_process.exec) |
| 15 | + |
| 16 | +export async function attw(options: ResolvedOptions): Promise<void> { |
| 17 | + if (!options.attw) return |
| 18 | + if (!options.pkg) { |
| 19 | + logger.warn('attw is enabled but package.json is not found') |
| 20 | + return |
| 21 | + } |
| 22 | + |
| 23 | + const t = performance.now() |
| 24 | + debug('Running attw check') |
| 25 | + |
| 26 | + const tempDir = await mkdtemp(path.join(tmpdir(), 'tsdown-attw-')) |
| 27 | + |
| 28 | + let attwCore: typeof import('@arethetypeswrong/core') |
| 29 | + try { |
| 30 | + attwCore = await import('@arethetypeswrong/core') |
| 31 | + } catch { |
| 32 | + logger.error( |
| 33 | + `ATTW check requires ${blue`@arethetypeswrong/core`} to be installed.`, |
| 34 | + ) |
| 35 | + return |
| 36 | + } |
| 37 | + |
| 38 | + try { |
| 39 | + const { stdout: tarballInfo } = await exec( |
| 40 | + `npm pack --json ----pack-destination ${tempDir}`, |
| 41 | + { encoding: 'utf-8' }, |
| 42 | + ) |
| 43 | + const parsed = JSON.parse(tarballInfo) |
| 44 | + if (!Array.isArray(parsed) || !parsed[0]?.filename) { |
| 45 | + throw new Error('Invalid npm pack output format') |
| 46 | + } |
| 47 | + const tarballPath = path.join(tempDir, parsed[0].filename as string) |
| 48 | + const tarball = await readFile(tarballPath) |
| 49 | + |
| 50 | + const pkg = attwCore.createPackageFromTarballData(tarball) |
| 51 | + const checkResult = await attwCore.checkPackage( |
| 52 | + pkg, |
| 53 | + options.attw === true ? {} : options.attw, |
| 54 | + ) |
| 55 | + |
| 56 | + if (checkResult.types !== false && checkResult.problems) { |
| 57 | + for (const problem of checkResult.problems) { |
| 58 | + logger.warn('Are the types wrong problem:', problem) |
| 59 | + } |
| 60 | + } else { |
| 61 | + logger.success( |
| 62 | + `No Are the types wrong problems found`, |
| 63 | + dim`(${Math.round(performance.now() - t)}ms)`, |
| 64 | + ) |
| 65 | + } |
| 66 | + } catch (error) { |
| 67 | + logger.error('ATTW check failed:', error) |
| 68 | + debug('Found errors, setting exit code to 1') |
| 69 | + process.exitCode = 1 |
| 70 | + } finally { |
| 71 | + await fsRemove(tempDir) |
| 72 | + } |
| 73 | +} |
0 commit comments