@kusto/monaco-kusto 10.0.6 → 10.0.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,154 +1,1173 @@
1
- var __assign = (this && this.__assign) || function () {
2
- __assign = Object.assign || function(t) {
3
- for (var s, i = 1, n = arguments.length; i < n; i++) {
4
- s = arguments[i];
5
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
6
- t[p] = s[p];
1
+ /*!-----------------------------------------------------------------------------
2
+ * Copyright (c) Microsoft Corporation. All rights reserved.
3
+ * monaco-kusto version: 10.0.8(134ff03184264a9900737e4b5cf93f69540e1c8e)
4
+ * Released under the MIT license
5
+ * https://https://github.com/Azure/monaco-kusto/blob/master/README.md
6
+ *-----------------------------------------------------------------------------*/
7
+
8
+ import * as monaco from 'monaco-editor/esm/vs/editor/editor.api';
9
+ import * as ls from 'vscode-languageserver-types';
10
+ import debounce from 'lodash-es/debounce';
11
+
12
+ class WorkerManager {
13
+ constructor(_monacoInstance, defaults) {
14
+ this._monacoInstance = _monacoInstance;
15
+ this._defaults = defaults;
16
+ this._worker = null;
17
+ this._idleCheckInterval = self.setInterval(() => this._checkIfIdle(), 30 * 1000);
18
+ this._lastUsedTime = 0;
19
+ this._configChangeListener = this._defaults.onDidChange(() => this._saveStateAndStopWorker());
20
+ }
21
+ _stopWorker() {
22
+ if (this._worker) {
23
+ this._worker.dispose();
24
+ this._worker = null;
25
+ }
26
+ this._client = null;
27
+ }
28
+ _saveStateAndStopWorker() {
29
+ if (!this._worker) {
30
+ return;
31
+ }
32
+ this._worker.getProxy().then(proxy => {
33
+ proxy.getSchema().then(schema => {
34
+ this._storedState = {
35
+ schema: schema
36
+ };
37
+ this._stopWorker();
38
+ });
39
+ });
40
+ }
41
+ dispose() {
42
+ clearInterval(this._idleCheckInterval);
43
+ this._configChangeListener.dispose();
44
+ this._stopWorker();
45
+ }
46
+ _checkIfIdle() {
47
+ if (!this._worker) {
48
+ return;
49
+ }
50
+ const maxIdleTime = this._defaults.getWorkerMaxIdleTime();
51
+ let timePassedSinceLastUsed = Date.now() - this._lastUsedTime;
52
+ if (maxIdleTime > 0 && timePassedSinceLastUsed > maxIdleTime) {
53
+ this._saveStateAndStopWorker();
54
+ }
55
+ }
56
+ _getClient() {
57
+ this._lastUsedTime = Date.now();
58
+
59
+ // Since onDidProvideCompletionItems is not used in web worker, and since functions cannot be trivially serialized (throws exception unable to clone), We remove it here.
60
+ const {
61
+ onDidProvideCompletionItems,
62
+ ...languageSettings
63
+ } = this._defaults.languageSettings;
64
+ if (!this._client) {
65
+ this._worker = this._monacoInstance.editor.createWebWorker({
66
+ // module that exports the create() method and returns a `KustoWorker` instance
67
+ moduleId: 'vs/language/kusto/kustoWorker',
68
+ label: 'kusto',
69
+ // passed in to the create() method
70
+ createData: {
71
+ languageSettings: languageSettings,
72
+ languageId: 'kusto'
7
73
  }
8
- return t;
9
- };
10
- return __assign.apply(this, arguments);
74
+ });
75
+ this._client = this._worker.getProxy().then(proxy => {
76
+ // push state we held onto before killing the client.
77
+ if (this._storedState) {
78
+ return proxy.setSchema(this._storedState.schema).then(() => proxy);
79
+ } else {
80
+ return proxy;
81
+ }
82
+ });
83
+ }
84
+ return this._client;
85
+ }
86
+ getLanguageServiceWorker(...resources) {
87
+ let _client;
88
+ return this._getClient().then(client => {
89
+ _client = client;
90
+ }).then(_ => {
91
+ return this._worker.withSyncedResources(resources);
92
+ }).then(_ => _client);
93
+ }
94
+ }
95
+
96
+ const KustoLanguageDefinition = {
97
+ name: 'kusto',
98
+ mimeTypes: ['text/kusto'],
99
+ displayName: 'Kusto',
100
+ defaultToken: 'invalid',
101
+ brackets: [['[', ']', 'delimiter.square'], ['(', ')', 'delimiter.parenthesis']],
102
+ // types are wrong
103
+ wordDefinition: /(-?\d*\.\d\w*)|([^\`\~\!\#\%\^\&\*\(\)\-\=\+\[\{\]\}\\\|\;\:\'\"\,\.\<\>\/\?\s]+)/g,
104
+ // .slice() call is for creating a shallow copy of the array since bridge.net shoves a $type property on the array which monaco doesn't like.
105
+ // Kusto.Data.IntelliSense.CslCommandParser.PromotedOperatorCommandTokens.slice(0),
106
+ promotedOperatorCommandTokens: ['where', 'count', 'extend', 'join', 'limit', 'order', 'project', 'project-away', 'project-rename', 'project-reorder', 'project-keep', 'render', 'sort', 'summarize', 'distinct', 'take', 'top', 'top-nested', 'top-hitters', 'union', 'mv-expand', 'mv-apply', 'reduce', 'evaluate', 'parse', 'parse-where', 'parse-kv', 'sample', 'sample-distinct', 'make-series', 'getschema', 'serialize', 'invoke', 'as', 'scan'],
107
+ // Kusto.Data.IntelliSense.CslCommandParser.OperatorCommandTokens.slice(0),
108
+ operatorCommandTokens: ['filter', 'fork', 'facet', 'range', 'consume', 'find', 'search', 'print', 'partition', 'lookup', 'where', 'count', 'extend', 'join', 'limit', 'order', 'project', 'project-away', 'project-rename', 'project-reorder', 'project-keep', 'render', 'sort', 'summarize', 'distinct', 'take', 'top', 'top-nested', 'top-hitters', 'union', 'mv-expand', 'mv-apply', 'reduce', 'evaluate', 'parse', 'parse-where', 'parse-kv', 'sample', 'sample-distinct', 'make-series', 'getschema', 'serialize', 'invoke', 'as', 'scan'],
109
+ keywords: ['by', 'on', 'contains', 'notcontains', 'containscs', 'notcontainscs', 'startswith', 'has', 'matches', 'regex', 'true', 'false', 'and', 'or', 'typeof', 'int', 'string', 'date', 'datetime', 'time', 'long', 'real', '​boolean', 'bool'],
110
+ operators: ['+', '-', '*', '/', '>', '<', '==', '<>', '<=', '>=', '~', '!~'],
111
+ builtinFunctions: ['countof', 'bin', 'extentid', 'extract', 'extractjson', 'floor', 'iif', 'isnull', 'isnotnull', 'notnull', 'isempty', 'isnotempty', 'notempty', 'now', 're2', 'strcat', 'strlen', 'toupper', 'tostring', 'count', 'cnt', 'sum', 'min', 'max', 'avg'],
112
+ tokenizer: {
113
+ root: [{
114
+ include: '@whitespace'
115
+ }, {
116
+ include: '@numbers'
117
+ }, {
118
+ include: '@strings'
119
+ }, {
120
+ include: '@dqstrings'
121
+ }, {
122
+ include: '@literals'
123
+ }, {
124
+ include: '@comments'
125
+ }, [/[;,.]/, 'delimiter'], [/[()\[\]]/, '@brackets'], [/[<>=!%&+\-*/|~^]/, 'operator'], [/[\w@#\-$]+/, {
126
+ cases: {
127
+ '@keywords': 'keyword',
128
+ '@promotedOperatorCommandTokens': 'operator.sql',
129
+ '@operatorCommandTokens': 'keyword',
130
+ '@operators': 'operator',
131
+ '@builtinFunctions': 'predefined',
132
+ '@default': 'identifier'
133
+ }
134
+ }]],
135
+ whitespace: [[/\s+/, 'white']],
136
+ comments: [['\\/\\/+.*', 'comment']],
137
+ numbers: [[/0[xX][0-9a-fA-F]*/, 'number'], [/[$][+-]*\d*(\.\d*)?/, 'number'], [/((\d+(\.\d*)?)|(\.\d+))([eE][\-+]?\d+)?/, 'number']],
138
+ strings: [[/H'/, {
139
+ token: 'string.quote',
140
+ bracket: '@open',
141
+ next: '@string'
142
+ }], [/h'/, {
143
+ token: 'string.quote',
144
+ bracket: '@open',
145
+ next: '@string'
146
+ }], [/'/, {
147
+ token: 'string.quote',
148
+ bracket: '@open',
149
+ next: '@string'
150
+ }]],
151
+ string: [[/[^']+/, 'string'], [/''/, 'string'], [/'/, {
152
+ token: 'string.quote',
153
+ bracket: '@close',
154
+ next: '@pop'
155
+ }]],
156
+ dqstrings: [[/H"/, {
157
+ token: 'string.quote',
158
+ bracket: '@open',
159
+ next: '@dqstring'
160
+ }], [/h"/, {
161
+ token: 'string.quote',
162
+ bracket: '@open',
163
+ next: '@dqstring'
164
+ }], [/"/, {
165
+ token: 'string.quote',
166
+ bracket: '@open',
167
+ next: '@dqstring'
168
+ }]],
169
+ dqstring: [[/[^"]+/, 'string'], [/""/, 'string'], [/"/, {
170
+ token: 'string.quote',
171
+ bracket: '@close',
172
+ next: '@pop'
173
+ }]],
174
+ literals: [[/datetime\(\d{4}-\d{2}-\d{2}(\s+\d{2}:\d{2}(:\d{2}(\.\d{0,3})?)?)?\)/, 'number'], [/time\((\d+(s(ec(onds?)?)?|m(in(utes?)?)?|h(ours?)?|d(ays?)?)|(\s*(('[^']+')|("[^"]+"))\s*))\)/, 'number'], [/guid\([\da-fA-F]{8}-[\da-fA-F]{4}-[\da-fA-F]{4}-[\da-fA-F]{4}-[\da-fA-F]{12}\)/, 'number'], [/typeof\((int|string|date|datetime|time|long|real|boolean|bool)\)/, 'number']]
175
+ }
11
176
  };
12
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
13
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
14
- return new (P || (P = Promise))(function (resolve, reject) {
15
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
16
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
17
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
18
- step((generator = generator.apply(thisArg, _arguments || [])).next());
177
+
178
+ // --- diagnostics ---
179
+
180
+ class DiagnosticsAdapter {
181
+ _disposables = [];
182
+ _contentListener = Object.create(null);
183
+ _configurationListener = Object.create(null);
184
+ _schemaListener = Object.create(null);
185
+ _cursorListener = Object.create(null);
186
+ _debouncedValidations = Object.create(null);
187
+ constructor(_monacoInstance, _languageId, _worker, defaults, onSchemaChange) {
188
+ this._monacoInstance = _monacoInstance;
189
+ this._languageId = _languageId;
190
+ this._worker = _worker;
191
+ this.defaults = defaults;
192
+ const onModelAdd = model => {
193
+ let languageId = model.getLanguageId();
194
+ const modelUri = model.uri.toString();
195
+ if (languageId !== this._languageId) {
196
+ return;
197
+ }
198
+ const debouncedValidation = this.getOrCreateDebouncedValidation(model, languageId);
199
+ this._contentListener[modelUri] = model.onDidChangeContent(e => {
200
+ const intervalsToValidate = changeEventToIntervals(e);
201
+ debouncedValidation(intervalsToValidate);
202
+ });
203
+ this._configurationListener[modelUri] = this.defaults.onDidChange(() => {
204
+ self.setTimeout(() => this._doValidate(model, languageId, []), 0);
205
+ });
206
+ this._schemaListener[modelUri] = onSchemaChange(() => {
207
+ self.setTimeout(() => this._doValidate(model, languageId, []), 0);
208
+ });
209
+ };
210
+ const onEditorAdd = editor => {
211
+ const editorId = editor.getId();
212
+ if (!this._cursorListener[editorId]) {
213
+ editor.onDidDispose(() => {
214
+ this._cursorListener[editorId]?.dispose();
215
+ delete this._cursorListener[editorId];
216
+ });
217
+ this._cursorListener[editorId] = editor.onDidChangeCursorSelection(e => {
218
+ const model = editor.getModel();
219
+ const languageId = model.getLanguageId();
220
+ if (languageId !== this._languageId) {
221
+ return;
222
+ }
223
+ const cursorOffset = model.getOffsetAt(e.selection.getPosition());
224
+ const debouncedValidation = this.getOrCreateDebouncedValidation(model, languageId);
225
+ debouncedValidation([{
226
+ start: cursorOffset,
227
+ end: cursorOffset
228
+ }]);
229
+ });
230
+ }
231
+ };
232
+ const onModelRemoved = model => {
233
+ this._monacoInstance.editor.setModelMarkers(model, this._languageId, []);
234
+ let uriStr = model.uri.toString();
235
+ let contentListener = this._contentListener[uriStr];
236
+ if (contentListener) {
237
+ contentListener.dispose();
238
+ delete this._contentListener[uriStr];
239
+ }
240
+ let configurationListener = this._configurationListener[uriStr];
241
+ if (configurationListener) {
242
+ configurationListener.dispose();
243
+ delete this._configurationListener[uriStr];
244
+ }
245
+ let schemaListener = this._schemaListener[uriStr];
246
+ if (schemaListener) {
247
+ schemaListener.dispose();
248
+ delete this._schemaListener[uriStr];
249
+ }
250
+ let debouncedValidation = this._debouncedValidations[uriStr];
251
+ if (debouncedValidation) {
252
+ debouncedValidation.cancel();
253
+ delete this._debouncedValidations[uriStr];
254
+ }
255
+ };
256
+ if (this.defaults.languageSettings.enableQuickFixes) {
257
+ this._disposables.push(monaco.languages.registerCodeActionProvider(this._languageId, {
258
+ provideCodeActions: async (model, range, context, _token) => {
259
+ const startOffset = model.getOffsetAt(range.getStartPosition());
260
+ const endOffset = model.getOffsetAt(range.getEndPosition());
261
+ // We want to show the quick fix option only if we have markers in our selected range
262
+ const showQuickFix = context.markers.length > 0;
263
+ const actions = await this.getMonacoCodeActions(model, startOffset, endOffset, showQuickFix);
264
+ return {
265
+ actions,
266
+ dispose: () => {}
267
+ };
268
+ }
269
+ }));
270
+ }
271
+ this._disposables.push(this._monacoInstance.editor.onDidCreateEditor(onEditorAdd));
272
+ this._disposables.push(this._monacoInstance.editor.onDidCreateModel(onModelAdd));
273
+ this._disposables.push(this._monacoInstance.editor.onWillDisposeModel(onModelRemoved));
274
+ this._disposables.push(this._monacoInstance.editor.onDidChangeModelLanguage(event => {
275
+ onModelRemoved(event.model);
276
+ onModelAdd(event.model);
277
+ }));
278
+ this._disposables.push({
279
+ dispose: () => {
280
+ for (let key in this._contentListener) {
281
+ this._contentListener[key].dispose();
282
+ }
283
+ for (let key in this._cursorListener) {
284
+ this._cursorListener[key].dispose();
285
+ }
286
+ for (let key in this._debouncedValidations) {
287
+ this._debouncedValidations[key].cancel();
288
+ }
289
+ }
19
290
  });
20
- };
21
- var __generator = (this && this.__generator) || function (thisArg, body) {
22
- var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
23
- return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
24
- function verb(n) { return function (v) { return step([n, v]); }; }
25
- function step(op) {
26
- if (f) throw new TypeError("Generator is already executing.");
27
- while (g && (g = 0, op[0] && (_ = 0)), _) try {
28
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
29
- if (y = 0, t) op = [op[0] & 2, t.value];
30
- switch (op[0]) {
31
- case 0: case 1: t = op; break;
32
- case 4: _.label++; return { value: op[1], done: false };
33
- case 5: _.label++; y = op[1]; op = [0]; continue;
34
- case 7: op = _.ops.pop(); _.trys.pop(); continue;
35
- default:
36
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
37
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
38
- if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
39
- if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
40
- if (t[2]) _.ops.pop();
41
- _.trys.pop(); continue;
42
- }
43
- op = body.call(thisArg, _);
44
- } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
45
- if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
291
+ this._monacoInstance.editor.getModels().forEach(onModelAdd);
292
+ this._monacoInstance.editor.getEditors().forEach(onEditorAdd);
293
+ }
294
+ async getMonacoCodeActions(model, startOffset, endOffset, enableQuickFix) {
295
+ const actions = [];
296
+ const worker = await this._worker(model.uri);
297
+ const resource = model.uri;
298
+ const codeActions = await worker.getResultActions(resource.toString(), startOffset, endOffset);
299
+ for (let i = 0; i < codeActions.length; i++) {
300
+ const codeAction = codeActions[i];
301
+ if (codeAction.kind.includes('Extract Function')) {
302
+ // Ignore extract function actions for now since they are buggy currently
303
+ continue;
304
+ }
305
+ const codeActionKind = this.defaults.languageSettings.quickFixCodeActions?.find(actionKind => codeAction.kind.includes(actionKind)) ? 'quickfix' : 'custom';
306
+ if (codeActionKind === 'quickfix' && !enableQuickFix) {
307
+ return;
308
+ }
309
+ const changes = codeAction.changes;
310
+ const edits = changes.map(change => {
311
+ const startPosition = model.getPositionAt(change.start);
312
+ const endPosition = model.getPositionAt(change.start + change.deleteLength);
313
+ return {
314
+ resource: model.uri,
315
+ textEdit: {
316
+ range: {
317
+ startLineNumber: startPosition.lineNumber,
318
+ startColumn: startPosition.column,
319
+ endLineNumber: endPosition.lineNumber,
320
+ endColumn: endPosition.column
321
+ },
322
+ text: change.insertText ?? ''
323
+ }
324
+ };
325
+ });
326
+ actions.push({
327
+ title: codeAction.title,
328
+ diagnostics: [],
329
+ kind: codeActionKind,
330
+ edit: {
331
+ edits: [...edits]
332
+ }
333
+ });
334
+ }
335
+ return actions;
336
+ }
337
+ getOrCreateDebouncedValidation(model, languageId) {
338
+ const modelUri = model.uri.toString();
339
+ if (!this._debouncedValidations[modelUri]) {
340
+ this._debouncedValidations[modelUri] = debounce(intervals => this._doValidate(model, languageId, intervals), 500);
341
+ }
342
+ return this._debouncedValidations[modelUri];
343
+ }
344
+ dispose() {
345
+ this._disposables.forEach(d => d && d.dispose());
346
+ this._disposables = [];
347
+ }
348
+ _doValidate(model, languageId, intervals) {
349
+ if (model.isDisposed()) {
350
+ return;
46
351
  }
352
+ const resource = model.uri;
353
+ const versionNumberBefore = model.getVersionId();
354
+ this._worker(resource).then(worker => {
355
+ return worker.doValidation(resource.toString(), intervals);
356
+ }).then(diagnostics => {
357
+ const newModel = this._monacoInstance.editor.getModel(resource);
358
+ const versionId = newModel.getVersionId();
359
+ if (versionId !== versionNumberBefore) {
360
+ return;
361
+ }
362
+ const markers = diagnostics.map(d => toDiagnostics(resource, d));
363
+ let model = this._monacoInstance.editor.getModel(resource);
364
+ let oldDecorations = model.getAllDecorations().filter(decoration => decoration.options.className == 'squiggly-error').map(decoration => decoration.id);
365
+ if (model && model.getLanguageId() === languageId) {
366
+ const syntaxErrorAsMarkDown = this.defaults.languageSettings.syntaxErrorAsMarkDown;
367
+ if (!syntaxErrorAsMarkDown || !syntaxErrorAsMarkDown.enableSyntaxErrorAsMarkDown) {
368
+ // Remove previous syntax error decorations and set the new markers (for example, when disabling syntaxErrorAsMarkDown after it was enabled)
369
+ model.deltaDecorations(oldDecorations, []);
370
+ this._monacoInstance.editor.setModelMarkers(model, languageId, markers);
371
+ } else {
372
+ // Add custom popup for syntax error: icon, header and message as markdown
373
+ const header = syntaxErrorAsMarkDown.header ? `**${syntaxErrorAsMarkDown.header}** \n\n` : '';
374
+ const icon = syntaxErrorAsMarkDown.icon ? `![](${syntaxErrorAsMarkDown.icon})` : '';
375
+ const popupErrorHoverHeaderMessage = `${icon} ${header}`;
376
+ const newDecorations = markers.map(marker => {
377
+ return {
378
+ range: {
379
+ startLineNumber: marker.startLineNumber,
380
+ startColumn: marker.startColumn,
381
+ endLineNumber: marker.endLineNumber,
382
+ endColumn: marker.endColumn
383
+ },
384
+ options: {
385
+ hoverMessage: {
386
+ value: popupErrorHoverHeaderMessage + marker.message
387
+ },
388
+ className: 'squiggly-error',
389
+ // monaco syntax error style (red underline)
390
+ zIndex: 100,
391
+ // This message will be the upper most mesage in the popup
392
+ overviewRuler: {
393
+ // The color indication on the right ruler
394
+ color: 'rgb(255, 18, 18, 0.7)',
395
+ position: monaco.editor.OverviewRulerLane.Right
396
+ },
397
+ minimap: {
398
+ color: 'rgb(255, 18, 18, 0.7)',
399
+ position: monaco.editor.MinimapPosition.Inline
400
+ }
401
+ }
402
+ };
403
+ });
404
+ const oldMarkers = monaco.editor.getModelMarkers({
405
+ owner: languageId,
406
+ resource: resource
407
+ });
408
+ if (oldMarkers && oldMarkers.length > 0) {
409
+ // In case there were previous markers, remove their decorations (for example, when enabling syntaxErrorAsMarkDown after it was disabled)
410
+ oldDecorations = [];
411
+ // Remove previous markers
412
+ this._monacoInstance.editor.setModelMarkers(model, languageId, []);
413
+ }
414
+
415
+ // Remove previous syntax error decorations and set the new decorations
416
+ model.deltaDecorations(oldDecorations, newDecorations);
417
+ }
418
+ }
419
+ }).then(undefined, err => {
420
+ console.error(err);
421
+ });
422
+ }
423
+ }
424
+ function changeEventToIntervals(e) {
425
+ return e.changes.map(change => ({
426
+ start: change.rangeOffset,
427
+ end: change.rangeOffset + change.text.length
428
+ }));
429
+ }
430
+ function toSeverity(lsSeverity) {
431
+ switch (lsSeverity) {
432
+ case ls.DiagnosticSeverity.Error:
433
+ return monaco.MarkerSeverity.Error;
434
+ case ls.DiagnosticSeverity.Warning:
435
+ return monaco.MarkerSeverity.Warning;
436
+ case ls.DiagnosticSeverity.Information:
437
+ return monaco.MarkerSeverity.Info;
438
+ case ls.DiagnosticSeverity.Hint:
439
+ return monaco.MarkerSeverity.Hint;
440
+ default:
441
+ return monaco.MarkerSeverity.Info;
442
+ }
443
+ }
444
+ function toDiagnostics(resource, diag) {
445
+ let code = typeof diag.code === 'number' ? String(diag.code) : diag.code;
446
+ return {
447
+ severity: toSeverity(diag.severity),
448
+ startLineNumber: diag.range.start.line + 1,
449
+ startColumn: diag.range.start.character + 1,
450
+ endLineNumber: diag.range.end.line + 1,
451
+ endColumn: diag.range.end.character + 1,
452
+ message: diag.message,
453
+ code: code,
454
+ source: diag.source
455
+ };
456
+ }
457
+ /**
458
+ * Copy of Kusto.Language.Editor.ClassificationKind we don't have to depend on it in this file
459
+ */
460
+ const ClassificationKind = {
461
+ PlainText: 0,
462
+ Comment: 1,
463
+ Punctuation: 2,
464
+ Directive: 3,
465
+ Literal: 4,
466
+ StringLiteral: 5,
467
+ Type: 6,
468
+ Column: 7,
469
+ Table: 8,
470
+ Database: 9,
471
+ Function: 10,
472
+ Parameter: 11,
473
+ Variable: 12,
474
+ Identifier: 13,
475
+ ClientParameter: 14,
476
+ QueryParameter: 15,
477
+ ScalarOperator: 16,
478
+ MathOperator: 17,
479
+ QueryOperator: 18,
480
+ Command: 19,
481
+ Keyword: 20,
482
+ MaterializedView: 21,
483
+ SchemaMember: 22,
484
+ SignatureParameter: 23,
485
+ Option: 24
47
486
  };
48
- import * as monaco from 'monaco-editor/esm/vs/editor/editor.api';
49
- import { WorkerManager } from './workerManager';
50
- import { KustoLanguageDefinition } from './languageService/kustoMonarchLanguageDefinition';
51
- import * as languageFeatures from './languageFeatures';
52
- var kustoWorker;
53
- var resolveWorker;
54
- var rejectWorker;
55
- var workerPromise = new Promise(function (resolve, reject) {
56
- resolveWorker = resolve;
57
- rejectWorker = reject;
58
- });
487
+ const ClassificationKindNames = {};
488
+ for (const [key, value] of Object.entries(ClassificationKind)) {
489
+ ClassificationKindNames[value] = key;
490
+ }
491
+
492
+ // commented here is the color definitions are were defined by v1 intellisense terminology:
493
+ // { token: 'comment', foreground: '008000' }, // CommentToken Green
494
+ // { token: 'variable.predefined', foreground: '800080' }, // CalculatedColumnToken Purple
495
+ // { token: 'function', foreground: '0000FF' }, // FunctionNameToken Blue
496
+ // { token: 'operator.sql', foreground: 'FF4500' }, // OperatorToken OrangeRed (now changed to darker color CC3700 because wasn't accessible)
497
+ // { token: 'string', foreground: 'B22222' }, // StringLiteralToken Firebrick
498
+ // { token: 'operator.scss', foreground: '0000FF' }, // SubOperatorToken Blue
499
+ // { token: 'variable', foreground: 'C71585' }, // TableColumnToken MediumVioletRed
500
+ // { token: 'variable.parameter', foreground: '9932CC' }, // TableToken DarkOrchid
501
+ // { token: '', foreground: '000000' }, // UnknownToken, PlainTextToken Black
502
+ // { token: 'type', foreground: '0000FF' }, // DataTypeToken Blue
503
+ // { token: 'tag', foreground: '0000FF' }, // ControlCommandToken Blue
504
+ // { token: 'annotation', foreground: '2B91AF' }, // QueryParametersToken FF2B91AF
505
+ // { token: 'keyword', foreground: '0000FF' }, // CslCommandToken, PluginToken Blue
506
+ // { token: 'number', foreground: '191970' }, // LetVariablesToken MidnightBlue
507
+ // { token: 'annotation', foreground: '9400D3' }, // ClientDirectiveToken DarkViolet
508
+ // { token: 'invalid', background: 'cd3131' },
509
+ const classificationToColorLight = {
510
+ Column: 'C71585',
511
+ Comment: '008000',
512
+ Database: 'C71585',
513
+ Function: '0000FF',
514
+ Identifier: '000000',
515
+ Keyword: '0000FF',
516
+ Literal: 'B22222',
517
+ ScalarOperator: '0000FF',
518
+ MaterializedView: 'C71585',
519
+ MathOperator: '000000',
520
+ Command: '0000FF',
521
+ Parameter: '2B91AF',
522
+ PlainText: '000000',
523
+ Punctuation: '000000',
524
+ QueryOperator: 'CC3700',
525
+ QueryParameter: 'CC3700',
526
+ StringLiteral: 'B22222',
527
+ Table: 'C71585',
528
+ Type: '0000FF',
529
+ Variable: '191970',
530
+ Directive: '9400D3',
531
+ ClientParameter: 'b5cea8',
532
+ SchemaMember: 'C71585',
533
+ SignatureParameter: '2B91AF',
534
+ Option: '000000'
535
+ };
536
+ const classificationToColorDark = {
537
+ Column: '4ec9b0',
538
+ Comment: '6A9B34',
539
+ Database: 'c586c0',
540
+ Function: 'dcdcaa',
541
+ Identifier: 'd4d4d4',
542
+ Keyword: '569cd6',
543
+ Literal: 'ce9178',
544
+ ScalarOperator: '569cd6',
545
+ MaterializedView: 'c586c0',
546
+ MathOperator: 'd4d4d4',
547
+ Command: 'd4d4d4',
548
+ Parameter: '2B91AF',
549
+ PlainText: 'd4d4d4',
550
+ Punctuation: 'd4d4d4',
551
+ QueryOperator: '9cdcfe',
552
+ QueryParameter: '9cdcfe',
553
+ StringLiteral: 'ce9178',
554
+ Table: 'c586c0',
555
+ Type: '569cd6',
556
+ Variable: 'd7ba7d',
557
+ Directive: 'b5cea8',
558
+ ClientParameter: 'b5cea8',
559
+ SchemaMember: '4ec9b0',
560
+ SignatureParameter: '2B91AF',
561
+ Option: 'd4d4d4'
562
+ };
563
+ class ColorizationAdapter {
564
+ _disposables = [];
565
+ _contentListener = Object.create(null);
566
+ _configurationListener = Object.create(null);
567
+ _schemaListener = Object.create(null);
568
+ decorations = [];
569
+ constructor(_monacoInstance, _languageId, _worker, defaults, onSchemaChange) {
570
+ this._monacoInstance = _monacoInstance;
571
+ this._languageId = _languageId;
572
+ this._worker = _worker;
573
+ injectCss();
574
+ const onModelAdd = model => {
575
+ let languageId = model.getLanguageId();
576
+ if (languageId !== this._languageId) {
577
+ return;
578
+ }
579
+ const debouncedColorization = debounce(intervals => this._doColorization(model, languageId, intervals), 500);
580
+ this._contentListener[model.uri.toString()] = model.onDidChangeContent(e => {
581
+ // Changes are represented as a range in doc before change, plus the text that it was replaced with.
582
+ // We are interested in the range _after_ the change (since that's what we need to colorize).
583
+ // following logic calculates that.
584
+ const intervalsToColorize = changeEventToIntervals(e);
585
+ debouncedColorization(intervalsToColorize);
586
+ });
587
+ this._configurationListener[model.uri.toString()] = defaults.onDidChange(() => {
588
+ self.setTimeout(() => this._doColorization(model, languageId, []), 0);
589
+ });
590
+ this._schemaListener[model.uri.toString()] = onSchemaChange(() => {
591
+ self.setTimeout(() => this._doColorization(model, languageId, []), 0);
592
+ });
593
+ };
594
+ const onModelRemoved = model => {
595
+ model.deltaDecorations(this.decorations, []);
596
+ let uriStr = model.uri.toString();
597
+ let contentListener = this._contentListener[uriStr];
598
+ if (contentListener) {
599
+ contentListener.dispose();
600
+ delete this._contentListener[uriStr];
601
+ }
602
+ let configurationListener = this._configurationListener[uriStr];
603
+ if (configurationListener) {
604
+ configurationListener.dispose();
605
+ delete this._configurationListener[uriStr];
606
+ }
607
+ let schemaListener = this._configurationListener[uriStr];
608
+ if (schemaListener) {
609
+ schemaListener.dispose();
610
+ delete this._schemaListener[uriStr];
611
+ }
612
+ };
613
+ this._disposables.push(this._monacoInstance.editor.onDidCreateModel(onModelAdd));
614
+ this._disposables.push(this._monacoInstance.editor.onWillDisposeModel(onModelRemoved));
615
+ this._disposables.push(this._monacoInstance.editor.onDidChangeModelLanguage(event => {
616
+ onModelRemoved(event.model);
617
+ onModelAdd(event.model);
618
+ }));
619
+ this._disposables.push({
620
+ dispose: () => {
621
+ for (let key in this._contentListener) {
622
+ this._contentListener[key].dispose();
623
+ }
624
+ }
625
+ });
626
+ this._monacoInstance.editor.getModels().forEach(onModelAdd);
627
+ }
628
+ dispose() {
629
+ this._disposables.forEach(d => d && d.dispose());
630
+ this._disposables = [];
631
+ }
632
+
633
+ /**
634
+ * Return true if the range doesn't intersect any of the line ranges.
635
+ * @param range monaco.Range
636
+ * @param impactedLineRanges an array of line ranges
637
+ */
638
+ _rangeDoesNotIntersectAny(range, impactedLineRanges) {
639
+ return impactedLineRanges.every(lineRange => range.startLineNumber > lineRange.lastImpactedLine || range.endLineNumber < lineRange.firstImpactedLine);
640
+ }
641
+ _doColorization(model, languageId, intervals) {
642
+ if (model.isDisposed()) {
643
+ return;
644
+ }
645
+ const resource = model.uri;
646
+ const versionNumberBeforeColorization = model.getVersionId();
647
+ this._worker(resource).then(worker => {
648
+ return worker.doColorization(resource.toString(), intervals);
649
+ }).then(colorizationRanges => {
650
+ const newModel = this._monacoInstance.editor.getModel(model.uri);
651
+ const versionId = newModel.getVersionId();
652
+
653
+ // don't colorize an older version of the document.
654
+ if (versionId !== versionNumberBeforeColorization) {
655
+ return;
656
+ }
657
+ const decorationRanges = colorizationRanges.map(colorizationRange => {
658
+ const decorations = colorizationRange.classifications.map(classification => toDecoration(model, classification))
659
+ // The following line will prevent things that aren't going to be colorized anyway to get a CSS class.
660
+ // This will prevent the case where the non-semantic colorizer already figured out that a keyword needs
661
+ // to be colorized, but the outdated semantic colorizer still thinks it's a plain text and wants it colored
662
+ // in black.
663
+ .filter(d => d.options.inlineClassName !== 'PlainText' && d.options.inlineClassName != 'Identifier');
664
+ const firstImpactedLine = model.getPositionAt(colorizationRange.absoluteStart).lineNumber;
665
+ const endPosition = model.getPositionAt(colorizationRange.absoluteEnd);
666
+
667
+ // A token that ends in the first column of the next line is not considered to be part of that line.
668
+ const lastImpactedLine = endPosition.column == 1 && endPosition.lineNumber > 1 ? endPosition.lineNumber - 1 : endPosition.lineNumber;
669
+ return {
670
+ decorations,
671
+ firstImpactedLine,
672
+ lastImpactedLine
673
+ };
674
+ });
675
+
676
+ // Compute the previous decorations we want to replace with the new ones.
677
+ const oldDecorations = decorationRanges.map(range => model.getLinesDecorations(range.firstImpactedLine, range.lastImpactedLine).filter(d => classificationToColorLight[d.options.inlineClassName]) // Don't delete any other decorations
678
+ .map(d => d.id)).reduce((prev, curr) => prev.concat(curr), []);
679
+
680
+ // Flatten decoration groups to an array of decorations
681
+ const newDecorations = decorationRanges.reduce((prev, next) => prev.concat(next.decorations), []);
682
+ if (model && model.getLanguageId() === languageId) {
683
+ this.decorations = model.deltaDecorations(oldDecorations, newDecorations);
684
+ }
685
+ }).then(undefined, err => {
686
+ console.error(err);
687
+ });
688
+ }
689
+ }
690
+
59
691
  /**
60
- * Called when Kusto language is first needed (a model has the language set)
61
- * @param defaults
692
+ * Generates a mapping between ClassificationKind and color.
693
+ */
694
+ function getClassificationColorTriplets() {
695
+ const result = Object.keys(ClassificationKind).map(key => ({
696
+ classification: key,
697
+ colorLight: classificationToColorLight[key],
698
+ colorDark: classificationToColorDark[key]
699
+ }));
700
+ return result;
701
+ }
702
+
703
+ /**
704
+ * Returns a string which is a css describing all tokens and their colors.
705
+ * looks a little bit something like this:
706
+ *
707
+ * .vs .Literal {color: '#000000';} .vs-dark .Literal {color: '#FFFFFF';}
708
+ * .vs .Comment {color: '#111111';} .vs-dark .Comment {color: '#EEEEEE';}
62
709
  */
63
- export function setupMode(defaults, monacoInstance) {
64
- var _this = this;
65
- var onSchemaChange = new monaco.Emitter();
66
- // TODO: when should we dispose of these? seems like monaco-css and monaco-typescript don't dispose of these.
67
- var disposables = [];
68
- var monarchTokensProvider;
69
- var client = new WorkerManager(monacoInstance, defaults);
70
- disposables.push(client);
71
- var workerAccessor = function (first) {
72
- var more = [];
73
- for (var _i = 1; _i < arguments.length; _i++) {
74
- more[_i - 1] = arguments[_i];
710
+ function getCssForClassification() {
711
+ const classificationColorTriplets = getClassificationColorTriplets();
712
+ const cssInnerHtml = classificationColorTriplets.map(pair => `.vs .${pair.classification} {color: #${pair.colorLight};} .vs-dark .${pair.classification} {color: #${pair.colorDark};}`).join('\n');
713
+ return cssInnerHtml;
714
+ }
715
+
716
+ /**
717
+ * Inject a CSS sheet to the head of document, coloring kusto elements by classification.
718
+ * TODO: make idempotent
719
+ */
720
+ function injectCss() {
721
+ const container = document.getElementsByTagName('head')[0];
722
+ var style = document.createElement('style');
723
+ style.type = 'text/css';
724
+ style.media = 'screen';
725
+ container.appendChild(style);
726
+ style.innerHTML = getCssForClassification();
727
+ }
728
+ function toDecoration(model, classification) {
729
+ const start = model.getPositionAt(classification.start);
730
+ const end = model.getPositionAt(classification.start + classification.length);
731
+ const range = new monaco.Range(start.lineNumber, start.column, end.lineNumber, end.column);
732
+ const inlineClassName = ClassificationKindNames[classification.kind];
733
+ return {
734
+ range,
735
+ options: {
736
+ inlineClassName,
737
+ stickiness: monaco.editor.TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges
738
+ }
739
+ };
740
+ }
741
+ // --- completion ------
742
+
743
+ function fromPosition(position) {
744
+ if (!position) {
745
+ return void 0;
746
+ }
747
+ return {
748
+ character: position.column - 1,
749
+ line: position.lineNumber - 1
750
+ };
751
+ }
752
+ function fromRange(range) {
753
+ if (!range) {
754
+ return void 0;
755
+ }
756
+ return {
757
+ start: fromPosition(range.getStartPosition()),
758
+ end: fromPosition(range.getEndPosition())
759
+ };
760
+ }
761
+ function toRange(range) {
762
+ if (!range) {
763
+ return void 0;
764
+ }
765
+ return new monaco.Range(range.start.line + 1, range.start.character + 1, range.end.line + 1, range.end.character + 1);
766
+ }
767
+ function toCompletionItemKind(kind) {
768
+ let mItemKind = monaco.languages.CompletionItemKind;
769
+ switch (kind) {
770
+ case ls.CompletionItemKind.Text:
771
+ return mItemKind.Text;
772
+ case ls.CompletionItemKind.Method:
773
+ return mItemKind.Method;
774
+ case ls.CompletionItemKind.Function:
775
+ return mItemKind.Function;
776
+ case ls.CompletionItemKind.Constructor:
777
+ return mItemKind.Constructor;
778
+ case ls.CompletionItemKind.Field:
779
+ return mItemKind.Field;
780
+ case ls.CompletionItemKind.Variable:
781
+ return mItemKind.Variable;
782
+ case ls.CompletionItemKind.Class:
783
+ return mItemKind.Class;
784
+ case ls.CompletionItemKind.Interface:
785
+ return mItemKind.Interface;
786
+ case ls.CompletionItemKind.Module:
787
+ return mItemKind.Module;
788
+ case ls.CompletionItemKind.Property:
789
+ return mItemKind.Property;
790
+ case ls.CompletionItemKind.Unit:
791
+ return mItemKind.Unit;
792
+ case ls.CompletionItemKind.Value:
793
+ return mItemKind.Value;
794
+ case ls.CompletionItemKind.Enum:
795
+ return mItemKind.Enum;
796
+ case ls.CompletionItemKind.Keyword:
797
+ return mItemKind.Keyword;
798
+ case ls.CompletionItemKind.Snippet:
799
+ return mItemKind.Snippet;
800
+ case ls.CompletionItemKind.Color:
801
+ return mItemKind.Color;
802
+ case ls.CompletionItemKind.File:
803
+ return mItemKind.File;
804
+ case ls.CompletionItemKind.Reference:
805
+ return mItemKind.Reference;
806
+ }
807
+ return mItemKind.Property;
808
+ }
809
+ function toTextEdit(textEdit) {
810
+ if (!textEdit) {
811
+ return void 0;
812
+ }
813
+ return {
814
+ range: toRange(textEdit.range),
815
+ text: textEdit.newText
816
+ };
817
+ }
818
+ const DEFAULT_DOCS_BASE_URL = 'https://learn.microsoft.com/azure/data-explorer/kusto/query';
819
+ class CompletionAdapter {
820
+ constructor(_worker, languageSettings) {
821
+ this._worker = _worker;
822
+ this.languageSettings = languageSettings;
823
+ }
824
+ get triggerCharacters() {
825
+ return [' '];
826
+ }
827
+ provideCompletionItems(model, position, context, token) {
828
+ const wordInfo = model.getWordUntilPosition(position);
829
+ const wordRange = new monaco.Range(position.lineNumber, wordInfo.startColumn, position.lineNumber, wordInfo.endColumn);
830
+ const resource = model.uri;
831
+ const onDidProvideCompletionItems = this.languageSettings.onDidProvideCompletionItems;
832
+ return this._worker(resource).then(worker => {
833
+ return worker.doComplete(resource.toString(), fromPosition(position));
834
+ }).then(info => onDidProvideCompletionItems ? onDidProvideCompletionItems(info) : info).then(info => {
835
+ if (!info) {
836
+ return;
837
+ }
838
+ let items = info.items.map(entry => {
839
+ let item = {
840
+ label: entry.label,
841
+ insertText: entry.insertText,
842
+ sortText: entry.sortText,
843
+ filterText: entry.filterText,
844
+ // TODO: Is this cast safe?
845
+ documentation: this.formatDocLink(entry.documentation?.value),
846
+ detail: entry.detail,
847
+ range: wordRange,
848
+ kind: toCompletionItemKind(entry.kind)
849
+ };
850
+ if (entry.textEdit) {
851
+ // TODO: Where is the "range" property coming from?
852
+ item.range = toRange(entry.textEdit.range);
853
+ item.insertText = entry.textEdit.newText;
75
854
  }
76
- var augmentedSetSchema = function (schema, worker) { return __awaiter(_this, void 0, void 0, function () {
77
- var workerPromise;
78
- return __generator(this, function (_a) {
79
- switch (_a.label) {
80
- case 0:
81
- workerPromise = worker.setSchema(schema);
82
- return [4 /*yield*/, workerPromise.then(function () {
83
- onSchemaChange.fire(schema);
84
- })];
85
- case 1:
86
- _a.sent();
87
- return [2 /*return*/];
88
- }
89
- });
90
- }); };
91
- var worker = client.getLanguageServiceWorker.apply(client, [first].concat(more));
92
- return worker.then(function (worker) { return (__assign(__assign({}, worker), { setSchema: function (schema) { return augmentedSetSchema(schema, worker); }, setSchemaFromShowSchema: function (schema, connection, database, globalScalarParameters, globalTabularParameters) {
93
- return __awaiter(this, void 0, void 0, function () {
94
- return __generator(this, function (_a) {
95
- switch (_a.label) {
96
- case 0: return [4 /*yield*/, worker.normalizeSchema(schema, connection, database).then(function (schema) {
97
- if (globalScalarParameters || globalTabularParameters) {
98
- schema = __assign(__assign({}, schema), { globalScalarParameters: globalScalarParameters, globalTabularParameters: globalTabularParameters });
99
- }
100
- augmentedSetSchema(schema, worker);
101
- })];
102
- case 1:
103
- _a.sent();
104
- return [2 /*return*/];
105
- }
106
- });
107
- });
108
- } })); });
109
- };
110
- var language = 'kusto';
111
- disposables.push(monacoInstance.languages.registerCompletionItemProvider(language, new languageFeatures.CompletionAdapter(workerAccessor, defaults.languageSettings)));
112
- // Monaco tokenization runs in main thread so we're using a quick schema-unaware tokenization.
113
- // a web worker will run semantic colorization in the background (ColorizationAdapter).
114
- if (defaults.languageSettings.useTokenColorization) {
115
- monarchTokensProvider = monacoInstance.languages.setMonarchTokensProvider(language, KustoLanguageDefinition);
116
- }
117
- // listen to configuration changes and if we're switching from semantic to monarch colorization, do the switch.
118
- defaults.onDidChange(function (e) {
119
- if (!e.languageSettings.useTokenColorization && monarchTokensProvider !== undefined) {
120
- monarchTokensProvider.dispose();
121
- monarchTokensProvider = undefined;
855
+ if (entry.insertTextFormat === ls.InsertTextFormat.Snippet) {
856
+ item.insertTextRules = monaco.languages.CompletionItemInsertTextRule.InsertAsSnippet;
122
857
  }
123
- if (e.languageSettings.useTokenColorization && monarchTokensProvider == undefined) {
124
- monarchTokensProvider = monacoInstance.languages.setMonarchTokensProvider(language, KustoLanguageDefinition);
858
+ return item;
859
+ });
860
+ return {
861
+ isIncomplete: info.isIncomplete,
862
+ suggestions: items
863
+ };
864
+ });
865
+ }
866
+ formatDocLink(docString) {
867
+ // If the docString is empty, we want to return undefined to prevent an empty documentation popup.
868
+ if (!docString) {
869
+ return undefined;
870
+ }
871
+ const {
872
+ documentationBaseUrl = DEFAULT_DOCS_BASE_URL,
873
+ documentationSuffix
874
+ } = this.languageSettings;
875
+ const urisProxy = new Proxy({}, {
876
+ get(_target, prop, _receiver) {
877
+ // The link comes with a postfix of ".md" that we want to remove
878
+ let url = prop.toString().replace('.md', '');
879
+ // Sometimes we get the link as a full URL. For example in the main doc link of the item
880
+ if (!url.startsWith('https')) {
881
+ url = `${documentationBaseUrl}/${url}`;
125
882
  }
883
+ const monacoUri = monaco.Uri.parse(url);
884
+ if (documentationSuffix) {
885
+ // We need to override the toString method to add the suffix, otherwise it gets encoded and page doesn't open
886
+ monacoUri.toString = () => url + documentationSuffix;
887
+ }
888
+ return monacoUri;
889
+ }
126
890
  });
127
- disposables.push(new languageFeatures.DiagnosticsAdapter(monacoInstance, language, workerAccessor, defaults, onSchemaChange.event));
128
- disposables.push(new languageFeatures.ColorizationAdapter(monacoInstance, language, workerAccessor, defaults, onSchemaChange.event));
129
- disposables.push(monacoInstance.languages.registerDocumentRangeFormattingEditProvider(language, new languageFeatures.FormatAdapter(workerAccessor)));
130
- disposables.push(monacoInstance.languages.registerFoldingRangeProvider(language, new languageFeatures.FoldingAdapter(workerAccessor)));
131
- disposables.push(monacoInstance.languages.registerDefinitionProvider(language, new languageFeatures.DefinitionAdapter(workerAccessor)));
132
- disposables.push(monacoInstance.languages.registerRenameProvider(language, new languageFeatures.RenameAdapter(workerAccessor)));
133
- disposables.push(monacoInstance.languages.registerReferenceProvider(language, new languageFeatures.ReferenceAdapter(workerAccessor)));
134
- if (defaults.languageSettings.enableHover) {
135
- disposables.push(monacoInstance.languages.registerHoverProvider(language, new languageFeatures.HoverAdapter(workerAccessor)));
136
- }
137
- monacoInstance.languages.registerDocumentFormattingEditProvider(language, new languageFeatures.DocumentFormatAdapter(workerAccessor));
138
- kustoWorker = workerAccessor;
139
- resolveWorker(workerAccessor);
140
- monacoInstance.languages.setLanguageConfiguration(language, {
141
- folding: {
142
- offSide: false,
143
- markers: { start: /^\s*[\r\n]/gm, end: /^\s*[\r\n]/gm },
144
- },
145
- comments: {
146
- lineComment: '//',
147
- blockComment: null,
891
+ return {
892
+ value: docString,
893
+ isTrusted: true,
894
+ uris: urisProxy
895
+ };
896
+ }
897
+ }
898
+ function isMarkupContent(thing) {
899
+ return thing && typeof thing === 'object' && typeof thing.kind === 'string';
900
+ }
901
+ function toMarkdownString(entry) {
902
+ if (typeof entry === 'string') {
903
+ return {
904
+ value: entry
905
+ };
906
+ }
907
+ if (isMarkupContent(entry)) {
908
+ if (entry.kind === 'plaintext') {
909
+ return {
910
+ value: entry.value.replace(/[\\`*_{}[\]()#+\-.!]/g, '\\$&')
911
+ };
912
+ }
913
+ return {
914
+ value: entry.value
915
+ };
916
+ }
917
+ return {
918
+ value: '```' + entry.value + '\n' + entry.value + '\n```\n'
919
+ };
920
+ }
921
+ function toMarkedStringArray(contents) {
922
+ if (!contents) {
923
+ return void 0;
924
+ }
925
+ if (Array.isArray(contents)) {
926
+ return contents.map(toMarkdownString);
927
+ }
928
+ return [toMarkdownString(contents)];
929
+ }
930
+
931
+ // --- definition ------
932
+
933
+ function toLocation(location) {
934
+ return {
935
+ uri: monaco.Uri.parse(location.uri),
936
+ range: toRange(location.range)
937
+ };
938
+ }
939
+ class DefinitionAdapter {
940
+ constructor(_worker) {
941
+ this._worker = _worker;
942
+ }
943
+ provideDefinition(model, position, token) {
944
+ const resource = model.uri;
945
+ return this._worker(resource).then(worker => {
946
+ return worker.findDefinition(resource.toString(), fromPosition(position));
947
+ }).then(definition => {
948
+ if (!definition || definition.length == 0) {
949
+ return;
950
+ }
951
+ return [toLocation(definition[0])];
952
+ });
953
+ }
954
+ }
955
+
956
+ // --- references ------
957
+
958
+ class ReferenceAdapter {
959
+ constructor(_worker) {
960
+ this._worker = _worker;
961
+ }
962
+ provideReferences(model, position, context, token) {
963
+ const resource = model.uri;
964
+ return this._worker(resource).then(worker => {
965
+ return worker.findReferences(resource.toString(), fromPosition(position));
966
+ }).then(entries => {
967
+ if (!entries) {
968
+ return;
969
+ }
970
+ return entries.map(toLocation);
971
+ });
972
+ }
973
+ }
974
+
975
+ // --- rename ------
976
+
977
+ function toWorkspaceEdit(edit) {
978
+ if (!edit || !edit.changes) {
979
+ return void 0;
980
+ }
981
+ let resourceEdits = [];
982
+ for (let uri in edit.changes) {
983
+ const _uri = monaco.Uri.parse(uri);
984
+ for (let e of edit.changes[uri]) {
985
+ resourceEdits.push({
986
+ resource: _uri,
987
+ textEdit: {
988
+ range: toRange(e.range),
989
+ text: e.newText
148
990
  },
991
+ versionId: undefined
992
+ });
993
+ }
994
+ }
995
+ return {
996
+ edits: resourceEdits
997
+ };
998
+ }
999
+ class RenameAdapter {
1000
+ constructor(_worker) {
1001
+ this._worker = _worker;
1002
+ }
1003
+ provideRenameEdits(model, position, newName, token) {
1004
+ const resource = model.uri;
1005
+ return this._worker(resource).then(worker => {
1006
+ return worker.doRename(resource.toString(), fromPosition(position), newName);
1007
+ }).then(edit => {
1008
+ return toWorkspaceEdit(edit);
1009
+ });
1010
+ }
1011
+ }
1012
+
1013
+ // --- formatting -----
1014
+
1015
+ class DocumentFormatAdapter {
1016
+ constructor(_worker) {
1017
+ this._worker = _worker;
1018
+ }
1019
+ provideDocumentFormattingEdits(model, options, token) {
1020
+ const resource = model.uri;
1021
+ return this._worker(resource).then(worker => {
1022
+ return worker.doDocumentFormat(resource.toString()).then(edits => edits.map(edit => toTextEdit(edit)));
1023
+ });
1024
+ }
1025
+ }
1026
+ class FormatAdapter {
1027
+ constructor(_worker) {
1028
+ this._worker = _worker;
1029
+ }
1030
+ provideDocumentRangeFormattingEdits(model, range, options, token) {
1031
+ const resource = model.uri;
1032
+ return this._worker(resource).then(worker => {
1033
+ return worker.doRangeFormat(resource.toString(), fromRange(range)).then(edits => edits.map(edit => toTextEdit(edit)));
1034
+ });
1035
+ }
1036
+ }
1037
+
1038
+ // --- Folding ---
1039
+ class FoldingAdapter {
1040
+ constructor(_worker) {
1041
+ this._worker = _worker;
1042
+ }
1043
+ provideFoldingRanges(model, context, token) {
1044
+ const resource = model.uri;
1045
+ return this._worker(resource).then(worker => {
1046
+ return worker.doFolding(resource.toString()).then(foldingRanges => foldingRanges.map(range => toFoldingRange(range)));
1047
+ });
1048
+ }
1049
+ }
1050
+ function toFoldingRange(range) {
1051
+ return {
1052
+ start: range.startLine + 1,
1053
+ end: range.endLine + 1,
1054
+ kind: monaco.languages.FoldingRangeKind.Region
1055
+ };
1056
+ }
1057
+
1058
+ // --- hover ------
1059
+
1060
+ class HoverAdapter {
1061
+ constructor(_worker) {
1062
+ this._worker = _worker;
1063
+ }
1064
+ provideHover(model, position, token) {
1065
+ let resource = model.uri;
1066
+ return this._worker(resource).then(worker => {
1067
+ return worker.doHover(resource.toString(), fromPosition(position));
1068
+ }).then(info => {
1069
+ if (!info) {
1070
+ return;
1071
+ }
1072
+ return {
1073
+ range: toRange(info.range),
1074
+ contents: toMarkedStringArray(info.contents)
1075
+ };
149
1076
  });
150
- return kustoWorker;
1077
+ }
1078
+ }
1079
+
1080
+ let kustoWorker;
1081
+ let resolveWorker;
1082
+ let workerPromise = new Promise((resolve, reject) => {
1083
+ resolveWorker = resolve;
1084
+ });
1085
+
1086
+ /**
1087
+ * Called when Kusto language is first needed (a model has the language set)
1088
+ * @param defaults
1089
+ */
1090
+ function setupMode(defaults, monacoInstance) {
1091
+ let onSchemaChange = new monaco.Emitter();
1092
+ // TODO: when should we dispose of these? seems like monaco-css and monaco-typescript don't dispose of these.
1093
+ let disposables = [];
1094
+ let monarchTokensProvider;
1095
+ const client = new WorkerManager(monacoInstance, defaults);
1096
+ disposables.push(client);
1097
+ const workerAccessor = (first, ...more) => {
1098
+ const augmentedSetSchema = async (schema, worker) => {
1099
+ const workerPromise = worker.setSchema(schema);
1100
+ await workerPromise.then(() => {
1101
+ onSchemaChange.fire(schema);
1102
+ });
1103
+ };
1104
+ const worker = client.getLanguageServiceWorker(...[first].concat(more));
1105
+ return worker.then(worker => ({
1106
+ ...worker,
1107
+ setSchema: schema => augmentedSetSchema(schema, worker),
1108
+ async setSchemaFromShowSchema(schema, connection, database, globalScalarParameters, globalTabularParameters) {
1109
+ await worker.normalizeSchema(schema, connection, database).then(schema => {
1110
+ if (globalScalarParameters || globalTabularParameters) {
1111
+ schema = {
1112
+ ...schema,
1113
+ globalScalarParameters,
1114
+ globalTabularParameters
1115
+ };
1116
+ }
1117
+ augmentedSetSchema(schema, worker);
1118
+ });
1119
+ }
1120
+ }));
1121
+ };
1122
+ const language = 'kusto';
1123
+ disposables.push(monacoInstance.languages.registerCompletionItemProvider(language, new CompletionAdapter(workerAccessor, defaults.languageSettings)));
1124
+
1125
+ // Monaco tokenization runs in main thread so we're using a quick schema-unaware tokenization.
1126
+ // a web worker will run semantic colorization in the background (ColorizationAdapter).
1127
+ if (defaults.languageSettings.useTokenColorization) {
1128
+ monarchTokensProvider = monacoInstance.languages.setMonarchTokensProvider(language, KustoLanguageDefinition);
1129
+ }
1130
+
1131
+ // listen to configuration changes and if we're switching from semantic to monarch colorization, do the switch.
1132
+ defaults.onDidChange(e => {
1133
+ if (!e.languageSettings.useTokenColorization && monarchTokensProvider !== undefined) {
1134
+ monarchTokensProvider.dispose();
1135
+ monarchTokensProvider = undefined;
1136
+ }
1137
+ if (e.languageSettings.useTokenColorization && monarchTokensProvider == undefined) {
1138
+ monarchTokensProvider = monacoInstance.languages.setMonarchTokensProvider(language, KustoLanguageDefinition);
1139
+ }
1140
+ });
1141
+ disposables.push(new DiagnosticsAdapter(monacoInstance, language, workerAccessor, defaults, onSchemaChange.event));
1142
+ disposables.push(new ColorizationAdapter(monacoInstance, language, workerAccessor, defaults, onSchemaChange.event));
1143
+ disposables.push(monacoInstance.languages.registerDocumentRangeFormattingEditProvider(language, new FormatAdapter(workerAccessor)));
1144
+ disposables.push(monacoInstance.languages.registerFoldingRangeProvider(language, new FoldingAdapter(workerAccessor)));
1145
+ disposables.push(monacoInstance.languages.registerDefinitionProvider(language, new DefinitionAdapter(workerAccessor)));
1146
+ disposables.push(monacoInstance.languages.registerRenameProvider(language, new RenameAdapter(workerAccessor)));
1147
+ disposables.push(monacoInstance.languages.registerReferenceProvider(language, new ReferenceAdapter(workerAccessor)));
1148
+ if (defaults.languageSettings.enableHover) {
1149
+ disposables.push(monacoInstance.languages.registerHoverProvider(language, new HoverAdapter(workerAccessor)));
1150
+ }
1151
+ monacoInstance.languages.registerDocumentFormattingEditProvider(language, new DocumentFormatAdapter(workerAccessor));
1152
+ kustoWorker = workerAccessor;
1153
+ resolveWorker(workerAccessor);
1154
+ monacoInstance.languages.setLanguageConfiguration(language, {
1155
+ folding: {
1156
+ offSide: false,
1157
+ markers: {
1158
+ start: /^\s*[\r\n]/gm,
1159
+ end: /^\s*[\r\n]/gm
1160
+ }
1161
+ },
1162
+ comments: {
1163
+ lineComment: '//',
1164
+ blockComment: null
1165
+ }
1166
+ });
1167
+ return kustoWorker;
151
1168
  }
152
- export function getKustoWorker() {
153
- return workerPromise.then(function () { return kustoWorker; });
1169
+ function getKustoWorker() {
1170
+ return workerPromise.then(() => kustoWorker);
154
1171
  }
1172
+
1173
+ export { getKustoWorker, setupMode };