49 lines
1.3 KiB
TypeScript
49 lines
1.3 KiB
TypeScript
////
|
|
// The shell runs on the server and processes input, returning output.
|
|
|
|
import type { Message, CommandResult } from "../shared/types.js"
|
|
import { addInput, setStatus, addOutput } from "./scrollback.js"
|
|
import { send } from "./websocket.js"
|
|
import { randomID } from "../shared/utils.js"
|
|
import { addToHistory } from "./history.js"
|
|
import { browserCommands, cacheCommands } from "./commands.js"
|
|
|
|
export function runCommand(input: string) {
|
|
if (!input.trim()) return
|
|
|
|
const id = randomID()
|
|
|
|
addToHistory(input)
|
|
addInput(id, input)
|
|
|
|
const [cmd = "", ...args] = input.split(" ")
|
|
|
|
if (browserCommands[cmd]) {
|
|
const result = browserCommands[cmd]()
|
|
if (typeof result === "string")
|
|
addOutput(id, result)
|
|
setStatus(id, "ok")
|
|
} else {
|
|
send({ id, type: "input", data: input })
|
|
}
|
|
}
|
|
|
|
// message received from server
|
|
export function handleMessage(msg: Message) {
|
|
if (msg.type === "output") {
|
|
handleOutput(msg)
|
|
} else if (msg.type === "commands") {
|
|
cacheCommands(msg.data as string[])
|
|
} else if (msg.type === "error") {
|
|
console.error(msg.data)
|
|
} else {
|
|
console.error("unknown message type", msg)
|
|
}
|
|
}
|
|
|
|
function handleOutput(msg: Message) {
|
|
const result = msg.data as CommandResult
|
|
setStatus(msg.id!, result.status)
|
|
addOutput(msg.id!, result.output)
|
|
}
|