ludus-repl/listener.ts

68 lines
1.9 KiB
TypeScript

import { run } from "@ludus/ludus-js-pure"
import { unlinkSync, readFileSync } from "node:fs"
export async function listen () {
const id = Math.floor(Math.random() * 1000) + 5000
const unix_socket = `/tmp/ludus-${id}.sock`
const repl_file_path = ".lrepl"
const repl_info = { unix_socket }
const repl_file = Bun.file(repl_file_path)
await Bun.write(repl_file, JSON.stringify(repl_info))
console.log(`Ludus REPL listening on ${unix_socket}`)
Bun.listen({
//hostname: "localhost",
//port,
unix: unix_socket,
socket: {
open: (_) => {console.log("=== === ===") },
data: (_, data) => {
const source = data.toString("utf-8")
const result = run(source)
if (!result.errors) console.log("=>", result.result)
else {
console.log("Ludus had some errors:")
console.log(result.errors)
}
},
error: (socket, error) => { console.log(error); socket.end() }
}
})
process.on("exit", async function () {
try { cleanup(repl_file_path, unix_socket) } catch (e) {}
console.log("\nGoodbye.")
})
process.on("SIGINT", () => process.exit())
// Below here, I'm trying to get ctrl-d to work to close the listener
// the while (true) loop locks the listener
// see: https://github.com/oven-sh/bun/issues/3255
// this should be doable with process.stdin.on("close"...)
//const mystdin = Bun.file("/dev/stdin").stream().getReader()
// while (true) {
// const {done, value} = await mystdin.read()
// if (done) process.exit()
// console.log(value)
// }
}
// Don't delete an .lrepl we don't own
function cleanup (path: string, my_socket: string) {
const repl_file = readFileSync(path).toString("utf-8")
let their_socket
try { their_socket = JSON.parse(repl_file).unix_socket } catch (e) { return }
if (their_socket === my_socket) {
unlinkSync(path)
unlinkSync(my_socket)
}
}
// await listen()