1/* 2 * Copyright (c) 2023 Huawei Device Co., Ltd. 3 * Licensed under the Apache License, Version 2.0 (the "License"); 4 * you may not use this file except in compliance with the License. 5 * You may obtain a copy of the License at 6 * 7 * http://www.apache.org/licenses/LICENSE-2.0 8 * 9 * Unless required by applicable law or agreed to in writing, software 10 * distributed under the License is distributed on an "AS IS" BASIS, 11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 * See the License for the specific language governing permissions and 13 * limitations under the License. 14 */ 15 16import { 17 createCompilerHost, 18 createSourceMapGenerator, 19} from 'typescript'; 20 21import type { 22 CompilerHost, 23 CompilerOptions, 24 EmitHost, 25 SourceMapGenerator, 26 SourceMapGeneratorOptions, 27} from 'typescript'; 28 29/** 30 * create sourcemap generator use api of typescript 31 * @param sourceFile: file path of source code 32 */ 33export function getSourceMapGenerator(sourceFile: string): SourceMapGenerator { 34 if (!sourceFile) { 35 return undefined; 36 } 37 38 let compilerOptions: CompilerOptions = {}; 39 let compilerHost: CompilerHost = createCompilerHost(compilerOptions); 40 41 function getCanonicalFileName(fileName: string): string { 42 return compilerHost.getCanonicalFileName(fileName); 43 } 44 45 const currentDirectory: string = compilerHost.getCurrentDirectory(); 46 47 let host: EmitHost = { 48 getSourceFileFromReference: undefined, 49 redirectTargetsMap: undefined, 50 fileExists(path: string): boolean { 51 return false; 52 }, 53 isEmitBlocked(emitFileName: string): boolean { 54 return false; 55 }, 56 useCaseSensitiveFileNames(): boolean { 57 return false; 58 }, 59 getPrependNodes: undefined, 60 getCanonicalFileName: getCanonicalFileName, 61 getCommonSourceDirectory: undefined, 62 getCompilerOptions: undefined, 63 getCurrentDirectory: () => currentDirectory, 64 getNewLine: undefined, 65 getSourceFile: undefined, 66 getSourceFileByPath: undefined, 67 getSourceFiles: undefined, 68 getLibFileFromReference: undefined, 69 isSourceFileFromExternalLibrary: undefined, 70 getResolvedProjectReferenceToRedirect: undefined, 71 getProjectReferenceRedirect: undefined, 72 isSourceOfProjectReferenceRedirect: undefined, 73 writeFile: undefined 74 }; 75 76 const generatorOptions: SourceMapGeneratorOptions = {extendedDiagnostics: false}; 77 return createSourceMapGenerator(host, sourceFile, currentDirectory, currentDirectory, generatorOptions); 78} 79