1
- import TsServerLibrary from 'typescript/lib/tsserverlibrary' ;
1
+ import TsServerLibrary , { CodeFixAction , ScriptElementKind } from 'typescript/lib/tsserverlibrary' ;
2
+ import * as path from 'path' ;
3
+
4
+ declare global {
5
+ namespace ts {
6
+ interface CompletionEntryData {
7
+ modulePath ?: string ;
8
+ }
9
+ }
10
+ }
11
+
12
+ function stripExt ( filePath : string ) {
13
+ return filePath . slice ( 0 , filePath . lastIndexOf ( '.' ) ) ;
14
+ }
2
15
3
16
function init ( { typescript : ts } : { typescript : typeof TsServerLibrary } ) {
4
- function create ( info : ts . server . PluginCreateInfo ) {
17
+ function create ( info : TsServerLibrary . server . PluginCreateInfo ) {
5
18
const log = ( ...params : unknown [ ] ) => {
6
19
const text = params . map ( ( p ) => ( p ? JSON . stringify ( p ) : p ) ) . join ( ' ' ) ;
7
20
info . project . projectService . logger . info ( `[namespace-import] ${ text } ` ) ;
@@ -23,11 +36,53 @@ function init({ typescript: ts }: { typescript: typeof TsServerLibrary }) {
23
36
source : '/Users/yukukotani/ghq/github.com/ubie-inc/yukustory/packages/client/src/TestService.ts' ,
24
37
sortText : 'TestService' ,
25
38
hasAction : true ,
39
+ isImportStatementCompletion : true ,
40
+ data : {
41
+ exportName : 'TestService' ,
42
+ modulePath : '/Users/yukukotani/ghq/github.com/ubie-inc/yukustory/packages/client/src/TestService.ts' ,
43
+ } ,
26
44
} ;
27
45
original . entries . push ( entry ) ;
28
46
29
47
return original ;
30
48
} ;
49
+
50
+ const getCompletionEntryDetails = info . languageService . getCompletionEntryDetails ;
51
+ info . languageService . getCompletionEntryDetails = ( fileName , position , name , options , source , preferences , data ) => {
52
+ log ( 'getCompletionEntryDetails' , { fileName, position, name, options, source } ) ;
53
+ if ( name === 'TestService' && data ?. modulePath ) {
54
+ const importPath = path . relative ( path . dirname ( fileName ) , data . modulePath ) ;
55
+ const text = `import * as ${ name } from "${ stripExt ( importPath ) } ";\n` ;
56
+ const action : CodeFixAction = {
57
+ fixName : 'namespace-import' ,
58
+ description : text ,
59
+ changes : [
60
+ {
61
+ fileName : fileName ,
62
+ textChanges : [
63
+ {
64
+ span : {
65
+ start : 0 ,
66
+ length : 0 ,
67
+ } ,
68
+ newText : text ,
69
+ } ,
70
+ ] ,
71
+ } ,
72
+ ] ,
73
+ commands : [ ] ,
74
+ } ;
75
+ return {
76
+ name : name ,
77
+ kind : ScriptElementKind . alias ,
78
+ kindModifiers : '' ,
79
+ displayParts : [ ] ,
80
+ codeActions : [ action ] ,
81
+ } ;
82
+ }
83
+
84
+ return getCompletionEntryDetails ( fileName , position , name , options , source , preferences , data ) ;
85
+ } ;
31
86
}
32
87
33
88
return { create } ;
0 commit comments