@kusto/monaco-kusto 3.2.4 → 3.2.7

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,1769 +6263,1792 @@ 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 lanugage 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: Currenlty 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 Microosft 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 funtion name (abs, tolower, ETC).
6586
- * The problem is that the 'Value' string also contains the arguments (e.g abs(nubmer)), 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 lagnuage 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
- * Retrun 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.getFormattedCommandsInDocumentV2 = function (document, rangeStart, rangeEnd) {
7021
- var script = this.parseDocumentV2(document);
7022
- var commands = this.toArray(script.Blocks).filter(function (command) {
7023
- if (!command.Text || command.Text.trim() == '')
7024
- return false;
7025
- if (rangeStart == null || rangeEnd == null)
7026
- return true;
7027
- // calculate command end position without \r\n.
7028
- var commandEnd = command.End;
7029
- var commandText = command.Text;
7030
- for (var i = commandText.length - 1; i >= 0; i--) {
7031
- if (commandText[i] != '\r' && commandText[i] != '\n') {
7032
- break;
7033
- }
7034
- else {
7035
- commandEnd--;
7036
- }
7037
- }
7038
- if (command.Start > rangeStart && command.Start < rangeEnd)
7039
- return true;
7040
- if (commandEnd > rangeStart && commandEnd < rangeEnd)
7041
- return true;
7042
- if (command.Start <= rangeStart && commandEnd >= rangeEnd)
7043
- return true;
7044
- });
7045
- if (commands.length === 0) {
7046
- return { formattedCommands: [] };
7047
- }
7048
- var formattedCommands = commands.map(function (command) {
7049
- var formatter = Kusto.Language.Editor.FormattingOptions.Default
7050
- .WithIndentationSize(4)
7051
- .WithInsertMissingTokens(false)
7052
- .WithPipeOperatorStyle(Kusto.Language.Editor.PlacementStyle.Smart)
7053
- .WithSemicolonStyle(Kusto.Language.Editor.PlacementStyle.None)
7054
- .WithBrackettingStyle(k2.BrackettingStyle.Diagonal);
7055
- if (rangeStart == null || rangeEnd == null || (rangeStart === command.Start && rangeEnd === command.End)) {
7056
- var result = command.Service.GetFormattedText(formatter);
7057
- return result.Text;
7058
- }
7059
- return command.Service.GetFormattedText(formatter).Text;
7060
- });
7061
- var originalRange = this.createRange(document, commands[0].Start, commands[commands.length - 1].End);
7062
- return { formattedCommands: formattedCommands, originalRange: originalRange };
7063
- };
7064
- KustoLanguageService.prototype.getCommandsInDocumentV2 = function (document) {
7065
- var script = this.parseDocumentV2(document);
7066
- var commands = this.toArray(script.Blocks).filter(function (command) { return command.Text.trim() != ''; });
7067
- return Promise.resolve(commands.map(function (_a) {
7068
- var Start = _a.Start, End = _a.End, Text = _a.Text;
7069
- return ({ absoluteStart: Start, absoluteEnd: End, text: Text });
7070
- }));
7071
- };
7072
- KustoLanguageService.prototype.getClientDirective = function (text) {
7073
- var outParam = { v: null };
7074
- var isClientDirective = k.CslCommandParser.IsClientDirective(text, outParam);
7075
- return Promise.resolve({
7076
- isClientDirective: isClientDirective,
7077
- directiveWithoutLeadingComments: outParam.v,
7078
- });
7079
- };
7080
- KustoLanguageService.prototype.getAdminCommand = function (text) {
7081
- var outParam = { v: null };
7082
- var isAdminCommand = k.CslCommandParser.IsAdminCommand$1(text, outParam);
7083
- return Promise.resolve({
7084
- isAdminCommand: isAdminCommand,
7085
- adminCommandWithoutLeadingComments: outParam.v,
7086
- });
7087
- };
7088
- KustoLanguageService.prototype.findDefinition = function (document, position) {
7089
- if (!document || !this.isIntellisenseV2()) {
7090
- return Promise.resolve([]);
7091
- }
7092
- var script = this.parseDocumentV2(document);
7093
- var cursorOffset = document.offsetAt(position);
7094
- var currentBlock = this.getCurrentCommandV2(script, cursorOffset);
7095
- if (!currentBlock) {
7096
- return Promise.resolve([]);
7097
- }
7098
- var relatedInfo = currentBlock.Service.GetRelatedElements(document.offsetAt(position));
7099
- var relatedElements = this.toArray(relatedInfo.Elements);
7100
- var definition = relatedElements[0];
7101
- if (!definition) {
7102
- return Promise.resolve([]);
7103
- }
7104
- var start = document.positionAt(definition.Start);
7105
- var end = document.positionAt(definition.End);
7106
- var range = ls.Range.create(start, end);
7107
- var location = ls.Location.create(document.uri, range);
7108
- return Promise.resolve([location]);
7109
- };
7110
- KustoLanguageService.prototype.findReferences = function (document, position) {
7111
- if (!document || !this.isIntellisenseV2()) {
7112
- return Promise.resolve([]);
7113
- }
7114
- var script = this.parseDocumentV2(document);
7115
- var cursorOffset = document.offsetAt(position);
7116
- var currentBlock = this.getCurrentCommandV2(script, cursorOffset);
7117
- if (!currentBlock) {
7118
- return Promise.resolve([]);
7119
- }
7120
- var relatedInfo = currentBlock.Service.GetRelatedElements(document.offsetAt(position));
7121
- var relatedElements = this.toArray(relatedInfo.Elements);
7122
- if (!relatedElements || relatedElements.length == 0) {
7123
- return Promise.resolve([]);
7124
- }
7125
- var references = relatedElements.map(function (relatedElement) {
7126
- var start = document.positionAt(relatedElement.Start);
7127
- var end = document.positionAt(relatedElement.End);
7128
- var range = ls.Range.create(start, end);
7129
- var location = ls.Location.create(document.uri, range);
7130
- return location;
7131
- });
7132
- return Promise.resolve(references);
7133
- };
7134
- KustoLanguageService.prototype.getQueryParams = function (document, cursorOffset) {
7135
- if (!document || !this.isIntellisenseV2()) {
7136
- return Promise.resolve([]);
7137
- }
7138
- var script = this.parseDocumentV2(document);
7139
- var parsedAndAnalyzed = this.parseAndAnalyze(document, cursorOffset);
7140
- var queryParamStatements = this.toArray(parsedAndAnalyzed.Syntax.GetDescendants(Kusto.Language.Syntax.QueryParametersStatement));
7141
- if (!queryParamStatements || queryParamStatements.length == 0) {
7142
- return Promise.resolve([]);
7143
- }
7144
- var queryParams = [];
7145
- queryParamStatements.forEach(function (paramStatement) {
7146
- paramStatement.WalkElements(function (el) {
7147
- return el.ReferencedSymbol && el.ReferencedSymbol.Type
7148
- ? queryParams.push({ name: el.ReferencedSymbol.Name, type: el.ReferencedSymbol.Type.Name })
7149
- : undefined;
7150
- });
7151
- });
7152
- return Promise.resolve(queryParams);
7153
- };
7154
- KustoLanguageService.prototype.getRenderInfo = function (document, cursorOffset) {
7155
- var _this = this;
7156
- var parsedAndAnalyzed = this.parseAndAnalyze(document, cursorOffset);
7157
- if (!parsedAndAnalyzed) {
7158
- return Promise.resolve(undefined);
7159
- }
7160
- var renderStatements = this.toArray(parsedAndAnalyzed.Syntax.GetDescendants(Kusto.Language.Syntax.RenderOperator));
7161
- if (!renderStatements || renderStatements.length === 0) {
7162
- return Promise.resolve(undefined);
7163
- }
7164
- // assuming a single render statement
7165
- var renderStatement = renderStatements[0];
7166
- // Start and end relative to block start.
7167
- var startOffset = renderStatement.TextStart;
7168
- var endOffset = renderStatement.End;
7169
- var visualization = renderStatement.ChartType.Text;
7170
- var withClause = renderStatement.WithClause;
7171
- if (!withClause) {
7172
- var info = {
7173
- options: {
7174
- visualization: visualization,
7175
- },
7176
- location: { startOffset: startOffset, endOffset: endOffset },
7177
- };
7178
- return Promise.resolve(info);
7179
- }
7180
- var properties = this.toArray(withClause.Properties);
7181
- var props = properties.reduce(function (prev, property) {
7182
- var name = property.Element$1.Name.SimpleName;
7183
- switch (name) {
7184
- case 'xcolumn':
7185
- var value = property.Element$1.Expression.ReferencedSymbol.Name;
7186
- prev[name] = value;
7187
- break;
7188
- case 'ycolumns':
7189
- case 'anomalycolumns':
7190
- var nameNodes = _this.toArray(property.Element$1.Expression.Names);
7191
- var values = nameNodes.map(function (nameNode) { return nameNode.Element$1.SimpleName; });
7192
- prev[name] = values;
7193
- break;
7194
- case 'ymin':
7195
- case 'ymax':
7196
- var numericVal = parseFloat(property.Element$1.Expression.ConstantValue);
7197
- prev[name] = numericVal;
7198
- break;
7199
- case 'title':
7200
- case 'xtitle':
7201
- case 'ytitle':
7202
- case 'visualization':
7203
- case 'series':
7204
- var strVal = property.Element$1.Expression.ConstantValue;
7205
- prev[name] = strVal;
7206
- break;
7207
- case 'xaxis':
7208
- case 'yaxis':
7209
- var scale = property.Element$1.Expression.ConstantValue;
7210
- prev[name] = scale;
7211
- break;
7212
- case 'legend':
7213
- var legend = property.Element$1.Expression.ConstantValue;
7214
- prev[name] = legend;
7215
- break;
7216
- case 'ySplit':
7217
- var split = property.Element$1.Expression.ConstantValue;
7218
- prev[name] = split;
7219
- break;
7220
- case 'accumulate':
7221
- var accumulate = property.Element$1.Expression.ConstantValue;
7222
- prev[name] = accumulate;
7223
- break;
7224
- case 'kind':
7225
- var val = property.Element$1.Expression.ConstantValue;
7226
- prev[name] = val;
7227
- break;
7228
- default:
7229
- assertNever(name);
7230
- }
7231
- return prev;
7232
- }, {});
7233
- var renderOptions = __assign({ visualization: visualization }, props);
7234
- var renderInfo = {
7235
- options: renderOptions,
7236
- location: { startOffset: startOffset, endOffset: endOffset },
7237
- };
7238
- return Promise.resolve(renderInfo);
7239
- };
7240
- KustoLanguageService.prototype.getReferencedGlobalParams = function (document, cursorOffset) {
7241
- if (!document || !this.isIntellisenseV2()) {
7242
- return Promise.resolve([]);
7243
- }
7244
- var script = this.parseDocumentV2(document);
7245
- var currentBlock = this.getCurrentCommandV2(script, cursorOffset);
7246
- if (!currentBlock) {
7247
- return Promise.resolve([]);
7248
- }
7249
- var text = currentBlock.Text;
7250
- var parsedAndAnalyzed = Kusto.Language.KustoCode.ParseAndAnalyze(text, this._kustoJsSchemaV2);
7251
- // We take the ambient parameters
7252
- var ambientParameters = this.toArray(this._kustoJsSchemaV2.Parameters);
7253
- // We take all referenced symbols in the query
7254
- var referencedSymbols = this.toArray(parsedAndAnalyzed.Syntax.GetDescendants(Kusto.Language.Syntax.Expression))
7255
- .filter(function (epression) { return epression.ReferencedSymbol !== null; })
7256
- .map(function (x) { return x.ReferencedSymbol; });
7257
- // The Intersection between them is the ambient parameters that are used in the query.
7258
- // Note: Ideally we would use Set here (or at least array.Include), but were' compiling down to es2015.
7259
- var intersection = referencedSymbols.filter(function (referencedSymbol) {
7260
- return ambientParameters.filter(function (ambientParameter) { return ambientParameter === referencedSymbol; }).length > 0;
7261
- });
7262
- var result = intersection.map(function (param) { return ({ name: param.Name, type: param.Type.Name }); });
7263
- return Promise.resolve(result);
7264
- };
7265
- KustoLanguageService.prototype.getGlobalParams = function (document) {
7266
- if (!this.isIntellisenseV2()) {
7267
- return Promise.resolve([]);
7268
- }
7269
- var params = this.toArray(this._kustoJsSchemaV2.Parameters);
7270
- var result = params.map(function (param) { return ({ name: param.Name, type: param.Type.Name }); });
7271
- return Promise.resolve(result);
7272
- };
7273
- KustoLanguageService.prototype.doRename = function (document, position, newName) {
7274
- var _a;
7275
- if (!document || !this.isIntellisenseV2()) {
7276
- return Promise.resolve(undefined);
7277
- }
7278
- var script = this.parseDocumentV2(document);
7279
- var cursorOffset = document.offsetAt(position);
7280
- var currentBLock = this.getCurrentCommandV2(script, cursorOffset);
7281
- if (!currentBLock) {
7282
- return Promise.resolve(undefined);
7283
- }
7284
- var relatedInfo = currentBLock.Service.GetRelatedElements(document.offsetAt(position));
7285
- var relatedElements = this.toArray(relatedInfo.Elements);
7286
- var declarations = relatedElements.filter(function (e) { return e.Kind == k2.RelatedElementKind.Declaration; });
7287
- // A declaration must be one of the elements
7288
- if (!declarations || declarations.length == 0) {
7289
- return Promise.resolve(undefined);
7290
- }
7291
- var edits = relatedElements.map(function (edit) {
7292
- var start = document.positionAt(edit.Start);
7293
- var end = document.positionAt(edit.End);
7294
- var range = ls.Range.create(start, end);
7295
- return ls.TextEdit.replace(range, newName);
7296
- });
7297
- // create a workspace edit
7298
- var workspaceEdit = { changes: (_a = {}, _a[document.uri] = edits, _a) };
7299
- return Promise.resolve(workspaceEdit);
7300
- };
7301
- KustoLanguageService.prototype.doHover = function (document, position) {
7302
- if (!document || !this.isIntellisenseV2()) {
7303
- return Promise.resolve(undefined);
7304
- }
7305
- var script = this.parseDocumentV2(document);
7306
- var cursorOffset = document.offsetAt(position);
7307
- var currentBLock = this.getCurrentCommandV2(script, cursorOffset);
7308
- if (!currentBLock) {
7309
- return Promise.resolve(undefined);
7310
- }
7311
- var isSupported = currentBLock.Service.IsFeatureSupported(k2.CodeServiceFeatures.QuickInfo, cursorOffset);
7312
- if (!isSupported) {
7313
- return Promise.resolve(undefined);
7314
- }
7315
- var quickInfo = currentBLock.Service.GetQuickInfo(cursorOffset);
7316
- if (!quickInfo || !quickInfo.Text) {
7317
- return Promise.resolve(undefined);
7318
- }
7319
- // Instead of just an empty line between the first line (the signature) and the second line (the description)
7320
- // add an horizontal line (* * * in markdown) between them.
7321
- return Promise.resolve({ contents: quickInfo.Text.replace('\n\n', '\n* * *\n') });
7322
- };
7323
- Object.defineProperty(KustoLanguageService, "dummySchema", {
7324
- //#region dummy schema for manual testing
7325
- get: function () {
7326
- var database = {
7327
- majorVersion: 0,
7328
- minorVersion: 0,
7329
- name: 'Kuskus',
7330
- tables: [
7331
- {
7332
- name: 'KustoLogs',
7333
- columns: [
7334
- {
7335
- name: 'Source',
7336
- type: 'string',
7337
- },
7338
- {
7339
- name: 'Timestamp',
7340
- type: 'datetime',
7341
- },
7342
- {
7343
- name: 'Directory',
7344
- type: 'string',
7345
- },
7346
- ],
7347
- docstring: 'A dummy description to test that docstring shows as expected when hovering over a table',
7348
- },
7349
- ],
7350
- functions: [
7351
- {
7352
- name: 'HowBig',
7353
- inputParameters: [
7354
- {
7355
- name: 'T',
7356
- columns: [
7357
- {
7358
- name: 'Timestamp',
7359
- type: 'System.DateTime',
7360
- cslType: 'datetime',
7361
- },
7362
- ],
7363
- },
7364
- ],
7365
- docstring: 'A dummy description to test that docstring shows as expected when hovering over a function',
7366
- 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}",
7367
- },
7368
- {
7369
- name: 'FindCIDPast24h',
7370
- inputParameters: [
7371
- {
7372
- name: 'clientActivityId',
7373
- type: 'System.String',
7374
- cslType: 'string',
7375
- },
7376
- ],
7377
- body: '{ KustoLogs | where Timestamp > now(-1d) | where ClientActivityId == clientActivityId} ',
7378
- },
7379
- ],
7380
- };
7381
- var languageServiceSchema = {
7382
- clusterType: 'Engine',
7383
- cluster: {
7384
- connectionString: 'https://kuskus.kusto.windows.net;fed=true',
7385
- databases: [database],
7386
- },
7387
- database: database,
7388
- };
7389
- return languageServiceSchema;
7390
- },
7391
- enumerable: false,
7392
- configurable: true
7393
- });
7394
- //#endregion
7395
- KustoLanguageService.convertToEntityDataType = function (kustoType) { };
7396
- /**
7397
- * We do not want to expose Bridge.Net generated schema, so we expose a cleaner javascript schema.
7398
- * Here it gets converted to the bridge.Net schema
7399
- * @param schema Language Service schema
7400
- */
7401
- KustoLanguageService.convertToKustoJsSchema = function (schema) {
7402
- switch (schema.clusterType) {
7403
- case 'Engine':
7404
- var currentDatabaseName_1 = schema.database ? schema.database.name : undefined;
7405
- var kCluster = new k.KustoIntelliSenseClusterEntity();
7406
- var kDatabaseInContext_1 = undefined;
7407
- kCluster.ConnectionString = schema.cluster.connectionString;
7408
- var databases_1 = [];
7409
- schema.cluster.databases.forEach(function (database) {
7410
- var kDatabase = new k.KustoIntelliSenseDatabaseEntity();
7411
- kDatabase.Name = database.name;
7412
- var tables = [];
7413
- database.tables.forEach(function (table) {
7414
- var kTable = new k.KustoIntelliSenseTableEntity();
7415
- kTable.Name = table.name;
7416
- var cols = [];
7417
- table.columns.forEach(function (column) {
7418
- var kColumn = new k.KustoIntelliSenseColumnEntity();
7419
- kColumn.Name = column.name;
7420
- kColumn.TypeCode = k.EntityDataType[schema_1.getEntityDataTypeFromCslType(column.type)];
7421
- cols.push(kColumn);
7422
- });
7423
- kTable.Columns = new Bridge.ArrayEnumerable(cols);
7424
- tables.push(kTable);
7425
- });
7426
- var functions = [];
7427
- database.functions.forEach(function (fn) {
7428
- var kFunction = new k.KustoIntelliSenseFunctionEntity();
7429
- (kFunction.Name = fn.name),
7430
- (kFunction.CallName = s.getCallName(fn)),
7431
- (kFunction.Expression = s.getExpression(fn)),
7432
- functions.push(kFunction);
7433
- });
7434
- kDatabase.Tables = new Bridge.ArrayEnumerable(tables);
7435
- kDatabase.Functions = new Bridge.ArrayEnumerable(functions);
7436
- databases_1.push(kDatabase);
7437
- if (database.name == currentDatabaseName_1) {
7438
- kDatabaseInContext_1 = kDatabase;
7439
- }
7440
- });
7441
- kCluster.Databases = new Bridge.ArrayEnumerable(databases_1);
7442
- var kSchema = new k.KustoIntelliSenseQuerySchema(kCluster, kDatabaseInContext_1);
7443
- return kSchema;
7444
- case 'ClusterManager':
7445
- var accounts = schema.accounts.map(function (account) {
7446
- var kAccount = new k.KustoIntelliSenseAccountEntity();
7447
- kAccount.Name = account;
7448
- return kAccount;
7449
- });
7450
- var services = schema.services.map(function (service) {
7451
- var kService = new k.KustoIntelliSenseServiceEntity();
7452
- kService.Name = service;
7453
- return kService;
7454
- });
7455
- var connectionString = schema.connectionString;
7456
- var result = {
7457
- accounts: accounts,
7458
- services: services,
7459
- connectionString: connectionString,
7460
- };
7461
- return result;
7462
- case 'DataManagement':
7463
- return undefined;
7464
- default:
7465
- return assertNever(schema);
7466
- }
7467
- };
7468
- /**
7469
- * Returns something like '(x: string, y: datetime)'
7470
- * @param params scalar parameters
7471
- */
7472
- KustoLanguageService.scalarParametersToSignature = function (params) {
7473
- var signatureWithoutParens = params.map(function (param) { return param.name + ": " + param.cslType; }).join(', ');
7474
- return "(" + signatureWithoutParens + ")";
7475
- };
7476
- /**
7477
- * Returns something like '(x: string, T: (y: int))'
7478
- * @param params input parameters (tabular or scalar)
7479
- */
7480
- KustoLanguageService.inputParameterToSignature = function (params) {
7481
- var _this = this;
7482
- var signatureWithoutParens = params
7483
- .map(function (param) {
7484
- if (param.columns) {
7485
- var tableSignature = _this.scalarParametersToSignature(param.columns);
7486
- return param.name + ": " + tableSignature;
7487
- }
7488
- else {
7489
- return param.name + ": " + param.cslType;
7490
- }
7491
- })
7492
- .join(', ');
7493
- return "(" + signatureWithoutParens + ")";
7494
- };
7495
- /**
7496
- * converts a function definition to a let statement.
7497
- * @param fn function
7498
- */
7499
- KustoLanguageService.toLetStatement = function (fn) {
7500
- var signature = this.inputParameterToSignature(fn.inputParameters);
7501
- return "let " + fn.name + " = " + signature + " " + fn.body;
7502
- };
7503
- KustoLanguageService.createColumnSymbol = function (col) {
7504
- return new sym.ColumnSymbol(col.name, sym.ScalarTypes.GetSymbol(schema_1.getCslTypeNameFromClrType(col.type)), col.docstring);
7505
- };
7506
- KustoLanguageService.createParameterSymbol = function (param) {
7507
- var paramSymbol = Kusto.Language.Symbols.ScalarTypes.GetSymbol(schema_1.getCslTypeNameFromClrType(param.type));
7508
- return new sym.ParameterSymbol(param.name, paramSymbol, null);
7509
- };
7510
- KustoLanguageService.createParameter = function (param) {
7511
- if (!param.columns) {
7512
- var paramSymbol = Kusto.Language.Symbols.ScalarTypes.GetSymbol(schema_1.getCslTypeNameFromClrType(param.type));
7513
- var expression = void 0;
7514
- if (param.cslDefaultValue && typeof param.cslDefaultValue === "string") {
7515
- var parser = parsing.QueryGrammar.From(Kusto.Language.GlobalState.Default).ConstantExpression;
7516
- expression = parsing.SyntaxParsers.ParseFirst({ prototype: parser }, parser, param.cslDefaultValue);
7517
- }
7518
- return new sym.Parameter.$ctor3(param.name, paramSymbol, null, null, null, false, null, 1, 1, expression, null);
7519
- }
7520
- if (param.columns.length == 0) {
7521
- return new sym.Parameter.ctor(param.name, sym.ParameterTypeKind.Tabular, sym.ArgumentKind.Expression, null, null, false, null, 1, 1, null, null);
7522
- }
7523
- var argumentType = new sym.TableSymbol.ctor(param.columns.map(function (col) { return KustoLanguageService.createColumnSymbol(col); }));
7524
- return new sym.Parameter.$ctor2(param.name, argumentType);
7525
- };
7526
- KustoLanguageService.convertToDatabaseSymbol = function (db, globalState, addFunctions) {
7527
- var createFunctionSymbol = function (fn) {
7528
- var parameters = fn.inputParameters.map(function (param) {
7529
- return KustoLanguageService.createParameter(param);
7530
- });
7531
- // TODO: handle outputColumns (right now it doesn't seem to be implemented for any function).
7532
- return new sym.FunctionSymbol.$ctor16(fn.name, fn.body, KustoLanguageService.toBridgeList(parameters), fn.docstring);
7533
- };
7534
- var createTableSymbol = function (tbl) {
7535
- var columnSymbols = tbl.columns.map(function (col) { return KustoLanguageService.createColumnSymbol(col); });
7536
- var symbol = new sym.TableSymbol.$ctor3(tbl.name, columnSymbols);
7537
- symbol.Description = tbl.docstring;
7538
- switch (tbl.entityType) {
7539
- case 'MaterializedViewTable':
7540
- symbol = symbol.WithIsMaterializedView(true);
7541
- case "ExternalTable":
7542
- symbol = symbol.WithIsExternal(true);
7543
- default:
7544
- }
7545
- return symbol;
7546
- };
7547
- var createDatabaseSymbol = function (db) {
7548
- var tableSymbols = db.tables ? db.tables.map(function (tbl) { return createTableSymbol(tbl); }) : [];
7549
- var functionSymbols = db.functions ? db.functions.map(function (fun) { return createFunctionSymbol(fun); }) : [];
7550
- return new sym.DatabaseSymbol.ctor(db.name, tableSymbols.concat(functionSymbols));
7551
- };
7552
- var databaseSymbol = createDatabaseSymbol(db);
7553
- return databaseSymbol;
7554
- };
7555
- KustoLanguageService.prototype.convertToKustoJsSchemaV2 = function (schema) {
7556
- var cached = this._schemaCache[schema.cluster.connectionString];
7557
- // create a cache entry for the cluster if non yet exists.
7558
- if (!cached) {
7559
- this._schemaCache[schema.cluster.connectionString] = {};
7560
- cached = this._schemaCache[schema.cluster.connectionString];
7561
- }
7562
- // Remove deleted databases from cache
7563
- var schemaDbLookup = schema.cluster.databases.reduce(function (prev, curr) { return (prev[curr.name] = curr); }, {});
7564
- Object.keys(cached).map(function (dbName) {
7565
- if (!schemaDbLookup[dbName]) {
7566
- delete cached.dbName;
7567
- }
7568
- });
7569
- var globalState = GlobalState.Default;
7570
- var currentDatabaseName = schema.database ? schema.database.name : undefined;
7571
- var databaseInContext = undefined;
7572
- // Update out-of-data databses to cache
7573
- var databases = schema.cluster.databases.map(function (db) {
7574
- var shouldIncludeFunctions = db.name === currentDatabaseName;
7575
- var cachedDb = cached[db.name];
7576
- // This is an older version than we have, or we need to parse functions.
7577
- if (!cachedDb ||
7578
- cachedDb.database.majorVersion < db.majorVersion ||
7579
- (shouldIncludeFunctions && !cachedDb.includesFunctions)) {
7580
- // only add functions for the database in context (it's very time consuming)
7581
- var databaseSymbol_1 = KustoLanguageService.convertToDatabaseSymbol(db, globalState, shouldIncludeFunctions);
7582
- cached[db.name] = { database: db, symbol: databaseSymbol_1, includesFunctions: shouldIncludeFunctions };
7583
- }
7584
- var databaseSymbol = cached[db.name].symbol;
7585
- if (db.name === currentDatabaseName) {
7586
- databaseInContext = databaseSymbol;
7587
- }
7588
- return databaseSymbol;
7589
- });
7590
- // Replace new URL due to polyfill issue in IE
7591
- // const hostname = new URL(schema.cluster.connectionString.split(';')[0]).hostname;
7592
- var hostname = schema.cluster.connectionString.match(/(.*\/\/)?([^\/;]*)/)[2];
7593
- var clusterName = hostname.split('.')[0];
7594
- var clusterSymbol = new sym.ClusterSymbol.ctor(clusterName, databases);
7595
- globalState = globalState.WithCluster(clusterSymbol);
7596
- if (databaseInContext) {
7597
- globalState = globalState.WithDatabase(databaseInContext);
7598
- }
7599
- // Inject gloabl parameters to global scope.
7600
- if (schema.globalParameters) {
7601
- var parameters = schema.globalParameters.map(function (param) {
7602
- return KustoLanguageService.createParameterSymbol(param);
7603
- });
7604
- globalState = globalState.WithParameters(KustoLanguageService.toBridgeList(parameters));
7605
- }
7606
- return globalState;
7607
- };
7608
- KustoLanguageService.prototype.getClassificationsFromParseResult = function (offset) {
7609
- var _this = this;
7610
- if (offset === void 0) { offset = 0; }
7611
- var classifications = this.toArray(this._parser.Results)
7612
- .map(function (command) { return _this.toArray(command.Tokens); })
7613
- .reduce(function (prev, curr) { return prev.concat(curr); }, [])
7614
- .map(function (cslCommandToken) {
7615
- var range = new k2.ClassifiedRange(_this.tokenKindToClassificationKind(cslCommandToken.TokenKind), cslCommandToken.AbsoluteStart + offset, cslCommandToken.Length);
7616
- return range;
7617
- });
7618
- return classifications;
7619
- };
7620
- /**
7621
- * trim trailing newlines from range
7622
- */
7623
- KustoLanguageService.trimTrailingNewlineFromRange = function (textInRange, rangeStartOffset, document, range) {
7624
- var currentIndex = textInRange.length - 1;
7625
- while (textInRange[currentIndex] === '\r' || textInRange[currentIndex] === '\n') {
7626
- --currentIndex;
7627
- }
7628
- var newEndOffset = rangeStartOffset + currentIndex + 1;
7629
- var newEndPosition = document.positionAt(newEndOffset);
7630
- var newRange = ls.Range.create(range.start, newEndPosition);
7631
- return newRange;
7632
- };
7633
- /**
7634
- * Maps numbers to strings, such that if a>b numerically, f(a)>f(b) lexicograhically.
7635
- * 1 -> "a", 26 -> "z", 27 -> "za", 28 -> "zb", 52 -> "zz", 53 ->"zza"
7636
- * @param order - The number to be converted to a sorting-string. order should start at 1.
7637
- * @returns A string repenting the order.
7638
- */
7639
- KustoLanguageService.prototype.getSortText = function (order) {
7640
- if (order <= 0) {
7641
- throw new RangeError("order should be a number >= 1. instead got " + order);
7642
- }
7643
- var sortText = '';
7644
- var numCharacters = 26; // "z" - "a" + 1;
7645
- var div = Math.floor(order / numCharacters);
7646
- for (var i = 0; i < div; ++i) {
7647
- sortText += 'z';
7648
- }
7649
- var reminder = order % numCharacters;
7650
- if (reminder > 0) {
7651
- sortText += String.fromCharCode(96 + reminder);
7652
- }
7653
- return sortText;
7654
- };
7655
- /**
7656
- * ParseTextV1 parses the given text with the given parse mode.
7657
- * Additionally - it will make sure not to provide rules provider for non-engine clusters
7658
- * since the only rules provider parse can handle is the engine's. It will try to look for function
7659
- * definitions to colorize and will throw since they're not there.
7660
- * @param text
7661
- * @param parseMode
7662
- */
7663
- KustoLanguageService.prototype.parseTextV1 = function (text, parseMode) {
7664
- this._parser.Parse(this._schema.clusterType === 'Engine' ? this._rulesProvider : null, text, parseMode);
7665
- };
7666
- KustoLanguageService.prototype.parseDocumentV1 = function (document, parseMode) {
7667
- // already parsed a later version, or better parse mode for this uri
7668
- if (this._parsePropertiesV1 &&
7669
- !this._parsePropertiesV1.isParseNeeded(document, this._rulesProvider, parseMode)) {
7670
- return;
7671
- }
7672
- this.parseTextV1(document.getText(), parseMode);
7673
- this._parsePropertiesV1 = new ParseProperties(document.version, document.uri, this._rulesProvider, parseMode);
7674
- };
7675
- KustoLanguageService.prototype.parseDocumentV2 = function (document) {
7676
- if (this._parsePropertiesV2 && !this._parsePropertiesV2.isParseNeeded(document, this._rulesProvider)) {
7677
- return this._script;
7678
- }
7679
- if (!this._script) {
7680
- this._script = k2.CodeScript.From$1(document.getText(), this._kustoJsSchemaV2);
7681
- }
7682
- else {
7683
- this._script = this._script.WithText(document.getText());
7684
- }
7685
- this._parsePropertiesV2 = new ParseProperties(document.version, document.uri);
7686
- return this._script;
7687
- };
7688
- /**
7689
- * Return the CslCommand that wraps the caret location, or undefined if caret is outside any command
7690
- * @param document the document to extract the current command from
7691
- * @param caretAbsolutePosition absolute caret position
7692
- */
7693
- KustoLanguageService.prototype.getCurrentCommand = function (document, caretAbsolutePosition) {
7694
- var commands = this.toArray(this._parser.Results);
7695
- var command = commands.filter(function (command) { return command.AbsoluteStart <= caretAbsolutePosition && command.AbsoluteEnd >= caretAbsolutePosition; })[0];
7696
- // There is an edge case when cursor appears at the end of the command
7697
- // which is not yet considered to be part of the parsed command (therefore: +1 for the AbsoluteEdit property)
7698
- if (!command) {
7699
- command = commands.filter(function (command) {
7700
- return command.AbsoluteStart <= caretAbsolutePosition && command.AbsoluteEnd + 1 >= caretAbsolutePosition;
7701
- })[0];
7702
- // If we have 2 newlines in the end of the text the cursor is _probably_ at the end of the text
7703
- // which this means that we're not actually standing on any command. Thus return null.
7704
- if (!command || command.Text.endsWith('\r\n\r\n')) {
7705
- return null;
7706
- }
7707
- }
7708
- return command;
7709
- };
7710
- KustoLanguageService.prototype.getCurrentCommandV2 = function (script, offset) {
7711
- var block = script.GetBlockAtPosition(offset);
7712
- return block;
7713
- };
7714
- KustoLanguageService.prototype.getTextToInsert = function (rule, option) {
7715
- var beforeApplyInfo = rule.GetBeforeApplyInfo(option.Value);
7716
- var afterApplyInfo = rule.GetAfterApplyInfo(option.Value);
7717
- // this is the basic text to be insterted,
7718
- // but we still need to figure out where the cursor will end up after completion is applied.
7719
- var insertText = beforeApplyInfo.Text || '' + option.Value + afterApplyInfo.Text || '';
7720
- var insertTextFormat = ls.InsertTextFormat.PlainText;
7721
- var snippetFinalTabStop = '$0';
7722
- if (afterApplyInfo.OffsetToken && afterApplyInfo.OffsetPosition) {
7723
- var tokenOffset = insertText.indexOf(afterApplyInfo.OffsetToken);
7724
- if (tokenOffset >= 0) {
7725
- insertText = this.insertToString(insertText, snippetFinalTabStop, tokenOffset - insertText.length + afterApplyInfo.OffsetPosition);
7726
- insertTextFormat = ls.InsertTextFormat.Snippet;
7727
- }
7728
- }
7729
- else if (afterApplyInfo.OffsetPosition) {
7730
- // We only handle negative offsets
7731
- insertText = this.insertToString(insertText, snippetFinalTabStop, afterApplyInfo.OffsetPosition);
7732
- insertTextFormat = ls.InsertTextFormat.Snippet;
7733
- }
7734
- return { insertText: insertText, insertTextFormat: insertTextFormat };
7735
- };
7736
- /**
7737
- * create a new string with stringToInsert inserted at offsetFromEnd in originalString.
7738
- * @param originalString string to insert to
7739
- * @param stringToInsert string to insert
7740
- * @param offsetFromEnd a negative number that will represent offset to the left. 0 means simple concat
7741
- */
7742
- KustoLanguageService.prototype.insertToString = function (originalString, stringToInsert, offsetFromEnd) {
7743
- var index = originalString.length + offsetFromEnd;
7744
- if (offsetFromEnd >= 0 || index < 0) {
7745
- return originalString; // Cannot insert before or after the string
7746
- }
7747
- var before = originalString.substring(0, index);
7748
- var after = originalString.substring(index);
7749
- return before + stringToInsert + after;
7750
- };
7751
- KustoLanguageService.prototype.getCommandWithoutLastWord = function (text) {
7752
- var lastWordRegex = XRegExp('[\\w_]*$', 's');
7753
- return text.replace(lastWordRegex, '');
7754
- };
7755
- KustoLanguageService.prototype.createRulesProvider = function (schema, clusterType) {
7756
- var queryParameters = new (List(String))();
7757
- var availableClusters = new (List(String))();
7758
- this._parser = new k.CslCommandParser();
7759
- if (clusterType == 'Engine') {
7760
- var engineSchema = schema;
7761
- this._rulesProvider =
7762
- this._languageSettings && this._languageSettings.includeControlCommands
7763
- ? new k.CslIntelliSenseRulesProvider.$ctor1(engineSchema.Cluster, engineSchema, queryParameters, availableClusters, null, true, true)
7764
- : new k.CslQueryIntelliSenseRulesProvider.$ctor1(engineSchema.Cluster, engineSchema, queryParameters, availableClusters, null, null, null);
7765
- return;
7766
- }
7767
- if (clusterType === 'DataManagement') {
7768
- this._rulesProvider = new k.DataManagerIntelliSenseRulesProvider(null);
7769
- return;
7770
- }
7771
- // This is a cluster manger
7772
- var _a = schema, accounts = _a.accounts, services = _a.services, connectionString = _a.connectionString;
7773
- new k.KustoIntelliSenseAccountEntity();
7774
- new k.KustoIntelliSenseServiceEntity();
7775
- this._rulesProvider = new k.ClusterManagerIntelliSenseRulesProvider.$ctor1(new Bridge.ArrayEnumerable(accounts), new Bridge.ArrayEnumerable(services), connectionString);
7776
- };
7777
- KustoLanguageService.prototype.kustoKindToLsKind = function (kustoKind) {
7778
- var res = this._kustoKindtolsKind[kustoKind];
7779
- return res ? res : ls.CompletionItemKind.Variable;
7780
- };
7781
- KustoLanguageService.prototype.kustoKindToLsKindV2 = function (kustoKind) {
7782
- var res = this._kustoKindToLsKindV2[kustoKind];
7783
- return res ? res : ls.CompletionItemKind.Variable;
7784
- };
7785
- KustoLanguageService.prototype.createRange = function (document, start, end) {
7786
- return ls.Range.create(document.positionAt(start), document.positionAt(end));
7787
- };
7788
- KustoLanguageService.prototype.toArray = function (bridgeList) {
7789
- return Bridge.toArray(bridgeList);
7790
- };
7791
- KustoLanguageService.toBridgeList = function (array) {
7792
- // copied from bridge.js from the implementation of Enumerable.prototype.toList
7793
- return new (System.Collections.Generic.List$1(System.Object).$ctor1)(array);
7794
- };
7795
- KustoLanguageService.prototype.tokenKindToClassificationKind = function (token) {
7796
- var conversion = this._tokenKindToClassificationKind[token];
7797
- return conversion || k2.ClassificationKind.PlainText;
7798
- };
7799
- KustoLanguageService.prototype.parseAndAnalyze = function (document, cursorOffset) {
7800
- if (!document || !this.isIntellisenseV2()) {
7801
- return undefined;
7802
- }
7803
- var script = this.parseDocumentV2(document);
7804
- var currentBlock = this.getCurrentCommandV2(script, cursorOffset);
7805
- if (!currentBlock) {
7806
- return undefined;
7807
- }
7808
- var text = currentBlock.Text;
7809
- var parsedAndAnalyzed = Kusto.Language.KustoCode.ParseAndAnalyze(text, this._kustoJsSchemaV2);
7810
- return parsedAndAnalyzed;
7811
- };
7812
- return KustoLanguageService;
7813
- }());
7814
- var languageService = new KustoLanguageService(KustoLanguageService.dummySchema, {
7815
- includeControlCommands: true,
7816
- useIntellisenseV2: true,
7817
- useSemanticColorization: true,
7818
- });
7819
- /**
7820
- * Obtain an instance of the kusto language service.
7821
- */
7822
- function getKustoLanguageService() {
7823
- return languageService;
7824
- }
7825
- exports.getKustoLanguageService = getKustoLanguageService;
7826
- });
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 lanugage 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: Currenlty 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 Microosft 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 funtion name (abs, tolower, ETC).
6586
+ * The problem is that the 'Value' string also contains the arguments (e.g abs(nubmer)), 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 lagnuage 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
+ * Retrun 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': return k2.PlacementStyle.None;
7026
+ case 'NewLine': return k2.PlacementStyle.NewLine;
7027
+ case 'Smart': return k2.PlacementStyle.Smart;
7028
+ default: throw new Error('Unknown PlacementStyle');
7029
+ }
7030
+ };
7031
+ KustoLanguageService.prototype.getFormattedCommandsInDocumentV2 = function (document, rangeStart, rangeEnd) {
7032
+ var _this = this;
7033
+ var script = this.parseDocumentV2(document);
7034
+ var commands = this.toArray(script.Blocks).filter(function (command) {
7035
+ if (!command.Text || command.Text.trim() == '')
7036
+ return false;
7037
+ if (rangeStart == null || rangeEnd == null)
7038
+ return true;
7039
+ // calculate command end position without \r\n.
7040
+ var commandEnd = command.End;
7041
+ var commandText = command.Text;
7042
+ for (var i = commandText.length - 1; i >= 0; i--) {
7043
+ if (commandText[i] != '\r' && commandText[i] != '\n') {
7044
+ break;
7045
+ }
7046
+ else {
7047
+ commandEnd--;
7048
+ }
7049
+ }
7050
+ if (command.Start > rangeStart && command.Start < rangeEnd)
7051
+ return true;
7052
+ if (commandEnd > rangeStart && commandEnd < rangeEnd)
7053
+ return true;
7054
+ if (command.Start <= rangeStart && commandEnd >= rangeEnd)
7055
+ return true;
7056
+ });
7057
+ if (commands.length === 0) {
7058
+ return { formattedCommands: [] };
7059
+ }
7060
+ var formattedCommands = commands.map(function (command) {
7061
+ var _a, _b;
7062
+ var formatterOptions = _this._languageSettings.formatter;
7063
+ var formatter = Kusto.Language.Editor.FormattingOptions.Default
7064
+ .WithIndentationSize((_a = formatterOptions === null || formatterOptions === void 0 ? void 0 : formatterOptions.indentationSize) !== null && _a !== void 0 ? _a : 4)
7065
+ .WithInsertMissingTokens(false)
7066
+ .WithPipeOperatorStyle((_b = _this.toPlacementStyle(formatterOptions === null || formatterOptions === void 0 ? void 0 : formatterOptions.pipeOperatorStyle)) !== null && _b !== void 0 ? _b : k2.PlacementStyle.Smart)
7067
+ .WithSemicolonStyle(Kusto.Language.Editor.PlacementStyle.None)
7068
+ .WithBrackettingStyle(k2.BrackettingStyle.Diagonal);
7069
+ if (rangeStart == null || rangeEnd == null || (rangeStart === command.Start && rangeEnd === command.End)) {
7070
+ var result = command.Service.GetFormattedText(formatter);
7071
+ return result.Text;
7072
+ }
7073
+ return command.Service.GetFormattedText(formatter).Text;
7074
+ });
7075
+ var originalRange = this.createRange(document, commands[0].Start, commands[commands.length - 1].End);
7076
+ return { formattedCommands: formattedCommands, originalRange: originalRange };
7077
+ };
7078
+ KustoLanguageService.prototype.getCommandsInDocumentV2 = function (document) {
7079
+ var script = this.parseDocumentV2(document);
7080
+ var commands = this.toArray(script.Blocks).filter(function (command) { return command.Text.trim() != ''; });
7081
+ return Promise.resolve(commands.map(function (_a) {
7082
+ var Start = _a.Start, End = _a.End, Text = _a.Text;
7083
+ return ({ absoluteStart: Start, absoluteEnd: End, text: Text });
7084
+ }));
7085
+ };
7086
+ KustoLanguageService.prototype.getClientDirective = function (text) {
7087
+ var outParam = { v: null };
7088
+ var isClientDirective = k.CslCommandParser.IsClientDirective(text, outParam);
7089
+ return Promise.resolve({
7090
+ isClientDirective: isClientDirective,
7091
+ directiveWithoutLeadingComments: outParam.v,
7092
+ });
7093
+ };
7094
+ KustoLanguageService.prototype.getAdminCommand = function (text) {
7095
+ var outParam = { v: null };
7096
+ var isAdminCommand = k.CslCommandParser.IsAdminCommand$1(text, outParam);
7097
+ return Promise.resolve({
7098
+ isAdminCommand: isAdminCommand,
7099
+ adminCommandWithoutLeadingComments: outParam.v,
7100
+ });
7101
+ };
7102
+ KustoLanguageService.prototype.findDefinition = function (document, position) {
7103
+ if (!document || !this.isIntellisenseV2()) {
7104
+ return Promise.resolve([]);
7105
+ }
7106
+ var script = this.parseDocumentV2(document);
7107
+ var cursorOffset = document.offsetAt(position);
7108
+ var currentBlock = this.getCurrentCommandV2(script, cursorOffset);
7109
+ if (!currentBlock) {
7110
+ return Promise.resolve([]);
7111
+ }
7112
+ var relatedInfo = currentBlock.Service.GetRelatedElements(document.offsetAt(position));
7113
+ var relatedElements = this.toArray(relatedInfo.Elements);
7114
+ var definition = relatedElements[0];
7115
+ if (!definition) {
7116
+ return Promise.resolve([]);
7117
+ }
7118
+ var start = document.positionAt(definition.Start);
7119
+ var end = document.positionAt(definition.End);
7120
+ var range = ls.Range.create(start, end);
7121
+ var location = ls.Location.create(document.uri, range);
7122
+ return Promise.resolve([location]);
7123
+ };
7124
+ KustoLanguageService.prototype.findReferences = function (document, position) {
7125
+ if (!document || !this.isIntellisenseV2()) {
7126
+ return Promise.resolve([]);
7127
+ }
7128
+ var script = this.parseDocumentV2(document);
7129
+ var cursorOffset = document.offsetAt(position);
7130
+ var currentBlock = this.getCurrentCommandV2(script, cursorOffset);
7131
+ if (!currentBlock) {
7132
+ return Promise.resolve([]);
7133
+ }
7134
+ var relatedInfo = currentBlock.Service.GetRelatedElements(document.offsetAt(position));
7135
+ var relatedElements = this.toArray(relatedInfo.Elements);
7136
+ if (!relatedElements || relatedElements.length == 0) {
7137
+ return Promise.resolve([]);
7138
+ }
7139
+ var references = relatedElements.map(function (relatedElement) {
7140
+ var start = document.positionAt(relatedElement.Start);
7141
+ var end = document.positionAt(relatedElement.End);
7142
+ var range = ls.Range.create(start, end);
7143
+ var location = ls.Location.create(document.uri, range);
7144
+ return location;
7145
+ });
7146
+ return Promise.resolve(references);
7147
+ };
7148
+ KustoLanguageService.prototype.getQueryParams = function (document, cursorOffset) {
7149
+ if (!document || !this.isIntellisenseV2()) {
7150
+ return Promise.resolve([]);
7151
+ }
7152
+ var script = this.parseDocumentV2(document);
7153
+ var parsedAndAnalyzed = this.parseAndAnalyze(document, cursorOffset);
7154
+ var queryParamStatements = this.toArray(parsedAndAnalyzed.Syntax.GetDescendants(Kusto.Language.Syntax.QueryParametersStatement));
7155
+ if (!queryParamStatements || queryParamStatements.length == 0) {
7156
+ return Promise.resolve([]);
7157
+ }
7158
+ var queryParams = [];
7159
+ queryParamStatements.forEach(function (paramStatement) {
7160
+ paramStatement.WalkElements(function (el) {
7161
+ return el.ReferencedSymbol && el.ReferencedSymbol.Type
7162
+ ? queryParams.push({ name: el.ReferencedSymbol.Name, type: el.ReferencedSymbol.Type.Name })
7163
+ : undefined;
7164
+ });
7165
+ });
7166
+ return Promise.resolve(queryParams);
7167
+ };
7168
+ KustoLanguageService.prototype.getRenderInfo = function (document, cursorOffset) {
7169
+ var _this = this;
7170
+ var parsedAndAnalyzed = this.parseAndAnalyze(document, cursorOffset);
7171
+ if (!parsedAndAnalyzed) {
7172
+ return Promise.resolve(undefined);
7173
+ }
7174
+ var renderStatements = this.toArray(parsedAndAnalyzed.Syntax.GetDescendants(Kusto.Language.Syntax.RenderOperator));
7175
+ if (!renderStatements || renderStatements.length === 0) {
7176
+ return Promise.resolve(undefined);
7177
+ }
7178
+ // assuming a single render statement
7179
+ var renderStatement = renderStatements[0];
7180
+ // Start and end relative to block start.
7181
+ var startOffset = renderStatement.TextStart;
7182
+ var endOffset = renderStatement.End;
7183
+ var visualization = renderStatement.ChartType.Text;
7184
+ var withClause = renderStatement.WithClause;
7185
+ if (!withClause) {
7186
+ var info = {
7187
+ options: {
7188
+ visualization: visualization,
7189
+ },
7190
+ location: { startOffset: startOffset, endOffset: endOffset },
7191
+ };
7192
+ return Promise.resolve(info);
7193
+ }
7194
+ var properties = this.toArray(withClause.Properties);
7195
+ var props = properties.reduce(function (prev, property) {
7196
+ var name = property.Element$1.Name.SimpleName;
7197
+ switch (name) {
7198
+ case 'xcolumn':
7199
+ var value = property.Element$1.Expression.ReferencedSymbol.Name;
7200
+ prev[name] = value;
7201
+ break;
7202
+ case 'ycolumns':
7203
+ case 'anomalycolumns':
7204
+ var nameNodes = _this.toArray(property.Element$1.Expression.Names);
7205
+ var values = nameNodes.map(function (nameNode) { return nameNode.Element$1.SimpleName; });
7206
+ prev[name] = values;
7207
+ break;
7208
+ case 'ymin':
7209
+ case 'ymax':
7210
+ var numericVal = parseFloat(property.Element$1.Expression.ConstantValue);
7211
+ prev[name] = numericVal;
7212
+ break;
7213
+ case 'title':
7214
+ case 'xtitle':
7215
+ case 'ytitle':
7216
+ case 'visualization':
7217
+ case 'series':
7218
+ var strVal = property.Element$1.Expression.ConstantValue;
7219
+ prev[name] = strVal;
7220
+ break;
7221
+ case 'xaxis':
7222
+ case 'yaxis':
7223
+ var scale = property.Element$1.Expression.ConstantValue;
7224
+ prev[name] = scale;
7225
+ break;
7226
+ case 'legend':
7227
+ var legend = property.Element$1.Expression.ConstantValue;
7228
+ prev[name] = legend;
7229
+ break;
7230
+ case 'ySplit':
7231
+ var split = property.Element$1.Expression.ConstantValue;
7232
+ prev[name] = split;
7233
+ break;
7234
+ case 'accumulate':
7235
+ var accumulate = property.Element$1.Expression.ConstantValue;
7236
+ prev[name] = accumulate;
7237
+ break;
7238
+ case 'kind':
7239
+ var val = property.Element$1.Expression.ConstantValue;
7240
+ prev[name] = val;
7241
+ break;
7242
+ default:
7243
+ assertNever(name);
7244
+ }
7245
+ return prev;
7246
+ }, {});
7247
+ var renderOptions = __assign({ visualization: visualization }, props);
7248
+ var renderInfo = {
7249
+ options: renderOptions,
7250
+ location: { startOffset: startOffset, endOffset: endOffset },
7251
+ };
7252
+ return Promise.resolve(renderInfo);
7253
+ };
7254
+ KustoLanguageService.prototype.getReferencedGlobalParams = function (document, cursorOffset) {
7255
+ if (!document || !this.isIntellisenseV2()) {
7256
+ return Promise.resolve([]);
7257
+ }
7258
+ var script = this.parseDocumentV2(document);
7259
+ var currentBlock = this.getCurrentCommandV2(script, cursorOffset);
7260
+ if (!currentBlock) {
7261
+ return Promise.resolve([]);
7262
+ }
7263
+ var text = currentBlock.Text;
7264
+ var parsedAndAnalyzed = Kusto.Language.KustoCode.ParseAndAnalyze(text, this._kustoJsSchemaV2);
7265
+ // We take the ambient parameters
7266
+ var ambientParameters = this.toArray(this._kustoJsSchemaV2.Parameters);
7267
+ // We take all referenced symbols in the query
7268
+ var referencedSymbols = this.toArray(parsedAndAnalyzed.Syntax.GetDescendants(Kusto.Language.Syntax.Expression))
7269
+ .filter(function (epression) { return epression.ReferencedSymbol !== null; })
7270
+ .map(function (x) { return x.ReferencedSymbol; });
7271
+ // The Intersection between them is the ambient parameters that are used in the query.
7272
+ // Note: Ideally we would use Set here (or at least array.Include), but were' compiling down to es2015.
7273
+ var intersection = referencedSymbols.filter(function (referencedSymbol) {
7274
+ return ambientParameters.filter(function (ambientParameter) { return ambientParameter === referencedSymbol; }).length > 0;
7275
+ });
7276
+ var result = intersection.map(function (param) { return ({ name: param.Name, type: param.Type.Name }); });
7277
+ return Promise.resolve(result);
7278
+ };
7279
+ KustoLanguageService.prototype.getGlobalParams = function (document) {
7280
+ if (!this.isIntellisenseV2()) {
7281
+ return Promise.resolve([]);
7282
+ }
7283
+ var params = this.toArray(this._kustoJsSchemaV2.Parameters);
7284
+ var result = params.map(function (param) { return ({ name: param.Name, type: param.Type.Name }); });
7285
+ return Promise.resolve(result);
7286
+ };
7287
+ KustoLanguageService.prototype.doRename = function (document, position, newName) {
7288
+ var _a;
7289
+ if (!document || !this.isIntellisenseV2()) {
7290
+ return Promise.resolve(undefined);
7291
+ }
7292
+ var script = this.parseDocumentV2(document);
7293
+ var cursorOffset = document.offsetAt(position);
7294
+ var currentBLock = this.getCurrentCommandV2(script, cursorOffset);
7295
+ if (!currentBLock) {
7296
+ return Promise.resolve(undefined);
7297
+ }
7298
+ var relatedInfo = currentBLock.Service.GetRelatedElements(document.offsetAt(position));
7299
+ var relatedElements = this.toArray(relatedInfo.Elements);
7300
+ var declarations = relatedElements.filter(function (e) { return e.Kind == k2.RelatedElementKind.Declaration; });
7301
+ // A declaration must be one of the elements
7302
+ if (!declarations || declarations.length == 0) {
7303
+ return Promise.resolve(undefined);
7304
+ }
7305
+ var edits = relatedElements.map(function (edit) {
7306
+ var start = document.positionAt(edit.Start);
7307
+ var end = document.positionAt(edit.End);
7308
+ var range = ls.Range.create(start, end);
7309
+ return ls.TextEdit.replace(range, newName);
7310
+ });
7311
+ // create a workspace edit
7312
+ var workspaceEdit = { changes: (_a = {}, _a[document.uri] = edits, _a) };
7313
+ return Promise.resolve(workspaceEdit);
7314
+ };
7315
+ KustoLanguageService.prototype.doHover = function (document, position) {
7316
+ if (!document || !this.isIntellisenseV2()) {
7317
+ return Promise.resolve(undefined);
7318
+ }
7319
+ var script = this.parseDocumentV2(document);
7320
+ var cursorOffset = document.offsetAt(position);
7321
+ var currentBLock = this.getCurrentCommandV2(script, cursorOffset);
7322
+ if (!currentBLock) {
7323
+ return Promise.resolve(undefined);
7324
+ }
7325
+ var isSupported = currentBLock.Service.IsFeatureSupported(k2.CodeServiceFeatures.QuickInfo, cursorOffset);
7326
+ if (!isSupported) {
7327
+ return Promise.resolve(undefined);
7328
+ }
7329
+ var quickInfo = currentBLock.Service.GetQuickInfo(cursorOffset);
7330
+ if (!quickInfo || !quickInfo.Items) {
7331
+ return Promise.resolve(undefined);
7332
+ }
7333
+ var items = this.toArray(quickInfo.Items);
7334
+ if (!items) {
7335
+ return Promise.resolve(undefined);
7336
+ }
7337
+ // Errors are already shown in getDiagnostics. we don't want them in doHover.
7338
+ items = items.filter(function (item) { return item.Kind !== k2.QuickInfoKind.Error; });
7339
+ var itemsText = items.map(function (item) { return item.Text.replace('\n\n', '\n* * *\n'); });
7340
+ // separate items by horizontal line.
7341
+ var text = itemsText.join("\n* * *\n");
7342
+ // Instead of just an empty line between the first line (the signature) and the second line (the description)
7343
+ // add an horizontal line (* * * in markdown) between them.
7344
+ return Promise.resolve({ contents: text });
7345
+ };
7346
+ Object.defineProperty(KustoLanguageService, "dummySchema", {
7347
+ //#region dummy schema for manual testing
7348
+ get: function () {
7349
+ var database = {
7350
+ majorVersion: 0,
7351
+ minorVersion: 0,
7352
+ name: 'Kuskus',
7353
+ tables: [
7354
+ {
7355
+ name: 'KustoLogs',
7356
+ columns: [
7357
+ {
7358
+ name: 'Source',
7359
+ type: 'string',
7360
+ },
7361
+ {
7362
+ name: 'Timestamp',
7363
+ type: 'datetime',
7364
+ },
7365
+ {
7366
+ name: 'Directory',
7367
+ type: 'string',
7368
+ },
7369
+ ],
7370
+ docstring: 'A dummy description to test that docstring shows as expected when hovering over a table',
7371
+ },
7372
+ ],
7373
+ functions: [
7374
+ {
7375
+ name: 'HowBig',
7376
+ inputParameters: [
7377
+ {
7378
+ name: 'T',
7379
+ columns: [
7380
+ {
7381
+ name: 'Timestamp',
7382
+ type: 'System.DateTime',
7383
+ cslType: 'datetime',
7384
+ },
7385
+ ],
7386
+ },
7387
+ ],
7388
+ docstring: 'A dummy description to test that docstring shows as expected when hovering over a function',
7389
+ 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}",
7390
+ },
7391
+ {
7392
+ name: 'FindCIDPast24h',
7393
+ inputParameters: [
7394
+ {
7395
+ name: 'clientActivityId',
7396
+ type: 'System.String',
7397
+ cslType: 'string',
7398
+ },
7399
+ ],
7400
+ body: '{ KustoLogs | where Timestamp > now(-1d) | where ClientActivityId == clientActivityId} ',
7401
+ },
7402
+ ],
7403
+ };
7404
+ var languageServiceSchema = {
7405
+ clusterType: 'Engine',
7406
+ cluster: {
7407
+ connectionString: 'https://kuskus.kusto.windows.net;fed=true',
7408
+ databases: [database],
7409
+ },
7410
+ database: database,
7411
+ };
7412
+ return languageServiceSchema;
7413
+ },
7414
+ enumerable: false,
7415
+ configurable: true
7416
+ });
7417
+ //#endregion
7418
+ KustoLanguageService.convertToEntityDataType = function (kustoType) { };
7419
+ /**
7420
+ * We do not want to expose Bridge.Net generated schema, so we expose a cleaner javascript schema.
7421
+ * Here it gets converted to the bridge.Net schema
7422
+ * @param schema Language Service schema
7423
+ */
7424
+ KustoLanguageService.convertToKustoJsSchema = function (schema) {
7425
+ switch (schema.clusterType) {
7426
+ case 'Engine':
7427
+ var currentDatabaseName_1 = schema.database ? schema.database.name : undefined;
7428
+ var kCluster = new k.KustoIntelliSenseClusterEntity();
7429
+ var kDatabaseInContext_1 = undefined;
7430
+ kCluster.ConnectionString = schema.cluster.connectionString;
7431
+ var databases_1 = [];
7432
+ schema.cluster.databases.forEach(function (database) {
7433
+ var kDatabase = new k.KustoIntelliSenseDatabaseEntity();
7434
+ kDatabase.Name = database.name;
7435
+ var tables = [];
7436
+ database.tables.forEach(function (table) {
7437
+ var kTable = new k.KustoIntelliSenseTableEntity();
7438
+ kTable.Name = table.name;
7439
+ var cols = [];
7440
+ table.columns.forEach(function (column) {
7441
+ var kColumn = new k.KustoIntelliSenseColumnEntity();
7442
+ kColumn.Name = column.name;
7443
+ kColumn.TypeCode = k.EntityDataType[schema_1.getEntityDataTypeFromCslType(column.type)];
7444
+ cols.push(kColumn);
7445
+ });
7446
+ kTable.Columns = new Bridge.ArrayEnumerable(cols);
7447
+ tables.push(kTable);
7448
+ });
7449
+ var functions = [];
7450
+ database.functions.forEach(function (fn) {
7451
+ var kFunction = new k.KustoIntelliSenseFunctionEntity();
7452
+ (kFunction.Name = fn.name),
7453
+ (kFunction.CallName = s.getCallName(fn)),
7454
+ (kFunction.Expression = s.getExpression(fn)),
7455
+ functions.push(kFunction);
7456
+ });
7457
+ kDatabase.Tables = new Bridge.ArrayEnumerable(tables);
7458
+ kDatabase.Functions = new Bridge.ArrayEnumerable(functions);
7459
+ databases_1.push(kDatabase);
7460
+ if (database.name == currentDatabaseName_1) {
7461
+ kDatabaseInContext_1 = kDatabase;
7462
+ }
7463
+ });
7464
+ kCluster.Databases = new Bridge.ArrayEnumerable(databases_1);
7465
+ var kSchema = new k.KustoIntelliSenseQuerySchema(kCluster, kDatabaseInContext_1);
7466
+ return kSchema;
7467
+ case 'ClusterManager':
7468
+ var accounts = schema.accounts.map(function (account) {
7469
+ var kAccount = new k.KustoIntelliSenseAccountEntity();
7470
+ kAccount.Name = account;
7471
+ return kAccount;
7472
+ });
7473
+ var services = schema.services.map(function (service) {
7474
+ var kService = new k.KustoIntelliSenseServiceEntity();
7475
+ kService.Name = service;
7476
+ return kService;
7477
+ });
7478
+ var connectionString = schema.connectionString;
7479
+ var result = {
7480
+ accounts: accounts,
7481
+ services: services,
7482
+ connectionString: connectionString,
7483
+ };
7484
+ return result;
7485
+ case 'DataManagement':
7486
+ return undefined;
7487
+ default:
7488
+ return assertNever(schema);
7489
+ }
7490
+ };
7491
+ /**
7492
+ * Returns something like '(x: string, y: datetime)'
7493
+ * @param params scalar parameters
7494
+ */
7495
+ KustoLanguageService.scalarParametersToSignature = function (params) {
7496
+ var signatureWithoutParens = params.map(function (param) { return param.name + ": " + param.cslType; }).join(', ');
7497
+ return "(" + signatureWithoutParens + ")";
7498
+ };
7499
+ /**
7500
+ * Returns something like '(x: string, T: (y: int))'
7501
+ * @param params input parameters (tabular or scalar)
7502
+ */
7503
+ KustoLanguageService.inputParameterToSignature = function (params) {
7504
+ var _this = this;
7505
+ var signatureWithoutParens = params
7506
+ .map(function (param) {
7507
+ if (param.columns) {
7508
+ var tableSignature = _this.scalarParametersToSignature(param.columns);
7509
+ return param.name + ": " + tableSignature;
7510
+ }
7511
+ else {
7512
+ return param.name + ": " + param.cslType;
7513
+ }
7514
+ })
7515
+ .join(', ');
7516
+ return "(" + signatureWithoutParens + ")";
7517
+ };
7518
+ /**
7519
+ * converts a function definition to a let statement.
7520
+ * @param fn function
7521
+ */
7522
+ KustoLanguageService.toLetStatement = function (fn) {
7523
+ var signature = this.inputParameterToSignature(fn.inputParameters);
7524
+ return "let " + fn.name + " = " + signature + " " + fn.body;
7525
+ };
7526
+ KustoLanguageService.createColumnSymbol = function (col) {
7527
+ return new sym.ColumnSymbol(col.name, sym.ScalarTypes.GetSymbol(schema_1.getCslTypeNameFromClrType(col.type)), col.docstring);
7528
+ };
7529
+ KustoLanguageService.createParameterSymbol = function (param) {
7530
+ var paramSymbol = Kusto.Language.Symbols.ScalarTypes.GetSymbol(schema_1.getCslTypeNameFromClrType(param.type));
7531
+ return new sym.ParameterSymbol(param.name, paramSymbol, null);
7532
+ };
7533
+ KustoLanguageService.createParameter = function (param) {
7534
+ if (!param.columns) {
7535
+ var paramSymbol = Kusto.Language.Symbols.ScalarTypes.GetSymbol(schema_1.getCslTypeNameFromClrType(param.type));
7536
+ var expression = void 0;
7537
+ if (param.cslDefaultValue && typeof param.cslDefaultValue === "string") {
7538
+ var parser = parsing.QueryGrammar.From(Kusto.Language.GlobalState.Default).ConstantExpression;
7539
+ expression = parsing.SyntaxParsers.ParseFirst({ prototype: parser }, parser, param.cslDefaultValue);
7540
+ }
7541
+ return new sym.Parameter.$ctor3(param.name, paramSymbol, null, null, null, false, null, 1, 1, expression, null);
7542
+ }
7543
+ if (param.columns.length == 0) {
7544
+ return new sym.Parameter.ctor(param.name, sym.ParameterTypeKind.Tabular, sym.ArgumentKind.Expression, null, null, false, null, 1, 1, null, null);
7545
+ }
7546
+ var argumentType = new sym.TableSymbol.ctor(param.columns.map(function (col) { return KustoLanguageService.createColumnSymbol(col); }));
7547
+ return new sym.Parameter.$ctor2(param.name, argumentType);
7548
+ };
7549
+ KustoLanguageService.convertToDatabaseSymbol = function (db, globalState, addFunctions) {
7550
+ var createFunctionSymbol = function (fn) {
7551
+ var parameters = fn.inputParameters.map(function (param) {
7552
+ return KustoLanguageService.createParameter(param);
7553
+ });
7554
+ // TODO: handle outputColumns (right now it doesn't seem to be implemented for any function).
7555
+ return new sym.FunctionSymbol.$ctor16(fn.name, fn.body, KustoLanguageService.toBridgeList(parameters), fn.docstring);
7556
+ };
7557
+ var createTableSymbol = function (tbl) {
7558
+ var columnSymbols = tbl.columns.map(function (col) { return KustoLanguageService.createColumnSymbol(col); });
7559
+ var symbol = new sym.TableSymbol.$ctor3(tbl.name, columnSymbols);
7560
+ symbol.Description = tbl.docstring;
7561
+ switch (tbl.entityType) {
7562
+ case 'MaterializedViewTable':
7563
+ symbol = symbol.WithIsMaterializedView(true);
7564
+ case "ExternalTable":
7565
+ symbol = symbol.WithIsExternal(true);
7566
+ default:
7567
+ }
7568
+ return symbol;
7569
+ };
7570
+ var createDatabaseSymbol = function (db) {
7571
+ var tableSymbols = db.tables ? db.tables.map(function (tbl) { return createTableSymbol(tbl); }) : [];
7572
+ var functionSymbols = db.functions ? db.functions.map(function (fun) { return createFunctionSymbol(fun); }) : [];
7573
+ return new sym.DatabaseSymbol.ctor(db.name, tableSymbols.concat(functionSymbols));
7574
+ };
7575
+ var databaseSymbol = createDatabaseSymbol(db);
7576
+ return databaseSymbol;
7577
+ };
7578
+ KustoLanguageService.prototype.convertToKustoJsSchemaV2 = function (schema) {
7579
+ var cached = this._schemaCache[schema.cluster.connectionString];
7580
+ // create a cache entry for the cluster if non yet exists.
7581
+ if (!cached) {
7582
+ this._schemaCache[schema.cluster.connectionString] = {};
7583
+ cached = this._schemaCache[schema.cluster.connectionString];
7584
+ }
7585
+ // Remove deleted databases from cache
7586
+ var schemaDbLookup = schema.cluster.databases.reduce(function (prev, curr) { return (prev[curr.name] = curr); }, {});
7587
+ Object.keys(cached).map(function (dbName) {
7588
+ if (!schemaDbLookup[dbName]) {
7589
+ delete cached.dbName;
7590
+ }
7591
+ });
7592
+ var globalState = GlobalState.Default;
7593
+ var currentDatabaseName = schema.database ? schema.database.name : undefined;
7594
+ var databaseInContext = undefined;
7595
+ // Update out-of-data databses to cache
7596
+ var databases = schema.cluster.databases.map(function (db) {
7597
+ var shouldIncludeFunctions = db.name === currentDatabaseName;
7598
+ var cachedDb = cached[db.name];
7599
+ // This is an older version than we have, or we need to parse functions.
7600
+ if (!cachedDb ||
7601
+ cachedDb.database.majorVersion < db.majorVersion ||
7602
+ (shouldIncludeFunctions && !cachedDb.includesFunctions)) {
7603
+ // only add functions for the database in context (it's very time consuming)
7604
+ var databaseSymbol_1 = KustoLanguageService.convertToDatabaseSymbol(db, globalState, shouldIncludeFunctions);
7605
+ cached[db.name] = { database: db, symbol: databaseSymbol_1, includesFunctions: shouldIncludeFunctions };
7606
+ }
7607
+ var databaseSymbol = cached[db.name].symbol;
7608
+ if (db.name === currentDatabaseName) {
7609
+ databaseInContext = databaseSymbol;
7610
+ }
7611
+ return databaseSymbol;
7612
+ });
7613
+ // Replace new URL due to polyfill issue in IE
7614
+ // const hostname = new URL(schema.cluster.connectionString.split(';')[0]).hostname;
7615
+ var hostname = schema.cluster.connectionString.match(/(.*\/\/)?([^\/;]*)/)[2];
7616
+ var clusterName = hostname.split('.')[0];
7617
+ var clusterSymbol = new sym.ClusterSymbol.ctor(clusterName, databases);
7618
+ globalState = globalState.WithCluster(clusterSymbol);
7619
+ if (databaseInContext) {
7620
+ globalState = globalState.WithDatabase(databaseInContext);
7621
+ }
7622
+ // Inject gloabl parameters to global scope.
7623
+ if (schema.globalParameters) {
7624
+ var parameters = schema.globalParameters.map(function (param) {
7625
+ return KustoLanguageService.createParameterSymbol(param);
7626
+ });
7627
+ globalState = globalState.WithParameters(KustoLanguageService.toBridgeList(parameters));
7628
+ }
7629
+ return globalState;
7630
+ };
7631
+ KustoLanguageService.prototype.getClassificationsFromParseResult = function (offset) {
7632
+ var _this = this;
7633
+ if (offset === void 0) { offset = 0; }
7634
+ var classifications = this.toArray(this._parser.Results)
7635
+ .map(function (command) { return _this.toArray(command.Tokens); })
7636
+ .reduce(function (prev, curr) { return prev.concat(curr); }, [])
7637
+ .map(function (cslCommandToken) {
7638
+ var range = new k2.ClassifiedRange(_this.tokenKindToClassificationKind(cslCommandToken.TokenKind), cslCommandToken.AbsoluteStart + offset, cslCommandToken.Length);
7639
+ return range;
7640
+ });
7641
+ return classifications;
7642
+ };
7643
+ /**
7644
+ * trim trailing newlines from range
7645
+ */
7646
+ KustoLanguageService.trimTrailingNewlineFromRange = function (textInRange, rangeStartOffset, document, range) {
7647
+ var currentIndex = textInRange.length - 1;
7648
+ while (textInRange[currentIndex] === '\r' || textInRange[currentIndex] === '\n') {
7649
+ --currentIndex;
7650
+ }
7651
+ var newEndOffset = rangeStartOffset + currentIndex + 1;
7652
+ var newEndPosition = document.positionAt(newEndOffset);
7653
+ var newRange = ls.Range.create(range.start, newEndPosition);
7654
+ return newRange;
7655
+ };
7656
+ /**
7657
+ * Maps numbers to strings, such that if a>b numerically, f(a)>f(b) lexicograhically.
7658
+ * 1 -> "a", 26 -> "z", 27 -> "za", 28 -> "zb", 52 -> "zz", 53 ->"zza"
7659
+ * @param order - The number to be converted to a sorting-string. order should start at 1.
7660
+ * @returns A string repenting the order.
7661
+ */
7662
+ KustoLanguageService.prototype.getSortText = function (order) {
7663
+ if (order <= 0) {
7664
+ throw new RangeError("order should be a number >= 1. instead got " + order);
7665
+ }
7666
+ var sortText = '';
7667
+ var numCharacters = 26; // "z" - "a" + 1;
7668
+ var div = Math.floor(order / numCharacters);
7669
+ for (var i = 0; i < div; ++i) {
7670
+ sortText += 'z';
7671
+ }
7672
+ var reminder = order % numCharacters;
7673
+ if (reminder > 0) {
7674
+ sortText += String.fromCharCode(96 + reminder);
7675
+ }
7676
+ return sortText;
7677
+ };
7678
+ /**
7679
+ * ParseTextV1 parses the given text with the given parse mode.
7680
+ * Additionally - it will make sure not to provide rules provider for non-engine clusters
7681
+ * since the only rules provider parse can handle is the engine's. It will try to look for function
7682
+ * definitions to colorize and will throw since they're not there.
7683
+ * @param text
7684
+ * @param parseMode
7685
+ */
7686
+ KustoLanguageService.prototype.parseTextV1 = function (text, parseMode) {
7687
+ this._parser.Parse(this._schema.clusterType === 'Engine' ? this._rulesProvider : null, text, parseMode);
7688
+ };
7689
+ KustoLanguageService.prototype.parseDocumentV1 = function (document, parseMode) {
7690
+ // already parsed a later version, or better parse mode for this uri
7691
+ if (this._parsePropertiesV1 &&
7692
+ !this._parsePropertiesV1.isParseNeeded(document, this._rulesProvider, parseMode)) {
7693
+ return;
7694
+ }
7695
+ this.parseTextV1(document.getText(), parseMode);
7696
+ this._parsePropertiesV1 = new ParseProperties(document.version, document.uri, this._rulesProvider, parseMode);
7697
+ };
7698
+ KustoLanguageService.prototype.parseDocumentV2 = function (document) {
7699
+ if (this._parsePropertiesV2 && !this._parsePropertiesV2.isParseNeeded(document, this._rulesProvider)) {
7700
+ return this._script;
7701
+ }
7702
+ if (!this._script) {
7703
+ this._script = k2.CodeScript.From$1(document.getText(), this._kustoJsSchemaV2);
7704
+ }
7705
+ else {
7706
+ this._script = this._script.WithText(document.getText());
7707
+ }
7708
+ this._parsePropertiesV2 = new ParseProperties(document.version, document.uri);
7709
+ return this._script;
7710
+ };
7711
+ /**
7712
+ * Return the CslCommand that wraps the caret location, or undefined if caret is outside any command
7713
+ * @param document the document to extract the current command from
7714
+ * @param caretAbsolutePosition absolute caret position
7715
+ */
7716
+ KustoLanguageService.prototype.getCurrentCommand = function (document, caretAbsolutePosition) {
7717
+ var commands = this.toArray(this._parser.Results);
7718
+ var command = commands.filter(function (command) { return command.AbsoluteStart <= caretAbsolutePosition && command.AbsoluteEnd >= caretAbsolutePosition; })[0];
7719
+ // There is an edge case when cursor appears at the end of the command
7720
+ // which is not yet considered to be part of the parsed command (therefore: +1 for the AbsoluteEdit property)
7721
+ if (!command) {
7722
+ command = commands.filter(function (command) {
7723
+ return command.AbsoluteStart <= caretAbsolutePosition && command.AbsoluteEnd + 1 >= caretAbsolutePosition;
7724
+ })[0];
7725
+ // If we have 2 newlines in the end of the text the cursor is _probably_ at the end of the text
7726
+ // which this means that we're not actually standing on any command. Thus return null.
7727
+ if (!command || command.Text.endsWith('\r\n\r\n')) {
7728
+ return null;
7729
+ }
7730
+ }
7731
+ return command;
7732
+ };
7733
+ KustoLanguageService.prototype.getCurrentCommandV2 = function (script, offset) {
7734
+ var block = script.GetBlockAtPosition(offset);
7735
+ return block;
7736
+ };
7737
+ KustoLanguageService.prototype.getTextToInsert = function (rule, option) {
7738
+ var beforeApplyInfo = rule.GetBeforeApplyInfo(option.Value);
7739
+ var afterApplyInfo = rule.GetAfterApplyInfo(option.Value);
7740
+ // this is the basic text to be insterted,
7741
+ // but we still need to figure out where the cursor will end up after completion is applied.
7742
+ var insertText = beforeApplyInfo.Text || '' + option.Value + afterApplyInfo.Text || '';
7743
+ var insertTextFormat = ls.InsertTextFormat.PlainText;
7744
+ var snippetFinalTabStop = '$0';
7745
+ if (afterApplyInfo.OffsetToken && afterApplyInfo.OffsetPosition) {
7746
+ var tokenOffset = insertText.indexOf(afterApplyInfo.OffsetToken);
7747
+ if (tokenOffset >= 0) {
7748
+ insertText = this.insertToString(insertText, snippetFinalTabStop, tokenOffset - insertText.length + afterApplyInfo.OffsetPosition);
7749
+ insertTextFormat = ls.InsertTextFormat.Snippet;
7750
+ }
7751
+ }
7752
+ else if (afterApplyInfo.OffsetPosition) {
7753
+ // We only handle negative offsets
7754
+ insertText = this.insertToString(insertText, snippetFinalTabStop, afterApplyInfo.OffsetPosition);
7755
+ insertTextFormat = ls.InsertTextFormat.Snippet;
7756
+ }
7757
+ return { insertText: insertText, insertTextFormat: insertTextFormat };
7758
+ };
7759
+ /**
7760
+ * create a new string with stringToInsert inserted at offsetFromEnd in originalString.
7761
+ * @param originalString string to insert to
7762
+ * @param stringToInsert string to insert
7763
+ * @param offsetFromEnd a negative number that will represent offset to the left. 0 means simple concat
7764
+ */
7765
+ KustoLanguageService.prototype.insertToString = function (originalString, stringToInsert, offsetFromEnd) {
7766
+ var index = originalString.length + offsetFromEnd;
7767
+ if (offsetFromEnd >= 0 || index < 0) {
7768
+ return originalString; // Cannot insert before or after the string
7769
+ }
7770
+ var before = originalString.substring(0, index);
7771
+ var after = originalString.substring(index);
7772
+ return before + stringToInsert + after;
7773
+ };
7774
+ KustoLanguageService.prototype.getCommandWithoutLastWord = function (text) {
7775
+ var lastWordRegex = XRegExp('[\\w_]*$', 's');
7776
+ return text.replace(lastWordRegex, '');
7777
+ };
7778
+ KustoLanguageService.prototype.createRulesProvider = function (schema, clusterType) {
7779
+ var queryParameters = new (List(String))();
7780
+ var availableClusters = new (List(String))();
7781
+ this._parser = new k.CslCommandParser();
7782
+ if (clusterType == 'Engine') {
7783
+ var engineSchema = schema;
7784
+ this._rulesProvider =
7785
+ this._languageSettings && this._languageSettings.includeControlCommands
7786
+ ? new k.CslIntelliSenseRulesProvider.$ctor1(engineSchema.Cluster, engineSchema, queryParameters, availableClusters, null, true, true)
7787
+ : new k.CslQueryIntelliSenseRulesProvider.$ctor1(engineSchema.Cluster, engineSchema, queryParameters, availableClusters, null, null, null);
7788
+ return;
7789
+ }
7790
+ if (clusterType === 'DataManagement') {
7791
+ this._rulesProvider = new k.DataManagerIntelliSenseRulesProvider(null);
7792
+ return;
7793
+ }
7794
+ // This is a cluster manger
7795
+ var _a = schema, accounts = _a.accounts, services = _a.services, connectionString = _a.connectionString;
7796
+ new k.KustoIntelliSenseAccountEntity();
7797
+ new k.KustoIntelliSenseServiceEntity();
7798
+ this._rulesProvider = new k.ClusterManagerIntelliSenseRulesProvider.$ctor1(new Bridge.ArrayEnumerable(accounts), new Bridge.ArrayEnumerable(services), connectionString);
7799
+ };
7800
+ KustoLanguageService.prototype.kustoKindToLsKind = function (kustoKind) {
7801
+ var res = this._kustoKindtolsKind[kustoKind];
7802
+ return res ? res : ls.CompletionItemKind.Variable;
7803
+ };
7804
+ KustoLanguageService.prototype.kustoKindToLsKindV2 = function (kustoKind) {
7805
+ var res = this._kustoKindToLsKindV2[kustoKind];
7806
+ return res ? res : ls.CompletionItemKind.Variable;
7807
+ };
7808
+ KustoLanguageService.prototype.createRange = function (document, start, end) {
7809
+ return ls.Range.create(document.positionAt(start), document.positionAt(end));
7810
+ };
7811
+ KustoLanguageService.prototype.toArray = function (bridgeList) {
7812
+ return Bridge.toArray(bridgeList);
7813
+ };
7814
+ KustoLanguageService.toBridgeList = function (array) {
7815
+ // copied from bridge.js from the implementation of Enumerable.prototype.toList
7816
+ return new (System.Collections.Generic.List$1(System.Object).$ctor1)(array);
7817
+ };
7818
+ KustoLanguageService.prototype.tokenKindToClassificationKind = function (token) {
7819
+ var conversion = this._tokenKindToClassificationKind[token];
7820
+ return conversion || k2.ClassificationKind.PlainText;
7821
+ };
7822
+ KustoLanguageService.prototype.parseAndAnalyze = function (document, cursorOffset) {
7823
+ if (!document || !this.isIntellisenseV2()) {
7824
+ return undefined;
7825
+ }
7826
+ var script = this.parseDocumentV2(document);
7827
+ var currentBlock = this.getCurrentCommandV2(script, cursorOffset);
7828
+ if (!currentBlock) {
7829
+ return undefined;
7830
+ }
7831
+ var text = currentBlock.Text;
7832
+ var parsedAndAnalyzed = Kusto.Language.KustoCode.ParseAndAnalyze(text, this._kustoJsSchemaV2);
7833
+ return parsedAndAnalyzed;
7834
+ };
7835
+ return KustoLanguageService;
7836
+ }());
7837
+ var languageService = new KustoLanguageService(KustoLanguageService.dummySchema, {
7838
+ includeControlCommands: true,
7839
+ useIntellisenseV2: true,
7840
+ useSemanticColorization: true,
7841
+ });
7842
+ /**
7843
+ * Obtain an instance of the kusto language service.
7844
+ */
7845
+ function getKustoLanguageService() {
7846
+ return languageService;
7847
+ }
7848
+ exports.getKustoLanguageService = getKustoLanguageService;
7849
+ });
7827
7850
 
7828
- define('vs/language/kusto/kustoWorker',["require", "exports", "./languageService/kustoLanguageService", "vscode-languageserver-types"], function (require, exports, kustoService, ls) {
7829
- "use strict";
7830
- Object.defineProperty(exports, "__esModule", { value: true });
7831
- exports.create = exports.KustoWorker = void 0;
7832
- var KustoWorker = /** @class */ (function () {
7833
- function KustoWorker(ctx, createData) {
7834
- this._ctx = ctx;
7835
- this._languageSettings = createData.languageSettings;
7836
- this._languageService = kustoService.getKustoLanguageService();
7837
- this._languageService.configure(this._languageSettings);
7838
- }
7839
- // --- language service host ---------------
7840
- KustoWorker.prototype.setSchema = function (schema) {
7841
- return this._languageService.setSchema(schema);
7842
- };
7843
- KustoWorker.prototype.setSchemaFromShowSchema = function (schema, clusterConnectionString, databaseInContextName) {
7844
- return this._languageService.setSchemaFromShowSchema(schema, clusterConnectionString, databaseInContextName);
7845
- };
7846
- KustoWorker.prototype.normalizeSchema = function (schema, clusterConnectionString, databaseInContextName) {
7847
- return this._languageService.normalizeSchema(schema, clusterConnectionString, databaseInContextName);
7848
- };
7849
- KustoWorker.prototype.getSchema = function () {
7850
- return this._languageService.getSchema();
7851
- };
7852
- KustoWorker.prototype.getCommandInContext = function (uri, cursorOffest) {
7853
- var document = this._getTextDocument(uri);
7854
- if (!document) {
7855
- console.error("getCommandInContext: document is " + document + ". uri is " + uri);
7856
- return null;
7857
- }
7858
- var commandInContext = this._languageService.getCommandInContext(document, cursorOffest);
7859
- if (commandInContext === undefined) {
7860
- return null;
7861
- }
7862
- return commandInContext;
7863
- };
7864
- KustoWorker.prototype.getQueryParams = function (uri, cursorOffest) {
7865
- var document = this._getTextDocument(uri);
7866
- if (!document) {
7867
- console.error("getQueryParams: document is " + document + ". uri is " + uri);
7868
- return null;
7869
- }
7870
- var queryParams = this._languageService.getQueryParams(document, cursorOffest);
7871
- if (queryParams === undefined) {
7872
- return null;
7873
- }
7874
- return queryParams;
7875
- };
7876
- KustoWorker.prototype.getGlobalParams = function (uri) {
7877
- var document = this._getTextDocument(uri);
7878
- if (!document) {
7879
- console.error("getGLobalParams: document is " + document + ". uri is " + uri);
7880
- return null;
7881
- }
7882
- var globalParams = this._languageService.getGlobalParams(document);
7883
- if (globalParams === undefined) {
7884
- return null;
7885
- }
7886
- return globalParams;
7887
- };
7888
- KustoWorker.prototype.getReferencedGlobalParams = function (uri, cursorOffest) {
7889
- var document = this._getTextDocument(uri);
7890
- if (!document) {
7891
- console.error("getReferencedGlobalParams: document is " + document + ". uri is " + uri);
7892
- return null;
7893
- }
7894
- var referencedParams = this._languageService.getReferencedGlobalParams(document, cursorOffest);
7895
- if (referencedParams === undefined) {
7896
- return null;
7897
- }
7898
- return referencedParams;
7899
- };
7900
- KustoWorker.prototype.getRenderInfo = function (uri, cursorOffset) {
7901
- var document = this._getTextDocument(uri);
7902
- if (!document) {
7903
- console.error("getRenderInfo: document is " + document + ". uri is " + uri);
7904
- }
7905
- return this._languageService.getRenderInfo(document, cursorOffset).then(function (result) {
7906
- if (!result) {
7907
- return null;
7908
- }
7909
- return result;
7910
- });
7911
- };
7912
- /**
7913
- * Get command in cotext and the command range.
7914
- * This method will basically convert generate microsoft language service interface to monaco interface.
7915
- * @param uri document URI
7916
- * @param cursorOffset offset from start of document to cursor
7917
- */
7918
- KustoWorker.prototype.getCommandAndLocationInContext = function (uri, cursorOffset) {
7919
- var document = this._getTextDocument(uri);
7920
- if (!document) {
7921
- console.error("getCommandAndLocationInContext: document is " + document + ". uri is " + uri);
7922
- return Promise.resolve(null);
7923
- }
7924
- return this._languageService.getCommandAndLocationInContext(document, cursorOffset).then(function (result) {
7925
- if (!result) {
7926
- return null;
7927
- }
7928
- // convert to monaco object.
7929
- var text = result.text, _a = result.location.range, start = _a.start, end = _a.end;
7930
- var range = new monaco.Range(start.line + 1, start.character + 1, end.line + 1, end.character + 1);
7931
- return {
7932
- range: range,
7933
- text: text,
7934
- };
7935
- });
7936
- };
7937
- KustoWorker.prototype.getCommandsInDocument = function (uri) {
7938
- var document = this._getTextDocument(uri);
7939
- if (!document) {
7940
- console.error("getCommandInDocument: document is " + document + ". uri is " + uri);
7941
- return null;
7942
- }
7943
- return this._languageService.getCommandsInDocument(document);
7944
- };
7945
- KustoWorker.prototype.doComplete = function (uri, position) {
7946
- var document = this._getTextDocument(uri);
7947
- if (!document) {
7948
- return null;
7949
- }
7950
- var completions = this._languageService.doComplete(document, position);
7951
- return completions;
7952
- };
7953
- KustoWorker.prototype.doValidation = function (uri, intervals) {
7954
- var document = this._getTextDocument(uri);
7955
- var diagnostics = this._languageService.doValidation(document, intervals);
7956
- return diagnostics;
7957
- };
7958
- KustoWorker.prototype.doRangeFormat = function (uri, range) {
7959
- var document = this._getTextDocument(uri);
7960
- var formatted = this._languageService.doRangeFormat(document, range);
7961
- return formatted;
7962
- };
7963
- KustoWorker.prototype.doFolding = function (uri) {
7964
- var document = this._getTextDocument(uri);
7965
- var folding = this._languageService.doFolding(document);
7966
- return folding;
7967
- };
7968
- KustoWorker.prototype.doDocumentFormat = function (uri) {
7969
- var document = this._getTextDocument(uri);
7970
- var formatted = this._languageService.doDocumentFormat(document);
7971
- return formatted;
7972
- };
7973
- KustoWorker.prototype.doCurrentCommandFormat = function (uri, caretPosition) {
7974
- var document = this._getTextDocument(uri);
7975
- var formatted = this._languageService.doCurrentCommandFormat(document, caretPosition);
7976
- return formatted;
7977
- };
7978
- // Colorize document. if offsets provided, will only colorize commands at these offsets. otherwise - will color the entire document.
7979
- KustoWorker.prototype.doColorization = function (uri, colorizationIntervals) {
7980
- var document = this._getTextDocument(uri);
7981
- var colorizationInfo = this._languageService.doColorization(document, colorizationIntervals);
7982
- return colorizationInfo;
7983
- };
7984
- KustoWorker.prototype.getClientDirective = function (text) {
7985
- return this._languageService.getClientDirective(text);
7986
- };
7987
- KustoWorker.prototype.getAdminCommand = function (text) {
7988
- return this._languageService.getAdminCommand(text);
7989
- };
7990
- KustoWorker.prototype.findDefinition = function (uri, position) {
7991
- var document = this._getTextDocument(uri);
7992
- var definition = this._languageService.findDefinition(document, position);
7993
- return definition;
7994
- };
7995
- KustoWorker.prototype.findReferences = function (uri, position) {
7996
- var document = this._getTextDocument(uri);
7997
- var references = this._languageService.findReferences(document, position);
7998
- return references;
7999
- };
8000
- KustoWorker.prototype.doRename = function (uri, position, newName) {
8001
- var document = this._getTextDocument(uri);
8002
- var workspaceEdit = this._languageService.doRename(document, position, newName);
8003
- return workspaceEdit;
8004
- };
8005
- KustoWorker.prototype.doHover = function (uri, position) {
8006
- var document = this._getTextDocument(uri);
8007
- var hover = this._languageService.doHover(document, position);
8008
- return hover;
8009
- };
8010
- KustoWorker.prototype.setParameters = function (parameters) {
8011
- return this._languageService.setParameters(parameters);
8012
- };
8013
- KustoWorker.prototype._getTextDocument = function (uri) {
8014
- var models = this._ctx.getMirrorModels();
8015
- for (var _i = 0, models_1 = models; _i < models_1.length; _i++) {
8016
- var model = models_1[_i];
8017
- if (model.uri.toString() === uri) {
8018
- return ls.TextDocument.create(uri, this._languageId, model.version, model.getValue());
8019
- }
8020
- }
8021
- return null;
8022
- };
8023
- return KustoWorker;
8024
- }());
8025
- exports.KustoWorker = KustoWorker;
8026
- function create(ctx, createData) {
8027
- return new KustoWorker(ctx, createData);
8028
- }
8029
- exports.create = create;
8030
- });
7851
+ define('vs/language/kusto/kustoWorker',["require", "exports", "./languageService/kustoLanguageService", "vscode-languageserver-types"], function (require, exports, kustoService, ls) {
7852
+ "use strict";
7853
+ Object.defineProperty(exports, "__esModule", { value: true });
7854
+ exports.create = exports.KustoWorker = void 0;
7855
+ var KustoWorker = /** @class */ (function () {
7856
+ function KustoWorker(ctx, createData) {
7857
+ this._ctx = ctx;
7858
+ this._languageSettings = createData.languageSettings;
7859
+ this._languageService = kustoService.getKustoLanguageService();
7860
+ this._languageService.configure(this._languageSettings);
7861
+ }
7862
+ // --- language service host ---------------
7863
+ KustoWorker.prototype.setSchema = function (schema) {
7864
+ return this._languageService.setSchema(schema);
7865
+ };
7866
+ KustoWorker.prototype.setSchemaFromShowSchema = function (schema, clusterConnectionString, databaseInContextName) {
7867
+ return this._languageService.setSchemaFromShowSchema(schema, clusterConnectionString, databaseInContextName);
7868
+ };
7869
+ KustoWorker.prototype.normalizeSchema = function (schema, clusterConnectionString, databaseInContextName) {
7870
+ return this._languageService.normalizeSchema(schema, clusterConnectionString, databaseInContextName);
7871
+ };
7872
+ KustoWorker.prototype.getSchema = function () {
7873
+ return this._languageService.getSchema();
7874
+ };
7875
+ KustoWorker.prototype.getCommandInContext = function (uri, cursorOffest) {
7876
+ var document = this._getTextDocument(uri);
7877
+ if (!document) {
7878
+ console.error("getCommandInContext: document is " + document + ". uri is " + uri);
7879
+ return null;
7880
+ }
7881
+ var commandInContext = this._languageService.getCommandInContext(document, cursorOffest);
7882
+ if (commandInContext === undefined) {
7883
+ return null;
7884
+ }
7885
+ return commandInContext;
7886
+ };
7887
+ KustoWorker.prototype.getQueryParams = function (uri, cursorOffest) {
7888
+ var document = this._getTextDocument(uri);
7889
+ if (!document) {
7890
+ console.error("getQueryParams: document is " + document + ". uri is " + uri);
7891
+ return null;
7892
+ }
7893
+ var queryParams = this._languageService.getQueryParams(document, cursorOffest);
7894
+ if (queryParams === undefined) {
7895
+ return null;
7896
+ }
7897
+ return queryParams;
7898
+ };
7899
+ KustoWorker.prototype.getGlobalParams = function (uri) {
7900
+ var document = this._getTextDocument(uri);
7901
+ if (!document) {
7902
+ console.error("getGLobalParams: document is " + document + ". uri is " + uri);
7903
+ return null;
7904
+ }
7905
+ var globalParams = this._languageService.getGlobalParams(document);
7906
+ if (globalParams === undefined) {
7907
+ return null;
7908
+ }
7909
+ return globalParams;
7910
+ };
7911
+ KustoWorker.prototype.getReferencedGlobalParams = function (uri, cursorOffest) {
7912
+ var document = this._getTextDocument(uri);
7913
+ if (!document) {
7914
+ console.error("getReferencedGlobalParams: document is " + document + ". uri is " + uri);
7915
+ return null;
7916
+ }
7917
+ var referencedParams = this._languageService.getReferencedGlobalParams(document, cursorOffest);
7918
+ if (referencedParams === undefined) {
7919
+ return null;
7920
+ }
7921
+ return referencedParams;
7922
+ };
7923
+ KustoWorker.prototype.getRenderInfo = function (uri, cursorOffset) {
7924
+ var document = this._getTextDocument(uri);
7925
+ if (!document) {
7926
+ console.error("getRenderInfo: document is " + document + ". uri is " + uri);
7927
+ }
7928
+ return this._languageService.getRenderInfo(document, cursorOffset).then(function (result) {
7929
+ if (!result) {
7930
+ return null;
7931
+ }
7932
+ return result;
7933
+ });
7934
+ };
7935
+ /**
7936
+ * Get command in cotext and the command range.
7937
+ * This method will basically convert generate microsoft language service interface to monaco interface.
7938
+ * @param uri document URI
7939
+ * @param cursorOffset offset from start of document to cursor
7940
+ */
7941
+ KustoWorker.prototype.getCommandAndLocationInContext = function (uri, cursorOffset) {
7942
+ var document = this._getTextDocument(uri);
7943
+ if (!document) {
7944
+ console.error("getCommandAndLocationInContext: document is " + document + ". uri is " + uri);
7945
+ return Promise.resolve(null);
7946
+ }
7947
+ return this._languageService.getCommandAndLocationInContext(document, cursorOffset).then(function (result) {
7948
+ if (!result) {
7949
+ return null;
7950
+ }
7951
+ // convert to monaco object.
7952
+ var text = result.text, _a = result.location.range, start = _a.start, end = _a.end;
7953
+ var range = new monaco.Range(start.line + 1, start.character + 1, end.line + 1, end.character + 1);
7954
+ return {
7955
+ range: range,
7956
+ text: text,
7957
+ };
7958
+ });
7959
+ };
7960
+ KustoWorker.prototype.getCommandsInDocument = function (uri) {
7961
+ var document = this._getTextDocument(uri);
7962
+ if (!document) {
7963
+ console.error("getCommandInDocument: document is " + document + ". uri is " + uri);
7964
+ return null;
7965
+ }
7966
+ return this._languageService.getCommandsInDocument(document);
7967
+ };
7968
+ KustoWorker.prototype.doComplete = function (uri, position) {
7969
+ var document = this._getTextDocument(uri);
7970
+ if (!document) {
7971
+ return null;
7972
+ }
7973
+ var completions = this._languageService.doComplete(document, position);
7974
+ return completions;
7975
+ };
7976
+ KustoWorker.prototype.doValidation = function (uri, intervals) {
7977
+ var document = this._getTextDocument(uri);
7978
+ var diagnostics = this._languageService.doValidation(document, intervals);
7979
+ return diagnostics;
7980
+ };
7981
+ KustoWorker.prototype.doRangeFormat = function (uri, range) {
7982
+ var document = this._getTextDocument(uri);
7983
+ var formatted = this._languageService.doRangeFormat(document, range);
7984
+ return formatted;
7985
+ };
7986
+ KustoWorker.prototype.doFolding = function (uri) {
7987
+ var document = this._getTextDocument(uri);
7988
+ var folding = this._languageService.doFolding(document);
7989
+ return folding;
7990
+ };
7991
+ KustoWorker.prototype.doDocumentFormat = function (uri) {
7992
+ var document = this._getTextDocument(uri);
7993
+ var formatted = this._languageService.doDocumentFormat(document);
7994
+ return formatted;
7995
+ };
7996
+ KustoWorker.prototype.doCurrentCommandFormat = function (uri, caretPosition) {
7997
+ var document = this._getTextDocument(uri);
7998
+ var formatted = this._languageService.doCurrentCommandFormat(document, caretPosition);
7999
+ return formatted;
8000
+ };
8001
+ // Colorize document. if offsets provided, will only colorize commands at these offsets. otherwise - will color the entire document.
8002
+ KustoWorker.prototype.doColorization = function (uri, colorizationIntervals) {
8003
+ var document = this._getTextDocument(uri);
8004
+ var colorizationInfo = this._languageService.doColorization(document, colorizationIntervals);
8005
+ return colorizationInfo;
8006
+ };
8007
+ KustoWorker.prototype.getClientDirective = function (text) {
8008
+ return this._languageService.getClientDirective(text);
8009
+ };
8010
+ KustoWorker.prototype.getAdminCommand = function (text) {
8011
+ return this._languageService.getAdminCommand(text);
8012
+ };
8013
+ KustoWorker.prototype.findDefinition = function (uri, position) {
8014
+ var document = this._getTextDocument(uri);
8015
+ var definition = this._languageService.findDefinition(document, position);
8016
+ return definition;
8017
+ };
8018
+ KustoWorker.prototype.findReferences = function (uri, position) {
8019
+ var document = this._getTextDocument(uri);
8020
+ var references = this._languageService.findReferences(document, position);
8021
+ return references;
8022
+ };
8023
+ KustoWorker.prototype.doRename = function (uri, position, newName) {
8024
+ var document = this._getTextDocument(uri);
8025
+ var workspaceEdit = this._languageService.doRename(document, position, newName);
8026
+ return workspaceEdit;
8027
+ };
8028
+ KustoWorker.prototype.doHover = function (uri, position) {
8029
+ var document = this._getTextDocument(uri);
8030
+ var hover = this._languageService.doHover(document, position);
8031
+ return hover;
8032
+ };
8033
+ KustoWorker.prototype.setParameters = function (parameters) {
8034
+ return this._languageService.setParameters(parameters);
8035
+ };
8036
+ KustoWorker.prototype._getTextDocument = function (uri) {
8037
+ var models = this._ctx.getMirrorModels();
8038
+ for (var _i = 0, models_1 = models; _i < models_1.length; _i++) {
8039
+ var model = models_1[_i];
8040
+ if (model.uri.toString() === uri) {
8041
+ return ls.TextDocument.create(uri, this._languageId, model.version, model.getValue());
8042
+ }
8043
+ }
8044
+ return null;
8045
+ };
8046
+ return KustoWorker;
8047
+ }());
8048
+ exports.KustoWorker = KustoWorker;
8049
+ function create(ctx, createData) {
8050
+ return new KustoWorker(ctx, createData);
8051
+ }
8052
+ exports.create = create;
8053
+ });
8031
8054