azure-kusto-data 4.0.3 → 5.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/README.md +1 -2
  2. package/dist-esm/src/client.js +227 -0
  3. package/dist-esm/src/clientDetails.js +79 -0
  4. package/{source → dist-esm/src}/clientRequestProperties.js +13 -0
  5. package/dist-esm/src/cloudSettings.js +60 -0
  6. package/dist-esm/src/connectionBuilder.browser.js +72 -0
  7. package/dist-esm/src/connectionBuilder.js +128 -0
  8. package/dist-esm/src/connectionBuilderBase.js +138 -0
  9. package/{source → dist-esm/src}/errors.js +0 -0
  10. package/{index.js → dist-esm/src/index.js} +8 -5
  11. package/{source → dist-esm/src}/kustoTrustedEndpoints.js +0 -0
  12. package/{source → dist-esm/src}/models.js +8 -6
  13. package/{source → dist-esm/src}/response.js +0 -0
  14. package/{source → dist-esm/src}/security.js +17 -31
  15. package/dist-esm/src/timeUtils.js +28 -0
  16. package/dist-esm/src/tokenProvider.js +252 -0
  17. package/{source → dist-esm/src}/typeUtilts.js +0 -0
  18. package/{source → dist-esm/src}/utils.js +0 -0
  19. package/dist-esm/src/version.js +8 -0
  20. package/{source → dist-esm/src}/wellKnownKustoEndpoints.json +0 -0
  21. package/dist-esm/tsconfig.tsbuildinfo +1 -0
  22. package/package.json +29 -15
  23. package/{source → types/src}/client.d.ts +1 -0
  24. package/types/src/clientDetails.d.ts +20 -0
  25. package/{source → types/src}/clientRequestProperties.d.ts +3 -0
  26. package/{source → types/src}/cloudSettings.d.ts +1 -0
  27. package/types/src/connectionBuilder.browser.d.ts +18 -0
  28. package/types/src/connectionBuilder.d.ts +24 -0
  29. package/types/src/connectionBuilderBase.d.ts +56 -0
  30. package/{source → types/src}/errors.d.ts +1 -0
  31. package/types/src/index.d.ts +10 -0
  32. package/{source → types/src}/kustoTrustedEndpoints.d.ts +1 -0
  33. package/{source → types/src}/models.d.ts +7 -1
  34. package/{source → types/src}/response.d.ts +1 -0
  35. package/{source → types/src}/security.d.ts +3 -3
  36. package/types/src/timeUtils.d.ts +3 -0
  37. package/{source → types/src}/tokenProvider.d.ts +36 -60
  38. package/{source → types/src}/typeUtilts.d.ts +1 -0
  39. package/{source → types/src}/utils.d.ts +1 -0
  40. package/types/src/version.d.ts +2 -0
  41. package/example.js +0 -49
  42. package/index.d.ts +0 -5
  43. package/source/client.js +0 -241
  44. package/source/cloudSettings.js +0 -73
  45. package/source/connectionBuilder.d.ts +0 -45
  46. package/source/connectionBuilder.js +0 -231
  47. package/source/tokenProvider.js +0 -350
  48. package/tsconfig.tsbuildinfo +0 -1
package/README.md CHANGED
@@ -1,4 +1,4 @@
1
- # Microsoft Azure Kusto Data Library for Node
1
+ # Microsoft Azure Kusto Data Library for JavaScript
2
2
 
3
3
  ## Installation
4
4
 
@@ -41,7 +41,6 @@ const kcsb = KustoConnectionStringBuilder.withAadApplicationCertificateAuthentic
41
41
  `https://${clusterName}.kusto.windows.net`,
42
42
  "appid",
43
43
  "certificate",
44
- "thumbprint",
45
44
  "authorityId"
46
45
  );
47
46
  ```
@@ -0,0 +1,227 @@
1
+ "use strict";
2
+ // Copyright (c) Microsoft Corporation.
3
+ // Licensed under the MIT License.
4
+ var __importDefault = (this && this.__importDefault) || function (mod) {
5
+ return (mod && mod.__esModule) ? mod : { "default": mod };
6
+ };
7
+ Object.defineProperty(exports, "__esModule", { value: true });
8
+ exports.KustoClient = void 0;
9
+ const uuid_1 = require("uuid");
10
+ const security_1 = __importDefault(require("./security"));
11
+ const response_1 = require("./response");
12
+ const connectionBuilder_1 = __importDefault(require("./connectionBuilder"));
13
+ const clientRequestProperties_1 = __importDefault(require("./clientRequestProperties"));
14
+ const errors_1 = require("./errors");
15
+ const version_1 = require("./version");
16
+ const axios_1 = __importDefault(require("axios"));
17
+ const http_1 = __importDefault(require("http"));
18
+ const https_1 = __importDefault(require("https"));
19
+ const core_util_1 = require("@azure/core-util");
20
+ const kustoTrustedEndpoints_1 = require("./kustoTrustedEndpoints");
21
+ const cloudSettings_1 = require("./cloudSettings");
22
+ const timeUtils_1 = require("./timeUtils");
23
+ const COMMAND_TIMEOUT_IN_MILLISECS = (0, timeUtils_1.toMilliseconds)(0, 10, 30);
24
+ const QUERY_TIMEOUT_IN_MILLISECS = (0, timeUtils_1.toMilliseconds)(0, 4, 30);
25
+ const CLIENT_SERVER_DELTA_IN_MILLISECS = (0, timeUtils_1.toMilliseconds)(0, 0, 30);
26
+ const MGMT_PREFIX = ".";
27
+ var ExecutionType;
28
+ (function (ExecutionType) {
29
+ ExecutionType["Mgmt"] = "mgmt";
30
+ ExecutionType["Query"] = "query";
31
+ ExecutionType["Ingest"] = "ingest";
32
+ ExecutionType["QueryV1"] = "queryv1";
33
+ })(ExecutionType || (ExecutionType = {}));
34
+ class KustoClient {
35
+ constructor(kcsb) {
36
+ this.cancelToken = axios_1.default.CancelToken.source();
37
+ this._isClosed = false;
38
+ this.connectionString = typeof kcsb === "string" ? new connectionBuilder_1.default(kcsb) : kcsb;
39
+ if (!this.connectionString.dataSource) {
40
+ throw new Error("Cluster url is required");
41
+ }
42
+ const url = new URL(this.connectionString.dataSource);
43
+ this.cluster = `${url.protocol}//${url.hostname}${url.port ? `:${url.port}` : ""}`;
44
+ this.defaultDatabase = this.connectionString.initialCatalog;
45
+ this.endpoints = {
46
+ [ExecutionType.Mgmt]: `${this.cluster}/v1/rest/mgmt`,
47
+ [ExecutionType.Query]: `${this.cluster}/v2/rest/query`,
48
+ [ExecutionType.Ingest]: `${this.cluster}/v1/rest/ingest`,
49
+ [ExecutionType.QueryV1]: `${this.cluster}/v1/rest/query`,
50
+ };
51
+ this.aadHelper = new security_1.default(this.connectionString);
52
+ const headers = {
53
+ Accept: "application/json",
54
+ "Accept-Encoding": "gzip,deflate",
55
+ "x-ms-client-version": `Kusto.Node.Client:${version_1.SDK_VERSION}`,
56
+ Connection: "Keep-Alive",
57
+ };
58
+ const axiosProps = {
59
+ headers,
60
+ validateStatus: (status) => status === 200,
61
+ };
62
+ // http and https are Node modules and are not found in browsers
63
+ if (core_util_1.isNode) {
64
+ // keepAlive pools and reuses TCP connections, so it's faster
65
+ axiosProps.httpAgent = new http_1.default.Agent({ keepAlive: true });
66
+ axiosProps.httpsAgent = new https_1.default.Agent({ keepAlive: true });
67
+ }
68
+ axiosProps.cancelToken = this.cancelToken.token;
69
+ this.axiosInstance = axios_1.default.create();
70
+ }
71
+ async execute(db, query, properties) {
72
+ query = query.trim();
73
+ if (query.startsWith(MGMT_PREFIX)) {
74
+ return this.executeMgmt(db, query, properties);
75
+ }
76
+ return this.executeQuery(db, query, properties);
77
+ }
78
+ async executeQuery(db, query, properties) {
79
+ return this._execute(this.endpoints[ExecutionType.Query], ExecutionType.Query, db, query, null, properties);
80
+ }
81
+ async executeQueryV1(db, query, properties) {
82
+ return this._execute(this.endpoints[ExecutionType.QueryV1], ExecutionType.QueryV1, db, query, null, properties);
83
+ }
84
+ async executeMgmt(db, query, properties) {
85
+ return this._execute(this.endpoints[ExecutionType.Mgmt], ExecutionType.Mgmt, db, query, null, properties);
86
+ }
87
+ async executeStreamingIngest(db, table, stream, streamFormat, mappingName, clientRequestId) {
88
+ let endpoint = `${this.endpoints[ExecutionType.Ingest]}/${this.getDb(db)}/${table}?streamFormat=${streamFormat}`;
89
+ if (mappingName != null) {
90
+ endpoint += `&mappingName=${mappingName}`;
91
+ }
92
+ let properties = null;
93
+ if (clientRequestId) {
94
+ properties = new clientRequestProperties_1.default();
95
+ properties.clientRequestId = clientRequestId;
96
+ }
97
+ return this._execute(endpoint, ExecutionType.Ingest, db, null, stream, properties);
98
+ }
99
+ async _execute(endpoint, executionType, db, query, stream, properties) {
100
+ this.ensureOpen();
101
+ kustoTrustedEndpoints_1.kustoTrustedEndpoints.validateTrustedEndpoint(endpoint, (await cloudSettings_1.CloudSettings.getInstance().getCloudInfoForCluster(this.cluster)).LoginEndpoint);
102
+ db = this.getDb(db);
103
+ const headers = {};
104
+ let payload;
105
+ let clientRequestPrefix = "";
106
+ const timeout = this._getClientTimeout(executionType, properties);
107
+ let payloadContent = "";
108
+ if (query != null) {
109
+ payload = {
110
+ db,
111
+ csl: query,
112
+ };
113
+ if (properties != null) {
114
+ payload.properties = properties.toJSON();
115
+ }
116
+ payloadContent = JSON.stringify(payload);
117
+ headers["Content-Type"] = "application/json; charset=utf-8";
118
+ clientRequestPrefix = "KNC.execute;";
119
+ }
120
+ else if (stream != null) {
121
+ payloadContent = stream;
122
+ clientRequestPrefix = "KNC.executeStreamingIngest;";
123
+ if (core_util_1.isNode) {
124
+ headers["Content-Encoding"] = "gzip";
125
+ headers["Content-Type"] = "application/octet-stream";
126
+ }
127
+ else {
128
+ headers["Content-Type"] = "application/json";
129
+ }
130
+ }
131
+ else {
132
+ throw new Error("Invalid parameters - expected query or streaming ingest");
133
+ }
134
+ let kustoHeaders = this.connectionString.clientDetails().getHeaders();
135
+ kustoHeaders["x-ms-client-request-id"] = `${clientRequestPrefix}${(0, uuid_1.v4)()}`;
136
+ if (properties != null) {
137
+ kustoHeaders = Object.assign(Object.assign({}, kustoHeaders), properties.getHeaders());
138
+ }
139
+ for (const key of Object.keys(kustoHeaders)) {
140
+ if (kustoHeaders[key]) {
141
+ headers[key] = kustoHeaders[key];
142
+ }
143
+ }
144
+ const authHeader = await this.aadHelper.getAuthHeader();
145
+ if (authHeader != null) {
146
+ headers.Authorization = authHeader;
147
+ }
148
+ return this._doRequest(endpoint, executionType, headers, payloadContent, timeout, properties);
149
+ }
150
+ getDb(db) {
151
+ if (db == null) {
152
+ if (this.defaultDatabase == null) {
153
+ throw new Error("No database provided, and no default database specified in connection string");
154
+ }
155
+ db = this.defaultDatabase;
156
+ }
157
+ return db;
158
+ }
159
+ async _doRequest(endpoint, executionType, headers, payload, timeout, properties) {
160
+ const axiosConfig = {
161
+ headers,
162
+ timeout,
163
+ };
164
+ let axiosResponse;
165
+ try {
166
+ axiosResponse = await this.axiosInstance.post(endpoint, payload, axiosConfig);
167
+ }
168
+ catch (error) {
169
+ if (axios_1.default.isAxiosError(error) && error.response) {
170
+ if (error.response.status === 429) {
171
+ throw new errors_1.ThrottlingError("POST request failed with status 429 (Too Many Requests)", error);
172
+ }
173
+ }
174
+ throw error;
175
+ }
176
+ return this._parseResponse(axiosResponse.data, executionType, properties, axiosResponse.status);
177
+ }
178
+ _parseResponse(response, executionType, properties, status) {
179
+ const { raw } = properties || {};
180
+ if (raw === true || executionType === ExecutionType.Ingest) {
181
+ return response;
182
+ }
183
+ let kustoResponse = null;
184
+ try {
185
+ if (executionType === ExecutionType.Query) {
186
+ kustoResponse = new response_1.KustoResponseDataSetV2(response);
187
+ }
188
+ else {
189
+ kustoResponse = new response_1.KustoResponseDataSetV1(response);
190
+ }
191
+ }
192
+ catch (ex) {
193
+ throw new Error(`Failed to parse response ({${status}}) with the following error [${ex}].`);
194
+ }
195
+ if (kustoResponse.getErrorsCount().errors > 0) {
196
+ throw new Error(`Kusto request had errors. ${kustoResponse.getExceptions()}`);
197
+ }
198
+ return kustoResponse;
199
+ }
200
+ _getClientTimeout(executionType, properties) {
201
+ if (properties != null) {
202
+ const clientTimeout = properties.getClientTimeout();
203
+ if (clientTimeout) {
204
+ return clientTimeout;
205
+ }
206
+ const serverTimeout = properties.getTimeout();
207
+ if (serverTimeout) {
208
+ return serverTimeout + CLIENT_SERVER_DELTA_IN_MILLISECS;
209
+ }
210
+ }
211
+ return executionType === ExecutionType.Query || executionType === ExecutionType.QueryV1 ? QUERY_TIMEOUT_IN_MILLISECS : COMMAND_TIMEOUT_IN_MILLISECS;
212
+ }
213
+ close() {
214
+ if (!this._isClosed) {
215
+ this.cancelToken.cancel("Client Closed");
216
+ }
217
+ this._isClosed = true;
218
+ }
219
+ ensureOpen() {
220
+ if (this._isClosed) {
221
+ throw new Error("Client is closed");
222
+ }
223
+ }
224
+ }
225
+ exports.KustoClient = KustoClient;
226
+ exports.default = KustoClient;
227
+ //# sourceMappingURL=client.js.map
@@ -0,0 +1,79 @@
1
+ "use strict";
2
+ // Copyright (c) Microsoft Corporation.
3
+ // Licensed under the MIT License.
4
+ Object.defineProperty(exports, "__esModule", { value: true });
5
+ exports.ClientDetails = void 0;
6
+ const core_util_1 = require("@azure/core-util");
7
+ const os_1 = require("os");
8
+ const version_1 = require("./version");
9
+ // REPLACE_REGEX = re.compile(r"[\r\n\s{}|]+")
10
+ const ReplaceRegex = /[\r\n\s{}|]+/g;
11
+ const None = "[none]";
12
+ class ClientDetails {
13
+ constructor(applicationNameForTracing, userNameForTracing) {
14
+ this.applicationNameForTracing = applicationNameForTracing;
15
+ this.userNameForTracing = userNameForTracing;
16
+ if (this.applicationNameForTracing === null) {
17
+ this.applicationNameForTracing = ClientDetails.defaultApplication();
18
+ }
19
+ if (this.userNameForTracing === null) {
20
+ this.userNameForTracing = ClientDetails.defaultUser();
21
+ }
22
+ this.versionForTracing = ClientDetails.defaultVersion();
23
+ }
24
+ static defaultApplication() {
25
+ var _a, _b;
26
+ if (core_util_1.isNode) {
27
+ return ((_a = process.env) === null || _a === void 0 ? void 0 : _a.npm_package_name) || process.title || None;
28
+ }
29
+ else {
30
+ return ((_b = window === null || window === void 0 ? void 0 : window.location) === null || _b === void 0 ? void 0 : _b.href) || None;
31
+ }
32
+ }
33
+ static defaultUser() {
34
+ if (core_util_1.isNode) {
35
+ const info = (0, os_1.userInfo)();
36
+ return info.username || (process.env.USERDOMAIN ? `${process.env.USERDOMAIN}\\${process.env.USERNAME}` : process.env.USERNAME) || None;
37
+ }
38
+ else {
39
+ return None;
40
+ }
41
+ }
42
+ static defaultVersion() {
43
+ var _a;
44
+ return this.formatHeader([
45
+ ["Kusto.JavaScript.Client", version_1.SDK_VERSION],
46
+ ["Runtime." + (core_util_1.isNode ? "Node" : "Browser"), (core_util_1.isNode ? process.version : (_a = window === null || window === void 0 ? void 0 : window.navigator) === null || _a === void 0 ? void 0 : _a.userAgent) || None],
47
+ ]);
48
+ }
49
+ static escapeHeader(header) {
50
+ return `{${header.replace(ReplaceRegex, "_")}}`;
51
+ }
52
+ static formatHeader(args) {
53
+ return args
54
+ .filter(([key, val]) => key && val)
55
+ .map(([key, val]) => `${key}:${this.escapeHeader(val)}`)
56
+ .join("|");
57
+ }
58
+ static setConnectorDetails(name, version, app_name = null, app_version = null, send_user = false, override_user = null, additional_fields = null) {
59
+ const params = [["Kusto." + name, version]];
60
+ app_name = app_name || this.defaultApplication();
61
+ app_version = app_version || None;
62
+ params.push(["App." + this.escapeHeader(app_name), app_version]);
63
+ params.push(...(additional_fields || []));
64
+ let user = None;
65
+ if (send_user) {
66
+ user = override_user || this.defaultUser();
67
+ }
68
+ return new ClientDetails(this.formatHeader(params), user);
69
+ }
70
+ getHeaders() {
71
+ return {
72
+ "x-ms-client-version": this.versionForTracing,
73
+ "x-ms-app": this.applicationNameForTracing,
74
+ "x-ms-user": this.userNameForTracing,
75
+ };
76
+ }
77
+ }
78
+ exports.ClientDetails = ClientDetails;
79
+ //# sourceMappingURL=clientDetails.js.map
@@ -78,6 +78,19 @@ class ClientRequestProperties {
78
78
  const secondsStr = seconds < 10 ? `0${seconds}` : String(seconds);
79
79
  return `${hoursStr}:${minutesStr}:${secondsStr}.${milliseconds}`;
80
80
  }
81
+ getHeaders() {
82
+ const headers = {};
83
+ if (this.clientRequestId) {
84
+ headers["x-ms-client-request-id"] = this.clientRequestId;
85
+ }
86
+ if (this.user) {
87
+ headers["x-ms-user"] = this.user;
88
+ }
89
+ if (this.application) {
90
+ headers["x-ms-app"] = this.application;
91
+ }
92
+ return headers;
93
+ }
81
94
  }
82
95
  exports.ClientRequestProperties = ClientRequestProperties;
83
96
  exports.default = ClientRequestProperties;
@@ -0,0 +1,60 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.CloudSettings = void 0;
7
+ // Copyright (c) Microsoft Corporation.
8
+ // Licensed under the MIT License.
9
+ const axios_1 = __importDefault(require("axios"));
10
+ /**
11
+ * This class holds data for all cloud instances, and returns the specific data instance by parsing the dns suffix from a URL
12
+ */
13
+ class CloudSettings {
14
+ constructor() {
15
+ this.METADATA_ENDPOINT = "/v1/rest/auth/metadata";
16
+ this.defaultCloudInfo = {
17
+ LoginEndpoint: process.env.AadAuthorityUri || "https://login.microsoftonline.com",
18
+ LoginMfaRequired: false,
19
+ KustoClientAppId: "db662dc1-0cfe-4e1c-a843-19a68e65be58",
20
+ KustoClientRedirectUri: "https://microsoft/kustoclient",
21
+ KustoServiceResourceId: "https://kusto.kusto.windows.net",
22
+ FirstPartyAuthorityUrl: "https://login.microsoftonline.com/f8cdef31-a31e-4b4a-93e4-5f571e91255a",
23
+ };
24
+ this.cloudCache = {};
25
+ }
26
+ static getInstance() {
27
+ return CloudSettings.instance;
28
+ }
29
+ async getCloudInfoForCluster(kustoUri) {
30
+ var _a;
31
+ if (kustoUri in this.cloudCache) {
32
+ return this.cloudCache[kustoUri];
33
+ }
34
+ try {
35
+ const response = await axios_1.default.get(kustoUri + this.METADATA_ENDPOINT);
36
+ if (response.status === 200) {
37
+ this.cloudCache[kustoUri] = response.data.AzureAD || this.defaultCloudInfo;
38
+ }
39
+ else {
40
+ throw new Error(`Kusto returned an invalid cloud metadata response - ${response}`);
41
+ }
42
+ }
43
+ catch (ex) {
44
+ if (axios_1.default.isAxiosError(ex) && ((_a = ex.response) === null || _a === void 0 ? void 0 : _a.status) === 404) {
45
+ // For now as long not all proxies implement the metadata endpoint, if no endpoint exists return public cloud data
46
+ this.cloudCache[kustoUri] = this.defaultCloudInfo;
47
+ }
48
+ else {
49
+ throw new Error(`Failed to get cloud info for cluster ${kustoUri} - ${ex}`);
50
+ }
51
+ }
52
+ return this.cloudCache[kustoUri];
53
+ }
54
+ static getAuthorityUri(cloudInfo, authorityId) {
55
+ return cloudInfo.LoginEndpoint + "/" + (authorityId || "organizations");
56
+ }
57
+ }
58
+ exports.CloudSettings = CloudSettings;
59
+ CloudSettings.instance = new CloudSettings();
60
+ //# sourceMappingURL=cloudSettings.js.map
@@ -0,0 +1,72 @@
1
+ "use strict";
2
+ // Copyright (c) Microsoft Corporation.
3
+ // Licensed under the MIT License.
4
+ var __importDefault = (this && this.__importDefault) || function (mod) {
5
+ return (mod && mod.__esModule) ? mod : { "default": mod };
6
+ };
7
+ Object.defineProperty(exports, "__esModule", { value: true });
8
+ exports.KustoConnectionStringBuilder = void 0;
9
+ const connectionBuilderBase_1 = __importDefault(require("./connectionBuilderBase"));
10
+ /* eslint-disable @typescript-eslint/no-unused-vars */
11
+ class KustoConnectionStringBuilder extends connectionBuilderBase_1.default {
12
+ static withAadUserPasswordAuthentication(_connectionString, _userId, _password, _authorityId) {
13
+ throw new Error("Not supported in browser - use withUserPrompt instead");
14
+ }
15
+ static withAadApplicationKeyAuthentication(_connectionString, _aadAppId, _appKey, _authorityId) {
16
+ throw new Error("Not supported in browser - use withUserPrompt instead");
17
+ }
18
+ static withAadApplicationCertificateAuthentication(_connectionString, _aadAppId, _applicationCertificatePrivateKey, _authorityId, _applicationCertificateSendX5c) {
19
+ throw new Error("Not supported in browser - use withUserPrompt instead");
20
+ }
21
+ static withAadDeviceAuthentication(_connectionString, _authorityId, _deviceCodeCallback) {
22
+ throw new Error("Not supported in browser - use withUserPrompt instead");
23
+ }
24
+ static withSystemManagedIdentity(_connectionString, _authorityId, _timeoutMs) {
25
+ throw new Error("Not supported in browser - use withUserPrompt instead");
26
+ }
27
+ static withUserManagedIdentity(_connectionString, _msiClientId, _authorityId, _timeoutMs) {
28
+ throw new Error("Not supported in browser - use withUserPrompt instead");
29
+ }
30
+ static withAzLoginIdentity(_connectionString, _authorityId, _timeoutMs) {
31
+ throw new Error("Not supported in browser - use withUserPrompt instead");
32
+ }
33
+ static withAccessToken(connectionString, accessToken) {
34
+ const kcsb = new KustoConnectionStringBuilder(connectionString);
35
+ kcsb.aadFederatedSecurity = true;
36
+ kcsb.accessToken = accessToken;
37
+ return kcsb;
38
+ }
39
+ static withTokenProvider(connectionString, tokenProvider) {
40
+ const kcsb = new KustoConnectionStringBuilder(connectionString);
41
+ kcsb.aadFederatedSecurity = true;
42
+ kcsb.tokenProvider = tokenProvider;
43
+ return kcsb;
44
+ }
45
+ static withUserPrompt(connectionString, interactiveCredentialOptions, timeoutMs) {
46
+ if (!interactiveCredentialOptions) {
47
+ throw new Error("Invalid parameters - You must provide interactiveCredentialOptions={clientId: string, redirectUri:string} to authenticate with user prompt in browser.");
48
+ }
49
+ const kcsb = new KustoConnectionStringBuilder(connectionString);
50
+ const { redirectUri, clientId, tenantId } = interactiveCredentialOptions;
51
+ if (!clientId) {
52
+ throw new Error("Invalid parameters - You must provide your SPA application client id to authenticate against");
53
+ }
54
+ if (!redirectUri) {
55
+ throw new Error("Invalid parameters - You must provide a redirectUri registered on the SPA app");
56
+ }
57
+ kcsb.interactiveCredentialOptions = interactiveCredentialOptions;
58
+ kcsb.aadFederatedSecurity = true;
59
+ kcsb.applicationClientId = clientId;
60
+ kcsb.useUserPromptAuth = true;
61
+ if (tenantId) {
62
+ kcsb.authorityId = tenantId;
63
+ }
64
+ kcsb.timeoutMs = timeoutMs;
65
+ return kcsb;
66
+ }
67
+ }
68
+ exports.KustoConnectionStringBuilder = KustoConnectionStringBuilder;
69
+ KustoConnectionStringBuilder.DefaultDatabaseName = "NetDefaultDB";
70
+ KustoConnectionStringBuilder.SecretReplacement = "****";
71
+ exports.default = KustoConnectionStringBuilder;
72
+ //# sourceMappingURL=connectionBuilder.browser.js.map
@@ -0,0 +1,128 @@
1
+ "use strict";
2
+ // Copyright (c) Microsoft Corporation.
3
+ // Licensed under the MIT License.
4
+ Object.defineProperty(exports, "__esModule", { value: true });
5
+ exports.KustoConnectionStringBuilder = void 0;
6
+ const connectionBuilderBase_1 = require("./connectionBuilderBase");
7
+ /*
8
+ * A builder for Kusto connection strings
9
+ * For browsers use withUserPrompt or provide the token yourself using withTokenProvider
10
+ */
11
+ class KustoConnectionStringBuilder extends connectionBuilderBase_1.KustoConnectionStringBuilderBase {
12
+ static withAadUserPasswordAuthentication(connectionString, userId, password, authorityId) {
13
+ if (userId.trim().length === 0)
14
+ throw new Error("Invalid user");
15
+ if (password.trim().length === 0)
16
+ throw new Error("Invalid password");
17
+ const kcsb = new KustoConnectionStringBuilder(connectionString);
18
+ kcsb.aadFederatedSecurity = true;
19
+ kcsb.aadUserId = userId;
20
+ kcsb.password = password;
21
+ if (authorityId) {
22
+ kcsb.authorityId = authorityId;
23
+ }
24
+ return kcsb;
25
+ }
26
+ static withAadApplicationKeyAuthentication(connectionString, aadAppId, appKey, authorityId) {
27
+ if (aadAppId.trim().length === 0)
28
+ throw new Error("Invalid app id");
29
+ if (appKey.trim().length === 0)
30
+ throw new Error("Invalid app key");
31
+ const kcsb = new KustoConnectionStringBuilder(connectionString);
32
+ kcsb.aadFederatedSecurity = true;
33
+ kcsb.applicationClientId = aadAppId;
34
+ kcsb.applicationKey = appKey;
35
+ if (authorityId) {
36
+ kcsb.authorityId = authorityId;
37
+ }
38
+ return kcsb;
39
+ }
40
+ static withAadApplicationCertificateAuthentication(connectionString, aadAppId, applicationCertificatePrivateKey, authorityId, applicationCertificateSendX5c) {
41
+ if (aadAppId.trim().length === 0)
42
+ throw new Error("Invalid app id");
43
+ if (applicationCertificatePrivateKey.trim().length === 0)
44
+ throw new Error("Invalid certificate");
45
+ const kcsb = new KustoConnectionStringBuilder(connectionString);
46
+ kcsb.aadFederatedSecurity = true;
47
+ kcsb.applicationClientId = aadAppId;
48
+ kcsb.applicationCertificatePrivateKey = applicationCertificatePrivateKey;
49
+ kcsb.applicationCertificateSendX5c = applicationCertificateSendX5c;
50
+ if (authorityId) {
51
+ kcsb.authorityId = authorityId;
52
+ }
53
+ return kcsb;
54
+ }
55
+ static withAadDeviceAuthentication(connectionString, authorityId, deviceCodeCallback) {
56
+ const kcsb = new KustoConnectionStringBuilder(connectionString);
57
+ kcsb.aadFederatedSecurity = true;
58
+ if (authorityId) {
59
+ kcsb.authorityId = authorityId;
60
+ }
61
+ kcsb.deviceCodeCallback = deviceCodeCallback;
62
+ kcsb.useDeviceCodeAuth = true;
63
+ return kcsb;
64
+ }
65
+ static withAadManagedIdentities(connectionString, msiClientId, authorityId, timeoutMs) {
66
+ const kcsb = new KustoConnectionStringBuilder(connectionString);
67
+ kcsb.aadFederatedSecurity = true;
68
+ if (authorityId) {
69
+ kcsb.authorityId = authorityId;
70
+ }
71
+ kcsb.msiClientId = msiClientId;
72
+ kcsb.timeoutMs = timeoutMs;
73
+ kcsb.useManagedIdentityAuth = true;
74
+ return kcsb;
75
+ }
76
+ static withSystemManagedIdentity(connectionString, authorityId, timeoutMs) {
77
+ return this.withAadManagedIdentities(connectionString, undefined, authorityId, timeoutMs);
78
+ }
79
+ static withUserManagedIdentity(connectionString, msiClientId, authorityId, timeoutMs) {
80
+ return this.withAadManagedIdentities(connectionString, msiClientId, authorityId, timeoutMs);
81
+ }
82
+ static withAzLoginIdentity(connectionString, authorityId, timeoutMs) {
83
+ const kcsb = new KustoConnectionStringBuilder(connectionString);
84
+ kcsb.aadFederatedSecurity = true;
85
+ kcsb.useAzLoginAuth = true;
86
+ if (authorityId) {
87
+ kcsb.authorityId = authorityId;
88
+ }
89
+ kcsb.timeoutMs = timeoutMs;
90
+ return kcsb;
91
+ }
92
+ static withAccessToken(connectionString, accessToken) {
93
+ const kcsb = new KustoConnectionStringBuilder(connectionString);
94
+ kcsb.aadFederatedSecurity = true;
95
+ kcsb.accessToken = accessToken;
96
+ return kcsb;
97
+ }
98
+ static withTokenProvider(connectionString, tokenProvider) {
99
+ const kcsb = new KustoConnectionStringBuilder(connectionString);
100
+ kcsb.aadFederatedSecurity = true;
101
+ kcsb.tokenProvider = tokenProvider;
102
+ return kcsb;
103
+ }
104
+ /**
105
+ * Use InteractiveBrowserCredentialNodeOptions in Node.JS and InteractiveBrowserCredentialInBrowserOptions in browser
106
+ * For browser cors issue: you need to visit your app registration and update the redirect URI you're using to the type spa (for "single page application").
107
+ * See: https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/identity/identity/test/manual/interactive-browser-credential
108
+ */
109
+ static withUserPrompt(connectionString, options, timeoutMs) {
110
+ const kcsb = new KustoConnectionStringBuilder(connectionString);
111
+ const { tenantId, clientId } = options || {};
112
+ if (clientId) {
113
+ throw new Error("clientId should be empty as it is retrived from the service management endpoint");
114
+ }
115
+ kcsb.aadFederatedSecurity = true;
116
+ kcsb.useUserPromptAuth = true;
117
+ if (tenantId) {
118
+ kcsb.authorityId = tenantId;
119
+ }
120
+ kcsb.timeoutMs = timeoutMs;
121
+ return kcsb;
122
+ }
123
+ }
124
+ exports.KustoConnectionStringBuilder = KustoConnectionStringBuilder;
125
+ KustoConnectionStringBuilder.DefaultDatabaseName = "NetDefaultDB";
126
+ KustoConnectionStringBuilder.SecretReplacement = "****";
127
+ exports.default = KustoConnectionStringBuilder;
128
+ //# sourceMappingURL=connectionBuilder.js.map