@kusto/monaco-kusto 4.0.4 → 4.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,72 +1,72 @@
1
- // Definition of schema object in the context of language services. This model is exposed to consumers of this library.
2
- define('vs/language/kusto/languageService/schema',["require", "exports"], function (require, exports) {
3
- "use strict";
4
- Object.defineProperty(exports, "__esModule", { value: true });
5
- exports.getInputParametersAsCslString = exports.getExpression = exports.getCallName = exports.getEntityDataTypeFromCslType = exports.getCslTypeNameFromClrType = void 0;
6
- var dotnetTypeToKustoType = {
7
- 'System.SByte': 'bool',
8
- 'System.Byte': 'uint8',
9
- 'System.Int16': 'int16',
10
- 'System.UInt16': 'uint16',
11
- 'System.Int32': 'int',
12
- 'System.UInt32': 'uint',
13
- 'System.Int64': 'long',
14
- 'System.UInt64': 'ulong',
15
- 'System.String': 'string',
16
- 'System.Single': 'float',
17
- 'System.Double': 'real',
18
- 'System.DateTime': 'datetime',
19
- 'System.TimeSpan': 'timespan',
20
- 'System.Guid': 'guid',
21
- 'System.Boolean': 'bool',
22
- 'Newtonsoft.Json.Linq.JArray': 'dynamic',
23
- 'Newtonsoft.Json.Linq.JObject': 'dynamic',
24
- 'Newtonsoft.Json.Linq.JToken': 'dynamic',
25
- 'System.Object': 'dynamic',
26
- 'System.Data.SqlTypes.SqlDecimal': 'decimal'
27
- };
28
- exports.getCslTypeNameFromClrType = function (clrType) { return dotnetTypeToKustoType[clrType] || clrType; };
29
- var kustoTypeToEntityDataType = {
30
- object: 'Object',
31
- bool: 'Boolean',
32
- uint8: 'Byte',
33
- int16: 'Int16',
34
- uint16: 'UInt16',
35
- int: 'Int32',
36
- uint: 'UInt32',
37
- long: 'Int64',
38
- ulong: 'UInt64',
39
- float: 'Single',
40
- real: 'Double',
41
- decimal: 'Decimal',
42
- datetime: 'DateTime',
43
- string: 'String',
44
- dynamic: 'Dynamic',
45
- timespan: 'TimeSpan'
46
- };
47
- exports.getEntityDataTypeFromCslType = function (cslType) { return kustoTypeToEntityDataType[cslType] || cslType; };
48
- exports.getCallName = function (fn) {
49
- return fn.name + "(" + fn.inputParameters.map(function (p) { return "{" + p.name + "}"; }).join(',') + ")";
50
- };
51
- exports.getExpression = function (fn) {
52
- return "let " + fn.name + " = " + exports.getInputParametersAsCslString(fn.inputParameters) + " " + fn.body;
53
- };
54
- exports.getInputParametersAsCslString = function (inputParameters) {
55
- return "(" + inputParameters.map(function (inputParameter) { return getInputParameterAsCslString(inputParameter); }).join(',') + ")";
56
- };
57
- var getInputParameterAsCslString = function (inputParameter) {
58
- // If this is a tabular parameter
59
- if (inputParameter.columns && inputParameter.columns.length > 0) {
60
- var attributesAsString = inputParameter.columns
61
- .map(function (col) { return col.name + ":" + (col.cslType || exports.getCslTypeNameFromClrType(col.type)); })
62
- .join(',');
63
- return inputParameter.name + ":" + (attributesAsString === '' ? '*' : attributesAsString);
64
- }
65
- else {
66
- return inputParameter.name + ":" + (inputParameter.cslType || exports.getCslTypeNameFromClrType(inputParameter.type));
67
- }
68
- };
69
- });
1
+ // Definition of schema object in the context of language services. This model is exposed to consumers of this library.
2
+ define('vs/language/kusto/languageService/schema',["require", "exports"], function (require, exports) {
3
+ "use strict";
4
+ Object.defineProperty(exports, "__esModule", { value: true });
5
+ exports.getInputParametersAsCslString = exports.getExpression = exports.getCallName = exports.getEntityDataTypeFromCslType = exports.getCslTypeNameFromClrType = void 0;
6
+ var dotnetTypeToKustoType = {
7
+ 'System.SByte': 'bool',
8
+ 'System.Byte': 'uint8',
9
+ 'System.Int16': 'int16',
10
+ 'System.UInt16': 'uint16',
11
+ 'System.Int32': 'int',
12
+ 'System.UInt32': 'uint',
13
+ 'System.Int64': 'long',
14
+ 'System.UInt64': 'ulong',
15
+ 'System.String': 'string',
16
+ 'System.Single': 'float',
17
+ 'System.Double': 'real',
18
+ 'System.DateTime': 'datetime',
19
+ 'System.TimeSpan': 'timespan',
20
+ 'System.Guid': 'guid',
21
+ 'System.Boolean': 'bool',
22
+ 'Newtonsoft.Json.Linq.JArray': 'dynamic',
23
+ 'Newtonsoft.Json.Linq.JObject': 'dynamic',
24
+ 'Newtonsoft.Json.Linq.JToken': 'dynamic',
25
+ 'System.Object': 'dynamic',
26
+ 'System.Data.SqlTypes.SqlDecimal': 'decimal'
27
+ };
28
+ exports.getCslTypeNameFromClrType = function (clrType) { return dotnetTypeToKustoType[clrType] || clrType; };
29
+ var kustoTypeToEntityDataType = {
30
+ object: 'Object',
31
+ bool: 'Boolean',
32
+ uint8: 'Byte',
33
+ int16: 'Int16',
34
+ uint16: 'UInt16',
35
+ int: 'Int32',
36
+ uint: 'UInt32',
37
+ long: 'Int64',
38
+ ulong: 'UInt64',
39
+ float: 'Single',
40
+ real: 'Double',
41
+ decimal: 'Decimal',
42
+ datetime: 'DateTime',
43
+ string: 'String',
44
+ dynamic: 'Dynamic',
45
+ timespan: 'TimeSpan'
46
+ };
47
+ exports.getEntityDataTypeFromCslType = function (cslType) { return kustoTypeToEntityDataType[cslType] || cslType; };
48
+ exports.getCallName = function (fn) {
49
+ return fn.name + "(" + fn.inputParameters.map(function (p) { return "{" + p.name + "}"; }).join(',') + ")";
50
+ };
51
+ exports.getExpression = function (fn) {
52
+ return "let " + fn.name + " = " + exports.getInputParametersAsCslString(fn.inputParameters) + " " + fn.body;
53
+ };
54
+ exports.getInputParametersAsCslString = function (inputParameters) {
55
+ return "(" + inputParameters.map(function (inputParameter) { return getInputParameterAsCslString(inputParameter); }).join(',') + ")";
56
+ };
57
+ var getInputParameterAsCslString = function (inputParameter) {
58
+ // If this is a tabular parameter
59
+ if (inputParameter.columns && inputParameter.columns.length > 0) {
60
+ var attributesAsString = inputParameter.columns
61
+ .map(function (col) { return col.name + ":" + (col.cslType || exports.getCslTypeNameFromClrType(col.type)); })
62
+ .join(',');
63
+ return inputParameter.name + ":" + (attributesAsString === '' ? '*' : attributesAsString);
64
+ }
65
+ else {
66
+ return inputParameter.name + ":" + (inputParameter.cslType || exports.getCslTypeNameFromClrType(inputParameter.type));
67
+ }
68
+ };
69
+ });
70
70
 
71
71
  (function (factory) {
72
72
  if (typeof module === "object" && typeof module.exports === "object") {
@@ -6263,1795 +6263,1983 @@ module.exports = XRegExp;
6263
6263
  });
6264
6264
  define('xregexp', ['xregexp/xregexp-all'], function (main) { return main; });
6265
6265
 
6266
- var __assign = (this && this.__assign) || function () {
6267
- __assign = Object.assign || function(t) {
6268
- for (var s, i = 1, n = arguments.length; i < n; i++) {
6269
- s = arguments[i];
6270
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
6271
- t[p] = s[p];
6272
- }
6273
- return t;
6274
- };
6275
- return __assign.apply(this, arguments);
6276
- };
6277
- define('vs/language/kusto/languageService/kustoLanguageService',["require", "exports", "./schema", "vscode-languageserver-types", "xregexp", "./schema"], function (require, exports, s, ls, XRegExp, schema_1) {
6278
- "use strict";
6279
- Object.defineProperty(exports, "__esModule", { value: true });
6280
- exports.getKustoLanguageService = exports.TokenKind = void 0;
6281
- // polyfill string endsWith
6282
- if (!String.prototype.endsWith) {
6283
- String.prototype.endsWith = function (search, this_len) {
6284
- if (this_len === undefined || this_len > this.length) {
6285
- this_len = this.length;
6286
- }
6287
- return this.substring(this_len - search.length, this_len) === search;
6288
- };
6289
- }
6290
- // If we're running in a web worker - which doesn't share global context with the main thread -
6291
- // we need to manually load dependencies that are not explicit- meaning our non-module dependencies
6292
- // generated by Bridge.Net
6293
- if (typeof document == 'undefined') {
6294
- // monaco will run the worker from vs/base/worker so the relative path needs to be from there (hence going up 2 dirs)
6295
- importScripts('../../language/kusto/bridge.min.js');
6296
- importScripts('../../language/kusto/kusto.javascript.client.min.js');
6297
- importScripts('../../language/kusto/Kusto.Language.Bridge.min.js');
6298
- }
6299
- var k = Kusto.Data.IntelliSense;
6300
- var parsing = Kusto.Language.Parsing;
6301
- var k2 = Kusto.Language.Editor;
6302
- var sym = Kusto.Language.Symbols;
6303
- var GlobalState = Kusto.Language.GlobalState;
6304
- var List = System.Collections.Generic.List$1;
6305
- function assertNever(x) {
6306
- throw new Error('Unexpected object: ' + x);
6307
- }
6308
- var ParseProperties = /** @class */ (function () {
6309
- function ParseProperties(version, uri, rulesProvider, parseMode) {
6310
- this.version = version;
6311
- this.uri = uri;
6312
- this.rulesProvider = rulesProvider;
6313
- this.parseMode = parseMode;
6314
- }
6315
- ParseProperties.prototype.isParseNeeded = function (document, rulesProvider, parseMode) {
6316
- if (document.uri === this.uri &&
6317
- (!rulesProvider || rulesProvider === this.rulesProvider) &&
6318
- document.version <= this.version &&
6319
- parseMode &&
6320
- parseMode <= this.parseMode) {
6321
- return false;
6322
- }
6323
- return true;
6324
- };
6325
- return ParseProperties;
6326
- }());
6327
- var TokenKind;
6328
- (function (TokenKind) {
6329
- TokenKind[TokenKind["TableToken"] = 2] = "TableToken";
6330
- TokenKind[TokenKind["TableColumnToken"] = 4] = "TableColumnToken";
6331
- TokenKind[TokenKind["OperatorToken"] = 8] = "OperatorToken";
6332
- TokenKind[TokenKind["SubOperatorToken"] = 16] = "SubOperatorToken";
6333
- TokenKind[TokenKind["CalculatedColumnToken"] = 32] = "CalculatedColumnToken";
6334
- TokenKind[TokenKind["StringLiteralToken"] = 64] = "StringLiteralToken";
6335
- TokenKind[TokenKind["FunctionNameToken"] = 128] = "FunctionNameToken";
6336
- TokenKind[TokenKind["UnknownToken"] = 256] = "UnknownToken";
6337
- TokenKind[TokenKind["CommentToken"] = 512] = "CommentToken";
6338
- TokenKind[TokenKind["PlainTextToken"] = 1024] = "PlainTextToken";
6339
- TokenKind[TokenKind["DataTypeToken"] = 2048] = "DataTypeToken";
6340
- TokenKind[TokenKind["ControlCommandToken"] = 4096] = "ControlCommandToken";
6341
- TokenKind[TokenKind["CommandPartToken"] = 8192] = "CommandPartToken";
6342
- TokenKind[TokenKind["QueryParametersToken"] = 16384] = "QueryParametersToken";
6343
- TokenKind[TokenKind["CslCommandToken"] = 32768] = "CslCommandToken";
6344
- TokenKind[TokenKind["LetVariablesToken"] = 65536] = "LetVariablesToken";
6345
- TokenKind[TokenKind["PluginToken"] = 131072] = "PluginToken";
6346
- TokenKind[TokenKind["BracketRangeToken"] = 262144] = "BracketRangeToken";
6347
- TokenKind[TokenKind["ClientDirectiveToken"] = 524288] = "ClientDirectiveToken";
6348
- })(TokenKind = exports.TokenKind || (exports.TokenKind = {}));
6349
- /**
6350
- * convert the bridge.net object to a plain javascript object that only contains data.
6351
- * @param k2Classifications @kusto/language-service-next bridge.net object
6352
- */
6353
- function toClassifiedRange(k2Classifications) {
6354
- return k2Classifications.map(function (classification) { return ({
6355
- start: classification.Start,
6356
- end: classification.End,
6357
- length: classification.Length,
6358
- kind: classification.Kind,
6359
- }); });
6360
- }
6361
- /**
6362
- * Kusto Language service translates the kusto object model (transpiled from C# by Bridge.Net)
6363
- * to the vscode language server types, which are used by vscode language extensions.
6364
- * This should make things easier in the future to provide a vscode extension based on this translation layer.
6365
- *
6366
- * Further translations, if needed, to support specific editors (Atom, sublime, Etc)
6367
- * should be done on top of this API, since it is (at least meant to be) a standard that is supported by multiple editors.
6368
- *
6369
- * Note1: Currently monaco isn't using this object model so further translation will be necessary on calling modules.
6370
- *
6371
- * Note2: This file is responsible for interacting with the kusto object model and exposing Microsoft language service types.
6372
- * An exception to that rule is tokenization (and syntax highlighting which depends on it) -
6373
- * since it's not currently part of the Microsoft language service protocol. Thus tokenize() _does_ 'leak' kusto types to the callers.
6374
- */
6375
- var KustoLanguageService = /** @class */ (function () {
6376
- function KustoLanguageService(schema, languageSettings) {
6377
- var _a, _b, _c, _d;
6378
- var _this = this;
6379
- this._toOptionKind = (_a = {},
6380
- _a[k2.CompletionKind.AggregateFunction] = k.OptionKind.FunctionAggregation,
6381
- _a[k2.CompletionKind.BuiltInFunction] = k.OptionKind.FunctionServerSide,
6382
- _a[k2.CompletionKind.Cluster] = k.OptionKind.Database,
6383
- _a[k2.CompletionKind.Column] = k.OptionKind.Column,
6384
- _a[k2.CompletionKind.CommandPrefix] = k.OptionKind.None,
6385
- _a[k2.CompletionKind.Database] = k.OptionKind.Database,
6386
- _a[k2.CompletionKind.DatabaseFunction] = k.OptionKind.FunctionServerSide,
6387
- _a[k2.CompletionKind.Example] = k.OptionKind.None,
6388
- _a[k2.CompletionKind.Identifier] = k.OptionKind.None,
6389
- _a[k2.CompletionKind.Keyword] = k.OptionKind.None,
6390
- _a[k2.CompletionKind.LocalFunction] = k.OptionKind.FunctionLocal,
6391
- _a[k2.CompletionKind.MaterialiedView] = k.OptionKind.MaterializedView,
6392
- _a[k2.CompletionKind.Parameter] = k.OptionKind.Parameter,
6393
- _a[k2.CompletionKind.Punctuation] = k.OptionKind.None,
6394
- _a[k2.CompletionKind.QueryPrefix] = k.OptionKind.Operator,
6395
- _a[k2.CompletionKind.RenderChart] = k.OptionKind.Operator,
6396
- _a[k2.CompletionKind.ScalarInfix] = k.OptionKind.None,
6397
- _a[k2.CompletionKind.ScalarPrefix] = k.OptionKind.None,
6398
- _a[k2.CompletionKind.ScalarType] = k.OptionKind.DataType,
6399
- _a[k2.CompletionKind.Syntax] = k.OptionKind.None,
6400
- _a[k2.CompletionKind.Table] = k.OptionKind.Table,
6401
- _a[k2.CompletionKind.TabularPrefix] = k.OptionKind.None,
6402
- _a[k2.CompletionKind.TabularSuffix] = k.OptionKind.None,
6403
- _a[k2.CompletionKind.Unknown] = k.OptionKind.None,
6404
- _a[k2.CompletionKind.Variable] = k.OptionKind.Parameter,
6405
- _a[k2.CompletionKind.Option] = k.OptionKind.Option,
6406
- _a);
6407
- this.disabledCompletionItemsV2 = {
6408
- // render charts
6409
- ladderchart: k2.CompletionKind.RenderChart,
6410
- pivotchart: k2.CompletionKind.RenderChart,
6411
- timeline: k2.CompletionKind.RenderChart,
6412
- timepivot: k2.CompletionKind.RenderChart,
6413
- '3Dchart': k2.CompletionKind.RenderChart,
6414
- list: k2.CompletionKind.RenderChart,
6415
- };
6416
- this.isIntellisenseV2 = function () {
6417
- return _this._languageSettings.useIntellisenseV2 && _this._schema && _this._schema.clusterType === 'Engine';
6418
- };
6419
- this.disabledCompletionItemsV1 = {
6420
- capacity: k.OptionKind.Policy,
6421
- callout: k.OptionKind.Policy,
6422
- encoding: k.OptionKind.Policy,
6423
- batching: k.OptionKind.Policy,
6424
- querythrottling: k.OptionKind.Policy,
6425
- merge: k.OptionKind.Policy,
6426
- querylimit: k.OptionKind.Policy,
6427
- rowstore: k.OptionKind.Policy,
6428
- streamingingestion: k.OptionKind.Policy,
6429
- restricted_view_access: k.OptionKind.Policy,
6430
- sharding: k.OptionKind.Policy,
6431
- 'restricted-viewers': k.OptionKind.Policy,
6432
- attach: k.OptionKind.Command,
6433
- purge: k.OptionKind.Command,
6434
- };
6435
- this._kustoKindtolsKind = (_b = {},
6436
- _b[k.OptionKind.None] = ls.CompletionItemKind.Interface,
6437
- _b[k.OptionKind.Operator] = ls.CompletionItemKind.Method,
6438
- _b[k.OptionKind.Command] = ls.CompletionItemKind.Method,
6439
- _b[k.OptionKind.Service] = ls.CompletionItemKind.Class,
6440
- _b[k.OptionKind.Policy] = ls.CompletionItemKind.Reference,
6441
- _b[k.OptionKind.Database] = ls.CompletionItemKind.Class,
6442
- _b[k.OptionKind.Table] = ls.CompletionItemKind.Class,
6443
- _b[k.OptionKind.DataType] = ls.CompletionItemKind.Class,
6444
- _b[k.OptionKind.Literal] = ls.CompletionItemKind.Property,
6445
- _b[k.OptionKind.Parameter] = ls.CompletionItemKind.Variable,
6446
- _b[k.OptionKind.IngestionMapping] = ls.CompletionItemKind.Variable,
6447
- _b[k.OptionKind.ExpressionFunction] = ls.CompletionItemKind.Variable,
6448
- _b[k.OptionKind.Option] = ls.CompletionItemKind.Interface,
6449
- _b[k.OptionKind.OptionKind] = ls.CompletionItemKind.Interface,
6450
- _b[k.OptionKind.OptionRender] = ls.CompletionItemKind.Interface,
6451
- _b[k.OptionKind.Column] = ls.CompletionItemKind.Function,
6452
- _b[k.OptionKind.ColumnString] = ls.CompletionItemKind.Field,
6453
- _b[k.OptionKind.ColumnNumeric] = ls.CompletionItemKind.Field,
6454
- _b[k.OptionKind.ColumnDateTime] = ls.CompletionItemKind.Field,
6455
- _b[k.OptionKind.ColumnTimespan] = ls.CompletionItemKind.Field,
6456
- _b[k.OptionKind.FunctionServerSide] = ls.CompletionItemKind.Field,
6457
- _b[k.OptionKind.FunctionAggregation] = ls.CompletionItemKind.Field,
6458
- _b[k.OptionKind.FunctionFilter] = ls.CompletionItemKind.Field,
6459
- _b[k.OptionKind.FunctionScalar] = ls.CompletionItemKind.Field,
6460
- _b[k.OptionKind.ClientDirective] = ls.CompletionItemKind.Enum,
6461
- _b);
6462
- this._kustoKindToLsKindV2 = (_c = {},
6463
- _c[k2.CompletionKind.AggregateFunction] = ls.CompletionItemKind.Field,
6464
- _c[k2.CompletionKind.BuiltInFunction] = ls.CompletionItemKind.Field,
6465
- _c[k2.CompletionKind.Cluster] = ls.CompletionItemKind.Class,
6466
- _c[k2.CompletionKind.Column] = ls.CompletionItemKind.Function,
6467
- _c[k2.CompletionKind.CommandPrefix] = ls.CompletionItemKind.Field,
6468
- _c[k2.CompletionKind.Database] = ls.CompletionItemKind.Class,
6469
- _c[k2.CompletionKind.DatabaseFunction] = ls.CompletionItemKind.Field,
6470
- _c[k2.CompletionKind.Example] = ls.CompletionItemKind.Text,
6471
- _c[k2.CompletionKind.Identifier] = ls.CompletionItemKind.Method,
6472
- _c[k2.CompletionKind.Keyword] = ls.CompletionItemKind.Method,
6473
- _c[k2.CompletionKind.LocalFunction] = ls.CompletionItemKind.Field,
6474
- _c[k2.CompletionKind.MaterialiedView] = ls.CompletionItemKind.Class,
6475
- _c[k2.CompletionKind.Parameter] = ls.CompletionItemKind.Variable,
6476
- _c[k2.CompletionKind.Punctuation] = ls.CompletionItemKind.Interface,
6477
- _c[k2.CompletionKind.QueryPrefix] = ls.CompletionItemKind.Function,
6478
- _c[k2.CompletionKind.RenderChart] = ls.CompletionItemKind.Method,
6479
- _c[k2.CompletionKind.ScalarInfix] = ls.CompletionItemKind.Field,
6480
- _c[k2.CompletionKind.ScalarPrefix] = ls.CompletionItemKind.Field,
6481
- _c[k2.CompletionKind.ScalarType] = ls.CompletionItemKind.TypeParameter,
6482
- _c[k2.CompletionKind.Syntax] = ls.CompletionItemKind.Method,
6483
- _c[k2.CompletionKind.Table] = ls.CompletionItemKind.Class,
6484
- _c[k2.CompletionKind.TabularPrefix] = ls.CompletionItemKind.Field,
6485
- // datatable, externaldata
6486
- _c[k2.CompletionKind.TabularSuffix] = ls.CompletionItemKind.Field,
6487
- _c[k2.CompletionKind.Unknown] = ls.CompletionItemKind.Interface,
6488
- _c[k2.CompletionKind.Variable] = ls.CompletionItemKind.Variable,
6489
- _c[k2.CompletionKind.Option] = ls.CompletionItemKind.Text,
6490
- _c);
6491
- this._tokenKindToClassificationKind = (_d = {},
6492
- _d[TokenKind.TableToken] = k2.ClassificationKind.Table,
6493
- _d[TokenKind.TableColumnToken] = k2.ClassificationKind.Column,
6494
- _d[TokenKind.OperatorToken] = k2.ClassificationKind.QueryOperator,
6495
- _d[TokenKind.SubOperatorToken] = k2.ClassificationKind.Function,
6496
- _d[TokenKind.CalculatedColumnToken] = k2.ClassificationKind.Column,
6497
- _d[TokenKind.StringLiteralToken] = k2.ClassificationKind.Literal,
6498
- _d[TokenKind.FunctionNameToken] = k2.ClassificationKind.Function,
6499
- _d[TokenKind.UnknownToken] = k2.ClassificationKind.PlainText,
6500
- _d[TokenKind.CommentToken] = k2.ClassificationKind.Comment,
6501
- _d[TokenKind.PlainTextToken] = k2.ClassificationKind.PlainText,
6502
- _d[TokenKind.DataTypeToken] = k2.ClassificationKind.Type,
6503
- _d[TokenKind.ControlCommandToken] = k2.ClassificationKind.PlainText,
6504
- _d[TokenKind.CommandPartToken] = k2.ClassificationKind.PlainText,
6505
- _d[TokenKind.QueryParametersToken] = k2.ClassificationKind.QueryParameter,
6506
- _d[TokenKind.CslCommandToken] = k2.ClassificationKind.Keyword,
6507
- _d[TokenKind.LetVariablesToken] = k2.ClassificationKind.Identifier,
6508
- _d[TokenKind.PluginToken] = k2.ClassificationKind.Function,
6509
- _d[TokenKind.BracketRangeToken] = k2.ClassificationKind.Keyword,
6510
- _d[TokenKind.ClientDirectiveToken] = k2.ClassificationKind.Keyword,
6511
- _d);
6512
- this._schemaCache = {};
6513
- this._kustoJsSchema = KustoLanguageService.convertToKustoJsSchema(schema);
6514
- this._kustoJsSchemaV2 = this.convertToKustoJsSchemaV2(schema);
6515
- this._schema = schema;
6516
- this.configure(languageSettings);
6517
- this._newlineAppendPipePolicy = new Kusto.Data.IntelliSense.ApplyPolicy();
6518
- this._newlineAppendPipePolicy.Text = '\n| ';
6519
- }
6520
- KustoLanguageService.prototype.configure = function (languageSettings) {
6521
- this._languageSettings = languageSettings;
6522
- // Since we're still reverting to V1 intellisense for control commands, we need to update the rules provider
6523
- // (which is a notion of V1 intellisense).
6524
- this.createRulesProvider(this._kustoJsSchema, this._schema.clusterType);
6525
- };
6526
- KustoLanguageService.prototype.doComplete = function (document, position) {
6527
- return this.isIntellisenseV2() ? this.doCompleteV2(document, position) : this.doCompleteV1(document, position);
6528
- };
6529
- KustoLanguageService.prototype.doCompleteV2 = function (document, position) {
6530
- var _this = this;
6531
- if (!document) {
6532
- return Promise.resolve(ls.CompletionList.create([]));
6533
- }
6534
- var script = this.parseDocumentV2(document);
6535
- var cursorOffset = document.offsetAt(position);
6536
- var currentcommand = this.getCurrentCommandV2(script, cursorOffset);
6537
- var completionItems = currentcommand.Service.GetCompletionItems(cursorOffset);
6538
- var disabledItems = this.disabledCompletionItemsV2;
6539
- if (this._languageSettings.disabledCompletionItems) {
6540
- this._languageSettings.disabledCompletionItems.map(function (item) {
6541
- // logic will treat unknown as a '*' wildcard, meaning that if the key is in the object
6542
- // the completion item will be suppressed.
6543
- disabledItems[item] = k2.CompletionKind.Unknown;
6544
- });
6545
- }
6546
- var items = this.toArray(completionItems.Items)
6547
- .filter(function (item) {
6548
- return !(item &&
6549
- item.MatchText &&
6550
- disabledItems[item.MatchText] !== undefined &&
6551
- (disabledItems[item.MatchText] === k2.CompletionKind.Unknown ||
6552
- disabledItems[item.MatchText] === item.Kind));
6553
- })
6554
- .map(function (kItem, i) {
6555
- var v1CompletionOption = new k.CompletionOption(_this._toOptionKind[kItem.Kind] || k.OptionKind.None, kItem.DisplayText);
6556
- var helpTopic = _this.getTopic(v1CompletionOption);
6557
- // If we have AfterText it means that the cursor should no be placed at end of suggested text.
6558
- // In that case we switch to snippet format and represent the point where the cursor should be as
6559
- // as '\$0'
6560
- var _a = kItem.AfterText && kItem.AfterText.length > 0
6561
- ? {
6562
- textToInsert: kItem.EditText + '$0' + kItem.AfterText,
6563
- format: ls.InsertTextFormat.Snippet,
6564
- }
6565
- : {
6566
- textToInsert: kItem.EditText,
6567
- format: ls.InsertTextFormat.PlainText,
6568
- }, textToInsert = _a.textToInsert, format = _a.format;
6569
- var lsItem = ls.CompletionItem.create(kItem.DisplayText);
6570
- var startPosition = document.positionAt(completionItems.EditStart);
6571
- var endPosition = document.positionAt(completionItems.EditStart + completionItems.EditLength);
6572
- lsItem.textEdit = ls.TextEdit.replace(ls.Range.create(startPosition, endPosition), textToInsert);
6573
- lsItem.sortText = _this.getSortText(i + 1);
6574
- lsItem.kind = _this.kustoKindToLsKindV2(kItem.Kind);
6575
- lsItem.insertTextFormat = format;
6576
- lsItem.detail = helpTopic ? helpTopic.ShortDescription : undefined;
6577
- lsItem.documentation = helpTopic
6578
- ? { value: helpTopic.LongDescription, kind: ls.MarkupKind.Markdown }
6579
- : undefined;
6580
- return lsItem;
6581
- });
6582
- return Promise.resolve(ls.CompletionList.create(items));
6583
- };
6584
- /**
6585
- * when trying to get a topic we need the function name (abs, toLower, ETC).
6586
- * The problem is that the 'Value' string also contains the arguments (e.g abs(number)), which means that we are
6587
- * not able to correlate the option with its documentation.
6588
- * This piece of code tries to strip this hwne getting topic.
6589
- * @param completionOption the Completion option
6590
- */
6591
- KustoLanguageService.prototype.getTopic = function (completionOption) {
6592
- if (completionOption.Kind == k.OptionKind.FunctionScalar ||
6593
- completionOption.Kind == k.OptionKind.FunctionAggregation) {
6594
- // from a value like 'abs(number)' remove the '(number)' so that only 'abs' will remain
6595
- var indexOfParen = completionOption.Value.indexOf('(');
6596
- if (indexOfParen >= 0) {
6597
- completionOption = new k.CompletionOption(completionOption.Kind, completionOption.Value.substring(0, indexOfParen));
6598
- }
6599
- }
6600
- return k.CslDocumentation.Instance.GetTopic(completionOption);
6601
- };
6602
- KustoLanguageService.prototype.doCompleteV1 = function (document, position) {
6603
- var _this = this;
6604
- // TODO: fix typing in CslCommandParser to allow rulesProvider to be query only.
6605
- var caretAbsolutePosition = document.offsetAt(position);
6606
- // find out what's the current command to only parse this one.
6607
- this.parseDocumentV1(document, k.ParseMode.CommandTokensOnly);
6608
- var currentCommand = this.getCurrentCommand(document, caretAbsolutePosition);
6609
- var commandTextUntilCursor = '';
6610
- if (currentCommand) {
6611
- var commandStartOffset = currentCommand.AbsoluteStart;
6612
- this.parseTextV1(currentCommand.Text, k.ParseMode.TokenizeAllText);
6613
- var caretRelativePosition = caretAbsolutePosition - currentCommand.AbsoluteStart;
6614
- commandTextUntilCursor = currentCommand.Text.substring(currentCommand.CslExpressionStartPosition, caretRelativePosition);
6615
- }
6616
- var commandTextWithoutLastWord = this.getCommandWithoutLastWord(commandTextUntilCursor);
6617
- var context = this._rulesProvider.AnalyzeCommand$1(commandTextUntilCursor, currentCommand).Context;
6618
- var result = { v: null };
6619
- this._rulesProvider.TryMatchAnyRule(commandTextWithoutLastWord, result);
6620
- var rule = result.v;
6621
- if (rule) {
6622
- var completionOptions = this.toArray(rule.GetCompletionOptions(context));
6623
- // TODO once AppendPipePolicy becomes a public static member of ApplyPolicy in our c# code, and bridge.Net transplies this,
6624
- // remove the 'as any' part..
6625
- // Also = DefaultApplyPolicy is internal in c# code, so not exposed in d.ts, so we cast it to any.
6626
- if (this._languageSettings.newlineAfterPipe &&
6627
- rule.DefaultAfterApplyPolicy === Kusto.Data.IntelliSense.ApplyPolicy.AppendPipePolicy) {
6628
- rule.DefaultAfterApplyPolicy = this._newlineAppendPipePolicy;
6629
- }
6630
- var options = completionOptions
6631
- .filter(function (option) {
6632
- return !(option && option.Value && _this.disabledCompletionItemsV1[option.Value] === option.Kind);
6633
- })
6634
- .map(function (option, ordinal) {
6635
- var _a = _this.getTextToInsert(rule, option), insertText = _a.insertText, insertTextFormat = _a.insertTextFormat;
6636
- var helpTopic = k.CslDocumentation.Instance.GetTopic(option);
6637
- var item = ls.CompletionItem.create(option.Value);
6638
- item.kind = _this.kustoKindToLsKind(option.Kind);
6639
- item.insertText = insertText;
6640
- item.insertTextFormat = insertTextFormat;
6641
- item.sortText = _this.getSortText(ordinal + 1);
6642
- item.detail = helpTopic ? helpTopic.ShortDescription : undefined;
6643
- item.documentation = helpTopic
6644
- ? { value: helpTopic.LongDescription, kind: ls.MarkupKind.Markdown }
6645
- : undefined;
6646
- return item;
6647
- });
6648
- return Promise.resolve(ls.CompletionList.create(options));
6649
- }
6650
- return Promise.resolve(ls.CompletionList.create([]));
6651
- };
6652
- KustoLanguageService.prototype.doRangeFormat = function (document, range) {
6653
- if (!document) {
6654
- return Promise.resolve([]);
6655
- }
6656
- var rangeStartOffset = document.offsetAt(range.start);
6657
- var rangeEndOffset = document.offsetAt(range.end);
6658
- var commands = this.getFormattedCommandsInDocumentV2(document, rangeStartOffset, rangeEndOffset);
6659
- if (!commands.originalRange || commands.formattedCommands.length === 0) {
6660
- return Promise.resolve([]);
6661
- }
6662
- return Promise.resolve([ls.TextEdit.replace(commands.originalRange, commands.formattedCommands.join(''))]);
6663
- };
6664
- KustoLanguageService.prototype.doDocumentFormat = function (document) {
6665
- if (!document) {
6666
- return Promise.resolve([]);
6667
- }
6668
- var startPos = document.positionAt(0);
6669
- var endPos = document.positionAt(document.getText().length);
6670
- var fullDocRange = ls.Range.create(startPos, endPos);
6671
- var formattedDoc = this.getFormattedCommandsInDocumentV2(document).formattedCommands.join('');
6672
- return Promise.resolve([ls.TextEdit.replace(fullDocRange, formattedDoc)]);
6673
- };
6674
- // Method is not triggered, instead doRangeFormat is invoked with the range of the caret's line.
6675
- KustoLanguageService.prototype.doCurrentCommandFormat = function (document, caretPosition) {
6676
- var offset = document.offsetAt(caretPosition);
6677
- var range = this.createRange(document, offset - 1, offset + 1);
6678
- return this.doRangeFormat(document, range);
6679
- };
6680
- KustoLanguageService.prototype.doFolding = function (document) {
6681
- if (!document) {
6682
- return Promise.resolve([]);
6683
- }
6684
- return this.getCommandsInDocument(document).then(function (commands) {
6685
- return commands.map(function (command) {
6686
- // don't count the last empty line as part of the folded range (consider linux, mac, pc newlines)
6687
- if (command.text.endsWith('\r\n')) {
6688
- command.absoluteEnd -= 2;
6689
- }
6690
- else if (command.text.endsWith('\r') || command.text.endsWith('\n')) {
6691
- --command.absoluteEnd;
6692
- }
6693
- var startPosition = document.positionAt(command.absoluteStart);
6694
- var endPosition = document.positionAt(command.absoluteEnd);
6695
- return {
6696
- startLine: startPosition.line,
6697
- startCharacter: startPosition.character,
6698
- endLine: endPosition.line,
6699
- endCharacter: endPosition.character,
6700
- };
6701
- });
6702
- });
6703
- };
6704
- KustoLanguageService.prototype.doValidation = function (document, changeIntervals) {
6705
- var _this = this;
6706
- // didn't implement validation for v1.
6707
- if (!document || !this.isIntellisenseV2()) {
6708
- return Promise.resolve([]);
6709
- }
6710
- var script = this.parseDocumentV2(document);
6711
- var blocks = this.toArray(script.Blocks);
6712
- if (changeIntervals.length > 0) {
6713
- blocks = this.getAffectedBlocks(blocks, changeIntervals);
6714
- }
6715
- var diagnostics = blocks
6716
- .map(function (block) {
6717
- var diagnostics = _this.toArray(block.Service.GetDiagnostics());
6718
- if (diagnostics) {
6719
- return diagnostics;
6720
- }
6721
- return [];
6722
- })
6723
- .reduce(function (prev, curr) { return prev.concat(curr); }, []);
6724
- var lsDiagnostics = this.toLsDiagnostics(diagnostics, document);
6725
- return Promise.resolve(lsDiagnostics);
6726
- };
6727
- KustoLanguageService.prototype.toLsDiagnostics = function (diagnostics, document) {
6728
- return diagnostics
6729
- .filter(function (diag) { return diag.HasLocation; })
6730
- .map(function (diag) {
6731
- var start = document.positionAt(diag.Start);
6732
- var end = document.positionAt(diag.Start + diag.Length);
6733
- var range = ls.Range.create(start, end);
6734
- return ls.Diagnostic.create(range, diag.Message, ls.DiagnosticSeverity.Error);
6735
- });
6736
- };
6737
- /**
6738
- * Colorize one or more kusto blocks (a.k.a commands), or just the entire document.
6739
- * Supports multi-cursor editing (colorizes blocks on multiple changes).
6740
- * @param document The document to colorize
6741
- * @param changeIntervals an array containing 0 or more changed intervals. if the array is empty - just colorize the entire row.
6742
- * if the array contains a single change - just color the kusto blocks that wraps this change. If multiple changes are provided,
6743
- * colorize all blocks that intersect these changes.
6744
- * The code will try to only parse once if this is the same command.
6745
- */
6746
- KustoLanguageService.prototype.doColorization = function (document, changeIntervals) {
6747
- var _this = this;
6748
- if (!document || !this._languageSettings.useSemanticColorization) {
6749
- return Promise.resolve([]);
6750
- }
6751
- // V1 intellisense
6752
- if (!this.isIntellisenseV2()) {
6753
- // Handle specific ranges changes (and not the whole doc)
6754
- if (changeIntervals.length > 0) {
6755
- this.parseDocumentV1(document, k.ParseMode.CommandTokensOnly);
6756
- var affectedCommands = this.toArray(this._parser.Results).filter(function (command) {
6757
- // a command is affected if it intersects at least on of changed ranges.
6758
- return command // command can be null. we're filtering all nulls in the array.
6759
- ? changeIntervals.some(function (_a) {
6760
- var changeStart = _a.start, changeEnd = _a.end;
6761
- // both intervals intersect if either the start or the end of interval A is inside interval B.
6762
- // If we deleted something at the end of a command, the interval will not intersect the current command.
6763
- // so we also want consider affected commands commands the end where the interval begins.
6764
- // hence the + 1.
6765
- return (command.AbsoluteStart >= changeStart && command.AbsoluteStart <= changeEnd) ||
6766
- (changeStart >= command.AbsoluteStart && changeStart <= command.AbsoluteEnd + 1);
6767
- })
6768
- : false;
6769
- });
6770
- // We're not on any command so don't return any classifications.
6771
- // this can happen if we're at the and of the file and deleting empty rows (for example).
6772
- if (!affectedCommands || affectedCommands.length === 0) {
6773
- return Promise.resolve([
6774
- {
6775
- classifications: [],
6776
- absoluteStart: changeIntervals[0].start,
6777
- absoluteEnd: changeIntervals[0].end,
6778
- },
6779
- ]);
6780
- }
6781
- var results = affectedCommands.map(function (command) {
6782
- _this.parseTextV1(command.Text, k.ParseMode.TokenizeAllText);
6783
- var k2Classifications = _this.getClassificationsFromParseResult(command.AbsoluteStart);
6784
- var classifications = toClassifiedRange(k2Classifications);
6785
- return {
6786
- classifications: classifications,
6787
- absoluteStart: command.AbsoluteStart,
6788
- absoluteEnd: command.AbsoluteEnd,
6789
- };
6790
- });
6791
- return Promise.resolve(results);
6792
- }
6793
- // Entire document requested
6794
- this.parseDocumentV1(document, k.ParseMode.TokenizeAllText);
6795
- var classifications_1 = this.getClassificationsFromParseResult();
6796
- return Promise.resolve([
6797
- {
6798
- classifications: toClassifiedRange(classifications_1),
6799
- absoluteStart: 0,
6800
- absoluteEnd: document.getText().length,
6801
- },
6802
- ]);
6803
- }
6804
- // V2 intellisense
6805
- var script = this.parseDocumentV2(document);
6806
- if (changeIntervals.length > 0) {
6807
- var blocks_1 = this.toArray(script.Blocks);
6808
- var affectedBlocks = this.getAffectedBlocks(blocks_1, changeIntervals);
6809
- var result = affectedBlocks.map(function (block) { return ({
6810
- classifications: toClassifiedRange(_this.toArray(block.Service.GetClassifications(block.Start, block.End).Classifications)),
6811
- absoluteStart: block.Start,
6812
- absoluteEnd: block.End,
6813
- }); });
6814
- return Promise.resolve(result);
6815
- }
6816
- // Entire document requested
6817
- var blocks = this.toArray(script.Blocks);
6818
- var classifications = blocks
6819
- .map(function (block) {
6820
- return _this.toArray(block.Service.GetClassifications(block.Start, block.Length).Classifications);
6821
- })
6822
- .reduce(function (prev, curr) { return prev.concat(curr); }, []);
6823
- return Promise.resolve([
6824
- {
6825
- classifications: toClassifiedRange(classifications),
6826
- absoluteStart: 0,
6827
- absoluteEnd: document.getText().length,
6828
- },
6829
- ]);
6830
- };
6831
- KustoLanguageService.prototype.getAffectedBlocks = function (blocks, changeIntervals) {
6832
- return blocks.filter(function (block) {
6833
- // a command is affected if it intersects at least on of changed ranges.
6834
- return block // command can be null. we're filtering all nulls in the array.
6835
- ? changeIntervals.some(function (_a) {
6836
- var changeStart = _a.start, changeEnd = _a.end;
6837
- // both intervals intersect if either the start or the end of interval A is inside interval B.
6838
- return (block.Start >= changeStart && block.Start <= changeEnd) ||
6839
- (changeStart >= block.Start && changeStart <= block.End + 1);
6840
- })
6841
- : false;
6842
- });
6843
- };
6844
- KustoLanguageService.prototype.setSchema = function (schema) {
6845
- var _this = this;
6846
- this._schema = schema;
6847
- if (this._languageSettings.useIntellisenseV2) {
6848
- var kustoJsSchemaV2 = schema && schema.clusterType === 'Engine' ? this.convertToKustoJsSchemaV2(schema) : null;
6849
- this._kustoJsSchemaV2 = kustoJsSchemaV2;
6850
- this._script = undefined;
6851
- this._parsePropertiesV2 = undefined;
6852
- }
6853
- // since V2 doesn't support control commands, we're initializing V1 intellisense for both cases and we'll going to use V1 intellisense for contorl commands.
6854
- return new Promise(function (resolve, reject) {
6855
- var kustoJsSchema = schema ? KustoLanguageService.convertToKustoJsSchema(schema) : undefined;
6856
- _this._kustoJsSchema = kustoJsSchema;
6857
- _this.createRulesProvider(kustoJsSchema, schema.clusterType);
6858
- resolve(undefined);
6859
- });
6860
- };
6861
- KustoLanguageService.prototype.setParameters = function (parameters) {
6862
- if (!this._languageSettings.useIntellisenseV2 || this._schema.clusterType !== 'Engine') {
6863
- throw new Error('setParameters requires intellisense V2 and Engine cluster');
6864
- }
6865
- this._schema.globalParameters = parameters;
6866
- var symbols = parameters.map(function (param) { return KustoLanguageService.createParameterSymbol(param); });
6867
- this._kustoJsSchemaV2 = this._kustoJsSchemaV2.WithParameters(KustoLanguageService.toBridgeList(symbols));
6868
- return Promise.resolve(undefined);
6869
- };
6870
- /**
6871
- * A combination of normalizeSchema and setSchema
6872
- * @param schema schema json as received from .show schema as json
6873
- * @param clusterConnectionString cluster connection string
6874
- * @param databaseInContextName name of database in context
6875
- */
6876
- KustoLanguageService.prototype.setSchemaFromShowSchema = function (schema, clusterConnectionString, databaseInContextName, globalParameters) {
6877
- var _this = this;
6878
- return this.normalizeSchema(schema, clusterConnectionString, databaseInContextName).then(function (normalized) {
6879
- return _this.setSchema(__assign(__assign({}, normalized), { globalParameters: globalParameters }));
6880
- });
6881
- };
6882
- /**
6883
- * Converts the result of .show schema as json to a normalized schema used by kusto language service.
6884
- * @param schema result of show schema
6885
- * @param clusterConnectionString cluster connection string`
6886
- * @param databaseInContextName database in context name
6887
- */
6888
- KustoLanguageService.prototype.normalizeSchema = function (schema, clusterConnectionString, databaseInContextName) {
6889
- var databases = Object.keys(schema.Databases)
6890
- .map(function (key) { return schema.Databases[key]; })
6891
- .map(function (_a) {
6892
- var Name = _a.Name, Tables = _a.Tables, Functions = _a.Functions, MinorVersion = _a.MinorVersion, MajorVersion = _a.MajorVersion;
6893
- return ({
6894
- name: Name,
6895
- minorVersion: MinorVersion,
6896
- majorVersion: MajorVersion,
6897
- tables: Object.keys(Tables)
6898
- .map(function (key) { return Tables[key]; })
6899
- .map(function (_a) {
6900
- var Name = _a.Name, OrderedColumns = _a.OrderedColumns, DocString = _a.DocString, EntityType = _a.EntityType;
6901
- return ({
6902
- name: Name,
6903
- docstring: DocString,
6904
- entityType: EntityType,
6905
- columns: OrderedColumns.map(function (_a) {
6906
- var Name = _a.Name, Type = _a.Type, DocString = _a.DocString, CslType = _a.CslType;
6907
- return ({
6908
- name: Name,
6909
- type: CslType,
6910
- docstring: DocString,
6911
- });
6912
- }),
6913
- });
6914
- }),
6915
- functions: Object.keys(Functions)
6916
- .map(function (key) { return Functions[key]; })
6917
- .map(function (_a) {
6918
- var Name = _a.Name, Body = _a.Body, DocString = _a.DocString, InputParameters = _a.InputParameters;
6919
- return ({
6920
- name: Name,
6921
- body: Body,
6922
- docstring: DocString,
6923
- inputParameters: InputParameters.map(function (inputParam) { return ({
6924
- name: inputParam.Name,
6925
- type: inputParam.Type,
6926
- cslType: inputParam.CslType,
6927
- cslDefaultValue: inputParam.CslDefaultValue,
6928
- columns: inputParam.Columns
6929
- ? inputParam.Columns.map(function (col) { return ({
6930
- name: col.Name,
6931
- type: col.Type,
6932
- cslType: col.CslType,
6933
- }); })
6934
- : inputParam.Columns,
6935
- }); }),
6936
- });
6937
- }),
6938
- });
6939
- });
6940
- var result = {
6941
- clusterType: 'Engine',
6942
- cluster: {
6943
- connectionString: clusterConnectionString,
6944
- databases: databases,
6945
- },
6946
- database: databases.filter(function (db) { return db.name === databaseInContextName; })[0],
6947
- };
6948
- return Promise.resolve(result);
6949
- };
6950
- KustoLanguageService.prototype.getSchema = function () {
6951
- return Promise.resolve(this._schema);
6952
- };
6953
- KustoLanguageService.prototype.getCommandInContext = function (document, cursorOffset) {
6954
- return this.isIntellisenseV2()
6955
- ? this.getCommandInContextV2(document, cursorOffset)
6956
- : this.getCommandInContextV1(document, cursorOffset);
6957
- };
6958
- KustoLanguageService.prototype.getCommandAndLocationInContext = function (document, cursorOffset) {
6959
- // We are going to remove v1 intellisense. no use to keep parity.
6960
- if (!document || !this.isIntellisenseV2()) {
6961
- return Promise.resolve(null);
6962
- }
6963
- var script = this.parseDocumentV2(document);
6964
- var block = this.getCurrentCommandV2(script, cursorOffset);
6965
- if (!block) {
6966
- return Promise.resolve(null);
6967
- }
6968
- var start = document.positionAt(block.Start);
6969
- var end = document.positionAt(block.End);
6970
- var location = ls.Location.create(document.uri, ls.Range.create(start, end));
6971
- var text = block.Text;
6972
- return Promise.resolve({
6973
- text: text,
6974
- location: location,
6975
- });
6976
- };
6977
- KustoLanguageService.prototype.getCommandInContextV1 = function (document, cursorOffset) {
6978
- this.parseDocumentV1(document, k.ParseMode.CommandTokensOnly);
6979
- var command = this.getCurrentCommand(document, cursorOffset);
6980
- if (!command) {
6981
- return Promise.resolve(null);
6982
- }
6983
- return Promise.resolve(command.Text);
6984
- };
6985
- KustoLanguageService.prototype.getCommandInContextV2 = function (document, cursorOffset) {
6986
- if (!document) {
6987
- return Promise.resolve(null);
6988
- }
6989
- var script = this.parseDocumentV2(document);
6990
- var block = this.getCurrentCommandV2(script, cursorOffset);
6991
- if (!block) {
6992
- return Promise.resolve(null);
6993
- }
6994
- // TODO: do we need to do tricks like V1 is doing in this.getCurrentCommand?
6995
- return Promise.resolve(block.Text);
6996
- };
6997
- /**
6998
- * Return an array of commands in document. each command contains the range and text.
6999
- */
7000
- KustoLanguageService.prototype.getCommandsInDocument = function (document) {
7001
- if (!document) {
7002
- return Promise.resolve([]);
7003
- }
7004
- return this.isIntellisenseV2()
7005
- ? this.getCommandsInDocumentV2(document)
7006
- : this.getCommandsInDocumentV1(document);
7007
- };
7008
- KustoLanguageService.prototype.getCommandsInDocumentV1 = function (document) {
7009
- this.parseDocumentV1(document, k.ParseMode.CommandTokensOnly);
7010
- var commands = this.toArray(this._parser.Results);
7011
- return Promise.resolve(commands.map(function (_a) {
7012
- var AbsoluteStart = _a.AbsoluteStart, AbsoluteEnd = _a.AbsoluteEnd, Text = _a.Text;
7013
- return ({
7014
- absoluteStart: AbsoluteStart,
7015
- absoluteEnd: AbsoluteEnd,
7016
- text: Text,
7017
- });
7018
- }));
7019
- };
7020
- KustoLanguageService.prototype.toPlacementStyle = function (formatterPlacementStyle) {
7021
- if (!formatterPlacementStyle) {
7022
- return undefined;
7023
- }
7024
- switch (formatterPlacementStyle) {
7025
- case 'None':
7026
- return k2.PlacementStyle.None;
7027
- case 'NewLine':
7028
- return k2.PlacementStyle.NewLine;
7029
- case 'Smart':
7030
- return k2.PlacementStyle.Smart;
7031
- default:
7032
- throw new Error('Unknown PlacementStyle');
7033
- }
7034
- };
7035
- KustoLanguageService.prototype.getFormattedCommandsInDocumentV2 = function (document, rangeStart, rangeEnd) {
7036
- var _this = this;
7037
- var script = this.parseDocumentV2(document);
7038
- var commands = this.toArray(script.Blocks).filter(function (command) {
7039
- if (!command.Text || command.Text.trim() == '')
7040
- return false;
7041
- if (rangeStart == null || rangeEnd == null)
7042
- return true;
7043
- // calculate command end position without \r\n.
7044
- var commandEnd = command.End;
7045
- var commandText = command.Text;
7046
- for (var i = commandText.length - 1; i >= 0; i--) {
7047
- if (commandText[i] != '\r' && commandText[i] != '\n') {
7048
- break;
7049
- }
7050
- else {
7051
- commandEnd--;
7052
- }
7053
- }
7054
- if (command.Start > rangeStart && command.Start < rangeEnd)
7055
- return true;
7056
- if (commandEnd > rangeStart && commandEnd < rangeEnd)
7057
- return true;
7058
- if (command.Start <= rangeStart && commandEnd >= rangeEnd)
7059
- return true;
7060
- });
7061
- if (commands.length === 0) {
7062
- return { formattedCommands: [] };
7063
- }
7064
- var formattedCommands = commands.map(function (command) {
7065
- var _a, _b;
7066
- var formatterOptions = _this._languageSettings.formatter;
7067
- var formatter = Kusto.Language.Editor.FormattingOptions.Default.WithIndentationSize((_a = formatterOptions === null || formatterOptions === void 0 ? void 0 : formatterOptions.indentationSize) !== null && _a !== void 0 ? _a : 4)
7068
- .WithInsertMissingTokens(false)
7069
- .WithPipeOperatorStyle((_b = _this.toPlacementStyle(formatterOptions === null || formatterOptions === void 0 ? void 0 : formatterOptions.pipeOperatorStyle)) !== null && _b !== void 0 ? _b : k2.PlacementStyle.Smart)
7070
- .WithSemicolonStyle(Kusto.Language.Editor.PlacementStyle.None)
7071
- .WithBrackettingStyle(k2.BrackettingStyle.Diagonal);
7072
- if (rangeStart == null || rangeEnd == null || (rangeStart === command.Start && rangeEnd === command.End)) {
7073
- var result = command.Service.GetFormattedText(formatter);
7074
- return result.Text;
7075
- }
7076
- return command.Service.GetFormattedText(formatter).Text;
7077
- });
7078
- var originalRange = this.createRange(document, commands[0].Start, commands[commands.length - 1].End);
7079
- return { formattedCommands: formattedCommands, originalRange: originalRange };
7080
- };
7081
- KustoLanguageService.prototype.getCommandsInDocumentV2 = function (document) {
7082
- var script = this.parseDocumentV2(document);
7083
- var commands = this.toArray(script.Blocks).filter(function (command) { return command.Text.trim() != ''; });
7084
- return Promise.resolve(commands.map(function (_a) {
7085
- var Start = _a.Start, End = _a.End, Text = _a.Text;
7086
- return ({ absoluteStart: Start, absoluteEnd: End, text: Text });
7087
- }));
7088
- };
7089
- KustoLanguageService.prototype.getClientDirective = function (text) {
7090
- var outParam = { v: null };
7091
- var isClientDirective = k.CslCommandParser.IsClientDirective(text, outParam);
7092
- return Promise.resolve({
7093
- isClientDirective: isClientDirective,
7094
- directiveWithoutLeadingComments: outParam.v,
7095
- });
7096
- };
7097
- KustoLanguageService.prototype.getAdminCommand = function (text) {
7098
- var outParam = { v: null };
7099
- var isAdminCommand = k.CslCommandParser.IsAdminCommand$1(text, outParam);
7100
- return Promise.resolve({
7101
- isAdminCommand: isAdminCommand,
7102
- adminCommandWithoutLeadingComments: outParam.v,
7103
- });
7104
- };
7105
- KustoLanguageService.prototype.findDefinition = function (document, position) {
7106
- if (!document || !this.isIntellisenseV2()) {
7107
- return Promise.resolve([]);
7108
- }
7109
- var script = this.parseDocumentV2(document);
7110
- var cursorOffset = document.offsetAt(position);
7111
- var currentBlock = this.getCurrentCommandV2(script, cursorOffset);
7112
- if (!currentBlock) {
7113
- return Promise.resolve([]);
7114
- }
7115
- var relatedInfo = currentBlock.Service.GetRelatedElements(document.offsetAt(position));
7116
- var relatedElements = this.toArray(relatedInfo.Elements);
7117
- var definition = relatedElements[0];
7118
- if (!definition) {
7119
- return Promise.resolve([]);
7120
- }
7121
- var start = document.positionAt(definition.Start);
7122
- var end = document.positionAt(definition.End);
7123
- var range = ls.Range.create(start, end);
7124
- var location = ls.Location.create(document.uri, range);
7125
- return Promise.resolve([location]);
7126
- };
7127
- KustoLanguageService.prototype.findReferences = function (document, position) {
7128
- if (!document || !this.isIntellisenseV2()) {
7129
- return Promise.resolve([]);
7130
- }
7131
- var script = this.parseDocumentV2(document);
7132
- var cursorOffset = document.offsetAt(position);
7133
- var currentBlock = this.getCurrentCommandV2(script, cursorOffset);
7134
- if (!currentBlock) {
7135
- return Promise.resolve([]);
7136
- }
7137
- var relatedInfo = currentBlock.Service.GetRelatedElements(document.offsetAt(position));
7138
- var relatedElements = this.toArray(relatedInfo.Elements);
7139
- if (!relatedElements || relatedElements.length == 0) {
7140
- return Promise.resolve([]);
7141
- }
7142
- var references = relatedElements.map(function (relatedElement) {
7143
- var start = document.positionAt(relatedElement.Start);
7144
- var end = document.positionAt(relatedElement.End);
7145
- var range = ls.Range.create(start, end);
7146
- var location = ls.Location.create(document.uri, range);
7147
- return location;
7148
- });
7149
- return Promise.resolve(references);
7150
- };
7151
- KustoLanguageService.prototype.getQueryParams = function (document, cursorOffset) {
7152
- if (!document || !this.isIntellisenseV2()) {
7153
- return Promise.resolve([]);
7154
- }
7155
- var script = this.parseDocumentV2(document);
7156
- var parsedAndAnalyzed = this.parseAndAnalyze(document, cursorOffset);
7157
- var queryParamStatements = this.toArray(parsedAndAnalyzed.Syntax.GetDescendants(Kusto.Language.Syntax.QueryParametersStatement));
7158
- if (!queryParamStatements || queryParamStatements.length == 0) {
7159
- return Promise.resolve([]);
7160
- }
7161
- var queryParams = [];
7162
- queryParamStatements.forEach(function (paramStatement) {
7163
- paramStatement.WalkElements(function (el) {
7164
- return el.ReferencedSymbol && el.ReferencedSymbol.Type
7165
- ? queryParams.push({ name: el.ReferencedSymbol.Name, type: el.ReferencedSymbol.Type.Name })
7166
- : undefined;
7167
- });
7168
- });
7169
- return Promise.resolve(queryParams);
7170
- };
7171
- KustoLanguageService.prototype.getRenderInfo = function (document, cursorOffset) {
7172
- var _this = this;
7173
- var parsedAndAnalyzed = this.parseAndAnalyze(document, cursorOffset);
7174
- if (!parsedAndAnalyzed) {
7175
- return Promise.resolve(undefined);
7176
- }
7177
- var renderStatements = this.toArray(parsedAndAnalyzed.Syntax.GetDescendants(Kusto.Language.Syntax.RenderOperator));
7178
- if (!renderStatements || renderStatements.length === 0) {
7179
- return Promise.resolve(undefined);
7180
- }
7181
- // assuming a single render statement
7182
- var renderStatement = renderStatements[0];
7183
- // Start and end relative to block start.
7184
- var startOffset = renderStatement.TextStart;
7185
- var endOffset = renderStatement.End;
7186
- var visualization = renderStatement.ChartType.ValueText;
7187
- var withClause = renderStatement.WithClause;
7188
- if (!withClause) {
7189
- var info = {
7190
- options: {
7191
- visualization: visualization,
7192
- },
7193
- location: { startOffset: startOffset, endOffset: endOffset },
7194
- };
7195
- return Promise.resolve(info);
7196
- }
7197
- var properties = this.toArray(withClause.Properties);
7198
- var props = properties.reduce(function (prev, property) {
7199
- var name = property.Element$1.Name.SimpleName;
7200
- switch (name) {
7201
- case 'xcolumn':
7202
- var value = property.Element$1.Expression.ReferencedSymbol.Name;
7203
- prev[name] = value;
7204
- break;
7205
- case 'ycolumns':
7206
- case 'anomalycolumns':
7207
- var nameNodes = _this.toArray(property.Element$1.Expression.Names);
7208
- var values = nameNodes.map(function (nameNode) { return nameNode.Element$1.SimpleName; });
7209
- prev[name] = values;
7210
- break;
7211
- case 'ymin':
7212
- case 'ymax':
7213
- var numericVal = parseFloat(property.Element$1.Expression.ConstantValue);
7214
- prev[name] = numericVal;
7215
- break;
7216
- case 'title':
7217
- case 'xtitle':
7218
- case 'ytitle':
7219
- case 'visualization':
7220
- case 'series':
7221
- var strVal = property.Element$1.Expression.ConstantValue;
7222
- prev[name] = strVal;
7223
- break;
7224
- case 'xaxis':
7225
- case 'yaxis':
7226
- var scale = property.Element$1.Expression.ConstantValue;
7227
- prev[name] = scale;
7228
- break;
7229
- case 'legend':
7230
- var legend = property.Element$1.Expression.ConstantValue;
7231
- prev[name] = legend;
7232
- break;
7233
- case 'ySplit':
7234
- var split = property.Element$1.Expression.ConstantValue;
7235
- prev[name] = split;
7236
- break;
7237
- case 'accumulate':
7238
- var accumulate = property.Element$1.Expression.ConstantValue;
7239
- prev[name] = accumulate;
7240
- break;
7241
- case 'kind':
7242
- var val = property.Element$1.Expression.ConstantValue;
7243
- prev[name] = val;
7244
- break;
7245
- default:
7246
- assertNever(name);
7247
- }
7248
- return prev;
7249
- }, {});
7250
- var renderOptions = __assign({ visualization: visualization }, props);
7251
- var renderInfo = {
7252
- options: renderOptions,
7253
- location: { startOffset: startOffset, endOffset: endOffset },
7254
- };
7255
- return Promise.resolve(renderInfo);
7256
- };
7257
- KustoLanguageService.prototype.getReferencedGlobalParams = function (document, cursorOffset) {
7258
- if (!document || !this.isIntellisenseV2()) {
7259
- return Promise.resolve([]);
7260
- }
7261
- var script = this.parseDocumentV2(document);
7262
- var currentBlock = this.getCurrentCommandV2(script, cursorOffset);
7263
- if (!currentBlock) {
7264
- return Promise.resolve([]);
7265
- }
7266
- var text = currentBlock.Text;
7267
- var parsedAndAnalyzed = Kusto.Language.KustoCode.ParseAndAnalyze(text, this._kustoJsSchemaV2);
7268
- // We take the ambient parameters
7269
- var ambientParameters = this.toArray(this._kustoJsSchemaV2.Parameters);
7270
- // We take all referenced symbols in the query
7271
- var referencedSymbols = this.toArray(parsedAndAnalyzed.Syntax.GetDescendants(Kusto.Language.Syntax.Expression))
7272
- .filter(function (expression) { return expression.ReferencedSymbol !== null; })
7273
- .map(function (x) { return x.ReferencedSymbol; });
7274
- // The Intersection between them is the ambient parameters that are used in the query.
7275
- // Note: Ideally we would use Set here (or at least array.Include), but were' compiling down to es2015.
7276
- var intersection = referencedSymbols.filter(function (referencedSymbol) {
7277
- return ambientParameters.filter(function (ambientParameter) { return ambientParameter === referencedSymbol; }).length > 0;
7278
- });
7279
- var result = intersection.map(function (param) { return ({ name: param.Name, type: param.Type.Name }); });
7280
- return Promise.resolve(result);
7281
- };
7282
- KustoLanguageService.prototype.getGlobalParams = function (document) {
7283
- if (!this.isIntellisenseV2()) {
7284
- return Promise.resolve([]);
7285
- }
7286
- var params = this.toArray(this._kustoJsSchemaV2.Parameters);
7287
- var result = params.map(function (param) { return ({ name: param.Name, type: param.Type.Name }); });
7288
- return Promise.resolve(result);
7289
- };
7290
- KustoLanguageService.prototype.doRename = function (document, position, newName) {
7291
- var _a;
7292
- if (!document || !this.isIntellisenseV2()) {
7293
- return Promise.resolve(undefined);
7294
- }
7295
- var script = this.parseDocumentV2(document);
7296
- var cursorOffset = document.offsetAt(position);
7297
- var currentBLock = this.getCurrentCommandV2(script, cursorOffset);
7298
- if (!currentBLock) {
7299
- return Promise.resolve(undefined);
7300
- }
7301
- var relatedInfo = currentBLock.Service.GetRelatedElements(document.offsetAt(position));
7302
- var relatedElements = this.toArray(relatedInfo.Elements);
7303
- var declarations = relatedElements.filter(function (e) { return e.Kind == k2.RelatedElementKind.Declaration; });
7304
- // A declaration must be one of the elements
7305
- if (!declarations || declarations.length == 0) {
7306
- return Promise.resolve(undefined);
7307
- }
7308
- var edits = relatedElements.map(function (edit) {
7309
- var start = document.positionAt(edit.Start);
7310
- var end = document.positionAt(edit.End);
7311
- var range = ls.Range.create(start, end);
7312
- return ls.TextEdit.replace(range, newName);
7313
- });
7314
- // create a workspace edit
7315
- var workspaceEdit = { changes: (_a = {}, _a[document.uri] = edits, _a) };
7316
- return Promise.resolve(workspaceEdit);
7317
- };
7318
- KustoLanguageService.prototype.doHover = function (document, position) {
7319
- if (!document || !this.isIntellisenseV2()) {
7320
- return Promise.resolve(undefined);
7321
- }
7322
- var script = this.parseDocumentV2(document);
7323
- var cursorOffset = document.offsetAt(position);
7324
- var currentBLock = this.getCurrentCommandV2(script, cursorOffset);
7325
- if (!currentBLock) {
7326
- return Promise.resolve(undefined);
7327
- }
7328
- var isSupported = currentBLock.Service.IsFeatureSupported(k2.CodeServiceFeatures.QuickInfo, cursorOffset);
7329
- if (!isSupported) {
7330
- return Promise.resolve(undefined);
7331
- }
7332
- var quickInfo = currentBLock.Service.GetQuickInfo(cursorOffset);
7333
- if (!quickInfo || !quickInfo.Items) {
7334
- return Promise.resolve(undefined);
7335
- }
7336
- var items = this.toArray(quickInfo.Items);
7337
- if (!items) {
7338
- return Promise.resolve(undefined);
7339
- }
7340
- // Errors are already shown in getDiagnostics. we don't want them in doHover.
7341
- items = items.filter(function (item) { return item.Kind !== k2.QuickInfoKind.Error; });
7342
- var itemsText = items.map(function (item) { return item.Text.replace('\n\n', '\n* * *\n'); });
7343
- // separate items by horizontal line.
7344
- var text = itemsText.join('\n* * *\n');
7345
- // Instead of just an empty line between the first line (the signature) and the second line (the description)
7346
- // add an horizontal line (* * * in markdown) between them.
7347
- return Promise.resolve({ contents: text });
7348
- };
7349
- Object.defineProperty(KustoLanguageService, "dummySchema", {
7350
- //#region dummy schema for manual testing
7351
- get: function () {
7352
- var database = {
7353
- majorVersion: 0,
7354
- minorVersion: 0,
7355
- name: 'Kuskus',
7356
- tables: [
7357
- {
7358
- name: 'KustoLogs',
7359
- columns: [
7360
- {
7361
- name: 'Source',
7362
- type: 'string',
7363
- },
7364
- {
7365
- name: 'Timestamp',
7366
- type: 'datetime',
7367
- },
7368
- {
7369
- name: 'Directory',
7370
- type: 'string',
7371
- },
7372
- ],
7373
- docstring: 'A dummy description to test that docstring shows as expected when hovering over a table',
7374
- },
7375
- ],
7376
- functions: [
7377
- {
7378
- name: 'HowBig',
7379
- inputParameters: [
7380
- {
7381
- name: 'T',
7382
- columns: [
7383
- {
7384
- name: 'Timestamp',
7385
- type: 'System.DateTime',
7386
- cslType: 'datetime',
7387
- },
7388
- ],
7389
- },
7390
- ],
7391
- docstring: 'A dummy description to test that docstring shows as expected when hovering over a function',
7392
- 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}",
7393
- },
7394
- {
7395
- name: 'FindCIDPast24h',
7396
- inputParameters: [
7397
- {
7398
- name: 'clientActivityId',
7399
- type: 'System.String',
7400
- cslType: 'string',
7401
- },
7402
- ],
7403
- body: '{ KustoLogs | where Timestamp > now(-1d) | where ClientActivityId == clientActivityId} ',
7404
- },
7405
- ],
7406
- };
7407
- var languageServiceSchema = {
7408
- clusterType: 'Engine',
7409
- cluster: {
7410
- connectionString: 'https://kuskus.kusto.windows.net;fed=true',
7411
- databases: [database],
7412
- },
7413
- database: database,
7414
- };
7415
- return languageServiceSchema;
7416
- },
7417
- enumerable: false,
7418
- configurable: true
7419
- });
7420
- //#endregion
7421
- KustoLanguageService.convertToEntityDataType = function (kustoType) { };
7422
- /**
7423
- * We do not want to expose Bridge.Net generated schema, so we expose a cleaner javascript schema.
7424
- * Here it gets converted to the bridge.Net schema
7425
- * @param schema Language Service schema
7426
- */
7427
- KustoLanguageService.convertToKustoJsSchema = function (schema) {
7428
- switch (schema.clusterType) {
7429
- case 'Engine':
7430
- var currentDatabaseName_1 = schema.database ? schema.database.name : undefined;
7431
- var kCluster = new k.KustoIntelliSenseClusterEntity();
7432
- var kDatabaseInContext_1 = undefined;
7433
- kCluster.ConnectionString = schema.cluster.connectionString;
7434
- var databases_1 = [];
7435
- schema.cluster.databases.forEach(function (database) {
7436
- var kDatabase = new k.KustoIntelliSenseDatabaseEntity();
7437
- kDatabase.Name = database.name;
7438
- var tables = [];
7439
- database.tables.forEach(function (table) {
7440
- var kTable = new k.KustoIntelliSenseTableEntity();
7441
- kTable.Name = table.name;
7442
- var cols = [];
7443
- table.columns.forEach(function (column) {
7444
- var kColumn = new k.KustoIntelliSenseColumnEntity();
7445
- kColumn.Name = column.name;
7446
- kColumn.TypeCode = k.EntityDataType[schema_1.getEntityDataTypeFromCslType(column.type)];
7447
- cols.push(kColumn);
7448
- });
7449
- kTable.Columns = new Bridge.ArrayEnumerable(cols);
7450
- tables.push(kTable);
7451
- });
7452
- var functions = [];
7453
- database.functions.forEach(function (fn) {
7454
- var kFunction = new k.KustoIntelliSenseFunctionEntity();
7455
- (kFunction.Name = fn.name),
7456
- (kFunction.CallName = s.getCallName(fn)),
7457
- (kFunction.Expression = s.getExpression(fn)),
7458
- functions.push(kFunction);
7459
- });
7460
- kDatabase.Tables = new Bridge.ArrayEnumerable(tables);
7461
- kDatabase.Functions = new Bridge.ArrayEnumerable(functions);
7462
- databases_1.push(kDatabase);
7463
- if (database.name == currentDatabaseName_1) {
7464
- kDatabaseInContext_1 = kDatabase;
7465
- }
7466
- });
7467
- kCluster.Databases = new Bridge.ArrayEnumerable(databases_1);
7468
- var kSchema = new k.KustoIntelliSenseQuerySchema(kCluster, kDatabaseInContext_1);
7469
- return kSchema;
7470
- case 'ClusterManager':
7471
- var accounts = schema.accounts.map(function (account) {
7472
- var kAccount = new k.KustoIntelliSenseAccountEntity();
7473
- kAccount.Name = account;
7474
- return kAccount;
7475
- });
7476
- var services = schema.services.map(function (service) {
7477
- var kService = new k.KustoIntelliSenseServiceEntity();
7478
- kService.Name = service;
7479
- return kService;
7480
- });
7481
- var connectionString = schema.connectionString;
7482
- var result = {
7483
- accounts: accounts,
7484
- services: services,
7485
- connectionString: connectionString,
7486
- };
7487
- return result;
7488
- case 'DataManagement':
7489
- return undefined;
7490
- default:
7491
- return assertNever(schema);
7492
- }
7493
- };
7494
- /**
7495
- * Returns something like '(x: string, y: datetime)'
7496
- * @param params scalar parameters
7497
- */
7498
- KustoLanguageService.scalarParametersToSignature = function (params) {
7499
- var signatureWithoutParens = params.map(function (param) { return param.name + ": " + param.cslType; }).join(', ');
7500
- return "(" + signatureWithoutParens + ")";
7501
- };
7502
- /**
7503
- * Returns something like '(x: string, T: (y: int))'
7504
- * @param params input parameters (tabular or scalar)
7505
- */
7506
- KustoLanguageService.inputParameterToSignature = function (params) {
7507
- var _this = this;
7508
- var signatureWithoutParens = params
7509
- .map(function (param) {
7510
- if (param.columns) {
7511
- var tableSignature = _this.scalarParametersToSignature(param.columns);
7512
- return param.name + ": " + tableSignature;
7513
- }
7514
- else {
7515
- return param.name + ": " + param.cslType;
7516
- }
7517
- })
7518
- .join(', ');
7519
- return "(" + signatureWithoutParens + ")";
7520
- };
7521
- /**
7522
- * converts a function definition to a let statement.
7523
- * @param fn function
7524
- */
7525
- KustoLanguageService.toLetStatement = function (fn) {
7526
- var signature = this.inputParameterToSignature(fn.inputParameters);
7527
- return "let " + fn.name + " = " + signature + " " + fn.body;
7528
- };
7529
- KustoLanguageService.createColumnSymbol = function (col) {
7530
- return new sym.ColumnSymbol(col.name, sym.ScalarTypes.GetSymbol(schema_1.getCslTypeNameFromClrType(col.type)), col.docstring);
7531
- };
7532
- KustoLanguageService.createParameterSymbol = function (param) {
7533
- var paramSymbol = Kusto.Language.Symbols.ScalarTypes.GetSymbol(schema_1.getCslTypeNameFromClrType(param.type));
7534
- return new sym.ParameterSymbol(param.name, paramSymbol, null);
7535
- };
7536
- KustoLanguageService.createParameter = function (param) {
7537
- if (!param.columns) {
7538
- var paramSymbol = Kusto.Language.Symbols.ScalarTypes.GetSymbol(schema_1.getCslTypeNameFromClrType(param.type));
7539
- var expression = param.cslDefaultValue && typeof param.cslDefaultValue === 'string'
7540
- ? parsing.QueryParser.ParseLiteral$1(param.cslDefaultValue)
7541
- : undefined;
7542
- return new sym.Parameter.$ctor3(param.name, paramSymbol, null, null, null, false, null, 1, 1, expression, null);
7543
- }
7544
- if (param.columns.length == 0) {
7545
- return new sym.Parameter.ctor(param.name, sym.ParameterTypeKind.Tabular, sym.ArgumentKind.Expression, null, null, false, null, 1, 1, null, null);
7546
- }
7547
- var argumentType = new sym.TableSymbol.ctor(param.columns.map(function (col) { return KustoLanguageService.createColumnSymbol(col); }));
7548
- return new sym.Parameter.$ctor2(param.name, argumentType);
7549
- };
7550
- KustoLanguageService.convertToDatabaseSymbol = function (db, globalState, addFunctions) {
7551
- var createFunctionSymbol = function (fn) {
7552
- var parameters = fn.inputParameters.map(function (param) {
7553
- return KustoLanguageService.createParameter(param);
7554
- });
7555
- // TODO: handle outputColumns (right now it doesn't seem to be implemented for any function).
7556
- return new sym.FunctionSymbol.$ctor16(fn.name, fn.body, KustoLanguageService.toBridgeList(parameters), fn.docstring);
7557
- };
7558
- var createTableSymbol = function (tbl) {
7559
- var columnSymbols = tbl.columns.map(function (col) { return KustoLanguageService.createColumnSymbol(col); });
7560
- var symbol = new sym.TableSymbol.$ctor3(tbl.name, columnSymbols);
7561
- symbol.Description = tbl.docstring;
7562
- switch (tbl.entityType) {
7563
- case 'MaterializedViewTable':
7564
- symbol = symbol.WithIsMaterializedView(true);
7565
- break;
7566
- case 'ExternalTable':
7567
- symbol = symbol.WithIsExternal(true);
7568
- break;
7569
- default:
7570
- }
7571
- return symbol;
7572
- };
7573
- var createDatabaseSymbol = function (db) {
7574
- var tableSymbols = db.tables ? db.tables.map(function (tbl) { return createTableSymbol(tbl); }) : [];
7575
- var functionSymbols = db.functions ? db.functions.map(function (fun) { return createFunctionSymbol(fun); }) : [];
7576
- return new sym.DatabaseSymbol.ctor(db.name, tableSymbols.concat(functionSymbols));
7577
- };
7578
- var databaseSymbol = createDatabaseSymbol(db);
7579
- return databaseSymbol;
7580
- };
7581
- KustoLanguageService.prototype.convertToKustoJsSchemaV2 = function (schema) {
7582
- var cached = this._schemaCache[schema.cluster.connectionString];
7583
- // create a cache entry for the cluster if non yet exists.
7584
- if (!cached) {
7585
- this._schemaCache[schema.cluster.connectionString] = {};
7586
- cached = this._schemaCache[schema.cluster.connectionString];
7587
- }
7588
- // Remove deleted databases from cache
7589
- var schemaDbLookup = schema.cluster.databases.reduce(function (prev, curr) { return (prev[curr.name] = curr); }, {});
7590
- Object.keys(cached).map(function (dbName) {
7591
- if (!schemaDbLookup[dbName]) {
7592
- delete cached.dbName;
7593
- }
7594
- });
7595
- var globalState = GlobalState.Default;
7596
- var currentDatabaseName = schema.database ? schema.database.name : undefined;
7597
- var databaseInContext = undefined;
7598
- // Update out-of-data databases to cache
7599
- var databases = schema.cluster.databases.map(function (db) {
7600
- var shouldIncludeFunctions = db.name === currentDatabaseName;
7601
- var cachedDb = cached[db.name];
7602
- // This is an older version than we have, or we need to parse functions.
7603
- if (!cachedDb ||
7604
- cachedDb.database.majorVersion < db.majorVersion ||
7605
- (shouldIncludeFunctions && !cachedDb.includesFunctions)) {
7606
- // only add functions for the database in context (it's very time consuming)
7607
- var databaseSymbol_1 = KustoLanguageService.convertToDatabaseSymbol(db, globalState, shouldIncludeFunctions);
7608
- cached[db.name] = { database: db, symbol: databaseSymbol_1, includesFunctions: shouldIncludeFunctions };
7609
- }
7610
- var databaseSymbol = cached[db.name].symbol;
7611
- if (db.name === currentDatabaseName) {
7612
- databaseInContext = databaseSymbol;
7613
- }
7614
- return databaseSymbol;
7615
- });
7616
- // Replace new URL due to polyfill issue in IE
7617
- // const hostname = new URL(schema.cluster.connectionString.split(';')[0]).hostname;
7618
- var hostname = schema.cluster.connectionString.match(/(.*\/\/)?([^\/;]*)/)[2];
7619
- var clusterName = hostname.split('.')[0];
7620
- var clusterSymbol = new sym.ClusterSymbol.ctor(clusterName, databases);
7621
- globalState = globalState.WithCluster(clusterSymbol);
7622
- if (databaseInContext) {
7623
- globalState = globalState.WithDatabase(databaseInContext);
7624
- }
7625
- // Inject global parameters to global scope.
7626
- if (schema.globalParameters) {
7627
- var parameters = schema.globalParameters.map(function (param) {
7628
- return KustoLanguageService.createParameterSymbol(param);
7629
- });
7630
- globalState = globalState.WithParameters(KustoLanguageService.toBridgeList(parameters));
7631
- }
7632
- return globalState;
7633
- };
7634
- KustoLanguageService.prototype.getClassificationsFromParseResult = function (offset) {
7635
- var _this = this;
7636
- if (offset === void 0) { offset = 0; }
7637
- var classifications = this.toArray(this._parser.Results)
7638
- .map(function (command) { return _this.toArray(command.Tokens); })
7639
- .reduce(function (prev, curr) { return prev.concat(curr); }, [])
7640
- .map(function (cslCommandToken) {
7641
- var range = new k2.ClassifiedRange(_this.tokenKindToClassificationKind(cslCommandToken.TokenKind), cslCommandToken.AbsoluteStart + offset, cslCommandToken.Length);
7642
- return range;
7643
- });
7644
- return classifications;
7645
- };
7646
- /**
7647
- * trim trailing newlines from range
7648
- */
7649
- KustoLanguageService.trimTrailingNewlineFromRange = function (textInRange, rangeStartOffset, document, range) {
7650
- var currentIndex = textInRange.length - 1;
7651
- while (textInRange[currentIndex] === '\r' || textInRange[currentIndex] === '\n') {
7652
- --currentIndex;
7653
- }
7654
- var newEndOffset = rangeStartOffset + currentIndex + 1;
7655
- var newEndPosition = document.positionAt(newEndOffset);
7656
- var newRange = ls.Range.create(range.start, newEndPosition);
7657
- return newRange;
7658
- };
7659
- /**
7660
- * Maps numbers to strings, such that if a>b numerically, f(a)>f(b) lexicographically.
7661
- * 1 -> "a", 26 -> "z", 27 -> "za", 28 -> "zb", 52 -> "zz", 53 ->"zza"
7662
- * @param order - The number to be converted to a sorting-string. order should start at 1.
7663
- * @returns A string repenting the order.
7664
- */
7665
- KustoLanguageService.prototype.getSortText = function (order) {
7666
- if (order <= 0) {
7667
- throw new RangeError("order should be a number >= 1. instead got " + order);
7668
- }
7669
- var sortText = '';
7670
- var numCharacters = 26; // "z" - "a" + 1;
7671
- var div = Math.floor(order / numCharacters);
7672
- for (var i = 0; i < div; ++i) {
7673
- sortText += 'z';
7674
- }
7675
- var reminder = order % numCharacters;
7676
- if (reminder > 0) {
7677
- sortText += String.fromCharCode(96 + reminder);
7678
- }
7679
- return sortText;
7680
- };
7681
- /**
7682
- * ParseTextV1 parses the given text with the given parse mode.
7683
- * Additionally - it will make sure not to provide rules provider for non-engine clusters
7684
- * since the only rules provider parse can handle is the engine's. It will try to look for function
7685
- * definitions to colorize and will throw since they're not there.
7686
- * @param text
7687
- * @param parseMode
7688
- */
7689
- KustoLanguageService.prototype.parseTextV1 = function (text, parseMode) {
7690
- this._parser.Parse(this._schema.clusterType === 'Engine' ? this._rulesProvider : null, text, parseMode);
7691
- };
7692
- KustoLanguageService.prototype.parseDocumentV1 = function (document, parseMode) {
7693
- // already parsed a later version, or better parse mode for this uri
7694
- if (this._parsePropertiesV1 &&
7695
- !this._parsePropertiesV1.isParseNeeded(document, this._rulesProvider, parseMode)) {
7696
- return;
7697
- }
7698
- this.parseTextV1(document.getText(), parseMode);
7699
- this._parsePropertiesV1 = new ParseProperties(document.version, document.uri, this._rulesProvider, parseMode);
7700
- };
7701
- KustoLanguageService.prototype.parseDocumentV2 = function (document) {
7702
- if (this._parsePropertiesV2 && !this._parsePropertiesV2.isParseNeeded(document, this._rulesProvider)) {
7703
- return this._script;
7704
- }
7705
- if (!this._script) {
7706
- this._script = k2.CodeScript.From$1(document.getText(), this._kustoJsSchemaV2);
7707
- }
7708
- else {
7709
- this._script = this._script.WithText(document.getText());
7710
- }
7711
- this._parsePropertiesV2 = new ParseProperties(document.version, document.uri);
7712
- return this._script;
7713
- };
7714
- /**
7715
- * Return the CslCommand that wraps the caret location, or undefined if caret is outside any command
7716
- * @param document the document to extract the current command from
7717
- * @param caretAbsolutePosition absolute caret position
7718
- */
7719
- KustoLanguageService.prototype.getCurrentCommand = function (document, caretAbsolutePosition) {
7720
- var commands = this.toArray(this._parser.Results);
7721
- var command = commands.filter(function (command) { return command.AbsoluteStart <= caretAbsolutePosition && command.AbsoluteEnd >= caretAbsolutePosition; })[0];
7722
- // There is an edge case when cursor appears at the end of the command
7723
- // which is not yet considered to be part of the parsed command (therefore: +1 for the AbsoluteEdit property)
7724
- if (!command) {
7725
- command = commands.filter(function (command) {
7726
- return command.AbsoluteStart <= caretAbsolutePosition && command.AbsoluteEnd + 1 >= caretAbsolutePosition;
7727
- })[0];
7728
- // If we have 2 newlines in the end of the text the cursor is _probably_ at the end of the text
7729
- // which this means that we're not actually standing on any command. Thus return null.
7730
- if (!command || command.Text.endsWith('\r\n\r\n')) {
7731
- return null;
7732
- }
7733
- }
7734
- return command;
7735
- };
7736
- KustoLanguageService.prototype.getCurrentCommandV2 = function (script, offset) {
7737
- var block = script.GetBlockAtPosition(offset);
7738
- return block;
7739
- };
7740
- KustoLanguageService.prototype.getTextToInsert = function (rule, option) {
7741
- var beforeApplyInfo = rule.GetBeforeApplyInfo(option.Value);
7742
- var afterApplyInfo = rule.GetAfterApplyInfo(option.Value);
7743
- // this is the basic text to be inserted,
7744
- // but we still need to figure out where the cursor will end up after completion is applied.
7745
- var insertText = beforeApplyInfo.Text || '' + option.Value + afterApplyInfo.Text || '';
7746
- var insertTextFormat = ls.InsertTextFormat.PlainText;
7747
- var snippetFinalTabStop = '$0';
7748
- if (afterApplyInfo.OffsetToken && afterApplyInfo.OffsetPosition) {
7749
- var tokenOffset = insertText.indexOf(afterApplyInfo.OffsetToken);
7750
- if (tokenOffset >= 0) {
7751
- insertText = this.insertToString(insertText, snippetFinalTabStop, tokenOffset - insertText.length + afterApplyInfo.OffsetPosition);
7752
- insertTextFormat = ls.InsertTextFormat.Snippet;
7753
- }
7754
- }
7755
- else if (afterApplyInfo.OffsetPosition) {
7756
- // We only handle negative offsets
7757
- insertText = this.insertToString(insertText, snippetFinalTabStop, afterApplyInfo.OffsetPosition);
7758
- insertTextFormat = ls.InsertTextFormat.Snippet;
7759
- }
7760
- return { insertText: insertText, insertTextFormat: insertTextFormat };
7761
- };
7762
- /**
7763
- * create a new string with stringToInsert inserted at offsetFromEnd in originalString.
7764
- * @param originalString string to insert to
7765
- * @param stringToInsert string to insert
7766
- * @param offsetFromEnd a negative number that will represent offset to the left. 0 means simple concat
7767
- */
7768
- KustoLanguageService.prototype.insertToString = function (originalString, stringToInsert, offsetFromEnd) {
7769
- var index = originalString.length + offsetFromEnd;
7770
- if (offsetFromEnd >= 0 || index < 0) {
7771
- return originalString; // Cannot insert before or after the string
7772
- }
7773
- var before = originalString.substring(0, index);
7774
- var after = originalString.substring(index);
7775
- return before + stringToInsert + after;
7776
- };
7777
- KustoLanguageService.prototype.getCommandWithoutLastWord = function (text) {
7778
- var lastWordRegex = XRegExp('[\\w_]*$', 's');
7779
- return text.replace(lastWordRegex, '');
7780
- };
7781
- KustoLanguageService.prototype.createRulesProvider = function (schema, clusterType) {
7782
- var queryParameters = new (List(String))();
7783
- var availableClusters = new (List(String))();
7784
- this._parser = new k.CslCommandParser();
7785
- if (clusterType == 'Engine') {
7786
- var engineSchema = schema;
7787
- this._rulesProvider =
7788
- this._languageSettings && this._languageSettings.includeControlCommands
7789
- ? new k.CslIntelliSenseRulesProvider.$ctor1(engineSchema.Cluster, engineSchema, queryParameters, availableClusters, null, true, true)
7790
- : new k.CslQueryIntelliSenseRulesProvider.$ctor1(engineSchema.Cluster, engineSchema, queryParameters, availableClusters, null, null, null);
7791
- return;
7792
- }
7793
- if (clusterType === 'DataManagement') {
7794
- this._rulesProvider = new k.DataManagerIntelliSenseRulesProvider(null);
7795
- return;
7796
- }
7797
- // This is a cluster manger
7798
- var _a = schema, accounts = _a.accounts, services = _a.services, connectionString = _a.connectionString;
7799
- new k.KustoIntelliSenseAccountEntity();
7800
- new k.KustoIntelliSenseServiceEntity();
7801
- this._rulesProvider = new k.ClusterManagerIntelliSenseRulesProvider.$ctor1(new Bridge.ArrayEnumerable(accounts), new Bridge.ArrayEnumerable(services), connectionString);
7802
- };
7803
- KustoLanguageService.prototype.kustoKindToLsKind = function (kustoKind) {
7804
- var res = this._kustoKindtolsKind[kustoKind];
7805
- return res ? res : ls.CompletionItemKind.Variable;
7806
- };
7807
- KustoLanguageService.prototype.kustoKindToLsKindV2 = function (kustoKind) {
7808
- var res = this._kustoKindToLsKindV2[kustoKind];
7809
- return res ? res : ls.CompletionItemKind.Variable;
7810
- };
7811
- KustoLanguageService.prototype.createRange = function (document, start, end) {
7812
- return ls.Range.create(document.positionAt(start), document.positionAt(end));
7813
- };
7814
- KustoLanguageService.prototype.toArray = function (bridgeList) {
7815
- return Bridge.toArray(bridgeList);
7816
- };
7817
- KustoLanguageService.toBridgeList = function (array) {
7818
- // copied from bridge.js from the implementation of Enumerable.prototype.toList
7819
- return new (System.Collections.Generic.List$1(System.Object).$ctor1)(array);
7820
- };
7821
- KustoLanguageService.prototype.tokenKindToClassificationKind = function (token) {
7822
- var conversion = this._tokenKindToClassificationKind[token];
7823
- return conversion || k2.ClassificationKind.PlainText;
7824
- };
7825
- KustoLanguageService.prototype.parseAndAnalyze = function (document, cursorOffset) {
7826
- if (!document || !this.isIntellisenseV2()) {
7827
- return undefined;
7828
- }
7829
- var script = this.parseDocumentV2(document);
7830
- var currentBlock = this.getCurrentCommandV2(script, cursorOffset);
7831
- if (!currentBlock) {
7832
- return undefined;
7833
- }
7834
- var text = currentBlock.Text;
7835
- var parsedAndAnalyzed = Kusto.Language.KustoCode.ParseAndAnalyze(text, this._kustoJsSchemaV2);
7836
- return parsedAndAnalyzed;
7837
- };
7838
- return KustoLanguageService;
7839
- }());
7840
- var languageService = new KustoLanguageService(KustoLanguageService.dummySchema, {
7841
- includeControlCommands: true,
7842
- useIntellisenseV2: true,
7843
- useSemanticColorization: true,
7844
- });
7845
- /**
7846
- * Obtain an instance of the kusto language service.
7847
- */
7848
- function getKustoLanguageService() {
7849
- return languageService;
7850
- }
7851
- exports.getKustoLanguageService = getKustoLanguageService;
7852
- });
6266
+ var __assign = (this && this.__assign) || function () {
6267
+ __assign = Object.assign || function(t) {
6268
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
6269
+ s = arguments[i];
6270
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
6271
+ t[p] = s[p];
6272
+ }
6273
+ return t;
6274
+ };
6275
+ return __assign.apply(this, arguments);
6276
+ };
6277
+ define('vs/language/kusto/languageService/kustoLanguageService',["require", "exports", "./schema", "vscode-languageserver-types", "xregexp", "./schema"], function (require, exports, s, ls, XRegExp, schema_1) {
6278
+ "use strict";
6279
+ Object.defineProperty(exports, "__esModule", { value: true });
6280
+ exports.getKustoLanguageService = exports.TokenKind = void 0;
6281
+ // polyfill string endsWith
6282
+ if (!String.prototype.endsWith) {
6283
+ String.prototype.endsWith = function (search, this_len) {
6284
+ if (this_len === undefined || this_len > this.length) {
6285
+ this_len = this.length;
6286
+ }
6287
+ return this.substring(this_len - search.length, this_len) === search;
6288
+ };
6289
+ }
6290
+ // If we're running in a web worker - which doesn't share global context with the main thread -
6291
+ // we need to manually load dependencies that are not explicit- meaning our non-module dependencies
6292
+ // generated by Bridge.Net
6293
+ if (typeof document == 'undefined') {
6294
+ // monaco will run the worker from vs/base/worker so the relative path needs to be from there (hence going up 2 dirs)
6295
+ importScripts('../../language/kusto/bridge.min.js');
6296
+ importScripts('../../language/kusto/kusto.javascript.client.min.js');
6297
+ importScripts('../../language/kusto/Kusto.Language.Bridge.min.js');
6298
+ }
6299
+ var k = Kusto.Data.IntelliSense;
6300
+ var parsing = Kusto.Language.Parsing;
6301
+ var k2 = Kusto.Language.Editor;
6302
+ var sym = Kusto.Language.Symbols;
6303
+ var GlobalState = Kusto.Language.GlobalState;
6304
+ var List = System.Collections.Generic.List$1;
6305
+ function assertNever(x) {
6306
+ throw new Error('Unexpected object: ' + x);
6307
+ }
6308
+ var ParseProperties = /** @class */ (function () {
6309
+ function ParseProperties(version, uri, rulesProvider, parseMode) {
6310
+ this.version = version;
6311
+ this.uri = uri;
6312
+ this.rulesProvider = rulesProvider;
6313
+ this.parseMode = parseMode;
6314
+ }
6315
+ ParseProperties.prototype.isParseNeeded = function (document, rulesProvider, parseMode) {
6316
+ if (document.uri === this.uri &&
6317
+ (!rulesProvider || rulesProvider === this.rulesProvider) &&
6318
+ document.version <= this.version &&
6319
+ parseMode &&
6320
+ parseMode <= this.parseMode) {
6321
+ return false;
6322
+ }
6323
+ return true;
6324
+ };
6325
+ return ParseProperties;
6326
+ }());
6327
+ var TokenKind;
6328
+ (function (TokenKind) {
6329
+ TokenKind[TokenKind["TableToken"] = 2] = "TableToken";
6330
+ TokenKind[TokenKind["TableColumnToken"] = 4] = "TableColumnToken";
6331
+ TokenKind[TokenKind["OperatorToken"] = 8] = "OperatorToken";
6332
+ TokenKind[TokenKind["SubOperatorToken"] = 16] = "SubOperatorToken";
6333
+ TokenKind[TokenKind["CalculatedColumnToken"] = 32] = "CalculatedColumnToken";
6334
+ TokenKind[TokenKind["StringLiteralToken"] = 64] = "StringLiteralToken";
6335
+ TokenKind[TokenKind["FunctionNameToken"] = 128] = "FunctionNameToken";
6336
+ TokenKind[TokenKind["UnknownToken"] = 256] = "UnknownToken";
6337
+ TokenKind[TokenKind["CommentToken"] = 512] = "CommentToken";
6338
+ TokenKind[TokenKind["PlainTextToken"] = 1024] = "PlainTextToken";
6339
+ TokenKind[TokenKind["DataTypeToken"] = 2048] = "DataTypeToken";
6340
+ TokenKind[TokenKind["ControlCommandToken"] = 4096] = "ControlCommandToken";
6341
+ TokenKind[TokenKind["CommandPartToken"] = 8192] = "CommandPartToken";
6342
+ TokenKind[TokenKind["QueryParametersToken"] = 16384] = "QueryParametersToken";
6343
+ TokenKind[TokenKind["CslCommandToken"] = 32768] = "CslCommandToken";
6344
+ TokenKind[TokenKind["LetVariablesToken"] = 65536] = "LetVariablesToken";
6345
+ TokenKind[TokenKind["PluginToken"] = 131072] = "PluginToken";
6346
+ TokenKind[TokenKind["BracketRangeToken"] = 262144] = "BracketRangeToken";
6347
+ TokenKind[TokenKind["ClientDirectiveToken"] = 524288] = "ClientDirectiveToken";
6348
+ })(TokenKind = exports.TokenKind || (exports.TokenKind = {}));
6349
+ /**
6350
+ * convert the bridge.net object to a plain javascript object that only contains data.
6351
+ * @param k2Classifications @kusto/language-service-next bridge.net object
6352
+ */
6353
+ function toClassifiedRange(k2Classifications) {
6354
+ return k2Classifications.map(function (classification) { return ({
6355
+ start: classification.Start,
6356
+ end: classification.End,
6357
+ length: classification.Length,
6358
+ kind: classification.Kind,
6359
+ }); });
6360
+ }
6361
+ ;
6362
+ /**
6363
+ * Kusto Language service translates the kusto object model (transpiled from C# by Bridge.Net)
6364
+ * to the vscode language server types, which are used by vscode language extensions.
6365
+ * This should make things easier in the future to provide a vscode extension based on this translation layer.
6366
+ *
6367
+ * Further translations, if needed, to support specific editors (Atom, sublime, Etc)
6368
+ * should be done on top of this API, since it is (at least meant to be) a standard that is supported by multiple editors.
6369
+ *
6370
+ * Note1: Currently monaco isn't using this object model so further translation will be necessary on calling modules.
6371
+ *
6372
+ * Note2: This file is responsible for interacting with the kusto object model and exposing Microsoft language service types.
6373
+ * An exception to that rule is tokenization (and syntax highlighting which depends on it) -
6374
+ * since it's not currently part of the Microsoft language service protocol. Thus tokenize() _does_ 'leak' kusto types to the callers.
6375
+ */
6376
+ var KustoLanguageService = /** @class */ (function () {
6377
+ function KustoLanguageService(schema, languageSettings) {
6378
+ var _a, _b, _c, _d;
6379
+ var _this = this;
6380
+ this._toOptionKind = (_a = {},
6381
+ _a[k2.CompletionKind.AggregateFunction] = k.OptionKind.FunctionAggregation,
6382
+ _a[k2.CompletionKind.BuiltInFunction] = k.OptionKind.FunctionServerSide,
6383
+ _a[k2.CompletionKind.Cluster] = k.OptionKind.Database,
6384
+ _a[k2.CompletionKind.Column] = k.OptionKind.Column,
6385
+ _a[k2.CompletionKind.CommandPrefix] = k.OptionKind.None,
6386
+ _a[k2.CompletionKind.Database] = k.OptionKind.Database,
6387
+ _a[k2.CompletionKind.DatabaseFunction] = k.OptionKind.FunctionServerSide,
6388
+ _a[k2.CompletionKind.Example] = k.OptionKind.None,
6389
+ _a[k2.CompletionKind.Identifier] = k.OptionKind.None,
6390
+ _a[k2.CompletionKind.Keyword] = k.OptionKind.None,
6391
+ _a[k2.CompletionKind.LocalFunction] = k.OptionKind.FunctionLocal,
6392
+ _a[k2.CompletionKind.MaterialiedView] = k.OptionKind.MaterializedView,
6393
+ _a[k2.CompletionKind.Parameter] = k.OptionKind.Parameter,
6394
+ _a[k2.CompletionKind.Punctuation] = k.OptionKind.None,
6395
+ _a[k2.CompletionKind.QueryPrefix] = k.OptionKind.Operator,
6396
+ _a[k2.CompletionKind.RenderChart] = k.OptionKind.Operator,
6397
+ _a[k2.CompletionKind.ScalarInfix] = k.OptionKind.None,
6398
+ _a[k2.CompletionKind.ScalarPrefix] = k.OptionKind.None,
6399
+ _a[k2.CompletionKind.ScalarType] = k.OptionKind.DataType,
6400
+ _a[k2.CompletionKind.Syntax] = k.OptionKind.None,
6401
+ _a[k2.CompletionKind.Table] = k.OptionKind.Table,
6402
+ _a[k2.CompletionKind.TabularPrefix] = k.OptionKind.None,
6403
+ _a[k2.CompletionKind.TabularSuffix] = k.OptionKind.None,
6404
+ _a[k2.CompletionKind.Unknown] = k.OptionKind.None,
6405
+ _a[k2.CompletionKind.Variable] = k.OptionKind.Parameter,
6406
+ _a[k2.CompletionKind.Option] = k.OptionKind.Option,
6407
+ _a);
6408
+ this.disabledCompletionItemsV2 = {
6409
+ // render charts
6410
+ ladderchart: k2.CompletionKind.RenderChart,
6411
+ pivotchart: k2.CompletionKind.RenderChart,
6412
+ timeline: k2.CompletionKind.RenderChart,
6413
+ timepivot: k2.CompletionKind.RenderChart,
6414
+ '3Dchart': k2.CompletionKind.RenderChart,
6415
+ list: k2.CompletionKind.RenderChart,
6416
+ };
6417
+ this.isIntellisenseV2 = function () {
6418
+ return _this._languageSettings.useIntellisenseV2 && _this._schema && _this._schema.clusterType === 'Engine';
6419
+ };
6420
+ this.disabledCompletionItemsV1 = {
6421
+ capacity: k.OptionKind.Policy,
6422
+ callout: k.OptionKind.Policy,
6423
+ encoding: k.OptionKind.Policy,
6424
+ batching: k.OptionKind.Policy,
6425
+ querythrottling: k.OptionKind.Policy,
6426
+ merge: k.OptionKind.Policy,
6427
+ querylimit: k.OptionKind.Policy,
6428
+ rowstore: k.OptionKind.Policy,
6429
+ streamingingestion: k.OptionKind.Policy,
6430
+ restricted_view_access: k.OptionKind.Policy,
6431
+ sharding: k.OptionKind.Policy,
6432
+ 'restricted-viewers': k.OptionKind.Policy,
6433
+ attach: k.OptionKind.Command,
6434
+ purge: k.OptionKind.Command,
6435
+ };
6436
+ this._kustoKindtolsKind = (_b = {},
6437
+ _b[k.OptionKind.None] = ls.CompletionItemKind.Interface,
6438
+ _b[k.OptionKind.Operator] = ls.CompletionItemKind.Method,
6439
+ _b[k.OptionKind.Command] = ls.CompletionItemKind.Method,
6440
+ _b[k.OptionKind.Service] = ls.CompletionItemKind.Class,
6441
+ _b[k.OptionKind.Policy] = ls.CompletionItemKind.Reference,
6442
+ _b[k.OptionKind.Database] = ls.CompletionItemKind.Class,
6443
+ _b[k.OptionKind.Table] = ls.CompletionItemKind.Class,
6444
+ _b[k.OptionKind.DataType] = ls.CompletionItemKind.Class,
6445
+ _b[k.OptionKind.Literal] = ls.CompletionItemKind.Property,
6446
+ _b[k.OptionKind.Parameter] = ls.CompletionItemKind.Variable,
6447
+ _b[k.OptionKind.IngestionMapping] = ls.CompletionItemKind.Variable,
6448
+ _b[k.OptionKind.ExpressionFunction] = ls.CompletionItemKind.Variable,
6449
+ _b[k.OptionKind.Option] = ls.CompletionItemKind.Interface,
6450
+ _b[k.OptionKind.OptionKind] = ls.CompletionItemKind.Interface,
6451
+ _b[k.OptionKind.OptionRender] = ls.CompletionItemKind.Interface,
6452
+ _b[k.OptionKind.Column] = ls.CompletionItemKind.Function,
6453
+ _b[k.OptionKind.ColumnString] = ls.CompletionItemKind.Field,
6454
+ _b[k.OptionKind.ColumnNumeric] = ls.CompletionItemKind.Field,
6455
+ _b[k.OptionKind.ColumnDateTime] = ls.CompletionItemKind.Field,
6456
+ _b[k.OptionKind.ColumnTimespan] = ls.CompletionItemKind.Field,
6457
+ _b[k.OptionKind.FunctionServerSide] = ls.CompletionItemKind.Field,
6458
+ _b[k.OptionKind.FunctionAggregation] = ls.CompletionItemKind.Field,
6459
+ _b[k.OptionKind.FunctionFilter] = ls.CompletionItemKind.Field,
6460
+ _b[k.OptionKind.FunctionScalar] = ls.CompletionItemKind.Field,
6461
+ _b[k.OptionKind.ClientDirective] = ls.CompletionItemKind.Enum,
6462
+ _b);
6463
+ this._kustoKindToLsKindV2 = (_c = {},
6464
+ _c[k2.CompletionKind.AggregateFunction] = ls.CompletionItemKind.Field,
6465
+ _c[k2.CompletionKind.BuiltInFunction] = ls.CompletionItemKind.Field,
6466
+ _c[k2.CompletionKind.Cluster] = ls.CompletionItemKind.Class,
6467
+ _c[k2.CompletionKind.Column] = ls.CompletionItemKind.Function,
6468
+ _c[k2.CompletionKind.CommandPrefix] = ls.CompletionItemKind.Field,
6469
+ _c[k2.CompletionKind.Database] = ls.CompletionItemKind.Class,
6470
+ _c[k2.CompletionKind.DatabaseFunction] = ls.CompletionItemKind.Field,
6471
+ _c[k2.CompletionKind.Example] = ls.CompletionItemKind.Text,
6472
+ _c[k2.CompletionKind.Identifier] = ls.CompletionItemKind.Method,
6473
+ _c[k2.CompletionKind.Keyword] = ls.CompletionItemKind.Method,
6474
+ _c[k2.CompletionKind.LocalFunction] = ls.CompletionItemKind.Field,
6475
+ _c[k2.CompletionKind.MaterialiedView] = ls.CompletionItemKind.Class,
6476
+ _c[k2.CompletionKind.Parameter] = ls.CompletionItemKind.Variable,
6477
+ _c[k2.CompletionKind.Punctuation] = ls.CompletionItemKind.Interface,
6478
+ _c[k2.CompletionKind.QueryPrefix] = ls.CompletionItemKind.Function,
6479
+ _c[k2.CompletionKind.RenderChart] = ls.CompletionItemKind.Method,
6480
+ _c[k2.CompletionKind.ScalarInfix] = ls.CompletionItemKind.Field,
6481
+ _c[k2.CompletionKind.ScalarPrefix] = ls.CompletionItemKind.Field,
6482
+ _c[k2.CompletionKind.ScalarType] = ls.CompletionItemKind.TypeParameter,
6483
+ _c[k2.CompletionKind.Syntax] = ls.CompletionItemKind.Method,
6484
+ _c[k2.CompletionKind.Table] = ls.CompletionItemKind.Class,
6485
+ _c[k2.CompletionKind.TabularPrefix] = ls.CompletionItemKind.Field,
6486
+ // datatable, externaldata
6487
+ _c[k2.CompletionKind.TabularSuffix] = ls.CompletionItemKind.Field,
6488
+ _c[k2.CompletionKind.Unknown] = ls.CompletionItemKind.Interface,
6489
+ _c[k2.CompletionKind.Variable] = ls.CompletionItemKind.Variable,
6490
+ _c[k2.CompletionKind.Option] = ls.CompletionItemKind.Text,
6491
+ _c);
6492
+ this._tokenKindToClassificationKind = (_d = {},
6493
+ _d[TokenKind.TableToken] = k2.ClassificationKind.Table,
6494
+ _d[TokenKind.TableColumnToken] = k2.ClassificationKind.Column,
6495
+ _d[TokenKind.OperatorToken] = k2.ClassificationKind.QueryOperator,
6496
+ _d[TokenKind.SubOperatorToken] = k2.ClassificationKind.Function,
6497
+ _d[TokenKind.CalculatedColumnToken] = k2.ClassificationKind.Column,
6498
+ _d[TokenKind.StringLiteralToken] = k2.ClassificationKind.Literal,
6499
+ _d[TokenKind.FunctionNameToken] = k2.ClassificationKind.Function,
6500
+ _d[TokenKind.UnknownToken] = k2.ClassificationKind.PlainText,
6501
+ _d[TokenKind.CommentToken] = k2.ClassificationKind.Comment,
6502
+ _d[TokenKind.PlainTextToken] = k2.ClassificationKind.PlainText,
6503
+ _d[TokenKind.DataTypeToken] = k2.ClassificationKind.Type,
6504
+ _d[TokenKind.ControlCommandToken] = k2.ClassificationKind.PlainText,
6505
+ _d[TokenKind.CommandPartToken] = k2.ClassificationKind.PlainText,
6506
+ _d[TokenKind.QueryParametersToken] = k2.ClassificationKind.QueryParameter,
6507
+ _d[TokenKind.CslCommandToken] = k2.ClassificationKind.Keyword,
6508
+ _d[TokenKind.LetVariablesToken] = k2.ClassificationKind.Identifier,
6509
+ _d[TokenKind.PluginToken] = k2.ClassificationKind.Function,
6510
+ _d[TokenKind.BracketRangeToken] = k2.ClassificationKind.Keyword,
6511
+ _d[TokenKind.ClientDirectiveToken] = k2.ClassificationKind.Keyword,
6512
+ _d);
6513
+ this._schemaCache = {};
6514
+ this._kustoJsSchema = KustoLanguageService.convertToKustoJsSchema(schema);
6515
+ this.__kustoJsSchemaV2 = this.convertToKustoJsSchemaV2(schema);
6516
+ this._schema = schema;
6517
+ this._clustersSetInGlobalState = new Set();
6518
+ this._nonEmptyDatabaseSetInGlobalState = new Set(); // used to remove clusters that are already in the global state
6519
+ this.configure(languageSettings);
6520
+ this._newlineAppendPipePolicy = new Kusto.Data.IntelliSense.ApplyPolicy();
6521
+ this._newlineAppendPipePolicy.Text = '\n| ';
6522
+ }
6523
+ KustoLanguageService.prototype.createDatabaseUniqueName = function (clusterName, databaseName) {
6524
+ return clusterName + "_" + databaseName;
6525
+ };
6526
+ Object.defineProperty(KustoLanguageService.prototype, "_kustoJsSchemaV2", {
6527
+ /**
6528
+ * A getter for __kustoJsSchemaV2
6529
+ */
6530
+ get: function () {
6531
+ return this.__kustoJsSchemaV2;
6532
+ },
6533
+ /**
6534
+ * A setter for _kustoJsSchemaV2. After a schema (global state) is set, create 2 sets of cluster and database names.
6535
+ */
6536
+ set: function (globalState) {
6537
+ this.__kustoJsSchemaV2 = globalState;
6538
+ this._clustersSetInGlobalState.clear();
6539
+ this._nonEmptyDatabaseSetInGlobalState.clear();
6540
+ // create 2 Sets with cluster names and database names based on the updated Global State.
6541
+ for (var i = 0; i < globalState.Clusters.Count; i++) {
6542
+ var clusterSymbol = this._kustoJsSchemaV2.Clusters.getItem(i);
6543
+ this._clustersSetInGlobalState.add(clusterSymbol.Name);
6544
+ for (var i2 = 0; i2 < clusterSymbol.Databases.Count; i2++) {
6545
+ var databaseSymbol = clusterSymbol.Databases.getItem(i2);
6546
+ if (databaseSymbol.Tables.Count > 0) { // only include database with tables
6547
+ this._nonEmptyDatabaseSetInGlobalState.add(this.createDatabaseUniqueName(clusterSymbol.Name, databaseSymbol.Name));
6548
+ }
6549
+ }
6550
+ }
6551
+ },
6552
+ enumerable: false,
6553
+ configurable: true
6554
+ });
6555
+ KustoLanguageService.prototype.configure = function (languageSettings) {
6556
+ this._languageSettings = languageSettings;
6557
+ // Since we're still reverting to V1 intellisense for control commands, we need to update the rules provider
6558
+ // (which is a notion of V1 intellisense).
6559
+ this.createRulesProvider(this._kustoJsSchema, this._schema.clusterType);
6560
+ };
6561
+ KustoLanguageService.prototype.doComplete = function (document, position) {
6562
+ return this.isIntellisenseV2() ? this.doCompleteV2(document, position) : this.doCompleteV1(document, position);
6563
+ };
6564
+ /**
6565
+ * important: Only use during development to test Global State.
6566
+ * Prints clusters, databases and tables that are currently in the GlobalState.
6567
+ */
6568
+ KustoLanguageService.prototype.debugGlobalState = function (globals) {
6569
+ // iterate over clusters
6570
+ console.log("globals.Clusters.Count: " + globals.Clusters.Count);
6571
+ for (var i = 0; i < globals.Clusters.Count; i++) {
6572
+ var cluster = globals.Clusters.getItem(i);
6573
+ console.log("cluster: " + cluster.Name);
6574
+ // iterate over databases
6575
+ console.log("cluster.Databases.Count: " + cluster.Databases.Count);
6576
+ for (var i2 = 0; i2 < cluster.Databases.Count; i2++) {
6577
+ var database = cluster.Databases.getItem(i2);
6578
+ console.log("cluster.database: [" + cluster.Name + "].[" + database.Name + "]");
6579
+ // iterate over tables
6580
+ console.log("cluster.Databases.Tables.Count: " + database.Tables.Count);
6581
+ for (var i3 = 0; i3 < database.Tables.Count; i3++) {
6582
+ var table = database.Tables.getItem(i3);
6583
+ console.log("cluster.database.table: [" + cluster.Name + "].[" + database.Name + "].[" + table.Name + "]");
6584
+ }
6585
+ }
6586
+ }
6587
+ };
6588
+ KustoLanguageService.prototype.doCompleteV2 = function (document, position) {
6589
+ var _this = this;
6590
+ if (!document) {
6591
+ return Promise.resolve(ls.CompletionList.create([]));
6592
+ }
6593
+ var script = this.parseDocumentV2(document);
6594
+ // print cluster/database/tables from CodeScript.Globals
6595
+ // this.debugGlobalState(script.Globals);
6596
+ // get current command
6597
+ var cursorOffset = document.offsetAt(position);
6598
+ var currentCommand = script.GetBlockAtPosition(cursorOffset);
6599
+ // get completion items
6600
+ var completionItems = currentCommand.Service.GetCompletionItems(cursorOffset);
6601
+ var disabledItems = this.disabledCompletionItemsV2;
6602
+ if (this._languageSettings.disabledCompletionItems) {
6603
+ this._languageSettings.disabledCompletionItems.map(function (item) {
6604
+ // logic will treat unknown as a '*' wildcard, meaning that if the key is in the object
6605
+ // the completion item will be suppressed.
6606
+ disabledItems[item] = k2.CompletionKind.Unknown;
6607
+ });
6608
+ }
6609
+ var items = this.toArray(completionItems.Items)
6610
+ .filter(function (item) {
6611
+ return !(item &&
6612
+ item.MatchText &&
6613
+ disabledItems[item.MatchText] !== undefined &&
6614
+ (disabledItems[item.MatchText] === k2.CompletionKind.Unknown ||
6615
+ disabledItems[item.MatchText] === item.Kind));
6616
+ })
6617
+ .map(function (kItem, i) {
6618
+ var v1CompletionOption = new k.CompletionOption(_this._toOptionKind[kItem.Kind] || k.OptionKind.None, kItem.DisplayText);
6619
+ var helpTopic = _this.getTopic(v1CompletionOption);
6620
+ // If we have AfterText it means that the cursor should no be placed at end of suggested text.
6621
+ // In that case we switch to snippet format and represent the point where the cursor should be as
6622
+ // as '\$0'
6623
+ var _a = kItem.AfterText && kItem.AfterText.length > 0
6624
+ ? {
6625
+ textToInsert: kItem.EditText + '$0' + kItem.AfterText,
6626
+ format: ls.InsertTextFormat.Snippet,
6627
+ }
6628
+ : {
6629
+ textToInsert: kItem.EditText,
6630
+ format: ls.InsertTextFormat.PlainText,
6631
+ }, textToInsert = _a.textToInsert, format = _a.format;
6632
+ var lsItem = ls.CompletionItem.create(kItem.DisplayText);
6633
+ var startPosition = document.positionAt(completionItems.EditStart);
6634
+ var endPosition = document.positionAt(completionItems.EditStart + completionItems.EditLength);
6635
+ lsItem.textEdit = ls.TextEdit.replace(ls.Range.create(startPosition, endPosition), textToInsert);
6636
+ lsItem.sortText = _this.getSortText(i + 1);
6637
+ lsItem.kind = _this.kustoKindToLsKindV2(kItem.Kind);
6638
+ lsItem.insertTextFormat = format;
6639
+ lsItem.detail = helpTopic ? helpTopic.ShortDescription : undefined;
6640
+ lsItem.documentation = helpTopic
6641
+ ? { value: helpTopic.LongDescription, kind: ls.MarkupKind.Markdown }
6642
+ : undefined;
6643
+ return lsItem;
6644
+ });
6645
+ return Promise.resolve(ls.CompletionList.create(items));
6646
+ };
6647
+ /**
6648
+ * when trying to get a topic we need the function name (abs, toLower, ETC).
6649
+ * The problem is that the 'Value' string also contains the arguments (e.g abs(number)), which means that we are
6650
+ * not able to correlate the option with its documentation.
6651
+ * This piece of code tries to strip this hwne getting topic.
6652
+ * @param completionOption the Completion option
6653
+ */
6654
+ KustoLanguageService.prototype.getTopic = function (completionOption) {
6655
+ if (completionOption.Kind == k.OptionKind.FunctionScalar ||
6656
+ completionOption.Kind == k.OptionKind.FunctionAggregation) {
6657
+ // from a value like 'abs(number)' remove the '(number)' so that only 'abs' will remain
6658
+ var indexOfParen = completionOption.Value.indexOf('(');
6659
+ if (indexOfParen >= 0) {
6660
+ completionOption = new k.CompletionOption(completionOption.Kind, completionOption.Value.substring(0, indexOfParen));
6661
+ }
6662
+ }
6663
+ return k.CslDocumentation.Instance.GetTopic(completionOption);
6664
+ };
6665
+ KustoLanguageService.prototype.doCompleteV1 = function (document, position) {
6666
+ var _this = this;
6667
+ // TODO: fix typing in CslCommandParser to allow rulesProvider to be query only.
6668
+ var caretAbsolutePosition = document.offsetAt(position);
6669
+ // find out what's the current command to only parse this one.
6670
+ this.parseDocumentV1(document, k.ParseMode.CommandTokensOnly);
6671
+ var currentCommand = this.getCurrentCommand(document, caretAbsolutePosition);
6672
+ var commandTextUntilCursor = '';
6673
+ if (currentCommand) {
6674
+ var commandStartOffset = currentCommand.AbsoluteStart;
6675
+ this.parseTextV1(currentCommand.Text, k.ParseMode.TokenizeAllText);
6676
+ var caretRelativePosition = caretAbsolutePosition - currentCommand.AbsoluteStart;
6677
+ commandTextUntilCursor = currentCommand.Text.substring(currentCommand.CslExpressionStartPosition, caretRelativePosition);
6678
+ }
6679
+ var commandTextWithoutLastWord = this.getCommandWithoutLastWord(commandTextUntilCursor);
6680
+ var context = this._rulesProvider.AnalyzeCommand$1(commandTextUntilCursor, currentCommand).Context;
6681
+ var result = { v: null };
6682
+ this._rulesProvider.TryMatchAnyRule(commandTextWithoutLastWord, result);
6683
+ var rule = result.v;
6684
+ if (rule) {
6685
+ var completionOptions = this.toArray(rule.GetCompletionOptions(context));
6686
+ // TODO once AppendPipePolicy becomes a public static member of ApplyPolicy in our c# code, and bridge.Net transplies this,
6687
+ // remove the 'as any' part..
6688
+ // Also = DefaultApplyPolicy is internal in c# code, so not exposed in d.ts, so we cast it to any.
6689
+ if (this._languageSettings.newlineAfterPipe &&
6690
+ rule.DefaultAfterApplyPolicy === Kusto.Data.IntelliSense.ApplyPolicy.AppendPipePolicy) {
6691
+ rule.DefaultAfterApplyPolicy = this._newlineAppendPipePolicy;
6692
+ }
6693
+ var options = completionOptions
6694
+ .filter(function (option) {
6695
+ return !(option && option.Value && _this.disabledCompletionItemsV1[option.Value] === option.Kind);
6696
+ })
6697
+ .map(function (option, ordinal) {
6698
+ var _a = _this.getTextToInsert(rule, option), insertText = _a.insertText, insertTextFormat = _a.insertTextFormat;
6699
+ var helpTopic = k.CslDocumentation.Instance.GetTopic(option);
6700
+ var item = ls.CompletionItem.create(option.Value);
6701
+ item.kind = _this.kustoKindToLsKind(option.Kind);
6702
+ item.insertText = insertText;
6703
+ item.insertTextFormat = insertTextFormat;
6704
+ item.sortText = _this.getSortText(ordinal + 1);
6705
+ item.detail = helpTopic ? helpTopic.ShortDescription : undefined;
6706
+ item.documentation = helpTopic
6707
+ ? { value: helpTopic.LongDescription, kind: ls.MarkupKind.Markdown }
6708
+ : undefined;
6709
+ return item;
6710
+ });
6711
+ return Promise.resolve(ls.CompletionList.create(options));
6712
+ }
6713
+ return Promise.resolve(ls.CompletionList.create([]));
6714
+ };
6715
+ KustoLanguageService.prototype.doRangeFormat = function (document, range) {
6716
+ if (!document) {
6717
+ return Promise.resolve([]);
6718
+ }
6719
+ var rangeStartOffset = document.offsetAt(range.start);
6720
+ var rangeEndOffset = document.offsetAt(range.end);
6721
+ var commands = this.getFormattedCommandsInDocumentV2(document, rangeStartOffset, rangeEndOffset);
6722
+ if (!commands.originalRange || commands.formattedCommands.length === 0) {
6723
+ return Promise.resolve([]);
6724
+ }
6725
+ return Promise.resolve([ls.TextEdit.replace(commands.originalRange, commands.formattedCommands.join(''))]);
6726
+ };
6727
+ KustoLanguageService.prototype.doDocumentFormat = function (document) {
6728
+ if (!document) {
6729
+ return Promise.resolve([]);
6730
+ }
6731
+ var startPos = document.positionAt(0);
6732
+ var endPos = document.positionAt(document.getText().length);
6733
+ var fullDocRange = ls.Range.create(startPos, endPos);
6734
+ var formattedDoc = this.getFormattedCommandsInDocumentV2(document).formattedCommands.join('');
6735
+ return Promise.resolve([ls.TextEdit.replace(fullDocRange, formattedDoc)]);
6736
+ };
6737
+ // Method is not triggered, instead doRangeFormat is invoked with the range of the caret's line.
6738
+ KustoLanguageService.prototype.doCurrentCommandFormat = function (document, caretPosition) {
6739
+ var offset = document.offsetAt(caretPosition);
6740
+ var range = this.createRange(document, offset - 1, offset + 1);
6741
+ return this.doRangeFormat(document, range);
6742
+ };
6743
+ KustoLanguageService.prototype.doFolding = function (document) {
6744
+ if (!document) {
6745
+ return Promise.resolve([]);
6746
+ }
6747
+ return this.getCommandsInDocument(document).then(function (commands) {
6748
+ return commands.map(function (command) {
6749
+ // don't count the last empty line as part of the folded range (consider linux, mac, pc newlines)
6750
+ if (command.text.endsWith('\r\n')) {
6751
+ command.absoluteEnd -= 2;
6752
+ }
6753
+ else if (command.text.endsWith('\r') || command.text.endsWith('\n')) {
6754
+ --command.absoluteEnd;
6755
+ }
6756
+ var startPosition = document.positionAt(command.absoluteStart);
6757
+ var endPosition = document.positionAt(command.absoluteEnd);
6758
+ return {
6759
+ startLine: startPosition.line,
6760
+ startCharacter: startPosition.character,
6761
+ endLine: endPosition.line,
6762
+ endCharacter: endPosition.character,
6763
+ };
6764
+ });
6765
+ });
6766
+ };
6767
+ KustoLanguageService.prototype.getClusterReferences = function (document, cursorOffset) {
6768
+ var _a;
6769
+ var script = this.parseDocumentV2(document);
6770
+ var currentBlock = this.getCurrentCommandV2(script, cursorOffset);
6771
+ var clusterReferences = (_a = currentBlock === null || currentBlock === void 0 ? void 0 : currentBlock.Service) === null || _a === void 0 ? void 0 : _a.GetClusterReferences();
6772
+ if (!clusterReferences) {
6773
+ return Promise.resolve([]);
6774
+ }
6775
+ var newClustersReferences = [];
6776
+ var newClustersReferencesSet = new Set(); // used to remove duplicates
6777
+ // Keep only unique clusters that aren't already exist in the Global State
6778
+ for (var i = 0; i < clusterReferences.Count; i++) {
6779
+ var clusterReference = clusterReferences.getItem(i);
6780
+ var clusterHostName = Kusto.Language.KustoFacts.GetHostName(clusterReference.Cluster);
6781
+ // ignore duplicates
6782
+ if (newClustersReferencesSet.has(clusterHostName)) {
6783
+ continue;
6784
+ }
6785
+ newClustersReferencesSet.add(clusterHostName);
6786
+ // ignore references that are already in the GlobalState.
6787
+ if (!this._clustersSetInGlobalState.has(clusterHostName)) {
6788
+ newClustersReferences.push({ clusterName: clusterHostName });
6789
+ }
6790
+ }
6791
+ return Promise.resolve(newClustersReferences);
6792
+ };
6793
+ KustoLanguageService.prototype.getDatabaseReferences = function (document, cursorOffset) {
6794
+ var _a;
6795
+ var script = this.parseDocumentV2(document);
6796
+ var currentBlock = this.getCurrentCommandV2(script, cursorOffset);
6797
+ var databasesReferences = (_a = currentBlock === null || currentBlock === void 0 ? void 0 : currentBlock.Service) === null || _a === void 0 ? void 0 : _a.GetDatabaseReferences();
6798
+ if (!databasesReferences) {
6799
+ return Promise.resolve([]);
6800
+ }
6801
+ var newDatabasesReferences = [];
6802
+ var newDatabasesReferencesSet = new Set();
6803
+ for (var i1 = 0; i1 < databasesReferences.Count; i1++) {
6804
+ var databaseReference = databasesReferences.getItem(i1);
6805
+ var clusterHostName = Kusto.Language.KustoFacts.GetHostName(databaseReference.Cluster);
6806
+ // ignore duplicates
6807
+ var databaseReferenceUniqueId = this.createDatabaseUniqueName(clusterHostName, databaseReference.Database);
6808
+ if (newDatabasesReferencesSet.has(databaseReferenceUniqueId)) {
6809
+ continue;
6810
+ }
6811
+ newDatabasesReferencesSet.add(databaseReferenceUniqueId);
6812
+ // ignore references that are already in the GlobalState.
6813
+ var foundInGlobalState = this._nonEmptyDatabaseSetInGlobalState.has(databaseReferenceUniqueId);
6814
+ if (!foundInGlobalState) {
6815
+ newDatabasesReferences.push({
6816
+ databaseName: databaseReference.Database,
6817
+ clusterName: databaseReference.Cluster
6818
+ });
6819
+ }
6820
+ }
6821
+ return Promise.resolve(newDatabasesReferences);
6822
+ };
6823
+ KustoLanguageService.prototype.doValidation = function (document, changeIntervals) {
6824
+ var _this = this;
6825
+ // didn't implement validation for v1.
6826
+ if (!document || !this.isIntellisenseV2()) {
6827
+ return Promise.resolve([]);
6828
+ }
6829
+ var script = this.parseDocumentV2(document);
6830
+ var blocks = this.toArray(script.Blocks);
6831
+ if (changeIntervals.length > 0) {
6832
+ blocks = this.getAffectedBlocks(blocks, changeIntervals);
6833
+ }
6834
+ var diagnostics = blocks
6835
+ .map(function (block) {
6836
+ var diagnostics = _this.toArray(block.Service.GetDiagnostics());
6837
+ if (diagnostics) {
6838
+ return diagnostics;
6839
+ }
6840
+ return [];
6841
+ })
6842
+ .reduce(function (prev, curr) { return prev.concat(curr); }, []);
6843
+ var lsDiagnostics = this.toLsDiagnostics(diagnostics, document);
6844
+ return Promise.resolve(lsDiagnostics);
6845
+ };
6846
+ KustoLanguageService.prototype.toLsDiagnostics = function (diagnostics, document) {
6847
+ return diagnostics
6848
+ .filter(function (diag) { return diag.HasLocation; })
6849
+ .map(function (diag) {
6850
+ var start = document.positionAt(diag.Start);
6851
+ var end = document.positionAt(diag.Start + diag.Length);
6852
+ var range = ls.Range.create(start, end);
6853
+ return ls.Diagnostic.create(range, diag.Message, ls.DiagnosticSeverity.Error);
6854
+ });
6855
+ };
6856
+ /**
6857
+ * Colorize one or more kusto blocks (a.k.a commands), or just the entire document.
6858
+ * Supports multi-cursor editing (colorizes blocks on multiple changes).
6859
+ * @param document The document to colorize
6860
+ * @param changeIntervals an array containing 0 or more changed intervals. if the array is empty - just colorize the entire row.
6861
+ * if the array contains a single change - just color the kusto blocks that wraps this change. If multiple changes are provided,
6862
+ * colorize all blocks that intersect these changes.
6863
+ * The code will try to only parse once if this is the same command.
6864
+ */
6865
+ KustoLanguageService.prototype.doColorization = function (document, changeIntervals) {
6866
+ var _this = this;
6867
+ if (!document || !this._languageSettings.useSemanticColorization) {
6868
+ return Promise.resolve([]);
6869
+ }
6870
+ // V1 intellisense
6871
+ if (!this.isIntellisenseV2()) {
6872
+ // Handle specific ranges changes (and not the whole doc)
6873
+ if (changeIntervals.length > 0) {
6874
+ this.parseDocumentV1(document, k.ParseMode.CommandTokensOnly);
6875
+ var affectedCommands = this.toArray(this._parser.Results).filter(function (command) {
6876
+ // a command is affected if it intersects at least on of changed ranges.
6877
+ return command // command can be null. we're filtering all nulls in the array.
6878
+ ? changeIntervals.some(function (_a) {
6879
+ var changeStart = _a.start, changeEnd = _a.end;
6880
+ // both intervals intersect if either the start or the end of interval A is inside interval B.
6881
+ // If we deleted something at the end of a command, the interval will not intersect the current command.
6882
+ // so we also want consider affected commands commands the end where the interval begins.
6883
+ // hence the + 1.
6884
+ return (command.AbsoluteStart >= changeStart && command.AbsoluteStart <= changeEnd) ||
6885
+ (changeStart >= command.AbsoluteStart && changeStart <= command.AbsoluteEnd + 1);
6886
+ })
6887
+ : false;
6888
+ });
6889
+ // We're not on any command so don't return any classifications.
6890
+ // this can happen if we're at the and of the file and deleting empty rows (for example).
6891
+ if (!affectedCommands || affectedCommands.length === 0) {
6892
+ return Promise.resolve([
6893
+ {
6894
+ classifications: [],
6895
+ absoluteStart: changeIntervals[0].start,
6896
+ absoluteEnd: changeIntervals[0].end,
6897
+ },
6898
+ ]);
6899
+ }
6900
+ var results = affectedCommands.map(function (command) {
6901
+ _this.parseTextV1(command.Text, k.ParseMode.TokenizeAllText);
6902
+ var k2Classifications = _this.getClassificationsFromParseResult(command.AbsoluteStart);
6903
+ var classifications = toClassifiedRange(k2Classifications);
6904
+ return {
6905
+ classifications: classifications,
6906
+ absoluteStart: command.AbsoluteStart,
6907
+ absoluteEnd: command.AbsoluteEnd,
6908
+ };
6909
+ });
6910
+ return Promise.resolve(results);
6911
+ }
6912
+ // Entire document requested
6913
+ this.parseDocumentV1(document, k.ParseMode.TokenizeAllText);
6914
+ var classifications_1 = this.getClassificationsFromParseResult();
6915
+ return Promise.resolve([
6916
+ {
6917
+ classifications: toClassifiedRange(classifications_1),
6918
+ absoluteStart: 0,
6919
+ absoluteEnd: document.getText().length,
6920
+ },
6921
+ ]);
6922
+ }
6923
+ // V2 intellisense
6924
+ var script = this.parseDocumentV2(document);
6925
+ if (changeIntervals.length > 0) {
6926
+ var blocks_1 = this.toArray(script.Blocks);
6927
+ var affectedBlocks = this.getAffectedBlocks(blocks_1, changeIntervals);
6928
+ var result = affectedBlocks.map(function (block) { return ({
6929
+ classifications: toClassifiedRange(_this.toArray(block.Service.GetClassifications(block.Start, block.End).Classifications)),
6930
+ absoluteStart: block.Start,
6931
+ absoluteEnd: block.End,
6932
+ }); });
6933
+ return Promise.resolve(result);
6934
+ }
6935
+ // Entire document requested
6936
+ var blocks = this.toArray(script.Blocks);
6937
+ var classifications = blocks
6938
+ .map(function (block) {
6939
+ return _this.toArray(block.Service.GetClassifications(block.Start, block.Length).Classifications);
6940
+ })
6941
+ .reduce(function (prev, curr) { return prev.concat(curr); }, []);
6942
+ return Promise.resolve([
6943
+ {
6944
+ classifications: toClassifiedRange(classifications),
6945
+ absoluteStart: 0,
6946
+ absoluteEnd: document.getText().length,
6947
+ },
6948
+ ]);
6949
+ };
6950
+ KustoLanguageService.prototype.getAffectedBlocks = function (blocks, changeIntervals) {
6951
+ return blocks.filter(function (block) {
6952
+ // a command is affected if it intersects at least on of changed ranges.
6953
+ return block // command can be null. we're filtering all nulls in the array.
6954
+ ? changeIntervals.some(function (_a) {
6955
+ var changeStart = _a.start, changeEnd = _a.end;
6956
+ // both intervals intersect if either the start or the end of interval A is inside interval B.
6957
+ return (block.Start >= changeStart && block.Start <= changeEnd) ||
6958
+ (changeStart >= block.Start && changeStart <= block.End + 1);
6959
+ })
6960
+ : false;
6961
+ });
6962
+ };
6963
+ KustoLanguageService.prototype.addClusterToSchema = function (document, clusterName, databaseNames) {
6964
+ var clusterNameOnly = Kusto.Language.KustoFacts.GetHostName(clusterName);
6965
+ var cluster = this._kustoJsSchemaV2.GetCluster$1(clusterNameOnly);
6966
+ if (cluster) {
6967
+ // add databases that are not already in the cluster.
6968
+ databaseNames
6969
+ .filter(function (databaseName) { return !cluster.GetDatabase(databaseName); })
6970
+ .map(function (databaseName) {
6971
+ var symbol = new sym.DatabaseSymbol.$ctor1(databaseName, undefined, false);
6972
+ cluster = cluster.AddDatabase(symbol);
6973
+ });
6974
+ }
6975
+ if (!cluster) {
6976
+ var databaseSymbols = databaseNames
6977
+ .map(function (databaseName) {
6978
+ var symbol = new sym.DatabaseSymbol.$ctor1(databaseName, undefined, false);
6979
+ return symbol;
6980
+ });
6981
+ var databaseSymbolsList = KustoLanguageService.toBridgeList(databaseSymbols);
6982
+ cluster = new sym.ClusterSymbol.$ctor1(clusterNameOnly, databaseSymbolsList, false);
6983
+ }
6984
+ this._kustoJsSchemaV2 = this._kustoJsSchemaV2.AddOrReplaceCluster(cluster);
6985
+ this._script = k2.CodeScript.From$1(document.getText(), this._kustoJsSchemaV2);
6986
+ return Promise.resolve();
6987
+ };
6988
+ KustoLanguageService.prototype.addDatabaseToSchema = function (document, clusterName, databaseSchema) {
6989
+ var clusterHostName = Kusto.Language.KustoFacts.GetHostName(clusterName);
6990
+ var cluster = this._kustoJsSchemaV2.GetCluster$1(clusterHostName);
6991
+ if (!cluster) {
6992
+ cluster = new sym.ClusterSymbol.$ctor1(clusterHostName, null, false);
6993
+ }
6994
+ var databaseSymbol = KustoLanguageService.convertToDatabaseSymbol(databaseSchema);
6995
+ cluster = cluster.AddOrUpdateDatabase(databaseSymbol);
6996
+ this._kustoJsSchemaV2 = this._kustoJsSchemaV2.AddOrReplaceCluster(cluster);
6997
+ this._script = k2.CodeScript.From$1(document.getText(), this._kustoJsSchemaV2);
6998
+ return Promise.resolve();
6999
+ };
7000
+ KustoLanguageService.prototype.setSchema = function (schema) {
7001
+ var _this = this;
7002
+ this._schema = schema;
7003
+ if (this._languageSettings.useIntellisenseV2) {
7004
+ var kustoJsSchemaV2 = schema && schema.clusterType === 'Engine' ? this.convertToKustoJsSchemaV2(schema) : null;
7005
+ this._kustoJsSchemaV2 = kustoJsSchemaV2;
7006
+ this._script = undefined;
7007
+ this._parsePropertiesV2 = undefined;
7008
+ }
7009
+ // since V2 doesn't support control commands, we're initializing V1 intellisense for both cases and we'll going to use V1 intellisense for contorl commands.
7010
+ return new Promise(function (resolve, reject) {
7011
+ var kustoJsSchema = schema ? KustoLanguageService.convertToKustoJsSchema(schema) : undefined;
7012
+ _this._kustoJsSchema = kustoJsSchema;
7013
+ _this.createRulesProvider(kustoJsSchema, schema.clusterType);
7014
+ resolve(undefined);
7015
+ });
7016
+ };
7017
+ KustoLanguageService.prototype.setParameters = function (parameters) {
7018
+ if (!this._languageSettings.useIntellisenseV2 || this._schema.clusterType !== 'Engine') {
7019
+ throw new Error('setParameters requires intellisense V2 and Engine cluster');
7020
+ }
7021
+ this._schema.globalParameters = parameters;
7022
+ var symbols = parameters.map(function (param) { return KustoLanguageService.createParameterSymbol(param); });
7023
+ this._kustoJsSchemaV2 = this._kustoJsSchemaV2.WithParameters(KustoLanguageService.toBridgeList(symbols));
7024
+ return Promise.resolve(undefined);
7025
+ };
7026
+ /**
7027
+ * A combination of normalizeSchema and setSchema
7028
+ * @param schema schema json as received from .show schema as json
7029
+ * @param clusterConnectionString cluster connection string
7030
+ * @param databaseInContextName name of database in context
7031
+ */
7032
+ KustoLanguageService.prototype.setSchemaFromShowSchema = function (schema, clusterConnectionString, databaseInContextName, globalParameters) {
7033
+ var _this = this;
7034
+ return this.normalizeSchema(schema, clusterConnectionString, databaseInContextName).then(function (normalized) {
7035
+ return _this.setSchema(__assign(__assign({}, normalized), { globalParameters: globalParameters }));
7036
+ });
7037
+ };
7038
+ /**
7039
+ * Converts the result of .show schema as json to a normalized schema used by kusto language service.
7040
+ * @param schema result of show schema
7041
+ * @param clusterConnectionString cluster connection string`
7042
+ * @param databaseInContextName database in context name
7043
+ */
7044
+ KustoLanguageService.prototype.normalizeSchema = function (schema, clusterConnectionString, databaseInContextName) {
7045
+ var databases = Object.keys(schema.Databases)
7046
+ .map(function (key) { return schema.Databases[key]; })
7047
+ .map(function (_a) {
7048
+ var Name = _a.Name, Tables = _a.Tables, ExternalTables = _a.ExternalTables, MaterializedViews = _a.MaterializedViews, Functions = _a.Functions, MinorVersion = _a.MinorVersion, MajorVersion = _a.MajorVersion;
7049
+ return ({
7050
+ name: Name,
7051
+ minorVersion: MinorVersion,
7052
+ majorVersion: MajorVersion,
7053
+ tables: [].concat.apply([], [[Tables, 'Table'], [MaterializedViews, 'MaterializedView'], [ExternalTables, 'ExternalTable']]
7054
+ .filter(function (_a) {
7055
+ var tableContainer = _a[0];
7056
+ return tableContainer;
7057
+ })
7058
+ .map(function (_a) {
7059
+ var tableContainer = _a[0], tableEntity = _a[1];
7060
+ return Object
7061
+ .values(tableContainer)
7062
+ .map(function (_a) {
7063
+ var Name = _a.Name, OrderedColumns = _a.OrderedColumns, DocString = _a.DocString;
7064
+ return ({
7065
+ name: Name,
7066
+ docstring: DocString,
7067
+ entityType: tableEntity,
7068
+ columns: OrderedColumns.map(function (_a) {
7069
+ var Name = _a.Name, Type = _a.Type, DocString = _a.DocString, CslType = _a.CslType;
7070
+ return ({
7071
+ name: Name,
7072
+ type: CslType,
7073
+ docstring: DocString,
7074
+ });
7075
+ }),
7076
+ });
7077
+ });
7078
+ })),
7079
+ functions: Object.keys(Functions)
7080
+ .map(function (key) { return Functions[key]; })
7081
+ .map(function (_a) {
7082
+ var Name = _a.Name, Body = _a.Body, DocString = _a.DocString, InputParameters = _a.InputParameters;
7083
+ return ({
7084
+ name: Name,
7085
+ body: Body,
7086
+ docstring: DocString,
7087
+ inputParameters: InputParameters.map(function (inputParam) { return ({
7088
+ name: inputParam.Name,
7089
+ type: inputParam.Type,
7090
+ cslType: inputParam.CslType,
7091
+ cslDefaultValue: inputParam.CslDefaultValue,
7092
+ columns: inputParam.Columns
7093
+ ? inputParam.Columns.map(function (col) { return ({
7094
+ name: col.Name,
7095
+ type: col.Type,
7096
+ cslType: col.CslType,
7097
+ }); })
7098
+ : inputParam.Columns,
7099
+ }); }),
7100
+ });
7101
+ }),
7102
+ });
7103
+ });
7104
+ var result = {
7105
+ clusterType: 'Engine',
7106
+ cluster: {
7107
+ connectionString: clusterConnectionString,
7108
+ databases: databases,
7109
+ },
7110
+ database: databases.filter(function (db) { return db.name === databaseInContextName; })[0],
7111
+ };
7112
+ return Promise.resolve(result);
7113
+ };
7114
+ KustoLanguageService.prototype.getSchema = function () {
7115
+ return Promise.resolve(this._schema);
7116
+ };
7117
+ KustoLanguageService.prototype.getCommandInContext = function (document, cursorOffset) {
7118
+ return this.isIntellisenseV2()
7119
+ ? this.getCommandInContextV2(document, cursorOffset)
7120
+ : this.getCommandInContextV1(document, cursorOffset);
7121
+ };
7122
+ KustoLanguageService.prototype.getCommandAndLocationInContext = function (document, cursorOffset) {
7123
+ // We are going to remove v1 intellisense. no use to keep parity.
7124
+ if (!document || !this.isIntellisenseV2()) {
7125
+ return Promise.resolve(null);
7126
+ }
7127
+ var script = this.parseDocumentV2(document);
7128
+ var block = this.getCurrentCommandV2(script, cursorOffset);
7129
+ if (!block) {
7130
+ return Promise.resolve(null);
7131
+ }
7132
+ var start = document.positionAt(block.Start);
7133
+ var end = document.positionAt(block.End);
7134
+ var location = ls.Location.create(document.uri, ls.Range.create(start, end));
7135
+ var text = block.Text;
7136
+ return Promise.resolve({
7137
+ text: text,
7138
+ location: location,
7139
+ });
7140
+ };
7141
+ KustoLanguageService.prototype.getCommandInContextV1 = function (document, cursorOffset) {
7142
+ this.parseDocumentV1(document, k.ParseMode.CommandTokensOnly);
7143
+ var command = this.getCurrentCommand(document, cursorOffset);
7144
+ if (!command) {
7145
+ return Promise.resolve(null);
7146
+ }
7147
+ return Promise.resolve(command.Text);
7148
+ };
7149
+ KustoLanguageService.prototype.getCommandInContextV2 = function (document, cursorOffset) {
7150
+ if (!document) {
7151
+ return Promise.resolve(null);
7152
+ }
7153
+ var script = this.parseDocumentV2(document);
7154
+ var block = this.getCurrentCommandV2(script, cursorOffset);
7155
+ if (!block) {
7156
+ return Promise.resolve(null);
7157
+ }
7158
+ // TODO: do we need to do tricks like V1 is doing in this.getCurrentCommand?
7159
+ return Promise.resolve(block.Text);
7160
+ };
7161
+ /**
7162
+ * Return an array of commands in document. each command contains the range and text.
7163
+ */
7164
+ KustoLanguageService.prototype.getCommandsInDocument = function (document) {
7165
+ if (!document) {
7166
+ return Promise.resolve([]);
7167
+ }
7168
+ return this.isIntellisenseV2()
7169
+ ? this.getCommandsInDocumentV2(document)
7170
+ : this.getCommandsInDocumentV1(document);
7171
+ };
7172
+ KustoLanguageService.prototype.getCommandsInDocumentV1 = function (document) {
7173
+ this.parseDocumentV1(document, k.ParseMode.CommandTokensOnly);
7174
+ var commands = this.toArray(this._parser.Results);
7175
+ return Promise.resolve(commands.map(function (_a) {
7176
+ var AbsoluteStart = _a.AbsoluteStart, AbsoluteEnd = _a.AbsoluteEnd, Text = _a.Text;
7177
+ return ({
7178
+ absoluteStart: AbsoluteStart,
7179
+ absoluteEnd: AbsoluteEnd,
7180
+ text: Text,
7181
+ });
7182
+ }));
7183
+ };
7184
+ KustoLanguageService.prototype.toPlacementStyle = function (formatterPlacementStyle) {
7185
+ if (!formatterPlacementStyle) {
7186
+ return undefined;
7187
+ }
7188
+ switch (formatterPlacementStyle) {
7189
+ case 'None':
7190
+ return k2.PlacementStyle.None;
7191
+ case 'NewLine':
7192
+ return k2.PlacementStyle.NewLine;
7193
+ case 'Smart':
7194
+ return k2.PlacementStyle.Smart;
7195
+ default:
7196
+ throw new Error('Unknown PlacementStyle');
7197
+ }
7198
+ };
7199
+ KustoLanguageService.prototype.getFormattedCommandsInDocumentV2 = function (document, rangeStart, rangeEnd) {
7200
+ var _this = this;
7201
+ var script = this.parseDocumentV2(document);
7202
+ var commands = this.toArray(script.Blocks).filter(function (command) {
7203
+ if (!command.Text || command.Text.trim() == '')
7204
+ return false;
7205
+ if (rangeStart == null || rangeEnd == null)
7206
+ return true;
7207
+ // calculate command end position without \r\n.
7208
+ var commandEnd = command.End;
7209
+ var commandText = command.Text;
7210
+ for (var i = commandText.length - 1; i >= 0; i--) {
7211
+ if (commandText[i] != '\r' && commandText[i] != '\n') {
7212
+ break;
7213
+ }
7214
+ else {
7215
+ commandEnd--;
7216
+ }
7217
+ }
7218
+ if (command.Start > rangeStart && command.Start < rangeEnd)
7219
+ return true;
7220
+ if (commandEnd > rangeStart && commandEnd < rangeEnd)
7221
+ return true;
7222
+ if (command.Start <= rangeStart && commandEnd >= rangeEnd)
7223
+ return true;
7224
+ });
7225
+ if (commands.length === 0) {
7226
+ return { formattedCommands: [] };
7227
+ }
7228
+ var formattedCommands = commands.map(function (command) {
7229
+ var _a, _b;
7230
+ var formatterOptions = _this._languageSettings.formatter;
7231
+ var formatter = Kusto.Language.Editor.FormattingOptions.Default.WithIndentationSize((_a = formatterOptions === null || formatterOptions === void 0 ? void 0 : formatterOptions.indentationSize) !== null && _a !== void 0 ? _a : 4)
7232
+ .WithInsertMissingTokens(false)
7233
+ .WithPipeOperatorStyle((_b = _this.toPlacementStyle(formatterOptions === null || formatterOptions === void 0 ? void 0 : formatterOptions.pipeOperatorStyle)) !== null && _b !== void 0 ? _b : k2.PlacementStyle.Smart)
7234
+ .WithSemicolonStyle(Kusto.Language.Editor.PlacementStyle.None)
7235
+ .WithBrackettingStyle(k2.BrackettingStyle.Diagonal);
7236
+ if (rangeStart == null || rangeEnd == null || (rangeStart === command.Start && rangeEnd === command.End)) {
7237
+ var result = command.Service.GetFormattedText(formatter);
7238
+ return result.Text;
7239
+ }
7240
+ return command.Service.GetFormattedText(formatter).Text;
7241
+ });
7242
+ var originalRange = this.createRange(document, commands[0].Start, commands[commands.length - 1].End);
7243
+ return { formattedCommands: formattedCommands, originalRange: originalRange };
7244
+ };
7245
+ KustoLanguageService.prototype.getCommandsInDocumentV2 = function (document) {
7246
+ var script = this.parseDocumentV2(document);
7247
+ var commands = this.toArray(script.Blocks).filter(function (command) { return command.Text.trim() != ''; });
7248
+ return Promise.resolve(commands.map(function (_a) {
7249
+ var Start = _a.Start, End = _a.End, Text = _a.Text;
7250
+ return ({ absoluteStart: Start, absoluteEnd: End, text: Text });
7251
+ }));
7252
+ };
7253
+ KustoLanguageService.prototype.getClientDirective = function (text) {
7254
+ var outParam = { v: null };
7255
+ var isClientDirective = k.CslCommandParser.IsClientDirective(text, outParam);
7256
+ return Promise.resolve({
7257
+ isClientDirective: isClientDirective,
7258
+ directiveWithoutLeadingComments: outParam.v,
7259
+ });
7260
+ };
7261
+ KustoLanguageService.prototype.getAdminCommand = function (text) {
7262
+ var outParam = { v: null };
7263
+ var isAdminCommand = k.CslCommandParser.IsAdminCommand$1(text, outParam);
7264
+ return Promise.resolve({
7265
+ isAdminCommand: isAdminCommand,
7266
+ adminCommandWithoutLeadingComments: outParam.v,
7267
+ });
7268
+ };
7269
+ KustoLanguageService.prototype.findDefinition = function (document, position) {
7270
+ if (!document || !this.isIntellisenseV2()) {
7271
+ return Promise.resolve([]);
7272
+ }
7273
+ var script = this.parseDocumentV2(document);
7274
+ var cursorOffset = document.offsetAt(position);
7275
+ var currentBlock = this.getCurrentCommandV2(script, cursorOffset);
7276
+ if (!currentBlock) {
7277
+ return Promise.resolve([]);
7278
+ }
7279
+ var relatedInfo = currentBlock.Service.GetRelatedElements(document.offsetAt(position));
7280
+ var relatedElements = this.toArray(relatedInfo.Elements);
7281
+ var definition = relatedElements[0];
7282
+ if (!definition) {
7283
+ return Promise.resolve([]);
7284
+ }
7285
+ var start = document.positionAt(definition.Start);
7286
+ var end = document.positionAt(definition.End);
7287
+ var range = ls.Range.create(start, end);
7288
+ var location = ls.Location.create(document.uri, range);
7289
+ return Promise.resolve([location]);
7290
+ };
7291
+ KustoLanguageService.prototype.findReferences = function (document, position) {
7292
+ if (!document || !this.isIntellisenseV2()) {
7293
+ return Promise.resolve([]);
7294
+ }
7295
+ var script = this.parseDocumentV2(document);
7296
+ var cursorOffset = document.offsetAt(position);
7297
+ var currentBlock = this.getCurrentCommandV2(script, cursorOffset);
7298
+ if (!currentBlock) {
7299
+ return Promise.resolve([]);
7300
+ }
7301
+ var relatedInfo = currentBlock.Service.GetRelatedElements(document.offsetAt(position));
7302
+ var relatedElements = this.toArray(relatedInfo.Elements);
7303
+ if (!relatedElements || relatedElements.length == 0) {
7304
+ return Promise.resolve([]);
7305
+ }
7306
+ var references = relatedElements.map(function (relatedElement) {
7307
+ var start = document.positionAt(relatedElement.Start);
7308
+ var end = document.positionAt(relatedElement.End);
7309
+ var range = ls.Range.create(start, end);
7310
+ var location = ls.Location.create(document.uri, range);
7311
+ return location;
7312
+ });
7313
+ return Promise.resolve(references);
7314
+ };
7315
+ KustoLanguageService.prototype.getQueryParams = function (document, cursorOffset) {
7316
+ if (!document || !this.isIntellisenseV2()) {
7317
+ return Promise.resolve([]);
7318
+ }
7319
+ var script = this.parseDocumentV2(document);
7320
+ var parsedAndAnalyzed = this.parseAndAnalyze(document, cursorOffset);
7321
+ var queryParamStatements = this.toArray(parsedAndAnalyzed.Syntax.GetDescendants(Kusto.Language.Syntax.QueryParametersStatement));
7322
+ if (!queryParamStatements || queryParamStatements.length == 0) {
7323
+ return Promise.resolve([]);
7324
+ }
7325
+ var queryParams = [];
7326
+ queryParamStatements.forEach(function (paramStatement) {
7327
+ paramStatement.WalkElements(function (el) {
7328
+ return el.ReferencedSymbol && el.ReferencedSymbol.Type
7329
+ ? queryParams.push({ name: el.ReferencedSymbol.Name, type: el.ReferencedSymbol.Type.Name })
7330
+ : undefined;
7331
+ });
7332
+ });
7333
+ return Promise.resolve(queryParams);
7334
+ };
7335
+ KustoLanguageService.prototype.getRenderInfo = function (document, cursorOffset) {
7336
+ var _this = this;
7337
+ var parsedAndAnalyzed = this.parseAndAnalyze(document, cursorOffset);
7338
+ if (!parsedAndAnalyzed) {
7339
+ return Promise.resolve(undefined);
7340
+ }
7341
+ var renderStatements = this.toArray(parsedAndAnalyzed.Syntax.GetDescendants(Kusto.Language.Syntax.RenderOperator));
7342
+ if (!renderStatements || renderStatements.length === 0) {
7343
+ return Promise.resolve(undefined);
7344
+ }
7345
+ // assuming a single render statement
7346
+ var renderStatement = renderStatements[0];
7347
+ // Start and end relative to block start.
7348
+ var startOffset = renderStatement.TextStart;
7349
+ var endOffset = renderStatement.End;
7350
+ var visualization = renderStatement.ChartType.ValueText;
7351
+ var withClause = renderStatement.WithClause;
7352
+ if (!withClause) {
7353
+ var info = {
7354
+ options: {
7355
+ visualization: visualization,
7356
+ },
7357
+ location: { startOffset: startOffset, endOffset: endOffset },
7358
+ };
7359
+ return Promise.resolve(info);
7360
+ }
7361
+ var properties = this.toArray(withClause.Properties);
7362
+ var props = properties.reduce(function (prev, property) {
7363
+ var name = property.Element$1.Name.SimpleName;
7364
+ switch (name) {
7365
+ case 'xcolumn':
7366
+ var value = property.Element$1.Expression.ReferencedSymbol.Name;
7367
+ prev[name] = value;
7368
+ break;
7369
+ case 'ycolumns':
7370
+ case 'anomalycolumns':
7371
+ var nameNodes = _this.toArray(property.Element$1.Expression.Names);
7372
+ var values = nameNodes.map(function (nameNode) { return nameNode.Element$1.SimpleName; });
7373
+ prev[name] = values;
7374
+ break;
7375
+ case 'ymin':
7376
+ case 'ymax':
7377
+ var numericVal = parseFloat(property.Element$1.Expression.ConstantValue);
7378
+ prev[name] = numericVal;
7379
+ break;
7380
+ case 'title':
7381
+ case 'xtitle':
7382
+ case 'ytitle':
7383
+ case 'visualization':
7384
+ case 'series':
7385
+ var strVal = property.Element$1.Expression.ConstantValue;
7386
+ prev[name] = strVal;
7387
+ break;
7388
+ case 'xaxis':
7389
+ case 'yaxis':
7390
+ var scale = property.Element$1.Expression.ConstantValue;
7391
+ prev[name] = scale;
7392
+ break;
7393
+ case 'legend':
7394
+ var legend = property.Element$1.Expression.ConstantValue;
7395
+ prev[name] = legend;
7396
+ break;
7397
+ case 'ySplit':
7398
+ var split = property.Element$1.Expression.ConstantValue;
7399
+ prev[name] = split;
7400
+ break;
7401
+ case 'accumulate':
7402
+ var accumulate = property.Element$1.Expression.ConstantValue;
7403
+ prev[name] = accumulate;
7404
+ break;
7405
+ case 'kind':
7406
+ var val = property.Element$1.Expression.ConstantValue;
7407
+ prev[name] = val;
7408
+ break;
7409
+ default:
7410
+ assertNever(name);
7411
+ }
7412
+ return prev;
7413
+ }, {});
7414
+ var renderOptions = __assign({ visualization: visualization }, props);
7415
+ var renderInfo = {
7416
+ options: renderOptions,
7417
+ location: { startOffset: startOffset, endOffset: endOffset },
7418
+ };
7419
+ return Promise.resolve(renderInfo);
7420
+ };
7421
+ KustoLanguageService.prototype.getReferencedGlobalParams = function (document, cursorOffset) {
7422
+ if (!document || !this.isIntellisenseV2()) {
7423
+ return Promise.resolve([]);
7424
+ }
7425
+ var script = this.parseDocumentV2(document);
7426
+ var currentBlock = this.getCurrentCommandV2(script, cursorOffset);
7427
+ if (!currentBlock) {
7428
+ return Promise.resolve([]);
7429
+ }
7430
+ var text = currentBlock.Text;
7431
+ var parsedAndAnalyzed = Kusto.Language.KustoCode.ParseAndAnalyze(text, this._kustoJsSchemaV2);
7432
+ // We take the ambient parameters
7433
+ var ambientParameters = this.toArray(this._kustoJsSchemaV2.Parameters);
7434
+ // We take all referenced symbols in the query
7435
+ var referencedSymbols = this.toArray(parsedAndAnalyzed.Syntax.GetDescendants(Kusto.Language.Syntax.Expression))
7436
+ .filter(function (expression) { return expression.ReferencedSymbol !== null; })
7437
+ .map(function (x) { return x.ReferencedSymbol; });
7438
+ // The Intersection between them is the ambient parameters that are used in the query.
7439
+ // Note: Ideally we would use Set here (or at least array.Include), but were' compiling down to es2015.
7440
+ var intersection = referencedSymbols.filter(function (referencedSymbol) {
7441
+ return ambientParameters.filter(function (ambientParameter) { return ambientParameter === referencedSymbol; }).length > 0;
7442
+ });
7443
+ var result = intersection.map(function (param) { return ({ name: param.Name, type: param.Type.Name }); });
7444
+ return Promise.resolve(result);
7445
+ };
7446
+ KustoLanguageService.prototype.getGlobalParams = function (document) {
7447
+ if (!this.isIntellisenseV2()) {
7448
+ return Promise.resolve([]);
7449
+ }
7450
+ var params = this.toArray(this._kustoJsSchemaV2.Parameters);
7451
+ var result = params.map(function (param) { return ({ name: param.Name, type: param.Type.Name }); });
7452
+ return Promise.resolve(result);
7453
+ };
7454
+ KustoLanguageService.prototype.doRename = function (document, position, newName) {
7455
+ var _a;
7456
+ if (!document || !this.isIntellisenseV2()) {
7457
+ return Promise.resolve(undefined);
7458
+ }
7459
+ var script = this.parseDocumentV2(document);
7460
+ var cursorOffset = document.offsetAt(position);
7461
+ var currentBLock = this.getCurrentCommandV2(script, cursorOffset);
7462
+ if (!currentBLock) {
7463
+ return Promise.resolve(undefined);
7464
+ }
7465
+ var relatedInfo = currentBLock.Service.GetRelatedElements(document.offsetAt(position));
7466
+ var relatedElements = this.toArray(relatedInfo.Elements);
7467
+ var declarations = relatedElements.filter(function (e) { return e.Kind == k2.RelatedElementKind.Declaration; });
7468
+ // A declaration must be one of the elements
7469
+ if (!declarations || declarations.length == 0) {
7470
+ return Promise.resolve(undefined);
7471
+ }
7472
+ var edits = relatedElements.map(function (edit) {
7473
+ var start = document.positionAt(edit.Start);
7474
+ var end = document.positionAt(edit.End);
7475
+ var range = ls.Range.create(start, end);
7476
+ return ls.TextEdit.replace(range, newName);
7477
+ });
7478
+ // create a workspace edit
7479
+ var workspaceEdit = { changes: (_a = {}, _a[document.uri] = edits, _a) };
7480
+ return Promise.resolve(workspaceEdit);
7481
+ };
7482
+ KustoLanguageService.prototype.doHover = function (document, position) {
7483
+ if (!document || !this.isIntellisenseV2()) {
7484
+ return Promise.resolve(undefined);
7485
+ }
7486
+ var script = this.parseDocumentV2(document);
7487
+ var cursorOffset = document.offsetAt(position);
7488
+ var currentBLock = this.getCurrentCommandV2(script, cursorOffset);
7489
+ if (!currentBLock) {
7490
+ return Promise.resolve(undefined);
7491
+ }
7492
+ var isSupported = currentBLock.Service.IsFeatureSupported(k2.CodeServiceFeatures.QuickInfo, cursorOffset);
7493
+ if (!isSupported) {
7494
+ return Promise.resolve(undefined);
7495
+ }
7496
+ var quickInfo = currentBLock.Service.GetQuickInfo(cursorOffset);
7497
+ if (!quickInfo || !quickInfo.Items) {
7498
+ return Promise.resolve(undefined);
7499
+ }
7500
+ var items = this.toArray(quickInfo.Items);
7501
+ if (!items) {
7502
+ return Promise.resolve(undefined);
7503
+ }
7504
+ // Errors are already shown in getDiagnostics. we don't want them in doHover.
7505
+ items = items.filter(function (item) { return item.Kind !== k2.QuickInfoKind.Error; });
7506
+ var itemsText = items.map(function (item) { return item.Text.replace('\n\n', '\n* * *\n'); });
7507
+ // separate items by horizontal line.
7508
+ var text = itemsText.join('\n* * *\n');
7509
+ // Instead of just an empty line between the first line (the signature) and the second line (the description)
7510
+ // add an horizontal line (* * * in markdown) between them.
7511
+ return Promise.resolve({ contents: text });
7512
+ };
7513
+ Object.defineProperty(KustoLanguageService, "dummySchema", {
7514
+ //#region dummy schema for manual testing
7515
+ get: function () {
7516
+ var database = {
7517
+ majorVersion: 0,
7518
+ minorVersion: 0,
7519
+ name: 'Kuskus',
7520
+ tables: [
7521
+ {
7522
+ name: 'KustoLogs',
7523
+ columns: [
7524
+ {
7525
+ name: 'Source',
7526
+ type: 'string',
7527
+ },
7528
+ {
7529
+ name: 'Timestamp',
7530
+ type: 'datetime',
7531
+ },
7532
+ {
7533
+ name: 'Directory',
7534
+ type: 'string',
7535
+ },
7536
+ ],
7537
+ docstring: 'A dummy description to test that docstring shows as expected when hovering over a table',
7538
+ },
7539
+ ],
7540
+ functions: [
7541
+ {
7542
+ name: 'HowBig',
7543
+ inputParameters: [
7544
+ {
7545
+ name: 'T',
7546
+ columns: [
7547
+ {
7548
+ name: 'Timestamp',
7549
+ type: 'System.DateTime',
7550
+ cslType: 'datetime',
7551
+ },
7552
+ ],
7553
+ },
7554
+ ],
7555
+ docstring: 'A dummy description to test that docstring shows as expected when hovering over a function',
7556
+ 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}",
7557
+ },
7558
+ {
7559
+ name: 'FindCIDPast24h',
7560
+ inputParameters: [
7561
+ {
7562
+ name: 'clientActivityId',
7563
+ type: 'System.String',
7564
+ cslType: 'string',
7565
+ },
7566
+ ],
7567
+ body: '{ KustoLogs | where Timestamp > now(-1d) | where ClientActivityId == clientActivityId} ',
7568
+ },
7569
+ ],
7570
+ };
7571
+ var languageServiceSchema = {
7572
+ clusterType: 'Engine',
7573
+ cluster: {
7574
+ connectionString: 'https://kuskus.kusto.windows.net;fed=true',
7575
+ databases: [database],
7576
+ },
7577
+ database: database,
7578
+ };
7579
+ return languageServiceSchema;
7580
+ },
7581
+ enumerable: false,
7582
+ configurable: true
7583
+ });
7584
+ //#endregion
7585
+ KustoLanguageService.convertToEntityDataType = function (kustoType) { };
7586
+ /**
7587
+ * We do not want to expose Bridge.Net generated schema, so we expose a cleaner javascript schema.
7588
+ * Here it gets converted to the bridge.Net schema
7589
+ * @param schema Language Service schema
7590
+ */
7591
+ KustoLanguageService.convertToKustoJsSchema = function (schema) {
7592
+ switch (schema.clusterType) {
7593
+ case 'Engine':
7594
+ var currentDatabaseName_1 = schema.database ? schema.database.name : undefined;
7595
+ var kCluster = new k.KustoIntelliSenseClusterEntity();
7596
+ var kDatabaseInContext_1 = undefined;
7597
+ kCluster.ConnectionString = schema.cluster.connectionString;
7598
+ var databases_1 = [];
7599
+ schema.cluster.databases.forEach(function (database) {
7600
+ var kDatabase = new k.KustoIntelliSenseDatabaseEntity();
7601
+ kDatabase.Name = database.name;
7602
+ var tables = [];
7603
+ database.tables.forEach(function (table) {
7604
+ var kTable = new k.KustoIntelliSenseTableEntity();
7605
+ kTable.Name = table.name;
7606
+ var cols = [];
7607
+ table.columns.forEach(function (column) {
7608
+ var kColumn = new k.KustoIntelliSenseColumnEntity();
7609
+ kColumn.Name = column.name;
7610
+ kColumn.TypeCode = k.EntityDataType[schema_1.getEntityDataTypeFromCslType(column.type)];
7611
+ cols.push(kColumn);
7612
+ });
7613
+ kTable.Columns = new Bridge.ArrayEnumerable(cols);
7614
+ tables.push(kTable);
7615
+ });
7616
+ var functions = [];
7617
+ database.functions.forEach(function (fn) {
7618
+ var kFunction = new k.KustoIntelliSenseFunctionEntity();
7619
+ (kFunction.Name = fn.name),
7620
+ (kFunction.CallName = s.getCallName(fn)),
7621
+ (kFunction.Expression = s.getExpression(fn)),
7622
+ functions.push(kFunction);
7623
+ });
7624
+ kDatabase.Tables = new Bridge.ArrayEnumerable(tables);
7625
+ kDatabase.Functions = new Bridge.ArrayEnumerable(functions);
7626
+ databases_1.push(kDatabase);
7627
+ if (database.name == currentDatabaseName_1) {
7628
+ kDatabaseInContext_1 = kDatabase;
7629
+ }
7630
+ });
7631
+ kCluster.Databases = new Bridge.ArrayEnumerable(databases_1);
7632
+ var kSchema = new k.KustoIntelliSenseQuerySchema(kCluster, kDatabaseInContext_1);
7633
+ return kSchema;
7634
+ case 'ClusterManager':
7635
+ var accounts = schema.accounts.map(function (account) {
7636
+ var kAccount = new k.KustoIntelliSenseAccountEntity();
7637
+ kAccount.Name = account;
7638
+ return kAccount;
7639
+ });
7640
+ var services = schema.services.map(function (service) {
7641
+ var kService = new k.KustoIntelliSenseServiceEntity();
7642
+ kService.Name = service;
7643
+ return kService;
7644
+ });
7645
+ var connectionString = schema.connectionString;
7646
+ var result = {
7647
+ accounts: accounts,
7648
+ services: services,
7649
+ connectionString: connectionString,
7650
+ };
7651
+ return result;
7652
+ case 'DataManagement':
7653
+ return undefined;
7654
+ default:
7655
+ return assertNever(schema);
7656
+ }
7657
+ };
7658
+ /**
7659
+ * Returns something like '(x: string, y: datetime)'
7660
+ * @param params scalar parameters
7661
+ */
7662
+ KustoLanguageService.scalarParametersToSignature = function (params) {
7663
+ var signatureWithoutParens = params.map(function (param) { return param.name + ": " + param.cslType; }).join(', ');
7664
+ return "(" + signatureWithoutParens + ")";
7665
+ };
7666
+ /**
7667
+ * Returns something like '(x: string, T: (y: int))'
7668
+ * @param params input parameters (tabular or scalar)
7669
+ */
7670
+ KustoLanguageService.inputParameterToSignature = function (params) {
7671
+ var _this = this;
7672
+ var signatureWithoutParens = params
7673
+ .map(function (param) {
7674
+ if (param.columns) {
7675
+ var tableSignature = _this.scalarParametersToSignature(param.columns);
7676
+ return param.name + ": " + tableSignature;
7677
+ }
7678
+ else {
7679
+ return param.name + ": " + param.cslType;
7680
+ }
7681
+ })
7682
+ .join(', ');
7683
+ return "(" + signatureWithoutParens + ")";
7684
+ };
7685
+ /**
7686
+ * converts a function definition to a let statement.
7687
+ * @param fn function
7688
+ */
7689
+ KustoLanguageService.toLetStatement = function (fn) {
7690
+ var signature = this.inputParameterToSignature(fn.inputParameters);
7691
+ return "let " + fn.name + " = " + signature + " " + fn.body;
7692
+ };
7693
+ KustoLanguageService.createColumnSymbol = function (col) {
7694
+ return new sym.ColumnSymbol(col.name, sym.ScalarTypes.GetSymbol(schema_1.getCslTypeNameFromClrType(col.type)), col.docstring);
7695
+ };
7696
+ KustoLanguageService.createParameterSymbol = function (param) {
7697
+ var paramSymbol = Kusto.Language.Symbols.ScalarTypes.GetSymbol(schema_1.getCslTypeNameFromClrType(param.type));
7698
+ return new sym.ParameterSymbol(param.name, paramSymbol, null);
7699
+ };
7700
+ KustoLanguageService.createParameter = function (param) {
7701
+ if (!param.columns) {
7702
+ var paramSymbol = Kusto.Language.Symbols.ScalarTypes.GetSymbol(schema_1.getCslTypeNameFromClrType(param.type));
7703
+ var expression = param.cslDefaultValue && typeof param.cslDefaultValue === 'string'
7704
+ ? parsing.QueryParser.ParseLiteral$1(param.cslDefaultValue)
7705
+ : undefined;
7706
+ return new sym.Parameter.$ctor3(param.name, paramSymbol, null, null, null, false, null, 1, 1, expression, null);
7707
+ }
7708
+ if (param.columns.length == 0) {
7709
+ return new sym.Parameter.ctor(param.name, sym.ParameterTypeKind.Tabular, sym.ArgumentKind.Expression, null, null, false, null, 1, 1, null, null);
7710
+ }
7711
+ var argumentType = new sym.TableSymbol.ctor(param.columns.map(function (col) { return KustoLanguageService.createColumnSymbol(col); }));
7712
+ return new sym.Parameter.$ctor2(param.name, argumentType);
7713
+ };
7714
+ KustoLanguageService.convertToDatabaseSymbol = function (db) {
7715
+ var createFunctionSymbol = function (fn) {
7716
+ var parameters = fn.inputParameters.map(function (param) {
7717
+ return KustoLanguageService.createParameter(param);
7718
+ });
7719
+ // TODO: handle outputColumns (right now it doesn't seem to be implemented for any function).
7720
+ return new sym.FunctionSymbol.$ctor16(fn.name, fn.body, KustoLanguageService.toBridgeList(parameters), fn.docstring);
7721
+ };
7722
+ var createTableSymbol = function (tbl) {
7723
+ var columnSymbols = tbl.columns.map(function (col) { return KustoLanguageService.createColumnSymbol(col); });
7724
+ var symbol = new sym.TableSymbol.$ctor3(tbl.name, columnSymbols);
7725
+ symbol.Description = tbl.docstring;
7726
+ switch (tbl.entityType) {
7727
+ case 'MaterializedViewTable':
7728
+ symbol = symbol.WithIsMaterializedView(true);
7729
+ break;
7730
+ case 'ExternalTable':
7731
+ symbol = symbol.WithIsExternal(true);
7732
+ break;
7733
+ default:
7734
+ }
7735
+ return symbol;
7736
+ };
7737
+ var createDatabaseSymbol = function (db) {
7738
+ var tableSymbols = db.tables ? db.tables.map(function (tbl) { return createTableSymbol(tbl); }) : [];
7739
+ var functionSymbols = db.functions ? db.functions.map(function (fun) { return createFunctionSymbol(fun); }) : [];
7740
+ return new sym.DatabaseSymbol.ctor(db.name, tableSymbols.concat(functionSymbols));
7741
+ };
7742
+ var databaseSymbol = createDatabaseSymbol(db);
7743
+ return databaseSymbol;
7744
+ };
7745
+ KustoLanguageService.prototype.convertToKustoJsSchemaV2 = function (schema) {
7746
+ var cached = this._schemaCache[schema.cluster.connectionString];
7747
+ // create a cache entry for the cluster if non yet exists.
7748
+ if (!cached) {
7749
+ this._schemaCache[schema.cluster.connectionString] = {};
7750
+ cached = this._schemaCache[schema.cluster.connectionString];
7751
+ }
7752
+ // Remove deleted databases from cache
7753
+ var schemaDbLookup = schema.cluster.databases.reduce(function (prev, curr) { return (prev[curr.name] = curr); }, {});
7754
+ Object.keys(cached).map(function (dbName) {
7755
+ if (!schemaDbLookup[dbName]) {
7756
+ delete cached.dbName;
7757
+ }
7758
+ });
7759
+ var globalState = GlobalState.Default;
7760
+ var currentDatabaseName = schema.database ? schema.database.name : undefined;
7761
+ var databaseInContext = undefined;
7762
+ // Update out-of-data databases to cache
7763
+ var databases = schema.cluster.databases.map(function (db) {
7764
+ var shouldIncludeFunctions = db.name === currentDatabaseName;
7765
+ var cachedDb = cached[db.name];
7766
+ // This is an older version than we have, or we need to parse functions.
7767
+ if (!cachedDb ||
7768
+ cachedDb.database.majorVersion < db.majorVersion ||
7769
+ (shouldIncludeFunctions && !cachedDb.includesFunctions)) {
7770
+ // only add functions for the database in context (it's very time consuming)
7771
+ var databaseSymbol_1 = KustoLanguageService.convertToDatabaseSymbol(db);
7772
+ cached[db.name] = { database: db, symbol: databaseSymbol_1, includesFunctions: shouldIncludeFunctions };
7773
+ }
7774
+ var databaseSymbol = cached[db.name].symbol;
7775
+ if (db.name === currentDatabaseName) {
7776
+ databaseInContext = databaseSymbol;
7777
+ }
7778
+ return databaseSymbol;
7779
+ });
7780
+ // Replace new URL due to polyfill issue in IE
7781
+ // const hostname = new URL(schema.cluster.connectionString.split(';')[0]).hostname;
7782
+ var hostname = schema.cluster.connectionString.match(/(.*\/\/)?([^\/;]*)/)[2];
7783
+ var clusterName = hostname.split('.')[0];
7784
+ var clusterSymbol = new sym.ClusterSymbol.ctor(clusterName, databases);
7785
+ globalState = globalState.WithCluster(clusterSymbol);
7786
+ if (databaseInContext) {
7787
+ globalState = globalState.WithDatabase(databaseInContext);
7788
+ }
7789
+ // Inject global parameters to global scope.
7790
+ if (schema.globalParameters) {
7791
+ var parameters = schema.globalParameters.map(function (param) {
7792
+ return KustoLanguageService.createParameterSymbol(param);
7793
+ });
7794
+ globalState = globalState.WithParameters(KustoLanguageService.toBridgeList(parameters));
7795
+ }
7796
+ return globalState;
7797
+ };
7798
+ KustoLanguageService.prototype.getClassificationsFromParseResult = function (offset) {
7799
+ var _this = this;
7800
+ if (offset === void 0) { offset = 0; }
7801
+ var classifications = this.toArray(this._parser.Results)
7802
+ .map(function (command) { return _this.toArray(command.Tokens); })
7803
+ .reduce(function (prev, curr) { return prev.concat(curr); }, [])
7804
+ .map(function (cslCommandToken) {
7805
+ var range = new k2.ClassifiedRange(_this.tokenKindToClassificationKind(cslCommandToken.TokenKind), cslCommandToken.AbsoluteStart + offset, cslCommandToken.Length);
7806
+ return range;
7807
+ });
7808
+ return classifications;
7809
+ };
7810
+ /**
7811
+ * trim trailing newlines from range
7812
+ */
7813
+ KustoLanguageService.trimTrailingNewlineFromRange = function (textInRange, rangeStartOffset, document, range) {
7814
+ var currentIndex = textInRange.length - 1;
7815
+ while (textInRange[currentIndex] === '\r' || textInRange[currentIndex] === '\n') {
7816
+ --currentIndex;
7817
+ }
7818
+ var newEndOffset = rangeStartOffset + currentIndex + 1;
7819
+ var newEndPosition = document.positionAt(newEndOffset);
7820
+ var newRange = ls.Range.create(range.start, newEndPosition);
7821
+ return newRange;
7822
+ };
7823
+ /**
7824
+ * Maps numbers to strings, such that if a>b numerically, f(a)>f(b) lexicographically.
7825
+ * 1 -> "a", 26 -> "z", 27 -> "za", 28 -> "zb", 52 -> "zz", 53 ->"zza"
7826
+ * @param order - The number to be converted to a sorting-string. order should start at 1.
7827
+ * @returns A string repenting the order.
7828
+ */
7829
+ KustoLanguageService.prototype.getSortText = function (order) {
7830
+ if (order <= 0) {
7831
+ throw new RangeError("order should be a number >= 1. instead got " + order);
7832
+ }
7833
+ var sortText = '';
7834
+ var numCharacters = 26; // "z" - "a" + 1;
7835
+ var div = Math.floor(order / numCharacters);
7836
+ for (var i = 0; i < div; ++i) {
7837
+ sortText += 'z';
7838
+ }
7839
+ var reminder = order % numCharacters;
7840
+ if (reminder > 0) {
7841
+ sortText += String.fromCharCode(96 + reminder);
7842
+ }
7843
+ return sortText;
7844
+ };
7845
+ /**
7846
+ * ParseTextV1 parses the given text with the given parse mode.
7847
+ * Additionally - it will make sure not to provide rules provider for non-engine clusters
7848
+ * since the only rules provider parse can handle is the engine's. It will try to look for function
7849
+ * definitions to colorize and will throw since they're not there.
7850
+ * @param text
7851
+ * @param parseMode
7852
+ */
7853
+ KustoLanguageService.prototype.parseTextV1 = function (text, parseMode) {
7854
+ this._parser.Parse(this._schema.clusterType === 'Engine' ? this._rulesProvider : null, text, parseMode);
7855
+ };
7856
+ KustoLanguageService.prototype.parseDocumentV1 = function (document, parseMode) {
7857
+ // already parsed a later version, or better parse mode for this uri
7858
+ if (this._parsePropertiesV1 &&
7859
+ !this._parsePropertiesV1.isParseNeeded(document, this._rulesProvider, parseMode)) {
7860
+ return;
7861
+ }
7862
+ this.parseTextV1(document.getText(), parseMode);
7863
+ this._parsePropertiesV1 = new ParseProperties(document.version, document.uri, this._rulesProvider, parseMode);
7864
+ };
7865
+ KustoLanguageService.prototype.parseDocumentV2 = function (document) {
7866
+ if (this._parsePropertiesV2 && !this._parsePropertiesV2.isParseNeeded(document, this._rulesProvider)) {
7867
+ return this._script;
7868
+ }
7869
+ if (!this._script) {
7870
+ this._script = k2.CodeScript.From$1(document.getText(), this._kustoJsSchemaV2);
7871
+ }
7872
+ else {
7873
+ this._script = this._script.WithText(document.getText());
7874
+ }
7875
+ this._parsePropertiesV2 = new ParseProperties(document.version, document.uri);
7876
+ return this._script;
7877
+ };
7878
+ /**
7879
+ * Return the CslCommand that wraps the caret location, or undefined if caret is outside any command
7880
+ * @param document the document to extract the current command from
7881
+ * @param caretAbsolutePosition absolute caret position
7882
+ */
7883
+ KustoLanguageService.prototype.getCurrentCommand = function (document, caretAbsolutePosition) {
7884
+ var commands = this.toArray(this._parser.Results);
7885
+ var command = commands.filter(function (command) { return command.AbsoluteStart <= caretAbsolutePosition && command.AbsoluteEnd >= caretAbsolutePosition; })[0];
7886
+ // There is an edge case when cursor appears at the end of the command
7887
+ // which is not yet considered to be part of the parsed command (therefore: +1 for the AbsoluteEdit property)
7888
+ if (!command) {
7889
+ command = commands.filter(function (command) {
7890
+ return command.AbsoluteStart <= caretAbsolutePosition && command.AbsoluteEnd + 1 >= caretAbsolutePosition;
7891
+ })[0];
7892
+ // If we have 2 newlines in the end of the text the cursor is _probably_ at the end of the text
7893
+ // which this means that we're not actually standing on any command. Thus return null.
7894
+ if (!command || command.Text.endsWith('\r\n\r\n')) {
7895
+ return null;
7896
+ }
7897
+ }
7898
+ return command;
7899
+ };
7900
+ KustoLanguageService.prototype.getCurrentCommandV2 = function (script, offset) {
7901
+ var block = script.GetBlockAtPosition(offset);
7902
+ return block;
7903
+ };
7904
+ KustoLanguageService.prototype.getTextToInsert = function (rule, option) {
7905
+ var beforeApplyInfo = rule.GetBeforeApplyInfo(option.Value);
7906
+ var afterApplyInfo = rule.GetAfterApplyInfo(option.Value);
7907
+ // this is the basic text to be inserted,
7908
+ // but we still need to figure out where the cursor will end up after completion is applied.
7909
+ var insertText = beforeApplyInfo.Text || '' + option.Value + afterApplyInfo.Text || '';
7910
+ var insertTextFormat = ls.InsertTextFormat.PlainText;
7911
+ var snippetFinalTabStop = '$0';
7912
+ if (afterApplyInfo.OffsetToken && afterApplyInfo.OffsetPosition) {
7913
+ var tokenOffset = insertText.indexOf(afterApplyInfo.OffsetToken);
7914
+ if (tokenOffset >= 0) {
7915
+ insertText = this.insertToString(insertText, snippetFinalTabStop, tokenOffset - insertText.length + afterApplyInfo.OffsetPosition);
7916
+ insertTextFormat = ls.InsertTextFormat.Snippet;
7917
+ }
7918
+ }
7919
+ else if (afterApplyInfo.OffsetPosition) {
7920
+ // We only handle negative offsets
7921
+ insertText = this.insertToString(insertText, snippetFinalTabStop, afterApplyInfo.OffsetPosition);
7922
+ insertTextFormat = ls.InsertTextFormat.Snippet;
7923
+ }
7924
+ return { insertText: insertText, insertTextFormat: insertTextFormat };
7925
+ };
7926
+ /**
7927
+ * create a new string with stringToInsert inserted at offsetFromEnd in originalString.
7928
+ * @param originalString string to insert to
7929
+ * @param stringToInsert string to insert
7930
+ * @param offsetFromEnd a negative number that will represent offset to the left. 0 means simple concat
7931
+ */
7932
+ KustoLanguageService.prototype.insertToString = function (originalString, stringToInsert, offsetFromEnd) {
7933
+ var index = originalString.length + offsetFromEnd;
7934
+ if (offsetFromEnd >= 0 || index < 0) {
7935
+ return originalString; // Cannot insert before or after the string
7936
+ }
7937
+ var before = originalString.substring(0, index);
7938
+ var after = originalString.substring(index);
7939
+ return before + stringToInsert + after;
7940
+ };
7941
+ KustoLanguageService.prototype.getCommandWithoutLastWord = function (text) {
7942
+ var lastWordRegex = XRegExp('[\\w_]*$', 's');
7943
+ return text.replace(lastWordRegex, '');
7944
+ };
7945
+ KustoLanguageService.prototype.createRulesProvider = function (schema, clusterType) {
7946
+ var queryParameters = new (List(String))();
7947
+ var availableClusters = new (List(String))();
7948
+ this._parser = new k.CslCommandParser();
7949
+ if (clusterType == 'Engine') {
7950
+ var engineSchema = schema;
7951
+ this._rulesProvider =
7952
+ this._languageSettings && this._languageSettings.includeControlCommands
7953
+ ? new k.CslIntelliSenseRulesProvider.$ctor1(engineSchema.Cluster, engineSchema, queryParameters, availableClusters, null, true, true)
7954
+ : new k.CslQueryIntelliSenseRulesProvider.$ctor1(engineSchema.Cluster, engineSchema, queryParameters, availableClusters, null, null, null);
7955
+ return;
7956
+ }
7957
+ if (clusterType === 'DataManagement') {
7958
+ this._rulesProvider = new k.DataManagerIntelliSenseRulesProvider(null);
7959
+ return;
7960
+ }
7961
+ // This is a cluster manger
7962
+ var _a = schema, accounts = _a.accounts, services = _a.services, connectionString = _a.connectionString;
7963
+ new k.KustoIntelliSenseAccountEntity();
7964
+ new k.KustoIntelliSenseServiceEntity();
7965
+ this._rulesProvider = new k.ClusterManagerIntelliSenseRulesProvider.$ctor1(new Bridge.ArrayEnumerable(accounts), new Bridge.ArrayEnumerable(services), connectionString);
7966
+ };
7967
+ KustoLanguageService.prototype.kustoKindToLsKind = function (kustoKind) {
7968
+ var res = this._kustoKindtolsKind[kustoKind];
7969
+ return res ? res : ls.CompletionItemKind.Variable;
7970
+ };
7971
+ KustoLanguageService.prototype.kustoKindToLsKindV2 = function (kustoKind) {
7972
+ var res = this._kustoKindToLsKindV2[kustoKind];
7973
+ return res ? res : ls.CompletionItemKind.Variable;
7974
+ };
7975
+ KustoLanguageService.prototype.createRange = function (document, start, end) {
7976
+ return ls.Range.create(document.positionAt(start), document.positionAt(end));
7977
+ };
7978
+ KustoLanguageService.prototype.toArray = function (bridgeList) {
7979
+ return Bridge.toArray(bridgeList);
7980
+ };
7981
+ KustoLanguageService.toBridgeList = function (array) {
7982
+ // copied from bridge.js from the implementation of Enumerable.prototype.toList
7983
+ return new (System.Collections.Generic.List$1(System.Object).$ctor1)(array);
7984
+ };
7985
+ KustoLanguageService.prototype.tokenKindToClassificationKind = function (token) {
7986
+ var conversion = this._tokenKindToClassificationKind[token];
7987
+ return conversion || k2.ClassificationKind.PlainText;
7988
+ };
7989
+ KustoLanguageService.prototype.parseAndAnalyze = function (document, cursorOffset) {
7990
+ if (!document || !this.isIntellisenseV2()) {
7991
+ return undefined;
7992
+ }
7993
+ var script = this.parseDocumentV2(document);
7994
+ var currentBlock = this.getCurrentCommandV2(script, cursorOffset);
7995
+ if (!currentBlock) {
7996
+ return undefined;
7997
+ }
7998
+ var text = currentBlock.Text;
7999
+ var parsedAndAnalyzed = Kusto.Language.KustoCode.ParseAndAnalyze(text, this._kustoJsSchemaV2);
8000
+ return parsedAndAnalyzed;
8001
+ };
8002
+ return KustoLanguageService;
8003
+ }());
8004
+ var languageService = new KustoLanguageService(KustoLanguageService.dummySchema, {
8005
+ includeControlCommands: true,
8006
+ useIntellisenseV2: true,
8007
+ useSemanticColorization: true,
8008
+ });
8009
+ /**
8010
+ * Obtain an instance of the kusto language service.
8011
+ */
8012
+ function getKustoLanguageService() {
8013
+ return languageService;
8014
+ }
8015
+ exports.getKustoLanguageService = getKustoLanguageService;
8016
+ });
7853
8017
 
7854
- define('vs/language/kusto/kustoWorker',["require", "exports", "./languageService/kustoLanguageService", "vscode-languageserver-types"], function (require, exports, kustoService, ls) {
7855
- "use strict";
7856
- Object.defineProperty(exports, "__esModule", { value: true });
7857
- exports.create = exports.KustoWorker = void 0;
7858
- var KustoWorker = /** @class */ (function () {
7859
- function KustoWorker(ctx, createData) {
7860
- this._ctx = ctx;
7861
- this._languageSettings = createData.languageSettings;
7862
- this._languageService = kustoService.getKustoLanguageService();
7863
- this._languageService.configure(this._languageSettings);
7864
- }
7865
- // --- language service host ---------------
7866
- KustoWorker.prototype.setSchema = function (schema) {
7867
- return this._languageService.setSchema(schema);
7868
- };
7869
- KustoWorker.prototype.setSchemaFromShowSchema = function (schema, clusterConnectionString, databaseInContextName) {
7870
- return this._languageService.setSchemaFromShowSchema(schema, clusterConnectionString, databaseInContextName);
7871
- };
7872
- KustoWorker.prototype.normalizeSchema = function (schema, clusterConnectionString, databaseInContextName) {
7873
- return this._languageService.normalizeSchema(schema, clusterConnectionString, databaseInContextName);
7874
- };
7875
- KustoWorker.prototype.getSchema = function () {
7876
- return this._languageService.getSchema();
7877
- };
7878
- KustoWorker.prototype.getCommandInContext = function (uri, cursorOffset) {
7879
- var document = this._getTextDocument(uri);
7880
- if (!document) {
7881
- console.error("getCommandInContext: document is " + document + ". uri is " + uri);
7882
- return null;
7883
- }
7884
- var commandInContext = this._languageService.getCommandInContext(document, cursorOffset);
7885
- if (commandInContext === undefined) {
7886
- return null;
7887
- }
7888
- return commandInContext;
7889
- };
7890
- KustoWorker.prototype.getQueryParams = function (uri, cursorOffset) {
7891
- var document = this._getTextDocument(uri);
7892
- if (!document) {
7893
- console.error("getQueryParams: document is " + document + ". uri is " + uri);
7894
- return null;
7895
- }
7896
- var queryParams = this._languageService.getQueryParams(document, cursorOffset);
7897
- if (queryParams === undefined) {
7898
- return null;
7899
- }
7900
- return queryParams;
7901
- };
7902
- KustoWorker.prototype.getGlobalParams = function (uri) {
7903
- var document = this._getTextDocument(uri);
7904
- if (!document) {
7905
- console.error("getGLobalParams: document is " + document + ". uri is " + uri);
7906
- return null;
7907
- }
7908
- var globalParams = this._languageService.getGlobalParams(document);
7909
- if (globalParams === undefined) {
7910
- return null;
7911
- }
7912
- return globalParams;
7913
- };
7914
- KustoWorker.prototype.getReferencedGlobalParams = function (uri, cursorOffest) {
7915
- var document = this._getTextDocument(uri);
7916
- if (!document) {
7917
- console.error("getReferencedGlobalParams: document is " + document + ". uri is " + uri);
7918
- return null;
7919
- }
7920
- var referencedParams = this._languageService.getReferencedGlobalParams(document, cursorOffest);
7921
- if (referencedParams === undefined) {
7922
- return null;
7923
- }
7924
- return referencedParams;
7925
- };
7926
- KustoWorker.prototype.getRenderInfo = function (uri, cursorOffset) {
7927
- var document = this._getTextDocument(uri);
7928
- if (!document) {
7929
- console.error("getRenderInfo: document is " + document + ". uri is " + uri);
7930
- }
7931
- return this._languageService.getRenderInfo(document, cursorOffset).then(function (result) {
7932
- if (!result) {
7933
- return null;
7934
- }
7935
- return result;
7936
- });
7937
- };
7938
- /**
7939
- * Get command in context and the command range.
7940
- * This method will basically convert generate microsoft language service interface to monaco interface.
7941
- * @param uri document URI
7942
- * @param cursorOffset offset from start of document to cursor
7943
- */
7944
- KustoWorker.prototype.getCommandAndLocationInContext = function (uri, cursorOffset) {
7945
- var document = this._getTextDocument(uri);
7946
- if (!document) {
7947
- console.error("getCommandAndLocationInContext: document is " + document + ". uri is " + uri);
7948
- return Promise.resolve(null);
7949
- }
7950
- return this._languageService.getCommandAndLocationInContext(document, cursorOffset).then(function (result) {
7951
- if (!result) {
7952
- return null;
7953
- }
7954
- // convert to monaco object.
7955
- var text = result.text, _a = result.location.range, start = _a.start, end = _a.end;
7956
- var range = new monaco.Range(start.line + 1, start.character + 1, end.line + 1, end.character + 1);
7957
- return {
7958
- range: range,
7959
- text: text,
7960
- };
7961
- });
7962
- };
7963
- KustoWorker.prototype.getCommandsInDocument = function (uri) {
7964
- var document = this._getTextDocument(uri);
7965
- if (!document) {
7966
- console.error("getCommandInDocument: document is " + document + ". uri is " + uri);
7967
- return null;
7968
- }
7969
- return this._languageService.getCommandsInDocument(document);
7970
- };
7971
- KustoWorker.prototype.doComplete = function (uri, position) {
7972
- var document = this._getTextDocument(uri);
7973
- if (!document) {
7974
- return null;
7975
- }
7976
- var completions = this._languageService.doComplete(document, position);
7977
- return completions;
7978
- };
7979
- KustoWorker.prototype.doValidation = function (uri, intervals) {
7980
- var document = this._getTextDocument(uri);
7981
- var diagnostics = this._languageService.doValidation(document, intervals);
7982
- return diagnostics;
7983
- };
7984
- KustoWorker.prototype.doRangeFormat = function (uri, range) {
7985
- var document = this._getTextDocument(uri);
7986
- var formatted = this._languageService.doRangeFormat(document, range);
7987
- return formatted;
7988
- };
7989
- KustoWorker.prototype.doFolding = function (uri) {
7990
- var document = this._getTextDocument(uri);
7991
- var folding = this._languageService.doFolding(document);
7992
- return folding;
7993
- };
7994
- KustoWorker.prototype.doDocumentFormat = function (uri) {
7995
- var document = this._getTextDocument(uri);
7996
- var formatted = this._languageService.doDocumentFormat(document);
7997
- return formatted;
7998
- };
7999
- KustoWorker.prototype.doCurrentCommandFormat = function (uri, caretPosition) {
8000
- var document = this._getTextDocument(uri);
8001
- var formatted = this._languageService.doCurrentCommandFormat(document, caretPosition);
8002
- return formatted;
8003
- };
8004
- // Colorize document. if offsets provided, will only colorize commands at these offsets. otherwise - will color the entire document.
8005
- KustoWorker.prototype.doColorization = function (uri, colorizationIntervals) {
8006
- var document = this._getTextDocument(uri);
8007
- var colorizationInfo = this._languageService.doColorization(document, colorizationIntervals);
8008
- return colorizationInfo;
8009
- };
8010
- KustoWorker.prototype.getClientDirective = function (text) {
8011
- return this._languageService.getClientDirective(text);
8012
- };
8013
- KustoWorker.prototype.getAdminCommand = function (text) {
8014
- return this._languageService.getAdminCommand(text);
8015
- };
8016
- KustoWorker.prototype.findDefinition = function (uri, position) {
8017
- var document = this._getTextDocument(uri);
8018
- var definition = this._languageService.findDefinition(document, position);
8019
- return definition;
8020
- };
8021
- KustoWorker.prototype.findReferences = function (uri, position) {
8022
- var document = this._getTextDocument(uri);
8023
- var references = this._languageService.findReferences(document, position);
8024
- return references;
8025
- };
8026
- KustoWorker.prototype.doRename = function (uri, position, newName) {
8027
- var document = this._getTextDocument(uri);
8028
- var workspaceEdit = this._languageService.doRename(document, position, newName);
8029
- return workspaceEdit;
8030
- };
8031
- KustoWorker.prototype.doHover = function (uri, position) {
8032
- var document = this._getTextDocument(uri);
8033
- var hover = this._languageService.doHover(document, position);
8034
- return hover;
8035
- };
8036
- KustoWorker.prototype.setParameters = function (parameters) {
8037
- return this._languageService.setParameters(parameters);
8038
- };
8039
- KustoWorker.prototype._getTextDocument = function (uri) {
8040
- var models = this._ctx.getMirrorModels();
8041
- for (var _i = 0, models_1 = models; _i < models_1.length; _i++) {
8042
- var model = models_1[_i];
8043
- if (model.uri.toString() === uri) {
8044
- return ls.TextDocument.create(uri, this._languageId, model.version, model.getValue());
8045
- }
8046
- }
8047
- return null;
8048
- };
8049
- return KustoWorker;
8050
- }());
8051
- exports.KustoWorker = KustoWorker;
8052
- function create(ctx, createData) {
8053
- return new KustoWorker(ctx, createData);
8054
- }
8055
- exports.create = create;
8056
- });
8018
+ define('vs/language/kusto/kustoWorker',["require", "exports", "./languageService/kustoLanguageService", "vscode-languageserver-types"], function (require, exports, kustoService, ls) {
8019
+ "use strict";
8020
+ Object.defineProperty(exports, "__esModule", { value: true });
8021
+ exports.create = exports.KustoWorker = void 0;
8022
+ var KustoWorker = /** @class */ (function () {
8023
+ function KustoWorker(ctx, createData) {
8024
+ this._ctx = ctx;
8025
+ this._languageSettings = createData.languageSettings;
8026
+ this._languageService = kustoService.getKustoLanguageService();
8027
+ this._languageService.configure(this._languageSettings);
8028
+ }
8029
+ // --- language service host ---------------
8030
+ KustoWorker.prototype.setSchema = function (schema) {
8031
+ return this._languageService.setSchema(schema);
8032
+ };
8033
+ KustoWorker.prototype.addClusterToSchema = function (uri, clusterName, databasesNames) {
8034
+ var document = this._getTextDocument(uri);
8035
+ if (!document) {
8036
+ console.error("addClusterToSchema: document is " + document + ". uri is " + uri);
8037
+ return null;
8038
+ }
8039
+ return this._languageService.addClusterToSchema(document, clusterName, databasesNames);
8040
+ };
8041
+ KustoWorker.prototype.addDatabaseToSchema = function (uri, clusterName, databaseSchema) {
8042
+ var document = this._getTextDocument(uri);
8043
+ if (!document) {
8044
+ console.error("addDatabaseToSchema: document is " + document + ". uri is " + uri);
8045
+ return null;
8046
+ }
8047
+ return this._languageService.addDatabaseToSchema(document, clusterName, databaseSchema);
8048
+ };
8049
+ KustoWorker.prototype.setSchemaFromShowSchema = function (schema, clusterConnectionString, databaseInContextName) {
8050
+ return this._languageService.setSchemaFromShowSchema(schema, clusterConnectionString, databaseInContextName);
8051
+ };
8052
+ KustoWorker.prototype.normalizeSchema = function (schema, clusterConnectionString, databaseInContextName) {
8053
+ return this._languageService.normalizeSchema(schema, clusterConnectionString, databaseInContextName);
8054
+ };
8055
+ KustoWorker.prototype.getSchema = function () {
8056
+ return this._languageService.getSchema();
8057
+ };
8058
+ KustoWorker.prototype.getCommandInContext = function (uri, cursorOffset) {
8059
+ var document = this._getTextDocument(uri);
8060
+ if (!document) {
8061
+ console.error("getCommandInContext: document is " + document + ". uri is " + uri);
8062
+ return null;
8063
+ }
8064
+ var commandInContext = this._languageService.getCommandInContext(document, cursorOffset);
8065
+ if (commandInContext === undefined) {
8066
+ return null;
8067
+ }
8068
+ return commandInContext;
8069
+ };
8070
+ KustoWorker.prototype.getQueryParams = function (uri, cursorOffset) {
8071
+ var document = this._getTextDocument(uri);
8072
+ if (!document) {
8073
+ console.error("getQueryParams: document is " + document + ". uri is " + uri);
8074
+ return null;
8075
+ }
8076
+ var queryParams = this._languageService.getQueryParams(document, cursorOffset);
8077
+ if (queryParams === undefined) {
8078
+ return null;
8079
+ }
8080
+ return queryParams;
8081
+ };
8082
+ KustoWorker.prototype.getGlobalParams = function (uri) {
8083
+ var document = this._getTextDocument(uri);
8084
+ if (!document) {
8085
+ console.error("getGLobalParams: document is " + document + ". uri is " + uri);
8086
+ return null;
8087
+ }
8088
+ var globalParams = this._languageService.getGlobalParams(document);
8089
+ if (globalParams === undefined) {
8090
+ return null;
8091
+ }
8092
+ return globalParams;
8093
+ };
8094
+ KustoWorker.prototype.getReferencedGlobalParams = function (uri, cursorOffest) {
8095
+ var document = this._getTextDocument(uri);
8096
+ if (!document) {
8097
+ console.error("getReferencedGlobalParams: document is " + document + ". uri is " + uri);
8098
+ return null;
8099
+ }
8100
+ var referencedParams = this._languageService.getReferencedGlobalParams(document, cursorOffest);
8101
+ if (referencedParams === undefined) {
8102
+ return null;
8103
+ }
8104
+ return referencedParams;
8105
+ };
8106
+ KustoWorker.prototype.getRenderInfo = function (uri, cursorOffset) {
8107
+ var document = this._getTextDocument(uri);
8108
+ if (!document) {
8109
+ console.error("getRenderInfo: document is " + document + ". uri is " + uri);
8110
+ }
8111
+ return this._languageService.getRenderInfo(document, cursorOffset).then(function (result) {
8112
+ if (!result) {
8113
+ return null;
8114
+ }
8115
+ return result;
8116
+ });
8117
+ };
8118
+ /**
8119
+ * Get command in context and the command range.
8120
+ * This method will basically convert generate microsoft language service interface to monaco interface.
8121
+ * @param uri document URI
8122
+ * @param cursorOffset offset from start of document to cursor
8123
+ */
8124
+ KustoWorker.prototype.getCommandAndLocationInContext = function (uri, cursorOffset) {
8125
+ var document = this._getTextDocument(uri);
8126
+ if (!document) {
8127
+ console.error("getCommandAndLocationInContext: document is " + document + ". uri is " + uri);
8128
+ return Promise.resolve(null);
8129
+ }
8130
+ return this._languageService.getCommandAndLocationInContext(document, cursorOffset).then(function (result) {
8131
+ if (!result) {
8132
+ return null;
8133
+ }
8134
+ // convert to monaco object.
8135
+ var text = result.text, _a = result.location.range, start = _a.start, end = _a.end;
8136
+ var range = new monaco.Range(start.line + 1, start.character + 1, end.line + 1, end.character + 1);
8137
+ return {
8138
+ range: range,
8139
+ text: text,
8140
+ };
8141
+ });
8142
+ };
8143
+ KustoWorker.prototype.getCommandsInDocument = function (uri) {
8144
+ var document = this._getTextDocument(uri);
8145
+ if (!document) {
8146
+ console.error("getCommandInDocument: document is " + document + ". uri is " + uri);
8147
+ return null;
8148
+ }
8149
+ return this._languageService.getCommandsInDocument(document);
8150
+ };
8151
+ KustoWorker.prototype.doComplete = function (uri, position) {
8152
+ var document = this._getTextDocument(uri);
8153
+ if (!document) {
8154
+ return null;
8155
+ }
8156
+ var completions = this._languageService.doComplete(document, position);
8157
+ return completions;
8158
+ };
8159
+ KustoWorker.prototype.doValidation = function (uri, intervals) {
8160
+ var document = this._getTextDocument(uri);
8161
+ var diagnostics = this._languageService.doValidation(document, intervals);
8162
+ return diagnostics;
8163
+ };
8164
+ KustoWorker.prototype.doRangeFormat = function (uri, range) {
8165
+ var document = this._getTextDocument(uri);
8166
+ var formatted = this._languageService.doRangeFormat(document, range);
8167
+ return formatted;
8168
+ };
8169
+ KustoWorker.prototype.doFolding = function (uri) {
8170
+ var document = this._getTextDocument(uri);
8171
+ var folding = this._languageService.doFolding(document);
8172
+ return folding;
8173
+ };
8174
+ KustoWorker.prototype.doDocumentFormat = function (uri) {
8175
+ var document = this._getTextDocument(uri);
8176
+ var formatted = this._languageService.doDocumentFormat(document);
8177
+ return formatted;
8178
+ };
8179
+ KustoWorker.prototype.doCurrentCommandFormat = function (uri, caretPosition) {
8180
+ var document = this._getTextDocument(uri);
8181
+ var formatted = this._languageService.doCurrentCommandFormat(document, caretPosition);
8182
+ return formatted;
8183
+ };
8184
+ // Colorize document. if offsets provided, will only colorize commands at these offsets. otherwise - will color the entire document.
8185
+ KustoWorker.prototype.doColorization = function (uri, colorizationIntervals) {
8186
+ var document = this._getTextDocument(uri);
8187
+ var colorizationInfo = this._languageService.doColorization(document, colorizationIntervals);
8188
+ return colorizationInfo;
8189
+ };
8190
+ KustoWorker.prototype.getClientDirective = function (text) {
8191
+ return this._languageService.getClientDirective(text);
8192
+ };
8193
+ KustoWorker.prototype.getAdminCommand = function (text) {
8194
+ return this._languageService.getAdminCommand(text);
8195
+ };
8196
+ KustoWorker.prototype.findDefinition = function (uri, position) {
8197
+ var document = this._getTextDocument(uri);
8198
+ var definition = this._languageService.findDefinition(document, position);
8199
+ return definition;
8200
+ };
8201
+ KustoWorker.prototype.findReferences = function (uri, position) {
8202
+ var document = this._getTextDocument(uri);
8203
+ var references = this._languageService.findReferences(document, position);
8204
+ return references;
8205
+ };
8206
+ KustoWorker.prototype.doRename = function (uri, position, newName) {
8207
+ var document = this._getTextDocument(uri);
8208
+ var workspaceEdit = this._languageService.doRename(document, position, newName);
8209
+ return workspaceEdit;
8210
+ };
8211
+ KustoWorker.prototype.doHover = function (uri, position) {
8212
+ var document = this._getTextDocument(uri);
8213
+ var hover = this._languageService.doHover(document, position);
8214
+ return hover;
8215
+ };
8216
+ KustoWorker.prototype.setParameters = function (parameters) {
8217
+ return this._languageService.setParameters(parameters);
8218
+ };
8219
+ KustoWorker.prototype.getClusterReferences = function (uri, cursorOffset) {
8220
+ var document = this._getTextDocument(uri);
8221
+ return this._languageService.getClusterReferences(document, cursorOffset);
8222
+ };
8223
+ KustoWorker.prototype.getDatabaseReferences = function (uri, cursorOffset) {
8224
+ var document = this._getTextDocument(uri);
8225
+ return this._languageService.getDatabaseReferences(document, cursorOffset);
8226
+ };
8227
+ KustoWorker.prototype._getTextDocument = function (uri) {
8228
+ var models = this._ctx.getMirrorModels();
8229
+ for (var _i = 0, models_1 = models; _i < models_1.length; _i++) {
8230
+ var model = models_1[_i];
8231
+ if (model.uri.toString() === uri) {
8232
+ return ls.TextDocument.create(uri, this._languageId, model.version, model.getValue());
8233
+ }
8234
+ }
8235
+ return null;
8236
+ };
8237
+ return KustoWorker;
8238
+ }());
8239
+ exports.KustoWorker = KustoWorker;
8240
+ function create(ctx, createData) {
8241
+ return new KustoWorker(ctx, createData);
8242
+ }
8243
+ exports.create = create;
8244
+ });
8057
8245