• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1import debug from 'debug';
2import * as ts from 'typescript';
3import { Extra } from '../parser-options';
4import {
5  ASTAndProgram,
6  createDefaultCompilerOptionsFromExtra,
7  getScriptKind,
8} from './shared';
9
10const log = debug('typescript-eslint:typescript-estree:createIsolatedProgram');
11
12/**
13 * @param code The code of the file being linted
14 * @returns Returns a new source file and program corresponding to the linted code
15 */
16function createIsolatedProgram(code: string, extra: Extra): ASTAndProgram {
17  log(
18    'Getting isolated program in %s mode for: %s',
19    extra.jsx ? 'TSX' : 'TS',
20    extra.filePath,
21  );
22
23  const compilerHost: ts.CompilerHost = {
24    fileExists() {
25      return true;
26    },
27    getCanonicalFileName() {
28      return extra.filePath;
29    },
30    getCurrentDirectory() {
31      return '';
32    },
33    getDirectories() {
34      return [];
35    },
36    getDefaultLibFileName() {
37      return 'lib.d.ts';
38    },
39
40    // TODO: Support Windows CRLF
41    getNewLine() {
42      return '\n';
43    },
44    getSourceFile(filename: string) {
45      return ts.createSourceFile(
46        filename,
47        code,
48        ts.ScriptTarget.Latest,
49        /* setParentNodes */ true,
50        getScriptKind(extra, filename),
51      );
52    },
53    readFile() {
54      return undefined;
55    },
56    useCaseSensitiveFileNames() {
57      return true;
58    },
59    writeFile() {
60      return null;
61    },
62  };
63
64  const program = ts.createProgram(
65    [extra.filePath],
66    {
67      noResolve: true,
68      target: ts.ScriptTarget.Latest,
69      jsx: extra.jsx ? ts.JsxEmit.Preserve : undefined,
70      ...createDefaultCompilerOptionsFromExtra(extra),
71    },
72    compilerHost,
73  );
74
75  const ast = program.getSourceFile(extra.filePath);
76  if (!ast) {
77    throw new Error(
78      'Expected an ast to be returned for the single-file isolated program.',
79    );
80  }
81
82  return { ast, program };
83}
84
85export { createIsolatedProgram };
86