@microsoft/teamsfx 0.6.2 → 0.6.3-alpha.768a76f6e.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.
@@ -3,9 +3,12 @@ import { ConfidentialClientApplication } from '@azure/msal-node';
3
3
  import { createHash } from 'crypto';
4
4
  import { Client } from '@microsoft/microsoft-graph-client';
5
5
  import { ManagedIdentityCredential } from '@azure/identity';
6
- import { ActivityTypes, Channels, TeamsInfo, CardFactory, ActionTypes, MessageFactory, StatusCodes, verifyStateOperationName, tokenExchangeOperationName } from 'botbuilder';
6
+ import { ActivityTypes, Channels, TeamsInfo, CardFactory, ActionTypes, MessageFactory, StatusCodes, verifyStateOperationName, tokenExchangeOperationName, TurnContext, BotFrameworkAdapter } from 'botbuilder';
7
7
  import { Dialog } from 'botbuilder-dialogs';
8
8
  import { v4 } from 'uuid';
9
+ import axios from 'axios';
10
+ import * as path from 'path';
11
+ import * as fs from 'fs';
9
12
 
10
13
  // Copyright (c) Microsoft Corporation.
11
14
  // Licensed under the MIT license.
@@ -1385,6 +1388,69 @@ class TeamsBotSsoPrompt extends Dialog {
1385
1388
  }
1386
1389
  }
1387
1390
 
1391
+ // Copyright (c) Microsoft Corporation.
1392
+ /**
1393
+ * Initializes new Axios instance with specific auth provider
1394
+ *
1395
+ * @param apiEndpoint - Base url of the API
1396
+ * @param authProvider - Auth provider that injects authentication info to each request
1397
+ * @returns axios instance configured with specfic auth provider
1398
+ *
1399
+ * @example
1400
+ * ```typescript
1401
+ * const client = createApiClient("https://my-api-endpoint-base-url", new BasicAuthProvider("xxx","xxx"));
1402
+ * ```
1403
+ *
1404
+ * @beta
1405
+ */
1406
+ function createApiClient(apiEndpoint, authProvider) {
1407
+ // Add a request interceptor
1408
+ const instance = axios.create({
1409
+ baseURL: apiEndpoint,
1410
+ });
1411
+ instance.interceptors.request.use(async function (config) {
1412
+ return await authProvider.AddAuthenticationInfo(config);
1413
+ });
1414
+ return instance;
1415
+ }
1416
+
1417
+ // Copyright (c) Microsoft Corporation.
1418
+ // Licensed under the MIT license.
1419
+ /**
1420
+ * Provider that handles Bearer Token authentication
1421
+ *
1422
+ * @beta
1423
+ */
1424
+ class BearerTokenAuthProvider {
1425
+ /**
1426
+ * @param getToken Function that returns the content of bearer token used in http request
1427
+ *
1428
+ * @beta
1429
+ */
1430
+ constructor(getToken) {
1431
+ this.getToken = getToken;
1432
+ }
1433
+ /**
1434
+ * Adds authentication info to http requests
1435
+ *
1436
+ * @param config - Contains all the request information and can be updated to include extra authentication info.
1437
+ * Refer https://axios-http.com/docs/req_config for detailed document.
1438
+ *
1439
+ * @beta
1440
+ */
1441
+ async AddAuthenticationInfo(config) {
1442
+ const token = await this.getToken();
1443
+ if (!config.headers) {
1444
+ config.headers = {};
1445
+ }
1446
+ if (config.headers["Authorization"]) {
1447
+ throw new Error("Authorization header already exists!");
1448
+ }
1449
+ config.headers["Authorization"] = `Bearer ${token}`;
1450
+ return config;
1451
+ }
1452
+ }
1453
+
1388
1454
  // Copyright (c) Microsoft Corporation.
1389
1455
  /**
1390
1456
  * A class providing credential and configuration.
@@ -1567,5 +1633,982 @@ class TeamsFx {
1567
1633
  }
1568
1634
  }
1569
1635
 
1570
- export { AppCredential, ErrorCode, ErrorWithCode, IdentityType, LogLevel, MsGraphAuthProvider, OnBehalfOfUserCredential, TeamsBotSsoPrompt, TeamsFx, TeamsUserCredential, createMicrosoftGraphClient, getLogLevel, getTediousConnectionConfig, setLogFunction, setLogLevel, setLogger };
1636
+ // Copyright (c) Microsoft Corporation.
1637
+ /**
1638
+ * @internal
1639
+ */
1640
+ var ActivityType;
1641
+ (function (ActivityType) {
1642
+ ActivityType[ActivityType["CurrentBotInstalled"] = 0] = "CurrentBotInstalled";
1643
+ ActivityType[ActivityType["CurrentBotMessaged"] = 1] = "CurrentBotMessaged";
1644
+ ActivityType[ActivityType["CurrentBotUninstalled"] = 2] = "CurrentBotUninstalled";
1645
+ ActivityType[ActivityType["TeamDeleted"] = 3] = "TeamDeleted";
1646
+ ActivityType[ActivityType["TeamRestored"] = 4] = "TeamRestored";
1647
+ ActivityType[ActivityType["Unknown"] = 5] = "Unknown";
1648
+ })(ActivityType || (ActivityType = {}));
1649
+ /**
1650
+ * @internal
1651
+ */
1652
+ class NotificationMiddleware {
1653
+ constructor(options) {
1654
+ this.conversationReferenceStore = options.conversationReferenceStore;
1655
+ }
1656
+ async onTurn(context, next) {
1657
+ const type = this.classifyActivity(context.activity);
1658
+ switch (type) {
1659
+ case ActivityType.CurrentBotInstalled:
1660
+ case ActivityType.TeamRestored: {
1661
+ const reference = TurnContext.getConversationReference(context.activity);
1662
+ await this.conversationReferenceStore.set(reference);
1663
+ break;
1664
+ }
1665
+ case ActivityType.CurrentBotMessaged: {
1666
+ const reference = TurnContext.getConversationReference(context.activity);
1667
+ if (!(await this.conversationReferenceStore.check(reference))) {
1668
+ await this.conversationReferenceStore.set(reference);
1669
+ }
1670
+ break;
1671
+ }
1672
+ case ActivityType.CurrentBotUninstalled:
1673
+ case ActivityType.TeamDeleted: {
1674
+ const reference = TurnContext.getConversationReference(context.activity);
1675
+ await this.conversationReferenceStore.delete(reference);
1676
+ break;
1677
+ }
1678
+ }
1679
+ await next();
1680
+ }
1681
+ classifyActivity(activity) {
1682
+ var _a, _b;
1683
+ const activityType = activity.type;
1684
+ if (activityType === "installationUpdate") {
1685
+ const action = (_a = activity.action) === null || _a === void 0 ? void 0 : _a.toLowerCase();
1686
+ if (action === "add") {
1687
+ return ActivityType.CurrentBotInstalled;
1688
+ }
1689
+ else {
1690
+ return ActivityType.CurrentBotUninstalled;
1691
+ }
1692
+ }
1693
+ else if (activityType === "message") {
1694
+ return ActivityType.CurrentBotMessaged;
1695
+ }
1696
+ else if (activityType === "conversationUpdate") {
1697
+ const eventType = (_b = activity.channelData) === null || _b === void 0 ? void 0 : _b.eventType;
1698
+ if (eventType === "teamDeleted") {
1699
+ return ActivityType.TeamDeleted;
1700
+ }
1701
+ else if (eventType === "teamRestored") {
1702
+ return ActivityType.TeamRestored;
1703
+ }
1704
+ }
1705
+ return ActivityType.Unknown;
1706
+ }
1707
+ }
1708
+ class CommandResponseMiddleware {
1709
+ constructor(handlers) {
1710
+ this.commandHandlers = [];
1711
+ if (handlers && handlers.length > 0) {
1712
+ this.commandHandlers.push(...handlers);
1713
+ }
1714
+ }
1715
+ async onTurn(context, next) {
1716
+ const type = this.classifyActivity(context.activity);
1717
+ switch (type) {
1718
+ case ActivityType.CurrentBotMessaged:
1719
+ // Invoke corresponding command handler for the command response
1720
+ const commandText = this.getActivityText(context.activity);
1721
+ const message = {
1722
+ text: commandText,
1723
+ };
1724
+ for (const handler of this.commandHandlers) {
1725
+ const matchResult = this.shouldTrigger(handler.triggerPatterns, commandText);
1726
+ // It is important to note that the command bot will stop processing handlers
1727
+ // when the first command handler is matched.
1728
+ if (!!matchResult) {
1729
+ message.matches = Array.isArray(matchResult) ? matchResult : void 0;
1730
+ const response = await handler.handleCommandReceived(context, message);
1731
+ await context.sendActivity(response);
1732
+ break;
1733
+ }
1734
+ }
1735
+ break;
1736
+ }
1737
+ await next();
1738
+ }
1739
+ classifyActivity(activity) {
1740
+ if (activity.type === ActivityTypes.Message) {
1741
+ return ActivityType.CurrentBotMessaged;
1742
+ }
1743
+ return ActivityType.Unknown;
1744
+ }
1745
+ matchPattern(pattern, text) {
1746
+ if (text) {
1747
+ if (typeof pattern === "string") {
1748
+ const regExp = new RegExp(pattern, "i");
1749
+ return regExp.test(text);
1750
+ }
1751
+ if (pattern instanceof RegExp) {
1752
+ const matches = text.match(pattern);
1753
+ return matches !== null && matches !== void 0 ? matches : false;
1754
+ }
1755
+ }
1756
+ return false;
1757
+ }
1758
+ shouldTrigger(patterns, text) {
1759
+ const expressions = Array.isArray(patterns) ? patterns : [patterns];
1760
+ for (const ex of expressions) {
1761
+ const arg = this.matchPattern(ex, text);
1762
+ if (arg)
1763
+ return arg;
1764
+ }
1765
+ return false;
1766
+ }
1767
+ getActivityText(activity) {
1768
+ let text = activity.text;
1769
+ const removedMentionText = TurnContext.removeRecipientMention(activity);
1770
+ if (removedMentionText) {
1771
+ text = removedMentionText
1772
+ .toLowerCase()
1773
+ .replace(/\n|\r\n/g, "")
1774
+ .trim();
1775
+ }
1776
+ return text;
1777
+ }
1778
+ }
1779
+
1780
+ // Copyright (c) Microsoft Corporation.
1781
+ /**
1782
+ * A command bot for receiving commands and sending responses in Teams.
1783
+ *
1784
+ * @remarks
1785
+ * 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.
1786
+ *
1787
+ * @beta
1788
+ */
1789
+ class CommandBot {
1790
+ /**
1791
+ * Creates a new instance of the `CommandBot`.
1792
+ *
1793
+ * @param adapter The bound `BotFrameworkAdapter`.
1794
+ * @param options - initialize options
1795
+ *
1796
+ * @beta
1797
+ */
1798
+ constructor(adapter, options) {
1799
+ this.middleware = new CommandResponseMiddleware(options === null || options === void 0 ? void 0 : options.commands);
1800
+ this.adapter = adapter.use(this.middleware);
1801
+ }
1802
+ /**
1803
+ * Registers a command into the command bot.
1804
+ *
1805
+ * @param command The command to registered.
1806
+ *
1807
+ * @beta
1808
+ */
1809
+ registerCommand(command) {
1810
+ if (command) {
1811
+ this.middleware.commandHandlers.push(command);
1812
+ }
1813
+ }
1814
+ /**
1815
+ * Registers commands into the command bot.
1816
+ *
1817
+ * @param commands The command to registered.
1818
+ *
1819
+ * @beta
1820
+ */
1821
+ registerCommands(commands) {
1822
+ if (commands) {
1823
+ this.middleware.commandHandlers.push(...commands);
1824
+ }
1825
+ }
1826
+ }
1827
+
1828
+ // Copyright (c) Microsoft Corporation.
1829
+ /**
1830
+ * @internal
1831
+ */
1832
+ class LocalFileStorage {
1833
+ constructor(fileDir) {
1834
+ this.localFileName = ".notification.localstore.json";
1835
+ this.filePath = path.resolve(fileDir, this.localFileName);
1836
+ }
1837
+ async read(key) {
1838
+ if (!(await this.storeFileExists())) {
1839
+ return undefined;
1840
+ }
1841
+ const data = await this.readFromFile();
1842
+ return data[key];
1843
+ }
1844
+ async list() {
1845
+ if (!(await this.storeFileExists())) {
1846
+ return [];
1847
+ }
1848
+ const data = await this.readFromFile();
1849
+ return Object.entries(data).map((entry) => entry[1]);
1850
+ }
1851
+ async write(key, object) {
1852
+ if (!(await this.storeFileExists())) {
1853
+ await this.writeToFile({ [key]: object });
1854
+ return;
1855
+ }
1856
+ const data = await this.readFromFile();
1857
+ await this.writeToFile(Object.assign(data, { [key]: object }));
1858
+ }
1859
+ async delete(key) {
1860
+ if (await this.storeFileExists()) {
1861
+ const data = await this.readFromFile();
1862
+ if (data[key] !== undefined) {
1863
+ delete data[key];
1864
+ await this.writeToFile(data);
1865
+ }
1866
+ }
1867
+ }
1868
+ storeFileExists() {
1869
+ return new Promise((resolve) => {
1870
+ try {
1871
+ fs.access(this.filePath, (err) => {
1872
+ if (err) {
1873
+ resolve(false);
1874
+ }
1875
+ else {
1876
+ resolve(true);
1877
+ }
1878
+ });
1879
+ }
1880
+ catch (error) {
1881
+ resolve(false);
1882
+ }
1883
+ });
1884
+ }
1885
+ readFromFile() {
1886
+ return new Promise((resolve, reject) => {
1887
+ try {
1888
+ fs.readFile(this.filePath, { encoding: "utf-8" }, (err, rawData) => {
1889
+ if (err) {
1890
+ reject(err);
1891
+ }
1892
+ else {
1893
+ resolve(JSON.parse(rawData));
1894
+ }
1895
+ });
1896
+ }
1897
+ catch (error) {
1898
+ reject(error);
1899
+ }
1900
+ });
1901
+ }
1902
+ async writeToFile(data) {
1903
+ return new Promise((resolve, reject) => {
1904
+ try {
1905
+ const rawData = JSON.stringify(data, undefined, 2);
1906
+ fs.writeFile(this.filePath, rawData, { encoding: "utf-8" }, (err) => {
1907
+ if (err) {
1908
+ reject(err);
1909
+ }
1910
+ else {
1911
+ resolve();
1912
+ }
1913
+ });
1914
+ }
1915
+ catch (error) {
1916
+ reject(error);
1917
+ }
1918
+ });
1919
+ }
1920
+ }
1921
+ /**
1922
+ * @internal
1923
+ */
1924
+ class ConversationReferenceStore {
1925
+ constructor(storage) {
1926
+ this.storage = storage;
1927
+ }
1928
+ async check(reference) {
1929
+ const ref = await this.storage.read(this.getKey(reference));
1930
+ return ref !== undefined;
1931
+ }
1932
+ getAll() {
1933
+ return this.storage.list();
1934
+ }
1935
+ set(reference) {
1936
+ return this.storage.write(this.getKey(reference), reference);
1937
+ }
1938
+ delete(reference) {
1939
+ return this.storage.delete(this.getKey(reference));
1940
+ }
1941
+ getKey(reference) {
1942
+ var _a, _b;
1943
+ return `_${(_a = reference.conversation) === null || _a === void 0 ? void 0 : _a.tenantId}_${(_b = reference.conversation) === null || _b === void 0 ? void 0 : _b.id}`;
1944
+ }
1945
+ }
1946
+
1947
+ // Copyright (c) Microsoft Corporation.
1948
+ // Licensed under the MIT license.
1949
+ /**
1950
+ * @internal
1951
+ */
1952
+ function cloneConversation(conversation) {
1953
+ return Object.assign({}, conversation);
1954
+ }
1955
+ /**
1956
+ * @internal
1957
+ */
1958
+ function getTargetType(conversationReference) {
1959
+ var _a;
1960
+ const conversationType = (_a = conversationReference.conversation) === null || _a === void 0 ? void 0 : _a.conversationType;
1961
+ if (conversationType === "personal") {
1962
+ return "Person";
1963
+ }
1964
+ else if (conversationType === "groupChat") {
1965
+ return "Group";
1966
+ }
1967
+ else if (conversationType === "channel") {
1968
+ return "Channel";
1969
+ }
1970
+ else {
1971
+ return undefined;
1972
+ }
1973
+ }
1974
+ /**
1975
+ * @internal
1976
+ */
1977
+ function getTeamsBotInstallationId(context) {
1978
+ var _a, _b, _c, _d;
1979
+ 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;
1980
+ }
1981
+
1982
+ // Copyright (c) Microsoft Corporation.
1983
+ /**
1984
+ * Send a plain text message to a notification target.
1985
+ *
1986
+ * @param target - the notification target.
1987
+ * @param text - the plain text message.
1988
+ * @returns A `Promise` representing the asynchronous operation.
1989
+ *
1990
+ * @beta
1991
+ */
1992
+ function sendMessage(target, text) {
1993
+ return target.sendMessage(text);
1994
+ }
1995
+ /**
1996
+ * Send an adaptive card message to a notification target.
1997
+ *
1998
+ * @param target - the notification target.
1999
+ * @param card - the adaptive card raw JSON.
2000
+ * @returns A `Promise` representing the asynchronous operation.
2001
+ *
2002
+ * @beta
2003
+ */
2004
+ function sendAdaptiveCard(target, card) {
2005
+ return target.sendAdaptiveCard(card);
2006
+ }
2007
+ /**
2008
+ * A {@link NotificationTarget} that represents a team channel.
2009
+ *
2010
+ * @remarks
2011
+ * It's recommended to get channels from {@link TeamsBotInstallation.channels()}.
2012
+ *
2013
+ * @beta
2014
+ */
2015
+ class Channel {
2016
+ /**
2017
+ * Constuctor.
2018
+ *
2019
+ * @remarks
2020
+ * It's recommended to get channels from {@link TeamsBotInstallation.channels()}, instead of using this constructor.
2021
+ *
2022
+ * @param parent - The parent {@link TeamsBotInstallation} where this channel is created from.
2023
+ * @param info - Detailed channel information.
2024
+ *
2025
+ * @beta
2026
+ */
2027
+ constructor(parent, info) {
2028
+ /**
2029
+ * Notification target type. For channel it's always "Channel".
2030
+ *
2031
+ * @beta
2032
+ */
2033
+ this.type = "Channel";
2034
+ this.parent = parent;
2035
+ this.info = info;
2036
+ }
2037
+ /**
2038
+ * Send a plain text message.
2039
+ *
2040
+ * @param text - the plain text message.
2041
+ * @returns A `Promise` representing the asynchronous operation.
2042
+ *
2043
+ * @beta
2044
+ */
2045
+ sendMessage(text) {
2046
+ return this.parent.adapter.continueConversation(this.parent.conversationReference, async (context) => {
2047
+ const conversation = await this.newConversation(context);
2048
+ await this.parent.adapter.continueConversation(conversation, async (ctx) => {
2049
+ await ctx.sendActivity(text);
2050
+ });
2051
+ });
2052
+ }
2053
+ /**
2054
+ * Send an adaptive card message.
2055
+ *
2056
+ * @param card - the adaptive card raw JSON.
2057
+ * @returns A `Promise` representing the asynchronous operation.
2058
+ *
2059
+ * @beta
2060
+ */
2061
+ async sendAdaptiveCard(card) {
2062
+ return this.parent.adapter.continueConversation(this.parent.conversationReference, async (context) => {
2063
+ const conversation = await this.newConversation(context);
2064
+ await this.parent.adapter.continueConversation(conversation, async (ctx) => {
2065
+ await ctx.sendActivity({
2066
+ attachments: [CardFactory.adaptiveCard(card)],
2067
+ });
2068
+ });
2069
+ });
2070
+ }
2071
+ /**
2072
+ * @internal
2073
+ */
2074
+ async newConversation(context) {
2075
+ const reference = TurnContext.getConversationReference(context.activity);
2076
+ const channelConversation = cloneConversation(reference);
2077
+ channelConversation.conversation.id = this.info.id || "";
2078
+ return channelConversation;
2079
+ }
2080
+ }
2081
+ /**
2082
+ * A {@link NotificationTarget} that represents a team member.
2083
+ *
2084
+ * @remarks
2085
+ * It's recommended to get members from {@link TeamsBotInstallation.members()}.
2086
+ *
2087
+ * @beta
2088
+ */
2089
+ class Member {
2090
+ /**
2091
+ * Constuctor.
2092
+ *
2093
+ * @remarks
2094
+ * It's recommended to get members from {@link TeamsBotInstallation.members()}, instead of using this constructor.
2095
+ *
2096
+ * @param parent - The parent {@link TeamsBotInstallation} where this member is created from.
2097
+ * @param account - Detailed member account information.
2098
+ *
2099
+ * @beta
2100
+ */
2101
+ constructor(parent, account) {
2102
+ /**
2103
+ * Notification target type. For member it's always "Person".
2104
+ *
2105
+ * @beta
2106
+ */
2107
+ this.type = "Person";
2108
+ this.parent = parent;
2109
+ this.account = account;
2110
+ }
2111
+ /**
2112
+ * Send a plain text message.
2113
+ *
2114
+ * @param text - the plain text message.
2115
+ * @returns A `Promise` representing the asynchronous operation.
2116
+ *
2117
+ * @beta
2118
+ */
2119
+ sendMessage(text) {
2120
+ return this.parent.adapter.continueConversation(this.parent.conversationReference, async (context) => {
2121
+ const conversation = await this.newConversation(context);
2122
+ await this.parent.adapter.continueConversation(conversation, async (ctx) => {
2123
+ await ctx.sendActivity(text);
2124
+ });
2125
+ });
2126
+ }
2127
+ /**
2128
+ * Send an adaptive card message.
2129
+ *
2130
+ * @param card - the adaptive card raw JSON.
2131
+ * @returns A `Promise` representing the asynchronous operation.
2132
+ *
2133
+ * @beta
2134
+ */
2135
+ async sendAdaptiveCard(card) {
2136
+ return this.parent.adapter.continueConversation(this.parent.conversationReference, async (context) => {
2137
+ const conversation = await this.newConversation(context);
2138
+ await this.parent.adapter.continueConversation(conversation, async (ctx) => {
2139
+ await ctx.sendActivity({
2140
+ attachments: [CardFactory.adaptiveCard(card)],
2141
+ });
2142
+ });
2143
+ });
2144
+ }
2145
+ /**
2146
+ * @internal
2147
+ */
2148
+ async newConversation(context) {
2149
+ const reference = TurnContext.getConversationReference(context.activity);
2150
+ const personalConversation = cloneConversation(reference);
2151
+ const connectorClient = context.turnState.get(this.parent.adapter.ConnectorClientKey);
2152
+ const conversation = await connectorClient.conversations.createConversation({
2153
+ isGroup: false,
2154
+ tenantId: context.activity.conversation.tenantId,
2155
+ bot: context.activity.recipient,
2156
+ members: [this.account],
2157
+ channelData: {},
2158
+ });
2159
+ personalConversation.conversation.id = conversation.id;
2160
+ return personalConversation;
2161
+ }
2162
+ }
2163
+ /**
2164
+ * A {@link NotificationTarget} that represents a bot installation. Teams Bot could be installed into
2165
+ * - Personal chat
2166
+ * - Group chat
2167
+ * - Team (by default the `General` channel)
2168
+ *
2169
+ * @remarks
2170
+ * It's recommended to get bot installations from {@link ConversationBot.installations()}.
2171
+ *
2172
+ * @beta
2173
+ */
2174
+ class TeamsBotInstallation {
2175
+ /**
2176
+ * Constructor
2177
+ *
2178
+ * @remarks
2179
+ * It's recommended to get bot installations from {@link ConversationBot.installations()}, instead of using this constructor.
2180
+ *
2181
+ * @param adapter - the bound `BotFrameworkAdapter`.
2182
+ * @param conversationReference - the bound `ConversationReference`.
2183
+ *
2184
+ * @beta
2185
+ */
2186
+ constructor(adapter, conversationReference) {
2187
+ this.adapter = adapter;
2188
+ this.conversationReference = conversationReference;
2189
+ this.type = getTargetType(conversationReference);
2190
+ }
2191
+ /**
2192
+ * Send a plain text message.
2193
+ *
2194
+ * @param text - the plain text message.
2195
+ * @returns A `Promise` representing the asynchronous operation.
2196
+ *
2197
+ * @beta
2198
+ */
2199
+ sendMessage(text) {
2200
+ return this.adapter.continueConversation(this.conversationReference, async (context) => {
2201
+ await context.sendActivity(text);
2202
+ });
2203
+ }
2204
+ /**
2205
+ * Send an adaptive card message.
2206
+ *
2207
+ * @param card - the adaptive card raw JSON.
2208
+ * @returns A `Promise` representing the asynchronous operation.
2209
+ *
2210
+ * @beta
2211
+ */
2212
+ sendAdaptiveCard(card) {
2213
+ return this.adapter.continueConversation(this.conversationReference, async (context) => {
2214
+ await context.sendActivity({
2215
+ attachments: [CardFactory.adaptiveCard(card)],
2216
+ });
2217
+ });
2218
+ }
2219
+ /**
2220
+ * Get channels from this bot installation.
2221
+ *
2222
+ * @returns an array of channels if bot is installed into a team, otherwise returns an empty array.
2223
+ *
2224
+ * @beta
2225
+ */
2226
+ async channels() {
2227
+ let teamsChannels = [];
2228
+ await this.adapter.continueConversation(this.conversationReference, async (context) => {
2229
+ const teamId = getTeamsBotInstallationId(context);
2230
+ if (teamId !== undefined) {
2231
+ teamsChannels = await TeamsInfo.getTeamChannels(context, teamId);
2232
+ }
2233
+ });
2234
+ const channels = [];
2235
+ for (const channel of teamsChannels) {
2236
+ channels.push(new Channel(this, channel));
2237
+ }
2238
+ return channels;
2239
+ }
2240
+ /**
2241
+ * Get members from this bot installation.
2242
+ *
2243
+ * @returns an array of members from where the bot is installed.
2244
+ *
2245
+ * @beta
2246
+ */
2247
+ async members() {
2248
+ const members = [];
2249
+ await this.adapter.continueConversation(this.conversationReference, async (context) => {
2250
+ let continuationToken;
2251
+ do {
2252
+ const pagedMembers = await TeamsInfo.getPagedMembers(context, undefined, continuationToken);
2253
+ continuationToken = pagedMembers.continuationToken;
2254
+ for (const member of pagedMembers.members) {
2255
+ members.push(new Member(this, member));
2256
+ }
2257
+ } while (continuationToken !== undefined);
2258
+ });
2259
+ return members;
2260
+ }
2261
+ }
2262
+ /**
2263
+ * Provide utilities to send notification to varies targets (e.g., member, group, channel).
2264
+ *
2265
+ * @beta
2266
+ */
2267
+ class NotificationBot {
2268
+ /**
2269
+ * constructor of the notification bot.
2270
+ *
2271
+ * @remarks
2272
+ * To ensure accuracy, it's recommended to initialize before handling any message.
2273
+ *
2274
+ * @param adapter - the bound `BotFrameworkAdapter`
2275
+ * @param options - initialize options
2276
+ *
2277
+ * @beta
2278
+ */
2279
+ constructor(adapter, options) {
2280
+ var _a, _b;
2281
+ const storage = (_a = options === null || options === void 0 ? void 0 : options.storage) !== null && _a !== void 0 ? _a : new LocalFileStorage(path.resolve(process.env.RUNNING_ON_AZURE === "1" ? (_b = process.env.TEMP) !== null && _b !== void 0 ? _b : "./" : "./"));
2282
+ this.conversationReferenceStore = new ConversationReferenceStore(storage);
2283
+ this.adapter = adapter.use(new NotificationMiddleware({
2284
+ conversationReferenceStore: this.conversationReferenceStore,
2285
+ }));
2286
+ }
2287
+ /**
2288
+ * Get all targets where the bot is installed.
2289
+ *
2290
+ * @remarks
2291
+ * The result is retrieving from the persisted storage.
2292
+ *
2293
+ * @returns - an array of {@link TeamsBotInstallation}.
2294
+ *
2295
+ * @beta
2296
+ */
2297
+ async installations() {
2298
+ if (this.conversationReferenceStore === undefined || this.adapter === undefined) {
2299
+ throw new Error("NotificationBot has not been initialized.");
2300
+ }
2301
+ const references = (await this.conversationReferenceStore.getAll()).values();
2302
+ const targets = [];
2303
+ for (const reference of references) {
2304
+ // validate connection
2305
+ let valid = true;
2306
+ this.adapter.continueConversation(reference, async (context) => {
2307
+ try {
2308
+ // try get member to see if the installation is still valid
2309
+ await TeamsInfo.getPagedMembers(context, 1);
2310
+ }
2311
+ catch (error) {
2312
+ if (error.code === "BotNotInConversationRoster") {
2313
+ valid = false;
2314
+ }
2315
+ }
2316
+ });
2317
+ if (valid) {
2318
+ targets.push(new TeamsBotInstallation(this.adapter, reference));
2319
+ }
2320
+ else {
2321
+ this.conversationReferenceStore.delete(reference);
2322
+ }
2323
+ }
2324
+ return targets;
2325
+ }
2326
+ }
2327
+
2328
+ // Copyright (c) Microsoft Corporation.
2329
+ /**
2330
+ * Provide utilities for bot conversation, including:
2331
+ * - handle command and response.
2332
+ * - send notification to varies targets (e.g., member, group, channel).
2333
+ *
2334
+ * @example
2335
+ * For command and response, you can register your commands through the constructor, or use the `registerCommand` and `registerCommands` API to add commands later.
2336
+ *
2337
+ * ```typescript
2338
+ * // register through constructor
2339
+ * const conversationBot = new ConversationBot({
2340
+ * command: {
2341
+ * enabled: true,
2342
+ * commands: [ new HelloWorldCommandHandler() ],
2343
+ * },
2344
+ * });
2345
+ *
2346
+ * // register through `register*` API
2347
+ * conversationBot.command.registerCommand(new HelpCommandHandler());
2348
+ * ```
2349
+ *
2350
+ * For notification, you can enable notification at initialization, then send notifications at any time.
2351
+ *
2352
+ * ```typescript
2353
+ * // enable through constructor
2354
+ * const conversationBot = new ConversationBot({
2355
+ * notification: {
2356
+ * enabled: true,
2357
+ * },
2358
+ * });
2359
+ *
2360
+ * // get all bot installations and send message
2361
+ * for (const target of await conversationBot.notification.installations()) {
2362
+ * await target.sendMessage("Hello Notification");
2363
+ * }
2364
+ *
2365
+ * // alternative - send message to all members
2366
+ * for (const target of await conversationBot.notification.installations()) {
2367
+ * for (const member of await target.members()) {
2368
+ * await member.sendMessage("Hello Notification");
2369
+ * }
2370
+ * }
2371
+ * ```
2372
+ *
2373
+ * @remarks
2374
+ * Set `adapter` in {@link ConversationOptions} to use your own bot adapter.
2375
+ *
2376
+ * 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.
2377
+ *
2378
+ * For notification, set `notification.storage` in {@link ConversationOptions} to use your own storage implementation.
2379
+ *
2380
+ * @beta
2381
+ */
2382
+ class ConversationBot {
2383
+ /**
2384
+ * Creates new instance of the `ConversationBot`.
2385
+ *
2386
+ * @remarks
2387
+ * It's recommended to create your own adapter and storage for production environment instead of the default one.
2388
+ *
2389
+ * @param options - initialize options
2390
+ *
2391
+ * @beta
2392
+ */
2393
+ constructor(options) {
2394
+ var _a, _b;
2395
+ if (options.adapter) {
2396
+ this.adapter = options.adapter;
2397
+ }
2398
+ else {
2399
+ this.adapter = this.createDefaultAdapter(options.adapterConfig);
2400
+ }
2401
+ if ((_a = options.command) === null || _a === void 0 ? void 0 : _a.enabled) {
2402
+ this.command = new CommandBot(this.adapter, options.command);
2403
+ }
2404
+ if ((_b = options.notification) === null || _b === void 0 ? void 0 : _b.enabled) {
2405
+ this.notification = new NotificationBot(this.adapter, options.notification);
2406
+ }
2407
+ }
2408
+ createDefaultAdapter(adapterConfig) {
2409
+ const adapter = adapterConfig === undefined
2410
+ ? new BotFrameworkAdapter({
2411
+ appId: process.env.BOT_ID,
2412
+ appPassword: process.env.BOT_PASSWORD,
2413
+ })
2414
+ : new BotFrameworkAdapter(adapterConfig);
2415
+ // the default error handler
2416
+ adapter.onTurnError = async (context, error) => {
2417
+ // This check writes out errors to console.
2418
+ console.error(`[onTurnError] unhandled error: ${error}`);
2419
+ // Send a trace activity, which will be displayed in Bot Framework Emulator
2420
+ await context.sendTraceActivity("OnTurnError Trace", `${error}`, "https://www.botframework.com/schemas/error", "TurnError");
2421
+ // Send a message to the user
2422
+ await context.sendActivity(`The bot encountered unhandled error: ${error.message}`);
2423
+ await context.sendActivity("To continue to run this bot, please fix the bot source code.");
2424
+ };
2425
+ return adapter;
2426
+ }
2427
+ /**
2428
+ * The request handler to integrate with web request.
2429
+ *
2430
+ * @param req - an Express or Restify style request object.
2431
+ * @param res - an Express or Restify style response object.
2432
+ * @param logic - the additional function to handle bot context.
2433
+ *
2434
+ * @example
2435
+ * For example, to use with Restify:
2436
+ * ``` typescript
2437
+ * // The default/empty behavior
2438
+ * server.post("api/messages", conversationBot.requestHandler);
2439
+ *
2440
+ * // Or, add your own logic
2441
+ * server.post("api/messages", async (req, res) => {
2442
+ * await conversationBot.requestHandler(req, res, async (context) => {
2443
+ * // your-own-context-logic
2444
+ * });
2445
+ * });
2446
+ * ```
2447
+ *
2448
+ * @beta
2449
+ */
2450
+ async requestHandler(req, res, logic) {
2451
+ if (logic === undefined) {
2452
+ // create empty logic
2453
+ logic = async () => { };
2454
+ }
2455
+ await this.adapter.processActivity(req, res, logic);
2456
+ }
2457
+ }
2458
+
2459
+ // Copyright (c) Microsoft Corporation.
2460
+ const { AdaptiveCards } = require("@microsoft/adaptivecards-tools");
2461
+ /**
2462
+ * Provides utility method to build bot message with cards that supported in Teams.
2463
+ */
2464
+ class MessageBuilder {
2465
+ /**
2466
+ * Build a bot message activity attached with adaptive card.
2467
+ *
2468
+ * @param getCardData Function to prepare your card data.
2469
+ * @param cardTemplate The adaptive card template.
2470
+ * @returns A bot message activity attached with an adaptive card.
2471
+ *
2472
+ * @example
2473
+ * ```javascript
2474
+ * const cardTemplate = {
2475
+ * type: "AdaptiveCard",
2476
+ * body: [
2477
+ * {
2478
+ * "type": "TextBlock",
2479
+ * "text": "${title}",
2480
+ * "size": "Large"
2481
+ * },
2482
+ * {
2483
+ * "type": "TextBlock",
2484
+ * "text": "${description}"
2485
+ * }],
2486
+ * $schema: "http://adaptivecards.io/schemas/adaptive-card.json",
2487
+ * version: "1.4"
2488
+ * };
2489
+ *
2490
+ * type CardData = {
2491
+ * title: string,
2492
+ * description: string
2493
+ * };
2494
+ * const card = MessageBuilder.attachAdaptiveCard<CardData>(() => {
2495
+ * return {
2496
+ * title: "sample card title",
2497
+ * description: "sample card description"
2498
+ * }}, cardTemplate);
2499
+ * ```
2500
+ *
2501
+ * @beta
2502
+ */
2503
+ static attachAdaptiveCard(getCardData, cardTemplate) {
2504
+ const cardData = getCardData();
2505
+ return {
2506
+ attachments: [CardFactory.adaptiveCard(AdaptiveCards.declare(cardTemplate).render(cardData))],
2507
+ };
2508
+ }
2509
+ /**
2510
+ * Build a bot message activity attached with an adaptive card.
2511
+ *
2512
+ * @param card The adaptive card content.
2513
+ * @returns A bot message activity attached with an adaptive card.
2514
+ *
2515
+ * @beta
2516
+ */
2517
+ static attachAdaptiveCardWithoutData(card) {
2518
+ return {
2519
+ attachments: [CardFactory.adaptiveCard(AdaptiveCards.declareWithoutData(card).render())],
2520
+ };
2521
+ }
2522
+ /**
2523
+ * Build a bot message activity attached with an hero card.
2524
+ *
2525
+ * @param title The card title.
2526
+ * @param images Optional. The array of images to include on the card.
2527
+ * @param buttons Optional. The array of buttons to include on the card. Each `string` in the array
2528
+ * is converted to an `imBack` button with a title and value set to the value of the string.
2529
+ * @param other Optional. Any additional properties to include on the card.
2530
+ *
2531
+ * @returns A bot message activity attached with a hero card.
2532
+ *
2533
+ * @example
2534
+ * ```javascript
2535
+ * const message = MessageBuilder.attachHeroCard(
2536
+ * 'sample title',
2537
+ * ['https://example.com/sample.jpg'],
2538
+ * ['action']
2539
+ * );
2540
+ * ```
2541
+ *
2542
+ * @beta
2543
+ */
2544
+ static attachHeroCard(title, images, buttons, other) {
2545
+ return MessageBuilder.attachContent(CardFactory.heroCard(title, images, buttons, other));
2546
+ }
2547
+ /**
2548
+ * Returns an attachment for a sign-in card.
2549
+ *
2550
+ * @param title The title for the card's sign-in button.
2551
+ * @param url The URL of the sign-in page to use.
2552
+ * @param text Optional. Additional text to include on the card.
2553
+ *
2554
+ * @returns A bot message activity attached with a sign-in card.
2555
+ *
2556
+ * @remarks
2557
+ * For channels that don't natively support sign-in cards, an alternative message is rendered.
2558
+ *
2559
+ * @beta
2560
+ */
2561
+ static attachSigninCard(title, url, text) {
2562
+ return MessageBuilder.attachContent(CardFactory.signinCard(title, url, text));
2563
+ }
2564
+ /**
2565
+ * Build a bot message activity attached with an Office 365 connector card.
2566
+ *
2567
+ * @param card A description of the Office 365 connector card.
2568
+ * @returns A bot message activity attached with an Office 365 connector card.
2569
+ *
2570
+ * @beta
2571
+ */
2572
+ static attachO365ConnectorCard(card) {
2573
+ return MessageBuilder.attachContent(CardFactory.o365ConnectorCard(card));
2574
+ }
2575
+ /**
2576
+ * Build a message activity attached with a receipt card.
2577
+ * @param card A description of the receipt card.
2578
+ * @returns A message activity attached with a receipt card.
2579
+ *
2580
+ * @beta
2581
+ */
2582
+ static AttachReceiptCard(card) {
2583
+ return MessageBuilder.attachContent(CardFactory.receiptCard(card));
2584
+ }
2585
+ /**
2586
+ *
2587
+ * @param title The card title.
2588
+ * @param images Optional. The array of images to include on the card.
2589
+ * @param buttons Optional. The array of buttons to include on the card. Each `string` in the array
2590
+ * is converted to an `imBack` button with a title and value set to the value of the string.
2591
+ * @param other Optional. Any additional properties to include on the card.
2592
+ * @returns A message activity attached with a thumbnail card
2593
+ *
2594
+ * @beta
2595
+ */
2596
+ static attachThumbnailCard(title, images, buttons, other) {
2597
+ return MessageBuilder.attachContent(CardFactory.thumbnailCard(title, images, buttons, other));
2598
+ }
2599
+ /**
2600
+ * Add an attachement to a bot activity.
2601
+ * @param attachement The attachment object to attach.
2602
+ * @returns A message activity with an attachment.
2603
+ *
2604
+ * @beta
2605
+ */
2606
+ static attachContent(attachement) {
2607
+ return {
2608
+ attachments: [attachement],
2609
+ };
2610
+ }
2611
+ }
2612
+
2613
+ export { AppCredential, BearerTokenAuthProvider, Channel, CommandBot, ConversationBot, ErrorCode, ErrorWithCode, IdentityType, LogLevel, Member, MessageBuilder, MsGraphAuthProvider, NotificationBot, OnBehalfOfUserCredential, TeamsBotInstallation, TeamsBotSsoPrompt, TeamsFx, TeamsUserCredential, createApiClient, createMicrosoftGraphClient, getLogLevel, getTediousConnectionConfig, sendAdaptiveCard, sendMessage, setLogFunction, setLogLevel, setLogger };
1571
2614
  //# sourceMappingURL=index.esm2017.mjs.map