forked from microsoft/BotFramework-WebChat
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcreateDirectLineEmulator.js
More file actions
236 lines (195 loc) · 7.59 KB
/
createDirectLineEmulator.js
File metadata and controls
236 lines (195 loc) · 7.59 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
import { withResolvers } from '@msinternal/botframework-webchat-base/utils';
import Observable from 'core-js/features/observable';
import random from 'math-random';
import updateIn from 'simple-update-in';
import createDeferredObservable from '../../utils/createDeferredObservable';
import became from '../pageConditions/became';
import { createStoreWithOptions } from './createStore';
import shareObservable from './shareObservable';
function isNativeClock() {
return ('' + setTimeout).endsWith('() { [native code] }');
}
function uniqueId() {
return random().toString(36).substring(2, 7);
}
export default function createDirectLineEmulator({ autoConnect = true, ponyfill = {} } = {}) {
const { Date = window.Date } = ponyfill;
const store = createStoreWithOptions({ ponyfill });
if (!isNativeClock()) {
throw new Error('Fake timer is detected at global-level. You must pass it via the "ponyfill" option.');
}
const now = Date.now();
const getTimestamp = () => new Date().toISOString();
const connectedWithResolvers = withResolvers();
const connectionStatusDeferredObservable = createDeferredObservable(() => {
connectionStatusDeferredObservable.next(0);
});
const activityDeferredObservable = createDeferredObservable(async () => {
connectionStatusDeferredObservable.next(1);
await connectedWithResolvers.promise;
connectionStatusDeferredObservable.next(2);
});
const postActivityCallDeferreds = [];
const postActivity = outgoingActivity => {
// Auto-handle voice activities (continuous sending by mic) without requiring actPostActivity
// Voice activities are fire-and-forget and don't echo back
if (outgoingActivity.type === 'event' && outgoingActivity.name.includes('media')) {
const id = uniqueId();
return new Observable(observer => {
try {
observer.next(id);
observer.complete();
} catch (error) {
observer.error(error);
}
});
}
const returnPostActivityWithResolvers = withResolvers();
const deferred = postActivityCallDeferreds.shift();
if (!deferred) {
throw new Error(
'When DirectLineEmulator is installed, you must call actPostActivity() before sending a message.'
);
}
deferred.resolve({ outgoingActivity, returnPostActivityDeferred: returnPostActivityWithResolvers });
return new Observable(observer => {
(async function () {
try {
observer.next(await returnPostActivityWithResolvers.promise);
observer.complete();
} catch (error) {
observer.error(error);
}
})();
});
};
const actPostActivity = async (fn, { id: idFromOptions } = {}) => {
const postActivityCallWithResolvers = withResolvers();
postActivityCallDeferreds.push(postActivityCallWithResolvers);
await fn();
const { outgoingActivity, returnPostActivityDeferred } = await postActivityCallWithResolvers.promise;
const id = idFromOptions || uniqueId();
let echoBackActivity = { ...outgoingActivity, id, timestamp: getTimestamp() };
const echoBack = async updater => {
if (typeof updater === 'function') {
echoBackActivity = updater(echoBackActivity);
}
activityDeferredObservable.next(echoBackActivity);
await became(
'echo back activity appears in the store',
() => store.getState().activities.find(activity => activity.id === echoBackActivity.id),
1000
);
};
const rejectPostActivity = error => returnPostActivityDeferred.reject(error);
const resolvePostActivity = () => returnPostActivityDeferred.resolve(id);
const resolveAll = async updater => {
await echoBack(updater);
resolvePostActivity();
};
return { activity: outgoingActivity, echoBack, rejectPostActivity, resolveAll, resolvePostActivity };
};
autoConnect && connectedWithResolvers.resolve();
// Generic capabilities storage
const capabilities = new Map();
// EventTarget for capability change notifications
const eventTarget = new EventTarget();
// Helper to dispatch capabilitieschanged event via EventTarget
const emitCapabilitiesChangedEvent = () => {
eventTarget.dispatchEvent(new Event('capabilitieschanged'));
};
const directLine = {
activity$: shareObservable(activityDeferredObservable.observable),
actPostActivity,
connectionStatus$: shareObservable(connectionStatusDeferredObservable.observable),
/**
* Generic capability setter - dynamically creates getter on directLine object.
*
* @example
* directLine.setCapability('getVoiceConfiguration', { voice: 'en-US', speed: 1.0 });
* directLine.setCapability('getSessionInfo', { sessionId: '123' }, { emitEvent: false });
*/
setCapability: (getterName, value, { emitEvent = true } = {}) => {
capabilities.set(getterName, value);
// Dynamically add/update getter on directLine object
// eslint-disable-next-line security/detect-object-injection
directLine[getterName] = () => capabilities.get(getterName);
if (emitEvent) {
emitCapabilitiesChangedEvent();
}
},
addEventListener: eventTarget.addEventListener.bind(eventTarget),
removeEventListener: eventTarget.removeEventListener.bind(eventTarget),
end: () => {
// This is a mock and will no-op on dispatch().
},
postActivity,
emulateReconnect: () => {
connectionStatusDeferredObservable.next(1);
return {
resolve: () => connectionStatusDeferredObservable.next(2)
};
},
emulateConnected: connectedWithResolvers.resolve,
emulateIncomingActivity: async (activity, { skipWait } = {}) => {
if (typeof activity === 'string') {
activity = {
from: { id: 'bot', role: 'bot' },
id: uniqueId(),
text: activity,
timestamp: getTimestamp(),
type: 'message'
};
} else {
activity = updateIn(activity, ['from', 'role'], role => role || 'bot');
activity = updateIn(activity, ['id'], id => id || uniqueId());
activity = updateIn(activity, ['timestamp'], timestamp =>
typeof timestamp === 'number'
? new Date(now + timestamp).toISOString()
: 'timestamp' in activity // If `activity.timestamp` is `undefined`, let it in.
? timestamp
: getTimestamp()
);
activity = updateIn(activity, ['type'], type => type || 'message');
}
const { id } = activity;
activityDeferredObservable.next(activity);
skipWait ||
(await became(
'incoming activity appears in the store',
() => store.getState().activities.find(activity => activity.id === id),
1000
));
},
emulateIncomingVoiceActivity: activity => {
activity = updateIn(activity, ['timestamp'], timestamp =>
typeof timestamp === 'number'
? new Date(now + timestamp).toISOString()
: 'timestamp' in activity
? timestamp
: getTimestamp()
);
activity = updateIn(activity, ['type'], type => type || 'event');
activityDeferredObservable.next(activity);
},
emulateOutgoingActivity: (activity, options) => {
if (typeof activity === 'string') {
activity = {
from: { id: 'user', role: 'user' },
text: activity,
type: 'message'
};
}
return actPostActivity(
() =>
store.dispatch({
meta: { method: 'code' },
payload: { activity },
type: 'DIRECT_LINE/POST_ACTIVITY'
}),
options
);
}
};
return { directLine, store };
}