All files / src/cli/infrastructure PackageJsonFinder.ts

92.59% Statements 25/27
81.81% Branches 9/11
100% Functions 2/2
92.59% Lines 25/27

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 331x   1x 1x 7x 7x 6x 6x   7x 1x 1x   4x 7x 3x 1x 1x   2x 3x 3x 3x 7x   1x 3x     3x 3x 1x  
import { promises as fs } from 'node:fs';
 
export class PackageJsonFinder {
  async readPackageJsonVersion(packageJsonPath: string): Promise<string> {
    try {
      await fs.access(packageJsonPath);
      const content = await fs.readFile(packageJsonPath, 'utf8');
      const pkg: { version?: unknown } = JSON.parse(content);
 
      if (typeof pkg.version !== 'string') {
        throw new Error('Version field not found in package.json');
      }
 
      return pkg.version;
    } catch (err) {
      if (this.isEnoentError(err)) {
        throw new Error('package.json not found');
      }
 
      throw new Error(
        `Failed to read or parse package.json: ${err instanceof Error ? err.message : String(err)}`,
      );
    }
  }
 
  private isEnoentError(err: unknown): boolean {
    if (!(err instanceof Error)) {
      return false;
    }
    return 'code' in err && (err as { code?: string }).code === 'ENOENT';
  }
}