@sodacore/cli
Version:
Sodacore CLI is a plugin that offers CLI functionality within the framework.
56 lines (55 loc) • 2.25 kB
JavaScript
import { connect } from 'bun';
import { log } from '@clack/prompts';
import Commands from './commands';
export default class Application {
constructor(connection) {
this.connection = connection;
}
init() {
return new Promise(resolve => {
this.exitHandler = (value) => {
if (this.socket)
this.socket.end();
resolve(value);
};
this.commands = new Commands(this.exitHandler.bind(this));
this.connect();
});
}
async connect() {
this.socket = await connect({
hostname: this.connection.host,
port: this.connection.port,
socket: {
end: () => this.exitHandler('Connected was closed.'),
timeout: () => this.exitHandler('Connection timed out.'),
connectError: (_, err) => this.exitHandler(`Connection error: ${err.message}`),
error: (_, err) => this.exitHandler(`Socket error: ${err.message}, connection closed.`),
close: (_, err) => this.exitHandler(`Socket disconnected${err ? `: reason: ${err.message}` : ''}`),
open: socket => this.onOpen.bind(this)(socket),
data: (_, data) => this.handle.bind(this)(data.toString()),
},
});
}
async onOpen(socket) {
this.commands.setSocket(socket);
socket.data = { uid: Bun.randomUUIDv7(), authenticated: false };
this.write(socket, '_:authenticate', { password: this.connection.pass });
log.success(`Connection established to ${this.connection.host}:${this.connection.port}`);
}
async handle(data) {
try {
const packet = JSON.parse(data);
const { command, context } = packet;
const status = this.commands.handle(command, context);
if (!status)
log.error(`Command ${command} not found.`);
}
catch (err) {
log.error(`Error processing response data: ${err instanceof Error ? err.message : String(err)}`);
}
}
write(socket, command, context = {}) {
socket.write(JSON.stringify({ _uid: socket.data.uid, command, context }));
}
}