Repository navigation
Expand file tree
/
Copy pathserver.ts
More file actions
97 lines (75 loc) · 1.89 KB
/
Copy pathserver.ts
File metadata and controls
97 lines (75 loc) · 1.89 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
import { Packet } from './common/protocol';
import { initSocket } from './socket';
interface Events {
open: () => void;
data: (data: string) => void;
reconnect: () => void;
}
interface Server {
runCode(python: string): void;
sendData(data: string): void;
resizeTerminal(cols: number, rows: number): void;
on<K extends keyof Events>(eventType: K, handler: Events[K]): void;
}
const stub = () => void 0;
async function newServer(): Promise<Server> {
const eventHandlers: Events = {
open: stub,
data: stub,
reconnect: stub,
};
const url = `ws://${getHost()}/terminal`;
const ws = await initSocket(url);
ws.on('data', (packet: Packet) => {
switch (packet.packetType) {
case 'data':
eventHandlers.data(packet.payload);
break;
}
});
ws.on('reconnect', () => eventHandlers.reconnect());
function runCode(python: string) {
const url = `http://${getHost()}/runcode`;
console.time('runCode');
const xhr = new XMLHttpRequest();
xhr.open('POST', url, true);
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.send('code=' + encodeURIComponent(python));
xhr.onload = (e) => {
console.timeEnd('runCode');
};
}
function getHost() {
if (location.protocol === 'file:') {
return '127.0.0.1:8081';
}
if (location.protocol === 'http:') {
return location.host;
}
return '';
}
function sendData(data: string) {
ws.sendPacket({
packetType: 'data',
payload: data,
});
}
function resizeTerminal(cols: number, rows: number) {
ws.sendPacket({
packetType: 'resize',
payload: { cols, rows },
});
}
function on<K extends keyof Events>(eventType: K, handler: Events[K]) {
eventHandlers[eventType] = handler;
}
return {
runCode,
sendData,
resizeTerminal,
on,
};
}
export {
newServer,
};