azure-kusto-data 4.0.5 → 5.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
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 +72 -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/{index.js → dist-esm/src/index.js} +8 -5
  10. package/{source → dist-esm/src}/models.js +8 -6
  11. package/{source → dist-esm/src}/security.js +17 -31
  12. package/dist-esm/src/timeUtils.js +28 -0
  13. package/dist-esm/src/tokenProvider.js +252 -0
  14. package/dist-esm/src/version.js +8 -0
  15. package/dist-esm/tsconfig.tsbuildinfo +1 -0
  16. package/package.json +29 -15
  17. package/{source → types/src}/client.d.ts +1 -0
  18. package/types/src/clientDetails.d.ts +20 -0
  19. package/{source → types/src}/clientRequestProperties.d.ts +3 -0
  20. package/{source → types/src}/cloudSettings.d.ts +1 -0
  21. package/types/src/connectionBuilder.browser.d.ts +18 -0
  22. package/types/src/connectionBuilder.d.ts +24 -0
  23. package/types/src/connectionBuilderBase.d.ts +56 -0
  24. package/{source → types/src}/errors.d.ts +1 -0
  25. package/types/src/index.d.ts +10 -0
  26. package/{source → types/src}/kustoTrustedEndpoints.d.ts +1 -0
  27. package/{source → types/src}/models.d.ts +7 -1
  28. package/{source → types/src}/response.d.ts +1 -0
  29. package/{source → types/src}/security.d.ts +3 -3
  30. package/types/src/timeUtils.d.ts +3 -0
  31. package/{source → types/src}/tokenProvider.d.ts +36 -60
  32. package/{source → types/src}/typeUtilts.d.ts +1 -0
  33. package/{source → types/src}/utils.d.ts +1 -0
  34. package/types/src/version.d.ts +2 -0
  35. package/example.js +0 -49
  36. package/index.d.ts +0 -5
  37. package/source/client.js +0 -241
  38. package/source/cloudSettings.js +0 -73
  39. package/source/connectionBuilder.d.ts +0 -45
  40. package/source/connectionBuilder.js +0 -231
  41. package/source/tokenProvider.js +0 -350
  42. package/tsconfig.tsbuildinfo +0 -1
  43. /package/{source → dist-esm/src}/errors.js +0 -0
  44. /package/{source → dist-esm/src}/kustoTrustedEndpoints.js +0 -0
  45. /package/{source → dist-esm/src}/response.js +0 -0
  46. /package/{source → dist-esm/src}/typeUtilts.js +0 -0
  47. /package/{source → dist-esm/src}/utils.js +0 -0
  48. /package/{source → dist-esm/src}/wellKnownKustoEndpoints.json +0 -0
package/index.d.ts DELETED
@@ -1,5 +0,0 @@
1
- import KustoClient from "./source/client";
2
- import ClientRequestProperties from "./source/clientRequestProperties";
3
- import KustoConnectionStringBuilder from "./source/connectionBuilder";
4
- import * as KustoDataErrors from "./source/errors";
5
- export { KustoClient as Client, ClientRequestProperties, KustoConnectionStringBuilder, KustoDataErrors };
package/source/client.js DELETED
@@ -1,241 +0,0 @@
1
- "use strict";
2
- // Copyright (c) Microsoft Corporation.
3
- // Licensed under the MIT License.
4
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
5
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
6
- return new (P || (P = Promise))(function (resolve, reject) {
7
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
8
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
9
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
10
- step((generator = generator.apply(thisArg, _arguments || [])).next());
11
- });
12
- };
13
- var __importDefault = (this && this.__importDefault) || function (mod) {
14
- return (mod && mod.__esModule) ? mod : { "default": mod };
15
- };
16
- Object.defineProperty(exports, "__esModule", { value: true });
17
- exports.KustoClient = void 0;
18
- const moment_1 = __importDefault(require("moment"));
19
- const uuid_1 = require("uuid");
20
- const security_1 = __importDefault(require("./security"));
21
- const response_1 = require("./response");
22
- const connectionBuilder_1 = __importDefault(require("./connectionBuilder"));
23
- const clientRequestProperties_1 = __importDefault(require("./clientRequestProperties"));
24
- const errors_1 = require("./errors");
25
- const package_json_1 = __importDefault(require("../package.json"));
26
- const axios_1 = __importDefault(require("axios"));
27
- const http_1 = __importDefault(require("http"));
28
- const https_1 = __importDefault(require("https"));
29
- const kustoTrustedEndpoints_1 = require("./kustoTrustedEndpoints");
30
- const cloudSettings_1 = require("./cloudSettings");
31
- const COMMAND_TIMEOUT_IN_MILLISECS = moment_1.default.duration(10.5, "minutes").asMilliseconds();
32
- const QUERY_TIMEOUT_IN_MILLISECS = moment_1.default.duration(4.5, "minutes").asMilliseconds();
33
- const CLIENT_SERVER_DELTA_IN_MILLISECS = moment_1.default.duration(0.5, "minutes").asMilliseconds();
34
- const MGMT_PREFIX = ".";
35
- var ExecutionType;
36
- (function (ExecutionType) {
37
- ExecutionType["Mgmt"] = "mgmt";
38
- ExecutionType["Query"] = "query";
39
- ExecutionType["Ingest"] = "ingest";
40
- ExecutionType["QueryV1"] = "queryv1";
41
- })(ExecutionType || (ExecutionType = {}));
42
- class KustoClient {
43
- constructor(kcsb) {
44
- this.cancelToken = axios_1.default.CancelToken.source();
45
- this._isClosed = false;
46
- this.connectionString = typeof kcsb === "string" ? new connectionBuilder_1.default(kcsb) : kcsb;
47
- if (!this.connectionString.dataSource) {
48
- throw new Error("Cluster url is required");
49
- }
50
- const url = new URL(this.connectionString.dataSource);
51
- this.cluster = `${url.protocol}//${url.hostname}${url.port ? `:${url.port}` : ""}`;
52
- this.defaultDatabase = this.connectionString.initialCatalog;
53
- this.endpoints = {
54
- [ExecutionType.Mgmt]: `${this.cluster}/v1/rest/mgmt`,
55
- [ExecutionType.Query]: `${this.cluster}/v2/rest/query`,
56
- [ExecutionType.Ingest]: `${this.cluster}/v1/rest/ingest`,
57
- [ExecutionType.QueryV1]: `${this.cluster}/v1/rest/query`,
58
- };
59
- this.aadHelper = new security_1.default(this.connectionString);
60
- const headers = {
61
- Accept: "application/json",
62
- "Accept-Encoding": "gzip,deflate",
63
- "x-ms-client-version": `Kusto.Node.Client:${package_json_1.default.version}`,
64
- Connection: "Keep-Alive",
65
- };
66
- this.axiosInstance = axios_1.default.create({
67
- headers,
68
- validateStatus: (status) => status === 200,
69
- // keepAlive pools and reuses TCP connections, so it's faster
70
- httpAgent: new http_1.default.Agent({ keepAlive: true }),
71
- httpsAgent: new https_1.default.Agent({ keepAlive: true }),
72
- cancelToken: this.cancelToken.token,
73
- });
74
- }
75
- execute(db, query, properties) {
76
- return __awaiter(this, void 0, void 0, function* () {
77
- query = query.trim();
78
- if (query.startsWith(MGMT_PREFIX)) {
79
- return this.executeMgmt(db, query, properties);
80
- }
81
- return this.executeQuery(db, query, properties);
82
- });
83
- }
84
- executeQuery(db, query, properties) {
85
- return __awaiter(this, void 0, void 0, function* () {
86
- return this._execute(this.endpoints[ExecutionType.Query], ExecutionType.Query, db, query, null, properties);
87
- });
88
- }
89
- executeQueryV1(db, query, properties) {
90
- return __awaiter(this, void 0, void 0, function* () {
91
- return this._execute(this.endpoints[ExecutionType.QueryV1], ExecutionType.QueryV1, db, query, null, properties);
92
- });
93
- }
94
- executeMgmt(db, query, properties) {
95
- return __awaiter(this, void 0, void 0, function* () {
96
- return this._execute(this.endpoints[ExecutionType.Mgmt], ExecutionType.Mgmt, db, query, null, properties);
97
- });
98
- }
99
- executeStreamingIngest(db, table, stream, streamFormat, mappingName, clientRequestId) {
100
- return __awaiter(this, void 0, void 0, function* () {
101
- let endpoint = `${this.endpoints[ExecutionType.Ingest]}/${this.getDb(db)}/${table}?streamFormat=${streamFormat}`;
102
- if (mappingName != null) {
103
- endpoint += `&mappingName=${mappingName}`;
104
- }
105
- let properties = null;
106
- if (clientRequestId) {
107
- properties = new clientRequestProperties_1.default();
108
- properties.clientRequestId = clientRequestId;
109
- }
110
- return this._execute(endpoint, ExecutionType.Ingest, db, null, stream, properties);
111
- });
112
- }
113
- _execute(endpoint, executionType, db, query, stream, properties) {
114
- return __awaiter(this, void 0, void 0, function* () {
115
- this.ensureOpen();
116
- kustoTrustedEndpoints_1.kustoTrustedEndpoints.validateTrustedEndpoint(endpoint, (yield cloudSettings_1.CloudSettings.getInstance().getCloudInfoForCluster(this.cluster)).LoginEndpoint);
117
- db = this.getDb(db);
118
- const headers = {};
119
- let payload;
120
- let clientRequestPrefix = "";
121
- let clientRequestId;
122
- const timeout = this._getClientTimeout(executionType, properties);
123
- let payloadContent = "";
124
- if (query != null) {
125
- payload = {
126
- db,
127
- csl: query,
128
- };
129
- if (properties != null) {
130
- payload.properties = properties.toJSON();
131
- }
132
- payloadContent = JSON.stringify(payload);
133
- headers["Content-Type"] = "application/json; charset=utf-8";
134
- clientRequestPrefix = "KNC.execute;";
135
- }
136
- else if (stream != null) {
137
- payloadContent = stream;
138
- clientRequestPrefix = "KNC.executeStreamingIngest;";
139
- headers["Content-Encoding"] = "gzip";
140
- headers["Content-Type"] = "application/octet-stream";
141
- }
142
- else {
143
- throw new Error("Invalid parameters - expected query or streaming ingest");
144
- }
145
- if (properties != null) {
146
- clientRequestId = properties.clientRequestId;
147
- if (properties.application != null) {
148
- headers["x-ms-app"] = properties.application;
149
- }
150
- if (properties.user != null) {
151
- headers["x-ms-user"] = properties.user;
152
- }
153
- }
154
- headers["x-ms-client-request-id"] = clientRequestId || clientRequestPrefix + `${(0, uuid_1.v4)()}`;
155
- const authHeader = yield this.aadHelper.getAuthHeader();
156
- if (authHeader != null) {
157
- headers.Authorization = authHeader;
158
- }
159
- return this._doRequest(endpoint, executionType, headers, payloadContent, timeout, properties);
160
- });
161
- }
162
- getDb(db) {
163
- if (db == null) {
164
- if (this.defaultDatabase == null) {
165
- throw new Error("No database provided, and no default database specified in connection string");
166
- }
167
- db = this.defaultDatabase;
168
- }
169
- return db;
170
- }
171
- _doRequest(endpoint, executionType, headers, payload, timeout, properties) {
172
- return __awaiter(this, void 0, void 0, function* () {
173
- const axiosConfig = {
174
- headers,
175
- timeout,
176
- };
177
- let axiosResponse;
178
- try {
179
- axiosResponse = yield this.axiosInstance.post(endpoint, payload, axiosConfig);
180
- }
181
- catch (error) {
182
- if (axios_1.default.isAxiosError(error) && error.response) {
183
- if (error.response.status === 429) {
184
- throw new errors_1.ThrottlingError("POST request failed with status 429 (Too Many Requests)", error);
185
- }
186
- }
187
- throw error;
188
- }
189
- return this._parseResponse(axiosResponse.data, executionType, properties, axiosResponse.status);
190
- });
191
- }
192
- _parseResponse(response, executionType, properties, status) {
193
- const { raw } = properties || {};
194
- if (raw === true || executionType === ExecutionType.Ingest) {
195
- return response;
196
- }
197
- let kustoResponse = null;
198
- try {
199
- if (executionType === ExecutionType.Query) {
200
- kustoResponse = new response_1.KustoResponseDataSetV2(response);
201
- }
202
- else {
203
- kustoResponse = new response_1.KustoResponseDataSetV1(response);
204
- }
205
- }
206
- catch (ex) {
207
- throw new Error(`Failed to parse response ({${status}}) with the following error [${ex}].`);
208
- }
209
- if (kustoResponse.getErrorsCount().errors > 0) {
210
- throw new Error(`Kusto request had errors. ${kustoResponse.getExceptions()}`);
211
- }
212
- return kustoResponse;
213
- }
214
- _getClientTimeout(executionType, properties) {
215
- if (properties != null) {
216
- const clientTimeout = properties.getClientTimeout();
217
- if (clientTimeout) {
218
- return clientTimeout;
219
- }
220
- const serverTimeout = properties.getTimeout();
221
- if (serverTimeout) {
222
- return serverTimeout + CLIENT_SERVER_DELTA_IN_MILLISECS;
223
- }
224
- }
225
- return executionType === ExecutionType.Query || executionType === ExecutionType.QueryV1 ? QUERY_TIMEOUT_IN_MILLISECS : COMMAND_TIMEOUT_IN_MILLISECS;
226
- }
227
- close() {
228
- if (!this._isClosed) {
229
- this.cancelToken.cancel("Client Closed");
230
- }
231
- this._isClosed = true;
232
- }
233
- ensureOpen() {
234
- if (this._isClosed) {
235
- throw new Error("Client is closed");
236
- }
237
- }
238
- }
239
- exports.KustoClient = KustoClient;
240
- exports.default = KustoClient;
241
- //# sourceMappingURL=client.js.map
@@ -1,73 +0,0 @@
1
- "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
- var __importDefault = (this && this.__importDefault) || function (mod) {
12
- return (mod && mod.__esModule) ? mod : { "default": mod };
13
- };
14
- Object.defineProperty(exports, "__esModule", { value: true });
15
- exports.CloudSettings = void 0;
16
- // Copyright (c) Microsoft Corporation.
17
- // Licensed under the MIT License.
18
- const axios_1 = __importDefault(require("axios"));
19
- /**
20
- * This class holds data for all cloud instances, and returns the specific data instance by parsing the dns suffix from a URL
21
- */
22
- class CloudSettings {
23
- constructor() {
24
- this.METADATA_ENDPOINT = "/v1/rest/auth/metadata";
25
- this.defaultCloudInfo = {
26
- LoginEndpoint: process.env.AadAuthorityUri || "https://login.microsoftonline.com",
27
- LoginMfaRequired: false,
28
- KustoClientAppId: "db662dc1-0cfe-4e1c-a843-19a68e65be58",
29
- KustoClientRedirectUri: "https://microsoft/kustoclient",
30
- KustoServiceResourceId: "https://kusto.kusto.windows.net",
31
- FirstPartyAuthorityUrl: "https://login.microsoftonline.com/f8cdef31-a31e-4b4a-93e4-5f571e91255a",
32
- };
33
- this.cloudCache = {};
34
- }
35
- static getInstance() {
36
- if (!CloudSettings.instance) {
37
- CloudSettings.instance = new CloudSettings();
38
- }
39
- return CloudSettings.instance;
40
- }
41
- getCloudInfoForCluster(kustoUri) {
42
- var _a;
43
- return __awaiter(this, void 0, void 0, function* () {
44
- if (kustoUri in this.cloudCache) {
45
- return this.cloudCache[kustoUri];
46
- }
47
- try {
48
- const response = yield axios_1.default.get(kustoUri + this.METADATA_ENDPOINT);
49
- if (response.status === 200) {
50
- this.cloudCache[kustoUri] = response.data.AzureAD || this.defaultCloudInfo;
51
- }
52
- else {
53
- throw new Error(`Kusto returned an invalid cloud metadata response - ${response}`);
54
- }
55
- }
56
- catch (ex) {
57
- if (axios_1.default.isAxiosError(ex) && ((_a = ex.response) === null || _a === void 0 ? void 0 : _a.status) === 404) {
58
- // For now as long not all proxies implement the metadata endpoint, if no endpoint exists return public cloud data
59
- this.cloudCache[kustoUri] = this.defaultCloudInfo;
60
- }
61
- else {
62
- throw new Error(`Failed to get cloud info for cluster ${kustoUri} - ${ex}`);
63
- }
64
- }
65
- return this.cloudCache[kustoUri];
66
- });
67
- }
68
- static getAuthorityUri(cloudInfo, authorityId) {
69
- return cloudInfo.LoginEndpoint + "/" + (authorityId || "organizations");
70
- }
71
- }
72
- exports.CloudSettings = CloudSettings;
73
- //# sourceMappingURL=cloudSettings.js.map
@@ -1,45 +0,0 @@
1
- import { DeviceCodeResponse } from "@azure/msal-common";
2
- export declare class KustoConnectionStringBuilder {
3
- static readonly DefaultDatabaseName = "NetDefaultDB";
4
- static readonly SecretReplacement = "****";
5
- static defaultDeviceCallback: (response: DeviceCodeResponse) => void;
6
- dataSource?: string;
7
- aadFederatedSecurity?: boolean;
8
- initialCatalog?: string;
9
- aadUserId?: string;
10
- password?: string;
11
- applicationClientId?: string;
12
- msiClientId?: string;
13
- applicationKey?: string;
14
- applicationCertificatePrivateKey?: string;
15
- applicationCertificateThumbprint?: string;
16
- applicationCertificateX5c?: string;
17
- authorityId: string;
18
- deviceCodeCallback?: (response: DeviceCodeResponse) => void;
19
- tokenProvider?: () => Promise<string>;
20
- loginHint?: string;
21
- timeoutMs?: number;
22
- accessToken?: string;
23
- useDeviceCodeAuth?: boolean;
24
- useUserPromptAuth?: boolean;
25
- useAzLoginAuth?: boolean;
26
- useManagedIdentityAuth?: boolean;
27
- constructor(connectionString: string);
28
- toString(removeSecrets?: boolean): string;
29
- static fromExisting(other: KustoConnectionStringBuilder): KustoConnectionStringBuilder;
30
- static withAadUserPasswordAuthentication(connectionString: string, userId: string, password: string, authorityId?: string): KustoConnectionStringBuilder;
31
- static withAadApplicationKeyAuthentication(connectionString: string, aadAppId: string, appKey: string, authorityId?: string): KustoConnectionStringBuilder;
32
- static withAadApplicationCertificateAuthentication(connectionString: string, aadAppId: string, applicationCertificatePrivateKey: string, applicationCertificateThumbprint: string, authorityId?: string, applicationCertificateX5c?: string): KustoConnectionStringBuilder;
33
- static withAadDeviceAuthentication(connectionString: string, authorityId?: string, deviceCodeCallback?: (response: DeviceCodeResponse) => void): KustoConnectionStringBuilder;
34
- /**
35
- * @deprecated - use `withSystemManagedIdentity` or `withUserManagedIdentity` instead
36
- */
37
- static withAadManagedIdentities(connectionString: string, msiClientId?: string, authorityId?: string, timeoutMs?: number): KustoConnectionStringBuilder;
38
- static withSystemManagedIdentity(connectionString: string, authorityId?: string, timeoutMs?: number): KustoConnectionStringBuilder;
39
- static withUserManagedIdentity(connectionString: string, msiClientId: string, authorityId?: string, timeoutMs?: number): KustoConnectionStringBuilder;
40
- static withAzLoginIdentity(connectionString: string, authorityId?: string, timeoutMs?: number): KustoConnectionStringBuilder;
41
- static withAccessToken(connectionString: string, accessToken: string): KustoConnectionStringBuilder;
42
- static withTokenProvider(connectionString: string, tokenProvider: () => Promise<string>): KustoConnectionStringBuilder;
43
- static withUserPrompt(connectionString: string, authorityId?: string, clientId?: string, timeoutMs?: number, loginHint?: string): KustoConnectionStringBuilder;
44
- }
45
- export default KustoConnectionStringBuilder;
@@ -1,231 +0,0 @@
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 KeywordMapping = Object.freeze({
7
- dataSource: {
8
- mappedTo: "Data Source",
9
- validNames: ["data source", "addr", "address", "network address", "server"],
10
- },
11
- aadFederatedSecurity: {
12
- mappedTo: "AAD Federated Security",
13
- validNames: ["aad federated security", "federated security", "federated", "fed", "aadfed"],
14
- isBool: true,
15
- },
16
- initialCatalog: {
17
- mappedTo: "Initial Catalog",
18
- validNames: ["initial catalog", "database"],
19
- },
20
- aadUserId: {
21
- mappedTo: "AAD User ID",
22
- validNames: ["aad user id"],
23
- },
24
- password: {
25
- mappedTo: "Password",
26
- validNames: ["password", "pwd"],
27
- isSecret: true,
28
- },
29
- applicationClientId: {
30
- mappedTo: "Application Client Id",
31
- validNames: ["application client id", "appclientid"],
32
- },
33
- applicationKey: {
34
- mappedTo: "Application Key",
35
- validNames: ["application key", "appkey"],
36
- isSecret: true,
37
- },
38
- applicationCertificatePrivateKey: {
39
- mappedTo: "Application Certificate PrivateKey",
40
- validNames: ["Application Certificate PrivateKey"],
41
- isSecret: true,
42
- },
43
- applicationCertificateThumbprint: {
44
- mappedTo: "Application Certificate Thumbprint",
45
- validNames: ["application certificate thumbprint", "AppCert"],
46
- },
47
- applicationCertificateX5c: {
48
- mappedTo: "Application Certificate x5c",
49
- validNames: ["application certificate x5c", "Application Certificate Send Public Certificate", "Application Certificate SendX5c", "SendX5c"],
50
- },
51
- authorityId: {
52
- mappedTo: "Authority Id",
53
- validNames: ["authority id", "authorityid", "authority", "tenantid", "tenant", "tid"],
54
- },
55
- });
56
- const getPropName = (key) => {
57
- const _key = key.trim().toLowerCase();
58
- for (const keyword of Object.keys(KeywordMapping)) {
59
- const k = KeywordMapping[keyword];
60
- if (!k) {
61
- continue;
62
- }
63
- if (k.validNames.map((n) => n.trim().toLowerCase()).indexOf(_key) >= 0) {
64
- return [keyword, k];
65
- }
66
- }
67
- throw new Error("Failed to get prop: " + key);
68
- };
69
- class KustoConnectionStringBuilder {
70
- constructor(connectionString) {
71
- var _a;
72
- this.authorityId = "organizations";
73
- if (connectionString.trim().length === 0)
74
- throw new Error("Missing connection string");
75
- if (connectionString.endsWith("/") || connectionString.endsWith("\\")) {
76
- connectionString = connectionString.slice(0, -1);
77
- }
78
- if (!!connectionString && connectionString.split(";")[0].indexOf("=") === -1) {
79
- connectionString = "Data Source=" + connectionString;
80
- }
81
- const params = connectionString.split(";");
82
- for (const item of params) {
83
- const kvp = item.split("=");
84
- const [mappingTypeName, mappingType] = getPropName(kvp[0]);
85
- if (mappingType.isBool) {
86
- this[mappingTypeName] = kvp[1].trim().toLowerCase() === "true";
87
- }
88
- else {
89
- this[mappingTypeName] = (_a = kvp[1]) === null || _a === void 0 ? void 0 : _a.trim();
90
- }
91
- }
92
- if (!this.initialCatalog) {
93
- this.initialCatalog = KustoConnectionStringBuilder.DefaultDatabaseName;
94
- }
95
- }
96
- toString(removeSecrets = true) {
97
- return Object.entries(KeywordMapping)
98
- .map(([key, mappingType]) => {
99
- const value = this[key];
100
- if (!mappingType || value === undefined) {
101
- return "";
102
- }
103
- if (mappingType.isSecret && removeSecrets) {
104
- return `${mappingType.mappedTo}=${KustoConnectionStringBuilder.SecretReplacement}`;
105
- }
106
- return `${mappingType.mappedTo}=${value.toString()}`;
107
- })
108
- .filter((x) => x !== "")
109
- .join(";");
110
- }
111
- static fromExisting(other) {
112
- return Object.assign({}, other);
113
- }
114
- static withAadUserPasswordAuthentication(connectionString, userId, password, authorityId) {
115
- if (userId.trim().length === 0)
116
- throw new Error("Invalid user");
117
- if (password.trim().length === 0)
118
- throw new Error("Invalid password");
119
- const kcsb = new KustoConnectionStringBuilder(connectionString);
120
- kcsb.aadFederatedSecurity = true;
121
- kcsb.aadUserId = userId;
122
- kcsb.password = password;
123
- if (authorityId) {
124
- kcsb.authorityId = authorityId;
125
- }
126
- return kcsb;
127
- }
128
- static withAadApplicationKeyAuthentication(connectionString, aadAppId, appKey, authorityId) {
129
- if (aadAppId.trim().length === 0)
130
- throw new Error("Invalid app id");
131
- if (appKey.trim().length === 0)
132
- throw new Error("Invalid app key");
133
- const kcsb = new KustoConnectionStringBuilder(connectionString);
134
- kcsb.aadFederatedSecurity = true;
135
- kcsb.applicationClientId = aadAppId;
136
- kcsb.applicationKey = appKey;
137
- if (authorityId) {
138
- kcsb.authorityId = authorityId;
139
- }
140
- return kcsb;
141
- }
142
- static withAadApplicationCertificateAuthentication(connectionString, aadAppId, applicationCertificatePrivateKey, applicationCertificateThumbprint, authorityId, applicationCertificateX5c) {
143
- if (aadAppId.trim().length === 0)
144
- throw new Error("Invalid app id");
145
- if (applicationCertificatePrivateKey.trim().length === 0)
146
- throw new Error("Invalid certificate");
147
- if (applicationCertificateThumbprint.trim().length === 0)
148
- throw new Error("Invalid thumbprint");
149
- const kcsb = new KustoConnectionStringBuilder(connectionString);
150
- kcsb.aadFederatedSecurity = true;
151
- kcsb.applicationClientId = aadAppId;
152
- kcsb.applicationCertificatePrivateKey = applicationCertificatePrivateKey;
153
- kcsb.applicationCertificateThumbprint = applicationCertificateThumbprint;
154
- kcsb.applicationCertificateX5c = applicationCertificateX5c;
155
- if (authorityId) {
156
- kcsb.authorityId = authorityId;
157
- }
158
- return kcsb;
159
- }
160
- static withAadDeviceAuthentication(connectionString, authorityId, deviceCodeCallback = KustoConnectionStringBuilder.defaultDeviceCallback) {
161
- const kcsb = new KustoConnectionStringBuilder(connectionString);
162
- kcsb.aadFederatedSecurity = true;
163
- if (authorityId) {
164
- kcsb.authorityId = authorityId;
165
- }
166
- kcsb.deviceCodeCallback = deviceCodeCallback;
167
- kcsb.useDeviceCodeAuth = true;
168
- return kcsb;
169
- }
170
- /**
171
- * @deprecated - use `withSystemManagedIdentity` or `withUserManagedIdentity` instead
172
- */
173
- static withAadManagedIdentities(connectionString, msiClientId, authorityId, timeoutMs) {
174
- const kcsb = new KustoConnectionStringBuilder(connectionString);
175
- kcsb.aadFederatedSecurity = true;
176
- if (authorityId) {
177
- kcsb.authorityId = authorityId;
178
- }
179
- kcsb.msiClientId = msiClientId;
180
- kcsb.timeoutMs = timeoutMs;
181
- kcsb.useManagedIdentityAuth = true;
182
- return kcsb;
183
- }
184
- static withSystemManagedIdentity(connectionString, authorityId, timeoutMs) {
185
- return this.withAadManagedIdentities(connectionString, undefined, authorityId, timeoutMs);
186
- }
187
- static withUserManagedIdentity(connectionString, msiClientId, authorityId, timeoutMs) {
188
- return this.withAadManagedIdentities(connectionString, msiClientId, authorityId, timeoutMs);
189
- }
190
- static withAzLoginIdentity(connectionString, authorityId, timeoutMs) {
191
- const kcsb = new KustoConnectionStringBuilder(connectionString);
192
- kcsb.aadFederatedSecurity = true;
193
- kcsb.useAzLoginAuth = true;
194
- if (authorityId) {
195
- kcsb.authorityId = authorityId;
196
- }
197
- kcsb.timeoutMs = timeoutMs;
198
- return kcsb;
199
- }
200
- static withAccessToken(connectionString, accessToken) {
201
- const kcsb = new KustoConnectionStringBuilder(connectionString);
202
- kcsb.aadFederatedSecurity = true;
203
- kcsb.accessToken = accessToken;
204
- return kcsb;
205
- }
206
- static withTokenProvider(connectionString, tokenProvider) {
207
- const kcsb = new KustoConnectionStringBuilder(connectionString);
208
- kcsb.aadFederatedSecurity = true;
209
- kcsb.tokenProvider = tokenProvider;
210
- return kcsb;
211
- }
212
- static withUserPrompt(connectionString, authorityId, clientId, timeoutMs, loginHint) {
213
- const kcsb = new KustoConnectionStringBuilder(connectionString);
214
- kcsb.aadFederatedSecurity = true;
215
- kcsb.useUserPromptAuth = true;
216
- if (authorityId) {
217
- kcsb.authorityId = authorityId;
218
- }
219
- kcsb.loginHint = loginHint;
220
- kcsb.applicationClientId = clientId;
221
- kcsb.timeoutMs = timeoutMs;
222
- return kcsb;
223
- }
224
- }
225
- exports.KustoConnectionStringBuilder = KustoConnectionStringBuilder;
226
- KustoConnectionStringBuilder.DefaultDatabaseName = "NetDefaultDB";
227
- KustoConnectionStringBuilder.SecretReplacement = "****";
228
- // eslint-disable-next-line no-console
229
- KustoConnectionStringBuilder.defaultDeviceCallback = (response) => console.log(response.message);
230
- exports.default = KustoConnectionStringBuilder;
231
- //# sourceMappingURL=connectionBuilder.js.map