• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

rokucommunity / brighterscript / #13563

06 Dec 2024 08:59PM UTC coverage: 88.168%. Remained the same
#13563

push

TwitchBronBron
0.68.2

6763 of 8118 branches covered (83.31%)

Branch coverage included in aggregate %.

8990 of 9749 relevant lines covered (92.21%)

1870.28 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

57.65
/src/LanguageServer.ts
1
import 'array-flat-polyfill';
1✔
2
import * as fastGlob from 'fast-glob';
1✔
3
import * as path from 'path';
1✔
4
import { rokuDeploy, util as rokuDeployUtil } from 'roku-deploy';
1✔
5
import type {
6
    CompletionItem,
7
    Connection,
8
    DidChangeWatchedFilesParams,
9
    InitializeParams,
10
    ServerCapabilities,
11
    TextDocumentPositionParams,
12
    ExecuteCommandParams,
13
    WorkspaceSymbolParams,
14
    SymbolInformation,
15
    DocumentSymbolParams,
16
    ReferenceParams,
17
    SignatureHelp,
18
    SignatureHelpParams,
19
    CodeActionParams,
20
    SemanticTokensOptions,
21
    SemanticTokens,
22
    SemanticTokensParams,
23
    TextDocumentChangeEvent,
24
    Hover
25
} from 'vscode-languageserver/node';
26
import {
1✔
27
    SemanticTokensRequest,
28
    createConnection,
29
    DidChangeConfigurationNotification,
30
    FileChangeType,
31
    ProposedFeatures,
32
    TextDocuments,
33
    TextDocumentSyncKind,
34
    CodeActionKind
35
} from 'vscode-languageserver/node';
36
import { URI } from 'vscode-uri';
1✔
37
import { TextDocument } from 'vscode-languageserver-textdocument';
1✔
38
import type { BsConfig } from './BsConfig';
39
import { Deferred } from './deferred';
1✔
40
import { DiagnosticMessages } from './DiagnosticMessages';
1✔
41
import { ProgramBuilder } from './ProgramBuilder';
1✔
42
import { standardizePath as s, util } from './util';
1✔
43
import { Throttler } from './Throttler';
1✔
44
import { KeyedThrottler } from './KeyedThrottler';
1✔
45
import { DiagnosticCollection } from './DiagnosticCollection';
1✔
46
import { isBrsFile } from './astUtils/reflection';
1✔
47
import { encodeSemanticTokens, semanticTokensLegend } from './SemanticTokenUtils';
1✔
48
import type { BusyStatus } from './BusyStatusTracker';
49
import { BusyStatusTracker } from './BusyStatusTracker';
1✔
50
import { logger } from './logging';
1✔
51

52
export class LanguageServer {
1✔
53
    private connection = undefined as any as Connection;
36✔
54

55
    public projects = [] as Project[];
36✔
56

57
    /**
58
     * The number of milliseconds that should be used for language server typing debouncing
59
     */
60
    private debounceTimeout = 150;
36✔
61

62
    /**
63
     * These projects are created on the fly whenever a file is opened that is not included
64
     * in any of the workspace-based projects.
65
     * Basically these are single-file projects to at least get parsing for standalone files.
66
     * Also, they should only be created when the file is opened, and destroyed when the file is closed.
67
     */
68
    public standaloneFileProjects = {} as Record<string, Project>;
36✔
69

70
    private hasConfigurationCapability = false;
36✔
71

72
    /**
73
     * Indicates whether the client supports workspace folders
74
     */
75
    private clientHasWorkspaceFolderCapability = false;
36✔
76

77
    /**
78
     * Create a simple text document manager.
79
     * The text document manager supports full document sync only
80
     */
81
    private documents = new TextDocuments(TextDocument);
36✔
82

83
    private createConnection() {
84
        return createConnection(ProposedFeatures.all);
×
85
    }
86

87
    private loggerSubscription: (() => void) | undefined;
88

89
    private keyedThrottler = new KeyedThrottler(this.debounceTimeout);
36✔
90

91
    public validateThrottler = new Throttler(0);
36✔
92

93
    private sendDiagnosticsThrottler = new Throttler(0);
36✔
94

95
    private boundValidateAll = this.validateAll.bind(this);
36✔
96

97
    private validateAllThrottled() {
98
        return this.validateThrottler.run(this.boundValidateAll);
4✔
99
    }
100

101
    public busyStatusTracker = new BusyStatusTracker();
36✔
102

103
    //run the server
104
    public run() {
105
        // Create a connection for the server. The connection uses Node's IPC as a transport.
106
        // Also include all preview / proposed LSP features.
107
        this.connection = this.createConnection();
14✔
108

109
        // Send the current status of the busyStatusTracker anytime it changes
110
        this.busyStatusTracker.on('change', (status) => {
14✔
111
            void this.sendBusyStatus(status);
38✔
112
        });
113

114
        //disable logger colors when running in LSP mode
115
        logger.enableColor = false;
14✔
116

117
        //listen to all of the output log events and pipe them into the debug channel in the extension
118
        this.loggerSubscription = logger.subscribe((message) => {
14✔
119
            this.connection.tracer.log(message.argsText);
111✔
120
        });
121

122
        this.connection.onInitialize(this.onInitialize.bind(this));
14✔
123

124
        this.connection.onInitialized(this.onInitialized.bind(this)); //eslint-disable-line
14✔
125

126
        this.connection.onDidChangeConfiguration(this.onDidChangeConfiguration.bind(this)); //eslint-disable-line
14✔
127

128
        this.connection.onDidChangeWatchedFiles(this.onDidChangeWatchedFiles.bind(this)); //eslint-disable-line
14✔
129

130
        // The content of a text document has changed. This event is emitted
131
        // when the text document is first opened, when its content has changed,
132
        // or when document is closed without saving (original contents are sent as a change)
133
        //
134
        this.documents.onDidChangeContent(this.validateTextDocument.bind(this));
14✔
135

136
        //whenever a document gets closed
137
        this.documents.onDidClose(this.onDocumentClose.bind(this));
14✔
138

139
        // This handler provides the initial list of the completion items.
140
        this.connection.onCompletion(this.onCompletion.bind(this));
14✔
141

142
        // This handler resolves additional information for the item selected in
143
        // the completion list.
144
        this.connection.onCompletionResolve(this.onCompletionResolve.bind(this));
14✔
145

146
        this.connection.onHover(this.onHover.bind(this));
14✔
147

148
        this.connection.onExecuteCommand(this.onExecuteCommand.bind(this));
14✔
149

150
        this.connection.onDefinition(this.onDefinition.bind(this));
14✔
151

152
        this.connection.onDocumentSymbol(this.onDocumentSymbol.bind(this));
14✔
153

154
        this.connection.onWorkspaceSymbol(this.onWorkspaceSymbol.bind(this));
14✔
155

156
        this.connection.onSignatureHelp(this.onSignatureHelp.bind(this));
14✔
157

158
        this.connection.onReferences(this.onReferences.bind(this));
14✔
159

160
        this.connection.onCodeAction(this.onCodeAction.bind(this));
14✔
161

162
        //TODO switch to a more specific connection function call once they actually add it
163
        this.connection.onRequest(SemanticTokensRequest.method, this.onFullSemanticTokens.bind(this));
14✔
164

165
        /*
166
        this.connection.onDidOpenTextDocument((params) => {
167
             // A text document got opened in VSCode.
168
             // params.uri uniquely identifies the document. For documents stored on disk this is a file URI.
169
             // params.text the initial full content of the document.
170
            this.connection.console.log(`${params.textDocument.uri} opened.`);
171
        });
172
        this.connection.onDidChangeTextDocument((params) => {
173
             // The content of a text document did change in VSCode.
174
             // params.uri uniquely identifies the document.
175
             // params.contentChanges describe the content changes to the document.
176
            this.connection.console.log(`${params.textDocument.uri} changed: ${JSON.stringify(params.contentChanges)}`);
177
        });
178
        this.connection.onDidCloseTextDocument((params) => {
179
             // A text document got closed in VSCode.
180
             // params.uri uniquely identifies the document.
181
            this.connection.console.log(`${params.textDocument.uri} closed.`);
182
        });
183
        */
184

185
        // listen for open, change and close text document events
186
        this.documents.listen(this.connection);
14✔
187

188
        // Listen on the connection
189
        this.connection.listen();
14✔
190
    }
191

192
    private busyStatusIndex = -1;
36✔
193
    private async sendBusyStatus(status: BusyStatus) {
194
        this.busyStatusIndex = ++this.busyStatusIndex <= 0 ? 0 : this.busyStatusIndex;
38✔
195

196
        await this.connection.sendNotification(NotificationName.busyStatus, {
38✔
197
            status: status,
198
            timestamp: Date.now(),
199
            index: this.busyStatusIndex,
200
            activeRuns: [...this.busyStatusTracker.activeRuns]
201
        });
202
    }
203

204
    /**
205
     * Called when the client starts initialization
206
     */
207
    @AddStackToErrorMessage
208
    public onInitialize(params: InitializeParams) {
1✔
209
        let clientCapabilities = params.capabilities;
2✔
210

211
        // Does the client support the `workspace/configuration` request?
212
        // If not, we will fall back using global settings
213
        this.hasConfigurationCapability = !!(clientCapabilities.workspace && !!clientCapabilities.workspace.configuration);
2✔
214
        this.clientHasWorkspaceFolderCapability = !!(clientCapabilities.workspace && !!clientCapabilities.workspace.workspaceFolders);
2✔
215

216
        //return the capabilities of the server
217
        return {
2✔
218
            capabilities: {
219
                textDocumentSync: TextDocumentSyncKind.Full,
220
                // Tell the client that the server supports code completion
221
                completionProvider: {
222
                    resolveProvider: true,
223
                    //anytime the user types a period, auto-show the completion results
224
                    triggerCharacters: ['.'],
225
                    allCommitCharacters: ['.', '@']
226
                },
227
                documentSymbolProvider: true,
228
                workspaceSymbolProvider: true,
229
                semanticTokensProvider: {
230
                    legend: semanticTokensLegend,
231
                    full: true
232
                } as SemanticTokensOptions,
233
                referencesProvider: true,
234
                codeActionProvider: {
235
                    codeActionKinds: [CodeActionKind.Refactor]
236
                },
237
                signatureHelpProvider: {
238
                    triggerCharacters: ['(', ',']
239
                },
240
                definitionProvider: true,
241
                hoverProvider: true,
242
                executeCommandProvider: {
243
                    commands: [
244
                        CustomCommands.TranspileFile
245
                    ]
246
                }
247
            } as ServerCapabilities
248
        };
249
    }
250

251
    private initialProjectsCreated: Promise<any> | undefined;
252

253
    /**
254
     * Ask the client for the list of `files.exclude` patterns. Useful when determining if we should process a file
255
     */
256
    private async getWorkspaceExcludeGlobs(workspaceFolder: string): Promise<string[]> {
257
        let config = {
15✔
258
            exclude: {} as Record<string, boolean>
259
        };
260
        //if supported, ask vscode for the `files.exclude` configuration
261
        if (this.hasConfigurationCapability) {
15✔
262
            //get any `files.exclude` globs to use to filter
263
            config = await this.connection.workspace.getConfiguration({
13✔
264
                scopeUri: workspaceFolder,
265
                section: 'files'
266
            });
267
        }
268
        return Object
15✔
269
            .keys(config?.exclude ?? {})
90!
270
            .filter(x => config?.exclude?.[x])
1!
271
            //vscode files.exclude patterns support ignoring folders without needing to add `**/*`. So for our purposes, we need to
272
            //append **/* to everything without a file extension or magic at the end
273
            .map(pattern => [
1✔
274
                //send the pattern as-is (this handles weird cases and exact file matches)
275
                pattern,
276
                //treat the pattern as a directory (no harm in doing this because if it's a file, the pattern will just never match anything)
277
                `${pattern}/**/*`
278
            ])
279
            .flat(1)
280
            .concat([
281
                //always ignore projects from node_modules
282
                '**/node_modules/**/*'
283
            ]);
284
    }
285

286
    /**
287
     * Scan the workspace for all `bsconfig.json` files. If at least one is found, then only folders who have bsconfig.json are returned.
288
     * If none are found, then the workspaceFolder itself is treated as a project
289
     */
290
    @TrackBusyStatus
291
    private async getProjectPaths(workspaceFolder: string) {
1✔
292
        const excludes = (await this.getWorkspaceExcludeGlobs(workspaceFolder)).map(x => s`!${x}`);
16✔
293
        const files = await rokuDeploy.getFilePaths([
14✔
294
            '**/bsconfig.json',
295
            //exclude all files found in `files.exclude`
296
            ...excludes
297
        ], workspaceFolder);
298
        //if we found at least one bsconfig.json, then ALL projects must have a bsconfig.json.
299
        if (files.length > 0) {
14✔
300
            return files.map(file => s`${path.dirname(file.src)}`);
9✔
301
        }
302

303
        //look for roku project folders
304
        const rokuLikeDirs = (await Promise.all(
7✔
305
            //find all folders containing a `manifest` file
306
            (await rokuDeploy.getFilePaths([
307
                '**/manifest',
308
                ...excludes
309

310
                //is there at least one .bs|.brs file under the `/source` folder?
311
            ], workspaceFolder)).map(async manifestEntry => {
312
                const manifestDir = path.dirname(manifestEntry.src);
3✔
313
                const files = await rokuDeploy.getFilePaths([
3✔
314
                    'source/**/*.{brs,bs}',
315
                    ...excludes
316
                ], manifestDir);
317
                if (files.length > 0) {
3✔
318
                    return manifestDir;
2✔
319
                }
320
            })
321
            //throw out nulls
322
        )).filter(x => !!x);
3✔
323
        if (rokuLikeDirs.length > 0) {
7✔
324
            return rokuLikeDirs;
1✔
325
        }
326

327
        //treat the workspace folder as a brightscript project itself
328
        return [workspaceFolder];
6✔
329
    }
330

331
    /**
332
     * Find all folders with bsconfig.json files in them, and treat each as a project.
333
     * Treat workspaces that don't have a bsconfig.json as a project.
334
     * Handle situations where bsconfig.json files were added or removed (to elevate/lower workspaceFolder projects accordingly)
335
     * Leave existing projects alone if they are not affected by these changes
336
     */
337
    @TrackBusyStatus
338
    private async syncProjects() {
1✔
339
        const workspacePaths = await this.getWorkspacePaths();
13✔
340
        let projectPaths = (await Promise.all(
13✔
341
            workspacePaths.map(async workspacePath => {
342
                const projectPaths = await this.getProjectPaths(workspacePath);
14✔
343
                return projectPaths.map(projectPath => ({
17✔
344
                    projectPath: projectPath,
345
                    workspacePath: workspacePath
346
                }));
347
            })
348
        )).flat(1);
349

350
        //delete projects not represented in the list
351
        for (const project of this.getProjects()) {
13✔
352
            if (!projectPaths.find(x => x.projectPath === project.projectPath)) {
5✔
353
                this.removeProject(project);
3✔
354
            }
355
        }
356

357
        //exclude paths to projects we already have
358
        projectPaths = projectPaths.filter(x => {
13✔
359
            //only keep this project path if there's not a project with that path
360
            return !this.projects.find(project => project.projectPath === x.projectPath);
17✔
361
        });
362

363
        //dedupe by project path
364
        projectPaths = [
13✔
365
            ...projectPaths.reduce(
366
                (acc, x) => acc.set(x.projectPath, x),
16✔
367
                new Map<string, typeof projectPaths[0]>()
368
            ).values()
369
        ];
370

371
        //create missing projects
372
        await Promise.all(
13✔
373
            projectPaths.map(x => this.createProject(x.projectPath, x.workspacePath))
15✔
374
        );
375
        //flush diagnostics
376
        await this.sendDiagnostics();
13✔
377
    }
378

379
    /**
380
     * Get all workspace paths from the client
381
     */
382
    private async getWorkspacePaths() {
383
        let workspaceFolders = await this.connection.workspace.getWorkspaceFolders() ?? [];
13!
384
        return workspaceFolders.map((x) => {
13✔
385
            return util.uriToPath(x.uri);
14✔
386
        });
387
    }
388

389
    /**
390
     * Called when the client has finished initializing
391
     */
392
    @AddStackToErrorMessage
393
    @TrackBusyStatus
394
    private async onInitialized() {
1✔
395
        let projectCreatedDeferred = new Deferred();
1✔
396
        this.initialProjectsCreated = projectCreatedDeferred.promise;
1✔
397

398
        try {
1✔
399
            if (this.hasConfigurationCapability) {
1!
400
                // Register for all configuration changes.
401
                await this.connection.client.register(
×
402
                    DidChangeConfigurationNotification.type,
403
                    undefined
404
                );
405
            }
406

407
            await this.syncProjects();
1✔
408

409
            if (this.clientHasWorkspaceFolderCapability) {
1!
410
                this.connection.workspace.onDidChangeWorkspaceFolders(async (evt) => {
×
411
                    await this.syncProjects();
×
412
                });
413
            }
414
            await this.waitAllProjectFirstRuns(false);
1✔
415
            projectCreatedDeferred.resolve();
1✔
416
        } catch (e: any) {
417
            await this.sendCriticalFailure(
×
418
                `Critical failure during BrighterScript language server startup.
419
                Please file a github issue and include the contents of the 'BrighterScript Language Server' output channel.
420

421
                Error message: ${e.message}`
422
            );
423
            throw e;
×
424
        }
425
    }
426

427
    /**
428
     * Send a critical failure notification to the client, which should show a notification of some kind
429
     */
430
    private async sendCriticalFailure(message: string) {
431
        await this.connection.sendNotification('critical-failure', message);
×
432
    }
433

434
    /**
435
     * Wait for all programs' first run to complete
436
     */
437
    private async waitAllProjectFirstRuns(waitForFirstProject = true) {
31✔
438
        if (waitForFirstProject) {
32✔
439
            await this.initialProjectsCreated;
31✔
440
        }
441

442
        for (let project of this.getProjects()) {
32✔
443
            try {
32✔
444
                await project.firstRunPromise;
32✔
445
            } catch (e: any) {
446
                //the first run failed...that won't change unless we reload the workspace, so replace with resolved promise
447
                //so we don't show this error again
448
                project.firstRunPromise = Promise.resolve();
×
449
                await this.sendCriticalFailure(`BrighterScript language server failed to start: \n${e.message}`);
×
450
            }
451
        }
452
    }
453

454
    /**
455
     * Event handler for when the program wants to load file contents.
456
     * anytime the program wants to load a file, check with our in-memory document cache first
457
     */
458
    private documentFileResolver(srcPath: string) {
459
        let pathUri = URI.file(srcPath).toString();
15✔
460
        let document = this.documents.get(pathUri);
15✔
461
        if (document) {
15!
462
            return document.getText();
×
463
        }
464
    }
465

466
    private async getConfigFilePath(workspacePath: string) {
467
        let scopeUri: string;
468
        if (workspacePath.startsWith('file:')) {
35!
469
            scopeUri = URI.parse(workspacePath).toString();
×
470
        } else {
471
            scopeUri = URI.file(workspacePath).toString();
35✔
472
        }
473
        let config = {
35✔
474
            configFile: undefined
475
        };
476
        //if the client supports configuration, look for config group called "brightscript"
477
        if (this.hasConfigurationCapability) {
35✔
478
            config = await this.connection.workspace.getConfiguration({
33✔
479
                scopeUri: scopeUri,
480
                section: 'brightscript'
481
            });
482
        }
483
        let configFilePath: string;
484

485
        //if there's a setting, we need to find the file or show error if it can't be found
486
        if (config?.configFile) {
35!
487
            configFilePath = path.resolve(workspacePath, config.configFile);
1✔
488
            if (await util.pathExists(configFilePath)) {
1!
489
                return configFilePath;
1✔
490
            } else {
491
                await this.sendCriticalFailure(`Cannot find config file specified in user / workspace settings at '${configFilePath}'`);
×
492
            }
493
        }
494

495
        //default to config file path found in the root of the workspace
496
        configFilePath = path.resolve(workspacePath, 'bsconfig.json');
34✔
497
        if (await util.pathExists(configFilePath)) {
34✔
498
            return configFilePath;
8✔
499
        }
500

501
        //look for the deprecated `brsconfig.json` file
502
        configFilePath = path.resolve(workspacePath, 'brsconfig.json');
26✔
503
        if (await util.pathExists(configFilePath)) {
26!
504
            return configFilePath;
×
505
        }
506

507
        //no config file could be found
508
        return undefined;
26✔
509
    }
510

511

512
    /**
513
     * A unique project counter to help distinguish log entries in lsp mode
514
     */
515
    private projectCounter = 0;
36✔
516

517
    /**
518
     * @param projectPath path to the project
519
     * @param workspacePath path to the workspace in which all project should reside or are referenced by
520
     * @param projectNumber an optional project number to assign to the project. Used when reloading projects that should keep the same number
521
     */
522
    @TrackBusyStatus
523
    private async createProject(projectPath: string, workspacePath = projectPath, projectNumber?: number) {
1✔
524
        workspacePath ??= projectPath;
33!
525
        let project = this.projects.find((x) => x.projectPath === projectPath);
33✔
526
        //skip this project if we already have it
527
        if (project) {
33!
528
            return;
×
529
        }
530

531
        let builder = new ProgramBuilder();
33✔
532
        projectNumber ??= this.projectCounter++;
33!
533
        builder.logger.prefix = `[prj${projectNumber}]`;
33✔
534
        builder.logger.log(`Created project #${projectNumber} for: "${projectPath}"`);
33✔
535

536
        //flush diagnostics every time the program finishes validating
537
        builder.plugins.add({
33✔
538
            name: 'bsc-language-server',
539
            afterProgramValidate: () => {
540
                void this.sendDiagnostics();
39✔
541
            }
542
        });
543

544
        //prevent clearing the console on run...this isn't the CLI so we want to keep a full log of everything
545
        builder.allowConsoleClearing = false;
33✔
546

547
        //look for files in our in-memory cache before going to the file system
548
        builder.addFileResolver(this.documentFileResolver.bind(this));
33✔
549

550
        let configFilePath = await this.getConfigFilePath(projectPath);
33✔
551

552
        let cwd = projectPath;
33✔
553

554
        //if the config file exists, use it and its folder as cwd
555
        if (configFilePath && await util.pathExists(configFilePath)) {
33✔
556
            cwd = path.dirname(configFilePath);
7✔
557
        } else {
558
            //config file doesn't exist...let `brighterscript` resolve the default way
559
            configFilePath = undefined;
26✔
560
        }
561

562
        const firstRunDeferred = new Deferred<any>();
33✔
563

564
        let newProject: Project = {
33✔
565
            projectNumber: projectNumber,
566
            builder: builder,
567
            firstRunPromise: firstRunDeferred.promise,
568
            projectPath: projectPath,
569
            workspacePath: workspacePath,
570
            isFirstRunComplete: false,
571
            isFirstRunSuccessful: false,
572
            configFilePath: configFilePath,
573
            isStandaloneFileProject: false
574
        };
575

576
        this.projects.push(newProject);
33✔
577

578
        try {
33✔
579
            await builder.run({
33✔
580
                cwd: cwd,
581
                project: configFilePath,
582
                watch: false,
583
                createPackage: false,
584
                deploy: false,
585
                copyToStaging: false,
586
                showDiagnosticsInConsole: false
587
            });
588
            newProject.isFirstRunComplete = true;
33✔
589
            newProject.isFirstRunSuccessful = true;
33✔
590
            firstRunDeferred.resolve();
33✔
591
        } catch (e) {
592
            builder.logger.error(e);
×
593
            firstRunDeferred.reject(e);
×
594
            newProject.isFirstRunComplete = true;
×
595
            newProject.isFirstRunSuccessful = false;
×
596
        }
597
        //if we found a deprecated brsconfig.json, add a diagnostic warning the user
598
        if (configFilePath && path.basename(configFilePath) === 'brsconfig.json') {
33!
599
            builder.addDiagnostic(configFilePath, {
×
600
                ...DiagnosticMessages.brsConfigJsonIsDeprecated(),
601
                range: util.createRange(0, 0, 0, 0)
602
            });
603
            return this.sendDiagnostics();
×
604
        }
605
    }
606

607
    private async createStandaloneFileProject(srcPath: string) {
608
        //skip this workspace if we already have it
609
        if (this.standaloneFileProjects[srcPath]) {
3✔
610
            return this.standaloneFileProjects[srcPath];
1✔
611
        }
612

613
        let builder = new ProgramBuilder();
2✔
614

615
        //prevent clearing the console on run...this isn't the CLI so we want to keep a full log of everything
616
        builder.allowConsoleClearing = false;
2✔
617

618
        //look for files in our in-memory cache before going to the file system
619
        builder.addFileResolver(this.documentFileResolver.bind(this));
2✔
620

621
        //get the path to the directory where this file resides
622
        let cwd = path.dirname(srcPath);
2✔
623

624
        //get the closest config file and use most of the settings from that
625
        let configFilePath = await util.findClosestConfigFile(srcPath);
2✔
626
        let project: BsConfig = {};
2✔
627
        if (configFilePath) {
2!
628
            project = util.normalizeAndResolveConfig({ project: configFilePath });
×
629
        }
630
        //override the rootDir and files array
631
        project.rootDir = cwd;
2✔
632
        project.files = [{
2✔
633
            src: srcPath,
634
            dest: path.basename(srcPath)
635
        }];
636

637
        let firstRunPromise = builder.run({
2✔
638
            ...project,
639
            cwd: cwd,
640
            project: configFilePath,
641
            watch: false,
642
            createPackage: false,
643
            deploy: false,
644
            copyToStaging: false,
645
            diagnosticFilters: [
646
                //hide the "file not referenced by any other file" error..that's expected in a standalone file.
647
                1013
648
            ]
649
        }).catch((err) => {
650
            console.error(err);
×
651
        });
652

653
        let newProject: Project = {
2✔
654
            projectNumber: this.projectCounter++,
655
            builder: builder,
656
            firstRunPromise: firstRunPromise,
657
            projectPath: srcPath,
658
            workspacePath: srcPath,
659
            isFirstRunComplete: false,
660
            isFirstRunSuccessful: false,
661
            configFilePath: configFilePath,
662
            isStandaloneFileProject: true
663
        };
664

665
        this.standaloneFileProjects[srcPath] = newProject;
2✔
666

667
        await firstRunPromise.then(() => {
2✔
668
            newProject.isFirstRunComplete = true;
2✔
669
            newProject.isFirstRunSuccessful = true;
2✔
670
        }).catch(() => {
671
            newProject.isFirstRunComplete = true;
×
672
            newProject.isFirstRunSuccessful = false;
×
673
        });
674
        return newProject;
2✔
675
    }
676

677
    private getProjects() {
678
        let projects = this.projects.slice();
77✔
679
        for (let key in this.standaloneFileProjects) {
77✔
680
            projects.push(this.standaloneFileProjects[key]);
×
681
        }
682
        return projects;
77✔
683
    }
684

685
    /**
686
     * Provide a list of completion items based on the current cursor position
687
     */
688
    @AddStackToErrorMessage
689
    @TrackBusyStatus
690
    private async onCompletion(params: TextDocumentPositionParams) {
1✔
691
        //ensure programs are initialized
692
        await this.waitAllProjectFirstRuns();
×
693

694
        let filePath = util.uriToPath(params.textDocument.uri);
×
695

696
        //wait until the file has settled
697
        await this.keyedThrottler.onIdleOnce(filePath, true);
×
698

699
        let completions = this
×
700
            .getProjects()
701
            .flatMap(workspace => workspace.builder.program.getCompletions(filePath, params.position));
×
702

703
        for (let completion of completions) {
×
704
            completion.commitCharacters = ['.'];
×
705
        }
706

707
        return completions;
×
708
    }
709

710
    /**
711
     * Provide a full completion item from the selection
712
     */
713
    @AddStackToErrorMessage
714
    private onCompletionResolve(item: CompletionItem): CompletionItem {
1✔
715
        if (item.data === 1) {
×
716
            item.detail = 'TypeScript details';
×
717
            item.documentation = 'TypeScript documentation';
×
718
        } else if (item.data === 2) {
×
719
            item.detail = 'JavaScript details';
×
720
            item.documentation = 'JavaScript documentation';
×
721
        }
722
        return item;
×
723
    }
724

725
    @AddStackToErrorMessage
726
    @TrackBusyStatus
727
    private async onCodeAction(params: CodeActionParams) {
1✔
728
        //ensure programs are initialized
729
        await this.waitAllProjectFirstRuns();
×
730

731
        let srcPath = util.uriToPath(params.textDocument.uri);
×
732

733
        //wait until the file has settled
734
        await this.keyedThrottler.onIdleOnce(srcPath, true);
×
735

736
        const codeActions = this
×
737
            .getProjects()
738
            //skip programs that don't have this file
739
            .filter(x => x.builder?.program?.hasFile(srcPath))
×
740
            .flatMap(workspace => workspace.builder.program.getCodeActions(srcPath, params.range));
×
741

742
        //clone the diagnostics for each code action, since certain diagnostics can have circular reference properties that kill the language server if serialized
743
        for (const codeAction of codeActions) {
×
744
            if (codeAction.diagnostics) {
×
745
                codeAction.diagnostics = codeAction.diagnostics?.map(x => util.toDiagnostic(x, params.textDocument.uri));
×
746
            }
747
        }
748
        return codeActions;
×
749
    }
750

751
    /**
752
     * Remove a project from the language server
753
     */
754
    private removeProject(project: Project) {
755
        const idx = this.projects.indexOf(project);
3✔
756
        if (idx > -1) {
3!
757
            this.projects.splice(idx, 1);
3✔
758
        }
759
        project?.builder?.dispose();
3!
760
    }
761

762
    /**
763
     * Reload each of the specified workspaces
764
     */
765
    private async reloadProjects(projects: Project[]) {
766
        await Promise.all(
×
767
            projects.map(async (project) => {
768
                //ensure the workspace has finished starting up
769
                try {
×
770
                    await project.firstRunPromise;
×
771
                } catch (e) { }
772

773
                //handle standard workspace
774
                if (project.isStandaloneFileProject === false) {
×
775
                    this.removeProject(project);
×
776

777
                    //create a new workspace/brs program
778
                    await this.createProject(project.projectPath, project.workspacePath, project.projectNumber);
×
779

780
                    //handle temp workspace
781
                } else {
782
                    project.builder.dispose();
×
783
                    delete this.standaloneFileProjects[project.projectPath];
×
784
                    await this.createStandaloneFileProject(project.projectPath);
×
785
                }
786
            })
787
        );
788
        if (projects.length > 0) {
×
789
            //wait for all of the programs to finish starting up
790
            await this.waitAllProjectFirstRuns();
×
791

792
            // valdiate all workspaces
793
            this.validateAllThrottled(); //eslint-disable-line
×
794
        }
795
    }
796

797
    private getRootDir(workspace: Project) {
798
        let options = workspace?.builder?.program?.options;
×
799
        return options?.rootDir ?? options?.cwd;
×
800
    }
801

802
    /**
803
     * Sometimes users will alter their bsconfig files array, and will include standalone files.
804
     * If this is the case, those standalone workspaces should be removed because the file was
805
     * included in an actual program now.
806
     *
807
     * Sometimes files that used to be included are now excluded, so those open files need to be re-processed as standalone
808
     */
809
    private async synchronizeStandaloneProjects() {
810

811
        //remove standalone workspaces that are now included in projects
812
        for (let standaloneFilePath in this.standaloneFileProjects) {
4✔
813
            let standaloneProject = this.standaloneFileProjects[standaloneFilePath];
×
814
            for (let project of this.projects) {
×
815
                await standaloneProject.firstRunPromise;
×
816

817
                let dest = rokuDeploy.getDestPath(
×
818
                    standaloneFilePath,
819
                    project?.builder?.program?.options?.files ?? [],
×
820
                    this.getRootDir(project)
821
                );
822
                //destroy this standalone workspace because the file has now been included in an actual workspace,
823
                //or if the workspace wants the file
824
                if (project?.builder?.program?.hasFile(standaloneFilePath) || dest) {
×
825
                    standaloneProject.builder.dispose();
×
826
                    delete this.standaloneFileProjects[standaloneFilePath];
×
827
                }
828
            }
829
        }
830

831
        //create standalone projects for open files that no longer have a project
832
        let textDocuments = this.documents.all();
4✔
833
        outer: for (let textDocument of textDocuments) {
4✔
834
            let filePath = URI.parse(textDocument.uri).fsPath;
×
835
            for (let project of this.getProjects()) {
×
836
                let dest = rokuDeploy.getDestPath(
×
837
                    filePath,
838
                    project?.builder?.program?.options?.files ?? [],
×
839
                    this.getRootDir(project)
840
                );
841
                //if this project has the file, or it wants the file, do NOT make a standaloneProject for this file
842
                if (project?.builder?.program?.hasFile(filePath) || dest) {
×
843
                    continue outer;
×
844
                }
845
            }
846
            //if we got here, no workspace has this file, so make a standalone file workspace
847
            let project = await this.createStandaloneFileProject(filePath);
×
848
            await project.firstRunPromise;
×
849
        }
850
    }
851

852
    @AddStackToErrorMessage
853
    private async onDidChangeConfiguration() {
1✔
854
        if (this.hasConfigurationCapability) {
×
855
            //if the user changes any config value, just mass-reload all projects
856
            await this.reloadProjects(this.getProjects());
×
857
            // Reset all cached document settings
858
        } else {
859
            // this.globalSettings = <ExampleSettings>(
860
            //     (change.settings.languageServerExample || this.defaultSettings)
861
            // );
862
        }
863
    }
864

865
    /**
866
     * Called when watched files changed (add/change/delete).
867
     * The CLIENT is in charge of what files to watch, so all client
868
     * implementations should ensure that all valid project
869
     * file types are watched (.brs,.bs,.xml,manifest, and any json/text/image files)
870
     */
871
    @AddStackToErrorMessage
872
    @TrackBusyStatus
873
    private async onDidChangeWatchedFiles(params: DidChangeWatchedFilesParams) {
1✔
874
        //ensure programs are initialized
875
        await this.waitAllProjectFirstRuns();
4✔
876

877
        let projects = this.getProjects();
4✔
878

879
        //convert all file paths to absolute paths
880
        let changes = params.changes.map(x => {
4✔
881
            return {
5✔
882
                type: x.type,
883
                srcPath: s`${URI.parse(x.uri).fsPath}`
884
            };
885
        });
886

887
        let keys = changes.map(x => x.srcPath);
5✔
888

889
        //filter the list of changes to only the ones that made it through the debounce unscathed
890
        changes = changes.filter(x => keys.includes(x.srcPath));
5✔
891

892
        //if we have changes to work with
893
        if (changes.length > 0) {
4!
894

895
            //if any bsconfig files were added or deleted, re-sync all projects instead of the more specific approach below
896
            if (changes.find(x => (x.type === FileChangeType.Created || x.type === FileChangeType.Deleted) && path.basename(x.srcPath).toLowerCase() === 'bsconfig.json')) {
5!
897
                return this.syncProjects();
×
898
            }
899

900
            //reload any workspace whose bsconfig.json file has changed
901
            {
902
                let projectsToReload = [] as Project[];
4✔
903
                //get the file paths as a string array
904
                let filePaths = changes.map((x) => x.srcPath);
5✔
905

906
                for (let project of projects) {
4✔
907
                    if (project.configFilePath && filePaths.includes(project.configFilePath)) {
4!
908
                        projectsToReload.push(project);
×
909
                    }
910
                }
911
                if (projectsToReload.length > 0) {
4!
912
                    //vsc can generate a ton of these changes, for vsc system files, so we need to bail if there's no work to do on any of our actual project files
913
                    //reload any projects that need to be reloaded
914
                    await this.reloadProjects(projectsToReload);
×
915
                }
916

917
                //reassign `projects` to the non-reloaded projects
918
                projects = projects.filter(x => !projectsToReload.includes(x));
4✔
919
            }
920

921
            //convert created folders into a list of files of their contents
922
            const directoryChanges = changes
4✔
923
                //get only creation items
924
                .filter(change => change.type === FileChangeType.Created)
5✔
925
                //keep only the directories
926
                .filter(change => util.isDirectorySync(change.srcPath));
3✔
927

928
            //remove the created directories from the changes array (we will add back each of their files next)
929
            changes = changes.filter(x => !directoryChanges.includes(x));
5✔
930

931
            //look up every file in each of the newly added directories
932
            const newFileChanges = directoryChanges
4✔
933
                //take just the path
934
                .map(x => x.srcPath)
2✔
935
                //exclude the roku deploy staging folder
936
                .filter(dirPath => !dirPath.includes('.roku-deploy-staging'))
2✔
937
                //get the files for each folder recursively
938
                .flatMap(dirPath => {
939
                    //look up all files
940
                    let files = fastGlob.sync('**/*', {
2✔
941
                        absolute: true,
942
                        cwd: rokuDeployUtil.toForwardSlashes(dirPath)
943
                    });
944
                    return files.map(x => {
2✔
945
                        return {
5✔
946
                            type: FileChangeType.Created,
947
                            srcPath: s`${x}`
948
                        };
949
                    });
950
                });
951

952
            //add the new file changes to the changes array.
953
            changes.push(...newFileChanges as any);
4✔
954

955
            //give every workspace the chance to handle file changes
956
            await Promise.all(
4✔
957
                projects.map((project) => this.handleFileChanges(project, changes))
4✔
958
            );
959
        }
960

961
    }
962

963
    /**
964
     * This only operates on files that match the specified files globs, so it is safe to throw
965
     * any file changes you receive with no unexpected side-effects
966
     */
967
    public async handleFileChanges(project: Project, changes: { type: FileChangeType; srcPath: string }[]) {
968
        //this loop assumes paths are both file paths and folder paths, which eliminates the need to detect.
969
        //All functions below can handle being given a file path AND a folder path, and will only operate on the one they are looking for
970
        let consumeCount = 0;
6✔
971
        await Promise.all(changes.map(async (change) => {
6✔
972
            await this.keyedThrottler.run(change.srcPath, async () => {
10✔
973
                consumeCount += await this.handleFileChange(project, change) ? 1 : 0;
10✔
974
            });
975
        }));
976

977
        if (consumeCount > 0) {
6✔
978
            await this.validateAllThrottled();
4✔
979
        }
980
    }
981

982
    /**
983
     * This only operates on files that match the specified files globs, so it is safe to throw
984
     * any file changes you receive with no unexpected side-effects
985
     */
986
    private async handleFileChange(project: Project, change: { type: FileChangeType; srcPath: string }) {
987
        const { program, options, rootDir } = project.builder;
10✔
988

989
        //deleted
990
        if (change.type === FileChangeType.Deleted) {
10!
991
            //try to act on this path as a directory
992
            project.builder.removeFilesInFolder(change.srcPath);
×
993

994
            //if this is a file loaded in the program, remove it
995
            if (program.hasFile(change.srcPath)) {
×
996
                program.removeFile(change.srcPath);
×
997
                return true;
×
998
            } else {
999
                return false;
×
1000
            }
1001

1002
            //created
1003
        } else if (change.type === FileChangeType.Created) {
10✔
1004
            // thanks to `onDidChangeWatchedFiles`, we can safely assume that all "Created" changes are file paths, (not directories)
1005

1006
            //get the dest path for this file.
1007
            let destPath = rokuDeploy.getDestPath(change.srcPath, options.files, rootDir);
8✔
1008

1009
            //if we got a dest path, then the program wants this file
1010
            if (destPath) {
8✔
1011
                program.setFile(
4✔
1012
                    {
1013
                        src: change.srcPath,
1014
                        dest: rokuDeploy.getDestPath(change.srcPath, options.files, rootDir)
1015
                    },
1016
                    await project.builder.getFileContents(change.srcPath)
1017
                );
1018
                return true;
4✔
1019
            } else {
1020
                //no dest path means the program doesn't want this file
1021
                return false;
4✔
1022
            }
1023

1024
            //changed
1025
        } else if (program.hasFile(change.srcPath)) {
2✔
1026
            //sometimes "changed" events are emitted on files that were actually deleted,
1027
            //so determine file existance and act accordingly
1028
            if (await util.pathExists(change.srcPath)) {
1!
1029
                program.setFile(
1✔
1030
                    {
1031
                        src: change.srcPath,
1032
                        dest: rokuDeploy.getDestPath(change.srcPath, options.files, rootDir)
1033
                    },
1034
                    await project.builder.getFileContents(change.srcPath)
1035
                );
1036
            } else {
1037
                program.removeFile(change.srcPath);
×
1038
            }
1039
            return true;
1✔
1040
        }
1041
    }
1042

1043
    @AddStackToErrorMessage
1044
    private async onHover(params: TextDocumentPositionParams) {
1✔
1045
        //ensure programs are initialized
1046
        await this.waitAllProjectFirstRuns();
×
1047

1048
        const srcPath = util.uriToPath(params.textDocument.uri);
×
1049
        let projects = this.getProjects();
×
1050
        let hovers = projects
×
1051
            //get hovers from all projects
1052
            .map((x) => x.builder.program.getHover(srcPath, params.position))
×
1053
            //flatten to a single list
1054
            .flat();
1055

1056
        const contents = [
×
1057
            ...(hovers ?? [])
×
1058
                //pull all hover contents out into a flag array of strings
1059
                .map(x => {
1060
                    return Array.isArray(x?.contents) ? x?.contents : [x?.contents];
×
1061
                }).flat()
1062
                //remove nulls
1063
                .filter(x => !!x)
×
1064
                //dedupe hovers across all projects
1065
                .reduce((set, content) => set.add(content), new Set<string>()).values()
×
1066
        ];
1067

1068
        if (contents.length > 0) {
×
1069
            let hover: Hover = {
×
1070
                //use the range from the first hover
1071
                range: hovers[0]?.range,
×
1072
                //the contents of all hovers
1073
                contents: contents
1074
            };
1075
            return hover;
×
1076
        }
1077
    }
1078

1079
    @AddStackToErrorMessage
1080
    private async onDocumentClose(event: TextDocumentChangeEvent<TextDocument>): Promise<void> {
1✔
1081
        const { document } = event;
×
1082
        let filePath = URI.parse(document.uri).fsPath;
×
1083
        let standaloneFileProject = this.standaloneFileProjects[filePath];
×
1084
        //if this was a temp file, close it
1085
        if (standaloneFileProject) {
×
1086
            await standaloneFileProject.firstRunPromise;
×
1087
            standaloneFileProject.builder.dispose();
×
1088
            delete this.standaloneFileProjects[filePath];
×
1089
            await this.sendDiagnostics();
×
1090
        }
1091
    }
1092

1093
    @AddStackToErrorMessage
1094
    @TrackBusyStatus
1095
    private async validateTextDocument(event: TextDocumentChangeEvent<TextDocument>): Promise<void> {
1✔
1096
        const { document } = event;
×
1097
        //ensure programs are initialized
1098
        await this.waitAllProjectFirstRuns();
×
1099

1100
        let filePath = URI.parse(document.uri).fsPath;
×
1101

1102
        try {
×
1103

1104
            //throttle file processing. first call is run immediately, and then the last call is processed.
1105
            await this.keyedThrottler.run(filePath, () => {
×
1106

1107
                let documentText = document.getText();
×
1108
                for (const project of this.getProjects()) {
×
1109
                    //only add or replace existing files. All of the files in the project should
1110
                    //have already been loaded by other means
1111
                    if (project.builder.program.hasFile(filePath)) {
×
1112
                        let rootDir = project.builder.program.options.rootDir ?? project.builder.program.options.cwd;
×
1113
                        let dest = rokuDeploy.getDestPath(filePath, project.builder.program.options.files, rootDir);
×
1114
                        project.builder.program.setFile({
×
1115
                            src: filePath,
1116
                            dest: dest
1117
                        }, documentText);
1118
                    }
1119
                }
1120
            });
1121
            // validate all projects
1122
            await this.validateAllThrottled();
×
1123
        } catch (e: any) {
1124
            await this.sendCriticalFailure(`Critical error parsing/validating ${filePath}: ${e.message}`);
×
1125
        }
1126
    }
1127

1128
    @TrackBusyStatus
1129
    private async validateAll() {
1✔
1130
        try {
4✔
1131
            //synchronize parsing for open files that were included/excluded from projects
1132
            await this.synchronizeStandaloneProjects();
4✔
1133

1134
            let projects = this.getProjects();
4✔
1135

1136
            //validate all programs
1137
            await Promise.all(
4✔
1138
                projects.map((project) => {
1139
                    project.builder.program.validate();
3✔
1140
                    return project;
3✔
1141
                })
1142
            );
1143
        } catch (e: any) {
1144
            this.connection.console.error(e);
×
1145
            await this.sendCriticalFailure(`Critical error validating project: ${e.message}${e.stack ?? ''}`);
×
1146
        }
1147
    }
1148

1149
    @AddStackToErrorMessage
1150
    @TrackBusyStatus
1151
    public async onWorkspaceSymbol(params: WorkspaceSymbolParams) {
1✔
1152
        await this.waitAllProjectFirstRuns();
4✔
1153

1154
        const results = util.flatMap(
4✔
1155
            await Promise.all(this.getProjects().map(project => {
1156
                return project.builder.program.getWorkspaceSymbols();
4✔
1157
            })),
1158
            c => c
4✔
1159
        );
1160

1161
        // Remove duplicates
1162
        const allSymbols = Object.values(results.reduce((map, symbol) => {
4✔
1163
            const key = symbol.location.uri + symbol.name;
24✔
1164
            map[key] = symbol;
24✔
1165
            return map;
24✔
1166
        }, {}));
1167
        return allSymbols as SymbolInformation[];
4✔
1168
    }
1169

1170
    @AddStackToErrorMessage
1171
    @TrackBusyStatus
1172
    public async onDocumentSymbol(params: DocumentSymbolParams) {
1✔
1173
        await this.waitAllProjectFirstRuns();
6✔
1174

1175
        await this.keyedThrottler.onIdleOnce(util.uriToPath(params.textDocument.uri), true);
6✔
1176

1177
        const srcPath = util.uriToPath(params.textDocument.uri);
6✔
1178
        for (const project of this.getProjects()) {
6✔
1179
            const file = project.builder.program.getFile(srcPath);
6✔
1180
            if (isBrsFile(file)) {
6!
1181
                return file.getDocumentSymbols();
6✔
1182
            }
1183
        }
1184
    }
1185

1186
    @AddStackToErrorMessage
1187
    @TrackBusyStatus
1188
    private async onDefinition(params: TextDocumentPositionParams) {
1✔
1189
        await this.waitAllProjectFirstRuns();
5✔
1190

1191
        const srcPath = util.uriToPath(params.textDocument.uri);
5✔
1192

1193
        const results = util.flatMap(
5✔
1194
            await Promise.all(this.getProjects().map(project => {
1195
                return project.builder.program.getDefinition(srcPath, params.position);
5✔
1196
            })),
1197
            c => c
5✔
1198
        );
1199
        return results;
5✔
1200
    }
1201

1202
    @AddStackToErrorMessage
1203
    @TrackBusyStatus
1204
    private async onSignatureHelp(params: SignatureHelpParams) {
1✔
1205
        await this.waitAllProjectFirstRuns();
4✔
1206

1207
        const filepath = util.uriToPath(params.textDocument.uri);
4✔
1208
        await this.keyedThrottler.onIdleOnce(filepath, true);
4✔
1209

1210
        try {
4✔
1211
            const signatures = util.flatMap(
4✔
1212
                await Promise.all(this.getProjects().map(project => project.builder.program.getSignatureHelp(filepath, params.position)
4✔
1213
                )),
1214
                c => c
4✔
1215
            );
1216

1217
            const activeSignature = signatures.length > 0 ? 0 : null;
4✔
1218

1219
            const activeParameter = activeSignature !== null ? signatures[activeSignature]?.index : null;
4!
1220

1221
            let results: SignatureHelp = {
4✔
1222
                signatures: signatures.map((s) => s.signature),
3✔
1223
                activeSignature: activeSignature,
1224
                activeParameter: activeParameter
1225
            };
1226
            return results;
4✔
1227
        } catch (e: any) {
1228
            this.connection.console.error(`error in onSignatureHelp: ${e.stack ?? e.message ?? e}`);
×
1229
            return {
×
1230
                signatures: [],
1231
                activeSignature: 0,
1232
                activeParameter: 0
1233
            };
1234
        }
1235
    }
1236

1237
    @AddStackToErrorMessage
1238
    @TrackBusyStatus
1239
    private async onReferences(params: ReferenceParams) {
1✔
1240
        await this.waitAllProjectFirstRuns();
3✔
1241

1242
        const position = params.position;
3✔
1243
        const srcPath = util.uriToPath(params.textDocument.uri);
3✔
1244

1245
        const results = util.flatMap(
3✔
1246
            await Promise.all(this.getProjects().map(project => {
1247
                return project.builder.program.getReferences(srcPath, position);
3✔
1248
            })),
1249
            c => c ?? []
3!
1250
        );
1251
        return results.filter((r) => r);
5✔
1252
    }
1253

1254
    private onValidateSettled() {
1255
        return Promise.all([
1✔
1256
            //wait for the validator to start running (or timeout if it never did)
1257
            this.validateThrottler.onRunOnce(100),
1258
            //wait for the validator to stop running (or resolve immediately if it's already idle)
1259
            this.validateThrottler.onIdleOnce(true)
1260
        ]);
1261
    }
1262

1263
    @AddStackToErrorMessage
1264
    @TrackBusyStatus
1265
    private async onFullSemanticTokens(params: SemanticTokensParams): Promise<SemanticTokens | undefined> {
1✔
1266
        await this.waitAllProjectFirstRuns();
1✔
1267
        //wait for the file to settle (in case there are multiple file changes in quick succession)
1268
        await this.keyedThrottler.onIdleOnce(util.uriToPath(params.textDocument.uri), true);
1✔
1269
        //wait for the validation cycle to settle
1270
        await this.onValidateSettled();
1✔
1271

1272
        const srcPath = util.uriToPath(params.textDocument.uri);
1✔
1273
        for (const project of this.projects) {
1✔
1274
            //find the first program that has this file, since it would be incredibly inefficient to generate semantic tokens for the same file multiple times.
1275
            if (project.builder.program.hasFile(srcPath)) {
1!
1276
                let semanticTokens = project.builder.program.getSemanticTokens(srcPath);
1✔
1277
                if (semanticTokens !== undefined) {
1!
1278
                    return {
1✔
1279
                        data: encodeSemanticTokens(semanticTokens)
1280
                    } as SemanticTokens;
1281
                }
1282
            }
1283
        }
1284
    }
1285

1286
    private diagnosticCollection = new DiagnosticCollection();
36✔
1287

1288
    private async sendDiagnostics() {
1289
        await this.sendDiagnosticsThrottler.run(async () => {
54✔
1290
            //wait for all programs to finish running. This ensures the `Program` exists.
1291
            await Promise.all(
54✔
1292
                this.projects.map(x => x.firstRunPromise)
64✔
1293
            );
1294

1295
            //Get only the changes to diagnostics since the last time we sent them to the client
1296
            const patch = this.diagnosticCollection.getPatch(this.projects);
54✔
1297

1298
            for (let filePath in patch) {
54✔
1299
                const uri = URI.file(filePath).toString();
5✔
1300
                const diagnostics = patch[filePath].map(d => util.toDiagnostic(d, uri));
5✔
1301

1302
                await this.connection.sendDiagnostics({
5✔
1303
                    uri: uri,
1304
                    diagnostics: diagnostics
1305
                });
1306
            }
1307
        });
1308
    }
1309

1310
    @AddStackToErrorMessage
1311
    @TrackBusyStatus
1312
    public async onExecuteCommand(params: ExecuteCommandParams) {
1✔
1313
        await this.waitAllProjectFirstRuns();
2✔
1314
        if (params.command === CustomCommands.TranspileFile) {
2!
1315
            const result = await this.transpileFile(params.arguments[0]);
2✔
1316
            //back-compat: include `pathAbsolute` property so older vscode versions still work
1317
            (result as any).pathAbsolute = result.srcPath;
2✔
1318
            return result;
2✔
1319
        }
1320
    }
1321

1322
    private async transpileFile(srcPath: string) {
1323
        //wait all program first runs
1324
        await this.waitAllProjectFirstRuns();
2✔
1325
        //find the first project that has this file
1326
        for (let project of this.getProjects()) {
2✔
1327
            if (project.builder.program.hasFile(srcPath)) {
2!
1328
                return project.builder.program.getTranspiledFileContents(srcPath);
2✔
1329
            }
1330
        }
1331
    }
1332

1333
    public dispose() {
1334
        this.loggerSubscription?.();
36✔
1335
        this.validateThrottler.dispose();
36✔
1336
    }
1337
}
1338

1339
export interface Project {
1340
    /**
1341
     * A unique number for this project, generated during this current language server session. Mostly used so we can identify which project is doing logging
1342
     */
1343
    projectNumber: number;
1344
    firstRunPromise: Promise<any>;
1345
    builder: ProgramBuilder;
1346
    /**
1347
     * The path to where the project resides
1348
     */
1349
    projectPath: string;
1350
    /**
1351
     * The path to the workspace where this project resides. A workspace can have multiple projects (by adding a bsconfig.json to each folder).
1352
     */
1353
    workspacePath: string;
1354
    isFirstRunComplete: boolean;
1355
    isFirstRunSuccessful: boolean;
1356
    configFilePath?: string;
1357
    isStandaloneFileProject: boolean;
1358
}
1359

1360
export enum CustomCommands {
1✔
1361
    TranspileFile = 'TranspileFile'
1✔
1362
}
1363

1364
export enum NotificationName {
1✔
1365
    busyStatus = 'busyStatus'
1✔
1366
}
1367

1368
/**
1369
 * Wraps a method. If there's an error (either sync or via a promise),
1370
 * this appends the error's stack trace at the end of the error message so that the connection will
1371
 */
1372
function AddStackToErrorMessage(target: any, propertyKey: string, descriptor: PropertyDescriptor) {
1373
    let originalMethod = descriptor.value;
17✔
1374

1375
    //wrapping the original method
1376
    descriptor.value = function value(...args: any[]) {
17✔
1377
        try {
32✔
1378
            let result = originalMethod.apply(this, args);
32✔
1379
            //if the result looks like a promise, log if there's a rejection
1380
            if (result?.then) {
32!
1381
                return Promise.resolve(result).catch((e: Error) => {
30✔
1382
                    if (e?.stack) {
×
1383
                        e.message = e.stack;
×
1384
                    }
1385
                    return Promise.reject(e);
×
1386
                });
1387
            } else {
1388
                return result;
2✔
1389
            }
1390
        } catch (e: any) {
1391
            if (e?.stack) {
×
1392
                e.message = e.stack;
×
1393
            }
1394
            throw e;
×
1395
        }
1396
    };
1397
}
1398

1399
/**
1400
 * An annotation used to wrap the method in a busyStatus tracking call
1401
 */
1402
function TrackBusyStatus(target: any, propertyKey: string, descriptor: PropertyDescriptor) {
1403
    let originalMethod = descriptor.value;
16✔
1404

1405
    //wrapping the original method
1406
    descriptor.value = function value(this: LanguageServer, ...args: any[]) {
16✔
1407
        return this.busyStatusTracker.run(() => {
94✔
1408
            return originalMethod.apply(this, args);
94✔
1409
        }, originalMethod.name);
1410
    };
1411
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc