eval-server/index.js

62 lines
1.6 KiB
JavaScript

const { Server } = require('socket.io')
const { Worker } = require('worker_threads')
const path = require('path')
const io = new Server(3069)
io.on('connection', (socket) => {
let worker
let isFirst = true
let jsonArray
function reset () {
worker = new Worker(path.join(__dirname, 'vm.js'))
worker.on('message', (msg) => {
switch (msg.type) {
case 'socketEmit':
socket.emit(...msg.data)
break
case 'socketOnce':
socket.once(msg.name, (message, parseJSON) => {
if (parseJSON) worker.postMessage({ type: 'resolvePromise', uuid: msg.uuid, data: JSON.parse(message) })
else worker.postMessage({ type: 'resolvePromise', uuid: msg.uuid, data: message })
})
break
}
})
// ohio
if (!isFirst) {
worker.postMessage({ type: 'setFunctions', jsonArray })
} else isFirst = false
}
reset()
socket.on('setFunctions', (_jsonArray) => {
jsonArray = _jsonArray
worker.postMessage({ type: 'setFunctions', jsonArray })
})
socket.on('runCode', (transactionId, code) => {
worker.postMessage({ type: 'runCode', code })
worker.on('message', ({ type, error, output }) => {
if (type !== 'codeOutput') return
socket.emit('codeOutput', transactionId, error, output)
})
})
socket.on('reset', reset)
})
process.on('uncaughtException', (e) => {
console.log(`Caught an uncaught exception!\n${e.stack}`)
})