• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1/* @internal */
2namespace ts.codefix {
3    registerCodeFix({
4        errorCodes: [
5            Diagnostics.Top_level_await_expressions_are_only_allowed_when_the_module_option_is_set_to_esnext_or_system_and_the_target_option_is_set_to_es2017_or_higher.code,
6            Diagnostics.Top_level_for_await_loops_are_only_allowed_when_the_module_option_is_set_to_esnext_or_system_and_the_target_option_is_set_to_es2017_or_higher.code,
7        ],
8        getCodeActions: context => {
9            const compilerOptions = context.program.getCompilerOptions();
10            const { configFile } = compilerOptions;
11            if (configFile === undefined) {
12                return undefined;
13            }
14
15            const codeFixes: CodeFixAction[] = [];
16            const moduleKind = getEmitModuleKind(compilerOptions);
17            const moduleOutOfRange = moduleKind >= ModuleKind.ES2015 && moduleKind < ModuleKind.ESNext;
18            if (moduleOutOfRange) {
19                const changes = textChanges.ChangeTracker.with(context, changes => {
20                    setJsonCompilerOptionValue(changes, configFile, "module", factory.createStringLiteral("esnext"));
21                });
22                codeFixes.push(createCodeFixActionWithoutFixAll("fixModuleOption", changes, [Diagnostics.Set_the_module_option_in_your_configuration_file_to_0, "esnext"]));
23            }
24
25            const target = getEmitScriptTarget(compilerOptions);
26            const targetOutOfRange = target < ScriptTarget.ES2017 || target > ScriptTarget.ESNext;
27            if (targetOutOfRange) {
28                const changes = textChanges.ChangeTracker.with(context, tracker => {
29                    const configObject = getTsConfigObjectLiteralExpression(configFile);
30                    if (!configObject) return;
31
32                    const options: [string, Expression][] = [["target", factory.createStringLiteral("es2017")]];
33                    if (moduleKind === ModuleKind.CommonJS) {
34                        // Ensure we preserve the default module kind (commonjs), as targets >= ES2015 have a default module kind of es2015.
35                        options.push(["module", factory.createStringLiteral("commonjs")]);
36                    }
37
38                    setJsonCompilerOptionValues(tracker, configFile, options);
39                });
40
41                codeFixes.push(createCodeFixActionWithoutFixAll("fixTargetOption", changes, [Diagnostics.Set_the_target_option_in_your_configuration_file_to_0, "es2017"]));
42            }
43
44            return codeFixes.length ? codeFixes : undefined;
45        }
46    });
47}
48