WIP: new abstraction layer, file system now a singleton, shell should be too

This commit is contained in:
2026-05-13 17:56:19 +02:00
parent 106abd851a
commit 619de5e1f8
24 changed files with 628 additions and 302 deletions
+1
View File
@@ -8,6 +8,7 @@ declare global {
// interface PageState {} // interface PageState {}
// interface Platform {} // interface Platform {}
} }
namespace TermOS {}
} }
export {}; export {};
+45 -43
View File
@@ -1,12 +1,17 @@
import { VirtualFS, type TreeNode } from './fs';
import { Terminal, type PrintData } from '../terminal/terminal';
import { Stack } from '../stack'; import { Stack } from '../stack';
import { PASSWD, type User } from './etc/userData'; import { Terminal, type PrintData } from '../terminal/terminal';
import { ExitCode } from './metadata'; import {
import { COMMANDS, type CommandArgs, type CommandResultData, type ICommand } from './commandRegistry'; COMMANDS,
type CommandArgs,
type CommandResultData,
type ICommand
} from './commandRegistry';
import { GROUP, type Group } from './etc/groupData'; import { GROUP, type Group } from './etc/groupData';
import { Process } from './process'; import { PASSWD, type User } from './etc/userData';
import { VirtualFS, type TreeNode } from './fs';
import type { KeybindInhibitor } from './keybindInhibitor'; import type { KeybindInhibitor } from './keybindInhibitor';
import { ExitCode } from './metadata';
import { Process } from './process';
export enum Signal { export enum Signal {
SIGINT, SIGINT,
@@ -16,7 +21,7 @@ export enum Signal {
export type BashInitArgs = { export type BashInitArgs = {
io?: Terminal; io?: Terminal;
fs: Map<number, TreeNode>; fs: Map<number, TreeNode>;
user: {username: string, password: string}; user: { username: string; password: string };
}; };
export type Result = { export type Result = {
@@ -31,13 +36,12 @@ export class Bash {
private readonly _group: Group[]; private readonly _group: Group[];
private readonly _terminal!: Terminal; private readonly _terminal!: Terminal;
private readonly _commands: Record<string, ICommand>; private readonly _commands: Record<string, ICommand>;
private _userInstances: Stack<User>; private _userInstances: Stack<User>;
private user: User; private user: User;
private _process?: Process; private _process?: Process;
constructor(args: BashInitArgs) { constructor(args: BashInitArgs) {
this._commands = COMMANDS; this._commands = COMMANDS;
this._passwd = PASSWD; this._passwd = PASSWD;
@@ -46,33 +50,29 @@ export class Bash {
this._terminal = args.io!; this._terminal = args.io!;
const loginResult = this.userLogin(args.user.username, args.user.password); const loginResult = this.userLogin(args.user.username, args.user.password);
if(loginResult == ExitCode.ERROR) if (loginResult == ExitCode.ERROR)
this._terminal.throwExeption( this._terminal.throwExeption(
`Failed to initialize bash instance - access denied for user ${args.user.username}`, `Failed to initialize bash instance - access denied for user ${args.user.username}`,
ExitCode.ERROR ExitCode.ERROR
) );
this.user = this._userInstances.peek()!;
this.user = this._userInstances.peek()! this.vfs = new VirtualFS({ fs: args.fs, user: this.user });
this.vfs = new VirtualFS({ fs: args.fs, user: this.user});
} }
private _initNewUserSession(user: User): User { private _initNewUserSession(user: User): User {
if(!this._passwd.includes(user)) if (!this._passwd.includes(user))
this._terminal.throwExeption(`user not found under the name ${user.username}`, ExitCode.ERROR) this._terminal.throwExeption(
`user not found under the name ${user.username}`,
ExitCode.ERROR
);
this._userInstances.push(user); this._userInstances.push(user);
return user return user;
} }
private async _initNewProcess(command: ICommand, args: CommandArgs) { private async _initNewProcess(command: ICommand, args: CommandArgs) {
this._process = new Process( this._process = new Process(this, this.user.uid, 'TEMP PROCESS NAME', command, args);
this,
this.user.uid,
'TEMP PROCESS NAME',
command,
args
);
//this._terminal.isProcessActive = true; //this._terminal.isProcessActive = true;
} }
@@ -83,7 +83,7 @@ export class Bash {
output: output, output: output,
cmd: cmd cmd: cmd
}; };
console.log(this.vfs.formatPath(this.vfs.getPathByInode(inode)), "TEST TEST !@#"); console.log(this.vfs.formatPath(this.vfs.getPathByInode(inode)), 'TEST TEST !@#');
this._terminal.PrintOutput(data); this._terminal.PrintOutput(data);
} }
@@ -118,17 +118,16 @@ export class Bash {
} }
getProcess(): Process | ExitCode.ERROR { getProcess(): Process | ExitCode.ERROR {
if(this._process) { if (this._process) {
return this._process; return this._process;
} }
return ExitCode.ERROR; return ExitCode.ERROR;
} }
getProcessKeybindInhibitor(): KeybindInhibitor | null { getProcessKeybindInhibitor(): KeybindInhibitor | null {
if(this._process) { if (this._process) {
return this._process.getKeybindInhibitor(); return this._process.getKeybindInhibitor();
} } else return null;
else return null;
} }
getTerminalWidth(): number { getTerminalWidth(): number {
@@ -140,20 +139,20 @@ export class Bash {
} }
hasSudoPerms(uid: number): boolean { hasSudoPerms(uid: number): boolean {
return this._group[1].members.includes(uid); return this._group[0].members.includes(uid);
} }
async executeCommand(commandName: string, args: CommandArgs): Promise<Result> { async executeCommand(commandName: string, args: CommandArgs): Promise<Result> {
let result: Result = { exitCode: ExitCode.ERROR, path: this.getCwd() }; let result: Result = { exitCode: ExitCode.ERROR, path: this.getCwd() };
const command: ICommand = this._commands[commandName]; const command: ICommand = this._commands[commandName];
if (!command) this.throwError(result); if (!command) this.throwError(result);
if (command.root) { if (command.root) {
if (this.hasSudoPerms(this.user.uid)) { if (this.hasSudoPerms(this.user.uid)) {
await this._initNewProcess(command, args); await this._initNewProcess(command, args);
if(!this._process) throw new Error('failed to init new process'); if (!this._process) throw new Error('failed to init new process');
const out: Result = await this._process.getResult(); const out: Result = await this._process.getResult();
this._appendNewResult(this.getCwd(), out, this.user.history[0]); this._appendNewResult(this.getCwd(), out, this.user.history[0]);
} }
@@ -161,7 +160,7 @@ export class Bash {
} }
await this._initNewProcess(command, args); await this._initNewProcess(command, args);
if(!this._process) throw new Error('failed to init new process'); if (!this._process) throw new Error('failed to init new process');
const out: Result = await this._process.getResult(); const out: Result = await this._process.getResult();
console.log(out); console.log(out);
@@ -170,6 +169,10 @@ export class Bash {
return out; return out;
} }
static testMethod() {
//
}
throwError(result: Result): void { throwError(result: Result): void {
switch (result.exitCode) { switch (result.exitCode) {
default: { default: {
@@ -188,13 +191,12 @@ export class Bash {
} }
userLogin(username: string, passwd: string): ExitCode { userLogin(username: string, passwd: string): ExitCode {
const user: User | undefined = const user: User | undefined = this._passwd.find((user) => user.username === username);
this._passwd.find((user) => user.username === username);
if(user && user.passwd === passwd) { if (user && user.passwd === passwd) {
this._initNewUserSession(user); this._initNewUserSession(user);
return ExitCode.SUCCESS; return ExitCode.SUCCESS;
} }
return ExitCode.ERROR; return ExitCode.ERROR;
} }
+22 -22
View File
@@ -1,39 +1,39 @@
import { isBuildCommand } from "typescript"; import { WebG } from '$lib/shimagic/renderer/web_g_engine';
import type { KeyBind } from "../terminal/keybindRegistry"; import type { KeyBind } from '../terminal/keybindRegistry';
import type { Bash, Result } from "./bash"; import type { Bash, Result } from './bash';
import { cd } from "./commands/cd"; import { cd } from './commands/cd';
import { clear } from "./commands/clear"; import { clear } from './commands/clear';
import { ls } from "./commands/ls"; import { ls } from './commands/ls';
import { testProcess } from "./commands/testAsync"; import { testProcess } from './commands/testAsync';
export type ICommand = { export type ICommand = {
method: (this: Bash, args: CommandArgs) => Result; method: (this: Bash, args: CommandArgs) => Result;
keybinds?: Map<KeyBind, () => any>; keybinds?: Map<KeyBind, () => any>;
flags: string[]; flags: string[];
help: string; help: string;
root: boolean; root: boolean;
}; };
export type CommandArgs = { export type CommandArgs = {
flags: string[]; flags: string[];
args: string[]; args: string[];
}; };
export type CommandResultData = { export type CommandResultData = {
cmd: string; //the string that contains the shorthand for the command that was executed - used in a switch statement in parseResult cmd: string; //the string that contains the shorthand for the command that was executed - used in a switch statement in parseResult
data: any; //the data that the commmand may have returned like TreeNodes[] from ls data: any; //the data that the commmand may have returned like TreeNodes[] from ls
args?: CommandArgs; args?: CommandArgs;
}; };
TermOS.Shell.Command.
export const COMMANDS = { export const COMMANDS = {
cd, cd,
ls, ls,
clear, clear,
testProcess testProcess
} as const satisfies Record<string, ICommand>; } as const satisfies Record<string, ICommand>;
WebG.
/* //export const commands { /* //export const commands {
return: { return: {
method: this.cmd_return, method: this.cmd_return,
@@ -150,4 +150,4 @@ export const COMMANDS = {
flags: [], flags: [],
help: "", help: "",
} }
} */ } */
+1
View File
@@ -22,6 +22,7 @@ export const cmd_cd = function (this: Bash, args: CommandArgs): Result {
if (args.args[0] === '-') { if (args.args[0] === '-') {
[this.getFs().cwd, this.getFs().pwd] = [this.getFs().pwd, this.getFs().cwd]; [this.getFs().cwd, this.getFs().pwd] = [this.getFs().pwd, this.getFs().cwd];
result.exitCode = ExitCode.SUCCESS; result.exitCode = ExitCode.SUCCESS;
return result; return result;
} }
-6
View File
@@ -9,9 +9,3 @@ export enum ExitCode {
SUCCESS = 0, SUCCESS = 0,
ERROR = 1 ERROR = 1
} }
export type Permission = {
r: boolean;
w: boolean;
x: boolean;
};
+61 -65
View File
@@ -1,74 +1,70 @@
import type { Bash, Result } from "./bash"; import type { Bash, Result } from './bash';
import type { CommandArgs, ICommand } from "./commandRegistry"; import type { CommandArgs, ICommand } from './commandRegistry';
import { KeybindInhibitor } from "./keybindInhibitor"; import { KeybindInhibitor } from './keybindInhibitor';
import { ExitCode } from "./metadata"; import { ExitCode } from './metadata';
export class Process { export class Process {
private _bash: Bash;
private _result: Result;
private _uid: number;
private _name: string;
private _initTimestamp: Date;
private _keybindInhibitor?: KeybindInhibitor;
private _abortController: AbortController;
private _bash: Bash; constructor(
private _result: Result; _bashInstance: Bash,
private _uid: number; uid: number,
private _name: string; name: string,
private _initTimestamp: Date; command: ICommand,
private _keybindInhibitor?: KeybindInhibitor; args: CommandArgs
private _abortController: AbortController; ) {
this._bash = _bashInstance;
constructor( this._result = { exitCode: ExitCode.ERROR, path: this._bash.getCwd() };
_bashInstance: Bash, this._uid = uid;
uid: number, this._name = name;
name: string, this._initTimestamp = new Date();
command: ICommand, this._abortController = new AbortController();
args: CommandArgs
) {
this._bash = _bashInstance;
this._result = { exitCode: ExitCode.ERROR, path: this._bash.getCwd() }
this._uid = uid;
this._name = name;
this._initTimestamp = new Date();
this._abortController = new AbortController();
if(command.keybinds) {
this._keybindInhibitor = new KeybindInhibitor(command.keybinds);
}
this._Run(command, _bashInstance, args);
}
public getKeybindInhibitor(): KeybindInhibitor | null {
if(this._keybindInhibitor) {
return this._keybindInhibitor;
}
else {
return null;
}
}
public sigKill(callback: () => void): ExitCode { if (command.keybinds) {
this._abortController.abort(); this._keybindInhibitor = new KeybindInhibitor(command.keybinds);
callback(); }
return ExitCode.SUCCESS //Only temp, need to add ExitCode.INT this._Run(command, _bashInstance, args);
} }
public getUid(): number { public getKeybindInhibitor(): KeybindInhibitor | null {
return this._uid; if (this._keybindInhibitor) {
} return this._keybindInhibitor;
} else {
return null;
}
}
public getInitTime(): Date { public sigKill(callback: () => void): ExitCode {
return this._initTimestamp; this._abortController.abort();
} callback();
public getName(): string { return ExitCode.SUCCESS; //Only temp, need to add ExitCode.INT
return this._name; }
}
public async getResult(): Promise<Result> { public getUid(): number {
return this._result; return this._uid;
} }
private async _Run(command: ICommand, bashInstance: Bash, args: CommandArgs) { public getInitTime(): Date {
this._result = command.method.call( return this._initTimestamp;
bashInstance, args); }
}
public getName(): string {
} return this._name;
}
public async getResult(): Promise<Result> {
return this._result;
}
private async _Run(command: ICommand, bashInstance: Bash, args: CommandArgs) {
this._result = command.method.call(bashInstance, args);
}
}
+5 -8
View File
@@ -1,4 +1,3 @@
import { TermOS } from '$lib/termos/termos';
import type { TreeNode } from '../bash/fs'; import type { TreeNode } from '../bash/fs';
//import { type ILocale } from './localeRegistry'; //import { type ILocale } from './localeRegistry';
import { Terminal, type PageCallbacks, type TermInitArgs } from './terminal'; import { Terminal, type PageCallbacks, type TermInitArgs } from './terminal';
@@ -9,7 +8,7 @@ export function isInitializing(): boolean {
return initializing; return initializing;
} }
function jsonToNodeTable(data: any): Map<number, TreeNode> { function jsonToNodeTable(data: JSON): Map<number, TreeNode> {
const FsTable: Map<number, TreeNode> = new Map<number, TreeNode>(); const FsTable: Map<number, TreeNode> = new Map<number, TreeNode>();
const entryList = Object.entries(data); const entryList = Object.entries(data);
@@ -24,7 +23,7 @@ function jsonToNodeTable(data: any): Map<number, TreeNode> {
func: object.Func, func: object.Func,
children: object.Children, children: object.Children,
content: object.Content, content: object.Content,
link: object.Link, link: object.Target,
permission: { permission: {
user: { user: {
r: object.Permission[0]?.Read, r: object.Permission[0]?.Read,
@@ -57,7 +56,7 @@ function jsonToNodeTable(data: any): Map<number, TreeNode> {
return FsTable; return FsTable;
} }
async function fetchFsJson(sig: string): Promise<any> { async function fetchFsJson(sig: string): Promise<JSON> {
const signature: string | null = localStorage.getItem('signature'); const signature: string | null = localStorage.getItem('signature');
if (signature !== sig || signature === null || localStorage.getItem('fs') === null) { if (signature !== sig || signature === null || localStorage.getItem('fs') === null) {
@@ -108,16 +107,14 @@ async function fetchLocale(id: string): Promise<any> {
return data; return data;
} }
TermOS.Shell.Bash;
export async function initTerminal( export async function initTerminal(
user: { username: string; password: string }, user: { username: string; password: string },
callbackInit: PageCallbacks, callbackInit: PageCallbacks,
localeId: string localeId: string
): Promise<Terminal> { ): Promise<Shell> {
try { try {
const sig = await fetchFsSignature('/src/lib/assets/fs/signature'); const sig = await fetchFsSignature('/src/lib/assets/fs/signature');
const fsJson = await fetchFsJson(sig); const fsJson: JSON = await fetchFsJson(sig);
const fs: Map<number, TreeNode> = jsonToNodeTable(fsJson); const fs: Map<number, TreeNode> = jsonToNodeTable(fsJson);
/* const locale: ILocale = { /* const locale: ILocale = {
id: localeId, id: localeId,
+2 -2
View File
@@ -23,7 +23,7 @@ function appendOutput(container: HTMLElement, props: OutputProps): Output | unde
} }
export function print(e: HTMLElement, data: PrintData): void { export function print(e: HTMLElement, data: PrintData): void {
if(data.cmd == 'clear') return; if (data.cmd == 'clear') return;
if (isInitializing()) { if (isInitializing()) {
console.error('Terminal is initializing! Skipping Print'); console.error('Terminal is initializing! Skipping Print');
@@ -37,7 +37,7 @@ export function print(e: HTMLElement, data: PrintData): void {
} }
export function clear(): void { export function clear(): void {
for(const instance of outputInstances) { for (const instance of outputInstances) {
unmount(instance, {}); unmount(instance, {});
} }
} }
+2
View File
@@ -33,6 +33,8 @@ export type PageCallbacks = {
getFontSize: () => number; getFontSize: () => number;
}; };
TermOS.Shell;
export class Terminal { export class Terminal {
private _bash: Bash; private _bash: Bash;
private _callbacks: Partial<PageCallbacks> = {}; private _callbacks: Partial<PageCallbacks> = {};
+3
View File
@@ -0,0 +1,3 @@
import { Command } from '../shell/command';
export class cd extends Command {}
+322
View File
@@ -0,0 +1,322 @@
import type { User } from '../shell/shell';
export class FileSystem {
static #instance: FileSystem;
private _fs: Map<number, TreeNode>;
private _root: number;
private constructor() {
const
this._fs = this._jsonToNodeTable();
this._root = this._fs.values().next().value!.inode;
if (!this._root) throw new Error('First entry in the filesystem map empty!');
}
private async _fetchFsSignature(path: string): Promise<any> {
try {
const response = await fetch(path);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.text();
return data.slice(0, 36); //32 characters of uuid + 4 dashes
} catch (error) {
console.error('Failed to fetch the file system signature', error);
}
}
private async _fetchFileSystem(path: string): Promise<any> {
const response = await fetch(path);
if (!response.ok) throw new Error('Failed to fetch the file system json');
const data = await response.json();
return data;
}
private async fetchFsJson(sig: string): Promise<JSON> {
const signature: string | null = localStorage.getItem('signature');
if (signature !== sig || signature === null || localStorage.getItem('fs') === null) {
const fs: JSON = await this._fetchFileSystem('/src/lib/assets/fs/fs.json');
localStorage.setItem('signature', sig);
localStorage.setItem('fs', JSON.stringify(fs));
console.info('FS fetched from file, new sinature:', sig);
return fs;
} else {
const fs: string | null = localStorage.getItem('fs');
if (fs === null) throw new Error('FS in LocalStorage is null!');
console.info('FS fetched from localStorage with signature:', sig);
return JSON.parse(fs);
}
}
private _jsonToNodeTable(data: JSON): Map<number, TreeNode> {
const FsTable: Map<number, TreeNode> = new Map<number, TreeNode>();
const entryList = Object.entries(data);
for (let i = 0; i < entryList.length; i++) {
const object: any = entryList[i][1];
const node: TreeNode = {
inode: object.Inode,
name: object.Name,
type: object.Type,
size: object.Size,
interactible: object.Interactible,
func: object.Func,
children: object.Children,
content: object.Content,
link: object.Target,
permission: {
user: {
r: object.Permission[0]?.Read,
w: object.Permission[0]?.Write,
x: object.Permission[0]?.Exec
},
group: {
r: object.Permission[1]?.Read,
w: object.Permission[1]?.Write,
x: object.Permission[1]?.Exec
},
other: {
r: object.Permission[2]?.Read,
w: object.Permission[2]?.Write,
x: object.Permission[2]?.Exec
}
},
owner: object.Owner,
group: object.Group,
timestamps: {
modified: new Date(object.TimeStamps.MTime),
changed: new Date(object.TimeStamps.CTime),
accessed: new Date(object.TimeStamps.ATime)
},
parent: object.Parent
};
FsTable.set(object.Inode, node);
}
return FsTable;
}
private _createNode(name: string, type: Type, path: number, user: User): void {
const currTime: Date = new Date();
const node: TreeNode = {
parent: path,
inode: this._fs.size + 1,
name: name,
type: type,
size: 4096,
children: [],
content: '',
link: -1,
permission: {
user: {
r: true,
w: true,
x: false
},
group: {
r: true,
w: false,
x: false
},
other: {
r: true,
w: false,
x: false
}
},
owner: user.uid,
group: user.gid,
timestamps: {
modified: currTime,
changed: currTime,
accessed: currTime
},
interactible: false,
func: null
};
this._fs.set(this._fs.size + 1, node);
}
private _deleteNode(inode: number): void {
this._fs.delete(inode);
}
private _iNodeToPathString(inode: number): string | null {
const currentNode = this._fs.get(inode);
if (!currentNode) return null;
if (!currentNode.parent || currentNode.inode === this._root) return '/';
const parentPath: string | null = this._iNodeToPathString(currentNode.parent);
if (!parentPath) return null;
return parentPath === '/' ? `/${currentNode.name}` : `${parentPath}/${currentNode.name}`;
}
private _pathStringToNode(path: string): TreeNode | null {
// Truncates all slatshes at the start and end of the string
const normalizedPath: string = path.replace(/^\/+|\/+$/g, '');
// Splits the path to node names and filters them out from empty strings
const pathComponents: string[] = normalizedPath.split('/').filter((node) => node.length > 0);
let currentNode: TreeNode | undefined = this._fs.get(this._root);
if (!currentNode) return null;
if (pathComponents.length === 0) return currentNode;
for (const component of pathComponents) {
const childINode: number | undefined = this._getChildNodeByName(
currentNode!,
component
)?.inode;
if (!childINode) return null;
const nextNode = this._fs.get(childINode);
if (!nextNode) return null;
currentNode = nextNode;
}
return currentNode;
}
private _getChildNodeByName(node: TreeNode, name: string): TreeNode | null {
for (const inode of node.children) {
const child = this._fs.get(inode);
if (child && child.name === name) return child;
}
return null;
}
private _isAbsolutePath = (path: string): boolean => {
return typeof path === 'string' && path.startsWith('/');
};
public getPathByINode(inode: number): string | null {
return this._iNodeToPathString(inode);
}
public formatPath(path: string, user: User): string {
if (path.startsWith(user.home)) return path.replace(user.home, '~');
return path;
}
public resolvePath(path: string, user: User): TreeNode | null {
if (path === '/') return this._fs.get(this._root)!;
let parsedPath: string = path;
if (!this._isAbsolutePath(path)) {
const trail = this._iNodeToPathString(user.cwd!);
if (!trail)
throw new Error('Somehow the current user has his cwd set to a nonexistant directory', {
cause: 'iNodeToPathString returned null from user.cwd'
});
parsedPath = `${trail}/${path}`;
}
if (path.startsWith('~')) {
const trail = user.home;
if (!trail)
throw new Error('User has his home directory set to a nonexistant one or is undefined', {
cause: 'iNodeToPathString returned null from user.home'
});
parsedPath = `${trail}/${path.replace('~', '')}`;
}
return this._pathStringToNode(parsedPath);
}
public recursiveTraversalPre(
node: TreeNode,
callback: (param: TreeNode) => void,
childIndex?: number[],
depthIndex?: number
): void | null {
if (!depthIndex) depthIndex = 0;
if (!childIndex) childIndex = [0];
if (node.type != Type.File && node.children[childIndex[depthIndex]]) {
let unNode = this._fs.get(node.children[childIndex[depthIndex]]);
if (!unNode) return null;
node = unNode;
depthIndex++;
if (!childIndex[depthIndex]) childIndex[depthIndex] = 0;
callback(node);
} else {
let unNode = this._fs.get(node.parent);
if (!unNode) return null;
node = unNode;
childIndex[depthIndex] = 0;
depthIndex--;
childIndex[depthIndex]++;
}
if (depthIndex < 0) return;
this.recursiveTraversalPre(node, callback, childIndex, depthIndex);
}
public static get instance(): FileSystem {
if(!FileSystem.#instance) {
FileSystem.#instance = new FileSystem();
}
return FileSystem.instance;
}
}
export type TreeNode = {
inode: number;
parent: number;
name: string;
type: Type;
size: number; //Size in Bytes
children: number[];
content: string; // GUID of the cache file that contains the file contents.
link: number; // Links
permission: NodePermission;
owner: number;
group: number;
timestamps: TimeStamps;
interactible: boolean;
func: any;
};
export enum Type {
Directory = 16384,
File = 32768,
SymbolicLink = 40960
}
export type NodePermission = {
user: Permission;
group: Permission;
other: Permission;
};
export type Permission = {
r: boolean;
w: boolean;
x: boolean;
};
export type TimeStamps = {
modified: Date;
changed: Date;
accessed: Date;
};
-1
View File
@@ -1 +0,0 @@
declare namespace FileSystem {}
-7
View File
@@ -1,7 +0,0 @@
namespace TermOS {
export namespace Shell {
export class Bash {
private readonly _fs: TermOS.
}
}
}
-27
View File
@@ -1,27 +0,0 @@
namespace TermOS {
export namespace Shell {
export abstract class Command {
public abstract readonly _flags: CommandFlag[];
public abstract readonly _root: boolean;
public abstract readonly _keybinds?: Map<KeyBind, () => any>;
public abstract readonly _help: string; //TODO: Dont know where to pull the help text from yet
public abstract result: CommandResult = { bin: this.constructor.name };
public abstract Main(this: Bash, flags: CommandFlag[], args: string[]) {}
}
export type CommandFlag = {
flag: string;
values?: string[];
};
export type CommandResult = {
bin: string;
flags?: CommandFlag[];
args?: string[];
path: number;
exitcode: ExitCode;
data?: any;
};
}
}
+23
View File
@@ -0,0 +1,23 @@
export abstract class Command {
public abstract readonly _flags: CommandFlag[];
public abstract readonly _root: boolean;
//public abstract readonly _keybinds?: Map<KeyBind, () => any>;
public abstract readonly _help: string; //TODO: Dont know where to pull the help text from yet
public abstract result: CommandResult;
public abstract Main(this: Shell, flags: CommandFlag[], args: string[]): void;
}
export type CommandFlag = {
flag: string;
values?: string[];
};
export type CommandResult = {
bin: string;
flags?: CommandFlag[];
args?: string[];
path: number;
exitcode: ExitCode;
data?: any;
};
@@ -1,30 +1,30 @@
import type { CommandArgs } from "$lib/stores/bash/commandRegistry"; import type { Command, CommandResult } from "./command";
import type { KeybindInhibitor } from "$lib/stores/bash/keybindInhibitor";
import type { ExitCode } from "$lib/stores/bash/metadata";
namespace TermOS {
export namespace Shell {
export class Process { export class Process {
private _bash: Bash; private _shell: Shell;
private _uid: number; private _uid: number;
private _name: string; private _name: string;
private _timestamp: Date; private _timestamp: Date;
private _keybindInhibitor?: KeybindInhibitor; //private _keybindInhibitor?: KeybindInhibitor;
private _abortController: AbortController; private _abortController: AbortController;
private _result: CommandResult;
constructor( constructor(
bash: Bash, bash: Shell,
uid: number, uid: number,
name: string, name: string,
command: Command, command: Command,
args: CommandArgs args: CommandArgs
) { ) {
this._bash = bash; this._shell = shell;
this._uid = uid; this._uid = uid;
this._name = name; this._name = name;
this._timestamp = new Date(); this._timestamp = new Date();
this._abortController = new AbortController(); this._abortController = new AbortController();
this._result: CommandResult = { exitCode: ExitCode.ERROR, path: this._bash.getCwd() }
if(command._keybinds) { if(command._keybinds) {
this._keybindInhibitor = new KeybindInhibitor(command.keybinds) this._keybindInhibitor = new KeybindInhibitor(command.keybinds)
} }
@@ -57,7 +57,11 @@ namespace TermOS {
return this._name return this._name
} }
public async get Result(): Promise<CommandResult> public async get Result(): Promise<CommandResult> {
return this._result;
}
private async _Exec(command: Command, shell: Shell, flags: CommandFlag[], args: string[]) {
this._result = Command.
}
} }
}
}
+44
View File
@@ -0,0 +1,44 @@
import type { Stack } from '$lib/stores/stack';
import { FileSystem } from '../filesystem/filesystem';
export class Shell {
private readonly _fs: FileSystem;
private _passwd: User[];
private _group: Group[];
private _commands: Command[];
private _userSessions: Stack<User>;
private user: User;
private _process?: Process;
constructor() {
this._fs = new FileSystem();
}
}
export enum ExitCode {
OK = 0,
ERR = 1,
INT = 2
}
export type User = {
username: string;
password: string;
readonly uid: number;
readonly gid: number;
home: string;
accessible: boolean;
history: string;
cwd?: number;
pwd?: number;
};
export type Group = {
groupname: string;
gid: number;
members: number[];
};
+11
View File
@@ -0,0 +1,11 @@
export namespace IO {
//const _io: HTMLElement = document.getElementById('output-wrapper');
export function PrintOutput(): void {}
export function ClearOutput(): void {
console.log('clear');
}
}
export {};
+48 -89
View File
@@ -1,82 +1,60 @@
declare namespace TermOS { import { Shell } from "./shell/shell";
export async function Initialize() {} import FileSystem
export declare namespace Shell {
async function _init() {}
export type User = { export async function Initialize() {}
username: string;
password: string;
readonly uid: number;
readonly gid: number;
home: string;
accessible: boolean;
history: string;
cwd?: number;
pwd?: number;
};
export type Group = { export const CommandRegistry: Record<string, Command> = {
groupname: string; cd
gid: number; } as const satisfies Record<string, Command>;
members: number[];
};
export enum ExitCode { export declare namespace Terminal {
OK = 0, async function _init() {}
ERR = 1,
INT = 2 export class KeybindInhibitor {
private readonly _keybinds: Map<KeyBind, () => any>;
constructor(keybinds: Map<KeyBind, () => any>) {
this._keybinds = keybinds;
}
private parseModifierStates(event: KeyboardEvent): Modifier[] | undefined {
const mods: Modifier[] = [];
if (event.altKey) mods.push('Alt');
if (event.ctrlKey) mods.push('Ctrl');
if (event.shiftKey) mods.push('Ctrl');
if (mods.length == 0) return undefined;
return mods;
}
processKeystroke(event: KeyboardEvent) {
const keybind: KeyBind = [
{
key: event.key,
mods: this.parseModifierStates(event)
}
];
const out = this._keybinds.get(keybind);
if (out) out();
} }
} }
export declare namespace Terminal { type Modifier = 'Ctrl' | 'Alt' | 'Shift';
async function _init() {}
export class KeybindInhibitor { type KeyStroke = {
private readonly _keybinds: Map<KeyBind, () => any>; key: string;
mods?: Modifier[];
};
constructor(keybinds: Map<KeyBind, () => any>) { export type KeyBind = [KeyStroke] | [KeyStroke, KeyStroke];
this._keybinds = keybinds;
}
private parseModifierStates(event: KeyboardEvent): Modifier[] | undefined {
const mods: Modifier[] = [];
if (event.altKey) mods.push('Alt');
if (event.ctrlKey) mods.push('Ctrl');
if (event.shiftKey) mods.push('Ctrl');
if (mods.length == 0) return undefined;
return mods;
}
processKeystroke(event: KeyboardEvent) {
const keybind: KeyBind = [
{
key: event.key,
mods: this.parseModifierStates(event)
}
];
const out = this._keybinds.get(keybind);
if (out) out();
}
}
type Modifier = 'Ctrl' | 'Alt' | 'Shift';
type KeyStroke = {
key: string;
mods?: Modifier[];
};
export type KeyBind = [KeyStroke] | [KeyStroke, KeyStroke];
}
export declare namespace FileSystem {}
} }
export declare namespace FileSystem {}
/* /*
namespace TermOS { namespace TermOS {
export async function Initialize() {} export async function Initialize() {}
@@ -230,22 +208,7 @@ namespace TermOS {
} }
} }
type TreeNode = {
inode: number;
parent: number;
name: string;
type: Type;
size: number; //Size in Bytes
children: number[];
content: string; // GUID of the cache file that contains the file contents.
link: number; // Links
permission: NodePermission;
owner: number;
group: number;
timestamps: TimeStamps;
interactible: boolean;
func: any;
}
enum Type { enum Type {
Directory = 16384, Directory = 16384,
@@ -259,11 +222,7 @@ namespace TermOS {
other: Permission; other: Permission;
} }
type TimeStamps = {
modified: Date;
changed: Date;
accessed: Date;
}
// TODO: Finish this // TODO: Finish this
enum ExitCode { enum ExitCode {
View File
View File
View File
+22 -20
View File
@@ -1,11 +1,9 @@
<script lang="ts"> <script lang="ts">
import { Terminal, type PrintData } from '$lib/stores/terminal/terminal';
import { onMount } from 'svelte';
import Input from './terminal/Input.svelte';
import { initTerminal, isInitializing } from '$lib/stores/terminal/init.svelte';
import { clear, print } from '$lib/stores/terminal/stdio/io';
import type { User } from '$lib/stores/bash/etc/userData';
import { ExitCode } from '$lib/stores/bash/metadata'; import { ExitCode } from '$lib/stores/bash/metadata';
import { initTerminal } from '$lib/stores/terminal/init.svelte';
import { clear, print } from '$lib/stores/terminal/stdio/io';
import { Terminal, type PrintData } from '$lib/stores/terminal/terminal';
import Input from './terminal/Input.svelte';
const clearTerminal = (): void => clear(); const clearTerminal = (): void => clear();
@@ -13,7 +11,7 @@
export async function init(username: string, password: string) { export async function init(username: string, password: string) {
try { try {
terminal = await initTerminal({username, password}, callbackInit, 'en_US'); terminal = await initTerminal({ username, password }, callbackInit, 'en_US');
updateTerminal(); updateTerminal();
} catch (error) { } catch (error) {
console.error('terminal init failed', error); console.error('terminal init failed', error);
@@ -30,23 +28,25 @@
function getWidth() { function getWidth() {
const e = document.getElementById('cout'); const e = document.getElementById('cout');
if(!e){ if (!e) {
throw new Error('cant get width of the teminal element. Its null'); throw new Error('cant get width of the teminal element. Its null');
} }
//gets an int from padding property value (which is a string) by cutting last 2 letters "px" and parsing to int //gets an int from padding property value (which is a string) by cutting last 2 letters "px" and parsing to int
const padding: number = parseInt(window.getComputedStyle(e, null).getPropertyValue('padding').slice(0, -2)); const padding: number = parseInt(
return e.clientWidth - (padding * 2); window.getComputedStyle(e, null).getPropertyValue('padding').slice(0, -2)
);
return e.clientWidth - padding * 2;
} }
function getFontSize() { function getFontSize() {
const e = document.getElementById('cout'); const e = document.getElementById('cout');
if(!e) { if (!e) {
throw new Error('cant get font size of the terminal element. its null'); throw new Error('cant get font size of the terminal element. its null');
} }
const canvas = document.createElement('canvas'); const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d')!; const ctx = canvas.getContext('2d')!;
ctx.font = `${window.getComputedStyle(e, null).getPropertyValue('font-size')} 'JetBrains Mono', monospace;`; ctx.font = `${window.getComputedStyle(e, null).getPropertyValue('font-size')} 'JetBrains Mono', monospace;`;
return ctx.measureText('M').width; return ctx.measureText('M').width;
} }
@@ -55,7 +55,7 @@
terminalKeyInhibitor.processKeystroke(event); terminalKeyInhibitor.processKeystroke(event);
const processKeyInhibitor = terminal.getProcessKeyInhibitor(); const processKeyInhibitor = terminal.getProcessKeyInhibitor();
if(processKeyInhibitor != ExitCode.ERROR) { if (processKeyInhibitor != ExitCode.ERROR) {
processKeyInhibitor.processKeystroke(event); processKeyInhibitor.processKeystroke(event);
} }
@@ -81,7 +81,7 @@
} }
const elem = document.getElementById('cout'); const elem = document.getElementById('cout');
if(!elem){ if (!elem) {
throw new Error('cant scroll to bottom, element is null'); throw new Error('cant scroll to bottom, element is null');
} }
@@ -111,11 +111,13 @@
//let isProcessActive = $state(false); //let isProcessActive = $state(false);
let inputValue = $state<string>(''); let inputValue = $state<string>('');
</script> </script>
<label for="input" onkeydowncapture={(event) => inputHandler(event)} class="w-11/12"> <label for="input" onkeydowncapture={(event) => inputHandler(event)} class="w-11/12">
<div id="terminal" class=" transition-discrete terminal-window shadow-() h-full w-full rounded-md shadow-bg"> <div
id="terminal"
class=" terminal-window shadow-() h-full w-full rounded-md shadow-bg transition-discrete"
>
<div <div
class="terminal-bar flex h-9 w-full flex-row items-center rounded-t-md bg-bg-dark text-center font-terminal text-sm font-bold text-primary-dark light:bg-bg-dark-light light:text-primary-light" class="terminal-bar flex h-9 w-full flex-row items-center rounded-t-md bg-bg-dark text-center font-terminal text-sm font-bold text-primary-dark light:bg-bg-dark-light light:text-primary-light"
> >
@@ -124,7 +126,7 @@
<button class="size-2.5 cursor-pointer rounded-full p-0" title=""></button> <button class="size-2.5 cursor-pointer rounded-full p-0" title=""></button>
<button class="size-2.5 cursor-pointer rounded-full p-0" title=""></button> <button class="size-2.5 cursor-pointer rounded-full p-0" title=""></button>
</div> </div>
<div class=" flex mr-2 grow"> <div class=" mr-2 flex grow">
<h5>{username}</h5> <h5>{username}</h5>
<!-- prettier-ignore --> <!-- prettier-ignore -->
<h5 class=" mr-2">@terminal: </h5> <h5 class=" mr-2">@terminal: </h5>
@@ -153,8 +155,8 @@
to { to {
opacity: 1; opacity: 1;
display: block; display: block;
} }
} }
.dots-wrapper { .dots-wrapper {
& > button { & > button {
border: none; border: none;