@microsoft/teamsfx 2.3.3-beta.2024091206.0 → 3.0.0-alpha.c1ca4fa41.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.
@@ -1,482 +1,487 @@
1
- import jwt_decode from 'jwt-decode';
1
+ import { jwtDecode } from 'jwt-decode';
2
2
  import { app, authentication } from '@microsoft/teams-js';
3
3
  import { PublicClientApplication } from '@azure/msal-browser';
4
- import { Client } from '@microsoft/microsoft-graph-client';
5
4
  import axios from 'axios';
6
5
 
7
- // Copyright (c) Microsoft Corporation.
8
- // Licensed under the MIT license.
9
- /**
10
- * Error code to trace the error types.
11
- */
12
- var ErrorCode;
13
- (function (ErrorCode) {
14
- /**
15
- * Invalid parameter error.
16
- */
17
- ErrorCode["InvalidParameter"] = "InvalidParameter";
18
- /**
19
- * Invalid configuration error.
20
- */
21
- ErrorCode["InvalidConfiguration"] = "InvalidConfiguration";
22
- /**
23
- * Invalid certificate error.
24
- */
25
- ErrorCode["InvalidCertificate"] = "InvalidCertificate";
26
- /**
27
- * Internal error.
28
- */
29
- ErrorCode["InternalError"] = "InternalError";
30
- /**
31
- * Channel is not supported error.
32
- */
33
- ErrorCode["ChannelNotSupported"] = "ChannelNotSupported";
34
- /**
35
- * Failed to retrieve sso token
36
- */
37
- ErrorCode["FailedToRetrieveSsoToken"] = "FailedToRetrieveSsoToken";
38
- /**
39
- * Failed to process sso handler
40
- */
41
- ErrorCode["FailedToProcessSsoHandler"] = "FailedToProcessSsoHandler";
42
- /**
43
- * Cannot find command
44
- */
45
- ErrorCode["CannotFindCommand"] = "CannotFindCommand";
46
- /**
47
- * Failed to run sso step
48
- */
49
- ErrorCode["FailedToRunSsoStep"] = "FailedToRunSsoStep";
50
- /**
51
- * Failed to run dedup step
52
- */
53
- ErrorCode["FailedToRunDedupStep"] = "FailedToRunDedupStep";
54
- /**
55
- * Sso activity handler is undefined
56
- */
57
- ErrorCode["SsoActivityHandlerIsUndefined"] = "SsoActivityHandlerIsUndefined";
58
- /**
59
- * Runtime is not supported error.
60
- */
61
- ErrorCode["RuntimeNotSupported"] = "RuntimeNotSupported";
62
- /**
63
- * User failed to finish the AAD consent flow failed.
64
- */
65
- ErrorCode["ConsentFailed"] = "ConsentFailed";
66
- /**
67
- * The user or administrator has not consented to use the application error.
68
- */
69
- ErrorCode["UiRequiredError"] = "UiRequiredError";
70
- /**
71
- * Token is not within its valid time range error.
72
- */
73
- ErrorCode["TokenExpiredError"] = "TokenExpiredError";
74
- /**
75
- * Call service (AAD or simple authentication server) failed.
76
- */
77
- ErrorCode["ServiceError"] = "ServiceError";
78
- /**
79
- * Operation failed.
80
- */
81
- ErrorCode["FailedOperation"] = "FailedOperation";
82
- /**
83
- * Invalid response error.
84
- */
85
- ErrorCode["InvalidResponse"] = "InvalidResponse";
86
- /**
87
- * Identity type error.
88
- */
89
- ErrorCode["IdentityTypeNotSupported"] = "IdentityTypeNotSupported";
90
- /**
91
- * Authentication info already exists error.
92
- */
93
- ErrorCode["AuthorizationInfoAlreadyExists"] = "AuthorizationInfoAlreadyExists";
94
- })(ErrorCode || (ErrorCode = {}));
95
- /**
96
- * @internal
97
- */
98
- class ErrorMessage {
99
- }
100
- // InvalidConfiguration Error
101
- ErrorMessage.InvalidConfiguration = "{0} in configuration is invalid: {1}.";
102
- ErrorMessage.ConfigurationNotExists = "Configuration does not exist. {0}";
103
- ErrorMessage.ResourceConfigurationNotExists = "{0} resource configuration does not exist.";
104
- ErrorMessage.MissingResourceConfiguration = "Missing resource configuration with type: {0}, name: {1}.";
105
- ErrorMessage.AuthenticationConfigurationNotExists = "Authentication configuration does not exist.";
106
- // RuntimeNotSupported Error
107
- ErrorMessage.BrowserRuntimeNotSupported = "{0} is not supported in browser.";
108
- ErrorMessage.NodejsRuntimeNotSupported = "{0} is not supported in Node.";
109
- // Internal Error
110
- ErrorMessage.FailToAcquireTokenOnBehalfOfUser = "Failed to acquire access token on behalf of user: {0}";
111
- // ChannelNotSupported Error
112
- ErrorMessage.OnlyMSTeamsChannelSupported = "{0} is only supported in MS Teams Channel";
113
- ErrorMessage.FailedToProcessSsoHandler = "Failed to process sso handler: {0}";
114
- // FailedToRetrieveSsoToken Error
115
- ErrorMessage.FailedToRetrieveSsoToken = "Failed to retrieve sso token, user failed to finish the AAD consent flow.";
116
- // CannotFindCommand Error
117
- ErrorMessage.CannotFindCommand = "Cannot find command: {0}";
118
- ErrorMessage.FailedToRunSsoStep = "Failed to run dialog to retrieve sso token: {0}";
119
- ErrorMessage.FailedToRunDedupStep = "Failed to run dialog to remove duplicated messages: {0}";
120
- // SsoActivityHandlerIsUndefined Error
121
- ErrorMessage.SsoActivityHandlerIsNull = "Sso command can only be used or added when sso activity handler is not undefined";
122
- // IdentityTypeNotSupported Error
123
- ErrorMessage.IdentityTypeNotSupported = "{0} identity is not supported in {1}";
124
- // AuthorizationInfoError
125
- ErrorMessage.AuthorizationHeaderAlreadyExists = "Authorization header already exists!";
126
- ErrorMessage.BasicCredentialAlreadyExists = "Basic credential already exists!";
127
- // InvalidParameter Error
128
- ErrorMessage.EmptyParameter = "Parameter {0} is empty";
129
- ErrorMessage.DuplicateHttpsOptionProperty = "Axios HTTPS agent already defined value for property {0}";
130
- ErrorMessage.DuplicateApiKeyInHeader = "The request already defined api key in request header with name {0}.";
131
- ErrorMessage.DuplicateApiKeyInQueryParam = "The request already defined api key in query parameter with name {0}.";
132
- ErrorMessage.OnlySupportInQueryActivity = "The handleMessageExtensionQueryWithToken only support in handleTeamsMessagingExtensionQuery with composeExtension/query type.";
133
- ErrorMessage.OnlySupportInLinkQueryActivity = "The handleMessageExtensionLinkQueryWithSSO only support in handleTeamsAppBasedLinkQuery with composeExtension/queryLink type.";
134
- /**
135
- * Error class with code and message thrown by the SDK.
136
- */
137
- class ErrorWithCode extends Error {
138
- /**
139
- * Constructor of ErrorWithCode.
140
- *
141
- * @param {string} message - error message.
142
- * @param {ErrorCode} code - error code.
143
- */
144
- constructor(message, code) {
145
- if (!code) {
146
- super(message);
147
- return this;
148
- }
149
- super(message);
150
- Object.setPrototypeOf(this, ErrorWithCode.prototype);
151
- this.name = `${new.target.name}.${code}`;
152
- this.code = code;
153
- }
6
+ // Copyright (c) Microsoft Corporation.
7
+ // Licensed under the MIT license.
8
+ /**
9
+ * Error code to trace the error types.
10
+ */
11
+ var ErrorCode;
12
+ (function (ErrorCode) {
13
+ /**
14
+ * Invalid parameter error.
15
+ */
16
+ ErrorCode["InvalidParameter"] = "InvalidParameter";
17
+ /**
18
+ * Invalid configuration error.
19
+ */
20
+ ErrorCode["InvalidConfiguration"] = "InvalidConfiguration";
21
+ /**
22
+ * Invalid certificate error.
23
+ */
24
+ ErrorCode["InvalidCertificate"] = "InvalidCertificate";
25
+ /**
26
+ * Internal error.
27
+ */
28
+ ErrorCode["InternalError"] = "InternalError";
29
+ /**
30
+ * Channel is not supported error.
31
+ */
32
+ ErrorCode["ChannelNotSupported"] = "ChannelNotSupported";
33
+ /**
34
+ * Failed to retrieve sso token
35
+ */
36
+ ErrorCode["FailedToRetrieveSsoToken"] = "FailedToRetrieveSsoToken";
37
+ /**
38
+ * Failed to process sso handler
39
+ */
40
+ ErrorCode["FailedToProcessSsoHandler"] = "FailedToProcessSsoHandler";
41
+ /**
42
+ * Cannot find command
43
+ */
44
+ ErrorCode["CannotFindCommand"] = "CannotFindCommand";
45
+ /**
46
+ * Failed to run sso step
47
+ */
48
+ ErrorCode["FailedToRunSsoStep"] = "FailedToRunSsoStep";
49
+ /**
50
+ * Failed to run dedup step
51
+ */
52
+ ErrorCode["FailedToRunDedupStep"] = "FailedToRunDedupStep";
53
+ /**
54
+ * Sso activity handler is undefined
55
+ */
56
+ ErrorCode["SsoActivityHandlerIsUndefined"] = "SsoActivityHandlerIsUndefined";
57
+ /**
58
+ * Runtime is not supported error.
59
+ */
60
+ ErrorCode["RuntimeNotSupported"] = "RuntimeNotSupported";
61
+ /**
62
+ * User failed to finish the AAD consent flow failed.
63
+ */
64
+ ErrorCode["ConsentFailed"] = "ConsentFailed";
65
+ /**
66
+ * The user or administrator has not consented to use the application error.
67
+ */
68
+ ErrorCode["UiRequiredError"] = "UiRequiredError";
69
+ /**
70
+ * Token is not within its valid time range error.
71
+ */
72
+ ErrorCode["TokenExpiredError"] = "TokenExpiredError";
73
+ /**
74
+ * Call service (AAD or simple authentication server) failed.
75
+ */
76
+ ErrorCode["ServiceError"] = "ServiceError";
77
+ /**
78
+ * Operation failed.
79
+ */
80
+ ErrorCode["FailedOperation"] = "FailedOperation";
81
+ /**
82
+ * Invalid response error.
83
+ */
84
+ ErrorCode["InvalidResponse"] = "InvalidResponse";
85
+ /**
86
+ * Authentication info already exists error.
87
+ */
88
+ ErrorCode["AuthorizationInfoAlreadyExists"] = "AuthorizationInfoAlreadyExists";
89
+ })(ErrorCode || (ErrorCode = {}));
90
+ /**
91
+ * @internal
92
+ */
93
+ class ErrorMessage {
94
+ }
95
+ // InvalidConfiguration Error
96
+ ErrorMessage.InvalidConfiguration = "{0} in configuration is invalid: {1}.";
97
+ ErrorMessage.ConfigurationNotExists = "Configuration does not exist. {0}";
98
+ ErrorMessage.ResourceConfigurationNotExists = "{0} resource configuration does not exist.";
99
+ ErrorMessage.MissingResourceConfiguration = "Missing resource configuration with type: {0}, name: {1}.";
100
+ ErrorMessage.AuthenticationConfigurationNotExists = "Authentication configuration does not exist.";
101
+ // RuntimeNotSupported Error
102
+ ErrorMessage.BrowserRuntimeNotSupported = "{0} is not supported in browser.";
103
+ ErrorMessage.NodejsRuntimeNotSupported = "{0} is not supported in Node.";
104
+ // Internal Error
105
+ ErrorMessage.FailToAcquireTokenOnBehalfOfUser = "Failed to acquire access token on behalf of user: {0}";
106
+ // ChannelNotSupported Error
107
+ ErrorMessage.OnlyMSTeamsChannelSupported = "{0} is only supported in MS Teams Channel";
108
+ ErrorMessage.FailedToProcessSsoHandler = "Failed to process sso handler: {0}";
109
+ // FailedToRetrieveSsoToken Error
110
+ ErrorMessage.FailedToRetrieveSsoToken = "Failed to retrieve sso token, user failed to finish the AAD consent flow.";
111
+ // CannotFindCommand Error
112
+ ErrorMessage.CannotFindCommand = "Cannot find command: {0}";
113
+ ErrorMessage.FailedToRunSsoStep = "Failed to run dialog to retrieve sso token: {0}";
114
+ ErrorMessage.FailedToRunDedupStep = "Failed to run dialog to remove duplicated messages: {0}";
115
+ // SsoActivityHandlerIsUndefined Error
116
+ ErrorMessage.SsoActivityHandlerIsNull = "Sso command can only be used or added when sso activity handler is not undefined";
117
+ // AuthorizationInfoError
118
+ ErrorMessage.AuthorizationHeaderAlreadyExists = "Authorization header already exists!";
119
+ ErrorMessage.BasicCredentialAlreadyExists = "Basic credential already exists!";
120
+ // InvalidParameter Error
121
+ ErrorMessage.EmptyParameter = "Parameter {0} is empty";
122
+ ErrorMessage.DuplicateHttpsOptionProperty = "Axios HTTPS agent already defined value for property {0}";
123
+ ErrorMessage.DuplicateApiKeyInHeader = "The request already defined api key in request header with name {0}.";
124
+ ErrorMessage.DuplicateApiKeyInQueryParam = "The request already defined api key in query parameter with name {0}.";
125
+ ErrorMessage.OnlySupportInQueryActivity = "The handleMessageExtensionQueryWithToken only support in handleTeamsMessagingExtensionQuery with composeExtension/query type.";
126
+ ErrorMessage.OnlySupportInLinkQueryActivity = "The handleMessageExtensionLinkQueryWithSSO only support in handleTeamsAppBasedLinkQuery with composeExtension/queryLink type.";
127
+ /**
128
+ * Error class with code and message thrown by the SDK.
129
+ */
130
+ class ErrorWithCode extends Error {
131
+ /**
132
+ * Constructor of ErrorWithCode.
133
+ *
134
+ * @param {string} message - error message.
135
+ * @param {ErrorCode} code - error code.
136
+ */
137
+ constructor(message, code) {
138
+ if (!code) {
139
+ super(message);
140
+ return this;
141
+ }
142
+ super(message);
143
+ Object.setPrototypeOf(this, ErrorWithCode.prototype);
144
+ this.name = `${new.target.name}.${code}`;
145
+ this.code = code;
146
+ }
154
147
  }
155
148
 
156
- // Copyright (c) Microsoft Corporation.
157
- // Licensed under the MIT license.
158
- /**
159
- * Log level.
160
- */
161
- var LogLevel;
162
- (function (LogLevel) {
163
- /**
164
- * Show verbose, information, warning and error message.
165
- */
166
- LogLevel[LogLevel["Verbose"] = 0] = "Verbose";
167
- /**
168
- * Show information, warning and error message.
169
- */
170
- LogLevel[LogLevel["Info"] = 1] = "Info";
171
- /**
172
- * Show warning and error message.
173
- */
174
- LogLevel[LogLevel["Warn"] = 2] = "Warn";
175
- /**
176
- * Show error message.
177
- */
178
- LogLevel[LogLevel["Error"] = 3] = "Error";
179
- })(LogLevel || (LogLevel = {}));
180
- /**
181
- * Update log level helper.
182
- *
183
- * @param { LogLevel } level - log level in configuration
184
- */
185
- function setLogLevel(level) {
186
- internalLogger.level = level;
187
- }
188
- /**
189
- * Get log level.
190
- *
191
- * @returns Log level
192
- */
193
- function getLogLevel() {
194
- return internalLogger.level;
195
- }
196
- class InternalLogger {
197
- constructor(name, logLevel) {
198
- this.level = undefined;
199
- this.defaultLogger = {
200
- verbose: console.debug,
201
- info: console.info,
202
- warn: console.warn,
203
- error: console.error,
204
- };
205
- this.name = name;
206
- this.level = logLevel;
207
- }
208
- error(message) {
209
- this.log(LogLevel.Error, (x) => x.error, message);
210
- }
211
- warn(message) {
212
- this.log(LogLevel.Warn, (x) => x.warn, message);
213
- }
214
- info(message) {
215
- this.log(LogLevel.Info, (x) => x.info, message);
216
- }
217
- verbose(message) {
218
- this.log(LogLevel.Verbose, (x) => x.verbose, message);
219
- }
220
- log(logLevel, logFunction, message) {
221
- if (message.trim() === "") {
222
- return;
223
- }
224
- const timestamp = new Date().toUTCString();
225
- let logHeader;
226
- if (this.name) {
227
- logHeader = `[${timestamp}] : @microsoft/teamsfx - ${this.name} : ${LogLevel[logLevel]} - `;
228
- }
229
- else {
230
- logHeader = `[${timestamp}] : @microsoft/teamsfx : ${LogLevel[logLevel]} - `;
231
- }
232
- const logMessage = `${logHeader}${message}`;
233
- if (this.level !== undefined && this.level <= logLevel) {
234
- if (this.customLogger) {
235
- logFunction(this.customLogger)(logMessage);
236
- }
237
- else if (this.customLogFunction) {
238
- this.customLogFunction(logLevel, logMessage);
239
- }
240
- else {
241
- logFunction(this.defaultLogger)(logMessage);
242
- }
243
- }
244
- }
245
- }
246
- /**
247
- * Logger instance used internally
248
- *
249
- * @internal
250
- */
251
- const internalLogger = new InternalLogger();
252
- /**
253
- * Set custom logger. Use the output functions if it's set. Priority is higher than setLogFunction.
254
- *
255
- * @param {Logger} logger - custom logger. If it's undefined, custom logger will be cleared.
256
- *
257
- * @example
258
- * ```typescript
259
- * setLogger({
260
- * verbose: console.debug,
261
- * info: console.info,
262
- * warn: console.warn,
263
- * error: console.error,
264
- * });
265
- * ```
266
- */
267
- function setLogger(logger) {
268
- internalLogger.customLogger = logger;
269
- }
270
- /**
271
- * Set custom log function. Use the function if it's set. Priority is lower than setLogger.
272
- *
273
- * @param {LogFunction} logFunction - custom log function. If it's undefined, custom log function will be cleared.
274
- *
275
- * @example
276
- * ```typescript
277
- * setLogFunction((level: LogLevel, message: string) => {
278
- * if (level === LogLevel.Error) {
279
- * console.log(message);
280
- * }
281
- * });
282
- * ```
283
- */
284
- function setLogFunction(logFunction) {
285
- internalLogger.customLogFunction = logFunction;
149
+ // Copyright (c) Microsoft Corporation.
150
+ // Licensed under the MIT license.
151
+ /**
152
+ * Log level.
153
+ */
154
+ var LogLevel;
155
+ (function (LogLevel) {
156
+ /**
157
+ * Show verbose, information, warning and error message.
158
+ */
159
+ LogLevel[LogLevel["Verbose"] = 0] = "Verbose";
160
+ /**
161
+ * Show information, warning and error message.
162
+ */
163
+ LogLevel[LogLevel["Info"] = 1] = "Info";
164
+ /**
165
+ * Show warning and error message.
166
+ */
167
+ LogLevel[LogLevel["Warn"] = 2] = "Warn";
168
+ /**
169
+ * Show error message.
170
+ */
171
+ LogLevel[LogLevel["Error"] = 3] = "Error";
172
+ })(LogLevel || (LogLevel = {}));
173
+ /**
174
+ * Update log level helper.
175
+ *
176
+ * @param { LogLevel } level - log level in configuration
177
+ */
178
+ function setLogLevel(level) {
179
+ internalLogger.level = level;
180
+ }
181
+ /**
182
+ * Get log level.
183
+ *
184
+ * @returns Log level
185
+ */
186
+ function getLogLevel() {
187
+ return internalLogger.level;
188
+ }
189
+ class InternalLogger {
190
+ constructor(name, logLevel) {
191
+ this.level = undefined;
192
+ this.defaultLogger = {
193
+ verbose: console.debug,
194
+ info: console.info,
195
+ warn: console.warn,
196
+ error: console.error,
197
+ };
198
+ this.name = name;
199
+ this.level = logLevel;
200
+ }
201
+ error(message) {
202
+ this.log(LogLevel.Error, (x) => x.error, message);
203
+ }
204
+ warn(message) {
205
+ this.log(LogLevel.Warn, (x) => x.warn, message);
206
+ }
207
+ info(message) {
208
+ this.log(LogLevel.Info, (x) => x.info, message);
209
+ }
210
+ verbose(message) {
211
+ this.log(LogLevel.Verbose, (x) => x.verbose, message);
212
+ }
213
+ log(logLevel, logFunction, message) {
214
+ if (message.trim() === "") {
215
+ return;
216
+ }
217
+ const timestamp = new Date().toUTCString();
218
+ let logHeader;
219
+ if (this.name) {
220
+ logHeader = `[${timestamp}] : @microsoft/teamsfx - ${this.name} : ${LogLevel[logLevel]} - `;
221
+ }
222
+ else {
223
+ logHeader = `[${timestamp}] : @microsoft/teamsfx : ${LogLevel[logLevel]} - `;
224
+ }
225
+ const logMessage = `${logHeader}${message}`;
226
+ if (this.level !== undefined && this.level <= logLevel) {
227
+ if (this.customLogger) {
228
+ logFunction(this.customLogger)(logMessage);
229
+ }
230
+ else if (this.customLogFunction) {
231
+ this.customLogFunction(logLevel, logMessage);
232
+ }
233
+ else {
234
+ logFunction(this.defaultLogger)(logMessage);
235
+ }
236
+ }
237
+ }
238
+ }
239
+ /**
240
+ * Logger instance used internally
241
+ *
242
+ * @internal
243
+ */
244
+ const internalLogger = new InternalLogger();
245
+ /**
246
+ * Set custom logger. Use the output functions if it's set. Priority is higher than setLogFunction.
247
+ *
248
+ * @param {Logger} logger - custom logger. If it's undefined, custom logger will be cleared.
249
+ *
250
+ * @example
251
+ * ```typescript
252
+ * setLogger({
253
+ * verbose: console.debug,
254
+ * info: console.info,
255
+ * warn: console.warn,
256
+ * error: console.error,
257
+ * });
258
+ * ```
259
+ */
260
+ function setLogger(logger) {
261
+ internalLogger.customLogger = logger;
262
+ }
263
+ /**
264
+ * Set custom log function. Use the function if it's set. Priority is lower than setLogger.
265
+ *
266
+ * @param {LogFunction} logFunction - custom log function. If it's undefined, custom log function will be cleared.
267
+ *
268
+ * @example
269
+ * ```typescript
270
+ * setLogFunction((level: LogLevel, message: string) => {
271
+ * if (level === LogLevel.Error) {
272
+ * console.log(message);
273
+ * }
274
+ * });
275
+ * ```
276
+ */
277
+ function setLogFunction(logFunction) {
278
+ internalLogger.customLogFunction = logFunction;
286
279
  }
287
280
 
288
- // Copyright (c) Microsoft Corporation.
289
- /**
290
- * Parse jwt token payload
291
- *
292
- * @param token
293
- *
294
- * @returns Payload object
295
- *
296
- * @internal
297
- */
298
- function parseJwt(token) {
299
- try {
300
- const tokenObj = jwt_decode(token);
301
- if (!tokenObj || !tokenObj.exp) {
302
- throw new ErrorWithCode("Decoded token is null or exp claim does not exists.", ErrorCode.InternalError);
303
- }
304
- return tokenObj;
305
- }
306
- catch (err) {
307
- const errorMsg = "Parse jwt token failed in node env with error: " + err.message;
308
- internalLogger.error(errorMsg);
309
- throw new ErrorWithCode(errorMsg, ErrorCode.InternalError);
310
- }
311
- }
312
- /**
313
- * @internal
314
- */
315
- function getUserInfoFromSsoToken(ssoToken) {
316
- if (!ssoToken) {
317
- const errorMsg = "SSO token is undefined.";
318
- internalLogger.error(errorMsg);
319
- throw new ErrorWithCode(errorMsg, ErrorCode.InvalidParameter);
320
- }
321
- const tokenObject = parseJwt(ssoToken);
322
- const userInfo = {
323
- displayName: tokenObject.name,
324
- objectId: tokenObject.oid,
325
- tenantId: tokenObject.tid,
326
- preferredUserName: "",
327
- };
328
- if (tokenObject.ver === "2.0") {
329
- userInfo.preferredUserName = tokenObject.preferred_username;
330
- }
331
- else if (tokenObject.ver === "1.0") {
332
- userInfo.preferredUserName = tokenObject.upn;
333
- }
334
- return userInfo;
335
- }
336
- /**
337
- * @internal
338
- */
339
- function getTenantIdAndLoginHintFromSsoToken(ssoToken) {
340
- if (!ssoToken) {
341
- const errorMsg = "SSO token is undefined.";
342
- internalLogger.error(errorMsg);
343
- throw new ErrorWithCode(errorMsg, ErrorCode.InvalidParameter);
344
- }
345
- const tokenObject = parseJwt(ssoToken);
346
- const userInfo = {
347
- tid: tokenObject.tid,
348
- loginHint: tokenObject.ver === "2.0"
349
- ? tokenObject.preferred_username
350
- : tokenObject.upn,
351
- };
352
- return userInfo;
353
- }
354
- /**
355
- * @internal
356
- */
357
- function parseAccessTokenFromAuthCodeTokenResponse(tokenResponse) {
358
- try {
359
- const tokenResponseObject = typeof tokenResponse == "string"
360
- ? JSON.parse(tokenResponse)
361
- : tokenResponse;
362
- if (!tokenResponseObject || !tokenResponseObject.accessToken) {
363
- const errorMsg = "Get empty access token from Auth Code token response.";
364
- internalLogger.error(errorMsg);
365
- throw new Error(errorMsg);
366
- }
367
- const token = tokenResponseObject.accessToken;
368
- const tokenObject = parseJwt(token);
369
- if (tokenObject.ver !== "1.0" && tokenObject.ver !== "2.0") {
370
- const errorMsg = "SSO token is not valid with an unknown version: " + tokenObject.ver;
371
- internalLogger.error(errorMsg);
372
- throw new Error(errorMsg);
373
- }
374
- const accessToken = {
375
- token: token,
376
- expiresOnTimestamp: tokenObject.exp * 1000,
377
- };
378
- return accessToken;
379
- }
380
- catch (error) {
381
- const errorMsg = "Parse access token failed from Auth Code token response in node env with error: " +
382
- error.message;
383
- internalLogger.error(errorMsg);
384
- throw new ErrorWithCode(errorMsg, ErrorCode.InternalError);
385
- }
386
- }
387
- /**
388
- * Format string template with replacements
389
- *
390
- * ```typescript
391
- * const template = "{0} and {1} are fruit. {0} is my favorite one."
392
- * const formattedStr = formatString(template, "apple", "pear"); // formattedStr: "apple and pear are fruit. apple is my favorite one."
393
- * ```
394
- *
395
- * @param str string template
396
- * @param replacements replacement string array
397
- * @returns Formatted string
398
- *
399
- * @internal
400
- */
401
- function formatString(str, ...replacements) {
402
- const args = replacements;
403
- return str.replace(/{(\d+)}/g, function (match, number) {
404
- return typeof args[number] != "undefined" ? args[number] : match;
405
- });
406
- }
407
- /**
408
- * @internal
409
- */
410
- function validateScopesType(value) {
411
- // string
412
- if (typeof value === "string" || value instanceof String) {
413
- return;
414
- }
415
- // empty array
416
- if (Array.isArray(value) && value.length === 0) {
417
- return;
418
- }
419
- // string array
420
- if (Array.isArray(value) && value.length > 0 && value.every((item) => typeof item === "string")) {
421
- return;
422
- }
423
- const errorMsg = "The type of scopes is not valid, it must be string or string array";
424
- internalLogger.error(errorMsg);
425
- throw new ErrorWithCode(errorMsg, ErrorCode.InvalidParameter);
281
+ // Copyright (c) Microsoft Corporation.
282
+ /**
283
+ * Parse jwt token payload
284
+ *
285
+ * @param token
286
+ *
287
+ * @returns Payload object
288
+ *
289
+ * @internal
290
+ */
291
+ function parseJwt(token) {
292
+ try {
293
+ const tokenObj = jwtDecode(token);
294
+ if (!tokenObj || !tokenObj.exp) {
295
+ throw new ErrorWithCode("Decoded token is null or exp claim does not exists.", ErrorCode.InternalError);
296
+ }
297
+ return tokenObj;
298
+ }
299
+ catch (err) {
300
+ const errorMsg = "Parse jwt token failed in node env with error: " + err.message;
301
+ internalLogger.error(errorMsg);
302
+ throw new ErrorWithCode(errorMsg, ErrorCode.InternalError);
303
+ }
304
+ }
305
+ /**
306
+ * @internal
307
+ */
308
+ function getUserInfoFromSsoToken(ssoToken) {
309
+ if (!ssoToken) {
310
+ const errorMsg = "SSO token is undefined.";
311
+ internalLogger.error(errorMsg);
312
+ throw new ErrorWithCode(errorMsg, ErrorCode.InvalidParameter);
313
+ }
314
+ const tokenObject = parseJwt(ssoToken);
315
+ const userInfo = {
316
+ displayName: tokenObject.name,
317
+ objectId: tokenObject.oid,
318
+ tenantId: tokenObject.tid,
319
+ preferredUserName: "",
320
+ };
321
+ if (tokenObject.ver === "2.0") {
322
+ userInfo.preferredUserName = tokenObject.preferred_username;
323
+ }
324
+ else if (tokenObject.ver === "1.0") {
325
+ userInfo.preferredUserName = tokenObject.upn;
326
+ }
327
+ return userInfo;
328
+ }
329
+ /**
330
+ * @internal
331
+ */
332
+ function getTenantIdAndLoginHintFromSsoToken(ssoToken) {
333
+ if (!ssoToken) {
334
+ const errorMsg = "SSO token is undefined.";
335
+ internalLogger.error(errorMsg);
336
+ throw new ErrorWithCode(errorMsg, ErrorCode.InvalidParameter);
337
+ }
338
+ const tokenObject = parseJwt(ssoToken);
339
+ const userInfo = {
340
+ tid: tokenObject.tid,
341
+ loginHint: tokenObject.ver === "2.0"
342
+ ? tokenObject.preferred_username
343
+ : tokenObject.upn,
344
+ };
345
+ return userInfo;
346
+ }
347
+ /**
348
+ * @internal
349
+ */
350
+ function parseAccessTokenFromAuthCodeTokenResponse(tokenResponse) {
351
+ try {
352
+ const tokenResponseObject = typeof tokenResponse == "string"
353
+ ? JSON.parse(tokenResponse)
354
+ : tokenResponse;
355
+ if (!tokenResponseObject || !tokenResponseObject.accessToken) {
356
+ const errorMsg = "Get empty access token from Auth Code token response.";
357
+ internalLogger.error(errorMsg);
358
+ throw new Error(errorMsg);
359
+ }
360
+ const token = tokenResponseObject.accessToken;
361
+ const tokenObject = parseJwt(token);
362
+ if (tokenObject.ver !== "1.0" && tokenObject.ver !== "2.0") {
363
+ const errorMsg = "SSO token is not valid with an unknown version: " + tokenObject.ver;
364
+ internalLogger.error(errorMsg);
365
+ throw new Error(errorMsg);
366
+ }
367
+ const accessToken = {
368
+ token: token,
369
+ expiresOnTimestamp: tokenObject.exp * 1000,
370
+ };
371
+ return accessToken;
372
+ }
373
+ catch (error) {
374
+ const errorMsg = "Parse access token failed from Auth Code token response in node env with error: " +
375
+ error.message;
376
+ internalLogger.error(errorMsg);
377
+ throw new ErrorWithCode(errorMsg, ErrorCode.InternalError);
378
+ }
379
+ }
380
+ /**
381
+ * Format string template with replacements
382
+ *
383
+ * ```typescript
384
+ * const template = "{0} and {1} are fruit. {0} is my favorite one."
385
+ * const formattedStr = formatString(template, "apple", "pear"); // formattedStr: "apple and pear are fruit. apple is my favorite one."
386
+ * ```
387
+ *
388
+ * @param str string template
389
+ * @param replacements replacement string array
390
+ * @returns Formatted string
391
+ *
392
+ * @internal
393
+ */
394
+ function formatString(str, ...replacements) {
395
+ const args = replacements;
396
+ return str.replace(/{(\d+)}/g, function (match, number) {
397
+ return typeof args[number] != "undefined" ? args[number] : match;
398
+ });
399
+ }
400
+ /**
401
+ * @internal
402
+ */
403
+ function validateScopesType(value) {
404
+ // string
405
+ if (typeof value === "string" || value instanceof String) {
406
+ return;
407
+ }
408
+ // empty array
409
+ if (Array.isArray(value) && value.length === 0) {
410
+ return;
411
+ }
412
+ // string array
413
+ if (Array.isArray(value) && value.length > 0 && value.every((item) => typeof item === "string")) {
414
+ return;
415
+ }
416
+ const errorMsg = "The type of scopes is not valid, it must be string or string array";
417
+ internalLogger.error(errorMsg);
418
+ throw new ErrorWithCode(errorMsg, ErrorCode.InvalidParameter);
426
419
  }
427
420
 
428
- // Copyright (c) Microsoft Corporation.
429
- /**
430
- * Represent Microsoft 365 tenant identity, and it is usually used when user is not involved.
431
- *
432
- * @remarks
433
- * Only works in in server side.
434
- */
435
- class AppCredential {
436
- constructor(authConfig) {
437
- throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "AppCredential"), ErrorCode.RuntimeNotSupported);
438
- }
439
- /**
440
- * Get access token for credential.
441
- *
442
- * @remarks
443
- * Only works in in server side.
444
- */
445
- getToken(scopes, options) {
446
- return Promise.reject(new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "AppCredential"), ErrorCode.RuntimeNotSupported));
447
- }
421
+ // Copyright (c) Microsoft Corporation.
422
+ /**
423
+ * Represent Microsoft 365 tenant identity, and it is usually used when user is not involved.
424
+ *
425
+ * @remarks
426
+ * Only works in in server side.
427
+ */
428
+ class AppCredential {
429
+ /**
430
+ * Constructor of AppCredential.
431
+ *
432
+ * @remarks
433
+ * Only works in in server side.
434
+ */
435
+ constructor(authConfig) {
436
+ throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "AppCredential"), ErrorCode.RuntimeNotSupported);
437
+ }
438
+ /**
439
+ * Get access token for credential.
440
+ *
441
+ * @remarks
442
+ * Only works in in server side.
443
+ */
444
+ getToken(scopes, options) {
445
+ return Promise.reject(new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "AppCredential"), ErrorCode.RuntimeNotSupported));
446
+ }
448
447
  }
449
448
 
450
- // Copyright (c) Microsoft Corporation.
451
- /**
452
- * Represent on-behalf-of flow to get user identity, and it is designed to be used in Azure Function or Bot scenarios.
453
- *
454
- * @remarks
455
- * Can only be used in server side.
456
- */
457
- class OnBehalfOfUserCredential {
458
- constructor(ssoToken, config) {
459
- throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "OnBehalfOfUserCredential"), ErrorCode.RuntimeNotSupported);
460
- }
461
- /**
462
- * Get access token from credential.
463
- * @remarks
464
- * Can only be used in server side.
465
- */
466
- getToken(scopes, options) {
467
- return Promise.reject(new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "OnBehalfOfUserCredential"), ErrorCode.RuntimeNotSupported));
468
- }
469
- /**
470
- * Get basic user info from SSO token.
471
- * @remarks
472
- * Can only be used in server side.
473
- */
474
- getUserInfo() {
475
- return Promise.reject(new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "OnBehalfOfUserCredential"), ErrorCode.RuntimeNotSupported));
476
- }
449
+ // Copyright (c) Microsoft Corporation.
450
+ /**
451
+ * Represent on-behalf-of flow to get user identity, and it is designed to be used in Azure Function or Bot scenarios.
452
+ *
453
+ * @remarks
454
+ * Can only be used in server side.
455
+ */
456
+ class OnBehalfOfUserCredential {
457
+ /**
458
+ * Constructor of OnBehalfOfUserCredential
459
+ *
460
+ * @remarks
461
+ * Can Only works in in server side.
462
+ */
463
+ constructor(ssoToken, config) {
464
+ throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "OnBehalfOfUserCredential"), ErrorCode.RuntimeNotSupported);
465
+ }
466
+ /**
467
+ * Get access token from credential.
468
+ * @remarks
469
+ * Can only be used in server side.
470
+ */
471
+ getToken(scopes, options) {
472
+ return Promise.reject(new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "OnBehalfOfUserCredential"), ErrorCode.RuntimeNotSupported));
473
+ }
474
+ /**
475
+ * Get basic user info from SSO token.
476
+ * @remarks
477
+ * Can only be used in server side.
478
+ */
479
+ getUserInfo() {
480
+ return Promise.reject(new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "OnBehalfOfUserCredential"), ErrorCode.RuntimeNotSupported));
481
+ }
477
482
  }
478
483
 
479
- /*! *****************************************************************************
484
+ /******************************************************************************
480
485
  Copyright (c) Microsoft Corporation.
481
486
 
482
487
  Permission to use, copy, modify, and/or distribute this software for any
@@ -499,2089 +504,1261 @@ function __awaiter(thisArg, _arguments, P, generator) {
499
504
  function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
500
505
  step((generator = generator.apply(thisArg, _arguments || [])).next());
501
506
  });
502
- }
503
-
504
- // Copyright (c) Microsoft Corporation.
505
- const tokenRefreshTimeSpanInMillisecond = 5 * 60 * 1000;
506
- const loginPageWidth = 600;
507
- const loginPageHeight = 535;
508
- /**
509
- * Represent Teams current user's identity, and it is used within Teams tab application.
510
- *
511
- * @remarks
512
- * Can only be used within Teams.
513
- */
514
- class TeamsUserCredential {
515
- constructor(authConfig) {
516
- internalLogger.info("Create teams user credential");
517
- this.config = this.loadAndValidateConfig(authConfig);
518
- this.ssoToken = null;
519
- this.initialized = false;
520
- }
521
- /**
522
- * Popup login page to get user's access token with specific scopes.
523
- *
524
- * @remarks
525
- * Only works in Teams client APP. User will be redirected to the authorization page to login and consent.
526
- *
527
- * @example
528
- * ```typescript
529
- * await credential.login(["https://graph.microsoft.com/User.Read"]); // single scope using string array
530
- * await credential.login("https://graph.microsoft.com/User.Read"); // single scopes using string
531
- * await credential.login(["https://graph.microsoft.com/User.Read", "Calendars.Read"]); // multiple scopes using string array
532
- * await credential.login("https://graph.microsoft.com/User.Read Calendars.Read"); // multiple scopes using string
533
- * ```
534
- * @param scopes - The list of scopes for which the token will have access, before that, we will request user to consent.
535
- * @param { string[] } resources - The optional list of resources for full trust Teams apps.
536
- *
537
- * @throws {@link ErrorCode|InternalError} when failed to login with unknown error.
538
- * @throws {@link ErrorCode|ConsentFailed} when user canceled or failed to consent.
539
- * @throws {@link ErrorCode|InvalidParameter} when scopes is not a valid string or string array.
540
- * @throws {@link ErrorCode|RuntimeNotSupported} when runtime is nodeJS.
541
- */
542
- login(scopes, resources) {
543
- return __awaiter(this, void 0, void 0, function* () {
544
- validateScopesType(scopes);
545
- const scopesStr = typeof scopes === "string" ? scopes : scopes.join(" ");
546
- internalLogger.info(`Popup login page to get user's access token with scopes: ${scopesStr}`);
547
- if (!this.initialized) {
548
- yield this.init(resources);
549
- }
550
- yield app.initialize();
551
- let result;
552
- try {
553
- const params = {
554
- url: `${this.config.initiateLoginEndpoint ? this.config.initiateLoginEndpoint : ""}?clientId=${this.config.clientId ? this.config.clientId : ""}&scope=${encodeURI(scopesStr)}&loginHint=${this.loginHint ? this.loginHint : ""}`,
555
- width: loginPageWidth,
556
- height: loginPageHeight,
557
- };
558
- result = yield authentication.authenticate(params);
559
- if (!result) {
560
- const errorMsg = "Get empty authentication result from MSAL";
561
- internalLogger.error(errorMsg);
562
- throw new ErrorWithCode(errorMsg, ErrorCode.InternalError);
563
- }
564
- }
565
- catch (err) {
566
- const errorMsg = `Consent failed for the scope ${scopesStr} with error: ${err.message}`;
567
- internalLogger.error(errorMsg);
568
- throw new ErrorWithCode(errorMsg, ErrorCode.ConsentFailed);
569
- }
570
- let resultJson = {};
571
- try {
572
- resultJson = typeof result == "string" ? JSON.parse(result) : result;
573
- }
574
- catch (error) {
575
- // If can not parse result as Json, will throw error.
576
- const failedToParseResult = "Failed to parse response to Json.";
577
- internalLogger.error(failedToParseResult);
578
- throw new ErrorWithCode(failedToParseResult, ErrorCode.InvalidResponse);
579
- }
580
- // If code exists in result, user may using previous auth-start and auth-end page.
581
- if (resultJson.code) {
582
- const helpLink = "https://aka.ms/teamsfx-auth-code-flow";
583
- const usingPreviousAuthPage = "Found auth code in response. Auth code is not support for current version of SDK. " +
584
- `Please refer to the help link for how to fix the issue: ${helpLink}.`;
585
- internalLogger.error(usingPreviousAuthPage);
586
- throw new ErrorWithCode(usingPreviousAuthPage, ErrorCode.InvalidResponse);
587
- }
588
- // If sessionStorage exists in result, set the values in current session storage.
589
- if (resultJson.sessionStorage) {
590
- this.setSessionStorage(resultJson.sessionStorage);
591
- }
592
- });
593
- }
594
- /**
595
- * Get access token from credential.
596
- *
597
- * Important: Access tokens are stored in sessionStorage, read more here: https://aka.ms/teamsfx-session-storage-notice
598
- * Important: Full trust applications do not read the resource information from the webApplicationInfo section of the app
599
- * manifest. Instead, this resource (along with any additional resources from which to request tokens) must be provided
600
- * as a list of resources to the getToken() method through a GetTeamsUserTokenOptions object.
601
- *
602
- * @example
603
- * ```typescript
604
- * await credential.getToken([]) // Get SSO token using empty string array
605
- * await credential.getToken("") // Get SSO token using empty string
606
- * await credential.getToken([".default"]) // Get Graph access token with default scope using string array
607
- * await credential.getToken(".default") // Get Graph access token with default scope using string
608
- * await credential.getToken(["User.Read"]) // Get Graph access token for single scope using string array
609
- * await credential.getToken("User.Read") // Get Graph access token for single scope using string
610
- * await credential.getToken(["User.Read", "Application.Read.All"]) // Get Graph access token for multiple scopes using string array
611
- * await credential.getToken("User.Read Application.Read.All") // Get Graph access token for multiple scopes using space-separated string
612
- * await credential.getToken("https://graph.microsoft.com/User.Read") // Get Graph access token with full resource URI
613
- * await credential.getToken(["https://outlook.office.com/Mail.Read"]) // Get Outlook access token
614
- *
615
- * const options: GetTeamsUserTokenOptions = { resources: ["https://domain.example.com"] }; // set up resources for full trust apps.
616
- * await credential.getToken([], options) // Get sso token from teams client - only use this approach for full trust apps.
617
- * ```
618
- *
619
- * @param {string | string[]} scopes - The list of scopes for which the token will have access.
620
- * @param {GetTokenOptions} options - The options used to configure any requests this TokenCredential implementation might make.
621
- *
622
- * @throws {@link ErrorCode|InternalError} when failed to get access token with unknown error.
623
- * @throws {@link ErrorCode|UiRequiredError} when need user consent to get access token.
624
- * @throws {@link ErrorCode|InvalidParameter} when scopes is not a valid string or string array.
625
- * @throws {@link ErrorCode|RuntimeNotSupported} when runtime is nodeJS.
626
- *
627
- * @returns User access token of defined scopes.
628
- * If scopes is empty string or array, it returns SSO token.
629
- * If scopes is non-empty, it returns access token for target scope.
630
- * Throw error if get access token failed.
631
- */
632
- getToken(scopes, options) {
633
- var _a;
634
- return __awaiter(this, void 0, void 0, function* () {
635
- validateScopesType(scopes);
636
- const resources = (_a = options) === null || _a === void 0 ? void 0 : _a.resources;
637
- const ssoToken = yield this.getSSOToken(resources);
638
- const scopeStr = typeof scopes === "string" ? scopes : scopes.join(" ");
639
- if (scopeStr === "") {
640
- internalLogger.info("Get SSO token");
641
- return ssoToken;
642
- }
643
- else {
644
- internalLogger.info("Get access token with scopes: " + scopeStr);
645
- if (!this.initialized) {
646
- yield this.init(resources);
647
- }
648
- let tokenResponse;
649
- const scopesArray = typeof scopes === "string" ? scopes.split(" ") : scopes;
650
- const domain = window.location.origin;
651
- // First try to get Access Token from cache.
652
- try {
653
- const account = this.msalInstance.getAccountByUsername(this.loginHint);
654
- const scopesRequestForAcquireTokenSilent = {
655
- scopes: scopesArray,
656
- account: account !== null && account !== void 0 ? account : undefined,
657
- redirectUri: `${domain}/blank-auth-end.html`,
658
- };
659
- tokenResponse = yield this.msalInstance.acquireTokenSilent(scopesRequestForAcquireTokenSilent);
660
- }
661
- catch (error) {
662
- const acquireTokenSilentFailedMessage = `Failed to call acquireTokenSilent. Reason: ${error === null || error === void 0 ? void 0 : error.message}. `;
663
- internalLogger.verbose(acquireTokenSilentFailedMessage);
664
- }
665
- if (!tokenResponse) {
666
- // If fail to get Access Token from cache, try to get Access token by silent login.
667
- try {
668
- const scopesRequestForSsoSilent = {
669
- scopes: scopesArray,
670
- loginHint: this.loginHint,
671
- redirectUri: `${domain}/blank-auth-end.html`,
672
- };
673
- tokenResponse = yield this.msalInstance.ssoSilent(scopesRequestForSsoSilent);
674
- }
675
- catch (error) {
676
- const ssoSilentFailedMessage = `Failed to call ssoSilent. Reason: ${error === null || error === void 0 ? void 0 : error.message}. `;
677
- internalLogger.verbose(ssoSilentFailedMessage);
678
- }
679
- }
680
- if (!tokenResponse) {
681
- const errorMsg = `Failed to get access token cache silently, please login first: you need login first before get access token.`;
682
- internalLogger.error(errorMsg);
683
- throw new ErrorWithCode(errorMsg, ErrorCode.UiRequiredError);
684
- }
685
- const accessToken = parseAccessTokenFromAuthCodeTokenResponse(tokenResponse);
686
- return accessToken;
687
- }
688
- });
689
- }
690
- /**
691
- * Get basic user info from SSO token
692
- *
693
- * @param {string[]} resources - The optional list of resources for full trust Teams apps.
694
- *
695
- * @example
696
- * ```typescript
697
- * const currentUser = await credential.getUserInfo();
698
- * ```
699
- *
700
- * @throws {@link ErrorCode|InternalError} when SSO token from Teams client is not valid.
701
- * @throws {@link ErrorCode|InvalidParameter} when SSO token from Teams client is empty.
702
- * @throws {@link ErrorCode|RuntimeNotSupported} when runtime is nodeJS.
703
- *
704
- * @returns Basic user info with user displayName, objectId and preferredUserName.
705
- */
706
- getUserInfo(resources) {
707
- return __awaiter(this, void 0, void 0, function* () {
708
- internalLogger.info("Get basic user info from SSO token");
709
- const ssoToken = yield this.getSSOToken(resources);
710
- return getUserInfoFromSsoToken(ssoToken.token);
711
- });
712
- }
713
- init(resources) {
714
- return __awaiter(this, void 0, void 0, function* () {
715
- const ssoToken = yield this.getSSOToken(resources);
716
- const info = getTenantIdAndLoginHintFromSsoToken(ssoToken.token);
717
- this.loginHint = info.loginHint;
718
- this.tid = info.tid;
719
- const msalConfig = {
720
- auth: {
721
- clientId: this.config.clientId,
722
- authority: `https://login.microsoftonline.com/${this.tid}`,
723
- },
724
- cache: {
725
- cacheLocation: "sessionStorage",
726
- },
727
- };
728
- this.msalInstance = new PublicClientApplication(msalConfig);
729
- yield this.msalInstance.initialize();
730
- this.initialized = true;
731
- });
732
- }
733
- /**
734
- * Get SSO token using teams SDK
735
- * It will try to get SSO token from memory first, if SSO token doesn't exist or about to expired, then it will using teams SDK to get SSO token
736
- *
737
- * @param {string[]} resources - The optional list of resources for full trust Teams apps.
738
- *
739
- * @returns SSO token
740
- */
741
- getSSOToken(resources) {
742
- return __awaiter(this, void 0, void 0, function* () {
743
- if (this.ssoToken) {
744
- if (this.ssoToken.expiresOnTimestamp - Date.now() > tokenRefreshTimeSpanInMillisecond) {
745
- internalLogger.verbose("Get SSO token from memory cache");
746
- return this.ssoToken;
747
- }
748
- }
749
- const params = { resources: resources !== null && resources !== void 0 ? resources : [] };
750
- let token;
751
- try {
752
- yield app.initialize();
753
- }
754
- catch (err) {
755
- const errorMsg = "Initialize teams sdk failed due to not running inside Teams environment";
756
- internalLogger.error(errorMsg);
757
- throw new ErrorWithCode(errorMsg, ErrorCode.InternalError);
758
- }
759
- try {
760
- token = yield authentication.getAuthToken(params);
761
- }
762
- catch (err) {
763
- const errorMsg = "Get SSO token failed with error: " + err.message;
764
- internalLogger.error(errorMsg);
765
- throw new ErrorWithCode(errorMsg, ErrorCode.InternalError);
766
- }
767
- if (!token) {
768
- const errorMsg = "Get empty SSO token from Teams";
769
- internalLogger.error(errorMsg);
770
- throw new ErrorWithCode(errorMsg, ErrorCode.InternalError);
771
- }
772
- const tokenObject = parseJwt(token);
773
- if (tokenObject.ver !== "1.0" && tokenObject.ver !== "2.0") {
774
- const errorMsg = "SSO token is not valid with an unknown version: " + tokenObject.ver;
775
- internalLogger.error(errorMsg);
776
- throw new ErrorWithCode(errorMsg, ErrorCode.InternalError);
777
- }
778
- const ssoToken = {
779
- token,
780
- expiresOnTimestamp: tokenObject.exp * 1000,
781
- };
782
- this.ssoToken = ssoToken;
783
- return ssoToken;
784
- });
785
- }
786
- /**
787
- * Load and validate authentication configuration
788
- *
789
- * @param {AuthenticationConfiguration?} config - The authentication configuration. Use environment variables if not provided.
790
- *
791
- * @returns Authentication configuration
792
- */
793
- loadAndValidateConfig(config) {
794
- internalLogger.verbose("Validate authentication configuration");
795
- if (config.initiateLoginEndpoint && config.clientId) {
796
- return config;
797
- }
798
- const missingValues = [];
799
- if (!config.initiateLoginEndpoint) {
800
- missingValues.push("initiateLoginEndpoint");
801
- }
802
- if (!config.clientId) {
803
- missingValues.push("clientId");
804
- }
805
- const errorMsg = formatString(ErrorMessage.InvalidConfiguration, missingValues.join(", "), "undefined");
806
- internalLogger.error(errorMsg);
807
- throw new ErrorWithCode(errorMsg, ErrorCode.InvalidConfiguration);
808
- }
809
- setSessionStorage(sessionStorageValues) {
810
- try {
811
- const sessionStorageKeys = Object.keys(sessionStorageValues);
812
- sessionStorageKeys.forEach((key) => {
813
- sessionStorage.setItem(key, sessionStorageValues[key]);
814
- });
815
- }
816
- catch (error) {
817
- // Values in result.sessionStorage can not be set into session storage.
818
- // Throw error since this may block user.
819
- const errorMessage = `Failed to set values in session storage. Error: ${error.message}`;
820
- internalLogger.error(errorMessage);
821
- throw new ErrorWithCode(errorMessage, ErrorCode.InternalError);
822
- }
823
- }
824
- }
825
-
826
- // Copyright (c) Microsoft Corporation.
827
- const defaultScope = "https://graph.microsoft.com/.default";
828
- // eslint-disable-next-line no-secrets/no-secrets
829
- /**
830
- * Microsoft Graph auth provider for Teams Framework
831
- * @deprecated Use `TokenCredentialAuthenticationProvider` from `@microsoft/microsoft-graph-client/authProviders/azureTokenCredentials` instead.
832
- */
833
- class MsGraphAuthProvider {
834
- constructor(credentialOrTeamsFx, scopes) {
835
- this.credentialOrTeamsFx = credentialOrTeamsFx;
836
- let scopesStr = defaultScope;
837
- if (scopes) {
838
- validateScopesType(scopes);
839
- scopesStr = typeof scopes === "string" ? scopes : scopes.join(" ");
840
- if (scopesStr === "") {
841
- scopesStr = defaultScope;
842
- }
843
- }
844
- internalLogger.info(`Create Microsoft Graph Authentication Provider with scopes: '${scopesStr}'`);
845
- this.scopes = scopesStr;
846
- }
847
- /**
848
- * Get access token for Microsoft Graph API requests.
849
- *
850
- * @throws {@link ErrorCode|InternalError} when get access token failed due to empty token or unknown other problems.
851
- * @throws {@link ErrorCode|TokenExpiredError} when SSO token has already expired.
852
- * @throws {@link ErrorCode|UiRequiredError} when need user consent to get access token.
853
- * @throws {@link ErrorCode|ServiceError} when failed to get access token from simple auth or AAD server.
854
- * @throws {@link ErrorCode|InvalidParameter} when scopes is not a valid string or string array.
855
- *
856
- * @returns Access token from the credential.
857
- *
858
- */
859
- getAccessToken() {
860
- return __awaiter(this, void 0, void 0, function* () {
861
- internalLogger.info(`Get Graph Access token with scopes: '${this.scopes.toString()}'`);
862
- let accessToken;
863
- if (this.credentialOrTeamsFx.getCredential) {
864
- accessToken = yield this.credentialOrTeamsFx
865
- .getCredential()
866
- .getToken(this.scopes);
867
- }
868
- else {
869
- accessToken = yield this.credentialOrTeamsFx.getToken(this.scopes);
870
- }
871
- return new Promise((resolve, reject) => {
872
- if (accessToken) {
873
- resolve(accessToken.token);
874
- }
875
- else {
876
- const errorMsg = "Graph access token is undefined or empty";
877
- internalLogger.error(errorMsg);
878
- reject(new ErrorWithCode(errorMsg, ErrorCode.InternalError));
879
- }
880
- });
881
- });
882
- }
883
- }
884
-
885
- // Copyright (c) Microsoft Corporation.
886
- /**
887
- * Get Microsoft graph client.
888
- * @deprecated Use `TokenCredentialAuthenticationProvider` and `Client.initWithMiddleware` instead.
889
- * ```typescript
890
- * const authProvider = new TokenCredentialAuthenticationProvider(credential, { scopes: scope });
891
- * const graph = Client.initWithMiddleware({
892
- * authProvider: authProvider,
893
- * });
894
- * ```
895
- *
896
- * @example
897
- * Get Microsoft graph client by TokenCredential
898
- * ```typescript
899
- * // Sso token example (Azure Function)
900
- * const ssoToken = "YOUR_TOKEN_STRING";
901
- * const options = {"AAD_APP_ID", "AAD_APP_SECRET"};
902
- * const credential = new OnBehalfOfAADUserCredential(ssoToken, options);
903
- * const graphClient = await createMicrosoftGraphClient(credential);
904
- * const profile = await graphClient.api("/me").get();
905
- *
906
- * // TeamsBotSsoPrompt example (Bot Application)
907
- * const requiredScopes = ["User.Read"];
908
- * const config: Configuration = {
909
- * loginUrl: loginUrl,
910
- * clientId: clientId,
911
- * clientSecret: clientSecret,
912
- * tenantId: tenantId
913
- * };
914
- * const prompt = new TeamsBotSsoPrompt(dialogId, {
915
- * config: config
916
- * scopes: ["User.Read"],
917
- * });
918
- * this.addDialog(prompt);
919
- *
920
- * const oboCredential = new OnBehalfOfAADUserCredential(
921
- * getUserId(dialogContext),
922
- * {
923
- * clientId: "AAD_APP_ID",
924
- * clientSecret: "AAD_APP_SECRET"
925
- * });
926
- * try {
927
- * const graphClient = await createMicrosoftGraphClient(credential);
928
- * const profile = await graphClient.api("/me").get();
929
- * } catch (e) {
930
- * dialogContext.beginDialog(dialogId);
931
- * return Dialog.endOfTurn();
932
- * }
933
- * ```
934
- *
935
- * @param {TeamsFx} teamsfx - Used to provide configuration and auth.
936
- * @param scopes - The array of Microsoft Token scope of access. Default value is `[.default]`.
937
- *
938
- * @throws {@link ErrorCode|InvalidParameter} when scopes is not a valid string or string array.
939
- *
940
- * @returns Graph client with specified scopes.
941
- */
942
- function createMicrosoftGraphClient(teamsfx, scopes) {
943
- internalLogger.info("Create Microsoft Graph Client");
944
- const authProvider = new MsGraphAuthProvider(teamsfx, scopes);
945
- const graphClient = Client.initWithMiddleware({
946
- authProvider,
947
- });
948
- return graphClient;
949
507
  }
950
- // eslint-disable-next-line no-secrets/no-secrets
951
- /**
952
- * Get Microsoft graph client.
953
- * @deprecated Use `TokenCredentialAuthenticationProvider` and `Client.initWithMiddleware` instead.
954
- * ```typescript
955
- * const authProvider = new TokenCredentialAuthenticationProvider(credential, { scopes: scope });
956
- * const graph = Client.initWithMiddleware({
957
- * authProvider: authProvider,
958
- * });
959
- * ```
960
- *
961
- * @example
962
- * Get Microsoft graph client by TokenCredential
963
- * ```typescript
964
- * // In browser: TeamsUserCredential
965
- * const authConfig: TeamsUserCredentialAuthConfig = {
966
- * clientId: "xxx",
967
- initiateLoginEndpoint: "https://xxx/auth-start.html",
968
- * };
969
-
970
- * const credential = new TeamsUserCredential(authConfig);
971
-
972
- * const scope = "User.Read";
973
- * await credential.login(scope);
974
-
975
- * const client = createMicrosoftGraphClientWithCredential(credential, scope);
976
-
977
- * // In node: OnBehalfOfUserCredential
978
- * const oboAuthConfig: OnBehalfOfCredentialAuthConfig = {
979
- * authorityHost: "xxx",
980
- * clientId: "xxx",
981
- * tenantId: "xxx",
982
- * clientSecret: "xxx",
983
- * };
984
-
985
- * const oboCredential = new OnBehalfOfUserCredential(ssoToken, oboAuthConfig);
986
- * const scope = "User.Read";
987
- * const client = createMicrosoftGraphClientWithCredential(oboCredential, scope);
508
+
509
+ typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
510
+ var e = new Error(message);
511
+ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
512
+ };
988
513
 
989
- * // In node: AppCredential
990
- * const appAuthConfig: AppCredentialAuthConfig = {
991
- * authorityHost: "xxx",
992
- * clientId: "xxx",
993
- * tenantId: "xxx",
994
- * clientSecret: "xxx",
995
- * };
996
- * const appCredential = new AppCredential(appAuthConfig);
997
- * const scope = "User.Read";
998
- * const client = createMicrosoftGraphClientWithCredential(appCredential, scope);
999
- *
1000
- * const profile = await client.api("/me").get();
1001
- * ```
1002
- *
1003
- * @param {TokenCredential} credential - Used to provide configuration and auth.
1004
- * @param scopes - The array of Microsoft Token scope of access. Default value is `[.default]`.
1005
- *
1006
- * @throws {@link ErrorCode|InvalidParameter} when scopes is not a valid string or string array.
1007
- *
1008
- * @returns Graph client with specified scopes.
1009
- */
1010
- function createMicrosoftGraphClientWithCredential(credential, scopes) {
1011
- internalLogger.info("Create Microsoft Graph Client");
1012
- const authProvider = new MsGraphAuthProvider(credential, scopes);
1013
- const graphClient = Client.initWithMiddleware({
1014
- authProvider,
1015
- });
1016
- return graphClient;
514
+ // Copyright (c) Microsoft Corporation.
515
+ const tokenRefreshTimeSpanInMillisecond = 5 * 60 * 1000;
516
+ const loginPageWidth = 600;
517
+ const loginPageHeight = 535;
518
+ /**
519
+ * Represent Teams current user's identity, and it is used within Teams tab application.
520
+ *
521
+ * @remarks
522
+ * Can only be used within Teams.
523
+ */
524
+ class TeamsUserCredential {
525
+ // eslint-disable-next-line no-secrets/no-secrets
526
+ /**
527
+ * Constructor of TeamsUserCredential.
528
+ *
529
+ * @example
530
+ * ```typescript
531
+ * const config: TeamsUserCredentialAuthConfig = {
532
+ * initiateLoginEndpoint: "https://localhost:3000/auth-start.html",
533
+ * clientId: "xxx"
534
+ * }
535
+ * const credential = new TeamsUserCredential(config);
536
+ * ```
537
+ *
538
+ * @param {TeamsUserCredentialAuthConfig} authConfig - The authentication configuration.
539
+ *
540
+ * @throws {@link ErrorCode|InvalidConfiguration} when client id, initiate login endpoint or simple auth endpoint is not found in config.
541
+ * @throws {@link ErrorCode|RuntimeNotSupported} when runtime is nodeJS.
542
+ */
543
+ constructor(authConfig) {
544
+ internalLogger.info("Create teams user credential");
545
+ this.config = this.loadAndValidateConfig(authConfig);
546
+ this.ssoToken = null;
547
+ this.initialized = false;
548
+ }
549
+ /**
550
+ * Popup login page to get user's access token with specific scopes.
551
+ *
552
+ * @remarks
553
+ * Only works in Teams client APP. User will be redirected to the authorization page to login and consent.
554
+ *
555
+ * @example
556
+ * ```typescript
557
+ * await credential.login(["https://graph.microsoft.com/User.Read"]); // single scope using string array
558
+ * await credential.login("https://graph.microsoft.com/User.Read"); // single scopes using string
559
+ * await credential.login(["https://graph.microsoft.com/User.Read", "Calendars.Read"]); // multiple scopes using string array
560
+ * await credential.login("https://graph.microsoft.com/User.Read Calendars.Read"); // multiple scopes using string
561
+ * ```
562
+ * @param scopes - The list of scopes for which the token will have access, before that, we will request user to consent.
563
+ * @param { string[] } resources - The optional list of resources for full trust Teams apps.
564
+ *
565
+ * @throws {@link ErrorCode|InternalError} when failed to login with unknown error.
566
+ * @throws {@link ErrorCode|ConsentFailed} when user canceled or failed to consent.
567
+ * @throws {@link ErrorCode|InvalidParameter} when scopes is not a valid string or string array.
568
+ * @throws {@link ErrorCode|RuntimeNotSupported} when runtime is nodeJS.
569
+ */
570
+ login(scopes, resources) {
571
+ return __awaiter(this, void 0, void 0, function* () {
572
+ validateScopesType(scopes);
573
+ const scopesStr = typeof scopes === "string" ? scopes : scopes.join(" ");
574
+ internalLogger.info(`Popup login page to get user's access token with scopes: ${scopesStr}`);
575
+ if (!this.initialized) {
576
+ yield this.init(resources);
577
+ }
578
+ yield app.initialize();
579
+ let result;
580
+ try {
581
+ const params = {
582
+ url: `${this.config.initiateLoginEndpoint ? this.config.initiateLoginEndpoint : ""}?clientId=${this.config.clientId ? this.config.clientId : ""}&scope=${encodeURI(scopesStr)}&loginHint=${this.loginHint ? this.loginHint : ""}`,
583
+ width: loginPageWidth,
584
+ height: loginPageHeight,
585
+ };
586
+ result = yield authentication.authenticate(params);
587
+ if (!result) {
588
+ const errorMsg = "Get empty authentication result from MSAL";
589
+ internalLogger.error(errorMsg);
590
+ throw new ErrorWithCode(errorMsg, ErrorCode.InternalError);
591
+ }
592
+ }
593
+ catch (err) {
594
+ const errorMsg = `Consent failed for the scope ${scopesStr} with error: ${err.message}`;
595
+ internalLogger.error(errorMsg);
596
+ throw new ErrorWithCode(errorMsg, ErrorCode.ConsentFailed);
597
+ }
598
+ let resultJson = {};
599
+ try {
600
+ resultJson = typeof result == "string" ? JSON.parse(result) : result;
601
+ }
602
+ catch (error) {
603
+ // If can not parse result as Json, will throw error.
604
+ const failedToParseResult = "Failed to parse response to Json.";
605
+ internalLogger.error(failedToParseResult);
606
+ throw new ErrorWithCode(failedToParseResult, ErrorCode.InvalidResponse);
607
+ }
608
+ // If code exists in result, user may using previous auth-start and auth-end page.
609
+ if (resultJson.code) {
610
+ const helpLink = "https://aka.ms/teamsfx-auth-code-flow";
611
+ const usingPreviousAuthPage = "Found auth code in response. Auth code is not support for current version of SDK. " +
612
+ `Please refer to the help link for how to fix the issue: ${helpLink}.`;
613
+ internalLogger.error(usingPreviousAuthPage);
614
+ throw new ErrorWithCode(usingPreviousAuthPage, ErrorCode.InvalidResponse);
615
+ }
616
+ // If sessionStorage exists in result, set the values in current session storage.
617
+ if (resultJson.sessionStorage) {
618
+ this.setSessionStorage(resultJson.sessionStorage);
619
+ }
620
+ });
621
+ }
622
+ /**
623
+ * Get access token from credential.
624
+ *
625
+ * Important: Access tokens are stored in sessionStorage, read more here: https://aka.ms/teamsfx-session-storage-notice
626
+ * Important: Full trust applications do not read the resource information from the webApplicationInfo section of the app
627
+ * manifest. Instead, this resource (along with any additional resources from which to request tokens) must be provided
628
+ * as a list of resources to the getToken() method through a GetTeamsUserTokenOptions object.
629
+ *
630
+ * @example
631
+ * ```typescript
632
+ * await credential.getToken([]) // Get SSO token using empty string array
633
+ * await credential.getToken("") // Get SSO token using empty string
634
+ * await credential.getToken([".default"]) // Get Graph access token with default scope using string array
635
+ * await credential.getToken(".default") // Get Graph access token with default scope using string
636
+ * await credential.getToken(["User.Read"]) // Get Graph access token for single scope using string array
637
+ * await credential.getToken("User.Read") // Get Graph access token for single scope using string
638
+ * await credential.getToken(["User.Read", "Application.Read.All"]) // Get Graph access token for multiple scopes using string array
639
+ * await credential.getToken("User.Read Application.Read.All") // Get Graph access token for multiple scopes using space-separated string
640
+ * await credential.getToken("https://graph.microsoft.com/User.Read") // Get Graph access token with full resource URI
641
+ * await credential.getToken(["https://outlook.office.com/Mail.Read"]) // Get Outlook access token
642
+ *
643
+ * const options: GetTeamsUserTokenOptions = { resources: ["https://domain.example.com"] }; // set up resources for full trust apps.
644
+ * await credential.getToken([], options) // Get sso token from teams client - only use this approach for full trust apps.
645
+ * ```
646
+ *
647
+ * @param {string | string[]} scopes - The list of scopes for which the token will have access.
648
+ * @param {GetTokenOptions} options - The options used to configure any requests this TokenCredential implementation might make.
649
+ *
650
+ * @throws {@link ErrorCode|InternalError} when failed to get access token with unknown error.
651
+ * @throws {@link ErrorCode|UiRequiredError} when need user consent to get access token.
652
+ * @throws {@link ErrorCode|InvalidParameter} when scopes is not a valid string or string array.
653
+ * @throws {@link ErrorCode|RuntimeNotSupported} when runtime is nodeJS.
654
+ *
655
+ * @returns User access token of defined scopes.
656
+ * If scopes is empty string or array, it returns SSO token.
657
+ * If scopes is non-empty, it returns access token for target scope.
658
+ * Throw error if get access token failed.
659
+ */
660
+ getToken(scopes, options) {
661
+ return __awaiter(this, void 0, void 0, function* () {
662
+ validateScopesType(scopes);
663
+ const resources = options === null || options === void 0 ? void 0 : options.resources;
664
+ const ssoToken = yield this.getSSOToken(resources);
665
+ const scopeStr = typeof scopes === "string" ? scopes : scopes.join(" ");
666
+ if (scopeStr === "") {
667
+ internalLogger.info("Get SSO token");
668
+ return ssoToken;
669
+ }
670
+ else {
671
+ internalLogger.info("Get access token with scopes: " + scopeStr);
672
+ if (!this.initialized) {
673
+ yield this.init(resources);
674
+ }
675
+ let tokenResponse;
676
+ const scopesArray = typeof scopes === "string" ? scopes.split(" ") : scopes;
677
+ const domain = window.location.origin;
678
+ // First try to get Access Token from cache.
679
+ try {
680
+ const account = this.msalInstance.getAccountByUsername(this.loginHint);
681
+ const scopesRequestForAcquireTokenSilent = {
682
+ scopes: scopesArray,
683
+ account: account !== null && account !== void 0 ? account : undefined,
684
+ redirectUri: `${domain}/blank-auth-end.html`,
685
+ };
686
+ tokenResponse = yield this.msalInstance.acquireTokenSilent(scopesRequestForAcquireTokenSilent);
687
+ }
688
+ catch (error) {
689
+ const acquireTokenSilentFailedMessage = `Failed to call acquireTokenSilent. Reason: ${error === null || error === void 0 ? void 0 : error.message}. `;
690
+ internalLogger.verbose(acquireTokenSilentFailedMessage);
691
+ }
692
+ if (!tokenResponse) {
693
+ // If fail to get Access Token from cache, try to get Access token by silent login.
694
+ try {
695
+ const scopesRequestForSsoSilent = {
696
+ scopes: scopesArray,
697
+ loginHint: this.loginHint,
698
+ redirectUri: `${domain}/blank-auth-end.html`,
699
+ };
700
+ tokenResponse = yield this.msalInstance.ssoSilent(scopesRequestForSsoSilent);
701
+ }
702
+ catch (error) {
703
+ const ssoSilentFailedMessage = `Failed to call ssoSilent. Reason: ${error === null || error === void 0 ? void 0 : error.message}. `;
704
+ internalLogger.verbose(ssoSilentFailedMessage);
705
+ }
706
+ }
707
+ if (!tokenResponse) {
708
+ const errorMsg = `Failed to get access token cache silently, please login first: you need login first before get access token.`;
709
+ internalLogger.error(errorMsg);
710
+ throw new ErrorWithCode(errorMsg, ErrorCode.UiRequiredError);
711
+ }
712
+ const accessToken = parseAccessTokenFromAuthCodeTokenResponse(tokenResponse);
713
+ return accessToken;
714
+ }
715
+ });
716
+ }
717
+ /**
718
+ * Get basic user info from SSO token
719
+ *
720
+ * @param {string[]} resources - The optional list of resources for full trust Teams apps.
721
+ *
722
+ * @example
723
+ * ```typescript
724
+ * const currentUser = await credential.getUserInfo();
725
+ * ```
726
+ *
727
+ * @throws {@link ErrorCode|InternalError} when SSO token from Teams client is not valid.
728
+ * @throws {@link ErrorCode|InvalidParameter} when SSO token from Teams client is empty.
729
+ * @throws {@link ErrorCode|RuntimeNotSupported} when runtime is nodeJS.
730
+ *
731
+ * @returns Basic user info with user displayName, objectId and preferredUserName.
732
+ */
733
+ getUserInfo(resources) {
734
+ return __awaiter(this, void 0, void 0, function* () {
735
+ internalLogger.info("Get basic user info from SSO token");
736
+ const ssoToken = yield this.getSSOToken(resources);
737
+ return getUserInfoFromSsoToken(ssoToken.token);
738
+ });
739
+ }
740
+ init(resources) {
741
+ return __awaiter(this, void 0, void 0, function* () {
742
+ const ssoToken = yield this.getSSOToken(resources);
743
+ const info = getTenantIdAndLoginHintFromSsoToken(ssoToken.token);
744
+ this.loginHint = info.loginHint;
745
+ this.tid = info.tid;
746
+ const msalConfig = {
747
+ auth: {
748
+ clientId: this.config.clientId,
749
+ authority: `https://login.microsoftonline.com/${this.tid}`,
750
+ },
751
+ cache: {
752
+ cacheLocation: "sessionStorage",
753
+ },
754
+ };
755
+ this.msalInstance = new PublicClientApplication(msalConfig);
756
+ yield this.msalInstance.initialize();
757
+ this.initialized = true;
758
+ });
759
+ }
760
+ /**
761
+ * Get SSO token using teams SDK
762
+ * It will try to get SSO token from memory first, if SSO token doesn't exist or about to expired, then it will using teams SDK to get SSO token
763
+ *
764
+ * @param {string[]} resources - The optional list of resources for full trust Teams apps.
765
+ *
766
+ * @returns SSO token
767
+ */
768
+ getSSOToken(resources) {
769
+ return __awaiter(this, void 0, void 0, function* () {
770
+ if (this.ssoToken) {
771
+ if (this.ssoToken.expiresOnTimestamp - Date.now() > tokenRefreshTimeSpanInMillisecond) {
772
+ internalLogger.verbose("Get SSO token from memory cache");
773
+ return this.ssoToken;
774
+ }
775
+ }
776
+ const params = { resources: resources !== null && resources !== void 0 ? resources : [] };
777
+ let token;
778
+ try {
779
+ yield app.initialize();
780
+ }
781
+ catch (err) {
782
+ const errorMsg = "Initialize teams sdk failed due to not running inside Teams environment";
783
+ internalLogger.error(errorMsg);
784
+ throw new ErrorWithCode(errorMsg, ErrorCode.InternalError);
785
+ }
786
+ try {
787
+ token = yield authentication.getAuthToken(params);
788
+ }
789
+ catch (err) {
790
+ const errorMsg = "Get SSO token failed with error: " + err.message;
791
+ internalLogger.error(errorMsg);
792
+ throw new ErrorWithCode(errorMsg, ErrorCode.InternalError);
793
+ }
794
+ if (!token) {
795
+ const errorMsg = "Get empty SSO token from Teams";
796
+ internalLogger.error(errorMsg);
797
+ throw new ErrorWithCode(errorMsg, ErrorCode.InternalError);
798
+ }
799
+ const tokenObject = parseJwt(token);
800
+ if (tokenObject.ver !== "1.0" && tokenObject.ver !== "2.0") {
801
+ const errorMsg = "SSO token is not valid with an unknown version: " + tokenObject.ver;
802
+ internalLogger.error(errorMsg);
803
+ throw new ErrorWithCode(errorMsg, ErrorCode.InternalError);
804
+ }
805
+ const ssoToken = {
806
+ token,
807
+ expiresOnTimestamp: tokenObject.exp * 1000,
808
+ };
809
+ this.ssoToken = ssoToken;
810
+ return ssoToken;
811
+ });
812
+ }
813
+ /**
814
+ * Load and validate authentication configuration
815
+ *
816
+ * @param {AuthenticationConfiguration?} config - The authentication configuration. Use environment variables if not provided.
817
+ *
818
+ * @returns Authentication configuration
819
+ */
820
+ loadAndValidateConfig(config) {
821
+ internalLogger.verbose("Validate authentication configuration");
822
+ if (config.initiateLoginEndpoint && config.clientId) {
823
+ return config;
824
+ }
825
+ const missingValues = [];
826
+ if (!config.initiateLoginEndpoint) {
827
+ missingValues.push("initiateLoginEndpoint");
828
+ }
829
+ if (!config.clientId) {
830
+ missingValues.push("clientId");
831
+ }
832
+ const errorMsg = formatString(ErrorMessage.InvalidConfiguration, missingValues.join(", "), "undefined");
833
+ internalLogger.error(errorMsg);
834
+ throw new ErrorWithCode(errorMsg, ErrorCode.InvalidConfiguration);
835
+ }
836
+ setSessionStorage(sessionStorageValues) {
837
+ try {
838
+ const sessionStorageKeys = Object.keys(sessionStorageValues);
839
+ sessionStorageKeys.forEach((key) => {
840
+ sessionStorage.setItem(key, sessionStorageValues[key]);
841
+ });
842
+ }
843
+ catch (error) {
844
+ // Values in result.sessionStorage can not be set into session storage.
845
+ // Throw error since this may block user.
846
+ const errorMessage = `Failed to set values in session storage. Error: ${error.message}`;
847
+ internalLogger.error(errorMessage);
848
+ throw new ErrorWithCode(errorMessage, ErrorCode.InternalError);
849
+ }
850
+ }
1017
851
  }
1018
852
 
1019
- // Copyright (c) Microsoft Corporation.
1020
- /**
1021
- * Generate connection configuration consumed by tedious.
1022
- *
1023
- * @deprecated we recommend you compose your own Tedious configuration for better flexibility.
1024
- *
1025
- * @remarks
1026
- * Only works in in server side.
1027
- */
1028
- function getTediousConnectionConfig(teamsfx, databaseName) {
1029
- return Promise.reject(new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "DefaultTediousConnectionConfiguration"), ErrorCode.RuntimeNotSupported));
853
+ // Copyright (c) Microsoft Corporation.
854
+ /**
855
+ * Creates a new prompt that leverage Teams Single Sign On (SSO) support for bot to automatically sign in user and
856
+ * help receive oauth token, asks the user to consent if needed.
857
+ *
858
+ * @remarks
859
+ * The prompt will attempt to retrieve the users current token of the desired scopes and store it in
860
+ * the token store.
861
+ *
862
+ * User will be automatically signed in leveraging Teams support of Bot Single Sign On(SSO):
863
+ * https://docs.microsoft.com/en-us/microsoftteams/platform/bots/how-to/authentication/auth-aad-sso-bots
864
+ *
865
+ * @example
866
+ * When used with your bots `DialogSet` you can simply add a new instance of the prompt as a named
867
+ * dialog using `DialogSet.add()`. You can then start the prompt from a waterfall step using either
868
+ * `DialogContext.beginDialog()` or `DialogContext.prompt()`. The user will be prompted to sign in as
869
+ * needed and their access token will be passed as an argument to the callers next waterfall step:
870
+ *
871
+ * ```JavaScript
872
+ * const { ConversationState, MemoryStorage } = require('botbuilder');
873
+ * const { DialogSet, WaterfallDialog } = require('botbuilder-dialogs');
874
+ * const { TeamsBotSsoPrompt } = require('@microsoft/teamsfx');
875
+ *
876
+ * const convoState = new ConversationState(new MemoryStorage());
877
+ * const dialogState = convoState.createProperty('dialogState');
878
+ * const dialogs = new DialogSet(dialogState);
879
+ *
880
+ * dialogs.add(new TeamsBotSsoPrompt('TeamsBotSsoPrompt', {
881
+ * scopes: ["User.Read"],
882
+ * }));
883
+ *
884
+ * dialogs.add(new WaterfallDialog('taskNeedingLogin', [
885
+ * async (step) => {
886
+ * return await step.beginDialog('TeamsBotSsoPrompt');
887
+ * },
888
+ * async (step) => {
889
+ * const token = step.result;
890
+ * if (token) {
891
+ *
892
+ * // ... continue with task needing access token ...
893
+ *
894
+ * } else {
895
+ * await step.context.sendActivity(`Sorry... We couldn't log you in. Try again later.`);
896
+ * return await step.endDialog();
897
+ * }
898
+ * }
899
+ * ]));
900
+ * ```
901
+ */
902
+ class TeamsBotSsoPrompt {
903
+ /**
904
+ * Constructor of TeamsBotSsoPrompt.
905
+ *
906
+ * @param dialogId Unique ID of the dialog within its parent `DialogSet` or `ComponentDialog`.
907
+ * @param settings Settings used to configure the prompt.
908
+ *
909
+ * @throws {@link ErrorCode|InvalidParameter} when scopes is not a valid string or string array.
910
+ * @throws {@link ErrorCode|RuntimeNotSupported} when runtime is browser.
911
+ */
912
+ constructor(authConfig, initiateLoginEndpoint, dialogId, settings) {
913
+ throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "TeamsBotSsoPrompt"), ErrorCode.RuntimeNotSupported);
914
+ }
915
+ /**
916
+ * Called when a prompt dialog is pushed onto the dialog stack and is being activated.
917
+ * @remarks
918
+ * If the task is successful, the result indicates whether the prompt is still
919
+ * active after the turn has been processed by the prompt.
920
+ *
921
+ * @param dc The DialogContext for the current turn of the conversation.
922
+ *
923
+ * @throws {@link ErrorCode|InvalidParameter} when timeout property in teams bot sso prompt settings is not number or is not positive.
924
+ * @throws {@link ErrorCode|ChannelNotSupported} when bot channel is not MS Teams.
925
+ * @throws {@link ErrorCode|RuntimeNotSupported} when runtime is browser.
926
+ *
927
+ * @returns A `Promise` representing the asynchronous operation.
928
+ */
929
+ beginDialog(dc) {
930
+ return Promise.reject(new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "TeamsBotSsoPrompt"), ErrorCode.RuntimeNotSupported));
931
+ }
932
+ /**
933
+ * Called when a prompt dialog is the active dialog and the user replied with a new activity.
934
+ *
935
+ * @remarks
936
+ * If the task is successful, the result indicates whether the dialog is still
937
+ * active after the turn has been processed by the dialog.
938
+ * The prompt generally continues to receive the user's replies until it accepts the
939
+ * user's reply as valid input for the prompt.
940
+ *
941
+ * @param dc The DialogContext for the current turn of the conversation.
942
+ *
943
+ * @returns A `Promise` representing the asynchronous operation.
944
+ *
945
+ * @throws {@link ErrorCode|ChannelNotSupported} when bot channel is not MS Teams.
946
+ * @throws {@link ErrorCode|RuntimeNotSupported} when runtime is browser.
947
+ */
948
+ continueDialog(dc) {
949
+ return Promise.reject(new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "TeamsBotSsoPrompt"), ErrorCode.RuntimeNotSupported));
950
+ }
1030
951
  }
1031
952
 
1032
- // Copyright (c) Microsoft Corporation.
1033
- /**
1034
- * Creates a new prompt that leverage Teams Single Sign On (SSO) support for bot to automatically sign in user and
1035
- * help receive oauth token, asks the user to consent if needed.
1036
- *
1037
- * @remarks
1038
- * The prompt will attempt to retrieve the users current token of the desired scopes and store it in
1039
- * the token store.
1040
- *
1041
- * User will be automatically signed in leveraging Teams support of Bot Single Sign On(SSO):
1042
- * https://docs.microsoft.com/en-us/microsoftteams/platform/bots/how-to/authentication/auth-aad-sso-bots
1043
- *
1044
- * @example
1045
- * When used with your bots `DialogSet` you can simply add a new instance of the prompt as a named
1046
- * dialog using `DialogSet.add()`. You can then start the prompt from a waterfall step using either
1047
- * `DialogContext.beginDialog()` or `DialogContext.prompt()`. The user will be prompted to sign in as
1048
- * needed and their access token will be passed as an argument to the callers next waterfall step:
1049
- *
1050
- * ```JavaScript
1051
- * const { ConversationState, MemoryStorage } = require('botbuilder');
1052
- * const { DialogSet, WaterfallDialog } = require('botbuilder-dialogs');
1053
- * const { TeamsBotSsoPrompt } = require('@microsoft/teamsfx');
1054
- *
1055
- * const convoState = new ConversationState(new MemoryStorage());
1056
- * const dialogState = convoState.createProperty('dialogState');
1057
- * const dialogs = new DialogSet(dialogState);
1058
- *
1059
- * dialogs.add(new TeamsBotSsoPrompt('TeamsBotSsoPrompt', {
1060
- * scopes: ["User.Read"],
1061
- * }));
1062
- *
1063
- * dialogs.add(new WaterfallDialog('taskNeedingLogin', [
1064
- * async (step) => {
1065
- * return await step.beginDialog('TeamsBotSsoPrompt');
1066
- * },
1067
- * async (step) => {
1068
- * const token = step.result;
1069
- * if (token) {
1070
- *
1071
- * // ... continue with task needing access token ...
1072
- *
1073
- * } else {
1074
- * await step.context.sendActivity(`Sorry... We couldn't log you in. Try again later.`);
1075
- * return await step.endDialog();
1076
- * }
1077
- * }
1078
- * ]));
1079
- * ```
1080
- */
1081
- class TeamsBotSsoPrompt {
1082
- /**
1083
- * Constructor of TeamsBotSsoPrompt.
1084
- *
1085
- * @param dialogId Unique ID of the dialog within its parent `DialogSet` or `ComponentDialog`.
1086
- * @param settings Settings used to configure the prompt.
1087
- *
1088
- * @throws {@link ErrorCode|InvalidParameter} when scopes is not a valid string or string array.
1089
- * @throws {@link ErrorCode|RuntimeNotSupported} when runtime is browser.
1090
- */
1091
- constructor(teamsfx, dialogId, settings) {
1092
- this.teamsfx = teamsfx;
1093
- this.settings = settings;
1094
- throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "TeamsBotSsoPrompt"), ErrorCode.RuntimeNotSupported);
1095
- }
1096
- /**
1097
- * Called when a prompt dialog is pushed onto the dialog stack and is being activated.
1098
- * @remarks
1099
- * If the task is successful, the result indicates whether the prompt is still
1100
- * active after the turn has been processed by the prompt.
1101
- *
1102
- * @param dc The DialogContext for the current turn of the conversation.
1103
- *
1104
- * @throws {@link ErrorCode|InvalidParameter} when timeout property in teams bot sso prompt settings is not number or is not positive.
1105
- * @throws {@link ErrorCode|ChannelNotSupported} when bot channel is not MS Teams.
1106
- * @throws {@link ErrorCode|RuntimeNotSupported} when runtime is browser.
1107
- *
1108
- * @returns A `Promise` representing the asynchronous operation.
1109
- */
1110
- beginDialog(dc) {
1111
- return Promise.reject(new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "TeamsBotSsoPrompt"), ErrorCode.RuntimeNotSupported));
1112
- }
1113
- /**
1114
- * Called when a prompt dialog is the active dialog and the user replied with a new activity.
1115
- *
1116
- * @remarks
1117
- * If the task is successful, the result indicates whether the dialog is still
1118
- * active after the turn has been processed by the dialog.
1119
- * The prompt generally continues to receive the user's replies until it accepts the
1120
- * user's reply as valid input for the prompt.
1121
- *
1122
- * @param dc The DialogContext for the current turn of the conversation.
1123
- *
1124
- * @returns A `Promise` representing the asynchronous operation.
1125
- *
1126
- * @throws {@link ErrorCode|ChannelNotSupported} when bot channel is not MS Teams.
1127
- * @throws {@link ErrorCode|RuntimeNotSupported} when runtime is browser.
1128
- */
1129
- continueDialog(dc) {
1130
- return Promise.reject(new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "TeamsBotSsoPrompt"), ErrorCode.RuntimeNotSupported));
1131
- }
953
+ // Copyright (c) Microsoft Corporation.
954
+ /**
955
+ * Initializes new Axios instance with specific auth provider
956
+ *
957
+ * @param apiEndpoint - Base url of the API
958
+ * @param authProvider - Auth provider that injects authentication info to each request
959
+ * @returns axios instance configured with specfic auth provider
960
+ *
961
+ * @example
962
+ * ```typescript
963
+ * const client = createApiClient("https://my-api-endpoint-base-url", new BasicAuthProvider("xxx","xxx"));
964
+ * ```
965
+ */
966
+ function createApiClient(apiEndpoint, authProvider) {
967
+ // Add a request interceptor
968
+ const instance = axios.create({
969
+ baseURL: apiEndpoint,
970
+ });
971
+ instance.interceptors.request.use(function (config) {
972
+ return __awaiter(this, void 0, void 0, function* () {
973
+ return (yield authProvider.AddAuthenticationInfo(config));
974
+ });
975
+ });
976
+ return instance;
1132
977
  }
1133
978
 
1134
- // Copyright (c) Microsoft Corporation.
1135
- /**
1136
- * Initializes new Axios instance with specific auth provider
1137
- *
1138
- * @param apiEndpoint - Base url of the API
1139
- * @param authProvider - Auth provider that injects authentication info to each request
1140
- * @returns axios instance configured with specfic auth provider
1141
- *
1142
- * @example
1143
- * ```typescript
1144
- * const client = createApiClient("https://my-api-endpoint-base-url", new BasicAuthProvider("xxx","xxx"));
1145
- * ```
1146
- */
1147
- function createApiClient(apiEndpoint, authProvider) {
1148
- // Add a request interceptor
1149
- const instance = axios.create({
1150
- baseURL: apiEndpoint,
1151
- });
1152
- instance.interceptors.request.use(function (config) {
1153
- return __awaiter(this, void 0, void 0, function* () {
1154
- return (yield authProvider.AddAuthenticationInfo(config));
1155
- });
1156
- });
1157
- return instance;
979
+ // Copyright (c) Microsoft Corporation.
980
+ /**
981
+ * Provider that handles Bearer Token authentication
982
+ */
983
+ class BearerTokenAuthProvider {
984
+ /**
985
+ * @param { () => Promise<string> } getToken - Function that returns the content of bearer token used in http request
986
+ */
987
+ constructor(getToken) {
988
+ this.getToken = getToken;
989
+ }
990
+ /**
991
+ * Adds authentication info to http requests
992
+ *
993
+ * @param { AxiosRequestConfig } config - Contains all the request information and can be updated to include extra authentication info.
994
+ * Refer https://axios-http.com/docs/req_config for detailed document.
995
+ *
996
+ * @returns Updated axios request config.
997
+ *
998
+ * @throws {@link ErrorCode|AuthorizationInfoAlreadyExists} - when Authorization header already exists in request configuration.
999
+ */
1000
+ AddAuthenticationInfo(config) {
1001
+ return __awaiter(this, void 0, void 0, function* () {
1002
+ const token = yield this.getToken();
1003
+ if (!config.headers) {
1004
+ config.headers = {};
1005
+ }
1006
+ if (config.headers["Authorization"]) {
1007
+ throw new ErrorWithCode(ErrorMessage.AuthorizationHeaderAlreadyExists, ErrorCode.AuthorizationInfoAlreadyExists);
1008
+ }
1009
+ config.headers["Authorization"] = `Bearer ${token}`;
1010
+ return config;
1011
+ });
1012
+ }
1158
1013
  }
1159
1014
 
1160
- // Copyright (c) Microsoft Corporation.
1161
- /**
1162
- * Provider that handles Bearer Token authentication
1163
- */
1164
- class BearerTokenAuthProvider {
1165
- /**
1166
- * @param { () => Promise<string> } getToken - Function that returns the content of bearer token used in http request
1167
- */
1168
- constructor(getToken) {
1169
- this.getToken = getToken;
1170
- }
1171
- /**
1172
- * Adds authentication info to http requests
1173
- *
1174
- * @param { AxiosRequestConfig } config - Contains all the request information and can be updated to include extra authentication info.
1175
- * Refer https://axios-http.com/docs/req_config for detailed document.
1176
- *
1177
- * @returns Updated axios request config.
1178
- *
1179
- * @throws {@link ErrorCode|AuthorizationInfoAlreadyExists} - when Authorization header already exists in request configuration.
1180
- */
1181
- AddAuthenticationInfo(config) {
1182
- return __awaiter(this, void 0, void 0, function* () {
1183
- const token = yield this.getToken();
1184
- if (!config.headers) {
1185
- config.headers = {};
1186
- }
1187
- if (config.headers["Authorization"]) {
1188
- throw new ErrorWithCode(ErrorMessage.AuthorizationHeaderAlreadyExists, ErrorCode.AuthorizationInfoAlreadyExists);
1189
- }
1190
- config.headers["Authorization"] = `Bearer ${token}`;
1191
- return config;
1192
- });
1193
- }
1015
+ // Copyright (c) Microsoft Corporation.
1016
+ /**
1017
+ * Provider that handles Basic authentication
1018
+ */
1019
+ class BasicAuthProvider {
1020
+ /**
1021
+ *
1022
+ * @param { string } userName - Username used in basic auth
1023
+ * @param { string } password - Password used in basic auth
1024
+ *
1025
+ * @throws {@link ErrorCode|InvalidParameter} - when username or password is empty.
1026
+ * @throws {@link ErrorCode|RuntimeNotSupported} when runtime is browser.
1027
+ */
1028
+ constructor(userName, password) {
1029
+ throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "BasicAuthProvider"), ErrorCode.RuntimeNotSupported);
1030
+ }
1031
+ /**
1032
+ * Adds authentication info to http requests
1033
+ *
1034
+ * @param { AxiosRequestConfig } config - Contains all the request information and can be updated to include extra authentication info.
1035
+ * Refer https://axios-http.com/docs/req_config for detailed document.
1036
+ *
1037
+ * @returns Updated axios request config.
1038
+ *
1039
+ * @throws {@link ErrorCode|AuthorizationInfoAlreadyExists} - when Authorization header or auth property already exists in request configuration.
1040
+ * @throws {@link ErrorCode|RuntimeNotSupported} when runtime is browser.
1041
+ */
1042
+ AddAuthenticationInfo(config) {
1043
+ return Promise.reject(new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "BasicAuthProvider"), ErrorCode.RuntimeNotSupported));
1044
+ }
1194
1045
  }
1195
1046
 
1196
- // Copyright (c) Microsoft Corporation.
1197
- /**
1198
- * Provider that handles Basic authentication
1199
- */
1200
- class BasicAuthProvider {
1201
- /**
1202
- *
1203
- * @param { string } userName - Username used in basic auth
1204
- * @param { string } password - Password used in basic auth
1205
- *
1206
- * @throws {@link ErrorCode|InvalidParameter} - when username or password is empty.
1207
- * @throws {@link ErrorCode|RuntimeNotSupported} when runtime is browser.
1208
- */
1209
- constructor(userName, password) {
1210
- throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "BasicAuthProvider"), ErrorCode.RuntimeNotSupported);
1211
- }
1212
- /**
1213
- * Adds authentication info to http requests
1214
- *
1215
- * @param { AxiosRequestConfig } config - Contains all the request information and can be updated to include extra authentication info.
1216
- * Refer https://axios-http.com/docs/req_config for detailed document.
1217
- *
1218
- * @returns Updated axios request config.
1219
- *
1220
- * @throws {@link ErrorCode|AuthorizationInfoAlreadyExists} - when Authorization header or auth property already exists in request configuration.
1221
- * @throws {@link ErrorCode|RuntimeNotSupported} when runtime is browser.
1222
- */
1223
- AddAuthenticationInfo(config) {
1224
- return Promise.reject(new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "BasicAuthProvider"), ErrorCode.RuntimeNotSupported));
1225
- }
1047
+ // Copyright (c) Microsoft Corporation.
1048
+ /**
1049
+ * Provider that handles API Key authentication
1050
+ */
1051
+ class ApiKeyProvider {
1052
+ /**
1053
+ *
1054
+ * @param { string } keyName - The name of request header or query parameter that specifies API Key
1055
+ * @param { string } keyValue - The value of API Key
1056
+ * @param { ApiKeyLocation } keyLocation - The location of API Key: request header or query parameter.
1057
+ *
1058
+ * @throws {@link ErrorCode|InvalidParameter} - when key name or key value is empty.
1059
+ * @throws {@link ErrorCode|RuntimeNotSupported} when runtime is browser.
1060
+ */
1061
+ constructor(keyName, keyValue, keyLocation) {
1062
+ throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "ApiKeyProvider"), ErrorCode.RuntimeNotSupported);
1063
+ }
1064
+ /**
1065
+ * Adds authentication info to http requests
1066
+ *
1067
+ * @param { AxiosRequestConfig } config - Contains all the request information and can be updated to include extra authentication info.
1068
+ * Refer https://axios-http.com/docs/req_config for detailed document.
1069
+ *
1070
+ * @returns Updated axios request config.
1071
+ *
1072
+ * @throws {@link ErrorCode|AuthorizationInfoAlreadyExists} - when API key already exists in request header or url query parameter.
1073
+ * @throws {@link ErrorCode|RuntimeNotSupported} when runtime is browser.
1074
+ */
1075
+ AddAuthenticationInfo(config) {
1076
+ return Promise.reject(new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "ApiKeyProvider"), ErrorCode.RuntimeNotSupported));
1077
+ }
1226
1078
  }
1227
-
1228
- // Copyright (c) Microsoft Corporation.
1229
- /**
1230
- * Provider that handles API Key authentication
1231
- */
1232
- class ApiKeyProvider {
1233
- /**
1234
- *
1235
- * @param { string } keyName - The name of request header or query parameter that specifies API Key
1236
- * @param { string } keyValue - The value of API Key
1237
- * @param { ApiKeyLocation } keyLocation - The location of API Key: request header or query parameter.
1238
- *
1239
- * @throws {@link ErrorCode|InvalidParameter} - when key name or key value is empty.
1240
- * @throws {@link ErrorCode|RuntimeNotSupported} when runtime is browser.
1241
- */
1242
- constructor(keyName, keyValue, keyLocation) {
1243
- throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "ApiKeyProvider"), ErrorCode.RuntimeNotSupported);
1244
- }
1245
- /**
1246
- * Adds authentication info to http requests
1247
- *
1248
- * @param { AxiosRequestConfig } config - Contains all the request information and can be updated to include extra authentication info.
1249
- * Refer https://axios-http.com/docs/req_config for detailed document.
1250
- *
1251
- * @returns Updated axios request config.
1252
- *
1253
- * @throws {@link ErrorCode|AuthorizationInfoAlreadyExists} - when API key already exists in request header or url query parameter.
1254
- * @throws {@link ErrorCode|RuntimeNotSupported} when runtime is browser.
1255
- */
1256
- AddAuthenticationInfo(config) {
1257
- return Promise.reject(new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "ApiKeyProvider"), ErrorCode.RuntimeNotSupported));
1258
- }
1259
- }
1260
- /**
1261
- * Define available location for API Key location
1262
- */
1263
- var ApiKeyLocation;
1264
- (function (ApiKeyLocation) {
1265
- /**
1266
- * The API Key is placed in request header
1267
- */
1268
- ApiKeyLocation[ApiKeyLocation["Header"] = 0] = "Header";
1269
- /**
1270
- * The API Key is placed in query parameter
1271
- */
1272
- ApiKeyLocation[ApiKeyLocation["QueryParams"] = 1] = "QueryParams";
1079
+ /**
1080
+ * Define available location for API Key location
1081
+ */
1082
+ var ApiKeyLocation;
1083
+ (function (ApiKeyLocation) {
1084
+ /**
1085
+ * The API Key is placed in request header
1086
+ */
1087
+ ApiKeyLocation[ApiKeyLocation["Header"] = 0] = "Header";
1088
+ /**
1089
+ * The API Key is placed in query parameter
1090
+ */
1091
+ ApiKeyLocation[ApiKeyLocation["QueryParams"] = 1] = "QueryParams";
1273
1092
  })(ApiKeyLocation || (ApiKeyLocation = {}));
1274
1093
 
1275
- // Copyright (c) Microsoft Corporation.
1276
- /**
1277
- * Provider that handles Certificate authentication
1278
- */
1279
- class CertificateAuthProvider {
1280
- /**
1281
- *
1282
- * @param { SecureContextOptions } certOption - information about the cert used in http requests
1283
- */
1284
- constructor(certOption) {
1285
- throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "CertificateAuthProvider"), ErrorCode.RuntimeNotSupported);
1286
- }
1287
- /**
1288
- * Adds authentication info to http requests.
1289
- *
1290
- * @param { AxiosRequestConfig } config - Contains all the request information and can be updated to include extra authentication info.
1291
- * Refer https://axios-http.com/docs/req_config for detailed document.
1292
- *
1293
- * @returns Updated axios request config.
1294
- *
1295
- * @throws {@link ErrorCode|InvalidParameter} - when custom httpsAgent in the request has duplicate properties with certOption provided in constructor.
1296
- * @throws {@link ErrorCode|RuntimeNotSupported} when runtime is browser.
1297
- */
1298
- AddAuthenticationInfo(config) {
1299
- return Promise.reject(new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "CertificateAuthProvider"), ErrorCode.RuntimeNotSupported));
1300
- }
1301
- }
1302
- /**
1303
- * Helper to create SecureContextOptions from PEM format cert
1304
- *
1305
- * @param { string | Buffer } cert - The cert chain in PEM format
1306
- * @param { string | Buffer } key - The private key for the cert chain
1307
- * @param { {passphrase?: string; ca?: string | Buffer} } options - Optional settings when create the cert options.
1308
- *
1309
- * @returns Instance of SecureContextOptions
1310
- *
1311
- * @throws {@link ErrorCode|InvalidParameter} - when any parameter is empty
1312
- * @throws {@link ErrorCode|RuntimeNotSupported} when runtime is browser.
1313
- *
1314
- */
1315
- function createPemCertOption(cert, key, options) {
1316
- throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "createPemCertOption"), ErrorCode.RuntimeNotSupported);
1317
- }
1318
- /**
1319
- * Helper to create SecureContextOptions from PFX format cert
1320
- *
1321
- * @param { string | Buffer } pfx - The content of .pfx file
1322
- * @param { {passphrase?: string} } options - Optional settings when create the cert options.
1323
- *
1324
- * @returns Instance of SecureContextOptions
1325
- *
1326
- * @throws {@link ErrorCode|InvalidParameter} - when any parameter is empty
1327
- * @throws {@link ErrorCode|RuntimeNotSupported} when runtime is browser.
1328
- *
1329
- */
1330
- function createPfxCertOption(pfx, options) {
1331
- throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "createPfxCertOption"), ErrorCode.RuntimeNotSupported);
1094
+ // Copyright (c) Microsoft Corporation.
1095
+ /**
1096
+ * Provider that handles Certificate authentication
1097
+ */
1098
+ class CertificateAuthProvider {
1099
+ /**
1100
+ *
1101
+ * @param { SecureContextOptions } certOption - information about the cert used in http requests
1102
+ */
1103
+ constructor(certOption) {
1104
+ throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "CertificateAuthProvider"), ErrorCode.RuntimeNotSupported);
1105
+ }
1106
+ /**
1107
+ * Adds authentication info to http requests.
1108
+ *
1109
+ * @param { AxiosRequestConfig } config - Contains all the request information and can be updated to include extra authentication info.
1110
+ * Refer https://axios-http.com/docs/req_config for detailed document.
1111
+ *
1112
+ * @returns Updated axios request config.
1113
+ *
1114
+ * @throws {@link ErrorCode|InvalidParameter} - when custom httpsAgent in the request has duplicate properties with certOption provided in constructor.
1115
+ * @throws {@link ErrorCode|RuntimeNotSupported} when runtime is browser.
1116
+ */
1117
+ AddAuthenticationInfo(config) {
1118
+ return Promise.reject(new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "CertificateAuthProvider"), ErrorCode.RuntimeNotSupported));
1119
+ }
1332
1120
  }
1333
-
1334
- // Copyright (c) Microsoft Corporation.
1335
- // Licensed under the MIT license.
1336
- /**
1337
- * Identity type to use in authentication.
1338
- */
1339
- var IdentityType;
1340
- (function (IdentityType) {
1341
- /**
1342
- * Represents the current user of Teams.
1343
- */
1344
- IdentityType["User"] = "User";
1345
- /**
1346
- * Represents the application itself.
1347
- */
1348
- IdentityType["App"] = "Application";
1349
- })(IdentityType || (IdentityType = {}));
1350
-
1351
- // Copyright (c) Microsoft Corporation.
1352
- /**
1353
- * A class providing credential and configuration.
1354
- * @deprecated Please use {@link TeamsUserCredential}
1355
- * in browser environment and {@link OnBehalfOfUserCredential} or {@link AppCredential} in NodeJS.
1356
- */
1357
- class TeamsFx {
1358
- constructor(identityType, customConfig) {
1359
- this.identityType = identityType !== null && identityType !== void 0 ? identityType : IdentityType.User;
1360
- if (this.identityType !== IdentityType.User) {
1361
- const errorMsg = formatString(ErrorMessage.IdentityTypeNotSupported, this.identityType.toString(), "TeamsFx");
1362
- internalLogger.error(errorMsg);
1363
- throw new ErrorWithCode(errorMsg, ErrorCode.IdentityTypeNotSupported);
1364
- }
1365
- this.configuration = new Map();
1366
- this.loadFromEnv();
1367
- if (customConfig) {
1368
- const myConfig = Object.assign({}, customConfig);
1369
- for (const key of Object.keys(myConfig)) {
1370
- const value = myConfig[key];
1371
- if (value) {
1372
- this.configuration.set(key, value);
1373
- }
1374
- }
1375
- }
1376
- if (this.configuration.size === 0) {
1377
- internalLogger.warn("No configuration is loaded, please pass required configs to TeamsFx constructor");
1378
- }
1379
- }
1380
- loadFromEnv() {
1381
- if (window && window.__env__) {
1382
- // testing purpose
1383
- const env = window.__env__;
1384
- this.configuration.set("authorityHost", env.REACT_APP_AUTHORITY_HOST);
1385
- this.configuration.set("tenantId", env.REACT_APP_TENANT_ID);
1386
- this.configuration.set("clientId", env.REACT_APP_CLIENT_ID);
1387
- this.configuration.set("initiateLoginEndpoint", env.REACT_APP_START_LOGIN_PAGE_URL);
1388
- this.configuration.set("applicationIdUri", env.M365_APPLICATION_ID_URI);
1389
- this.configuration.set("apiEndpoint", env.REACT_APP_FUNC_ENDPOINT);
1390
- this.configuration.set("apiName", env.REACT_APP_FUNC_NAME);
1391
- }
1392
- else {
1393
- // TODO: support common environment variable name
1394
- try {
1395
- this.configuration.set("authorityHost", process.env.REACT_APP_AUTHORITY_HOST);
1396
- this.configuration.set("tenantId", process.env.REACT_APP_TENANT_ID);
1397
- this.configuration.set("clientId", process.env.REACT_APP_CLIENT_ID);
1398
- this.configuration.set("initiateLoginEndpoint", process.env.REACT_APP_START_LOGIN_PAGE_URL);
1399
- this.configuration.set("applicationIdUri", process.env.M365_APPLICATION_ID_URI);
1400
- this.configuration.set("apiEndpoint", process.env.REACT_APP_FUNC_ENDPOINT);
1401
- this.configuration.set("apiName", process.env.REACT_APP_FUNC_NAME);
1402
- }
1403
- catch (_) {
1404
- internalLogger.warn("Cannot read process.env, please use webpack if you want to use environment variables.");
1405
- return;
1406
- }
1407
- }
1408
- }
1409
- getIdentityType() {
1410
- return this.identityType;
1411
- }
1412
- getCredential() {
1413
- if (!this.teamsUserCredential) {
1414
- this.teamsUserCredential = new TeamsUserCredential(Object.fromEntries(this.configuration));
1415
- }
1416
- return this.teamsUserCredential;
1417
- }
1418
- getUserInfo(resources) {
1419
- return __awaiter(this, void 0, void 0, function* () {
1420
- return yield this.getCredential().getUserInfo(resources);
1421
- });
1422
- }
1423
- login(scopes, resources) {
1424
- return __awaiter(this, void 0, void 0, function* () {
1425
- yield this.getCredential().login(scopes, resources);
1426
- });
1427
- }
1428
- setSsoToken(ssoToken) {
1429
- return this;
1430
- }
1431
- getConfig(key) {
1432
- const value = this.configuration.get(key);
1433
- if (!value) {
1434
- throw new Error();
1435
- }
1436
- return value;
1437
- }
1438
- hasConfig(key) {
1439
- const value = this.configuration.get(key);
1440
- return !!value;
1441
- }
1442
- getConfigs() {
1443
- const config = {};
1444
- for (const key of this.configuration.keys()) {
1445
- const value = this.configuration.get(key);
1446
- if (value) {
1447
- config[key] = value;
1448
- }
1449
- }
1450
- return config;
1451
- }
1121
+ /**
1122
+ * Helper to create SecureContextOptions from PEM format cert
1123
+ *
1124
+ * @param { string | Buffer } cert - The cert chain in PEM format
1125
+ * @param { string | Buffer } key - The private key for the cert chain
1126
+ * @param { {passphrase?: string; ca?: string | Buffer} } options - Optional settings when create the cert options.
1127
+ *
1128
+ * @returns Instance of SecureContextOptions
1129
+ *
1130
+ * @throws {@link ErrorCode|InvalidParameter} - when any parameter is empty
1131
+ * @throws {@link ErrorCode|RuntimeNotSupported} when runtime is browser.
1132
+ *
1133
+ */
1134
+ function createPemCertOption(cert, key, options) {
1135
+ throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "createPemCertOption"), ErrorCode.RuntimeNotSupported);
1136
+ }
1137
+ /**
1138
+ * Helper to create SecureContextOptions from PFX format cert
1139
+ *
1140
+ * @param { string | Buffer } pfx - The content of .pfx file
1141
+ * @param { {passphrase?: string} } options - Optional settings when create the cert options.
1142
+ *
1143
+ * @returns Instance of SecureContextOptions
1144
+ *
1145
+ * @throws {@link ErrorCode|InvalidParameter} - when any parameter is empty
1146
+ * @throws {@link ErrorCode|RuntimeNotSupported} when runtime is browser.
1147
+ *
1148
+ */
1149
+ function createPfxCertOption(pfx, options) {
1150
+ throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "createPfxCertOption"), ErrorCode.RuntimeNotSupported);
1452
1151
  }
1453
1152
 
1454
- // Copyright (c) Microsoft Corporation.
1455
- // Licensed under the MIT license.
1456
- /**
1457
- * The target type where the notification will be sent to.
1458
- *
1459
- * @remarks
1460
- * - "Channel" means to a team channel. (By default, notification to a team will be sent to its "General" channel.)
1461
- * - "Group" means to a group chat.
1462
- * - "Person" means to a personal chat.
1463
- */
1464
- var NotificationTargetType;
1465
- (function (NotificationTargetType) {
1466
- /**
1467
- * The notification will be sent to a team channel.
1468
- * (By default, notification to a team will be sent to its "General" channel.)
1469
- */
1470
- NotificationTargetType["Channel"] = "Channel";
1471
- /**
1472
- * The notification will be sent to a group chat.
1473
- */
1474
- NotificationTargetType["Group"] = "Group";
1475
- /**
1476
- * The notification will be sent to a personal chat.
1477
- */
1478
- NotificationTargetType["Person"] = "Person";
1479
- })(NotificationTargetType || (NotificationTargetType = {}));
1480
- /**
1481
- * Options used to control how the response card will be sent to users.
1482
- */
1483
- var AdaptiveCardResponse;
1484
- (function (AdaptiveCardResponse) {
1485
- /**
1486
- * The response card will be replaced the current one for the interactor who trigger the action.
1487
- */
1488
- AdaptiveCardResponse[AdaptiveCardResponse["ReplaceForInteractor"] = 0] = "ReplaceForInteractor";
1489
- /**
1490
- * The response card will be replaced the current one for all users in the chat.
1491
- */
1492
- AdaptiveCardResponse[AdaptiveCardResponse["ReplaceForAll"] = 1] = "ReplaceForAll";
1493
- /**
1494
- * The response card will be sent as a new message for all users in the chat.
1495
- */
1496
- AdaptiveCardResponse[AdaptiveCardResponse["NewForAll"] = 2] = "NewForAll";
1497
- })(AdaptiveCardResponse || (AdaptiveCardResponse = {}));
1498
- /**
1499
- * Status code for an `application/vnd.microsoft.error` invoke response.
1500
- */
1501
- var InvokeResponseErrorCode;
1502
- (function (InvokeResponseErrorCode) {
1503
- /**
1504
- * Invalid request.
1505
- */
1506
- InvokeResponseErrorCode[InvokeResponseErrorCode["BadRequest"] = 400] = "BadRequest";
1507
- /**
1508
- * Internal server error.
1509
- */
1510
- InvokeResponseErrorCode[InvokeResponseErrorCode["InternalServerError"] = 500] = "InternalServerError";
1153
+ // Copyright (c) Microsoft Corporation.
1154
+ // Licensed under the MIT license.
1155
+ /**
1156
+ * The target type where the notification will be sent to.
1157
+ *
1158
+ * @remarks
1159
+ * - "Channel" means to a team channel. (By default, notification to a team will be sent to its "General" channel.)
1160
+ * - "Group" means to a group chat.
1161
+ * - "Person" means to a personal chat.
1162
+ */
1163
+ var NotificationTargetType;
1164
+ (function (NotificationTargetType) {
1165
+ /**
1166
+ * The notification will be sent to a team channel.
1167
+ * (By default, notification to a team will be sent to its "General" channel.)
1168
+ */
1169
+ NotificationTargetType["Channel"] = "Channel";
1170
+ /**
1171
+ * The notification will be sent to a group chat.
1172
+ */
1173
+ NotificationTargetType["Group"] = "Group";
1174
+ /**
1175
+ * The notification will be sent to a personal chat.
1176
+ */
1177
+ NotificationTargetType["Person"] = "Person";
1178
+ })(NotificationTargetType || (NotificationTargetType = {}));
1179
+ /**
1180
+ * Options used to control how the response card will be sent to users.
1181
+ */
1182
+ var AdaptiveCardResponse;
1183
+ (function (AdaptiveCardResponse) {
1184
+ /**
1185
+ * The response card will be replaced the current one for the interactor who trigger the action.
1186
+ */
1187
+ AdaptiveCardResponse[AdaptiveCardResponse["ReplaceForInteractor"] = 0] = "ReplaceForInteractor";
1188
+ /**
1189
+ * The response card will be replaced the current one for all users in the chat.
1190
+ */
1191
+ AdaptiveCardResponse[AdaptiveCardResponse["ReplaceForAll"] = 1] = "ReplaceForAll";
1192
+ /**
1193
+ * The response card will be sent as a new message for all users in the chat.
1194
+ */
1195
+ AdaptiveCardResponse[AdaptiveCardResponse["NewForAll"] = 2] = "NewForAll";
1196
+ })(AdaptiveCardResponse || (AdaptiveCardResponse = {}));
1197
+ /**
1198
+ * Status code for an `application/vnd.microsoft.error` invoke response.
1199
+ */
1200
+ var InvokeResponseErrorCode;
1201
+ (function (InvokeResponseErrorCode) {
1202
+ /**
1203
+ * Invalid request.
1204
+ */
1205
+ InvokeResponseErrorCode[InvokeResponseErrorCode["BadRequest"] = 400] = "BadRequest";
1206
+ /**
1207
+ * Internal server error.
1208
+ */
1209
+ InvokeResponseErrorCode[InvokeResponseErrorCode["InternalServerError"] = 500] = "InternalServerError";
1511
1210
  })(InvokeResponseErrorCode || (InvokeResponseErrorCode = {}));
1512
1211
 
1513
- // Copyright (c) Microsoft Corporation.
1514
- /**
1515
- * Provide utilities for bot conversation, including:
1516
- * - handle command and response.
1517
- * - send notification to varies targets (e.g., member, group, channel).
1518
- *
1519
- * @remarks
1520
- * Only work on server side.
1521
- */
1522
- /**
1523
- * @deprecated Use `BotBuilderCloudAdapter.ConversationBot` instead.
1524
- */
1525
- class ConversationBot$1 {
1526
- /**
1527
- * Creates new instance of the `ConversationBot`.
1528
- *
1529
- * @param options - initialize options
1530
- *
1531
- * @remarks
1532
- * Only work on server side.
1533
- */
1534
- constructor(options) {
1535
- throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "ConversationBot"), ErrorCode.RuntimeNotSupported);
1536
- }
1537
- /**
1538
- * The request handler to integrate with web request.
1539
- *
1540
- * @param req - an Express or Restify style request object.
1541
- * @param res - an Express or Restify style response object.
1542
- * @param logic - the additional function to handle bot context.
1543
- *
1544
- * @remarks
1545
- * Only work on server side.
1546
- */
1547
- requestHandler(req, res, logic) {
1548
- throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "ConversationBot"), ErrorCode.RuntimeNotSupported);
1549
- }
1212
+ // Copyright (c) Microsoft Corporation.
1213
+ /*
1214
+ * Sso execution dialog, use to handle sso command
1215
+ */
1216
+ class BotSsoExecutionDialog {
1217
+ constructor(dedupStorage, ssoPromptSettings, authConfig, ...args) {
1218
+ throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "BotSsoExecutionDialog"), ErrorCode.RuntimeNotSupported);
1219
+ }
1220
+ // eslint-disable-next-line no-secrets/no-secrets
1221
+ /**
1222
+ * Add TeamsFxBotSsoCommandHandler instance
1223
+ * @param handler {@link BotSsoExecutionDialogHandler} callback function
1224
+ * @param triggerPatterns The trigger pattern
1225
+ */
1226
+ addCommand(handler, triggerPatterns) {
1227
+ throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "BotSsoExecutionDialog"), ErrorCode.RuntimeNotSupported);
1228
+ }
1229
+ /**
1230
+ * The run method handles the incoming activity (in the form of a DialogContext) and passes it through the dialog system.
1231
+ *
1232
+ * @param context The context object for the current turn.
1233
+ * @param accessor The instance of StatePropertyAccessor for dialog system.
1234
+ */
1235
+ run(context, accessor) {
1236
+ throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "BotSsoExecutionDialog"), ErrorCode.RuntimeNotSupported);
1237
+ }
1238
+ /**
1239
+ * Called when the component is ending.
1240
+ *
1241
+ * @param context Context for the current turn of conversation.
1242
+ */
1243
+ onEndDialog(context) {
1244
+ throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "BotSsoExecutionDialog"), ErrorCode.RuntimeNotSupported);
1245
+ }
1550
1246
  }
1551
1247
 
1552
- // Copyright (c) Microsoft Corporation.
1553
- /*
1554
- * Sso execution dialog, use to handle sso command
1555
- */
1556
- class BotSsoExecutionDialog {
1557
- constructor(dedupStorage, ssoPromptSettings, authConfig, ...args) {
1558
- throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "BotSsoExecutionDialog"), ErrorCode.RuntimeNotSupported);
1559
- }
1560
- /**
1561
- * Add TeamsFxBotSsoCommandHandler instance
1562
- * @param handler {@link BotSsoExecutionDialogHandler} callback function
1563
- * @param triggerPatterns The trigger pattern
1564
- */
1565
- addCommand(handler, triggerPatterns) {
1566
- throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "BotSsoExecutionDialog"), ErrorCode.RuntimeNotSupported);
1567
- }
1568
- /**
1569
- * The run method handles the incoming activity (in the form of a DialogContext) and passes it through the dialog system.
1570
- *
1571
- * @param context The context object for the current turn.
1572
- * @param accessor The instance of StatePropertyAccessor for dialog system.
1573
- */
1574
- run(context, accessor) {
1575
- return __awaiter(this, void 0, void 0, function* () {
1576
- throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "BotSsoExecutionDialog"), ErrorCode.RuntimeNotSupported);
1577
- });
1578
- }
1579
- /**
1580
- * Called when the component is ending.
1581
- *
1582
- * @param context Context for the current turn of conversation.
1583
- */
1584
- onEndDialog(context) {
1585
- return __awaiter(this, void 0, void 0, function* () {
1586
- throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "BotSsoExecutionDialog"), ErrorCode.RuntimeNotSupported);
1587
- });
1588
- }
1248
+ /**
1249
+ * Users execute query with SSO or Access Token.
1250
+ * @remarks
1251
+ * Only works in in server side.
1252
+ */
1253
+ function handleMessageExtensionQueryWithSSO(context, config, initiateLoginEndpoint, scopes, logic) {
1254
+ throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "queryWithToken in message extension"), ErrorCode.RuntimeNotSupported);
1589
1255
  }
1590
1256
 
1591
- // Copyright (c) Microsoft Corporation.
1592
- /**
1593
- * Send a plain text message to a notification target.
1594
- *
1595
- * @remarks
1596
- * Only work on server side.
1597
- *
1598
- * @param target - the notification target.
1599
- * @param text - the plain text message.
1600
- * @param onError - an optional error handler that can catch exceptions during message sending.
1601
- * @returns A `Promise` representing the asynchronous operation.
1602
- */
1603
- function sendMessage$1(target, text, onError) {
1604
- throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "sendMessage"), ErrorCode.RuntimeNotSupported);
1605
- }
1606
- /**
1607
- * Send an adaptive card message to a notification target.
1608
- *
1609
- * @remarks
1610
- * Only work on server side.
1611
- *
1612
- * @param target - the notification target.
1613
- * @param card - the adaptive card raw JSON.
1614
- * @param onError - an optional error handler that can catch exceptions during adaptive card sending.
1615
- * @returns A `Promise` representing the asynchronous operation.
1616
- */
1617
- function sendAdaptiveCard$1(target, card, onError) {
1618
- throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "sendAdaptiveCard"), ErrorCode.RuntimeNotSupported);
1619
- }
1620
- /**
1621
- * A {@link NotificationTarget} that represents a team channel.
1622
- *
1623
- * @remarks
1624
- * Only work on server side.
1625
- *
1626
- * It's recommended to get channels from {@link TeamsBotInstallation.channels()}.
1627
- */
1628
- class Channel$1 {
1629
- /**
1630
- * Constructor.
1631
- *
1632
- * @remarks
1633
- * Only work on server side.
1634
- *
1635
- * It's recommended to get channels from {@link TeamsBotInstallation.channels()}, instead of using this constructor.
1636
- *
1637
- * @param parent - The parent {@link TeamsBotInstallation} where this channel is created from.
1638
- * @param info - Detailed channel information.
1639
- */
1640
- constructor(parent, info) {
1641
- /**
1642
- * Notification target type. For channel it's always "Channel".
1643
- *
1644
- * @remarks
1645
- * Only work on server side.
1646
- */
1647
- this.type = NotificationTargetType.Channel;
1648
- throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "Channel"), ErrorCode.RuntimeNotSupported);
1649
- }
1650
- /**
1651
- * Send a plain text message.
1652
- *
1653
- * @remarks
1654
- * Only work on server side.
1655
- *
1656
- * @param text - the plain text message.
1657
- * @param onError - an optional error handler that can catch exceptions during message sending.
1658
- * @returns the response of sending message.
1659
- */
1660
- sendMessage(text, onError) {
1661
- throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "Channel"), ErrorCode.RuntimeNotSupported);
1662
- }
1663
- /**
1664
- * Send an adaptive card message.
1665
- *
1666
- * @remarks
1667
- * Only work on server side.
1668
- *
1669
- * @param card - the adaptive card raw JSON.
1670
- * @param onError - an optional error handler that can catch exceptions during adaptive card sending.
1671
- * @returns the response of sending adaptive card message.
1672
- */
1673
- sendAdaptiveCard(card, onError) {
1674
- throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "Channel"), ErrorCode.RuntimeNotSupported);
1675
- }
1676
- }
1677
- /**
1678
- * A {@link NotificationTarget} that represents a team member.
1679
- *
1680
- * @remarks
1681
- * Only work on server side.
1682
- *
1683
- * It's recommended to get members from {@link TeamsBotInstallation.members()}.
1684
- */
1685
- class Member$1 {
1686
- /**
1687
- * Constructor.
1688
- *
1689
- * @remarks
1690
- * Only work on server side.
1691
- *
1692
- * It's recommended to get members from {@link TeamsBotInstallation.members()}, instead of using this constructor.
1693
- *
1694
- * @param parent - The parent {@link TeamsBotInstallation} where this member is created from.
1695
- * @param account - Detailed member account information.
1696
- */
1697
- constructor(parent, account) {
1698
- /**
1699
- * Notification target type. For member it's always "Person".
1700
- *
1701
- * @remarks
1702
- * Only work on server side.
1703
- */
1704
- this.type = NotificationTargetType.Person;
1705
- throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "Member"), ErrorCode.RuntimeNotSupported);
1706
- }
1707
- /**
1708
- * Send a plain text message.
1709
- *
1710
- * @remarks
1711
- * Only work on server side.
1712
- *
1713
- * @param text - the plain text message.
1714
- * @param onError - an optional error handler that can catch exceptions during message sending.
1715
- * @returns the response of sending message.
1716
- */
1717
- sendMessage(text, onError) {
1718
- throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "Member"), ErrorCode.RuntimeNotSupported);
1719
- }
1720
- /**
1721
- * Send an adaptive card message.
1722
- *
1723
- * @remarks
1724
- * Only work on server side.
1725
- *
1726
- * @param card - the adaptive card raw JSON.
1727
- * @param onError - an optional error handler that can catch exceptions during adaptive card sending.
1728
- * @returns the response of sending adaptive card message.
1729
- */
1730
- sendAdaptiveCard(card, onError) {
1731
- throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "Member"), ErrorCode.RuntimeNotSupported);
1732
- }
1733
- }
1734
- /**
1735
- * A {@link NotificationTarget} that represents a bot installation. Teams Bot could be installed into
1736
- * - Personal chat
1737
- * - Group chat
1738
- * - Team (by default the `General` channel)
1739
- *
1740
- * @remarks
1741
- * Only work on server side.
1742
- *
1743
- * It's recommended to get bot installations from {@link ConversationBot.installations()}.
1744
- */
1745
- /**
1746
- * @deprecated Use `BotBuilderCloudAdapter.TeamsBotInstallation` instead.
1747
- */
1748
- class TeamsBotInstallation$1 {
1749
- /**
1750
- * Constructor
1751
- *
1752
- * @remarks
1753
- * Only work on server side.
1754
- *
1755
- * It's recommended to get bot installations from {@link ConversationBot.installations()}, instead of using this constructor.
1756
- *
1757
- * @param adapter - the bound `BotFrameworkAdapter`.
1758
- * @param conversationReference - the bound `ConversationReference`.
1759
- */
1760
- constructor(adapter, conversationReference) {
1761
- throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "TeamsBotInstallation"), ErrorCode.RuntimeNotSupported);
1762
- }
1763
- /**
1764
- * Send a plain text message.
1765
- *
1766
- * @remarks
1767
- * Only work on server side.
1768
- *
1769
- * @param text - the plain text message.
1770
- * @param onError - an optional error handler that can catch exceptions during message sending.
1771
- * @returns the response of sending message.
1772
- */
1773
- sendMessage(text, onError) {
1774
- throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "TeamsBotInstallation"), ErrorCode.RuntimeNotSupported);
1775
- }
1776
- /**
1777
- * Send an adaptive card message.
1778
- *
1779
- * @remarks
1780
- * Only work on server side.
1781
- *
1782
- * @param card - the adaptive card raw JSON.
1783
- * @param onError - an optional error handler that can catch exceptions during adaptive card sending.
1784
- * @returns the response of sending adaptive card message.
1785
- */
1786
- sendAdaptiveCard(card, onError) {
1787
- throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "TeamsBotInstallation"), ErrorCode.RuntimeNotSupported);
1788
- }
1789
- /**
1790
- * Get channels from this bot installation.
1791
- *
1792
- * @remarks
1793
- * Only work on server side.
1794
- *
1795
- * @returns an array of channels if bot is installed into a team, otherwise returns an empty array.
1796
- */
1797
- channels() {
1798
- throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "TeamsBotInstallation"), ErrorCode.RuntimeNotSupported);
1799
- }
1800
- /**
1801
- * Get members from this bot installation.
1802
- *
1803
- * @remarks
1804
- * Only work on server side.
1805
- *
1806
- * @returns an array of members from where the bot is installed.
1807
- */
1808
- members() {
1809
- throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "TeamsBotInstallation"), ErrorCode.RuntimeNotSupported);
1810
- }
1811
- /**
1812
- * Get team details from this bot installation
1813
- *
1814
- * @returns the team details if bot is installed into a team, otherwise returns undefined.
1815
- */
1816
- getTeamDetails() {
1817
- throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "TeamsBotInstallation"), ErrorCode.RuntimeNotSupported);
1818
- }
1819
- }
1820
- /**
1821
- * Provide static utilities for bot notification.
1822
- *
1823
- * @remarks
1824
- * Only work on server side.
1825
- *
1826
- * @example
1827
- * Here's an example on how to send notification via Teams Bot.
1828
- * ```typescript
1829
- * // initialize (it's recommended to be called before handling any bot message)
1830
- * const notificationBot = new NotificationBot(adapter);
1831
- *
1832
- * // get all bot installations and send message
1833
- * for (const target of await notificationBot.installations()) {
1834
- * await target.sendMessage("Hello Notification");
1835
- * }
1836
- *
1837
- * // alternative - send message to all members
1838
- * for (const target of await notificationBot.installations()) {
1839
- * for (const member of await target.members()) {
1840
- * await member.sendMessage("Hello Notification");
1841
- * }
1842
- * }
1843
- * ```
1844
- */
1845
- /**
1846
- * @deprecated Use `BotBuilderCloudAdapter.NotificationBot` instead.
1847
- */
1848
- class NotificationBot$1 {
1849
- /**
1850
- * constructor of the notification bot.
1851
- *
1852
- * @remarks
1853
- * Only work on server side.
1854
- *
1855
- * To ensure accuracy, it's recommended to initialize before handling any message.
1856
- *
1857
- * @param adapter - the bound `BotFrameworkAdapter`
1858
- * @param options - initialize options
1859
- */
1860
- constructor(adapter, options) {
1861
- throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "NotificationBot"), ErrorCode.RuntimeNotSupported);
1862
- }
1863
- /**
1864
- * Get all targets where the bot is installed.
1865
- *
1866
- * @remarks
1867
- * Only work on server side.
1868
- *
1869
- * The result is retrieving from the persisted storage.
1870
- *
1871
- * @returns - an array of {@link TeamsBotInstallation}.
1872
- */
1873
- static installations() {
1874
- throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "NotificationBot"), ErrorCode.RuntimeNotSupported);
1875
- }
1876
- /**
1877
- * Returns the first {@link Member} where predicate is true, and undefined otherwise.
1878
- *
1879
- * @remarks
1880
- * Only work on server side.
1881
- *
1882
- * @param predicate find calls predicate once for each member of the installation,
1883
- * until it finds one where predicate returns true. If such a member is found, find
1884
- * immediately returns that member. Otherwise, find returns undefined.
1885
- * @param scope the scope to find members from the installations
1886
- * (personal chat, group chat, Teams channel).
1887
- * @returns the first {@link Member} where predicate is true, and undefined otherwise.
1888
- */
1889
- findMember(predicate, scope) {
1890
- throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "NotificationBot"), ErrorCode.RuntimeNotSupported);
1891
- }
1892
- /**
1893
- * Returns the first {@link Channel} where predicate is true, and undefined otherwise.
1894
- * (Ensure the bot app is installed into the `General` channel, otherwise undefined will be returned.)
1895
- *
1896
- * @remarks
1897
- * Only work on server side.
1898
- *
1899
- * @param predicate find calls predicate once for each channel of the installation,
1900
- * until it finds one where predicate returns true. If such a channel is found, find
1901
- * immediately returns that channel. Otherwise, find returns undefined.
1902
- * @returns the first {@link Channel} where predicate is true, and undefined otherwise.
1903
- */
1904
- findChannel(predicate) {
1905
- throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "NotificationBot"), ErrorCode.RuntimeNotSupported);
1906
- }
1907
- /**
1908
- * Returns all {@link Member} where predicate is true, and empty array otherwise.
1909
- *
1910
- * @remarks
1911
- * Only work on server side.
1912
- *
1913
- * @param predicate find calls predicate for each member of the installation.
1914
- * @param scope the scope to find members from the installations
1915
- * (personal chat, group chat, Teams channel).
1916
- * @returns an array of {@link Member} where predicate is true, and empty array otherwise.
1917
- */
1918
- findAllMembers(predicate, scope) {
1919
- throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "NotificationBot"), ErrorCode.RuntimeNotSupported);
1920
- }
1921
- /**
1922
- * Returns all {@link Channel} where predicate is true, and empty array otherwise.
1923
- * (Ensure the bot app is installed into the `General` channel, otherwise empty array will be returned.)
1924
- *
1925
- * @remarks
1926
- * Only work on server side.
1927
- *
1928
- * @param predicate find calls predicate for each channel of the installation.
1929
- * @returns an array of {@link Channel} where predicate is true, and empty array otherwise.
1930
- */
1931
- findAllChannels(predicate) {
1932
- throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "NotificationBot"), ErrorCode.RuntimeNotSupported);
1933
- }
1934
- }
1935
- /**
1936
- * The search scope when calling {@link NotificationBot.findMember} and {@link NotificationBot.findAllMembers}.
1937
- * The search scope is a flagged enum and it can be combined with `|`.
1938
- * For example, to search from personal chat and group chat, use `SearchScope.Person | SearchScope.Group`.
1939
- */
1940
- var SearchScope$1;
1941
- (function (SearchScope) {
1942
- /**
1943
- * Search members from the installations in personal chat only.
1944
- */
1945
- SearchScope[SearchScope["Person"] = 1] = "Person";
1946
- /**
1947
- * Search members from the installations in group chat only.
1948
- */
1949
- SearchScope[SearchScope["Group"] = 2] = "Group";
1950
- /**
1951
- * Search members from the installations in Teams channel only.
1952
- */
1953
- SearchScope[SearchScope["Channel"] = 4] = "Channel";
1954
- /**
1955
- * Search members from all installations including personal chat, group chat and Teams channel.
1956
- */
1957
- SearchScope[SearchScope["All"] = 7] = "All";
1958
- })(SearchScope$1 || (SearchScope$1 = {}));
1959
-
1960
- // Copyright (c) Microsoft Corporation.
1961
- /**
1962
- * A command bot for receiving commands and sending responses in Teams.
1963
- *
1964
- * @remarks
1965
- * Only work on server side.
1966
- */
1967
- /**
1968
- * @deprecated Use `BotBuilderCloudAdapter.CommandBot` instead.
1969
- */
1970
- class CommandBot$1 {
1971
- /**
1972
- * Creates a new instance of the `CommandBot`.
1973
- *
1974
- * @param adapter The bound `BotFrameworkAdapter`.
1975
- * @param commands The commands to registered with the command bot. Each command should implement the interface {@link TeamsFxBotCommandHandler} so that it can be correctly handled by this command bot.
1976
- */
1977
- constructor(adapter, commands) {
1978
- throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "CommandBot"), ErrorCode.RuntimeNotSupported);
1979
- }
1980
- /**
1981
- * Registers a command into the command bot.
1982
- *
1983
- * @param command The command to registered.
1984
- *
1985
- * @remarks
1986
- * Only work on server side.
1987
- */
1988
- registerCommand(command) {
1989
- throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "CommandBot"), ErrorCode.RuntimeNotSupported);
1990
- }
1991
- /**
1992
- * Registers commands into the command bot.
1993
- *
1994
- * @param commands The command to registered.
1995
- *
1996
- * @remarks
1997
- * Only work on server side.
1998
- */
1999
- registerCommands(commands) {
2000
- throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "CommandBot"), ErrorCode.RuntimeNotSupported);
2001
- }
2002
- /**
2003
- * Registers a sso command into the command bot.
2004
- *
2005
- * @param command The command to register.
2006
- */
2007
- registerSsoCommand(ssoCommand) {
2008
- throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "CommandBot"), ErrorCode.RuntimeNotSupported);
2009
- }
2010
- /**
2011
- * Registers commands into the command bot.
2012
- *
2013
- * @param commands The commands to register.
2014
- */
2015
- registerSsoCommands(ssoCommands) {
2016
- throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "CommandBot"), ErrorCode.RuntimeNotSupported);
2017
- }
1257
+ // Copyright (c) Microsoft Corporation.
1258
+ /**
1259
+ * Provide utilities for bot conversation, including:
1260
+ * - handle command and response.
1261
+ * - send notification to varies targets (e.g., member, group, channel).
1262
+ *
1263
+ * @remarks
1264
+ * Only work on server side.
1265
+ */
1266
+ class ConversationBot {
1267
+ /**
1268
+ * Create new instance of the `ConversationBot`.
1269
+ *
1270
+ * @param options - The initialize options.
1271
+ *
1272
+ * @remarks
1273
+ * Only work on server side.
1274
+ */
1275
+ constructor(options) {
1276
+ throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "ConversationBot"), ErrorCode.RuntimeNotSupported);
1277
+ }
1278
+ /**
1279
+ * The request handler to integrate with web request.
1280
+ *
1281
+ * @param req - An incoming HTTP [Request](xref:botbuilder.Request).
1282
+ * @param res - The corresponding HTTP [Response](xref:botbuilder.Response).
1283
+ * @param logic - The additional function to handle bot context.
1284
+ *
1285
+ * @remarks
1286
+ * Only work on server side.
1287
+ */
1288
+ requestHandler(req, res, logic) {
1289
+ return Promise.reject(new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "ConversationBot"), ErrorCode.RuntimeNotSupported));
1290
+ }
2018
1291
  }
2019
1292
 
2020
- /**
2021
- * A card action bot to respond to adaptive card universal actions.
2022
- *
2023
- * @remarks
2024
- * Only work on server side.
2025
- */
2026
- /**
2027
- * @deprecated Use `BotBuilderCloudAdapter.CardActionBot` instead.
2028
- */
2029
- class CardActionBot$1 {
2030
- /**
2031
- * Creates a new instance of the `CardActionBot`.
2032
- *
2033
- * @param adapter The bound `BotFrameworkAdapter`.
2034
- * @param options - initialize options
2035
- */
2036
- constructor(adapter, options) {
2037
- throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "CardActionBot"), ErrorCode.RuntimeNotSupported);
2038
- }
2039
- /**
2040
- * Registers a card action handler to the bot.
2041
- * @param actionHandler A card action handler to be registered.
2042
- *
2043
- * @remarks
2044
- * Only work on server side.
2045
- */
2046
- registerHandler(actionHandler) {
2047
- throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "CardActionBot"), ErrorCode.RuntimeNotSupported);
2048
- }
2049
- /**
2050
- * Registers card action handlers to the bot.
2051
- * @param actionHandlers A set of card action handlers to be registered.
2052
- *
2053
- * @remarks
2054
- * Only work on server side.
2055
- */
2056
- registerHandlers(actionHandlers) {
2057
- throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "CardActionBot"), ErrorCode.RuntimeNotSupported);
2058
- }
1293
+ // Copyright (c) Microsoft Corporation.
1294
+ /**
1295
+ * Send a plain text message to a notification target.
1296
+ *
1297
+ * @remarks
1298
+ * Only work on server side.
1299
+ *
1300
+ * @param target - The notification target.
1301
+ * @param text - The plain text message.
1302
+ * @param onError - An optional error handler that can catch exceptions during message sending.
1303
+ *
1304
+ * @returns A `Promise` representing the asynchronous operation.
1305
+ */
1306
+ function sendMessage(target, text, onError) {
1307
+ return Promise.reject(new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "sendMessage"), ErrorCode.RuntimeNotSupported));
2059
1308
  }
2060
-
2061
- // eslint-disable-next-line no-secrets/no-secrets
2062
- /**
2063
- * Users execute query with SSO or Access Token.
2064
- * @deprecated
2065
- * @remarks
2066
- * Only works in in server side.
2067
- */
2068
- function handleMessageExtensionQueryWithToken(context, config, scopes, logic) {
2069
- throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "queryWithToken in message extension"), ErrorCode.RuntimeNotSupported);
2070
- }
2071
- /**
2072
- * Users execute query with SSO or Access Token.
2073
- * @remarks
2074
- * Only works in in server side.
2075
- */
2076
- function handleMessageExtensionQueryWithSSO(context, config, initiateLoginEndpoint, scopes, logic) {
2077
- throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "queryWithToken in message extension"), ErrorCode.RuntimeNotSupported);
1309
+ /**
1310
+ * Send an adaptive card message to a notification target.
1311
+ *
1312
+ * @remarks
1313
+ * Only work on server side.
1314
+ *
1315
+ * @param target - The notification target.
1316
+ * @param card - The adaptive card raw JSON.
1317
+ * @param onError - An optional error handler that can catch exceptions during adaptive card sending.
1318
+ *
1319
+ * @returns A `Promise` representing the asynchronous operation.
1320
+ */
1321
+ function sendAdaptiveCard(target, card, onError) {
1322
+ return Promise.reject(new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "sendAdaptiveCard"), ErrorCode.RuntimeNotSupported));
2078
1323
  }
2079
-
2080
- // Copyright (c) Microsoft Corporation.
2081
- /**
2082
- * Provide utilities for bot conversation, including:
2083
- * - handle command and response.
2084
- * - send notification to varies targets (e.g., member, group, channel).
2085
- *
2086
- * @remarks
2087
- * Only work on server side.
2088
- */
2089
- class ConversationBot {
2090
- /**
2091
- * Create new instance of the `ConversationBot`.
2092
- *
2093
- * @param options - The initialize options.
2094
- *
2095
- * @remarks
2096
- * Only work on server side.
2097
- */
2098
- constructor(options) {
2099
- throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "ConversationBot"), ErrorCode.RuntimeNotSupported);
2100
- }
2101
- /**
2102
- * The request handler to integrate with web request.
2103
- *
2104
- * @param req - An incoming HTTP [Request](xref:botbuilder.Request).
2105
- * @param res - The corresponding HTTP [Response](xref:botbuilder.Response).
2106
- * @param logic - The additional function to handle bot context.
2107
- *
2108
- * @remarks
2109
- * Only work on server side.
2110
- */
2111
- requestHandler(req, res, logic) {
2112
- return Promise.reject(new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "ConversationBot"), ErrorCode.RuntimeNotSupported));
2113
- }
1324
+ /**
1325
+ * A {@link NotificationTarget} that represents a team channel.
1326
+ *
1327
+ * @remarks
1328
+ * Only work on server side.
1329
+ *
1330
+ * It's recommended to get channels from {@link TeamsBotInstallation.channels()}.
1331
+ */
1332
+ class Channel {
1333
+ /**
1334
+ * Constructor.
1335
+ *
1336
+ * @remarks
1337
+ * Only work on server side.
1338
+ *
1339
+ * It's recommended to get channels from {@link TeamsBotInstallation.channels()}, instead of using this constructor.
1340
+ *
1341
+ * @param parent - The parent {@link TeamsBotInstallation} where this channel is created from.
1342
+ * @param info - Detailed channel information.
1343
+ */
1344
+ constructor(parent, info) {
1345
+ /**
1346
+ * Notification target type. For channel it's always "Channel".
1347
+ *
1348
+ * @remarks
1349
+ * Only work on server side.
1350
+ */
1351
+ this.type = NotificationTargetType.Channel;
1352
+ throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "Channel"), ErrorCode.RuntimeNotSupported);
1353
+ }
1354
+ /**
1355
+ * Send a plain text message.
1356
+ *
1357
+ * @remarks
1358
+ * Only work on server side.
1359
+ *
1360
+ * @param text - The plain text message.
1361
+ * @param onError - An optional error handler that can catch exceptions during message sending.
1362
+ *
1363
+ * @returns The response of sending message.
1364
+ */
1365
+ sendMessage(text, onError) {
1366
+ return Promise.reject(new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "Channel"), ErrorCode.RuntimeNotSupported));
1367
+ }
1368
+ /**
1369
+ * Send an adaptive card message.
1370
+ *
1371
+ * @remarks
1372
+ * Only work on server side.
1373
+ *
1374
+ * @param card - The adaptive card raw JSON.
1375
+ * @param onError - An optional error handler that can catch exceptions during adaptive card sending.
1376
+ *
1377
+ * @returns The response of sending adaptive card message.
1378
+ */
1379
+ sendAdaptiveCard(card, onError) {
1380
+ return Promise.reject(new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "Channel"), ErrorCode.RuntimeNotSupported));
1381
+ }
2114
1382
  }
2115
-
2116
- // Copyright (c) Microsoft Corporation.
2117
- /**
2118
- * Send a plain text message to a notification target.
2119
- *
2120
- * @remarks
2121
- * Only work on server side.
2122
- *
2123
- * @param target - The notification target.
2124
- * @param text - The plain text message.
2125
- * @param onError - An optional error handler that can catch exceptions during message sending.
2126
- *
2127
- * @returns A `Promise` representing the asynchronous operation.
2128
- */
2129
- function sendMessage(target, text, onError) {
2130
- return Promise.reject(new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "sendMessage"), ErrorCode.RuntimeNotSupported));
2131
- }
2132
- /**
2133
- * Send an adaptive card message to a notification target.
2134
- *
2135
- * @remarks
2136
- * Only work on server side.
2137
- *
2138
- * @param target - The notification target.
2139
- * @param card - The adaptive card raw JSON.
2140
- * @param onError - An optional error handler that can catch exceptions during adaptive card sending.
2141
- *
2142
- * @returns A `Promise` representing the asynchronous operation.
2143
- */
2144
- function sendAdaptiveCard(target, card, onError) {
2145
- return Promise.reject(new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "sendAdaptiveCard"), ErrorCode.RuntimeNotSupported));
2146
- }
2147
- /**
2148
- * A {@link NotificationTarget} that represents a team channel.
2149
- *
2150
- * @remarks
2151
- * Only work on server side.
2152
- *
2153
- * It's recommended to get channels from {@link TeamsBotInstallation.channels()}.
2154
- */
2155
- class Channel {
2156
- /**
2157
- * Constructor.
2158
- *
2159
- * @remarks
2160
- * Only work on server side.
2161
- *
2162
- * It's recommended to get channels from {@link TeamsBotInstallation.channels()}, instead of using this constructor.
2163
- *
2164
- * @param parent - The parent {@link TeamsBotInstallation} where this channel is created from.
2165
- * @param info - Detailed channel information.
2166
- */
2167
- constructor(parent, info) {
2168
- /**
2169
- * Notification target type. For channel it's always "Channel".
2170
- *
2171
- * @remarks
2172
- * Only work on server side.
2173
- */
2174
- this.type = NotificationTargetType.Channel;
2175
- throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "Channel"), ErrorCode.RuntimeNotSupported);
2176
- }
2177
- /**
2178
- * Send a plain text message.
2179
- *
2180
- * @remarks
2181
- * Only work on server side.
2182
- *
2183
- * @param text - The plain text message.
2184
- * @param onError - An optional error handler that can catch exceptions during message sending.
2185
- *
2186
- * @returns The response of sending message.
2187
- */
2188
- sendMessage(text, onError) {
2189
- return Promise.reject(new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "Channel"), ErrorCode.RuntimeNotSupported));
2190
- }
2191
- /**
2192
- * Send an adaptive card message.
2193
- *
2194
- * @remarks
2195
- * Only work on server side.
2196
- *
2197
- * @param card - The adaptive card raw JSON.
2198
- * @param onError - An optional error handler that can catch exceptions during adaptive card sending.
2199
- *
2200
- * @returns The response of sending adaptive card message.
2201
- */
2202
- sendAdaptiveCard(card, onError) {
2203
- return Promise.reject(new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "Channel"), ErrorCode.RuntimeNotSupported));
2204
- }
2205
- }
2206
- /**
2207
- * A {@link NotificationTarget} that represents a team member.
2208
- *
2209
- * @remarks
2210
- * Only work on server side.
2211
- *
2212
- * It's recommended to get members from {@link TeamsBotInstallation.members()}.
2213
- */
2214
- class Member {
2215
- /**
2216
- * Constructor.
2217
- *
2218
- * @remarks
2219
- * Only work on server side.
2220
- *
2221
- * It's recommended to get members from {@link TeamsBotInstallation.members()}, instead of using this constructor.
2222
- *
2223
- * @param parent - The parent {@link TeamsBotInstallation} where this member is created from.
2224
- * @param account - Detailed member account information.
2225
- */
2226
- constructor(parent, account) {
2227
- /**
2228
- * Notification target type. For member it's always "Person".
2229
- *
2230
- * @remarks
2231
- * Only work on server side.
2232
- */
2233
- this.type = NotificationTargetType.Person;
2234
- throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "Member"), ErrorCode.RuntimeNotSupported);
2235
- }
2236
- /**
2237
- * Send a plain text message.
2238
- *
2239
- * @remarks
2240
- * Only work on server side.
2241
- *
2242
- * @param text - The plain text message.
2243
- * @param onError - An optional error handler that can catch exceptions during message sending.
2244
- *
2245
- * @returns The response of sending message.
2246
- */
2247
- sendMessage(text, onError) {
2248
- return Promise.reject(new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "Member"), ErrorCode.RuntimeNotSupported));
2249
- }
2250
- /**
2251
- * Send an adaptive card message.
2252
- *
2253
- * @remarks
2254
- * Only work on server side.
2255
- *
2256
- * @param card - The adaptive card raw JSON.
2257
- * @param onError - An optional error handler that can catch exceptions during adaptive card sending.
2258
- *
2259
- * @returns The response of sending adaptive card message.
2260
- */
2261
- sendAdaptiveCard(card, onError) {
2262
- return Promise.reject(Promise.reject(new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "Member"), ErrorCode.RuntimeNotSupported)));
2263
- }
2264
- }
2265
- /**
2266
- * A {@link NotificationTarget} that represents a bot installation. Teams Bot could be installed into
2267
- * - Personal chat
2268
- * - Group chat
2269
- * - Team (by default the `General` channel)
2270
- *
2271
- * @remarks
2272
- * Only work on server side.
2273
- *
2274
- * It's recommended to get bot installations from {@link ConversationBot.installations()}.
2275
- */
2276
- class TeamsBotInstallation {
2277
- /**
2278
- * Constructor
2279
- *
2280
- * @remarks
2281
- * Only work on server side.
2282
- *
2283
- * It's recommended to get bot installations from {@link ConversationBot.installations()}, instead of using this constructor.
2284
- *
2285
- * @param adapter - The bound `CloudAdapter`.
2286
- * @param conversationReference - The bound `ConversationReference`.
2287
- */
2288
- constructor(adapter, conversationReference) {
2289
- throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "TeamsBotInstallation"), ErrorCode.RuntimeNotSupported);
2290
- }
2291
- /**
2292
- * Send a plain text message.
2293
- *
2294
- * @remarks
2295
- * Only work on server side.
2296
- *
2297
- * @param text - The plain text message.
2298
- * @param onError - An optional error handler that can catch exceptions during message sending.
2299
- *
2300
- * @returns The response of sending message.
2301
- */
2302
- sendMessage(text, onError) {
2303
- return Promise.reject(new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "TeamsBotInstallation"), ErrorCode.RuntimeNotSupported));
2304
- }
2305
- /**
2306
- * Send an adaptive card message.
2307
- *
2308
- * @remarks
2309
- * Only work on server side.
2310
- *
2311
- * @param card - The adaptive card raw JSON.
2312
- * @param onError - An optional error handler that can catch exceptions during adaptive card sending.
2313
- *
2314
- * @returns The response of sending adaptive card message.
2315
- */
2316
- sendAdaptiveCard(card, onError) {
2317
- return Promise.reject(new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "TeamsBotInstallation"), ErrorCode.RuntimeNotSupported));
2318
- }
2319
- /**
2320
- * Get channels from this bot installation.
2321
- *
2322
- * @remarks
2323
- * Only work on server side.
2324
- *
2325
- * @returns An array of channels if bot is installed into a team, otherwise returns an empty array.
2326
- */
2327
- channels() {
2328
- return Promise.reject(new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "TeamsBotInstallation"), ErrorCode.RuntimeNotSupported));
2329
- }
2330
- /**
2331
- * Get members from this bot installation.
2332
- *
2333
- * @remarks
2334
- * Only work on server side.
2335
- *
2336
- * @returns An array of members from where the bot is installed.
2337
- */
2338
- members() {
2339
- return Promise.reject(new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "TeamsBotInstallation"), ErrorCode.RuntimeNotSupported));
2340
- }
2341
- /**
2342
- * Get team details from this bot installation
2343
- *
2344
- * @returns The team details if bot is installed into a team, otherwise returns undefined.
2345
- */
2346
- getTeamDetails() {
2347
- return Promise.reject(new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "TeamsBotInstallation"), ErrorCode.RuntimeNotSupported));
2348
- }
2349
- }
2350
- /**
2351
- * Provide static utilities for bot notification.
2352
- *
2353
- * @remarks
2354
- * Only work on server side.
2355
- *
2356
- * @example
2357
- * Here's an example on how to send notification via Teams Bot.
2358
- * ```typescript
2359
- * // initialize (it's recommended to be called before handling any bot message)
2360
- * const notificationBot = new NotificationBot(adapter);
2361
- *
2362
- * // get all bot installations and send message
2363
- * for (const target of await notificationBot.installations()) {
2364
- * await target.sendMessage("Hello Notification");
2365
- * }
2366
- *
2367
- * // alternative - send message to all members
2368
- * for (const target of await notificationBot.installations()) {
2369
- * for (const member of await target.members()) {
2370
- * await member.sendMessage("Hello Notification");
2371
- * }
2372
- * }
2373
- * ```
2374
- */
2375
- class NotificationBot {
2376
- /**
2377
- * Constructor of the notification bot.
2378
- *
2379
- * @remarks
2380
- * Only work on server side.
2381
- *
2382
- * To ensure accuracy, it's recommended to initialize before handling any message.
2383
- *
2384
- * @param adapter - The bound `CloudAdapter`
2385
- * @param options - The initialize options
2386
- */
2387
- constructor(adapter, options) {
2388
- throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "NotificationBot"), ErrorCode.RuntimeNotSupported);
2389
- }
2390
- /**
2391
- * Get all targets where the bot is installed.
2392
- *
2393
- * @remarks
2394
- * Only work on server side.
2395
- *
2396
- * The result is retrieving from the persisted storage.
2397
- *
2398
- * @returns An array of {@link TeamsBotInstallation}.
2399
- */
2400
- static installations() {
2401
- return Promise.reject(new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "NotificationBot"), ErrorCode.RuntimeNotSupported));
2402
- }
2403
- /**
2404
- * Return the first {@link Member} where predicate is true, and undefined otherwise.
2405
- *
2406
- * @remarks
2407
- * Only work on server side.
2408
- *
2409
- * @param predicate find calls predicate once for each member of the installation,
2410
- * until it finds one where predicate returns true. If such a member is found,
2411
- * find immediately returns that member. Otherwise, find returns undefined.
2412
- * @param scope the scope to find members from the installations (personal chat, group chat, Teams channel).
2413
- *
2414
- * @returns The first {@link Member} where predicate is true, and undefined otherwise.
2415
- */
2416
- findMember(predicate, scope) {
2417
- return Promise.reject(new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "NotificationBot"), ErrorCode.RuntimeNotSupported));
2418
- }
2419
- /**
2420
- * Return the first {@link Channel} where predicate is true, and undefined otherwise.
2421
- * (Ensure the bot app is installed into the `General` channel, otherwise undefined will be returned.)
2422
- *
2423
- * @remarks
2424
- * Only work on server side.
2425
- *
2426
- * @param predicate - Find calls predicate once for each channel of the installation,
2427
- * until it finds one where predicate returns true. If such a channel is found, find
2428
- * immediately returns that channel. Otherwise, find returns undefined.
2429
- *
2430
- * @returns The first {@link Channel} where predicate is true, and `undefined` otherwise.
2431
- */
2432
- findChannel(predicate) {
2433
- return Promise.reject(new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "NotificationBot"), ErrorCode.RuntimeNotSupported));
2434
- }
2435
- /**
2436
- * Return all {@link Member} where predicate is true, and empty array otherwise.
2437
- *
2438
- * @remarks
2439
- * Only work on server side.
2440
- *
2441
- * @param predicate - Find calls predicate for each member of the installation.
2442
- * @param scope - The scope to find members from the installations.
2443
- * (personal chat, group chat, Teams channel).
2444
- *
2445
- * @returns An array of {@link Member} where predicate is true, and empty array otherwise.
2446
- */
2447
- findAllMembers(predicate, scope) {
2448
- return Promise.reject(new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "NotificationBot"), ErrorCode.RuntimeNotSupported));
2449
- }
2450
- /**
2451
- * Return all {@link Channel} where predicate is true, and empty array otherwise.
2452
- * (Ensure the bot app is installed into the `General` channel, otherwise empty array will be returned.)
2453
- *
2454
- * @remarks
2455
- * Only work on server side.
2456
- *
2457
- * @param predicate - Find calls predicate for each channel of the installation.
2458
- *
2459
- * @returns An array of {@link Channel} where predicate is true, and empty array otherwise.
2460
- */
2461
- findAllChannels(predicate) {
2462
- return Promise.reject(new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "NotificationBot"), ErrorCode.RuntimeNotSupported));
2463
- }
2464
- }
2465
- /**
2466
- * The search scope when calling {@link NotificationBot.findMember} and {@link NotificationBot.findAllMembers}.
2467
- * The search scope is a flagged enum and it can be combined with `|`.
2468
- * For example, to search from personal chat and group chat, use `SearchScope.Person | SearchScope.Group`.
2469
- */
2470
- var SearchScope;
2471
- (function (SearchScope) {
2472
- /**
2473
- * Search members from the installations in personal chat only.
2474
- */
2475
- SearchScope[SearchScope["Person"] = 1] = "Person";
2476
- /**
2477
- * Search members from the installations in group chat only.
2478
- */
2479
- SearchScope[SearchScope["Group"] = 2] = "Group";
2480
- /**
2481
- * Search members from the installations in Teams channel only.
2482
- */
2483
- SearchScope[SearchScope["Channel"] = 4] = "Channel";
2484
- /**
2485
- * Search members from all installations including personal chat, group chat and Teams channel.
2486
- */
2487
- SearchScope[SearchScope["All"] = 7] = "All";
1383
+ /**
1384
+ * A {@link NotificationTarget} that represents a team member.
1385
+ *
1386
+ * @remarks
1387
+ * Only work on server side.
1388
+ *
1389
+ * It's recommended to get members from {@link TeamsBotInstallation.members()}.
1390
+ */
1391
+ class Member {
1392
+ /**
1393
+ * Constructor.
1394
+ *
1395
+ * @remarks
1396
+ * Only work on server side.
1397
+ *
1398
+ * It's recommended to get members from {@link TeamsBotInstallation.members()}, instead of using this constructor.
1399
+ *
1400
+ * @param parent - The parent {@link TeamsBotInstallation} where this member is created from.
1401
+ * @param account - Detailed member account information.
1402
+ */
1403
+ constructor(parent, account) {
1404
+ /**
1405
+ * Notification target type. For member it's always "Person".
1406
+ *
1407
+ * @remarks
1408
+ * Only work on server side.
1409
+ */
1410
+ this.type = NotificationTargetType.Person;
1411
+ throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "Member"), ErrorCode.RuntimeNotSupported);
1412
+ }
1413
+ /**
1414
+ * Send a plain text message.
1415
+ *
1416
+ * @remarks
1417
+ * Only work on server side.
1418
+ *
1419
+ * @param text - The plain text message.
1420
+ * @param onError - An optional error handler that can catch exceptions during message sending.
1421
+ *
1422
+ * @returns The response of sending message.
1423
+ */
1424
+ sendMessage(text, onError) {
1425
+ return Promise.reject(new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "Member"), ErrorCode.RuntimeNotSupported));
1426
+ }
1427
+ /**
1428
+ * Send an adaptive card message.
1429
+ *
1430
+ * @remarks
1431
+ * Only work on server side.
1432
+ *
1433
+ * @param card - The adaptive card raw JSON.
1434
+ * @param onError - An optional error handler that can catch exceptions during adaptive card sending.
1435
+ *
1436
+ * @returns The response of sending adaptive card message.
1437
+ */
1438
+ sendAdaptiveCard(card, onError) {
1439
+ return Promise.reject(Promise.reject(new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "Member"), ErrorCode.RuntimeNotSupported)));
1440
+ }
1441
+ }
1442
+ /**
1443
+ * A {@link NotificationTarget} that represents a bot installation. Teams Bot could be installed into
1444
+ * - Personal chat
1445
+ * - Group chat
1446
+ * - Team (by default the `General` channel)
1447
+ *
1448
+ * @remarks
1449
+ * Only work on server side.
1450
+ *
1451
+ * It's recommended to get bot installations from {@link ConversationBot.installations()}.
1452
+ */
1453
+ class TeamsBotInstallation {
1454
+ /**
1455
+ * Constructor
1456
+ *
1457
+ * @remarks
1458
+ * Only work on server side.
1459
+ *
1460
+ * It's recommended to get bot installations from {@link ConversationBot.installations()}, instead of using this constructor.
1461
+ *
1462
+ * @param adapter - The bound `CloudAdapter`.
1463
+ * @param conversationReference - The bound `ConversationReference`.
1464
+ */
1465
+ constructor(adapter, conversationReference) {
1466
+ throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "TeamsBotInstallation"), ErrorCode.RuntimeNotSupported);
1467
+ }
1468
+ /**
1469
+ * Send a plain text message.
1470
+ *
1471
+ * @remarks
1472
+ * Only work on server side.
1473
+ *
1474
+ * @param text - The plain text message.
1475
+ * @param onError - An optional error handler that can catch exceptions during message sending.
1476
+ *
1477
+ * @returns The response of sending message.
1478
+ */
1479
+ sendMessage(text, onError) {
1480
+ return Promise.reject(new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "TeamsBotInstallation"), ErrorCode.RuntimeNotSupported));
1481
+ }
1482
+ /**
1483
+ * Send an adaptive card message.
1484
+ *
1485
+ * @remarks
1486
+ * Only work on server side.
1487
+ *
1488
+ * @param card - The adaptive card raw JSON.
1489
+ * @param onError - An optional error handler that can catch exceptions during adaptive card sending.
1490
+ *
1491
+ * @returns The response of sending adaptive card message.
1492
+ */
1493
+ sendAdaptiveCard(card, onError) {
1494
+ return Promise.reject(new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "TeamsBotInstallation"), ErrorCode.RuntimeNotSupported));
1495
+ }
1496
+ /**
1497
+ * Get channels from this bot installation.
1498
+ *
1499
+ * @remarks
1500
+ * Only work on server side.
1501
+ *
1502
+ * @returns An array of channels if bot is installed into a team, otherwise returns an empty array.
1503
+ */
1504
+ channels() {
1505
+ return Promise.reject(new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "TeamsBotInstallation"), ErrorCode.RuntimeNotSupported));
1506
+ }
1507
+ /**
1508
+ * Get members from this bot installation.
1509
+ *
1510
+ * @remarks
1511
+ * Only work on server side.
1512
+ *
1513
+ * @returns An array of members from where the bot is installed.
1514
+ */
1515
+ members() {
1516
+ return Promise.reject(new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "TeamsBotInstallation"), ErrorCode.RuntimeNotSupported));
1517
+ }
1518
+ /**
1519
+ * Get team details from this bot installation
1520
+ *
1521
+ * @returns The team details if bot is installed into a team, otherwise returns undefined.
1522
+ */
1523
+ getTeamDetails() {
1524
+ return Promise.reject(new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "TeamsBotInstallation"), ErrorCode.RuntimeNotSupported));
1525
+ }
1526
+ }
1527
+ /**
1528
+ * Provide static utilities for bot notification.
1529
+ *
1530
+ * @remarks
1531
+ * Only work on server side.
1532
+ *
1533
+ * @example
1534
+ * Here's an example on how to send notification via Teams Bot.
1535
+ * ```typescript
1536
+ * // initialize (it's recommended to be called before handling any bot message)
1537
+ * const notificationBot = new NotificationBot(adapter);
1538
+ *
1539
+ * // get all bot installations and send message
1540
+ * for (const target of await notificationBot.installations()) {
1541
+ * await target.sendMessage("Hello Notification");
1542
+ * }
1543
+ *
1544
+ * // alternative - send message to all members
1545
+ * for (const target of await notificationBot.installations()) {
1546
+ * for (const member of await target.members()) {
1547
+ * await member.sendMessage("Hello Notification");
1548
+ * }
1549
+ * }
1550
+ * ```
1551
+ */
1552
+ class NotificationBot {
1553
+ /**
1554
+ * Constructor of the notification bot.
1555
+ *
1556
+ * @remarks
1557
+ * Only work on server side.
1558
+ *
1559
+ * To ensure accuracy, it's recommended to initialize before handling any message.
1560
+ *
1561
+ * @param adapter - The bound `CloudAdapter`
1562
+ * @param options - The initialize options
1563
+ */
1564
+ constructor(adapter, options) {
1565
+ throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "NotificationBot"), ErrorCode.RuntimeNotSupported);
1566
+ }
1567
+ /**
1568
+ * Get all targets where the bot is installed.
1569
+ *
1570
+ * @remarks
1571
+ * Only work on server side.
1572
+ *
1573
+ * The result is retrieving from the persisted storage.
1574
+ *
1575
+ * @returns An array of {@link TeamsBotInstallation}.
1576
+ */
1577
+ static installations() {
1578
+ return Promise.reject(new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "NotificationBot"), ErrorCode.RuntimeNotSupported));
1579
+ }
1580
+ /**
1581
+ * Return the first {@link Member} where predicate is true, and undefined otherwise.
1582
+ *
1583
+ * @remarks
1584
+ * Only work on server side.
1585
+ *
1586
+ * @param predicate find calls predicate once for each member of the installation,
1587
+ * until it finds one where predicate returns true. If such a member is found,
1588
+ * find immediately returns that member. Otherwise, find returns undefined.
1589
+ * @param scope the scope to find members from the installations (personal chat, group chat, Teams channel).
1590
+ *
1591
+ * @returns The first {@link Member} where predicate is true, and undefined otherwise.
1592
+ */
1593
+ findMember(predicate, scope) {
1594
+ return Promise.reject(new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "NotificationBot"), ErrorCode.RuntimeNotSupported));
1595
+ }
1596
+ /**
1597
+ * Return the first {@link Channel} where predicate is true, and undefined otherwise.
1598
+ * (Ensure the bot app is installed into the `General` channel, otherwise undefined will be returned.)
1599
+ *
1600
+ * @remarks
1601
+ * Only work on server side.
1602
+ *
1603
+ * @param predicate - Find calls predicate once for each channel of the installation,
1604
+ * until it finds one where predicate returns true. If such a channel is found, find
1605
+ * immediately returns that channel. Otherwise, find returns undefined.
1606
+ *
1607
+ * @returns The first {@link Channel} where predicate is true, and `undefined` otherwise.
1608
+ */
1609
+ findChannel(predicate) {
1610
+ return Promise.reject(new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "NotificationBot"), ErrorCode.RuntimeNotSupported));
1611
+ }
1612
+ /**
1613
+ * Return all {@link Member} where predicate is true, and empty array otherwise.
1614
+ *
1615
+ * @remarks
1616
+ * Only work on server side.
1617
+ *
1618
+ * @param predicate - Find calls predicate for each member of the installation.
1619
+ * @param scope - The scope to find members from the installations.
1620
+ * (personal chat, group chat, Teams channel).
1621
+ *
1622
+ * @returns An array of {@link Member} where predicate is true, and empty array otherwise.
1623
+ */
1624
+ findAllMembers(predicate, scope) {
1625
+ return Promise.reject(new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "NotificationBot"), ErrorCode.RuntimeNotSupported));
1626
+ }
1627
+ /**
1628
+ * Return all {@link Channel} where predicate is true, and empty array otherwise.
1629
+ * (Ensure the bot app is installed into the `General` channel, otherwise empty array will be returned.)
1630
+ *
1631
+ * @remarks
1632
+ * Only work on server side.
1633
+ *
1634
+ * @param predicate - Find calls predicate for each channel of the installation.
1635
+ *
1636
+ * @returns An array of {@link Channel} where predicate is true, and empty array otherwise.
1637
+ */
1638
+ findAllChannels(predicate) {
1639
+ return Promise.reject(new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "NotificationBot"), ErrorCode.RuntimeNotSupported));
1640
+ }
1641
+ }
1642
+ /**
1643
+ * The search scope when calling {@link NotificationBot.findMember} and {@link NotificationBot.findAllMembers}.
1644
+ * The search scope is a flagged enum and it can be combined with `|`.
1645
+ * For example, to search from personal chat and group chat, use `SearchScope.Person | SearchScope.Group`.
1646
+ */
1647
+ var SearchScope;
1648
+ (function (SearchScope) {
1649
+ /**
1650
+ * Search members from the installations in personal chat only.
1651
+ */
1652
+ SearchScope[SearchScope["Person"] = 1] = "Person";
1653
+ /**
1654
+ * Search members from the installations in group chat only.
1655
+ */
1656
+ SearchScope[SearchScope["Group"] = 2] = "Group";
1657
+ /**
1658
+ * Search members from the installations in Teams channel only.
1659
+ */
1660
+ SearchScope[SearchScope["Channel"] = 4] = "Channel";
1661
+ /**
1662
+ * Search members from all installations including personal chat, group chat and Teams channel.
1663
+ */
1664
+ SearchScope[SearchScope["All"] = 7] = "All";
2488
1665
  })(SearchScope || (SearchScope = {}));
2489
1666
 
2490
- // Copyright (c) Microsoft Corporation.
2491
- /**
2492
- * A command bot for receiving commands and sending responses in Teams.
2493
- *
2494
- * @remarks
2495
- * Only work on server side.
2496
- */
2497
- class CommandBot {
2498
- /**
2499
- * Create a new instance of the `CommandBot`.
2500
- *
2501
- * @param adapter - The bound `CloudAdapter`.
2502
- * @param commands - The commands to be registered with the command bot. Each command should implement the interface {@link TeamsFxBotCommandHandler} so that it can be correctly handled by this command bot.
2503
- */
2504
- constructor(adapter, commands) {
2505
- throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "CommandBot"), ErrorCode.RuntimeNotSupported);
2506
- }
2507
- /**
2508
- * Register a command into the command bot.
2509
- *
2510
- * @param command - The command to be registered.
2511
- *
2512
- * @remarks
2513
- * Only work on server side.
2514
- */
2515
- registerCommand(command) {
2516
- throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "CommandBot"), ErrorCode.RuntimeNotSupported);
2517
- }
2518
- /**
2519
- * Register commands into the command bot.
2520
- *
2521
- * @param commands - The commands to be registered.
2522
- *
2523
- * @remarks
2524
- * Only work on server side.
2525
- */
2526
- registerCommands(commands) {
2527
- throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "CommandBot"), ErrorCode.RuntimeNotSupported);
2528
- }
2529
- /**
2530
- * Register a sso command into the command bot.
2531
- *
2532
- * @param ssoCommand - The sso command to be registered.
2533
- */
2534
- registerSsoCommand(ssoCommand) {
2535
- throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "CommandBot"), ErrorCode.RuntimeNotSupported);
2536
- }
2537
- /**
2538
- * Register sso commands into the command bot.
2539
- *
2540
- * @param ssoCommands - The sso commands to be registered.
2541
- */
2542
- registerSsoCommands(ssoCommands) {
2543
- throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "CommandBot"), ErrorCode.RuntimeNotSupported);
2544
- }
1667
+ // Copyright (c) Microsoft Corporation.
1668
+ /**
1669
+ * A command bot for receiving commands and sending responses in Teams.
1670
+ *
1671
+ * @remarks
1672
+ * Only work on server side.
1673
+ */
1674
+ class CommandBot {
1675
+ /**
1676
+ * Create a new instance of the `CommandBot`.
1677
+ *
1678
+ * @param adapter - The bound `CloudAdapter`.
1679
+ * @param commands - The commands to be registered with the command bot. Each command should implement the interface {@link TeamsFxBotCommandHandler} so that it can be correctly handled by this command bot.
1680
+ */
1681
+ constructor(adapter, commands) {
1682
+ throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "CommandBot"), ErrorCode.RuntimeNotSupported);
1683
+ }
1684
+ /**
1685
+ * Register a command into the command bot.
1686
+ *
1687
+ * @param command - The command to be registered.
1688
+ *
1689
+ * @remarks
1690
+ * Only work on server side.
1691
+ */
1692
+ registerCommand(command) {
1693
+ throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "CommandBot"), ErrorCode.RuntimeNotSupported);
1694
+ }
1695
+ /**
1696
+ * Register commands into the command bot.
1697
+ *
1698
+ * @param commands - The commands to be registered.
1699
+ *
1700
+ * @remarks
1701
+ * Only work on server side.
1702
+ */
1703
+ registerCommands(commands) {
1704
+ throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "CommandBot"), ErrorCode.RuntimeNotSupported);
1705
+ }
1706
+ /**
1707
+ * Register a sso command into the command bot.
1708
+ *
1709
+ * @param ssoCommand - The sso command to be registered.
1710
+ */
1711
+ registerSsoCommand(ssoCommand) {
1712
+ throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "CommandBot"), ErrorCode.RuntimeNotSupported);
1713
+ }
1714
+ /**
1715
+ * Register sso commands into the command bot.
1716
+ *
1717
+ * @param ssoCommands - The sso commands to be registered.
1718
+ */
1719
+ registerSsoCommands(ssoCommands) {
1720
+ throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "CommandBot"), ErrorCode.RuntimeNotSupported);
1721
+ }
2545
1722
  }
2546
1723
 
2547
- /**
2548
- * A card action bot to respond to adaptive card universal actions.
2549
- *
2550
- * @remarks
2551
- * Only work on server side.
2552
- */
2553
- class CardActionBot {
2554
- /**
2555
- * Create a new instance of the `CardActionBot`.
2556
- *
2557
- * @param adapter - The bound `CloudAdapter`.
2558
- * @param options - The initialize options.
2559
- */
2560
- constructor(adapter, options) {
2561
- throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "CardActionBot"), ErrorCode.RuntimeNotSupported);
2562
- }
2563
- /**
2564
- * Register a card action handler to the bot.
2565
- *
2566
- * @param actionHandler - A card action handler to be registered.
2567
- *
2568
- * @remarks
2569
- * Only work on server side.
2570
- */
2571
- registerHandler(actionHandler) {
2572
- return Promise.reject(new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "CardActionBot"), ErrorCode.RuntimeNotSupported));
2573
- }
2574
- /**
2575
- * Register card action handlers to the bot.
2576
- *
2577
- * @param actionHandlers - A set of card action handlers to be registered.
2578
- *
2579
- * @remarks
2580
- * Only work on server side.
2581
- */
2582
- registerHandlers(actionHandlers) {
2583
- return Promise.reject(new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "CardActionBot"), ErrorCode.RuntimeNotSupported));
2584
- }
1724
+ /**
1725
+ * A card action bot to respond to adaptive card universal actions.
1726
+ *
1727
+ * @remarks
1728
+ * Only work on server side.
1729
+ */
1730
+ class CardActionBot {
1731
+ /**
1732
+ * Create a new instance of the `CardActionBot`.
1733
+ *
1734
+ * @param adapter - The bound `CloudAdapter`.
1735
+ * @param options - The initialize options.
1736
+ */
1737
+ constructor(adapter, options) {
1738
+ throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "CardActionBot"), ErrorCode.RuntimeNotSupported);
1739
+ }
1740
+ /**
1741
+ * Register a card action handler to the bot.
1742
+ *
1743
+ * @param actionHandler - A card action handler to be registered.
1744
+ *
1745
+ * @remarks
1746
+ * Only work on server side.
1747
+ */
1748
+ registerHandler(actionHandler) {
1749
+ return Promise.reject(new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "CardActionBot"), ErrorCode.RuntimeNotSupported));
1750
+ }
1751
+ /**
1752
+ * Register card action handlers to the bot.
1753
+ *
1754
+ * @param actionHandlers - A set of card action handlers to be registered.
1755
+ *
1756
+ * @remarks
1757
+ * Only work on server side.
1758
+ */
1759
+ registerHandlers(actionHandlers) {
1760
+ return Promise.reject(new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "CardActionBot"), ErrorCode.RuntimeNotSupported));
1761
+ }
2585
1762
  }
2586
1763
 
2587
1764
  var conversationWithCloudAdapter_browser = /*#__PURE__*/Object.freeze({
@@ -2598,5 +1775,5 @@ var conversationWithCloudAdapter_browser = /*#__PURE__*/Object.freeze({
2598
1775
  CardActionBot: CardActionBot
2599
1776
  });
2600
1777
 
2601
- export { AdaptiveCardResponse, ApiKeyLocation, ApiKeyProvider, AppCredential, BasicAuthProvider, BearerTokenAuthProvider, conversationWithCloudAdapter_browser as BotBuilderCloudAdapter, BotSsoExecutionDialog, CardActionBot$1 as CardActionBot, CertificateAuthProvider, Channel$1 as Channel, CommandBot$1 as CommandBot, ConversationBot$1 as ConversationBot, ErrorCode, ErrorWithCode, IdentityType, InvokeResponseErrorCode, LogLevel, Member$1 as Member, MsGraphAuthProvider, NotificationBot$1 as NotificationBot, NotificationTargetType, OnBehalfOfUserCredential, TeamsBotInstallation$1 as TeamsBotInstallation, TeamsBotSsoPrompt, TeamsFx, TeamsUserCredential, createApiClient, createMicrosoftGraphClient, createMicrosoftGraphClientWithCredential, createPemCertOption, createPfxCertOption, getLogLevel, getTediousConnectionConfig, handleMessageExtensionQueryWithSSO, handleMessageExtensionQueryWithToken, sendAdaptiveCard$1 as sendAdaptiveCard, sendMessage$1 as sendMessage, setLogFunction, setLogLevel, setLogger };
1778
+ export { AdaptiveCardResponse, ApiKeyLocation, ApiKeyProvider, AppCredential, BasicAuthProvider, BearerTokenAuthProvider, conversationWithCloudAdapter_browser as BotBuilderCloudAdapter, BotSsoExecutionDialog, CertificateAuthProvider, ErrorCode, ErrorWithCode, InvokeResponseErrorCode, LogLevel, NotificationTargetType, OnBehalfOfUserCredential, TeamsBotSsoPrompt, TeamsUserCredential, createApiClient, createPemCertOption, createPfxCertOption, getLogLevel, handleMessageExtensionQueryWithSSO, setLogFunction, setLogLevel, setLogger };
2602
1779
  //# sourceMappingURL=index.esm5.js.map