()
| 6 | * Reliably gets the package.json contents even when the package is published |
| 7 | */ |
| 8 | export function getVersion(): string { |
| 9 | try { |
| 10 | // Start from the current file's directory |
| 11 | let currentDir = dirname(fileURLToPath(import.meta.url)); |
| 12 | let packagePath = ''; |
| 13 | while (true) { |
| 14 | packagePath = resolve(currentDir, 'package.json'); |
| 15 | |
| 16 | if (fs.existsSync(packagePath)) { |
| 17 | break; |
| 18 | } |
| 19 | |
| 20 | // Move up to parent directory |
| 21 | const parentDir = resolve(currentDir, '..'); |
| 22 | |
| 23 | // Stop if we've reached the root |
| 24 | if (parentDir === currentDir) { |
| 25 | throw new Error('Could not find package.json in any parent directory'); |
| 26 | } |
| 27 | |
| 28 | currentDir = parentDir; |
| 29 | } |
| 30 | |
| 31 | const packageJSON = JSON.parse(readFileSync(packagePath, 'utf8')); |
| 32 | return packageJSON.version; |
| 33 | } catch (error) { |
| 34 | console.error('Failed to read package.json:', error instanceof Error ? error.message : error); |
| 35 | return 'unknown'; |
| 36 | } |
| 37 | } |
no test coverage detected