UNPKG

6.17 kBJavaScriptView Raw
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3const tslib_1 = require("tslib");
4const request = require("request");
5const semver = require("semver");
6const fs = require("fs-extra");
7const path = require("path");
8const crypto = require("crypto");
9const CLM = require("@conversationlearner/models");
10class Utils {
11 static SendTyping(adapter, address) {
12 /* TODO
13 let msg = <builder.IMessage>{ type: 'typing'};
14 msg.address = address;
15 bot.post(msg);
16 */
17 }
18 /** Trick to get errors to render on Azure */
19 static ReplaceErrors(key, value) {
20 if (value instanceof Error) {
21 const error = {};
22 Object.getOwnPropertyNames(value).forEach(k => {
23 error[k] = value[k];
24 });
25 return error;
26 }
27 return value;
28 }
29 /** Handle that catch clauses can be any type */
30 static ErrorString(error, context = '') {
31 let prefix = context ? `${context}: ` : '';
32 try {
33 if (!error) {
34 return prefix + 'Unknown';
35 }
36 // Special message for 403 as it's like a bad ModelId
37 else if (error.statusCode === 403) {
38 return `403 Forbidden: Please check you have set a valid CONVERSATION_LEARNER_MODEL_ID`;
39 }
40 else if (!error.body) {
41 if (typeof error == 'string') {
42 return prefix + error;
43 }
44 else {
45 return prefix + JSON.stringify(error, this.ReplaceErrors);
46 }
47 }
48 else if (error.body.message) {
49 return prefix + error.body.message;
50 }
51 else if (error.body.errorMessages) {
52 return prefix + error.body.errorMessages.join();
53 }
54 else if (typeof error.body == 'string') {
55 return prefix + error.body;
56 }
57 else {
58 return prefix + JSON.stringify(error.body);
59 }
60 }
61 catch (e) {
62 return prefix + `Error Parsing Failed`; //: ${Object.prototype.toString.call(e)} ${JSON.stringify(e)}`;
63 }
64 }
65 static ReadFromFile(url) {
66 return new Promise((resolve, reject) => {
67 const requestData = {
68 url: url,
69 json: true,
70 encoding: 'utf8'
71 };
72 request.get(requestData, (error, response, body) => {
73 if (error) {
74 reject(error);
75 }
76 else if (response.statusCode && response.statusCode >= 300) {
77 reject(body.message);
78 }
79 else {
80 let model = String.fromCharCode.apply(null, body.data);
81 resolve(model);
82 }
83 });
84 });
85 }
86}
87exports.Utils = Utils;
88const convertToMapById = (entityMap) => {
89 const map = Object.keys(entityMap.map).reduce((newMap, key) => {
90 const filledEntity = entityMap.map[key];
91 if (!filledEntity.entityId) {
92 throw new Error(`Cannot convert filledEntityMap by name to filledEntityMap by id because id does not exist for entity: ${key}`);
93 }
94 newMap[filledEntity.entityId] = filledEntity;
95 return newMap;
96 }, {});
97 return new CLM.FilledEntityMap({ map });
98};
99exports.addEntitiesById = (valuesByName) => {
100 const valuesById = convertToMapById(valuesByName);
101 const map = Object.assign({}, valuesByName.map, valuesById.map);
102 return new CLM.FilledEntityMap({ map });
103};
104function replace(xs, updatedX, getId) {
105 const index = xs.findIndex(x => getId(x) === getId(updatedX));
106 if (index < 0) {
107 throw new Error(`You attempted to replace item in list with id: ${getId(updatedX)} but no item could be found. Perhaps you meant to add the item to the list or it was already removed.`);
108 }
109 return [...xs.slice(0, index), updatedX, ...xs.slice(index + 1)];
110}
111exports.replace = replace;
112// Create checksum for determining when bot has changed
113function botChecksum(callbacks, templates) {
114 const source = `${JSON.stringify(callbacks)}${JSON.stringify(templates)}}`;
115 return crypto.createHash('sha256').update(source).digest('hex');
116}
117exports.botChecksum = botChecksum;
118/* Returns true is SDK version in package is less than passed in version */
119const packageJsonPath = path.join(__dirname, '..', 'package.json');
120function isSDKOld(curVersion) {
121 return tslib_1.__awaiter(this, void 0, void 0, function* () {
122 const packageJson = yield fs.readJson(packageJsonPath);
123 if (packageJson.version === "0.0.0-development") {
124 return false;
125 }
126 return semver.lt(packageJson.version, curVersion);
127 });
128}
129exports.isSDKOld = isSDKOld;
130function IsCardValid(card) {
131 if (typeof card === 'string') {
132 return true;
133 }
134 if (card.id && typeof card.id !== 'string') {
135 return false;
136 }
137 return true;
138}
139exports.IsCardValid = IsCardValid;
140function GetLogicAPIError(logicResult) {
141 if (!logicResult) {
142 return null;
143 }
144 if (!logicResult.logicValue) {
145 return null;
146 }
147 const logicAPIResult = JSON.parse(logicResult.logicValue);
148 if (!logicAPIResult || !logicAPIResult.APIError) {
149 return null;
150 }
151 return logicAPIResult;
152}
153exports.GetLogicAPIError = GetLogicAPIError;
154/* Converts user intput into BB.Activity */
155function InputToActivity(userText, roundNum) {
156 let clData = {
157 senderType: CLM.SenderType.User,
158 roundIndex: roundNum,
159 scoreIndex: null
160 };
161 // Generate activity
162 return {
163 id: CLM.ModelUtils.generateGUID(),
164 channelData: {
165 clData,
166 clientActivityId: CLM.ModelUtils.generateGUID()
167 },
168 type: 'message',
169 text: userText
170 };
171}
172exports.InputToActivity = InputToActivity;
173exports.CL_DEVELOPER = 'ConversationLearnerDeveloper';
174exports.UI_RUNNER_APPID = 'UIRunner_AppId';
175exports.DEFAULT_MAX_SESSION_LENGTH = 20 * 60 * 1000; // 20 minutes
176//# sourceMappingURL=Utils.js.map
\No newline at end of file