WRITE UNIT TESTS!!!
first async command working, no unit tests done AGAING
This commit is contained in:
@@ -1,11 +1,13 @@
|
|||||||
import type { CommandDescriptor } from "./command";
|
import type { CommandDescriptor } from "./command";
|
||||||
import { descriptor as cd } from "./commands/cd";
|
import { descriptor as cd } from "./commands/cd";
|
||||||
import { descriptor as echo } from "./commands/echo";
|
import { descriptor as echo } from "./commands/echo";
|
||||||
|
import { descriptor as testasync } from "./commands/testasync";
|
||||||
|
|
||||||
const reg = new Map<string, CommandDescriptor>();
|
const reg = new Map<string, CommandDescriptor>();
|
||||||
//reg.set(descriptor.name, descriptor <- imported const from command implementation file);
|
//reg.set(descriptor.name, descriptor <- imported const from command implementation file);
|
||||||
reg.set(echo.name, echo);
|
reg.set(echo.name, echo);
|
||||||
reg.set(cd.name, cd);
|
reg.set(cd.name, cd);
|
||||||
|
reg.set(testasync.name, testasync);
|
||||||
Object.freeze(reg);
|
Object.freeze(reg);
|
||||||
|
|
||||||
export const COMMAND_REGISTRY: ReadonlyMap<string, CommandDescriptor> = reg;
|
export const COMMAND_REGISTRY: ReadonlyMap<string, CommandDescriptor> = reg;
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import type { CommandDescriptor, CommandOutput } from "@core/command";
|
import type { CommandDescriptor, CommandOutput } from "@core/command";
|
||||||
|
import type { CommandIO } from "@core/command_io";
|
||||||
import type { FileSystem } from "@core/filesystem/filesystem";
|
import type { FileSystem } from "@core/filesystem/filesystem";
|
||||||
import { createErrorResult, createSuccessResult } from "@core/result";
|
import { createErrorResult, createSuccessResult } from "@core/result";
|
||||||
import { getCurrentSession } from "@core/session_manager";
|
import { getCurrentSession } from "@core/session_manager";
|
||||||
@@ -14,7 +15,12 @@ import { resolveInode, resolvePath } from "@core/util/path_resolver";
|
|||||||
|
|
||||||
export const COMMAND_NAME = "cd";
|
export const COMMAND_NAME = "cd";
|
||||||
|
|
||||||
function main(state: ShellState, __flags: string[], args: string[]): CommandOutput<ShellError> {
|
async function main(
|
||||||
|
__io: CommandIO,
|
||||||
|
state: ShellState,
|
||||||
|
__flags: string[],
|
||||||
|
args: string[],
|
||||||
|
): Promise<CommandOutput<ShellError>> {
|
||||||
if (args.length > 1) {
|
if (args.length > 1) {
|
||||||
return {
|
return {
|
||||||
state,
|
state,
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import type { CommandDescriptor, CommandOutput } from "@core/command";
|
import type { CommandDescriptor, CommandOutput } from "@core/command";
|
||||||
|
import type { CommandIO } from "@core/command_io";
|
||||||
import type { ResultSuccess } from "@core/result";
|
import type { ResultSuccess } from "@core/result";
|
||||||
import type { ShellState } from "@core/shell_state";
|
import type { ShellState } from "@core/shell_state";
|
||||||
import type { ShellError } from "@core/util/errors";
|
import type { ShellError } from "@core/util/errors";
|
||||||
@@ -7,16 +8,21 @@ import { createImmutableBuffer } from "@core/util/immutable_buffer";
|
|||||||
export const COMMAND_NAME = "echo";
|
export const COMMAND_NAME = "echo";
|
||||||
|
|
||||||
//Need to implement escape sequences
|
//Need to implement escape sequences
|
||||||
function main(state: ShellState, flags: string[], args: string[]): CommandOutput<ShellError> {
|
async function main(
|
||||||
|
io: CommandIO,
|
||||||
|
state: ShellState,
|
||||||
|
__flags: string[],
|
||||||
|
args: string[],
|
||||||
|
): Promise<CommandOutput<ShellError>> {
|
||||||
const joined = args.join(" ");
|
const joined = args.join(" ");
|
||||||
const encoded = new TextEncoder().encode(joined);
|
const encoded = new TextEncoder().encode(joined);
|
||||||
|
|
||||||
const stdout = createImmutableBuffer(encoded);
|
io.writeStdout(encoded);
|
||||||
|
|
||||||
const result: ResultSuccess = {
|
const result: ResultSuccess = {
|
||||||
type: "success",
|
type: "success",
|
||||||
exitCode: 0,
|
exitCode: 0,
|
||||||
stdout,
|
stdout: createImmutableBuffer(new Uint8Array()),
|
||||||
stderr: createImmutableBuffer(new Uint8Array()),
|
stderr: createImmutableBuffer(new Uint8Array()),
|
||||||
commandName: COMMAND_NAME,
|
commandName: COMMAND_NAME,
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -0,0 +1,44 @@
|
|||||||
|
import type { CommandDescriptor, CommandOutput } from "@core/command";
|
||||||
|
import type { CommandIO } from "@core/command_io";
|
||||||
|
import type { ResultSuccess } from "@core/result";
|
||||||
|
import type { ShellState } from "@core/shell_state";
|
||||||
|
import type { ShellError } from "@core/util/errors";
|
||||||
|
import { createImmutableBuffer } from "@core/util/immutable_buffer";
|
||||||
|
|
||||||
|
const COMMAND_NAME = "async";
|
||||||
|
|
||||||
|
async function main(
|
||||||
|
io: CommandIO,
|
||||||
|
state: ShellState,
|
||||||
|
__flags: string[],
|
||||||
|
__args: string[],
|
||||||
|
): Promise<CommandOutput<ShellError>> {
|
||||||
|
while (true) {
|
||||||
|
const out = await io.getSignal();
|
||||||
|
|
||||||
|
if (out.type === "INPUT") {
|
||||||
|
const encoded = new TextEncoder().encode(("user pressed: " + out.payload + "\n") as string);
|
||||||
|
io.writeStdout(encoded);
|
||||||
|
|
||||||
|
if (out.payload === "ctrl+c") {
|
||||||
|
const result: ResultSuccess = {
|
||||||
|
type: "success",
|
||||||
|
exitCode: 0,
|
||||||
|
stdout: createImmutableBuffer(new Uint8Array()),
|
||||||
|
stderr: createImmutableBuffer(new Uint8Array()),
|
||||||
|
commandName: COMMAND_NAME,
|
||||||
|
};
|
||||||
|
|
||||||
|
return {
|
||||||
|
state: state,
|
||||||
|
result,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export const descriptor = {
|
||||||
|
fn: main,
|
||||||
|
name: COMMAND_NAME,
|
||||||
|
} satisfies CommandDescriptor;
|
||||||
@@ -38,6 +38,7 @@ const EXIT_CODE_MAP: Record<string, number> = {
|
|||||||
GenericError: 1,
|
GenericError: 1,
|
||||||
InvalidArguments: 2,
|
InvalidArguments: 2,
|
||||||
|
|
||||||
|
ParseError: 62,
|
||||||
UsageError: 63,
|
UsageError: 63,
|
||||||
PathResolutionError: 64,
|
PathResolutionError: 64,
|
||||||
DataFormatError: 65,
|
DataFormatError: 65,
|
||||||
|
|||||||
+3
-3
@@ -1,4 +1,4 @@
|
|||||||
import { defaultConfig, TermosConfig } from "./config";
|
/* import { defaultConfig, TermosConfig } from "./config";
|
||||||
|
|
||||||
let config: TermosConfig = { ...defaultConfig };
|
let config: TermosConfig = { ...defaultConfig };
|
||||||
|
|
||||||
@@ -8,8 +8,8 @@ namespace Termos {
|
|||||||
console.log("termos initialized");
|
console.log("termos initialized");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
*/
|
||||||
const message: string = "Hello, World!";
|
const message: string = "Hello, World!";
|
||||||
console.log(message);
|
console.log(message);
|
||||||
|
|
||||||
export { Termos };
|
//export { Termos };
|
||||||
|
|||||||
@@ -1,17 +0,0 @@
|
|||||||
/*
|
|
||||||
Create an interface for the rest of the library to use to fetch nessesary data.
|
|
||||||
To do that, implement a termos config that will contain the table and db names, aswell as other relevant information -
|
|
||||||
maybe a flag for headless mode (uses the built-in console frontend module - need to evaluate this idea more)
|
|
||||||
*/
|
|
||||||
|
|
||||||
export async fetchFileSystem(): Promise<JSON> {
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
export async fetchUserGroups(): Promise<JSON> {
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
export async fetchUsers(): Promise<JSON> {
|
|
||||||
|
|
||||||
}
|
|
||||||
@@ -1,14 +1,16 @@
|
|||||||
|
type Listener = (payload: unknown) => void;
|
||||||
|
|
||||||
export class EventEmitter<TEvents> {
|
export class EventEmitter<TEvents> {
|
||||||
private Handlers: Map<keyof TEvents, Set<Function>> = new Map();
|
private Handlers: Map<keyof TEvents, Set<Listener>> = new Map();
|
||||||
|
|
||||||
public on<K extends keyof TEvents>(type: K, handler: (payload: TEvents[K]) => void): () => void {
|
public on<K extends keyof TEvents>(type: K, handler: (payload: TEvents[K]) => void): () => void {
|
||||||
const listeners = this.Handlers.get(type);
|
const listeners = this.Handlers.get(type);
|
||||||
|
|
||||||
if (listeners) {
|
if (listeners) {
|
||||||
listeners.add(handler);
|
listeners.add(handler as Listener);
|
||||||
} else {
|
} else {
|
||||||
const set: Set<Function> = new Set();
|
const set: Set<Listener> = new Set();
|
||||||
set.add(handler);
|
set.add(handler as Listener);
|
||||||
this.Handlers.set(type, set);
|
this.Handlers.set(type, set);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -16,7 +18,7 @@ export class EventEmitter<TEvents> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public off<K extends keyof TEvents>(type: K, handler: (payload: TEvents[K]) => void): void {
|
public off<K extends keyof TEvents>(type: K, handler: (payload: TEvents[K]) => void): void {
|
||||||
this.Handlers.get(type)?.delete(handler);
|
this.Handlers.get(type)?.delete(handler as Listener);
|
||||||
}
|
}
|
||||||
|
|
||||||
public once<K extends keyof TEvents>(type: K, handler: (payload: TEvents[K]) => void): () => void {
|
public once<K extends keyof TEvents>(type: K, handler: (payload: TEvents[K]) => void): () => void {
|
||||||
@@ -28,10 +30,10 @@ export class EventEmitter<TEvents> {
|
|||||||
};
|
};
|
||||||
|
|
||||||
if (listeners) {
|
if (listeners) {
|
||||||
listeners.add(wrapper);
|
listeners.add(wrapper as Listener);
|
||||||
} else {
|
} else {
|
||||||
const set: Set<Function> = new Set();
|
const set: Set<Listener> = new Set();
|
||||||
set.add(wrapper);
|
set.add(wrapper as Listener);
|
||||||
this.Handlers.set(type, set);
|
this.Handlers.set(type, set);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+19
-7
@@ -14,6 +14,7 @@ export class Process {
|
|||||||
private _StdoutChunks: Uint8Array[] = [];
|
private _StdoutChunks: Uint8Array[] = [];
|
||||||
private _StderrChunks: Uint8Array[] = [];
|
private _StderrChunks: Uint8Array[] = [];
|
||||||
private _Settled: boolean = false;
|
private _Settled: boolean = false;
|
||||||
|
private _EventEmitter: EventEmitter<ShellEventMap>;
|
||||||
private readonly _MaxChunkByteSize: number;
|
private readonly _MaxChunkByteSize: number;
|
||||||
|
|
||||||
readonly PID: number;
|
readonly PID: number;
|
||||||
@@ -21,7 +22,6 @@ export class Process {
|
|||||||
readonly State: ShellState;
|
readonly State: ShellState;
|
||||||
readonly Args: string[];
|
readonly Args: string[];
|
||||||
readonly Flags: string[];
|
readonly Flags: string[];
|
||||||
EventEmitter: EventEmitter<ShellEventMap>;
|
|
||||||
|
|
||||||
constructor(pid: number, state: ShellState, descriptor: CommandDescriptor, flags: string[], args: string[]) {
|
constructor(pid: number, state: ShellState, descriptor: CommandDescriptor, flags: string[], args: string[]) {
|
||||||
this.PID = pid;
|
this.PID = pid;
|
||||||
@@ -31,7 +31,7 @@ export class Process {
|
|||||||
this.Args = args;
|
this.Args = args;
|
||||||
// Check if positive later and throw an error if so
|
// Check if positive later and throw an error if so
|
||||||
this._MaxChunkByteSize = 1024;
|
this._MaxChunkByteSize = 1024;
|
||||||
this.EventEmitter = new EventEmitter<ShellEventMap>();
|
this._EventEmitter = new EventEmitter<ShellEventMap>();
|
||||||
}
|
}
|
||||||
|
|
||||||
private concatUint8Arrays(arrays: Uint8Array[]): Uint8Array {
|
private concatUint8Arrays(arrays: Uint8Array[]): Uint8Array {
|
||||||
@@ -67,13 +67,13 @@ export class Process {
|
|||||||
|
|
||||||
if (data.length <= this._MaxChunkByteSize) {
|
if (data.length <= this._MaxChunkByteSize) {
|
||||||
chunks.push(data);
|
chunks.push(data);
|
||||||
this.EventEmitter.emit(eventType, { pid: this.PID, data });
|
this._EventEmitter.emit(eventType, { pid: this.PID, data });
|
||||||
return;
|
return;
|
||||||
} else {
|
} else {
|
||||||
const arr = this.divideToChunks(data);
|
const arr = this.divideToChunks(data);
|
||||||
for (const ent of arr) {
|
for (const ent of arr) {
|
||||||
chunks.push(ent);
|
chunks.push(ent);
|
||||||
this.EventEmitter.emit(eventType, { pid: this.PID, data: ent });
|
this._EventEmitter.emit(eventType, { pid: this.PID, data: ent });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -118,7 +118,7 @@ export class Process {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
this.EventEmitter.emit("result", { pid: this.PID, result, state: output.state });
|
this._EventEmitter.emit("result", { pid: this.PID, result, state: output.state });
|
||||||
this._Settled = true;
|
this._Settled = true;
|
||||||
})
|
})
|
||||||
.catch(error => {
|
.catch(error => {
|
||||||
@@ -137,7 +137,7 @@ export class Process {
|
|||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
this.EventEmitter.emit("result", { pid: this.PID, result, state: this.State });
|
this._EventEmitter.emit("result", { pid: this.PID, result, state: this.State });
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -161,7 +161,7 @@ export class Process {
|
|||||||
this.CommandDescriptor.name,
|
this.CommandDescriptor.name,
|
||||||
);
|
);
|
||||||
|
|
||||||
this.EventEmitter.emit("result", { pid: this.PID, result, state: this.State });
|
this._EventEmitter.emit("result", { pid: this.PID, result, state: this.State });
|
||||||
return;
|
return;
|
||||||
} else {
|
} else {
|
||||||
if (this._SignalHandler !== null) {
|
if (this._SignalHandler !== null) {
|
||||||
@@ -172,4 +172,16 @@ export class Process {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public on<K extends keyof ShellEventMap>(type: K, handler: (payload: ShellEventMap[K]) => void): () => void {
|
||||||
|
return this._EventEmitter.on(type, handler);
|
||||||
|
}
|
||||||
|
|
||||||
|
public once<K extends keyof ShellEventMap>(type: K, handler: (payload: ShellEventMap[K]) => void): () => void {
|
||||||
|
return this._EventEmitter.once(type, handler);
|
||||||
|
}
|
||||||
|
|
||||||
|
public off<K extends keyof ShellEventMap>(type: K, handler: (payload: ShellEventMap[K]) => void): void {
|
||||||
|
this._EventEmitter.off(type, handler);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -9,22 +9,24 @@ export class ProcessManager {
|
|||||||
private _Processes: Map<number, Process> = new Map();
|
private _Processes: Map<number, Process> = new Map();
|
||||||
private _PIDIndex: number = 0;
|
private _PIDIndex: number = 0;
|
||||||
|
|
||||||
EventEmitter: EventEmitter<ShellEventMap> = new EventEmitter();
|
private _EventEmitter: EventEmitter<ShellEventMap> = new EventEmitter();
|
||||||
|
|
||||||
public createProcess(state: ShellState, descriptor: CommandDescriptor, flags: string[], args: string[]): void {
|
public createProcess(state: ShellState, descriptor: CommandDescriptor, flags: string[], args: string[]): number {
|
||||||
const pid = ++this._PIDIndex;
|
const pid = ++this._PIDIndex;
|
||||||
const process = new Process(pid, state, descriptor, flags, args);
|
const process = new Process(pid, state, descriptor, flags, args);
|
||||||
this._Processes.set(pid, process);
|
this._Processes.set(pid, process);
|
||||||
|
|
||||||
process.EventEmitter.on("stdout", payload => this.EventEmitter.emit("stdout", payload));
|
process.on("stdout", payload => this._EventEmitter.emit("stdout", payload));
|
||||||
process.EventEmitter.on("stderr", payload => this.EventEmitter.emit("stderr", payload));
|
process.on("stderr", payload => this._EventEmitter.emit("stderr", payload));
|
||||||
process.EventEmitter.on("result", payload => {
|
process.on("result", payload => {
|
||||||
this._Processes.delete(payload.pid);
|
this._Processes.delete(payload.pid);
|
||||||
this.EventEmitter.emit("result", payload);
|
this._EventEmitter.emit("result", payload);
|
||||||
});
|
});
|
||||||
|
|
||||||
this.EventEmitter.emit("process", { pid, name: descriptor.name });
|
this._EventEmitter.emit("process", { pid, name: descriptor.name });
|
||||||
process.execute();
|
process.execute();
|
||||||
|
|
||||||
|
return pid;
|
||||||
}
|
}
|
||||||
|
|
||||||
public sendSignal(pid: number, signal: Signal): void {
|
public sendSignal(pid: number, signal: Signal): void {
|
||||||
@@ -51,4 +53,16 @@ export class ProcessManager {
|
|||||||
//Make global signals an enum later
|
//Make global signals an enum later
|
||||||
process.sendSignal({ type: "SIGKILL" } satisfies Signal);
|
process.sendSignal({ type: "SIGKILL" } satisfies Signal);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public on<K extends keyof ShellEventMap>(type: K, handler: (payload: ShellEventMap[K]) => void): () => void {
|
||||||
|
return this._EventEmitter.on(type, handler);
|
||||||
|
}
|
||||||
|
|
||||||
|
public once<K extends keyof ShellEventMap>(type: K, handler: (payload: ShellEventMap[K]) => void): () => void {
|
||||||
|
return this._EventEmitter.once(type, handler);
|
||||||
|
}
|
||||||
|
|
||||||
|
public off<K extends keyof ShellEventMap>(type: K, handler: (payload: ShellEventMap[K]) => void): void {
|
||||||
|
this._EventEmitter.off(type, handler);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -27,7 +27,8 @@ const DirectoryNodeSchema = z.object({
|
|||||||
ctime: z.number(),
|
ctime: z.number(),
|
||||||
atime: z.number(),
|
atime: z.number(),
|
||||||
type: z.literal("directory"),
|
type: z.literal("directory"),
|
||||||
children: z.array(z.lazy((): any => TreeNodeSchema)),
|
//eslint-ignore
|
||||||
|
children: z.array(z.lazy((): any => TreeNodeSchema)), // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||||
});
|
});
|
||||||
|
|
||||||
const TreeNodeSchema = z.union([FileNodeSchema, DirectoryNodeSchema]);
|
const TreeNodeSchema = z.union([FileNodeSchema, DirectoryNodeSchema]);
|
||||||
@@ -40,7 +41,8 @@ export function deserializeFileSystem(json: string): ReadonlyMap<number, TreeNod
|
|||||||
|
|
||||||
const map = new Map<number, TreeNode>();
|
const map = new Map<number, TreeNode>();
|
||||||
|
|
||||||
function parseNode(tree: any, parent: number): void {
|
// prettier-ignore
|
||||||
|
function parseNode(tree: any, parent: number): void { // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||||
if (tree.type === "directory") {
|
if (tree.type === "directory") {
|
||||||
const children: Record<string, number> = {};
|
const children: Record<string, number> = {};
|
||||||
|
|
||||||
@@ -75,7 +77,7 @@ export function deserializeFileSystem(json: string): ReadonlyMap<number, TreeNod
|
|||||||
mtime: tree.mtime,
|
mtime: tree.mtime,
|
||||||
ctime: tree.ctime,
|
ctime: tree.ctime,
|
||||||
atime: tree.atime,
|
atime: tree.atime,
|
||||||
content: createImmutableBuffer(new Uint8Array()),
|
content: createImmutableBuffer(Uint8Array.from(tree.content)),
|
||||||
};
|
};
|
||||||
map.set(tree.inode, Object.freeze(fileNode));
|
map.set(tree.inode, Object.freeze(fileNode));
|
||||||
}
|
}
|
||||||
|
|||||||
+71
-25
@@ -1,18 +1,40 @@
|
|||||||
import { COMMAND_REGISTRY } from "@core/command_registry";
|
import { COMMAND_REGISTRY } from "@core/command_registry";
|
||||||
import { createErrorResult, createSuccessResult, type Result, type ResultError } from "@core/result";
|
import { createErrorResult, type Result } from "@core/result";
|
||||||
import { getCurrentSession } from "@core/session_manager";
|
import { getCurrentSession } from "@core/session_manager";
|
||||||
import { withExitCode, withHistory, type ShellState } from "@core/shell_state";
|
import { withExitCode, withHistory, type ShellState } from "@core/shell_state";
|
||||||
import type { CommandNotFoundError, ParseError, PermissionDeniedError, ShellError } from "@core/util/errors";
|
import type { ShellError } from "@core/util/errors";
|
||||||
import { createImmutableBuffer } from "@core/util/immutable_buffer";
|
import { createImmutableBuffer } from "@core/util/immutable_buffer";
|
||||||
import { parseCommand } from "@core/util/parser";
|
import { parseCommand } from "@core/util/parser";
|
||||||
|
import { EventEmitter } from "./event_emitter";
|
||||||
|
import { ProcessManager } from "./process_manager";
|
||||||
|
|
||||||
export class Shell {
|
export class Shell {
|
||||||
static #Instance: Shell;
|
static #Instance: Shell;
|
||||||
static #Promise: Promise<Shell> | null = null;
|
static #Promise: Promise<Shell> | null = null;
|
||||||
private _State: Readonly<ShellState>;
|
private _State: Readonly<ShellState>;
|
||||||
|
private _ProcessManager: ProcessManager = new ProcessManager();
|
||||||
|
private _EventEmitter: EventEmitter<ShellEventMap> = new EventEmitter();
|
||||||
|
private _GlobalKeyMap: ReadonlyMap<string, string>;
|
||||||
|
|
||||||
|
public BoundPID: number | null = null;
|
||||||
|
|
||||||
private constructor(state: ShellState) {
|
private constructor(state: ShellState) {
|
||||||
this._State = Object.freeze(state);
|
this._State = Object.freeze(state);
|
||||||
|
this._GlobalKeyMap = new Map();
|
||||||
|
|
||||||
|
this._ProcessManager.on("stdout", payload => this._EventEmitter.emit("stdout", payload));
|
||||||
|
this._ProcessManager.on("stderr", payload => this._EventEmitter.emit("stderr", payload));
|
||||||
|
this._ProcessManager.on("process", payload => this._EventEmitter.emit("process", payload));
|
||||||
|
this._ProcessManager.on("result", payload => {
|
||||||
|
this._State = payload.state;
|
||||||
|
this._State = withExitCode(
|
||||||
|
this._State,
|
||||||
|
payload.result.type === "success" ? payload.result.exitCode : payload.result.error.exitCode,
|
||||||
|
);
|
||||||
|
|
||||||
|
if (this.BoundPID === payload.pid) this.BoundPID = null;
|
||||||
|
this._EventEmitter.emit("result", payload);
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
static async init(initialState: ShellState): Promise<Shell> {
|
static async init(initialState: ShellState): Promise<Shell> {
|
||||||
@@ -35,64 +57,76 @@ export class Shell {
|
|||||||
return Shell.#Promise;
|
return Shell.#Promise;
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Execute(input: string): Promise<Result<ShellError>> {
|
public async execute(input: string): Promise<void> {
|
||||||
let parsed;
|
let parsed;
|
||||||
try {
|
try {
|
||||||
parsed = parseCommand(input);
|
parsed = parseCommand(input);
|
||||||
} catch {
|
} catch {
|
||||||
return createErrorResult(
|
const result = createErrorResult(
|
||||||
"ParseError",
|
"ParseError",
|
||||||
`Parsing error - ${input}`,
|
`Parsing error - ${input}`,
|
||||||
{},
|
{},
|
||||||
createImmutableBuffer(new Uint8Array()),
|
createImmutableBuffer(new Uint8Array()),
|
||||||
createImmutableBuffer(new Uint8Array()),
|
createImmutableBuffer(new Uint8Array()),
|
||||||
"",
|
"",
|
||||||
) satisfies ResultError<ParseError>;
|
);
|
||||||
|
|
||||||
|
this._State = withExitCode(this._State, result.error.exitCode);
|
||||||
|
this._EventEmitter.emit("result", { pid: 0, result, state: this._State });
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (parsed.command === "") {
|
if (parsed.command === "") return;
|
||||||
return createSuccessResult(
|
|
||||||
"",
|
|
||||||
0,
|
|
||||||
createImmutableBuffer(new Uint8Array()),
|
|
||||||
createImmutableBuffer(new Uint8Array()),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
this._State = withHistory(this._State, input);
|
this._State = withHistory(this._State, input);
|
||||||
const command = COMMAND_REGISTRY.get(parsed.command);
|
const command = COMMAND_REGISTRY.get(parsed.command);
|
||||||
|
|
||||||
if (!command)
|
if (!command) {
|
||||||
return createErrorResult(
|
const result = createErrorResult(
|
||||||
"CommandNotFound",
|
"CommandNotFound",
|
||||||
`Command ${parsed.command} not found`,
|
`Command ${parsed.command} not found`,
|
||||||
{ command: parsed.command },
|
{ command: parsed.command },
|
||||||
createImmutableBuffer(new Uint8Array()),
|
createImmutableBuffer(new Uint8Array()),
|
||||||
createImmutableBuffer(new Uint8Array()),
|
createImmutableBuffer(new Uint8Array()),
|
||||||
parsed.command,
|
parsed.command,
|
||||||
) satisfies ResultError<CommandNotFoundError>;
|
);
|
||||||
|
|
||||||
|
this._State = withExitCode(this._State, result.error.exitCode);
|
||||||
|
this._EventEmitter.emit("result", { pid: 0, result, state: this._State });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
if (command.requiresRoot && getCurrentSession(this._State).user.uid != 0) {
|
if (command.requiresRoot && getCurrentSession(this._State).user.uid != 0) {
|
||||||
return createErrorResult(
|
const result = createErrorResult(
|
||||||
"PermissionDenied",
|
"PermissionDenied",
|
||||||
`Permission Denied`,
|
`Permission Denied`,
|
||||||
{ resource: `Execution of the ${command.name} command` },
|
{ resource: `Execution of the ${command.name} command` },
|
||||||
createImmutableBuffer(new Uint8Array()),
|
createImmutableBuffer(new Uint8Array()),
|
||||||
createImmutableBuffer(new Uint8Array()),
|
createImmutableBuffer(new Uint8Array()),
|
||||||
parsed.command,
|
parsed.command,
|
||||||
) satisfies ResultError<PermissionDeniedError>;
|
);
|
||||||
|
|
||||||
|
this._State = withExitCode(this._State, result.error.exitCode);
|
||||||
|
this._EventEmitter.emit("result", { pid: 0, result, state: this._State });
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const out = command.fn(this._State, parsed.flags, parsed.args);
|
const pid = this._ProcessManager.createProcess(this._State, command, parsed.flags, parsed.args);
|
||||||
this._State = out.state;
|
this.BoundPID = pid;
|
||||||
|
}
|
||||||
|
|
||||||
if (out.result.type === "error") {
|
public sendInput(input: string): void {
|
||||||
this._State = withExitCode(this._State, out.result.error.exitCode);
|
const signal = this._GlobalKeyMap.get(input);
|
||||||
|
|
||||||
|
if (signal !== undefined) {
|
||||||
|
if (this.BoundPID !== null) {
|
||||||
|
this._ProcessManager.sendSignal(this.BoundPID, { type: signal });
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
this._State = withExitCode(this._State, out.result.exitCode);
|
if (this.BoundPID !== null) {
|
||||||
|
this._ProcessManager.sendSignal(this.BoundPID, { type: "INPUT", payload: input });
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return out.result;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public get State(): Readonly<ShellState> {
|
public get State(): Readonly<ShellState> {
|
||||||
@@ -106,6 +140,18 @@ export class Shell {
|
|||||||
}
|
}
|
||||||
return Shell.#Instance;
|
return Shell.#Instance;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public on<K extends keyof ShellEventMap>(type: K, handler: (payload: ShellEventMap[K]) => void): () => void {
|
||||||
|
return this._EventEmitter.on(type, handler);
|
||||||
|
}
|
||||||
|
|
||||||
|
public once<K extends keyof ShellEventMap>(type: K, handler: (payload: ShellEventMap[K]) => void): () => void {
|
||||||
|
return this._EventEmitter.once(type, handler);
|
||||||
|
}
|
||||||
|
|
||||||
|
public off<K extends keyof ShellEventMap>(type: K, handler: (payload: ShellEventMap[K]) => void): void {
|
||||||
|
this._EventEmitter.off(type, handler);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface ShellEventMap {
|
export interface ShellEventMap {
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { MD5 } from "./hash";
|
/* import { MD5 } from "./hash";
|
||||||
|
|
||||||
//INDEXED DB IS SO FUCKING DOGSHIT ITS INSANE
|
//INDEXED DB IS SO FUCKING DOGSHIT ITS INSANE
|
||||||
|
|
||||||
@@ -71,3 +71,4 @@ function isChecksumMatching(json: string, checksum: string): boolean {
|
|||||||
const resourceChksm = MD5.hash(json);
|
const resourceChksm = MD5.hash(json);
|
||||||
return resourceChksm === checksum;
|
return resourceChksm === checksum;
|
||||||
}
|
}
|
||||||
|
*/
|
||||||
|
|||||||
+3
-3
@@ -52,7 +52,7 @@ export class MD5 {
|
|||||||
return (b & d) | (c & ~d);
|
return (b & d) | (c & ~d);
|
||||||
}
|
}
|
||||||
|
|
||||||
let AA = A,
|
const AA = A,
|
||||||
BB = B,
|
BB = B,
|
||||||
CC = C,
|
CC = C,
|
||||||
DD = D;
|
DD = D;
|
||||||
@@ -129,7 +129,7 @@ export class MD5 {
|
|||||||
return new Uint8Array([...out, ...zeroArray, ...lengthBytes]);
|
return new Uint8Array([...out, ...zeroArray, ...lengthBytes]);
|
||||||
}
|
}
|
||||||
|
|
||||||
private static sliceToBlocks(input: Uint8Array): number[][] {
|
/* private static sliceToBlocks(input: Uint8Array): number[][] {
|
||||||
const blocks: number[][] = [];
|
const blocks: number[][] = [];
|
||||||
|
|
||||||
for (let i = 0; i < input.length; i += 64) {
|
for (let i = 0; i < input.length; i += 64) {
|
||||||
@@ -138,7 +138,7 @@ export class MD5 {
|
|||||||
}
|
}
|
||||||
|
|
||||||
return blocks;
|
return blocks;
|
||||||
}
|
} */
|
||||||
|
|
||||||
private static sliceToWords(block: Uint8Array): number[] {
|
private static sliceToWords(block: Uint8Array): number[] {
|
||||||
const words: number[] = new Array<number>(16);
|
const words: number[] = new Array<number>(16);
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import type { CommandIO } from "@core/command_io";
|
||||||
import { descriptor as cd } from "@core/commands/cd";
|
import { descriptor as cd } from "@core/commands/cd";
|
||||||
import type { ResultError, ResultSuccess } from "@core/result";
|
import type { ResultError, ResultSuccess } from "@core/result";
|
||||||
import type { UserInfo } from "@core/session_manager";
|
import type { UserInfo } from "@core/session_manager";
|
||||||
@@ -44,6 +45,21 @@ const testTree: FixtureNode = {
|
|||||||
|
|
||||||
const fs = buildTestFS(testTree);
|
const fs = buildTestFS(testTree);
|
||||||
|
|
||||||
|
const stdout: Uint8Array[] = [];
|
||||||
|
const stderr: Uint8Array[] = [];
|
||||||
|
|
||||||
|
const io: CommandIO = {
|
||||||
|
writeStdout: (data: Uint8Array) => {
|
||||||
|
stdout.push(data);
|
||||||
|
},
|
||||||
|
writeStderr: (data: Uint8Array) => {
|
||||||
|
stderr.push(data);
|
||||||
|
},
|
||||||
|
getSignal: () => {
|
||||||
|
return new Promise(() => {});
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
const users: Map<number, UserInfo> = new Map();
|
const users: Map<number, UserInfo> = new Map();
|
||||||
const user: UserInfo = {
|
const user: UserInfo = {
|
||||||
username: "root",
|
username: "root",
|
||||||
@@ -56,9 +72,9 @@ users.set(0, user);
|
|||||||
|
|
||||||
const state: ShellState = createInitialShellState(fs, users, user);
|
const state: ShellState = createInitialShellState(fs, users, user);
|
||||||
|
|
||||||
test("changes cwd to home", () => {
|
test("changes cwd to home", async () => {
|
||||||
let newState = withCwd(state, 2);
|
let newState = withCwd(state, 2);
|
||||||
const output = cd.fn(newState, [], []);
|
const output = await cd.fn(io, newState, [], []);
|
||||||
newState = output.state;
|
newState = output.state;
|
||||||
const result = output.result;
|
const result = output.result;
|
||||||
const session = getCurrentSession(newState);
|
const session = getCurrentSession(newState);
|
||||||
@@ -67,10 +83,10 @@ test("changes cwd to home", () => {
|
|||||||
expect(session.cwd).toBe(0);
|
expect(session.cwd).toBe(0);
|
||||||
expect(session.pwd).toBe(2);
|
expect(session.pwd).toBe(2);
|
||||||
});
|
});
|
||||||
test("changes cwd to pwd", () => {
|
test("changes cwd to pwd", async () => {
|
||||||
let newState = withCwd(state, 2);
|
let newState = withCwd(state, 2);
|
||||||
|
|
||||||
const output = cd.fn(newState, [], ["-"]);
|
const output = await cd.fn(io, newState, [], ["-"]);
|
||||||
newState = output.state;
|
newState = output.state;
|
||||||
const result = output.result;
|
const result = output.result;
|
||||||
const session = getCurrentSession(newState);
|
const session = getCurrentSession(newState);
|
||||||
@@ -79,8 +95,8 @@ test("changes cwd to pwd", () => {
|
|||||||
expect(session.cwd).toBe(0);
|
expect(session.cwd).toBe(0);
|
||||||
expect(session.pwd).toBe(2);
|
expect(session.pwd).toBe(2);
|
||||||
});
|
});
|
||||||
test("changes cwd to 4", () => {
|
test("changes cwd to 4", async () => {
|
||||||
const output = cd.fn(state, [], ["/sub/bye"]);
|
const output = await cd.fn(io, state, [], ["/sub/bye"]);
|
||||||
const newState = output.state;
|
const newState = output.state;
|
||||||
const result = output.result;
|
const result = output.result;
|
||||||
const session = getCurrentSession(newState);
|
const session = getCurrentSession(newState);
|
||||||
@@ -90,8 +106,8 @@ test("changes cwd to 4", () => {
|
|||||||
expect(session.pwd).toBe(0);
|
expect(session.pwd).toBe(0);
|
||||||
});
|
});
|
||||||
|
|
||||||
test("returns an error result (tried to enter a non existent location)", () => {
|
test("returns an error result (tried to enter a non existent location)", async () => {
|
||||||
const output = cd.fn(state, [], ["/not/real"]);
|
const output = await cd.fn(io, state, [], ["/not/real"]);
|
||||||
const newState = output.state;
|
const newState = output.state;
|
||||||
const result = output.result;
|
const result = output.result;
|
||||||
const session = getCurrentSession(newState);
|
const session = getCurrentSession(newState);
|
||||||
@@ -101,8 +117,8 @@ test("returns an error result (tried to enter a non existent location)", () => {
|
|||||||
expect(session.pwd).toBe(0);
|
expect(session.pwd).toBe(0);
|
||||||
});
|
});
|
||||||
|
|
||||||
test("returns an error result (tried to enter a file)", () => {
|
test("returns an error result (tried to enter a file)", async () => {
|
||||||
const output = cd.fn(state, [], ["/hello.txt"]);
|
const output = await cd.fn(io, state, [], ["/hello.txt"]);
|
||||||
const newState = output.state;
|
const newState = output.state;
|
||||||
const result = output.result;
|
const result = output.result;
|
||||||
const session = getCurrentSession(newState);
|
const session = getCurrentSession(newState);
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import type { CommandIO } from "@core/command_io";
|
||||||
import { descriptor as echo } from "@core/commands/echo";
|
import { descriptor as echo } from "@core/commands/echo";
|
||||||
import type { ResultSuccess } from "@core/result";
|
import type { ResultSuccess } from "@core/result";
|
||||||
import type { UserInfo } from "@core/session_manager";
|
import type { UserInfo } from "@core/session_manager";
|
||||||
@@ -42,6 +43,21 @@ const testTree: FixtureNode = {
|
|||||||
|
|
||||||
const fs = buildTestFS(testTree);
|
const fs = buildTestFS(testTree);
|
||||||
|
|
||||||
|
const stdout: Uint8Array[] = [];
|
||||||
|
const stderr: Uint8Array[] = [];
|
||||||
|
|
||||||
|
const io: CommandIO = {
|
||||||
|
writeStdout: (data: Uint8Array) => {
|
||||||
|
stdout.push(data);
|
||||||
|
},
|
||||||
|
writeStderr: (data: Uint8Array) => {
|
||||||
|
stderr.push(data);
|
||||||
|
},
|
||||||
|
getSignal: () => {
|
||||||
|
return new Promise(() => {});
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
const users: Map<number, UserInfo> = new Map();
|
const users: Map<number, UserInfo> = new Map();
|
||||||
const user: UserInfo = {
|
const user: UserInfo = {
|
||||||
username: "root",
|
username: "root",
|
||||||
@@ -54,9 +70,9 @@ users.set(0, user);
|
|||||||
|
|
||||||
const state: ShellState = createInitialShellState(fs, users, user);
|
const state: ShellState = createInitialShellState(fs, users, user);
|
||||||
|
|
||||||
test("returns a Result of type success", () => {
|
test("returns a Result of type success", async () => {
|
||||||
const output = echo.fn(state, [], ["hello", "world"]);
|
const output = await echo.fn(io, state, [], ["hello", "world"]);
|
||||||
const string = new TextDecoder().decode(output.result.stdout.toArray());
|
const string = new TextDecoder().decode(stdout[0]);
|
||||||
|
|
||||||
expect(output.result.type).toBe("success");
|
expect(output.result.type).toBe("success");
|
||||||
expect((output.result as ResultSuccess).exitCode).toBe(0);
|
expect((output.result as ResultSuccess).exitCode).toBe(0);
|
||||||
|
|||||||
@@ -0,0 +1,79 @@
|
|||||||
|
import type { UserInfo } from "@core/session_manager";
|
||||||
|
import { createInitialShellState, type ShellState } from "@core/shell_state";
|
||||||
|
import { Shell } from "@shell/shell";
|
||||||
|
import { buildTestFS, type FixtureNode } from "@tests/helpers/filesystems_fixture";
|
||||||
|
import { test } from "vitest";
|
||||||
|
|
||||||
|
const testTree: FixtureNode = {
|
||||||
|
inode: 0,
|
||||||
|
name: "root",
|
||||||
|
type: "Dir",
|
||||||
|
children: [
|
||||||
|
{
|
||||||
|
inode: 1,
|
||||||
|
name: "hello.txt",
|
||||||
|
type: "File",
|
||||||
|
content: "Goodbye World!",
|
||||||
|
children: [],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
inode: 2,
|
||||||
|
name: "sub",
|
||||||
|
type: "Dir",
|
||||||
|
children: [
|
||||||
|
{
|
||||||
|
inode: 3,
|
||||||
|
name: "world.txt",
|
||||||
|
type: "File",
|
||||||
|
content: "Goodbye!",
|
||||||
|
children: [],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
inode: 4,
|
||||||
|
name: "bye",
|
||||||
|
type: "Dir",
|
||||||
|
children: [],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
};
|
||||||
|
|
||||||
|
const fs = buildTestFS(testTree);
|
||||||
|
|
||||||
|
const stdout: Uint8Array[] = [];
|
||||||
|
|
||||||
|
const users: Map<number, UserInfo> = new Map();
|
||||||
|
const user: UserInfo = {
|
||||||
|
username: "root",
|
||||||
|
uid: 0,
|
||||||
|
gid: 0,
|
||||||
|
group: [0],
|
||||||
|
home: 0,
|
||||||
|
};
|
||||||
|
users.set(0, user);
|
||||||
|
|
||||||
|
const state: ShellState = createInitialShellState(fs, users, user);
|
||||||
|
|
||||||
|
test("returns a Result of type success", async () => {
|
||||||
|
await Shell.init(state);
|
||||||
|
|
||||||
|
let result;
|
||||||
|
|
||||||
|
Shell.Instance?.on("result", payload => {
|
||||||
|
const decoder = new TextDecoder();
|
||||||
|
console.log(decoder.decode(payload.result.stdout.toArray()));
|
||||||
|
console.log(payload);
|
||||||
|
result = payload.result;
|
||||||
|
});
|
||||||
|
|
||||||
|
await Shell.Instance?.execute("async");
|
||||||
|
Shell.Instance?.sendInput("a");
|
||||||
|
Shell.Instance?.sendInput("b");
|
||||||
|
Shell.Instance?.sendInput("c");
|
||||||
|
Shell.Instance?.sendInput("d");
|
||||||
|
Shell.Instance?.sendInput(
|
||||||
|
"right now technically anything goes because its just a plain string however i plan on improving this system a bit later on",
|
||||||
|
);
|
||||||
|
Shell.Instance?.sendInput("ctrl+c");
|
||||||
|
});
|
||||||
@@ -56,10 +56,18 @@ const state: ShellState = createInitialShellState(fs, users, user);
|
|||||||
describe("Shell tests", () => {
|
describe("Shell tests", () => {
|
||||||
test("Successfully executes the cd command", async () => {
|
test("Successfully executes the cd command", async () => {
|
||||||
await Shell.init(state);
|
await Shell.init(state);
|
||||||
const result = await Shell.Instance?.Execute("cd /sub");
|
|
||||||
|
let result;
|
||||||
|
|
||||||
|
Shell.Instance?.on("result", payload => {
|
||||||
|
console.log(payload);
|
||||||
|
result = payload.result;
|
||||||
|
});
|
||||||
|
|
||||||
|
await Shell.Instance?.execute("cd /sub");
|
||||||
const statee = Shell.Instance?.State;
|
const statee = Shell.Instance?.State;
|
||||||
|
|
||||||
expect(result?.type).toEqual("success");
|
expect(result!.type).toEqual("success");
|
||||||
expect(getCurrentSession(statee!).history.length).toBe(1);
|
expect(getCurrentSession(statee!).history.length).toBe(1);
|
||||||
expect(getCurrentSession(statee!).history[0]).toEqual("cd /sub");
|
expect(getCurrentSession(statee!).history[0]).toEqual("cd /sub");
|
||||||
expect(getCurrentSession(statee!).cwd).toBe(2);
|
expect(getCurrentSession(statee!).cwd).toBe(2);
|
||||||
|
|||||||
Reference in New Issue
Block a user