@kusto/monaco-kusto 5.6.6 → 6.1.0

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.
Files changed (65) hide show
  1. package/package.json +26 -16
  2. package/release/dev/commandFormatter.d.ts +6 -0
  3. package/release/dev/commandHighlighter.d.ts +20 -0
  4. package/release/dev/extendedEditor.d.ts +7 -0
  5. package/release/dev/kustoMode.d.ts +8 -0
  6. package/release/dev/kustoMode.js +1730 -3278
  7. package/release/dev/kustoWorker.d.ts +92 -0
  8. package/release/dev/kustoWorker.js +5687 -8534
  9. package/release/dev/languageFeatures.d.ts +91 -0
  10. package/release/dev/languageService/kustoLanguageService.d.ts +143 -0
  11. package/release/dev/languageService/kustoMonarchLanguageDefinition.d.ts +1 -0
  12. package/release/dev/languageService/renderInfo.d.ts +31 -0
  13. package/release/dev/languageService/schema.d.ts +144 -0
  14. package/release/dev/languageService/settings.d.ts +30 -0
  15. package/release/dev/main-ac12725e.js +1958 -0
  16. package/release/dev/monaco.contribution.d.ts +15 -0
  17. package/release/dev/monaco.contribution.js +462 -309
  18. package/release/dev/workerManager.d.ts +23 -0
  19. package/release/esm/commandFormatter.d.ts +6 -0
  20. package/release/esm/commandHighlighter.d.ts +20 -0
  21. package/release/esm/extendedEditor.d.ts +7 -0
  22. package/release/esm/kusto.worker.js +2246 -5
  23. package/release/esm/kustoMode.d.ts +8 -0
  24. package/release/esm/kustoMode.js +1120 -88
  25. package/release/esm/kustoWorker.d.ts +92 -0
  26. package/release/esm/languageFeatures.d.ts +91 -0
  27. package/release/esm/languageService/kustoLanguageService.d.ts +143 -0
  28. package/release/esm/languageService/kustoMonarchLanguageDefinition.d.ts +1 -0
  29. package/release/esm/languageService/renderInfo.d.ts +31 -0
  30. package/release/esm/languageService/schema.d.ts +144 -0
  31. package/release/esm/languageService/settings.d.ts +30 -0
  32. package/release/esm/monaco.contribution.d.ts +1 -0
  33. package/release/esm/monaco.contribution.js +424 -181
  34. package/release/esm/workerManager.d.ts +23 -0
  35. package/release/min/commandFormatter.d.ts +6 -0
  36. package/release/min/commandHighlighter.d.ts +20 -0
  37. package/release/min/extendedEditor.d.ts +7 -0
  38. package/release/min/kustoMode.d.ts +8 -0
  39. package/release/min/kustoMode.js +2 -11
  40. package/release/min/kustoWorker.d.ts +92 -0
  41. package/release/min/kustoWorker.js +10 -53
  42. package/release/min/languageFeatures.d.ts +91 -0
  43. package/release/min/languageService/kustoLanguageService.d.ts +143 -0
  44. package/release/min/languageService/kustoMonarchLanguageDefinition.d.ts +1 -0
  45. package/release/min/languageService/renderInfo.d.ts +31 -0
  46. package/release/min/languageService/schema.d.ts +144 -0
  47. package/release/min/languageService/settings.d.ts +30 -0
  48. package/release/min/main-5b1cc297.js +7 -0
  49. package/release/min/monaco.contribution.d.ts +1 -0
  50. package/release/min/monaco.contribution.js +2 -2
  51. package/release/min/monaco.d.ts +1 -319
  52. package/release/min/workerManager.d.ts +23 -0
  53. package/release/{esm/monaco.d.ts → monaco.d.ts} +1 -1
  54. package/release/esm/_deps/lodash/lodash.js +0 -17209
  55. package/release/esm/_deps/vscode-languageserver-types/main.js +0 -1908
  56. package/release/esm/_deps/xregexp/xregexp-all.js +0 -4652
  57. package/release/esm/commandFormatter.js +0 -36
  58. package/release/esm/commandHighlighter.js +0 -51
  59. package/release/esm/extendedEditor.js +0 -38
  60. package/release/esm/kustoWorker.js +0 -245
  61. package/release/esm/languageFeatures.js +0 -1032
  62. package/release/esm/languageService/kustoLanguageService.js +0 -1912
  63. package/release/esm/languageService/kustoMonarchLanguageDefinition.js +0 -127
  64. package/release/esm/languageService/schema.js +0 -64
  65. package/release/esm/workerManager.js +0 -102
@@ -1,1912 +0,0 @@
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];
7
- }
8
- return t;
9
- };
10
- return __assign.apply(this, arguments);
11
- };
12
- var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
13
- if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
14
- if (ar || !(i in from)) {
15
- if (!ar) ar = Array.prototype.slice.call(from, 0, i);
16
- ar[i] = from[i];
17
- }
18
- }
19
- return to.concat(ar || Array.prototype.slice.call(from));
20
- };
21
- var _a;
22
- import * as s from './schema';
23
- // polyfill string endsWith
24
- if (!String.prototype.endsWith) {
25
- String.prototype.endsWith = function (search, this_len) {
26
- if (this_len === undefined || this_len > this.length) {
27
- this_len = this.length;
28
- }
29
- return this.substring(this_len - search.length, this_len) === search;
30
- };
31
- }
32
- // If we're running in a web worker - which doesn't share global context with the main thread -
33
- // we need to manually load dependencies that are not explicit- meaning our non-module dependencies
34
- // generated by Bridge.Net
35
- if (typeof document == 'undefined') {
36
- // monaco will run the worker from vs/base/worker so the relative path needs to be from there (hence going up 2 dirs)
37
- importScripts('../../language/kusto/bridge.min.js');
38
- importScripts('../../language/kusto/kusto.javascript.client.min.js');
39
- importScripts('../../language/kusto/Kusto.Language.Bridge.min.js');
40
- }
41
- import * as ls from '../_deps/vscode-languageserver-types/main';
42
- import * as XRegExp from '../_deps/xregexp/xregexp-all';
43
- var k = Kusto.Data.IntelliSense;
44
- var parsing = Kusto.Language.Parsing;
45
- var k2 = Kusto.Language.Editor;
46
- var sym = Kusto.Language.Symbols;
47
- var GlobalState = Kusto.Language.GlobalState;
48
- import { getCslTypeNameFromClrType, getEntityDataTypeFromCslType } from './schema';
49
- var List = System.Collections.Generic.List$1;
50
- function assertNever(x) {
51
- throw new Error('Unexpected object: ' + x);
52
- }
53
- var ParseProperties = /** @class */ (function () {
54
- function ParseProperties(version, uri, rulesProvider, parseMode) {
55
- this.version = version;
56
- this.uri = uri;
57
- this.rulesProvider = rulesProvider;
58
- this.parseMode = parseMode;
59
- }
60
- ParseProperties.prototype.isParseNeeded = function (document, rulesProvider, parseMode) {
61
- if (document.uri === this.uri &&
62
- (!rulesProvider || rulesProvider === this.rulesProvider) &&
63
- document.version <= this.version &&
64
- parseMode &&
65
- parseMode <= this.parseMode) {
66
- return false;
67
- }
68
- return true;
69
- };
70
- return ParseProperties;
71
- }());
72
- export var TokenKind;
73
- (function (TokenKind) {
74
- TokenKind[TokenKind["TableToken"] = 2] = "TableToken";
75
- TokenKind[TokenKind["TableColumnToken"] = 4] = "TableColumnToken";
76
- TokenKind[TokenKind["OperatorToken"] = 8] = "OperatorToken";
77
- TokenKind[TokenKind["SubOperatorToken"] = 16] = "SubOperatorToken";
78
- TokenKind[TokenKind["CalculatedColumnToken"] = 32] = "CalculatedColumnToken";
79
- TokenKind[TokenKind["StringLiteralToken"] = 64] = "StringLiteralToken";
80
- TokenKind[TokenKind["FunctionNameToken"] = 128] = "FunctionNameToken";
81
- TokenKind[TokenKind["UnknownToken"] = 256] = "UnknownToken";
82
- TokenKind[TokenKind["CommentToken"] = 512] = "CommentToken";
83
- TokenKind[TokenKind["PlainTextToken"] = 1024] = "PlainTextToken";
84
- TokenKind[TokenKind["DataTypeToken"] = 2048] = "DataTypeToken";
85
- TokenKind[TokenKind["ControlCommandToken"] = 4096] = "ControlCommandToken";
86
- TokenKind[TokenKind["CommandPartToken"] = 8192] = "CommandPartToken";
87
- TokenKind[TokenKind["QueryParametersToken"] = 16384] = "QueryParametersToken";
88
- TokenKind[TokenKind["CslCommandToken"] = 32768] = "CslCommandToken";
89
- TokenKind[TokenKind["LetVariablesToken"] = 65536] = "LetVariablesToken";
90
- TokenKind[TokenKind["PluginToken"] = 131072] = "PluginToken";
91
- TokenKind[TokenKind["BracketRangeToken"] = 262144] = "BracketRangeToken";
92
- TokenKind[TokenKind["ClientDirectiveToken"] = 524288] = "ClientDirectiveToken";
93
- })(TokenKind || (TokenKind = {}));
94
- /**
95
- * convert the bridge.net object to a plain javascript object that only contains data.
96
- * @param k2Classifications @kusto/language-service-next bridge.net object
97
- */
98
- function toClassifiedRange(k2Classifications) {
99
- return k2Classifications.map(function (classification) { return ({
100
- start: classification.Start,
101
- end: classification.End,
102
- length: classification.Length,
103
- kind: classification.Kind,
104
- }); });
105
- }
106
- var symbolKindToName = (_a = {},
107
- _a[sym.SymbolKind.Cluster] = 'Cluster',
108
- _a[sym.SymbolKind.Column] = 'Column',
109
- _a[sym.SymbolKind.Command] = 'Command',
110
- _a[sym.SymbolKind.Database] = 'Database',
111
- _a[sym.SymbolKind.EntityGroup] = 'EntityGroup',
112
- _a[sym.SymbolKind.EntityGroupElement] = 'EntityGroupElement',
113
- _a[sym.SymbolKind.Error] = 'Error',
114
- _a[sym.SymbolKind.Function] = 'Function',
115
- _a[sym.SymbolKind.Graph] = 'Graph',
116
- _a[sym.SymbolKind.Group] = 'Group',
117
- _a[sym.SymbolKind.MaterializedView] = 'MaterializedView',
118
- _a[sym.SymbolKind.None] = 'None',
119
- _a[sym.SymbolKind.Operator] = 'Operator',
120
- _a[sym.SymbolKind.Option] = 'Option',
121
- _a[sym.SymbolKind.Parameter] = 'Parameter',
122
- _a[sym.SymbolKind.Pattern] = 'Pattern',
123
- _a[sym.SymbolKind.QueryOperatorParameter] = 'QueryOperatorParameter',
124
- _a[sym.SymbolKind.Scalar] = 'Scalar',
125
- _a[sym.SymbolKind.Table] = 'Table',
126
- _a[sym.SymbolKind.Tuple] = 'Tuple',
127
- _a[sym.SymbolKind.Variable] = 'Variable',
128
- _a[sym.SymbolKind.Void] = 'Void',
129
- _a);
130
- /**
131
- * Kusto Language service translates the kusto object model (transpiled from C# by Bridge.Net)
132
- * to the vscode language server types, which are used by vscode language extensions.
133
- * This should make things easier in the future to provide a vscode extension based on this translation layer.
134
- *
135
- * Further translations, if needed, to support specific editors (Atom, sublime, Etc)
136
- * should be done on top of this API, since it is (at least meant to be) a standard that is supported by multiple editors.
137
- *
138
- * Note1: Currently monaco isn't using this object model so further translation will be necessary on calling modules.
139
- *
140
- * Note2: This file is responsible for interacting with the kusto object model and exposing Microsoft language service types.
141
- * An exception to that rule is tokenization (and syntax highlighting which depends on it) -
142
- * since it's not currently part of the Microsoft language service protocol. Thus tokenize() _does_ 'leak' kusto types to the callers.
143
- */
144
- var KustoLanguageService = /** @class */ (function () {
145
- function KustoLanguageService(schema, languageSettings) {
146
- var _a, _b, _c, _d;
147
- var _this = this;
148
- /**
149
- * Taken from:
150
- * https://msazure.visualstudio.com/One/_git/Azure-Kusto-Service?path=/Src/Tools/Kusto.Explorer.Control/QueryEditors/KustoScriptEditor/KustoScriptEditorControl2.xaml.cs&version=GBdev&line=2075&lineEnd=2075&lineStartColumn=9&lineEndColumn=77&lineStyle=plain&_a=contents
151
- */
152
- this._toOptionKind = (_a = {},
153
- _a[k2.CompletionKind.AggregateFunction] = k.OptionKind.FunctionAggregation,
154
- _a[k2.CompletionKind.BuiltInFunction] = k.OptionKind.FunctionScalar,
155
- _a[k2.CompletionKind.Cluster] = k.OptionKind.Database,
156
- _a[k2.CompletionKind.Column] = k.OptionKind.Column,
157
- _a[k2.CompletionKind.CommandPrefix] = k.OptionKind.Command,
158
- _a[k2.CompletionKind.Database] = k.OptionKind.Database,
159
- _a[k2.CompletionKind.DatabaseFunction] = k.OptionKind.FunctionServerSide,
160
- _a[k2.CompletionKind.Example] = k.OptionKind.Literal,
161
- _a[k2.CompletionKind.Identifier] = k.OptionKind.None,
162
- _a[k2.CompletionKind.Keyword] = k.OptionKind.Option,
163
- _a[k2.CompletionKind.LocalFunction] = k.OptionKind.FunctionLocal,
164
- _a[k2.CompletionKind.MaterialiedView] = k.OptionKind.MaterializedView,
165
- _a[k2.CompletionKind.Parameter] = k.OptionKind.Parameter,
166
- _a[k2.CompletionKind.Punctuation] = k.OptionKind.None,
167
- _a[k2.CompletionKind.QueryPrefix] = k.OptionKind.Operator,
168
- _a[k2.CompletionKind.RenderChart] = k.OptionKind.OptionRender,
169
- _a[k2.CompletionKind.ScalarInfix] = k.OptionKind.None,
170
- _a[k2.CompletionKind.ScalarPrefix] = k.OptionKind.Literal,
171
- _a[k2.CompletionKind.ScalarType] = k.OptionKind.DataType,
172
- _a[k2.CompletionKind.Syntax] = k.OptionKind.None,
173
- _a[k2.CompletionKind.Table] = k.OptionKind.Table,
174
- _a[k2.CompletionKind.TabularPrefix] = k.OptionKind.None,
175
- _a[k2.CompletionKind.TabularSuffix] = k.OptionKind.None,
176
- _a[k2.CompletionKind.Unknown] = k.OptionKind.None,
177
- _a[k2.CompletionKind.Variable] = k.OptionKind.Parameter,
178
- _a[k2.CompletionKind.Option] = k.OptionKind.Option,
179
- _a[k2.CompletionKind.Graph] = k.OptionKind.Graph,
180
- _a);
181
- this.disabledCompletionItemsV2 = {
182
- // render charts
183
- ladderchart: k2.CompletionKind.RenderChart,
184
- pivotchart: k2.CompletionKind.RenderChart,
185
- timeline: k2.CompletionKind.RenderChart,
186
- timepivot: k2.CompletionKind.RenderChart,
187
- '3Dchart': k2.CompletionKind.RenderChart,
188
- list: k2.CompletionKind.RenderChart,
189
- };
190
- this.isIntellisenseV2 = function () {
191
- return _this._languageSettings.useIntellisenseV2 && _this._schema && _this._schema.clusterType === 'Engine';
192
- };
193
- this.disabledCompletionItemsV1 = {
194
- capacity: k.OptionKind.Policy,
195
- callout: k.OptionKind.Policy,
196
- encoding: k.OptionKind.Policy,
197
- batching: k.OptionKind.Policy,
198
- querythrottling: k.OptionKind.Policy,
199
- merge: k.OptionKind.Policy,
200
- querylimit: k.OptionKind.Policy,
201
- rowstore: k.OptionKind.Policy,
202
- streamingingestion: k.OptionKind.Policy,
203
- restricted_view_access: k.OptionKind.Policy,
204
- sharding: k.OptionKind.Policy,
205
- 'restricted-viewers': k.OptionKind.Policy,
206
- attach: k.OptionKind.Command,
207
- purge: k.OptionKind.Command,
208
- };
209
- this._kustoKindtolsKind = (_b = {},
210
- _b[k.OptionKind.None] = ls.CompletionItemKind.Interface,
211
- _b[k.OptionKind.Operator] = ls.CompletionItemKind.Method,
212
- _b[k.OptionKind.Command] = ls.CompletionItemKind.Method,
213
- _b[k.OptionKind.Service] = ls.CompletionItemKind.Class,
214
- _b[k.OptionKind.Policy] = ls.CompletionItemKind.Reference,
215
- _b[k.OptionKind.Database] = ls.CompletionItemKind.Class,
216
- _b[k.OptionKind.Table] = ls.CompletionItemKind.Class,
217
- _b[k.OptionKind.DataType] = ls.CompletionItemKind.Class,
218
- _b[k.OptionKind.Literal] = ls.CompletionItemKind.Property,
219
- _b[k.OptionKind.Parameter] = ls.CompletionItemKind.Variable,
220
- _b[k.OptionKind.IngestionMapping] = ls.CompletionItemKind.Variable,
221
- _b[k.OptionKind.ExpressionFunction] = ls.CompletionItemKind.Variable,
222
- _b[k.OptionKind.Option] = ls.CompletionItemKind.Interface,
223
- _b[k.OptionKind.OptionKind] = ls.CompletionItemKind.Interface,
224
- _b[k.OptionKind.OptionRender] = ls.CompletionItemKind.Interface,
225
- _b[k.OptionKind.Column] = ls.CompletionItemKind.Function,
226
- _b[k.OptionKind.ColumnString] = ls.CompletionItemKind.Field,
227
- _b[k.OptionKind.ColumnNumeric] = ls.CompletionItemKind.Field,
228
- _b[k.OptionKind.ColumnDateTime] = ls.CompletionItemKind.Field,
229
- _b[k.OptionKind.ColumnTimespan] = ls.CompletionItemKind.Field,
230
- _b[k.OptionKind.FunctionServerSide] = ls.CompletionItemKind.Field,
231
- _b[k.OptionKind.FunctionAggregation] = ls.CompletionItemKind.Field,
232
- _b[k.OptionKind.FunctionFilter] = ls.CompletionItemKind.Field,
233
- _b[k.OptionKind.FunctionScalar] = ls.CompletionItemKind.Field,
234
- _b[k.OptionKind.ClientDirective] = ls.CompletionItemKind.Enum,
235
- _b);
236
- this._kustoKindToLsKindV2 = (_c = {},
237
- _c[k2.CompletionKind.AggregateFunction] = ls.CompletionItemKind.Field,
238
- _c[k2.CompletionKind.BuiltInFunction] = ls.CompletionItemKind.Field,
239
- _c[k2.CompletionKind.Cluster] = ls.CompletionItemKind.Class,
240
- _c[k2.CompletionKind.Column] = ls.CompletionItemKind.Function,
241
- _c[k2.CompletionKind.CommandPrefix] = ls.CompletionItemKind.Field,
242
- _c[k2.CompletionKind.Database] = ls.CompletionItemKind.Class,
243
- _c[k2.CompletionKind.DatabaseFunction] = ls.CompletionItemKind.Field,
244
- _c[k2.CompletionKind.Example] = ls.CompletionItemKind.Text,
245
- _c[k2.CompletionKind.Identifier] = ls.CompletionItemKind.Method,
246
- _c[k2.CompletionKind.Keyword] = ls.CompletionItemKind.Method,
247
- _c[k2.CompletionKind.LocalFunction] = ls.CompletionItemKind.Field,
248
- _c[k2.CompletionKind.MaterialiedView] = ls.CompletionItemKind.Class,
249
- _c[k2.CompletionKind.Parameter] = ls.CompletionItemKind.Variable,
250
- _c[k2.CompletionKind.Punctuation] = ls.CompletionItemKind.Interface,
251
- _c[k2.CompletionKind.QueryPrefix] = ls.CompletionItemKind.Function,
252
- _c[k2.CompletionKind.RenderChart] = ls.CompletionItemKind.Method,
253
- _c[k2.CompletionKind.ScalarInfix] = ls.CompletionItemKind.Field,
254
- _c[k2.CompletionKind.ScalarPrefix] = ls.CompletionItemKind.Field,
255
- _c[k2.CompletionKind.ScalarType] = ls.CompletionItemKind.TypeParameter,
256
- _c[k2.CompletionKind.Syntax] = ls.CompletionItemKind.Method,
257
- _c[k2.CompletionKind.Table] = ls.CompletionItemKind.Class,
258
- _c[k2.CompletionKind.TabularPrefix] = ls.CompletionItemKind.Field,
259
- // datatable, externaldata
260
- _c[k2.CompletionKind.TabularSuffix] = ls.CompletionItemKind.Field,
261
- _c[k2.CompletionKind.Unknown] = ls.CompletionItemKind.Interface,
262
- _c[k2.CompletionKind.Variable] = ls.CompletionItemKind.Variable,
263
- _c[k2.CompletionKind.Option] = ls.CompletionItemKind.Text,
264
- _c[k2.CompletionKind.Graph] = ls.CompletionItemKind.Class,
265
- _c);
266
- this._tokenKindToClassificationKind = (_d = {},
267
- _d[TokenKind.TableToken] = k2.ClassificationKind.Table,
268
- _d[TokenKind.TableColumnToken] = k2.ClassificationKind.Column,
269
- _d[TokenKind.OperatorToken] = k2.ClassificationKind.QueryOperator,
270
- _d[TokenKind.SubOperatorToken] = k2.ClassificationKind.Function,
271
- _d[TokenKind.CalculatedColumnToken] = k2.ClassificationKind.Column,
272
- _d[TokenKind.StringLiteralToken] = k2.ClassificationKind.Literal,
273
- _d[TokenKind.FunctionNameToken] = k2.ClassificationKind.Function,
274
- _d[TokenKind.UnknownToken] = k2.ClassificationKind.PlainText,
275
- _d[TokenKind.CommentToken] = k2.ClassificationKind.Comment,
276
- _d[TokenKind.PlainTextToken] = k2.ClassificationKind.PlainText,
277
- _d[TokenKind.DataTypeToken] = k2.ClassificationKind.Type,
278
- _d[TokenKind.ControlCommandToken] = k2.ClassificationKind.PlainText,
279
- _d[TokenKind.CommandPartToken] = k2.ClassificationKind.PlainText,
280
- _d[TokenKind.QueryParametersToken] = k2.ClassificationKind.QueryParameter,
281
- _d[TokenKind.CslCommandToken] = k2.ClassificationKind.Keyword,
282
- _d[TokenKind.LetVariablesToken] = k2.ClassificationKind.Identifier,
283
- _d[TokenKind.PluginToken] = k2.ClassificationKind.Function,
284
- _d[TokenKind.BracketRangeToken] = k2.ClassificationKind.Keyword,
285
- _d[TokenKind.ClientDirectiveToken] = k2.ClassificationKind.Keyword,
286
- _d);
287
- this._schemaCache = {};
288
- this._kustoJsSchema = KustoLanguageService.convertToKustoJsSchema(schema);
289
- this.__kustoJsSchemaV2 = this.convertToKustoJsSchemaV2(schema);
290
- this._schema = schema;
291
- this._clustersSetInGlobalState = new Set();
292
- this._nonEmptyDatabaseSetInGlobalState = new Set(); // used to remove clusters that are already in the global state
293
- this.configure(languageSettings);
294
- this._newlineAppendPipePolicy = new Kusto.Data.IntelliSense.ApplyPolicy();
295
- this._newlineAppendPipePolicy.Text = '\n| ';
296
- }
297
- KustoLanguageService.prototype.createDatabaseUniqueName = function (clusterName, databaseName) {
298
- return "".concat(clusterName, "_").concat(databaseName);
299
- };
300
- Object.defineProperty(KustoLanguageService.prototype, "_kustoJsSchemaV2", {
301
- /**
302
- * A getter for __kustoJsSchemaV2
303
- */
304
- get: function () {
305
- return this.__kustoJsSchemaV2;
306
- },
307
- /**
308
- * A setter for _kustoJsSchemaV2. After a schema (global state) is set, create 2 sets of cluster and database names.
309
- */
310
- set: function (globalState) {
311
- this.__kustoJsSchemaV2 = globalState;
312
- this._clustersSetInGlobalState.clear();
313
- this._nonEmptyDatabaseSetInGlobalState.clear();
314
- // create 2 Sets with cluster names and database names based on the updated Global State.
315
- for (var i = 0; i < globalState.Clusters.Count; i++) {
316
- var clusterSymbol = this._kustoJsSchemaV2.Clusters.getItem(i);
317
- this._clustersSetInGlobalState.add(clusterSymbol.Name);
318
- for (var i2 = 0; i2 < clusterSymbol.Databases.Count; i2++) {
319
- var databaseSymbol = clusterSymbol.Databases.getItem(i2);
320
- if (databaseSymbol.Tables.Count > 0) {
321
- // only include database with tables
322
- this._nonEmptyDatabaseSetInGlobalState.add(this.createDatabaseUniqueName(clusterSymbol.Name, databaseSymbol.Name));
323
- }
324
- }
325
- }
326
- },
327
- enumerable: false,
328
- configurable: true
329
- });
330
- KustoLanguageService.prototype.configure = function (languageSettings) {
331
- this._languageSettings = languageSettings;
332
- // Since we're still reverting to V1 intellisense for control commands, we need to update the rules provider
333
- // (which is a notion of V1 intellisense).
334
- this.createRulesProvider(this._kustoJsSchema, this._schema.clusterType);
335
- };
336
- KustoLanguageService.prototype.doComplete = function (document, position) {
337
- return this.isIntellisenseV2() ? this.doCompleteV2(document, position) : this.doCompleteV1(document, position);
338
- };
339
- /**
340
- * important: Only use during development to test Global State.
341
- * Prints clusters, databases and tables that are currently in the GlobalState.
342
- */
343
- KustoLanguageService.prototype.debugGlobalState = function (globals) {
344
- // iterate over clusters
345
- console.log("globals.Clusters.Count: ".concat(globals.Clusters.Count));
346
- for (var i = 0; i < globals.Clusters.Count; i++) {
347
- var cluster = globals.Clusters.getItem(i);
348
- console.log("cluster: ".concat(cluster.Name));
349
- // iterate over databases
350
- console.log("cluster.Databases.Count: ".concat(cluster.Databases.Count));
351
- for (var i2 = 0; i2 < cluster.Databases.Count; i2++) {
352
- var database = cluster.Databases.getItem(i2);
353
- console.log("cluster.database: [".concat(cluster.Name, "].[").concat(database.Name, "]"));
354
- // iterate over tables
355
- console.log("cluster.Databases.Tables.Count: ".concat(database.Tables.Count));
356
- for (var i3 = 0; i3 < database.Tables.Count; i3++) {
357
- var table = database.Tables.getItem(i3);
358
- console.log("cluster.database.table: [".concat(cluster.Name, "].[").concat(database.Name, "].[").concat(table.Name, "]"));
359
- }
360
- }
361
- }
362
- };
363
- /**
364
- * Prepending the doc of the actual topic at the top
365
- */
366
- KustoLanguageService.prototype.formatHelpTopic = function (helpTopic) {
367
- return "**".concat(helpTopic.Name, " [(view online)](").concat(helpTopic.Url, ")**\n\n").concat(helpTopic.LongDescription);
368
- };
369
- KustoLanguageService.prototype.doCompleteV2 = function (document, position) {
370
- var _this = this;
371
- if (!document) {
372
- return Promise.resolve(ls.CompletionList.create([]));
373
- }
374
- var script = this.parseDocumentV2(document);
375
- // print cluster/database/tables from CodeScript.Globals
376
- // this.debugGlobalState(script.Globals);
377
- // get current command
378
- var cursorOffset = document.offsetAt(position);
379
- var currentCommand = script.GetBlockAtPosition(cursorOffset);
380
- // get completion items
381
- var completionItems = currentCommand.Service.GetCompletionItems(cursorOffset);
382
- var disabledItems = this.disabledCompletionItemsV2;
383
- if (this._languageSettings.disabledCompletionItems) {
384
- this._languageSettings.disabledCompletionItems.map(function (item) {
385
- // logic will treat unknown as a '*' wildcard, meaning that if the key is in the object
386
- // the completion item will be suppressed.
387
- disabledItems[item] = k2.CompletionKind.Unknown;
388
- });
389
- }
390
- var itemsAsArray = this.toArray(completionItems.Items);
391
- var items = itemsAsArray
392
- .filter(function (item) {
393
- return !(item &&
394
- item.MatchText &&
395
- disabledItems[item.MatchText] !== undefined &&
396
- (disabledItems[item.MatchText] === k2.CompletionKind.Unknown ||
397
- disabledItems[item.MatchText] === item.Kind));
398
- })
399
- .map(function (kItem, i) {
400
- var v1CompletionOption = new k.CompletionOption(_this._toOptionKind[kItem.Kind] || k.OptionKind.None, kItem.DisplayText);
401
- var helpTopic = _this.getTopic(v1CompletionOption);
402
- // If we have AfterText it means that the cursor should no be placed at end of suggested text.
403
- // In that case we switch to snippet format and represent the point where the cursor should be as
404
- // as '\$0'
405
- var _a = kItem.AfterText && kItem.AfterText.length > 0
406
- ? {
407
- // Need to escape dollar sign since it is used as a placeholder in snippet.
408
- // Usually dollar sign is not a valid character in a function name, but grafana uses macros that start with dollars.
409
- textToInsert: "".concat(kItem.EditText.replace('$', '\\$'), "$0").concat(kItem.AfterText),
410
- format: ls.InsertTextFormat.Snippet,
411
- }
412
- : {
413
- textToInsert: kItem.EditText,
414
- format: ls.InsertTextFormat.PlainText,
415
- }, textToInsert = _a.textToInsert, format = _a.format;
416
- var lsItem = ls.CompletionItem.create(kItem.DisplayText);
417
- // Adding to columns a prefix to their sortText so they will appear first in the list
418
- var sortTextPrefix = lsItem.kind === ls.CompletionItemKind.Field ? 0 : itemsAsArray.length;
419
- var startPosition = document.positionAt(completionItems.EditStart);
420
- var endPosition = document.positionAt(completionItems.EditStart + completionItems.EditLength);
421
- lsItem.textEdit = ls.TextEdit.replace(ls.Range.create(startPosition, endPosition), textToInsert);
422
- lsItem.sortText = _this.getSortText(sortTextPrefix + i + 1);
423
- // Changing the first letter to be lower case, to ignore case-sensitive matching
424
- lsItem.filterText = lsItem.label.charAt(0).toLowerCase() + lsItem.label.slice(1);
425
- lsItem.kind = _this.kustoKindToLsKindV2(kItem.Kind);
426
- lsItem.insertTextFormat = format;
427
- lsItem.detail = helpTopic ? helpTopic.ShortDescription : undefined;
428
- lsItem.documentation = helpTopic
429
- ? { value: _this.formatHelpTopic(helpTopic), kind: ls.MarkupKind.Markdown }
430
- : undefined;
431
- return lsItem;
432
- });
433
- return Promise.resolve(ls.CompletionList.create(items));
434
- };
435
- /**
436
- * when trying to get a topic we need the function name (abs, toLower, ETC).
437
- * The problem is that the 'Value' string also contains the arguments (e.g abs(number)), which means that we are
438
- * not able to correlate the option with its documentation.
439
- * This piece of code tries to strip this hwne getting topic.
440
- * @param completionOption the Completion option
441
- */
442
- KustoLanguageService.prototype.getTopic = function (completionOption) {
443
- if (completionOption.Kind == k.OptionKind.FunctionScalar ||
444
- completionOption.Kind == k.OptionKind.FunctionAggregation) {
445
- // from a value like 'abs(number)' remove the '(number)' so that only 'abs' will remain
446
- var indexOfParen = completionOption.Value.indexOf('(');
447
- if (indexOfParen >= 0) {
448
- completionOption = new k.CompletionOption(completionOption.Kind, completionOption.Value.substring(0, indexOfParen));
449
- }
450
- }
451
- return k.CslDocumentation.Instance.GetTopic(completionOption);
452
- };
453
- KustoLanguageService.prototype.doCompleteV1 = function (document, position) {
454
- var _this = this;
455
- // TODO: fix typing in CslCommandParser to allow rulesProvider to be query only.
456
- var caretAbsolutePosition = document.offsetAt(position);
457
- // find out what's the current command to only parse this one.
458
- this.parseDocumentV1(document, k.ParseMode.CommandTokensOnly);
459
- var currentCommand = this.getCurrentCommand(document, caretAbsolutePosition);
460
- var commandTextUntilCursor = '';
461
- if (currentCommand) {
462
- var commandStartOffset = currentCommand.AbsoluteStart;
463
- this.parseTextV1(currentCommand.Text, k.ParseMode.TokenizeAllText);
464
- var caretRelativePosition = caretAbsolutePosition - currentCommand.AbsoluteStart;
465
- commandTextUntilCursor = currentCommand.Text.substring(currentCommand.CslExpressionStartPosition, caretRelativePosition);
466
- }
467
- var commandTextWithoutLastWord = this.getCommandWithoutLastWord(commandTextUntilCursor);
468
- var context = this._rulesProvider.AnalyzeCommand$1(commandTextUntilCursor, currentCommand).Context;
469
- var result = { v: null };
470
- this._rulesProvider.TryMatchAnyRule(commandTextWithoutLastWord, result);
471
- var rule = result.v;
472
- if (rule) {
473
- var completionOptions = this.toArray(rule.GetCompletionOptions(context));
474
- // TODO once AppendPipePolicy becomes a public static member of ApplyPolicy in our c# code, and bridge.Net transplies this,
475
- // remove the 'as any' part..
476
- // Also = DefaultApplyPolicy is internal in c# code, so not exposed in d.ts, so we cast it to any.
477
- if (this._languageSettings.newlineAfterPipe &&
478
- rule.DefaultAfterApplyPolicy === Kusto.Data.IntelliSense.ApplyPolicy.AppendPipePolicy) {
479
- rule.DefaultAfterApplyPolicy = this._newlineAppendPipePolicy;
480
- }
481
- var options = completionOptions
482
- .filter(function (option) {
483
- return !(option && option.Value && _this.disabledCompletionItemsV1[option.Value] === option.Kind);
484
- })
485
- .map(function (option, ordinal) {
486
- var _a = _this.getTextToInsert(rule, option), insertText = _a.insertText, insertTextFormat = _a.insertTextFormat;
487
- var helpTopic = k.CslDocumentation.Instance.GetTopic(option);
488
- var item = ls.CompletionItem.create(option.Value);
489
- item.kind = _this.kustoKindToLsKind(option.Kind);
490
- item.insertText = insertText;
491
- item.insertTextFormat = insertTextFormat;
492
- item.sortText = _this.getSortText(ordinal + 1);
493
- item.detail = helpTopic ? helpTopic.ShortDescription : undefined;
494
- item.documentation = helpTopic
495
- ? { value: helpTopic.LongDescription, kind: ls.MarkupKind.Markdown }
496
- : undefined;
497
- return item;
498
- });
499
- return Promise.resolve(ls.CompletionList.create(options));
500
- }
501
- return Promise.resolve(ls.CompletionList.create([]));
502
- };
503
- KustoLanguageService.prototype.doRangeFormat = function (document, range) {
504
- if (!document) {
505
- return Promise.resolve([]);
506
- }
507
- var rangeStartOffset = document.offsetAt(range.start);
508
- var rangeEndOffset = document.offsetAt(range.end);
509
- var commands = this.getFormattedCommandsInDocumentV2(document, rangeStartOffset, rangeEndOffset);
510
- if (!commands.originalRange || commands.formattedCommands.length === 0) {
511
- return Promise.resolve([]);
512
- }
513
- return Promise.resolve([ls.TextEdit.replace(commands.originalRange, commands.formattedCommands.join(''))]);
514
- };
515
- KustoLanguageService.prototype.doDocumentFormat = function (document) {
516
- if (!document) {
517
- return Promise.resolve([]);
518
- }
519
- var startPos = document.positionAt(0);
520
- var endPos = document.positionAt(document.getText().length);
521
- var fullDocRange = ls.Range.create(startPos, endPos);
522
- var formattedDoc = this.getFormattedCommandsInDocumentV2(document).formattedCommands.join('');
523
- return Promise.resolve([ls.TextEdit.replace(fullDocRange, formattedDoc)]);
524
- };
525
- // Method is not triggered, instead doRangeFormat is invoked with the range of the caret's line.
526
- KustoLanguageService.prototype.doCurrentCommandFormat = function (document, caretPosition) {
527
- var offset = document.offsetAt(caretPosition);
528
- var range = this.createRange(document, offset - 1, offset + 1);
529
- return this.doRangeFormat(document, range);
530
- };
531
- KustoLanguageService.prototype.doFolding = function (document) {
532
- if (!document) {
533
- return Promise.resolve([]);
534
- }
535
- return this.getCommandsInDocument(document).then(function (commands) {
536
- return commands.map(function (command) {
537
- // don't count the last empty line as part of the folded range (consider linux, mac, pc newlines)
538
- if (command.text.endsWith('\r\n')) {
539
- command.absoluteEnd -= 2;
540
- }
541
- else if (command.text.endsWith('\r') || command.text.endsWith('\n')) {
542
- --command.absoluteEnd;
543
- }
544
- var startPosition = document.positionAt(command.absoluteStart);
545
- var endPosition = document.positionAt(command.absoluteEnd);
546
- return {
547
- startLine: startPosition.line,
548
- startCharacter: startPosition.character,
549
- endLine: endPosition.line,
550
- endCharacter: endPosition.character,
551
- };
552
- });
553
- });
554
- };
555
- KustoLanguageService.prototype.getClusterReferences = function (document, cursorOffset) {
556
- var _a;
557
- var script = this.parseDocumentV2(document);
558
- var currentBlock = this.getCurrentCommandV2(script, cursorOffset);
559
- var clusterReferences = (_a = currentBlock === null || currentBlock === void 0 ? void 0 : currentBlock.Service) === null || _a === void 0 ? void 0 : _a.GetClusterReferences();
560
- if (!clusterReferences) {
561
- return Promise.resolve([]);
562
- }
563
- var newClustersReferences = [];
564
- var newClustersReferencesSet = new Set(); // used to remove duplicates
565
- // Keep only unique clusters that aren't already exist in the Global State
566
- for (var i = 0; i < clusterReferences.Count; i++) {
567
- var clusterReference = clusterReferences.getItem(i);
568
- var clusterHostName = Kusto.Language.KustoFacts.GetHostName(clusterReference.Cluster);
569
- // ignore duplicates
570
- if (newClustersReferencesSet.has(clusterHostName)) {
571
- continue;
572
- }
573
- newClustersReferencesSet.add(clusterHostName);
574
- // ignore references that are already in the GlobalState.
575
- if (!this._clustersSetInGlobalState.has(clusterHostName)) {
576
- newClustersReferences.push({ clusterName: clusterHostName });
577
- }
578
- }
579
- return Promise.resolve(newClustersReferences);
580
- };
581
- KustoLanguageService.prototype.getDatabaseReferences = function (document, cursorOffset) {
582
- var _a;
583
- var script = this.parseDocumentV2(document);
584
- var currentBlock = this.getCurrentCommandV2(script, cursorOffset);
585
- var databasesReferences = (_a = currentBlock === null || currentBlock === void 0 ? void 0 : currentBlock.Service) === null || _a === void 0 ? void 0 : _a.GetDatabaseReferences();
586
- if (!databasesReferences) {
587
- return Promise.resolve([]);
588
- }
589
- var newDatabasesReferences = [];
590
- var newDatabasesReferencesSet = new Set();
591
- for (var i1 = 0; i1 < databasesReferences.Count; i1++) {
592
- var databaseReference = databasesReferences.getItem(i1);
593
- var clusterHostName = Kusto.Language.KustoFacts.GetHostName(databaseReference.Cluster);
594
- // ignore duplicates
595
- var databaseReferenceUniqueId = this.createDatabaseUniqueName(clusterHostName, databaseReference.Database);
596
- if (newDatabasesReferencesSet.has(databaseReferenceUniqueId)) {
597
- continue;
598
- }
599
- newDatabasesReferencesSet.add(databaseReferenceUniqueId);
600
- // ignore references that are already in the GlobalState.
601
- var foundInGlobalState = this._nonEmptyDatabaseSetInGlobalState.has(databaseReferenceUniqueId);
602
- if (!foundInGlobalState) {
603
- newDatabasesReferences.push({
604
- databaseName: databaseReference.Database,
605
- clusterName: databaseReference.Cluster,
606
- });
607
- }
608
- }
609
- return Promise.resolve(newDatabasesReferences);
610
- };
611
- KustoLanguageService.prototype.doValidation = function (document, changeIntervals, includeWarnings, includeSuggestions) {
612
- var _this = this;
613
- // didn't implement validation for v1.
614
- if (!document || !this.isIntellisenseV2()) {
615
- return Promise.resolve([]);
616
- }
617
- var script = this.parseDocumentV2(document);
618
- var blocks = this.toArray(script.Blocks);
619
- if (changeIntervals.length > 0) {
620
- blocks = this.getAffectedBlocks(blocks, changeIntervals);
621
- }
622
- var diagnostics = blocks
623
- .map(function (block) {
624
- // GetDiagnostics returns the errors in the block
625
- var diagnostics = _this.toArray(block.Service.GetDiagnostics());
626
- var enableWarnings = includeWarnings !== null && includeWarnings !== void 0 ? includeWarnings : _this._languageSettings.enableQueryWarnings;
627
- var enableSuggestions = includeSuggestions !== null && includeSuggestions !== void 0 ? includeSuggestions : _this._languageSettings.enableQuerySuggestions;
628
- if (enableWarnings || enableSuggestions) {
629
- // Concat Warnings and suggestions to the diagnostics
630
- var warningAndSuggestionDiagnostics = block.Service.GetAnalyzerDiagnostics(true);
631
- var filterredDiagnostics = _this.toArray(warningAndSuggestionDiagnostics).filter(function (d) {
632
- var _a;
633
- var allowSeverity = (enableWarnings && d.Severity === 'Warning') ||
634
- (enableSuggestions && d.Severity === 'Suggestion');
635
- var allowCode = !((_a = _this._languageSettings.disabledDiagnoticCodes) === null || _a === void 0 ? void 0 : _a.includes(d.Code));
636
- return allowSeverity && allowCode;
637
- });
638
- diagnostics = diagnostics.concat(filterredDiagnostics);
639
- }
640
- return diagnostics;
641
- })
642
- .reduce(function (prev, curr) { return prev.concat(curr); }, []);
643
- var lsDiagnostics = this.toLsDiagnostics(diagnostics, document);
644
- return Promise.resolve(lsDiagnostics);
645
- };
646
- KustoLanguageService.prototype.getApplyCodeActions = function (document, start, end) {
647
- var script = this.parseDocumentV2(document);
648
- var block = this.getAffectedBlocks(this.toArray(script.Blocks), [{ start: start, end: end }])[0];
649
- var codeActionInfo = block.Service.GetCodeActions(start, start, end - start + 1, null, true, null, new Kusto.Language.Utils.CancellationToken());
650
- var codeActions = this.toArray(codeActionInfo.Actions);
651
- // Some code actions are of type "MenuAction". We want to flat them out, to show them seperately.
652
- var flatCodeActions = [];
653
- for (var i = 0; i < codeActions.length; i++) {
654
- flatCodeActions.push.apply(flatCodeActions, this.flattenCodeActions(codeActions[i]));
655
- }
656
- return flatCodeActions;
657
- };
658
- KustoLanguageService.prototype.getResultActions = function (document, start, end) {
659
- var _this = this;
660
- var script = this.parseDocumentV2(document);
661
- var block = this.getAffectedBlocks(this.toArray(script.Blocks), [{ start: start, end: end }])[0];
662
- var applyCodeActions = this.getApplyCodeActions(document, start, end);
663
- var resultActionsMap = applyCodeActions
664
- .map(function (applyCodeAction) {
665
- var changes = [];
666
- var codeActionResults = _this.toArray(block.Service.ApplyCodeAction(applyCodeAction, start).Actions);
667
- var changeTextAction = codeActionResults.find(function (c) { return c instanceof Kusto.Language.Editor.ChangeTextAction; });
668
- if (changeTextAction) {
669
- changes = _this.toArray(changeTextAction.Changes).map(function (change) { return ({
670
- start: change.Start + block.Start,
671
- deleteLength: change.DeleteLength,
672
- insertText: change.InsertText,
673
- }); });
674
- }
675
- return { title: applyCodeAction.Title, changes: changes };
676
- })
677
- .filter(function (resultAction) { return resultAction.changes.length; });
678
- return Promise.resolve(resultActionsMap);
679
- };
680
- KustoLanguageService.prototype.flattenCodeActions = function (codeAction) {
681
- var applyActions = [];
682
- if (codeAction instanceof k2.ApplyAction) {
683
- applyActions.push(codeAction);
684
- }
685
- else if (codeAction instanceof k2.MenuAction) {
686
- var nestedCodeActions = this.toArray(codeAction.Actions);
687
- for (var i = 0; i < nestedCodeActions.length; i++) {
688
- applyActions.push.apply(applyActions, this.flattenCodeActions(nestedCodeActions[i]));
689
- }
690
- }
691
- return applyActions;
692
- };
693
- KustoLanguageService.prototype.toLsDiagnostics = function (diagnostics, document) {
694
- return diagnostics
695
- .filter(function (diag) { return diag.HasLocation; })
696
- .map(function (diag) {
697
- var start = document.positionAt(diag.Start);
698
- var end = document.positionAt(diag.Start + diag.Length);
699
- var range = ls.Range.create(start, end);
700
- var severity;
701
- switch (diag.Severity) {
702
- case 'Suggestion':
703
- severity = ls.DiagnosticSeverity.Information;
704
- break;
705
- case 'Warning':
706
- severity = ls.DiagnosticSeverity.Warning;
707
- break;
708
- default:
709
- severity = ls.DiagnosticSeverity.Error;
710
- }
711
- return ls.Diagnostic.create(range, diag.Message, severity, diag.Code);
712
- });
713
- };
714
- /**
715
- * Colorize one or more kusto blocks (a.k.a commands), or just the entire document.
716
- * Supports multi-cursor editing (colorizes blocks on multiple changes).
717
- * @param document The document to colorize
718
- * @param changeIntervals an array containing 0 or more changed intervals. if the array is empty - just colorize the entire row.
719
- * if the array contains a single change - just color the kusto blocks that wraps this change. If multiple changes are provided,
720
- * colorize all blocks that intersect these changes.
721
- * The code will try to only parse once if this is the same command.
722
- */
723
- KustoLanguageService.prototype.doColorization = function (document, changeIntervals) {
724
- var _this = this;
725
- if (!document || !this._languageSettings.useSemanticColorization) {
726
- return Promise.resolve([]);
727
- }
728
- // V1 intellisense
729
- if (!this.isIntellisenseV2()) {
730
- // Handle specific ranges changes (and not the whole doc)
731
- if (changeIntervals.length > 0) {
732
- this.parseDocumentV1(document, k.ParseMode.CommandTokensOnly);
733
- var affectedCommands = this.toArray(this._parser.Results).filter(function (command) {
734
- // a command is affected if it intersects at least on of changed ranges.
735
- return command // command can be null. we're filtering all nulls in the array.
736
- ? changeIntervals.some(function (_a) {
737
- var changeStart = _a.start, changeEnd = _a.end;
738
- // both intervals intersect if either the start or the end of interval A is inside interval B.
739
- // If we deleted something at the end of a command, the interval will not intersect the current command.
740
- // so we also want consider affected commands commands the end where the interval begins.
741
- // hence the + 1.
742
- return (command.AbsoluteStart >= changeStart && command.AbsoluteStart <= changeEnd) ||
743
- (changeStart >= command.AbsoluteStart && changeStart <= command.AbsoluteEnd + 1);
744
- })
745
- : false;
746
- });
747
- // We're not on any command so don't return any classifications.
748
- // this can happen if we're at the and of the file and deleting empty rows (for example).
749
- if (!affectedCommands || affectedCommands.length === 0) {
750
- return Promise.resolve([
751
- {
752
- classifications: [],
753
- absoluteStart: changeIntervals[0].start,
754
- absoluteEnd: changeIntervals[0].end,
755
- },
756
- ]);
757
- }
758
- var results = affectedCommands.map(function (command) {
759
- _this.parseTextV1(command.Text, k.ParseMode.TokenizeAllText);
760
- var k2Classifications = _this.getClassificationsFromParseResult(command.AbsoluteStart);
761
- var classifications = toClassifiedRange(k2Classifications);
762
- return {
763
- classifications: classifications,
764
- absoluteStart: command.AbsoluteStart,
765
- absoluteEnd: command.AbsoluteEnd,
766
- };
767
- });
768
- return Promise.resolve(results);
769
- }
770
- // Entire document requested
771
- this.parseDocumentV1(document, k.ParseMode.TokenizeAllText);
772
- var classifications_1 = this.getClassificationsFromParseResult();
773
- return Promise.resolve([
774
- {
775
- classifications: toClassifiedRange(classifications_1),
776
- absoluteStart: 0,
777
- absoluteEnd: document.getText().length,
778
- },
779
- ]);
780
- }
781
- // V2 intellisense
782
- var script = this.parseDocumentV2(document);
783
- if (changeIntervals.length > 0) {
784
- var blocks_1 = this.toArray(script.Blocks);
785
- var affectedBlocks = this.getAffectedBlocks(blocks_1, changeIntervals);
786
- var result = affectedBlocks.map(function (block) { return ({
787
- classifications: toClassifiedRange(_this.toArray(block.Service.GetClassifications(block.Start, block.End).Classifications)),
788
- absoluteStart: block.Start,
789
- absoluteEnd: block.End,
790
- }); });
791
- return Promise.resolve(result);
792
- }
793
- // Entire document requested
794
- var blocks = this.toArray(script.Blocks);
795
- var classifications = blocks
796
- .map(function (block) {
797
- return _this.toArray(block.Service.GetClassifications(block.Start, block.Length).Classifications);
798
- })
799
- .reduce(function (prev, curr) { return prev.concat(curr); }, []);
800
- return Promise.resolve([
801
- {
802
- classifications: toClassifiedRange(classifications),
803
- absoluteStart: 0,
804
- absoluteEnd: document.getText().length,
805
- },
806
- ]);
807
- };
808
- KustoLanguageService.prototype.getAffectedBlocks = function (blocks, changeIntervals) {
809
- return blocks.filter(function (block) {
810
- // a command is affected if it intersects at least on of changed ranges.
811
- return block // command can be null. we're filtering all nulls in the array.
812
- ? changeIntervals.some(function (_a) {
813
- var changeStart = _a.start, changeEnd = _a.end;
814
- // both intervals intersect if either the start or the end of interval A is inside interval B.
815
- return (block.Start >= changeStart && block.Start <= changeEnd) ||
816
- (changeStart >= block.Start && changeStart <= block.End + 1);
817
- })
818
- : false;
819
- });
820
- };
821
- KustoLanguageService.prototype.addClusterToSchema = function (document, clusterName, databaseNames) {
822
- var clusterNameOnly = Kusto.Language.KustoFacts.GetHostName(clusterName);
823
- var cluster = this._kustoJsSchemaV2.GetCluster$1(clusterNameOnly);
824
- if (cluster) {
825
- // add databases that are not already in the cluster.
826
- databaseNames
827
- .filter(function (databaseName) { return !cluster.GetDatabase(databaseName); })
828
- .map(function (databaseName) {
829
- var symbol = new sym.DatabaseSymbol.$ctor1(databaseName, undefined, false);
830
- cluster = cluster.AddDatabase(symbol);
831
- });
832
- }
833
- if (!cluster) {
834
- var databaseSymbols = databaseNames.map(function (databaseName) {
835
- var symbol = new sym.DatabaseSymbol.$ctor1(databaseName, undefined, false);
836
- return symbol;
837
- });
838
- var databaseSymbolsList = new (List(sym.DatabaseSymbol).$ctor1)(databaseSymbols);
839
- cluster = new sym.ClusterSymbol.$ctor1(clusterNameOnly, databaseSymbolsList, false);
840
- }
841
- this._kustoJsSchemaV2 = this._kustoJsSchemaV2.AddOrReplaceCluster(cluster);
842
- this._script = k2.CodeScript.From$1(document.getText(), this._kustoJsSchemaV2);
843
- return Promise.resolve();
844
- };
845
- KustoLanguageService.prototype.addDatabaseToSchema = function (document, clusterName, databaseSchema) {
846
- var clusterHostName = Kusto.Language.KustoFacts.GetHostName(clusterName);
847
- var cluster = this._kustoJsSchemaV2.GetCluster$1(clusterHostName);
848
- if (!cluster) {
849
- cluster = new sym.ClusterSymbol.$ctor1(clusterHostName, null, false);
850
- }
851
- var databaseSymbol = KustoLanguageService.convertToDatabaseSymbol(databaseSchema);
852
- cluster = cluster.AddOrUpdateDatabase(databaseSymbol);
853
- this._kustoJsSchemaV2 = this._kustoJsSchemaV2.AddOrReplaceCluster(cluster);
854
- this._script = k2.CodeScript.From$1(document.getText(), this._kustoJsSchemaV2);
855
- return Promise.resolve();
856
- };
857
- KustoLanguageService.prototype.setSchema = function (schema) {
858
- var _this = this;
859
- this._schema = schema;
860
- // We support intellisenseV2 only if the clusterType is "Engine", even if the setting is enabled
861
- if (this._languageSettings.useIntellisenseV2 && schema && schema.clusterType === 'Engine') {
862
- var kustoJsSchemaV2 = this.convertToKustoJsSchemaV2(schema);
863
- this._kustoJsSchemaV2 = kustoJsSchemaV2;
864
- this._script = undefined;
865
- this._parsePropertiesV2 = undefined;
866
- }
867
- // since V2 doesn't support control commands, we're initializing V1 intellisense for both cases and we'll going to use V1 intellisense for control commands.
868
- return new Promise(function (resolve, reject) {
869
- var kustoJsSchema = schema ? KustoLanguageService.convertToKustoJsSchema(schema) : undefined;
870
- _this._kustoJsSchema = kustoJsSchema;
871
- _this.createRulesProvider(kustoJsSchema, schema.clusterType);
872
- resolve(undefined);
873
- });
874
- };
875
- KustoLanguageService.prototype.setParameters = function (scalarParameters, tabularParameters) {
876
- if (!this._languageSettings.useIntellisenseV2 || this._schema.clusterType !== 'Engine') {
877
- throw new Error('setParameters requires intellisense V2 and Engine cluster');
878
- }
879
- this._schema.globalScalarParameters = scalarParameters;
880
- this._schema.globalTabularParameters = tabularParameters;
881
- var scalarSymbols = scalarParameters.map(function (param) { return KustoLanguageService.createParameterSymbol(param); });
882
- var tabularSymbols = tabularParameters.map(function (param) {
883
- return KustoLanguageService.createTabularParameterSymbol(param);
884
- });
885
- this._kustoJsSchemaV2 = this._kustoJsSchemaV2.WithParameters(KustoLanguageService.toBridgeList(__spreadArray(__spreadArray([], scalarSymbols, true), tabularSymbols, true)));
886
- return Promise.resolve(undefined);
887
- };
888
- /**
889
- * A combination of normalizeSchema and setSchema
890
- * @param schema schema json as received from .show schema as json
891
- * @param clusterConnectionString cluster connection string
892
- * @param databaseInContextName name of database in context
893
- */
894
- KustoLanguageService.prototype.setSchemaFromShowSchema = function (schema, clusterConnectionString, databaseInContextName, globalScalarParameters, globalTabularParameters) {
895
- var _this = this;
896
- return this.normalizeSchema(schema, clusterConnectionString, databaseInContextName).then(function (normalized) {
897
- return _this.setSchema(__assign(__assign({}, normalized), { globalScalarParameters: globalScalarParameters, globalTabularParameters: globalTabularParameters }));
898
- });
899
- };
900
- /**
901
- * Converts the result of .show schema as json to a normalized schema used by kusto language service.
902
- * @param schema result of show schema
903
- * @param clusterConnectionString cluster connection string`
904
- * @param databaseInContextName database in context name
905
- */
906
- KustoLanguageService.prototype.normalizeSchema = function (schema, clusterConnectionString, databaseInContextName) {
907
- var databases = Object.keys(schema.Databases)
908
- .map(function (key) { return schema.Databases[key]; })
909
- .map(function (_a) {
910
- var Name = _a.Name, Tables = _a.Tables, ExternalTables = _a.ExternalTables, MaterializedViews = _a.MaterializedViews, Functions = _a.Functions, MinorVersion = _a.MinorVersion, MajorVersion = _a.MajorVersion;
911
- return ({
912
- name: Name,
913
- minorVersion: MinorVersion,
914
- majorVersion: MajorVersion,
915
- tables: [].concat.apply([], [
916
- [Tables, 'Table'],
917
- [MaterializedViews, 'MaterializedView'],
918
- [ExternalTables, 'ExternalTable'],
919
- ]
920
- .filter(function (_a) {
921
- var tableContainer = _a[0];
922
- return tableContainer;
923
- })
924
- .map(function (_a) {
925
- var tableContainer = _a[0], tableEntity = _a[1];
926
- return Object.values(tableContainer).map(function (_a) {
927
- var Name = _a.Name, OrderedColumns = _a.OrderedColumns, DocString = _a.DocString;
928
- return ({
929
- name: Name,
930
- docstring: DocString,
931
- entityType: tableEntity,
932
- columns: OrderedColumns.map(function (_a) {
933
- var Name = _a.Name, Type = _a.Type, DocString = _a.DocString, CslType = _a.CslType, Examples = _a.Examples;
934
- return ({
935
- name: Name,
936
- type: CslType,
937
- docstring: DocString,
938
- examples: Examples,
939
- });
940
- }),
941
- });
942
- });
943
- })),
944
- functions: Object.keys(Functions)
945
- .map(function (key) { return Functions[key]; })
946
- .map(function (_a) {
947
- var Name = _a.Name, Body = _a.Body, DocString = _a.DocString, InputParameters = _a.InputParameters;
948
- return ({
949
- name: Name,
950
- body: Body,
951
- docstring: DocString,
952
- inputParameters: InputParameters.map(function (inputParam) { return ({
953
- name: inputParam.Name,
954
- type: inputParam.Type,
955
- cslType: inputParam.CslType,
956
- cslDefaultValue: inputParam.CslDefaultValue,
957
- columns: inputParam.Columns
958
- ? inputParam.Columns.map(function (col) { return ({
959
- name: col.Name,
960
- type: col.Type,
961
- cslType: col.CslType,
962
- }); })
963
- : inputParam.Columns,
964
- }); }),
965
- });
966
- }),
967
- });
968
- });
969
- var result = {
970
- clusterType: 'Engine',
971
- cluster: {
972
- connectionString: clusterConnectionString,
973
- databases: databases,
974
- },
975
- database: databases.filter(function (db) { return db.name === databaseInContextName; })[0],
976
- };
977
- return Promise.resolve(result);
978
- };
979
- KustoLanguageService.prototype.getSchema = function () {
980
- return Promise.resolve(this._schema);
981
- };
982
- KustoLanguageService.prototype.getCommandInContext = function (document, cursorOffset) {
983
- return this.isIntellisenseV2()
984
- ? this.getCommandInContextV2(document, cursorOffset)
985
- : this.getCommandInContextV1(document, cursorOffset);
986
- };
987
- KustoLanguageService.prototype.getCommandAndLocationInContext = function (document, cursorOffset) {
988
- // We are going to remove v1 intellisense. no use to keep parity.
989
- if (!document || !this.isIntellisenseV2()) {
990
- return Promise.resolve(null);
991
- }
992
- var script = this.parseDocumentV2(document);
993
- var block = this.getCurrentCommandV2(script, cursorOffset);
994
- if (!block) {
995
- return Promise.resolve(null);
996
- }
997
- var start = document.positionAt(block.Start);
998
- var end = document.positionAt(block.End);
999
- var location = ls.Location.create(document.uri, ls.Range.create(start, end));
1000
- var text = block.Text;
1001
- return Promise.resolve({
1002
- text: text,
1003
- location: location,
1004
- });
1005
- };
1006
- KustoLanguageService.prototype.getCommandInContextV1 = function (document, cursorOffset) {
1007
- this.parseDocumentV1(document, k.ParseMode.CommandTokensOnly);
1008
- var command = this.getCurrentCommand(document, cursorOffset);
1009
- if (!command) {
1010
- return Promise.resolve(null);
1011
- }
1012
- return Promise.resolve(command.Text);
1013
- };
1014
- KustoLanguageService.prototype.getCommandInContextV2 = function (document, cursorOffset) {
1015
- if (!document) {
1016
- return Promise.resolve(null);
1017
- }
1018
- var script = this.parseDocumentV2(document);
1019
- var block = this.getCurrentCommandV2(script, cursorOffset);
1020
- if (!block) {
1021
- return Promise.resolve(null);
1022
- }
1023
- // TODO: do we need to do tricks like V1 is doing in this.getCurrentCommand?
1024
- return Promise.resolve(block.Text);
1025
- };
1026
- /**
1027
- * Return an array of commands in document. each command contains the range and text.
1028
- */
1029
- KustoLanguageService.prototype.getCommandsInDocument = function (document) {
1030
- if (!document) {
1031
- return Promise.resolve([]);
1032
- }
1033
- return this.isIntellisenseV2()
1034
- ? this.getCommandsInDocumentV2(document)
1035
- : this.getCommandsInDocumentV1(document);
1036
- };
1037
- KustoLanguageService.prototype.getCommandsInDocumentV1 = function (document) {
1038
- this.parseDocumentV1(document, k.ParseMode.CommandTokensOnly);
1039
- var commands = this.toArray(this._parser.Results);
1040
- return Promise.resolve(commands.map(function (_a) {
1041
- var AbsoluteStart = _a.AbsoluteStart, AbsoluteEnd = _a.AbsoluteEnd, Text = _a.Text;
1042
- return ({
1043
- absoluteStart: AbsoluteStart,
1044
- absoluteEnd: AbsoluteEnd,
1045
- text: Text,
1046
- });
1047
- }));
1048
- };
1049
- KustoLanguageService.prototype.toPlacementStyle = function (formatterPlacementStyle) {
1050
- if (!formatterPlacementStyle) {
1051
- return undefined;
1052
- }
1053
- switch (formatterPlacementStyle) {
1054
- case 'None':
1055
- return k2.PlacementStyle.None;
1056
- case 'NewLine':
1057
- return k2.PlacementStyle.NewLine;
1058
- case 'Smart':
1059
- return k2.PlacementStyle.Smart;
1060
- default:
1061
- throw new Error('Unknown PlacementStyle');
1062
- }
1063
- };
1064
- KustoLanguageService.prototype.getFormattedCommandsInDocumentV2 = function (document, rangeStart, rangeEnd) {
1065
- var _this = this;
1066
- var script = this.parseDocumentV2(document);
1067
- var commands = this.toArray(script.Blocks).filter(function (command) {
1068
- if (!command.Text || command.Text.trim() == '')
1069
- return false;
1070
- if (rangeStart == null || rangeEnd == null)
1071
- return true;
1072
- // calculate command end position without \r\n.
1073
- var commandEnd = command.End;
1074
- var commandText = command.Text;
1075
- for (var i = commandText.length - 1; i >= 0; i--) {
1076
- if (commandText[i] != '\r' && commandText[i] != '\n') {
1077
- break;
1078
- }
1079
- else {
1080
- commandEnd--;
1081
- }
1082
- }
1083
- if (command.Start > rangeStart && command.Start < rangeEnd)
1084
- return true;
1085
- if (commandEnd > rangeStart && commandEnd < rangeEnd)
1086
- return true;
1087
- if (command.Start <= rangeStart && commandEnd >= rangeEnd)
1088
- return true;
1089
- });
1090
- if (commands.length === 0) {
1091
- return { formattedCommands: [] };
1092
- }
1093
- var formattedCommands = commands.map(function (command) {
1094
- var _a, _b;
1095
- var formatterOptions = _this._languageSettings.formatter;
1096
- var formatter = Kusto.Language.Editor.FormattingOptions.Default.WithIndentationSize((_a = formatterOptions === null || formatterOptions === void 0 ? void 0 : formatterOptions.indentationSize) !== null && _a !== void 0 ? _a : 4)
1097
- .WithInsertMissingTokens(false)
1098
- .WithPipeOperatorStyle((_b = _this.toPlacementStyle(formatterOptions === null || formatterOptions === void 0 ? void 0 : formatterOptions.pipeOperatorStyle)) !== null && _b !== void 0 ? _b : k2.PlacementStyle.Smart)
1099
- .WithSemicolonStyle(Kusto.Language.Editor.PlacementStyle.None)
1100
- .WithBrackettingStyle(k2.BrackettingStyle.Diagonal);
1101
- if (rangeStart == null || rangeEnd == null || (rangeStart === command.Start && rangeEnd === command.End)) {
1102
- var result = command.Service.GetFormattedText(formatter);
1103
- return result.Text;
1104
- }
1105
- return command.Service.GetFormattedText(formatter).Text;
1106
- });
1107
- var originalRange = this.createRange(document, commands[0].Start, commands[commands.length - 1].End);
1108
- return { formattedCommands: formattedCommands, originalRange: originalRange };
1109
- };
1110
- KustoLanguageService.prototype.getCommandsInDocumentV2 = function (document) {
1111
- var script = this.parseDocumentV2(document);
1112
- var commands = this.toArray(script.Blocks).filter(function (command) { return command.Text.trim() != ''; });
1113
- return Promise.resolve(commands.map(function (_a) {
1114
- var Start = _a.Start, End = _a.End, Text = _a.Text;
1115
- return ({ absoluteStart: Start, absoluteEnd: End, text: Text });
1116
- }));
1117
- };
1118
- KustoLanguageService.prototype.getClientDirective = function (text) {
1119
- var outParam = { v: null };
1120
- var isClientDirective = k.CslCommandParser.IsClientDirective(text, outParam);
1121
- return Promise.resolve({
1122
- isClientDirective: isClientDirective,
1123
- directiveWithoutLeadingComments: outParam.v,
1124
- });
1125
- };
1126
- KustoLanguageService.prototype.getAdminCommand = function (text) {
1127
- var outParam = { v: null };
1128
- var isAdminCommand = k.CslCommandParser.IsAdminCommand$1(text, outParam);
1129
- return Promise.resolve({
1130
- isAdminCommand: isAdminCommand,
1131
- adminCommandWithoutLeadingComments: outParam.v,
1132
- });
1133
- };
1134
- KustoLanguageService.prototype.findDefinition = function (document, position) {
1135
- if (!document || !this.isIntellisenseV2()) {
1136
- return Promise.resolve([]);
1137
- }
1138
- var script = this.parseDocumentV2(document);
1139
- var cursorOffset = document.offsetAt(position);
1140
- var currentBlock = this.getCurrentCommandV2(script, cursorOffset);
1141
- if (!currentBlock) {
1142
- return Promise.resolve([]);
1143
- }
1144
- var relatedInfo = currentBlock.Service.GetRelatedElements(document.offsetAt(position));
1145
- var relatedElements = this.toArray(relatedInfo.Elements);
1146
- var definition = relatedElements[0];
1147
- if (!definition) {
1148
- return Promise.resolve([]);
1149
- }
1150
- var start = document.positionAt(definition.Start);
1151
- var end = document.positionAt(definition.End);
1152
- var range = ls.Range.create(start, end);
1153
- var location = ls.Location.create(document.uri, range);
1154
- return Promise.resolve([location]);
1155
- };
1156
- KustoLanguageService.prototype.findReferences = function (document, position) {
1157
- if (!document || !this.isIntellisenseV2()) {
1158
- return Promise.resolve([]);
1159
- }
1160
- var script = this.parseDocumentV2(document);
1161
- var cursorOffset = document.offsetAt(position);
1162
- var currentBlock = this.getCurrentCommandV2(script, cursorOffset);
1163
- if (!currentBlock) {
1164
- return Promise.resolve([]);
1165
- }
1166
- var relatedInfo = currentBlock.Service.GetRelatedElements(document.offsetAt(position));
1167
- var relatedElements = this.toArray(relatedInfo.Elements);
1168
- if (!relatedElements || relatedElements.length == 0) {
1169
- return Promise.resolve([]);
1170
- }
1171
- var references = relatedElements.map(function (relatedElement) {
1172
- var start = document.positionAt(relatedElement.Start);
1173
- var end = document.positionAt(relatedElement.End);
1174
- var range = ls.Range.create(start, end);
1175
- var location = ls.Location.create(document.uri, range);
1176
- return location;
1177
- });
1178
- return Promise.resolve(references);
1179
- };
1180
- KustoLanguageService.prototype.getQueryParams = function (document, cursorOffset) {
1181
- if (!document || !this.isIntellisenseV2()) {
1182
- return Promise.resolve([]);
1183
- }
1184
- var script = this.parseDocumentV2(document);
1185
- var parsedAndAnalyzed = this.parseAndAnalyze(document, cursorOffset);
1186
- var queryParamStatements = this.toArray(parsedAndAnalyzed.Syntax.GetDescendants(Kusto.Language.Syntax.QueryParametersStatement));
1187
- if (!queryParamStatements || queryParamStatements.length == 0) {
1188
- return Promise.resolve([]);
1189
- }
1190
- var queryParams = [];
1191
- queryParamStatements.forEach(function (paramStatement) {
1192
- paramStatement.WalkElements(function (el) {
1193
- return el.ReferencedSymbol && el.ReferencedSymbol.Type
1194
- ? queryParams.push({ name: el.ReferencedSymbol.Name, type: el.ReferencedSymbol.Type.Name })
1195
- : undefined;
1196
- });
1197
- });
1198
- return Promise.resolve(queryParams);
1199
- };
1200
- KustoLanguageService.prototype.getRenderInfo = function (document, cursorOffset) {
1201
- var _this = this;
1202
- var parsedAndAnalyzed = this.parseAndAnalyze(document, cursorOffset);
1203
- if (!parsedAndAnalyzed) {
1204
- return Promise.resolve(undefined);
1205
- }
1206
- var renderStatements = this.toArray(parsedAndAnalyzed.Syntax.GetDescendants(Kusto.Language.Syntax.RenderOperator));
1207
- if (!renderStatements || renderStatements.length === 0) {
1208
- return Promise.resolve(undefined);
1209
- }
1210
- // assuming a single render statement
1211
- var renderStatement = renderStatements[0];
1212
- // Start and end relative to block start.
1213
- var startOffset = renderStatement.TextStart;
1214
- var endOffset = renderStatement.End;
1215
- var visualization = renderStatement.ChartType.ValueText;
1216
- var withClause = renderStatement.WithClause;
1217
- if (!withClause) {
1218
- var info = {
1219
- options: {
1220
- visualization: visualization,
1221
- },
1222
- location: { startOffset: startOffset, endOffset: endOffset },
1223
- };
1224
- return Promise.resolve(info);
1225
- }
1226
- var properties = this.toArray(withClause.Properties);
1227
- var props = properties.reduce(function (prev, property) {
1228
- var name = property.Element$1.Name.SimpleName;
1229
- switch (name) {
1230
- case 'xcolumn':
1231
- var value = property.Element$1.Expression.ReferencedSymbol.Name;
1232
- prev[name] = value;
1233
- break;
1234
- case 'ycolumns':
1235
- case 'anomalycolumns':
1236
- var nameNodes = _this.toArray(property.Element$1.Expression.Names);
1237
- var values = nameNodes.map(function (nameNode) { return nameNode.Element$1.SimpleName; });
1238
- prev[name] = values;
1239
- break;
1240
- case 'ymin':
1241
- case 'ymax':
1242
- var numericVal = parseFloat(property.Element$1.Expression.ConstantValue);
1243
- prev[name] = numericVal;
1244
- break;
1245
- case 'title':
1246
- case 'xtitle':
1247
- case 'ytitle':
1248
- case 'visualization':
1249
- case 'series':
1250
- var strVal = property.Element$1.Expression.ConstantValue;
1251
- prev[name] = strVal;
1252
- break;
1253
- case 'xaxis':
1254
- case 'yaxis':
1255
- var scale = property.Element$1.Expression.ConstantValue;
1256
- prev[name] = scale;
1257
- break;
1258
- case 'legend':
1259
- var legend = property.Element$1.Expression.ConstantValue;
1260
- prev[name] = legend;
1261
- break;
1262
- case 'ysplit':
1263
- var split = property.Element$1.Expression.ConstantValue;
1264
- prev[name] = split;
1265
- break;
1266
- case 'accumulate':
1267
- var accumulate = property.Element$1.Expression.ConstantValue;
1268
- prev[name] = accumulate;
1269
- break;
1270
- case 'kind':
1271
- var val = property.Element$1.Expression.ConstantValue;
1272
- prev[name] = val;
1273
- break;
1274
- default:
1275
- assertNever(name);
1276
- }
1277
- return prev;
1278
- }, {});
1279
- var renderOptions = __assign({ visualization: visualization }, props);
1280
- var renderInfo = {
1281
- options: renderOptions,
1282
- location: { startOffset: startOffset, endOffset: endOffset },
1283
- };
1284
- return Promise.resolve(renderInfo);
1285
- };
1286
- KustoLanguageService.prototype.getReferencedSymbols = function (document, offset) {
1287
- var parsedAndAnalyzed = this.parseAndAnalyze(document, offset);
1288
- if (!parsedAndAnalyzed) {
1289
- Promise.resolve([]);
1290
- }
1291
- // We take all referenced symbols in the query
1292
- var referencedSymbols = this.toArray(parsedAndAnalyzed.Syntax.GetDescendants(Kusto.Language.Syntax.Expression))
1293
- .filter(function (expression) { return expression.ReferencedSymbol !== null; })
1294
- .map(function (x) { return x.ReferencedSymbol; });
1295
- var result = referencedSymbols.map(function (sym) {
1296
- var _a;
1297
- return ({
1298
- name: sym.Name,
1299
- kind: (_a = symbolKindToName[sym.Kind]) !== null && _a !== void 0 ? _a : "".concat(sym.Kind),
1300
- display: sym.Display,
1301
- });
1302
- });
1303
- return Promise.resolve(result);
1304
- };
1305
- KustoLanguageService.prototype.getReferencedGlobalParams = function (document, cursorOffset) {
1306
- var parsedAndAnalyzed = this.parseAndAnalyze(document, cursorOffset);
1307
- if (!parsedAndAnalyzed) {
1308
- Promise.resolve([]);
1309
- }
1310
- // We take the ambient parameters
1311
- var ambientParameters = this.toArray(this._kustoJsSchemaV2.Parameters);
1312
- // We take all referenced symbols in the query
1313
- var referencedSymbols = this.toArray(parsedAndAnalyzed.Syntax.GetDescendants(Kusto.Language.Syntax.Expression))
1314
- .filter(function (expression) { return expression.ReferencedSymbol !== null; })
1315
- .map(function (x) { return x.ReferencedSymbol; });
1316
- // The Intersection between them is the ambient parameters that are used in the query.
1317
- // Note: Ideally we would use Set here (or at least array.Include), but were' compiling down to es2015.
1318
- var intersection = referencedSymbols.filter(function (referencedSymbol) {
1319
- return ambientParameters.filter(function (ambientParameter) { return ambientParameter === referencedSymbol; }).length > 0;
1320
- });
1321
- var result = intersection.map(function (param) { return ({ name: param.Name, type: param.Type.Name }); });
1322
- return Promise.resolve(result);
1323
- };
1324
- KustoLanguageService.prototype.getGlobalParams = function (document) {
1325
- if (!this.isIntellisenseV2()) {
1326
- return Promise.resolve([]);
1327
- }
1328
- var params = this.toArray(this._kustoJsSchemaV2.Parameters);
1329
- var result = params.map(function (param) { return ({ name: param.Name, type: param.Type.Name }); });
1330
- return Promise.resolve(result);
1331
- };
1332
- KustoLanguageService.prototype.doRename = function (document, position, newName) {
1333
- var _a;
1334
- if (!document || !this.isIntellisenseV2()) {
1335
- return Promise.resolve(undefined);
1336
- }
1337
- var script = this.parseDocumentV2(document);
1338
- var cursorOffset = document.offsetAt(position);
1339
- var currentBLock = this.getCurrentCommandV2(script, cursorOffset);
1340
- if (!currentBLock) {
1341
- return Promise.resolve(undefined);
1342
- }
1343
- var relatedInfo = currentBLock.Service.GetRelatedElements(document.offsetAt(position));
1344
- var relatedElements = this.toArray(relatedInfo.Elements);
1345
- var declarations = relatedElements.filter(function (e) { return e.Kind == k2.RelatedElementKind.Declaration; });
1346
- // A declaration must be one of the elements
1347
- if (!declarations || declarations.length == 0) {
1348
- return Promise.resolve(undefined);
1349
- }
1350
- var edits = relatedElements.map(function (edit) {
1351
- var start = document.positionAt(edit.Start);
1352
- var end = document.positionAt(edit.End);
1353
- var range = ls.Range.create(start, end);
1354
- return ls.TextEdit.replace(range, newName);
1355
- });
1356
- // create a workspace edit
1357
- var workspaceEdit = { changes: (_a = {}, _a[document.uri] = edits, _a) };
1358
- return Promise.resolve(workspaceEdit);
1359
- };
1360
- KustoLanguageService.prototype.doHover = function (document, position) {
1361
- if (!document || !this.isIntellisenseV2()) {
1362
- return Promise.resolve(undefined);
1363
- }
1364
- var script = this.parseDocumentV2(document);
1365
- var cursorOffset = document.offsetAt(position);
1366
- var currentBLock = this.getCurrentCommandV2(script, cursorOffset);
1367
- if (!currentBLock) {
1368
- return Promise.resolve(undefined);
1369
- }
1370
- var isSupported = currentBLock.Service.IsFeatureSupported(k2.CodeServiceFeatures.QuickInfo, cursorOffset);
1371
- if (!isSupported) {
1372
- return Promise.resolve(undefined);
1373
- }
1374
- var quickInfo = currentBLock.Service.GetQuickInfo(cursorOffset);
1375
- if (!quickInfo || !quickInfo.Items) {
1376
- return Promise.resolve(undefined);
1377
- }
1378
- var items = this.toArray(quickInfo.Items);
1379
- if (!items) {
1380
- return Promise.resolve(undefined);
1381
- }
1382
- // Errors, Warnings and Suggestions are already shown in getDiagnostics. we don't want them in doHover.
1383
- items = items.filter(function (item) {
1384
- return item.Kind !== k2.QuickInfoKind.Error &&
1385
- item.Kind !== k2.QuickInfoKind.Suggestion &&
1386
- item.Kind !== k2.QuickInfoKind.Warning;
1387
- });
1388
- var itemsText = items.map(function (item) { return item.Text.replace('\n\n', '\n* * *\n'); });
1389
- // separate items by horizontal line.
1390
- var text = itemsText.join('\n* * *\n');
1391
- // Instead of just an empty line between the first line (the signature) and the second line (the description)
1392
- // add an horizontal line (* * * in markdown) between them.
1393
- return Promise.resolve({ contents: text });
1394
- };
1395
- Object.defineProperty(KustoLanguageService, "dummySchema", {
1396
- //#region dummy schema for manual testing
1397
- get: function () {
1398
- var database = {
1399
- majorVersion: 0,
1400
- minorVersion: 0,
1401
- name: 'Kuskus',
1402
- tables: [
1403
- {
1404
- name: 'KustoLogs',
1405
- columns: [
1406
- {
1407
- name: 'Source',
1408
- type: 'string',
1409
- },
1410
- {
1411
- name: 'Timestamp',
1412
- type: 'datetime',
1413
- },
1414
- {
1415
- name: 'Directory',
1416
- type: 'string',
1417
- },
1418
- ],
1419
- docstring: 'A dummy description to test that docstring shows as expected when hovering over a table',
1420
- },
1421
- ],
1422
- functions: [
1423
- {
1424
- name: 'HowBig',
1425
- inputParameters: [
1426
- {
1427
- name: 'T',
1428
- columns: [
1429
- {
1430
- name: 'Timestamp',
1431
- type: 'System.DateTime',
1432
- cslType: 'datetime',
1433
- },
1434
- ],
1435
- },
1436
- ],
1437
- docstring: 'A dummy description to test that docstring shows as expected when hovering over a function',
1438
- body: "{\r\n union \r\n (T | count | project V='Volume', Metric = strcat(Count/1e9, ' Billion records')),\r\n (T | summarize FirstRecord=min(Timestamp)| project V='Volume', Metric = strcat(toint((now()-FirstRecord)/1d), ' Days of data (from: ', format_datetime(FirstRecord, 'yyyy-MM-dd'),')')),\r\n (T | where Timestamp > ago(1h) | count | project V='Velocity', Metric = strcat(Count/1e6, ' Million records / hour')),\r\n (T | summarize Latency=now()-max(Timestamp) | project V='Velocity', Metric = strcat(Latency / 1sec, ' seconds latency')),\r\n (T | take 1 | project V='Variety', Metric=tostring(pack_all()))\r\n | order by V \r\n}",
1439
- },
1440
- {
1441
- name: 'FindCIDPast24h',
1442
- inputParameters: [
1443
- {
1444
- name: 'clientActivityId',
1445
- type: 'System.String',
1446
- cslType: 'string',
1447
- },
1448
- ],
1449
- body: '{ KustoLogs | where Timestamp > now(-1d) | where ClientActivityId == clientActivityId} ',
1450
- },
1451
- ],
1452
- };
1453
- var languageServiceSchema = {
1454
- clusterType: 'Engine',
1455
- cluster: {
1456
- connectionString: 'https://kuskus.kusto.windows.net;fed=true',
1457
- databases: [database],
1458
- },
1459
- database: database,
1460
- };
1461
- return languageServiceSchema;
1462
- },
1463
- enumerable: false,
1464
- configurable: true
1465
- });
1466
- //#endregion
1467
- KustoLanguageService.convertToEntityDataType = function (kustoType) { };
1468
- /**
1469
- * We do not want to expose Bridge.Net generated schema, so we expose a cleaner javascript schema.
1470
- * Here it gets converted to the bridge.Net schema
1471
- * @param schema Language Service schema
1472
- */
1473
- KustoLanguageService.convertToKustoJsSchema = function (schema) {
1474
- switch (schema.clusterType) {
1475
- case 'Engine':
1476
- var currentDatabaseName_1 = schema.database ? schema.database.name : undefined;
1477
- var kCluster = new k.KustoIntelliSenseClusterEntity();
1478
- var kDatabaseInContext_1 = undefined;
1479
- kCluster.ConnectionString = schema.cluster.connectionString;
1480
- var databases_1 = [];
1481
- schema.cluster.databases.forEach(function (database) {
1482
- var kDatabase = new k.KustoIntelliSenseDatabaseEntity();
1483
- kDatabase.Name = database.name;
1484
- var tables = [];
1485
- database.tables.forEach(function (table) {
1486
- var kTable = new k.KustoIntelliSenseTableEntity();
1487
- kTable.Name = table.name;
1488
- var cols = [];
1489
- table.columns.forEach(function (column) {
1490
- var kColumn = new k.KustoIntelliSenseColumnEntity();
1491
- kColumn.Name = column.name;
1492
- kColumn.TypeCode = k.EntityDataType[getEntityDataTypeFromCslType(column.type)];
1493
- cols.push(kColumn);
1494
- });
1495
- kTable.Columns = new Bridge.ArrayEnumerable(cols);
1496
- tables.push(kTable);
1497
- });
1498
- var functions = [];
1499
- database.functions.forEach(function (fn) {
1500
- var kFunction = new k.KustoIntelliSenseFunctionEntity();
1501
- (kFunction.Name = fn.name),
1502
- (kFunction.CallName = s.getCallName(fn)),
1503
- (kFunction.Expression = s.getExpression(fn)),
1504
- functions.push(kFunction);
1505
- });
1506
- kDatabase.Tables = new Bridge.ArrayEnumerable(tables);
1507
- kDatabase.Functions = new Bridge.ArrayEnumerable(functions);
1508
- databases_1.push(kDatabase);
1509
- if (database.name == currentDatabaseName_1) {
1510
- kDatabaseInContext_1 = kDatabase;
1511
- }
1512
- });
1513
- kCluster.Databases = new Bridge.ArrayEnumerable(databases_1);
1514
- var kSchema = new k.KustoIntelliSenseQuerySchema(kCluster, kDatabaseInContext_1);
1515
- return kSchema;
1516
- case 'ClusterManager':
1517
- var accounts = schema.accounts.map(function (account) {
1518
- var kAccount = new k.KustoIntelliSenseAccountEntity();
1519
- kAccount.Name = account;
1520
- return kAccount;
1521
- });
1522
- var services = schema.services.map(function (service) {
1523
- var kService = new k.KustoIntelliSenseServiceEntity();
1524
- kService.Name = service;
1525
- return kService;
1526
- });
1527
- var connectionString = schema.connectionString;
1528
- var result = {
1529
- accounts: accounts,
1530
- services: services,
1531
- connectionString: connectionString,
1532
- };
1533
- return result;
1534
- case 'DataManagement':
1535
- return undefined;
1536
- default:
1537
- return assertNever(schema);
1538
- }
1539
- };
1540
- /**
1541
- * Returns something like '(x: string, y: datetime)'
1542
- * @param params scalar parameters
1543
- */
1544
- KustoLanguageService.scalarParametersToSignature = function (params) {
1545
- var signatureWithoutParens = params.map(function (param) { return "".concat(param.name, ": ").concat(param.cslType); }).join(', ');
1546
- return "(".concat(signatureWithoutParens, ")");
1547
- };
1548
- /**
1549
- * Returns something like '(x: string, T: (y: int))'
1550
- * @param params input parameters (tabular or scalar)
1551
- */
1552
- KustoLanguageService.inputParameterToSignature = function (params) {
1553
- var _this = this;
1554
- var signatureWithoutParens = params
1555
- .map(function (param) {
1556
- if (param.columns) {
1557
- var tableSignature = _this.scalarParametersToSignature(param.columns);
1558
- return "".concat(param.name, ": ").concat(tableSignature);
1559
- }
1560
- else {
1561
- return "".concat(param.name, ": ").concat(param.cslType);
1562
- }
1563
- })
1564
- .join(', ');
1565
- return "(".concat(signatureWithoutParens, ")");
1566
- };
1567
- /**
1568
- * converts a function definition to a let statement.
1569
- * @param fn function
1570
- */
1571
- KustoLanguageService.toLetStatement = function (fn) {
1572
- var signature = this.inputParameterToSignature(fn.inputParameters);
1573
- return "let ".concat(fn.name, " = ").concat(signature, " ").concat(fn.body);
1574
- };
1575
- KustoLanguageService.createColumnSymbol = function (col) {
1576
- return new sym.ColumnSymbol(col.name, sym.ScalarTypes.GetSymbol(getCslTypeNameFromClrType(col.type)), col.docstring, null, null, col.examples ? KustoLanguageService.toBridgeList(col.examples) : null);
1577
- };
1578
- KustoLanguageService.createParameterSymbol = function (param) {
1579
- var paramSymbol = Kusto.Language.Symbols.ScalarTypes.GetSymbol(getCslTypeNameFromClrType(param.type));
1580
- return new sym.ParameterSymbol(param.name, paramSymbol, null);
1581
- };
1582
- KustoLanguageService.createTabularParameterSymbol = function (param) {
1583
- var columnSymbols = param.columns.map(function (col) { return KustoLanguageService.createColumnSymbol(col); });
1584
- var para = new Kusto.Language.Symbols.TableSymbol.$ctor4(param.name, columnSymbols);
1585
- return new sym.ParameterSymbol(param.name, para, param.docstring);
1586
- };
1587
- KustoLanguageService.createParameter = function (param) {
1588
- if (!param.columns) {
1589
- var paramSymbol = Kusto.Language.Symbols.ScalarTypes.GetSymbol(getCslTypeNameFromClrType(param.type));
1590
- var expression = param.cslDefaultValue && typeof param.cslDefaultValue === 'string'
1591
- ? parsing.QueryParser.ParseLiteral$1(param.cslDefaultValue)
1592
- : undefined;
1593
- return new sym.Parameter.$ctor3(param.name, paramSymbol, null, null, null, false, null, 1, 1, expression, null);
1594
- }
1595
- if (param.columns.length == 0) {
1596
- return new sym.Parameter.ctor(param.name, sym.ParameterTypeKind.Tabular, sym.ArgumentKind.Expression, null, null, false, null, 1, 1, null, null);
1597
- }
1598
- var argumentType = new sym.TableSymbol.ctor(param.columns.map(function (col) { return KustoLanguageService.createColumnSymbol(col); }));
1599
- return new sym.Parameter.$ctor2(param.name, argumentType);
1600
- };
1601
- KustoLanguageService.convertToDatabaseSymbol = function (db) {
1602
- var createFunctionSymbol = function (fn) {
1603
- var parameters = fn.inputParameters.map(function (param) {
1604
- return KustoLanguageService.createParameter(param);
1605
- });
1606
- // TODO: handle outputColumns (right now it doesn't seem to be implemented for any function).
1607
- return new sym.FunctionSymbol.$ctor14(fn.name, fn.body, KustoLanguageService.toBridgeList(parameters), fn.docstring);
1608
- };
1609
- var createTableSymbol = function (tbl) {
1610
- var _a;
1611
- var columnSymbols = tbl.columns.map(function (col) { return KustoLanguageService.createColumnSymbol(col); });
1612
- var symbol = new sym.TableSymbol.$ctor4(tbl.name, columnSymbols);
1613
- symbol.Description = tbl.docstring;
1614
- switch (tbl.entityType) {
1615
- case 'MaterializedViewTable':
1616
- var mvQuery = (_a = tbl.mvQuery) !== null && _a !== void 0 ? _a : null;
1617
- symbol = new sym.MaterializedViewSymbol.$ctor2(tbl.name, symbol.Columns, mvQuery, tbl.docstring);
1618
- symbol = symbol.WithIsMaterializedView(true);
1619
- break;
1620
- case 'ExternalTable':
1621
- symbol = symbol.WithIsExternal(true);
1622
- break;
1623
- default:
1624
- }
1625
- return symbol;
1626
- };
1627
- var createDatabaseSymbol = function (db) {
1628
- var tableSymbols = db.tables ? db.tables.map(function (tbl) { return createTableSymbol(tbl); }) : [];
1629
- var functionSymbols = db.functions ? db.functions.map(function (fun) { return createFunctionSymbol(fun); }) : [];
1630
- return new sym.DatabaseSymbol.ctor(db.name, tableSymbols.concat(functionSymbols));
1631
- };
1632
- var databaseSymbol = createDatabaseSymbol(db);
1633
- return databaseSymbol;
1634
- };
1635
- KustoLanguageService.prototype.convertToKustoJsSchemaV2 = function (schema) {
1636
- var _a, _b;
1637
- var cached = this._schemaCache[schema.cluster.connectionString];
1638
- // create a cache entry for the cluster if non yet exists.
1639
- if (!cached) {
1640
- this._schemaCache[schema.cluster.connectionString] = {};
1641
- cached = this._schemaCache[schema.cluster.connectionString];
1642
- }
1643
- // Remove deleted databases from cache
1644
- var schemaDbLookup = schema.cluster.databases.reduce(function (prev, curr) { return (prev[curr.name] = curr); }, {});
1645
- Object.keys(cached).map(function (dbName) {
1646
- if (!schemaDbLookup[dbName]) {
1647
- delete cached.dbName;
1648
- }
1649
- });
1650
- var globalState = GlobalState.Default;
1651
- var currentDatabaseName = schema.database ? schema.database.name : undefined;
1652
- var databaseInContext = undefined;
1653
- // Update out-of-data databases to cache
1654
- var databases = schema.cluster.databases.map(function (db) {
1655
- var shouldIncludeFunctions = db.name === currentDatabaseName;
1656
- var cachedDb = cached[db.name];
1657
- // This is an older version than we have, or we need to parse functions.
1658
- if (!cachedDb ||
1659
- cachedDb.database.majorVersion < db.majorVersion ||
1660
- (shouldIncludeFunctions && !cachedDb.includesFunctions)) {
1661
- // only add functions for the database in context (it's very time consuming)
1662
- var databaseSymbol_1 = KustoLanguageService.convertToDatabaseSymbol(db);
1663
- cached[db.name] = { database: db, symbol: databaseSymbol_1, includesFunctions: shouldIncludeFunctions };
1664
- }
1665
- var databaseSymbol = cached[db.name].symbol;
1666
- if (db.name === currentDatabaseName) {
1667
- databaseInContext = databaseSymbol;
1668
- }
1669
- return databaseSymbol;
1670
- });
1671
- // Replace new URL due to polyfill issue in IE
1672
- // const hostname = new URL(schema.cluster.connectionString.split(';')[0]).hostname;
1673
- var hostname = schema.cluster.connectionString.match(/(.*\/\/)?([^\/;]*)/)[2];
1674
- var clusterName = hostname.split('.')[0];
1675
- var clusterSymbol = new sym.ClusterSymbol.ctor(clusterName, databases);
1676
- globalState = globalState.WithCluster(clusterSymbol);
1677
- if (databaseInContext) {
1678
- globalState = globalState.WithDatabase(databaseInContext);
1679
- }
1680
- // Inject global scalar parameters to global scope.
1681
- var scalarParameters = ((_a = schema.globalScalarParameters) !== null && _a !== void 0 ? _a : []).map(function (param) {
1682
- return KustoLanguageService.createParameterSymbol(param);
1683
- });
1684
- // Inject global tabular parameters to global scope.
1685
- var tabularParameters = ((_b = schema.globalTabularParameters) !== null && _b !== void 0 ? _b : []).map(function (param) {
1686
- return KustoLanguageService.createTabularParameterSymbol(param);
1687
- });
1688
- if (tabularParameters.length || scalarParameters.length) {
1689
- globalState = globalState.WithParameters(KustoLanguageService.toBridgeList(__spreadArray(__spreadArray([], scalarParameters, true), tabularParameters, true)));
1690
- }
1691
- return globalState;
1692
- };
1693
- KustoLanguageService.prototype.getClassificationsFromParseResult = function (offset) {
1694
- var _this = this;
1695
- if (offset === void 0) { offset = 0; }
1696
- var classifications = this.toArray(this._parser.Results)
1697
- .map(function (command) { return _this.toArray(command.Tokens); })
1698
- .reduce(function (prev, curr) { return prev.concat(curr); }, [])
1699
- .map(function (cslCommandToken) {
1700
- var range = new k2.ClassifiedRange(_this.tokenKindToClassificationKind(cslCommandToken.TokenKind), cslCommandToken.AbsoluteStart + offset, cslCommandToken.Length);
1701
- return range;
1702
- });
1703
- return classifications;
1704
- };
1705
- /**
1706
- * trim trailing newlines from range
1707
- */
1708
- KustoLanguageService.trimTrailingNewlineFromRange = function (textInRange, rangeStartOffset, document, range) {
1709
- var currentIndex = textInRange.length - 1;
1710
- while (textInRange[currentIndex] === '\r' || textInRange[currentIndex] === '\n') {
1711
- --currentIndex;
1712
- }
1713
- var newEndOffset = rangeStartOffset + currentIndex + 1;
1714
- var newEndPosition = document.positionAt(newEndOffset);
1715
- var newRange = ls.Range.create(range.start, newEndPosition);
1716
- return newRange;
1717
- };
1718
- /**
1719
- * Maps numbers to strings, such that if a>b numerically, f(a)>f(b) lexicographically.
1720
- * 1 -> "a", 26 -> "z", 27 -> "za", 28 -> "zb", 52 -> "zz", 53 ->"zza"
1721
- * @param order - The number to be converted to a sorting-string. order should start at 1.
1722
- * @returns A string repenting the order.
1723
- */
1724
- KustoLanguageService.prototype.getSortText = function (order) {
1725
- if (order <= 0) {
1726
- throw new RangeError("order should be a number >= 1. instead got ".concat(order));
1727
- }
1728
- var sortText = '';
1729
- var numCharacters = 26; // "z" - "a" + 1;
1730
- var div = Math.floor(order / numCharacters);
1731
- for (var i = 0; i < div; ++i) {
1732
- sortText += 'z';
1733
- }
1734
- var reminder = order % numCharacters;
1735
- if (reminder > 0) {
1736
- sortText += String.fromCharCode(96 + reminder);
1737
- }
1738
- return sortText;
1739
- };
1740
- /**
1741
- * ParseTextV1 parses the given text with the given parse mode.
1742
- * Additionally - it will make sure not to provide rules provider for non-engine clusters
1743
- * since the only rules provider parse can handle is the engine's. It will try to look for function
1744
- * definitions to colorize and will throw since they're not there.
1745
- * @param text
1746
- * @param parseMode
1747
- */
1748
- KustoLanguageService.prototype.parseTextV1 = function (text, parseMode) {
1749
- this._parser.Parse(this._schema.clusterType === 'Engine' ? this._rulesProvider : null, text, parseMode);
1750
- };
1751
- KustoLanguageService.prototype.parseDocumentV1 = function (document, parseMode) {
1752
- // already parsed a later version, or better parse mode for this uri
1753
- if (this._parsePropertiesV1 &&
1754
- !this._parsePropertiesV1.isParseNeeded(document, this._rulesProvider, parseMode)) {
1755
- return;
1756
- }
1757
- this.parseTextV1(document.getText(), parseMode);
1758
- this._parsePropertiesV1 = new ParseProperties(document.version, document.uri, this._rulesProvider, parseMode);
1759
- };
1760
- KustoLanguageService.prototype.parseDocumentV2 = function (document) {
1761
- if (this._parsePropertiesV2 && !this._parsePropertiesV2.isParseNeeded(document, this._rulesProvider)) {
1762
- return this._script;
1763
- }
1764
- if (!this._script) {
1765
- this._script = k2.CodeScript.From$1(document.getText(), this._kustoJsSchemaV2);
1766
- }
1767
- else {
1768
- this._script = this._script.WithText(document.getText());
1769
- }
1770
- this._parsePropertiesV2 = new ParseProperties(document.version, document.uri);
1771
- return this._script;
1772
- };
1773
- /**
1774
- * Return the CslCommand that wraps the caret location, or undefined if caret is outside any command
1775
- * @param document the document to extract the current command from
1776
- * @param caretAbsolutePosition absolute caret position
1777
- */
1778
- KustoLanguageService.prototype.getCurrentCommand = function (document, caretAbsolutePosition) {
1779
- var commands = this.toArray(this._parser.Results);
1780
- var command = commands.filter(function (command) { return command.AbsoluteStart <= caretAbsolutePosition && command.AbsoluteEnd >= caretAbsolutePosition; })[0];
1781
- // There is an edge case when cursor appears at the end of the command
1782
- // which is not yet considered to be part of the parsed command (therefore: +1 for the AbsoluteEdit property)
1783
- if (!command) {
1784
- command = commands.filter(function (command) {
1785
- return command.AbsoluteStart <= caretAbsolutePosition && command.AbsoluteEnd + 1 >= caretAbsolutePosition;
1786
- })[0];
1787
- // If we have 2 newlines in the end of the text the cursor is _probably_ at the end of the text
1788
- // which this means that we're not actually standing on any command. Thus return null.
1789
- if (!command || command.Text.endsWith('\r\n\r\n')) {
1790
- return null;
1791
- }
1792
- }
1793
- return command;
1794
- };
1795
- KustoLanguageService.prototype.getCurrentCommandV2 = function (script, offset) {
1796
- var block = script.GetBlockAtPosition(offset);
1797
- return block;
1798
- };
1799
- KustoLanguageService.prototype.getTextToInsert = function (rule, option) {
1800
- var beforeApplyInfo = rule.GetBeforeApplyInfo(option.Value);
1801
- var afterApplyInfo = rule.GetAfterApplyInfo(option.Value);
1802
- // this is the basic text to be inserted,
1803
- // but we still need to figure out where the cursor will end up after completion is applied.
1804
- var insertText = beforeApplyInfo.Text || '' + option.Value + afterApplyInfo.Text || '';
1805
- var insertTextFormat = ls.InsertTextFormat.PlainText;
1806
- var snippetFinalTabStop = '$0';
1807
- if (afterApplyInfo.OffsetToken && afterApplyInfo.OffsetPosition) {
1808
- var tokenOffset = insertText.indexOf(afterApplyInfo.OffsetToken);
1809
- if (tokenOffset >= 0) {
1810
- insertText = this.insertToString(insertText, snippetFinalTabStop, tokenOffset - insertText.length + afterApplyInfo.OffsetPosition);
1811
- insertTextFormat = ls.InsertTextFormat.Snippet;
1812
- }
1813
- }
1814
- else if (afterApplyInfo.OffsetPosition) {
1815
- // We only handle negative offsets
1816
- insertText = this.insertToString(insertText, snippetFinalTabStop, afterApplyInfo.OffsetPosition);
1817
- insertTextFormat = ls.InsertTextFormat.Snippet;
1818
- }
1819
- return { insertText: insertText, insertTextFormat: insertTextFormat };
1820
- };
1821
- /**
1822
- * create a new string with stringToInsert inserted at offsetFromEnd in originalString.
1823
- * @param originalString string to insert to
1824
- * @param stringToInsert string to insert
1825
- * @param offsetFromEnd a negative number that will represent offset to the left. 0 means simple concat
1826
- */
1827
- KustoLanguageService.prototype.insertToString = function (originalString, stringToInsert, offsetFromEnd) {
1828
- var index = originalString.length + offsetFromEnd;
1829
- if (offsetFromEnd >= 0 || index < 0) {
1830
- return originalString; // Cannot insert before or after the string
1831
- }
1832
- var before = originalString.substring(0, index);
1833
- var after = originalString.substring(index);
1834
- return before + stringToInsert + after;
1835
- };
1836
- KustoLanguageService.prototype.getCommandWithoutLastWord = function (text) {
1837
- var lastWordRegex = XRegExp('[\\w_]*$', 's');
1838
- return text.replace(lastWordRegex, '');
1839
- };
1840
- KustoLanguageService.prototype.createRulesProvider = function (schema, clusterType) {
1841
- var queryParameters = new (List(String))();
1842
- var availableClusters = new (List(String))();
1843
- this._parser = new k.CslCommandParser();
1844
- if (clusterType == 'Engine') {
1845
- var engineSchema = schema;
1846
- this._rulesProvider =
1847
- this._languageSettings && this._languageSettings.includeControlCommands
1848
- ? new k.CslIntelliSenseRulesProvider.$ctor1(engineSchema.Cluster, engineSchema, queryParameters, availableClusters, null, true, true)
1849
- : new k.CslQueryIntelliSenseRulesProvider.$ctor1(engineSchema.Cluster, engineSchema, queryParameters, availableClusters, null, null, null);
1850
- return;
1851
- }
1852
- if (clusterType === 'DataManagement') {
1853
- this._rulesProvider = new k.DataManagerIntelliSenseRulesProvider(null);
1854
- return;
1855
- }
1856
- // This is a cluster manger
1857
- var _a = schema, accounts = _a.accounts, services = _a.services, connectionString = _a.connectionString;
1858
- new k.KustoIntelliSenseAccountEntity();
1859
- new k.KustoIntelliSenseServiceEntity();
1860
- this._rulesProvider = new k.ClusterManagerIntelliSenseRulesProvider.$ctor1(new Bridge.ArrayEnumerable(accounts), new Bridge.ArrayEnumerable(services), connectionString);
1861
- };
1862
- KustoLanguageService.prototype.kustoKindToLsKind = function (kustoKind) {
1863
- var res = this._kustoKindtolsKind[kustoKind];
1864
- return res ? res : ls.CompletionItemKind.Variable;
1865
- };
1866
- KustoLanguageService.prototype.kustoKindToLsKindV2 = function (kustoKind) {
1867
- var res = this._kustoKindToLsKindV2[kustoKind];
1868
- return res ? res : ls.CompletionItemKind.Variable;
1869
- };
1870
- KustoLanguageService.prototype.createRange = function (document, start, end) {
1871
- return ls.Range.create(document.positionAt(start), document.positionAt(end));
1872
- };
1873
- KustoLanguageService.prototype.toArray = function (bridgeList) {
1874
- return Bridge.toArray(bridgeList);
1875
- };
1876
- KustoLanguageService.toBridgeList = function (array) {
1877
- // copied from bridge.js from the implementation of Enumerable.prototype.toList
1878
- return new (System.Collections.Generic.List$1(System.Object).$ctor1)(array);
1879
- };
1880
- KustoLanguageService.prototype.tokenKindToClassificationKind = function (token) {
1881
- var conversion = this._tokenKindToClassificationKind[token];
1882
- return conversion || k2.ClassificationKind.PlainText;
1883
- };
1884
- KustoLanguageService.prototype.parseAndAnalyze = function (document, cursorOffset) {
1885
- if (!document || !this.isIntellisenseV2()) {
1886
- return undefined;
1887
- }
1888
- var script = this.parseDocumentV2(document);
1889
- var text = script.Text;
1890
- if (cursorOffset !== undefined) {
1891
- var currentBlock = this.getCurrentCommandV2(script, cursorOffset);
1892
- if (!currentBlock) {
1893
- return undefined;
1894
- }
1895
- text = currentBlock.Text;
1896
- }
1897
- var parsedAndAnalyzed = Kusto.Language.KustoCode.ParseAndAnalyze(text, this._kustoJsSchemaV2);
1898
- return parsedAndAnalyzed;
1899
- };
1900
- return KustoLanguageService;
1901
- }());
1902
- var languageService = new KustoLanguageService(KustoLanguageService.dummySchema, {
1903
- includeControlCommands: true,
1904
- useIntellisenseV2: true,
1905
- useSemanticColorization: true,
1906
- });
1907
- /**
1908
- * Obtain an instance of the kusto language service.
1909
- */
1910
- export function getKustoLanguageService() {
1911
- return languageService;
1912
- }