UNPKG

@travetto/compiler

Version:

The compiler infrastructure for the Travetto framework

70 lines (62 loc) 2.27 kB
import ts from 'typescript'; import { ManifestModuleFileType, ManifestModuleUtil, ManifestRoot, Package } from '@travetto/manifest'; const nativeCwd = process.cwd(); /** * Standard utilities for compiler */ export class CompilerUtil { /** * Determine if this is a manifest file we care about */ static validFile = (type: ManifestModuleFileType): boolean => type === 'ts' || type === 'package-json' || type === 'js' || type === 'typings'; /** * Rewrites the package.json to target output file names, and pins versions * @param manifest * @param file * @param text * @returns */ static rewritePackageJSON(manifest: ManifestRoot, text: string): string { const pkg: Package = JSON.parse(text); if (pkg.files) { pkg.files = pkg.files.map(x => ManifestModuleUtil.withOutputExtension(x)); } if (pkg.main) { pkg.main = ManifestModuleUtil.withOutputExtension(pkg.main); } pkg.type = manifest.workspace.type; for (const key of ['devDependencies', 'dependencies', 'peerDependencies'] as const) { if (key in pkg) { for (const dep of Object.keys(pkg[key] ?? {})) { if (dep in manifest.modules) { pkg[key]![dep] = manifest.modules[dep].version; } } } } return JSON.stringify(pkg, null, 2); } /** * Build transpilation error * @param filename The name of the file * @param diagnostics The diagnostic errors */ static buildTranspileError(filename: string, diagnostics: Error | readonly ts.Diagnostic[]): Error { if (diagnostics instanceof Error) { return diagnostics; } const errors: string[] = diagnostics.slice(0, 5).map(diag => { const message = ts.flattenDiagnosticMessageText(diag.messageText, '\n'); if (diag.file) { const { line, character } = diag.file.getLineAndCharacterOfPosition(diag.start!); return ` @ ${diag.file.fileName.replace(nativeCwd, '.')}(${line + 1}, ${character + 1}): ${message}`; } else { return ` ${message}`; } }); if (diagnostics.length > 5) { errors.push(`${diagnostics.length - 5} more ...`); } return new Error(`Transpiling ${filename.replace(nativeCwd, '.')} failed: \n${errors.join('\n')}`); } }