• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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  let compilerOptions: CompilerOptions = {};
35  let compilerHost: CompilerHost = createCompilerHost(compilerOptions);
36
37  function getCanonicalFileName(fileName: string): string {
38    return compilerHost.getCanonicalFileName(fileName);
39  }
40
41  const currentDirectory: string = compilerHost.getCurrentDirectory();
42
43  let host: EmitHost = {
44    getSourceFileFromReference: undefined,
45    redirectTargetsMap: undefined,
46    fileExists(path: string): boolean {
47      return false;
48    },
49    isEmitBlocked(emitFileName: string): boolean {
50      return false;
51    },
52    useCaseSensitiveFileNames(): boolean {
53      return false;
54    },
55    getPrependNodes: undefined,
56    getCanonicalFileName: getCanonicalFileName,
57    getCommonSourceDirectory: undefined,
58    getCompilerOptions: undefined,
59    getCurrentDirectory: () => currentDirectory,
60    getNewLine: undefined,
61    getSourceFile: undefined,
62    getSourceFileByPath: undefined,
63    getSourceFiles: undefined,
64    getLibFileFromReference: undefined,
65    isSourceFileFromExternalLibrary: undefined,
66    getResolvedProjectReferenceToRedirect: undefined,
67    getProjectReferenceRedirect: undefined,
68    isSourceOfProjectReferenceRedirect: undefined,
69    writeFile: undefined
70  };
71
72  const generatorOptions: SourceMapGeneratorOptions = {extendedDiagnostics: false};
73  return createSourceMapGenerator(host, sourceFile, currentDirectory, currentDirectory, generatorOptions);
74}
75