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

rokucommunity / brighterscript / #12841

24 Jul 2024 05:52PM UTC coverage: 87.936%. Remained the same
#12841

push

TwitchBronBron
0.67.4

6069 of 7376 branches covered (82.28%)

Branch coverage included in aggregate %.

8793 of 9525 relevant lines covered (92.31%)

1741.54 hits per line

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

57.58
/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
                status = 'critical-error';
×
447
                //the first run failed...that won't change unless we reload the workspace, so replace with resolved promise
448
                //so we don't show this error again
449
                project.firstRunPromise = Promise.resolve();
×
450
                await this.sendCriticalFailure(`BrighterScript language server failed to start: \n${e.message}`);
×
451
            }
452
        }
453
    }
454

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

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

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

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

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

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

512

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

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

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

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

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

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

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

553
        let cwd = projectPath;
33✔
554

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

708
        return completions;
×
709
    }
710

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

907
                for (let project of projects) {
4✔
908
                    if (project.configFilePath && filePaths.includes(project.configFilePath)) {
4!
909
                        projectsToReload.push(project);
×
910
                    }
911
                }
912
                if (projectsToReload.length > 0) {
4!
913
                    //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
914
                    //reload any projects that need to be reloaded
915
                    await this.reloadProjects(projectsToReload);
×
916
                }
917

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

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

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

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

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

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

962
    }
963

964
    /**
965
     * This only operates on files that match the specified files globs, so it is safe to throw
966
     * any file changes you receive with no unexpected side-effects
967
     */
968
    public async handleFileChanges(project: Project, changes: { type: FileChangeType; srcPath: string }[]) {
969
        //this loop assumes paths are both file paths and folder paths, which eliminates the need to detect.
970
        //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
971
        let consumeCount = 0;
6✔
972
        await Promise.all(changes.map(async (change) => {
6✔
973
            await this.keyedThrottler.run(change.srcPath, async () => {
10✔
974
                consumeCount += await this.handleFileChange(project, change) ? 1 : 0;
10✔
975
            });
976
        }));
977

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1103
        try {
×
1104

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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