forked from codesandbox/codesandbox-client
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
55 lines (50 loc) · 1.47 KB
/
index.js
File metadata and controls
55 lines (50 loc) · 1.47 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
import { dispatch, listen, intializedPromise } from 'codesandbox-api';
import Hook from 'console-feed/lib/Hook';
import { Encode } from 'console-feed/lib/Transform';
export default function setupConsole() {
Hook(window.console, async log => {
await intializedPromise;
dispatch({
type: 'console',
log,
});
});
function handleMessage(data, source) {
if (source) {
if (data.type === 'evaluate') {
let result = null;
let error = false;
try {
// Attempt to wrap command in parentheses, fixing issues
// where directly returning objects results in unexpected
// behaviour.
if (data.command && data.command.charAt(0) === '{') {
try {
const wrapped = `(${data.command})`;
// `new Function` is used to validate Javascript syntax
// eslint-disable-next-line
const validate = new Function(wrapped);
data.command = wrapped;
} catch (e) {
// We shouldn't wrap the expression
}
}
result = (0, eval)(data.command); // eslint-disable-line no-eval
} catch (e) {
result = e;
error = true;
}
try {
dispatch({
type: 'eval-result',
error,
result: Encode(result),
});
} catch (e) {
console.error(e);
}
}
}
}
return listen(handleMessage);
}