Repository navigation
Expand file tree
/
Copy pathinstallTypesForPackage.ts
More file actions
73 lines (64 loc) · 2.73 KB
/
Copy pathinstallTypesForPackage.ts
File metadata and controls
73 lines (64 loc) · 2.73 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
/* @internal */
namespace ts.refactor.installTypesForPackage {
const actionName = "install";
const installTypesForPackage: Refactor = {
name: "Install missing types package",
description: "Install missing types package",
getEditsForAction,
getAvailableActions,
};
registerRefactor(installTypesForPackage);
function getAvailableActions(context: RefactorContext): ApplicableRefactorInfo[] | undefined {
if (getStrictOptionValue(context.program.getCompilerOptions(), "noImplicitAny")) {
// Then it will be available via `fixCannotFindModule`.
return undefined;
}
const action = getAction(context);
return action && [
{
name: installTypesForPackage.name,
description: installTypesForPackage.description,
actions: [
{
description: action.description,
name: actionName,
},
],
},
];
}
function getEditsForAction(context: RefactorContext, _actionName: string): RefactorEditInfo | undefined {
Debug.assertEqual(actionName, _actionName);
const action = getAction(context)!; // Should be defined if we said there was an action available.
return {
edits: [],
renameFilename: undefined,
renameLocation: undefined,
commands: action.commands,
};
}
function getAction(context: RefactorContext): CodeAction | undefined {
const { file, startPosition } = context;
const node = getTokenAtPosition(file, startPosition, /*includeJsDocComment*/ false);
if (!isStringLiteral(node) || !isModuleIdentifier(node)) {
return undefined;
}
const resolvedTo = getResolvedModule(file, node.text);
// Still offer to install types if it resolved to e.g. a ".js" file.
// `tryGetCodeActionForInstallPackageTypes` will verify that we're looking for a valid package name,
// so the fix won't trigger for imports of ".js" files that couldn't be better replaced by typings.
if (resolvedTo && extensionIsTypeScript(resolvedTo.extension)) {
return undefined;
}
return codefix.tryGetCodeActionForInstallPackageTypes(context.host, file.fileName, node.text);
}
function isModuleIdentifier(node: StringLiteral): boolean {
switch (node.parent.kind) {
case SyntaxKind.ImportDeclaration:
case SyntaxKind.ExternalModuleReference:
return true;
default:
return false;
}
}
}