Back to Epheos Library
Epheos Tech10 min read•Developer Tools & CLI Architecture
Engineering an Interactive Web CLI Sandbox & POSIX Tokenizer in TypeScript
How we built a lightweight, zero-dependency browser command-line sandbox featuring quote-aware POSIX argument parsing, prefix Trie autocompletion, ring buffer history, and ANSI terminal formatting.
Key Architectural Takeaways
Zero-Dependency Execution: Pure TypeScript command dispatcher with isolated stdout, stderr, exit codes, and environment variables.
POSIX Quote-Aware Tokenizer: Handles nested single/double quotes, spaces, and backslash escape sequences without string slicing bugs.
Trie Tab Autocomplete: High-speed prefix tree lookup across commands, subcommands, and flags.
Ring Buffer History: Full Up/Down shell history navigation with transient input preservation and duplicate suppression.
1. The POSIX Argument Tokenizer
Splitting input by spaces (input.split(' ')) destroys quoted strings like git commit -m "feat: initial commit". A state machine parser processes character-by-character:
export function tokenize(input: string): string[] {
const tokens: string[] = [];
let current = '';
let inDouble = false, inSingle = false, escape = false;
for (let i = 0; i < input.length; i++) {
const char = input[i];
if (escape) { current += char; escape = false; continue; }
if (char === '\\') { escape = true; continue; }
if (char === '"' && !inSingle) { inDouble = !inDouble; continue; }
if (char === "'" && !inDouble) { inSingle = !inSingle; continue; }
if (/\s/.test(char) && !inDouble && !inSingle) {
if (current.length > 0) { tokens.push(current); current = ''; }
continue;
}
current += char;
}
if (current.length > 0) tokens.push(current);
return tokens;
}2. Sub-Millisecond Trie Autocomplete
To provide instantaneous tab completion without lagging the browser event loop, all registered commands and subcommands are indexed in an in-memory prefix Trie tree:
// Tab Autocomplete with Prefix Trie
const trie = new TrieAutocomplete();
trie.insert('help');
trie.insert('history');
trie.insert('deploy');
trie.complete('he'); // Returns ['help']
trie.complete('h'); // Returns ['help', 'history']Available Open Source on npm & GitHub
Install @epheos/terminal-core to embed developer CLIs and interactive sandboxes in any web app.
