Compare commits
60
Commits
cd08a4bf32
...
0.1.0
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
031f8f7726 | ||
|
|
ed8c27677c | ||
|
|
f4a74f67cf | ||
|
|
2f25e44681 | ||
|
|
d4ec6b0c49 | ||
|
|
de1ce64226 | ||
|
|
d5566aa494 | ||
|
|
cb9cd7a67a | ||
|
|
b161e42b3f | ||
|
|
492f1ba372 | ||
|
|
00200b4c75 | ||
|
|
584e594726 | ||
|
|
4fa284de13 | ||
|
|
dd804f6f14 | ||
|
|
832fc6c759 | ||
|
|
2a6e6c57c3 | ||
|
|
f2b5f86a6c | ||
|
|
933b1fc5e8 | ||
|
|
849e0e61f5 | ||
|
|
d642ee6258 | ||
|
|
9c5bd71a5c | ||
|
|
ec13299e95 | ||
|
|
e2ade5de29 | ||
|
|
b75e691a0b | ||
|
|
776a93e21b | ||
|
|
6cc9727091 | ||
|
|
2715e5e28e | ||
|
|
8a349330b0 | ||
|
|
2e9227f6d8 | ||
|
|
8e054a220d | ||
|
|
4776232377 | ||
|
|
d0f8376244 | ||
|
|
f1b69bb282 | ||
|
|
1b3314ab87 | ||
|
|
96e15a87f2 | ||
|
|
55b5d3a873 | ||
|
|
1ee2a2fe7a | ||
|
|
310218663d | ||
|
|
20718604e4 | ||
|
|
dad18cd4cc | ||
|
|
48aac3c883 | ||
|
|
268729bb62 | ||
|
|
e313aa5b9d | ||
|
|
16a1805f25 | ||
|
|
075c999435 | ||
|
|
dfa393b4d9 | ||
|
|
c39bbae091 | ||
|
|
a7798436d2 | ||
|
|
3ec3de71f4 | ||
|
|
0149937526 | ||
|
|
394e0b9e7c | ||
|
|
d26d7d35ac | ||
|
|
3e6d607e18 | ||
|
|
5d197b4513 | ||
|
|
6bbaaf60e6 | ||
|
|
7348d3723e | ||
|
|
8c0a7e7a6c | ||
|
|
f87aa4eb85 | ||
|
|
3b50214041 | ||
|
|
b9a27cea2a |
Vendored
+1
@@ -0,0 +1 @@
|
||||
{}
|
||||
Vendored
+1
@@ -0,0 +1 @@
|
||||
{}
|
||||
Vendored
+33
@@ -0,0 +1,33 @@
|
||||
{
|
||||
"file-explorer": true,
|
||||
"global-search": true,
|
||||
"switcher": true,
|
||||
"graph": true,
|
||||
"backlink": true,
|
||||
"canvas": true,
|
||||
"outgoing-link": true,
|
||||
"tag-pane": true,
|
||||
"footnotes": false,
|
||||
"properties": true,
|
||||
"page-preview": true,
|
||||
"daily-notes": true,
|
||||
"templates": true,
|
||||
"note-composer": true,
|
||||
"command-palette": true,
|
||||
"slash-command": false,
|
||||
"editor-status": true,
|
||||
"bookmarks": true,
|
||||
"markdown-importer": false,
|
||||
"zk-prefixer": false,
|
||||
"random-note": false,
|
||||
"outline": true,
|
||||
"word-count": true,
|
||||
"slides": false,
|
||||
"audio-recorder": false,
|
||||
"workspaces": false,
|
||||
"file-recovery": true,
|
||||
"publish": false,
|
||||
"sync": true,
|
||||
"bases": true,
|
||||
"webviewer": false
|
||||
}
|
||||
Vendored
+196
@@ -0,0 +1,196 @@
|
||||
{
|
||||
"main": {
|
||||
"id": "89ee32072433406f",
|
||||
"type": "split",
|
||||
"children": [
|
||||
{
|
||||
"id": "21d78959e637e988",
|
||||
"type": "tabs",
|
||||
"children": [
|
||||
{
|
||||
"id": "1db1d6b317bc05ae",
|
||||
"type": "leaf",
|
||||
"state": {
|
||||
"type": "markdown",
|
||||
"state": {
|
||||
"file": "README.md",
|
||||
"mode": "source",
|
||||
"source": false
|
||||
},
|
||||
"icon": "lucide-file",
|
||||
"title": "README"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"direction": "vertical"
|
||||
},
|
||||
"left": {
|
||||
"id": "6703a701fa3161c8",
|
||||
"type": "split",
|
||||
"children": [
|
||||
{
|
||||
"id": "59a1957ef4b6aa34",
|
||||
"type": "tabs",
|
||||
"children": [
|
||||
{
|
||||
"id": "af4cfba92021d1c8",
|
||||
"type": "leaf",
|
||||
"state": {
|
||||
"type": "file-explorer",
|
||||
"state": {
|
||||
"sortOrder": "alphabetical",
|
||||
"autoReveal": false,
|
||||
"showSearch": false,
|
||||
"searchQuery": ""
|
||||
},
|
||||
"icon": "lucide-folder-closed",
|
||||
"title": "Files"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "195ed2a7004c5679",
|
||||
"type": "leaf",
|
||||
"state": {
|
||||
"type": "search",
|
||||
"state": {
|
||||
"query": "",
|
||||
"matchingCase": false,
|
||||
"explainSearch": false,
|
||||
"collapseAll": false,
|
||||
"extraContext": false,
|
||||
"sortOrder": "alphabetical"
|
||||
},
|
||||
"icon": "lucide-search",
|
||||
"title": "Search"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "e0b0a93bee04adf7",
|
||||
"type": "leaf",
|
||||
"state": {
|
||||
"type": "bookmarks",
|
||||
"state": {
|
||||
"showSearch": false,
|
||||
"searchQuery": ""
|
||||
},
|
||||
"icon": "lucide-bookmark",
|
||||
"title": "Bookmarks"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"direction": "horizontal",
|
||||
"width": 300
|
||||
},
|
||||
"right": {
|
||||
"id": "cdb5787bc7b074a1",
|
||||
"type": "split",
|
||||
"children": [
|
||||
{
|
||||
"id": "4f7b084c90edcafa",
|
||||
"type": "tabs",
|
||||
"children": [
|
||||
{
|
||||
"id": "87c20e5388b56742",
|
||||
"type": "leaf",
|
||||
"state": {
|
||||
"type": "backlink",
|
||||
"state": {
|
||||
"file": "todo.md",
|
||||
"collapseAll": false,
|
||||
"extraContext": false,
|
||||
"sortOrder": "alphabetical",
|
||||
"showSearch": false,
|
||||
"searchQuery": "",
|
||||
"backlinkCollapsed": false,
|
||||
"unlinkedCollapsed": true
|
||||
},
|
||||
"icon": "links-coming-in",
|
||||
"title": "Backlinks"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "d06f3a18f218bb85",
|
||||
"type": "leaf",
|
||||
"state": {
|
||||
"type": "outgoing-link",
|
||||
"state": {
|
||||
"file": "todo.md",
|
||||
"linksCollapsed": false,
|
||||
"unlinkedCollapsed": true
|
||||
},
|
||||
"icon": "links-going-out",
|
||||
"title": "Outgoing links"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "5e8256b0c8cb4527",
|
||||
"type": "leaf",
|
||||
"state": {
|
||||
"type": "tag",
|
||||
"state": {
|
||||
"sortOrder": "frequency",
|
||||
"useHierarchy": true,
|
||||
"showSearch": false,
|
||||
"searchQuery": ""
|
||||
},
|
||||
"icon": "lucide-tags",
|
||||
"title": "Tags"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "c4c977be0ce05b9d",
|
||||
"type": "leaf",
|
||||
"state": {
|
||||
"type": "all-properties",
|
||||
"state": {
|
||||
"sortOrder": "frequency",
|
||||
"showSearch": false,
|
||||
"searchQuery": ""
|
||||
},
|
||||
"icon": "lucide-archive",
|
||||
"title": "All properties"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "bf5df26d52eb2371",
|
||||
"type": "leaf",
|
||||
"state": {
|
||||
"type": "outline",
|
||||
"state": {
|
||||
"file": "todo.md",
|
||||
"followCursor": false,
|
||||
"showSearch": false,
|
||||
"searchQuery": ""
|
||||
},
|
||||
"icon": "lucide-list",
|
||||
"title": "Outline"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"direction": "horizontal",
|
||||
"width": 300,
|
||||
"collapsed": true
|
||||
},
|
||||
"left-ribbon": {
|
||||
"hiddenItems": {
|
||||
"switcher:Open quick switcher": false,
|
||||
"graph:Open graph view": false,
|
||||
"canvas:Create new canvas": false,
|
||||
"daily-notes:Open today's daily note": false,
|
||||
"templates:Insert template": false,
|
||||
"command-palette:Open command palette": false,
|
||||
"bases:Create new base": false
|
||||
}
|
||||
},
|
||||
"active": "1db1d6b317bc05ae",
|
||||
"lastOpenFiles": [
|
||||
"src/util/posix.ts",
|
||||
"src/core/util/sort.ts"
|
||||
]
|
||||
}
|
||||
Vendored
+1
-1
@@ -19,7 +19,7 @@
|
||||
"type": "node",
|
||||
"request": "launch",
|
||||
"runtimeExecutable": "${workspaceFolder}/node_modules/.bin/tsx",
|
||||
"runtimeArgs": ["src/index.ts"],
|
||||
"runtimeArgs": ["src/dev.ts"],
|
||||
"cwd": "${workspaceFolder}",
|
||||
"console": "integratedTerminal",
|
||||
"skipFiles": ["<node_internals>/**"]
|
||||
|
||||
Vendored
+4
@@ -0,0 +1,4 @@
|
||||
{
|
||||
"typescript.validate.enable": true,
|
||||
"typescript.tsserver.experimental.enableProjectDiagnostics": true
|
||||
}
|
||||
@@ -1,3 +1,43 @@
|
||||
# termos
|
||||
# Termos
|
||||
|
||||
terminal emulation library that bases its functionality on the bash shell
|
||||
This library allows running a fully contained unix-like operating system written in pure typescript.
|
||||
|
||||
It supports all the basic operations like saving and reading files, creating new files and folders.
|
||||
It has support for users and permissions and can handle multiple user sessions at the same time.
|
||||
It doesnt implement a website friendly interface on its own. Thats one of the desing choices in this project, to make it as versatile as possible. But it shares a easy to use interface that you can plug into your frontend code to interact with it properly.
|
||||
|
||||
> [!NOTE]
|
||||
> Right now the project is still in alpha and this is just a small portion of whats to come that serves for demonstration purposes. The code and design will change in the future so most of this is not set in stone
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- [Node.js](https://nodejs.org/) installed (version 22 or higher)
|
||||
- [pnpm](https://pnpm.io/) installed (version 12 or higher)
|
||||
|
||||
## Installation
|
||||
|
||||
> [!NOTE]
|
||||
> If youre using Windows or MacOS as your operating system then the installation process might be different.
|
||||
> Refer to [this website][ref1] on how to install nodejs on your operating system
|
||||
> and [this website][ref2] for pnpm accordingly.
|
||||
|
||||
[ref1]: https://nodejs.org/en/download
|
||||
[ref2]: https://pnpm.io/installation
|
||||
|
||||
```bash
|
||||
git clone https://git.gornodox.dev/ChaosMaker/termos.git
|
||||
cd termos
|
||||
npm install
|
||||
```
|
||||
|
||||
## Running the project
|
||||
|
||||
```bash
|
||||
npm run dev
|
||||
```
|
||||
|
||||
## Running the test suite
|
||||
|
||||
```bash
|
||||
npm run test
|
||||
```
|
||||
|
||||
+1
-1
@@ -11,7 +11,7 @@ export default [
|
||||
...functional.configs.recommended,
|
||||
rules: {
|
||||
"functional/no-mixed-types": "off",
|
||||
"@typescript-eslint/no-unused-vars": ["error", { varsIgnorePattern: "^__" }],
|
||||
"@typescript-eslint/no-unused-vars": ["error", { varsIgnorePattern: "^__", argsIgnorePattern: "^__" }],
|
||||
"@typescript-eslint/no-restricted-imports": [
|
||||
"error",
|
||||
{
|
||||
|
||||
Generated
-3265
File diff suppressed because it is too large
Load Diff
+36
-5
@@ -1,22 +1,42 @@
|
||||
{
|
||||
"name": "termos",
|
||||
"version": "1.0.0",
|
||||
"description": "terminal emulation library that bases its functionality on the bash shell",
|
||||
"main": "index.ts",
|
||||
"version": "0.1.0",
|
||||
"description": "Emulation library for a unix-like operating-system written in pure typescript",
|
||||
"files": [
|
||||
"dist"
|
||||
],
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./dist/index.d.ts",
|
||||
"import": "./dist/index.js",
|
||||
"default": "./dist/index.js"
|
||||
}
|
||||
},
|
||||
"main": "./dist/index.js",
|
||||
"types": "./dist/index.d.ts",
|
||||
"scripts": {
|
||||
"test": "eslint . && vitest"
|
||||
"test": "eslint . && vitest",
|
||||
"dev": "pnpx tsx src/dev.ts",
|
||||
"build": "tsup src/index.ts --format esm --dts --clean"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "ssh://git@git.gornodox.dev:2222/ChaosMaker/termos.git"
|
||||
},
|
||||
"devEngines": {
|
||||
"packageManager": {
|
||||
"name": "pnpm",
|
||||
"version": "12^",
|
||||
"onFail": "warn"
|
||||
}
|
||||
},
|
||||
"keywords": [],
|
||||
"author": "gornodox",
|
||||
"license": "ISC",
|
||||
"type": "module",
|
||||
"devDependencies": {
|
||||
"@eslint/js": "^10.0.1",
|
||||
"@types/node": "^26.1.0",
|
||||
"@types/node": "^26.2.0",
|
||||
"eslint": "^10.6.0",
|
||||
"eslint-config-prettier": "^10.1.8",
|
||||
"eslint-plugin-functional": "^10.0.0",
|
||||
@@ -26,5 +46,16 @@
|
||||
"typescript-eslint": "^8.63.0",
|
||||
"vite-tsconfig-paths": "^6.1.1",
|
||||
"vitest": "^4.1.10"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"@types/node": {
|
||||
"optional": true
|
||||
}
|
||||
},
|
||||
"allowScripts": {
|
||||
"esbuild@0.28.1": true
|
||||
},
|
||||
"dependencies": {
|
||||
"tsup": "^9.0.0"
|
||||
}
|
||||
}
|
||||
|
||||
Generated
+2699
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,2 @@
|
||||
allowBuilds:
|
||||
esbuild: true
|
||||
@@ -0,0 +1,20 @@
|
||||
export interface TermosConfig {
|
||||
groups: string[];
|
||||
users: {
|
||||
username: string;
|
||||
groups: string[];
|
||||
home: string;
|
||||
}[];
|
||||
general: {
|
||||
user: string;
|
||||
serverAddress?: string;
|
||||
dbName?: string;
|
||||
idbName?: string;
|
||||
};
|
||||
filesystem: {
|
||||
json: string;
|
||||
maxNameLength?: number;
|
||||
maxPathLength?: number;
|
||||
maxSymlinkDepth?: number;
|
||||
};
|
||||
}
|
||||
+5
-3
@@ -1,13 +1,15 @@
|
||||
import type { Result, ShellError } from "./result";
|
||||
import type { CommandIO } from "./command_io";
|
||||
import type { Result } from "./result";
|
||||
import type { ShellState } from "./shell_state";
|
||||
import type { ShellError } from "./util/errors";
|
||||
|
||||
type CommandFn = (state: ShellState, flags: string[], args: string[]) => CommandOutput<ShellError>;
|
||||
export type CommandFn = (io: CommandIO, state: ShellState, args: string[]) => Promise<CommandOutput<ShellError>>;
|
||||
|
||||
export interface CommandDescriptor {
|
||||
fn: CommandFn;
|
||||
name: string;
|
||||
flags?: readonly FlagDescriptor[];
|
||||
requresRoot?: boolean;
|
||||
requiresRoot?: boolean;
|
||||
description?: string;
|
||||
keybinds?: readonly string[];
|
||||
}
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
import type { Signal } from "./signal";
|
||||
|
||||
export interface CommandIO {
|
||||
writeStdout(data: Uint8Array): void;
|
||||
writeStderr(data: Uint8Array): void;
|
||||
getSignal(): Promise<Signal>;
|
||||
}
|
||||
@@ -1,9 +1,21 @@
|
||||
import type { CommandDescriptor } from "./command";
|
||||
import { descriptor as cat } from "./commands/cat";
|
||||
import { descriptor as cd } from "./commands/cd";
|
||||
import { descriptor as clear } from "./commands/clear";
|
||||
import { descriptor as echo } from "./commands/echo";
|
||||
import { descriptor as ls } from "./commands/ls";
|
||||
import { descriptor as pwd } from "./commands/pwd";
|
||||
import { descriptor as testasync } from "./commands/testasync";
|
||||
|
||||
const reg = new Map<string, CommandDescriptor>();
|
||||
//reg.set(descriptor.name, descriptor <- imported const from command implementation file);
|
||||
reg.set(echo.name, echo);
|
||||
reg.set(cd.name, cd);
|
||||
reg.set(testasync.name, testasync);
|
||||
reg.set(ls.name, ls);
|
||||
reg.set(cat.name, cat);
|
||||
reg.set(pwd.name, pwd);
|
||||
reg.set(clear.name, clear);
|
||||
Object.freeze(reg);
|
||||
|
||||
export const COMMAND_REGISTRY: ReadonlyMap<string, CommandDescriptor> = reg;
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
import type { CommandDescriptor, CommandOutput } from "@core/command";
|
||||
import type { CommandIO } from "@core/command_io";
|
||||
import { createSuccessResult, type ResultSuccess } from "@core/result";
|
||||
import type { ShellState } from "@core/shell_state";
|
||||
import type { ShellError } from "@core/util/errors";
|
||||
|
||||
export const COMMAND_NAME = "";
|
||||
|
||||
async function main(io: CommandIO, state: ShellState, args: string[]): Promise<CommandOutput<ShellError>> {
|
||||
const result: ResultSuccess = createSuccessResult(COMMAND_NAME);
|
||||
|
||||
return {
|
||||
state: state,
|
||||
result,
|
||||
};
|
||||
}
|
||||
|
||||
export const descriptor: CommandDescriptor = {
|
||||
fn: main,
|
||||
name: COMMAND_NAME,
|
||||
};
|
||||
@@ -0,0 +1,76 @@
|
||||
import type { CommandDescriptor, CommandOutput } from "@core/command";
|
||||
import type { CommandIO } from "@core/command_io";
|
||||
import type { FileSystemCorruptionError } from "@core/filesystem/errors";
|
||||
import { type NodePointer } from "@core/filesystem/node";
|
||||
import { createErrorResult, createSuccessResult, type ResultSuccess } from "@core/result";
|
||||
import { getCurrentSession } from "@core/session_manager";
|
||||
import type { ShellState } from "@core/shell_state";
|
||||
import type { PathResolutionError, PermissionDeniedError, ShellError } from "@core/util/errors";
|
||||
import { resolvePath } from "@core/util/path_resolver";
|
||||
|
||||
export const COMMAND_NAME = "cat";
|
||||
|
||||
//Need to implement escape sequences
|
||||
async function main(io: CommandIO, state: ShellState, args: string[]): Promise<CommandOutput<ShellError>> {
|
||||
for (const arg of args) {
|
||||
let ptr: NodePointer;
|
||||
try {
|
||||
ptr = resolvePath(state, arg);
|
||||
} catch (e) {
|
||||
return {
|
||||
state,
|
||||
result: createErrorResult(
|
||||
"PathResolutionError",
|
||||
"No such file or directory",
|
||||
{ path: arg },
|
||||
COMMAND_NAME,
|
||||
),
|
||||
} satisfies CommandOutput<PathResolutionError>;
|
||||
}
|
||||
|
||||
if (!state.filesystem.isFile(ptr)) {
|
||||
const entries = state.filesystem.getNodeEntries(ptr);
|
||||
if (!entries) {
|
||||
throw {
|
||||
type: "FileSystemCorruption",
|
||||
message: "Reverse index entry missing. FileSystem corrupted",
|
||||
timestamp: Date.now(),
|
||||
} satisfies FileSystemCorruptionError;
|
||||
}
|
||||
return {
|
||||
state,
|
||||
result: createErrorResult(
|
||||
"PathResolutionError",
|
||||
`${entries[0]!.name} is a directory`,
|
||||
{ path: arg },
|
||||
COMMAND_NAME,
|
||||
),
|
||||
} satisfies CommandOutput<PathResolutionError>;
|
||||
}
|
||||
|
||||
const session = getCurrentSession(state);
|
||||
|
||||
if (!state.filesystem.canRead(ptr, session.user)) {
|
||||
return {
|
||||
state,
|
||||
result: createErrorResult("PermissionDenied", "Permission denied", { resource: arg }, COMMAND_NAME),
|
||||
} satisfies CommandOutput<PermissionDeniedError>;
|
||||
}
|
||||
|
||||
const content = await state.filesystem.read(ptr);
|
||||
|
||||
io.writeStdout(content);
|
||||
}
|
||||
|
||||
const result: ResultSuccess = createSuccessResult(COMMAND_NAME);
|
||||
|
||||
return {
|
||||
state: state,
|
||||
result,
|
||||
};
|
||||
}
|
||||
|
||||
export const descriptor: CommandDescriptor = {
|
||||
fn: main,
|
||||
name: COMMAND_NAME,
|
||||
};
|
||||
@@ -0,0 +1,78 @@
|
||||
import type { CommandDescriptor, CommandOutput } from "@core/command";
|
||||
import type { CommandIO } from "@core/command_io";
|
||||
import type { NodePointer } from "@core/filesystem/node";
|
||||
import { createErrorResult, createSuccessResult } from "@core/result";
|
||||
import { getCurrentSession } from "@core/session_manager";
|
||||
import { ShellState, withCwd } from "@core/shell_state";
|
||||
import {
|
||||
type InvalidArgumentsError,
|
||||
type PathResolutionError,
|
||||
type PermissionDeniedError,
|
||||
type ShellError,
|
||||
} from "@core/util/errors";
|
||||
import { resolvePath } from "@core/util/path_resolver";
|
||||
|
||||
export const COMMAND_NAME = "cd";
|
||||
|
||||
async function main(__io: CommandIO, state: ShellState, args: string[]): Promise<CommandOutput<ShellError>> {
|
||||
if (args.length > 1) {
|
||||
return {
|
||||
state,
|
||||
result: createErrorResult(
|
||||
"InvalidArguments",
|
||||
"The maximum ammount of arguments for this command is 1",
|
||||
{ expected: "cd <path>", actual: `cd ${args.toString().replace(/[,]/g, " ")}` },
|
||||
COMMAND_NAME,
|
||||
),
|
||||
} satisfies CommandOutput<InvalidArgumentsError>;
|
||||
}
|
||||
|
||||
let ptr: NodePointer;
|
||||
const session = getCurrentSession(state);
|
||||
|
||||
if (args[0] === undefined) {
|
||||
ptr = session.user.home;
|
||||
} else if (args[0] === "-") {
|
||||
ptr = session.pwd;
|
||||
} else {
|
||||
try {
|
||||
ptr = resolvePath(state, args[0]);
|
||||
} catch (e) {
|
||||
return {
|
||||
state,
|
||||
result: createErrorResult(
|
||||
"PathResolutionError",
|
||||
"No such file or directory",
|
||||
{ path: args[0]! },
|
||||
COMMAND_NAME,
|
||||
),
|
||||
} satisfies CommandOutput<PathResolutionError>;
|
||||
}
|
||||
}
|
||||
|
||||
if (state.filesystem.isFile(ptr)) {
|
||||
return {
|
||||
state,
|
||||
result: createErrorResult("PathResolutionError", "Not a directory", { path: args[0]! }, COMMAND_NAME),
|
||||
} satisfies CommandOutput<PathResolutionError>;
|
||||
}
|
||||
|
||||
if (!state.filesystem.canExecute(ptr, session.user)) {
|
||||
return {
|
||||
state,
|
||||
result: createErrorResult("PermissionDenied", "Permission denied", { resource: args[0]! }, COMMAND_NAME),
|
||||
} satisfies CommandOutput<PermissionDeniedError>;
|
||||
}
|
||||
|
||||
const returnState = withCwd(state, ptr);
|
||||
|
||||
return {
|
||||
state: returnState,
|
||||
result: createSuccessResult(COMMAND_NAME),
|
||||
};
|
||||
}
|
||||
|
||||
export const descriptor: CommandDescriptor = {
|
||||
fn: main,
|
||||
name: COMMAND_NAME,
|
||||
};
|
||||
@@ -0,0 +1,23 @@
|
||||
import type { CommandDescriptor, CommandOutput } from "@core/command";
|
||||
import type { CommandIO } from "@core/command_io";
|
||||
import { createSuccessResult, type ResultSuccess } from "@core/result";
|
||||
import type { ShellState } from "@core/shell_state";
|
||||
import type { ShellError } from "@core/util/errors";
|
||||
|
||||
export const COMMAND_NAME = "clear";
|
||||
|
||||
async function main(io: CommandIO, state: ShellState, __args: string[]): Promise<CommandOutput<ShellError>> {
|
||||
io.writeStdout(new TextEncoder().encode("\x1b[2J\x1b[0;0H"));
|
||||
|
||||
const result: ResultSuccess = createSuccessResult(COMMAND_NAME);
|
||||
|
||||
return {
|
||||
state: state,
|
||||
result,
|
||||
};
|
||||
}
|
||||
|
||||
export const descriptor: CommandDescriptor = {
|
||||
fn: main,
|
||||
name: COMMAND_NAME,
|
||||
};
|
||||
@@ -1,23 +1,19 @@
|
||||
import type { CommandDescriptor, CommandOutput } from "@core/command";
|
||||
import type { ResultSuccess, ShellError } from "@core/result";
|
||||
import type { CommandIO } from "@core/command_io";
|
||||
import { createSuccessResult, type ResultSuccess } from "@core/result";
|
||||
import type { ShellState } from "@core/shell_state";
|
||||
import { createImmutableBuffer } from "@core/util/immutable_buffer";
|
||||
import type { ShellError } from "@core/util/errors";
|
||||
|
||||
export const COMMAND_NAME = "echo";
|
||||
|
||||
function main(state: ShellState, flags: string[], args: string[]): CommandOutput<ShellError> {
|
||||
//Need to implement escape sequences
|
||||
async function main(io: CommandIO, state: ShellState, args: string[]): Promise<CommandOutput<ShellError>> {
|
||||
const joined = args.join(" ");
|
||||
const encoded = new TextEncoder().encode(joined);
|
||||
const encoded = new TextEncoder().encode(joined + "\n");
|
||||
|
||||
const stdout = createImmutableBuffer(encoded);
|
||||
io.writeStdout(encoded);
|
||||
|
||||
const result: ResultSuccess = {
|
||||
type: "success",
|
||||
exitCode: 0,
|
||||
stdout,
|
||||
stderr: createImmutableBuffer(new Uint8Array()),
|
||||
commandName: COMMAND_NAME,
|
||||
};
|
||||
const result: ResultSuccess = createSuccessResult(COMMAND_NAME);
|
||||
|
||||
return {
|
||||
state: state,
|
||||
|
||||
@@ -0,0 +1,488 @@
|
||||
import type { CommandDescriptor, CommandOutput } from "@core/command";
|
||||
import type { CommandIO } from "@core/command_io";
|
||||
import { NodePointer, NodeType, type DirectoryNode, type FileNode, type Node } from "@core/filesystem/node";
|
||||
import { createErrorResult, createSuccessResult } from "@core/result";
|
||||
import { getCurrentSession } from "@core/session_manager";
|
||||
import type { ShellState } from "@core/shell_state";
|
||||
import type { ShellError } from "@core/util/errors";
|
||||
import { resolvePath } from "@core/util/path_resolver";
|
||||
import { SortNodeBy, sortNodes } from "@core/util/sort";
|
||||
import { concatUint8Arrays } from "@termos/util/concat";
|
||||
import { convertToUnit } from "@termos/util/format_unit";
|
||||
|
||||
export const COMMAND_NAME = "ls";
|
||||
|
||||
interface DirEntry {
|
||||
name: string;
|
||||
ptr: NodePointer;
|
||||
}
|
||||
|
||||
async function main(io: CommandIO, state: ShellState, args: string[]): Promise<CommandOutput<ShellError>> {
|
||||
const entries: { ptr: NodePointer; path: string }[] = [];
|
||||
const paths: string[] = [];
|
||||
const e = new TextEncoder();
|
||||
|
||||
let options = {
|
||||
all: false,
|
||||
almostAll: false,
|
||||
long: false,
|
||||
noSort: false,
|
||||
noOwner: false,
|
||||
noGroup: false,
|
||||
sortBy: SortNodeBy.NAME,
|
||||
humanReadable: false,
|
||||
f: false,
|
||||
x: false,
|
||||
timestamp: "atime",
|
||||
reverse: false,
|
||||
recursive: false,
|
||||
quoteName: false,
|
||||
appendIndicator: false,
|
||||
numericUidGid: false,
|
||||
literal: false,
|
||||
inode: false,
|
||||
si: false,
|
||||
dereference: false,
|
||||
fullTime: false,
|
||||
};
|
||||
|
||||
for (let arg of args) {
|
||||
let val;
|
||||
if (arg.startsWith("--")) {
|
||||
arg = arg.slice(2);
|
||||
|
||||
if (arg.match(/\w+[=]{1}\w+/g)) {
|
||||
const flag = arg.split("=")[0];
|
||||
val = arg.split("=")[1] ?? "";
|
||||
|
||||
if (flag === "time" && isValidTimestamp(val)) {
|
||||
options.timestamp = val;
|
||||
continue;
|
||||
}
|
||||
if (flag === "sort" && isValidSortMethod(val)) {
|
||||
options.sortBy = val as SortNodeBy;
|
||||
continue;
|
||||
}
|
||||
return {
|
||||
state,
|
||||
result: createErrorResult("UsageError", `Invalid options`, {}, COMMAND_NAME),
|
||||
};
|
||||
}
|
||||
|
||||
switch (arg) {
|
||||
case "all":
|
||||
options.all = true;
|
||||
break;
|
||||
case "almost-all":
|
||||
options.almostAll = true;
|
||||
break;
|
||||
case "no-group":
|
||||
options.noGroup = true;
|
||||
break;
|
||||
case "human-readable":
|
||||
options.humanReadable = true;
|
||||
break;
|
||||
case "reverse":
|
||||
options.reverse = true;
|
||||
break;
|
||||
case "recursive":
|
||||
options.recursive = true;
|
||||
break;
|
||||
case "quote-name":
|
||||
options.quoteName = true;
|
||||
break;
|
||||
case "numeric-uid-gid":
|
||||
options.numericUidGid = true;
|
||||
break;
|
||||
case "inode":
|
||||
options.inode = true;
|
||||
break;
|
||||
case "dereference":
|
||||
options.dereference = true;
|
||||
break;
|
||||
case "literal":
|
||||
options.literal = true;
|
||||
break;
|
||||
case "si":
|
||||
options.si = true;
|
||||
options.humanReadable = true;
|
||||
break;
|
||||
case "full-time":
|
||||
options.fullTime = true;
|
||||
break;
|
||||
case "help":
|
||||
// handled separately
|
||||
break;
|
||||
default:
|
||||
return {
|
||||
state,
|
||||
result: createErrorResult("UsageError", `Invalid options`, {}, COMMAND_NAME),
|
||||
};
|
||||
break;
|
||||
}
|
||||
} else if (arg.startsWith("-")) {
|
||||
arg = arg.slice(1);
|
||||
|
||||
for (const c of arg) {
|
||||
switch (c) {
|
||||
case "l":
|
||||
options.long = true;
|
||||
break;
|
||||
case "a":
|
||||
options.all = true;
|
||||
break;
|
||||
case "A":
|
||||
options.almostAll = true;
|
||||
break;
|
||||
case "c":
|
||||
options.timestamp = "ctime";
|
||||
break;
|
||||
case "U":
|
||||
options.noSort = true;
|
||||
break;
|
||||
case "g":
|
||||
options.noOwner = true;
|
||||
options.long = true;
|
||||
break;
|
||||
case "G":
|
||||
options.noGroup = true;
|
||||
break;
|
||||
case "h":
|
||||
options.humanReadable = true;
|
||||
break;
|
||||
case "f":
|
||||
options.f = true;
|
||||
options.noSort = true;
|
||||
options.all = true;
|
||||
break;
|
||||
case "x":
|
||||
options.x = true;
|
||||
break;
|
||||
case "X":
|
||||
options.sortBy = SortNodeBy.EXTENSION;
|
||||
break;
|
||||
case "u":
|
||||
options.timestamp = "atime";
|
||||
break;
|
||||
case "t":
|
||||
options.sortBy = options.timestamp as SortNodeBy;
|
||||
break;
|
||||
case "S":
|
||||
options.sortBy = SortNodeBy.SIZE;
|
||||
break;
|
||||
case "r":
|
||||
options.reverse = true;
|
||||
break;
|
||||
case "R":
|
||||
options.recursive = true;
|
||||
break;
|
||||
case "Q":
|
||||
options.quoteName = true;
|
||||
break;
|
||||
case "p":
|
||||
options.appendIndicator = true;
|
||||
break;
|
||||
case "o":
|
||||
options.noGroup = true;
|
||||
options.long = true;
|
||||
break;
|
||||
case "n":
|
||||
options.numericUidGid = true;
|
||||
break;
|
||||
case "N":
|
||||
options.literal = true;
|
||||
break;
|
||||
case "i":
|
||||
options.inode = true;
|
||||
break;
|
||||
case "L":
|
||||
options.dereference = true;
|
||||
break;
|
||||
case "m":
|
||||
// -m: comma separated list (not in options yet)
|
||||
break;
|
||||
default:
|
||||
return {
|
||||
state,
|
||||
result: createErrorResult("UsageError", `Invalid options`, {}, COMMAND_NAME),
|
||||
};
|
||||
}
|
||||
}
|
||||
} else {
|
||||
paths.push(arg);
|
||||
}
|
||||
}
|
||||
|
||||
const session = getCurrentSession(state);
|
||||
|
||||
if (paths.length === 0) {
|
||||
entries.push({ ptr: session.cwd, path: "." });
|
||||
} else {
|
||||
for (const path of paths) {
|
||||
const ptr = resolvePath(state, path);
|
||||
if (!state.filesystem.exists(ptr)) {
|
||||
return {
|
||||
state,
|
||||
result: createErrorResult(
|
||||
"PathResolutionError",
|
||||
`No such file or directory`,
|
||||
{ path },
|
||||
COMMAND_NAME,
|
||||
),
|
||||
};
|
||||
}
|
||||
entries.push({ ptr, path });
|
||||
}
|
||||
}
|
||||
|
||||
if (options.long) {
|
||||
for (const entry of entries) {
|
||||
listDirEntries(entry);
|
||||
}
|
||||
} else {
|
||||
for (const entry of entries) {
|
||||
//shortDirEntries(entry);
|
||||
}
|
||||
io.writeStdout(e.encode(`No support for short format yet\n`));
|
||||
}
|
||||
|
||||
return {
|
||||
state,
|
||||
result: createSuccessResult(COMMAND_NAME),
|
||||
};
|
||||
|
||||
function listDirEntries(entry: { ptr: NodePointer; path: string }): void {
|
||||
const node = state.filesystem.getNode(entry.ptr) as DirectoryNode;
|
||||
|
||||
if (options.recursive) io.writeStdout(e.encode(`${entry.path}:\n`));
|
||||
io.writeStdout(e.encode(`total ${Object.entries(node.children).length}\n`));
|
||||
|
||||
let children: DirEntry[] = Array.from(node.children.entries()).map(([name, inode]) => ({
|
||||
name,
|
||||
ptr: NodePointer.of(entry.ptr.device, inode),
|
||||
}));
|
||||
if (!options.noSort) children = sortNodes(state, children, options.reverse, options.sortBy);
|
||||
|
||||
if (!options.all && !options.almostAll) {
|
||||
children = children.filter(c => !c.name.startsWith("."));
|
||||
}
|
||||
|
||||
if (options.long) {
|
||||
longMode(io, state, children);
|
||||
if (options.recursive) io.writeStdout(e.encode("\n"));
|
||||
}
|
||||
|
||||
if (options.recursive) {
|
||||
for (const c of children) {
|
||||
if (c.name.match(/^[.]{1,2}$/)) continue;
|
||||
const child = state.filesystem.getNode(c.ptr)!;
|
||||
if (child.type === NodeType.Directory) {
|
||||
let path;
|
||||
if (entry.path === "/") {
|
||||
path = "/" + c.name;
|
||||
} else if (entry.path.endsWith("/")) {
|
||||
path = entry.path + c.name;
|
||||
} else path = entry.path + "/" + c.name;
|
||||
listDirEntries({ ptr: c.ptr, path });
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function longMode(io: CommandIO, state: ShellState, children: DirEntry[]): void {
|
||||
const e = new TextEncoder();
|
||||
const buff: Uint8Array[] = [];
|
||||
const nodes: DirEntry[] = [...children];
|
||||
|
||||
// Calculate the string size of the biggerst node in the array;
|
||||
// Sets 4 length for directories because the arbitrary size is 4096 later in the code
|
||||
const maxInodeWidth = Math.max(...nodes.map(c => c.ptr.inode.toString().length));
|
||||
|
||||
const maxSizeWidth = Math.max(
|
||||
...nodes.map(c =>
|
||||
state.filesystem.getNode(c.ptr)!.type === NodeType.File
|
||||
? (state.filesystem.getNode(c.ptr) as FileNode).size.toString().length
|
||||
: 4,
|
||||
),
|
||||
);
|
||||
|
||||
const maxLinksWidth = Math.max(
|
||||
...nodes.map((c): number => {
|
||||
const node = state.filesystem.getNode(c.ptr)!;
|
||||
const o = node.link_count.toString().length;
|
||||
return o;
|
||||
}),
|
||||
);
|
||||
const namePadding = nodes.every(c => !c.name.includes(" "));
|
||||
|
||||
for (const n of nodes) {
|
||||
const node = state.filesystem.getNode(n.ptr)!;
|
||||
|
||||
if (options.inode) {
|
||||
const inode = node.inode.toString().padStart(maxInodeWidth, " ");
|
||||
buff.push(e.encode(inode + " "));
|
||||
}
|
||||
|
||||
// Mode
|
||||
const mode: string = parseMode(node.mode);
|
||||
|
||||
switch (node.type) {
|
||||
case NodeType.Directory:
|
||||
buff.push(e.encode("d" + mode + " "));
|
||||
break;
|
||||
case NodeType.File:
|
||||
buff.push(e.encode("-" + mode + " "));
|
||||
break;
|
||||
}
|
||||
|
||||
//Link count
|
||||
const linkCount = node.link_count.toString().padStart(maxLinksWidth, " ") + " ";
|
||||
buff.push(e.encode(linkCount));
|
||||
|
||||
// owner group
|
||||
if (options.noGroup) {
|
||||
buff.push(e.encode(`${state.users.get(node.owner)?.username} `));
|
||||
} else if (options.noOwner) {
|
||||
buff.push(e.encode(`${state.groups.get(node.group)?.groupname} `));
|
||||
} else if (options.numericUidGid) {
|
||||
buff.push(e.encode(`${node.owner} ${node.group} `));
|
||||
} else {
|
||||
buff.push(
|
||||
e.encode(`${state.users.get(node.owner)?.username} ${state.groups.get(node.group)?.groupname} `),
|
||||
);
|
||||
}
|
||||
|
||||
//Size
|
||||
// Holy abomination, pad the stringified bytesize number with whitespaces so the actual length of the string matches across all rows
|
||||
// Sets the folder size to an arbitrary 4096, could change it later to smth else
|
||||
let size;
|
||||
if (options.humanReadable) {
|
||||
const bytes = node.type === NodeType.File ? node.size : 4096;
|
||||
size = convertToUnit(bytes, 1, options.si ? 1000 : 1024);
|
||||
} else {
|
||||
size =
|
||||
node.type === NodeType.File
|
||||
? `${node.size.toString().padStart(maxSizeWidth, " ")} `
|
||||
: `${"4096".padStart(maxSizeWidth, " ")} `;
|
||||
}
|
||||
|
||||
buff.push(e.encode(size));
|
||||
|
||||
//Timestamp
|
||||
const date = getDateTimestamp(node, options.timestamp);
|
||||
if (options.fullTime) {
|
||||
buff.push(
|
||||
// Month + 1 because January is 0
|
||||
e.encode(
|
||||
`${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()} ${date.getHours()}:${date.getMinutes()} `,
|
||||
),
|
||||
);
|
||||
} else {
|
||||
buff.push(
|
||||
// Month + 1 because January is 0
|
||||
e.encode(`${date.getMonth() + 1}-${date.getDate()} ${date.getHours()}:${date.getMinutes()} `),
|
||||
);
|
||||
}
|
||||
|
||||
//Name
|
||||
if (options.quoteName) {
|
||||
buff.push(
|
||||
e.encode(
|
||||
`"${node.type === NodeType.Directory ? n.name + '"' + (options.appendIndicator ? "/" : "") : n.name + '"'}\n`,
|
||||
),
|
||||
);
|
||||
} else {
|
||||
const unpadded = `${n.name.includes(" ") && !options.literal ? "'" + n.name + "'" : n.name}`;
|
||||
const name = `${!namePadding ? (unpadded.includes(" ") ? unpadded : " " + unpadded) : unpadded}`;
|
||||
buff.push(
|
||||
e.encode(
|
||||
`${node.type === NodeType.Directory ? name + (options.appendIndicator ? "/" : "") : name}\n`,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const out = concatUint8Arrays(buff);
|
||||
io.writeStdout(out);
|
||||
}
|
||||
|
||||
function getDateTimestamp(node: Node, ts: string): Date {
|
||||
if (ts === "atime") return new Date(node.atime);
|
||||
if (ts === "ctime") return new Date(node.ctime);
|
||||
if (ts === "mtime") return new Date(node.mtime);
|
||||
return new Date();
|
||||
}
|
||||
|
||||
function parseMode(mode: number) {
|
||||
const owner = (mode >> 6) & 7;
|
||||
const group = (mode >> 3) & 7;
|
||||
const other = mode & 7;
|
||||
|
||||
const map = (bits: number) => {
|
||||
let s = "";
|
||||
s += bits & 4 ? "r" : "-";
|
||||
s += bits & 2 ? "w" : "-";
|
||||
s += bits & 1 ? "x" : "-";
|
||||
return s;
|
||||
};
|
||||
|
||||
return map(owner) + map(group) + map(other);
|
||||
}
|
||||
|
||||
function isValidSortMethod(value: string): value is SortNodeBy {
|
||||
return Object.values(SortNodeBy).includes(value as SortNodeBy);
|
||||
}
|
||||
|
||||
function isValidTimestamp(value: string): value is SortNodeBy.ATIME | SortNodeBy.MTIME | SortNodeBy.CTIME {
|
||||
return Object.values(SortNodeBy).includes(value as SortNodeBy.ATIME | SortNodeBy.MTIME | SortNodeBy.CTIME);
|
||||
}
|
||||
}
|
||||
|
||||
//function normalMode(io: CommandIO, state: ShellState, flags: string[], args: string[]): void {}
|
||||
|
||||
export const descriptor: CommandDescriptor = {
|
||||
fn: main,
|
||||
flags: [
|
||||
{ name: "l" }, // done
|
||||
{ name: "a" }, // done
|
||||
{ name: "A" }, // done
|
||||
{ name: "c" },
|
||||
{ name: "U" }, // done
|
||||
{ name: "g" }, // done
|
||||
{ name: "G" }, // done
|
||||
{ name: "h" }, // done
|
||||
{ name: "f" }, // done
|
||||
{ name: "x" },
|
||||
{ name: "X" }, // done
|
||||
{ name: "u" },
|
||||
{ name: "t" }, // done
|
||||
{ name: "S" }, // done
|
||||
{ name: "r" }, // done
|
||||
{ name: "R" }, // done
|
||||
{ name: "Q" }, // done
|
||||
{ name: "p" }, // done
|
||||
{ name: "o" }, // done
|
||||
{ name: "n" }, // done
|
||||
{ name: "N" }, // done
|
||||
{ name: "L" },
|
||||
{ name: "m" },
|
||||
{ name: "i" }, // done
|
||||
{ name: "sort", takesValue: true }, // done
|
||||
{ name: "time", takesValue: true }, // done
|
||||
{ name: "help" },
|
||||
{ name: "all" }, // done
|
||||
{ name: "almost-all" }, // done
|
||||
{ name: "full-time" }, // done
|
||||
{ name: "no-group" }, // done
|
||||
{ name: "human-readable" }, // done
|
||||
{ name: "reverse" }, // done
|
||||
{ name: "recursive" }, // done
|
||||
{ name: "quote-name" }, // done
|
||||
{ name: "literal" }, // done
|
||||
{ name: "numeric-uid-gid" }, // done
|
||||
{ name: "inode" }, // done
|
||||
{ name: "si" }, // done
|
||||
{ name: "dereference" },
|
||||
],
|
||||
name: "ls",
|
||||
};
|
||||
@@ -0,0 +1,41 @@
|
||||
import type { CommandDescriptor, CommandOutput } from "@core/command";
|
||||
import type { CommandIO } from "@core/command_io";
|
||||
import { createErrorResult, createSuccessResult, type ResultSuccess } from "@core/result";
|
||||
import { getCurrentSession } from "@core/session_manager";
|
||||
import type { ShellState } from "@core/shell_state";
|
||||
import type { InvalidArgumentsError, ShellError } from "@core/util/errors";
|
||||
import { resolvePointer } from "@core/util/path_resolver";
|
||||
|
||||
export const COMMAND_NAME = "pwd";
|
||||
|
||||
//Need to implement escape sequences
|
||||
async function main(io: CommandIO, state: ShellState, args: string[]): Promise<CommandOutput<ShellError>> {
|
||||
if (args.length > 0) {
|
||||
return {
|
||||
state,
|
||||
result: createErrorResult(
|
||||
"InvalidArguments",
|
||||
`Expected aruments 0, got ${args.length}.`,
|
||||
{ expected: "pwd", actual: `pwd ${args.toString().replace(/[,]/g, " ")}` },
|
||||
COMMAND_NAME,
|
||||
),
|
||||
} satisfies CommandOutput<InvalidArgumentsError>;
|
||||
}
|
||||
|
||||
const session = getCurrentSession(state);
|
||||
const path = resolvePointer(state, session.cwd);
|
||||
|
||||
io.writeStdout(new TextEncoder().encode(path));
|
||||
|
||||
const result: ResultSuccess = createSuccessResult(COMMAND_NAME);
|
||||
|
||||
return {
|
||||
state: state,
|
||||
result,
|
||||
};
|
||||
}
|
||||
|
||||
export const descriptor: CommandDescriptor = {
|
||||
fn: main,
|
||||
name: COMMAND_NAME,
|
||||
};
|
||||
@@ -0,0 +1,40 @@
|
||||
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 { SIGNAL_MAP } from "@core/signal";
|
||||
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, __args: string[]): Promise<CommandOutput<ShellError>> {
|
||||
while (true) {
|
||||
const out = await io.getSignal();
|
||||
|
||||
if (out.type === SIGNAL_MAP.INPUT) {
|
||||
const encoded = new TextEncoder().encode(("user pressed: " + out.payload + "\n") as string);
|
||||
io.writeStdout(encoded);
|
||||
|
||||
if (out.payload === "x") {
|
||||
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;
|
||||
@@ -0,0 +1,53 @@
|
||||
import type { CommandDescriptor, CommandOutput } from "@core/command";
|
||||
import type { CommandIO } from "@core/command_io";
|
||||
import { createSuccessResult, type ResultSuccess } from "@core/result";
|
||||
import { getCurrentSession } from "@core/session_manager";
|
||||
import type { ShellState } from "@core/shell_state";
|
||||
import type { ShellError } from "@core/util/errors";
|
||||
import { resolvePath } from "@core/util/path_resolver";
|
||||
|
||||
export const COMMAND_NAME = "touch";
|
||||
|
||||
//Need to implement escape sequences
|
||||
async function main(io: CommandIO, state: ShellState, args: string[]): Promise<CommandOutput<ShellError>> {
|
||||
for (const arg of args) {
|
||||
const inode = resolvePath(state, arg);
|
||||
const session = getCurrentSession(state);
|
||||
|
||||
let newState;
|
||||
|
||||
if (inode === -1) {
|
||||
const index = arg.lastIndexOf("/");
|
||||
let parentPath;
|
||||
if (index === -1) {
|
||||
parentPath = "./";
|
||||
} else {
|
||||
parentPath = arg.slice(0, index);
|
||||
}
|
||||
const fileName = arg.slice(index + 1);
|
||||
const parent = resolvePath(state, parentPath);
|
||||
|
||||
newState = state.filesystem.createNode(
|
||||
parent,
|
||||
fileName,
|
||||
TreeNodeType.File,
|
||||
0o644,
|
||||
session.user.uid,
|
||||
session.user.gid,
|
||||
);
|
||||
} else {
|
||||
}
|
||||
}
|
||||
|
||||
const result: ResultSuccess = createSuccessResult(COMMAND_NAME);
|
||||
|
||||
return {
|
||||
state: state,
|
||||
result,
|
||||
};
|
||||
}
|
||||
|
||||
export const descriptor: CommandDescriptor = {
|
||||
fn: main,
|
||||
name: COMMAND_NAME,
|
||||
};
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { TreeNodeType } from "./treenode";
|
||||
import type { NodePointer, NodeType } from "./node";
|
||||
|
||||
export type FileSystemError =
|
||||
NotADirectoryError | AlreadyExistsError | NodeNotFoundError | IllegalMutationError | FileSystemInitializationError;
|
||||
@@ -14,7 +14,15 @@ export interface NotADirectoryError {
|
||||
message: string;
|
||||
timestamp: number;
|
||||
type: "NotADirectory";
|
||||
nodeType: TreeNodeType;
|
||||
nodeType: NodeType;
|
||||
}
|
||||
|
||||
export interface NotAFileError {
|
||||
inode: number;
|
||||
message: string;
|
||||
timestamp: number;
|
||||
type: "NotAFile";
|
||||
nodeType: NodeType;
|
||||
}
|
||||
|
||||
export interface AlreadyExistsError {
|
||||
@@ -28,7 +36,21 @@ export interface AlreadyExistsError {
|
||||
export interface NodeNotFoundError {
|
||||
type: "NodeNotFound";
|
||||
message: string;
|
||||
inode: number;
|
||||
pointer: NodePointer;
|
||||
timestamp: number;
|
||||
}
|
||||
|
||||
export interface DeviceNotFoundError {
|
||||
type: "DeviceNotFound";
|
||||
message: string;
|
||||
device_id: number;
|
||||
timestamp: number;
|
||||
}
|
||||
|
||||
export interface MountPointNotFoundError {
|
||||
type: "MountPointNotFound";
|
||||
message: string;
|
||||
pointer: NodePointer;
|
||||
timestamp: number;
|
||||
}
|
||||
|
||||
@@ -45,3 +67,18 @@ export interface DirectoryLoopError {
|
||||
descendantInode: number;
|
||||
ancestorInode: number;
|
||||
}
|
||||
|
||||
export interface InvalidNodeNameError {
|
||||
type: "InvalidNodeName";
|
||||
message: string;
|
||||
timestamp: number;
|
||||
pointer: NodePointer;
|
||||
attemptedName: string;
|
||||
}
|
||||
|
||||
export interface FileSystemCorruptionError {
|
||||
type: "FileSystemCorruption";
|
||||
message: string;
|
||||
timestamp: number;
|
||||
override?: {};
|
||||
}
|
||||
|
||||
+442
-370
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,120 @@
|
||||
export type Node = FileNode | DirectoryNode | SymlinkNode;
|
||||
|
||||
export type NodeHash = ReadonlyMap<number, Node>;
|
||||
export type ShadowHash = ReadonlyMap<number, Node | null>;
|
||||
|
||||
export class NodePointer {
|
||||
private static readonly _cache = new Map<string, NodePointer>();
|
||||
|
||||
private readonly _device_id: number;
|
||||
private readonly _inode: number;
|
||||
|
||||
private constructor(device_id: number, inode: number) {
|
||||
this._device_id = device_id;
|
||||
this._inode = inode;
|
||||
}
|
||||
|
||||
static of(device_id: number, inode: number): NodePointer {
|
||||
const key = `${device_id}:${inode}`;
|
||||
let p = NodePointer._cache.get(key);
|
||||
if (!p) {
|
||||
p = new NodePointer(device_id, inode);
|
||||
NodePointer._cache.set(key, p);
|
||||
}
|
||||
return p;
|
||||
}
|
||||
|
||||
static parse(s: string): NodePointer {
|
||||
const m = /^(\d+):(\d+)$/.exec(s);
|
||||
if (!m) throw new Error(`Invalid NodePointer: ${s}`);
|
||||
let p = NodePointer._cache.get(s);
|
||||
if (!p) {
|
||||
p = new NodePointer(Number(m[1]), Number(m[2]));
|
||||
NodePointer._cache.set(s, p);
|
||||
}
|
||||
return p;
|
||||
}
|
||||
|
||||
get device(): number {
|
||||
return this._device_id;
|
||||
}
|
||||
get inode(): number {
|
||||
return this._inode;
|
||||
}
|
||||
toString(): string {
|
||||
return `${this._device_id}:${this.inode}`;
|
||||
}
|
||||
equals(other: NodePointer): boolean {
|
||||
return this._device_id === other._device_id && this.inode === other.inode;
|
||||
}
|
||||
}
|
||||
|
||||
//export type NodePointer = `${string}:${string}`;
|
||||
|
||||
export interface NodeEntry {
|
||||
readonly pinode: number;
|
||||
readonly pdevice_id: number;
|
||||
readonly name: string;
|
||||
}
|
||||
|
||||
export interface FileNode {
|
||||
readonly type: NodeType.File;
|
||||
readonly inode: number;
|
||||
readonly link_count: number;
|
||||
readonly mode: number;
|
||||
readonly owner: number;
|
||||
readonly group: number;
|
||||
readonly mtime: number;
|
||||
readonly ctime: number;
|
||||
readonly atime: number;
|
||||
readonly content: string;
|
||||
readonly size: number;
|
||||
}
|
||||
|
||||
export interface DirectoryNode {
|
||||
readonly type: NodeType.Directory;
|
||||
readonly inode: number;
|
||||
readonly link_count: number;
|
||||
readonly mode: number;
|
||||
readonly owner: number;
|
||||
readonly group: number;
|
||||
readonly mtime: number;
|
||||
readonly ctime: number;
|
||||
readonly atime: number;
|
||||
readonly children: Map<string, number>;
|
||||
}
|
||||
|
||||
export interface SymlinkNode {
|
||||
readonly type: NodeType.Symlink;
|
||||
readonly inode: number;
|
||||
readonly link_count: number;
|
||||
readonly mode: number;
|
||||
readonly owner: number;
|
||||
readonly group: number;
|
||||
readonly mtime: number;
|
||||
readonly ctime: number;
|
||||
readonly atime: number;
|
||||
readonly target: string;
|
||||
}
|
||||
|
||||
export enum NodeType {
|
||||
File = 0,
|
||||
Directory = 1,
|
||||
Symlink = 2,
|
||||
}
|
||||
|
||||
/* export function toPtr({ device_id, inode }: { device_id: number; inode: number }): NodePointer {
|
||||
return `${device_id}:${inode}`;
|
||||
}
|
||||
|
||||
export function fromPtr(ptr: NodePointer): { device_id: number; inode: number } {
|
||||
if (!ptr.match(/^\d+[:]\d+$/)) {
|
||||
//TODO: Make typed
|
||||
throw new Error("Invalid node pointer format");
|
||||
}
|
||||
const arr = ptr.split(":");
|
||||
return {
|
||||
device_id: Number(arr[0]),
|
||||
inode: Number(arr[1]),
|
||||
};
|
||||
} */
|
||||
@@ -1,51 +0,0 @@
|
||||
import type { ImmutableBuffer } from "@core/util/immutable_buffer";
|
||||
|
||||
export type TreeNode = FileNode | DirectoryNode;
|
||||
|
||||
export interface FileNode {
|
||||
readonly type: TreeNodeType.File;
|
||||
readonly inode: number;
|
||||
readonly name: string;
|
||||
readonly parent: number;
|
||||
readonly mode: number;
|
||||
readonly owner: number;
|
||||
readonly group: number;
|
||||
readonly mtime: number;
|
||||
readonly ctime: number;
|
||||
readonly atime: number;
|
||||
readonly content: ImmutableBuffer;
|
||||
}
|
||||
|
||||
export interface DirectoryNode {
|
||||
readonly type: TreeNodeType.Directory;
|
||||
readonly inode: number;
|
||||
readonly name: string;
|
||||
readonly parent: number;
|
||||
readonly mode: number;
|
||||
readonly owner: number;
|
||||
readonly group: number;
|
||||
readonly mtime: number;
|
||||
readonly ctime: number;
|
||||
readonly atime: number;
|
||||
readonly children: Readonly<Record<string, number>>;
|
||||
}
|
||||
|
||||
/* export interface SymlinkNode {
|
||||
readonly type: TreeNodeType.Symlink;
|
||||
readonly inode: number;
|
||||
readonly name: string;
|
||||
readonly parent: number;
|
||||
readonly mode: number;
|
||||
readonly owner: number;
|
||||
readonly group: number;
|
||||
readonly mtime: number;
|
||||
readonly ctime: number;
|
||||
readonly atime: number;
|
||||
readonly target: string;
|
||||
} */
|
||||
|
||||
export enum TreeNodeType {
|
||||
File = "0",
|
||||
Directory = "1",
|
||||
//Symlink = "2",
|
||||
}
|
||||
@@ -0,0 +1,447 @@
|
||||
import type { Blob } from "node:buffer";
|
||||
import { Readable } from "node:stream";
|
||||
import { blob } from "node:stream/consumers";
|
||||
import { NodePointer, NodeType, type DirectoryNode, type Node, type NodeEntry, type NodeHash } from "./node";
|
||||
|
||||
export function DefaultVDiskConfig(id: number): VDiskConfig {
|
||||
const base = new Map();
|
||||
const root = {
|
||||
type: NodeType.Directory,
|
||||
inode: 0,
|
||||
link_count: 2,
|
||||
mode: 0o0555,
|
||||
owner: 0,
|
||||
group: 0,
|
||||
mtime: 0,
|
||||
ctime: 0,
|
||||
atime: 0,
|
||||
children: new Map(),
|
||||
} satisfies DirectoryNode;
|
||||
|
||||
base.set(0, root);
|
||||
|
||||
return {
|
||||
id,
|
||||
label: `disk-${id}`,
|
||||
readonly: false,
|
||||
size: Infinity,
|
||||
base,
|
||||
index: 0,
|
||||
dataC: {
|
||||
chunkSize: 8096,
|
||||
cacheSize: 64 * 1024 * 1024,
|
||||
cacheTTL: 60_000,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export interface VDiskConfig {
|
||||
id: number;
|
||||
label: string;
|
||||
index: number;
|
||||
readonly: boolean;
|
||||
size: number;
|
||||
base: NodeHash;
|
||||
dataC: DataConfig;
|
||||
}
|
||||
|
||||
export interface DataConfig {
|
||||
chunkSize: number;
|
||||
cacheSize: number;
|
||||
cacheTTL: number;
|
||||
}
|
||||
|
||||
export interface IDataStore {
|
||||
read(uuid: string): Promise<Uint8Array>;
|
||||
stream(uuid: string): Readable;
|
||||
put(uuid: string, blob: Blob): Promise<void>;
|
||||
delete(uuid: string): Promise<void>;
|
||||
has(uuid: string): Promise<boolean>;
|
||||
list(): Promise<string[]>;
|
||||
}
|
||||
|
||||
export interface IMetaStore {
|
||||
loadAll(): Promise<Map<number, Node | null>>;
|
||||
write(entries: Array<[number, Node | null]>): Promise<void>;
|
||||
delete(entries: Array<number>): Promise<void>;
|
||||
}
|
||||
|
||||
export class VDisk {
|
||||
private readonly _id: number;
|
||||
private readonly _label: string;
|
||||
private readonly _readonly: boolean;
|
||||
private readonly _totalSize: number;
|
||||
private readonly _base: NodeHash;
|
||||
private readonly _dataStore: IDataStore;
|
||||
private readonly _metaStore: IMetaStore;
|
||||
|
||||
private _iIndex: number;
|
||||
private _rIndex: ReadonlyMap<NodePointer, ReadonlyArray<NodeEntry>>;
|
||||
private _overlay: Map<number, Node | null>;
|
||||
private _pending: Map<number, Node | null> | null;
|
||||
|
||||
private _rIndexInvalid: boolean;
|
||||
private _flush: Promise<void>;
|
||||
|
||||
private constructor(config: VDiskConfig, data: IDataStore, meta: IMetaStore) {
|
||||
this._id = config.id;
|
||||
this._label = config.label;
|
||||
this._readonly = config.readonly;
|
||||
this._totalSize = config.size;
|
||||
this._base = config.base;
|
||||
this._iIndex = config.index;
|
||||
|
||||
this._dataStore = data;
|
||||
this._metaStore = meta;
|
||||
|
||||
this._overlay = new Map();
|
||||
this._rIndex = new Map();
|
||||
this._rIndexInvalid = false;
|
||||
this._pending = null;
|
||||
this._flush = Promise.resolve();
|
||||
}
|
||||
|
||||
private async _batch<T>(fn: () => T): Promise<T> {
|
||||
if (this._pending) {
|
||||
console.error("Nested batch not ok");
|
||||
}
|
||||
|
||||
this._pending = new Map();
|
||||
|
||||
let result: T;
|
||||
try {
|
||||
result = fn();
|
||||
} catch (err) {
|
||||
this._pending = null;
|
||||
throw err;
|
||||
}
|
||||
|
||||
const pending = this._pending;
|
||||
this._pending = null;
|
||||
|
||||
for (const [inode, node] of pending) {
|
||||
this._overlay.set(inode, node);
|
||||
}
|
||||
|
||||
const entries = Array.from(pending.entries());
|
||||
const next = this._flush.then(() => this._metaStore.write(entries));
|
||||
this._flush = next.catch(() => {});
|
||||
await next;
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
private _isWritable(): void {
|
||||
if (this._readonly) throw Error(`The ${this._label} device under id - ${this._id} is marked readonly`);
|
||||
}
|
||||
|
||||
private _buildReverseIndex(): Map<NodePointer, NodeEntry[]> {
|
||||
const index: Map<NodePointer, NodeEntry[]> = new Map();
|
||||
const stack: [number, number, number, string][] = [];
|
||||
|
||||
const root = this.getNode(0) as DirectoryNode;
|
||||
for (const [name, inode] of root.children) {
|
||||
if (name === "." || name === "..") continue;
|
||||
stack.push([inode, 0, this._id, name]);
|
||||
}
|
||||
|
||||
while (stack.length > 0) {
|
||||
const [inode, pinode, pdevice_id, name] = stack.pop()!;
|
||||
const node = this.getNode(inode);
|
||||
if (node === undefined) continue;
|
||||
|
||||
const key = NodePointer.of(this._id, inode);
|
||||
const entry = {
|
||||
pinode,
|
||||
pdevice_id,
|
||||
name,
|
||||
};
|
||||
|
||||
const arr = index.get(key);
|
||||
if (arr) arr.push(entry);
|
||||
else index.set(key, [entry]);
|
||||
|
||||
if (node.type === NodeType.Directory) {
|
||||
for (const [name, cinode] of node.children) {
|
||||
if (name === "." || name === "..") continue;
|
||||
stack.push([cinode, inode, pdevice_id, name]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return index;
|
||||
}
|
||||
|
||||
private _putNode(inode: number, node: Node | null): void {
|
||||
if (!this._pending)
|
||||
throw new Error(
|
||||
"_putNode called outside of batch. This is not a BUG. Every mutation must be wrapped in a _batch call",
|
||||
);
|
||||
|
||||
this._pending.set(inode, node);
|
||||
}
|
||||
|
||||
public static async open(config: VDiskConfig, data: IDataStore, meta: IMetaStore): Promise<VDisk> {
|
||||
const vdisk = new VDisk(config, data, meta);
|
||||
await vdisk.loadOverlay();
|
||||
vdisk._rIndex = vdisk._buildReverseIndex();
|
||||
|
||||
return vdisk;
|
||||
}
|
||||
|
||||
public getNode(inode: number): Node | undefined {
|
||||
if (this._pending && this._pending.has(inode)) {
|
||||
return this._pending.get(inode) ?? undefined;
|
||||
}
|
||||
|
||||
const node = this._overlay.get(inode);
|
||||
if (node) return node;
|
||||
if (node === null) return undefined;
|
||||
|
||||
return this._base.get(inode);
|
||||
}
|
||||
|
||||
public async createNodeEntry(
|
||||
pinode: number,
|
||||
name: string,
|
||||
data:
|
||||
| {
|
||||
type: NodeType.File;
|
||||
mode: number;
|
||||
owner: number;
|
||||
group: number;
|
||||
content: Blob | Readable;
|
||||
size: number;
|
||||
}
|
||||
| { type: NodeType.Directory; mode: number; owner: number; group: number }
|
||||
| { type: NodeType.Symlink; mode: number; owner: number; group: number; target: string },
|
||||
): Promise<number> {
|
||||
return this._batch(async () => {
|
||||
this._isWritable();
|
||||
const index = ++this._iIndex;
|
||||
const time = Date.now();
|
||||
const link_count = data.type === NodeType.Directory ? 2 : 1;
|
||||
|
||||
const base = {
|
||||
inode: index,
|
||||
link_count,
|
||||
type: data.type,
|
||||
mode: data.mode,
|
||||
owner: data.owner,
|
||||
group: data.group,
|
||||
mtime: time,
|
||||
ctime: time,
|
||||
atime: time,
|
||||
};
|
||||
|
||||
const pnode = this.getNode(pinode) as DirectoryNode;
|
||||
const uuid = crypto.randomUUID();
|
||||
|
||||
let node: Node;
|
||||
switch (data.type) {
|
||||
case NodeType.File:
|
||||
node = { ...base, type: NodeType.File, content: uuid, size: data.size };
|
||||
this.writeContent(uuid, data.content instanceof Readable ? await blob(data.content) : data.content);
|
||||
break;
|
||||
case NodeType.Directory:
|
||||
node = { ...base, type: NodeType.Directory, children: new Map() };
|
||||
break;
|
||||
case NodeType.Symlink:
|
||||
node = { ...base, type: NodeType.Symlink, target: data.target };
|
||||
break;
|
||||
}
|
||||
|
||||
const children = new Map(pnode.children);
|
||||
children.set(name, index);
|
||||
|
||||
const parent = {
|
||||
...pnode,
|
||||
children,
|
||||
link_count: pnode.link_count + (data.type === NodeType.Directory ? 1 : 0),
|
||||
mtime: time,
|
||||
ctime: time,
|
||||
};
|
||||
|
||||
this._putNode(index, node);
|
||||
this._putNode(pinode, parent);
|
||||
this.invalidateRIndex();
|
||||
|
||||
return index;
|
||||
});
|
||||
}
|
||||
|
||||
public linkNodeEntry(pinode: number, name: string, tinode: number): Promise<void> {
|
||||
return this._batch(() => {
|
||||
this._isWritable();
|
||||
|
||||
const pnode = this.getNode(pinode) as DirectoryNode;
|
||||
const tnode = this.getNode(tinode) as Node;
|
||||
const time = Date.now();
|
||||
|
||||
const children = new Map(pnode.children);
|
||||
children.set(name, tnode.inode);
|
||||
|
||||
const parent = { ...pnode, children, mtime: time, ctime: time };
|
||||
const target = { ...tnode, link_count: tnode.link_count + 1, ctime: time };
|
||||
|
||||
this._putNode(tinode, target);
|
||||
this._putNode(pinode, parent);
|
||||
this.invalidateRIndex();
|
||||
});
|
||||
}
|
||||
|
||||
public unlinkNodeEntry(inode: number, name: string): Promise<void> {
|
||||
return this._batch(() => {
|
||||
this._isWritable();
|
||||
|
||||
const pnode = this.getNode(inode) as DirectoryNode;
|
||||
const tinode = pnode.children.get(name)!;
|
||||
const tnode = this.getNode(tinode) as Node;
|
||||
const time = Date.now();
|
||||
|
||||
const children = new Map(pnode.children);
|
||||
children.delete(name);
|
||||
const parent = { ...pnode, children, mtime: time, ctime: time };
|
||||
|
||||
const link_count = tnode.link_count - 1;
|
||||
const wasLast = link_count === 0;
|
||||
|
||||
this._putNode(inode, parent);
|
||||
this._putNode(tinode, wasLast ? null : { ...tnode, link_count, ctime: Date.now() });
|
||||
this.invalidateRIndex();
|
||||
});
|
||||
}
|
||||
|
||||
public moveNodeEntry(pinode: number, dinode: number, tname: string, dname?: string): Promise<void> {
|
||||
return this._batch(() => {
|
||||
this._isWritable();
|
||||
|
||||
const pnode = this.getNode(pinode) as DirectoryNode;
|
||||
const dnode = this.getNode(dinode) as DirectoryNode;
|
||||
|
||||
const tinode = pnode.children.get(tname)!;
|
||||
const tnode = this.getNode(tinode)!;
|
||||
|
||||
const name = dname ?? tname;
|
||||
const isDir = tnode.type === NodeType.Directory;
|
||||
const time = Date.now();
|
||||
|
||||
if (pinode === dinode) {
|
||||
const pchildren = new Map(pnode.children);
|
||||
pchildren.delete(tname);
|
||||
pchildren.set(name, tinode);
|
||||
|
||||
const parent = { ...pnode, children: pchildren, mtime: time, ctime: time };
|
||||
const target = { ...tnode, ctime: time };
|
||||
|
||||
this._putNode(pinode, parent);
|
||||
this._putNode(tinode, target);
|
||||
this.invalidateRIndex();
|
||||
return;
|
||||
}
|
||||
|
||||
const pchildren = new Map(pnode.children);
|
||||
pchildren.delete(tname);
|
||||
|
||||
const dchildren = new Map(dnode.children);
|
||||
dchildren.set(name, tinode);
|
||||
|
||||
const parent = {
|
||||
...pnode,
|
||||
children: pchildren,
|
||||
mtime: time,
|
||||
ctime: time,
|
||||
link_count: pnode.link_count - (isDir ? 1 : 0),
|
||||
};
|
||||
const target = { ...tnode, ctime: time };
|
||||
const destination = {
|
||||
...dnode,
|
||||
children: dchildren,
|
||||
mtime: time,
|
||||
ctime: time,
|
||||
link_count: dnode.link_count + (isDir ? 1 : 0),
|
||||
};
|
||||
|
||||
this._putNode(pinode, parent);
|
||||
this._putNode(tinode, target);
|
||||
this._putNode(dinode, destination);
|
||||
this.invalidateRIndex();
|
||||
});
|
||||
}
|
||||
|
||||
public writeNodeEntry(inode: number, data: { mode?: number; owner?: number; group?: number }): Promise<void> {
|
||||
return this._batch(() => {
|
||||
this._isWritable();
|
||||
|
||||
const node = this.getNode(inode)!;
|
||||
|
||||
const newNode: Node = {
|
||||
...node,
|
||||
mode: data.mode ?? node.mode,
|
||||
owner: data.owner ?? node.owner,
|
||||
group: data.group ?? node.group,
|
||||
ctime: Date.now(),
|
||||
};
|
||||
|
||||
this._putNode(inode, newNode);
|
||||
});
|
||||
}
|
||||
|
||||
public readContent(uuid: string): Promise<Uint8Array> {
|
||||
return this._dataStore.read(uuid);
|
||||
}
|
||||
|
||||
public streamContent(uuid: string): Readable {
|
||||
return this._dataStore.stream(uuid);
|
||||
}
|
||||
|
||||
public async writeContent(uuid: string, blob: Blob): Promise<void> {
|
||||
this._isWritable();
|
||||
await this._dataStore.put(uuid, blob);
|
||||
}
|
||||
|
||||
public async deleteContent(uuid: string): Promise<void> {
|
||||
this._isWritable();
|
||||
await this._dataStore.delete(uuid);
|
||||
}
|
||||
|
||||
public hasContent(uuid: string): Promise<boolean> {
|
||||
return this._dataStore.has(uuid);
|
||||
}
|
||||
|
||||
public async loadOverlay(): Promise<void> {
|
||||
const overlay = await this._metaStore.loadAll();
|
||||
this._overlay = new Map(overlay);
|
||||
}
|
||||
|
||||
// public sweepOrphans(): Promise<void> {}
|
||||
// public sweepDangling(): Promise<void> {}
|
||||
|
||||
public invalidateRIndex(): void {
|
||||
this._rIndexInvalid = true;
|
||||
}
|
||||
|
||||
public getIndex(): ReadonlyMap<NodePointer, ReadonlyArray<NodeEntry>> {
|
||||
if (this._rIndexInvalid) {
|
||||
this._rIndex = this._buildReverseIndex();
|
||||
this._rIndexInvalid = false;
|
||||
}
|
||||
return this._rIndex;
|
||||
}
|
||||
|
||||
public get ID(): number {
|
||||
return this._id;
|
||||
}
|
||||
|
||||
public get Label(): string {
|
||||
return this._label;
|
||||
}
|
||||
|
||||
public get IsReadonly(): boolean {
|
||||
return this._readonly;
|
||||
}
|
||||
|
||||
public get ByteSize(): number {
|
||||
return this._totalSize;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
export function resolveKeybind(input: string, map: ReadonlyMap<string, string>): string | undefined {
|
||||
return map.get(input);
|
||||
}
|
||||
@@ -1,54 +0,0 @@
|
||||
import type { NodeNotFoundError, NotADirectoryError } from "./filesystem/errors";
|
||||
import type { FileSystem } from "./filesystem/filesystem";
|
||||
import { TreeNodeType, type DirectoryNode } from "./filesystem/treenode";
|
||||
|
||||
export function resolvePath(fs: FileSystem, cwd: number, path: string): number {
|
||||
const isAbsolute = path.startsWith("/");
|
||||
|
||||
const normalizedPath: string = path.replace(/^\/+|\/+$/g, "");
|
||||
const pathComponents: string[] = normalizedPath.split("/").filter(name => name.length > 0);
|
||||
|
||||
if (pathComponents.length === 0 && isAbsolute) return 0;
|
||||
if (pathComponents.length === 0) return cwd;
|
||||
|
||||
let currentNode = isAbsolute ? fs.getRoot() : (fs.getNode(cwd) as DirectoryNode);
|
||||
if (!currentNode) {
|
||||
throw {
|
||||
type: "NodeNotFound",
|
||||
message: `CWD node under inode ${cwd} not found`,
|
||||
timestamp: Date.now(),
|
||||
inode: cwd,
|
||||
} satisfies NodeNotFoundError;
|
||||
}
|
||||
|
||||
for (const name of pathComponents) {
|
||||
if (name === ".") continue;
|
||||
|
||||
if (name === "..") {
|
||||
currentNode = fs.getNode(currentNode.parent) as DirectoryNode;
|
||||
continue;
|
||||
}
|
||||
|
||||
const inode = currentNode.children[name];
|
||||
|
||||
if (!inode)
|
||||
throw {
|
||||
type: "NodeNotFound",
|
||||
message: `Child node in ${currentNode.name} under name ${name} not found`,
|
||||
timestamp: Date.now(),
|
||||
inode: currentNode.inode,
|
||||
} satisfies NodeNotFoundError;
|
||||
if (fs.isFile(inode))
|
||||
throw {
|
||||
type: "NotADirectory",
|
||||
message: `Child node ${name} is not a directory`,
|
||||
timestamp: Date.now(),
|
||||
inode: inode,
|
||||
nodeType: TreeNodeType.File,
|
||||
} satisfies NotADirectoryError;
|
||||
|
||||
currentNode = fs.getNode(inode) as DirectoryNode;
|
||||
}
|
||||
|
||||
return currentNode.inode;
|
||||
}
|
||||
+40
-13
@@ -1,18 +1,8 @@
|
||||
import type { ImmutableBuffer } from "./util/immutable_buffer";
|
||||
|
||||
export interface ShellError {
|
||||
readonly errorType: string;
|
||||
readonly message: string;
|
||||
readonly timestamp: number;
|
||||
readonly cause?: {
|
||||
readonly name: string;
|
||||
readonly message: string;
|
||||
};
|
||||
}
|
||||
import { createShellError, type ShellError } from "./util/errors";
|
||||
import { createImmutableBuffer, type ImmutableBuffer } from "./util/immutable_buffer";
|
||||
|
||||
export interface ResultError<E extends ShellError> {
|
||||
readonly type: "error";
|
||||
readonly exitCode: number;
|
||||
readonly stdout: ImmutableBuffer;
|
||||
readonly stderr: ImmutableBuffer;
|
||||
readonly commandName?: string;
|
||||
@@ -21,10 +11,47 @@ export interface ResultError<E extends ShellError> {
|
||||
|
||||
export interface ResultSuccess {
|
||||
readonly type: "success";
|
||||
readonly exitCode: number;
|
||||
readonly stdout: ImmutableBuffer;
|
||||
readonly stderr: ImmutableBuffer;
|
||||
readonly exitCode: number;
|
||||
readonly commandName?: string;
|
||||
}
|
||||
|
||||
export type Result<E extends ShellError> = ResultSuccess | ResultError<E>;
|
||||
|
||||
export function createErrorResult<E extends ShellError>(
|
||||
errorType: E["errorType"],
|
||||
message: string,
|
||||
// Omit - includes all properties of E except the ones that are already inside ShellError - basically skipping duplicates and allowing this to be a one-liner
|
||||
extraProps: Omit<E, keyof ShellError>,
|
||||
commandName?: string,
|
||||
stdout?: ImmutableBuffer,
|
||||
stderr?: ImmutableBuffer,
|
||||
cause?: { name: string; message: string },
|
||||
): ResultError<E> {
|
||||
const error = createShellError<E>(errorType, message, extraProps, cause);
|
||||
return Object.freeze({
|
||||
type: "error",
|
||||
stdout: stdout ?? createImmutableBuffer(new Uint8Array()),
|
||||
stderr: stderr ?? createImmutableBuffer(new Uint8Array()),
|
||||
error,
|
||||
// commandName is either undefined or string but when undefined - has to be ommited - we achieve that with a condition wrapped in a spread
|
||||
...(commandName !== undefined && { commandName }),
|
||||
});
|
||||
}
|
||||
|
||||
export function createSuccessResult(
|
||||
commandName?: string,
|
||||
exitCode?: number,
|
||||
stdout?: ImmutableBuffer,
|
||||
stderr?: ImmutableBuffer,
|
||||
): ResultSuccess {
|
||||
return Object.freeze({
|
||||
type: "success",
|
||||
stdout: stdout ?? createImmutableBuffer(new Uint8Array()),
|
||||
stderr: stderr ?? createImmutableBuffer(new Uint8Array()),
|
||||
exitCode: exitCode ?? 0,
|
||||
// commandName is either undefined or string but when undefined - has to be ommited - we achieve that with a condition wrapped in a spread
|
||||
...(commandName !== undefined && { commandName }),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1,27 +0,0 @@
|
||||
import { type HistoryState } from "./history_state";
|
||||
import type { ShellState } from "./shell_state";
|
||||
import type { UserInfo } from "./user_info";
|
||||
|
||||
export interface SessionState {
|
||||
readonly user: UserInfo;
|
||||
readonly envVars: ReadonlyMap<string, string>;
|
||||
readonly history: HistoryState;
|
||||
readonly cwd: number;
|
||||
readonly pwd: number;
|
||||
readonly exitCode: number;
|
||||
}
|
||||
|
||||
export function createInitialSessionState(user: UserInfo): SessionState {
|
||||
return Object.freeze({
|
||||
user,
|
||||
envVars: Object.freeze(new Map()),
|
||||
history: Object.freeze([]),
|
||||
cwd: user.home,
|
||||
pwd: user.home,
|
||||
exitCode: 0,
|
||||
} satisfies SessionState);
|
||||
}
|
||||
|
||||
export function getCurrentSession(state: ShellState): SessionState {
|
||||
return state.sessionStack[state.sessionStack.length - 1]!;
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
import type { NodePointer } from "./filesystem/node";
|
||||
import { type HistoryState } from "./history_state";
|
||||
import { createShellState, type ShellState } from "./shell_state";
|
||||
import { createShellError, type LoginError, type UserNotFoundError } from "./util/errors";
|
||||
|
||||
export interface GroupInfo {
|
||||
readonly groupname: string;
|
||||
readonly gid: number;
|
||||
readonly members: number[];
|
||||
}
|
||||
|
||||
export interface UserInfo {
|
||||
readonly username: string;
|
||||
readonly uid: number;
|
||||
readonly gid: number;
|
||||
readonly group: readonly number[];
|
||||
readonly home: NodePointer;
|
||||
}
|
||||
|
||||
export interface SessionState {
|
||||
readonly user: UserInfo;
|
||||
readonly envVars: ReadonlyMap<string, string>;
|
||||
readonly history: HistoryState;
|
||||
readonly cwd: NodePointer;
|
||||
readonly pwd: NodePointer;
|
||||
readonly exitCode: number;
|
||||
}
|
||||
|
||||
export function createInitialSessionState(user: UserInfo): SessionState {
|
||||
return Object.freeze({
|
||||
user,
|
||||
envVars: Object.freeze(new Map()),
|
||||
history: Object.freeze([]),
|
||||
cwd: user.home,
|
||||
pwd: user.home,
|
||||
exitCode: 0,
|
||||
} satisfies SessionState);
|
||||
}
|
||||
|
||||
export function getCurrentSession(state: ShellState): SessionState {
|
||||
return state.sessionStack[state.sessionStack.length - 1]!;
|
||||
}
|
||||
|
||||
export function login(
|
||||
state: ShellState,
|
||||
username: string,
|
||||
password: string,
|
||||
passwdMap: ReadonlyMap<number, string>,
|
||||
): ShellState {
|
||||
const user = state.users.values().find(value => value.username === username);
|
||||
if (!user) {
|
||||
throw createShellError<UserNotFoundError>("UserNotFound", "The specified user does not exist", { username });
|
||||
}
|
||||
|
||||
const passwd = passwdMap.get(user.uid);
|
||||
if (!passwd) {
|
||||
throw createShellError<LoginError>("LoginError", "The user does not have a password mapped to their uid", {
|
||||
user: user.uid,
|
||||
});
|
||||
}
|
||||
|
||||
// Change this to hashed passwords later on
|
||||
if (!(password === passwd)) {
|
||||
throw createShellError<LoginError>("LoginError", "The password is incorrect", { user: user.uid });
|
||||
}
|
||||
|
||||
const stack = [...state.sessionStack];
|
||||
stack.push(createInitialSessionState(user));
|
||||
return createShellState(state.filesystem, state.users, state.groups, stack);
|
||||
}
|
||||
|
||||
export function logout(state: ShellState): ShellState {
|
||||
if (state.sessionStack.length > 1) {
|
||||
const stack = [...state.sessionStack];
|
||||
stack.pop();
|
||||
|
||||
return createShellState(state.filesystem, state.users, state.groups, stack);
|
||||
}
|
||||
return state;
|
||||
}
|
||||
+26
-4
@@ -1,34 +1,52 @@
|
||||
import type { FileSystem } from "./filesystem/filesystem";
|
||||
import type { NodePointer } from "./filesystem/node";
|
||||
import { addHistoryEntry } from "./history_state";
|
||||
import { createInitialSessionState, getCurrentSession, type SessionState } from "./session";
|
||||
import type { UserInfo } from "./user_info";
|
||||
import type { GroupInfo, UserInfo } from "./session_manager";
|
||||
import { createInitialSessionState, getCurrentSession, type SessionState } from "./session_manager";
|
||||
|
||||
export interface ShellState {
|
||||
readonly filesystem: FileSystem;
|
||||
readonly users: ReadonlyMap<number, UserInfo>;
|
||||
readonly groups: ReadonlyMap<number, GroupInfo>;
|
||||
readonly sessionStack: ReadonlyArray<SessionState>;
|
||||
}
|
||||
|
||||
export function createInitialShellState(
|
||||
filesystem: FileSystem,
|
||||
users: ReadonlyMap<number, UserInfo>,
|
||||
groups: ReadonlyMap<number, GroupInfo>,
|
||||
user: UserInfo,
|
||||
): ShellState {
|
||||
return Object.freeze({
|
||||
filesystem,
|
||||
users,
|
||||
groups,
|
||||
sessionStack: Object.freeze([createInitialSessionState(user)]),
|
||||
});
|
||||
}
|
||||
|
||||
export function withCwd(state: ShellState, inode: number): ShellState {
|
||||
export function createShellState(
|
||||
filesystem: FileSystem,
|
||||
users: ReadonlyMap<number, UserInfo>,
|
||||
groups: ReadonlyMap<number, GroupInfo>,
|
||||
sessionStack: ReadonlyArray<SessionState>,
|
||||
): ShellState {
|
||||
return Object.freeze({
|
||||
filesystem,
|
||||
users,
|
||||
groups,
|
||||
sessionStack: Object.freeze(sessionStack),
|
||||
});
|
||||
}
|
||||
|
||||
export function withCwd(state: ShellState, ptr: NodePointer): ShellState {
|
||||
const session = getCurrentSession(state);
|
||||
|
||||
const newSession = Object.freeze({
|
||||
user: session.user,
|
||||
envVars: Object.freeze(session.envVars),
|
||||
history: Object.freeze(session.history),
|
||||
cwd: inode,
|
||||
cwd: ptr,
|
||||
pwd: session.cwd,
|
||||
exitCode: session.exitCode,
|
||||
} satisfies SessionState);
|
||||
@@ -40,6 +58,7 @@ export function withCwd(state: ShellState, inode: number): ShellState {
|
||||
return Object.freeze({
|
||||
filesystem: state.filesystem,
|
||||
users: state.users,
|
||||
groups: state.groups,
|
||||
sessionStack: Object.freeze(sessionStack),
|
||||
} satisfies ShellState);
|
||||
}
|
||||
@@ -63,6 +82,7 @@ export function withHistory(state: ShellState, input: string): ShellState {
|
||||
return Object.freeze({
|
||||
filesystem: state.filesystem,
|
||||
users: state.users,
|
||||
groups: state.groups,
|
||||
sessionStack: Object.freeze(sessionStack),
|
||||
} satisfies ShellState);
|
||||
}
|
||||
@@ -89,6 +109,7 @@ export function withEnv(state: ShellState, key: string, value: string): ShellSta
|
||||
return Object.freeze({
|
||||
filesystem: state.filesystem,
|
||||
users: state.users,
|
||||
groups: state.groups,
|
||||
sessionStack: Object.freeze(sessionStack),
|
||||
} satisfies ShellState);
|
||||
}
|
||||
@@ -112,6 +133,7 @@ export function withExitCode(state: ShellState, exitCode: number): ShellState {
|
||||
return Object.freeze({
|
||||
filesystem: state.filesystem,
|
||||
users: state.users,
|
||||
groups: state.groups,
|
||||
sessionStack: Object.freeze(sessionStack),
|
||||
} satisfies ShellState);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
//Payload optional because command that handles that signal
|
||||
// is going to know what shape it is, therefore also able to cast it;
|
||||
export type Signal = {
|
||||
type: SIGNAL_MAP;
|
||||
payload?: unknown;
|
||||
};
|
||||
|
||||
export enum SIGNAL_MAP {
|
||||
SIGINT = 2,
|
||||
SIGTERM = 3,
|
||||
SIGKILL = 9,
|
||||
INPUT = 10,
|
||||
}
|
||||
@@ -1,7 +0,0 @@
|
||||
export interface UserInfo {
|
||||
readonly name: string;
|
||||
readonly uid: number;
|
||||
readonly gid: number;
|
||||
readonly group: readonly number[];
|
||||
readonly home: number;
|
||||
}
|
||||
@@ -0,0 +1,224 @@
|
||||
export interface ShellError {
|
||||
readonly errorType: string;
|
||||
readonly message: string;
|
||||
readonly timestamp: number;
|
||||
readonly exitCode: number;
|
||||
readonly cause?: {
|
||||
readonly name: string;
|
||||
readonly message: string;
|
||||
};
|
||||
}
|
||||
|
||||
export function createShellError<E extends ShellError>(
|
||||
errorType: E["errorType"],
|
||||
message: string,
|
||||
extraProps: Omit<E, keyof ShellError>,
|
||||
cause?: { name: string; message: string },
|
||||
): E {
|
||||
let exitCode = EXIT_CODE_MAP[errorType] ?? 1;
|
||||
|
||||
// Special handling for signal termination
|
||||
if (errorType === "SignalTermination") {
|
||||
const signalError = extraProps as unknown as { signalNumber: number };
|
||||
exitCode = 128 + signalError.signalNumber;
|
||||
}
|
||||
|
||||
const base: ShellError = Object.freeze({
|
||||
errorType,
|
||||
message,
|
||||
timestamp: Date.now(),
|
||||
exitCode,
|
||||
...Object.freeze(cause !== undefined && { cause }),
|
||||
});
|
||||
|
||||
return Object.freeze({ ...base, ...extraProps }) as E;
|
||||
}
|
||||
|
||||
const EXIT_CODE_MAP: Record<string, number> = {
|
||||
GenericError: 1,
|
||||
InvalidArguments: 2,
|
||||
|
||||
ParseError: 62,
|
||||
UsageError: 63,
|
||||
PathResolutionError: 64,
|
||||
DataFormatError: 65,
|
||||
FileNotFound: 66,
|
||||
UserNotFound: 67,
|
||||
LoginError: 68,
|
||||
InternalSoftwareError: 70,
|
||||
OperatingSystemError: 71,
|
||||
SystemFileError: 72,
|
||||
CannotCreateOutput: 73,
|
||||
IoError: 74,
|
||||
TemporaryFailure: 75,
|
||||
TimeoutError: 75, // Same as TEMPFAIL
|
||||
ProtocolError: 76,
|
||||
PermissionDenied: 77,
|
||||
ConfigurationError: 78,
|
||||
CommandNotFound: 127,
|
||||
NotExecutable: 126,
|
||||
// SIGNAL_TERMINATION is handled dynamically (128 + signal)
|
||||
};
|
||||
|
||||
/** Generic catch-all error (Exit 1) */
|
||||
|
||||
// Its actually the ShellError itself - no need for a custom type
|
||||
|
||||
/* export interface GenericError extends ShellError {
|
||||
errorType: "GENERIC_ERROR";
|
||||
} */
|
||||
|
||||
export interface InvalidArgumentsError extends ShellError {
|
||||
errorType: "InvalidArguments";
|
||||
expected: string; // e.g., "Usage: command <file>"
|
||||
actual: string; // e.g., the user's input
|
||||
}
|
||||
|
||||
// Codes 3 - 62 reserved for currently running processes, and their specific error handling.
|
||||
|
||||
export interface ParseError extends ShellError {
|
||||
errorType: "ParseError";
|
||||
}
|
||||
|
||||
/** Command used incorrectly (bad flag, wrong arg count) - maps to EX_USAGE (Exit 64) */
|
||||
export interface UsageError extends ShellError {
|
||||
errorType: "UsageError";
|
||||
usageHint: string; // e.g., "command [-a] [-b] <filename>"
|
||||
}
|
||||
|
||||
// ===================== 2. FILE / I/O ERRORS (Exit: 65, 66, 72, 73, 74) =====================
|
||||
|
||||
/** Input file does not exist or is unreadable (Exit 66 - EX_NOINPUT) */
|
||||
export interface FileNotFoundError extends ShellError {
|
||||
errorType: "FileNotFound";
|
||||
path: string;
|
||||
}
|
||||
|
||||
export interface PathResolutionError extends ShellError {
|
||||
errorType: "PathResolutionError";
|
||||
path: string;
|
||||
}
|
||||
|
||||
/** Input data has invalid format (Exit 65 - EX_DATAERR) */
|
||||
export interface DataFormatError extends ShellError {
|
||||
errorType: "DataFormatError";
|
||||
path?: string; // Optional: which file had bad data
|
||||
line?: number; // Optional: line number if applicable
|
||||
}
|
||||
|
||||
/** System file (e.g., /etc/passwd, /etc/hosts) is broken or missing (Exit 72 - EX_OSFILE) */
|
||||
export interface SystemFileError extends ShellError {
|
||||
errorType: "SystemFileError";
|
||||
path: string;
|
||||
}
|
||||
|
||||
/** Cannot create user-specified output file (Exit 73 - EX_CANTCREAT) */
|
||||
export interface CannotCreateOutputError extends ShellError {
|
||||
errorType: "CannotCreateOutput";
|
||||
path: string;
|
||||
reason: string; // e.g., "Directory does not exist", "Read-only filesystem"
|
||||
}
|
||||
|
||||
/** I/O error while reading/writing a file (Exit 74 - EX_IOERR) */
|
||||
export interface IOError extends ShellError {
|
||||
errorType: "IoError";
|
||||
path: string;
|
||||
operation: "read" | "write" | "seek";
|
||||
}
|
||||
|
||||
// ===================== 3. PERMISSION / USER ERRORS (Exit: 67, 77) =====================
|
||||
|
||||
/** Insufficient permission to access a resource (Exit 77 - EX_NOPERM) */
|
||||
export interface PermissionDeniedError extends ShellError {
|
||||
errorType: "PermissionDenied";
|
||||
resource: string; // File path, port, socket, etc.
|
||||
}
|
||||
|
||||
/** Specified user does not exist (Exit 67 - EX_NOUSER) */
|
||||
export interface UserNotFoundError extends ShellError {
|
||||
errorType: "UserNotFound";
|
||||
username: string;
|
||||
}
|
||||
|
||||
export interface LoginError extends ShellError {
|
||||
errorType: "LoginError";
|
||||
user: number;
|
||||
}
|
||||
|
||||
/** Required service is unavailable (Exit 69 - EX_UNAVAILABLE) */
|
||||
export interface ServiceUnavailableError extends ShellError {
|
||||
errorType: "ServiceUnavailable";
|
||||
service: string; // e.g., "database", "DNS", "SSH"
|
||||
port?: number;
|
||||
}
|
||||
|
||||
// ===================== 5. PROCESS / EXECUTION ERRORS (Exit: 126, 127, 71) =====================
|
||||
|
||||
/** Command not found (Exit 127 - POSIX standard) */
|
||||
export interface CommandNotFoundError extends ShellError {
|
||||
errorType: "CommandNotFound";
|
||||
command: string;
|
||||
}
|
||||
|
||||
/** Command found but not executable (Exit 126 - POSIX standard) */
|
||||
export interface NotExecutableError extends ShellError {
|
||||
errorType: "NotExecutable";
|
||||
path: string;
|
||||
}
|
||||
|
||||
/** Operating system error (fork, pipe, process table full) (Exit 71 - EX_OSERR) */
|
||||
export interface OperatingSystemError extends ShellError {
|
||||
errorType: "OperatingSystemError";
|
||||
syscall: string; // e.g., "fork", "pipe", "execve"
|
||||
errno?: number; // Optional: underlying OS error code
|
||||
}
|
||||
|
||||
// ===================== 6. TIMING / RETRY ERRORS (Exit: 75) =====================
|
||||
|
||||
/** Temporary failure; user should retry (Exit 75 - EX_TEMPFAIL) */
|
||||
export interface TemporaryFailureError extends ShellError {
|
||||
errorType: "TemporaryFailure";
|
||||
retryAfter?: number; // Optional: recommended seconds to wait
|
||||
resource?: string; // Optional: what resource is temporarily busy
|
||||
}
|
||||
|
||||
/** Operation timed out (Often mapped to EX_TEMPFAIL, Exit 75) */
|
||||
export interface TimeoutError extends ShellError {
|
||||
errorType: "TimeoutError";
|
||||
timeoutSeconds: number;
|
||||
operation: string; // e.g., "HTTP request", "Database query"
|
||||
}
|
||||
|
||||
// ===================== 7. INTERNAL / CONFIGURATION ERRORS (Exit: 70, 78) =====================
|
||||
|
||||
/** Internal software error (bug, assertion failed) (Exit 70 - EX_SOFTWARE) */
|
||||
export interface InternalSoftwareError extends ShellError {
|
||||
errorType: "InternalSoftwareError";
|
||||
component: string; // e.g., "parser", "network layer"
|
||||
}
|
||||
|
||||
/** Configuration error in the program or system (Exit 78 - EX_CONFIG) */
|
||||
export interface ConfigurationError extends ShellError {
|
||||
errorType: "ConfigurationError";
|
||||
configFile?: string;
|
||||
key?: string; // Which config key is wrong
|
||||
}
|
||||
|
||||
// ===================== 8. PROTOCOL / REMOTE ERRORS (Exit: 76) =====================
|
||||
|
||||
/** Remote system protocol error (Exit 76 - EX_PROTOCOL) */
|
||||
export interface ProtocolError extends ShellError {
|
||||
errorType: "ProtocolError";
|
||||
remoteHost?: string;
|
||||
protocol: string; // e.g., "HTTP", "SSH", "FTP"
|
||||
statusCode?: number; // Optional: e.g., HTTP 400/500
|
||||
}
|
||||
|
||||
// ===================== 9. SIGNAL TERMINATION (Exit: 128 + signal) =====================
|
||||
|
||||
/** Process was killed by a signal (Exit = 128 + signalNumber) */
|
||||
export interface SignalTerminationError extends ShellError {
|
||||
errorType: "SignalTermination";
|
||||
signalNumber: number; // e.g., 9 (SIGKILL), 15 (SIGTERM), 2 (SIGINT)
|
||||
signalName: string; // e.g., "SIGTERM", "SIGKILL"
|
||||
}
|
||||
@@ -2,6 +2,7 @@ export interface ImmutableBuffer {
|
||||
readonly length: number;
|
||||
get(index: number): number;
|
||||
slice(start?: number, end?: number): ImmutableBuffer;
|
||||
byteSize(): number;
|
||||
toArray(): Uint8Array;
|
||||
}
|
||||
|
||||
@@ -22,10 +23,15 @@ export function createImmutableBuffer(input: Uint8Array): ImmutableBuffer {
|
||||
return Uint8Array.from(buffer);
|
||||
};
|
||||
|
||||
const byteSize = (): number => {
|
||||
return buffer.byteLength;
|
||||
};
|
||||
|
||||
const result: ImmutableBuffer = {
|
||||
length: buffer.length,
|
||||
get,
|
||||
slice,
|
||||
byteSize,
|
||||
toArray,
|
||||
};
|
||||
|
||||
|
||||
+1
-52
@@ -6,13 +6,7 @@ interface UnclosedQuoteError {
|
||||
timestamp: number;
|
||||
}
|
||||
|
||||
interface ParsedCommand {
|
||||
command: string;
|
||||
flags: string[];
|
||||
args: string[];
|
||||
}
|
||||
|
||||
function tokenize(input: string): string[] {
|
||||
export function tokenize(input: string): string[] {
|
||||
enum State {
|
||||
Normal,
|
||||
SingleQuote,
|
||||
@@ -98,48 +92,3 @@ function tokenize(input: string): string[] {
|
||||
flushBuffer();
|
||||
return tokens;
|
||||
}
|
||||
|
||||
export function parseCommand(input: string): ParsedCommand {
|
||||
const tokens = tokenize(input);
|
||||
const command = tokens[0] ?? "";
|
||||
const flags: string[] = [];
|
||||
const args: string[] = [];
|
||||
|
||||
let pastEndOfOptions = false;
|
||||
|
||||
for (let i = 1; i < tokens.length; i++) {
|
||||
const token = tokens[i]!;
|
||||
|
||||
if (pastEndOfOptions) {
|
||||
args.push(token);
|
||||
continue;
|
||||
}
|
||||
if (token === "--") {
|
||||
pastEndOfOptions = true;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (token.startsWith("--")) {
|
||||
flags.push(token.slice(2));
|
||||
continue;
|
||||
} else if (token.startsWith("-")) {
|
||||
if (token.includes("=")) {
|
||||
flags.push(token.slice(1));
|
||||
continue;
|
||||
}
|
||||
for (const char of token.slice(1)) {
|
||||
flags.push(char);
|
||||
}
|
||||
continue;
|
||||
} else {
|
||||
args.push(token);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
command,
|
||||
flags,
|
||||
args,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -0,0 +1,269 @@
|
||||
import type { FileSystemCorruptionError, NodeNotFoundError, NotADirectoryError } from "@core/filesystem/errors";
|
||||
import { NodePointer, NodeType, type Node } from "@core/filesystem/node";
|
||||
import { getCurrentSession } from "@core/session_manager";
|
||||
import type { ShellState } from "@core/shell_state";
|
||||
|
||||
export function resolvePath(state: ShellState, path: string): NodePointer {
|
||||
let linkDepth = 0;
|
||||
const maxDepth = state.filesystem.maxSymlinkDepth;
|
||||
|
||||
const session = getCurrentSession(state);
|
||||
const isAbsolute = path.startsWith("/");
|
||||
|
||||
const pathComponents: string[] = path.split("/").filter(c => c.length > 0);
|
||||
|
||||
let currentDeviceId: number;
|
||||
let currentNode: Node;
|
||||
|
||||
if (isAbsolute) {
|
||||
currentDeviceId = 0;
|
||||
currentNode = state.filesystem.getRoot();
|
||||
} else if (!isAbsolute && pathComponents[0] === "~") {
|
||||
const home = session.user.home;
|
||||
currentDeviceId = home.device;
|
||||
currentNode = state.filesystem.getNode(session.user.home)!;
|
||||
if (!currentNode) {
|
||||
throw {
|
||||
type: "NodeNotFound",
|
||||
message: `[Panic] ${session.user.username}'s home directory does not exist!`,
|
||||
timestamp: Date.now(),
|
||||
pointer: session.user.home,
|
||||
} satisfies NodeNotFoundError;
|
||||
}
|
||||
pathComponents.shift();
|
||||
|
||||
if (currentNode.type === NodeType.Symlink) {
|
||||
if (++linkDepth > maxDepth) throw new Error("Symlink max depth - aborting!");
|
||||
const target = currentNode.target;
|
||||
if (target.startsWith("/")) {
|
||||
currentDeviceId = 0;
|
||||
currentNode = state.filesystem.getRoot();
|
||||
} else {
|
||||
const entries = state.filesystem.getNodeEntries(session.user.home);
|
||||
if (!entries?.[0]) {
|
||||
throw {
|
||||
type: "FileSystemCorruption",
|
||||
message: "Reverse index entry missing, FileSystem corrupted",
|
||||
timestamp: Date.now(),
|
||||
} satisfies FileSystemCorruptionError;
|
||||
}
|
||||
currentDeviceId = entries[0].pdevice_id;
|
||||
currentNode = state.filesystem.getNode(NodePointer.of(entries[0].pdevice_id, entries[0].pinode))!;
|
||||
}
|
||||
|
||||
pathComponents.unshift(...target.split("/").filter(c => c.length > 0));
|
||||
}
|
||||
} else {
|
||||
currentDeviceId = session.cwd.device;
|
||||
currentNode = state.filesystem.getNode(session.cwd)!;
|
||||
if (!currentNode) {
|
||||
throw {
|
||||
type: "NodeNotFound",
|
||||
message: "[Panic] Current working directory does not exist!",
|
||||
timestamp: Date.now(),
|
||||
pointer: session.cwd,
|
||||
} satisfies NodeNotFoundError;
|
||||
}
|
||||
}
|
||||
|
||||
while (pathComponents.length > 0) {
|
||||
const name = pathComponents.shift()!;
|
||||
|
||||
if (name === ".") continue;
|
||||
if (name === "..") {
|
||||
if (state.filesystem.isMountTarget(NodePointer.of(currentDeviceId, currentNode.inode))) {
|
||||
const mount = state.filesystem.getMountPoint(NodePointer.of(currentDeviceId, currentNode.inode));
|
||||
if (!mount) {
|
||||
throw {
|
||||
type: "FileSystemCorruption",
|
||||
message: "Mount registry entry missing, FileSystem corrupted",
|
||||
timestamp: Date.now(),
|
||||
} satisfies FileSystemCorruptionError;
|
||||
}
|
||||
|
||||
const entries = state.filesystem.getNodeEntries(mount);
|
||||
if (!entries?.[0]) {
|
||||
throw {
|
||||
type: "FileSystemCorruption",
|
||||
message: "Reverse index entry missing, FileSystem corrupted",
|
||||
timestamp: Date.now(),
|
||||
} satisfies FileSystemCorruptionError;
|
||||
}
|
||||
|
||||
currentDeviceId = entries[0].pdevice_id;
|
||||
currentNode = state.filesystem.getNode(NodePointer.of(entries[0].pdevice_id, entries[0].pinode))!;
|
||||
continue;
|
||||
}
|
||||
if (currentNode.inode === 0) continue;
|
||||
|
||||
const entries = state.filesystem.getNodeEntries(NodePointer.of(currentDeviceId, currentNode.inode));
|
||||
|
||||
if (!entries?.[0]) {
|
||||
throw {
|
||||
type: "FileSystemCorruption",
|
||||
message: "Reverse index entry missing, FileSystem corrupted",
|
||||
timestamp: Date.now(),
|
||||
} satisfies FileSystemCorruptionError;
|
||||
}
|
||||
|
||||
currentDeviceId = entries[0].pdevice_id;
|
||||
currentNode = state.filesystem.getNode(NodePointer.of(entries[0].pdevice_id, entries[0].pinode))!;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (currentNode.type !== NodeType.Directory) {
|
||||
throw {
|
||||
type: "NotADirectory",
|
||||
message: "Not a directory",
|
||||
timestamp: Date.now(),
|
||||
inode: currentNode.inode,
|
||||
nodeType: currentNode.type,
|
||||
} satisfies NotADirectoryError;
|
||||
}
|
||||
|
||||
const childInode = currentNode.children.get(name);
|
||||
if (childInode === undefined) {
|
||||
throw {
|
||||
type: "NodeNotFound",
|
||||
message: `${name} not found`,
|
||||
timestamp: Date.now(),
|
||||
pointer: NodePointer.of(currentDeviceId, currentNode.inode),
|
||||
} satisfies NodeNotFoundError;
|
||||
}
|
||||
|
||||
let childPtr = NodePointer.of(currentDeviceId, childInode);
|
||||
|
||||
if (state.filesystem.isMountPoint(childPtr)) {
|
||||
const mount = state.filesystem.getMountTarget(childPtr)!;
|
||||
childPtr = mount;
|
||||
currentDeviceId = mount.device;
|
||||
}
|
||||
|
||||
let child = state.filesystem.getNode(childPtr);
|
||||
if (!child) {
|
||||
throw {
|
||||
type: "NodeNotFound",
|
||||
message: `Node under ${childPtr} not found (probable dangling orphan)`,
|
||||
timestamp: Date.now(),
|
||||
pointer: childPtr,
|
||||
} satisfies NodeNotFoundError;
|
||||
}
|
||||
|
||||
if (child.type === NodeType.Symlink) {
|
||||
// Change to typed error later on
|
||||
if (++linkDepth > maxDepth) throw new Error("Symlink max depth - aborting!");
|
||||
const target = child.target;
|
||||
if (target.startsWith("/")) {
|
||||
currentDeviceId = 0;
|
||||
currentNode = state.filesystem.getRoot();
|
||||
} else {
|
||||
const entries = state.filesystem.getNodeEntries(childPtr);
|
||||
if (!entries?.[0]) {
|
||||
throw {
|
||||
type: "FileSystemCorruption",
|
||||
message: "Reverse index entry missing, FileSystem corrupted",
|
||||
timestamp: Date.now(),
|
||||
} satisfies FileSystemCorruptionError;
|
||||
}
|
||||
currentDeviceId = entries[0].pdevice_id;
|
||||
currentNode = state.filesystem.getNode(NodePointer.of(entries[0].pdevice_id, entries[0].pinode))!;
|
||||
}
|
||||
|
||||
pathComponents.unshift(...target.split("/").filter(c => c.length > 0));
|
||||
continue;
|
||||
}
|
||||
|
||||
currentNode = child;
|
||||
}
|
||||
|
||||
return NodePointer.of(currentDeviceId, currentNode.inode);
|
||||
}
|
||||
|
||||
export function resolvePointer(state: ShellState, pointer: NodePointer): string {
|
||||
const node = state.filesystem.getNode(pointer);
|
||||
const components: string[] = [];
|
||||
|
||||
if (node === undefined) return "";
|
||||
|
||||
let ptr = pointer;
|
||||
// TODO: Change while statements condition to not be hardcoded
|
||||
while (!ptr.equals(NodePointer.of(0, 0))) {
|
||||
if (state.filesystem.isMountTarget(ptr)) {
|
||||
const mount = state.filesystem.getMountPoint(ptr);
|
||||
if (!mount) {
|
||||
throw {
|
||||
type: "FileSystemCorruption",
|
||||
message: "Mount registry entry missing, FileSystem corrupted",
|
||||
timestamp: Date.now(),
|
||||
} satisfies FileSystemCorruptionError;
|
||||
}
|
||||
|
||||
const entries = state.filesystem.getNodeEntries(mount);
|
||||
if (!entries?.[0]) {
|
||||
throw {
|
||||
type: "FileSystemCorruption",
|
||||
message: "Reverse index entry missing, FileSystem corrupted",
|
||||
timestamp: Date.now(),
|
||||
} satisfies FileSystemCorruptionError;
|
||||
}
|
||||
|
||||
components.push(entries[0].name);
|
||||
ptr = NodePointer.of(entries[0].pdevice_id, entries[0].pinode);
|
||||
continue;
|
||||
}
|
||||
|
||||
const entries = state.filesystem.getNodeEntries(ptr);
|
||||
if (!entries?.[0]) {
|
||||
throw {
|
||||
type: "FileSystemCorruption",
|
||||
message: "Reverse index entry missing, FileSystem corrupted",
|
||||
timestamp: Date.now(),
|
||||
} satisfies FileSystemCorruptionError;
|
||||
}
|
||||
|
||||
components.push(entries[0].name);
|
||||
ptr = NodePointer.of(entries[0].pdevice_id, entries[0].pinode);
|
||||
}
|
||||
if (components.length === 0) {
|
||||
components.push("/");
|
||||
return components.join("");
|
||||
}
|
||||
|
||||
components.reverse().unshift("");
|
||||
let result = components.join("/");
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
export function resolvePointerToHome(state: ShellState, ptr: NodePointer): string {
|
||||
const home = resolvePointer(state, getCurrentSession(state).user.home);
|
||||
let result = resolvePointer(state, ptr);
|
||||
|
||||
if (result.startsWith(home)) {
|
||||
result = `~${result.slice(home.length)}`;
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
export function resolvePointerToCwd(state: ShellState, ptr: NodePointer): string {
|
||||
const cwd = resolvePointer(state, getCurrentSession(state).cwd);
|
||||
let result = resolvePointer(state, ptr);
|
||||
|
||||
if (result.startsWith(cwd)) {
|
||||
result = `.${result.slice(cwd.length)}`;
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
export function resolvePointerRelative(state: ShellState, ptr: NodePointer, relative: NodePointer): string {
|
||||
const rel = resolvePointer(state, relative);
|
||||
let result = resolvePointer(state, ptr);
|
||||
|
||||
if (result.startsWith(rel)) {
|
||||
result = `.${result.slice(rel.length)}`;
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
import { FileNode, NodePointer } from "@core/filesystem/node";
|
||||
import type { ShellState } from "@core/shell_state";
|
||||
import { Posix } from "@termos/util/posix";
|
||||
|
||||
export enum SortNodeBy {
|
||||
NAME = "name",
|
||||
INODE = "inode",
|
||||
SIZE = "size",
|
||||
EXTENSION = "extension",
|
||||
TYPE = "type",
|
||||
MTIME = "mtime",
|
||||
ATIME = "atime",
|
||||
CTIME = "ctime",
|
||||
}
|
||||
|
||||
export function sortNodes<T extends { name: string; ptr: NodePointer }>(
|
||||
state: ShellState,
|
||||
arr: T[],
|
||||
r: boolean = false,
|
||||
by: SortNodeBy = SortNodeBy.NAME,
|
||||
): T[] {
|
||||
if (arr.length === 0) return [];
|
||||
|
||||
nodeQS(arr, r, by, 0, arr.length - 1, state);
|
||||
return arr;
|
||||
}
|
||||
|
||||
function nodeQS(
|
||||
arr: { name: string; ptr: NodePointer }[],
|
||||
r: boolean,
|
||||
by: SortNodeBy,
|
||||
start: number,
|
||||
end: number,
|
||||
state: ShellState,
|
||||
): void {
|
||||
if (end <= start) return;
|
||||
|
||||
const pivot = partitionNodeArray(arr, r, by, start, end, state);
|
||||
nodeQS(arr, r, by, start, pivot - 1, state);
|
||||
nodeQS(arr, r, by, pivot + 1, end, state);
|
||||
}
|
||||
|
||||
function partitionNodeArray(
|
||||
part: { name: string; ptr: NodePointer }[],
|
||||
r: boolean,
|
||||
by: SortNodeBy,
|
||||
start: number,
|
||||
end: number,
|
||||
state: ShellState,
|
||||
): number {
|
||||
const pivot = part[end];
|
||||
let i = start - 1;
|
||||
|
||||
for (let j = start; j <= end; j++) {
|
||||
if (compareNode(part[j]!, pivot!, by, r, state) < 0) {
|
||||
i++;
|
||||
const temp = part[i]!;
|
||||
part[i] = part[j]!;
|
||||
part[j] = temp;
|
||||
}
|
||||
}
|
||||
|
||||
i++;
|
||||
const temp = part[i]!;
|
||||
part[i] = part[end]!;
|
||||
part[end] = temp;
|
||||
|
||||
return i;
|
||||
}
|
||||
|
||||
function compareNode(
|
||||
a: { name: string; ptr: NodePointer },
|
||||
b: { name: string; ptr: NodePointer },
|
||||
by: SortNodeBy,
|
||||
r: boolean,
|
||||
state: ShellState,
|
||||
): number {
|
||||
switch (by) {
|
||||
case SortNodeBy.NAME: {
|
||||
const A: string = a.name;
|
||||
const B: string = b.name;
|
||||
const min = Math.min(A.length, B.length);
|
||||
|
||||
for (let i = 0; i < min; i++) {
|
||||
const charA = Posix.GetCharWeight(A.charAt(i));
|
||||
const charB = Posix.GetCharWeight(B.charAt(i));
|
||||
|
||||
if (charA !== charB) {
|
||||
return r ? charB - charA : charA - charB;
|
||||
}
|
||||
}
|
||||
|
||||
return r ? B.length - A.length : A.length - B.length;
|
||||
}
|
||||
|
||||
case SortNodeBy.MTIME:
|
||||
case SortNodeBy.ATIME:
|
||||
case SortNodeBy.CTIME: {
|
||||
const nodeA = state.filesystem.getNode(a.ptr)!;
|
||||
const nodeB = state.filesystem.getNode(b.ptr)!;
|
||||
const A: number = nodeA[by];
|
||||
const B: number = nodeB[by];
|
||||
|
||||
return r ? A - B : B - A;
|
||||
}
|
||||
|
||||
case SortNodeBy.SIZE: {
|
||||
const nodeA = state.filesystem.getNode(a.ptr)!;
|
||||
const nodeB = state.filesystem.getNode(b.ptr)!;
|
||||
const A: number = (nodeA as FileNode).size;
|
||||
const B: number = (nodeB as FileNode).size;
|
||||
|
||||
return r ? A - B : B - A;
|
||||
}
|
||||
|
||||
case SortNodeBy.EXTENSION: {
|
||||
const A: string = a.name.split(".").pop() ?? "";
|
||||
const B: string = b.name.split(".").pop() ?? "";
|
||||
const min = Math.min(A.length, B.length);
|
||||
|
||||
for (let i = 0; i < min; i++) {
|
||||
const charA = Posix.GetCharWeight(A.charAt(i));
|
||||
const charB = Posix.GetCharWeight(B.charAt(i));
|
||||
|
||||
if (charA !== charB) {
|
||||
return r ? charB - charA : charA - charB;
|
||||
}
|
||||
}
|
||||
|
||||
return r ? B.length - A.length : A.length - B.length;
|
||||
}
|
||||
|
||||
case SortNodeBy.INODE: {
|
||||
return r ? a.ptr.inode - b.ptr.inode : b.ptr.inode - a.ptr.inode;
|
||||
}
|
||||
|
||||
case SortNodeBy.TYPE: {
|
||||
const nodeA = state.filesystem.getNode(a.ptr)!;
|
||||
const nodeB = state.filesystem.getNode(a.ptr)!;
|
||||
return r ? nodeB.type - nodeA.type : nodeA.type - nodeB.type;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
import type { Node } from "@core/filesystem/node";
|
||||
import type { IDataStore, IMetaStore } from "@core/filesystem/vdisk";
|
||||
import type { Blob } from "node:buffer";
|
||||
import { Readable } from "node:stream";
|
||||
|
||||
export class MemMetaStore implements IMetaStore {
|
||||
private _data: Map<number, Node | null> = new Map();
|
||||
|
||||
public loadAll(): Promise<Map<number, Node | null>> {
|
||||
return Promise.resolve(this._data);
|
||||
}
|
||||
|
||||
public write(entries: Array<[number, Node | null]>): Promise<void> {
|
||||
for (const [inode, node] of entries) {
|
||||
this._data.set(inode, node);
|
||||
}
|
||||
return Promise.resolve();
|
||||
}
|
||||
|
||||
public delete(entries: number[]): Promise<void> {
|
||||
for (const inode of entries) {
|
||||
this._data.delete(inode);
|
||||
}
|
||||
return Promise.resolve();
|
||||
}
|
||||
}
|
||||
|
||||
export class MemDataStore implements IDataStore {
|
||||
private _data: Map<string, Blob> = new Map();
|
||||
|
||||
public async read(uuid: string): Promise<Uint8Array> {
|
||||
const blob = this._data.get(uuid);
|
||||
if (!blob) throw new Error("Content missing - " + uuid);
|
||||
const buff = await blob.arrayBuffer();
|
||||
return new Uint8Array(buff);
|
||||
}
|
||||
|
||||
public stream(uuid: string): Readable {
|
||||
const blob = this._data.get(uuid);
|
||||
if (!blob) throw new Error("Content missing - " + uuid);
|
||||
|
||||
return Readable.from(blob.stream());
|
||||
}
|
||||
|
||||
public put(uuid: string, blob: Blob): Promise<void> {
|
||||
this._data.set(uuid, blob);
|
||||
return Promise.resolve();
|
||||
}
|
||||
|
||||
public delete(uuid: string): Promise<void> {
|
||||
this._data.delete(uuid);
|
||||
return Promise.resolve();
|
||||
}
|
||||
|
||||
public has(uuid: string): Promise<boolean> {
|
||||
return Promise.resolve(this._data.has(uuid));
|
||||
}
|
||||
|
||||
public list(): Promise<string[]> {
|
||||
return Promise.resolve(Array.from(this._data.keys()));
|
||||
}
|
||||
}
|
||||
@@ -1,41 +1,44 @@
|
||||
import type { FileSystem } from "@core/filesystem/filesystem";
|
||||
import { TreeNodeType, type TreeNode } from "@core/filesystem/treenode";
|
||||
import { NodePointer, NodeType, type NodeEntry } from "@core/filesystem/node";
|
||||
|
||||
export function dnTraverseTree(fs: FileSystem, root: number): number[] {
|
||||
export function dnTraverseTree(fs: FileSystem, root: NodePointer): NodePointer[] {
|
||||
if (fs.getNode(root) === undefined) return [];
|
||||
|
||||
const result: number[] = [];
|
||||
const stack: number[] = [];
|
||||
const result: NodePointer[] = [];
|
||||
const stack: NodePointer[] = [];
|
||||
stack.push(root);
|
||||
while (stack.length > 0) {
|
||||
const node = fs.getNode(stack.pop() as number);
|
||||
if (node === undefined) continue;
|
||||
const ptr = stack.pop()!;
|
||||
const node = fs.getNode(ptr);
|
||||
if (!node) continue;
|
||||
|
||||
result.push(node.inode);
|
||||
result.push(ptr);
|
||||
|
||||
if (node.type === TreeNodeType.Directory) {
|
||||
for (const value of Object.values(node.children)) {
|
||||
stack.push(value);
|
||||
if (node.type === NodeType.Directory) {
|
||||
const children = Array.from(node.children.values());
|
||||
for (let i = children.length - 1; i >= 0; i--) {
|
||||
const child = children[i]!;
|
||||
const pointer = NodePointer.of(ptr.device, child);
|
||||
stack.push(pointer);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
export function upTraverseTree(fs: FileSystem, inode: number): number[] {
|
||||
if (fs.getNode(inode) === undefined) return [];
|
||||
export function upTraverseTree(fs: FileSystem, ptr: NodePointer): NodePointer[] {
|
||||
if (fs.getNode(ptr) === undefined) return [];
|
||||
|
||||
const result: number[] = [];
|
||||
result.push(inode);
|
||||
const result: NodePointer[] = [ptr];
|
||||
let currentPtr = ptr;
|
||||
|
||||
let currentInode = inode;
|
||||
while (currentInode !== 0) {
|
||||
const node = fs.getNode(currentInode) as TreeNode;
|
||||
if (!node) break;
|
||||
while (currentPtr.inode !== 0) {
|
||||
const entries = fs.getNodeEntries(currentPtr);
|
||||
if (!entries || entries.length === 0) throw new Error(`No reverse-index entry found for ${currentPtr}`);
|
||||
|
||||
result.push(node.parent);
|
||||
currentInode = node.parent;
|
||||
const parent = entries[0] as NodeEntry;
|
||||
currentPtr = NodePointer.of(parent.pdevice_id, parent.pinode);
|
||||
result.push(currentPtr);
|
||||
}
|
||||
|
||||
return result;
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
import { IDataStore, IMetaStore, VDisk, VDiskConfig } from "@core/filesystem/vdisk";
|
||||
|
||||
export class VDiskManager {
|
||||
private _disks: Map<number, VDisk>;
|
||||
|
||||
constructor() {
|
||||
this._disks = new Map();
|
||||
}
|
||||
|
||||
public async registerDisk(config: VDiskConfig, data: IDataStore, meta: IMetaStore): Promise<VDisk> {
|
||||
if (this._disks.has(config.id)) {
|
||||
throw new Error("Disk of this id already exists");
|
||||
}
|
||||
|
||||
const vd = await VDisk.open(config, data, meta);
|
||||
this._disks.set(config.id, vd);
|
||||
|
||||
return vd;
|
||||
}
|
||||
|
||||
public getDisk(id: number): VDisk | undefined {
|
||||
const vd = this._disks.get(id);
|
||||
return vd;
|
||||
}
|
||||
|
||||
public hasDisk(id: number): boolean {
|
||||
return this._disks.has(id);
|
||||
}
|
||||
|
||||
public listDisk(): VDisk[] {
|
||||
return Array.from(this._disks.values());
|
||||
}
|
||||
|
||||
public listID(): number[] {
|
||||
return Array.from(this._disks.keys());
|
||||
}
|
||||
|
||||
public unregisterDisk(id: number): void {
|
||||
if (!this._disks.has(id)) {
|
||||
throw new Error("Disk of this id doesnt exist");
|
||||
}
|
||||
|
||||
this._disks.delete(id);
|
||||
}
|
||||
}
|
||||
+60
File diff suppressed because one or more lines are too long
+188
@@ -0,0 +1,188 @@
|
||||
import type { FileSystemCorruptionError, NodeNotFoundError, NotADirectoryError } from "@core/filesystem/errors";
|
||||
import { FileSystem } from "@core/filesystem/filesystem";
|
||||
import { NodePointer, NodeType, type Node } from "@core/filesystem/node";
|
||||
import type { GroupInfo, UserInfo } from "@core/session_manager";
|
||||
import { createInitialShellState, type ShellState } from "@core/shell_state";
|
||||
import { deserializeFileSystem } from "@shell/serializer";
|
||||
import { Shell } from "@shell/shell";
|
||||
import type { TermosConfig } from "./config";
|
||||
|
||||
async function getShell(config: TermosConfig): Promise<Shell> {
|
||||
// TODO: Validate json schema
|
||||
const devices = deserializeFileSystem(config.filesystem.json);
|
||||
|
||||
const fs = await FileSystem.init(devices);
|
||||
|
||||
const users: Map<number, UserInfo> = new Map();
|
||||
const groups: Map<number, GroupInfo> = new Map();
|
||||
const reverseGroups: Map<string, number> = new Map();
|
||||
const reverseUsers: Map<string, number> = new Map();
|
||||
|
||||
if (config.users.length === 0) throw new Error("System needs to have at least one user");
|
||||
if (config.groups.length === 0) throw new Error("System needs to have at least one user group");
|
||||
for (let i = 1000; i < config.groups.length + 1000; i++) {
|
||||
const group = config.groups[i - 1000]!;
|
||||
reverseGroups.set(group, i);
|
||||
|
||||
const members: number[] = [];
|
||||
for (let i = 1000; i < config.users.length + 1000; i++) {
|
||||
const user = config.users[i - 1000]!;
|
||||
if (user.groups.some(g => g === group)) {
|
||||
members.push(i);
|
||||
}
|
||||
}
|
||||
groups.set(i, { groupname: group, gid: i, members });
|
||||
}
|
||||
|
||||
for (let i = 1000; i < config.users.length + 1000; i++) {
|
||||
const user = config.users[i - 1000]!;
|
||||
if (user.groups.length === 0) throw new Error("User must belong to at least one user group");
|
||||
|
||||
const gid = reverseGroups.get(user.groups[0]!);
|
||||
if (!gid) throw new Error("User is a member of an undefined group");
|
||||
|
||||
const groups: number[] = [];
|
||||
|
||||
for (const group of user.groups) {
|
||||
if (group === "sudoers") continue;
|
||||
const gid = reverseGroups.get(group);
|
||||
if (!gid) throw new Error("User is a member of an undefined group");
|
||||
groups.push(gid);
|
||||
}
|
||||
|
||||
reverseUsers.set(user.username, i);
|
||||
users.set(i, { username: user.username, uid: i, gid, group: groups, home: resPath(user.home) });
|
||||
}
|
||||
const uid = reverseUsers.get(config.general.user);
|
||||
if (!uid) throw new Error("Tried to initialize termos with an undefined user");
|
||||
|
||||
const user = users.get(uid)!;
|
||||
|
||||
const state: ShellState = createInitialShellState(fs, users, groups, user);
|
||||
return new Shell(state);
|
||||
|
||||
function resPath(path: string) {
|
||||
let linkDepth = 0;
|
||||
const maxDepth = fs.maxSymlinkDepth;
|
||||
|
||||
const pathComponents: string[] = path.split("/").filter(c => c.length > 0);
|
||||
|
||||
let currentDeviceId: number = 0;
|
||||
let currentNode: Node = fs.getRoot();
|
||||
|
||||
while (pathComponents.length > 0) {
|
||||
const name = pathComponents.shift()!;
|
||||
|
||||
if (name === ".") continue;
|
||||
if (name === "..") {
|
||||
if (fs.isMountTarget(NodePointer.of(currentDeviceId, currentNode.inode))) {
|
||||
const mount = fs.getMountPoint(NodePointer.of(currentDeviceId, currentNode.inode));
|
||||
if (!mount) {
|
||||
throw {
|
||||
type: "FileSystemCorruption",
|
||||
message: "Mount registry entry missing, FileSystem corrupted",
|
||||
timestamp: Date.now(),
|
||||
} satisfies FileSystemCorruptionError;
|
||||
}
|
||||
|
||||
const entries = fs.getNodeEntries(mount);
|
||||
if (!entries?.[0]) {
|
||||
throw {
|
||||
type: "FileSystemCorruption",
|
||||
message: "Reverse index entry missing, FileSystem corrupted",
|
||||
timestamp: Date.now(),
|
||||
} satisfies FileSystemCorruptionError;
|
||||
}
|
||||
|
||||
currentDeviceId = entries[0].pdevice_id;
|
||||
currentNode = fs.getNode(NodePointer.of(entries[0].pdevice_id, entries[0].pinode))!;
|
||||
continue;
|
||||
}
|
||||
if (currentNode.inode === 0) continue;
|
||||
|
||||
const entries = fs.getNodeEntries(NodePointer.of(currentDeviceId, currentNode.inode));
|
||||
|
||||
if (!entries?.[0]) {
|
||||
throw {
|
||||
type: "FileSystemCorruption",
|
||||
message: "Reverse index entry missing, FileSystem corrupted",
|
||||
timestamp: Date.now(),
|
||||
} satisfies FileSystemCorruptionError;
|
||||
}
|
||||
|
||||
currentDeviceId = entries[0].pdevice_id;
|
||||
currentNode = fs.getNode(NodePointer.of(entries[0].pdevice_id, entries[0].pinode))!;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (currentNode.type !== NodeType.Directory) {
|
||||
throw {
|
||||
type: "NotADirectory",
|
||||
message: "Not a directory",
|
||||
timestamp: Date.now(),
|
||||
inode: currentNode.inode,
|
||||
nodeType: currentNode.type,
|
||||
} satisfies NotADirectoryError;
|
||||
}
|
||||
|
||||
const childInode = currentNode.children.get(name);
|
||||
if (childInode === undefined) {
|
||||
throw {
|
||||
type: "NodeNotFound",
|
||||
message: `${name} not found`,
|
||||
timestamp: Date.now(),
|
||||
pointer: NodePointer.of(currentDeviceId, currentNode.inode),
|
||||
} satisfies NodeNotFoundError;
|
||||
}
|
||||
|
||||
let childPtr = NodePointer.of(currentDeviceId, childInode);
|
||||
|
||||
if (fs.isMountPoint(childPtr)) {
|
||||
const mount = fs.getMountTarget(childPtr)!;
|
||||
childPtr = mount;
|
||||
currentDeviceId = mount.device;
|
||||
}
|
||||
|
||||
let child = fs.getNode(childPtr);
|
||||
if (!child) {
|
||||
throw {
|
||||
type: "NodeNotFound",
|
||||
message: `Node under ${childPtr} not found (probable dangling orphan)`,
|
||||
timestamp: Date.now(),
|
||||
pointer: childPtr,
|
||||
} satisfies NodeNotFoundError;
|
||||
}
|
||||
|
||||
if (child.type === NodeType.Symlink) {
|
||||
if (++linkDepth > maxDepth) throw new Error("Symlink max depth - aborting!");
|
||||
const target = child.target;
|
||||
if (target.startsWith("/")) {
|
||||
currentDeviceId = 0;
|
||||
currentNode = fs.getRoot();
|
||||
} else {
|
||||
const entries = fs.getNodeEntries(childPtr);
|
||||
if (!entries?.[0]) {
|
||||
throw {
|
||||
type: "FileSystemCorruption",
|
||||
message: "Reverse index entry missing, FileSystem corrupted",
|
||||
timestamp: Date.now(),
|
||||
} satisfies FileSystemCorruptionError;
|
||||
}
|
||||
currentDeviceId = entries[0].pdevice_id;
|
||||
currentNode = fs.getNode(NodePointer.of(entries[0].pdevice_id, entries[0].pinode))!;
|
||||
}
|
||||
|
||||
pathComponents.unshift(...target.split("/").filter(c => c.length > 0));
|
||||
continue;
|
||||
}
|
||||
|
||||
currentNode = child;
|
||||
}
|
||||
|
||||
return NodePointer.of(currentDeviceId, currentNode.inode);
|
||||
}
|
||||
}
|
||||
|
||||
export const Termos = {
|
||||
getShell,
|
||||
};
|
||||
+1
-2
@@ -1,2 +1 @@
|
||||
const message: string = "Hello, World!";
|
||||
console.log(message);
|
||||
export { Termos } from "./entry";
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
type Listener = (payload: unknown) => void;
|
||||
|
||||
export class EventEmitter<TEvents> {
|
||||
private Handlers: Map<keyof TEvents, Set<Listener>> = new Map();
|
||||
|
||||
public on<K extends keyof TEvents>(type: K, handler: (payload: TEvents[K]) => void): () => void {
|
||||
const listeners = this.Handlers.get(type);
|
||||
|
||||
if (listeners) {
|
||||
listeners.add(handler as Listener);
|
||||
} else {
|
||||
const set: Set<Listener> = new Set();
|
||||
set.add(handler as Listener);
|
||||
this.Handlers.set(type, set);
|
||||
}
|
||||
|
||||
return (): void => this.off(type, handler);
|
||||
}
|
||||
|
||||
public off<K extends keyof TEvents>(type: K, handler: (payload: TEvents[K]) => void): void {
|
||||
this.Handlers.get(type)?.delete(handler as Listener);
|
||||
}
|
||||
|
||||
public once<K extends keyof TEvents>(type: K, handler: (payload: TEvents[K]) => void): () => void {
|
||||
const listeners = this.Handlers.get(type);
|
||||
|
||||
const wrapper = (payload: TEvents[K]) => {
|
||||
handler(payload);
|
||||
this.off(type, wrapper);
|
||||
};
|
||||
|
||||
if (listeners) {
|
||||
listeners.add(wrapper as Listener);
|
||||
} else {
|
||||
const set: Set<Listener> = new Set();
|
||||
set.add(wrapper as Listener);
|
||||
this.Handlers.set(type, set);
|
||||
}
|
||||
|
||||
return (): void => this.off(type, wrapper);
|
||||
}
|
||||
|
||||
public emit<K extends keyof TEvents>(type: K, payload: TEvents[K]): void {
|
||||
const listeners = this.Handlers.get(type);
|
||||
|
||||
if (listeners) {
|
||||
for (const listener of [...listeners]) {
|
||||
listener(payload);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,177 @@
|
||||
import type { CommandDescriptor } from "@core/command";
|
||||
import type { CommandIO } from "@core/command_io";
|
||||
import { createErrorResult, createSuccessResult, type ResultError, type ResultSuccess } from "@core/result";
|
||||
import type { ShellState } from "@core/shell_state";
|
||||
import { SIGNAL_MAP, type Signal } from "@core/signal";
|
||||
import type { ShellError, SignalTerminationError } from "@core/util/errors";
|
||||
import { createImmutableBuffer } from "@core/util/immutable_buffer";
|
||||
import { concatUint8Arrays, splitUint8Array } from "@termos/util/concat";
|
||||
import { EventEmitter } from "./event_emitter";
|
||||
import type { ShellEventMap } from "./shell";
|
||||
|
||||
export class Process {
|
||||
private _SignalQueue: Signal[] = [];
|
||||
private _SignalHandler: ((signal: Signal) => void) | null = null;
|
||||
private _StdoutChunks: Uint8Array[] = [];
|
||||
private _StderrChunks: Uint8Array[] = [];
|
||||
private _Settled: boolean = false;
|
||||
private _EventEmitter: EventEmitter<ShellEventMap>;
|
||||
private readonly _MaxChunkByteSize: number;
|
||||
|
||||
readonly PID: number;
|
||||
readonly Name: string;
|
||||
readonly CommandDescriptor: CommandDescriptor;
|
||||
readonly State: ShellState;
|
||||
readonly Args: string[];
|
||||
|
||||
constructor(pid: number, state: ShellState, descriptor: CommandDescriptor, args: string[]) {
|
||||
this.PID = pid;
|
||||
this.State = state;
|
||||
this.Name = descriptor.name;
|
||||
this.CommandDescriptor = descriptor;
|
||||
this.Args = args;
|
||||
// Check if positive later and throw an error if so
|
||||
this._MaxChunkByteSize = 1024;
|
||||
this._EventEmitter = new EventEmitter<ShellEventMap>();
|
||||
}
|
||||
|
||||
// WARNING, CHUNKING OUTPUT BREAKS FORMATING
|
||||
private writeToOutput(chunks: Uint8Array[], eventType: "stdout" | "stderr", data: Uint8Array): void {
|
||||
if (this._Settled) return;
|
||||
|
||||
if (data.length <= this._MaxChunkByteSize) {
|
||||
chunks.push(data);
|
||||
this._EventEmitter.emit(eventType, { pid: this.PID, data });
|
||||
return;
|
||||
} else {
|
||||
const arr = splitUint8Array(data, this._MaxChunkByteSize);
|
||||
for (const ent of arr) {
|
||||
chunks.push(ent);
|
||||
this._EventEmitter.emit(eventType, { pid: this.PID, data: ent });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public execute(): void {
|
||||
const io: CommandIO = {
|
||||
writeStdout: (data: Uint8Array) => this.writeToOutput(this._StdoutChunks, "stdout", data),
|
||||
writeStderr: (data: Uint8Array) => this.writeToOutput(this._StderrChunks, "stderr", data),
|
||||
getSignal: () => {
|
||||
const signal: Signal | undefined = this._SignalQueue.shift();
|
||||
if (signal !== undefined) return Promise.resolve(signal);
|
||||
|
||||
const promise = new Promise<Signal>(resolve => {
|
||||
this._SignalHandler = resolve;
|
||||
});
|
||||
return promise;
|
||||
},
|
||||
};
|
||||
|
||||
const promise = this.CommandDescriptor.fn(io, this.State, this.Args);
|
||||
|
||||
promise
|
||||
.then(output => {
|
||||
if (this._Settled) return;
|
||||
|
||||
let result: ResultSuccess | ResultError<ShellError>;
|
||||
const stdout: Uint8Array = concatUint8Arrays(this._StdoutChunks);
|
||||
const stderr: Uint8Array = concatUint8Arrays(this._StderrChunks);
|
||||
|
||||
if (output.result.type === "success") {
|
||||
result = createSuccessResult(
|
||||
this.CommandDescriptor.name,
|
||||
0,
|
||||
createImmutableBuffer(stdout),
|
||||
createImmutableBuffer(stderr),
|
||||
);
|
||||
} else {
|
||||
result = {
|
||||
...output.result,
|
||||
stdout: createImmutableBuffer(stdout),
|
||||
stderr: createImmutableBuffer(stderr),
|
||||
};
|
||||
}
|
||||
|
||||
this._EventEmitter.emit("result", { pid: this.PID, result, state: output.state });
|
||||
this._Settled = true;
|
||||
})
|
||||
.catch(error => {
|
||||
if (this._Settled) return;
|
||||
|
||||
const result: ResultError<ShellError> = createErrorResult(
|
||||
"GenericError",
|
||||
"Promised output from command function rejected",
|
||||
{},
|
||||
this.CommandDescriptor.name,
|
||||
undefined,
|
||||
undefined,
|
||||
{
|
||||
name: "Caught error",
|
||||
message: String(error),
|
||||
},
|
||||
);
|
||||
|
||||
this._EventEmitter.emit("result", { pid: this.PID, result, state: this.State });
|
||||
});
|
||||
}
|
||||
|
||||
public sendSignal(signal: Signal): void {
|
||||
if (this._Settled) return;
|
||||
|
||||
const result: ResultError<SignalTerminationError> = createErrorResult(
|
||||
"SignalTermination",
|
||||
`Process ${this.Name}(${this.PID}) killed by a ${SIGNAL_MAP[signal.type]}(${signal.type})`,
|
||||
{ signalNumber: signal.type, signalName: SIGNAL_MAP[signal.type] },
|
||||
this.CommandDescriptor.name,
|
||||
);
|
||||
|
||||
switch (signal.type) {
|
||||
case SIGNAL_MAP.SIGKILL:
|
||||
this._SignalHandler = null;
|
||||
this._Settled = true;
|
||||
|
||||
this._EventEmitter.emit("result", { pid: this.PID, result: result, state: this.State });
|
||||
return;
|
||||
|
||||
case SIGNAL_MAP.SIGTERM:
|
||||
if (this._SignalHandler !== null) {
|
||||
this._SignalHandler(signal);
|
||||
this._SignalHandler = null;
|
||||
}
|
||||
|
||||
this._Settled = true;
|
||||
this._EventEmitter.emit("result", { pid: this.PID, result: result, state: this.State });
|
||||
|
||||
return;
|
||||
case SIGNAL_MAP.SIGINT:
|
||||
if (this._SignalHandler !== null) {
|
||||
this._SignalHandler(signal);
|
||||
this._SignalHandler = null;
|
||||
}
|
||||
|
||||
this._Settled = true;
|
||||
|
||||
this._EventEmitter.emit("result", { pid: this.PID, result: result, state: this.State });
|
||||
return;
|
||||
default:
|
||||
if (this._SignalHandler !== null) {
|
||||
this._SignalHandler(signal);
|
||||
this._SignalHandler = null;
|
||||
} else {
|
||||
this._SignalQueue.push(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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
import type { CommandDescriptor } from "@core/command";
|
||||
import type { ShellState } from "@core/shell_state";
|
||||
import { SIGNAL_MAP, type Signal } from "@core/signal";
|
||||
import { EventEmitter } from "./event_emitter";
|
||||
import { Process } from "./process";
|
||||
import type { ShellEventMap } from "./shell";
|
||||
|
||||
export class ProcessManager {
|
||||
private _Processes: Map<number, Process> = new Map();
|
||||
private _PIDIndex: number = 0;
|
||||
|
||||
private _EventEmitter: EventEmitter<ShellEventMap> = new EventEmitter();
|
||||
|
||||
public createProcess(state: ShellState, descriptor: CommandDescriptor, args: string[]): number {
|
||||
const pid = ++this._PIDIndex;
|
||||
const process = new Process(pid, state, descriptor, args);
|
||||
this._Processes.set(pid, process);
|
||||
|
||||
process.on("stdout", payload => this._EventEmitter.emit("stdout", payload));
|
||||
process.on("stderr", payload => this._EventEmitter.emit("stderr", payload));
|
||||
process.on("result", payload => {
|
||||
this._Processes.delete(payload.pid);
|
||||
this._EventEmitter.emit("result", payload);
|
||||
});
|
||||
|
||||
this._EventEmitter.emit("process", { pid, name: descriptor.name });
|
||||
process.execute();
|
||||
|
||||
return pid;
|
||||
}
|
||||
|
||||
public sendSignal(pid: number, signal: Signal): void {
|
||||
const process = this._Processes.get(pid);
|
||||
|
||||
if (!process) {
|
||||
//Implement a proper error object later to return to shell
|
||||
console.error("PID not found");
|
||||
return;
|
||||
}
|
||||
|
||||
process.sendSignal(signal);
|
||||
}
|
||||
|
||||
public kill(pid: number): void {
|
||||
const process = this._Processes.get(pid);
|
||||
|
||||
if (!process) {
|
||||
//Implement a proper error object later to return to shell
|
||||
console.error("PID not found");
|
||||
return;
|
||||
}
|
||||
|
||||
//Make global signals an enum later
|
||||
process.sendSignal({ type: SIGNAL_MAP.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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
import type { IDataStore, IMetaStore, VDiskConfig } from "@core/filesystem/vdisk";
|
||||
import { MemDataStore, MemMetaStore } from "@core/util/temp_mem_stores";
|
||||
import { Blob } from "node:buffer";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { NodeType, type DirectoryNode, type FileNode, type Node, type SymlinkNode } from "../core/filesystem/node";
|
||||
|
||||
/* export function serializeFileSystem(map: ReadonlyMap<number, TreeNode | null>): string {
|
||||
|
||||
} */
|
||||
|
||||
export function deserializeFileSystem(json: string): { dstore: IDataStore; mstore: IMetaStore; config: VDiskConfig }[] {
|
||||
const raw = JSON.parse(json);
|
||||
|
||||
// prettier-ignore
|
||||
function parseNode(tree: any, parent: number, store: MemDataStore, map: Map<number, Node>): void { // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
if(tree === null || tree.type === undefined) {
|
||||
const time = Date.now();
|
||||
const defaultNode: DirectoryNode = {
|
||||
type: NodeType.Directory,
|
||||
inode: 0,
|
||||
link_count: 2,
|
||||
mode: 0o0555,
|
||||
owner: 0,
|
||||
group: 0,
|
||||
mtime: time,
|
||||
ctime: time,
|
||||
atime: time,
|
||||
children: new Map(),
|
||||
};
|
||||
map.set(0, Object.freeze(defaultNode));
|
||||
return;
|
||||
}
|
||||
|
||||
switch(tree.type) {
|
||||
case "directory": {
|
||||
const children: Map<string, number> = new Map();
|
||||
|
||||
for (const child of tree.children) {
|
||||
parseNode(child, tree.inode, store, map);
|
||||
children.set(child.name, child.inode);
|
||||
}
|
||||
|
||||
const directoryNode: DirectoryNode = {
|
||||
type: NodeType.Directory,
|
||||
inode: tree.inode,
|
||||
link_count: tree.link_count,
|
||||
mode: tree.mode,
|
||||
owner: tree.owner,
|
||||
group: tree.group,
|
||||
mtime: tree.mtime,
|
||||
ctime: tree.ctime,
|
||||
atime: tree.atime,
|
||||
children,
|
||||
};
|
||||
|
||||
|
||||
if(Object.values(directoryNode).some(e => e === undefined))
|
||||
throw new Error(`Serialization failed, object contains undefined fields - ${directoryNode}`);
|
||||
|
||||
children.set('..', parent);
|
||||
children.set('.', tree.inode);
|
||||
map.set(tree.inode, Object.freeze(directoryNode));
|
||||
break;
|
||||
}
|
||||
case "regular": {
|
||||
const uuid = randomUUID();
|
||||
const fileNode: FileNode = {
|
||||
type: NodeType.File,
|
||||
inode: tree.inode,
|
||||
mode: tree.mode,
|
||||
link_count: tree.link_count,
|
||||
owner: tree.owner,
|
||||
group: tree.group,
|
||||
mtime: tree.mtime,
|
||||
ctime: tree.ctime,
|
||||
atime: tree.atime,
|
||||
content: uuid,
|
||||
size: tree.size,
|
||||
};
|
||||
|
||||
if(Object.values(fileNode).some(e => e === undefined))
|
||||
throw new Error(`Serialization failed, object contains undefined fields - ${fileNode}`);
|
||||
|
||||
const buff: Uint8Array<ArrayBuffer> = Uint8Array.from(tree.content);
|
||||
store.put(uuid, new Blob([buff]));
|
||||
map.set(tree.inode, Object.freeze(fileNode));
|
||||
break;
|
||||
}
|
||||
case "symlink": {
|
||||
const symlinkNode: SymlinkNode = {
|
||||
type: NodeType.Symlink,
|
||||
inode: tree.inode,
|
||||
mode: tree.mode,
|
||||
link_count: tree.link_count,
|
||||
owner: tree.owner,
|
||||
group: tree.group,
|
||||
mtime: tree.mtime,
|
||||
ctime: tree.ctime,
|
||||
atime: tree.atime,
|
||||
target: tree.target,
|
||||
};
|
||||
|
||||
if(Object.values(symlinkNode).some(e => e === undefined))
|
||||
throw new Error(`Serialization failed, object contains undefined fields - ${symlinkNode}`);
|
||||
|
||||
map.set(tree.inode, Object.freeze(symlinkNode));
|
||||
break;
|
||||
}
|
||||
default:
|
||||
throw new Error(`Unknown node type in JSON ${tree.type}`);
|
||||
}
|
||||
}
|
||||
|
||||
const result: { dstore: IDataStore; mstore: IMetaStore; config: VDiskConfig }[] = [];
|
||||
for (const dev of raw.dev) {
|
||||
const map = new Map();
|
||||
const data = new MemDataStore();
|
||||
const meta = new MemMetaStore();
|
||||
parseNode(dev.tree, dev.tree.inode, data, map);
|
||||
|
||||
const config: VDiskConfig = {
|
||||
id: dev.id,
|
||||
label: `disk-${dev.id}`,
|
||||
index: 0,
|
||||
readonly: false,
|
||||
size: 1024 * 1024 * 1024 * 8, //8 GiB
|
||||
base: map,
|
||||
dataC: {
|
||||
chunkSize: 1024 * 8, //8 KiB
|
||||
cacheSize: 1024 * 1024 * 64, //64 MiB
|
||||
cacheTTL: 1000 * 60, // 1 min
|
||||
},
|
||||
};
|
||||
result.push({ dstore: data, mstore: meta, config });
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
import { COMMAND_REGISTRY } from "@core/command_registry";
|
||||
import { createErrorResult, type Result } from "@core/result";
|
||||
import { getCurrentSession } from "@core/session_manager";
|
||||
import { withExitCode, withHistory, type ShellState } from "@core/shell_state";
|
||||
import { SIGNAL_MAP } from "@core/signal";
|
||||
import type { ShellError } from "@core/util/errors";
|
||||
import { createImmutableBuffer } from "@core/util/immutable_buffer";
|
||||
import { tokenize } from "@core/util/parser";
|
||||
import { EventEmitter } from "./event_emitter";
|
||||
import { ProcessManager } from "./process_manager";
|
||||
|
||||
export class Shell {
|
||||
private _State: Readonly<ShellState>;
|
||||
private _ProcessManager: ProcessManager = new ProcessManager();
|
||||
private _EventEmitter: EventEmitter<ShellEventMap> = new EventEmitter();
|
||||
private _GlobalKeyMap: ReadonlyMap<string, SIGNAL_MAP>;
|
||||
|
||||
public BoundPID: number | null = null;
|
||||
|
||||
constructor(state: ShellState) {
|
||||
this._State = Object.freeze(state);
|
||||
|
||||
//Temporary solution for sigint keybind
|
||||
const map = new Map();
|
||||
map.set("ctrl+c", SIGNAL_MAP.SIGINT);
|
||||
|
||||
this._GlobalKeyMap = 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);
|
||||
});
|
||||
}
|
||||
|
||||
public async execute(input: string): Promise<void> {
|
||||
const parsed = tokenize(input);
|
||||
|
||||
if (!parsed[0]) return;
|
||||
|
||||
this._State = withHistory(this._State, input);
|
||||
const command = COMMAND_REGISTRY.get(parsed[0]);
|
||||
|
||||
if (!command) {
|
||||
const encoded = new TextEncoder().encode(`Command ${parsed[0]} not found`);
|
||||
|
||||
const result = createErrorResult(
|
||||
"CommandNotFound",
|
||||
`Command ${parsed[0]} not found`,
|
||||
{ command: parsed[0] },
|
||||
parsed[0],
|
||||
createImmutableBuffer(encoded),
|
||||
createImmutableBuffer(new Uint8Array()),
|
||||
);
|
||||
|
||||
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) {
|
||||
const result = createErrorResult(
|
||||
"PermissionDenied",
|
||||
`Permission Denied`,
|
||||
{ resource: `Execution of the ${command.name} command` },
|
||||
parsed[0],
|
||||
);
|
||||
|
||||
this._State = withExitCode(this._State, result.error.exitCode);
|
||||
this._EventEmitter.emit("result", { pid: 0, result, state: this._State });
|
||||
return;
|
||||
}
|
||||
|
||||
parsed.shift();
|
||||
|
||||
const pid = this._ProcessManager.createProcess(this._State, command, parsed);
|
||||
this.BoundPID = pid;
|
||||
}
|
||||
|
||||
public sendInput(input: string): void {
|
||||
const signal = this._GlobalKeyMap.get(input);
|
||||
|
||||
if (signal !== undefined) {
|
||||
if (this.BoundPID !== null) {
|
||||
this._ProcessManager.sendSignal(this.BoundPID, { type: signal });
|
||||
}
|
||||
} else {
|
||||
if (this.BoundPID !== null) {
|
||||
this._ProcessManager.sendSignal(this.BoundPID, { type: SIGNAL_MAP.INPUT, payload: input });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public get State(): Readonly<ShellState> {
|
||||
return this._State;
|
||||
}
|
||||
|
||||
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 {
|
||||
process: { pid: number; name: string };
|
||||
stdout: { pid: number; data: Uint8Array };
|
||||
stderr: { pid: number; data: Uint8Array };
|
||||
result: { pid: number; result: Result<ShellError>; state: ShellState };
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
export function concatUint8Arrays(arrays: Uint8Array[]): Uint8Array {
|
||||
const size = arrays.reduce((sum, arr) => sum + arr.length, 0);
|
||||
const array = new Uint8Array(size);
|
||||
|
||||
let offset = 0;
|
||||
for (const arr of arrays) {
|
||||
array.set(arr, offset);
|
||||
offset += arr.length;
|
||||
}
|
||||
|
||||
return array;
|
||||
}
|
||||
|
||||
export function splitUint8Array(data: Uint8Array, size: number): Uint8Array[] {
|
||||
const nChunks: number = Math.ceil(data.length / size);
|
||||
const chunks: Uint8Array[] = [];
|
||||
|
||||
for (let i = 0; i < nChunks; i++) {
|
||||
const start = size * i;
|
||||
const end = size * (i + 1);
|
||||
|
||||
chunks.push(data.subarray(start, end));
|
||||
}
|
||||
|
||||
return chunks;
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
export function convertToUnit(bytes: number, decimalPoint?: number, pow: 1024 | 1000 = 1024): string {
|
||||
if (!+bytes) return "0";
|
||||
|
||||
const k: number = pow;
|
||||
const dp: number = decimalPoint ? (decimalPoint < 0 ? 0 : decimalPoint) : 1;
|
||||
const units: string[] = ["", "K", "M", "G", "T", "P"];
|
||||
|
||||
const i: number = Math.floor(Math.log(bytes) / Math.log(k));
|
||||
|
||||
return `${(bytes / Math.pow(k, i)).toFixed(dp)}${units[i]}`;
|
||||
}
|
||||
@@ -0,0 +1,178 @@
|
||||
export class MD5 {
|
||||
private static encoder: TextEncoder = new TextEncoder();
|
||||
|
||||
// prettier-ignore
|
||||
private static K: number[] = [
|
||||
0xd76aa478, 0xe8c7b756, 0x242070db, 0xc1bdceee,
|
||||
0xf57c0faf, 0x4787c62a, 0xa8304613, 0xfd469501,
|
||||
0x698098d8, 0x8b44f7af, 0xffff5bb1, 0x895cd7be,
|
||||
0x6b901122, 0xfd987193, 0xa679438e, 0x49b40821,
|
||||
0xf61e2562, 0xc040b340, 0x265e5a51, 0xe9b6c7aa,
|
||||
0xd62f105d, 0x02441453, 0xd8a1e681, 0xe7d3fbc8,
|
||||
0x21e1cde6, 0xc33707d6, 0xf4d50d87, 0x455a14ed,
|
||||
0xa9e3e905, 0xfcefa3f8, 0x676f02d9, 0x8d2a4c8a,
|
||||
0xfffa3942, 0x8771f681, 0x6d9d6122, 0xfde5380c,
|
||||
0xa4beea44, 0x4bdecfa9, 0xf6bb4b60, 0xbebfbc70,
|
||||
0x289b7ec6, 0xeaa127fa, 0xd4ef3085, 0x04881d05,
|
||||
0xd9d4d039, 0xe6db99e5, 0x1fa27cf8, 0xc4ac5665,
|
||||
0xf4292244, 0x432aff97, 0xab9423a7, 0xfc93a039,
|
||||
0x655b59c3, 0x8f0ccc92, 0xffeff47d, 0x85845dd1,
|
||||
0x6fa87e4f, 0xfe2ce6e0, 0xa3014314, 0x4e0811a1,
|
||||
0xf7537e82, 0xbd3af235, 0x2ad7d2bb, 0xeb86d391
|
||||
];
|
||||
|
||||
// prettier-ignore
|
||||
private static S: number[] = [
|
||||
7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22,
|
||||
5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20,
|
||||
4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23,
|
||||
6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21
|
||||
];
|
||||
|
||||
public static hash(input: string) {
|
||||
const inputArr: Uint8Array<ArrayBuffer> = this.encoder.encode(input);
|
||||
const padded = MD5.pad(inputArr);
|
||||
|
||||
let A = 0x67452301;
|
||||
let B = 0xefcdab89;
|
||||
let C = 0x98badcfe;
|
||||
let D = 0x10325476;
|
||||
|
||||
function processBlock(M: number[]) {
|
||||
function F(b: number, c: number, d: number): number {
|
||||
return (b & c) | (~b & d);
|
||||
}
|
||||
function H(b: number, c: number, d: number): number {
|
||||
return b ^ c ^ d;
|
||||
}
|
||||
function I(b: number, c: number, d: number): number {
|
||||
return c ^ (b | ~d);
|
||||
}
|
||||
function G(b: number, c: number, d: number): number {
|
||||
return (b & d) | (c & ~d);
|
||||
}
|
||||
|
||||
const AA = A,
|
||||
BB = B,
|
||||
CC = C,
|
||||
DD = D;
|
||||
|
||||
for (let i = 0; i < 64; i++) {
|
||||
let f: number, g: number;
|
||||
|
||||
if (i < 16) {
|
||||
f = F(B, C, D);
|
||||
g = i;
|
||||
} else if (i < 32) {
|
||||
f = G(B, C, D);
|
||||
g = (5 * i + 1) % 16;
|
||||
} else if (i < 48) {
|
||||
f = H(B, C, D);
|
||||
g = (3 * i + 5) % 16;
|
||||
} else {
|
||||
f = I(B, C, D);
|
||||
g = (7 * i) % 16;
|
||||
}
|
||||
|
||||
const sum = MD5.add32(A, MD5.add32(f, MD5.add32(M[g]!, MD5.K[i]!)));
|
||||
const temp = MD5.add32(B, MD5.leftRotate(sum, MD5.S[i]!));
|
||||
|
||||
A = D;
|
||||
D = C;
|
||||
C = B;
|
||||
B = temp;
|
||||
}
|
||||
|
||||
A = MD5.add32(A, AA);
|
||||
B = MD5.add32(B, BB);
|
||||
C = MD5.add32(C, CC);
|
||||
D = MD5.add32(D, DD);
|
||||
}
|
||||
|
||||
for (let i = 0; i < padded.length; i += 64) {
|
||||
const M = MD5.sliceToWords(padded.slice(i, i + 64));
|
||||
processBlock(M); // modifies A, B, C, D directly
|
||||
}
|
||||
|
||||
const hashBytes = new Uint8Array([
|
||||
...MD5.wordToBytesLE(A),
|
||||
...MD5.wordToBytesLE(B),
|
||||
...MD5.wordToBytesLE(C),
|
||||
...MD5.wordToBytesLE(D),
|
||||
]);
|
||||
|
||||
return MD5.toHexString(hashBytes);
|
||||
}
|
||||
|
||||
private static pad(input: Uint8Array): Uint8Array {
|
||||
const inputBitLength: number = input.length * 8;
|
||||
|
||||
const out: Uint8Array = new Uint8Array([...input, 0x80]);
|
||||
const NBytes: number = (56 - (out.length % 64) + 64) % 64;
|
||||
|
||||
const zeroArray = new Uint8Array(NBytes);
|
||||
|
||||
const low = inputBitLength >>> 0;
|
||||
const high = (inputBitLength / 0x100000000) >>> 0;
|
||||
|
||||
const lengthBytes = new Uint8Array([
|
||||
low & 0xff,
|
||||
(low >> 8) & 0xff,
|
||||
(low >> 16) & 0xff,
|
||||
(low >> 24) & 0xff,
|
||||
high & 0xff,
|
||||
(high >> 8) & 0xff,
|
||||
(high >> 16) & 0xff,
|
||||
(high >> 24) & 0xff,
|
||||
]);
|
||||
|
||||
return new Uint8Array([...out, ...zeroArray, ...lengthBytes]);
|
||||
}
|
||||
|
||||
/* private static sliceToBlocks(input: Uint8Array): number[][] {
|
||||
const blocks: number[][] = [];
|
||||
|
||||
for (let i = 0; i < input.length; i += 64) {
|
||||
const block = input.slice(i, i + 64);
|
||||
blocks.push(MD5.sliceToWords(block));
|
||||
}
|
||||
|
||||
return blocks;
|
||||
} */
|
||||
|
||||
private static sliceToWords(block: Uint8Array): number[] {
|
||||
const words: number[] = new Array<number>(16);
|
||||
|
||||
for (let i = 0; i < 16; i++) {
|
||||
const offset: number = i * 4;
|
||||
|
||||
words[i] =
|
||||
(block[offset]! |
|
||||
(block[offset + 1]! << 8) |
|
||||
(block[offset + 2]! << 16) |
|
||||
(block[offset + 3]! << 24)) >>>
|
||||
0;
|
||||
}
|
||||
|
||||
return words;
|
||||
}
|
||||
|
||||
private static leftRotate(x: number, n: number): number {
|
||||
x = x >>> 0;
|
||||
return ((x << n) | (x >>> (32 - n))) >>> 0;
|
||||
}
|
||||
|
||||
private static add32(a: number, b: number): number {
|
||||
return ((a >>> 0) + (b >>> 0)) >>> 0;
|
||||
}
|
||||
|
||||
private static wordToBytesLE(word: number): Uint8Array {
|
||||
return new Uint8Array([word & 0xff, (word >>> 8) & 0xff, (word >>> 16) & 0xff, (word >>> 24) & 0xff]);
|
||||
}
|
||||
|
||||
private static toHexString(bytes: Uint8Array): string {
|
||||
return Array.from(bytes)
|
||||
.map(b => b.toString(16).padStart(2, "0"))
|
||||
.join("");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
export class Posix {
|
||||
private static readonly CharTable = {
|
||||
// Space and punctuation (32-47)
|
||||
" ": 32,
|
||||
"!": 33,
|
||||
'"': 34,
|
||||
"#": 35,
|
||||
$: 36,
|
||||
"%": 37,
|
||||
"&": 38,
|
||||
"'": 39,
|
||||
"(": 40,
|
||||
")": 41,
|
||||
"*": 42,
|
||||
"+": 43,
|
||||
",": 44,
|
||||
"-": 45,
|
||||
".": 46,
|
||||
"/": 47,
|
||||
|
||||
// Numbers 0-9 (48-57)
|
||||
"0": 48,
|
||||
"1": 49,
|
||||
"2": 50,
|
||||
"3": 51,
|
||||
"4": 52,
|
||||
"5": 53,
|
||||
"6": 54,
|
||||
"7": 55,
|
||||
"8": 56,
|
||||
"9": 57,
|
||||
|
||||
// More punctuation (58-64)
|
||||
":": 58,
|
||||
";": 59,
|
||||
"<": 60,
|
||||
"=": 61,
|
||||
">": 62,
|
||||
"?": 63,
|
||||
"@": 64,
|
||||
|
||||
// LETTERS - INTERLEAVED AaBbCc... (65-116)
|
||||
A: 65,
|
||||
a: 66,
|
||||
B: 67,
|
||||
b: 68,
|
||||
C: 69,
|
||||
c: 70,
|
||||
D: 71,
|
||||
d: 72,
|
||||
E: 73,
|
||||
e: 74,
|
||||
F: 75,
|
||||
f: 76,
|
||||
G: 77,
|
||||
g: 78,
|
||||
H: 79,
|
||||
h: 80,
|
||||
I: 81,
|
||||
i: 82,
|
||||
J: 83,
|
||||
j: 84,
|
||||
K: 85,
|
||||
k: 86,
|
||||
L: 87,
|
||||
l: 88,
|
||||
M: 89,
|
||||
m: 90,
|
||||
N: 91,
|
||||
n: 92,
|
||||
O: 93,
|
||||
o: 94,
|
||||
P: 95,
|
||||
p: 96,
|
||||
Q: 97,
|
||||
q: 98,
|
||||
R: 99,
|
||||
r: 100,
|
||||
S: 101,
|
||||
s: 102,
|
||||
T: 103,
|
||||
t: 104,
|
||||
U: 105,
|
||||
u: 106,
|
||||
V: 107,
|
||||
v: 108,
|
||||
W: 109,
|
||||
w: 110,
|
||||
X: 111,
|
||||
x: 112,
|
||||
Y: 113,
|
||||
y: 114,
|
||||
Z: 115,
|
||||
z: 116,
|
||||
|
||||
// Specials after letters (now 117-126)
|
||||
"[": 117,
|
||||
"\\": 118,
|
||||
"]": 119,
|
||||
"^": 120,
|
||||
_: 121,
|
||||
"`": 122,
|
||||
"{": 123,
|
||||
"|": 124,
|
||||
"}": 125,
|
||||
"~": 126,
|
||||
} as const;
|
||||
|
||||
public static GetCharWeight(char: string): number {
|
||||
return this.CharTable[char as keyof typeof this.CharTable];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
/*
|
||||
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 function fetchFileSystem(ep: string = `/api/v1/filesystem`): Promise<string> {
|
||||
// FUCK IT NO CACHE FOR NOW, IDB IS RETARDED
|
||||
const cacheETag = "suck my dick";
|
||||
const cacheData = "no data here";
|
||||
|
||||
const headers: HeadersInit = {};
|
||||
if (cacheETag) {
|
||||
headers["If-None-Match"] = cacheETag;
|
||||
}
|
||||
|
||||
const response = await fetch(ep, { headers });
|
||||
|
||||
let json: string;
|
||||
if (response.status === 304 && cacheData) {
|
||||
json = cacheData;
|
||||
} else if (response.ok) {
|
||||
json = await response.text();
|
||||
const newETag = response.headers.get("ETag");
|
||||
// cache the json string here
|
||||
|
||||
if (newETag) {
|
||||
// cache the new checksum (etag) here
|
||||
}
|
||||
} else {
|
||||
throw new Error(`Failed to load filesystem: ${response.status}`);
|
||||
}
|
||||
|
||||
return json;
|
||||
}
|
||||
|
||||
//export async function fetchUserGroups(ep: string = ): Promise<JSON> {}
|
||||
|
||||
//export async function fetchUsers(): Promise<JSON> {}
|
||||
+73
-30
@@ -1,61 +1,104 @@
|
||||
import type { FileSystem } from "@core/filesystem/filesystem";
|
||||
import { TreeNodeType } from "@core/filesystem/treenode";
|
||||
|
||||
export function printTree(fs: FileSystem, root: number): string {
|
||||
const rootNode = fs.getNode(root);
|
||||
if (rootNode === undefined) return "";
|
||||
|
||||
const lines: string[] = [];
|
||||
|
||||
lines.push(rootNode.name);
|
||||
import { NodePointer, NodeType, type SymlinkNode } from "@core/filesystem/node";
|
||||
|
||||
type Frame = {
|
||||
inode: number;
|
||||
ptr: NodePointer;
|
||||
name: string;
|
||||
prefix: string;
|
||||
isLast: boolean;
|
||||
};
|
||||
|
||||
const stack: Frame[] = [];
|
||||
function getSortedChildren(fs: FileSystem, ptr: NodePointer): Array<{ name: string; ptr: NodePointer }> {
|
||||
const node = fs.getNode(ptr);
|
||||
if (!node || node.type !== NodeType.Directory) return [];
|
||||
|
||||
const getSorterChildren = (inode: number): number[] => {
|
||||
const node = fs.getNode(inode);
|
||||
if (!node || node.type !== TreeNodeType.Directory) return [];
|
||||
|
||||
const entries = Object.entries(node.children);
|
||||
const entries = Array.from(node.children.entries());
|
||||
entries.sort(([a], [b]) => a.localeCompare(b));
|
||||
return entries.map(([, childInode]) => childInode) as number[];
|
||||
};
|
||||
|
||||
const rootChildren = getSorterChildren(root);
|
||||
return entries.map(([name, inode]) => ({
|
||||
name,
|
||||
ptr: NodePointer.of(ptr.device, inode),
|
||||
}));
|
||||
}
|
||||
|
||||
function mountSuffix(fs: FileSystem, ptr: NodePointer): string {
|
||||
if (!fs.isMountPoint(ptr)) return "";
|
||||
const target = fs.getMountPoint(ptr);
|
||||
if (!target) return " -> [mount: target missing]";
|
||||
return ` -> ${target.toString()}`;
|
||||
}
|
||||
|
||||
function symlinkSuffix(node: { type: NodeType; target?: string }): string {
|
||||
return node.type === NodeType.Symlink ? ` -> ${(node as SymlinkNode).target}` : "";
|
||||
}
|
||||
|
||||
export function printTree(fs: FileSystem, root: NodePointer, rootLabel = "/"): string {
|
||||
const rootNode = fs.getNode(root);
|
||||
if (rootNode === undefined) return "";
|
||||
|
||||
const lines: string[] = [];
|
||||
const rootSuffix = mountSuffix(fs, root) + symlinkSuffix(rootNode);
|
||||
lines.push(`${rootLabel} ${root.toString()}${rootSuffix}`);
|
||||
|
||||
const stack: Frame[] = [];
|
||||
const rootChildren = getSortedChildren(fs, root);
|
||||
for (let i = rootChildren.length - 1; i >= 0; i--) {
|
||||
const childInode: number = rootChildren[i] as number;
|
||||
const child = rootChildren[i]!;
|
||||
if (child.name.startsWith(".")) continue;
|
||||
const isLast = i === rootChildren.length - 1;
|
||||
|
||||
stack.push({ inode: childInode, prefix: "", isLast });
|
||||
stack.push({ ptr: child.ptr, name: child.name, prefix: "", isLast });
|
||||
}
|
||||
|
||||
while (stack.length > 0) {
|
||||
const frame = stack.pop()!;
|
||||
const node = fs.getNode(frame.inode);
|
||||
const node = fs.getNode(frame.ptr);
|
||||
if (!node) continue;
|
||||
|
||||
const name = node.name;
|
||||
const connector = frame.isLast ? "└── " : "├── ";
|
||||
lines.push(frame.prefix + connector + name);
|
||||
const suffix = mountSuffix(fs, frame.ptr) + symlinkSuffix(node);
|
||||
lines.push(`${frame.prefix}${connector}${frame.name} ${frame.ptr.toString()}${suffix}`);
|
||||
|
||||
if (node.type === TreeNodeType.Directory) {
|
||||
if (node.type === NodeType.Directory && !fs.isMountPoint(frame.ptr)) {
|
||||
const childPrefix = frame.prefix + (frame.isLast ? " " : "│ ");
|
||||
const children = getSorterChildren(frame.inode);
|
||||
const children = getSortedChildren(fs, frame.ptr);
|
||||
|
||||
for (let i = children.length - 1; i >= 0; i--) {
|
||||
const childInode = children[i] as number;
|
||||
const child = children[i]!;
|
||||
if (child.name.startsWith(".")) continue;
|
||||
const childIsLast = i === children.length - 1;
|
||||
|
||||
stack.push({ inode: childInode, prefix: childPrefix, isLast: childIsLast });
|
||||
stack.push({
|
||||
ptr: child.ptr,
|
||||
name: child.name,
|
||||
prefix: childPrefix,
|
||||
isLast: childIsLast,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return lines.join("\n");
|
||||
}
|
||||
|
||||
export function printDeviceTree(fs: FileSystem, deviceId: number, rootLabel?: string): string {
|
||||
return printTree(fs, NodePointer.of(deviceId, 0), rootLabel ?? `disk-${deviceId}:/`);
|
||||
}
|
||||
|
||||
export function printAllDeviceTrees(fs: FileSystem, deviceIds?: number[]): string {
|
||||
const ids =
|
||||
deviceIds ??
|
||||
(() => {
|
||||
const mgr = (fs as unknown as { _VDiskManager?: { listID(): number[] } })._VDiskManager;
|
||||
if (!mgr) {
|
||||
throw new Error(
|
||||
"printAllDeviceTrees: FileSystem has no public device list — pass deviceIds explicitly",
|
||||
);
|
||||
}
|
||||
return mgr.listID();
|
||||
})();
|
||||
|
||||
return ids
|
||||
.slice()
|
||||
.sort((a, b) => a - b)
|
||||
.map(id => printDeviceTree(fs, id))
|
||||
.join("\n\n");
|
||||
}
|
||||
|
||||
@@ -0,0 +1,92 @@
|
||||
import type { CommandIO } from "@core/command_io";
|
||||
import { descriptor as cd } from "@core/commands/cd";
|
||||
import type { ResultError, ResultSuccess } from "@core/result";
|
||||
import type { UserInfo } from "@core/session_manager";
|
||||
import { getCurrentSession } from "@core/session_manager";
|
||||
import { withCwd, type ShellState } from "@core/shell_state";
|
||||
import type { PathResolutionError } from "@core/util/errors";
|
||||
import { Fixture } from "@tests/helpers/state_fixture";
|
||||
import { expect, test } from "vitest";
|
||||
|
||||
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 user: UserInfo = {
|
||||
username: "root",
|
||||
uid: 0,
|
||||
gid: 0,
|
||||
group: [0],
|
||||
home: 0,
|
||||
};
|
||||
users.set(0, user);
|
||||
|
||||
const state: ShellState = Fixture.State;
|
||||
|
||||
test("changes cwd to home", async () => {
|
||||
let newState = withCwd(state, 2);
|
||||
const output = await cd.fn(io, newState, [], []);
|
||||
newState = output.state;
|
||||
const result = output.result;
|
||||
const session = getCurrentSession(newState);
|
||||
|
||||
expect((result as ResultSuccess).exitCode).toBe(0);
|
||||
expect(session.cwd).toBe(Fixture.user.home);
|
||||
expect(session.pwd).toBe(2);
|
||||
});
|
||||
test("changes cwd to pwd", async () => {
|
||||
let newState = withCwd(state, 2);
|
||||
|
||||
const output = await cd.fn(io, newState, [], ["-"]);
|
||||
newState = output.state;
|
||||
const result = output.result;
|
||||
const session = getCurrentSession(newState);
|
||||
|
||||
expect((result as ResultSuccess).exitCode).toBe(0);
|
||||
expect(session.cwd).toBe(0);
|
||||
expect(session.pwd).toBe(2);
|
||||
});
|
||||
test("changes cwd to 4", async () => {
|
||||
const output = await cd.fn(io, state, [], ["/folder2/subdir2"]);
|
||||
const newState = output.state;
|
||||
const result = output.result;
|
||||
const session = getCurrentSession(newState);
|
||||
|
||||
expect((result as ResultSuccess).exitCode).toBe(0);
|
||||
expect(session.cwd).toBe(4);
|
||||
expect(session.pwd).toBe(0);
|
||||
});
|
||||
|
||||
test("returns an error result (tried to enter a non existent location)", async () => {
|
||||
const output = await cd.fn(io, state, [], ["/not/real"]);
|
||||
const newState = output.state;
|
||||
const result = output.result;
|
||||
const session = getCurrentSession(newState);
|
||||
|
||||
expect((result as ResultError<PathResolutionError>).error.exitCode).toBe(64);
|
||||
expect(session.cwd).toBe(0);
|
||||
expect(session.pwd).toBe(0);
|
||||
});
|
||||
|
||||
test("returns an error result (tried to enter a file)", async () => {
|
||||
const output = await cd.fn(io, state, [], ["/some-file"]);
|
||||
const newState = output.state;
|
||||
const result = output.result;
|
||||
const session = getCurrentSession(newState);
|
||||
|
||||
expect((result as ResultError<PathResolutionError>).error.exitCode).toBe(64);
|
||||
expect(session.cwd).toBe(0);
|
||||
expect(session.pwd).toBe(0);
|
||||
});
|
||||
@@ -1,63 +1,33 @@
|
||||
import type { CommandIO } from "@core/command_io";
|
||||
import { descriptor as echo } from "@core/commands/echo";
|
||||
import { createInitialShellState, type ShellState } from "@core/shell_state";
|
||||
import type { UserInfo } from "@core/user_info";
|
||||
import { buildTestFS, type FixtureNode } from "@tests/helpers/filesystems_fixture";
|
||||
import type { ResultSuccess } from "@core/result";
|
||||
import { type ShellState } from "@core/shell_state";
|
||||
import { Fixture } from "@tests/helpers/state_fixture";
|
||||
import { expect, test } from "vitest";
|
||||
|
||||
const testTree: FixtureNode = {
|
||||
inode: 0,
|
||||
name: "root",
|
||||
type: "Dir",
|
||||
children: [
|
||||
{
|
||||
inode: 1,
|
||||
name: "hello.txt",
|
||||
type: "File",
|
||||
content: "Goodbye World!",
|
||||
children: [],
|
||||
const stdout: Uint8Array[] = [];
|
||||
const stderr: Uint8Array[] = [];
|
||||
|
||||
const io: CommandIO = {
|
||||
writeStdout: (data: Uint8Array) => {
|
||||
stdout.push(data);
|
||||
},
|
||||
{
|
||||
inode: 2,
|
||||
name: "sub",
|
||||
type: "Dir",
|
||||
children: [
|
||||
{
|
||||
inode: 3,
|
||||
name: "world.txt",
|
||||
type: "File",
|
||||
content: "Goodbye!",
|
||||
children: [],
|
||||
writeStderr: (data: Uint8Array) => {
|
||||
stderr.push(data);
|
||||
},
|
||||
{
|
||||
inode: 4,
|
||||
name: "bye",
|
||||
type: "Dir",
|
||||
children: [],
|
||||
getSignal: () => {
|
||||
return new Promise(() => {});
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
const fs = buildTestFS(testTree);
|
||||
const state: ShellState = Fixture.State;
|
||||
|
||||
const users: Map<number, UserInfo> = new Map();
|
||||
const user: UserInfo = {
|
||||
name: "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", () => {
|
||||
const output = echo.fn(state, [], ["hello", "world"]);
|
||||
const string = new TextDecoder().decode(output.result.stdout.toArray());
|
||||
test("returns a Result of type success", async () => {
|
||||
const output = await echo.fn(io, state, [], ["hello", "world"]);
|
||||
const string = new TextDecoder().decode(stdout[0]);
|
||||
|
||||
expect(output.result.type).toBe("success");
|
||||
expect(output.result.exitCode).toBe(0);
|
||||
expect(string).toBe("hello world");
|
||||
expect((output.result as ResultSuccess).exitCode).toBe(0);
|
||||
// Fix: added a newline character
|
||||
expect(string).toEqual("hello world\n");
|
||||
});
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
import type { ResultError } from "@core/result";
|
||||
import { type ShellState } from "@core/shell_state";
|
||||
import { SIGNAL_MAP } from "@core/signal";
|
||||
import type { SignalTerminationError } from "@core/util/errors";
|
||||
import { Shell } from "@shell/shell";
|
||||
import { Fixture } from "@tests/helpers/state_fixture";
|
||||
import { expect, test } from "vitest";
|
||||
|
||||
const state: ShellState = Fixture.State;
|
||||
|
||||
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;
|
||||
|
||||
expect(result.type).toBe("error");
|
||||
expect((result as ResultError<SignalTerminationError>).error.exitCode).toEqual(130);
|
||||
expect((result as ResultError<SignalTerminationError>).error.signalNumber).toEqual(SIGNAL_MAP.SIGINT);
|
||||
});
|
||||
|
||||
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");
|
||||
});
|
||||
+1260
-343
File diff suppressed because it is too large
Load Diff
+673
-42
@@ -1,63 +1,694 @@
|
||||
import { resolvePath } from "@core/path_resolver";
|
||||
// @tests/core/util/path_resolver.test.ts (adjust)
|
||||
import { toPtr, type NodePointer } from "@core/filesystem/node";
|
||||
import { resolvePath } from "@core/util/path_resolver";
|
||||
import { expectNodeNotFoundError, expectNotADirectoryError } from "@tests/helpers/error_matchers";
|
||||
import { buildTestFS } from "@tests/helpers/filesystems_fixture";
|
||||
import { depth7Tree } from "@tests/helpers/tree_fixture";
|
||||
import { describe, expect, test } from "vitest";
|
||||
import { makeFS, makeShellState, makeTree, makeUser } from "@tests/helpers/filesystems_fixture";
|
||||
import fc from "fast-check";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
const fs = buildTestFS(depth7Tree);
|
||||
// ============================================================================
|
||||
// Path normalization
|
||||
// ============================================================================
|
||||
|
||||
describe("resolvePath", () => {
|
||||
test("returns an inode from an absolute path", () => {
|
||||
const path = "/d1/d2/d3/d4/";
|
||||
const result = resolvePath(fs, 1, path);
|
||||
|
||||
expect(result).toBeDefined();
|
||||
expect(fs.getNode(result as number)!.name).toBe("d4");
|
||||
describe("resolvePath — path normalization", () => {
|
||||
/**
|
||||
* `/` is the root of device 0; no traversal is needed.
|
||||
*/
|
||||
it("resolves '/' to the root of device 0", async () => {
|
||||
const fs = await makeFS([makeTree().build()]);
|
||||
expect(resolvePath(makeShellState(fs), "/")).toEqual({ device_id: 0, inode: 0 });
|
||||
});
|
||||
|
||||
test("returns an inode from a relative path", () => {
|
||||
const path = "./d2/d3/d4/";
|
||||
const result = resolvePath(fs, 1, path);
|
||||
|
||||
expect(result).toBeDefined();
|
||||
expect(fs.getNode(result as number)!.name).toBe("d4");
|
||||
/**
|
||||
* Redundant leading slashes are stripped by the normalizer.
|
||||
*/
|
||||
it("resolves '/', '//', and '///' identically", async () => {
|
||||
const fs = await makeFS([makeTree().build()]);
|
||||
const state = makeShellState(fs);
|
||||
for (const p of ["/", "//", "///"]) {
|
||||
expect(resolvePath(state, p)).toEqual({ device_id: 0, inode: 0 });
|
||||
}
|
||||
});
|
||||
|
||||
test("returns an inode from a relative parent path", () => {
|
||||
const path = "../d1/d2/d3/d4/";
|
||||
const result = resolvePath(fs, 1, path);
|
||||
|
||||
expect(result).toBeDefined();
|
||||
expect(fs.getNode(result as number)!.name).toBe("d4");
|
||||
/**
|
||||
* Empty path returns the current working directory without traversal.
|
||||
*/
|
||||
it("resolves an empty string to the current working directory", async () => {
|
||||
const t = makeTree();
|
||||
const work = t.addDir(0, "work");
|
||||
const fs = await makeFS([t.build()]);
|
||||
const state = makeShellState(fs, { cwd: toPtr({ device_id: 0, inode: work }) });
|
||||
expect(resolvePath(state, "")).toEqual({ device_id: 0, inode: work });
|
||||
});
|
||||
|
||||
test("returns inode 0", () => {
|
||||
const path = "/";
|
||||
const result = resolvePath(fs, 1, path);
|
||||
/**
|
||||
* Property: leading, trailing, and interior redundant slashes never change
|
||||
* the resolved pointer.
|
||||
*/
|
||||
it("resolves identically regardless of redundant slashes", async () => {
|
||||
const t = makeTree();
|
||||
const a = t.addDir(0, "a");
|
||||
t.addFile(a, "b");
|
||||
const fs = await makeFS([t.build()]);
|
||||
const state = makeShellState(fs);
|
||||
const expected = resolvePath(state, "/a/b");
|
||||
|
||||
expect(result).toBeDefined();
|
||||
expect(result).toBe(0);
|
||||
expect(fs.getNode(result as number)!.name).toBe("root");
|
||||
fc.assert(
|
||||
fc.property(
|
||||
fc.integer({ min: 0, max: 5 }),
|
||||
fc.integer({ min: 0, max: 5 }),
|
||||
fc.integer({ min: 1, max: 4 }),
|
||||
(lead, trail, mid) => {
|
||||
const path = "/".repeat(lead) + "a" + "/".repeat(mid) + "b" + "/".repeat(trail);
|
||||
expect(resolvePath(state, path)).toEqual(expected);
|
||||
},
|
||||
),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
// ============================================================================
|
||||
// Absolute paths
|
||||
// ============================================================================
|
||||
|
||||
describe("resolvePath — absolute paths", () => {
|
||||
/**
|
||||
* Single-component absolute path resolves to the child's pointer.
|
||||
*/
|
||||
it("resolves '/name' to the child node of root", async () => {
|
||||
const t = makeTree();
|
||||
const foo = t.addFile(0, "foo");
|
||||
const fs = await makeFS([t.build()]);
|
||||
expect(resolvePath(makeShellState(fs), "/foo")).toEqual({ device_id: 0, inode: foo });
|
||||
});
|
||||
|
||||
/**
|
||||
* Nested paths traverse each directory in turn.
|
||||
*/
|
||||
it("resolves a nested path '/a/b' to the final child", async () => {
|
||||
const t = makeTree();
|
||||
const a = t.addDir(0, "a");
|
||||
const b = t.addFile(a, "b");
|
||||
const fs = await makeFS([t.build()]);
|
||||
expect(resolvePath(makeShellState(fs), "/a/b")).toEqual({ device_id: 0, inode: b });
|
||||
});
|
||||
|
||||
/**
|
||||
* Deeper paths traverse more levels.
|
||||
*/
|
||||
it("resolves a deep path '/a/b/c/d' to the final child", async () => {
|
||||
const t = makeTree();
|
||||
const a = t.addDir(0, "a");
|
||||
const b = t.addDir(a, "b");
|
||||
const c = t.addDir(b, "c");
|
||||
const d = t.addFile(c, "d");
|
||||
const fs = await makeFS([t.build()]);
|
||||
expect(resolvePath(makeShellState(fs), "/a/b/c/d")).toEqual({ device_id: 0, inode: d });
|
||||
});
|
||||
|
||||
/**
|
||||
* Trailing slash is stripped and resolves the same as without it.
|
||||
*/
|
||||
it("resolves '/a/b/' to the same pointer as '/a/b'", async () => {
|
||||
const t = makeTree();
|
||||
const a = t.addDir(0, "a");
|
||||
t.addFile(a, "b");
|
||||
const fs = await makeFS([t.build()]);
|
||||
const state = makeShellState(fs);
|
||||
expect(resolvePath(state, "/a/b/")).toEqual(resolvePath(state, "/a/b"));
|
||||
});
|
||||
|
||||
/**
|
||||
* Missing top-level component raises a typed NodeNotFound.
|
||||
*/
|
||||
it("throws NodeNotFound when the first component does not exist", async () => {
|
||||
const fs = await makeFS([makeTree().build()]);
|
||||
await expectNodeNotFoundError(() => resolvePath(makeShellState(fs), "/missing"));
|
||||
});
|
||||
|
||||
/**
|
||||
* Missing intermediate component raises a typed NodeNotFound.
|
||||
*/
|
||||
it("throws NodeNotFound when an intermediate component does not exist", async () => {
|
||||
const t = makeTree();
|
||||
t.addDir(0, "a");
|
||||
const fs = await makeFS([t.build()]);
|
||||
await expectNodeNotFoundError(() => resolvePath(makeShellState(fs), "/a/missing/b"));
|
||||
});
|
||||
|
||||
/**
|
||||
* Descending through a file at a non-final position is rejected with
|
||||
* NotADirectory (this one works — the isFile check fires because `a` is
|
||||
* not the last component).
|
||||
*/
|
||||
it("throws NotADirectory when traversing through a file at a non-final position", async () => {
|
||||
const t = makeTree();
|
||||
t.addFile(0, "a");
|
||||
const fs = await makeFS([t.build()]);
|
||||
await expectNotADirectoryError(() => resolvePath(makeShellState(fs), "/a/b/c"));
|
||||
});
|
||||
|
||||
/**
|
||||
* EXPECTED-TO-FAIL: descending through a file at the final position should
|
||||
* also throw NotADirectory. Current implementation skips the isFile check
|
||||
* on the last iteration and then crashes on `(file as Directory).children`.
|
||||
*/
|
||||
it("should throw NotADirectory when descending through a file at the final position", async () => {
|
||||
const t = makeTree();
|
||||
t.addFile(0, "a");
|
||||
const fs = await makeFS([t.build()]);
|
||||
await expectNotADirectoryError(() => resolvePath(makeShellState(fs), "/a/b"));
|
||||
});
|
||||
});
|
||||
|
||||
// ============================================================================
|
||||
// Relative paths
|
||||
// ============================================================================
|
||||
|
||||
describe("resolvePath — relative paths", () => {
|
||||
/**
|
||||
* A single relative component resolves against cwd.
|
||||
*/
|
||||
it("resolves a relative path from a device-0 cwd", async () => {
|
||||
const t = makeTree();
|
||||
const work = t.addDir(0, "work");
|
||||
const file = t.addFile(work, "file");
|
||||
const fs = await makeFS([t.build()]);
|
||||
const state = makeShellState(fs, { cwd: toPtr({ device_id: 0, inode: work }) });
|
||||
expect(resolvePath(state, "file")).toEqual({ device_id: 0, inode: file });
|
||||
});
|
||||
|
||||
/**
|
||||
* Multi-component relative paths traverse from cwd.
|
||||
*/
|
||||
it("resolves a multi-component relative path from cwd", async () => {
|
||||
const t = makeTree();
|
||||
const work = t.addDir(0, "work");
|
||||
const sub = t.addDir(work, "sub");
|
||||
const leaf = t.addFile(sub, "leaf");
|
||||
const fs = await makeFS([t.build()]);
|
||||
const state = makeShellState(fs, { cwd: toPtr({ device_id: 0, inode: work }) });
|
||||
expect(resolvePath(state, "sub/leaf")).toEqual({ device_id: 0, inode: leaf });
|
||||
});
|
||||
|
||||
/**
|
||||
* Missing relative component raises a typed NodeNotFound.
|
||||
*/
|
||||
it("throws NodeNotFound for a missing relative component", async () => {
|
||||
const fs = await makeFS([makeTree().build()]);
|
||||
await expectNodeNotFoundError(() => resolvePath(makeShellState(fs), "nope"));
|
||||
});
|
||||
});
|
||||
|
||||
test("returns inode 1 (cwd)", () => {
|
||||
const path = "";
|
||||
const result = resolvePath(fs, 1, path);
|
||||
// ============================================================================
|
||||
// ~ expansion
|
||||
// ============================================================================
|
||||
|
||||
expect(result).toBeDefined();
|
||||
expect(result).toBe(1);
|
||||
expect(fs.getNode(result as number)!.name).toBe("d1");
|
||||
describe("resolvePath — '~' expansion", () => {
|
||||
/**
|
||||
* `~` expands to the user's home directory (home on device 0).
|
||||
*/
|
||||
it("expands '~' to the user's home directory", async () => {
|
||||
const t = makeTree();
|
||||
const home = t.addDir(0, "home");
|
||||
const fs = await makeFS([t.build()]);
|
||||
const user = makeUser(toPtr({ device_id: 0, inode: home }));
|
||||
const state = makeShellState(fs, { user });
|
||||
expect(resolvePath(state, "~")).toEqual({ device_id: 0, inode: home });
|
||||
});
|
||||
|
||||
test("throws because of a nonexistent path", () => {
|
||||
expectNodeNotFoundError(() => resolvePath(fs, 1, "/d3"));
|
||||
/**
|
||||
* `~/name` expands home first, then resolves `name` beneath it.
|
||||
*/
|
||||
it("expands '~/name' to a child of home", async () => {
|
||||
const t = makeTree();
|
||||
const home = t.addDir(0, "home");
|
||||
const file = t.addFile(home, "file");
|
||||
const fs = await makeFS([t.build()]);
|
||||
const user = makeUser(toPtr({ device_id: 0, inode: home }));
|
||||
const state = makeShellState(fs, { user });
|
||||
expect(resolvePath(state, "~/file")).toEqual({ device_id: 0, inode: file });
|
||||
});
|
||||
|
||||
test("throws because of file path component", () => {
|
||||
expectNotADirectoryError(() => resolvePath(fs, 6, "./deep_file.txt/d8"));
|
||||
/**
|
||||
* EXPECTED-TO-FAIL: `~` expansion never touches `currentVD`, so a home on
|
||||
* device 1 resolves the first component but then reads subsequent children
|
||||
* from device 0 — usually crashing on a missing inode.
|
||||
*/
|
||||
it("should resolve '~/file' when home lives on device 1", async () => {
|
||||
const t0 = makeTree();
|
||||
const t1 = makeTree();
|
||||
const home = t1.addDir(0, "home");
|
||||
const file = t1.addFile(home, "file");
|
||||
const fs = await makeFS([t0.build(), t1.build()]);
|
||||
const user = makeUser(toPtr({ device_id: 1, inode: home }));
|
||||
const state = makeShellState(fs, { user });
|
||||
expect(resolvePath(state, "~/file")).toEqual({ device_id: 1, inode: file });
|
||||
});
|
||||
});
|
||||
|
||||
// ============================================================================
|
||||
// Symlink resolution
|
||||
// ============================================================================
|
||||
|
||||
describe("resolvePath — symlink resolution", () => {
|
||||
/**
|
||||
* Absolute symlink targets resolve from device 0's root.
|
||||
*/
|
||||
it("follows an absolute symlink target", async () => {
|
||||
const t = makeTree();
|
||||
const real = t.addDir(0, "real");
|
||||
const leaf = t.addFile(real, "leaf");
|
||||
t.addSymlink(0, "link", "/real/leaf");
|
||||
const fs = await makeFS([t.build()]);
|
||||
expect(resolvePath(makeShellState(fs), "/link")).toEqual({ device_id: 0, inode: leaf });
|
||||
});
|
||||
});
|
||||
|
||||
// ============================================================================
|
||||
// Mount points
|
||||
// ============================================================================
|
||||
|
||||
describe("resolvePath — mount points", () => {
|
||||
/**
|
||||
* EXPECTED-TO-FAIL: mount redirect must fire on the child before descent.
|
||||
* `/mnt` alone should return the mounted device's root, not the mountpoint
|
||||
* directory on the parent device.
|
||||
*/
|
||||
it("should resolve '/mnt' to the mounted device's root", async () => {
|
||||
const t0 = makeTree();
|
||||
const mnt = t0.addDir(0, "mnt");
|
||||
const t1 = makeTree();
|
||||
const fs = await makeFS([t0.build(), t1.build()]);
|
||||
fs.mount(toPtr({ device_id: 0, inode: mnt }), toPtr({ device_id: 1, inode: 0 }));
|
||||
expect(resolvePath(makeShellState(fs), "/mnt")).toEqual({ device_id: 1, inode: 0 });
|
||||
});
|
||||
|
||||
/**
|
||||
* EXPECTED-TO-FAIL: `/mnt/file` should descend through the mount and land
|
||||
* on `/file` on device 1 — the trailing component must not be consumed by
|
||||
* the redirect.
|
||||
*/
|
||||
it("should resolve '/mnt/file' to '/file' on the mounted device", async () => {
|
||||
const t0 = makeTree();
|
||||
const mnt = t0.addDir(0, "mnt");
|
||||
const t1 = makeTree();
|
||||
const file = t1.addFile(0, "file");
|
||||
const fs = await makeFS([t0.build(), t1.build()]);
|
||||
fs.mount(toPtr({ device_id: 0, inode: mnt }), toPtr({ device_id: 1, inode: 0 }));
|
||||
expect(resolvePath(makeShellState(fs), "/mnt/file")).toEqual({ device_id: 1, inode: file });
|
||||
});
|
||||
|
||||
/**
|
||||
* EXPECTED-TO-FAIL: deep paths through a mount must traverse the mounted
|
||||
* device for every subsequent component.
|
||||
*/
|
||||
it("should resolve '/mnt/sub/leaf' to '/sub/leaf' on the mounted device", async () => {
|
||||
const t0 = makeTree();
|
||||
const mnt = t0.addDir(0, "mnt");
|
||||
const t1 = makeTree();
|
||||
const sub = t1.addDir(0, "sub");
|
||||
const leaf = t1.addFile(sub, "leaf");
|
||||
const fs = await makeFS([t0.build(), t1.build()]);
|
||||
fs.mount(toPtr({ device_id: 0, inode: mnt }), toPtr({ device_id: 1, inode: 0 }));
|
||||
expect(resolvePath(makeShellState(fs), "/mnt/sub/leaf")).toEqual({ device_id: 1, inode: leaf });
|
||||
});
|
||||
|
||||
/**
|
||||
* A non-mountpoint directory resolves to itself on the parent device —
|
||||
* `/a` is not a mount, so no redirect.
|
||||
*/
|
||||
it("resolves a non-mountpoint directory to itself on the parent device", async () => {
|
||||
const t0 = makeTree();
|
||||
const a = t0.addDir(0, "a"); // /a = device 0:1 (not a mountpoint)
|
||||
const mnt = t0.addDir(0, "mnt"); // /mnt = device 0:2 (the mountpoint)
|
||||
const t1 = makeTree();
|
||||
const fs = await makeFS([t0.build(), t1.build()]);
|
||||
fs.mount(
|
||||
toPtr({ device_id: 0, inode: mnt }), // "0:2" — the mountpoint
|
||||
toPtr({ device_id: 1, inode: 0 }),
|
||||
);
|
||||
|
||||
const state = makeShellState(fs);
|
||||
|
||||
// /a is not a mountpoint → resolves to itself on device 0
|
||||
expect(resolvePath(state, "/a")).toEqual({ device_id: 0, inode: a });
|
||||
|
||||
// /mnt IS a mountpoint → redirects to device 1's root
|
||||
// (this is already covered by the /mnt tests; include for contrast or drop)
|
||||
expect(resolvePath(state, "/mnt")).toEqual({ device_id: 1, inode: 0 });
|
||||
});
|
||||
|
||||
/**
|
||||
* EXPECTED-TO-FAIL: nested mount at `/a/b` should redirect to dev1's sub.
|
||||
*/
|
||||
it("should resolve '/a/b' (nested mount) to the mounted device's sub", async () => {
|
||||
const t0 = makeTree();
|
||||
const a = t0.addDir(0, "a");
|
||||
const b = t0.addDir(a, "b");
|
||||
const t1 = makeTree();
|
||||
const sub = t1.addDir(0, "sub");
|
||||
const fs = await makeFS([t0.build(), t1.build()]);
|
||||
fs.mount(toPtr({ device_id: 0, inode: b }), toPtr({ device_id: 1, inode: sub }));
|
||||
expect(resolvePath(makeShellState(fs), "/a/b")).toEqual({ device_id: 1, inode: sub });
|
||||
});
|
||||
|
||||
/**
|
||||
* EXPECTED-TO-FAIL: continuation of the nested case — `/a/b/leaf` should
|
||||
* land on dev1's leaf through the mounted sub.
|
||||
*/
|
||||
it("should resolve '/a/b/leaf' through a nested mount", async () => {
|
||||
const t0 = makeTree();
|
||||
const a = t0.addDir(0, "a");
|
||||
const b = t0.addDir(a, "b");
|
||||
const t1 = makeTree();
|
||||
const sub = t1.addDir(0, "sub");
|
||||
const leaf = t1.addFile(sub, "leaf");
|
||||
const fs = await makeFS([t0.build(), t1.build()]);
|
||||
fs.mount(toPtr({ device_id: 0, inode: b }), toPtr({ device_id: 1, inode: sub }));
|
||||
expect(resolvePath(makeShellState(fs), "/a/b/leaf")).toEqual({ device_id: 1, inode: leaf });
|
||||
});
|
||||
|
||||
/**
|
||||
* EXPECTED-TO-FAIL: two independent mounts must redirect independently.
|
||||
*/
|
||||
it("should resolve multiple independent mounts", async () => {
|
||||
const t0 = makeTree();
|
||||
const mnt = t0.addDir(0, "mnt");
|
||||
const other = t0.addDir(0, "other");
|
||||
const t1 = makeTree();
|
||||
const file = t1.addFile(0, "file");
|
||||
const sub = t1.addDir(0, "sub");
|
||||
const leaf = t1.addFile(sub, "leaf");
|
||||
const fs = await makeFS([t0.build(), t1.build()]);
|
||||
fs.mount(toPtr({ device_id: 0, inode: mnt }), toPtr({ device_id: 1, inode: 0 }));
|
||||
fs.mount(toPtr({ device_id: 0, inode: other }), toPtr({ device_id: 1, inode: sub }));
|
||||
|
||||
const state = makeShellState(fs);
|
||||
expect(resolvePath(state, "/mnt/file")).toEqual({ device_id: 1, inode: file });
|
||||
expect(resolvePath(state, "/other/leaf")).toEqual({ device_id: 1, inode: leaf });
|
||||
});
|
||||
});
|
||||
|
||||
// ============================================================================
|
||||
// Symlinks across mount points
|
||||
// ============================================================================
|
||||
|
||||
describe("resolvePath — symlinks across mount points", () => {
|
||||
/**
|
||||
* EXPECTED-TO-FAIL: symlink whose target lands on another device must
|
||||
* return the target's device id in the result. Without threading, the loop
|
||||
* terminates with currentNode from dev1 but currentVD still 0.
|
||||
*/
|
||||
it("should thread the target's device into currentVD after a symlink→mount hop", async () => {
|
||||
const t0 = makeTree();
|
||||
t0.addSymlink(0, "link", "/mnt");
|
||||
const mnt = t0.addDir(0, "mnt");
|
||||
const t1 = makeTree();
|
||||
const fs = await makeFS([t0.build(), t1.build()]);
|
||||
fs.mount(toPtr({ device_id: 0, inode: mnt }), toPtr({ device_id: 1, inode: 0 }));
|
||||
|
||||
expect(resolvePath(makeShellState(fs), "/link")).toEqual({ device_id: 1, inode: 0 });
|
||||
});
|
||||
|
||||
/**
|
||||
* EXPECTED-TO-FAIL: full traversal through the symlink and across the
|
||||
* mount. Verifies not only the final pointer is right, but that the loop
|
||||
* can continue descending on the mounted device.
|
||||
*/
|
||||
it("should resolve through a symlink→mount hop and continue on the mounted device", async () => {
|
||||
const t0 = makeTree();
|
||||
t0.addSymlink(0, "link", "/mnt");
|
||||
const mnt = t0.addDir(0, "mnt");
|
||||
const t1 = makeTree();
|
||||
const file = t1.addFile(0, "file");
|
||||
const fs = await makeFS([t0.build(), t1.build()]);
|
||||
fs.mount(toPtr({ device_id: 0, inode: mnt }), toPtr({ device_id: 1, inode: 0 }));
|
||||
|
||||
expect(resolvePath(makeShellState(fs), "/link/file")).toEqual({ device_id: 1, inode: file });
|
||||
});
|
||||
});
|
||||
|
||||
// ============================================================================
|
||||
// Integration
|
||||
// ============================================================================
|
||||
|
||||
describe("resolvePath — integration", () => {
|
||||
/**
|
||||
* Full traversal across multiple levels with a file terminus.
|
||||
*/
|
||||
it("resolves a multi-level path through directories to a file", async () => {
|
||||
const t = makeTree();
|
||||
const varInode = t.addDir(0, "var");
|
||||
const logInode = t.addDir(varInode, "log");
|
||||
const appLog = t.addFile(logInode, "app.log");
|
||||
const fs = await makeFS([t.build()]);
|
||||
expect(resolvePath(makeShellState(fs), "/var/log/app.log")).toEqual({ device_id: 0, inode: appLog });
|
||||
});
|
||||
});
|
||||
|
||||
// ============================================================================
|
||||
// Known bugs — each test asserts *current* behavior and goes red on the fix.
|
||||
// ============================================================================
|
||||
|
||||
describe("resolvePath — known bugs", () => {
|
||||
/**
|
||||
* BUG: symlink depth overflow throws a raw `Error`, not a typed error.
|
||||
* Same setup as above; asserts the thrown object isn't a discriminated
|
||||
* union member (no `type` field).
|
||||
*
|
||||
* Fix: throw a typed `SymlinkLoopError` (or similar) from `errors.ts`.
|
||||
*/
|
||||
it("BUG: symlink depth overflow throws a raw Error, not a typed one", async () => {
|
||||
const t = makeTree();
|
||||
const sNames = Array.from({ length: 41 }, (_, i) => `s${i + 1}`);
|
||||
t.addFile(0, "target");
|
||||
for (let i = 0; i < 40; i++) {
|
||||
t.addSymlink(0, sNames[i]!, `/${sNames[i + 1]}`);
|
||||
}
|
||||
t.addSymlink(0, sNames[40]!, "/target");
|
||||
const fs = await makeFS([t.build()]);
|
||||
|
||||
let thrown: unknown = undefined;
|
||||
try {
|
||||
resolvePath(makeShellState(fs), "/s1");
|
||||
} catch (e) {
|
||||
thrown = e;
|
||||
}
|
||||
|
||||
expect(thrown).toBeInstanceOf(Error);
|
||||
expect(thrown).not.toHaveProperty("type");
|
||||
// ^ BUG: no `type` discriminant. Correct: typed (e.g. SymlinkLoop).
|
||||
});
|
||||
|
||||
/**
|
||||
* BUG: a malformed cwd pointer is not validated; `fromPtr(session.cwd)`
|
||||
* throws a raw `Error("Invalid node pointer format")`, not a typed one.
|
||||
* Same "untyped" class as the symlink-depth bug.
|
||||
*
|
||||
* Fix: wrap `fromPtr` calls in a typed try/catch, or add a validating
|
||||
* parse (e.g. `tryFromPtr`) that returns `undefined` on failure.
|
||||
*/
|
||||
it("BUG: malformed cwd throws a raw Error from fromPtr", async () => {
|
||||
const fs = await makeFS([makeTree().build()]);
|
||||
const state = makeShellState(fs, {
|
||||
cwd: "garbage" as NodePointer,
|
||||
});
|
||||
expect(() => resolvePath(state, "foo")).toThrow(/Invalid node pointer format/);
|
||||
});
|
||||
|
||||
/**
|
||||
* BUG: same as above, for `session.user.home` when expanding `~`.
|
||||
*/
|
||||
it("BUG: malformed home pointer throws a raw Error from fromPtr", async () => {
|
||||
const fs = await makeFS([makeTree().build()]);
|
||||
const user = makeUser("garbage" as NodePointer);
|
||||
const state = makeShellState(fs, { user });
|
||||
expect(() => resolvePath(state, "~")).toThrow(/Invalid node pointer format/);
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolvePath — '..' across mount boundaries", () => {
|
||||
/**
|
||||
* BASIC CASE. Mount `/mnt` (device 0) → device 1's root. From inside the
|
||||
* mount (at `1:0`), `..` must exit through the reverse mount index to
|
||||
* `/mnt`'s parent (`/`) — not stay put via the `inode === 0` shortcut.
|
||||
*
|
||||
* This is the direct fix target: the `..` branch must check
|
||||
* `getMountSource(currentPtr)` *before* the `inode === 0` shortcut.
|
||||
*/
|
||||
it("'..' from a mount root returns to the mountpoint's parent", async () => {
|
||||
const t0 = makeTree();
|
||||
const mnt = t0.addDir(0, "mnt");
|
||||
const fs = await makeFS([t0.build(), makeTree().build()]);
|
||||
await fs.mount(toPtr({ device_id: 0, inode: mnt }), toPtr({ device_id: 1, inode: 0 }));
|
||||
|
||||
const atMountedRoot = makeShellState(fs, { cwd: toPtr({ device_id: 1, inode: 0 }) });
|
||||
expect(resolvePath(atMountedRoot, "..")).toEqual({ device_id: 0, inode: 0 });
|
||||
});
|
||||
|
||||
/**
|
||||
* NON-ROOT MOUNTPOINT. Mount `/home/user/mnt` → device 1's root. `..` from
|
||||
* the mounted root must land on `/home/user` (device 0), *not* `/`.
|
||||
* Catches a fix that hardcodes "go to root on mount exit".
|
||||
*/
|
||||
it("'..' from a non-root mount returns to the mountpoint's immediate parent", async () => {
|
||||
const t0 = makeTree();
|
||||
const home = t0.addDir(0, "home");
|
||||
const user = t0.addDir(home, "user");
|
||||
const mnt = t0.addDir(user, "mnt");
|
||||
const fs = await makeFS([t0.build(), makeTree().build()]);
|
||||
await fs.mount(toPtr({ device_id: 0, inode: mnt }), toPtr({ device_id: 1, inode: 0 }));
|
||||
|
||||
const atMountedRoot = makeShellState(fs, { cwd: toPtr({ device_id: 1, inode: 0 }) });
|
||||
expect(resolvePath(atMountedRoot, "..")).toEqual({ device_id: 0, inode: user });
|
||||
});
|
||||
|
||||
/**
|
||||
* INSIDE-MOUNT `..`. A subdirectory of the mounted device is *not* the
|
||||
* mount root, so `..` from `1:sub` must stay inside device 1 (regular
|
||||
* reverse-index walk), not exit the mount. Catches a fix that exits the
|
||||
* mount on every `..` inside the mounted device instead of only at its
|
||||
* root.
|
||||
*/
|
||||
it("'..' from inside a mount (not at its root) stays inside the mount", async () => {
|
||||
const t0 = makeTree();
|
||||
const mnt = t0.addDir(0, "mnt");
|
||||
const t1 = makeTree();
|
||||
const sub = t1.addDir(0, "sub");
|
||||
const fs = await makeFS([t0.build(), t1.build()]);
|
||||
await fs.mount(toPtr({ device_id: 0, inode: mnt }), toPtr({ device_id: 1, inode: 0 }));
|
||||
|
||||
const atSub = makeShellState(fs, { cwd: toPtr({ device_id: 1, inode: sub }) });
|
||||
expect(resolvePath(atSub, "..")).toEqual({ device_id: 1, inode: 0 });
|
||||
});
|
||||
|
||||
/**
|
||||
* MULTI-STEP `..`. From `/mnt/sub/leaf`, three consecutive `..` should
|
||||
* produce `/mnt/sub` → `/mnt` → `/`. Exercises both the in-mount walk and
|
||||
* the final mount exit in one flow. Catches a fix that only handles the
|
||||
* "already at mount root" case but breaks when coming from deeper.
|
||||
*/
|
||||
it("multi-step '..' walks from deep inside a mount out to the parent device", async () => {
|
||||
const t0 = makeTree();
|
||||
const mnt = t0.addDir(0, "mnt");
|
||||
const t1 = makeTree();
|
||||
const sub = t1.addDir(0, "sub");
|
||||
const leaf = t1.addFile(sub, "leaf");
|
||||
const fs = await makeFS([t0.build(), t1.build()]);
|
||||
await fs.mount(toPtr({ device_id: 0, inode: mnt }), toPtr({ device_id: 1, inode: 0 }));
|
||||
|
||||
// Sanity: full descent lands at `1:leaf`
|
||||
expect(resolvePath(makeShellState(fs), "/mnt/sub/leaf")).toEqual({ device_id: 1, inode: leaf });
|
||||
|
||||
// One `..` up: /mnt/sub
|
||||
const atLeaf = makeShellState(fs, { cwd: toPtr({ device_id: 1, inode: leaf }) });
|
||||
expect(resolvePath(atLeaf, "..")).toEqual({ device_id: 1, inode: sub });
|
||||
|
||||
// Another `..`: /mnt's content = dev1 root
|
||||
const atSub = makeShellState(fs, { cwd: toPtr({ device_id: 1, inode: sub }) });
|
||||
expect(resolvePath(atSub, "..")).toEqual({ device_id: 1, inode: 0 });
|
||||
|
||||
// Final `..`: exit the mount → /
|
||||
const atMountedRoot = makeShellState(fs, { cwd: toPtr({ device_id: 1, inode: 0 }) });
|
||||
expect(resolvePath(atMountedRoot, "..")).toEqual({ device_id: 0, inode: 0 });
|
||||
});
|
||||
|
||||
/**
|
||||
* INDEPENDENT MOUNTS AT DIFFERENT DEPTHS. Mount A at `/a` (dev0 → dev1)
|
||||
* and Mount B at `/b/nested` (dev0 → dev2). `..` from dev1's root must go
|
||||
* to `/` (parent of `/a`), while `..` from dev2's root must go to `/b`
|
||||
* (parent of `/b/nested`).
|
||||
*
|
||||
* Catches a fix that collapses the reverse index to a single entry — e.g.,
|
||||
* if `getMountSource` returns the *first* mount's mountpoint for any
|
||||
* target, or if `mount()` overwrites the wrong entry.
|
||||
*/
|
||||
it("'..' from different mounts returns to each mountpoint's own parent", async () => {
|
||||
const t0 = makeTree();
|
||||
const a = t0.addDir(0, "a");
|
||||
const b = t0.addDir(0, "b");
|
||||
const nested = t0.addDir(b, "nested");
|
||||
|
||||
const fs = await makeFS([t0.build(), makeTree().build(), makeTree().build()]);
|
||||
await fs.mount(toPtr({ device_id: 0, inode: a }), toPtr({ device_id: 1, inode: 0 })); // /a → dev1
|
||||
await fs.mount(toPtr({ device_id: 0, inode: nested }), toPtr({ device_id: 2, inode: 0 })); // /b/nested → dev2
|
||||
|
||||
// `..` from dev1's root → parent of `/a` = `/`
|
||||
const atDev1Root = makeShellState(fs, { cwd: toPtr({ device_id: 1, inode: 0 }) });
|
||||
expect(resolvePath(atDev1Root, "..")).toEqual({ device_id: 0, inode: 0 });
|
||||
|
||||
// `..` from dev2's root → parent of `/b/nested` = `/b`
|
||||
const atDev2Root = makeShellState(fs, { cwd: toPtr({ device_id: 2, inode: 0 }) });
|
||||
expect(resolvePath(atDev2Root, "..")).toEqual({ device_id: 0, inode: b });
|
||||
});
|
||||
|
||||
/**
|
||||
* MOUNT NESTED IN A MOUNTED DEVICE'S TREE. The most realistic cross-device
|
||||
* scenario:
|
||||
*
|
||||
* dev0: /mnt (0:1)
|
||||
* dev1: / (1:0)
|
||||
* /b (1:2) ← mountpoint of B
|
||||
* dev2: / (2:0)
|
||||
*
|
||||
* Mount A: 0:1 → 1:0 (/mnt shows dev1)
|
||||
* Mount B: 1:2 → 2:0 (/mnt/b shows dev2)
|
||||
*
|
||||
* From `/mnt/b` (dev2 root), `..` must exit B's mount to `/mnt/b`'s parent
|
||||
* in the *mounted* device 1 (`1:0`), not skip straight to device 0. A
|
||||
* second `..` then exits A's mount to `/`.
|
||||
*
|
||||
* This is the true "chained mount exit" case. Each `..` handles exactly
|
||||
* one mount; the reverse index for `1:2` (B's mountpoint) lands on `1:0`
|
||||
* (dev1 root), which is itself a mount target of A. The second `..` then
|
||||
* exits A. Both steps go through the same `getMountSource` branch.
|
||||
*/
|
||||
it("'..' walks out of a mount nested inside another mount's device tree", async () => {
|
||||
const t0 = makeTree();
|
||||
const mnt = t0.addDir(0, "mnt");
|
||||
|
||||
const t1 = makeTree();
|
||||
const b = t1.addDir(0, "b");
|
||||
|
||||
const fs = await makeFS([t0.build(), t1.build(), makeTree().build()]);
|
||||
await fs.mount(toPtr({ device_id: 0, inode: mnt }), toPtr({ device_id: 1, inode: 0 })); // /mnt → dev1
|
||||
await fs.mount(toPtr({ device_id: 1, inode: b }), toPtr({ device_id: 2, inode: 0 })); // /mnt/b → dev2
|
||||
|
||||
// Sanity: /mnt/b resolves to dev2 root
|
||||
expect(resolvePath(makeShellState(fs), "/mnt/b")).toEqual({ device_id: 2, inode: 0 });
|
||||
|
||||
// `..` from dev2 root → exit B's mount → parent of `1:b` = `1:0` (dev1 root)
|
||||
const atDev2Root = makeShellState(fs, { cwd: toPtr({ device_id: 2, inode: 0 }) });
|
||||
expect(resolvePath(atDev2Root, "..")).toEqual({ device_id: 1, inode: 0 });
|
||||
|
||||
// `..` from dev1 root → exit A's mount → parent of `0:mnt` = `/`
|
||||
const atDev1Root = makeShellState(fs, { cwd: toPtr({ device_id: 1, inode: 0 }) });
|
||||
expect(resolvePath(atDev1Root, "..")).toEqual({ device_id: 0, inode: 0 });
|
||||
});
|
||||
|
||||
/**
|
||||
* ROUND TRIP. `cd /mnt`, `cd ..`, `cd mnt` should land back at `{1:0}`.
|
||||
* Catches a fix that mutates mount state (e.g., a stale `currentDeviceId`
|
||||
* that leaks across calls) or that resolves `/mnt` differently after a
|
||||
* `..` exit.
|
||||
*/
|
||||
it("entering and exiting a mount via resolvePath round-trips", async () => {
|
||||
const t0 = makeTree();
|
||||
const mnt = t0.addDir(0, "mnt");
|
||||
const fs = await makeFS([t0.build(), makeTree().build()]);
|
||||
await fs.mount(toPtr({ device_id: 0, inode: mnt }), toPtr({ device_id: 1, inode: 0 }));
|
||||
|
||||
// Start at /, enter /mnt
|
||||
const fromRoot = makeShellState(fs);
|
||||
expect(resolvePath(fromRoot, "/mnt")).toEqual({ device_id: 1, inode: 0 });
|
||||
|
||||
// `..` from mounted root → /
|
||||
const atMnt = makeShellState(fs, { cwd: toPtr({ device_id: 1, inode: 0 }) });
|
||||
expect(resolvePath(atMnt, "..")).toEqual({ device_id: 0, inode: 0 });
|
||||
|
||||
test("throws because of a nonexistent cwd inode (technicaly should never happen)", () => {
|
||||
expectNodeNotFoundError(() => resolvePath(fs, 69, "/d3"));
|
||||
// `mnt` again from / → back to mounted root
|
||||
const atRoot = makeShellState(fs, { cwd: toPtr({ device_id: 0, inode: 0 }) });
|
||||
expect(resolvePath(atRoot, "mnt")).toEqual({ device_id: 1, inode: 0 });
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import type { Result, ResultError, ResultSuccess, ShellError } from "@core/result";
|
||||
import type { Result, ResultError, ResultSuccess } from "@core/result";
|
||||
import type { ShellError } from "@core/util/errors";
|
||||
import { createImmutableBuffer, type ImmutableBuffer } from "@core/util/immutable_buffer";
|
||||
import { expect, test } from "vitest";
|
||||
|
||||
@@ -36,13 +37,13 @@ test("error result passed through getstdout should throw error with 'Goodbye, Wo
|
||||
|
||||
const result: ResultError<TestError> = {
|
||||
type: "error",
|
||||
exitCode: 1,
|
||||
stdout: createImmutableBuffer(new Uint8Array()),
|
||||
stderr: createImmutableBuffer(new Uint8Array()),
|
||||
error: {
|
||||
errorType: "TestError",
|
||||
message,
|
||||
timestamp: 0,
|
||||
exitCode: 1,
|
||||
},
|
||||
};
|
||||
expect(() => getStdout(result)).toThrow(message);
|
||||
|
||||
@@ -1,21 +0,0 @@
|
||||
import { createInitialSessionState } from "@core/session";
|
||||
import type { UserInfo } from "@core/user_info";
|
||||
import { expect, test } from "vitest";
|
||||
|
||||
const user: UserInfo = {
|
||||
name: "root",
|
||||
uid: 0,
|
||||
gid: 0,
|
||||
group: [0],
|
||||
home: 0,
|
||||
};
|
||||
|
||||
test("createInitialSessionState - successfully creates a new session state", () => {
|
||||
const state = createInitialSessionState(user);
|
||||
|
||||
expect(state.cwd).toEqual(user.home);
|
||||
expect(state.pwd).toEqual(user.home);
|
||||
expect(state.exitCode).toEqual(0);
|
||||
expect(state.user).toBe(user);
|
||||
expect(Object.isFrozen(state)).toBe(true);
|
||||
});
|
||||
@@ -0,0 +1,57 @@
|
||||
import { createInitialSessionState, getCurrentSession, login, logout } from "@core/session_manager";
|
||||
import { Fixture } from "@tests/helpers/state_fixture";
|
||||
import { describe, expect, test } from "vitest";
|
||||
|
||||
const state = Fixture.State;
|
||||
|
||||
const passMap = new Map();
|
||||
passMap.set(0, "123");
|
||||
passMap.set(1000, "321");
|
||||
|
||||
test("createInitialSessionState - successfully creates a new session state", () => {
|
||||
const state = createInitialSessionState(Fixture.user);
|
||||
|
||||
expect(state.cwd).toEqual(Fixture.user.home);
|
||||
expect(state.pwd).toEqual(Fixture.user.home);
|
||||
expect(state.exitCode).toEqual(0);
|
||||
expect(state.user).toBe(Fixture.user);
|
||||
expect(Object.isFrozen(state)).toBe(true);
|
||||
});
|
||||
|
||||
describe("login", () => {
|
||||
test("it successfully starts a new session under the user test", () => {
|
||||
const newState = login(state, "user", "321", passMap);
|
||||
const pop = getCurrentSession(newState);
|
||||
|
||||
expect(pop.user).toEqual(Fixture.user2);
|
||||
});
|
||||
|
||||
test("fails to start a new session. Cause: no password mapped to the uid", () => {
|
||||
//TODO: Fix to expect the correct object;
|
||||
expect(() => login(state, "no pass", "321", passMap)).toThrow();
|
||||
});
|
||||
|
||||
test("fails to start a new session. Cause: Incorrect password", () => {
|
||||
//TODO: Fix to expect the correct object;
|
||||
expect(() => login(state, "no pass", "333", passMap)).toThrow();
|
||||
});
|
||||
|
||||
test("fails to start a new session. Cause: Specified user does not exist", () => {
|
||||
//TODO: Fix to expect the correct object;
|
||||
expect(() => login(state, "no user", "321", passMap)).toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
describe("logout", () => {
|
||||
test("returns the state with the current user poped from the stack", () => {
|
||||
const newState = login(state, "user", "321", passMap);
|
||||
const newPop = getCurrentSession(newState);
|
||||
|
||||
expect(newPop.user).toEqual(Fixture.user2);
|
||||
|
||||
const newNewState = logout(state);
|
||||
const pop = getCurrentSession(newNewState);
|
||||
|
||||
expect(pop.user).toEqual(Fixture.user);
|
||||
});
|
||||
});
|
||||
@@ -1,48 +1,14 @@
|
||||
import { FileSystem } from "@core/filesystem/filesystem";
|
||||
import { TreeNodeType, type DirectoryNode, type TreeNode } from "@core/filesystem/treenode";
|
||||
import { getCurrentSession } from "@core/session";
|
||||
import { createInitialShellState, withCwd, withEnv, withExitCode, withHistory } from "@core/shell_state";
|
||||
import type { UserInfo } from "@core/user_info";
|
||||
import { getCurrentSession } from "@core/session_manager";
|
||||
import { withCwd, withEnv, withExitCode, withHistory } from "@core/shell_state";
|
||||
import { Fixture } from "@tests/helpers/state_fixture";
|
||||
import { expect, test } from "vitest";
|
||||
|
||||
const map: Map<number, TreeNode> = new Map();
|
||||
const time = Date.now();
|
||||
|
||||
const root: DirectoryNode = {
|
||||
type: TreeNodeType.Directory,
|
||||
inode: 0,
|
||||
name: "root",
|
||||
parent: 0,
|
||||
mode: 0o555,
|
||||
owner: 0,
|
||||
group: 0,
|
||||
mtime: time,
|
||||
atime: time,
|
||||
ctime: time,
|
||||
children: {},
|
||||
};
|
||||
map.set(0, root);
|
||||
|
||||
const base: ReadonlyMap<number, TreeNode> = map;
|
||||
const overlay: ReadonlyMap<number, TreeNode | null> = new Map();
|
||||
const fs = FileSystem.init(base, overlay, 0);
|
||||
|
||||
const users: Map<number, UserInfo> = new Map();
|
||||
const user: UserInfo = {
|
||||
name: "root",
|
||||
uid: 0,
|
||||
gid: 0,
|
||||
group: [0],
|
||||
home: 0,
|
||||
};
|
||||
users.set(0, user);
|
||||
|
||||
const state = createInitialShellState(fs, users, user);
|
||||
const state = Fixture.State;
|
||||
|
||||
test("createInitialShellState - initializes successfully", () => {
|
||||
expect(state.sessionStack.at(0)).toBeDefined();
|
||||
|
||||
expect(state.users.get(user.uid)).toEqual(user);
|
||||
expect(state.users.get(Fixture.user.uid)).toEqual(Fixture.user);
|
||||
expect(Object.isFrozen(state)).toBe(true);
|
||||
});
|
||||
|
||||
@@ -61,7 +27,7 @@ test("getCurrentSession - successfully returns the current (top most) session fr
|
||||
expect(session.exitCode).toBe(0);
|
||||
expect(session.history).toEqual([]);
|
||||
expect(session.envVars.size).toBe(0);
|
||||
expect(session.user).toBe(user);
|
||||
expect(session.user).toBe(Fixture.user);
|
||||
});
|
||||
|
||||
test("withCwd", () => {
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -1,17 +1,23 @@
|
||||
// @core/filesystem/errors.test-util.ts (adjust path to match yours)
|
||||
import type {
|
||||
AlreadyExistsError,
|
||||
DeviceNotFoundError,
|
||||
DirectoryLoopError,
|
||||
FileSystemCorruptionError,
|
||||
FileSystemInitializationError,
|
||||
IllegalMutationError,
|
||||
InvalidNodeNameError,
|
||||
NodeNotFoundError,
|
||||
NotADirectoryError,
|
||||
NotAFileError,
|
||||
} from "@core/filesystem/errors";
|
||||
import type { TreeNodeType } from "@core/filesystem/treenode";
|
||||
import type { NodeType } from "@core/filesystem/node";
|
||||
import { expect } from "vitest";
|
||||
|
||||
export function expectThrows(fn: () => unknown, expectedShape: Record<string, unknown>) {
|
||||
export async function expectThrows(fn: () => unknown, expectedShape: Record<string, unknown>) {
|
||||
let thrown: unknown;
|
||||
try {
|
||||
fn();
|
||||
await fn();
|
||||
} catch (e) {
|
||||
thrown = e;
|
||||
}
|
||||
@@ -20,19 +26,19 @@ export function expectThrows(fn: () => unknown, expectedShape: Record<string, un
|
||||
expect(thrown).toMatchObject(expectedShape);
|
||||
}
|
||||
|
||||
export function expectNotADirectoryError(fn: () => unknown, overrides?: Partial<NotADirectoryError>) {
|
||||
expectThrows(fn, {
|
||||
export async function expectNotADirectoryError(fn: () => unknown, overrides?: Partial<NotADirectoryError>) {
|
||||
return await expectThrows(fn, {
|
||||
type: "NotADirectory",
|
||||
inode: expect.any(Number) as number,
|
||||
message: expect.any(String) as string,
|
||||
timestamp: expect.any(Number) as number,
|
||||
nodeType: expect.any(String) as TreeNodeType,
|
||||
nodeType: expect.any(Number) as NodeType,
|
||||
...overrides,
|
||||
});
|
||||
}
|
||||
|
||||
export function expectAlreadyExistsError(fn: () => unknown, overrides?: Partial<AlreadyExistsError>) {
|
||||
expectThrows(fn, {
|
||||
export async function expectAlreadyExistsError(fn: () => unknown, overrides?: Partial<AlreadyExistsError>) {
|
||||
return await expectThrows(fn, {
|
||||
type: "AlreadyExists",
|
||||
parentInode: expect.any(Number) as number,
|
||||
name: expect.any(String) as string,
|
||||
@@ -42,18 +48,23 @@ export function expectAlreadyExistsError(fn: () => unknown, overrides?: Partial<
|
||||
});
|
||||
}
|
||||
|
||||
export function expectNodeNotFoundError(fn: () => unknown, overrides?: Partial<NodeNotFoundError>) {
|
||||
expectThrows(fn, {
|
||||
/**
|
||||
* FIXED: `NodeNotFoundError` has `pointer: NodePointer` (a string), not `inode: number`.
|
||||
* The previous version asserted `inode: expect.any(Number)` and would have failed
|
||||
* against every real thrown `NodeNotFoundError`.
|
||||
*/
|
||||
export async function expectNodeNotFoundError(fn: () => unknown, overrides?: Partial<NodeNotFoundError>) {
|
||||
return await expectThrows(fn, {
|
||||
type: "NodeNotFound",
|
||||
inode: expect.any(Number) as number,
|
||||
pointer: expect.any(String) as string,
|
||||
message: expect.any(String) as string,
|
||||
timestamp: expect.any(Number) as number,
|
||||
...overrides,
|
||||
});
|
||||
}
|
||||
|
||||
export function expectIllegalMutationError(fn: () => unknown, overrides?: Partial<IllegalMutationError>) {
|
||||
expectThrows(fn, {
|
||||
export async function expectIllegalMutationError(fn: () => unknown, overrides?: Partial<IllegalMutationError>) {
|
||||
return await expectThrows(fn, {
|
||||
type: "IllegalMutation",
|
||||
message: expect.any(String) as string,
|
||||
timestamp: expect.any(Number) as number,
|
||||
@@ -61,8 +72,8 @@ export function expectIllegalMutationError(fn: () => unknown, overrides?: Partia
|
||||
});
|
||||
}
|
||||
|
||||
export function expectDirectoryLoopError(fn: () => void, overrides?: Partial<DirectoryLoopError>) {
|
||||
expectThrows(fn, {
|
||||
export async function expectDirectoryLoopError(fn: () => void, overrides?: Partial<DirectoryLoopError>) {
|
||||
return await expectThrows(fn, {
|
||||
type: "DirectoryLoop",
|
||||
descendantInode: expect.any(Number) as number,
|
||||
ancestorInode: expect.any(Number) as number,
|
||||
@@ -71,3 +82,61 @@ export function expectDirectoryLoopError(fn: () => void, overrides?: Partial<Dir
|
||||
...overrides,
|
||||
});
|
||||
}
|
||||
|
||||
// ---- NEW helpers below ----
|
||||
|
||||
export async function expectDeviceNotFoundError(fn: () => unknown, overrides?: Partial<DeviceNotFoundError>) {
|
||||
return await expectThrows(fn, {
|
||||
type: "DeviceNotFound",
|
||||
device_id: expect.any(Number) as number,
|
||||
message: expect.any(String) as string,
|
||||
timestamp: expect.any(Number) as number,
|
||||
...overrides,
|
||||
});
|
||||
}
|
||||
|
||||
export async function expectNotAFileError(fn: () => unknown, overrides?: Partial<NotAFileError>) {
|
||||
return await expectThrows(fn, {
|
||||
type: "NotAFile",
|
||||
inode: expect.any(Number) as number,
|
||||
message: expect.any(String) as string,
|
||||
timestamp: expect.any(Number) as number,
|
||||
nodeType: expect.any(Number) as NodeType,
|
||||
...overrides,
|
||||
});
|
||||
}
|
||||
|
||||
export async function expectFileSystemInitializationError(
|
||||
fn: () => unknown,
|
||||
overrides?: Partial<FileSystemInitializationError>,
|
||||
) {
|
||||
return await expectThrows(fn, {
|
||||
type: "FileSystemInitializationError",
|
||||
message: expect.any(String) as string,
|
||||
timestamp: expect.any(Number) as number,
|
||||
...overrides,
|
||||
});
|
||||
}
|
||||
|
||||
export async function expectInvalidNodeNameError(fn: () => unknown, overrides?: Partial<InvalidNodeNameError>) {
|
||||
return await expectThrows(fn, {
|
||||
type: "InvalidNodeName",
|
||||
pointer: expect.any(String) as string,
|
||||
attemptedName: expect.any(String) as string,
|
||||
message: expect.any(String) as string,
|
||||
timestamp: expect.any(Number) as number,
|
||||
...overrides,
|
||||
});
|
||||
}
|
||||
|
||||
export async function expectFileSystemCorruptionError(
|
||||
fn: () => unknown,
|
||||
overrides?: Partial<FileSystemCorruptionError>,
|
||||
) {
|
||||
return await expectThrows(fn, {
|
||||
type: "FileSystemCorruption",
|
||||
message: expect.any(String) as string,
|
||||
timestamp: expect.any(Number) as number,
|
||||
...overrides,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1,71 +1,182 @@
|
||||
// ============================================================================
|
||||
// Node fixtures
|
||||
// ============================================================================
|
||||
|
||||
import { FileSystem } from "@core/filesystem/filesystem";
|
||||
import { TreeNodeType, type DirectoryNode, type FileNode, type TreeNode } from "@core/filesystem/treenode";
|
||||
import { createImmutableBuffer } from "@core/util/immutable_buffer";
|
||||
import {
|
||||
NodeType,
|
||||
toPtr,
|
||||
type DirectoryNode,
|
||||
type FileNode,
|
||||
type Node,
|
||||
type NodePointer,
|
||||
type SymlinkNode,
|
||||
} from "@core/filesystem/node";
|
||||
import { DefaultVDiskConfig } from "@core/filesystem/vdisk";
|
||||
import type { SessionState, UserInfo } from "@core/session_manager";
|
||||
import type { ShellState } from "@core/shell_state";
|
||||
import { MemDataStore, MemMetaStore } from "@core/util/temp_mem_stores";
|
||||
|
||||
export interface FixtureNode {
|
||||
inode: number;
|
||||
name: string;
|
||||
type: "File" | "Dir";
|
||||
children: FixtureNode[];
|
||||
content?: string;
|
||||
mode?: number;
|
||||
owner?: number;
|
||||
group?: number;
|
||||
mtime?: number;
|
||||
ctime?: number;
|
||||
atime?: number;
|
||||
}
|
||||
|
||||
export function buildTestFS(tree: FixtureNode): FileSystem {
|
||||
const map = new Map<number, TreeNode>();
|
||||
|
||||
function parse(node: FixtureNode, parent: number): void {
|
||||
if (node.type === "Dir") {
|
||||
for (const child of node.children) {
|
||||
parse(child, node.inode);
|
||||
}
|
||||
|
||||
const children: Record<string, number> = {};
|
||||
for (const child of node.children) {
|
||||
children[child.name] = child.inode;
|
||||
}
|
||||
|
||||
const directoryNode: DirectoryNode = {
|
||||
type: TreeNodeType.Directory,
|
||||
inode: node.inode,
|
||||
name: node.name,
|
||||
parent: parent,
|
||||
mode: node.mode ?? 0o777,
|
||||
owner: node.owner ?? 0,
|
||||
group: node.group ?? 0,
|
||||
mtime: node.mtime ?? Date.now(),
|
||||
ctime: node.ctime ?? Date.now(),
|
||||
atime: node.atime ?? Date.now(),
|
||||
children: children,
|
||||
export function makeDir(inode: number, children: Record<string, number> = {}): DirectoryNode {
|
||||
return {
|
||||
type: NodeType.Directory,
|
||||
inode,
|
||||
link_count: 2,
|
||||
mode: 0o755,
|
||||
owner: 0,
|
||||
group: 0,
|
||||
mtime: 0,
|
||||
ctime: 0,
|
||||
atime: 0,
|
||||
children: new Map(Object.entries(children)),
|
||||
};
|
||||
map.set(node.inode, Object.freeze(directoryNode));
|
||||
} else {
|
||||
const fileNode: FileNode = {
|
||||
type: TreeNodeType.File,
|
||||
inode: node.inode,
|
||||
name: node.name,
|
||||
parent: parent,
|
||||
mode: node.mode ?? 0o777,
|
||||
owner: node.owner ?? 0,
|
||||
group: node.group ?? 0,
|
||||
mtime: node.mtime ?? Date.now(),
|
||||
ctime: node.ctime ?? Date.now(),
|
||||
atime: node.atime ?? Date.now(),
|
||||
content: createImmutableBuffer(new TextEncoder().encode(node.content)),
|
||||
}
|
||||
|
||||
export function makeFile(inode: number): FileNode {
|
||||
return {
|
||||
type: NodeType.File,
|
||||
inode,
|
||||
link_count: 1,
|
||||
mode: 0o644,
|
||||
owner: 0,
|
||||
group: 0,
|
||||
mtime: 0,
|
||||
ctime: 0,
|
||||
atime: 0,
|
||||
content: `uuid-${inode}`,
|
||||
size: 0,
|
||||
};
|
||||
map.set(node.inode, Object.freeze(fileNode));
|
||||
}
|
||||
}
|
||||
|
||||
parse(tree, 0);
|
||||
export function makeSymlink(inode: number, target: string): SymlinkNode {
|
||||
return {
|
||||
type: NodeType.Symlink,
|
||||
inode,
|
||||
link_count: 1,
|
||||
mode: 0o777,
|
||||
owner: 0,
|
||||
group: 0,
|
||||
mtime: 0,
|
||||
ctime: 0,
|
||||
atime: 0,
|
||||
target,
|
||||
};
|
||||
}
|
||||
|
||||
const base: ReadonlyMap<number, TreeNode> = map;
|
||||
const overlay: ReadonlyMap<number, TreeNode | null> = new Map();
|
||||
export function makeUser(home: NodePointer = toPtr({ device_id: 0, inode: 0 })): UserInfo {
|
||||
return {
|
||||
username: "test",
|
||||
uid: 1000,
|
||||
gid: 1000,
|
||||
group: [],
|
||||
home,
|
||||
};
|
||||
}
|
||||
|
||||
return FileSystem.init(base, overlay, base.size - 1);
|
||||
// ============================================================================
|
||||
// Tree builder — auto-assigns inodes, validates before use
|
||||
// ============================================================================
|
||||
|
||||
export interface TreeBuilder {
|
||||
addDir(parentInode: number, name: string): number;
|
||||
addFile(parentInode: number, name: string): number;
|
||||
addSymlink(parentInode: number, name: string, target: string): number;
|
||||
build(): Map<number, Node>;
|
||||
}
|
||||
|
||||
export function makeTree(): TreeBuilder {
|
||||
const nodes = new Map<number, Node>([[0, makeDir(0)]]);
|
||||
let nextInode = 1;
|
||||
|
||||
function attach(parentInode: number, name: string, childInode: number): void {
|
||||
const parent = nodes.get(parentInode);
|
||||
if (!parent || parent.type !== NodeType.Directory) {
|
||||
throw new Error(`Parent inode ${parentInode} is not a directory`);
|
||||
}
|
||||
const children = new Map(parent.children);
|
||||
children.set(name, childInode);
|
||||
nodes.set(parentInode, { ...parent, children });
|
||||
}
|
||||
|
||||
function add(node: Node, parentInode: number, name: string): number {
|
||||
attach(parentInode, name, node.inode);
|
||||
nodes.set(node.inode, node);
|
||||
return node.inode;
|
||||
}
|
||||
|
||||
return {
|
||||
addDir(parentInode, name) {
|
||||
return add(makeDir(nextInode++), parentInode, name);
|
||||
},
|
||||
addFile(parentInode, name) {
|
||||
return add(makeFile(nextInode++), parentInode, name);
|
||||
},
|
||||
addSymlink(parentInode, name, target) {
|
||||
return add(makeSymlink(nextInode++, target), parentInode, name);
|
||||
},
|
||||
build() {
|
||||
for (const [key, node] of nodes) {
|
||||
if (node.inode !== key) {
|
||||
throw new Error(`inode mismatch: key=${key}, node.inode=${node.inode}`);
|
||||
}
|
||||
if (node.type === NodeType.Directory) {
|
||||
for (const [cname, cinode] of node.children) {
|
||||
if (!nodes.has(cinode)) {
|
||||
throw new Error(`dangling child '${cname}' → inode ${cinode}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return nodes;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// FileSystem builder — real VDisk stack, one device per base map
|
||||
// ============================================================================
|
||||
|
||||
export async function makeFS(bases: Map<number, Node>[]): Promise<FileSystem> {
|
||||
const devices = bases.map((base, id) => ({
|
||||
dstore: new MemDataStore(),
|
||||
mstore: new MemMetaStore(),
|
||||
config: {
|
||||
...DefaultVDiskConfig(id),
|
||||
base,
|
||||
index: Math.max(0, ...base.keys()),
|
||||
},
|
||||
}));
|
||||
|
||||
const fs = FileSystem.init(devices);
|
||||
// `FileSystem.init` does not await `registerDisk` (see the init suite BUG);
|
||||
// flush a macrotask so every disk is registered before the first resolve.
|
||||
await new Promise(r => setImmediate(r));
|
||||
return fs;
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Shell state fixture
|
||||
// ============================================================================
|
||||
|
||||
export function makeShellState(
|
||||
fs: FileSystem,
|
||||
opts: { cwd?: NodePointer; home?: NodePointer; user?: UserInfo } = {},
|
||||
): ShellState {
|
||||
const cwd = opts.cwd ?? toPtr({ device_id: 0, inode: 0 });
|
||||
const user = opts.user ?? makeUser(opts.home);
|
||||
const session = {
|
||||
user,
|
||||
envVars: new Map<string, string>(),
|
||||
history: [],
|
||||
cwd,
|
||||
pwd: cwd,
|
||||
exitCode: 0,
|
||||
} as unknown as SessionState;
|
||||
|
||||
return {
|
||||
filesystem: fs,
|
||||
users: new Map(),
|
||||
groups: new Map(),
|
||||
sessionStack: [session],
|
||||
} as unknown as ShellState;
|
||||
}
|
||||
|
||||
@@ -1,58 +0,0 @@
|
||||
import type { FixtureNode } from "./filesystems_fixture";
|
||||
|
||||
export const depth7Tree: FixtureNode = {
|
||||
inode: 0,
|
||||
name: "root",
|
||||
type: "Dir",
|
||||
children: [
|
||||
{
|
||||
inode: 1,
|
||||
name: "d1",
|
||||
type: "Dir",
|
||||
children: [
|
||||
{
|
||||
inode: 2,
|
||||
name: "d2",
|
||||
type: "Dir",
|
||||
children: [
|
||||
{
|
||||
inode: 3,
|
||||
name: "d3",
|
||||
type: "Dir",
|
||||
children: [
|
||||
{
|
||||
inode: 4,
|
||||
name: "d4",
|
||||
type: "Dir",
|
||||
children: [
|
||||
{
|
||||
inode: 5,
|
||||
name: "d5",
|
||||
type: "Dir",
|
||||
children: [
|
||||
{
|
||||
inode: 6,
|
||||
name: "d6",
|
||||
type: "Dir",
|
||||
children: [
|
||||
{
|
||||
inode: 7,
|
||||
name: "deep_file.txt",
|
||||
type: "File",
|
||||
content: "Deepest node at depth 7",
|
||||
children: [],
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
};
|
||||
@@ -0,0 +1,8 @@
|
||||
import { test } from "vitest";
|
||||
|
||||
//const rawJson = `{"atime": 1786341244,"children": [{"atime": 1786341264,"children": [{"atime": 1786341330,"children": [],"content": null,"ctime": 1786341330,"group": 1000,"inode": 2,"mode": 493,"mtime": 1786341330,"name": "subdir1","owner": 1000,"parent": 1,"type": "directory"}],"content": null,"ctime": 1786341330,"group": 1000,"inode": 1,"mode": 493,"mtime": 1786341330,"name": "folder1","owner": 1000,"parent": 0,"type": "directory"},{"atime": 1786341269,"children": [{"atime": 1786341344,"children": [],"content": null,"ctime": 1786341344,"group": 1000,"inode": 4,"mode": 493,"mtime": 1786341344,"name": "subdir2","owner": 1000,"parent": 3,"type": "directory"},{"atime": 1786341345,"children": [{"atime": 1786341356,"children": [],"content": [],"ctime": 1786341356,"group": 1000,"inode": 6,"mode": 420,"mtime": 1786341356,"name": "empty-foo","owner": 1000,"parent": 5,"type": "regular"}],"content": null,"ctime": 1786341356,"group": 1000,"inode": 5,"mode": 493,"mtime": 1786341356,"name": "subdir3","owner": 1000,"parent": 3,"type": "directory"}],"content": null,"ctime": 1786341345,"group": 1000,"inode": 3,"mode": 493,"mtime": 1786341345,"name": "folder2","owner": 1000,"parent": 0,"type": "directory"},{"atime": 1786341312,"children": [],"content": [72,101,108,108,111,44,32,87,111,114,108,100,33,10],"ctime": 1786341312,"group": 1000,"inode": 7,"mode": 420,"mtime": 1786341312,"name": "some-file","owner": 1000,"parent": 0,"type": "regular"}],"content": null,"ctime": 1786341312,"group": 1000,"inode": 0,"mode": 493,"mtime": 1786341312,"name": "root","owner": 1000,"parent": 0,"type": "directory"}`;
|
||||
|
||||
test("deserialize json into the correct tree structure", () => {
|
||||
//const base = deserializeFileSystem(rawJson);
|
||||
//expect(true).toEqual(false);
|
||||
});
|
||||
@@ -0,0 +1,29 @@
|
||||
import { getCurrentSession } from "@core/session_manager";
|
||||
import { Shell } from "@shell/shell";
|
||||
import { Fixture } from "@tests/helpers/state_fixture";
|
||||
import { describe, expect, test } from "vitest";
|
||||
|
||||
const state = Fixture.State;
|
||||
|
||||
describe("Shell tests", () => {
|
||||
test("Successfully executes the cd command", async () => {
|
||||
await Shell.init(state);
|
||||
|
||||
let result;
|
||||
|
||||
Shell.Instance?.on("result", payload => {
|
||||
result = payload.result;
|
||||
});
|
||||
|
||||
await Shell.Instance?.execute("cd /folder1");
|
||||
const statee = Shell.Instance?.State;
|
||||
|
||||
expect(result!.type).toEqual("success");
|
||||
expect(getCurrentSession(statee!).history.length).toBe(1);
|
||||
expect(getCurrentSession(statee!).history[0]).toEqual("cd /folder1");
|
||||
expect(getCurrentSession(statee!).cwd).toBe(1);
|
||||
expect(getCurrentSession(statee!).exitCode).toBe(0);
|
||||
});
|
||||
test("Returns a proper command error from cd", () => {});
|
||||
test("Returns an empty success result as per parsing a whitespace character or inputing nothing", () => {});
|
||||
});
|
||||
@@ -0,0 +1,20 @@
|
||||
import { splitUint8Array } from "@termos/util/concat";
|
||||
import { expect, test } from "vitest";
|
||||
|
||||
test("divide to chunks", () => {
|
||||
const data: Uint8Array = new Uint8Array(2048);
|
||||
const result = splitUint8Array(data, 1024);
|
||||
expect(result.length).toEqual(2);
|
||||
});
|
||||
|
||||
test("divide to chunks", () => {
|
||||
const data: Uint8Array = new Uint8Array(2049);
|
||||
const result = splitUint8Array(data, 1024);
|
||||
expect(result.length).toEqual(3);
|
||||
});
|
||||
|
||||
test("divide to chunks", () => {
|
||||
const data: Uint8Array = new Uint8Array(2048);
|
||||
const result = splitUint8Array(data, 53);
|
||||
expect(result.length).toEqual(Math.ceil(2048 / 53));
|
||||
});
|
||||
@@ -23,6 +23,7 @@
|
||||
"sourceMap": true,
|
||||
"ignoreDeprecations": "6.0",
|
||||
"baseUrl": "./",
|
||||
"types": ["node"],
|
||||
"paths": {
|
||||
"@tests/*": ["test/*"],
|
||||
"@shell/*": ["src/shell/*"],
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
import { defineConfig } from "tsup";
|
||||
|
||||
export default defineConfig({
|
||||
entry: ["src/index.ts", "!src/dev.ts", "!src/**/*.test.ts", "!src/**/*.spec.ts"],
|
||||
format: ["esm"],
|
||||
dts: true,
|
||||
clean: true,
|
||||
sourcemap: true,
|
||||
});
|
||||
Reference in New Issue
Block a user