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

rokucommunity / brighterscript / #13683

03 Feb 2025 04:19PM UTC coverage: 86.753% (-1.4%) from 88.185%
#13683

push

web-flow
Merge 34e72243e into 4afb6f658

12476 of 15203 branches covered (82.06%)

Branch coverage included in aggregate %.

7751 of 8408 new or added lines in 101 files covered. (92.19%)

85 existing lines in 17 files now uncovered.

13398 of 14622 relevant lines covered (91.63%)

34302.41 hits per line

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

64.88
/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 { ProgramBuilder } from './ProgramBuilder';
1✔
41
import { standardizePath as s, util } from './util';
1✔
42
import { Throttler } from './Throttler';
1✔
43
import { KeyedThrottler } from './KeyedThrottler';
1✔
44
import { DiagnosticCollection } from './DiagnosticCollection';
1✔
45
import { isBrsFile } from './astUtils/reflection';
1✔
46
import { encodeSemanticTokens, semanticTokensLegend } from './SemanticTokenUtils';
1✔
47
import type { BusyStatus } from './BusyStatusTracker';
48
import { BusyStatusTracker } from './BusyStatusTracker';
1✔
49
import { logger } from './logging';
1✔
50

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

54
    public projects = [] as Project[];
37✔
55

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

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

69
    private hasConfigurationCapability = false;
37✔
70

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

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

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

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

88
    private keyedThrottler = new KeyedThrottler(this.debounceTimeout);
37✔
89

90
    public validateThrottler = new Throttler(0);
37✔
91

92
    private sendDiagnosticsThrottler = new Throttler(0);
37✔
93

94
    private boundValidateAll = this.validateAll.bind(this);
37✔
95

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

100
    public busyStatusTracker = new BusyStatusTracker();
37✔
101

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

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

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

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

121
        this.connection.onInitialize(this.onInitialize.bind(this));
15✔
122

123
        this.connection.onInitialized(this.onInitialized.bind(this)); //eslint-disable-line
15✔
124

125
        this.connection.onDidChangeConfiguration(this.onDidChangeConfiguration.bind(this)); //eslint-disable-line
15✔
126

127
        this.connection.onDidChangeWatchedFiles(this.onDidChangeWatchedFiles.bind(this)); //eslint-disable-line
15✔
128

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

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

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

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

145
        this.connection.onHover(this.onHover.bind(this));
15✔
146

147
        this.connection.onExecuteCommand(this.onExecuteCommand.bind(this));
15✔
148

149
        this.connection.onDefinition(this.onDefinition.bind(this));
15✔
150

151
        this.connection.onDocumentSymbol(this.onDocumentSymbol.bind(this));
15✔
152

153
        this.connection.onWorkspaceSymbol(this.onWorkspaceSymbol.bind(this));
15✔
154

155
        this.connection.onSignatureHelp(this.onSignatureHelp.bind(this));
15✔
156

157
        this.connection.onReferences(this.onReferences.bind(this));
15✔
158

159
        this.connection.onCodeAction(this.onCodeAction.bind(this));
15✔
160

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

406
            await this.syncProjects();
1✔
407

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

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

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

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

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

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

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

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

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

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

506
        //no config file could be found
507
        return undefined;
29✔
508
    }
509

510

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

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

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

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

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

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

549
        let configFilePath = await this.getConfigFilePath(projectPath);
36✔
550

551
        let cwd = projectPath;
36✔
552

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

561
        const firstRunDeferred = new Deferred<any>();
36✔
562

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

575
        this.projects.push(newProject);
36✔
576

577
        try {
36✔
578
            await builder.run({
36✔
579
                cwd: cwd,
580
                project: configFilePath,
581
                watch: false,
582
                createPackage: false,
583
                deploy: false,
584
                copyToStaging: false,
585
                showDiagnosticsInConsole: false
586
            });
587
            newProject.isFirstRunComplete = true;
36✔
588
            newProject.isFirstRunSuccessful = true;
36✔
589
            firstRunDeferred.resolve();
36✔
590
        } catch (e) {
591
            builder.logger.error(e);
×
592
            firstRunDeferred.reject(e);
×
593
            newProject.isFirstRunComplete = true;
×
594
            newProject.isFirstRunSuccessful = false;
×
595
        }
596
    }
597

598
    private async createStandaloneFileProject(srcPath: string) {
599
        //skip this workspace if we already have it
600
        if (this.standaloneFileProjects[srcPath]) {
3✔
601
            return this.standaloneFileProjects[srcPath];
1✔
602
        }
603

604
        let builder = new ProgramBuilder();
2✔
605

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

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

612
        //get the path to the directory where this file resides
613
        let cwd = path.dirname(srcPath);
2✔
614

615
        //get the closest config file and use most of the settings from that
616
        let configFilePath = await util.findClosestConfigFile(srcPath);
2✔
617
        let project: BsConfig = {};
2✔
618
        if (configFilePath) {
2!
619
            project = util.normalizeAndResolveConfig({ project: configFilePath });
×
620
        }
621
        //override the rootDir and files array
622
        project.rootDir = cwd;
2✔
623
        project.files = [{
2✔
624
            src: srcPath,
625
            dest: path.basename(srcPath)
626
        }];
627

628
        let firstRunPromise = builder.run({
2✔
629
            ...project,
630
            cwd: cwd,
631
            project: configFilePath,
632
            watch: false,
633
            createPackage: false,
634
            deploy: false,
635
            copyToStaging: false,
636
            diagnosticFilters: [
637
                //hide the "file not referenced by any other file" error..that's expected in a standalone file.
638
                1013
639
            ]
640
        }).catch((err) => {
641
            console.error(err);
×
642
        });
643

644
        let newProject: Project = {
2✔
645
            projectNumber: this.projectCounter++,
646
            builder: builder,
647
            firstRunPromise: firstRunPromise,
648
            projectPath: srcPath,
649
            workspacePath: srcPath,
650
            isFirstRunComplete: false,
651
            isFirstRunSuccessful: false,
652
            configFilePath: configFilePath,
653
            isStandaloneFileProject: true
654
        };
655

656
        this.standaloneFileProjects[srcPath] = newProject;
2✔
657

658
        await firstRunPromise.then(() => {
2✔
659
            newProject.isFirstRunComplete = true;
2✔
660
            newProject.isFirstRunSuccessful = true;
2✔
661
        }).catch(() => {
662
            newProject.isFirstRunComplete = true;
×
663
            newProject.isFirstRunSuccessful = false;
×
664
        });
665
        return newProject;
2✔
666
    }
667

668
    private getProjects() {
669
        let projects = this.projects.slice();
86✔
670
        for (let key in this.standaloneFileProjects) {
86✔
671
            projects.push(this.standaloneFileProjects[key]);
×
672
        }
673
        return projects;
86✔
674
    }
675

676
    /**
677
     * Provide a list of completion items based on the current cursor position
678
     */
679
    @AddStackToErrorMessage
680
    @TrackBusyStatus
681
    private async onCompletion(params: TextDocumentPositionParams) {
1✔
682
        //ensure programs are initialized
683
        await this.waitAllProjectFirstRuns();
1✔
684

685
        let filePath = util.uriToPath(params.textDocument.uri);
1✔
686

687
        //wait until the file has settled
688
        await this.keyedThrottler.onIdleOnce(filePath, true);
1✔
689
        // make sure validation is complete
690
        await this.validateAllThrottled();
1✔
691
        //wait for the validation cycle to settle
692
        await this.onValidateSettled();
1✔
693

694
        let completions = this
1✔
695
            .getProjects()
696
            .flatMap(workspace => workspace.builder.program.getCompletions(filePath, params.position));
3✔
697

698
        //only send one completion if name and type are the same
699
        let completionsMap = new Map<string, CompletionItem>();
1✔
700

701
        for (let completion of completions) {
1✔
702
            completion.commitCharacters = ['.'];
402✔
703
            let key = `${completion.sortText}-${completion.label}-${completion.kind}`;
402✔
704
            completionsMap.set(key, completion);
402✔
705
        }
706

707
        return [...completionsMap.values()];
1✔
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;
6!
799
        return options?.rootDir ?? options?.cwd;
6!
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) {
7✔
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();
7✔
833
        outer: for (let textDocument of textDocuments) {
7✔
834
            let filePath = URI.parse(textDocument.uri).fsPath;
3✔
835
            for (let project of this.getProjects()) {
3✔
836
                let dest = rokuDeploy.getDestPath(
6✔
837
                    filePath,
838
                    project?.builder?.program?.options?.files ?? [],
90!
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) {
6!
843
                    continue outer;
3✔
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
        await Promise.all(changes.map(async (change) => {
6✔
971
            await this.keyedThrottler.run(change.srcPath, async () => {
10✔
972
                if (await this.handleFileChange(project, change)) {
10✔
973
                    await this.validateAllThrottled();
5✔
974
                }
975
            });
976
        }));
977
    }
978

979
    /**
980
     * This only operates on files that match the specified files globs, so it is safe to throw
981
     * any file changes you receive with no unexpected side-effects
982
     * @returns true if the file was handled by this project, false if it was not
983
     */
984
    private async handleFileChange(project: Project, change: { type: FileChangeType; srcPath: string }): Promise<boolean> {
985
        const { program, options, rootDir } = project.builder;
10✔
986

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

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

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

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

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

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

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

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

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

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

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

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

1098
        let filePath = URI.parse(document.uri).fsPath;
×
1099

1100
        try {
×
1101

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

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

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

1132
            let projects = this.getProjects();
7✔
1133
            //validate all programs
1134
            await Promise.all(
7✔
1135
                projects.map((project) => {
1136
                    project.builder.program.validate();
8✔
1137
                    return project;
8✔
1138
                })
1139
            );
1140

1141
        } catch (e: any) {
1142
            this.connection.console.error(e);
×
1143
            await this.sendCriticalFailure(`Critical error validating project: ${e.message}${e.stack ?? ''}`);
×
1144
        }
1145
    }
1146

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

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

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

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

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

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

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

1189
        const srcPath = util.uriToPath(params.textDocument.uri);
5✔
1190

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

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

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

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

1215
            const activeSignature = signatures.length > 0 ? 0 : null;
4✔
1216

1217
            const activeParameter = activeSignature !== null ? signatures[activeSignature]?.index : null;
4!
1218

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

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

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

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

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

1261
    @AddStackToErrorMessage
1262
    @TrackBusyStatus
1263
    private async onFullSemanticTokens(params: SemanticTokensParams): Promise<SemanticTokens | undefined> {
1✔
1264
        await this.waitAllProjectFirstRuns();
1✔
1265
        //wait for the file to settle (in case there are multiple file changes in quick succession)
1266
        await this.keyedThrottler.onIdleOnce(util.uriToPath(params.textDocument.uri), true);
1✔
1267
        // make sure validation is complete
1268
        await this.validateAllThrottled();
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();
37✔
1287

1288
    private async sendDiagnostics() {
1289
        await this.sendDiagnosticsThrottler.run(async () => {
63✔
1290
            //wait for all programs to finish running. This ensures the `Program` exists.
1291
            await Promise.all(
62✔
1292
                this.projects.map(x => x.firstRunPromise)
81✔
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);
62✔
1297

1298
            for (let fileUri in patch) {
62✔
1299
                const diagnostics = patch[fileUri].map(d => util.toDiagnostic(d, fileUri));
6✔
1300

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

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

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

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

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

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

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

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

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

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

1404
    //wrapping the original method
1405
    descriptor.value = function value(this: LanguageServer, ...args: any[]) {
16✔
1406
        return this.busyStatusTracker.run(() => {
103✔
1407
            return originalMethod.apply(this, args);
103✔
1408
        }, originalMethod.name);
1409
    };
1410
}
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

© 2026 Coveralls, Inc