Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
const compileTypescript = ({
source,
entries,
}: {|
source: string,
entries: Array,
|}) => {
const options = getCompilerOptions(source);
const host = ts.createCompilerHost(options);
host.resolveModuleNames = resolveModuleNames(options);
const program = ts.createProgram(
getTypescriptFiles(source, entries),
getCompilerOptions(source),
host,
);
const emitResult = program.emit();
const allDiagnostics = ts.getPreEmitDiagnostics(program).concat(emitResult.diagnostics);
allDiagnostics.forEach(diagnostic => {
if (diagnostic.file) {
const { line, character } = diagnostic.file.getLineAndCharacterOfPosition(diagnostic.start);
const message = ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n');
// eslint-disable-next-line
console.log(`${diagnostic.file.fileName} (${line + 1},${character + 1}): ${message}`);
}
else {
let options = {
outDir: compilerOptions.outDir,
module: ts.ModuleKind[compilerOptions.module.toUpperCase()],
target: ts.ScriptTarget[compilerOptions.target.toUpperCase()],
sourceMap: compilerOptions.sourceMap
};
// let options = {
// outDir: compilerOptions.outDir,
// module: ts.ModuleKind.ES2015,
// target: ts.ScriptTarget.ES2017,
// sourceMap: compilerOptions.sourceMap
// };
console.log('options: ', options);
const tsfiles = fs.readdirSync('ts').map(f => `ts/${f}`);
console.log('tsfiles: ', tsfiles);
const program = ts.createProgram(tsfiles, options);
const emitResult = program.emit();
/*
const allDiagnostics = ts
.getPreEmitDiagnostics(program)
.concat(emitResult.diagnostics);
allDiagnostics.forEach(diagnostic => {
if (diagnostic.file) {
let {line, character} = diagnostic.file.getLineAndCharacterOfPosition(
diagnostic.start
);
let message = ts.flattenDiagnosticMessageText(
diagnostic.messageText,
"\n"
);
export function functionTypesToSchemaConverter(
functionPath: string,
options: ts.CompilerOptions = { target: ts.ScriptTarget.ES5, module: ts.ModuleKind.CommonJS }
): TOutput {
const program = ts.createProgram([functionPath], options)
const sourceFile = program.getSourceFile(functionPath)
const checker = program.getTypeChecker()
const output: TOutput = {
requestBody: {},
response: {}
}
if (sourceFile) {
ts.forEachChild(sourceFile, visit)
}
return output
function visit(node: ts.Node) {
// Only consider exported nodes
// This error message talks specifically about having a single .ts file in "files". However
// the actual logic is a bit more permissive. If a single file exists, that will be taken,
// otherwise the highest level (shortest path) "index.ts" file will be used as the flat
// module entry point instead. If neither of these conditions apply, the error below is
// given.
//
// The user is not informed about the "index.ts" option as this behavior is deprecated -
// an explicit entrypoint should always be specified.
throw new Error('Angular compiler option "flatModuleIndex" requires one and only one .ts file in the "files" field.');
}
}
if (generators.length > 0) {
this.host = new shims_1.GeneratedShimsHostWrapper(host, generators);
}
this.tsProgram =
ts.createProgram(rootFiles, options, this.host, oldProgram && oldProgram.getTsProgram());
}
NgtscProgram.prototype.getTsProgram = function () { return this.tsProgram; };
export default function build({
fileName,
destDir,
transpileModule,
verbose = false,
importHelpers = true,
}: {
fileName: string;
destDir: string;
transpileModule: boolean;
verbose?: boolean;
importHelpers?: boolean;
}) {
const MantaStyleTranformer = createTransformer(importHelpers, destDir);
const program = ts.createProgram([fileName], {
strict: true,
noEmitOnError: true,
target: ts.ScriptTarget.ES5,
moduleResolution: ts.ModuleResolutionKind.NodeJs,
module: ts.ModuleKind.ESNext,
// We output our customized declaration file
// therefore we wont let TS compiler output dts
declaration: false,
// Do not scan and compile third-party libraries
// which make the compiling process likely to fail
// and very slow
types: [],
typeRoots: [],
outDir: destDir,
listEmittedFiles: true,
});
function testFileForCompilationErrors(path) {
const fileName = last(path.split('/'))
console.log(chalk.blue('Testing compilation errors in "' + fileName + '" :'))
const expectedErrorCount = (fs.readFileSync(path, 'utf8').match(/@shouldNotCompile/g) || []).length
const program = ts.createProgram([...libPaths, path], tsOptions)
const diagnostics = ts.getPreEmitDiagnostics(program)
if (diagnostics.length === expectedErrorCount) {
console.log(chalk.green('All the expected compilation errors were found'))
}
else {
const lines = errors(diagnostics).map(d => d.line).join(', ')
console.log(chalk.red(`${expectedErrorCount} errors were expected but ${diagnostics.length} errors were found at these lines: ${lines}`))
}
}
const output = Unicode.stringOutput(OutputSettings.styled());
OutputStyle.greenBold(output);
output.write("compiling");
OutputStyle.reset(output);
output.write(" ");
OutputStyle.yellow(output);
output.write(this.uid);
OutputStyle.reset(output);
console.log(output.bind());
const configPath = ts.findConfigFile(this.baseDir, ts.sys.fileExists, "tsconfig.json");
const commandLine = ts.getParsedCommandLineOfConfigFile(configPath!, this.compilerOptions, ts.sys as any)!;
const projectReferences = this.injectProjectReferences(commandLine.projectReferences, commandLine.options);
this.injectCompilerOptions(commandLine.options);
this.program = ts.createProgram({
rootNames: commandLine.fileNames,
options: commandLine.options,
projectReferences: projectReferences,
configFileParsingDiagnostics: commandLine.errors,
});
this.compileStart = Date.now();
const emitResult = this.program.emit();
const diagnostics = ts.getPreEmitDiagnostics(this.program).concat(emitResult.diagnostics);
for (let i = 0; i < diagnostics.length; i += 1) {
const diagnostic = diagnostics[i];
if (diagnostic.category !== ts.DiagnosticCategory.Message) {
this.onCompileError(diagnostics[i]);
}
}
let outputsResult: FileReflection[] = [];
if (options.compilerOptions.noEmit) {
roots.forEach(sf => {
outputsResult.push({ name: sf.fileName, text: sf.text });
})
} else {
options.compilerOptions.noEmit = false;
fileMap = new Map(roots.map(sf => {
return [sf.fileName, sf] as [string, ts.SourceFile];
}));
rootNames = Array.from(fileMap.keys());
program = ts.createProgram(rootNames, options.compilerOptions, host);
sourceFiles = program.getSourceFiles().filter(sf => !sf.isDeclarationFile);
program.emit(/*targetSourceFile*/ undefined, host.writeFile, /*cancellationToken*/ undefined, /*emitOnlyDtsFiles*/ false);
outputs.forEach((value: string, key: string) => {
outputsResult.push({ name: key, text: value });
})
}
const declarations = getDeclarations();
if (declarations) {
outputsResult.push(declarations);
}
return outputsResult;
it('should work', () => {
const host = new WebpackCompilerHost({}, '');
host.writeFile('/file.ts', `
export const obj = { moduleId: 123 };
export const obj2 = { moduleId: 123, otherValue: 1 };
export const obj3 = { otherValue: 1, moduleId: 123 };
`, false);
host.writeFile('/file2.ts', `
@SomeDecorator({ moduleId: 123 }) class CLS {}
@SomeDecorator({ moduleId: 123, otherValue1: 1 }) class CLS2 {}
@SomeDecorator({ otherValue2: 2, moduleId: 123, otherValue3: 3 }) class CLS3 {}
@SomeDecorator({ otherValue4: 4, moduleId: 123 }) class CLS4 {}
`, false);
const program = ts.createProgram(['/file.ts', '/file2.ts'], {}, host);
const refactor = new TypeScriptFileRefactor('/file.ts', host, program);
removeModuleIdOnlyForTesting(refactor);
expect(refactor.sourceText).not.toMatch(/obj = \{\s+};/);
expect(refactor.sourceText).not.toMatch(/\{\s*otherValue: 1\s*};/);
const refactor2 = new TypeScriptFileRefactor('/file2.ts', host, program);
removeModuleIdOnlyForTesting(refactor2);
expect(refactor2.sourceText).toMatch(/\(\{\s+}\)/);
expect(refactor2.sourceText).toMatch(/\(\{\s*otherValue1: 1\s*}\)/);
expect(refactor2.sourceText).toMatch(/\(\{\s*otherValue2: 2\s*,\s*otherValue3: 3\s*}\)/);
expect(refactor2.sourceText).toMatch(/\(\{\s*otherValue4: 4\s*}\)/);
});
.filter(({ normalizedPath }) => getCanonicalPath(normalizedPath).startsWith(canonicalSrcPath));
const programs: Array<{ folderName: string; program: ts.Program }> = [];
for (const { folderName, getCompilerOptions } of formats) {
const compilerOptions: ts.CompilerOptions = {
...getCompilerOptions(tsconfigOptions),
outDir: undefined,
outFile: undefined,
out: undefined,
noEmit: false
};
programs.push({
folderName,
program: ts.createProgram({
rootNames: fileNames,
options: compilerOptions
})
});
}
const outputFiles: ts.OutputFile[] = [];
for (const { folderName, program } of programs) {
const optionsDiagnostics = program.getOptionsDiagnostics();
if (optionsDiagnostics.length) {
throw ts.formatDiagnosticsWithColorAndContext(optionsDiagnostics, formatDiagnosticsHost);
}
const globalDiagnostics = program.getGlobalDiagnostics();
if (globalDiagnostics.length) {
throw ts.formatDiagnosticsWithColorAndContext(globalDiagnostics, formatDiagnosticsHost);