@microsoft/teamsfx 0.6.2-alpha.eb3c5cc12.0 → 0.6.3-alpha.266fa3b9f.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.
@@ -11,10 +11,35 @@ var identity = require('@azure/identity');
11
11
  var botbuilder = require('botbuilder');
12
12
  var botbuilderDialogs = require('botbuilder-dialogs');
13
13
  var uuid = require('uuid');
14
+ var axios = require('axios');
15
+ var https = require('https');
16
+ var path = require('path');
17
+ var fs = require('fs');
14
18
 
15
19
  function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
16
20
 
21
+ function _interopNamespace(e) {
22
+ if (e && e.__esModule) return e;
23
+ var n = Object.create(null);
24
+ if (e) {
25
+ Object.keys(e).forEach(function (k) {
26
+ if (k !== 'default') {
27
+ var d = Object.getOwnPropertyDescriptor(e, k);
28
+ Object.defineProperty(n, k, d.get ? d : {
29
+ enumerable: true,
30
+ get: function () { return e[k]; }
31
+ });
32
+ }
33
+ });
34
+ }
35
+ n["default"] = e;
36
+ return Object.freeze(n);
37
+ }
38
+
17
39
  var jwt_decode__default = /*#__PURE__*/_interopDefaultLegacy(jwt_decode);
40
+ var axios__default = /*#__PURE__*/_interopDefaultLegacy(axios);
41
+ var path__namespace = /*#__PURE__*/_interopNamespace(path);
42
+ var fs__namespace = /*#__PURE__*/_interopNamespace(fs);
18
43
 
19
44
  // Copyright (c) Microsoft Corporation.
20
45
  // Licensed under the MIT license.
@@ -76,6 +101,10 @@ exports.ErrorCode = void 0;
76
101
  * Identity type error.
77
102
  */
78
103
  ErrorCode["IdentityTypeNotSupported"] = "IdentityTypeNotSupported";
104
+ /**
105
+ * Authentication info already exists error.
106
+ */
107
+ ErrorCode["AuthorizationInfoAlreadyExists"] = "AuthorizationInfoAlreadyExists";
79
108
  })(exports.ErrorCode || (exports.ErrorCode = {}));
80
109
  /**
81
110
  * @internal
@@ -97,6 +126,14 @@ ErrorMessage.FailToAcquireTokenOnBehalfOfUser = "Failed to acquire access token
97
126
  ErrorMessage.OnlyMSTeamsChannelSupported = "{0} is only supported in MS Teams Channel";
98
127
  // IdentityTypeNotSupported Error
99
128
  ErrorMessage.IdentityTypeNotSupported = "{0} identity is not supported in {1}";
129
+ // AuthorizationInfoError
130
+ ErrorMessage.AuthorizationHeaderAlreadyExists = "Authorization header already exists!";
131
+ ErrorMessage.BasicCredentialAlreadyExists = "Basic credential already exists!";
132
+ // InvalidParameter Error
133
+ ErrorMessage.EmptyParameter = "Parameter {0} is empty";
134
+ ErrorMessage.DuplicateHttpsOptionProperty = "Axios HTTPS agent already defined value for property {0}";
135
+ ErrorMessage.DuplicateApiKeyInHeader = "The request already defined api key in request header with name {0}.";
136
+ ErrorMessage.DuplicateApiKeyInQueryParam = "The request already defined api key in query parameter with name {0}.";
100
137
  /**
101
138
  * Error class with code and message thrown by the SDK.
102
139
  *
@@ -1417,6 +1454,332 @@ class TeamsBotSsoPrompt extends botbuilderDialogs.Dialog {
1417
1454
  }
1418
1455
 
1419
1456
  // Copyright (c) Microsoft Corporation.
1457
+ /**
1458
+ * Initializes new Axios instance with specific auth provider
1459
+ *
1460
+ * @param apiEndpoint - Base url of the API
1461
+ * @param authProvider - Auth provider that injects authentication info to each request
1462
+ * @returns axios instance configured with specfic auth provider
1463
+ *
1464
+ * @example
1465
+ * ```typescript
1466
+ * const client = createApiClient("https://my-api-endpoint-base-url", new BasicAuthProvider("xxx","xxx"));
1467
+ * ```
1468
+ *
1469
+ * @beta
1470
+ */
1471
+ function createApiClient(apiEndpoint, authProvider) {
1472
+ // Add a request interceptor
1473
+ const instance = axios__default["default"].create({
1474
+ baseURL: apiEndpoint,
1475
+ });
1476
+ instance.interceptors.request.use(function (config) {
1477
+ return tslib.__awaiter(this, void 0, void 0, function* () {
1478
+ return yield authProvider.AddAuthenticationInfo(config);
1479
+ });
1480
+ });
1481
+ return instance;
1482
+ }
1483
+
1484
+ // Copyright (c) Microsoft Corporation.
1485
+ /**
1486
+ * Provider that handles Bearer Token authentication
1487
+ *
1488
+ * @beta
1489
+ */
1490
+ class BearerTokenAuthProvider {
1491
+ /**
1492
+ * @param { () => Promise<string> } getToken - Function that returns the content of bearer token used in http request
1493
+ *
1494
+ * @beta
1495
+ */
1496
+ constructor(getToken) {
1497
+ this.getToken = getToken;
1498
+ }
1499
+ /**
1500
+ * Adds authentication info to http requests
1501
+ *
1502
+ * @param { AxiosRequestConfig } config - Contains all the request information and can be updated to include extra authentication info.
1503
+ * Refer https://axios-http.com/docs/req_config for detailed document.
1504
+ *
1505
+ * @returns Updated axios request config.
1506
+ *
1507
+ * @throws {@link ErrorCode|AuthorizationInfoAlreadyExists} - when Authorization header already exists in request configuration.
1508
+ *
1509
+ * @beta
1510
+ */
1511
+ AddAuthenticationInfo(config) {
1512
+ return tslib.__awaiter(this, void 0, void 0, function* () {
1513
+ const token = yield this.getToken();
1514
+ if (!config.headers) {
1515
+ config.headers = {};
1516
+ }
1517
+ if (config.headers["Authorization"]) {
1518
+ throw new ErrorWithCode(ErrorMessage.AuthorizationHeaderAlreadyExists, exports.ErrorCode.AuthorizationInfoAlreadyExists);
1519
+ }
1520
+ config.headers["Authorization"] = `Bearer ${token}`;
1521
+ return config;
1522
+ });
1523
+ }
1524
+ }
1525
+
1526
+ // Copyright (c) Microsoft Corporation.
1527
+ /**
1528
+ * Provider that handles Basic authentication
1529
+ *
1530
+ * @beta
1531
+ */
1532
+ class BasicAuthProvider {
1533
+ /**
1534
+ *
1535
+ * @param { string } userName - Username used in basic auth
1536
+ * @param { string } password - Password used in basic auth
1537
+ *
1538
+ * @throws {@link ErrorCode|InvalidParameter} - when username or password is empty.
1539
+ *
1540
+ * @beta
1541
+ */
1542
+ constructor(userName, password) {
1543
+ if (!userName) {
1544
+ throw new ErrorWithCode(formatString(ErrorMessage.EmptyParameter, "username"), exports.ErrorCode.InvalidParameter);
1545
+ }
1546
+ if (!password) {
1547
+ throw new ErrorWithCode(formatString(ErrorMessage.EmptyParameter, "password"), exports.ErrorCode.InvalidParameter);
1548
+ }
1549
+ this.userName = userName;
1550
+ this.password = password;
1551
+ }
1552
+ /**
1553
+ * Adds authentication info to http requests
1554
+ *
1555
+ * @param { AxiosRequestConfig } config - Contains all the request information and can be updated to include extra authentication info.
1556
+ * Refer https://axios-http.com/docs/req_config for detailed document.
1557
+ *
1558
+ * @returns Updated axios request config.
1559
+ *
1560
+ * @throws {@link ErrorCode|AuthorizationInfoAlreadyExists} - when Authorization header or auth property already exists in request configuration.
1561
+ *
1562
+ * @beta
1563
+ */
1564
+ AddAuthenticationInfo(config) {
1565
+ return tslib.__awaiter(this, void 0, void 0, function* () {
1566
+ if (config.headers && config.headers["Authorization"]) {
1567
+ throw new ErrorWithCode(ErrorMessage.AuthorizationHeaderAlreadyExists, exports.ErrorCode.AuthorizationInfoAlreadyExists);
1568
+ }
1569
+ if (config.auth) {
1570
+ throw new ErrorWithCode(ErrorMessage.BasicCredentialAlreadyExists, exports.ErrorCode.AuthorizationInfoAlreadyExists);
1571
+ }
1572
+ config.auth = {
1573
+ username: this.userName,
1574
+ password: this.password,
1575
+ };
1576
+ return config;
1577
+ });
1578
+ }
1579
+ }
1580
+
1581
+ // Copyright (c) Microsoft Corporation.
1582
+ /**
1583
+ * Provider that handles API Key authentication
1584
+ *
1585
+ * @beta
1586
+ */
1587
+ class ApiKeyProvider {
1588
+ /**
1589
+ *
1590
+ * @param { string } keyName - The name of request header or query parameter that specifies API Key
1591
+ * @param { string } keyValue - The value of API Key
1592
+ * @param { ApiKeyLocation } keyLocation - The location of API Key: request header or query parameter.
1593
+ *
1594
+ * @throws {@link ErrorCode|InvalidParameter} - when key name or key value is empty.
1595
+ *
1596
+ * @beta
1597
+ */
1598
+ constructor(keyName, keyValue, keyLocation) {
1599
+ if (!keyName) {
1600
+ throw new ErrorWithCode(formatString(ErrorMessage.EmptyParameter, "keyName"), exports.ErrorCode.InvalidParameter);
1601
+ }
1602
+ if (!keyValue) {
1603
+ throw new ErrorWithCode(formatString(ErrorMessage.EmptyParameter, "keyVaule"), exports.ErrorCode.InvalidParameter);
1604
+ }
1605
+ this.keyName = keyName;
1606
+ this.keyValue = keyValue;
1607
+ this.keyLocation = keyLocation;
1608
+ }
1609
+ /**
1610
+ * Adds authentication info to http requests
1611
+ *
1612
+ * @param { AxiosRequestConfig } config - Contains all the request information and can be updated to include extra authentication info.
1613
+ * Refer https://axios-http.com/docs/req_config for detailed document.
1614
+ *
1615
+ * @returns Updated axios request config.
1616
+ *
1617
+ * @throws {@link ErrorCode|AuthorizationInfoAlreadyExists} - when API key already exists in request header or url query parameter.
1618
+ *
1619
+ * @beta
1620
+ */
1621
+ AddAuthenticationInfo(config) {
1622
+ return tslib.__awaiter(this, void 0, void 0, function* () {
1623
+ switch (this.keyLocation) {
1624
+ case exports.ApiKeyLocation.Header:
1625
+ if (!config.headers) {
1626
+ config.headers = {};
1627
+ }
1628
+ if (config.headers[this.keyName]) {
1629
+ throw new ErrorWithCode(formatString(ErrorMessage.DuplicateApiKeyInHeader, this.keyName), exports.ErrorCode.AuthorizationInfoAlreadyExists);
1630
+ }
1631
+ config.headers[this.keyName] = this.keyValue;
1632
+ break;
1633
+ case exports.ApiKeyLocation.QueryParams:
1634
+ if (!config.params) {
1635
+ config.params = {};
1636
+ }
1637
+ const url = new URL(config.url, config.baseURL);
1638
+ if (config.params[this.keyName] || url.searchParams.has(this.keyName)) {
1639
+ throw new ErrorWithCode(formatString(ErrorMessage.DuplicateApiKeyInQueryParam, this.keyName), exports.ErrorCode.AuthorizationInfoAlreadyExists);
1640
+ }
1641
+ config.params[this.keyName] = this.keyValue;
1642
+ break;
1643
+ }
1644
+ return config;
1645
+ });
1646
+ }
1647
+ }
1648
+ /**
1649
+ * Define available location for API Key location
1650
+ *
1651
+ * @beta
1652
+ */
1653
+ exports.ApiKeyLocation = void 0;
1654
+ (function (ApiKeyLocation) {
1655
+ /**
1656
+ * The API Key is placed in request header
1657
+ */
1658
+ ApiKeyLocation[ApiKeyLocation["Header"] = 0] = "Header";
1659
+ /**
1660
+ * The API Key is placed in query parameter
1661
+ */
1662
+ ApiKeyLocation[ApiKeyLocation["QueryParams"] = 1] = "QueryParams";
1663
+ })(exports.ApiKeyLocation || (exports.ApiKeyLocation = {}));
1664
+
1665
+ // Copyright (c) Microsoft Corporation.
1666
+ /**
1667
+ * Provider that handles Certificate authentication
1668
+ *
1669
+ * @beta
1670
+ */
1671
+ class CertificateAuthProvider {
1672
+ /**
1673
+ *
1674
+ * @param { SecureContextOptions } certOption - information about the cert used in http requests
1675
+ *
1676
+ * @throws {@link ErrorCode|InvalidParameter} - when cert option is empty.
1677
+ *
1678
+ * @beta
1679
+ */
1680
+ constructor(certOption) {
1681
+ if (certOption && Object.keys(certOption).length !== 0) {
1682
+ this.certOption = certOption;
1683
+ }
1684
+ else {
1685
+ throw new ErrorWithCode(formatString(ErrorMessage.EmptyParameter, "certOption"), exports.ErrorCode.InvalidParameter);
1686
+ }
1687
+ }
1688
+ /**
1689
+ * Adds authentication info to http requests.
1690
+ *
1691
+ * @param { AxiosRequestConfig } config - Contains all the request information and can be updated to include extra authentication info.
1692
+ * Refer https://axios-http.com/docs/req_config for detailed document.
1693
+ *
1694
+ * @returns Updated axios request config.
1695
+ *
1696
+ * @throws {@link ErrorCode|InvalidParameter} - when custom httpsAgent in the request has duplicate properties with certOption provided in constructor.
1697
+ *
1698
+ * @beta
1699
+ */
1700
+ AddAuthenticationInfo(config) {
1701
+ return tslib.__awaiter(this, void 0, void 0, function* () {
1702
+ if (!config.httpsAgent) {
1703
+ config.httpsAgent = new https.Agent(this.certOption);
1704
+ }
1705
+ else {
1706
+ const existingProperties = new Set(Object.keys(config.httpsAgent.options));
1707
+ for (const property of Object.keys(this.certOption)) {
1708
+ if (existingProperties.has(property)) {
1709
+ throw new ErrorWithCode(formatString(ErrorMessage.DuplicateHttpsOptionProperty, property), exports.ErrorCode.InvalidParameter);
1710
+ }
1711
+ }
1712
+ Object.assign(config.httpsAgent.options, this.certOption);
1713
+ }
1714
+ return config;
1715
+ });
1716
+ }
1717
+ }
1718
+ /**
1719
+ * Helper to create SecureContextOptions from PEM format cert
1720
+ *
1721
+ * @param { string | Buffer } cert - The cert chain in PEM format
1722
+ * @param { string | Buffer } key - The private key for the cert chain
1723
+ * @param { string? } passphrase - The passphrase for private key
1724
+ * @param { string? | Buffer? } ca - Overrides the trusted CA certificates
1725
+ *
1726
+ * @returns Instance of SecureContextOptions
1727
+ *
1728
+ * @throws {@link ErrorCode|InvalidParameter} - when any parameter is empty
1729
+ *
1730
+ */
1731
+ function createPemCertOption(cert, key, passphrase, ca) {
1732
+ if (cert.length === 0) {
1733
+ throw new ErrorWithCode(formatString(ErrorMessage.EmptyParameter, "cert"), exports.ErrorCode.InvalidParameter);
1734
+ }
1735
+ if (key.length === 0) {
1736
+ throw new ErrorWithCode(formatString(ErrorMessage.EmptyParameter, "key"), exports.ErrorCode.InvalidParameter);
1737
+ }
1738
+ return {
1739
+ cert,
1740
+ key,
1741
+ passphrase,
1742
+ ca,
1743
+ };
1744
+ }
1745
+ /**
1746
+ * Helper to create SecureContextOptions from PFX format cert
1747
+ *
1748
+ * @param { string | Buffer } pfx - The content of .pfx file
1749
+ * @param { string? } passphrase - Optional. The passphrase of .pfx file
1750
+ *
1751
+ * @returns Instance of SecureContextOptions
1752
+ *
1753
+ * @throws {@link ErrorCode|InvalidParameter} - when any parameter is empty
1754
+ *
1755
+ */
1756
+ function createPfxCertOption(pfx, passphrase) {
1757
+ if (pfx.length === 0) {
1758
+ throw new ErrorWithCode(formatString(ErrorMessage.EmptyParameter, "pfx"), exports.ErrorCode.InvalidParameter);
1759
+ }
1760
+ return {
1761
+ pfx,
1762
+ passphrase,
1763
+ };
1764
+ }
1765
+
1766
+ // Copyright (c) Microsoft Corporation.
1767
+ // Following keys are used by SDK internally
1768
+ const ReservedKey = new Set([
1769
+ "authorityHost",
1770
+ "tenantId",
1771
+ "clientId",
1772
+ "clientSecret",
1773
+ "initiateLoginEndpoint",
1774
+ "applicationIdUri",
1775
+ "apiEndpoint",
1776
+ "apiName",
1777
+ "sqlServerEndpoint",
1778
+ "sqlUsername",
1779
+ "sqlPassword",
1780
+ "sqlDatabaseName",
1781
+ "sqlIdentityId",
1782
+ ]);
1420
1783
  /**
1421
1784
  * A class providing credential and configuration.
1422
1785
  * @beta
@@ -1594,24 +1957,1038 @@ class TeamsFx {
1594
1957
  this.configuration.set("sqlDatabaseName", env.SQL_DATABASE_NAME);
1595
1958
  this.configuration.set("sqlIdentityId", env.IDENTITY_ID);
1596
1959
  Object.keys(env).forEach((key) => {
1597
- const value = env[key];
1598
- if (key.startsWith("TEAMSFX_") && value) {
1599
- this.configuration.set(key.substring(8), value);
1960
+ if (ReservedKey.has(key)) {
1961
+ internalLogger.warn(`The name of environment variable ${key} is preserved. Will not load it as configuration.`);
1962
+ }
1963
+ this.configuration.set(key, env[key]);
1964
+ });
1965
+ }
1966
+ }
1967
+
1968
+ // Copyright (c) Microsoft Corporation.
1969
+ /**
1970
+ * @internal
1971
+ */
1972
+ var ActivityType;
1973
+ (function (ActivityType) {
1974
+ ActivityType[ActivityType["CurrentBotInstalled"] = 0] = "CurrentBotInstalled";
1975
+ ActivityType[ActivityType["CurrentBotMessaged"] = 1] = "CurrentBotMessaged";
1976
+ ActivityType[ActivityType["CurrentBotUninstalled"] = 2] = "CurrentBotUninstalled";
1977
+ ActivityType[ActivityType["TeamDeleted"] = 3] = "TeamDeleted";
1978
+ ActivityType[ActivityType["TeamRestored"] = 4] = "TeamRestored";
1979
+ ActivityType[ActivityType["Unknown"] = 5] = "Unknown";
1980
+ })(ActivityType || (ActivityType = {}));
1981
+ /**
1982
+ * @internal
1983
+ */
1984
+ class NotificationMiddleware {
1985
+ constructor(options) {
1986
+ this.conversationReferenceStore = options.conversationReferenceStore;
1987
+ }
1988
+ onTurn(context, next) {
1989
+ return tslib.__awaiter(this, void 0, void 0, function* () {
1990
+ const type = this.classifyActivity(context.activity);
1991
+ switch (type) {
1992
+ case ActivityType.CurrentBotInstalled:
1993
+ case ActivityType.TeamRestored: {
1994
+ const reference = botbuilder.TurnContext.getConversationReference(context.activity);
1995
+ yield this.conversationReferenceStore.set(reference);
1996
+ break;
1997
+ }
1998
+ case ActivityType.CurrentBotUninstalled:
1999
+ case ActivityType.TeamDeleted: {
2000
+ const reference = botbuilder.TurnContext.getConversationReference(context.activity);
2001
+ yield this.conversationReferenceStore.delete(reference);
2002
+ break;
2003
+ }
2004
+ }
2005
+ yield next();
2006
+ });
2007
+ }
2008
+ classifyActivity(activity) {
2009
+ var _a, _b;
2010
+ const activityType = activity.type;
2011
+ if (activityType === "installationUpdate") {
2012
+ const action = (_a = activity.action) === null || _a === void 0 ? void 0 : _a.toLowerCase();
2013
+ if (action === "add") {
2014
+ return ActivityType.CurrentBotInstalled;
2015
+ }
2016
+ else {
2017
+ return ActivityType.CurrentBotUninstalled;
2018
+ }
2019
+ }
2020
+ else if (activityType === "conversationUpdate") {
2021
+ const eventType = (_b = activity.channelData) === null || _b === void 0 ? void 0 : _b.eventType;
2022
+ if (eventType === "teamDeleted") {
2023
+ return ActivityType.TeamDeleted;
1600
2024
  }
2025
+ else if (eventType === "teamRestored") {
2026
+ return ActivityType.TeamRestored;
2027
+ }
2028
+ }
2029
+ return ActivityType.Unknown;
2030
+ }
2031
+ }
2032
+ class CommandResponseMiddleware {
2033
+ constructor(handlers) {
2034
+ this.commandHandlers = [];
2035
+ if (handlers && handlers.length > 0) {
2036
+ this.commandHandlers.push(...handlers);
2037
+ }
2038
+ }
2039
+ onTurn(context, next) {
2040
+ return tslib.__awaiter(this, void 0, void 0, function* () {
2041
+ const type = this.classifyActivity(context.activity);
2042
+ switch (type) {
2043
+ case ActivityType.CurrentBotMessaged:
2044
+ // Invoke corresponding command handler for the command response
2045
+ const commandText = this.getActivityText(context.activity);
2046
+ const message = {
2047
+ text: commandText,
2048
+ };
2049
+ for (const handler of this.commandHandlers) {
2050
+ const matchResult = this.shouldTrigger(handler.triggerPatterns, commandText);
2051
+ // It is important to note that the command bot will stop processing handlers
2052
+ // when the first command handler is matched.
2053
+ if (!!matchResult) {
2054
+ message.matches = Array.isArray(matchResult) ? matchResult : void 0;
2055
+ const response = yield handler.handleCommandReceived(context, message);
2056
+ yield context.sendActivity(response);
2057
+ break;
2058
+ }
2059
+ }
2060
+ break;
2061
+ }
2062
+ yield next();
2063
+ });
2064
+ }
2065
+ classifyActivity(activity) {
2066
+ if (activity.type === botbuilder.ActivityTypes.Message) {
2067
+ return ActivityType.CurrentBotMessaged;
2068
+ }
2069
+ return ActivityType.Unknown;
2070
+ }
2071
+ matchPattern(pattern, text) {
2072
+ if (text) {
2073
+ if (typeof pattern === "string") {
2074
+ const regExp = new RegExp(pattern, "i");
2075
+ return regExp.test(text);
2076
+ }
2077
+ if (pattern instanceof RegExp) {
2078
+ const matches = text.match(pattern);
2079
+ return matches !== null && matches !== void 0 ? matches : false;
2080
+ }
2081
+ }
2082
+ return false;
2083
+ }
2084
+ shouldTrigger(patterns, text) {
2085
+ const expressions = Array.isArray(patterns) ? patterns : [patterns];
2086
+ for (const ex of expressions) {
2087
+ const arg = this.matchPattern(ex, text);
2088
+ if (arg)
2089
+ return arg;
2090
+ }
2091
+ return false;
2092
+ }
2093
+ getActivityText(activity) {
2094
+ let text = activity.text;
2095
+ const removedMentionText = botbuilder.TurnContext.removeRecipientMention(activity);
2096
+ if (removedMentionText) {
2097
+ text = removedMentionText
2098
+ .toLowerCase()
2099
+ .replace(/\n|\r\n/g, "")
2100
+ .trim();
2101
+ }
2102
+ return text;
2103
+ }
2104
+ }
2105
+
2106
+ // Copyright (c) Microsoft Corporation.
2107
+ /**
2108
+ * A command bot for receiving commands and sending responses in Teams.
2109
+ *
2110
+ * @remarks
2111
+ * Ensure each command should ONLY be registered with the command once, otherwise it'll cause unexpected behavior if you register the same command more than once.
2112
+ *
2113
+ * @beta
2114
+ */
2115
+ class CommandBot {
2116
+ /**
2117
+ * Creates a new instance of the `CommandBot`.
2118
+ *
2119
+ * @param adapter The bound `BotFrameworkAdapter`.
2120
+ * @param options - initialize options
2121
+ *
2122
+ * @beta
2123
+ */
2124
+ constructor(adapter, options) {
2125
+ this.middleware = new CommandResponseMiddleware(options === null || options === void 0 ? void 0 : options.commands);
2126
+ this.adapter = adapter.use(this.middleware);
2127
+ }
2128
+ /**
2129
+ * Registers a command into the command bot.
2130
+ *
2131
+ * @param command The command to registered.
2132
+ *
2133
+ * @beta
2134
+ */
2135
+ registerCommand(command) {
2136
+ if (command) {
2137
+ this.middleware.commandHandlers.push(command);
2138
+ }
2139
+ }
2140
+ /**
2141
+ * Registers commands into the command bot.
2142
+ *
2143
+ * @param commands The command to registered.
2144
+ *
2145
+ * @beta
2146
+ */
2147
+ registerCommands(commands) {
2148
+ if (commands) {
2149
+ this.middleware.commandHandlers.push(...commands);
2150
+ }
2151
+ }
2152
+ }
2153
+
2154
+ // Copyright (c) Microsoft Corporation.
2155
+ /**
2156
+ * @internal
2157
+ */
2158
+ class LocalFileStorage {
2159
+ constructor(fileDir) {
2160
+ this.localFileName = ".notification.localstore.json";
2161
+ this.filePath = path__namespace.resolve(fileDir, this.localFileName);
2162
+ }
2163
+ read(key) {
2164
+ return tslib.__awaiter(this, void 0, void 0, function* () {
2165
+ if (!(yield this.storeFileExists())) {
2166
+ return undefined;
2167
+ }
2168
+ const data = yield this.readFromFile();
2169
+ return data[key];
1601
2170
  });
1602
2171
  }
2172
+ list() {
2173
+ return tslib.__awaiter(this, void 0, void 0, function* () {
2174
+ if (!(yield this.storeFileExists())) {
2175
+ return [];
2176
+ }
2177
+ const data = yield this.readFromFile();
2178
+ return Object.entries(data).map((entry) => entry[1]);
2179
+ });
2180
+ }
2181
+ write(key, object) {
2182
+ return tslib.__awaiter(this, void 0, void 0, function* () {
2183
+ if (!(yield this.storeFileExists())) {
2184
+ yield this.writeToFile({ [key]: object });
2185
+ return;
2186
+ }
2187
+ const data = yield this.readFromFile();
2188
+ yield this.writeToFile(Object.assign(data, { [key]: object }));
2189
+ });
2190
+ }
2191
+ delete(key) {
2192
+ return tslib.__awaiter(this, void 0, void 0, function* () {
2193
+ if (yield this.storeFileExists()) {
2194
+ const data = yield this.readFromFile();
2195
+ if (data[key] !== undefined) {
2196
+ delete data[key];
2197
+ yield this.writeToFile(data);
2198
+ }
2199
+ }
2200
+ });
2201
+ }
2202
+ storeFileExists() {
2203
+ return new Promise((resolve) => {
2204
+ try {
2205
+ fs__namespace.access(this.filePath, (err) => {
2206
+ if (err) {
2207
+ resolve(false);
2208
+ }
2209
+ else {
2210
+ resolve(true);
2211
+ }
2212
+ });
2213
+ }
2214
+ catch (error) {
2215
+ resolve(false);
2216
+ }
2217
+ });
2218
+ }
2219
+ readFromFile() {
2220
+ return new Promise((resolve, reject) => {
2221
+ try {
2222
+ fs__namespace.readFile(this.filePath, { encoding: "utf-8" }, (err, rawData) => {
2223
+ if (err) {
2224
+ reject(err);
2225
+ }
2226
+ else {
2227
+ resolve(JSON.parse(rawData));
2228
+ }
2229
+ });
2230
+ }
2231
+ catch (error) {
2232
+ reject(error);
2233
+ }
2234
+ });
2235
+ }
2236
+ writeToFile(data) {
2237
+ return tslib.__awaiter(this, void 0, void 0, function* () {
2238
+ return new Promise((resolve, reject) => {
2239
+ try {
2240
+ const rawData = JSON.stringify(data, undefined, 2);
2241
+ fs__namespace.writeFile(this.filePath, rawData, { encoding: "utf-8" }, (err) => {
2242
+ if (err) {
2243
+ reject(err);
2244
+ }
2245
+ else {
2246
+ resolve();
2247
+ }
2248
+ });
2249
+ }
2250
+ catch (error) {
2251
+ reject(error);
2252
+ }
2253
+ });
2254
+ });
2255
+ }
2256
+ }
2257
+ /**
2258
+ * @internal
2259
+ */
2260
+ class ConversationReferenceStore {
2261
+ constructor(storage) {
2262
+ this.storage = storage;
2263
+ }
2264
+ check(reference) {
2265
+ return tslib.__awaiter(this, void 0, void 0, function* () {
2266
+ const ref = yield this.storage.read(this.getKey(reference));
2267
+ return ref !== undefined;
2268
+ });
2269
+ }
2270
+ getAll() {
2271
+ return this.storage.list();
2272
+ }
2273
+ set(reference) {
2274
+ return this.storage.write(this.getKey(reference), reference);
2275
+ }
2276
+ delete(reference) {
2277
+ return this.storage.delete(this.getKey(reference));
2278
+ }
2279
+ getKey(reference) {
2280
+ var _a, _b;
2281
+ return `_${(_a = reference.conversation) === null || _a === void 0 ? void 0 : _a.tenantId}_${(_b = reference.conversation) === null || _b === void 0 ? void 0 : _b.id}`;
2282
+ }
2283
+ }
2284
+
2285
+ // Copyright (c) Microsoft Corporation.
2286
+ // Licensed under the MIT license.
2287
+ /**
2288
+ * @internal
2289
+ */
2290
+ function cloneConversation(conversation) {
2291
+ return Object.assign({}, conversation);
2292
+ }
2293
+ /**
2294
+ * @internal
2295
+ */
2296
+ function getTargetType(conversationReference) {
2297
+ var _a;
2298
+ const conversationType = (_a = conversationReference.conversation) === null || _a === void 0 ? void 0 : _a.conversationType;
2299
+ if (conversationType === "personal") {
2300
+ return "Person";
2301
+ }
2302
+ else if (conversationType === "groupChat") {
2303
+ return "Group";
2304
+ }
2305
+ else if (conversationType === "channel") {
2306
+ return "Channel";
2307
+ }
2308
+ else {
2309
+ return undefined;
2310
+ }
2311
+ }
2312
+ /**
2313
+ * @internal
2314
+ */
2315
+ function getTeamsBotInstallationId(context) {
2316
+ var _a, _b, _c, _d;
2317
+ return (_d = (_c = (_b = (_a = context.activity) === null || _a === void 0 ? void 0 : _a.channelData) === null || _b === void 0 ? void 0 : _b.team) === null || _c === void 0 ? void 0 : _c.id) !== null && _d !== void 0 ? _d : context.activity.conversation.id;
2318
+ }
2319
+
2320
+ // Copyright (c) Microsoft Corporation.
2321
+ /**
2322
+ * Send a plain text message to a notification target.
2323
+ *
2324
+ * @param target - the notification target.
2325
+ * @param text - the plain text message.
2326
+ * @returns A `Promise` representing the asynchronous operation.
2327
+ *
2328
+ * @beta
2329
+ */
2330
+ function sendMessage(target, text) {
2331
+ return target.sendMessage(text);
2332
+ }
2333
+ /**
2334
+ * Send an adaptive card message to a notification target.
2335
+ *
2336
+ * @param target - the notification target.
2337
+ * @param card - the adaptive card raw JSON.
2338
+ * @returns A `Promise` representing the asynchronous operation.
2339
+ *
2340
+ * @beta
2341
+ */
2342
+ function sendAdaptiveCard(target, card) {
2343
+ return target.sendAdaptiveCard(card);
2344
+ }
2345
+ /**
2346
+ * A {@link NotificationTarget} that represents a team channel.
2347
+ *
2348
+ * @remarks
2349
+ * It's recommended to get channels from {@link TeamsBotInstallation.channels()}.
2350
+ *
2351
+ * @beta
2352
+ */
2353
+ class Channel {
2354
+ /**
2355
+ * Constuctor.
2356
+ *
2357
+ * @remarks
2358
+ * It's recommended to get channels from {@link TeamsBotInstallation.channels()}, instead of using this constructor.
2359
+ *
2360
+ * @param parent - The parent {@link TeamsBotInstallation} where this channel is created from.
2361
+ * @param info - Detailed channel information.
2362
+ *
2363
+ * @beta
2364
+ */
2365
+ constructor(parent, info) {
2366
+ /**
2367
+ * Notification target type. For channel it's always "Channel".
2368
+ *
2369
+ * @beta
2370
+ */
2371
+ this.type = "Channel";
2372
+ this.parent = parent;
2373
+ this.info = info;
2374
+ }
2375
+ /**
2376
+ * Send a plain text message.
2377
+ *
2378
+ * @param text - the plain text message.
2379
+ * @returns A `Promise` representing the asynchronous operation.
2380
+ *
2381
+ * @beta
2382
+ */
2383
+ sendMessage(text) {
2384
+ return this.parent.adapter.continueConversation(this.parent.conversationReference, (context) => tslib.__awaiter(this, void 0, void 0, function* () {
2385
+ const conversation = yield this.newConversation(context);
2386
+ yield this.parent.adapter.continueConversation(conversation, (ctx) => tslib.__awaiter(this, void 0, void 0, function* () {
2387
+ yield ctx.sendActivity(text);
2388
+ }));
2389
+ }));
2390
+ }
2391
+ /**
2392
+ * Send an adaptive card message.
2393
+ *
2394
+ * @param card - the adaptive card raw JSON.
2395
+ * @returns A `Promise` representing the asynchronous operation.
2396
+ *
2397
+ * @beta
2398
+ */
2399
+ sendAdaptiveCard(card) {
2400
+ return tslib.__awaiter(this, void 0, void 0, function* () {
2401
+ return this.parent.adapter.continueConversation(this.parent.conversationReference, (context) => tslib.__awaiter(this, void 0, void 0, function* () {
2402
+ const conversation = yield this.newConversation(context);
2403
+ yield this.parent.adapter.continueConversation(conversation, (ctx) => tslib.__awaiter(this, void 0, void 0, function* () {
2404
+ yield ctx.sendActivity({
2405
+ attachments: [botbuilder.CardFactory.adaptiveCard(card)],
2406
+ });
2407
+ }));
2408
+ }));
2409
+ });
2410
+ }
2411
+ /**
2412
+ * @internal
2413
+ */
2414
+ newConversation(context) {
2415
+ return tslib.__awaiter(this, void 0, void 0, function* () {
2416
+ const reference = botbuilder.TurnContext.getConversationReference(context.activity);
2417
+ const channelConversation = cloneConversation(reference);
2418
+ channelConversation.conversation.id = this.info.id || "";
2419
+ return channelConversation;
2420
+ });
2421
+ }
2422
+ }
2423
+ /**
2424
+ * A {@link NotificationTarget} that represents a team member.
2425
+ *
2426
+ * @remarks
2427
+ * It's recommended to get members from {@link TeamsBotInstallation.members()}.
2428
+ *
2429
+ * @beta
2430
+ */
2431
+ class Member {
2432
+ /**
2433
+ * Constuctor.
2434
+ *
2435
+ * @remarks
2436
+ * It's recommended to get members from {@link TeamsBotInstallation.members()}, instead of using this constructor.
2437
+ *
2438
+ * @param parent - The parent {@link TeamsBotInstallation} where this member is created from.
2439
+ * @param account - Detailed member account information.
2440
+ *
2441
+ * @beta
2442
+ */
2443
+ constructor(parent, account) {
2444
+ /**
2445
+ * Notification target type. For member it's always "Person".
2446
+ *
2447
+ * @beta
2448
+ */
2449
+ this.type = "Person";
2450
+ this.parent = parent;
2451
+ this.account = account;
2452
+ }
2453
+ /**
2454
+ * Send a plain text message.
2455
+ *
2456
+ * @param text - the plain text message.
2457
+ * @returns A `Promise` representing the asynchronous operation.
2458
+ *
2459
+ * @beta
2460
+ */
2461
+ sendMessage(text) {
2462
+ return this.parent.adapter.continueConversation(this.parent.conversationReference, (context) => tslib.__awaiter(this, void 0, void 0, function* () {
2463
+ const conversation = yield this.newConversation(context);
2464
+ yield this.parent.adapter.continueConversation(conversation, (ctx) => tslib.__awaiter(this, void 0, void 0, function* () {
2465
+ yield ctx.sendActivity(text);
2466
+ }));
2467
+ }));
2468
+ }
2469
+ /**
2470
+ * Send an adaptive card message.
2471
+ *
2472
+ * @param card - the adaptive card raw JSON.
2473
+ * @returns A `Promise` representing the asynchronous operation.
2474
+ *
2475
+ * @beta
2476
+ */
2477
+ sendAdaptiveCard(card) {
2478
+ return tslib.__awaiter(this, void 0, void 0, function* () {
2479
+ return this.parent.adapter.continueConversation(this.parent.conversationReference, (context) => tslib.__awaiter(this, void 0, void 0, function* () {
2480
+ const conversation = yield this.newConversation(context);
2481
+ yield this.parent.adapter.continueConversation(conversation, (ctx) => tslib.__awaiter(this, void 0, void 0, function* () {
2482
+ yield ctx.sendActivity({
2483
+ attachments: [botbuilder.CardFactory.adaptiveCard(card)],
2484
+ });
2485
+ }));
2486
+ }));
2487
+ });
2488
+ }
2489
+ /**
2490
+ * @internal
2491
+ */
2492
+ newConversation(context) {
2493
+ return tslib.__awaiter(this, void 0, void 0, function* () {
2494
+ const reference = botbuilder.TurnContext.getConversationReference(context.activity);
2495
+ const personalConversation = cloneConversation(reference);
2496
+ const connectorClient = context.turnState.get(this.parent.adapter.ConnectorClientKey);
2497
+ const conversation = yield connectorClient.conversations.createConversation({
2498
+ isGroup: false,
2499
+ tenantId: context.activity.conversation.tenantId,
2500
+ bot: context.activity.recipient,
2501
+ members: [this.account],
2502
+ channelData: {},
2503
+ });
2504
+ personalConversation.conversation.id = conversation.id;
2505
+ return personalConversation;
2506
+ });
2507
+ }
2508
+ }
2509
+ /**
2510
+ * A {@link NotificationTarget} that represents a bot installation. Teams Bot could be installed into
2511
+ * - Personal chat
2512
+ * - Group chat
2513
+ * - Team (by default the `General` channel)
2514
+ *
2515
+ * @remarks
2516
+ * It's recommended to get bot installations from {@link ConversationBot.installations()}.
2517
+ *
2518
+ * @beta
2519
+ */
2520
+ class TeamsBotInstallation {
2521
+ /**
2522
+ * Constructor
2523
+ *
2524
+ * @remarks
2525
+ * It's recommended to get bot installations from {@link ConversationBot.installations()}, instead of using this constructor.
2526
+ *
2527
+ * @param adapter - the bound `BotFrameworkAdapter`.
2528
+ * @param conversationReference - the bound `ConversationReference`.
2529
+ *
2530
+ * @beta
2531
+ */
2532
+ constructor(adapter, conversationReference) {
2533
+ this.adapter = adapter;
2534
+ this.conversationReference = conversationReference;
2535
+ this.type = getTargetType(conversationReference);
2536
+ }
2537
+ /**
2538
+ * Send a plain text message.
2539
+ *
2540
+ * @param text - the plain text message.
2541
+ * @returns A `Promise` representing the asynchronous operation.
2542
+ *
2543
+ * @beta
2544
+ */
2545
+ sendMessage(text) {
2546
+ return this.adapter.continueConversation(this.conversationReference, (context) => tslib.__awaiter(this, void 0, void 0, function* () {
2547
+ yield context.sendActivity(text);
2548
+ }));
2549
+ }
2550
+ /**
2551
+ * Send an adaptive card message.
2552
+ *
2553
+ * @param card - the adaptive card raw JSON.
2554
+ * @returns A `Promise` representing the asynchronous operation.
2555
+ *
2556
+ * @beta
2557
+ */
2558
+ sendAdaptiveCard(card) {
2559
+ return this.adapter.continueConversation(this.conversationReference, (context) => tslib.__awaiter(this, void 0, void 0, function* () {
2560
+ yield context.sendActivity({
2561
+ attachments: [botbuilder.CardFactory.adaptiveCard(card)],
2562
+ });
2563
+ }));
2564
+ }
2565
+ /**
2566
+ * Get channels from this bot installation.
2567
+ *
2568
+ * @returns an array of channels if bot is installed into a team, otherwise returns an empty array.
2569
+ *
2570
+ * @beta
2571
+ */
2572
+ channels() {
2573
+ return tslib.__awaiter(this, void 0, void 0, function* () {
2574
+ let teamsChannels = [];
2575
+ yield this.adapter.continueConversation(this.conversationReference, (context) => tslib.__awaiter(this, void 0, void 0, function* () {
2576
+ const teamId = getTeamsBotInstallationId(context);
2577
+ if (teamId !== undefined) {
2578
+ teamsChannels = yield botbuilder.TeamsInfo.getTeamChannels(context, teamId);
2579
+ }
2580
+ }));
2581
+ const channels = [];
2582
+ for (const channel of teamsChannels) {
2583
+ channels.push(new Channel(this, channel));
2584
+ }
2585
+ return channels;
2586
+ });
2587
+ }
2588
+ /**
2589
+ * Get members from this bot installation.
2590
+ *
2591
+ * @returns an array of members from where the bot is installed.
2592
+ *
2593
+ * @beta
2594
+ */
2595
+ members() {
2596
+ return tslib.__awaiter(this, void 0, void 0, function* () {
2597
+ const members = [];
2598
+ yield this.adapter.continueConversation(this.conversationReference, (context) => tslib.__awaiter(this, void 0, void 0, function* () {
2599
+ let continuationToken;
2600
+ do {
2601
+ const pagedMembers = yield botbuilder.TeamsInfo.getPagedMembers(context, undefined, continuationToken);
2602
+ continuationToken = pagedMembers.continuationToken;
2603
+ for (const member of pagedMembers.members) {
2604
+ members.push(new Member(this, member));
2605
+ }
2606
+ } while (continuationToken !== undefined);
2607
+ }));
2608
+ return members;
2609
+ });
2610
+ }
2611
+ }
2612
+ /**
2613
+ * Provide utilities to send notification to varies targets (e.g., member, group, channel).
2614
+ *
2615
+ * @beta
2616
+ */
2617
+ class NotificationBot {
2618
+ /**
2619
+ * constructor of the notification bot.
2620
+ *
2621
+ * @remarks
2622
+ * To ensure accuracy, it's recommended to initialize before handling any message.
2623
+ *
2624
+ * @param adapter - the bound `BotFrameworkAdapter`
2625
+ * @param options - initialize options
2626
+ *
2627
+ * @beta
2628
+ */
2629
+ constructor(adapter, options) {
2630
+ var _a, _b;
2631
+ const storage = (_a = options === null || options === void 0 ? void 0 : options.storage) !== null && _a !== void 0 ? _a : new LocalFileStorage(path__namespace.resolve(process.env.RUNNING_ON_AZURE === "1" ? (_b = process.env.TEMP) !== null && _b !== void 0 ? _b : "./" : "./"));
2632
+ this.conversationReferenceStore = new ConversationReferenceStore(storage);
2633
+ this.adapter = adapter.use(new NotificationMiddleware({
2634
+ conversationReferenceStore: this.conversationReferenceStore,
2635
+ }));
2636
+ }
2637
+ /**
2638
+ * Get all targets where the bot is installed.
2639
+ *
2640
+ * @remarks
2641
+ * The result is retrieving from the persisted storage.
2642
+ *
2643
+ * @returns - an array of {@link TeamsBotInstallation}.
2644
+ *
2645
+ * @beta
2646
+ */
2647
+ installations() {
2648
+ return tslib.__awaiter(this, void 0, void 0, function* () {
2649
+ if (this.conversationReferenceStore === undefined || this.adapter === undefined) {
2650
+ throw new Error("NotificationBot has not been initialized.");
2651
+ }
2652
+ const references = (yield this.conversationReferenceStore.getAll()).values();
2653
+ const targets = [];
2654
+ for (const reference of references) {
2655
+ // validate connection
2656
+ let valid = true;
2657
+ this.adapter.continueConversation(reference, (context) => tslib.__awaiter(this, void 0, void 0, function* () {
2658
+ try {
2659
+ // try get member to see if the installation is still valid
2660
+ yield botbuilder.TeamsInfo.getPagedMembers(context, 1);
2661
+ }
2662
+ catch (error) {
2663
+ if (error.code === "BotNotInConversationRoster") {
2664
+ valid = false;
2665
+ }
2666
+ }
2667
+ }));
2668
+ if (valid) {
2669
+ targets.push(new TeamsBotInstallation(this.adapter, reference));
2670
+ }
2671
+ else {
2672
+ this.conversationReferenceStore.delete(reference);
2673
+ }
2674
+ }
2675
+ return targets;
2676
+ });
2677
+ }
2678
+ }
2679
+
2680
+ // Copyright (c) Microsoft Corporation.
2681
+ /**
2682
+ * Provide utilities for bot conversation, including:
2683
+ * - handle command and response.
2684
+ * - send notification to varies targets (e.g., member, group, channel).
2685
+ *
2686
+ * @example
2687
+ * For command and response, you can register your commands through the constructor, or use the `registerCommand` and `registerCommands` API to add commands later.
2688
+ *
2689
+ * ```typescript
2690
+ * // register through constructor
2691
+ * const conversationBot = new ConversationBot({
2692
+ * command: {
2693
+ * enabled: true,
2694
+ * commands: [ new HelloWorldCommandHandler() ],
2695
+ * },
2696
+ * });
2697
+ *
2698
+ * // register through `register*` API
2699
+ * conversationBot.command.registerCommand(new HelpCommandHandler());
2700
+ * ```
2701
+ *
2702
+ * For notification, you can enable notification at initialization, then send notifications at any time.
2703
+ *
2704
+ * ```typescript
2705
+ * // enable through constructor
2706
+ * const conversationBot = new ConversationBot({
2707
+ * notification: {
2708
+ * enabled: true,
2709
+ * },
2710
+ * });
2711
+ *
2712
+ * // get all bot installations and send message
2713
+ * for (const target of await conversationBot.notification.installations()) {
2714
+ * await target.sendMessage("Hello Notification");
2715
+ * }
2716
+ *
2717
+ * // alternative - send message to all members
2718
+ * for (const target of await conversationBot.notification.installations()) {
2719
+ * for (const member of await target.members()) {
2720
+ * await member.sendMessage("Hello Notification");
2721
+ * }
2722
+ * }
2723
+ * ```
2724
+ *
2725
+ * @remarks
2726
+ * Set `adapter` in {@link ConversationOptions} to use your own bot adapter.
2727
+ *
2728
+ * For command and response, ensure each command should ONLY be registered with the command once, otherwise it'll cause unexpected behavior if you register the same command more than once.
2729
+ *
2730
+ * For notification, set `notification.storage` in {@link ConversationOptions} to use your own storage implementation.
2731
+ *
2732
+ * @beta
2733
+ */
2734
+ class ConversationBot {
2735
+ /**
2736
+ * Creates new instance of the `ConversationBot`.
2737
+ *
2738
+ * @remarks
2739
+ * It's recommended to create your own adapter and storage for production environment instead of the default one.
2740
+ *
2741
+ * @param options - initialize options
2742
+ *
2743
+ * @beta
2744
+ */
2745
+ constructor(options) {
2746
+ var _a, _b;
2747
+ if (options.adapter) {
2748
+ this.adapter = options.adapter;
2749
+ }
2750
+ else {
2751
+ this.adapter = this.createDefaultAdapter(options.adapterConfig);
2752
+ }
2753
+ if ((_a = options.command) === null || _a === void 0 ? void 0 : _a.enabled) {
2754
+ this.command = new CommandBot(this.adapter, options.command);
2755
+ }
2756
+ if ((_b = options.notification) === null || _b === void 0 ? void 0 : _b.enabled) {
2757
+ this.notification = new NotificationBot(this.adapter, options.notification);
2758
+ }
2759
+ }
2760
+ createDefaultAdapter(adapterConfig) {
2761
+ const adapter = adapterConfig === undefined
2762
+ ? new botbuilder.BotFrameworkAdapter({
2763
+ appId: process.env.BOT_ID,
2764
+ appPassword: process.env.BOT_PASSWORD,
2765
+ })
2766
+ : new botbuilder.BotFrameworkAdapter(adapterConfig);
2767
+ // the default error handler
2768
+ adapter.onTurnError = (context, error) => tslib.__awaiter(this, void 0, void 0, function* () {
2769
+ // This check writes out errors to console.
2770
+ console.error(`[onTurnError] unhandled error: ${error}`);
2771
+ // Send a trace activity, which will be displayed in Bot Framework Emulator
2772
+ yield context.sendTraceActivity("OnTurnError Trace", `${error}`, "https://www.botframework.com/schemas/error", "TurnError");
2773
+ // Send a message to the user
2774
+ yield context.sendActivity(`The bot encountered unhandled error: ${error.message}`);
2775
+ yield context.sendActivity("To continue to run this bot, please fix the bot source code.");
2776
+ });
2777
+ return adapter;
2778
+ }
2779
+ /**
2780
+ * The request handler to integrate with web request.
2781
+ *
2782
+ * @param req - an Express or Restify style request object.
2783
+ * @param res - an Express or Restify style response object.
2784
+ * @param logic - the additional function to handle bot context.
2785
+ *
2786
+ * @example
2787
+ * For example, to use with Restify:
2788
+ * ``` typescript
2789
+ * // The default/empty behavior
2790
+ * server.post("api/messages", conversationBot.requestHandler);
2791
+ *
2792
+ * // Or, add your own logic
2793
+ * server.post("api/messages", async (req, res) => {
2794
+ * await conversationBot.requestHandler(req, res, async (context) => {
2795
+ * // your-own-context-logic
2796
+ * });
2797
+ * });
2798
+ * ```
2799
+ *
2800
+ * @beta
2801
+ */
2802
+ requestHandler(req, res, logic) {
2803
+ return tslib.__awaiter(this, void 0, void 0, function* () {
2804
+ if (logic === undefined) {
2805
+ // create empty logic
2806
+ logic = () => tslib.__awaiter(this, void 0, void 0, function* () { });
2807
+ }
2808
+ yield this.adapter.processActivity(req, res, logic);
2809
+ });
2810
+ }
2811
+ }
2812
+
2813
+ // Copyright (c) Microsoft Corporation.
2814
+ const { AdaptiveCards } = require("@microsoft/adaptivecards-tools");
2815
+ /**
2816
+ * Provides utility method to build bot message with cards that supported in Teams.
2817
+ */
2818
+ class MessageBuilder {
2819
+ /**
2820
+ * Build a bot message activity attached with adaptive card.
2821
+ *
2822
+ * @param cardTemplate The adaptive card template.
2823
+ * @param data card data used to render the template.
2824
+ * @returns A bot message activity attached with an adaptive card.
2825
+ *
2826
+ * @example
2827
+ * ```javascript
2828
+ * const cardTemplate = {
2829
+ * type: "AdaptiveCard",
2830
+ * body: [
2831
+ * {
2832
+ * "type": "TextBlock",
2833
+ * "text": "${title}",
2834
+ * "size": "Large"
2835
+ * },
2836
+ * {
2837
+ * "type": "TextBlock",
2838
+ * "text": "${description}"
2839
+ * }],
2840
+ * $schema: "http://adaptivecards.io/schemas/adaptive-card.json",
2841
+ * version: "1.4"
2842
+ * };
2843
+ *
2844
+ * type CardData = {
2845
+ * title: string,
2846
+ * description: string
2847
+ * };
2848
+ * const card = MessageBuilder.attachAdaptiveCard<CardData>(
2849
+ * cardTemplate, {
2850
+ * title: "sample card title",
2851
+ * description: "sample card description"
2852
+ * });
2853
+ * ```
2854
+ *
2855
+ * @beta
2856
+ */
2857
+ static attachAdaptiveCard(cardTemplate, data) {
2858
+ return {
2859
+ attachments: [botbuilder.CardFactory.adaptiveCard(AdaptiveCards.declare(cardTemplate).render(data))],
2860
+ };
2861
+ }
2862
+ /**
2863
+ * Build a bot message activity attached with an adaptive card.
2864
+ *
2865
+ * @param card The adaptive card content.
2866
+ * @returns A bot message activity attached with an adaptive card.
2867
+ *
2868
+ * @beta
2869
+ */
2870
+ static attachAdaptiveCardWithoutData(card) {
2871
+ return {
2872
+ attachments: [botbuilder.CardFactory.adaptiveCard(AdaptiveCards.declareWithoutData(card).render())],
2873
+ };
2874
+ }
2875
+ /**
2876
+ * Build a bot message activity attached with an hero card.
2877
+ *
2878
+ * @param title The card title.
2879
+ * @param images Optional. The array of images to include on the card.
2880
+ * @param buttons Optional. The array of buttons to include on the card. Each `string` in the array
2881
+ * is converted to an `imBack` button with a title and value set to the value of the string.
2882
+ * @param other Optional. Any additional properties to include on the card.
2883
+ *
2884
+ * @returns A bot message activity attached with a hero card.
2885
+ *
2886
+ * @example
2887
+ * ```javascript
2888
+ * const message = MessageBuilder.attachHeroCard(
2889
+ * 'sample title',
2890
+ * ['https://example.com/sample.jpg'],
2891
+ * ['action']
2892
+ * );
2893
+ * ```
2894
+ *
2895
+ * @beta
2896
+ */
2897
+ static attachHeroCard(title, images, buttons, other) {
2898
+ return MessageBuilder.attachContent(botbuilder.CardFactory.heroCard(title, images, buttons, other));
2899
+ }
2900
+ /**
2901
+ * Returns an attachment for a sign-in card.
2902
+ *
2903
+ * @param title The title for the card's sign-in button.
2904
+ * @param url The URL of the sign-in page to use.
2905
+ * @param text Optional. Additional text to include on the card.
2906
+ *
2907
+ * @returns A bot message activity attached with a sign-in card.
2908
+ *
2909
+ * @remarks
2910
+ * For channels that don't natively support sign-in cards, an alternative message is rendered.
2911
+ *
2912
+ * @beta
2913
+ */
2914
+ static attachSigninCard(title, url, text) {
2915
+ return MessageBuilder.attachContent(botbuilder.CardFactory.signinCard(title, url, text));
2916
+ }
2917
+ /**
2918
+ * Build a bot message activity attached with an Office 365 connector card.
2919
+ *
2920
+ * @param card A description of the Office 365 connector card.
2921
+ * @returns A bot message activity attached with an Office 365 connector card.
2922
+ *
2923
+ * @beta
2924
+ */
2925
+ static attachO365ConnectorCard(card) {
2926
+ return MessageBuilder.attachContent(botbuilder.CardFactory.o365ConnectorCard(card));
2927
+ }
2928
+ /**
2929
+ * Build a message activity attached with a receipt card.
2930
+ * @param card A description of the receipt card.
2931
+ * @returns A message activity attached with a receipt card.
2932
+ *
2933
+ * @beta
2934
+ */
2935
+ static AttachReceiptCard(card) {
2936
+ return MessageBuilder.attachContent(botbuilder.CardFactory.receiptCard(card));
2937
+ }
2938
+ /**
2939
+ *
2940
+ * @param title The card title.
2941
+ * @param images Optional. The array of images to include on the card.
2942
+ * @param buttons Optional. The array of buttons to include on the card. Each `string` in the array
2943
+ * is converted to an `imBack` button with a title and value set to the value of the string.
2944
+ * @param other Optional. Any additional properties to include on the card.
2945
+ * @returns A message activity attached with a thumbnail card
2946
+ *
2947
+ * @beta
2948
+ */
2949
+ static attachThumbnailCard(title, images, buttons, other) {
2950
+ return MessageBuilder.attachContent(botbuilder.CardFactory.thumbnailCard(title, images, buttons, other));
2951
+ }
2952
+ /**
2953
+ * Add an attachement to a bot activity.
2954
+ * @param attachement The attachment object to attach.
2955
+ * @returns A message activity with an attachment.
2956
+ *
2957
+ * @beta
2958
+ */
2959
+ static attachContent(attachement) {
2960
+ return {
2961
+ attachments: [attachement],
2962
+ };
2963
+ }
1603
2964
  }
1604
2965
 
2966
+ exports.ApiKeyProvider = ApiKeyProvider;
1605
2967
  exports.AppCredential = AppCredential;
2968
+ exports.BasicAuthProvider = BasicAuthProvider;
2969
+ exports.BearerTokenAuthProvider = BearerTokenAuthProvider;
2970
+ exports.CertificateAuthProvider = CertificateAuthProvider;
2971
+ exports.Channel = Channel;
2972
+ exports.CommandBot = CommandBot;
2973
+ exports.ConversationBot = ConversationBot;
1606
2974
  exports.ErrorWithCode = ErrorWithCode;
2975
+ exports.Member = Member;
2976
+ exports.MessageBuilder = MessageBuilder;
1607
2977
  exports.MsGraphAuthProvider = MsGraphAuthProvider;
2978
+ exports.NotificationBot = NotificationBot;
1608
2979
  exports.OnBehalfOfUserCredential = OnBehalfOfUserCredential;
2980
+ exports.TeamsBotInstallation = TeamsBotInstallation;
1609
2981
  exports.TeamsBotSsoPrompt = TeamsBotSsoPrompt;
1610
2982
  exports.TeamsFx = TeamsFx;
1611
2983
  exports.TeamsUserCredential = TeamsUserCredential;
2984
+ exports.createApiClient = createApiClient;
1612
2985
  exports.createMicrosoftGraphClient = createMicrosoftGraphClient;
2986
+ exports.createPemCertOption = createPemCertOption;
2987
+ exports.createPfxCertOption = createPfxCertOption;
1613
2988
  exports.getLogLevel = getLogLevel;
1614
2989
  exports.getTediousConnectionConfig = getTediousConnectionConfig;
2990
+ exports.sendAdaptiveCard = sendAdaptiveCard;
2991
+ exports.sendMessage = sendMessage;
1615
2992
  exports.setLogFunction = setLogFunction;
1616
2993
  exports.setLogLevel = setLogLevel;
1617
2994
  exports.setLogger = setLogger;