forked from intersystems-community/vscode-objectscript
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathextension.ts
1680 lines (1591 loc) · 69.2 KB
/
extension.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
export const extensionId = "intersystems-community.vscode-objectscript";
export const lsExtensionId = "intersystems.language-server";
export const smExtensionId = "intersystems-community.servermanager";
import vscode = require("vscode");
import * as semver from "semver";
import * as serverManager from "@intersystems-community/intersystems-servermanager";
import { AtelierJob, Content, Response, ServerInfo } from "./api/atelier";
export const OBJECTSCRIPT_FILE_SCHEMA = "objectscript";
export const OBJECTSCRIPTXML_FILE_SCHEMA = "objectscriptxml";
export const FILESYSTEM_SCHEMA = "isfs";
export const FILESYSTEM_READONLY_SCHEMA = "isfs-readonly";
export const schemas = [
OBJECTSCRIPT_FILE_SCHEMA,
OBJECTSCRIPTXML_FILE_SCHEMA,
FILESYSTEM_SCHEMA,
FILESYSTEM_READONLY_SCHEMA,
];
export const filesystemSchemas = [FILESYSTEM_SCHEMA, FILESYSTEM_READONLY_SCHEMA];
export const clsLangId = "objectscript-class";
export const macLangId = "objectscript";
export const intLangId = "objectscript-int";
export const incLangId = "objectscript-macros";
export const cspLangId = "objectscript-csp";
import * as url from "url";
import path = require("path");
import {
importAndCompile,
importFolder as importFileOrFolder,
namespaceCompile,
compileExplorerItems,
checkChangedOnServer,
compileOnly,
importLocalFilesToServerSideFolder,
loadChanges,
importXMLFiles,
} from "./commands/compile";
import { deleteExplorerItems } from "./commands/delete";
import {
exportAll,
exportCurrentFile,
exportDocumentsToXMLFile,
exportExplorerItems,
getCategory,
} from "./commands/export";
import { serverActions } from "./commands/serverActions";
import { subclass } from "./commands/subclass";
import { superclass } from "./commands/superclass";
import { viewOthers } from "./commands/viewOthers";
import { extractXMLFileContents, previewXMLAsUDL } from "./commands/xmlToUdl";
import {
mainCommandMenu,
contextCommandMenu,
fireOtherStudioAction,
OtherStudioAction,
contextSourceControlMenu,
mainSourceControlMenu,
} from "./commands/studio";
import { addServerNamespaceToWorkspace, pickServerAndNamespace } from "./commands/addServerNamespaceToWorkspace";
import { jumpToTagAndOffset, openErrorLocation } from "./commands/jumpToTagAndOffset";
import { connectFolderToServerNamespace } from "./commands/connectFolderToServerNamespace";
import { DocumaticPreviewPanel } from "./commands/documaticPreviewPanel";
import { getLanguageConfiguration } from "./languageConfiguration";
import { DocumentContentProvider } from "./providers/DocumentContentProvider";
import { DocumentFormattingEditProvider } from "./providers/DocumentFormattingEditProvider";
import { ObjectScriptClassFoldingRangeProvider } from "./providers/ObjectScriptClassFoldingRangeProvider";
import { ObjectScriptClassSymbolProvider } from "./providers/ObjectScriptClassSymbolProvider";
import { ObjectScriptCompletionItemProvider } from "./providers/ObjectScriptCompletionItemProvider";
import { ObjectScriptDefinitionProvider } from "./providers/ObjectScriptDefinitionProvider";
import { ObjectScriptFoldingRangeProvider } from "./providers/ObjectScriptFoldingRangeProvider";
import { ObjectScriptHoverProvider } from "./providers/ObjectScriptHoverProvider";
import { ObjectScriptRoutineSymbolProvider } from "./providers/ObjectScriptRoutineSymbolProvider";
import { ObjectScriptCodeLensProvider } from "./providers/ObjectScriptCodeLensProvider";
import { XmlContentProvider } from "./providers/XmlContentProvider";
import { AtelierAPI } from "./api";
import { ObjectScriptDebugAdapterDescriptorFactory } from "./debug/debugAdapterFactory";
import { ObjectScriptConfigurationProvider } from "./debug/debugConfProvider";
import { ProjectsExplorerProvider } from "./explorer/projectsExplorer";
import { ObjectScriptExplorerProvider, registerExplorerOpen } from "./explorer/explorer";
import { FileSystemProvider, generateFileContent } from "./providers/FileSystemProvider/FileSystemProvider";
import { WorkspaceSymbolProvider } from "./providers/WorkspaceSymbolProvider";
import {
connectionTarget,
currentWorkspaceFolder,
outputChannel,
portFromDockerCompose,
terminalWithDocker,
notNull,
currentFile,
workspaceFolderOfUri,
uriOfWorkspaceFolder,
isUnauthenticated,
notIsfs,
handleError,
cspApps,
otherDocExts,
getWsServerConnection,
} from "./utils";
import { ObjectScriptDiagnosticProvider } from "./providers/ObjectScriptDiagnosticProvider";
import { DocumentLinkProvider } from "./providers/DocumentLinkProvider";
/* proposed */
import { FileSearchProvider } from "./providers/FileSystemProvider/FileSearchProvider";
import { TextSearchProvider } from "./providers/FileSystemProvider/TextSearchProvider";
export let fileSystemProvider: FileSystemProvider;
export let explorerProvider: ObjectScriptExplorerProvider;
export let projectsExplorerProvider: ProjectsExplorerProvider;
export let documentContentProvider: DocumentContentProvider;
export let workspaceState: vscode.Memento;
export let extensionContext: vscode.ExtensionContext;
export let panel: vscode.StatusBarItem;
export let posPanel: vscode.StatusBarItem;
export const terminals: vscode.Terminal[] = [];
export let xmlContentProvider: XmlContentProvider;
export let iscIcon: vscode.Uri;
import TelemetryReporter from "vscode-extension-telemetry";
import { CodeActionProvider } from "./providers/CodeActionProvider";
import {
addWorkspaceFolderForProject,
compileProjectContents,
createProject,
deleteProject,
exportProjectContents,
modifyProject,
modifyProjectMetadata,
} from "./commands/project";
import { loadStudioColors, loadStudioSnippets } from "./commands/studioMigration";
import { RuleEditorProvider } from "./providers/RuleEditorProvider";
import { newFile, NewFileType } from "./commands/newFile";
import { FileDecorationProvider } from "./providers/FileDecorationProvider";
import { RESTDebugPanel } from "./commands/restDebugPanel";
import { modifyWsFolder } from "./commands/addServerNamespaceToWorkspace";
import { WebSocketTerminalProfileProvider, launchWebSocketTerminal } from "./commands/webSocketTerminal";
import { setUpTestController } from "./commands/unitTest";
import { pickDocument } from "./utils/documentPicker";
import {
disposeDocumentIndex,
indexWorkspaceFolder,
removeIndexOfWorkspaceFolder,
updateIndexForDocument,
} from "./utils/documentIndex";
import { WorkspaceNode, NodeBase } from "./explorer/nodes";
const packageJson = vscode.extensions.getExtension(extensionId).packageJSON;
const extensionVersion = packageJson.version;
const aiKey = packageJson.aiKey;
const PANEL_LABEL = "ObjectScript";
const _onDidChangeConnection = new vscode.EventEmitter<void>();
export const config = (setting?: string, workspaceFolderName?: string): vscode.WorkspaceConfiguration | any => {
workspaceFolderName = workspaceFolderName || currentWorkspaceFolder();
if (
vscode.workspace.workspaceFolders?.length &&
workspaceFolderName &&
workspaceFolderName !== "" &&
vscode.workspace.getConfiguration("intersystems.servers", null).has(workspaceFolderName)
) {
workspaceFolderName = vscode.workspace.workspaceFolders[0].name;
}
let prefix: string;
const workspaceFolder = vscode.workspace.workspaceFolders?.find(
(el) => el.name.toLowerCase() === workspaceFolderName.toLowerCase()
);
if (setting && setting.startsWith("intersystems")) {
return vscode.workspace.getConfiguration(setting, workspaceFolder);
} else {
prefix = "objectscript";
}
if (["conn", "export"].includes(setting)) {
if (workspaceFolderName && workspaceFolderName !== "") {
if (workspaceFolderName.match(/.+:\d+$/)) {
const { port, hostname: host, auth, query } = url.parse("http://" + workspaceFolderName, true);
const { ns = "USER", https = false } = query;
const [username, password] = (auth || "_SYSTEM:SYS").split(":");
if (setting == "conn") {
return {
active: true,
https,
ns,
host,
port,
username,
password,
};
} else if (setting == "export") {
return {};
}
}
}
}
const result = vscode.workspace.getConfiguration(prefix, workspaceFolder?.uri);
return setting && setting.length ? result.get(setting) : result;
};
let reporter: TelemetryReporter = null;
export let checkingConnection = false;
let serverManagerApi: serverManager.ServerManagerAPI;
/** Map of the intersystems.server connection specs we have resolved via the API to that extension */
const resolvedConnSpecs = new Map<string, any>();
/**
* If servermanager extension is available, fetch the connection spec unless already cached.
* Prompt for credentials if necessary.
* @param serverName authority element of an isfs uri, or `objectscript.conn.server` property, or the name of a root folder with an `objectscript.conn.docker-compose` property object
* @param uri if passed, re-check the `objectscript.conn.docker-compose` case in case servermanager API couldn't do that because we're still running our own `activate` method.
*/
export async function resolveConnectionSpec(serverName: string, uri?: vscode.Uri): Promise<void> {
if (!serverManagerApi || !serverManagerApi.getServerSpec || serverName === "") {
return;
}
if (resolvedConnSpecs.has(serverName)) {
// Already resolved
return;
}
if (!vscode.workspace.getConfiguration("intersystems.servers", null).has(serverName)) {
// When not a defined server see it already resolved as a foldername that matches case-insensitively
if (getResolvedConnectionSpec(serverName, undefined)) {
return;
}
}
let connSpec = await serverManagerApi.getServerSpec(serverName);
if (!connSpec && uri) {
// Caller passed uri as a signal to process any docker-compose settings
const { configName } = connectionTarget(uri);
if (config("conn", configName)["docker-compose"]) {
const serverForUri = await asyncServerForUri(uri);
if (serverForUri) {
connSpec = {
name: serverForUri.serverName,
webServer: {
scheme: serverForUri.scheme,
host: serverForUri.host,
port: serverForUri.port,
pathPrefix: serverForUri.pathPrefix,
},
username: serverForUri.username,
password: serverForUri.password ? serverForUri.password : undefined,
description: `Server for workspace folder '${serverName}'`,
};
}
}
}
if (connSpec) {
await resolvePassword(connSpec);
resolvedConnSpecs.set(serverName, connSpec);
}
}
async function resolvePassword(serverSpec, ignoreUnauthenticated = false): Promise<void> {
if (
// Connection isn't unauthenticated
(!isUnauthenticated(serverSpec.username) || ignoreUnauthenticated) &&
// A password is missing
typeof serverSpec.password == "undefined"
) {
const scopes = [serverSpec.name, serverSpec.username || ""];
// Handle Server Manager extension version < 3.8.0
const account = serverManagerApi.getAccount ? serverManagerApi.getAccount(serverSpec) : undefined;
let session = await vscode.authentication.getSession(serverManager.AUTHENTICATION_PROVIDER, scopes, {
silent: true,
account,
});
if (!session) {
session = await vscode.authentication.getSession(serverManager.AUTHENTICATION_PROVIDER, scopes, {
createIfNone: true,
account,
});
}
if (session) {
// If original spec lacked username use the one obtained by the authprovider
serverSpec.username = serverSpec.username || session.scopes[1];
serverSpec.password = session.accessToken;
}
}
}
/** Accessor for the cache of resolved connection specs */
export function getResolvedConnectionSpec(key: string, dflt: any): any {
let spec = resolvedConnSpecs.get(key);
if (spec) {
return spec;
}
// Try a case-insensitive match
key = resolvedConnSpecs.keys().find((oneKey) => oneKey.toLowerCase() === key.toLowerCase());
if (key) {
spec = resolvedConnSpecs.get(key);
if (spec) {
return spec;
}
}
// Return the default if not found
return dflt;
}
export async function checkConnection(
clearCookies = false,
uri?: vscode.Uri,
triggerRefreshes?: boolean
): Promise<void> {
// Do nothing if already checking the connection
if (checkingConnection) {
return;
}
const { apiTarget, configName } = connectionTarget(uri);
const wsKey = configName.toLowerCase();
if (clearCookies) {
/// clean-up cached values
await workspaceState.update(wsKey + ":host", undefined);
await workspaceState.update(wsKey + ":port", undefined);
await workspaceState.update(wsKey + ":password", undefined);
await workspaceState.update(wsKey + ":apiVersion", undefined);
await workspaceState.update(wsKey + ":serverVersion", undefined);
await workspaceState.update(wsKey + ":docker", undefined);
_onDidChangeConnection.fire();
}
let api = new AtelierAPI(apiTarget, false);
const { active, host = "", port = 0, username, ns = "" } = api.config;
vscode.commands.executeCommand("setContext", "vscode-objectscript.connectActive", active);
if (!panel.text) {
panel.text = `${PANEL_LABEL}`;
}
if (!host.length && !port && !ns.length) {
panel.text = `${PANEL_LABEL}`;
panel.tooltip = `No connection configured`;
return;
}
let connInfo = api.connInfo;
if (!active) {
panel.text = `${PANEL_LABEL} $(warning)`;
panel.tooltip = new vscode.MarkdownString(
`Connection to${
!host.length || !port || !ns.length ? " incompletely specified server" : ""
} \`${connInfo}\` is disabled`
);
return;
}
if (!workspaceState.get(wsKey + ":port") && !api.externalServer) {
try {
const { port: dockerPort, docker: withDocker, service } = await portFromDockerCompose();
workspaceState.update(wsKey + ":docker", withDocker);
workspaceState.update(wsKey + ":dockerService", service);
if (withDocker) {
if (!dockerPort) {
const errorMessage = `Something is wrong with your docker-compose connection settings, or your service is not running.`;
handleError(errorMessage);
panel.text = `${PANEL_LABEL} $(error)`;
panel.tooltip = `ERROR - ${errorMessage}`;
return;
}
const { autoShowTerminal } = config();
autoShowTerminal && terminalWithDocker();
if (dockerPort !== port) {
workspaceState.update(wsKey + ":host", "localhost");
workspaceState.update(wsKey + ":port", dockerPort);
}
connInfo = `localhost:${dockerPort}[${ns}]`;
_onDidChangeConnection.fire();
}
} catch (error) {
handleError(error);
workspaceState.update(wsKey + ":docker", true);
panel.text = `${PANEL_LABEL} $(error)`;
panel.tooltip = error;
return;
}
}
if (clearCookies) {
api.clearCookies();
}
// Why must this be recreated here? Maybe in case something has updated connection details since we last fetched them.
api = new AtelierAPI(apiTarget, false);
if (!api.config.host || !api.config.port || !api.config.ns) {
const message = "'host', 'port' and 'ns' must be specified.";
handleError(message);
panel.text = `${PANEL_LABEL} $(error)`;
panel.tooltip = `ERROR - ${message}`;
if (!api.externalServer) {
await setConnectionState(configName, false);
}
return;
}
checkingConnection = true;
// What we do when api.serverInfo call succeeds
const gotServerInfo = async (info: Response<Content<ServerInfo>>) => {
panel.text = api.connInfo;
if (api.config.serverName) {
panel.tooltip = new vscode.MarkdownString(
`Connected to \`${api.config.host}:${api.config.port}${api.config.pathPrefix}\` as \`${username}\``
);
} else {
panel.tooltip = new vscode.MarkdownString(
`Connected${api.config.pathPrefix ? ` to \`${api.config.pathPrefix}\`` : ""} as \`${username}\``
);
}
const hasHS = info.result.content.features.find((el) => el.name === "HEALTHSHARE" && el.enabled) !== undefined;
reporter &&
reporter.sendTelemetryEvent("connected", {
serverVersion: info.result.content.version,
healthshare: hasHS ? "yes" : "no",
});
// Update CSP web app cache if required
const key = `${api.serverId}:${api.config.ns}`.toLowerCase();
if (!cspApps.has(key)) {
cspApps.set(key, await api.getCSPApps().then((data) => data.result.content || []));
}
if (!otherDocExts.has(key)) {
otherDocExts.set(
key,
await api
.actionQuery("SELECT Extention FROM %Library.RoutineMgr_DocumentTypes()", [])
.then((data) => data.result?.content?.map((e) => e.Extention) ?? [])
.catch(() => [])
);
}
if (!api.externalServer) {
await setConnectionState(configName, true);
}
return;
};
// Do the check
const serverInfoTimeout = 5000;
return api
.serverInfo(true, serverInfoTimeout)
.then(gotServerInfo)
.catch(async (error) => {
let message = error.message;
let errorMessage;
if (error.statusCode === 401) {
let success = false;
message = "Not Authorized.";
errorMessage = `Authorization error: Check your credentials in Settings, and that you have sufficient privileges on the /api/atelier web application on ${connInfo}`;
const username = api.config.username;
if (isUnauthenticated(username)) {
vscode.window.showErrorMessage(
`Unauthenticated access rejected by '${api.serverId}'.${
!api.externalServer ? " Connection has been disabled." : ""
}`,
"Dismiss"
);
if (api.externalServer) {
// Attempt to resolve a username and password
const newSpec: { name: string; username?: string; password?: string } = {
name: api.config.serverName,
username,
};
await resolvePassword(newSpec, true);
if (newSpec.password) {
// Update the connection spec and try again
await workspaceState.update(wsKey + ":password", newSpec.password);
resolvedConnSpecs.set(api.config.serverName, {
...resolvedConnSpecs.get(api.config.serverName),
username: newSpec.username,
password: newSpec.password,
});
api = new AtelierAPI(apiTarget, false);
await api
.serverInfo(true, serverInfoTimeout)
.then(async (info) => {
await gotServerInfo(info);
_onDidChangeConnection.fire();
success = true;
})
.catch(async (err) => {
error = err;
if (error?.statusCode != 401) errorMessage = undefined;
await workspaceState.update(wsKey + ":password", undefined);
success = false;
})
.finally(() => {
checkingConnection = false;
});
}
} else {
await setConnectionState(configName, false);
}
} else {
success = await new Promise<boolean>((resolve) => {
vscode.window
.showInputBox({
password: true,
placeHolder: `Not Authorized. Enter password to connect as user '${username}' to ${connInfo}`,
prompt: !api.externalServer ? "If no password is entered the connection will be disabled." : "",
ignoreFocusOut: true,
})
.then(async (password) => {
if (password) {
await workspaceState.update(wsKey + ":password", password);
resolve(
api
.serverInfo(true, serverInfoTimeout)
.then(async (info): Promise<boolean> => {
await gotServerInfo(info);
_onDidChangeConnection.fire();
return true;
})
.catch(async (err) => {
error = err;
if (error?.statusCode != 401) errorMessage = undefined;
await workspaceState.update(wsKey + ":password", undefined);
return false;
})
.finally(() => {
checkingConnection = false;
})
);
} else if (!api.externalServer) {
await setConnectionState(configName, false);
}
resolve(false);
});
});
}
if (success) return;
}
handleError(
errorMessage ?? error,
`Failed to connect to server '${api.serverId}'. Check your server configuration.`
);
panel.text = `${connInfo} $(error)`;
panel.tooltip = `ERROR - ${message}`;
await setConnectionState(configName, false);
})
.finally(() => {
checkingConnection = false;
if (triggerRefreshes) {
setTimeout(() => {
explorerProvider.refresh();
projectsExplorerProvider.refresh();
// Refreshing Files Explorer also switches to it, so only do this if the uri is part of the workspace,
// otherwise files opened from ObjectScript Explorer (objectscript://) will cause an unwanted switch.
if (uri && schemas.includes(uri.scheme) && vscode.workspace.getWorkspaceFolder(uri)) {
vscode.commands.executeCommand("workbench.files.action.refreshFilesExplorer");
}
}, 20);
}
});
}
/**
* Set objectscript.conn.active at WorkspaceFolder level if objectscript.conn
* is defined there, else set it at Workspace level.
*/
function setConnectionState(configName: string, active: boolean) {
const connConfig: vscode.WorkspaceConfiguration = config("", configName);
const target: vscode.ConfigurationTarget = connConfig.inspect("conn").workspaceFolderValue
? vscode.ConfigurationTarget.WorkspaceFolder
: vscode.ConfigurationTarget.Workspace;
const targetConfig: any =
connConfig.inspect("conn").workspaceFolderValue || connConfig.inspect("conn").workspaceValue;
return connConfig.update("conn", { ...targetConfig, active }, target);
}
function languageServer(install = true): vscode.Extension<any> {
let extension = vscode.extensions.getExtension(lsExtensionId);
async function languageServerInstall() {
if (config("ignoreInstallLanguageServer")) {
return;
}
try {
await vscode.commands.executeCommand("extension.open", lsExtensionId);
} catch (ex) {
// Such command do not exists, suppose we are under Theia, it's not possible to install this extension this way
return;
}
await vscode.window
.showInformationMessage(
`Install the [InterSystems Language Server extension](https://marketplace.visualstudio.com/items?itemName=${lsExtensionId}) for improved intellisense and syntax coloring for ObjectScript code.`,
"Install",
"Later"
)
.then(async (action) => {
if (action == "Install") {
await vscode.commands.executeCommand("workbench.extensions.search", `@tag:"intersystems"`).then(null, null);
await vscode.commands.executeCommand("workbench.extensions.installExtension", lsExtensionId);
extension = vscode.extensions.getExtension(lsExtensionId);
}
});
}
if (!extension && install) {
languageServerInstall();
}
return extension;
}
/** Show the proposed API prompt if required */
function proposedApiPrompt(active: boolean, added?: readonly vscode.WorkspaceFolder[]): void {
if (
(added || vscode.workspace.workspaceFolders || []).some((e) => filesystemSchemas.includes(e.uri.scheme)) &&
!active &&
config("showProposedApiPrompt")
) {
// Prompt the user with the proposed api install instructions
vscode.window
.showInformationMessage(
"[Searching across](https://code.visualstudio.com/docs/editor/codebasics#_search-across-files) and [quick opening](https://code.visualstudio.com/docs/getstarted/tips-and-tricks#_quick-open) server-side files requires [VS Code proposed APIs](https://code.visualstudio.com/api/advanced-topics/using-proposed-api). Show the instructions?",
"Yes",
"Later",
"Never"
)
.then(async (action) => {
switch (action) {
case "Yes":
vscode.env.openExternal(
vscode.Uri.parse("https://github.com/intersystems-community/vscode-objectscript#enable-proposed-apis")
);
break;
case "Never":
config().update("showProposedApiPrompt", false, vscode.ConfigurationTarget.Global);
break;
case "Later":
default:
}
});
}
}
/**
* A map of SystemModes for known servers.
* The key is either `serverName`, or `host:port/pathPrefix`, lowercase.
* The value is the value of `^%SYS("SystemMode")`, uppercase.
*/
const systemModes: Map<string, string> = new Map();
/** Output a message notifying the user of the SystemMode of any servers they are connected to. */
async function systemModeWarning(wsFolders: readonly vscode.WorkspaceFolder[]): Promise<void> {
if (!wsFolders || wsFolders.length == 0) return;
for (const wsFolder of wsFolders) {
const api = new AtelierAPI(wsFolder.uri),
mapKey = api.serverId.toLowerCase(),
serverUrl = `${api.config.host}:${api.config.port}${api.config.pathPrefix}`,
serverStr = ![undefined, ""].includes(api.config.serverName)
? `'${api.config.serverName}' (${serverUrl})`
: serverUrl;
if (!api.active) continue; // Skip inactive connections
let systemMode = systemModes.get(mapKey);
if (systemMode == undefined) {
systemMode = await api
.actionQuery("SELECT UPPER(Value) AS SystemMode FROM %Library.Global_Get(?,'^%SYS(\"SystemMode\")')", [api.ns])
.then((data) => data.result.content[0]?.SystemMode ?? "")
.catch(() => ""); // Swallow any errors, which will likely be SQL permissions errors
}
switch (systemMode) {
case "LIVE":
outputChannel.appendLine(
`WARNING: Workspace folder '${wsFolder.name}' is connected to Live System ${serverStr}`
);
outputChannel.show(); // Steal focus because this is an important message
break;
case "TEST":
case "FAILOVER":
outputChannel.appendLine(
`NOTE: Workspace folder '${wsFolder.name}' is connected to ${
systemMode == "TEST" ? "Test" : "Failover"
} System ${serverStr}`
);
outputChannel.show(true);
}
systemModes.set(mapKey, systemMode);
}
}
/**
* Set when clause context keys so the ObjectScript Explorer and
* Projects Explorer views are correctly shown or hidden depending
* on the folders in this workspace
*/
function setExplorerContextKeys(): void {
const wsFolders = vscode.workspace.workspaceFolders ?? [];
// Need to show both views if there are no folders in
// this workspace so the "viewsWelcome" messages are shown
vscode.commands.executeCommand(
"setContext",
"vscode-objectscript.showExplorer",
wsFolders.length == 0 || wsFolders.some((wf) => notIsfs(wf.uri))
);
vscode.commands.executeCommand(
"setContext",
"vscode-objectscript.showProjectsExplorer",
wsFolders.length == 0 || wsFolders.some((wf) => filesystemSchemas.includes(wf.uri.scheme))
);
}
/** The URIs of all classes that have been opened. Used when `objectscript.openClassContracted` is true */
let openedClasses: string[];
// Disposables for language configurations that can be modifed by settings
let macLangConf: vscode.Disposable;
let incLangConf: vscode.Disposable;
let intLangConf: vscode.Disposable;
export async function activate(context: vscode.ExtensionContext): Promise<any> {
if (!packageJson.version.includes("SNAPSHOT")) {
try {
reporter = new TelemetryReporter(extensionId, extensionVersion, aiKey);
} catch (_error) {
reporter = null;
}
}
// workaround for Theia, issue https://github.com/eclipse-theia/theia/issues/8435
workspaceState = {
keys: context.workspaceState.keys,
get: <T>(key: string, defaultValue?: T): T | undefined =>
context.workspaceState.get(key, defaultValue) || defaultValue,
update: (key: string, value: any): Thenable<void> => context.workspaceState.update(key, value),
};
extensionContext = context;
workspaceState.update("workspaceFolder", undefined);
// Get api for servermanager extension
const smExt = vscode.extensions.getExtension(smExtensionId);
if (!smExt.isActive) await smExt.activate();
serverManagerApi = smExt.exports;
documentContentProvider = new DocumentContentProvider();
fileSystemProvider = new FileSystemProvider();
explorerProvider = new ObjectScriptExplorerProvider();
vscode.window.createTreeView("ObjectScriptExplorer", {
treeDataProvider: explorerProvider,
showCollapseAll: true,
canSelectMany: true,
});
projectsExplorerProvider = new ProjectsExplorerProvider();
vscode.window.createTreeView("ObjectScriptProjectsExplorer", {
treeDataProvider: projectsExplorerProvider,
showCollapseAll: true,
canSelectMany: false,
});
posPanel = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Left, 0);
posPanel.command = "vscode-objectscript.jumpToTagAndOffset";
posPanel.show();
panel = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Left, 1);
panel.text = `${PANEL_LABEL}`;
panel.command = "vscode-objectscript.serverActions";
panel.show();
const debugAdapterFactory = new ObjectScriptDebugAdapterDescriptorFactory();
// Show or hide explorer views as needed
setExplorerContextKeys();
// Check one time (flushing cookies) each connection that is used by the workspace.
// This gets any prompting for missing credentials done upfront, for simplicity.
const toCheck = new Map<string, vscode.Uri>();
vscode.workspace.workspaceFolders?.map((workspaceFolder) => {
const uri = workspaceFolder.uri;
const { configName } = connectionTarget(uri);
const conn = config("conn", configName);
// When docker-compose object is defined don't fall back to server name, which may have come from user-level settings
const serverName = notIsfs(uri) && !conn["docker-compose"] ? conn.server : configName;
toCheck.set(serverName, uri);
});
for await (const oneToCheck of toCheck) {
const serverName = oneToCheck[0];
const uri = oneToCheck[1];
try {
try {
// Pass the uri to resolveConnectionSpec so it will fall back to docker-compose logic if required.
// Necessary because we are in our activate method, so its call to the Server Manager API cannot call back to our API to do that.
await resolveConnectionSpec(serverName, uri);
} finally {
await checkConnection(true, uri, true);
}
} catch (_) {
// Ignore any failure
continue;
}
}
xmlContentProvider = new XmlContentProvider();
const documentSelector = (...list) =>
["file", ...schemas].reduce((acc, scheme) => acc.concat(list.map((language) => ({ scheme, language }))), []);
const diagnosticProvider = new ObjectScriptDiagnosticProvider();
// Gather the proposed APIs we will register to use when building with enabledApiProposals != []
const proposed = [
typeof packageJson.enabledApiProposals === "object" &&
packageJson.enabledApiProposals.includes("fileSearchProvider") &&
typeof vscode.workspace.registerFileSearchProvider === "function"
? vscode.workspace.registerFileSearchProvider(FILESYSTEM_SCHEMA, new FileSearchProvider())
: null,
typeof packageJson.enabledApiProposals === "object" &&
packageJson.enabledApiProposals.includes("fileSearchProvider") &&
typeof vscode.workspace.registerFileSearchProvider === "function"
? vscode.workspace.registerFileSearchProvider(FILESYSTEM_READONLY_SCHEMA, new FileSearchProvider())
: null,
typeof packageJson.enabledApiProposals === "object" &&
packageJson.enabledApiProposals.includes("textSearchProvider") &&
typeof vscode.workspace.registerTextSearchProvider === "function"
? vscode.workspace.registerTextSearchProvider(FILESYSTEM_SCHEMA, new TextSearchProvider())
: null,
typeof packageJson.enabledApiProposals === "object" &&
packageJson.enabledApiProposals.includes("textSearchProvider") &&
typeof vscode.workspace.registerTextSearchProvider === "function"
? vscode.workspace.registerTextSearchProvider(FILESYSTEM_READONLY_SCHEMA, new TextSearchProvider())
: null,
].filter(notNull);
if (proposed.length > 0) {
outputChannel.appendLine(`${extensionId} version ${extensionVersion} activating with proposed APIs available.\n`);
}
const languageServerExt =
context.extensionMode && context.extensionMode !== vscode.ExtensionMode.Test ? languageServer() : null;
const noLSsubscriptions: { dispose(): any }[] = [];
if (!languageServerExt) {
if (!config("ignoreInstallLanguageServer")) {
outputChannel.appendLine("The intersystems.language-server extension is not installed or has been disabled.");
outputChannel.show(true);
}
if (vscode.window.activeTextEditor) {
diagnosticProvider.updateDiagnostics(vscode.window.activeTextEditor.document);
}
noLSsubscriptions.push(
vscode.workspace.onDidChangeTextDocument((event) => {
diagnosticProvider.updateDiagnostics(event.document);
}),
vscode.window.onDidChangeActiveTextEditor(async (editor) => {
if (editor) {
diagnosticProvider.updateDiagnostics(editor.document);
}
}),
vscode.languages.registerHoverProvider(
documentSelector(clsLangId, macLangId, intLangId, incLangId),
new ObjectScriptHoverProvider()
),
vscode.languages.registerDocumentFormattingEditProvider(
documentSelector(clsLangId, macLangId, intLangId, incLangId),
new DocumentFormattingEditProvider()
),
vscode.languages.registerDefinitionProvider(
documentSelector(clsLangId, macLangId, intLangId, incLangId),
new ObjectScriptDefinitionProvider()
),
vscode.languages.registerCompletionItemProvider(
documentSelector(clsLangId, macLangId, intLangId, incLangId),
new ObjectScriptCompletionItemProvider(),
"$",
"^",
".",
"#"
),
vscode.languages.registerDocumentSymbolProvider(
documentSelector(clsLangId),
new ObjectScriptClassSymbolProvider()
),
vscode.languages.registerDocumentSymbolProvider(
documentSelector(macLangId, intLangId),
new ObjectScriptRoutineSymbolProvider()
)
);
context.subscriptions.push(...noLSsubscriptions);
} else {
const lsVersion = languageServerExt.packageJSON.version;
// Language Server implements FoldingRangeProvider starting from 1.0.5
if (semver.lt(lsVersion, "1.0.5")) {
context.subscriptions.push(
vscode.languages.registerFoldingRangeProvider(
documentSelector(clsLangId),
new ObjectScriptClassFoldingRangeProvider()
),
vscode.languages.registerFoldingRangeProvider(
documentSelector(macLangId, intLangId),
new ObjectScriptFoldingRangeProvider()
)
);
}
}
openedClasses = workspaceState.get("openedClasses") ?? [];
/** The stringified URIs of all `isfs` documents that are currently open in a UI tab */
const isfsTabs: string[] = [];
// Create this here so we can fire its event
const fileDecorationProvider = new FileDecorationProvider();
// Show the proposed API prompt if required
proposedApiPrompt(proposed.length > 0);
// Warn about SystemMode
systemModeWarning(vscode.workspace.workspaceFolders);
iscIcon = vscode.Uri.joinPath(context.extensionUri, "images", "fileIcon.svg");
// Index documents in all local workspace folders
for (const wf of vscode.workspace.workspaceFolders ?? []) indexWorkspaceFolder(wf);
macLangConf = vscode.languages.setLanguageConfiguration(macLangId, getLanguageConfiguration(macLangId));
incLangConf = vscode.languages.setLanguageConfiguration(incLangId, getLanguageConfiguration(incLangId));
intLangConf = vscode.languages.setLanguageConfiguration(intLangId, getLanguageConfiguration(intLangId));
// Migrate removed importOnSave setting to new, more generic syncLocalChanges
const conf = vscode.workspace.getConfiguration("objectscript");
const importOnSave = conf.inspect("importOnSave");
if (typeof importOnSave.globalValue == "boolean") {
if (!importOnSave.globalValue) {
conf.update("syncLocalChanges", false, vscode.ConfigurationTarget.Global);
}
conf.update("importOnSave", undefined, vscode.ConfigurationTarget.Global);
}
if (typeof importOnSave.workspaceValue == "boolean") {
if (!importOnSave.workspaceValue) {
conf.update("syncLocalChanges", false, vscode.ConfigurationTarget.Workspace);
}
conf.update("importOnSave", undefined, vscode.ConfigurationTarget.Workspace);
}
context.subscriptions.push(
reporter,
panel,
posPanel,
vscode.extensions.onDidChange(async () => {
const languageServerExt2 = languageServer(false);
if (typeof languageServerExt !== typeof languageServerExt2) {
noLSsubscriptions.forEach((event) => {
event.dispose();
});
}
}),
vscode.workspace.onDidChangeTextDocument((event) => {
if (
event.document.uri.scheme == FILESYSTEM_SCHEMA &&
// These two expressions will both be true only for
// the edit that makes a document go from clean to dirty
event.contentChanges.length == 0 &&
event.document.isDirty
) {
fireOtherStudioAction(OtherStudioAction.AttemptedEdit, event.document.uri);
}
if (!event.document.isDirty) {
checkChangedOnServer(currentFile(event.document));
}
if (
[clsLangId, macLangId, intLangId, incLangId].includes(event.document.languageId) &&
notIsfs(event.document.uri)
) {
// Update the local workspace folder index to incorporate this change
updateIndexForDocument(event.document.uri);
}
}),
vscode.window.onDidChangeActiveTextEditor(async (editor) => {
if (vscode.workspace.workspaceFolders && vscode.workspace.workspaceFolders.length > 1) {
const workspaceFolder = currentWorkspaceFolder();
if (workspaceFolder && workspaceFolder !== workspaceState.get<string>("workspaceFolder")) {
await workspaceState.update("workspaceFolder", workspaceFolder);
await checkConnection(false, editor?.document.uri);
}
}
}),
vscode.commands.registerCommand("vscode-objectscript.output", () => {
outputChannel.show(true);
}),
vscode.commands.registerCommand("vscode-objectscript.compile", () => importAndCompile(false)),
vscode.commands.registerCommand("vscode-objectscript.touchBar.compile", () => importAndCompile(false)),
vscode.commands.registerCommand("vscode-objectscript.compileWithFlags", () => importAndCompile(true)),
vscode.commands.registerCommand("vscode-objectscript.compileAll", () => namespaceCompile(false)),
vscode.commands.registerCommand("vscode-objectscript.compileAllWithFlags", () => namespaceCompile(true)),
vscode.commands.registerCommand("vscode-objectscript.refreshLocalFile", async () => {
const file = currentFile();