@microsoft/teamsfx 0.6.2-alpha.83ce60286.0 → 0.6.2-alpha.aafc68d57.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,34 @@ 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 path = require('path');
16
+ var fs = require('fs');
14
17
 
15
18
  function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
16
19
 
20
+ function _interopNamespace(e) {
21
+ if (e && e.__esModule) return e;
22
+ var n = Object.create(null);
23
+ if (e) {
24
+ Object.keys(e).forEach(function (k) {
25
+ if (k !== 'default') {
26
+ var d = Object.getOwnPropertyDescriptor(e, k);
27
+ Object.defineProperty(n, k, d.get ? d : {
28
+ enumerable: true,
29
+ get: function () { return e[k]; }
30
+ });
31
+ }
32
+ });
33
+ }
34
+ n["default"] = e;
35
+ return Object.freeze(n);
36
+ }
37
+
17
38
  var jwt_decode__default = /*#__PURE__*/_interopDefaultLegacy(jwt_decode);
39
+ var axios__default = /*#__PURE__*/_interopDefaultLegacy(axios);
40
+ var path__namespace = /*#__PURE__*/_interopNamespace(path);
41
+ var fs__namespace = /*#__PURE__*/_interopNamespace(fs);
18
42
 
19
43
  // Copyright (c) Microsoft Corporation.
20
44
  // Licensed under the MIT license.
@@ -1416,6 +1440,72 @@ class TeamsBotSsoPrompt extends botbuilderDialogs.Dialog {
1416
1440
  }
1417
1441
  }
1418
1442
 
1443
+ // Copyright (c) Microsoft Corporation.
1444
+ /**
1445
+ * Initializes new Axios instance with specific auth provider
1446
+ *
1447
+ * @param apiEndpoint - Base url of the API
1448
+ * @param authProvider - Auth provider that injects authentication info to each request
1449
+ * @returns axios instance configured with specfic auth provider
1450
+ *
1451
+ * @example
1452
+ * ```typescript
1453
+ * const client = createApiClient("https://my-api-endpoint-base-url", new BasicAuthProvider("xxx","xxx"));
1454
+ * ```
1455
+ *
1456
+ * @beta
1457
+ */
1458
+ function createApiClient(apiEndpoint, authProvider) {
1459
+ // Add a request interceptor
1460
+ const instance = axios__default["default"].create({
1461
+ baseURL: apiEndpoint,
1462
+ });
1463
+ instance.interceptors.request.use(function (config) {
1464
+ return tslib.__awaiter(this, void 0, void 0, function* () {
1465
+ return yield authProvider.AddAuthenticationInfo(config);
1466
+ });
1467
+ });
1468
+ return instance;
1469
+ }
1470
+
1471
+ // Copyright (c) Microsoft Corporation.
1472
+ /**
1473
+ * Provider that handles Bearer Token authentication
1474
+ *
1475
+ * @beta
1476
+ */
1477
+ class BearerTokenAuthProvider {
1478
+ /**
1479
+ * @param getToken Function that returns the content of bearer token used in http request
1480
+ *
1481
+ * @beta
1482
+ */
1483
+ constructor(getToken) {
1484
+ this.getToken = getToken;
1485
+ }
1486
+ /**
1487
+ * Adds authentication info to http requests
1488
+ *
1489
+ * @param config - Contains all the request information and can be updated to include extra authentication info.
1490
+ * Refer https://axios-http.com/docs/req_config for detailed document.
1491
+ *
1492
+ * @beta
1493
+ */
1494
+ AddAuthenticationInfo(config) {
1495
+ return tslib.__awaiter(this, void 0, void 0, function* () {
1496
+ const token = yield this.getToken();
1497
+ if (!config.headers) {
1498
+ config.headers = {};
1499
+ }
1500
+ if (config.headers["Authorization"]) {
1501
+ throw new Error("Authorization header already exists!");
1502
+ }
1503
+ config.headers["Authorization"] = `Bearer ${token}`;
1504
+ return config;
1505
+ });
1506
+ }
1507
+ }
1508
+
1419
1509
  // Copyright (c) Microsoft Corporation.
1420
1510
  /**
1421
1511
  * A class providing credential and configuration.
@@ -1602,16 +1692,927 @@ class TeamsFx {
1602
1692
  }
1603
1693
  }
1604
1694
 
1695
+ // Copyright (c) Microsoft Corporation.
1696
+ /**
1697
+ * @internal
1698
+ */
1699
+ var ActivityType;
1700
+ (function (ActivityType) {
1701
+ ActivityType[ActivityType["CurrentBotInstalled"] = 0] = "CurrentBotInstalled";
1702
+ ActivityType[ActivityType["CurrentBotMessaged"] = 1] = "CurrentBotMessaged";
1703
+ ActivityType[ActivityType["CurrentBotUninstalled"] = 2] = "CurrentBotUninstalled";
1704
+ ActivityType[ActivityType["TeamDeleted"] = 3] = "TeamDeleted";
1705
+ ActivityType[ActivityType["TeamRestored"] = 4] = "TeamRestored";
1706
+ ActivityType[ActivityType["CommandReceived"] = 5] = "CommandReceived";
1707
+ ActivityType[ActivityType["Unknown"] = 6] = "Unknown";
1708
+ })(ActivityType || (ActivityType = {}));
1709
+ /**
1710
+ * @internal
1711
+ */
1712
+ class NotificationMiddleware {
1713
+ constructor(options) {
1714
+ this.conversationReferenceStore = options.conversationReferenceStore;
1715
+ }
1716
+ onTurn(context, next) {
1717
+ return tslib.__awaiter(this, void 0, void 0, function* () {
1718
+ const type = this.classifyActivity(context.activity);
1719
+ switch (type) {
1720
+ case ActivityType.CurrentBotInstalled:
1721
+ case ActivityType.TeamRestored: {
1722
+ const reference = botbuilder.TurnContext.getConversationReference(context.activity);
1723
+ yield this.conversationReferenceStore.set(reference);
1724
+ break;
1725
+ }
1726
+ case ActivityType.CurrentBotMessaged: {
1727
+ const reference = botbuilder.TurnContext.getConversationReference(context.activity);
1728
+ if (!(yield this.conversationReferenceStore.check(reference))) {
1729
+ yield this.conversationReferenceStore.set(reference);
1730
+ }
1731
+ break;
1732
+ }
1733
+ case ActivityType.CurrentBotUninstalled:
1734
+ case ActivityType.TeamDeleted: {
1735
+ const reference = botbuilder.TurnContext.getConversationReference(context.activity);
1736
+ yield this.conversationReferenceStore.delete(reference);
1737
+ break;
1738
+ }
1739
+ }
1740
+ yield next();
1741
+ });
1742
+ }
1743
+ classifyActivity(activity) {
1744
+ var _a, _b;
1745
+ const activityType = activity.type;
1746
+ if (activityType === "installationUpdate") {
1747
+ const action = (_a = activity.action) === null || _a === void 0 ? void 0 : _a.toLowerCase();
1748
+ if (action === "add") {
1749
+ return ActivityType.CurrentBotInstalled;
1750
+ }
1751
+ else {
1752
+ return ActivityType.CurrentBotUninstalled;
1753
+ }
1754
+ }
1755
+ else if (activityType === "message") {
1756
+ return ActivityType.CurrentBotMessaged;
1757
+ }
1758
+ else if (activityType === "conversationUpdate") {
1759
+ const eventType = (_b = activity.channelData) === null || _b === void 0 ? void 0 : _b.eventType;
1760
+ if (eventType === "teamDeleted") {
1761
+ return ActivityType.TeamDeleted;
1762
+ }
1763
+ else if (eventType === "teamRestored") {
1764
+ return ActivityType.TeamRestored;
1765
+ }
1766
+ }
1767
+ return ActivityType.Unknown;
1768
+ }
1769
+ }
1770
+ class CommandResponseMiddleware {
1771
+ constructor(handlers) {
1772
+ this.commandHandlers = [];
1773
+ if (handlers && handlers.length > 0) {
1774
+ this.commandHandlers.push(...handlers);
1775
+ }
1776
+ }
1777
+ onTurn(context, next) {
1778
+ return tslib.__awaiter(this, void 0, void 0, function* () {
1779
+ const type = this.classifyActivity(context.activity);
1780
+ let handlers = [];
1781
+ switch (type) {
1782
+ case ActivityType.CommandReceived:
1783
+ // Invoke corresponding command handler for the command response
1784
+ const commandText = this.getActivityText(context.activity);
1785
+ handlers = this.filterCommandHandler(commandText, this.commandHandlers);
1786
+ if (handlers.length > 0) {
1787
+ const response = yield handlers[0].handleCommandReceived(context, commandText);
1788
+ yield context.sendActivity(response);
1789
+ }
1790
+ break;
1791
+ }
1792
+ yield next();
1793
+ });
1794
+ }
1795
+ classifyActivity(activity) {
1796
+ if (this.isCommandReceived(activity)) {
1797
+ return ActivityType.CommandReceived;
1798
+ }
1799
+ return ActivityType.Unknown;
1800
+ }
1801
+ isCommandReceived(activity) {
1802
+ if (this.commandHandlers) {
1803
+ const commandText = this.getActivityText(activity);
1804
+ const handlers = this.filterCommandHandler(commandText, this.commandHandlers);
1805
+ return handlers.length > 0;
1806
+ }
1807
+ else {
1808
+ return false;
1809
+ }
1810
+ }
1811
+ filterCommandHandler(commandText, commandHandlers) {
1812
+ const handlers = commandHandlers.filter((handler) => {
1813
+ var _a;
1814
+ if (typeof handler.commandNameOrPattern === "string") {
1815
+ return handler.commandNameOrPattern.toLocaleLowerCase() === commandText;
1816
+ }
1817
+ else {
1818
+ return (_a = handler.commandNameOrPattern) === null || _a === void 0 ? void 0 : _a.test(commandText);
1819
+ }
1820
+ });
1821
+ return handlers;
1822
+ }
1823
+ getActivityText(activity) {
1824
+ let text = activity.text;
1825
+ const removedMentionText = botbuilder.TurnContext.removeRecipientMention(activity);
1826
+ if (removedMentionText) {
1827
+ text = removedMentionText
1828
+ .toLowerCase()
1829
+ .replace(/\n|\r\n/g, "")
1830
+ .trim();
1831
+ }
1832
+ return text;
1833
+ }
1834
+ }
1835
+
1836
+ // Copyright (c) Microsoft Corporation.
1837
+ /**
1838
+ * @internal
1839
+ */
1840
+ class LocalFileStorage {
1841
+ constructor(fileDir) {
1842
+ this.localFileName = ".notification.localstore.json";
1843
+ this.filePath = path__namespace.resolve(fileDir, this.localFileName);
1844
+ }
1845
+ read(key) {
1846
+ return tslib.__awaiter(this, void 0, void 0, function* () {
1847
+ if (!(yield this.storeFileExists())) {
1848
+ return undefined;
1849
+ }
1850
+ const data = yield this.readFromFile();
1851
+ return data[key];
1852
+ });
1853
+ }
1854
+ list() {
1855
+ return tslib.__awaiter(this, void 0, void 0, function* () {
1856
+ if (!(yield this.storeFileExists())) {
1857
+ return [];
1858
+ }
1859
+ const data = yield this.readFromFile();
1860
+ return Object.entries(data).map((entry) => entry[1]);
1861
+ });
1862
+ }
1863
+ write(key, object) {
1864
+ return tslib.__awaiter(this, void 0, void 0, function* () {
1865
+ if (!(yield this.storeFileExists())) {
1866
+ yield this.writeToFile({ [key]: object });
1867
+ return;
1868
+ }
1869
+ const data = yield this.readFromFile();
1870
+ yield this.writeToFile(Object.assign(data, { [key]: object }));
1871
+ });
1872
+ }
1873
+ delete(key) {
1874
+ return tslib.__awaiter(this, void 0, void 0, function* () {
1875
+ if (yield this.storeFileExists()) {
1876
+ const data = yield this.readFromFile();
1877
+ if (data[key] !== undefined) {
1878
+ delete data[key];
1879
+ yield this.writeToFile(data);
1880
+ }
1881
+ }
1882
+ });
1883
+ }
1884
+ storeFileExists() {
1885
+ return new Promise((resolve) => {
1886
+ try {
1887
+ fs__namespace.access(this.filePath, (err) => {
1888
+ if (err) {
1889
+ resolve(false);
1890
+ }
1891
+ else {
1892
+ resolve(true);
1893
+ }
1894
+ });
1895
+ }
1896
+ catch (error) {
1897
+ resolve(false);
1898
+ }
1899
+ });
1900
+ }
1901
+ readFromFile() {
1902
+ return new Promise((resolve, reject) => {
1903
+ try {
1904
+ fs__namespace.readFile(this.filePath, { encoding: "utf-8" }, (err, rawData) => {
1905
+ if (err) {
1906
+ reject(err);
1907
+ }
1908
+ else {
1909
+ resolve(JSON.parse(rawData));
1910
+ }
1911
+ });
1912
+ }
1913
+ catch (error) {
1914
+ reject(error);
1915
+ }
1916
+ });
1917
+ }
1918
+ writeToFile(data) {
1919
+ return tslib.__awaiter(this, void 0, void 0, function* () {
1920
+ return new Promise((resolve, reject) => {
1921
+ try {
1922
+ const rawData = JSON.stringify(data, undefined, 2);
1923
+ fs__namespace.writeFile(this.filePath, rawData, { encoding: "utf-8" }, (err) => {
1924
+ if (err) {
1925
+ reject(err);
1926
+ }
1927
+ else {
1928
+ resolve();
1929
+ }
1930
+ });
1931
+ }
1932
+ catch (error) {
1933
+ reject(error);
1934
+ }
1935
+ });
1936
+ });
1937
+ }
1938
+ }
1939
+ /**
1940
+ * @internal
1941
+ */
1942
+ class ConversationReferenceStore {
1943
+ constructor(storage) {
1944
+ this.storage = storage;
1945
+ }
1946
+ check(reference) {
1947
+ return tslib.__awaiter(this, void 0, void 0, function* () {
1948
+ const ref = yield this.storage.read(this.getKey(reference));
1949
+ return ref !== undefined;
1950
+ });
1951
+ }
1952
+ getAll() {
1953
+ return this.storage.list();
1954
+ }
1955
+ set(reference) {
1956
+ return this.storage.write(this.getKey(reference), reference);
1957
+ }
1958
+ delete(reference) {
1959
+ return this.storage.delete(this.getKey(reference));
1960
+ }
1961
+ getKey(reference) {
1962
+ var _a, _b;
1963
+ return `_${(_a = reference.conversation) === null || _a === void 0 ? void 0 : _a.tenantId}_${(_b = reference.conversation) === null || _b === void 0 ? void 0 : _b.id}`;
1964
+ }
1965
+ }
1966
+
1967
+ // Copyright (c) Microsoft Corporation.
1968
+ // Licensed under the MIT license.
1969
+ /**
1970
+ * @internal
1971
+ */
1972
+ function cloneConversation(conversation) {
1973
+ return Object.assign({}, conversation);
1974
+ }
1975
+ /**
1976
+ * @internal
1977
+ */
1978
+ function getTargetType(conversationReference) {
1979
+ var _a;
1980
+ const conversationType = (_a = conversationReference.conversation) === null || _a === void 0 ? void 0 : _a.conversationType;
1981
+ if (conversationType === "personal") {
1982
+ return "Person";
1983
+ }
1984
+ else if (conversationType === "groupChat") {
1985
+ return "Group";
1986
+ }
1987
+ else if (conversationType === "channel") {
1988
+ return "Channel";
1989
+ }
1990
+ else {
1991
+ return undefined;
1992
+ }
1993
+ }
1994
+ /**
1995
+ * @internal
1996
+ */
1997
+ function getTeamsBotInstallationId(context) {
1998
+ var _a, _b, _c, _d;
1999
+ 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;
2000
+ }
2001
+
2002
+ // Copyright (c) Microsoft Corporation.
2003
+ /**
2004
+ * Send a plain text message to a notification target.
2005
+ *
2006
+ * @param target - the notification target.
2007
+ * @param text - the plain text message.
2008
+ * @returns A `Promise` representing the asynchronous operation.
2009
+ *
2010
+ * @beta
2011
+ */
2012
+ function sendMessage(target, text) {
2013
+ return target.sendMessage(text);
2014
+ }
2015
+ /**
2016
+ * Send an adaptive card message to a notification target.
2017
+ *
2018
+ * @param target - the notification target.
2019
+ * @param card - the adaptive card raw JSON.
2020
+ * @returns A `Promise` representing the asynchronous operation.
2021
+ *
2022
+ * @beta
2023
+ */
2024
+ function sendAdaptiveCard(target, card) {
2025
+ return target.sendAdaptiveCard(card);
2026
+ }
2027
+ /**
2028
+ * A {@link NotificationTarget} that represents a team channel.
2029
+ *
2030
+ * @remarks
2031
+ * It's recommended to get channels from {@link TeamsBotInstallation.channels()}.
2032
+ *
2033
+ * @beta
2034
+ */
2035
+ class Channel {
2036
+ /**
2037
+ * Constuctor.
2038
+ *
2039
+ * @remarks
2040
+ * It's recommended to get channels from {@link TeamsBotInstallation.channels()}, instead of using this constructor.
2041
+ *
2042
+ * @param parent - The parent {@link TeamsBotInstallation} where this channel is created from.
2043
+ * @param info - Detailed channel information.
2044
+ *
2045
+ * @beta
2046
+ */
2047
+ constructor(parent, info) {
2048
+ /**
2049
+ * Notification target type. For channel it's always "Channel".
2050
+ *
2051
+ * @beta
2052
+ */
2053
+ this.type = "Channel";
2054
+ this.parent = parent;
2055
+ this.info = info;
2056
+ }
2057
+ /**
2058
+ * Send a plain text message.
2059
+ *
2060
+ * @param text - the plain text message.
2061
+ * @returns A `Promise` representing the asynchronous operation.
2062
+ *
2063
+ * @beta
2064
+ */
2065
+ sendMessage(text) {
2066
+ return this.parent.adapter.continueConversation(this.parent.conversationReference, (context) => tslib.__awaiter(this, void 0, void 0, function* () {
2067
+ const conversation = yield this.newConversation(context);
2068
+ yield this.parent.adapter.continueConversation(conversation, (ctx) => tslib.__awaiter(this, void 0, void 0, function* () {
2069
+ yield ctx.sendActivity(text);
2070
+ }));
2071
+ }));
2072
+ }
2073
+ /**
2074
+ * Send an adaptive card message.
2075
+ *
2076
+ * @param card - the adaptive card raw JSON.
2077
+ * @returns A `Promise` representing the asynchronous operation.
2078
+ *
2079
+ * @beta
2080
+ */
2081
+ sendAdaptiveCard(card) {
2082
+ return tslib.__awaiter(this, void 0, void 0, function* () {
2083
+ return this.parent.adapter.continueConversation(this.parent.conversationReference, (context) => tslib.__awaiter(this, void 0, void 0, function* () {
2084
+ const conversation = yield this.newConversation(context);
2085
+ yield this.parent.adapter.continueConversation(conversation, (ctx) => tslib.__awaiter(this, void 0, void 0, function* () {
2086
+ yield ctx.sendActivity({
2087
+ attachments: [botbuilder.CardFactory.adaptiveCard(card)],
2088
+ });
2089
+ }));
2090
+ }));
2091
+ });
2092
+ }
2093
+ /**
2094
+ * @internal
2095
+ */
2096
+ newConversation(context) {
2097
+ return tslib.__awaiter(this, void 0, void 0, function* () {
2098
+ const reference = botbuilder.TurnContext.getConversationReference(context.activity);
2099
+ const channelConversation = cloneConversation(reference);
2100
+ channelConversation.conversation.id = this.info.id || "";
2101
+ return channelConversation;
2102
+ });
2103
+ }
2104
+ }
2105
+ /**
2106
+ * A {@link NotificationTarget} that represents a team member.
2107
+ *
2108
+ * @remarks
2109
+ * It's recommended to get members from {@link TeamsBotInstallation.members()}.
2110
+ *
2111
+ * @beta
2112
+ */
2113
+ class Member {
2114
+ /**
2115
+ * Constuctor.
2116
+ *
2117
+ * @remarks
2118
+ * It's recommended to get members from {@link TeamsBotInstallation.members()}, instead of using this constructor.
2119
+ *
2120
+ * @param parent - The parent {@link TeamsBotInstallation} where this member is created from.
2121
+ * @param account - Detailed member account information.
2122
+ *
2123
+ * @beta
2124
+ */
2125
+ constructor(parent, account) {
2126
+ /**
2127
+ * Notification target type. For member it's always "Person".
2128
+ *
2129
+ * @beta
2130
+ */
2131
+ this.type = "Person";
2132
+ this.parent = parent;
2133
+ this.account = account;
2134
+ }
2135
+ /**
2136
+ * Send a plain text message.
2137
+ *
2138
+ * @param text - the plain text message.
2139
+ * @returns A `Promise` representing the asynchronous operation.
2140
+ *
2141
+ * @beta
2142
+ */
2143
+ sendMessage(text) {
2144
+ return this.parent.adapter.continueConversation(this.parent.conversationReference, (context) => tslib.__awaiter(this, void 0, void 0, function* () {
2145
+ const conversation = yield this.newConversation(context);
2146
+ yield this.parent.adapter.continueConversation(conversation, (ctx) => tslib.__awaiter(this, void 0, void 0, function* () {
2147
+ yield ctx.sendActivity(text);
2148
+ }));
2149
+ }));
2150
+ }
2151
+ /**
2152
+ * Send an adaptive card message.
2153
+ *
2154
+ * @param card - the adaptive card raw JSON.
2155
+ * @returns A `Promise` representing the asynchronous operation.
2156
+ *
2157
+ * @beta
2158
+ */
2159
+ sendAdaptiveCard(card) {
2160
+ return tslib.__awaiter(this, void 0, void 0, function* () {
2161
+ return this.parent.adapter.continueConversation(this.parent.conversationReference, (context) => tslib.__awaiter(this, void 0, void 0, function* () {
2162
+ const conversation = yield this.newConversation(context);
2163
+ yield this.parent.adapter.continueConversation(conversation, (ctx) => tslib.__awaiter(this, void 0, void 0, function* () {
2164
+ yield ctx.sendActivity({
2165
+ attachments: [botbuilder.CardFactory.adaptiveCard(card)],
2166
+ });
2167
+ }));
2168
+ }));
2169
+ });
2170
+ }
2171
+ /**
2172
+ * @internal
2173
+ */
2174
+ newConversation(context) {
2175
+ return tslib.__awaiter(this, void 0, void 0, function* () {
2176
+ const reference = botbuilder.TurnContext.getConversationReference(context.activity);
2177
+ const personalConversation = cloneConversation(reference);
2178
+ const connectorClient = context.turnState.get(this.parent.adapter.ConnectorClientKey);
2179
+ const conversation = yield connectorClient.conversations.createConversation({
2180
+ isGroup: false,
2181
+ tenantId: context.activity.conversation.tenantId,
2182
+ bot: context.activity.recipient,
2183
+ members: [this.account],
2184
+ channelData: {},
2185
+ });
2186
+ personalConversation.conversation.id = conversation.id;
2187
+ return personalConversation;
2188
+ });
2189
+ }
2190
+ }
2191
+ /**
2192
+ * A {@link NotificationTarget} that represents a bot installation. Teams Bot could be installed into
2193
+ * - Personal chat
2194
+ * - Group chat
2195
+ * - Team (by default the `General` channel)
2196
+ *
2197
+ * @remarks
2198
+ * It's recommended to get bot installations from {@link ConversationBot.installations()}.
2199
+ *
2200
+ * @beta
2201
+ */
2202
+ class TeamsBotInstallation {
2203
+ /**
2204
+ * Constructor
2205
+ *
2206
+ * @remarks
2207
+ * It's recommended to get bot installations from {@link ConversationBot.installations()}, instead of using this constructor.
2208
+ *
2209
+ * @param adapter - the bound `BotFrameworkAdapter`.
2210
+ * @param conversationReference - the bound `ConversationReference`.
2211
+ *
2212
+ * @beta
2213
+ */
2214
+ constructor(adapter, conversationReference) {
2215
+ this.adapter = adapter;
2216
+ this.conversationReference = conversationReference;
2217
+ this.type = getTargetType(conversationReference);
2218
+ }
2219
+ /**
2220
+ * Send a plain text message.
2221
+ *
2222
+ * @param text - the plain text message.
2223
+ * @returns A `Promise` representing the asynchronous operation.
2224
+ *
2225
+ * @beta
2226
+ */
2227
+ sendMessage(text) {
2228
+ return this.adapter.continueConversation(this.conversationReference, (context) => tslib.__awaiter(this, void 0, void 0, function* () {
2229
+ yield context.sendActivity(text);
2230
+ }));
2231
+ }
2232
+ /**
2233
+ * Send an adaptive card message.
2234
+ *
2235
+ * @param card - the adaptive card raw JSON.
2236
+ * @returns A `Promise` representing the asynchronous operation.
2237
+ *
2238
+ * @beta
2239
+ */
2240
+ sendAdaptiveCard(card) {
2241
+ return this.adapter.continueConversation(this.conversationReference, (context) => tslib.__awaiter(this, void 0, void 0, function* () {
2242
+ yield context.sendActivity({
2243
+ attachments: [botbuilder.CardFactory.adaptiveCard(card)],
2244
+ });
2245
+ }));
2246
+ }
2247
+ /**
2248
+ * Get channels from this bot installation.
2249
+ *
2250
+ * @returns an array of channels if bot is installed into a team, otherwise returns an empty array.
2251
+ *
2252
+ * @beta
2253
+ */
2254
+ channels() {
2255
+ return tslib.__awaiter(this, void 0, void 0, function* () {
2256
+ let teamsChannels = [];
2257
+ yield this.adapter.continueConversation(this.conversationReference, (context) => tslib.__awaiter(this, void 0, void 0, function* () {
2258
+ const teamId = getTeamsBotInstallationId(context);
2259
+ if (teamId !== undefined) {
2260
+ teamsChannels = yield botbuilder.TeamsInfo.getTeamChannels(context, teamId);
2261
+ }
2262
+ }));
2263
+ const channels = [];
2264
+ for (const channel of teamsChannels) {
2265
+ channels.push(new Channel(this, channel));
2266
+ }
2267
+ return channels;
2268
+ });
2269
+ }
2270
+ /**
2271
+ * Get members from this bot installation.
2272
+ *
2273
+ * @returns an array of members from where the bot is installed.
2274
+ *
2275
+ * @beta
2276
+ */
2277
+ members() {
2278
+ return tslib.__awaiter(this, void 0, void 0, function* () {
2279
+ const members = [];
2280
+ yield this.adapter.continueConversation(this.conversationReference, (context) => tslib.__awaiter(this, void 0, void 0, function* () {
2281
+ let continuationToken;
2282
+ do {
2283
+ const pagedMembers = yield botbuilder.TeamsInfo.getPagedMembers(context, undefined, continuationToken);
2284
+ continuationToken = pagedMembers.continuationToken;
2285
+ for (const member of pagedMembers.members) {
2286
+ members.push(new Member(this, member));
2287
+ }
2288
+ } while (continuationToken !== undefined);
2289
+ }));
2290
+ return members;
2291
+ });
2292
+ }
2293
+ }
2294
+ /**
2295
+ * Provide static utilities for bot conversation, including
2296
+ * - send notification to varies targets (e.g., member, channel, incoming wehbook)
2297
+ * - handle command and response.
2298
+ *
2299
+ * @example
2300
+ * Here's an example on how to send notification via Teams Bot.
2301
+ * ```typescript
2302
+ * // initialize (it's recommended to be called before handling any bot message)
2303
+ * const notificationBot = new NotificationBot(adapter);
2304
+ *
2305
+ * // get all bot installations and send message
2306
+ * for (const target of await notificationBot.installations()) {
2307
+ * await target.sendMessage("Hello Notification");
2308
+ * }
2309
+ *
2310
+ * // alternative - send message to all members
2311
+ * for (const target of await notificationBot.installations()) {
2312
+ * for (const member of await target.members()) {
2313
+ * await member.sendMessage("Hello Notification");
2314
+ * }
2315
+ * }
2316
+ * ```
2317
+ *
2318
+ * @beta
2319
+ */
2320
+ class NotificationBot {
2321
+ /**
2322
+ * constructor of the notification bot.
2323
+ *
2324
+ * @remarks
2325
+ * To ensure accuracy, it's recommended to initialize before handling any message.
2326
+ *
2327
+ * @param adapter - the bound `BotFrameworkAdapter`
2328
+ * @param options - initialize options
2329
+ *
2330
+ * @beta
2331
+ */
2332
+ constructor(adapter, options) {
2333
+ var _a, _b;
2334
+ 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 : "./" : "./"));
2335
+ this.conversationReferenceStore = new ConversationReferenceStore(storage);
2336
+ this.adapter = adapter.use(new NotificationMiddleware({
2337
+ conversationReferenceStore: this.conversationReferenceStore,
2338
+ }));
2339
+ }
2340
+ /**
2341
+ * Get all targets where the bot is installed.
2342
+ *
2343
+ * @remarks
2344
+ * The result is retrieving from the persisted storage.
2345
+ *
2346
+ * @returns - an array of {@link TeamsBotInstallation}.
2347
+ *
2348
+ * @beta
2349
+ */
2350
+ installations() {
2351
+ return tslib.__awaiter(this, void 0, void 0, function* () {
2352
+ if (this.conversationReferenceStore === undefined || this.adapter === undefined) {
2353
+ throw new Error("NotificationBot has not been initialized.");
2354
+ }
2355
+ const references = (yield this.conversationReferenceStore.getAll()).values();
2356
+ const targets = [];
2357
+ for (const reference of references) {
2358
+ // validate connection
2359
+ let valid = true;
2360
+ this.adapter.continueConversation(reference, (context) => tslib.__awaiter(this, void 0, void 0, function* () {
2361
+ try {
2362
+ // try get member to see if the installation is still valid
2363
+ yield botbuilder.TeamsInfo.getPagedMembers(context, 1);
2364
+ }
2365
+ catch (error) {
2366
+ if (error.code === "BotNotInConversationRoster") {
2367
+ valid = false;
2368
+ }
2369
+ }
2370
+ }));
2371
+ if (valid) {
2372
+ targets.push(new TeamsBotInstallation(this.adapter, reference));
2373
+ }
2374
+ else {
2375
+ this.conversationReferenceStore.delete(reference);
2376
+ }
2377
+ }
2378
+ return targets;
2379
+ });
2380
+ }
2381
+ }
2382
+
2383
+ // Copyright (c) Microsoft Corporation.
2384
+ /**
2385
+ * A command bot for receiving commands and sending responses in Teams.
2386
+ *
2387
+ * @remarks
2388
+ * 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.
2389
+ *
2390
+ * @example
2391
+ * You can register your commands through the constructor of the {@link CommandBot}, or use the `registerCommand` and `registerCommands` API to add commands after creating the `CommandBot` instance.
2392
+ *
2393
+ * ```typescript
2394
+ * // register through constructor
2395
+ * const commandBot = new CommandBot(adapter, [ new HelloWorldCommandHandler() ]);
2396
+ *
2397
+ * // register through `register*` API
2398
+ * commandBot.registerCommand(new HelpCommandHandler());
2399
+ * ```
2400
+ *
2401
+ * @beta
2402
+ */
2403
+ class CommandBot {
2404
+ /**
2405
+ * Creates a new instance of the `CommandBot`.
2406
+ *
2407
+ * @param adapter The bound `BotFrameworkAdapter`.
2408
+ * @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.
2409
+ *
2410
+ * @beta
2411
+ */
2412
+ constructor(adapter, commands) {
2413
+ this.middleware = new CommandResponseMiddleware(commands);
2414
+ this.adapter = adapter.use(this.middleware);
2415
+ }
2416
+ /**
2417
+ * Registers a command into the command bot.
2418
+ *
2419
+ * @param command The command to registered.
2420
+ *
2421
+ * @beta
2422
+ */
2423
+ registerCommand(command) {
2424
+ if (command) {
2425
+ this.middleware.commandHandlers.push(command);
2426
+ }
2427
+ }
2428
+ /**
2429
+ * Registers commands into the command bot.
2430
+ *
2431
+ * @param commands The command to registered.
2432
+ *
2433
+ * @beta
2434
+ */
2435
+ registerCommands(commands) {
2436
+ if (commands) {
2437
+ this.middleware.commandHandlers.push(...commands);
2438
+ }
2439
+ }
2440
+ }
2441
+
2442
+ // Copyright (c) Microsoft Corporation.
2443
+ const { AdaptiveCards } = require("@microsoft/adaptivecards-tools");
2444
+ /**
2445
+ * Provides utility method to build bot message with cards that supported in Teams.
2446
+ */
2447
+ class MessageBuilder {
2448
+ /**
2449
+ * Build a bot message activity attached with adaptive card.
2450
+ *
2451
+ * @param getCardData Function to prepare your card data.
2452
+ * @param cardTemplate The adaptive card template.
2453
+ * @returns A bot message activity attached with an adaptive card.
2454
+ *
2455
+ * @example
2456
+ * ```javascript
2457
+ * const cardTemplate = {
2458
+ * type: "AdaptiveCard",
2459
+ * body: [
2460
+ * {
2461
+ * "type": "TextBlock",
2462
+ * "text": "${title}",
2463
+ * "size": "Large"
2464
+ * },
2465
+ * {
2466
+ * "type": "TextBlock",
2467
+ * "text": "${description}"
2468
+ * }],
2469
+ * $schema: "http://adaptivecards.io/schemas/adaptive-card.json",
2470
+ * version: "1.4"
2471
+ * };
2472
+ *
2473
+ * type CardData = {
2474
+ * title: string,
2475
+ * description: string
2476
+ * };
2477
+ * const card = MessageBuilder.attachAdaptiveCard<CardData>(() => {
2478
+ * return {
2479
+ * title: "sample card title",
2480
+ * description: "sample card description"
2481
+ * }}, cardTemplate);
2482
+ * ```
2483
+ *
2484
+ * @beta
2485
+ */
2486
+ static attachAdaptiveCard(getCardData, cardTemplate) {
2487
+ const cardData = getCardData();
2488
+ return {
2489
+ attachments: [botbuilder.CardFactory.adaptiveCard(AdaptiveCards.declare(cardTemplate).render(cardData))],
2490
+ };
2491
+ }
2492
+ /**
2493
+ * Build a bot message activity attached with an adaptive card.
2494
+ *
2495
+ * @param card The adaptive card content.
2496
+ * @returns A bot message activity attached with an adaptive card.
2497
+ *
2498
+ * @beta
2499
+ */
2500
+ static attachAdaptiveCardWithoutData(card) {
2501
+ return {
2502
+ attachments: [botbuilder.CardFactory.adaptiveCard(AdaptiveCards.declareWithoutData(card).render())],
2503
+ };
2504
+ }
2505
+ /**
2506
+ * Build a bot message activity attached with an hero card.
2507
+ *
2508
+ * @param title The card title.
2509
+ * @param images Optional. The array of images to include on the card.
2510
+ * @param buttons Optional. The array of buttons to include on the card. Each `string` in the array
2511
+ * is converted to an `imBack` button with a title and value set to the value of the string.
2512
+ * @param other Optional. Any additional properties to include on the card.
2513
+ *
2514
+ * @returns A bot message activity attached with a hero card.
2515
+ *
2516
+ * @example
2517
+ * ```javascript
2518
+ * const message = MessageBuilder.attachHeroCard(
2519
+ * 'sample title',
2520
+ * ['https://example.com/sample.jpg'],
2521
+ * ['action']
2522
+ * );
2523
+ * ```
2524
+ *
2525
+ * @beta
2526
+ */
2527
+ static attachHeroCard(title, images, buttons, other) {
2528
+ return MessageBuilder.attachContent(botbuilder.CardFactory.heroCard(title, images, buttons, other));
2529
+ }
2530
+ /**
2531
+ * Returns an attachment for a sign-in card.
2532
+ *
2533
+ * @param title The title for the card's sign-in button.
2534
+ * @param url The URL of the sign-in page to use.
2535
+ * @param text Optional. Additional text to include on the card.
2536
+ *
2537
+ * @returns A bot message activity attached with a sign-in card.
2538
+ *
2539
+ * @remarks
2540
+ * For channels that don't natively support sign-in cards, an alternative message is rendered.
2541
+ *
2542
+ * @beta
2543
+ */
2544
+ static attachSigninCard(title, url, text) {
2545
+ return MessageBuilder.attachContent(botbuilder.CardFactory.signinCard(title, url, text));
2546
+ }
2547
+ /**
2548
+ * Build a bot message activity attached with an Office 365 connector card.
2549
+ *
2550
+ * @param card A description of the Office 365 connector card.
2551
+ * @returns A bot message activity attached with an Office 365 connector card.
2552
+ *
2553
+ * @beta
2554
+ */
2555
+ static attachO365ConnectorCard(card) {
2556
+ return MessageBuilder.attachContent(botbuilder.CardFactory.o365ConnectorCard(card));
2557
+ }
2558
+ /**
2559
+ * Build a message activity attached with a receipt card.
2560
+ * @param card A description of the receipt card.
2561
+ * @returns A message activity attached with a receipt card.
2562
+ *
2563
+ * @beta
2564
+ */
2565
+ static AttachReceiptCard(card) {
2566
+ return MessageBuilder.attachContent(botbuilder.CardFactory.receiptCard(card));
2567
+ }
2568
+ /**
2569
+ *
2570
+ * @param title The card title.
2571
+ * @param images Optional. The array of images to include on the card.
2572
+ * @param buttons Optional. The array of buttons to include on the card. Each `string` in the array
2573
+ * is converted to an `imBack` button with a title and value set to the value of the string.
2574
+ * @param other Optional. Any additional properties to include on the card.
2575
+ * @returns A message activity attached with a thumbnail card
2576
+ *
2577
+ * @beta
2578
+ */
2579
+ static attachThumbnailCard(title, images, buttons, other) {
2580
+ return MessageBuilder.attachContent(botbuilder.CardFactory.thumbnailCard(title, images, buttons, other));
2581
+ }
2582
+ /**
2583
+ * Add an attachement to a bot activity.
2584
+ * @param attachement The attachment object to attach.
2585
+ * @returns A message activity with an attachment.
2586
+ *
2587
+ * @beta
2588
+ */
2589
+ static attachContent(attachement) {
2590
+ return {
2591
+ attachments: [attachement],
2592
+ };
2593
+ }
2594
+ }
2595
+
1605
2596
  exports.AppCredential = AppCredential;
2597
+ exports.BearerTokenAuthProvider = BearerTokenAuthProvider;
2598
+ exports.Channel = Channel;
2599
+ exports.CommandBot = CommandBot;
1606
2600
  exports.ErrorWithCode = ErrorWithCode;
2601
+ exports.Member = Member;
2602
+ exports.MessageBuilder = MessageBuilder;
1607
2603
  exports.MsGraphAuthProvider = MsGraphAuthProvider;
2604
+ exports.NotificationBot = NotificationBot;
1608
2605
  exports.OnBehalfOfUserCredential = OnBehalfOfUserCredential;
2606
+ exports.TeamsBotInstallation = TeamsBotInstallation;
1609
2607
  exports.TeamsBotSsoPrompt = TeamsBotSsoPrompt;
1610
2608
  exports.TeamsFx = TeamsFx;
1611
2609
  exports.TeamsUserCredential = TeamsUserCredential;
2610
+ exports.createApiClient = createApiClient;
1612
2611
  exports.createMicrosoftGraphClient = createMicrosoftGraphClient;
1613
2612
  exports.getLogLevel = getLogLevel;
1614
2613
  exports.getTediousConnectionConfig = getTediousConnectionConfig;
2614
+ exports.sendAdaptiveCard = sendAdaptiveCard;
2615
+ exports.sendMessage = sendMessage;
1615
2616
  exports.setLogFunction = setLogFunction;
1616
2617
  exports.setLogLevel = setLogLevel;
1617
2618
  exports.setLogger = setLogger;