1
+ const { languages, Uri, DocumentLink, Range } = require ( 'vscode' ) ;
2
+ const path = require ( 'path' ) ;
3
+
4
+ exports . activate = function ( context ) {
5
+ const disposable = languages . registerDocumentLinkProvider ( [ 'javascript' , { language : 'json' , pattern : '**/package.json' } ] , {
6
+ provideDocumentLinks ( document , token ) {
7
+ const { fileName } = document ;
8
+
9
+ // Check why pattern is not working
10
+ if ( path . basename ( fileName ) !== 'package.json' ) {
11
+ return ;
12
+ }
13
+
14
+ const pkg = JSON . parse ( document . getText ( ) ) ;
15
+ const { dependencies = { } , devDependencies = { } , optionalDependencies = { } } = pkg ;
16
+
17
+ const links = [ ] ;
18
+ let lineIndex = 0 ;
19
+
20
+ function extractLink ( line , package , version ) {
21
+ if ( line . text . match ( package , version ) ) {
22
+ const startCharacter = line . text . indexOf ( package ) ;
23
+ const endCaracter = startCharacter + package . length ;
24
+ const linkRange = new Range ( lineIndex , startCharacter , lineIndex , endCaracter ) ;
25
+ const linkUri = Uri . parse ( `https://www.npmjs.com/package/${ package } ` ) ;
26
+ links . push ( new DocumentLink ( linkRange , linkUri ) ) ;
27
+ }
28
+ }
29
+
30
+ while ( lineIndex < document . lineCount ) {
31
+ const line = document . lineAt ( lineIndex ) ;
32
+
33
+ [
34
+ ...Object . entries ( dependencies ) ,
35
+ ...Object . entries ( devDependencies ) ,
36
+ ...Object . entries ( optionalDependencies )
37
+ ] . forEach ( ( [ package , version ] ) => {
38
+ extractLink ( line , package , version ) ;
39
+ } ) ;
40
+
41
+ lineIndex += 1 ;
42
+ }
43
+
44
+ return links ;
45
+ }
46
+ } ) ;
47
+
48
+ context . subscriptions . push ( disposable )
49
+ } ;
50
+
51
+ exports . deactivate = function ( ) {
52
+ } ;
0 commit comments