file_path
stringlengths
3
280
file_language
stringclasses
66 values
content
stringlengths
1
1.04M
repo_name
stringlengths
5
92
repo_stars
int64
0
154k
repo_description
stringlengths
0
402
repo_primary_language
stringclasses
108 values
developer_username
stringlengths
1
25
developer_name
stringlengths
0
30
developer_company
stringlengths
0
82
test/simple-node-repl-test.js
JavaScript
import { replManager } from '../dist/repl-manager.js'; async function testNodeREPL() { try { console.log('Creating a Node.js REPL session...'); const pid = await replManager.createSession('node', 5000); console.log(`Created Node.js REPL session with PID ${pid}`); console.log('Executing a simple Node.js command...'); const result = await replManager.executeCode(pid, 'console.log("Hello from Node.js!")', { waitForPrompt: true, timeout: 5000 }); console.log(`Result: ${JSON.stringify(result)}`); console.log('Executing a multi-line Node.js code block...'); const nodeCode = ` function greet(name) { return \`Hello, \${name}!\`; } console.log(greet("World")); `; const result2 = await replManager.executeCode(pid, nodeCode, { multiline: true, timeout: 10000, waitForPrompt: true }); console.log(`Multi-line result: ${JSON.stringify(result2)}`); console.log('Terminating the session...'); const terminated = await replManager.terminateSession(pid); console.log(`Session terminated: ${terminated}`); console.log('Test completed successfully'); } catch (error) { console.error(`Test failed with error: ${error.message}`); } } testNodeREPL();
wonderwhy-er/DesktopCommanderMCP
5,467
This is MCP server for Claude that gives it terminal control, file system search and diff file editing capabilities
TypeScript
wonderwhy-er
Eduard Ruzga
test/simple-python-test.js
JavaScript
import { executeCommand, readOutput, forceTerminate } from '../dist/tools/execute.js'; import { sendInput } from '../dist/tools/send-input.js'; async function simplePythonTest() { try { console.log("Starting Python with a simple command..."); // Run Python with a print command directly const result = await executeCommand({ command: 'python -c "print(\'Hello from Python\')"', timeout_ms: 5000 }); console.log("Result:", JSON.stringify(result, null, 2)); // Now let's try interactive mode console.log("\nStarting Python in interactive mode..."); const interactiveResult = await executeCommand({ command: 'python -i', timeout_ms: 5000 }); console.log("Interactive result:", JSON.stringify(interactiveResult, null, 2)); // Extract PID from the result text const pidMatch = interactiveResult.content[0].text.match(/Command started with PID (\d+)/); const pid = pidMatch ? parseInt(pidMatch[1]) : null; if (!pid) { console.error("Failed to get PID from Python process"); return; } console.log(`Started Python session with PID: ${pid}`); // Initial read to get the Python prompt console.log("Reading initial output..."); const initialOutput = await readOutput({ pid }); console.log("Initial output:", JSON.stringify(initialOutput, null, 2)); // Send a simple Python command with explicit newline console.log("Sending command..."); const inputResult = await sendInput({ pid, input: 'print("Hello from interactive Python")\n' }); console.log("Input result:", JSON.stringify(inputResult, null, 2)); // Wait a moment for Python to process console.log("Waiting for processing..."); await new Promise(resolve => setTimeout(resolve, 500)); // Read the output console.log("Reading output..."); const output = await readOutput({ pid }); console.log("Output:", JSON.stringify(output, null, 2)); // Terminate the session console.log("Terminating session..."); const terminateResult = await forceTerminate({ pid }); console.log("Terminate result:", JSON.stringify(terminateResult, null, 2)); console.log("Test completed"); } catch (error) { console.error("Error in test:", error); } } simplePythonTest();
wonderwhy-er/DesktopCommanderMCP
5,467
This is MCP server for Claude that gives it terminal control, file system search and diff file editing capabilities
TypeScript
wonderwhy-er
Eduard Ruzga
test/simple-repl-test.js
JavaScript
import { replManager } from '../dist/repl-manager.js'; async function testBasicREPL() { try { console.log('Creating a Python REPL session...'); const pid = await replManager.createSession('python', 5000); console.log(`Created Python REPL session with PID ${pid}`); console.log('Executing a simple Python command...'); const result = await replManager.executeCode(pid, 'print("Hello from Python!")'); console.log(`Result: ${JSON.stringify(result)}`); console.log('Terminating the session...'); const terminated = await replManager.terminateSession(pid); console.log(`Session terminated: ${terminated}`); console.log('Test completed successfully'); } catch (error) { console.error(`Test failed with error: ${error.message}`); } } testBasicREPL();
wonderwhy-er/DesktopCommanderMCP
5,467
This is MCP server for Claude that gives it terminal control, file system search and diff file editing capabilities
TypeScript
wonderwhy-er
Eduard Ruzga
test/test-allowed-directories.js
JavaScript
/** * Test script for allowedDirectories configuration functionality * * This script tests how different allowedDirectories settings affect file access: * 1. Testing file access with empty allowedDirectories array (should allow full access) * 2. Testing file access with specific directory in allowedDirectories * 3. Testing file access outside allowed directories * 4. Testing file access with root directory in allowedDirectories */ import { configManager } from '../dist/config-manager.js'; import { validatePath } from '../dist/tools/filesystem.js'; import fs from 'fs/promises'; import path from 'path'; import { fileURLToPath } from 'url'; import assert from 'assert'; import os from 'os'; // Get directory name const __filename = fileURLToPath(import.meta.url); const __dirname = path.dirname(__filename); // Define test paths for different locations const HOME_DIR = os.homedir(); const TEST_DIR_WITH_SLASH = path.join(__dirname, 'test_allowed_dirs') + '/'; const TEST_DIR = path.join(__dirname, 'test_allowed_dirs'); const OUTSIDE_DIR = path.join(os.tmpdir(), 'test_outside_allowed'); const ROOT_PATH = '/'; // For Windows compatibility - use forward slash for more consistent recognition const isWindows = process.platform === 'win32'; const TEST_ROOT_PATH = isWindows ? 'C:/' : '/'; /** * Helper function to clean up test directories */ async function cleanupTestDirectories() { try { console.log('Cleaning up test directories...'); await fs.rm(TEST_DIR, { recursive: true, force: true }); await fs.rm(OUTSIDE_DIR, { recursive: true, force: true }); // Clean up additional test directories await fs.rm(path.join(__dirname, 'test_dir_abc'), { recursive: true, force: true }).catch(() => {}); await fs.rm(path.join(__dirname, 'test_dir_abc_xyz'), { recursive: true, force: true }).catch(() => {}); console.log('Cleanup complete.'); } catch (error) { // Ignore errors if directory doesn't exist if (error.code !== 'ENOENT') { console.error('Error during cleanup:', error); } } } /** * Check if a path is accessible */ async function isPathAccessible(testPath) { console.log(`DEBUG isPathAccessible - Checking access to: ${testPath}`); try { const validatedPath = await validatePath(testPath); console.log(`DEBUG isPathAccessible - Validation successful: ${validatedPath}`); return true } catch (error) { console.log(`DEBUG isPathAccessible - Validation failed: ${error}`); return false; } } /** * Setup function to prepare the test environment */ async function setup() { // Clean up before tests await cleanupTestDirectories(); // Create test directories await fs.mkdir(TEST_DIR, { recursive: true }); await fs.mkdir(OUTSIDE_DIR, { recursive: true }); console.log(`✓ Setup: created test directories`); console.log(` - Test dir: ${TEST_DIR}`); console.log(` - Outside dir: ${OUTSIDE_DIR}`); // Create a test file in each directory await fs.writeFile(path.join(TEST_DIR, 'test-file.txt'), 'Test content'); await fs.writeFile(path.join(OUTSIDE_DIR, 'outside-file.txt'), 'Outside content'); // Save original config to restore later const originalConfig = await configManager.getConfig(); return originalConfig; } /** * Teardown function to clean up after tests */ async function teardown(originalConfig) { // Reset configuration to original await configManager.updateConfig(originalConfig); // Clean up test directories await cleanupTestDirectories(); console.log('✓ Teardown: test directories cleaned up and config restored'); } /** * Test empty allowedDirectories array (should allow full access) */ async function testEmptyAllowedDirectories() { console.log('\nTest 1: Empty allowedDirectories array'); // Set empty allowedDirectories await configManager.setValue('allowedDirectories', []); // Verify config was set correctly const config = await configManager.getConfig(); console.log(`DEBUG Test1 - Config: ${JSON.stringify(config.allowedDirectories)}`); assert.deepStrictEqual(config.allowedDirectories, [], 'allowedDirectories should be an empty array'); // Test access to various locations const homeAccess = await isPathAccessible(HOME_DIR); const testDirAccess = await isPathAccessible(TEST_DIR); const outsideDirAccess = await isPathAccessible(OUTSIDE_DIR); const rootAccess = await isPathAccessible(TEST_ROOT_PATH); // All paths should be accessible with an empty array assert.strictEqual(homeAccess, true, 'Home directory should be accessible with empty allowedDirectories'); assert.strictEqual(testDirAccess, true, 'Test directory should be accessible with empty allowedDirectories'); assert.strictEqual(outsideDirAccess, true, 'Outside directory should be accessible with empty allowedDirectories'); assert.strictEqual(rootAccess, true, 'Root path should be accessible with empty allowedDirectories'); console.log('✓ Empty allowedDirectories array allows access to all directories as expected'); } /** * Test with specific directory in allowedDirectories */ async function testSpecificAllowedDirectory() { console.log('\nTest 2: Specific directory in allowedDirectories'); // Set allowedDirectories to just the test directory await configManager.setValue('allowedDirectories', [TEST_DIR]); // Verify config was set correctly const config = await configManager.getConfig(); console.log(`DEBUG Test2 - Config: ${JSON.stringify(config.allowedDirectories)}`); assert.deepStrictEqual(config.allowedDirectories, [TEST_DIR], 'allowedDirectories should contain only the test directory'); // Test access to various locations const testDirAccess = await isPathAccessible(TEST_DIR); const testFileAccess = await isPathAccessible(path.join(TEST_DIR, 'test-file.txt')); const homeDirAccess = await isPathAccessible(HOME_DIR); const homeTildaDirAccess = await isPathAccessible('~'); const outsideDirAccess = await isPathAccessible(OUTSIDE_DIR); const rootAccess = await isPathAccessible(TEST_ROOT_PATH); // Only test directory and its contents should be accessible assert.strictEqual(testDirAccess, true, 'Test directory should be accessible'); assert.strictEqual(testFileAccess, true, 'Files in test directory should be accessible'); assert.strictEqual(homeDirAccess, TEST_DIR === HOME_DIR, 'Home directory should not be accessible (unless it equals test dir)'); assert.strictEqual(homeTildaDirAccess, TEST_DIR === HOME_DIR, 'Home directory should not be accessible (unless it equals test dir)'); assert.strictEqual(outsideDirAccess, false, 'Outside directory should not be accessible'); assert.strictEqual(rootAccess, false, 'Root path should not be accessible'); console.log('✓ Specific allowedDirectories setting correctly restricts access'); } /** * Test with root directory in allowedDirectories * * NOTE: This test was modified to accommodate the current behavior on Windows systems. * On Windows, setting C:/ or C:\ as an allowed directory only allows access to the * root directory itself but not to all subdirectories, which differs from Unix behavior. */ async function testRootInAllowedDirectories() { console.log('\nTest 3: Root directory in allowedDirectories'); console.log(`DEBUG: Using TEST_ROOT_PATH: ${TEST_ROOT_PATH}`); // Set allowedDirectories to include root path await configManager.setValue('allowedDirectories', [TEST_ROOT_PATH]); // Verify config was set correctly const config = await configManager.getConfig(); console.log(`DEBUG Test3 - Config: ${JSON.stringify(config.allowedDirectories)}`); assert.deepStrictEqual(config.allowedDirectories, [TEST_ROOT_PATH], 'allowedDirectories should contain only the root path'); // Test access to various locations console.log(`DEBUG Test3 - Testing ROOT_PATH access: ${TEST_ROOT_PATH}`); const rootAccess = await isPathAccessible(TEST_ROOT_PATH); console.log(`DEBUG Test3 - ROOT_PATH access result: ${rootAccess}`); const rootTildaAccess = await isPathAccessible('~'); // Root path should be accessible assert.strictEqual(rootAccess, true, 'Root path should be accessible when set in allowedDirectories'); assert.strictEqual(rootTildaAccess, true, 'Root path should be accessible when set in allowedDirectories'); // Check if we're on Windows if (isWindows) { console.log('DEBUG Test3 - Running on Windows, using modified expectations for root path'); // Since we're on Windows, we've already established that C:/ is accessible when set as // an allowed directory. This is sufficient to demonstrate the root path allowance is working as expected. // We'll skip the other path tests that would fail in the current implementation. } else { // On Unix systems, setting the root directory should allow access to all paths console.log(`DEBUG Test3 - Testing HOME_DIR access: ${HOME_DIR}`); const homeAccess = await isPathAccessible(HOME_DIR); console.log(`DEBUG Test3 - HOME_DIR access result: ${homeAccess}`); console.log(`DEBUG Test3 - Testing TEST_DIR access: ${TEST_DIR}`); const testDirAccess = await isPathAccessible(TEST_DIR); console.log(`DEBUG Test3 - TEST_DIR access result: ${testDirAccess}`); console.log(`DEBUG Test3 - Testing OUTSIDE_DIR access: ${OUTSIDE_DIR}`); const outsideDirAccess = await isPathAccessible(OUTSIDE_DIR); console.log(`DEBUG Test3 - OUTSIDE_DIR access result: ${outsideDirAccess}`); // All paths should be accessible on Unix assert.strictEqual(homeAccess, true, 'Home directory should be accessible with root in allowedDirectories'); assert.strictEqual(testDirAccess, true, 'Test directory should be accessible with root in allowedDirectories'); assert.strictEqual(outsideDirAccess, true, 'Outside directory should be accessible with root in allowedDirectories'); } console.log('✓ Root in allowedDirectories test passed with platform-specific behavior'); } /** * Test with home directory in allowedDirectories */ async function testHomeAllowedDirectory() { console.log('\nTest 4: Home directory in allowedDirectories'); // Set allowedDirectories to just the home directory await configManager.setValue('allowedDirectories', [HOME_DIR]); // Verify config was set correctly const config = await configManager.getConfig(); console.log(`DEBUG Test4 - Config: ${JSON.stringify(config.allowedDirectories)}`); assert.deepStrictEqual(config.allowedDirectories, [HOME_DIR], 'allowedDirectories should contain only the home directory'); // Check if OUTSIDE_DIR is inside the home directory const isOutsideDirInHome = OUTSIDE_DIR.toLowerCase().startsWith(HOME_DIR.toLowerCase()); // Test access to various locations const testDirAccess = await isPathAccessible(TEST_DIR); const testFileAccess = await isPathAccessible(path.join(TEST_DIR, 'test-file.txt')); const homeDirAccess = await isPathAccessible(HOME_DIR); const homeTildaDirAccess = await isPathAccessible('~'); const outsideDirAccess = await isPathAccessible(OUTSIDE_DIR); const rootAccess = await isPathAccessible(TEST_ROOT_PATH); // Only test directory and its contents should be accessible assert.strictEqual(testDirAccess, true, 'Test directory should be accessible'); assert.strictEqual(testFileAccess, true, 'Files in test directory should be accessible'); assert.strictEqual(homeDirAccess, true, 'Home directory should be accessible'); assert.strictEqual(homeTildaDirAccess, true, 'HOME TILDA directory should be accessible'); // For the outside directory, the expectation depends on whether it's inside the home directory // On Windows, the temp directory is often inside the user home directory if (isOutsideDirInHome) { assert.strictEqual(outsideDirAccess, true, 'Outside directory is inside home, so it should be accessible'); } else { assert.strictEqual(outsideDirAccess, false, 'Outside directory should not be accessible'); } assert.strictEqual(rootAccess, false, 'Root path should not be accessible'); console.log('✓ Home directory allowedDirectories setting correctly restricts access'); } /** * Test with specific directory with slash at the end in allowedDirectories */ async function testSpecificAllowedDirectoryWithSlash() { console.log('\nTest 5: Specific directory with slash at the end in allowedDirectories'); // Set allowedDirectories to just the test directory await configManager.setValue('allowedDirectories', [TEST_DIR_WITH_SLASH]); // Verify config was set correctly const config = await configManager.getConfig(); console.log(`DEBUG Test5 - Config: ${JSON.stringify(config.allowedDirectories)}`); console.log("TEST_DIR_WITH_SLASH", TEST_DIR_WITH_SLASH) assert.deepStrictEqual(config.allowedDirectories, [TEST_DIR_WITH_SLASH], 'allowedDirectories should contain only the test directory'); // Test access to various locations const testDirAccess = await isPathAccessible(TEST_DIR); const testFileAccess = await isPathAccessible(path.join(TEST_DIR, 'test-file.txt')); const homeDirAccess = await isPathAccessible(HOME_DIR); const homeTildaDirAccess = await isPathAccessible('~'); const outsideDirAccess = await isPathAccessible(OUTSIDE_DIR); const rootAccess = await isPathAccessible(TEST_ROOT_PATH); // Only test directory and its contents should be accessible assert.strictEqual(testDirAccess, true, 'Test directory should be accessible'); assert.strictEqual(testFileAccess, true, 'Files in test directory should be accessible'); assert.strictEqual(homeDirAccess, TEST_DIR === HOME_DIR, 'Home directory should not be accessible (unless it equals test dir)'); assert.strictEqual(homeTildaDirAccess, TEST_DIR === HOME_DIR, 'Home directory should not be accessible (unless it equals test dir)'); assert.strictEqual(outsideDirAccess, false, 'Outside directory should not be accessible'); assert.strictEqual(rootAccess, false, 'Root path should not be accessible'); console.log('✓ Specific allowedDirectories setting correctly restricts access'); } /** * Test that a path sharing a prefix with an allowed directory (but not a subdirectory) is correctly blocked */ async function testPrefixPathBlocking() { console.log('\nTest 6: Prefix path blocking'); // Create a directory with a name that would be caught by string prefix matching // Deliberately use path names that are clearly not subdirectories of each other const baseDir = path.join(__dirname, 'test_dir_abc'); const prefixMatchDir = path.join(__dirname, 'test_dir_abc_xyz'); console.log(`DEBUG Test6 - Base directory: ${baseDir}`); console.log(`DEBUG Test6 - Prefix-matching directory: ${prefixMatchDir}`); try { // Create both directories for testing await fs.mkdir(baseDir, { recursive: true }); await fs.mkdir(prefixMatchDir, { recursive: true }); // Create test files await fs.writeFile(path.join(baseDir, 'base-file.txt'), 'Base content'); await fs.writeFile(path.join(prefixMatchDir, 'prefix-file.txt'), 'Prefix content'); // Set allowedDirectories to just the base directory await configManager.setValue('allowedDirectories', [baseDir]); // Verify config was set correctly const config = await configManager.getConfig(); console.log(`DEBUG Test6 - Config: ${JSON.stringify(config.allowedDirectories)}`); assert.deepStrictEqual(config.allowedDirectories, [baseDir], 'allowedDirectories should contain only the base directory'); // Test access to the base directory and its contents const baseDirAccess = await isPathAccessible(baseDir); const baseFileAccess = await isPathAccessible(path.join(baseDir, 'base-file.txt')); // Test access to the prefix-matching directory and its contents const prefixDirAccess = await isPathAccessible(prefixMatchDir); const prefixFileAccess = await isPathAccessible(path.join(prefixMatchDir, 'prefix-file.txt')); // Base directory and its contents should be accessible assert.strictEqual(baseDirAccess, true, 'Base directory should be accessible'); assert.strictEqual(baseFileAccess, true, 'Files in base directory should be accessible'); // Prefix-matching directory should NOT be accessible assert.strictEqual(prefixDirAccess, false, 'Prefix-matching directory should not be accessible'); assert.strictEqual(prefixFileAccess, false, 'Files in prefix-matching directory should not be accessible'); console.log('✓ Prefix path blocking works correctly'); } finally { // Clean up test directories await fs.rm(baseDir, { recursive: true, force: true }).catch(() => {}); await fs.rm(prefixMatchDir, { recursive: true, force: true }).catch(() => {}); } } /** * Main test function */ async function testAllowedDirectories() { console.log('=== allowedDirectories Configuration Tests ===\n'); // Test 1: Empty allowedDirectories array await testEmptyAllowedDirectories(); // Test 2: Specific directory in allowedDirectories await testSpecificAllowedDirectory(); // Test 3: Root directory in allowedDirectories await testRootInAllowedDirectories(); // Test 4: Home directory in allowedDirectories await testHomeAllowedDirectory(); // Test 5: Specific directory in allowedDirectories await testSpecificAllowedDirectoryWithSlash(); // Test 6: Prefix path blocking await testPrefixPathBlocking(); console.log('\n✅ All allowedDirectories tests passed!'); } // Export the main test function export default async function runTests() { let originalConfig; try { originalConfig = await setup(); await testAllowedDirectories(); } catch (error) { console.error('❌ Test failed:', error.message); return false; } finally { if (originalConfig) { await teardown(originalConfig); } } return true; } // If this file is run directly (not imported), execute the test if (import.meta.url === `file://${process.argv[1]}`) { runTests().catch(error => { console.error('❌ Unhandled error:', error); process.exit(1); }); }
wonderwhy-er/DesktopCommanderMCP
5,467
This is MCP server for Claude that gives it terminal control, file system search and diff file editing capabilities
TypeScript
wonderwhy-er
Eduard Ruzga
test/test-blocked-commands.js
JavaScript
/** * Test script for blockedCommands configuration functionality * * This script tests how blockedCommands settings affect command execution: * 1. Testing execution of non-blocked commands * 2. Testing execution of blocked commands * 3. Testing updated blockedCommands list * 4. Testing empty blockedCommands array */ import { configManager } from '../dist/config-manager.js'; import { commandManager } from '../dist/command-manager.js'; import { startProcess, forceTerminate } from '../dist/tools/improved-process-tools.js'; // We need a wrapper because startProcess in tools/improved-process-tools.js returns a ServerResult // but our tests expect to receive the actual command result async function executeCommand(command, timeout_ms = 2000, shell = null) { const args = { command: command, timeout_ms: timeout_ms }; if (shell) { args.shell = shell; } return await startProcess(args); } import fs from 'fs/promises'; import path from 'path'; import { fileURLToPath } from 'url'; import assert from 'assert'; import os from 'os'; // Get directory name const __filename = fileURLToPath(import.meta.url); const __dirname = path.dirname(__filename); // Define test directory const TEST_DIR = path.join(__dirname, 'test_blocked_commands'); // Define some test commands const SAFE_COMMANDS = [ 'echo "Hello World"', 'pwd', 'date' ]; const POTENTIALLY_HARMFUL_COMMANDS = [ 'rm', 'mkfs', 'dd' ]; /** * Helper function to clean up test directories */ async function cleanupTestDirectories() { try { console.log('Cleaning up test directories...'); await fs.rm(TEST_DIR, { recursive: true, force: true }); console.log('Cleanup complete.'); } catch (error) { // Ignore errors if directory doesn't exist if (error.code !== 'ENOENT') { console.error('Error during cleanup:', error); } } } /** * Execute a command and return true if it executed successfully, false if blocked */ async function tryCommand(command) { try { const result = await executeCommand(command, null, 2000); // Check if the result indicates the command was blocked if (result.isError && result.content && result.content[0] && result.content[0].text && result.content[0].text.includes('Command not allowed')) { return { blocked: true, error: result.content[0].text }; } // Command was executed successfully return { blocked: false, output: result.content && result.content[0] ? result.content[0].text : '', pid: result.content && result.content[0] && result.content[0].text ? parseInt(result.content[0].text.match(/PID (\d+)/)?.[1] || '-1') : -1 }; } catch (error) { // Check if the error message indicates blocking if (error.message && ( error.message.includes('Command not allowed') || error.message.includes('blocked by configuration'))) { return { blocked: true, error: error.message }; } // Otherwise it's another type of error throw error; } } /** * Setup function to prepare the test environment */ async function setup() { // Clean up before tests await cleanupTestDirectories(); // Create test directory await fs.mkdir(TEST_DIR, { recursive: true }); // Create a test file in the directory await fs.writeFile(path.join(TEST_DIR, 'test-file.txt'), 'Test content'); console.log(`✓ Setup: created test directory: ${TEST_DIR}`); // Save original config to restore later const originalConfig = await configManager.getConfig(); return originalConfig; } /** * Teardown function to clean up after tests */ async function teardown(originalConfig) { // Reset configuration to original await configManager.updateConfig(originalConfig); // Clean up test directories await cleanupTestDirectories(); console.log('✓ Teardown: test directories cleaned up and config restored'); } /** * Test execution of non-blocked commands */ async function testNonBlockedCommands() { console.log('\nTest 1: Execution of non-blocked commands'); // Set blockedCommands to include specific harmful commands const blockedCommands = [ "rm -rf /", ":(){ :|:& };:", "> /dev/sda", "dd if=/dev/zero of=/dev/sda", "mkfs", "mkfs.ext4", "format" ]; await configManager.setValue('blockedCommands', blockedCommands); // Verify config was set correctly const config = await configManager.getConfig(); assert.deepStrictEqual(config.blockedCommands, blockedCommands, 'blockedCommands should be correctly set'); // Try to execute safe commands for (const command of SAFE_COMMANDS) { console.log(`Testing command: ${command}`); const result = await tryCommand(command); assert.strictEqual(result.blocked, false, `Command should not be blocked: ${command}`); console.log(`✓ Command executed successfully: ${command}`); } } /** * Test execution of blocked commands */ async function testBlockedCommandsExecution() { console.log('\nTest 2: Execution of blocked commands'); // Set blockedCommands to block our test harmful commands const blockedCommands = POTENTIALLY_HARMFUL_COMMANDS.slice(); await configManager.setValue('blockedCommands', blockedCommands); // Verify config was set correctly const config = await configManager.getConfig(); assert.deepStrictEqual(config.blockedCommands, blockedCommands, 'blockedCommands should be correctly set'); // We'll test this by directly checking against commandManager.validateCommand // since that's what determines if a command is blocked for (const command of POTENTIALLY_HARMFUL_COMMANDS) { console.log(`Testing blocked command: ${command}`); // Check validation directly const isAllowed = await commandManager.validateCommand(command); console.log(`Command ${command} allowed:`, isAllowed); // The command should NOT be allowed assert.strictEqual(isAllowed, false, `Command should be blocked: ${command}`); console.log(`✓ Command was correctly blocked: ${command}`); } } /** * Test updating blockedCommands list */ async function testUpdatingBlockedCommands() { console.log('\nTest 3: Updating blockedCommands list'); // Start with one blocked command const testCommand = 'echo'; await configManager.setValue('blockedCommands', [testCommand]); // Verify the command is blocked const isAllowed1 = await commandManager.validateCommand(testCommand); assert.strictEqual(isAllowed1, false, 'Command should be blocked before update'); console.log(`Command ${testCommand} blocked before update: ${!isAllowed1}`); // Update blockedCommands to empty array await configManager.setValue('blockedCommands', []); // Verify the command is now allowed const isAllowed2 = await commandManager.validateCommand(testCommand); assert.strictEqual(isAllowed2, true, 'Command should be allowed after update'); console.log(`Command ${testCommand} allowed after update: ${isAllowed2}`); console.log('✓ blockedCommands list was successfully updated'); } /** * Test empty blockedCommands array */ async function testEmptyBlockedCommands() { console.log('\nTest 4: Empty blockedCommands array'); // Set blockedCommands to empty array await configManager.setValue('blockedCommands', []); // Verify config was set correctly const config = await configManager.getConfig(); assert.deepStrictEqual(config.blockedCommands, [], 'blockedCommands should be an empty array'); // Try to execute both safe and potentially harmful commands const allCommands = [...SAFE_COMMANDS, ...POTENTIALLY_HARMFUL_COMMANDS]; for (const command of allCommands) { console.log(`Testing with empty blockedCommands: ${command}`); const isAllowed = await commandManager.validateCommand(command); assert.strictEqual(isAllowed, true, `No commands should be blocked with empty blockedCommands: ${command}`); console.log(`✓ Command allowed with empty blockedCommands: ${command}`); } } /** * Main test function */ async function runBlockedCommandsTests() { console.log('=== blockedCommands Configuration Tests ===\n'); // Test 1: Execution of non-blocked commands await testNonBlockedCommands(); // Test 2: Execution of blocked commands await testBlockedCommandsExecution(); // Test 3: Updating blockedCommands list await testUpdatingBlockedCommands(); // Test 4: Empty blockedCommands array await testEmptyBlockedCommands(); console.log('\n✅ All blockedCommands tests passed!'); } // Export the main test function export default async function runTests() { let originalConfig; try { originalConfig = await setup(); await runBlockedCommandsTests(); } catch (error) { console.error('❌ Test failed:', error.message); return false; } finally { if (originalConfig) { await teardown(originalConfig); } } return true; } // If this file is run directly (not imported), execute the test if (import.meta.url === `file://${process.argv[1]}`) { runTests().catch(error => { console.error('❌ Unhandled error:', error); process.exit(1); }); }
wonderwhy-er/DesktopCommanderMCP
5,467
This is MCP server for Claude that gives it terminal control, file system search and diff file editing capabilities
TypeScript
wonderwhy-er
Eduard Ruzga
test/test-blocklist-bypass.js
JavaScript
/** * Tests for command blocklist bypass fixes * Covers: absolute path bypass (#218), command substitution bypass (#217) */ import assert from 'assert'; import { commandManager } from '../dist/command-manager.js'; async function runTests() { // mock config with blocked commands const blockedCmds = ['sudo', 'iptables', 'rm']; console.log('Testing extractCommands...\n'); try { // Test 1: absolute path should be normalized const cmds1 = commandManager.extractCommands('/usr/bin/sudo ls'); console.log(' /usr/bin/sudo ls =>', cmds1); assert.ok(cmds1.includes('sudo'), 'FAIL: should extract "sudo" from absolute path'); // Test 2: $() command substitution inside quotes const cmds2 = commandManager.extractCommands('echo "$(iptables -L)"'); console.log(' echo "$(iptables -L)" =>', cmds2); assert.ok(cmds2.includes('iptables'), 'FAIL: should extract "iptables" from $() inside quotes'); // Test 3: backtick substitution const cmds3 = commandManager.extractCommands('echo `rm -rf /`'); console.log(' echo `rm -rf /` =>', cmds3); assert.ok(cmds3.includes('rm'), 'FAIL: should extract "rm" from backticks'); // Test 4: normal command still works const cmds4 = commandManager.extractCommands('ls -la /home'); console.log(' ls -la /home =>', cmds4); assert.ok(cmds4.includes('ls'), 'FAIL: should extract "ls" normally'); // Test 5: nested $() inside $() const cmds5 = commandManager.extractCommands('echo $(cat $(which sudo))'); console.log(' echo $(cat $(which sudo)) =>', cmds5); assert.ok(cmds5.includes('cat'), 'FAIL: should extract "cat" from nested $()'); // Test 6: path with env var prefix const cmds6 = commandManager.extractCommands('HOME=/tmp /usr/sbin/iptables'); console.log(' HOME=/tmp /usr/sbin/iptables =>', cmds6); assert.ok(cmds6.includes('iptables'), 'FAIL: should extract "iptables" from path with env'); // Test 7: backtick substitution inside quotes const cmds7 = commandManager.extractCommands('echo "`/usr/bin/sudo`"'); console.log(' echo "`/usr/bin/sudo`" =>', cmds7); assert.ok(cmds7.includes('sudo'), 'FAIL: should extract "sudo" from backticks inside quotes'); // Test 8: dollar-prefixed tokens should be ignored const cmds8 = commandManager.extractCommands('$MYVAR ls'); console.log(' $MYVAR ls =>', cmds8); assert.ok(cmds8.includes('ls'), 'FAIL: should extract "ls" and ignore $MYVAR'); assert.ok(!cmds8.includes('$MYVAR'), 'FAIL: should not include $MYVAR as a command'); console.log('\nAll tests passed!'); } catch (error) { console.error('Test failed:', error.message); process.exit(1); } } runTests().catch((error) => { console.error('Test execution failed:', error); process.exit(1); });
wonderwhy-er/DesktopCommanderMCP
5,467
This is MCP server for Claude that gives it terminal control, file system search and diff file editing capabilities
TypeScript
wonderwhy-er
Eduard Ruzga
test/test-conditional-tools.js
JavaScript
#!/usr/bin/env node /** * Test: Verify conditional tool registration based on client name * Tests that give_feedback_to_desktop_commander is excluded for desktop-commander client */ import { Client } from "@modelcontextprotocol/sdk/client/index.js"; import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js"; async function testConditionalTools() { console.log('\n=== Test: Conditional Tool Registration ===\n'); // Test 1: Regular client (should include feedback tool) console.log('Test 1: Testing with regular client (should include feedback tool)...'); const regularClient = new Client( { name: "test-client", version: "1.0.0" }, { capabilities: {} } ); const regularTransport = new StdioClientTransport({ command: "node", args: ["../dist/index.js"] }); await regularClient.connect(regularTransport); const regularTools = await regularClient.listTools(); const hasFeedbackRegular = regularTools.tools.some(t => t.name === 'give_feedback_to_desktop_commander'); console.log(` Tools count: ${regularTools.tools.length}`); console.log(` Has give_feedback_to_desktop_commander: ${hasFeedbackRegular}`); if (hasFeedbackRegular) { console.log(' ✅ PASS: Feedback tool is included for regular client'); } else { console.log(' ❌ FAIL: Feedback tool should be included for regular client'); process.exit(1); } await regularClient.close(); // Wait a bit between tests await new Promise(resolve => setTimeout(resolve, 1000)); // Test 2: desktop-commander client (should exclude feedback tool) console.log('\nTest 2: Testing with desktop-commander client (should exclude feedback tool)...'); const dcClient = new Client( { name: "desktop-commander", version: "1.0.0" }, { capabilities: {} } ); const dcTransport = new StdioClientTransport({ command: "node", args: ["../dist/index.js"] }); await dcClient.connect(dcTransport); const dcTools = await dcClient.listTools(); const hasFeedbackDC = dcTools.tools.some(t => t.name === 'give_feedback_to_desktop_commander'); console.log(` Tools count: ${dcTools.tools.length}`); console.log(` Has give_feedback_to_desktop_commander: ${hasFeedbackDC}`); if (!hasFeedbackDC) { console.log(' ✅ PASS: Feedback tool is excluded for desktop-commander client'); } else { console.log(' ❌ FAIL: Feedback tool should be excluded for desktop-commander client'); process.exit(1); } await dcClient.close(); console.log('\n=== All Tests Passed! ===\n'); } testConditionalTools().catch(error => { console.error('Test failed:', error); process.exit(1); });
wonderwhy-er/DesktopCommanderMCP
5,467
This is MCP server for Claude that gives it terminal control, file system search and diff file editing capabilities
TypeScript
wonderwhy-er
Eduard Ruzga
test/test-default-shell.js
JavaScript
/** * Test script for defaultShell configuration functionality * * This script tests how defaultShell settings affect command execution: * 1. Testing execution with /bin/sh as default shell * 2. Testing execution with bash as default shell * 3. Testing shell changes are properly applied * 4. Testing restoration of original configuration */ import { configManager } from '../dist/config-manager.js'; import { startProcess, forceTerminate } from '../dist/tools/improved-process-tools.js'; import assert from 'assert'; import os from 'os'; // We need a wrapper because startProcess in tools/improved-process-tools.js returns a ServerResult // but our tests expect to receive the actual command result async function executeCommand(command, timeout_ms = 2000, shell = null) { const args = { command: command, timeout_ms: timeout_ms }; if (shell) { args.shell = shell; } return await startProcess(args); } /** * Check if a shell is available on the system */ async function isShellAvailable(shellPath) { try { // For Windows shells, use different detection methods if (shellPath === 'cmd' || shellPath === 'cmd.exe') { // On Windows, cmd should always be available if (os.platform() === 'win32') { return true; } return false; } if (shellPath === 'pwsh' || shellPath === 'powershell') { // Check if PowerShell is available try { const result = await executeCommand(`${shellPath} -Command "Get-Host"`, 2000); return result.content && result.content[0] && !result.content[0].text.includes('not found'); } catch (error) { return false; } } // For Unix shells, check if the file exists and is executable try { const result = await executeCommand(`test -x "${shellPath}" && echo "available"`, 2000); return result.content && result.content[0] && result.content[0].text.includes('available'); } catch (error) { return false; } } catch (error) { console.log(`Could not check availability of ${shellPath}: ${error.message}`); return false; } } /** * Get expected shell output for a given shell path */ function getExpectedShellOutput(shellPath) { switch (shellPath) { case '/bin/sh': return ['/bin/sh']; case '/bin/bash': return ['/bin/bash', 'bash']; case 'cmd': case 'cmd.exe': return ['cmd', 'cmd.exe']; case 'pwsh': return ['pwsh']; case 'powershell': return ['powershell']; default: return [shellPath]; } } /** * Execute echo $0 command and extract the shell name from the output * For Windows shells, use appropriate commands */ async function getShellFromCommand(shellPath = null) { try { let command = 'echo $0'; // Use different commands for Windows shells if (shellPath === 'cmd' || shellPath === 'cmd.exe') { command = 'echo %0'; } else if (shellPath === 'pwsh' || shellPath === 'powershell') { command = 'Write-Host $MyInvocation.MyCommand.Name'; } const result = await executeCommand(command, 2000); // Extract shell name from the result if (result.content && result.content[0] && result.content[0].text) { const output = result.content[0].text; // Look for the shell name in the output, handling both PID line and actual output const lines = output.split('\n').filter(line => line.trim() !== ''); // Find the line that contains the actual shell output (not the PID line, Command started, or Initial output) for (const line of lines) { if (!line.includes('PID') && !line.includes('Command started') && !line.includes('Initial output:') && line.trim() !== '') { return line.trim(); } } } throw new Error('Could not extract shell name from command output'); } catch (error) { console.error('Error executing shell command:', error); throw error; } } /** * Setup function to prepare the test environment */ async function setup() { console.log('Setting up test environment...'); // Save original config to restore later const originalConfig = await configManager.getConfig(); console.log(`✓ Setup: saved original configuration`); console.log(` - Original defaultShell: ${originalConfig.defaultShell || 'not set'}`); return originalConfig; } /** * Teardown function to clean up after tests */ async function teardown(originalConfig) { // Reset configuration to original await configManager.updateConfig(originalConfig); console.log('✓ Teardown: original configuration restored'); console.log(` - Restored defaultShell: ${originalConfig.defaultShell || 'not set'}`); } /** * Test setting defaultShell to /bin/sh */ async function testDefaultShellSh() { console.log('\nTest 1: Setting defaultShell to /bin/sh'); // Check if /bin/sh is available const isAvailable = await isShellAvailable('/bin/sh'); if (!isAvailable) { console.log('⚠️ Skipping /bin/sh test: shell not available on this system'); return; } // Set defaultShell to /bin/sh await configManager.setValue('defaultShell', '/bin/sh'); // Verify config was set correctly const config = await configManager.getConfig(); assert.strictEqual(config.defaultShell, '/bin/sh', 'defaultShell should be set to /bin/sh'); console.log(`✓ Configuration updated: defaultShell = ${config.defaultShell}`); // Execute echo $0 to check the shell const shellOutput = await getShellFromCommand(config.defaultShell); console.log(`✓ Command output: ${shellOutput}`); // Verify the shell is /bin/sh const expectedOutputs = getExpectedShellOutput('/bin/sh'); const isValidOutput = expectedOutputs.includes(shellOutput); assert(isValidOutput, `Shell should be one of ${expectedOutputs.join(', ')}, got: ${shellOutput}`); console.log('✓ Test 1 passed: /bin/sh is correctly set as default shell'); } /** * Test setting defaultShell to bash */ async function testDefaultShellBash() { console.log('\nTest 2: Setting defaultShell to /bin/bash'); // Check if /bin/bash is available const isAvailable = await isShellAvailable('/bin/bash'); if (!isAvailable) { console.log('⚠️ Skipping /bin/bash test: shell not available on this system'); return; } // Set defaultShell to /bin/bash (use full path) await configManager.setValue('defaultShell', '/bin/bash'); // Verify config was set correctly const config = await configManager.getConfig(); assert.strictEqual(config.defaultShell, '/bin/bash', 'defaultShell should be set to /bin/bash'); console.log(`✓ Configuration updated: defaultShell = ${config.defaultShell}`); // Execute echo $0 to check the shell const shellOutput = await getShellFromCommand(config.defaultShell); console.log(`✓ Command output: ${shellOutput}`); // Verify the shell is /bin/bash (note: bash may show as just "bash" or full path) const expectedOutputs = getExpectedShellOutput('/bin/bash'); const isValidOutput = expectedOutputs.includes(shellOutput); assert(isValidOutput, `Shell should be one of ${expectedOutputs.join(', ')}, got: ${shellOutput}`); console.log('✓ Test 2 passed: /bin/bash is correctly set as default shell'); } /** * Test setting defaultShell to cmd (Windows Command Prompt) */ async function testDefaultShellCmd() { console.log('\nTest 3: Setting defaultShell to cmd'); // Check if cmd is available (Windows only) const isAvailable = await isShellAvailable('cmd'); if (!isAvailable) { console.log('⚠️ Skipping cmd test: shell not available on this system (likely not Windows)'); return; } // Set defaultShell to cmd await configManager.setValue('defaultShell', 'cmd'); // Verify config was set correctly const config = await configManager.getConfig(); assert.strictEqual(config.defaultShell, 'cmd', 'defaultShell should be set to cmd'); console.log(`✓ Configuration updated: defaultShell = ${config.defaultShell}`); // Execute echo %0 to check the shell (Windows command) const shellOutput = await getShellFromCommand('cmd'); console.log(`✓ Command output: ${shellOutput}`); // Verify the shell is cmd const expectedOutputs = getExpectedShellOutput('cmd'); const isValidOutput = expectedOutputs.includes(shellOutput); assert(isValidOutput, `Shell should be one of ${expectedOutputs.join(', ')}, got: ${shellOutput}`); console.log('✓ Test 3 passed: cmd is correctly set as default shell'); } /** * Test setting defaultShell to pwsh (PowerShell Core) */ async function testDefaultShellPwsh() { console.log('\nTest 4: Setting defaultShell to pwsh'); // Check if pwsh is available const isAvailable = await isShellAvailable('pwsh'); if (!isAvailable) { console.log('⚠️ Skipping pwsh test: PowerShell Core not available on this system'); return; } // Set defaultShell to pwsh await configManager.setValue('defaultShell', 'pwsh'); // Verify config was set correctly const config = await configManager.getConfig(); assert.strictEqual(config.defaultShell, 'pwsh', 'defaultShell should be set to pwsh'); console.log(`✓ Configuration updated: defaultShell = ${config.defaultShell}`); // Execute PowerShell command to check the shell const shellOutput = await getShellFromCommand('pwsh'); console.log(`✓ Command output: ${shellOutput}`); // Verify the shell is pwsh const expectedOutputs = getExpectedShellOutput('pwsh'); const isValidOutput = expectedOutputs.includes(shellOutput); assert(isValidOutput, `Shell should be one of ${expectedOutputs.join(', ')}, got: ${shellOutput}`); console.log('✓ Test 4 passed: pwsh is correctly set as default shell'); } /** * Test switching between different shells */ async function testShellSwitching() { console.log('\nTest 5: Testing shell switching'); // Get available shells for switching test const availableShells = []; if (await isShellAvailable('/bin/sh')) availableShells.push('/bin/sh'); if (await isShellAvailable('/bin/bash')) availableShells.push('/bin/bash'); if (await isShellAvailable('cmd')) availableShells.push('cmd'); if (await isShellAvailable('pwsh')) availableShells.push('pwsh'); if (availableShells.length < 2) { console.log('⚠️ Skipping shell switching test: need at least 2 available shells'); return; } console.log(`✓ Available shells for switching test: ${availableShells.join(', ')}`); // Test switching between first two available shells const shell1 = availableShells[0]; const shell2 = availableShells[1]; // Switch to first shell await configManager.setValue('defaultShell', shell1); let shellOutput = await getShellFromCommand(shell1); let expectedOutputs = getExpectedShellOutput(shell1); let isValidOutput = expectedOutputs.includes(shellOutput); assert(isValidOutput, `Switch to ${shell1} should work, got: ${shellOutput}`); console.log(`✓ Successfully switched to ${shell1}: ${shellOutput}`); // Switch to second shell await configManager.setValue('defaultShell', shell2); shellOutput = await getShellFromCommand(shell2); expectedOutputs = getExpectedShellOutput(shell2); isValidOutput = expectedOutputs.includes(shellOutput); assert(isValidOutput, `Switch to ${shell2} should work, got: ${shellOutput}`); console.log(`✓ Successfully switched to ${shell2}: ${shellOutput}`); // Switch back to first shell await configManager.setValue('defaultShell', shell1); shellOutput = await getShellFromCommand(shell1); expectedOutputs = getExpectedShellOutput(shell1); isValidOutput = expectedOutputs.includes(shellOutput); assert(isValidOutput, `Switch back to ${shell1} should work, got: ${shellOutput}`); console.log(`✓ Successfully switched back to ${shell1}: ${shellOutput}`); console.log('✓ Test 5 passed: shell switching works correctly'); } /** * Test that configuration changes persist */ async function testConfigurationPersistence() { console.log('\nTest 6: Testing configuration persistence'); // Find an available shell for testing let testShell = '/bin/sh'; if (!(await isShellAvailable('/bin/sh'))) { if (await isShellAvailable('/bin/bash')) { testShell = '/bin/bash'; } else if (await isShellAvailable('cmd')) { testShell = 'cmd'; } else if (await isShellAvailable('pwsh')) { testShell = 'pwsh'; } else { console.log('⚠️ Skipping persistence test: no available shells found'); return; } } // Set defaultShell to the test shell await configManager.setValue('defaultShell', testShell); // Get config multiple times to ensure it persists const config1 = await configManager.getConfig(); const config2 = await configManager.getConfig(); assert.strictEqual(config1.defaultShell, testShell, 'Configuration should persist on first read'); assert.strictEqual(config2.defaultShell, testShell, 'Configuration should persist on second read'); assert.strictEqual(config1.defaultShell, config2.defaultShell, 'Configuration should be consistent across reads'); console.log(`✓ Configuration persists correctly: ${config1.defaultShell}`); console.log('✓ Test 6 passed: configuration persistence works correctly'); } /** * Main test function */ async function runDefaultShellTests() { console.log('=== defaultShell Configuration Tests ===\n'); console.log(`Platform: ${os.platform()}`); // Test 1: Setting defaultShell to /bin/sh await testDefaultShellSh(); // Test 2: Setting defaultShell to /bin/bash await testDefaultShellBash(); // Test 3: Setting defaultShell to cmd (Windows) await testDefaultShellCmd(); // Test 4: Setting defaultShell to pwsh (PowerShell Core) await testDefaultShellPwsh(); // Test 5: Testing shell switching await testShellSwitching(); // Test 6: Testing configuration persistence await testConfigurationPersistence(); console.log('\n✅ All defaultShell tests completed!'); } // Export the main test function export default async function runTests() { let originalConfig; try { originalConfig = await setup(); await runDefaultShellTests(); } catch (error) { console.error('❌ Test failed:', error.message); console.error('Full error:', error); return false; } finally { if (originalConfig) { await teardown(originalConfig); } } return true; } // If this file is run directly (not imported), execute the test if (import.meta.url === `file://${process.argv[1]}`) { runTests().catch(error => { console.error('❌ Unhandled error:', error); process.exit(1); }); }
wonderwhy-er/DesktopCommanderMCP
5,467
This is MCP server for Claude that gives it terminal control, file system search and diff file editing capabilities
TypeScript
wonderwhy-er
Eduard Ruzga
test/test-directory-creation.js
JavaScript
/** * Test script for directory creation functionality * * This script tests the create_directory functionality by: * 1. Testing creation of a directory with an existing parent * 2. Testing creation of a directory with a non-existent parent path * 3. Testing nested directory creation */ // Import the filesystem module and assert for testing import { createDirectory } from '../dist/tools/filesystem.js'; import { configManager } from '../dist/config-manager.js'; import fs from 'fs/promises'; import path from 'path'; import { fileURLToPath } from 'url'; import assert from 'assert'; // Get directory name const __filename = fileURLToPath(import.meta.url); const __dirname = path.dirname(__filename); // Define test paths const BASE_TEST_DIR = path.join(__dirname, 'test_directories'); const SIMPLE_DIR = path.join(BASE_TEST_DIR, 'simple_dir'); const NONEXISTENT_PARENT_DIR = path.join(BASE_TEST_DIR, 'nonexistent', 'test_dir'); const NESTED_DIR = path.join(BASE_TEST_DIR, 'nested', 'path', 'structure'); /** * Helper function to clean up test directories */ async function cleanupTestDirectories() { try { console.log('Cleaning up test directories...'); await fs.rm(BASE_TEST_DIR, { recursive: true, force: true }); console.log('Cleanup complete.'); } catch (error) { // Ignore errors if directory doesn't exist if (error.code !== 'ENOENT') { console.error('Error during cleanup:', error); } } } /** * Setup function to prepare the test environment */ async function setup() { // Clean up before tests await cleanupTestDirectories(); // Create base test directory await fs.mkdir(BASE_TEST_DIR, { recursive: true }); console.log(`✓ Setup: created base test directory: ${BASE_TEST_DIR}`); // Save original config to restore later const originalConfig = await configManager.getConfig(); // Set allowed directories to include our test directory await configManager.setValue('allowedDirectories', [BASE_TEST_DIR]); console.log(`✓ Setup: set allowed directories to include: ${BASE_TEST_DIR}`); return originalConfig; } /** * Teardown function to clean up after tests */ async function teardown(originalConfig) { if (originalConfig) { // Restore original config await configManager.updateConfig(originalConfig); } await cleanupTestDirectories(); console.log('✓ Teardown: test directories cleaned up'); } /** * Test function for directory creation */ async function testDirectoryCreation() { console.log('=== Directory Creation Tests ===\n'); // Test 1: Create directory with existing parent console.log('\nTest 1: Create directory with existing parent'); await createDirectory(SIMPLE_DIR); // Test 2: Create directory with non-existent parent console.log('\nTest 2: Create directory with non-existent parent'); await createDirectory(NONEXISTENT_PARENT_DIR); // Test 3: Create nested directory structure console.log('\nTest 3: Create nested directory structure'); await createDirectory(NESTED_DIR); // Verify directories were created using assertions console.log('\nVerifying directory creation:'); for (const dir of [SIMPLE_DIR, NONEXISTENT_PARENT_DIR, NESTED_DIR]) { const stats = await fs.stat(dir); assert.ok(stats.isDirectory(), `Directory should exist and be a directory: ${dir}`); console.log(`✓ Verified: ${dir} exists and is a directory`); } console.log('\n✅ All tests passed!'); } // Export the main test function export default async function runTests() { let originalConfig; try { originalConfig = await setup(); await testDirectoryCreation(); } catch (error) { console.error('❌ Test failed:', error.message); return false; } finally { if (originalConfig) { await teardown(originalConfig); } } return true; } // If this file is run directly (not imported), execute the test if (import.meta.url === `file://${process.argv[1]}`) { runTests().catch(error => { console.error('❌ Unhandled error:', error); process.exit(1); }); }
wonderwhy-er/DesktopCommanderMCP
5,467
This is MCP server for Claude that gives it terminal control, file system search and diff file editing capabilities
TypeScript
wonderwhy-er
Eduard Ruzga
test/test-edit-block-line-endings.js
JavaScript
/** * Test script for edit_block functionality with different line endings * * This script tests how edit_block handles files with different line ending styles: * 1. Files with LF line endings (Unix/Linux) * 2. Files with CRLF line endings (Windows) * 3. Files with CR line endings (Old Mac) * 4. Files with mixed line endings * 5. Edge cases and corner scenarios */ import { configManager } from '../dist/config-manager.js'; import fs from 'fs/promises'; import path from 'path'; import { fileURLToPath } from 'url'; import assert from 'assert'; import { handleEditBlock } from '../dist/handlers/edit-search-handlers.js'; // Get directory name const __filename = fileURLToPath(import.meta.url); const __dirname = path.dirname(__filename); // Define test directory and files const TEST_DIR = path.join(__dirname, 'test_edit_line_endings'); const LF_FILE = path.join(TEST_DIR, 'file_with_lf.txt'); const CRLF_FILE = path.join(TEST_DIR, 'file_with_crlf.txt'); const CR_FILE = path.join(TEST_DIR, 'file_with_cr.txt'); const MIXED_FILE = path.join(TEST_DIR, 'file_with_mixed.txt'); /** * Setup function to prepare the test environment */ async function setup() { // Create test directory await fs.mkdir(TEST_DIR, { recursive: true }); // Create test files with different line endings // LF file (Unix/Linux) const lfContent = `First line with LF Second line with LF Target line to replace Fourth line with LF Fifth line with LF`; await fs.writeFile(LF_FILE, lfContent, { encoding: 'utf8' }); // CRLF file (Windows) const crlfContent = `First line with CRLF\r\nSecond line with CRLF\r\nTarget line to replace\r\nFourth line with CRLF\r\nFifth line with CRLF\r\n`; await fs.writeFile(CRLF_FILE, crlfContent); // CR file (Old Mac) const crContent = `First line with CR\rSecond line with CR\rTarget line to replace\rFourth line with CR\rFifth line with CR\r`; await fs.writeFile(CR_FILE, crContent); // Mixed line endings file const mixedContent = `First line with LF\nSecond line with CRLF\r\nTarget line to replace\nFourth line with CR\rFifth line with LF\n`; await fs.writeFile(MIXED_FILE, mixedContent); console.log(`✓ Setup: created test directory and files`); // Save original config to restore later const originalConfig = await configManager.getConfig(); return originalConfig; } /** * Teardown function to clean up after tests */ async function teardown(originalConfig) { // Reset configuration to original await configManager.updateConfig(originalConfig); // Clean up test directory await fs.rm(TEST_DIR, { recursive: true, force: true }); console.log('✓ Teardown: test directory cleaned up and config restored'); } /** * Helper function to read file as raw buffer to preserve binary line endings */ async function readRawFile(filePath) { const buffer = await fs.readFile(filePath); return buffer.toString('binary'); } /** * Test edit_block with LF line endings */ async function testLFLineEndings() { console.log('\nTest 1: LF line endings (Unix/Linux)'); try { // Allow access to test directory await configManager.setValue('allowedDirectories', [TEST_DIR]); // Replace a line using LF line endings in search string const result = await handleEditBlock({ file_path: LF_FILE, old_string: 'Target line to replace', new_string: 'REPLACED LINE WITH LF', expected_replacements: 1 }); // Check that the operation succeeded assert.strictEqual(result.content[0].type, 'text', 'Result should be text'); assert.ok( result.content[0].text.includes('Successfully applied 1 edit'), 'Should report success with the LF edit' ); // Verify file still has LF line endings const rawContent = await readRawFile(LF_FILE); assert.ok(!rawContent.includes('\r\n'), 'File should not contain CRLF'); assert.ok(!rawContent.includes('\r'), 'File should not contain CR'); assert.ok(rawContent.includes('\n'), 'File should contain LF'); console.log('✓ LF line endings test passed'); } catch (error) { console.error('❌ Test failed:', error); throw error; } } /** * Test edit_block with CRLF line endings */ async function testCRLFLineEndings() { console.log('\nTest 2: CRLF line endings (Windows)'); try { // Replace a line in CRLF file - try with LF search string first let result = await handleEditBlock({ file_path: CRLF_FILE, old_string: 'Target line to replace', new_string: 'REPLACED LINE WITH CRLF', expected_replacements: 1 }); // Check that the operation succeeded assert.strictEqual(result.content[0].type, 'text', 'Result should be text'); assert.ok( result.content[0].text.includes('Successfully applied 1 edit'), 'Should report success with the CRLF edit' ); // Verify file still has CRLF line endings const rawContent = await readRawFile(CRLF_FILE); assert.ok(rawContent.includes('\r\n'), 'File should contain CRLF'); // Test with multi-line replacement including line endings result = await handleEditBlock({ file_path: CRLF_FILE, old_string: 'Second line with CRLF\nREPLACED LINE WITH CRLF', new_string: 'New second line\nAnother replacement', expected_replacements: 1 }); // Check that the operation succeeded assert.strictEqual(result.content[0].type, 'text', 'Result should be text'); assert.ok( result.content[0].text.includes('Successfully applied 1 edit'), 'Should report success with the multi-line CRLF edit' ); console.log('✓ CRLF line endings test passed'); } catch (error) { console.error('❌ Test failed:', error); throw error; } } /** * Test edit_block with CR line endings */ async function testCRLineEndings() { console.log('\nTest 3: CR line endings (Old Mac)'); try { // Replace a line using CR line endings const result = await handleEditBlock({ file_path: CR_FILE, old_string: 'Target line to replace', new_string: 'REPLACED LINE WITH CR', expected_replacements: 1 }); // Check that the operation succeeded assert.strictEqual(result.content[0].type, 'text', 'Result should be text'); assert.ok( result.content[0].text.includes('Successfully applied 1 edit'), 'Should report success with the CR edit' ); // Verify file still has CR line endings const rawContent = await readRawFile(CR_FILE); assert.ok(!rawContent.includes('\n'), 'File should not contain LF'); assert.ok(!rawContent.includes('\r\n'), 'File should not contain CRLF'); assert.ok(rawContent.includes('\r'), 'File should contain CR'); console.log('✓ CR line endings test passed'); } catch (error) { console.error('❌ Test failed:', error); throw error; } } /** * Test edit_block with mixed line endings */ async function testMixedLineEndings() { console.log('\nTest 4: Mixed line endings'); try { // Replace a line in file with mixed line endings const result = await handleEditBlock({ file_path: MIXED_FILE, old_string: 'Target line to replace', new_string: 'REPLACED LINE IN MIXED FILE', expected_replacements: 1 }); // Check that the operation succeeded assert.strictEqual(result.content[0].type, 'text', 'Result should be text'); assert.ok( result.content[0].text.includes('Successfully applied 1 edit'), 'Should report success with the mixed line ending edit' ); // Verify file preserves mixed line endings const rawContent = await readRawFile(MIXED_FILE); assert.ok(rawContent.includes('\n'), 'File should contain LF'); assert.ok(rawContent.includes('\r\n'), 'File should contain CRLF'); assert.ok(rawContent.match(/\r[^\n]/), 'File should contain standalone CR'); console.log('✓ Mixed line endings test passed'); } catch (error) { console.error('❌ Test failed:', error); throw error; } } /** * Test context-aware replacement with different line endings */ async function testContextAwareReplacement() { console.log('\nTest 5: Context-aware replacement across line ending types'); try { // Re-create CRLF file (it was modified in previous tests) const crlfContent = `First line with CRLF\r\nSecond line with CRLF\r\nREPLACED LINE WITH CRLF\r\nFourth line with CRLF\r\nFifth line with CRLF\r\n`; await fs.writeFile(CRLF_FILE, crlfContent); // Test multi-line replacement with CRLF let result = await handleEditBlock({ file_path: CRLF_FILE, old_string: 'Second line with CRLF\nREPLACED LINE WITH CRLF', new_string: 'Multi-line replacement\nWith new content', expected_replacements: 1 }); assert.ok( result.content[0].text.includes('Successfully applied 1 edit'), 'Should handle multi-line replacement in CRLF file' ); // Re-create LF file (it was modified in previous tests) const lfContent = `First line with LF Second line with LF REPLACED LINE WITH LF Fourth line with LF Fifth line with LF`; await fs.writeFile(LF_FILE, lfContent, { encoding: 'utf8' }); // Test multi-line replacement with LF result = await handleEditBlock({ file_path: LF_FILE, old_string: 'Second line with LF\nREPLACED LINE WITH LF', new_string: 'Another multi-line replacement\nWith LF endings', expected_replacements: 1 }); assert.ok( result.content[0].text.includes('Successfully applied 1 edit'), 'Should handle multi-line replacement in LF file' ); console.log('✓ Context-aware replacement test passed'); } catch (error) { console.error('❌ Test failed:', error); throw error; } } /** * Test performance with large files of different line ending types */ async function testLargeFilePerformance() { console.log('\nTest 6: Performance with large files'); const LARGE_FILE_LF = path.join(TEST_DIR, 'large_lf.txt'); const LARGE_FILE_CRLF = path.join(TEST_DIR, 'large_crlf.txt'); try { // Create large test files (but not too large to exceed line limit) // With line-based reading, we need to ensure we don't exceed the line limit const lines = Array(800).fill('This is a line in a large file.\n'); // Reduced from 2000 to 800 lines[400] = 'TARGET LINE TO FIND AND REPLACE\n'; // Adjusted position // LF version await fs.writeFile(LARGE_FILE_LF, lines.join('')); // CRLF version const crlfLines = lines.map(line => line.replace('\n', '\r\n')); await fs.writeFile(LARGE_FILE_CRLF, crlfLines.join('')); // Test LF file const startLF = Date.now(); let result = await handleEditBlock({ file_path: LARGE_FILE_LF, old_string: 'TARGET LINE TO FIND AND REPLACE', new_string: 'REPLACED TARGET LINE IN LF FILE', expected_replacements: 1 }); const timeLF = Date.now() - startLF; assert.ok( result.content[0].text.includes('Successfully applied 1 edit'), 'Should handle large LF file' ); // Test CRLF file const startCRLF = Date.now(); result = await handleEditBlock({ file_path: LARGE_FILE_CRLF, old_string: 'TARGET LINE TO FIND AND REPLACE', new_string: 'REPLACED TARGET LINE IN CRLF FILE', expected_replacements: 1 }); const timeCRLF = Date.now() - startCRLF; assert.ok( result.content[0].text.includes('Successfully applied 1 edit'), 'Should handle large CRLF file' ); console.log(`✓ Performance test passed (LF: ${timeLF}ms, CRLF: ${timeCRLF}ms)`); } catch (error) { console.error('❌ Test failed:', error); throw error; } } /** * Test edge cases */ async function testEdgeCases() { console.log('\nTest 7: Edge cases'); const EMPTY_FILE = path.join(TEST_DIR, 'empty.txt'); const SINGLE_LINE_FILE = path.join(TEST_DIR, 'single_line.txt'); const NO_ENDING_FILE = path.join(TEST_DIR, 'no_ending.txt'); try { // Create edge case files await fs.writeFile(EMPTY_FILE, ''); await fs.writeFile(SINGLE_LINE_FILE, 'Only one line with no ending'); await fs.writeFile(NO_ENDING_FILE, 'Two lines\nBut no ending'); // Test empty file let result = await handleEditBlock({ file_path: EMPTY_FILE, old_string: 'non-existent', new_string: 'replacement', expected_replacements: 1 }); assert.ok( result.content[0].text.includes('Search content not found'), 'Should handle empty file correctly' ); // Test single line file result = await handleEditBlock({ file_path: SINGLE_LINE_FILE, old_string: 'Only one line with no ending', new_string: 'Replaced single line', expected_replacements: 1 }); assert.ok( result.content[0].text.includes('Successfully applied 1 edit'), 'Should handle single line file' ); // Test file without trailing line ending result = await handleEditBlock({ file_path: NO_ENDING_FILE, old_string: 'But no ending', new_string: 'With replacement', expected_replacements: 1 }); assert.ok( result.content[0].text.includes('Successfully applied 1 edit'), 'Should handle file without trailing line ending' ); console.log('✓ Edge cases test passed'); } catch (error) { console.error('❌ Test failed:', error); throw error; } } /** * Main test function */ async function runEditBlockLineEndingTests() { console.log('=== edit_block Line Ending Tests ===\n'); // Test 1: LF line endings await testLFLineEndings(); // Test 2: CRLF line endings await testCRLFLineEndings(); // Test 3: CR line endings await testCRLineEndings(); // Test 4: Mixed line endings await testMixedLineEndings(); // Test 5: Context-aware replacement await testContextAwareReplacement(); // Test 6: Performance with large files await testLargeFilePerformance(); // Test 7: Edge cases await testEdgeCases(); console.log('\n✅ All edit_block line ending tests passed!'); } // Export the main test function export default async function runTests() { let originalConfig; try { originalConfig = await setup(); await runEditBlockLineEndingTests(); return true; } catch (error) { console.error('❌ Test failed:', error.message); return false; } finally { if (originalConfig) { await teardown(originalConfig); } } } // If this file is run directly (not imported), execute the test if (import.meta.url === `file://${process.argv[1]}`) { runTests().then(success => { process.exit(success ? 0 : 1); }).catch(error => { console.error('❌ Unhandled error:', error); process.exit(1); }); }
wonderwhy-er/DesktopCommanderMCP
5,467
This is MCP server for Claude that gives it terminal control, file system search and diff file editing capabilities
TypeScript
wonderwhy-er
Eduard Ruzga
test/test-edit-block-occurrences.js
JavaScript
/** * Test script for edit_block functionality with multiple occurrences * * This script tests how edit_block handles multiple occurrences: * 1. Testing failure when more occurrences than expected * 2. Testing failure when fewer occurrences than expected * 3. Testing success when exactly the right number of occurrences * 4. Testing context-specific replacements * 5. Testing handling of non-existent patterns * 6. Testing handling of empty search strings */ import { configManager } from '../dist/config-manager.js'; import fs from 'fs/promises'; import path from 'path'; import { fileURLToPath } from 'url'; import assert from 'assert'; import { handleEditBlock } from '../dist/handlers/edit-search-handlers.js'; // Get directory name const __filename = fileURLToPath(import.meta.url); const __dirname = path.dirname(__filename); // Define test directory and files const TEST_DIR = path.join(__dirname, 'test_edit_occurrences'); const MULTI_OCCURRENCE_FILE = path.join(TEST_DIR, 'multiple_occurrences.txt'); const CONTEXT_TEST_FILE = path.join(TEST_DIR, 'context_test.txt'); /** * Setup function to prepare the test environment */ async function setup() { // Create test directory await fs.mkdir(TEST_DIR, { recursive: true }); // Create test files await fs.writeFile(MULTI_OCCURRENCE_FILE, `This is a repeating line. This is a unique line. This is a repeating line. This is another unique line. This is a repeating line. One more unique line. This is a repeating line.`); await fs.writeFile(CONTEXT_TEST_FILE, `Header section This is a target line. End of header section Main content section This is a target line. More content here This is a target line. End of main content Footer section This is a target line. End of footer`); console.log(`✓ Setup: created test directory and files`); // Save original config to restore later const originalConfig = await configManager.getConfig(); return originalConfig; } /** * Teardown function to clean up after tests */ async function teardown(originalConfig) { // Reset configuration to original await configManager.updateConfig(originalConfig); // Clean up test directory await fs.rm(TEST_DIR, { recursive: true, force: true }); console.log('✓ Teardown: test directory cleaned up and config restored'); } /** * Test case when there are more occurrences than expected */ async function testMoreOccurrencesThanExpected() { console.log('\nTest 1: More occurrences than expected'); try { // Allow access to test directory await configManager.setValue('allowedDirectories', [TEST_DIR]); // Try to replace all occurrences but only specify 1 expected replacement const result = await handleEditBlock({ file_path: MULTI_OCCURRENCE_FILE, old_string: 'This is a repeating line.', new_string: 'This line has been changed.', expected_replacements: 1 }); // Check that we got an error about the number of occurrences assert.strictEqual(result.content[0].type, 'text', 'Result should be text'); assert.ok( result.content[0].text.includes('Expected 1 occurrences but found 4'), 'Should report the correct number of occurrences' ); console.log('✓ Test correctly failed with more occurrences than expected'); } catch (error) { console.error('❌ Test failed:', error); throw error; } } /** * Test case when there are fewer occurrences than expected */ async function testFewerOccurrencesThanExpected() { console.log('\nTest 2: Fewer occurrences than expected'); try { // Try to replace with more expected replacements than actual occurrences const result = await handleEditBlock({ file_path: MULTI_OCCURRENCE_FILE, old_string: 'This is another unique line.', new_string: 'This unique line has been modified.', expected_replacements: 3 }); // Check that we got an error about the number of occurrences assert.strictEqual(result.content[0].type, 'text', 'Result should be text'); assert.ok( result.content[0].text.includes('Expected 3 occurrences but found 1'), 'Should report the correct number of occurrences' ); console.log('✓ Test correctly failed with fewer occurrences than expected'); } catch (error) { console.error('❌ Test failed:', error); throw error; } } /** * Test case with exactly the right number of occurrences */ async function testExactNumberOfOccurrences() { console.log('\nTest 3: Exactly the right number of occurrences'); try { // Replace with correct number of expected replacements const result = await handleEditBlock({ file_path: MULTI_OCCURRENCE_FILE, old_string: 'This is a repeating line.', new_string: 'This line has been replaced correctly.', expected_replacements: 4 }); // Check that the operation succeeded assert.strictEqual(result.content[0].type, 'text', 'Result should be text'); assert.ok( result.content[0].text.includes('Successfully applied 4 edits'), 'Should report success with the correct number of edits' ); // Verify the file content const fileContent = await fs.readFile(MULTI_OCCURRENCE_FILE, 'utf8'); const expectedContent = `This line has been replaced correctly. This is a unique line. This line has been replaced correctly. This is another unique line. This line has been replaced correctly. One more unique line. This line has been replaced correctly.`; assert.strictEqual(fileContent, expectedContent, 'File content should be updated correctly'); console.log('✓ Test succeeded with exact number of occurrences'); } catch (error) { console.error('❌ Test failed:', error); throw error; } } /** * Test context-specific replacements to target specific occurrences */ async function testContextSpecificReplacements() { console.log('\nTest 4: Context-specific replacements'); try { // Target the occurrence in the header section using context let result = await handleEditBlock({ file_path: CONTEXT_TEST_FILE, old_string: `Header section This is a target line.`, new_string: `Header section This is a MODIFIED target line in the header.`, expected_replacements: 1 }); // Check that the operation succeeded assert.strictEqual(result.content[0].type, 'text', 'Result should be text'); assert.ok( result.content[0].text.includes('Successfully applied 1 edit'), 'Should report success with the header edit' ); // Target the occurrence in the footer section using context result = await handleEditBlock({ file_path: CONTEXT_TEST_FILE, old_string: `Footer section This is a target line.`, new_string: `Footer section This is a MODIFIED target line in the footer.`, expected_replacements: 1 }); // Check that the operation succeeded assert.strictEqual(result.content[0].type, 'text', 'Result should be text'); assert.ok( result.content[0].text.includes('Successfully applied 1 edit'), 'Should report success with the footer edit' ); // Verify the file content const fileContent = await fs.readFile(CONTEXT_TEST_FILE, 'utf8'); const expectedContent = `Header section This is a MODIFIED target line in the header. End of header section Main content section This is a target line. More content here This is a target line. End of main content Footer section This is a MODIFIED target line in the footer. End of footer`; assert.strictEqual(fileContent, expectedContent, 'File content should be updated correctly'); console.log('✓ Test succeeded with context-specific replacements'); } catch (error) { console.error('❌ Test failed:', error); throw error; } } /** * Test case for string pattern that doesn't exist */ async function testNonExistentPattern() { console.log('\nTest 5: Non-existent pattern'); try { // Try to replace a pattern that doesn't exist const result = await handleEditBlock({ file_path: CONTEXT_TEST_FILE, old_string: 'This pattern does not exist in the file.', new_string: 'This replacement will not be applied.', expected_replacements: 1 }); // Check that we got an error about not finding the content assert.strictEqual(result.content[0].type, 'text', 'Result should be text'); assert.ok( result.content[0].text.includes('Search content not found'), 'Should report that the search content was not found' ); console.log('✓ Test correctly handled non-existent pattern'); } catch (error) { console.error('❌ Test failed:', error); throw error; } } /** * Test case for empty search string */ async function testEmptySearchString() { console.log('\nTest 6: Empty search string'); try { // Try to use an empty search string const result = await handleEditBlock({ file_path: CONTEXT_TEST_FILE, old_string: '', new_string: 'This replacement should not be applied.', expected_replacements: 1 }); // Check that we got the appropriate error message assert.strictEqual(result.content[0].type, 'text', 'Result should be text'); assert.ok( result.content[0].text.includes('Empty search strings are not allowed'), 'Should report that empty search strings are not allowed' ); console.log('✓ Test correctly rejected empty search string'); } catch (error) { console.error('❌ Test failed:', error); throw error; } } /** * Main test function */ async function runEditBlockOccurrencesTests() { console.log('=== edit_block Multiple Occurrences Tests ===\n'); // Test 1: More occurrences than expected await testMoreOccurrencesThanExpected(); // Test 2: Fewer occurrences than expected await testFewerOccurrencesThanExpected(); // Test 3: Exactly the right number of occurrences await testExactNumberOfOccurrences(); // Test 4: Context-specific replacements await testContextSpecificReplacements(); // Test 5: Non-existent pattern await testNonExistentPattern(); // Test 6: Empty search string await testEmptySearchString(); console.log('\n✅ All edit_block multiple occurrences tests passed!'); } // Export the main test function export default async function runTests() { let originalConfig; try { originalConfig = await setup(); await runEditBlockOccurrencesTests(); } catch (error) { console.error('❌ Test failed:', error.message); return false; } finally { if (originalConfig) { await teardown(originalConfig); } } return true; } // If this file is run directly (not imported), execute the test if (import.meta.url === `file://${process.argv[1]}`) { runTests().catch(error => { console.error('❌ Unhandled error:', error); process.exit(1); }); }
wonderwhy-er/DesktopCommanderMCP
5,467
This is MCP server for Claude that gives it terminal control, file system search and diff file editing capabilities
TypeScript
wonderwhy-er
Eduard Ruzga
test/test-enhanced-repl.js
JavaScript
import assert from 'assert'; import { execSync } from 'child_process'; import { startProcess, readProcessOutput, forceTerminate, interactWithProcess } from '../dist/tools/improved-process-tools.js'; /** * Determines the correct python command to use * @returns {string} 'python3' or 'python' */ function getPythonCommand() { try { // Prefer python3 if available execSync('command -v python3', { stdio: 'ignore' }); return 'python3'; } catch (e) { // Fallback to python try { execSync('command -v python', { stdio: 'ignore' }); return 'python'; } catch (error) { throw new Error('Neither python3 nor python command is available in the PATH'); } } } /** * Test enhanced REPL functionality */ async function testEnhancedREPL() { console.log('Testing enhanced REPL functionality...'); const pythonCommand = getPythonCommand(); console.log(`Using python command: ${pythonCommand}`); // Start Python in interactive mode console.log('Starting Python REPL...'); const result = await startProcess({ command: `${pythonCommand} -i`, timeout_ms: 10000, shell: '/bin/bash' }); console.log('Result from start_process:', result); // Extract PID from the result text const pidMatch = result.content[0].text.match(/Process started with PID (\d+)/); const pid = pidMatch ? parseInt(pidMatch[1]) : null; if (!pid) { console.error("Failed to get PID from Python process"); return false; } console.log(`Started Python session with PID: ${pid}`); // Test read_process_output with timeout console.log('Testing read_process_output with timeout...'); const initialOutput = await readProcessOutput({ pid, timeout_ms: 2000 }); console.log('Initial Python prompt:', initialOutput.content[0].text); // Test interact_with_process with wait_for_prompt console.log('Testing interact_with_process with wait_for_prompt...'); const inputResult = await interactWithProcess({ pid, input: 'print("Hello from Python with wait!")', wait_for_prompt: true, timeout_ms: 5000 }); console.log('Python output with wait_for_prompt:', inputResult.content[0].text); // Check that the output contains the expected text assert(inputResult.content[0].text.includes('Hello from Python with wait!'), 'Output should contain the printed message'); // Test interact_with_process without wait_for_prompt console.log('Testing interact_with_process without wait_for_prompt...'); await interactWithProcess({ pid, input: 'print("Hello from Python without wait!")', wait_for_prompt: false }); // Wait a moment for Python to process await new Promise(resolve => setTimeout(resolve, 1000)); // Read the output const output = await readProcessOutput({ pid }); console.log('Python output without wait_for_prompt:', output.content[0].text); // Check that the output contains the expected text assert(output.content[0].text.includes('Hello from Python without wait!'), 'Output should contain the printed message'); // Test multi-line code with wait_for_prompt console.log('Testing multi-line code with wait_for_prompt...'); const multilineCode = `def greet(name): return f"Hello, {name}!" for i in range(3): print(greet(f"Guest {i+1}"))`; // Send the multi-line code await interactWithProcess({ pid, input: multilineCode, wait_for_prompt: true, timeout_ms: 5000 }); // Send an empty line to complete and execute the block const multilineResult = await interactWithProcess({ pid, input: '', wait_for_prompt: true, timeout_ms: 5000 }); console.log('Python multi-line output with wait_for_prompt:', multilineResult.content[0].text); // Check that the output contains all three greetings assert(multilineResult.content[0].text.includes('Hello, Guest 1!'), 'Output should contain greeting for Guest 1'); assert(multilineResult.content[0].text.includes('Hello, Guest 2!'), 'Output should contain greeting for Guest 2'); assert(multilineResult.content[0].text.includes('Hello, Guest 3!'), 'Output should contain greeting for Guest 3'); // Terminate the session console.log("Terminating session..."); await forceTerminate({ pid }); console.log('Python session terminated'); return true; } // Run the test testEnhancedREPL() .then(success => { console.log(`Enhanced REPL test ${success ? 'PASSED' : 'FAILED'}`); process.exit(success ? 0 : 1); }) .catch(error => { console.error('Test error:', error); process.exit(1); });
wonderwhy-er/DesktopCommanderMCP
5,467
This is MCP server for Claude that gives it terminal control, file system search and diff file editing capabilities
TypeScript
wonderwhy-er
Eduard Ruzga
test/test-error-sanitization.js
JavaScript
import assert from 'assert'; import path from 'path'; // Local implementation of sanitizeError for testing // This mirrors the implementation in src/utils/capture.ts but avoids import issues // when running tests. The actual sanitization logic is identical. // // NOTE: If you update the sanitizeError function in src/utils/capture.ts, // be sure to update this implementation as well to keep tests accurate. function sanitizeError(error) { let errorMessage = ''; let errorCode = undefined; if (error instanceof Error) { // Extract just the error name and message without stack trace errorMessage = error.name + ': ' + error.message; // Extract error code if available (common in Node.js errors) if ('code' in error) { errorCode = error.code; } } else if (typeof error === 'string') { errorMessage = error; } else if (error && error.message) { errorMessage = error.message; } else { errorMessage = 'Unknown error'; } // Remove any file paths using regex // This pattern matches common path formats including Windows and Unix-style paths errorMessage = errorMessage.replace(/(?:\/|\\)[\w\d_.-\/\\]+/g, '[PATH]'); errorMessage = errorMessage.replace(/[A-Za-z]:\\[\w\d_.-\/\\]+/g, '[PATH]'); return { message: errorMessage, code: errorCode }; } // Helper function to run a test and report results const runTest = (name, testFn) => { try { testFn(); console.log(`✅ Test passed: ${name}`); return true; } catch (error) { console.error(`❌ Test failed: ${name}`); console.error(error); return false; } }; // Main test function that will be exported const runAllTests = async () => { let allPassed = true; // Test sanitization of error objects with file paths allPassed = runTest('sanitizeError - Error object with path', () => { const mockError = new Error('Failed to read file at /Users/username/sensitive/path/file.txt'); const sanitized = sanitizeError(mockError); assert(!sanitized.message.includes('/Users/username/sensitive/path/file.txt'), 'Error message should not contain file path'); assert(sanitized.message.includes('[PATH]'), 'Error message should replace path with [PATH]'); }) && allPassed; // Test sanitization of Windows-style paths allPassed = runTest('sanitizeError - Windows path', () => { const mockError = new Error('Failed to read file at C:\\Users\\username\\Documents\\file.txt'); const sanitized = sanitizeError(mockError); assert(!sanitized.message.includes('C:\\Users\\username\\Documents\\file.txt'), 'Error message should not contain Windows file path'); assert(sanitized.message.includes('[PATH]'), 'Error message should replace Windows path with [PATH]'); }) && allPassed; // Test sanitization of error with multiple paths allPassed = runTest('sanitizeError - Multiple paths', () => { const mockError = new Error('Failed to move file from /path/source.txt to /path/destination.txt'); const sanitized = sanitizeError(mockError); assert(!sanitized.message.includes('/path/source.txt'), 'Error message should not contain source path'); assert(!sanitized.message.includes('/path/destination.txt'), 'Error message should not contain destination path'); assert(sanitized.message.includes('[PATH]'), 'Error message should replace paths with [PATH]'); }) && allPassed; // Test sanitization of string errors allPassed = runTest('sanitizeError - String error', () => { const errorString = 'Cannot access /var/log/sensitive/data.log due to permissions'; const sanitized = sanitizeError(errorString); assert(!sanitized.message.includes('/var/log/sensitive/data.log'), 'String error should not contain file path'); assert(sanitized.message.includes('[PATH]'), 'String error should replace path with [PATH]'); }) && allPassed; // Test error code preservation allPassed = runTest('sanitizeError - Error code preservation', () => { const mockError = new Error('ENOENT: no such file or directory, open \'/path/to/file.txt\''); mockError.code = 'ENOENT'; const sanitized = sanitizeError(mockError); assert(sanitized.code === 'ENOENT', 'Error code should be preserved'); assert(!sanitized.message.includes('/path/to/file.txt'), 'Error message should not contain file path'); }) && allPassed; // Test path with special characters allPassed = runTest('sanitizeError - Path with special characters', () => { const mockError = new Error('Failed to process /path/with-special_chars/file!@#$%.txt'); const sanitized = sanitizeError(mockError); assert(!sanitized.message.includes('/path/with-special_chars/file!@#$%.txt'), 'Error message should sanitize paths with special characters'); }) && allPassed; // Test non-error input allPassed = runTest('sanitizeError - Non-error input', () => { const nonError = { custom: 'object' }; const sanitized = sanitizeError(nonError); assert(sanitized.message === 'Unknown error', 'Non-error objects should be handled gracefully'); }) && allPassed; // Test actual paths from the current environment allPassed = runTest('sanitizeError - Actual system paths', () => { const currentDir = process.cwd(); const homeDir = process.env.HOME || process.env.USERPROFILE; const mockError = new Error(`Failed to operate on ${currentDir} or ${homeDir}`); const sanitized = sanitizeError(mockError); assert(!sanitized.message.includes(currentDir), 'Error message should not contain current directory'); assert(!sanitized.message.includes(homeDir), 'Error message should not contain home directory'); }) && allPassed; // Integration test with capture function mock allPassed = runTest('Integration - capture with error object', () => { // Create a mock capture function to test integration const mockCapture = (event, properties) => { // Check that no file paths are in the properties const stringified = JSON.stringify(properties); const containsPaths = /(?:\/|\\)[\w\d_.-\/\\]+/.test(stringified) || /[A-Za-z]:\\[\w\d_.-\/\\]+/.test(stringified); assert(!containsPaths, 'Capture properties should not contain file paths'); return properties; }; // Create an error with file path const mockError = new Error(`Failed to read ${process.cwd()}/sensitive/file.txt`); // Manually sanitize for test const sanitizedError = sanitizeError(mockError).message; // Call the mock capture with the error const properties = mockCapture('test_event', { error: sanitizedError, operation: 'read_file' }); // Verify the error was properly processed assert(typeof properties.error === 'string', 'Error property should be a string'); assert(!properties.error.includes(process.cwd()), 'Error should not contain file path'); }) && allPassed; console.log('All error sanitization tests complete.'); return allPassed; }; // Run tests if this file is executed directly if (process.argv[1] === import.meta.url) { runAllTests().then(success => { process.exit(success ? 0 : 1); }); } // Export the test function for the test runner export default runAllTests;
wonderwhy-er/DesktopCommanderMCP
5,467
This is MCP server for Claude that gives it terminal control, file system search and diff file editing capabilities
TypeScript
wonderwhy-er
Eduard Ruzga
test/test-excel-files.js
JavaScript
/** * Test script for Excel file handling functionality * * This script tests the ExcelFileHandler implementation: * 1. Reading Excel files (basic, sheet selection, range, offset/length) * 2. Writing Excel files (single sheet, multiple sheets, append mode) * 3. Editing Excel files (range updates) * 4. Getting Excel file info (sheet metadata) * 5. File handler factory (correct handler selection) */ import { configManager } from '../dist/config-manager.js'; import fs from 'fs/promises'; import path from 'path'; import { fileURLToPath } from 'url'; import assert from 'assert'; import { readFile, writeFile, getFileInfo } from '../dist/tools/filesystem.js'; import { handleEditBlock } from '../dist/handlers/edit-search-handlers.js'; import { getFileHandler } from '../dist/utils/files/factory.js'; // Get directory name const __filename = fileURLToPath(import.meta.url); const __dirname = path.dirname(__filename); // Define test directory and files const TEST_DIR = path.join(__dirname, 'test_excel_files'); const BASIC_EXCEL = path.join(TEST_DIR, 'basic.xlsx'); const MULTI_SHEET_EXCEL = path.join(TEST_DIR, 'multi_sheet.xlsx'); const EDIT_EXCEL = path.join(TEST_DIR, 'edit_test.xlsx'); /** * Helper function to clean up test directories */ async function cleanupTestDirectories() { try { await fs.rm(TEST_DIR, { recursive: true, force: true }); } catch (error) { if (error.code !== 'ENOENT') { console.error('Error during cleanup:', error); } } } /** * Setup function to prepare the test environment */ async function setup() { // Clean up before tests (in case previous run left files) await cleanupTestDirectories(); // Create test directory await fs.mkdir(TEST_DIR, { recursive: true }); console.log(`✓ Setup: created test directory: ${TEST_DIR}`); // Save original config to restore later const originalConfig = await configManager.getConfig(); // Set allowed directories to include our test directory await configManager.setValue('allowedDirectories', [TEST_DIR]); console.log(`✓ Setup: set allowed directories`); return originalConfig; } /** * Teardown function to clean up after tests */ async function teardown(originalConfig) { // Reset configuration to original if (originalConfig) { await configManager.updateConfig(originalConfig); } await cleanupTestDirectories(); console.log('✓ Teardown: test directory cleaned up and config restored'); } /** * Test 1: File handler factory selects ExcelFileHandler for .xlsx files */ async function testFileHandlerFactory() { console.log('\n--- Test 1: File Handler Factory ---'); const handler = await getFileHandler('test.xlsx'); assert.ok(handler, 'Handler should be returned for .xlsx file'); assert.ok(handler.constructor.name === 'ExcelFileHandler', `Expected ExcelFileHandler but got ${handler.constructor.name}`); const txtHandler = await getFileHandler('test.txt'); assert.ok(txtHandler.constructor.name === 'TextFileHandler', `Expected TextFileHandler for .txt but got ${txtHandler.constructor.name}`); console.log('✓ File handler factory correctly selects handlers'); } /** * Test 2: Write and read basic Excel file */ async function testBasicWriteRead() { console.log('\n--- Test 2: Basic Write and Read ---'); // Write a simple Excel file const data = JSON.stringify([ ['Name', 'Age', 'City'], ['Alice', 30, 'New York'], ['Bob', 25, 'Los Angeles'], ['Charlie', 35, 'Chicago'] ]); await writeFile(BASIC_EXCEL, data); console.log('✓ Wrote basic Excel file'); // Read it back const result = await readFile(BASIC_EXCEL); assert.ok(result.content, 'Should have content'); // Excel handler returns application/json because content is JSON-formatted for LLM consumption assert.ok(result.mimeType === 'application/json', `Expected application/json mime type but got ${result.mimeType}`); // Verify content contains our data const content = result.content.toString(); assert.ok(content.includes('Name'), 'Content should include Name header'); assert.ok(content.includes('Alice'), 'Content should include Alice'); assert.ok(content.includes('Chicago'), 'Content should include Chicago'); console.log('✓ Read back Excel file with correct content'); } /** * Test 3: Write and read multi-sheet Excel file */ async function testMultiSheetWriteRead() { console.log('\n--- Test 3: Multi-Sheet Write and Read ---'); // Write multi-sheet Excel file const data = JSON.stringify({ 'Employees': [ ['Name', 'Department'], ['Alice', 'Engineering'], ['Bob', 'Sales'] ], 'Departments': [ ['Name', 'Budget'], ['Engineering', 100000], ['Sales', 50000] ] }); await writeFile(MULTI_SHEET_EXCEL, data); console.log('✓ Wrote multi-sheet Excel file'); // Read specific sheet by name const result1 = await readFile(MULTI_SHEET_EXCEL, { sheet: 'Employees' }); const content1 = result1.content.toString(); assert.ok(content1.includes('Alice'), 'Employees sheet should contain Alice'); assert.ok(content1.includes('Engineering'), 'Employees sheet should contain Engineering'); console.log('✓ Read Employees sheet by name'); // Read specific sheet by index const result2 = await readFile(MULTI_SHEET_EXCEL, { sheet: 1 }); const content2 = result2.content.toString(); assert.ok(content2.includes('Budget'), 'Departments sheet should contain Budget'); assert.ok(content2.includes('100000'), 'Departments sheet should contain 100000'); console.log('✓ Read Departments sheet by index'); } /** * Test 4: Read with range parameter */ async function testRangeRead() { console.log('\n--- Test 4: Range Read ---'); // Use the basic file we created const result = await readFile(BASIC_EXCEL, { sheet: 'Sheet1', range: 'A1:B2' }); const content = result.content.toString(); // Should only have first 2 rows and 2 columns assert.ok(content.includes('Name'), 'Range should include Name'); assert.ok(content.includes('Age'), 'Range should include Age'); assert.ok(content.includes('Alice'), 'Range should include Alice'); // City is column C, should NOT be included assert.ok(!content.includes('City') || content.split('City').length === 1, 'Range A1:B2 should not include City column'); console.log('✓ Range read returns correct subset of data'); } /** * Test 5: Read with offset and length */ async function testOffsetLengthRead() { console.log('\n--- Test 5: Offset and Length Read ---'); // Read with offset (skip header) const result = await readFile(BASIC_EXCEL, { offset: 1, length: 2 }); const content = result.content.toString(); // Should have rows 2-3 (Alice, Bob) but not header or Charlie assert.ok(content.includes('Alice'), 'Should include Alice (row 2)'); assert.ok(content.includes('Bob'), 'Should include Bob (row 3)'); console.log('✓ Offset and length read works correctly'); } /** * Test 6: Edit Excel range */ async function testEditRange() { console.log('\n--- Test 6: Edit Excel Range ---'); // Create a file to edit const data = JSON.stringify([ ['Product', 'Price'], ['Apple', 1.00], ['Banana', 0.50], ['Cherry', 2.00] ]); await writeFile(EDIT_EXCEL, data); console.log('✓ Created file for editing'); // Edit a cell using edit_block with range const editResult = await handleEditBlock({ file_path: EDIT_EXCEL, range: 'Sheet1!B2', content: [[1.50]] // Update Apple price }); assert.ok(!editResult.isError, `Edit should succeed: ${editResult.content?.[0]?.text}`); console.log('✓ Edit range succeeded'); // Verify the edit const readResult = await readFile(EDIT_EXCEL); const content = readResult.content.toString(); assert.ok(content.includes('1.5'), 'Price should be updated to 1.50'); console.log('✓ Edit was persisted correctly'); } /** * Test 7: Get Excel file info */ async function testGetFileInfo() { console.log('\n--- Test 7: Get File Info ---'); const info = await getFileInfo(MULTI_SHEET_EXCEL); assert.ok(info.isExcelFile, 'Should be marked as Excel file'); assert.ok(info.sheets, 'Should have sheets info'); assert.ok(Array.isArray(info.sheets), 'Sheets should be an array'); assert.strictEqual(info.sheets.length, 2, 'Should have 2 sheets'); // Check sheet details const sheetNames = info.sheets.map(s => s.name); assert.ok(sheetNames.includes('Employees'), 'Should have Employees sheet'); assert.ok(sheetNames.includes('Departments'), 'Should have Departments sheet'); // Check row/column counts const employeesSheet = info.sheets.find(s => s.name === 'Employees'); assert.ok(employeesSheet.rowCount >= 3, 'Employees sheet should have at least 3 rows'); assert.ok(employeesSheet.colCount >= 2, 'Employees sheet should have at least 2 columns'); console.log('✓ File info returns correct sheet metadata'); } /** * Test 8: Append mode */ async function testAppendMode() { console.log('\n--- Test 8: Append Mode ---'); // Create initial file const initialData = JSON.stringify([ ['Name', 'Score'], ['Alice', 100] ]); await writeFile(BASIC_EXCEL, initialData); // Append more data const appendData = JSON.stringify([ ['Bob', 95], ['Charlie', 88] ]); await writeFile(BASIC_EXCEL, appendData, 'append'); console.log('✓ Appended data to Excel file'); // Read and verify const result = await readFile(BASIC_EXCEL); const content = result.content.toString(); assert.ok(content.includes('Alice'), 'Should still have Alice'); assert.ok(content.includes('Bob'), 'Should have appended Bob'); assert.ok(content.includes('Charlie'), 'Should have appended Charlie'); console.log('✓ Append mode works correctly'); } /** * Test 9: Negative offset (read from end) */ async function testNegativeOffset() { console.log('\n--- Test 9: Negative Offset (Tail) ---'); // Create file with multiple rows const data = JSON.stringify([ ['Row', 'Value'], ['1', 'First'], ['2', 'Second'], ['3', 'Third'], ['4', 'Fourth'], ['5', 'Fifth'] ]); await writeFile(BASIC_EXCEL, data); // Read last 2 rows const result = await readFile(BASIC_EXCEL, { offset: -2 }); const content = result.content.toString(); assert.ok(content.includes('Fourth') || content.includes('Fifth'), 'Should include data from last rows'); console.log('✓ Negative offset reads from end'); } /** * Run all tests */ async function runAllTests() { console.log('=== Excel File Handling Tests ===\n'); await testFileHandlerFactory(); await testBasicWriteRead(); await testMultiSheetWriteRead(); await testRangeRead(); await testOffsetLengthRead(); await testEditRange(); await testGetFileInfo(); await testAppendMode(); await testNegativeOffset(); console.log('\n✅ All Excel tests passed!'); } // Export the main test function export default async function runTests() { let originalConfig; try { originalConfig = await setup(); await runAllTests(); } catch (error) { console.error('❌ Test failed:', error.message); console.error(error.stack); return false; } finally { if (originalConfig) { await teardown(originalConfig); } } return true; } // If this file is run directly, execute the test if (import.meta.url === `file://${process.argv[1]}`) { runTests().then(success => { process.exit(success ? 0 : 1); }).catch(error => { console.error('❌ Unhandled error:', error); process.exit(1); }); }
wonderwhy-er/DesktopCommanderMCP
5,467
This is MCP server for Claude that gives it terminal control, file system search and diff file editing capabilities
TypeScript
wonderwhy-er
Eduard Ruzga
test/test-file-handlers.js
JavaScript
/** * Test script for file handler system * * This script tests the file handler architecture: * 1. File handler factory returns correct handler types * 2. FileResult interface consistency * 3. ReadOptions interface usage * 4. Handler canHandle() method * 5. Text file handler basic operations * 6. Image file handler detection * 7. Binary file handler fallback */ import { configManager } from '../dist/config-manager.js'; import fs from 'fs/promises'; import path from 'path'; import { fileURLToPath } from 'url'; import assert from 'assert'; import { readFile, writeFile, getFileInfo } from '../dist/tools/filesystem.js'; import { getFileHandler } from '../dist/utils/files/factory.js'; import { handleReadFile } from '../dist/handlers/filesystem-handlers.js'; import { FILE_PREVIEW_RESOURCE_URI } from '../dist/ui/contracts.js'; // Get directory name const __filename = fileURLToPath(import.meta.url); const __dirname = path.dirname(__filename); // Define test directory and files const TEST_DIR = path.join(__dirname, 'test_file_handlers'); const TEXT_FILE = path.join(TEST_DIR, 'test.txt'); const JSON_FILE = path.join(TEST_DIR, 'test.json'); const MD_FILE = path.join(TEST_DIR, 'test.md'); const HTML_FILE = path.join(TEST_DIR, 'test.html'); const IMAGE_FILE = path.join(TEST_DIR, 'test.png'); /** * Helper function to clean up test directories */ async function cleanupTestDirectories() { try { await fs.rm(TEST_DIR, { recursive: true, force: true }); } catch (error) { if (error.code !== 'ENOENT') { console.error('Error during cleanup:', error); } } } /** * Setup function */ async function setup() { // Clean up before tests (in case previous run left files) await cleanupTestDirectories(); await fs.mkdir(TEST_DIR, { recursive: true }); console.log(`✓ Setup: created test directory: ${TEST_DIR}`); const originalConfig = await configManager.getConfig(); await configManager.setValue('allowedDirectories', [TEST_DIR]); return originalConfig; } /** * Teardown function * Always runs cleanup, restores config only if provided */ async function teardown(originalConfig) { // Always clean up test directories, even if setup failed try { await cleanupTestDirectories(); console.log('✓ Teardown: cleaned up test directories'); } catch (error) { console.error('Warning: Failed to clean up test directories:', error.message); } // Restore config only if we have the original if (originalConfig) { try { await configManager.updateConfig(originalConfig); console.log('✓ Teardown: restored config'); } catch (error) { console.error('Warning: Failed to restore config:', error.message); } } } /** * Test 1: Handler factory returns correct types */ async function testHandlerFactory() { console.log('\n--- Test 1: Handler Factory Types ---'); // Note: TextFileHandler.canHandle() returns true for all files, // so it catches most files before BinaryFileHandler. // BinaryFileHandler only handles files that fail binary detection at read time. const testCases = [ { file: 'test.xlsx', expected: 'ExcelFileHandler' }, { file: 'test.xls', expected: 'ExcelFileHandler' }, { file: 'test.xlsm', expected: 'ExcelFileHandler' }, { file: 'test.txt', expected: 'TextFileHandler' }, { file: 'test.js', expected: 'TextFileHandler' }, { file: 'test.json', expected: 'TextFileHandler' }, { file: 'test.md', expected: 'TextFileHandler' }, { file: 'test.png', expected: 'ImageFileHandler' }, { file: 'test.jpg', expected: 'ImageFileHandler' }, { file: 'test.jpeg', expected: 'ImageFileHandler' }, { file: 'test.gif', expected: 'ImageFileHandler' }, { file: 'test.webp', expected: 'ImageFileHandler' }, ]; for (const { file, expected } of testCases) { const handler = await getFileHandler(file); assert.strictEqual(handler.constructor.name, expected, `${file} should use ${expected} but got ${handler.constructor.name}`); } console.log('✓ All file types map to correct handlers'); } /** * Test 2: FileResult interface consistency */ async function testFileResultInterface() { console.log('\n--- Test 2: FileResult Interface ---'); // Create a text file await fs.writeFile(TEXT_FILE, 'Hello, World!\nLine 2\nLine 3'); const result = await readFile(TEXT_FILE); // Check FileResult structure assert.ok('content' in result, 'FileResult should have content'); assert.ok('mimeType' in result, 'FileResult should have mimeType'); assert.ok(result.content !== undefined, 'Content should not be undefined'); assert.ok(typeof result.mimeType === 'string', 'mimeType should be a string'); // metadata is optional but should be an object if present if (result.metadata) { assert.ok(typeof result.metadata === 'object', 'metadata should be an object'); } console.log('✓ FileResult interface is consistent'); } /** * Test 3: ReadOptions interface */ async function testReadOptionsInterface() { console.log('\n--- Test 3: ReadOptions Interface ---'); await fs.writeFile(TEXT_FILE, 'Line 1\nLine 2\nLine 3\nLine 4\nLine 5'); // Test offset option const result1 = await readFile(TEXT_FILE, { offset: 2 }); const content1 = result1.content.toString(); assert.ok(content1.includes('Line 3'), 'Offset should skip to line 3'); // Test length option const result2 = await readFile(TEXT_FILE, { offset: 0, length: 2 }); const content2 = result2.content.toString(); assert.ok(content2.includes('Line 1'), 'Should include Line 1'); assert.ok(content2.includes('Line 2'), 'Should include Line 2'); console.log('✓ ReadOptions work correctly'); } /** * Test 4: Handler canHandle method */ async function testCanHandle() { console.log('\n--- Test 4: canHandle Method ---'); const excelHandler = await getFileHandler('test.xlsx'); const textHandler = await getFileHandler('test.txt'); const imageHandler = await getFileHandler('test.png'); // Excel handler should handle xlsx assert.ok(excelHandler.canHandle('anything.xlsx'), 'Excel handler should handle .xlsx'); assert.ok(excelHandler.canHandle('file.xls'), 'Excel handler should handle .xls'); // Image handler should handle images assert.ok(imageHandler.canHandle('photo.png'), 'Image handler should handle .png'); assert.ok(imageHandler.canHandle('photo.jpg'), 'Image handler should handle .jpg'); assert.ok(imageHandler.canHandle('photo.jpeg'), 'Image handler should handle .jpeg'); // Text handler handles most things (fallback) assert.ok(textHandler.canHandle('file.txt'), 'Text handler should handle .txt'); console.log('✓ canHandle methods work correctly'); } /** * Test 5: Text handler read/write */ async function testTextHandler() { console.log('\n--- Test 5: Text Handler Operations ---'); const content = 'Test content\nWith multiple lines\nAnd special chars: äöü'; // Write await writeFile(TEXT_FILE, content); console.log('✓ Text write succeeded'); // Read const result = await readFile(TEXT_FILE); const readContent = result.content.toString(); assert.ok(readContent.includes('Test content'), 'Should read back content'); assert.ok(readContent.includes('äöü'), 'Should preserve special characters'); console.log('✓ Text handler read/write works'); } /** * Test 6: Text handler with JSON file */ async function testJsonFile() { console.log('\n--- Test 6: JSON File Handling ---'); const data = { name: 'Test', values: [1, 2, 3] }; const content = JSON.stringify(data, null, 2); await writeFile(JSON_FILE, content); const result = await readFile(JSON_FILE); const readContent = result.content.toString(); const parsed = JSON.parse(readContent.replace(/^\[.*?\]\n\n/, '')); // Remove status message assert.strictEqual(parsed.name, 'Test', 'JSON should be preserved'); assert.deepStrictEqual(parsed.values, [1, 2, 3], 'Array should be preserved'); console.log('✓ JSON file handling works'); } /** * Test 7: File info returns correct structure */ async function testFileInfo() { console.log('\n--- Test 7: File Info Structure ---'); await fs.writeFile(TEXT_FILE, 'Some content'); const info = await getFileInfo(TEXT_FILE); // Check required fields assert.ok('size' in info, 'Should have size'); assert.ok('created' in info || 'birthtime' in info, 'Should have creation time'); assert.ok('modified' in info || 'mtime' in info, 'Should have modification time'); assert.ok('isFile' in info, 'Should have isFile'); assert.ok('isDirectory' in info, 'Should have isDirectory'); assert.ok(info.size > 0, 'Size should be > 0'); assert.ok(info.isFile === true || info.isFile === 'true', 'Should be a file'); console.log('✓ File info structure is correct'); } /** * Test 8: Write mode (rewrite vs append) */ async function testWriteModes() { console.log('\n--- Test 8: Write Modes ---'); // Initial write (rewrite mode - default) await writeFile(TEXT_FILE, 'Initial content'); // Overwrite await writeFile(TEXT_FILE, 'New content', 'rewrite'); let result = await readFile(TEXT_FILE); let content = result.content.toString(); assert.ok(!content.includes('Initial'), 'Rewrite should replace content'); assert.ok(content.includes('New content'), 'Should have new content'); console.log('✓ Rewrite mode works'); // Append await writeFile(TEXT_FILE, '\nAppended content', 'append'); result = await readFile(TEXT_FILE); content = result.content.toString(); assert.ok(content.includes('New content'), 'Should keep original'); assert.ok(content.includes('Appended content'), 'Should have appended'); console.log('✓ Append mode works'); } /** * Test 9: read_file handler returns preview metadata for markdown/text */ async function testReadFilePreviewMetadata() { console.log('\n--- Test 9: read_file preview metadata ---'); const markdownContent = '# Title\n\n```js\nconst x = 1;\n```'; const textContent = 'hello\nplain text'; const tinyPngBase64 = 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO6p6xkAAAAASUVORK5CYII='; await fs.writeFile(MD_FILE, markdownContent); await fs.writeFile(TEXT_FILE, textContent); await fs.writeFile(HTML_FILE, '<h1>Preview</h1><script>alert(1)</script>'); await fs.writeFile(IMAGE_FILE, Buffer.from(tinyPngBase64, 'base64')); const markdownResult = await handleReadFile({ path: MD_FILE }); assert.ok(Array.isArray(markdownResult.content), 'Result should include content array'); assert.ok(markdownResult.content[0].text.includes(markdownContent), 'Legacy content should still include markdown body'); assert.ok(markdownResult.structuredContent, 'Markdown should include structuredContent'); assert.strictEqual(markdownResult.structuredContent.fileType, 'markdown', 'Markdown fileType should be markdown'); assert.strictEqual(markdownResult.structuredContent.filePath, MD_FILE, 'Markdown file path should be present'); assert.strictEqual(markdownResult._meta['ui/resourceUri'], FILE_PREVIEW_RESOURCE_URI, 'Markdown should include ui/resourceUri'); assert.strictEqual(markdownResult._meta.ui.resourceUri, FILE_PREVIEW_RESOURCE_URI, 'Markdown should include preview resource URI'); assert.strictEqual(markdownResult._meta['openai/widgetAccessible'], true, 'Markdown should enable widget accessibility'); const textResult = await handleReadFile({ path: TEXT_FILE }); assert.ok(Array.isArray(textResult.content), 'Result should include content array'); assert.ok(textResult.content[0].text.includes(textContent), 'Legacy content should still include text body'); assert.ok(textResult.structuredContent, 'Text should include structuredContent'); assert.strictEqual(textResult.structuredContent.fileType, 'text', 'Text fileType should be text'); assert.strictEqual(textResult._meta['ui/resourceUri'], FILE_PREVIEW_RESOURCE_URI, 'Text should include ui/resourceUri'); assert.strictEqual(textResult._meta.ui.resourceUri, FILE_PREVIEW_RESOURCE_URI, 'Text should include preview resource URI'); assert.strictEqual(textResult._meta['openai/widgetAccessible'], true, 'Text should enable widget accessibility'); const htmlResult = await handleReadFile({ path: HTML_FILE }); assert.ok(Array.isArray(htmlResult.content), 'Result should include content array'); assert.ok(htmlResult.content[0].text.includes('<h1>Preview</h1>'), 'Legacy content should still include html body'); assert.ok(htmlResult.structuredContent, 'HTML should include structuredContent'); assert.strictEqual(htmlResult.structuredContent.fileType, 'html', 'HTML fileType should be html'); assert.strictEqual(htmlResult._meta['ui/resourceUri'], FILE_PREVIEW_RESOURCE_URI, 'HTML should include ui/resourceUri'); assert.strictEqual(htmlResult._meta.ui.resourceUri, FILE_PREVIEW_RESOURCE_URI, 'HTML should include preview resource URI'); assert.strictEqual(htmlResult._meta['openai/widgetAccessible'], true, 'HTML should enable widget accessibility'); const imageResult = await handleReadFile({ path: IMAGE_FILE }); assert.ok(Array.isArray(imageResult.content), 'Image result should include content array'); assert.ok(imageResult.content.some((item) => item.type === 'image'), 'Image result should include image content'); assert.ok(imageResult.structuredContent, 'Image should include structuredContent'); assert.strictEqual(imageResult.structuredContent.fileType, 'unsupported', 'Image fileType should map to unsupported preview state'); assert.strictEqual(imageResult.structuredContent.filePath, IMAGE_FILE, 'Image file path should be present'); assert.strictEqual(imageResult._meta['ui/resourceUri'], FILE_PREVIEW_RESOURCE_URI, 'Image should include ui/resourceUri'); assert.strictEqual(imageResult._meta.ui.resourceUri, FILE_PREVIEW_RESOURCE_URI, 'Image should include preview resource URI'); assert.strictEqual(imageResult._meta['openai/widgetAccessible'], true, 'Image should enable widget accessibility'); const nullArgsResult = await handleReadFile(null); assert.ok(Array.isArray(nullArgsResult.content), 'Null-args result should include content array'); assert.strictEqual(nullArgsResult.isError, true, 'Null-args should be returned as error'); assert.ok(nullArgsResult.content[0].text.includes('Error: No arguments provided for read_file command'), 'Null-args should include standard error text'); console.log('✓ read_file preview metadata contract works'); } /** * Run all tests */ async function runAllTests() { console.log('=== File Handler System Tests ===\n'); await testHandlerFactory(); await testFileResultInterface(); await testReadOptionsInterface(); await testCanHandle(); await testTextHandler(); await testJsonFile(); await testFileInfo(); await testWriteModes(); await testReadFilePreviewMetadata(); console.log('\n✅ All file handler tests passed!'); } // Export the main test function export default async function runTests() { let originalConfig; try { originalConfig = await setup(); await runAllTests(); } catch (error) { console.error('❌ Test failed:', error.message); console.error(error.stack); return false; } finally { // Always run teardown to clean up test directories and restore config // teardown handles the case where originalConfig is undefined await teardown(originalConfig); } return true; } // If this file is run directly, execute the test if (import.meta.url === `file://${process.argv[1]}`) { runTests().then(success => { process.exit(success ? 0 : 1); }).catch(error => { console.error('❌ Unhandled error:', error); process.exit(1); }); }
wonderwhy-er/DesktopCommanderMCP
5,467
This is MCP server for Claude that gives it terminal control, file system search and diff file editing capabilities
TypeScript
wonderwhy-er
Eduard Ruzga
test/test-home-directory.js
JavaScript
/** * Test script for home directory (~) path handling * * This script tests the tilde expansion and path validation with: * 1. Testing tilde (~) expansion in paths * 2. Testing tilde with subdirectory (~/Documents) expansion * 3. Testing tilde expansion in the allowedDirectories configuration * 4. Testing file operations with tilde notation */ import { configManager } from '../dist/config-manager.js'; import { validatePath, listDirectory, readFile, writeFile, createDirectory } from '../dist/tools/filesystem.js'; import fs from 'fs/promises'; import path from 'path'; import { fileURLToPath } from 'url'; import assert from 'assert'; import os from 'os'; // Get directory name const __filename = fileURLToPath(import.meta.url); const __dirname = path.dirname(__filename); // Define test paths const HOME_DIR = os.homedir(); const HOME_TILDE = '~'; const HOME_DOCS_PATH = path.join(HOME_DIR, 'Documents'); const HOME_DOCS_TILDE = '~/Documents'; const TEST_DIR = path.join(HOME_DIR, '.claude-test-tilde'); const TEST_DIR_TILDE = '~/.claude-test-tilde'; const TEST_FILE = path.join(TEST_DIR, 'test-file.txt'); const TEST_FILE_TILDE = '~/.claude-test-tilde/test-file.txt'; const TEST_CONTENT = 'This is a test file for tilde expansion'; /** * Helper function to clean up test directories */ async function cleanupTestDirectories() { try { console.log('Cleaning up test directories...'); await fs.rm(TEST_DIR, { recursive: true, force: true }); console.log('Cleanup complete.'); } catch (error) { // Ignore errors if directory doesn't exist if (error.code !== 'ENOENT') { console.error('Error during cleanup:', error); } } } /** * Setup function to prepare the test environment */ async function setup() { // Clean up before tests await cleanupTestDirectories(); // Save original config to restore later const originalConfig = await configManager.getConfig(); // Set allowed directories to include the home directory for testing tilde expansion await configManager.setValue('allowedDirectories', [HOME_DIR, __dirname]); console.log(`Set allowed directories to: ${HOME_DIR}, ${__dirname}`); return originalConfig; } /** * Teardown function to clean up after tests */ async function teardown(originalConfig) { // Reset configuration to original await configManager.updateConfig(originalConfig); // Clean up test directories await cleanupTestDirectories(); console.log('✓ Teardown: test directories cleaned up and config restored'); } /** * Test simple tilde expansion */ async function testTildeExpansion() { console.log('\nTest 1: Basic tilde expansion'); // Test path validation with tilde console.log(`Testing tilde expansion for: ${HOME_TILDE}`); console.log(`Home directory from os.homedir(): ${HOME_DIR}`); try { const expandedPath = await validatePath(HOME_TILDE); console.log(`Tilde (~) expanded to: ${expandedPath}`); // Check if the expanded path is the home directory assert.ok( expandedPath.toLowerCase() === HOME_DIR.toLowerCase() || expandedPath.toLowerCase().startsWith(HOME_DIR.toLowerCase()), 'Tilde (~) should expand to the home directory' ); console.log('✓ Basic tilde expansion works correctly'); return expandedPath; // Return expandedPath for use in the outer function } catch (error) { console.error(`Error during tilde expansion: ${error.message || error}`); throw error; } } /** * Test tilde with subdirectory expansion */ async function testTildeWithSubdirectory() { console.log('\nTest 2: Tilde with subdirectory expansion'); try { // Test path validation with tilde and subdirectory console.log(`Testing tilde with subdirectory expansion for: ${HOME_DOCS_TILDE}`); console.log(`Home documents directory: ${HOME_DOCS_PATH}`); const expandedPath = await validatePath(HOME_DOCS_TILDE); console.log(`~/Documents expanded to: ${expandedPath}`); // Check if the expanded path is the home documents directory assert.ok( expandedPath.toLowerCase() === HOME_DOCS_PATH.toLowerCase() || expandedPath.toLowerCase().startsWith(HOME_DOCS_PATH.toLowerCase()), '~/Documents should expand to the home documents directory' ); console.log('✓ Tilde with subdirectory expansion works correctly'); } catch (error) { console.error(`Error during tilde with subdirectory expansion: ${error.message || error}`); throw error; } } /** * Test tilde in allowedDirectories config */ async function testTildeInAllowedDirectories() { console.log('\nTest 3: Tilde in allowedDirectories config'); try { // Set allowedDirectories to tilde await configManager.setValue('allowedDirectories', [HOME_TILDE]); // Verify config was set correctly const config = await configManager.getConfig(); console.log(`Config: ${JSON.stringify(config.allowedDirectories)}`); assert.deepStrictEqual(config.allowedDirectories, [HOME_TILDE], 'allowedDirectories should contain tilde'); // Test access to home directory and subdirectory try { const homeDirAccess = await validatePath(HOME_DIR); console.log(`Home directory access: ${homeDirAccess}`); const homeDocsDirAccess = await validatePath(HOME_DOCS_PATH); console.log(`Home documents directory access: ${homeDocsDirAccess}`); console.log('✓ Tilde in allowedDirectories works correctly'); } catch (error) { console.error(`Error accessing paths: ${error.message || error}`); throw error; } finally { // Reset allowedDirectories to original value await configManager.setValue('allowedDirectories', []); } } catch (error) { console.error(`Error in tilde allowedDirectories test: ${error.message || error}`); throw error; } } /** * Test file operations with tilde */ async function testFileOperationsWithTilde() { console.log('\nTest 4: File operations with tilde'); try { // Test directory creation with tilde console.log(`Attempting to create directory: ${TEST_DIR_TILDE}`); await createDirectory(TEST_DIR_TILDE); console.log(`Created test directory: ${TEST_DIR_TILDE}`); // Verify the directory exists const dirStats = await fs.stat(TEST_DIR); assert.ok(dirStats.isDirectory(), 'Test directory should exist and be a directory'); // Test writing to a file with tilde console.log(`Attempting to write to file: ${TEST_FILE_TILDE}`); await writeFile(TEST_FILE_TILDE, TEST_CONTENT); console.log(`Wrote to test file: ${TEST_FILE_TILDE}`); // Test reading from a file with tilde console.log(`Attempting to read file: ${TEST_FILE_TILDE}`); const fileResult = await readFile(TEST_FILE_TILDE); let content; // Handle either string or object response from readFile if (typeof fileResult === 'string') { content = fileResult; } else if (fileResult && typeof fileResult === 'object') { content = fileResult.content; } else { throw new Error('Unexpected return format from readFile'); } console.log(`Read from test file content: ${content}`); // Verify the content assert.ok( content === TEST_CONTENT || content.includes(TEST_CONTENT), 'File content should match what was written' ); // Test listing a directory with tilde console.log(`Attempting to list directory: ${TEST_DIR_TILDE}`); const entries = await listDirectory(TEST_DIR_TILDE); console.log(`Listed test directory: ${entries}`); // Verify the entries assert.ok(entries.some(entry => entry.includes('test-file.txt')), 'Directory listing should include test file'); console.log('✓ File operations with tilde work correctly'); } catch (error) { console.error(`Error during file operations with tilde: ${error.message || error}`); throw error; } } /** * Main test function */ async function testHomeDirectory() { console.log('=== Home Directory (~) Path Handling Tests ===\n'); try { // Test 1: Basic tilde expansion const expandedPath = await testTildeExpansion(); // Check if the expanded path is the home directory assert.ok( expandedPath.toLowerCase() === HOME_DIR.toLowerCase() || expandedPath.toLowerCase().startsWith(HOME_DIR.toLowerCase()), 'Tilde (~) should expand to the home directory' ); // Test 2: Tilde with subdirectory expansion await testTildeWithSubdirectory(); // Test 3: Tilde in allowedDirectories config await testTildeInAllowedDirectories(); // Test 4: File operations with tilde await testFileOperationsWithTilde(); console.log('\n✅ All home directory (~) tests passed!'); } catch (error) { console.error(`Main test function error: ${error.message || error}`); throw error; } } // Export the main test function export default async function runTests() { let originalConfig; try { originalConfig = await setup(); await testHomeDirectory(); return true; // Explicitly return true on success } catch (error) { console.error('❌ Test failed:', error.message || error); return false; } finally { if (originalConfig) { await teardown(originalConfig); } } } // If this file is run directly (not imported), execute the test if (import.meta.url === `file://${process.argv[1]}`) { runTests().catch(error => { console.error('❌ Unhandled error:', error); process.exit(1); }); }
wonderwhy-er/DesktopCommanderMCP
5,467
This is MCP server for Claude that gives it terminal control, file system search and diff file editing capabilities
TypeScript
wonderwhy-er
Eduard Ruzga
test/test-literal-search.js
JavaScript
/** * Test for literal search functionality - testing regex vs literal string matching */ import path from 'path'; import fs from 'fs/promises'; import { fileURLToPath } from 'url'; import { handleStartSearch, handleGetMoreSearchResults, handleStopSearch } from '../dist/handlers/search-handlers.js'; import { configManager } from '../dist/config-manager.js'; const __filename = fileURLToPath(import.meta.url); const __dirname = path.dirname(__filename); // Test directory for literal search tests const LITERAL_SEARCH_TEST_DIR = path.join(__dirname, 'literal-search-test-files'); // Colors for console output const colors = { reset: '\x1b[0m', green: '\x1b[32m', red: '\x1b[31m', yellow: '\x1b[33m', blue: '\x1b[34m' }; /** * Helper function to wait for search completion and get all results */ async function searchAndWaitForCompletion(searchArgs, timeout = 10000) { const result = await handleStartSearch(searchArgs); // Extract session ID from result const sessionIdMatch = result.content[0].text.match(/Started .+ session: (.+)/); if (!sessionIdMatch) { throw new Error('Could not extract session ID from search result'); } const sessionId = sessionIdMatch[1]; try { // Wait for completion by polling const startTime = Date.now(); while (Date.now() - startTime < timeout) { const moreResults = await handleGetMoreSearchResults({ sessionId }); if (moreResults.content[0].text.includes('✅ Search completed')) { return { initialResult: result, finalResult: moreResults, sessionId }; } if (moreResults.content[0].text.includes('❌ ERROR')) { throw new Error(`Search failed: ${moreResults.content[0].text}`); } // Wait a bit before polling again await new Promise(resolve => setTimeout(resolve, 100)); } throw new Error('Search timed out'); } finally { // Always stop the search session to prevent hanging try { await handleStopSearch({ sessionId }); } catch (e) { // Ignore errors when stopping - session might already be completed } } } /** * Setup function to prepare literal search test environment */ async function setup() { console.log(`${colors.blue}Setting up literal search tests...${colors.reset}`); // Save original config const originalConfig = await configManager.getConfig(); // Set allowed directories to include test directory await configManager.setValue('allowedDirectories', [LITERAL_SEARCH_TEST_DIR]); // Create test directory await fs.mkdir(LITERAL_SEARCH_TEST_DIR, { recursive: true }); // Create test file with patterns that contain regex special characters await fs.writeFile(path.join(LITERAL_SEARCH_TEST_DIR, 'code-patterns.js'), `// JavaScript file with common code patterns // These patterns contain regex special characters that should be matched literally // Function calls with parentheses toast.error("test"); console.log("hello world"); alert("message"); // Array access with brackets array[0] data[index] items[key] // Object method calls with dots obj.method() user.getName() config.getValue() // Template literals with backticks const msg = \`Hello \${name}\`; const query = \`SELECT * FROM users WHERE id = \${id}\`; // Regex special characters const pattern = ".*"; const wildcard = "test*"; const question = "value?"; const plus = "count++"; const caret = "^start"; const dollar = "end$"; const pipe = "a|b"; const backslash = "path\\\\to\\\\file"; // Complex patterns if (condition && obj.method()) { toast.error("Error occurred"); } function validateEmail(email) { return email.includes("@") && email.includes("."); } `); // Create another file with similar but different patterns await fs.writeFile(path.join(LITERAL_SEARCH_TEST_DIR, 'similar-patterns.ts'), `// TypeScript file with similar patterns interface Config { getValue(): string; } class Logger { static error(message: string): void { console.error(\`[ERROR] \${message}\`); } static log(message: string): void { console.log(message); } } // These should NOT match when searching for exact patterns toast.errorHandler("test"); // Similar but different console.logout("hello world"); // Similar but different array.slice(0, 1); // Similar but different `); console.log(`${colors.green}✓ Setup complete: Literal search test files created${colors.reset}`); return originalConfig; } /** * Teardown function to clean up after tests */ async function teardown(originalConfig) { console.log(`${colors.blue}Cleaning up literal search tests...${colors.reset}`); // Clean up test directory await fs.rm(LITERAL_SEARCH_TEST_DIR, { force: true, recursive: true }); // Restore original config await configManager.updateConfig(originalConfig); console.log(`${colors.green}✓ Teardown complete: Test files removed and config restored${colors.reset}`); } /** * Assert function for test validation */ function assert(condition, message) { if (!condition) { throw new Error(`Assertion failed: ${message}`); } } /** * Count occurrences of a pattern in text */ function countOccurrences(text, pattern) { return (text.match(new RegExp(pattern, 'g')) || []).length; } /** * Test that literal search finds exact matches for patterns with special characters * This test should FAIL initially since literalSearch parameter doesn't exist yet */ async function testLiteralSearchExactMatches() { console.log(`${colors.yellow}Testing literal search for exact matches...${colors.reset}`); // Test 1: Search for exact function call with quotes and parentheses const { finalResult: result1 } = await searchAndWaitForCompletion({ path: LITERAL_SEARCH_TEST_DIR, pattern: 'toast.error("test")', searchType: 'content', literalSearch: true // This parameter should be added }); const text1 = result1.content[0].text; // Should find exactly 2 occurrences (one in each file: the exact match and in comment) const exactMatches = countOccurrences(text1, 'toast\\.error\\("test"\\)'); assert(exactMatches >= 1, `Should find exact matches for 'toast.error("test")', found: ${exactMatches}`); // Should NOT find the similar but different pattern assert(!text1.includes('toast.errorHandler'), 'Should not match similar but different patterns'); console.log(`${colors.green}✓ Literal search exact matches test passed${colors.reset}`); } /** * Test that regex search works differently than literal search */ async function testRegexVsLiteralDifference() { console.log(`${colors.yellow}Testing difference between regex and literal search...${colors.reset}`); // Test with regex (default behavior) - should interpret dots as wildcard const { finalResult: regexResult } = await searchAndWaitForCompletion({ path: LITERAL_SEARCH_TEST_DIR, pattern: 'console.log', // Dot should match any character in regex mode searchType: 'content', literalSearch: false // Explicit regex mode }); // Test with literal search - should match exact dots const { finalResult: literalResult } = await searchAndWaitForCompletion({ path: LITERAL_SEARCH_TEST_DIR, pattern: 'console.log', // Dot should match literal dot only searchType: 'content', literalSearch: true }); const regexText = regexResult.content[0].text; const literalText = literalResult.content[0].text; // Both should find console.log, but regex might find more due to dot wildcard behavior assert(regexText.includes('console.log'), 'Regex search should find console.log'); assert(literalText.includes('console.log'), 'Literal search should find console.log'); console.log(`${colors.green}✓ Regex vs literal difference test passed${colors.reset}`); } /** * Test literal search with various special characters */ async function testSpecialCharactersLiteralSearch() { console.log(`${colors.yellow}Testing literal search with various special characters...${colors.reset}`); const testPatterns = [ 'array[0]', // Brackets 'obj.method()', // Dots and parentheses 'count++', // Plus signs 'value?', // Question mark 'pattern.*', // Dot and asterisk '^start', // Caret 'end$', // Dollar sign 'a|b', // Pipe 'path\\\\to\\\\file' // Backslashes ]; for (const pattern of testPatterns) { console.log(` Testing pattern: ${pattern}`); const { finalResult } = await searchAndWaitForCompletion({ path: LITERAL_SEARCH_TEST_DIR, pattern: pattern, searchType: 'content', literalSearch: true }); const text = finalResult.content[0].text; // Should find the pattern or indicate no matches (both are valid for literal search) const hasResults = text.includes(pattern) || text.includes('No matches found') || text.includes('Total results found: 0'); assert(hasResults, `Should handle literal search for pattern '${pattern}' (found results or no matches message)`); } console.log(`${colors.green}✓ Special characters literal search test passed${colors.reset}`); } /** * Test that literalSearch parameter defaults to false (maintains backward compatibility) */ async function testLiteralSearchDefault() { console.log(`${colors.yellow}Testing that literalSearch defaults to false...${colors.reset}`); // Search without specifying literalSearch - should default to regex behavior const { finalResult } = await searchAndWaitForCompletion({ path: LITERAL_SEARCH_TEST_DIR, pattern: 'console.log', searchType: 'content' // literalSearch not specified - should default to false }); const text = finalResult.content[0].text; // Should work (either find matches or no matches, but not error) const isValidResult = text.includes('console.log') || text.includes('No matches found') || text.includes('Total results found'); assert(isValidResult, 'Should handle search with default literalSearch behavior'); console.log(`${colors.green}✓ Literal search default behavior test passed${colors.reset}`); } /** * Test the specific failing case that motivated this fix */ async function testOriginalFailingCase() { console.log(`${colors.yellow}Testing the original failing case that motivated this fix...${colors.reset}`); // This was the original failing search: toast.error("test") const { finalResult } = await searchAndWaitForCompletion({ path: LITERAL_SEARCH_TEST_DIR, pattern: 'toast.error("test")', searchType: 'content', literalSearch: true }); const text = finalResult.content[0].text; // Should find the exact match assert(text.includes('toast.error("test")') || text.includes('code-patterns.js'), 'Should find the exact pattern that was originally failing'); // Verify it contains the file where we know the pattern exists assert(text.includes('code-patterns.js'), 'Should find matches in code-patterns.js file'); console.log(`${colors.green}✓ Original failing case test passed${colors.reset}`); } /** * Test that demonstrates regex mode fails while literal mode succeeds * This is the key test that shows the problem we solved */ async function testRegexFailureLiteralSuccess() { console.log(`${colors.yellow}Testing that regex mode fails where literal mode succeeds...${colors.reset}`); // Test with regex mode (default) - should fail to find exact pattern due to regex interpretation const { finalResult: regexResult } = await searchAndWaitForCompletion({ path: LITERAL_SEARCH_TEST_DIR, pattern: 'toast.error("test")', // This pattern has regex special chars searchType: 'content', literalSearch: false // Use regex mode (default) }); // Test with literal mode - should succeed in finding exact pattern const { finalResult: literalResult } = await searchAndWaitForCompletion({ path: LITERAL_SEARCH_TEST_DIR, pattern: 'toast.error("test")', // Same pattern searchType: 'content', literalSearch: true // Use literal mode }); const regexText = regexResult.content[0].text; const literalText = literalResult.content[0].text; // Regex mode should find few/no matches due to special character interpretation const regexMatches = (regexText.match(/toast\.error\("test"\)/g) || []).length; // Literal mode should find the exact matches const literalMatches = (literalText.match(/toast\.error\("test"\)/g) || []).length; console.log(` Regex mode found: ${regexMatches} matches`); console.log(` Literal mode found: ${literalMatches} matches`); // The key assertion: literal should find more matches than regex assert(literalMatches > regexMatches, `Literal search should find more matches (${literalMatches}) than regex search (${regexMatches}) for patterns with special characters`); // Literal should find at least one match assert(literalMatches >= 1, 'Literal search should find at least one exact match'); console.log(`${colors.green}✓ Regex failure vs literal success test passed${colors.reset}`); } /** * Main test runner function for literal search tests */ export async function testLiteralSearch() { console.log(`${colors.blue}Starting literal search functionality tests...${colors.reset}`); let originalConfig; try { // Setup originalConfig = await setup(); // Run all literal search tests await testLiteralSearchExactMatches(); await testRegexVsLiteralDifference(); await testSpecialCharactersLiteralSearch(); await testLiteralSearchDefault(); await testOriginalFailingCase(); await testRegexFailureLiteralSuccess(); // NEW: Critical test showing the problem we solved console.log(`${colors.green}✅ All literal search tests passed!${colors.reset}`); return true; } catch (error) { console.error(`${colors.red}❌ Literal search test failed: ${error.message}${colors.reset}`); console.error(error.stack); throw error; } finally { // Cleanup if (originalConfig) { await teardown(originalConfig); } } } // Export for use in run-all-tests.js export default testLiteralSearch; // Run tests if this file is executed directly if (import.meta.url === `file://${process.argv[1]}`) { testLiteralSearch().then(() => { console.log('Literal search tests completed successfully.'); process.exit(0); }).catch(error => { console.error('Literal search test execution failed:', error); process.exit(1); }); }
wonderwhy-er/DesktopCommanderMCP
5,467
This is MCP server for Claude that gives it terminal control, file system search and diff file editing capabilities
TypeScript
wonderwhy-er
Eduard Ruzga
test/test-negative-offset-analysis.js
JavaScript
/** * Test Results: Negative Offset Analysis for read_file * * FINDINGS: * ❌ Negative offsets DO NOT work correctly in the current implementation * ❌ They return empty content due to invalid slice() range calculations * ⚠️ The implementation has a bug when handling negative offsets * * CURRENT BEHAVIOR: * - offset: -2, length: 5 → slice(-2, 3) → returns empty [] * - offset: -100, length: undefined → slice(-100, undefined) → works by accident * * RECOMMENDATION: * Either fix the implementation to properly support negative offsets, * or add validation to reject them with a clear error message. */ console.log("🔍 NEGATIVE OFFSET BEHAVIOR ANALYSIS"); console.log("===================================="); console.log(""); console.log("❌ CONCLUSION: Negative offsets are BROKEN in current implementation"); console.log(""); console.log("🐛 BUG DETAILS:"); console.log(" Current code: Math.min(offset, totalLines) creates invalid ranges"); console.log(" Example: offset=-2, totalLines=6 → slice(-2, 3) → empty result"); console.log(""); console.log("✅ ACCIDENTAL SUCCESS:"); console.log(" My original attempt worked because length was undefined"); console.log(" slice(-100, undefined) → slice(-100) → works correctly"); console.log(""); console.log("🔧 NEEDS FIX:"); console.log(" Either implement proper negative offset support or reject them"); export default async function runTests() { return false; // Test documents that negative offsets are broken }
wonderwhy-er/DesktopCommanderMCP
5,467
This is MCP server for Claude that gives it terminal control, file system search and diff file editing capabilities
TypeScript
wonderwhy-er
Eduard Ruzga
test/test-negative-offset-readfile.js
JavaScript
/** * Test script for negative offset handling in read_file * * This script tests: * 1. Whether negative offsets work correctly (like Unix tail) * 2. How the tool handles edge cases with negative offsets * 3. Comparison with positive offset behavior * 4. Error handling for invalid parameters */ import { configManager } from '../dist/config-manager.js'; import { handleReadFile } from '../dist/handlers/filesystem-handlers.js'; import fs from 'fs/promises'; import path from 'path'; import { fileURLToPath } from 'url'; import assert from 'assert'; // Get directory name const __filename = fileURLToPath(import.meta.url); const __dirname = path.dirname(__filename); // Define test paths const TEST_FILE = path.join(__dirname, 'test-negative-offset.txt'); /** * Setup function to prepare test environment */ async function setup() { console.log('🔧 Setting up negative offset test...'); // Save original config to restore later const originalConfig = await configManager.getConfig(); // Set allowed directories to include test directory await configManager.setValue('allowedDirectories', [__dirname]); // Create test file with numbered lines for easy verification const testLines = []; for (let i = 1; i <= 50; i++) { testLines.push(`Line ${i}: This is line number ${i} in the test file.`); } const testContent = testLines.join('\n'); await fs.writeFile(TEST_FILE, testContent, 'utf8'); console.log(`✓ Created test file with 50 lines: ${TEST_FILE}`); return originalConfig; } /** * Teardown function to clean up after tests */ async function teardown(originalConfig) { console.log('🧹 Cleaning up test environment...'); // Reset configuration to original await configManager.updateConfig(originalConfig); // Remove test file try { await fs.rm(TEST_FILE, { force: true }); console.log('✓ Test file cleaned up'); } catch (error) { console.log('⚠️ Warning: Could not clean up test file:', error.message); } } /** * Test negative offset functionality */ async function testNegativeOffset() { console.log('\n📋 Testing negative offset behavior...'); const tests = [ { name: 'Negative offset -10 (last 10 lines)', args: { path: TEST_FILE, offset: -10, length: 20 }, expectLines: ['Line 41:', 'Line 42:', 'Line 43:', 'Line 44:', 'Line 45:', 'Line 46:', 'Line 47:', 'Line 48:', 'Line 49:', 'Line 50:'] }, { name: 'Negative offset -5 (last 5 lines)', args: { path: TEST_FILE, offset: -5, length: 10 }, expectLines: ['Line 46:', 'Line 47:', 'Line 48:', 'Line 49:', 'Line 50:'] }, { name: 'Negative offset -1 (last 1 line)', args: { path: TEST_FILE, offset: -1, length: 5 }, expectLines: ['Line 50:'] }, { name: 'Large negative offset -100 (beyond file size)', args: { path: TEST_FILE, offset: -100, length: 10 }, expectLines: ['Line 1:', 'Line 2:', 'Line 3:', 'Line 4:', 'Line 5:', 'Line 6:', 'Line 7:', 'Line 8:', 'Line 9:', 'Line 10:'] } ]; let passedTests = 0; for (const test of tests) { console.log(`\n 🧪 ${test.name}`); try { const result = await handleReadFile(test.args); if (result.isError) { console.log(` ❌ Error: ${result.content[0].text}`); continue; } const content = result.content[0].text; console.log(` 📄 Result (first 200 chars): ${content.substring(0, 200)}...`); // Check if expected lines are present let foundExpected = 0; for (const expectedLine of test.expectLines) { if (content.includes(expectedLine)) { foundExpected++; } } if (foundExpected === test.expectLines.length) { console.log(` ✅ PASS: Found all ${foundExpected} expected lines`); passedTests++; } else { console.log(` ❌ FAIL: Found only ${foundExpected}/${test.expectLines.length} expected lines`); console.log(` Expected: ${test.expectLines.join(', ')}`); } } catch (error) { console.log(` ❌ Exception: ${error.message}`); } } return passedTests === tests.length; } /** * Test comparison between negative and positive offsets */ async function testOffsetComparison() { console.log('\n📊 Testing offset comparison (negative vs positive)...'); try { // Test reading last 5 lines with negative offset const negativeResult = await handleReadFile({ path: TEST_FILE, offset: -5, length: 10 }); // Test reading same lines with positive offset (45 to get last 5 lines of 50) const positiveResult = await handleReadFile({ path: TEST_FILE, offset: 45, length: 5 }); if (negativeResult.isError || positiveResult.isError) { console.log(' ❌ One or both requests failed'); return false; } const negativeContent = negativeResult.content[0].text; const positiveContent = positiveResult.content[0].text; console.log(' 📄 Negative offset result:'); console.log(` ${negativeContent.split('\n').slice(2, 4).join('\\n')}`); // Skip header lines console.log(' 📄 Positive offset result:'); console.log(` ${positiveContent.split('\n').slice(2, 4).join('\\n')}`); // Skip header lines // Extract actual content lines (skip informational headers) const negativeLines = negativeContent.split('\n').filter(line => line.startsWith('Line ')); const positiveLines = positiveContent.split('\n').filter(line => line.startsWith('Line ')); const isMatching = negativeLines.join('\\n') === positiveLines.join('\\n'); if (isMatching) { console.log(' ✅ PASS: Negative and positive offsets return same content'); return true; } else { console.log(' ❌ FAIL: Negative and positive offsets return different content'); console.log(` Negative: ${negativeLines.slice(0, 2).join(', ')}`); console.log(` Positive: ${positiveLines.slice(0, 2).join(', ')}`); return false; } } catch (error) { console.log(` ❌ Exception during comparison: ${error.message}`); return false; } } /** * Test edge cases and error handling */ async function testEdgeCases() { console.log('\n🔍 Testing edge cases...'); const edgeTests = [ { name: 'Zero offset with length', args: { path: TEST_FILE, offset: 0, length: 3 }, shouldPass: true }, { name: 'Very large negative offset', args: { path: TEST_FILE, offset: -1000, length: 5 }, shouldPass: true // Should handle gracefully }, { name: 'Negative offset with zero length', args: { path: TEST_FILE, offset: -5, length: 0 }, shouldPass: true // Should return empty or minimal content } ]; let passedEdgeTests = 0; for (const test of edgeTests) { console.log(`\n 🧪 ${test.name}`); try { const result = await handleReadFile(test.args); if (result.isError && test.shouldPass) { console.log(` ❌ Unexpected error: ${result.content[0].text}`); } else if (!result.isError && test.shouldPass) { console.log(` ✅ PASS: Handled gracefully`); console.log(` 📄 Result length: ${result.content[0].text.length} chars`); passedEdgeTests++; } else if (result.isError && !test.shouldPass) { console.log(` ✅ PASS: Expected error occurred`); passedEdgeTests++; } } catch (error) { if (test.shouldPass) { console.log(` ❌ Unexpected exception: ${error.message}`); } else { console.log(` ✅ PASS: Expected exception occurred`); passedEdgeTests++; } } } return passedEdgeTests === edgeTests.length; } /** * Main test runner */ async function runAllTests() { console.log('🧪 Starting negative offset read_file tests...\n'); let originalConfig; let allTestsPassed = true; try { originalConfig = await setup(); // Run all test suites const negativeOffsetPassed = await testNegativeOffset(); const comparisonPassed = await testOffsetComparison(); const edgeCasesPassed = await testEdgeCases(); allTestsPassed = negativeOffsetPassed && comparisonPassed && edgeCasesPassed; console.log('\n📊 Test Results Summary:'); console.log(` Negative offset tests: ${negativeOffsetPassed ? '✅ PASS' : '❌ FAIL'}`); console.log(` Comparison tests: ${comparisonPassed ? '✅ PASS' : '❌ FAIL'}`); console.log(` Edge case tests: ${edgeCasesPassed ? '✅ PASS' : '❌ FAIL'}`); console.log(`\n🎯 Overall result: ${allTestsPassed ? '✅ ALL TESTS PASSED!' : '❌ SOME TESTS FAILED'}`); } catch (error) { console.error('❌ Test setup/execution failed:', error.message); allTestsPassed = false; } finally { if (originalConfig) { await teardown(originalConfig); } } return allTestsPassed; } // Export the main test function export default runAllTests; // If this file is run directly (not imported), execute the test if (import.meta.url === `file://${process.argv[1]}`) { runAllTests().then(success => { process.exit(success ? 0 : 1); }).catch(error => { console.error('❌ Unhandled error:', error); process.exit(1); }); }
wonderwhy-er/DesktopCommanderMCP
5,467
This is MCP server for Claude that gives it terminal control, file system search and diff file editing capabilities
TypeScript
wonderwhy-er
Eduard Ruzga
test/test-node-repl.js
JavaScript
/** * Specialized test for Node.js REPL interaction * This test uses a direct approach with the child_process module * to better understand and debug Node.js REPL behavior */ import { spawn } from 'child_process'; import fs from 'fs/promises'; import path from 'path'; import { fileURLToPath } from 'url'; // Get directory name const __filename = fileURLToPath(import.meta.url); const __dirname = path.dirname(__filename); // Colors for console output const colors = { reset: '\x1b[0m', green: '\x1b[32m', red: '\x1b[31m', yellow: '\x1b[33m', blue: '\x1b[34m', cyan: '\x1b[36m' }; /** * Sleep function */ function sleep(ms) { return new Promise(resolve => setTimeout(resolve, ms)); } /** * Test Node.js REPL interaction directly */ async function testNodeREPL() { console.log(`${colors.blue}Direct Node.js REPL test...${colors.reset}`); // Create output directory if it doesn't exist const OUTPUT_DIR = path.join(__dirname, 'test_output'); try { await fs.mkdir(OUTPUT_DIR, { recursive: true }); } catch (error) { console.warn(`${colors.yellow}Warning: Could not create output directory: ${error.message}${colors.reset}`); } // File for debugging output const debugFile = path.join(OUTPUT_DIR, 'node_repl_debug.txt'); let debugLog = ''; // Log both to console and to file function log(message) { console.log(message); debugLog += message + '\n'; } // Start Node.js REPL log(`${colors.blue}Starting Node.js REPL...${colors.reset}`); // Use the -i flag to ensure interactive mode const node = spawn('node', ['-i']); // Track all output let outputBuffer = ''; // Set up output listeners node.stdout.on('data', (data) => { const text = data.toString(); outputBuffer += text; log(`${colors.green}[STDOUT] ${text.trim()}${colors.reset}`); }); node.stderr.on('data', (data) => { const text = data.toString(); outputBuffer += text; log(`${colors.red}[STDERR] ${text.trim()}${colors.reset}`); }); // Set up exit handler node.on('exit', (code) => { log(`${colors.blue}Node.js process exited with code ${code}${colors.reset}`); // Write debug log to file after exit fs.writeFile(debugFile, debugLog).catch(err => { console.error(`Failed to write debug log: ${err.message}`); }); }); // Wait for Node.js to initialize log(`${colors.blue}Waiting for Node.js startup...${colors.reset}`); await sleep(2000); // Log initial state log(`${colors.blue}Initial output buffer: ${outputBuffer}${colors.reset}`); // Send a simple command log(`${colors.blue}Sending simple command...${colors.reset}`); node.stdin.write('console.log("Hello from Node.js!");\n'); // Wait for command to execute await sleep(2000); // Log state after first command log(`${colors.blue}Output after first command: ${outputBuffer}${colors.reset}`); // Send a multi-line command directly log(`${colors.blue}Sending multi-line command directly...${colors.reset}`); // Define the multi-line code const multilineCode = ` function greet(name) { return \`Hello, \${name}!\`; } for (let i = 0; i < 3; i++) { console.log(greet(\`User \${i}\`)); } `; log(`${colors.blue}Sending code:${colors.reset}\n${multilineCode}`); // Send the multi-line code directly node.stdin.write(multilineCode + '\n'); // Wait for execution await sleep(3000); // Log final state log(`${colors.blue}Final output buffer: ${outputBuffer}${colors.reset}`); // Check if we got the expected output const containsHello = outputBuffer.includes('Hello from Node.js!'); const containsGreetings = outputBuffer.includes('Hello, User 0!') && outputBuffer.includes('Hello, User 1!') && outputBuffer.includes('Hello, User 2!'); log(`${colors.blue}Found "Hello from Node.js!": ${containsHello}${colors.reset}`); log(`${colors.blue}Found greetings: ${containsGreetings}${colors.reset}`); // Terminate the process log(`${colors.blue}Terminating Node.js process...${colors.reset}`); node.stdin.end(); // Wait for process to exit await sleep(1000); // Return success status return containsHello && containsGreetings; } // Run the test testNodeREPL() .then(success => { console.log(`\n${colors.blue}Direct Node.js REPL test ${success ? colors.green + 'PASSED' : colors.red + 'FAILED'}${colors.reset}`); // Print file location for debug log console.log(`${colors.blue}Debug log saved to: ${path.join(__dirname, 'test_output', 'node_repl_debug.txt')}${colors.reset}`); process.exit(success ? 0 : 1); }) .catch(error => { console.error(`${colors.red}Test error: ${error.message}${colors.reset}`); process.exit(1); });
wonderwhy-er/DesktopCommanderMCP
5,467
This is MCP server for Claude that gives it terminal control, file system search and diff file editing capabilities
TypeScript
wonderwhy-er
Eduard Ruzga
test/test-pdf-creation.js
JavaScript
#!/usr/bin/env node /** * Test script for PDF creation functionality * Creates PDF from markdown string and verifies it */ import { writePdf } from '../dist/tools/filesystem.js'; import fs from 'fs/promises'; import path from 'path'; import { fileURLToPath } from 'url'; const __filename = fileURLToPath(import.meta.url); const __dirname = path.dirname(__filename); const OUTPUT_DIR = path.join(__dirname, 'test_output'); const OUTPUT_FILE = path.join(OUTPUT_DIR, 'created_sample.pdf'); const MODIFIED_FILE = path.join(OUTPUT_DIR, 'modified_sample.pdf'); const SAMPLE_FILE = path.join(__dirname, 'samples', 'Presentation Example.pdf'); const SAMPLE_FILE_MODIFIED = path.join(OUTPUT_DIR, 'Presentation Example Modified.pdf'); async function main() { console.log('🧪 PDF Creation & Modification Test Suite'); // Ensure output directory exists try { await fs.mkdir(OUTPUT_DIR, { recursive: true }); } catch (e) { // Ignore if exists } // Create a multi-page markdown to allow for meaningful delete operations const markdown = ` # Page 1: Introduction This is the first page of the test PDF. ## Features - Simple text - **Bold text** - *Italic text* (Padding to ensure content...) 1. Item 1 2. Item 2 3. Item 3 # Page 2: Code Section This should be on a new page if the previous content fills the page, but since we don't have explicit page breaks, we'll rely on the structure. Actually, let's just assume this is a single document we will modify. ## Code \`\`\`javascript console.log('Hello World'); console.log('Line 2'); console.log('Line 3'); \`\`\` `; console.log(`\n1. Creating PDF at: ${OUTPUT_FILE}`); try { // writePdf now writes directly to file await writePdf(OUTPUT_FILE, markdown); // Verify creation try { const stats = await fs.stat(OUTPUT_FILE); console.log('✅ PDF created successfully'); console.log(` File Size: ${stats.size} bytes`); if (stats.size === 0) { throw new Error('Created PDF is empty'); } } catch (e) { console.error('❌ Failed to verify created PDF:', e); process.exit(1); } // --- Modification Test --- console.log('\n2. Testing PDF Modification (Insert & Delete & Merge)...'); // Create a temporary PDF to merge const tempMergeFile = path.join(OUTPUT_DIR, 'temp_merge.pdf'); await writePdf(tempMergeFile, '# Merged Page\n\nThis page was merged from another PDF file.'); // We will: // 1. Delete page 0 (the first page) // 2. Insert a new cover page at the beginning (from markdown) // 3. Insert an appendix page at the end (from markdown) // 4. Merge the temporary PDF at the very end (from file path) await writePdf(OUTPUT_FILE, [ { type: 'delete', pageIndexes: [0] }, { type: 'delete', pageIndexes: [-1] // Delete the last page. }, { type: 'insert', pageIndex: 0, markdown: '# New Cover Page\n\nThis page was inserted dynamically.\n\n## Summary\nWe deleted the original pages and added this one.' }, { type: 'insert', pageIndex: 1, markdown: '# Appendix\n\nThis page was appended to the end.' }, { type: 'insert', pageIndex: 2, sourcePdfPath: tempMergeFile } ], MODIFIED_FILE); console.log('✅ PDF modified successfully'); console.log(` Saved to: ${MODIFIED_FILE}`); const modStats = await fs.stat(MODIFIED_FILE); if (modStats.size > 0) { console.log('✅ Modified PDF is valid (non-empty)'); console.log(` Modified File Size: ${modStats.size} bytes`); } else { console.error('❌ Modified PDF file is empty'); process.exit(1); } // Cleanup temp file await fs.unlink(tempMergeFile).catch(() => { }); } catch (error) { console.error('❌ Failed:', error); process.exit(1); } // --- Modification Test --- console.log('\n3. Testing PDF Modification - keep layout...'); await writePdf(SAMPLE_FILE, [ { type: 'insert', pageIndex: 0, markdown: '# New Cover Page\n\nThis page was inserted dynamically.\n\n## Summary\nWe deleted the original pages and added this one.' }, { type: 'insert', pageIndex: 1, markdown: '# Appendix\n\nThis page was appended to the end.' } ], SAMPLE_FILE_MODIFIED); console.log('✅ PDF modified successfully'); console.log(` Saved to: ${SAMPLE_FILE_MODIFIED}`); } if (import.meta.url === `file://${process.argv[1]}`) { main().catch(console.error); }
wonderwhy-er/DesktopCommanderMCP
5,467
This is MCP server for Claude that gives it terminal control, file system search and diff file editing capabilities
TypeScript
wonderwhy-er
Eduard Ruzga
test/test-pdf-parsing.js
JavaScript
#!/usr/bin/env node /** * Test script for PDF parsing functionality using @opendocsg/pdf2md (v3) * Verifies parsing of sample PDFs and URL */ import { parsePdfToMarkdown } from '../dist/tools/pdf/index.js'; import path from 'path'; import { fileURLToPath } from 'url'; import fs from 'fs/promises'; const __filename = fileURLToPath(import.meta.url); const __dirname = path.dirname(__filename); const SAMPLES_DIR = path.join(__dirname, 'samples'); const SAMPLES = [ '01_sample_simple.pdf', '02_sample_invoice.pdf', '03_sample_compex.pdf', // 'gpc-genai-ocsummaryv2-content.pdf', // '2025-Wharton-GBK-AI-Adoption-Report_Full-Report.pdf' // 'statement.pdf' ]; const URL_SAMPLE = 'https://pdfobject.com/pdf/sample.pdf'; async function testSample(name, source) { console.log(`\n================================================================================`); console.log(`Processing: ${name}`); console.log(`Source: ${source}`); console.log(`--------------------------------------------------------------------------------`); try { const startTime = Date.now(); // Content (Markdown) console.log('\n📝 CONTENT PREVIEW (Markdown):'); const result = await parsePdfToMarkdown(source); // Verify new structure if (result.pages) { console.log(`\n📄 Pages Found: ${result.pages.length}`); result.pages.forEach((p, i) => { console.log(` Page ${p.pageNumber}: ${p.text.length} chars, ${p.images.length} images`); }); } const markdown = result.pages.map(p => p.text).join(''); const images = result.pages.flatMap(p => p.images); const processingTime = Date.now() - startTime; console.log('\n--- Full Text Preview ---'); console.log(markdown.substring(0, 200) + '...'); // Save extracted images to disk if (images && images.length > 0) { console.log(`\n🖼️ EXTRACTED IMAGES (${images.length}):`); // Create images directory for this PDF const imagesDir = path.join(SAMPLES_DIR, `${name}_images`); await fs.mkdir(imagesDir, { recursive: true }); for (let i = 0; i < images.length; i++) { const img = images[i]; // Determine file extension from MIME type const ext = img.mimeType.split('/')[1] || 'png'; const filename = `page_${img.page}_img_${i + 1}.${ext}`; const filepath = path.join(imagesDir, filename); // Decode base64 and save to file const buffer = Buffer.from(img.data, 'base64'); await fs.writeFile(filepath, buffer); console.log(` - Saved: ${filename} (${img.width}x${img.height}, ${img.mimeType})`); } console.log(`\n Images saved to: ${imagesDir}`); } // save to markdown file const markdownPath = path.join(SAMPLES_DIR, `${name}.md`); await fs.writeFile(markdownPath, markdown); const preview = markdown.substring(0, 500).replace(/\n/g, '\n '); console.log(` ${preview}...`); console.log(`\n [Total Length: ${markdown.length} chars]`); console.log(` Processing Time: ${processingTime}ms`); } catch (error) { console.error(`❌ Error processing ${name}:`, error); } } async function testPageFiltering() { console.log(`\n================================================================================`); console.log(`🧪 Testing Page Filtering`); console.log(`--------------------------------------------------------------------------------`); const sampleName = '03_sample_compex.pdf'; const samplePath = path.join(SAMPLES_DIR, sampleName); try { // Case 1: Specific Pages (Array) console.log('\nCase 1: Specific Pages [1]'); const result1 = await parsePdfToMarkdown(samplePath, [1]); console.log(`Pages returned: ${result1.pages.length}`); console.log(`Page numbers: ${result1.pages.map(p => p.pageNumber).join(', ')}`); // Case 2: Page Range (Positive Offset) - First Page console.log('\nCase 2: Page Range { offset: 0, length: 1 } (First Page)'); const result2 = await parsePdfToMarkdown(samplePath, { offset: 0, length: 1 }); console.log(`Pages returned: ${result2.pages.length}`); console.log(`Page numbers: ${result2.pages.map(p => p.pageNumber).join(', ')}`); // Case 3: Page Range (Negative Offset) - Last Page console.log('\nCase 3: Page Range { offset: -2, length: 2 } (Last Page)'); const result3 = await parsePdfToMarkdown(samplePath, { offset: -2, length: 2 }); console.log(`Pages returned: ${result3.pages.length}`); console.log(`Page numbers: ${result3.pages.map(p => p.pageNumber).join(', ')}`); // Case 4: Page Range (Large Length) - All Pages from start console.log('\nCase 4: Page Range { offset: 0, length: 100 } (All Pages)'); const result4 = await parsePdfToMarkdown(samplePath, { offset: 0, length: 100 }); console.log(`Pages returned: ${result4.pages.length}`); console.log(`Page numbers: ${result4.pages.map(p => p.pageNumber).join(', ')}`); // Case 5: Page Range (Large Negative Offset) - All Pages from end console.log('\nCase 5: Page Range { offset: -100, length: 100 } (All Pages from end)'); const result5 = await parsePdfToMarkdown(samplePath, { offset: -100, length: 100 }); console.log(`Pages returned: ${result5.pages.length}`); console.log(`Page numbers: ${result5.pages.map(p => p.pageNumber).join(', ')}`); // Case 6: Page Range (Large Length) - All Pages console.log('\nCase 6: Page Range [1,5,14] (All Pages)'); const result6 = await parsePdfToMarkdown(samplePath, [1, 5, 14]); console.log(`Pages returned: ${result6.pages.length}`); console.log(`Page numbers: ${result6.pages.map(p => p.pageNumber).join(', ')}`); } catch (error) { console.error('❌ Error in page filtering test:', error); } } async function main() { console.log('🧪 PDF v3 Sample Test Suite (@opendocsg/pdf2md)'); // Test Page Filtering await testPageFiltering(); // Test Local Samples for (const sample of SAMPLES) { const samplePath = path.join(SAMPLES_DIR, sample); await testSample(sample, samplePath); } // Test URL await testSample('URL Sample', URL_SAMPLE); } if (import.meta.url === `file://${process.argv[1]}`) { main().catch(console.error); }
wonderwhy-er/DesktopCommanderMCP
5,467
This is MCP server for Claude that gives it terminal control, file system search and diff file editing capabilities
TypeScript
wonderwhy-er
Eduard Ruzga
test/test-process-pagination.js
JavaScript
import assert from 'assert'; import { startProcess, readProcessOutput, interactWithProcess } from '../dist/tools/improved-process-tools.js'; /** * Test suite for process output pagination features * Tests offset/length parameters and context overflow protection */ // Helper to extract PID from start result function extractPid(result) { const match = result.content[0].text.match(/PID (\d+)/); return match ? parseInt(match[1]) : null; } // Helper to wait const wait = (ms) => new Promise(resolve => setTimeout(resolve, ms)); /** * Test 1: Basic offset=0 (new output) behavior for RUNNING processes */ async function testNewOutputBehavior() { console.log('\n📋 Test 1: Basic new output behavior (offset=0) for running process...'); // Start a long-running process that outputs incrementally const startResult = await startProcess({ command: 'node -e "let i=0; setInterval(() => { console.log(\'tick\' + i++); if(i>5) process.exit(0); }, 200)"', timeout_ms: 500 // Return before completion }); const pid = extractPid(startResult); assert(pid, 'Should get PID'); // First read - get initial output const read1 = await readProcessOutput({ pid, timeout_ms: 300 }); assert(!read1.isError, 'First read should succeed'); const lines1 = (read1.content[0].text.match(/tick\d/g) || []).length; console.log(` First read got ${lines1} tick lines`); // Wait for more output await wait(400); // Second read should get NEW output only const read2 = await readProcessOutput({ pid, timeout_ms: 300 }); assert(!read2.isError, 'Second read should succeed'); const text2 = read2.content[0].text; // Should NOT re-read tick0 if we already read it // (unless process completed, in which case all output is available) if (text2.includes('Process completed')) { console.log(' Process completed - all output available'); } else { console.log(` Second read status: ${text2.split('\n')[0]}`); } console.log('✅ Test 1 passed: New output behavior works correctly'); } /** * Test 2: Positive offset (absolute position) */ async function testAbsoluteOffset() { console.log('\n📋 Test 2: Absolute position (positive offset)...'); const startResult = await startProcess({ command: "node -e \"for(let i=0; i<10; i++) console.log('line' + i)\"", timeout_ms: 3000 }); const pid = extractPid(startResult); assert(pid, 'Should get PID'); await wait(500); // Read from line 5 const read = await readProcessOutput({ pid, offset: 5, length: 3, timeout_ms: 1000 }); assert(!read.isError, 'Read should succeed'); assert(read.content[0].text.includes('line5'), 'Should contain line5'); assert(read.content[0].text.includes('line6'), 'Should contain line6'); assert(read.content[0].text.includes('line7'), 'Should contain line7'); assert(!read.content[0].text.includes('line4'), 'Should NOT contain line4'); assert(read.content[0].text.includes('from line 5'), 'Status should show reading from line 5'); console.log('✅ Test 2 passed: Absolute position works correctly'); } /** * Test 3: Negative offset (tail behavior) */ async function testTailBehavior() { console.log('\n📋 Test 3: Tail behavior (negative offset)...'); const startResult = await startProcess({ command: "node -e \"for(let i=0; i<20; i++) console.log('line' + i)\"", timeout_ms: 3000 }); const pid = extractPid(startResult); assert(pid, 'Should get PID'); await wait(500); // Read last 5 lines (output has 21 lines: line0-line19 + empty) // Last 5 lines should include line16, line17, line18, line19 const read = await readProcessOutput({ pid, offset: -5, timeout_ms: 1000 }); assert(!read.isError, 'Read should succeed'); assert(read.content[0].text.includes('line16'), 'Should contain line16'); assert(read.content[0].text.includes('line19'), 'Should contain line19'); assert(!read.content[0].text.includes('line15'), 'Should NOT contain line15'); assert(read.content[0].text.includes('Reading last'), 'Status should indicate tail read'); console.log('✅ Test 3 passed: Tail behavior works correctly'); } /** * Test 4: Length limit enforcement */ async function testLengthLimit() { console.log('\n📋 Test 4: Length limit enforcement...'); const startResult = await startProcess({ command: "node -e \"for(let i=0; i<100; i++) console.log('line' + i)\"", timeout_ms: 3000 }); const pid = extractPid(startResult); assert(pid, 'Should get PID'); await wait(500); // Read with length limit of 10 from absolute position 0 const read = await readProcessOutput({ pid, offset: 1, length: 10, timeout_ms: 1000 }); assert(!read.isError, 'Read should succeed'); const outputText = read.content[0].text; // Should show "remaining" since we're only reading 10 of 100 lines assert(outputText.includes('remaining'), 'Should show remaining lines'); assert(outputText.includes('Reading 10 lines'), 'Should indicate reading 10 lines'); console.log('✅ Test 4 passed: Length limit works correctly'); } /** * Test 5: Runtime info for completed processes */ async function testRuntimeInfo() { console.log('\n📋 Test 5: Runtime info for completed processes...'); const startResult = await startProcess({ command: "node -e \"setTimeout(() => console.log('done'), 500)\"", timeout_ms: 200 // Return before completion }); const pid = extractPid(startResult); assert(pid, 'Should get PID'); // Wait for process to complete await wait(1000); const read = await readProcessOutput({ pid, timeout_ms: 1000 }); assert(!read.isError, 'Read should succeed'); assert(read.content[0].text.includes('runtime:'), 'Should show runtime'); assert(read.content[0].text.includes('Process completed'), 'Should show completion'); console.log('✅ Test 5 passed: Runtime info works correctly'); } /** * Test 6: interact_with_process output truncation */ async function testInteractTruncation() { console.log('\n📋 Test 6: interact_with_process output truncation...'); // Start a Python REPL const startResult = await startProcess({ command: 'python3 -i', timeout_ms: 3000 }); const pid = extractPid(startResult); if (!pid) { console.log('⚠️ Test 6 skipped: Could not start Python REPL'); return; } await wait(500); // Generate lots of output (more than default 1000 lines) const result = await interactWithProcess({ pid, input: 'for i in range(1500): print(f"line {i}")', timeout_ms: 10000 }); if (result.isError) { console.log('⚠️ Test 6 skipped: Python interaction failed'); return; } const outputText = result.content[0].text; // Check for truncation warning if (outputText.includes('truncated')) { assert(outputText.includes('use read_process_output'), 'Should suggest using read_process_output'); console.log('✅ Test 6 passed: Output truncation warning works'); } else { // If fileReadLineLimit is set higher than 1500, no truncation expected console.log('✅ Test 6 passed: Output within limits (no truncation needed)'); } } /** * Test 7: Re-reading output with absolute offset */ async function testReReadOutput() { console.log('\n📋 Test 7: Re-reading output with absolute offset...'); const startResult = await startProcess({ command: "node -e \"for(let i=0; i<5; i++) console.log('data' + i)\"", timeout_ms: 3000 }); const pid = extractPid(startResult); assert(pid, 'Should get PID'); await wait(500); // First read with offset=0 (consumes the "new" pointer for running sessions) const read1 = await readProcessOutput({ pid, offset: 0, timeout_ms: 1000 }); assert(!read1.isError, 'First read should succeed'); // Re-read from beginning using absolute offset const read2 = await readProcessOutput({ pid, offset: 1, length: 3, timeout_ms: 1000 }); assert(!read2.isError, 'Second read should succeed'); assert(read2.content[0].text.includes('data1'), 'Should re-read data1'); assert(read2.content[0].text.includes('data2'), 'Should re-read data2'); console.log('✅ Test 7 passed: Re-reading with absolute offset works'); } // Run all tests async function runAllTests() { console.log('🚀 Starting process pagination tests...\n'); try { await testNewOutputBehavior(); await testAbsoluteOffset(); await testTailBehavior(); await testLengthLimit(); await testRuntimeInfo(); await testInteractTruncation(); await testReReadOutput(); console.log('\n🎉 All pagination tests passed!'); return true; } catch (error) { console.error('\n❌ Test failed:', error.message); console.error(error.stack); return false; } } runAllTests() .then(success => process.exit(success ? 0 : 1)) .catch(error => { console.error('Test error:', error); process.exit(1); });
wonderwhy-er/DesktopCommanderMCP
5,467
This is MCP server for Claude that gives it terminal control, file system search and diff file editing capabilities
TypeScript
wonderwhy-er
Eduard Ruzga
test/test-read-completed-process.js
JavaScript
import assert from 'assert'; import { startProcess, readProcessOutput } from '../dist/tools/improved-process-tools.js'; /** * Proper test for read_process_output on completed processes * * This test should: * - FAIL when the bug exists (current behavior) * - PASS when the bug is fixed (desired behavior) */ async function testReadCompletedProcessOutput() { console.log('Testing read_process_output on completed process...'); // Start echo command with delay, but timeout before echo happens const startResult = await startProcess({ // Cross-platform delay + output using Node command: 'node -e "setTimeout(() => console.log(\'SUCCESS MESSAGE\'), 1000)"', timeout_ms: 500 // Returns before the output happens }); // Extract PID const pidMatch = startResult.content[0].text.match(/Process started with PID (\d+)/); assert(pidMatch, 'Should get PID from start_process'); const pid = parseInt(pidMatch[1]); // Wait for the actual command to complete await new Promise(resolve => setTimeout(resolve, 2000)); // Try to read the output - this should work when fixed const readResult = await readProcessOutput({ pid, timeout_ms: 1000 }); // ASSERT: Should be able to read from completed process assert(!readResult.isError, 'Should be able to read from completed process without error'); // ASSERT: Should contain the echo output assert(readResult.content[0].text.includes('SUCCESS MESSAGE'), 'Should contain the echo output from completed process'); console.log('✅ Successfully read from completed process'); console.log('✅ Retrieved echo output:', readResult.content[0].text); } /** * Test immediate completion scenario */ async function testImmediateCompletion() { console.log('Testing immediate completion...'); const startResult = await startProcess({ command: 'node -e "console.log(\'IMMEDIATE OUTPUT\')"', timeout_ms: 2000 }); // Extract PID const pidMatch = startResult.content[0].text.match(/Process started with PID (\d+)/); assert(pidMatch, 'Should get PID from start_process'); const pid = parseInt(pidMatch[1]); // Small delay to ensure process completed await new Promise(resolve => setTimeout(resolve, 100)); // Should be able to read from immediately completed process const readResult = await readProcessOutput({ pid, timeout_ms: 1000 }); assert(!readResult.isError, 'Should be able to read from immediately completed process'); assert(readResult.content[0].text.includes('IMMEDIATE OUTPUT'), 'Should contain immediate output from completed process'); console.log('✅ Successfully read from immediately completed process'); } // Run tests async function runTests() { try { await testReadCompletedProcessOutput(); await testImmediateCompletion(); console.log('\n🎉 All tests passed - read_process_output works on completed processes!'); return true; } catch (error) { console.log('\n❌ Test failed:', error.message); console.log('\n💡 This indicates the bug still exists:'); console.log(' read_process_output cannot read from completed processes'); console.log(' Expected behavior: Should return completion info and final output'); return false; } } runTests() .then(success => { process.exit(success ? 0 : 1); }) .catch(error => { console.error('Test error:', error); process.exit(1); });
wonderwhy-er/DesktopCommanderMCP
5,467
This is MCP server for Claude that gives it terminal control, file system search and diff file editing capabilities
TypeScript
wonderwhy-er
Eduard Ruzga
test/test-repl-interaction.js
JavaScript
import path from 'path'; import { fileURLToPath } from 'url'; import fs from 'fs/promises'; import { configManager } from '../dist/config-manager.js'; import { terminalManager } from '../dist/terminal-manager.js'; // Get directory name const __filename = fileURLToPath(import.meta.url); const __dirname = path.dirname(__filename); // Test output directory const OUTPUT_DIR = path.join(__dirname, 'test_output'); const OUTPUT_FILE = path.join(OUTPUT_DIR, 'repl_test_output.txt'); // Colors for console output const colors = { reset: '\x1b[0m', green: '\x1b[32m', red: '\x1b[31m', yellow: '\x1b[33m', blue: '\x1b[34m', cyan: '\x1b[36m' }; /** * Setup function to prepare for tests */ async function setup() { console.log(`${colors.blue}Setting up REPL interaction test...${colors.reset}`); // Save original config to restore later const originalConfig = await configManager.getConfig(); // Create output directory if it doesn't exist try { await fs.mkdir(OUTPUT_DIR, { recursive: true }); } catch (error) { console.warn(`${colors.yellow}Warning: Could not create output directory: ${error.message}${colors.reset}`); } return originalConfig; } /** * Teardown function to clean up after tests */ async function teardown(originalConfig) { console.log(`${colors.blue}Cleaning up after tests...${colors.reset}`); // Reset configuration to original await configManager.updateConfig(originalConfig); console.log(`${colors.green}✓ Teardown: config restored${colors.reset}`); } /** * Wait for the specified number of milliseconds */ function sleep(ms) { return new Promise(resolve => setTimeout(resolve, ms)); } /** * Test Python REPL interaction */ async function testPythonREPL() { console.log(`${colors.cyan}Running Python REPL interaction test...${colors.reset}`); try { // Setup Python test // Find Python executable const pythonCmd = process.platform === 'win32' ? 'python' : 'python3'; // Start a Python REPL process const result = await terminalManager.executeCommand(pythonCmd + ' -i', 5000); if (result.pid <= 0) { throw new Error(`Failed to start Python REPL: ${result.output}`); } console.log(`${colors.green}✓ Started Python REPL with PID ${result.pid}${colors.reset}`); // Wait for REPL to initialize await sleep(1000); // Send a command to the REPL with explicit Python print const testValue = Math.floor(Math.random() * 100); console.log(`${colors.blue}Test value: ${testValue}${colors.reset}`); // Send two different commands to increase chances of seeing output let success = terminalManager.sendInputToProcess(result.pid, `print("STARTING PYTHON TEST")\n`) if (!success) { throw new Error('Failed to send initial input to Python REPL'); } // Wait a bit between commands await sleep(1000); // Send the actual test command success = terminalManager.sendInputToProcess(result.pid, `print(f"REPL_TEST_VALUE: {${testValue} * 2}")\n`) if (!success) { throw new Error('Failed to send test input to Python REPL'); } console.log(`${colors.green}✓ Sent test commands to Python REPL${colors.reset}`); // Wait longer for the command to execute await sleep(3000); // Get output from the REPL const output = terminalManager.getNewOutput(result.pid); console.log(`Python REPL output: ${output || 'No output received'}`); // Write output to file for inspection await fs.writeFile(OUTPUT_FILE, `Python REPL output:\n${output || 'No output received'}`); // Terminate the REPL process const terminated = terminalManager.forceTerminate(result.pid); if (!terminated) { console.warn(`${colors.yellow}Warning: Could not terminate Python REPL process${colors.reset}`); } else { console.log(`${colors.green}✓ Terminated Python REPL process${colors.reset}`); } // Check if we got the expected output if (output && output.includes(`REPL_TEST_VALUE: ${testValue * 2}`)) { console.log(`${colors.green}✓ Python REPL test passed!${colors.reset}`); return true; } else { console.log(`${colors.red}✗ Python REPL test failed: Expected output containing "REPL_TEST_VALUE: ${testValue * 2}" but got: ${output}${colors.reset}`); return false; } } catch (error) { console.error(`${colors.red}✗ Python REPL test error: ${error.message}${colors.reset}`); return false; } } /** * Test Node.js REPL interaction */ async function testNodeREPL() { console.log(`${colors.cyan}Running Node.js REPL interaction test...${colors.reset}`); try { // Start a Node.js REPL process const result = await terminalManager.executeCommand('node -i', 5000); if (result.pid <= 0) { throw new Error(`Failed to start Node.js REPL: ${result.output}`); } console.log(`${colors.green}✓ Started Node.js REPL with PID ${result.pid}${colors.reset}`); // Wait for REPL to initialize await sleep(1000); // Send commands to the Node.js REPL const testValue = Math.floor(Math.random() * 100); console.log(`${colors.blue}Test value: ${testValue}${colors.reset}`); // Send multiple commands to increase chances of seeing output let success = terminalManager.sendInputToProcess(result.pid, `console.log("STARTING NODE TEST")\n`) if (!success) { throw new Error('Failed to send initial input to Node.js REPL'); } // Wait a bit between commands await sleep(1000); // Send the actual test command success = terminalManager.sendInputToProcess(result.pid, `console.log("NODE_REPL_TEST_VALUE:", ${testValue} * 3)\n`) if (!success) { throw new Error('Failed to send test input to Node.js REPL'); } console.log(`${colors.green}✓ Sent test commands to Node.js REPL${colors.reset}`); // Wait longer for the command to execute await sleep(3000); // Get output from the REPL const output = terminalManager.getNewOutput(result.pid); console.log(`Node.js REPL output: ${output || 'No output received'}`); // Append output to file for inspection await fs.appendFile(OUTPUT_FILE, `\n\nNode.js REPL output:\n${output || 'No output received'}`); // Terminate the REPL process const terminated = terminalManager.forceTerminate(result.pid); if (!terminated) { console.warn(`${colors.yellow}Warning: Could not terminate Node.js REPL process${colors.reset}`); } else { console.log(`${colors.green}✓ Terminated Node.js REPL process${colors.reset}`); } // Check if we got the expected output if (output && output.includes(`NODE_REPL_TEST_VALUE: ${testValue * 3}`)) { console.log(`${colors.green}✓ Node.js REPL test passed!${colors.reset}`); return true; } else { console.log(`${colors.red}✗ Node.js REPL test failed: Expected output containing "NODE_REPL_TEST_VALUE: ${testValue * 3}" but got: ${output}${colors.reset}`); return false; } } catch (error) { console.error(`${colors.red}✗ Node.js REPL test error: ${error.message}${colors.reset}`); return false; } } /** * Run all REPL interaction tests */ export default async function runTests() { let originalConfig; try { originalConfig = await setup(); const pythonTestResult = await testPythonREPL(); const nodeTestResult = await testNodeREPL(); // Overall test result const allPassed = pythonTestResult && nodeTestResult; console.log(`\n${colors.cyan}===== REPL Interaction Test Summary =====\n${colors.reset}`); console.log(`Python REPL test: ${pythonTestResult ? colors.green + 'PASSED' : colors.red + 'FAILED'}${colors.reset}`); console.log(`Node.js REPL test: ${nodeTestResult ? colors.green + 'PASSED' : colors.red + 'FAILED'}${colors.reset}`); console.log(`\nOverall result: ${allPassed ? colors.green + 'ALL TESTS PASSED! 🎉' : colors.red + 'SOME TESTS FAILED!'}${colors.reset}`); return allPassed; } catch (error) { console.error(`${colors.red}✗ Test execution error: ${error.message}${colors.reset}`); return false; } finally { if (originalConfig) { await teardown(originalConfig); } } } // If this file is run directly (not imported), execute the test if (import.meta.url === `file://${process.argv[1]}`) { runTests().catch(error => { console.error(`${colors.red}✗ Unhandled error: ${error}${colors.reset}`); process.exit(1); }); }
wonderwhy-er/DesktopCommanderMCP
5,467
This is MCP server for Claude that gives it terminal control, file system search and diff file editing capabilities
TypeScript
wonderwhy-er
Eduard Ruzga
test/test-search-code-edge-cases.js
JavaScript
/** * Additional comprehensive tests for search functionality using new streaming API * These tests cover edge cases and advanced scenarios */ import path from 'path'; import fs from 'fs/promises'; import { fileURLToPath } from 'url'; import { handleStartSearch, handleGetMoreSearchResults, handleStopSearch } from '../dist/handlers/search-handlers.js'; import { configManager } from '../dist/config-manager.js'; const __filename = fileURLToPath(import.meta.url); const __dirname = path.dirname(__filename); const EDGE_CASE_TEST_DIR = path.join(__dirname, 'search-edge-case-tests'); // Colors for console output const colors = { reset: '\x1b[0m', green: '\x1b[32m', red: '\x1b[31m', yellow: '\x1b[33m', blue: '\x1b[34m' }; /** * Helper function to wait for search completion and get all results */ async function searchAndWaitForCompletion(searchArgs, timeout = 10000) { const result = await handleStartSearch(searchArgs); // Extract session ID from result const sessionIdMatch = result.content[0].text.match(/Started .+ session: (.+)/); if (!sessionIdMatch) { throw new Error('Could not extract session ID from search result'); } const sessionId = sessionIdMatch[1]; try { // Wait for completion by polling const startTime = Date.now(); while (Date.now() - startTime < timeout) { const moreResults = await handleGetMoreSearchResults({ sessionId }); if (moreResults.content[0].text.includes('✅ Search completed')) { return { initialResult: result, finalResult: moreResults, sessionId }; } if (moreResults.content[0].text.includes('❌ ERROR')) { throw new Error(`Search failed: ${moreResults.content[0].text}`); } // Wait a bit before polling again await new Promise(resolve => setTimeout(resolve, 100)); } throw new Error('Search timed out'); } finally { // Always stop the search session to prevent hanging try { await handleStopSearch({ sessionId }); } catch (e) { // Ignore errors when stopping - session might already be completed } } } /** * Setup function for edge case tests */ async function setupEdgeCases() { console.log(`${colors.blue}Setting up edge case tests...${colors.reset}`); const originalConfig = await configManager.getConfig(); await configManager.setValue('allowedDirectories', [EDGE_CASE_TEST_DIR]); await fs.mkdir(EDGE_CASE_TEST_DIR, { recursive: true }); // Create files with edge cases // Empty file await fs.writeFile(path.join(EDGE_CASE_TEST_DIR, 'empty.txt'), ''); // File with only whitespace await fs.writeFile(path.join(EDGE_CASE_TEST_DIR, 'whitespace.txt'), ' \n\t\n \n'); // File with very long lines (use unique pattern to avoid conflicts with large.txt) const longLine = 'a'.repeat(10000) + 'LONGLINEPATTERN' + 'b'.repeat(10000); await fs.writeFile(path.join(EDGE_CASE_TEST_DIR, 'long-lines.txt'), longLine); // File with special characters await fs.writeFile(path.join(EDGE_CASE_TEST_DIR, 'special-chars.txt'), 'Special chars: @#$%^&*(){}[]|\\:";\'<>?,./\nUnicode: 😀🎉🔍\nPattern with special chars: test@pattern'); // File with binary content (should be handled gracefully) const binaryData = Buffer.from([0x00, 0x01, 0x02, 0x03, 0xFF, 0xFE, 0xFD]); await fs.writeFile(path.join(EDGE_CASE_TEST_DIR, 'binary.bin'), binaryData); // Large file (for performance testing) const largeContent = 'This is line with pattern\n'.repeat(1000); await fs.writeFile(path.join(EDGE_CASE_TEST_DIR, 'large.txt'), largeContent); // File with regex special characters in content await fs.writeFile(path.join(EDGE_CASE_TEST_DIR, 'regex-chars.txt'), 'Content with regex chars: .+*?^${}()|[]\\\nPattern: test.pattern\nAnother: test*pattern'); return originalConfig; } /** * Teardown function for edge case tests */ async function teardownEdgeCases(originalConfig) { // Clean up any remaining search sessions try { const { handleListSearches, handleStopSearch } = await import('../dist/handlers/search-handlers.js'); const sessionsResult = await handleListSearches(); if (sessionsResult.content && sessionsResult.content[0] && sessionsResult.content[0].text) { const sessionsText = sessionsResult.content[0].text; if (!sessionsText.includes('No active searches')) { // Extract session IDs and stop them const sessionMatches = sessionsText.match(/Session: (\S+)/g); if (sessionMatches) { for (const match of sessionMatches) { const sessionId = match.replace('Session: ', ''); try { await handleStopSearch({ sessionId }); } catch (e) { // Ignore errors - session might already be stopped } } } } } } catch (e) { // Ignore errors in cleanup } await fs.rm(EDGE_CASE_TEST_DIR, { force: true, recursive: true }); await configManager.updateConfig(originalConfig); } /** * Assert function */ function assert(condition, message) { if (!condition) { throw new Error(`Assertion failed: ${message}`); } } /** * Test empty and whitespace files */ async function testEmptyFiles() { console.log(`${colors.yellow}Testing empty and whitespace files...${colors.reset}`); const { finalResult } = await searchAndWaitForCompletion({ path: EDGE_CASE_TEST_DIR, pattern: 'pattern', searchType: 'content' }); const text = finalResult.content[0].text; // Should not find matches in empty files, but should handle gracefully const isValidResponse = !text.includes('empty.txt') && !text.includes('whitespace.txt') || text.includes('No matches'); assert(isValidResponse, 'Should not find matches in empty files'); console.log(`${colors.green}✓ Empty files test passed${colors.reset}`); } /** * Test very long lines */ async function testLongLines() { console.log(`${colors.yellow}Testing very long lines...${colors.reset}`); const { finalResult } = await searchAndWaitForCompletion({ path: EDGE_CASE_TEST_DIR, pattern: 'LONGLINEPATTERN', searchType: 'content' }); const text = finalResult.content[0].text; assert(text.includes('long-lines.txt'), 'Should find pattern in files with very long lines'); console.log(`${colors.green}✓ Long lines test passed${colors.reset}`); } /** * Test special characters and Unicode */ async function testSpecialCharacters() { console.log(`${colors.yellow}Testing special characters and Unicode...${colors.reset}`); const { finalResult } = await searchAndWaitForCompletion({ path: EDGE_CASE_TEST_DIR, pattern: 'test@pattern', searchType: 'content' }); const text = finalResult.content[0].text; assert(text.includes('special-chars.txt'), 'Should find patterns with special characters'); console.log(`${colors.green}✓ Special characters test passed${colors.reset}`); } /** * Test binary files handling */ async function testBinaryFiles() { console.log(`${colors.yellow}Testing binary files handling...${colors.reset}`); const { finalResult } = await searchAndWaitForCompletion({ path: EDGE_CASE_TEST_DIR, pattern: 'pattern', searchType: 'content' }); const text = finalResult.content[0].text; // Binary files should either be ignored or handled gracefully // Should not crash the search assert(typeof text === 'string', 'Should return string result even with binary files present'); console.log(`${colors.green}✓ Binary files test passed${colors.reset}`); } /** * Test large file performance */ async function testLargeFiles() { console.log(`${colors.yellow}Testing large file performance...${colors.reset}`); const startTime = Date.now(); const { finalResult } = await searchAndWaitForCompletion({ path: EDGE_CASE_TEST_DIR, pattern: 'pattern', searchType: 'content', maxResults: 10 // Limit results for performance }); const endTime = Date.now(); const duration = endTime - startTime; const text = finalResult.content[0].text; assert(text.includes('large.txt'), 'Should find matches in large files'); // Performance check - should complete within reasonable time (10 seconds) assert(duration < 10000, `Search should complete within 10 seconds, took ${duration}ms`); console.log(`${colors.green}✓ Large files test passed (${duration}ms)${colors.reset}`); } /** * Test concurrent searches */ async function testConcurrentSearches() { console.log(`${colors.yellow}Testing concurrent searches...${colors.reset}`); // Start multiple searches concurrently const promises = [ handleStartSearch({ path: EDGE_CASE_TEST_DIR, pattern: 'pattern', searchType: 'content' }), handleStartSearch({ path: EDGE_CASE_TEST_DIR, pattern: 'test', searchType: 'content' }), handleStartSearch({ path: EDGE_CASE_TEST_DIR, pattern: 'chars', searchType: 'content' }) ]; const results = await Promise.all(promises); // All searches should complete successfully results.forEach((result, index) => { assert(result.content, `Search ${index + 1} should have content`); assert(result.content.length > 0, `Search ${index + 1} should not be empty`); }); console.log(`${colors.green}✓ Concurrent searches test passed${colors.reset}`); } /** * Test search with very short timeout */ async function testVeryShortTimeout() { console.log(`${colors.yellow}Testing very short timeout...${colors.reset}`); const result = await handleStartSearch({ path: EDGE_CASE_TEST_DIR, pattern: 'pattern', searchType: 'content', timeout_ms: 1 // Extremely short timeout }); assert(result.content, 'Should handle timeout gracefully'); const text = result.content[0].text; // Should either return results or handle timeout gracefully const hasValidResponse = text.includes('session:') || text.includes('Error') || text.includes('timeout'); assert(hasValidResponse, 'Should handle very short timeout appropriately'); console.log(`${colors.green}✓ Very short timeout test passed${colors.reset}`); } /** * Test invalid file patterns */ async function testInvalidFilePatterns() { console.log(`${colors.yellow}Testing invalid file patterns...${colors.reset}`); // Test with invalid glob pattern const result = await handleStartSearch({ path: EDGE_CASE_TEST_DIR, pattern: 'pattern', searchType: 'content', filePattern: '***invalid***' }); // Should handle gracefully assert(result.content, 'Should handle invalid file patterns gracefully'); console.log(`${colors.green}✓ Invalid file patterns test passed${colors.reset}`); } /** * Test zero max results */ async function testZeroMaxResults() { console.log(`${colors.yellow}Testing zero max results...${colors.reset}`); const result = await handleStartSearch({ path: EDGE_CASE_TEST_DIR, pattern: 'pattern', searchType: 'content', maxResults: 0 }); const text = result.content[0].text; // Should return appropriate response assert(typeof text === 'string', 'Should return string result'); console.log(`${colors.green}✓ Zero max results test passed${colors.reset}`); } /** * Test extremely large context lines */ async function testLargeContextLines() { console.log(`${colors.yellow}Testing large context lines...${colors.reset}`); const result = await handleStartSearch({ path: EDGE_CASE_TEST_DIR, pattern: 'pattern', searchType: 'content', contextLines: 1000 // Very large context }); assert(result.content, 'Should handle large context lines'); const text = result.content[0].text; assert(typeof text === 'string', 'Should return string result'); console.log(`${colors.green}✓ Large context lines test passed${colors.reset}`); } /** * Test path traversal security */ async function testPathTraversalSecurity() { console.log(`${colors.yellow}Testing path traversal security...${colors.reset}`); // Test with path traversal attempts try { const result = await handleStartSearch({ path: EDGE_CASE_TEST_DIR + '/../../../etc', pattern: 'pattern', searchType: 'content' }); // If it doesn't throw, it should handle gracefully assert(result.content, 'Should handle path traversal attempts gracefully'); const text = result.content[0].text; const isSecure = text.includes('not allowed') || text.includes('Error') || text.includes('permission'); assert(isSecure, 'Should handle path traversal securely'); } catch (error) { // It's acceptable to throw an error for security violations const isSecurityError = error.message.includes('not allowed') || error.message.includes('permission'); assert(isSecurityError, 'Should reject unauthorized path access'); } console.log(`${colors.green}✓ Path traversal security test passed${colors.reset}`); } /** * Test memory usage with many small files */ async function testManySmallFiles() { console.log(`${colors.yellow}Testing many small files...${colors.reset}`); // Create subdirectory with many small files const manyFilesDir = path.join(EDGE_CASE_TEST_DIR, 'many-files'); await fs.mkdir(manyFilesDir, { recursive: true }); try { // Create 100 small files const promises = []; for (let i = 0; i < 100; i++) { promises.push(fs.writeFile( path.join(manyFilesDir, `file${i}.txt`), `This is file ${i} with pattern ${i}` )); } await Promise.all(promises); const { finalResult } = await searchAndWaitForCompletion({ path: manyFilesDir, pattern: 'pattern', searchType: 'content', maxResults: 50 }); const text = finalResult.content[0].text; assert(text.includes('pattern') || text.includes('No matches'), 'Should handle many small files'); console.log(`${colors.green}✓ Many small files test passed${colors.reset}`); } finally { // Clean up many files await fs.rm(manyFilesDir, { force: true, recursive: true }); } } /** * Test filePattern with multiple values, including whitespace and empty tokens */ async function testFilePatternWithMultipleValues() { console.log(`${colors.yellow}Testing filePattern with multiple values...${colors.reset}`); // Create test files await fs.writeFile(path.join(EDGE_CASE_TEST_DIR, 'file1.ts'), 'export const myTsVar = "patternTs";'); await fs.writeFile(path.join(EDGE_CASE_TEST_DIR, 'file2.js'), 'const myJsVar = "patternJs";'); await fs.writeFile(path.join(EDGE_CASE_TEST_DIR, 'file3.py'), 'my_py_var = "patternPy"'); await fs.writeFile(path.join(EDGE_CASE_TEST_DIR, 'file4.java'), 'String myJavaVar = "patternJava";'); await fs.writeFile(path.join(EDGE_CASE_TEST_DIR, 'file5.go'), 'var myGoVar = "patternGo"'); await fs.writeFile(path.join(EDGE_CASE_TEST_DIR, 'file6.txt'), 'This is a text file.'); // Test with valid multiple patterns let { finalResult } = await searchAndWaitForCompletion({ path: EDGE_CASE_TEST_DIR, pattern: 'pattern', searchType: 'content', filePattern: '*.ts|*.js|*.py' }); let text = finalResult.content[0].text; assert(text.includes('file1.ts'), 'Should find match in file1.ts'); assert(text.includes('file2.js'), 'Should find match in file2.js'); assert(text.includes('file3.py'), 'Should find match in file3.py'); assert(!text.includes('file4.java'), 'Should not find match in file4.java'); assert(!text.includes('file5.go'), 'Should not find match in file5.go'); // Test with patterns including whitespace ({ finalResult } = await searchAndWaitForCompletion({ path: EDGE_CASE_TEST_DIR, pattern: 'pattern', searchType: 'content', filePattern: ' *.ts | *.js ' })); text = finalResult.content[0].text; assert(text.includes('file1.ts'), 'Should find match with whitespace-padded patterns (file1.ts)'); assert(text.includes('file2.js'), 'Should find match with whitespace-padded patterns (file2.js)'); assert(!text.includes('file3.py'), 'Should not find match with whitespace-padded patterns (file3.py)'); console.log(`${colors.green}✓ FilePattern with multiple values test passed${colors.reset}`); } /** * Main test runner for edge cases */ export async function testSearchCodeEdgeCases() { console.log(`${colors.blue}Starting search functionality edge case tests...${colors.reset}`); let originalConfig; try { // Setup originalConfig = await setupEdgeCases(); // Run all edge case tests await testEmptyFiles(); await testLongLines(); await testSpecialCharacters(); await testBinaryFiles(); await testLargeFiles(); await testConcurrentSearches(); await testVeryShortTimeout(); await testInvalidFilePatterns(); await testZeroMaxResults(); await testLargeContextLines(); await testPathTraversalSecurity(); await testManySmallFiles(); await testFilePatternWithMultipleValues(); console.log(`${colors.green}✅ All search functionality edge case tests passed!${colors.reset}`); return true; } catch (error) { console.error(`${colors.red}❌ Edge case test failed: ${error.message}${colors.reset}`); console.error(error.stack); throw error; } finally { // Cleanup if (originalConfig) { await teardownEdgeCases(originalConfig); } // Force cleanup of search manager to ensure process can exit try { const { searchManager, stopSearchManagerCleanup } = await import('../dist/search-manager.js'); // Terminate all active sessions const activeSessions = searchManager.listSearchSessions(); for (const session of activeSessions) { searchManager.terminateSearch(session.id); } // Stop the cleanup interval stopSearchManagerCleanup(); // Clear the sessions map searchManager.sessions?.clear?.(); } catch (e) { // Ignore import errors } } } // Export for use in test runners export default testSearchCodeEdgeCases; // Run tests if this file is executed directly if (import.meta.url === `file://${process.argv[1]}`) { testSearchCodeEdgeCases().then(() => { console.log('Edge case tests completed successfully.'); process.exit(0); }).catch(error => { console.error('Edge case test execution failed:', error); process.exit(1); }); }
wonderwhy-er/DesktopCommanderMCP
5,467
This is MCP server for Claude that gives it terminal control, file system search and diff file editing capabilities
TypeScript
wonderwhy-er
Eduard Ruzga
test/test-search-code.js
JavaScript
/** * Unit tests for search functionality using new streaming search API */ import path from 'path'; import fs from 'fs/promises'; import { fileURLToPath } from 'url'; import { handleStartSearch, handleGetMoreSearchResults, handleStopSearch } from '../dist/handlers/search-handlers.js'; import { configManager } from '../dist/config-manager.js'; const __filename = fileURLToPath(import.meta.url); const __dirname = path.dirname(__filename); // Test directory and files const TEST_DIR = path.join(__dirname, 'search-test-files'); const TEST_FILE_1 = path.join(TEST_DIR, 'test1.js'); const TEST_FILE_2 = path.join(TEST_DIR, 'test2.ts'); const TEST_FILE_3 = path.join(TEST_DIR, 'hidden.txt'); const TEST_FILE_4 = path.join(TEST_DIR, 'subdir', 'nested.py'); // Colors for console output const colors = { reset: '\x1b[0m', green: '\x1b[32m', red: '\x1b[31m', yellow: '\x1b[33m', blue: '\x1b[34m' }; /** * Helper function to wait for search completion and get all results */ async function searchAndWaitForCompletion(searchArgs, timeout = 10000) { const result = await handleStartSearch(searchArgs); // Extract session ID from result const sessionIdMatch = result.content[0].text.match(/Started .+ session: (.+)/); if (!sessionIdMatch) { throw new Error('Could not extract session ID from search result'); } const sessionId = sessionIdMatch[1]; try { // Wait for completion by polling const startTime = Date.now(); while (Date.now() - startTime < timeout) { const moreResults = await handleGetMoreSearchResults({ sessionId }); if (moreResults.content[0].text.includes('✅ Search completed')) { return { initialResult: result, finalResult: moreResults, sessionId }; } if (moreResults.content[0].text.includes('❌ ERROR')) { throw new Error(`Search failed: ${moreResults.content[0].text}`); } // Wait a bit before polling again await new Promise(resolve => setTimeout(resolve, 100)); } throw new Error('Search timed out'); } finally { // Always stop the search session to prevent hanging try { await handleStopSearch({ sessionId }); } catch (e) { // Ignore errors when stopping - session might already be completed } } } /** * Setup function to prepare test environment */ async function setup() { console.log(`${colors.blue}Setting up search code tests...${colors.reset}`); // Save original config const originalConfig = await configManager.getConfig(); // Set allowed directories to include test directory await configManager.setValue('allowedDirectories', [TEST_DIR]); // Create test directory structure await fs.mkdir(TEST_DIR, { recursive: true }); await fs.mkdir(path.join(TEST_DIR, 'subdir'), { recursive: true }); // Create test files with various content await fs.writeFile(TEST_FILE_1, `// JavaScript test file function searchFunction() { const pattern = 'test pattern'; console.log('This is a test function'); return pattern; } // Another function function anotherFunction() { const result = searchFunction(); return result; } `); await fs.writeFile(TEST_FILE_2, `// TypeScript test file interface TestInterface { pattern: string; value: number; } class TestClass implements TestInterface { pattern: string = 'test pattern'; value: number = 42; searchMethod(): string { return this.pattern; } } export { TestClass }; `); await fs.writeFile(TEST_FILE_3, `This is a hidden text file. It contains some test content. Pattern matching should work here too. Multiple lines with different patterns. `); await fs.writeFile(TEST_FILE_4, `# Python test file import os import sys def search_function(): pattern = "test pattern" print("This is a python function") return pattern class TestClass: def __init__(self): self.pattern = "test pattern" def search_method(self): return self.pattern `); console.log(`${colors.green}✓ Setup complete: Test files created${colors.reset}`); return originalConfig; } /** * Teardown function to clean up after tests */ async function teardown(originalConfig) { console.log(`${colors.blue}Cleaning up search code tests...${colors.reset}`); // Clean up any remaining search sessions try { const { handleListSearches, handleStopSearch } = await import('../dist/handlers/search-handlers.js'); const sessionsResult = await handleListSearches(); if (sessionsResult.content && sessionsResult.content[0] && sessionsResult.content[0].text) { const sessionsText = sessionsResult.content[0].text; if (!sessionsText.includes('No active searches')) { // Extract session IDs and stop them const sessionMatches = sessionsText.match(/Session: (\S+)/g); if (sessionMatches) { for (const match of sessionMatches) { const sessionId = match.replace('Session: ', ''); try { await handleStopSearch({ sessionId }); } catch (e) { // Ignore errors - session might already be stopped } } } } } } catch (e) { // Ignore errors in cleanup } // Remove test directory and all files await fs.rm(TEST_DIR, { force: true, recursive: true }); // Restore original config await configManager.updateConfig(originalConfig); console.log(`${colors.green}✓ Teardown complete: Test files removed and config restored${colors.reset}`); } /** * Assert function for test validation */ function assert(condition, message) { if (!condition) { throw new Error(`Assertion failed: ${message}`); } } /** * Test basic search functionality */ async function testBasicSearch() { console.log(`${colors.yellow}Testing basic search functionality...${colors.reset}`); const { finalResult } = await searchAndWaitForCompletion({ path: TEST_DIR, pattern: 'pattern', searchType: 'content' }); assert(finalResult.content, 'Result should have content'); assert(finalResult.content.length > 0, 'Content should not be empty'); const text = finalResult.content[0].text; assert(text.includes('test1.js'), 'Should find matches in test1.js'); assert(text.includes('test2.ts'), 'Should find matches in test2.ts'); assert(text.includes('nested.py'), 'Should find matches in nested.py'); console.log(`${colors.green}✓ Basic search test passed${colors.reset}`); } /** * Test case-sensitive search */ async function testCaseSensitiveSearch() { console.log(`${colors.yellow}Testing case-sensitive search...${colors.reset}`); // Search for 'Pattern' (capital P) with case sensitivity const { finalResult } = await searchAndWaitForCompletion({ path: TEST_DIR, pattern: 'Pattern', searchType: 'content', ignoreCase: false }); const text = finalResult.content[0].text; // Should only find matches where 'Pattern' appears with capital P assert(text.includes('hidden.txt'), 'Should find Pattern in hidden.txt'); console.log(`${colors.green}✓ Case-sensitive search test passed${colors.reset}`); } /** * Test case-insensitive search */ async function testCaseInsensitiveSearch() { console.log(`${colors.yellow}Testing case-insensitive search...${colors.reset}`); const { finalResult } = await searchAndWaitForCompletion({ path: TEST_DIR, pattern: 'PATTERN', searchType: 'content', ignoreCase: true }); const text = finalResult.content[0].text; assert(text.includes('test1.js'), 'Should find pattern in test1.js'); assert(text.includes('test2.ts'), 'Should find pattern in test2.ts'); assert(text.includes('nested.py'), 'Should find pattern in nested.py'); console.log(`${colors.green}✓ Case-insensitive search test passed${colors.reset}`); } /** * Test file pattern filtering */ async function testFilePatternFiltering() { console.log(`${colors.yellow}Testing file pattern filtering...${colors.reset}`); // Search only in TypeScript files const { finalResult } = await searchAndWaitForCompletion({ path: TEST_DIR, pattern: 'pattern', searchType: 'content', filePattern: '*.ts' }); const text = finalResult.content[0].text; assert(text.includes('test2.ts'), 'Should find matches in TypeScript files'); assert(!text.includes('test1.js'), 'Should not include JavaScript files'); assert(!text.includes('nested.py'), 'Should not include Python files'); console.log(`${colors.green}✓ File pattern filtering test passed${colors.reset}`); } /** * Test maximum results limiting */ async function testMaxResults() { console.log(`${colors.yellow}Testing maximum results limiting...${colors.reset}`); // Test that the maxResults parameter is accepted and doesn't cause errors const { finalResult } = await searchAndWaitForCompletion({ path: TEST_DIR, pattern: 'function', // This pattern should appear multiple times searchType: 'content', maxResults: 5 // Small limit }); assert(finalResult.content, 'Should have content'); assert(finalResult.content.length > 0, 'Content should not be empty'); const text = finalResult.content[0].text; // Verify we get some results assert(text.length > 0, 'Should have some results'); // Should have results but respect the limit const hasResults = text.includes('function') || text.includes('No matches found'); assert(hasResults, 'Should have function results or no matches'); console.log(`${colors.green}✓ Max results limiting test passed${colors.reset}`); } /** * Test context lines functionality */ async function testContextLines() { console.log(`${colors.yellow}Testing context lines functionality...${colors.reset}`); const { finalResult } = await searchAndWaitForCompletion({ path: TEST_DIR, pattern: 'searchFunction', searchType: 'content', contextLines: 1 }); const text = finalResult.content[0].text; // With context lines, we should see lines before and after the match assert(text.length > 0, 'Should have context around matches'); console.log(`${colors.green}✓ Context lines test passed${colors.reset}`); } /** * Test hidden files inclusion */ async function testIncludeHidden() { console.log(`${colors.yellow}Testing hidden files inclusion...${colors.reset}`); // First, create a hidden file (starts with dot) const hiddenFile = path.join(TEST_DIR, '.hidden-file.txt'); await fs.writeFile(hiddenFile, 'This is hidden content with pattern'); try { const { finalResult } = await searchAndWaitForCompletion({ path: TEST_DIR, pattern: 'hidden content', searchType: 'content', includeHidden: true }); const text = finalResult.content[0].text; const hasHiddenResults = text.includes('.hidden-file.txt') || text.includes('No matches found'); assert(hasHiddenResults, 'Should handle hidden files when includeHidden is true'); console.log(`${colors.green}✓ Include hidden files test passed${colors.reset}`); } finally { // Clean up hidden file await fs.rm(hiddenFile, { force: true }); } } /** * Test timeout functionality */ async function testTimeout() { console.log(`${colors.yellow}Testing timeout functionality...${colors.reset}`); // Use a reasonable timeout const { finalResult } = await searchAndWaitForCompletion({ path: TEST_DIR, pattern: 'pattern', searchType: 'content', timeout_ms: 5000 // 5 seconds should be plenty }); assert(finalResult.content, 'Result should have content even with timeout'); assert(finalResult.content.length > 0, 'Content should not be empty'); const text = finalResult.content[0].text; // Should have results or indicate completion const hasValidResult = text.includes('pattern') || text.includes('No matches found') || text.includes('completed'); assert(hasValidResult, 'Should handle timeout gracefully'); console.log(`${colors.green}✓ Timeout test passed${colors.reset}`); } /** * Test no matches found scenario */ async function testNoMatches() { console.log(`${colors.yellow}Testing no matches found scenario...${colors.reset}`); const { finalResult } = await searchAndWaitForCompletion({ path: TEST_DIR, pattern: 'this-pattern-definitely-does-not-exist-anywhere', searchType: 'content' }); assert(finalResult.content, 'Result should have content'); assert(finalResult.content.length > 0, 'Content should not be empty'); const text = finalResult.content[0].text; assert(text.includes('No matches') || text.includes('Total results found: 0'), 'Should return no matches message'); console.log(`${colors.green}✓ No matches test passed${colors.reset}`); } /** * Test invalid path handling */ async function testInvalidPath() { console.log(`${colors.yellow}Testing invalid path handling...${colors.reset}`); try { const result = await handleStartSearch({ path: '/nonexistent/path/that/does/not/exist', pattern: 'pattern', searchType: 'content' }); // Should handle gracefully assert(result.content, 'Result should have content'); const text = result.content[0].text; const isValidResponse = text.includes('Error') || text.includes('session:') || text.includes('not allowed'); assert(isValidResponse, 'Should handle invalid path gracefully'); console.log(`${colors.green}✓ Invalid path test passed${colors.reset}`); } catch (error) { // It's also acceptable for the function to throw an error for invalid paths console.log(`${colors.green}✓ Invalid path test passed (threw error as expected)${colors.reset}`); } } /** * Test schema validation with invalid arguments */ async function testInvalidArguments() { console.log(`${colors.yellow}Testing invalid arguments handling...${colors.reset}`); // Test missing required path try { const result = await handleStartSearch({ pattern: 'test' // Missing path }); const text = result.content[0].text; assert(text.includes('Invalid arguments'), 'Should validate path is required'); } catch (error) { // Also acceptable to throw assert(error.message.includes('path') || error.message.includes('required'), 'Should validate path is required'); } // Test missing required pattern try { const result = await handleStartSearch({ path: TEST_DIR // Missing pattern }); const text = result.content[0].text; assert(text.includes('Invalid arguments'), 'Should validate pattern is required'); } catch (error) { // Also acceptable to throw assert(error.message.includes('pattern') || error.message.includes('required'), 'Should validate pattern is required'); } console.log(`${colors.green}✓ Invalid arguments test passed${colors.reset}`); } /** * Test file search functionality */ async function testFileSearch() { console.log(`${colors.yellow}Testing file search functionality...${colors.reset}`); const { finalResult } = await searchAndWaitForCompletion({ path: TEST_DIR, pattern: '*.js', searchType: 'files' }); const text = finalResult.content[0].text; assert(text.includes('test1.js'), 'Should find JavaScript files'); console.log(`${colors.green}✓ File search test passed${colors.reset}`); } /** * Main test runner function */ export async function testSearchCode() { console.log(`${colors.blue}Starting search functionality tests...${colors.reset}`); let originalConfig; try { // Setup originalConfig = await setup(); // Run all tests await testBasicSearch(); await testCaseSensitiveSearch(); await testCaseInsensitiveSearch(); await testFilePatternFiltering(); await testMaxResults(); await testContextLines(); await testIncludeHidden(); await testTimeout(); await testNoMatches(); await testInvalidPath(); await testInvalidArguments(); await testFileSearch(); console.log(`${colors.green}✅ All search functionality tests passed!${colors.reset}`); return true; } catch (error) { console.error(`${colors.red}❌ Test failed: ${error.message}${colors.reset}`); console.error(error.stack); throw error; } finally { // Cleanup if (originalConfig) { await teardown(originalConfig); } // Force cleanup of search manager to ensure process can exit try { const { searchManager, stopSearchManagerCleanup } = await import('../dist/search-manager.js'); // Terminate all active sessions const activeSessions = searchManager.listSearchSessions(); for (const session of activeSessions) { searchManager.terminateSearch(session.id); } // Stop the cleanup interval stopSearchManagerCleanup(); // Clear the sessions map searchManager.sessions?.clear?.(); } catch (e) { // Ignore import errors } } } // Export for use in run-all-tests.js export default testSearchCode; // Run tests if this file is executed directly if (import.meta.url === `file://${process.argv[1]}`) { testSearchCode().then(() => { console.log('Search tests completed successfully.'); process.exit(0); }).catch(error => { console.error('Test execution failed:', error); process.exit(1); }); }
wonderwhy-er/DesktopCommanderMCP
5,467
This is MCP server for Claude that gives it terminal control, file system search and diff file editing capabilities
TypeScript
wonderwhy-er
Eduard Ruzga
test/test-symlink-security.js
JavaScript
/** * Test script for symlink security in validatePath * * This script tests that symlinks cannot be used to bypass allowedDirectories restrictions. * The attack scenario: * 1. User configures allowedDirectories to ["/allowed"] * 2. Attacker creates symlink: /allowed/evil → /etc/passwd (or other restricted path) * 3. validatePath should detect this and block access */ import { configManager } from '../dist/config-manager.js'; import { validatePath } from '../dist/tools/filesystem.js'; import fs from 'fs/promises'; import path from 'path'; import { fileURLToPath } from 'url'; import assert from 'assert'; import os from 'os'; const __filename = fileURLToPath(import.meta.url); const __dirname = path.dirname(__filename); // Test directories const ALLOWED_DIR = path.join(__dirname, 'test_symlink_allowed'); const RESTRICTED_DIR = path.join(__dirname, 'test_symlink_restricted'); const SYMLINK_TO_RESTRICTED = path.join(ALLOWED_DIR, 'link_to_restricted'); const SYMLINK_TO_RESTRICTED_FILE = path.join(ALLOWED_DIR, 'link_to_secret'); /** * Clean up test directories */ async function cleanup() { console.log('Cleaning up test directories...'); await fs.rm(ALLOWED_DIR, { recursive: true, force: true }).catch(() => {}); await fs.rm(RESTRICTED_DIR, { recursive: true, force: true }).catch(() => {}); } /** * Setup test environment */ async function setup() { await cleanup(); // Create directories await fs.mkdir(ALLOWED_DIR, { recursive: true }); await fs.mkdir(RESTRICTED_DIR, { recursive: true }); // Create a file in the restricted directory (simulates /etc/passwd or ~/.ssh/id_rsa) await fs.writeFile(path.join(RESTRICTED_DIR, 'secret.txt'), 'TOP SECRET DATA'); // Create a normal file in the allowed directory await fs.writeFile(path.join(ALLOWED_DIR, 'normal.txt'), 'Normal allowed content'); // Create symlinks pointing to restricted locations // Symlink to restricted directory await fs.symlink(RESTRICTED_DIR, SYMLINK_TO_RESTRICTED); // Symlink to specific restricted file await fs.symlink(path.join(RESTRICTED_DIR, 'secret.txt'), SYMLINK_TO_RESTRICTED_FILE); console.log('✓ Setup complete'); console.log(` Allowed dir: ${ALLOWED_DIR}`); console.log(` Restricted dir: ${RESTRICTED_DIR}`); console.log(` Symlink (dir): ${SYMLINK_TO_RESTRICTED} → ${RESTRICTED_DIR}`); console.log(` Symlink (file): ${SYMLINK_TO_RESTRICTED_FILE} → ${RESTRICTED_DIR}/secret.txt`); // Save original config return await configManager.getConfig(); } /** * Test helper: check if path validation succeeds or fails */ async function canAccessPath(testPath) { try { const result = await validatePath(testPath); console.log(` ✓ validatePath("${testPath}") → "${result}"`); return { success: true, result }; } catch (error) { console.log(` ✗ validatePath("${testPath}") → Error: ${error.message}`); return { success: false, error: error.message }; } } /** * Test 1: Normal file access within allowed directory (should succeed) */ async function testNormalFileAccess() { console.log('\n--- Test 1: Normal file access within allowed directory ---'); await configManager.setValue('allowedDirectories', [ALLOWED_DIR]); const normalFile = path.join(ALLOWED_DIR, 'normal.txt'); const result = await canAccessPath(normalFile); assert.strictEqual(result.success, true, 'Normal file in allowed directory should be accessible'); console.log('✓ Test 1 passed: Normal files are accessible'); } /** * Test 2: Direct access to restricted directory (should fail) */ async function testDirectRestrictedAccess() { console.log('\n--- Test 2: Direct access to restricted directory ---'); await configManager.setValue('allowedDirectories', [ALLOWED_DIR]); const result = await canAccessPath(RESTRICTED_DIR); assert.strictEqual(result.success, false, 'Direct access to restricted directory should fail'); console.log('✓ Test 2 passed: Direct restricted access is blocked'); } /** * Test 3: SYMLINK BYPASS - Directory symlink pointing outside allowed dirs * This is the main security test! */ async function testSymlinkDirectoryBypass() { console.log('\n--- Test 3: SYMLINK BYPASS - Directory symlink pointing outside ---'); console.log(' Attack scenario: symlink inside allowed dir points to restricted dir'); await configManager.setValue('allowedDirectories', [ALLOWED_DIR]); // The symlink path LOOKS like it's in ALLOWED_DIR // But it actually points to RESTRICTED_DIR const result = await canAccessPath(SYMLINK_TO_RESTRICTED); assert.strictEqual(result.success, false, 'SECURITY: Symlink pointing to restricted directory should be BLOCKED'); console.log('✓ Test 3 passed: Symlink directory bypass is blocked'); } /** * Test 4: SYMLINK BYPASS - File symlink pointing outside allowed dirs */ async function testSymlinkFileBypass() { console.log('\n--- Test 4: SYMLINK BYPASS - File symlink pointing outside ---'); console.log(' Attack scenario: symlink inside allowed dir points to restricted file'); await configManager.setValue('allowedDirectories', [ALLOWED_DIR]); const result = await canAccessPath(SYMLINK_TO_RESTRICTED_FILE); assert.strictEqual(result.success, false, 'SECURITY: Symlink pointing to restricted file should be BLOCKED'); console.log('✓ Test 4 passed: Symlink file bypass is blocked'); } /** * Test 5: Access file through directory symlink * Attempt to access a file via the symlinked directory */ async function testAccessThroughSymlinkDir() { console.log('\n--- Test 5: Access file through directory symlink ---'); await configManager.setValue('allowedDirectories', [ALLOWED_DIR]); // Try to access a file through the symlinked directory // This path: /allowed/link_to_restricted/secret.txt // Would resolve to: /restricted/secret.txt const throughSymlinkPath = path.join(SYMLINK_TO_RESTRICTED, 'secret.txt'); console.log(` Path through symlink: ${throughSymlinkPath}`); const result = await canAccessPath(throughSymlinkPath); // This should fail because even though the path looks like it's in allowed dir, // the resolved real path is in the restricted dir assert.strictEqual(result.success, false, 'SECURITY: Accessing file through symlinked directory should be BLOCKED'); console.log('✓ Test 5 passed: Access through symlink dir is blocked'); } /** * Test 6: Symlink within allowed directory pointing to another allowed location (should succeed) */ async function testSymlinkWithinAllowed() { console.log('\n--- Test 6: Symlink within allowed directories ---'); // Create another allowed subdirectory and symlink within it const subdir = path.join(ALLOWED_DIR, 'subdir'); await fs.mkdir(subdir, { recursive: true }); await fs.writeFile(path.join(subdir, 'allowed_secret.txt'), 'Allowed secret'); const internalSymlink = path.join(ALLOWED_DIR, 'link_to_subdir'); await fs.symlink(subdir, internalSymlink).catch(() => {}); await configManager.setValue('allowedDirectories', [ALLOWED_DIR]); const result = await canAccessPath(internalSymlink); // This SHOULD succeed because the resolved path is still within allowed dirs assert.strictEqual(result.success, true, 'Symlink pointing within allowed directories should be accessible'); console.log('✓ Test 6 passed: Internal symlinks work correctly'); } /** * Test 7: Broken symlink (pointing to non-existent target) */ async function testBrokenSymlink() { console.log('\n--- Test 7: Broken symlink ---'); const brokenSymlink = path.join(ALLOWED_DIR, 'broken_link'); await fs.symlink('/nonexistent/path/that/does/not/exist', brokenSymlink).catch(() => {}); await configManager.setValue('allowedDirectories', [ALLOWED_DIR]); const result = await canAccessPath(brokenSymlink); // Broken symlinks should be handled gracefully - the behavior depends on implementation // Current PR falls back to original path for ENOENT console.log(` Broken symlink result: success=${result.success}`); console.log('✓ Test 7 passed: Broken symlinks handled gracefully'); } /** * Main test runner */ async function runAllTests() { console.log('=== Symlink Security Tests ==='); console.log('Testing that symlinks cannot bypass allowedDirectories restrictions\n'); let originalConfig; let passed = 0; let failed = 0; try { originalConfig = await setup(); // Run tests const tests = [ testNormalFileAccess, testDirectRestrictedAccess, testSymlinkDirectoryBypass, testSymlinkFileBypass, testAccessThroughSymlinkDir, testSymlinkWithinAllowed, testBrokenSymlink, ]; for (const test of tests) { try { await test(); passed++; } catch (error) { console.error(`\n❌ ${test.name} FAILED:`, error.message); failed++; } } } finally { // Restore config if (originalConfig) { await configManager.updateConfig(originalConfig); } await cleanup(); } console.log('\n' + '='.repeat(50)); console.log(`Results: ${passed} passed, ${failed} failed`); if (failed > 0) { console.log('\n⚠️ SECURITY TESTS FAILED - symlink bypass may be possible!'); process.exit(1); } else { console.log('\n✅ All symlink security tests passed!'); } } // Run if executed directly if (import.meta.url === `file://${process.argv[1]}`) { runAllTests().catch(error => { console.error('❌ Unhandled error:', error); process.exit(1); }); } export default runAllTests;
wonderwhy-er/DesktopCommanderMCP
5,467
This is MCP server for Claude that gives it terminal control, file system search and diff file editing capabilities
TypeScript
wonderwhy-er
Eduard Ruzga
test/test-ui-event-tracking.js
JavaScript
/** * Tests for UI event tracking plumbing between apps and host interfaces. It verifies expected event envelopes so telemetry and diagnostics remain stable. */ import assert from 'assert'; import { server } from '../dist/server.js'; import { buildTrackUiEventCapturePayload } from '../dist/handlers/history-handlers.js'; function getRequestHandler(method) { const handlers = server._requestHandlers; assert.ok(handlers, 'Server request handlers should be initialized'); const handler = handlers.get(method); assert.ok(handler, `Expected request handler for ${method}`); return handler; } async function testTrackUiEventCall() { console.log('\n--- Test: track_ui_event call ---'); const callToolHandler = getRequestHandler('tools/call'); const response = await callToolHandler({ method: 'tools/call', params: { name: 'track_ui_event', arguments: { event: 'widget_expanded', component: 'file_preview', params: { file_type: 'markdown', line_count: 36, expanded: true } } } }, {}); assert.ok(response, 'tools/call should return a response'); assert.ok(Array.isArray(response.content), 'track_ui_event should return content array'); assert.strictEqual(response.isError, undefined, 'track_ui_event should not return isError'); assert.ok(response.content[0].text.includes('Tracked UI event'), 'track_ui_event should acknowledge event tracking'); console.log('✓ track_ui_event call works'); } async function testTrackUiEventPayloadCollisionProtection() { console.log('\n--- Test: track_ui_event payload collision protection ---'); const payload = buildTrackUiEventCapturePayload('widget_expanded', 'file_preview', { event: 'spoofed', component: 'spoofed_component', line_count: 12 }); assert.strictEqual(payload.event, 'widget_expanded', 'Canonical event should override params.event'); assert.strictEqual(payload.component, 'file_preview', 'Canonical component should override params.component'); assert.strictEqual(payload.line_count, 12, 'Custom params should be preserved'); console.log('✓ track_ui_event payload collision protection works'); } export default async function runTests() { try { await testTrackUiEventCall(); await testTrackUiEventPayloadCollisionProtection(); console.log('\n✅ UI event tracking tests passed!'); return true; } catch (error) { const message = error instanceof Error ? error.message : String(error); console.error('❌ Test failed:', message); if (error instanceof Error && error.stack) { console.error(error.stack); } return false; } } if (import.meta.url === `file://${process.argv[1]}`) { runTests().then((success) => { process.exit(success ? 0 : 1); }).catch((error) => { console.error('❌ Unhandled error:', error); process.exit(1); }); }
wonderwhy-er/DesktopCommanderMCP
5,467
This is MCP server for Claude that gives it terminal control, file system search and diff file editing capabilities
TypeScript
wonderwhy-er
Eduard Ruzga
test/test.js
JavaScript
import path from 'path'; import fs from 'fs/promises'; import { fileURLToPath } from 'url'; import { handleEditBlock } from '../dist/handlers/edit-search-handlers.js'; import { configManager } from '../dist/config-manager.js'; const __filename = fileURLToPath(import.meta.url); const __dirname = path.dirname(__filename); const TEST_FILEPATH = path.join(__dirname, 'test.txt') async function setup() { // Save original config to restore later const originalConfig = await configManager.getConfig(); return originalConfig; } /** * Teardown function to clean up after tests */ async function teardown(originalConfig) { // Reset configuration to original await configManager.updateConfig(originalConfig); await fs.rm(TEST_FILEPATH, { force: true, recursive: true }); // Clean up test directories console.log('✓ Teardown: test directories cleaned up and config restored'); } // Export the main test function async function testEditBlock() { try { await configManager.setValue('allowedDirectories', [__dirname]); // Create a test file const fs = await import('fs/promises'); await fs.writeFile(TEST_FILEPATH, 'This is old content to replace'); // Test handleEditBlock const result = await handleEditBlock({ file_path: TEST_FILEPATH, old_string: 'old content', new_string: 'new content', expected_replacements: 1 }); console.log('Edit block result:', result); const fileContent = await fs.readFile(TEST_FILEPATH, 'utf8'); console.log('File content after replacement:', fileContent); if (fileContent.includes('new content')) { console.log('Replace test passed!'); } else { throw new Error('Replace test failed!'); } // Cleanup await fs.unlink(TEST_FILEPATH); console.log('All tests passed! 🎉'); return true; } catch (error) { console.error('Test failed:', error); return false; } } // Export the main test function export default async function runTests() { let originalConfig; try { originalConfig = await setup(); await testEditBlock(); } catch (error) { console.error('❌ Test failed:', error.message); return false; } finally { if (originalConfig) { await teardown(originalConfig); } } return true; } // If this file is run directly (not imported), execute the test if (import.meta.url === `file://${process.argv[1]}`) { runTests().catch(error => { console.error('❌ Unhandled error:', error); process.exit(1); }); }
wonderwhy-er/DesktopCommanderMCP
5,467
This is MCP server for Claude that gives it terminal control, file system search and diff file editing capabilities
TypeScript
wonderwhy-er
Eduard Ruzga
test/test_enhanced_read.js
JavaScript
// Test script to verify enhanced file reading import { readFileInternal } from '../dist/tools/filesystem.js'; import { fileURLToPath } from 'url'; import { dirname, join } from 'path'; // Get the test directory path const __filename = fileURLToPath(import.meta.url); const __dirname = dirname(__filename); const TEST_FILE_PATH = join(__dirname, 'test_output', 'file_with_1500_lines.txt'); async function testEnhancedReading() { let testsPassed = 0; let totalTests = 3; console.log('Testing enhanced file reading with our 1500-line file...'); try { // Test 1: Read first 10 lines console.log('\n=== Test 1: Read first 10 lines ==='); try { const result1 = await readFileInternal(TEST_FILE_PATH, 0, 10); console.log('Result length:', result1.length); console.log('First few lines of result:'); console.log(result1.substring(0, 200) + '...'); // Validate the result const lines = result1.split('\n').filter(line => line.length > 0); if (lines.length === 10 && lines[0].includes('line 1')) { testsPassed++; console.log('✓ Test 1 PASSED'); } else { throw new Error(`Expected 10 lines starting with line 1, got ${lines.length} lines`); } } catch (error) { console.error('✗ Test 1 FAILED:', error.message); } // Test 2: Read from middle with offset console.log('\n=== Test 2: Read from offset 500, length 5 ==='); try { const result2 = await readFileInternal(TEST_FILE_PATH, 500, 5); console.log('Result length:', result2.length); console.log('First few lines of result:'); console.log(result2.substring(0, 200) + '...'); // Validate the result const lines = result2.split('\n').filter(line => line.length > 0); if (lines.length === 5 && lines[0].includes('line 501')) { testsPassed++; console.log('✓ Test 2 PASSED'); } else { throw new Error(`Expected 5 lines starting with line 501, got ${lines.length} lines, first line: ${lines[0]}`); } } catch (error) { console.error('✗ Test 2 FAILED:', error.message); } // Test 3: Read last 10 lines (using positive offset: 1490 for lines 1491-1500) console.log('\n=== Test 3: Read last 10 lines (lines 1491-1500) ==='); try { const result3 = await readFileInternal(TEST_FILE_PATH, 1490, 10); console.log('Result length:', result3.length); console.log('First few lines of result:'); console.log(result3.substring(0, 300) + '...'); // Validate the result const lines = result3.split('\n').filter(line => line.length > 0); if (lines.length === 10 && lines[0].includes('line 1491') && lines[9].includes('line 1500')) { testsPassed++; console.log('✓ Test 3 PASSED'); } else { throw new Error(`Expected 10 lines from 1491 to 1500, got ${lines.length} lines, first line: ${lines[0]}, last line: ${lines[lines.length-1]}`); } } catch (error) { console.error('✗ Test 3 FAILED:', error.message); } // Summary console.log(`\n=== SUMMARY ===`); console.log(`Tests passed: ${testsPassed}/${totalTests}`); if (testsPassed === totalTests) { console.log('🎉 All tests PASSED!'); process.exit(0); } else { console.log('❌ Some tests FAILED!'); process.exit(1); } } catch (error) { console.error('❌ Test suite failed with error:', error); process.exit(1); } } testEnhancedReading().catch(console.error);
wonderwhy-er/DesktopCommanderMCP
5,467
This is MCP server for Claude that gives it terminal control, file system search and diff file editing capabilities
TypeScript
wonderwhy-er
Eduard Ruzga
test/test_improved_search_truncation.js
JavaScript
// Test script to verify improved search result behavior using new streaming API import { handleStartSearch, handleGetMoreSearchResults, handleStopSearch } from '../dist/handlers/search-handlers.js'; /** * Helper function to wait for search completion and get all results */ async function searchAndWaitForCompletion(searchArgs, timeout = 30000) { const result = await handleStartSearch(searchArgs); // Extract session ID from result with tighter regex const sessionIdMatch = result.content[0].text.match(/Started .* session:\s*([a-zA-Z0-9_-]+)/); if (!sessionIdMatch) { throw new Error('Could not extract session ID from search result'); } const sessionId = sessionIdMatch[1]; try { // Wait for completion by polling const startTime = Date.now(); while (Date.now() - startTime < timeout) { const moreResults = await handleGetMoreSearchResults({ sessionId }); if (moreResults.content[0].text.includes('✅ Search completed')) { return { initialResult: result, finalResult: moreResults, sessionId }; } if (moreResults.content[0].text.includes('❌ ERROR')) { throw new Error(`Search failed: ${moreResults.content[0].text}`); } // Wait a bit before polling again await new Promise(resolve => setTimeout(resolve, 100)); } throw new Error('Search timed out'); } finally { // Always stop the search session to prevent hanging try { await handleStopSearch({ sessionId }); } catch (e) { // Ignore errors when stopping - session might already be completed } } } async function testImprovedSearchTruncation() { try { console.log('Testing improved search result behavior with streaming API...'); // Test search that will produce many results to trigger potential limits const searchArgs = { path: '.', pattern: '.', // Match almost every line - this should be a lot of results searchType: 'content', maxResults: 50000, // Very high limit to get lots of results, but may be capped ignoreCase: true }; console.log('Searching for "." to get maximum results...'); const start = Date.now(); const { initialResult, finalResult } = await searchAndWaitForCompletion(searchArgs); const end = Date.now(); console.log(`Search completed in ${end - start}ms`); console.log('Initial result type:', typeof initialResult.content[0].text); console.log('Initial result length:', initialResult.content[0].text.length); console.log('Final result type:', typeof finalResult.content[0].text); console.log('Final result length:', finalResult.content[0].text.length); const totalLength = initialResult.content[0].text.length + finalResult.content[0].text.length; const apiLimit = 1048576; // 1 MiB - use consistent constant // Check if we're within the safe limits using single source of truth if (totalLength > apiLimit) { console.log('❌ Results still quite large - over 1MB combined'); } else if (totalLength > Math.floor(0.8 * apiLimit)) { console.log('⚠️ Results approaching limits but acceptable'); } else { console.log('✅ Results well within safe limits'); } if (finalResult.content[0].text.includes('Results truncated')) { console.log('✅ Results properly truncated with warning message'); const truncationIndex = finalResult.content[0].text.indexOf('Results truncated'); console.log('Truncation message:', finalResult.content[0].text.substring(truncationIndex, truncationIndex + 150)); } else { console.log('ℹ️ Results complete, no truncation needed with new streaming API'); } console.log('First 200 characters of final result:'); console.log(finalResult.content[0].text.substring(0, 200)); // Check character length safety const safetyMargin = apiLimit - totalLength; console.log(`\n📊 Safety Analysis:`); console.log(` Initial response: ${initialResult.content[0].text.length.toLocaleString()} characters`); console.log(` Final response: ${finalResult.content[0].text.length.toLocaleString()} characters`); console.log(` Combined size: ${totalLength.toLocaleString()} characters`); console.log(` API limit: ${apiLimit.toLocaleString()} characters`); console.log(` Safety margin: ${safetyMargin.toLocaleString()} characters`); console.log(` Utilization: ${((totalLength / apiLimit) * 100).toFixed(1)}%`); } catch (error) { console.error('Test failed:', error); } } testImprovedSearchTruncation().then(() => { console.log('Improved search truncation test completed successfully.'); process.exit(0); }).catch(error => { console.error('Test failed:', error); process.exit(1); });
wonderwhy-er/DesktopCommanderMCP
5,467
This is MCP server for Claude that gives it terminal control, file system search and diff file editing capabilities
TypeScript
wonderwhy-er
Eduard Ruzga
test/test_search_truncation.js
JavaScript
// Test script to verify search result behavior using new streaming API import { handleStartSearch, handleGetMoreSearchResults } from '../dist/handlers/search-handlers.js'; /** * Helper function to wait for search completion and get all results */ async function searchAndWaitForCompletion(searchArgs, timeout = 30000) { const result = await handleStartSearch(searchArgs); // Extract session ID from result with tighter regex const sessionIdMatch = result.content[0].text.match(/Started .* session:\s*([a-zA-Z0-9_-]+)/); if (!sessionIdMatch) { throw new Error('Could not extract session ID from search result'); } const sessionId = sessionIdMatch[1]; try { // Wait for completion by polling const startTime = Date.now(); while (Date.now() - startTime < timeout) { const moreResults = await handleGetMoreSearchResults({ sessionId }); if (moreResults.content[0].text.includes('✅ Search completed')) { return { initialResult: result, finalResult: moreResults, sessionId }; } if (moreResults.content[0].text.includes('❌ ERROR')) { throw new Error(`Search failed: ${moreResults.content[0].text}`); } // Wait a bit before polling again await new Promise(resolve => setTimeout(resolve, 100)); } throw new Error('Search timed out'); } finally { // Always stop the search session to prevent hanging try { await handleStopSearch({ sessionId }); } catch (e) { // Ignore errors when stopping - session might already be completed } } } async function testSearchTruncation() { try { console.log('Testing search result behavior with new streaming API...'); // Test search that will produce many results const searchArgs = { path: '.', pattern: 'function|const|let|var', // This should match many lines searchType: 'content', maxResults: 50000, // Very high limit to get lots of results ignoreCase: true }; console.log('Searching for common JavaScript patterns...'); const { initialResult, finalResult } = await searchAndWaitForCompletion(searchArgs); console.log('Initial result type:', typeof initialResult.content[0].text); console.log('Initial result length:', initialResult.content[0].text.length); console.log('Final result type:', typeof finalResult.content[0].text); console.log('Final result length:', finalResult.content[0].text.length); const combinedLength = initialResult.content[0].text.length + finalResult.content[0].text.length; // Use consistent API limit constant const apiLimit = 1048576; // 1 MiB if (combinedLength > apiLimit) { console.log('⚠️ Combined results quite large - may need truncation handling'); } else if (finalResult.content[0].text.includes('Results truncated')) { console.log('✅ Results properly truncated with warning message'); const truncationIndex = finalResult.content[0].text.indexOf('Results truncated'); console.log('Truncation message:', finalResult.content[0].text.substring(truncationIndex, truncationIndex + 100)); } else { console.log('✅ Results manageable size, no truncation needed'); } console.log('First 200 characters of final result:'); console.log(finalResult.content[0].text.substring(0, 200)); // Character length analysis console.log(`\n📊 Response Analysis:`); console.log(` Initial response: ${initialResult.content[0].text.length.toLocaleString()} characters`); console.log(` Final response: ${finalResult.content[0].text.length.toLocaleString()} characters`); console.log(` Combined: ${combinedLength.toLocaleString()} characters`); } catch (error) { console.error('Test failed:', error); } } testSearchTruncation().then(() => { console.log('Search truncation test completed successfully.'); process.exit(0); }).catch(error => { console.error('Test failed:', error); process.exit(1); });
wonderwhy-er/DesktopCommanderMCP
5,467
This is MCP server for Claude that gives it terminal control, file system search and diff file editing capabilities
TypeScript
wonderwhy-er
Eduard Ruzga
track-installation.js
JavaScript
#!/usr/bin/env node /** * Installation Source Tracking Script * Runs during npm install to detect how Desktop Commander was installed * * Debug logging can be enabled with: * - DEBUG=desktop-commander npm install * - DEBUG=* npm install * - NODE_ENV=development npm install * - DC_DEBUG=true npm install */ import { randomUUID } from 'crypto'; import * as https from 'https'; import { platform } from 'os'; import path from 'path'; import { fileURLToPath } from 'url'; // Get current file directory const __filename = fileURLToPath(import.meta.url); const __dirname = path.dirname(__filename); // Debug logging utility - configurable via environment variables const DEBUG_ENABLED = process.env.DEBUG === 'desktop-commander' || process.env.DEBUG === '*' || process.env.NODE_ENV === 'development' || process.env.DC_DEBUG === 'true'; const debug = (...args) => { if (DEBUG_ENABLED) { console.log('[Desktop Commander Debug]', ...args); } }; const log = (...args) => { // Always show important messages, but prefix differently for debug vs production if (DEBUG_ENABLED) { console.log('[Desktop Commander]', ...args); } }; /** * Get the client ID from the Desktop Commander config file, or generate a new one */ async function getClientId() { try { const { homedir } = await import('os'); const { join } = await import('path'); const fs = await import('fs'); const USER_HOME = homedir(); const CONFIG_DIR = join(USER_HOME, '.claude-server-commander'); const CONFIG_FILE = join(CONFIG_DIR, 'config.json'); // Try to read existing config if (fs.existsSync(CONFIG_FILE)) { const configData = fs.readFileSync(CONFIG_FILE, 'utf8'); const config = JSON.parse(configData); if (config.clientId) { debug(`Using existing clientId from config: ${config.clientId.substring(0, 8)}...`); return config.clientId; } } debug('No existing clientId found, generating new one'); // Fallback to random UUID if config doesn't exist or lacks clientId return randomUUID(); } catch (error) { debug(`Error reading config file: ${error.message}, using random UUID`); // If anything goes wrong, fall back to random UUID return randomUUID(); } } // Google Analytics configuration (same as setup script) const GA_MEASUREMENT_ID = 'G-NGGDNL0K4L'; const GA_API_SECRET = '5M0mC--2S_6t94m8WrI60A'; const GA_BASE_URL = `https://www.google-analytics.com/mp/collect?measurement_id=${GA_MEASUREMENT_ID}&api_secret=${GA_API_SECRET}`; /** * Detect installation source from environment and process context */ async function detectInstallationSource() { // Check npm environment variables for clues const npmConfigUserAgent = process.env.npm_config_user_agent || ''; const npmExecpath = process.env.npm_execpath || ''; const npmCommand = process.env.npm_command || ''; const npmLifecycleEvent = process.env.npm_lifecycle_event || ''; // Check process arguments and parent commands const processArgs = process.argv.join(' '); const processTitle = process.title || ''; debug('Installation source detection...'); debug(`npm_config_user_agent: ${npmConfigUserAgent}`); debug(`npm_execpath: ${npmExecpath}`); debug(`npm_command: ${npmCommand}`); debug(`npm_lifecycle_event: ${npmLifecycleEvent}`); debug(`process.argv: ${processArgs}`); debug(`process.title: ${processTitle}`); // Try to get parent process information let parentProcessInfo = null; try { const { execSync } = await import('child_process'); const ppid = process.ppid; if (ppid && process.platform !== 'win32') { // Get parent process command line on Unix systems const parentCmd = execSync(`ps -p ${ppid} -o command=`, { encoding: 'utf8' }).trim(); parentProcessInfo = parentCmd; debug(`parent process: ${parentCmd}`); } } catch (error) { debug(`Could not get parent process info: ${error.message}`); } // Smithery detection - look for smithery in the process chain const smitheryIndicators = [ npmConfigUserAgent.includes('smithery'), npmExecpath.includes('smithery'), processArgs.includes('smithery'), processArgs.includes('@smithery/cli'), processTitle.includes('smithery'), parentProcessInfo && parentProcessInfo.includes('smithery'), parentProcessInfo && parentProcessInfo.includes('@smithery/cli') ]; if (smitheryIndicators.some(indicator => indicator)) { return { source: 'smithery', details: { detection_method: 'process_chain', user_agent: npmConfigUserAgent, exec_path: npmExecpath, command: npmCommand, parent_process: parentProcessInfo || 'unknown', process_args: processArgs } }; } // Direct NPX usage if (npmCommand === 'exec' || processArgs.includes('npx')) { return { source: 'npx-direct', details: { user_agent: npmConfigUserAgent, command: npmCommand, lifecycle_event: npmLifecycleEvent } }; } // Regular npm install if (npmCommand === 'install' || npmLifecycleEvent === 'postinstall') { return { source: 'npm-install', details: { user_agent: npmConfigUserAgent, command: npmCommand, lifecycle_event: npmLifecycleEvent } }; } // GitHub Codespaces if (process.env.CODESPACES) { return { source: 'github-codespaces', details: { codespace: process.env.CODESPACE_NAME || 'unknown' } }; } // VS Code if (process.env.VSCODE_PID || process.env.TERM_PROGRAM === 'vscode') { return { source: 'vscode', details: { term_program: process.env.TERM_PROGRAM, vscode_pid: process.env.VSCODE_PID } }; } // GitPod if (process.env.GITPOD_WORKSPACE_ID) { return { source: 'gitpod', details: { workspace_id: process.env.GITPOD_WORKSPACE_ID.substring(0, 8) + '...' // Truncate for privacy } }; } // CI/CD environments if (process.env.CI) { if (process.env.GITHUB_ACTIONS) { return { source: 'github-actions', details: { repository: process.env.GITHUB_REPOSITORY, workflow: process.env.GITHUB_WORKFLOW } }; } if (process.env.GITLAB_CI) { return { source: 'gitlab-ci', details: { project: process.env.CI_PROJECT_NAME } }; } if (process.env.JENKINS_URL) { return { source: 'jenkins', details: { job: process.env.JOB_NAME } }; } return { source: 'ci-cd-other', details: { ci_env: 'unknown' } }; } // Docker detection if (process.env.DOCKER_CONTAINER) { return { source: 'docker', details: { container_id: process.env.HOSTNAME?.substring(0, 8) + '...' || 'unknown' } }; } // Check for .dockerenv file (need to use fs import) try { const fs = await import('fs'); if (fs.existsSync('/.dockerenv')) { return { source: 'docker', details: { container_id: process.env.HOSTNAME?.substring(0, 8) + '...' || 'unknown' } }; } } catch (error) { // Ignore fs errors } // Default fallback return { source: 'unknown', details: { user_agent: npmConfigUserAgent || 'none', command: npmCommand || 'none', lifecycle: npmLifecycleEvent || 'none' } }; } /** * Send installation tracking to analytics */ async function trackInstallation(installationData) { if (!GA_MEASUREMENT_ID || !GA_API_SECRET) { debug('Analytics not configured, skipping tracking'); return; } try { const uniqueUserId = await getClientId(); log("user id", uniqueUserId) // Prepare GA4 payload const payload = { client_id: uniqueUserId, non_personalized_ads: false, timestamp_micros: Date.now() * 1000, events: [{ name: 'package_installed', params: { timestamp: new Date().toISOString(), platform: platform(), installation_source: installationData.source, installation_details: JSON.stringify(installationData.details), package_name: '@wonderwhy-er/desktop-commander', install_method: 'npm-lifecycle', node_version: process.version, npm_version: process.env.npm_version || 'unknown' } }] }; const postData = JSON.stringify(payload); const options = { method: 'POST', headers: { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(postData) } }; await new Promise((resolve, reject) => { const req = https.request(GA_BASE_URL, options); const timeoutId = setTimeout(() => { req.destroy(); reject(new Error('Request timeout')); }, 5000); req.on('error', (error) => { clearTimeout(timeoutId); debug(`Analytics error: ${error.message}`); resolve(); // Don't fail installation on analytics error }); req.on('response', (res) => { clearTimeout(timeoutId); // Consume the response data to complete the request res.on('data', () => {}); // Ignore response data res.on('end', () => { log(`Installation tracked: ${installationData.source}`); resolve(); }); }); req.write(postData); req.end(); }); } catch (error) { debug(`Failed to track installation: ${error.message}`); // Don't fail the installation process } } /** * Main execution */ async function main() { try { log('Package installation detected'); const installationData = await detectInstallationSource(); log(`Installation source: ${installationData.source}`); await trackInstallation(installationData); } catch (error) { debug(`Installation tracking error: ${error.message}`); // Don't fail the installation } } // Only run if this script is executed directly (not imported) if (import.meta.url === `file://${process.argv[1]}`) { main(); } export { detectInstallationSource, trackInstallation };
wonderwhy-er/DesktopCommanderMCP
5,467
This is MCP server for Claude that gives it terminal control, file system search and diff file editing capabilities
TypeScript
wonderwhy-er
Eduard Ruzga
uninstall-claude-server.js
JavaScript
import { homedir, platform } from 'os'; import fs from 'fs/promises'; import path from 'path'; import { join } from 'path'; import { readFileSync, writeFileSync, existsSync, appendFileSync, mkdirSync } from 'fs'; import { fileURLToPath } from 'url'; import { dirname } from 'path'; import { exec } from "node:child_process"; import { version as nodeVersion } from 'process'; import * as https from 'https'; import { randomUUID } from 'crypto'; // Google Analytics configuration const GA_MEASUREMENT_ID = 'G-NGGDNL0K4L'; // Replace with your GA4 Measurement ID const GA_API_SECRET = '5M0mC--2S_6t94m8WrI60A'; // Replace with your GA4 API Secret const GA_BASE_URL = `https://www.google-analytics.com/mp/collect?measurement_id=${GA_MEASUREMENT_ID}&api_secret=${GA_API_SECRET}`; // Read clientId and telemetry settings from existing config let uniqueUserId = 'unknown'; let telemetryEnabled = false; // Default to disabled for privacy async function getConfigSettings() { try { const USER_HOME = homedir(); const CONFIG_DIR = path.join(USER_HOME, '.claude-server-commander'); const CONFIG_FILE = path.join(CONFIG_DIR, 'config.json'); if (existsSync(CONFIG_FILE)) { const configData = readFileSync(CONFIG_FILE, 'utf8'); const config = JSON.parse(configData); return { clientId: config.clientId || randomUUID(), telemetryEnabled: config.telemetryEnabled === true // Explicit check for true }; } // Fallback: generate new ID and default telemetry to false if config doesn't exist return { clientId: `unknown-${Date.now()}-${Math.random().toString(36).substring(2, 15)}`, telemetryEnabled: false }; } catch (error) { // Final fallback return { clientId: `random-${Date.now()}-${Math.random().toString(36).substring(2, 15)}`, telemetryEnabled: false }; } } // Uninstall tracking let uninstallSteps = []; let uninstallStartTime = Date.now(); // Fix for Windows ESM path resolution const __filename = fileURLToPath(import.meta.url); const __dirname = dirname(__filename); // Setup logging const LOG_FILE = join(__dirname, 'setup.log'); function logToFile(message, isError = false) { const timestamp = new Date().toISOString(); const logMessage = `${timestamp} - ${isError ? 'ERROR: ' : ''}${message}\n`; try { appendFileSync(LOG_FILE, logMessage); const jsonOutput = { type: isError ? 'error' : 'info', timestamp, message }; process.stdout.write(`${message}\n`); } catch (err) { process.stderr.write(`${JSON.stringify({ type: 'error', timestamp: new Date().toISOString(), message: `Failed to write to log file: ${err.message}` })}\n`); } } // Function to get npm version async function getNpmVersion() { try { return new Promise((resolve, reject) => { exec('npm --version', (error, stdout, stderr) => { if (error) { resolve('unknown'); return; } resolve(stdout.trim()); }); }); } catch (error) { return 'unknown'; } } // Get Desktop Commander version const getVersion = async () => { try { if (process.env.npm_package_version) { return process.env.npm_package_version; } const versionPath = join(__dirname, 'version.js'); if (existsSync(versionPath)) { const { VERSION } = await import(versionPath); return VERSION; } const packageJsonPath = join(__dirname, 'package.json'); if (existsSync(packageJsonPath)) { const packageJsonContent = readFileSync(packageJsonPath, 'utf8'); const packageJson = JSON.parse(packageJsonContent); if (packageJson.version) { return packageJson.version; } } return 'unknown'; } catch (error) { return 'unknown'; } }; // Function to detect shell environment function detectShell() { if (process.platform === 'win32') { if (process.env.TERM_PROGRAM === 'vscode') return 'vscode-terminal'; if (process.env.WT_SESSION) return 'windows-terminal'; if (process.env.SHELL?.includes('bash')) return 'git-bash'; if (process.env.TERM?.includes('xterm')) return 'xterm-on-windows'; if (process.env.ComSpec?.toLowerCase().includes('powershell')) return 'powershell'; if (process.env.PROMPT) return 'cmd'; if (process.env.WSL_DISTRO_NAME || process.env.WSLENV) { return `wsl-${process.env.WSL_DISTRO_NAME || 'unknown'}`; } return 'windows-unknown'; } if (process.env.SHELL) { const shellPath = process.env.SHELL.toLowerCase(); if (shellPath.includes('bash')) return 'bash'; if (shellPath.includes('zsh')) return 'zsh'; if (shellPath.includes('fish')) return 'fish'; if (shellPath.includes('ksh')) return 'ksh'; if (shellPath.includes('csh')) return 'csh'; if (shellPath.includes('dash')) return 'dash'; return `other-unix-${shellPath.split('/').pop()}`; } if (process.env.TERM_PROGRAM) { return process.env.TERM_PROGRAM.toLowerCase(); } return 'unknown-shell'; } // Function to determine execution context function getExecutionContext() { const isNpx = process.env.npm_lifecycle_event === 'npx' || process.env.npm_execpath?.includes('npx') || process.env._?.includes('npx') || import.meta.url.includes('node_modules'); const isGlobal = process.env.npm_config_global === 'true' || process.argv[1]?.includes('node_modules/.bin'); const isNpmScript = !!process.env.npm_lifecycle_script; return { runMethod: isNpx ? 'npx' : (isGlobal ? 'global' : (isNpmScript ? 'npm_script' : 'direct')), isCI: !!process.env.CI || !!process.env.GITHUB_ACTIONS || !!process.env.TRAVIS || !!process.env.CIRCLECI, shell: detectShell() }; } // Enhanced tracking properties let npmVersionCache = null; async function getTrackingProperties(additionalProps = {}) { const propertiesStep = addUninstallStep('get_tracking_properties'); try { if (npmVersionCache === null) { npmVersionCache = await getNpmVersion(); } const context = getExecutionContext(); const version = await getVersion(); updateUninstallStep(propertiesStep, 'completed'); return { platform: platform(), node_version: nodeVersion, npm_version: npmVersionCache, execution_context: context.runMethod, is_ci: context.isCI, shell: context.shell, app_version: version, engagement_time_msec: "100", ...additionalProps }; } catch (error) { updateUninstallStep(propertiesStep, 'failed', error); return { platform: platform(), node_version: nodeVersion, error: error.message, ...additionalProps }; } } // Enhanced tracking function with retries async function trackEvent(eventName, additionalProps = {}) { const trackingStep = addUninstallStep(`track_event_${eventName}`); // Check if telemetry is disabled if (!telemetryEnabled) { updateUninstallStep(trackingStep, 'skipped_telemetry_disabled'); return true; // Return success since this is expected behavior } if (!GA_MEASUREMENT_ID || !GA_API_SECRET) { updateUninstallStep(trackingStep, 'skipped', new Error('GA not configured')); return; } const maxRetries = 2; let attempt = 0; let lastError = null; while (attempt <= maxRetries) { try { attempt++; const eventProperties = await getTrackingProperties(additionalProps); const payload = { client_id: uniqueUserId, non_personalized_ads: false, timestamp_micros: Date.now() * 1000, events: [{ name: eventName, params: eventProperties }] }; const postData = JSON.stringify(payload); const options = { method: 'POST', headers: { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(postData) } }; const result = await new Promise((resolve, reject) => { const req = https.request(GA_BASE_URL, options); const timeoutId = setTimeout(() => { req.destroy(); reject(new Error('Request timeout')); }, 5000); req.on('error', (error) => { clearTimeout(timeoutId); reject(error); }); req.on('response', (res) => { clearTimeout(timeoutId); let data = ''; res.on('data', (chunk) => { data += chunk; }); res.on('error', (error) => { reject(error); }); res.on('end', () => { if (res.statusCode >= 200 && res.statusCode < 300) { resolve({ success: true, data }); } else { reject(new Error(`HTTP error ${res.statusCode}: ${data}`)); } }); }); req.write(postData); req.end(); }); updateUninstallStep(trackingStep, 'completed'); return result; } catch (error) { lastError = error; if (attempt <= maxRetries) { await new Promise(resolve => setTimeout(resolve, 1000 * attempt)); } } } updateUninstallStep(trackingStep, 'failed', lastError); return false; } // Ensure tracking completes before process exits async function ensureTrackingCompleted(eventName, additionalProps = {}, timeoutMs = 6000) { return new Promise(async (resolve) => { const timeoutId = setTimeout(() => { resolve(false); }, timeoutMs); try { await trackEvent(eventName, additionalProps); clearTimeout(timeoutId); resolve(true); } catch (error) { clearTimeout(timeoutId); resolve(false); } }); } // Setup global error handlers (will be initialized after config is loaded) let errorHandlersInitialized = false; function initializeErrorHandlers() { if (errorHandlersInitialized) return; process.on('uncaughtException', async (error) => { if (telemetryEnabled) { await trackEvent('uninstall_uncaught_exception', { error: error.message }); } setTimeout(() => { process.exit(1); }, 1000); }); process.on('unhandledRejection', async (reason, promise) => { if (telemetryEnabled) { await trackEvent('uninstall_unhandled_rejection', { error: String(reason) }); } setTimeout(() => { process.exit(1); }, 1000); }); errorHandlersInitialized = true; } // Track when the process is about to exit let isExiting = false; process.on('exit', () => { if (!isExiting) { isExiting = true; } }); // Determine OS and set appropriate config path const os = platform(); const isWindows = os === 'win32'; let claudeConfigPath; switch (os) { case 'win32': claudeConfigPath = join(process.env.APPDATA, 'Claude', 'claude_desktop_config.json'); break; case 'darwin': claudeConfigPath = join(homedir(), 'Library', 'Application Support', 'Claude', 'claude_desktop_config.json'); break; case 'linux': claudeConfigPath = join(homedir(), '.config', 'Claude', 'claude_desktop_config.json'); break; default: claudeConfigPath = join(homedir(), '.claude_desktop_config.json'); } // Step tracking functions function addUninstallStep(step, status = 'started', error = null) { const timestamp = Date.now(); uninstallSteps.push({ step, status, timestamp, timeFromStart: timestamp - uninstallStartTime, error: error ? error.message || String(error) : null }); return uninstallSteps.length - 1; } function updateUninstallStep(index, status, error = null) { if (uninstallSteps[index]) { const timestamp = Date.now(); uninstallSteps[index].status = status; uninstallSteps[index].completionTime = timestamp; uninstallSteps[index].timeFromStart = timestamp - uninstallStartTime; if (error) { uninstallSteps[index].error = error.message || String(error); } } } async function execAsync(command) { const execStep = addUninstallStep(`exec_${command.substring(0, 20)}...`); return new Promise((resolve, reject) => { const actualCommand = isWindows ? `cmd.exe /c ${command}` : command; exec(actualCommand, { timeout: 10000 }, (error, stdout, stderr) => { if (error) { updateUninstallStep(execStep, 'failed', error); reject(error); return; } updateUninstallStep(execStep, 'completed'); resolve({ stdout, stderr }); }); }); } // Backup configuration before removal async function createConfigBackup(configPath) { const backupStep = addUninstallStep('create_config_backup'); try { const timestamp = new Date().toISOString().replace(/[:.]/g, '-'); const backupPath = `${configPath}.backup.${timestamp}`; if (existsSync(configPath)) { const configData = readFileSync(configPath, 'utf8'); writeFileSync(backupPath, configData, 'utf8'); updateUninstallStep(backupStep, 'completed'); logToFile(`Configuration backup created: ${backupPath}`); await trackEvent('uninstall_backup_created'); return backupPath; } else { updateUninstallStep(backupStep, 'no_config_file'); return null; } } catch (error) { updateUninstallStep(backupStep, 'failed', error); await trackEvent('uninstall_backup_failed', { error: error.message }); logToFile(`Failed to create backup: ${error.message}`, true); return null; } } // Restore configuration from backup async function restoreFromBackup(backupPath) { if (!backupPath || !existsSync(backupPath)) { return false; } try { const backupData = readFileSync(backupPath, 'utf8'); writeFileSync(claudeConfigPath, backupData, 'utf8'); logToFile(`Configuration restored from backup: ${backupPath}`); await trackEvent('uninstall_backup_restored'); return true; } catch (error) { logToFile(`Failed to restore from backup: ${error.message}`, true); await trackEvent('uninstall_backup_restore_failed', { error: error.message }); return false; } } async function restartClaude() { const restartStep = addUninstallStep('restart_claude'); try { const platform = process.platform; logToFile('Attempting to restart Claude...'); await trackEvent('uninstall_restart_claude_attempt'); // Try to kill Claude process first const killStep = addUninstallStep('kill_claude_process'); try { switch (platform) { case "win32": await execAsync(`taskkill /F /IM "Claude.exe"`); break; case "darwin": await execAsync(`killall "Claude"`); break; case "linux": await execAsync(`pkill -f "claude"`); break; } updateUninstallStep(killStep, 'completed'); logToFile("Claude process terminated successfully"); await trackEvent('uninstall_kill_claude_success'); } catch (killError) { updateUninstallStep(killStep, 'no_process_found', killError); logToFile("Claude process not found or already terminated"); await trackEvent('uninstall_kill_claude_not_needed'); } // Wait a bit to ensure process termination await new Promise((resolve) => setTimeout(resolve, 2000)); // Try to start Claude const startStep = addUninstallStep('start_claude_process'); try { if (platform === "win32") { logToFile("Windows: Claude restart skipped - please restart Claude manually"); updateUninstallStep(startStep, 'skipped'); await trackEvent('uninstall_start_claude_skipped'); } else if (platform === "darwin") { await execAsync(`open -a "Claude"`); updateUninstallStep(startStep, 'completed'); logToFile("✅ Claude has been restarted automatically!"); await trackEvent('uninstall_start_claude_success'); } else if (platform === "linux") { await execAsync(`claude`); updateUninstallStep(startStep, 'completed'); logToFile("✅ Claude has been restarted automatically!"); await trackEvent('uninstall_start_claude_success'); } else { logToFile('To complete uninstallation, restart Claude if it\'s currently running'); updateUninstallStep(startStep, 'manual_required'); } updateUninstallStep(restartStep, 'completed'); await trackEvent('uninstall_restart_claude_success'); } catch (startError) { updateUninstallStep(startStep, 'failed', startError); await trackEvent('uninstall_start_claude_error', { error: startError.message }); logToFile(`Could not automatically restart Claude: ${startError.message}. Please restart it manually.`); } } catch (error) { updateUninstallStep(restartStep, 'failed', error); await trackEvent('uninstall_restart_claude_error', { error: error.message }); logToFile(`Failed to restart Claude: ${error.message}. Please restart it manually.`, true); } } async function removeDesktopCommanderConfig() { const configStep = addUninstallStep('remove_mcp_config'); let backupPath = null; try { // Check if config file exists if (!existsSync(claudeConfigPath)) { updateUninstallStep(configStep, 'no_config_file'); logToFile(`Claude config file not found at: ${claudeConfigPath}`); logToFile('✅ Desktop Commander was not configured or already removed.'); await trackEvent('uninstall_config_not_found'); return true; } // Create backup before making changes backupPath = await createConfigBackup(claudeConfigPath); // Read existing config let config; const readStep = addUninstallStep('read_config_file'); try { const configData = readFileSync(claudeConfigPath, 'utf8'); config = JSON.parse(configData); updateUninstallStep(readStep, 'completed'); } catch (readError) { updateUninstallStep(readStep, 'failed', readError); await trackEvent('uninstall_config_read_error', { error: readError.message }); throw new Error(`Failed to read config file: ${readError.message}`); } // Check if mcpServers exists if (!config.mcpServers) { updateUninstallStep(configStep, 'no_mcp_servers'); logToFile('No MCP servers configured in Claude.'); logToFile('✅ Desktop Commander was not configured or already removed.'); await trackEvent('uninstall_no_mcp_servers'); return true; } // Track what we're removing const serversToRemove = []; if (config.mcpServers["desktop-commander"]) { serversToRemove.push("desktop-commander"); } if (serversToRemove.length === 0) { updateUninstallStep(configStep, 'not_found'); logToFile('Desktop Commander MCP server not found in configuration.'); logToFile('✅ Desktop Commander was not configured or already removed.'); await trackEvent('uninstall_server_not_found'); return true; } // Remove the server configurations const removeStep = addUninstallStep('remove_server_configs'); try { serversToRemove.forEach(serverName => { delete config.mcpServers[serverName]; logToFile(`Removed "${serverName}" from Claude configuration`); }); updateUninstallStep(removeStep, 'completed'); await trackEvent('uninstall_servers_removed'); } catch (removeError) { updateUninstallStep(removeStep, 'failed', removeError); await trackEvent('uninstall_servers_remove_error', { error: removeError.message }); throw new Error(`Failed to remove server configs: ${removeError.message}`); } // Write the updated config back const writeStep = addUninstallStep('write_updated_config'); try { writeFileSync(claudeConfigPath, JSON.stringify(config, null, 2), 'utf8'); updateUninstallStep(writeStep, 'completed'); updateUninstallStep(configStep, 'completed'); logToFile('✅ Desktop Commander successfully removed from Claude configuration'); logToFile(`Configuration updated at: ${claudeConfigPath}`); await trackEvent('uninstall_config_updated'); } catch (writeError) { updateUninstallStep(writeStep, 'failed', writeError); await trackEvent('uninstall_config_write_error', { error: writeError.message }); // Try to restore from backup if (backupPath) { logToFile('Attempting to restore configuration from backup...'); const restored = await restoreFromBackup(backupPath); if (restored) { throw new Error(`Failed to write updated config, but backup was restored: ${writeError.message}`); } else { throw new Error(`Failed to write updated config and backup restoration failed: ${writeError.message}`); } } else { throw new Error(`Failed to write updated config: ${writeError.message}`); } } return true; } catch (error) { updateUninstallStep(configStep, 'failed', error); await trackEvent('uninstall_config_error', { error: error.message }); logToFile(`Error removing Desktop Commander configuration: ${error.message}`, true); // Try to restore from backup if we have one if (backupPath) { logToFile('Attempting to restore configuration from backup...'); await restoreFromBackup(backupPath); } return false; } } // Main uninstall function export default async function uninstall() { // Initialize clientId and telemetry settings from existing config const configSettings = await getConfigSettings(); uniqueUserId = configSettings.clientId; telemetryEnabled = configSettings.telemetryEnabled; // Initialize error handlers now that telemetry setting is known initializeErrorHandlers(); // Log telemetry status for transparency if (!telemetryEnabled) { logToFile('Telemetry disabled - no analytics will be sent'); } // Initial tracking (only if telemetry enabled) await ensureTrackingCompleted('uninstall_start'); const mainStep = addUninstallStep('main_uninstall'); try { logToFile('Starting Desktop Commander uninstallation...'); // Remove the server configuration from Claude const configRemoved = await removeDesktopCommanderConfig(); if (configRemoved) { // Try to restart Claude // await restartClaude(); updateUninstallStep(mainStep, 'completed'); const appVersion = await getVersion(); logToFile(`\n✅ Desktop Commander has been successfully uninstalled!`); logToFile('The MCP server has been removed from Claude\'s configuration.'); logToFile('\nIf you want to reinstall later, you can run:'); logToFile('npx @wonderwhy-er/desktop-commander@latest setup'); logToFile('\n🎁 We\'re sorry to see you leaving, we’d love to understand your decision not to use Desktop Commander.') logToFile('In return for a brief 30-minute call, we’ll send you a $20 Amazon gift card as a thank-you.'); logToFile('To get a gift card, please fill out this form:'); logToFile(' https://tally.so/r/w8lyRo'); logToFile('\nThank you for using Desktop Commander! 👋\n'); // Send final tracking event await ensureTrackingCompleted('uninstall_complete'); return true; } else { updateUninstallStep(mainStep, 'failed_config_removal'); logToFile('\n❌ Uninstallation completed with errors.'); logToFile('You may need to manually remove Desktop Commander from Claude\'s configuration.'); logToFile(`Configuration file location: ${claudeConfigPath}\n`); logToFile('\n🎁 We\'re sorry to see you leaving, we\'d love to understand your decision not to use Desktop Commander.') logToFile('In return for a brief 30-minute call, we\'ll send you a $20 Amazon gift card as a thank-you.'); logToFile('To get a gift card, please fill out this form:'); logToFile(' https://tally.so/r/w8lyRo'); await ensureTrackingCompleted('uninstall_partial_failure'); return false; } } catch (error) { updateUninstallStep(mainStep, 'fatal_error', error); await ensureTrackingCompleted('uninstall_fatal_error', { error: error.message, error_stack: error.stack, last_successful_step: uninstallSteps.filter(s => s.status === 'completed').pop()?.step || 'none' }); logToFile(`Fatal error during uninstallation: ${error.message}`, true); logToFile('\n❌ Uninstallation failed.'); logToFile('You may need to manually remove Desktop Commander from Claude\'s configuration.'); logToFile(`Configuration file location: ${claudeConfigPath}\n`); logToFile('\n🎁 We\'re sorry to see you leaving, we\'d love to understand your decision not to use Desktop Commander.') logToFile('In return for a brief 30-minute call, we\'ll send you a $20 Amazon gift card as a thank-you.'); logToFile('To get a gift card, please fill out this form:'); logToFile('https://tally.so/r/w8lyRo'); return false; } } // Allow direct execution if (process.argv.length >= 2 && process.argv[1] === fileURLToPath(import.meta.url)) { uninstall().then(success => { if (!success) { process.exit(1); } }).catch(async error => { await ensureTrackingCompleted('uninstall_execution_error', { error: error.message, error_stack: error.stack }); logToFile(`Fatal error: ${error}`, true); process.exit(1); }); }
wonderwhy-er/DesktopCommanderMCP
5,467
This is MCP server for Claude that gives it terminal control, file system search and diff file editing capabilities
TypeScript
wonderwhy-er
Eduard Ruzga
app.js
JavaScript
// DOM Elements const video = document.getElementById('webcam'); const drawingCanvas = document.getElementById('drawing-canvas'); const handsCanvas = document.getElementById('hands-canvas'); const colorPicker = document.getElementById('color-picker'); const cameraSelect = document.getElementById('camera-select'); const clearButton = document.getElementById('clear-button'); const saveButton = document.getElementById('save-button'); // Track current media stream to stop it when switching cameras let currentStream = null; // Canvas contexts const drawingCtx = drawingCanvas.getContext('2d'); const handsCtx = handsCanvas.getContext('2d'); // Drawing state let isDrawing = false; let isErasing = false; let prevX = 0; let prevY = 0; // Debug mode (helps visualize metrics) const DEBUG = false; // Gesture Recognition state let indexFingerTip = null; let handPose = null; let handMetrics = null; // Initialize canvas size function setupCanvas() { drawingCanvas.width = video.videoWidth || window.innerWidth; drawingCanvas.height = video.videoHeight || window.innerHeight; handsCanvas.width = video.videoWidth || window.innerWidth; handsCanvas.height = video.videoHeight || window.innerHeight; } // Get list of available cameras async function getCameras() { try { // Ensure we have camera permissions first to get complete information await navigator.mediaDevices.getUserMedia({ video: true }); // Now get the devices with complete information const devices = await navigator.mediaDevices.enumerateDevices(); const videoDevices = devices.filter(device => device.kind === 'videoinput'); console.log('Found cameras:', videoDevices); return videoDevices; } catch (err) { console.error('Error getting cameras:', err); return []; } } // Populate camera select dropdown async function populateCameraOptions() { const cameras = await getCameras(); // Clear existing options cameraSelect.innerHTML = ''; if (cameras.length === 0) { const option = document.createElement('option'); option.value = ''; option.text = 'No cameras found'; cameraSelect.appendChild(option); return; } // Add all available cameras cameras.forEach((camera, index) => { const option = document.createElement('option'); option.value = camera.deviceId; // Create a more user-friendly label // If no label is available (before permission), use a generic name const label = camera.label || `Camera ${index + 1}`; option.text = label; // Check if it's the front-facing camera if (label.toLowerCase().includes('front')) { option.selected = true; } cameraSelect.appendChild(option); }); // Force a change event to ensure the camera is updated if needed if (cameras.length > 0 && !cameraSelect.value) { cameraSelect.selectedIndex = 0; cameraSelect.dispatchEvent(new Event('change')); } } // Initialize webcam async function setupCamera(deviceId = null) { // Stop any existing stream if (currentStream) { currentStream.getTracks().forEach(track => track.stop()); } // Set up constraints based on selected camera const constraints = { video: { width: { ideal: 1920 }, height: { ideal: 1080 } } }; // If deviceId is provided, use it if (deviceId) { constraints.video.deviceId = { exact: deviceId }; } else { constraints.video.facingMode = 'user'; // Default to front camera } try { const stream = await navigator.mediaDevices.getUserMedia(constraints); video.srcObject = stream; currentStream = stream; return new Promise((resolve) => { video.onloadedmetadata = () => { setupCanvas(); resolve(video); }; }); } catch (err) { console.error('Error accessing webcam:', err); alert('Error accessing webcam. Please make sure you have granted camera permission.'); } } // MediaPipe camera controller let cameraController = null; // Initialize MediaPipe Hands function setupHands() { // If there's an existing camera controller, stop it if (cameraController) { cameraController.stop(); } const hands = new Hands({ locateFile: (file) => { return `https://cdn.jsdelivr.net/npm/@mediapipe/hands/${file}`; } }); hands.setOptions({ maxNumHands: 1, modelComplexity: 1, minDetectionConfidence: 0.5, minTrackingConfidence: 0.5 }); hands.onResults(onHandResults); // Start camera and detect hands cameraController = new Camera(video, { onFrame: async () => { await hands.send({ image: video }); }, width: 1280, height: 720 }); cameraController.start(); } // Calculate palm size and depth function calculateHandMetrics(landmarks) { // Calculate the palm width (distance between pinky MCP and index MCP) const pinkyMCP = landmarks[17]; // Pinky MCP joint const indexMCP = landmarks[5]; // Index MCP joint const dx = (pinkyMCP.x - indexMCP.x) * handsCanvas.width; const dy = (pinkyMCP.y - indexMCP.y) * handsCanvas.height; // Euclidean distance for palm width const palmWidth = Math.sqrt(dx * dx + dy * dy); // Calculate palm size (area of the palm - approximated as distance from wrist to middle MCP) const wrist = landmarks[0]; const middleMCP = landmarks[9]; const palmX = (middleMCP.x - wrist.x) * handsCanvas.width; const palmY = (middleMCP.y - wrist.y) * handsCanvas.height; const palmHeight = Math.sqrt(palmX * palmX + palmY * palmY); // Calculate total hand size (wrist to middle finger tip) const middleTip = landmarks[12]; const handX = (middleTip.x - wrist.x) * handsCanvas.width; const handY = (middleTip.y - wrist.y) * handsCanvas.height; const handLength = Math.sqrt(handX * handX + handY * handY); // Use the palm area to determine overall hand size metric const palmSize = palmWidth * palmHeight; // Calculate a normalized depth value (0-1) // We'll use the palm size relative to the canvas area as a depth indicator // Bigger size = closer to camera const canvasArea = handsCanvas.width * handsCanvas.height; const relativePalmSize = palmSize / canvasArea; // Apply a scaling factor and clamp between 0-1 const depthScalingFactor = 50000; // Adjust this based on typical palm sizes const depth = Math.min(Math.max(relativePalmSize * depthScalingFactor, 0), 1); return { palmWidth: palmWidth, palmHeight: palmHeight, handLength: handLength, palmSize: palmSize, depth: depth }; } // Get dynamic brush size based on hand metrics - scaled directly from palm width function getBrushSize(metrics) { if (!metrics) return 10; // Default fallback // Scale the brush size to be a fraction of the palm width // Small enough to write with precision using the finger tip return metrics.palmWidth * 0.4; } // Get eraser size based on palm width function getEraserSize(metrics) { if (!metrics) return 50; // Default fallback // Make eraser approximately the size of the palm // Use 1.5x the width between pinky and index MCP return metrics.palmWidth * 1.5; } // Draw pointer or eraser circle based on hand position function drawPointer(x, y, isEraser, size) { handsCtx.beginPath(); if (isEraser) { handsCtx.strokeStyle = 'rgba(255, 0, 0, 0.8)'; handsCtx.fillStyle = 'rgba(255, 0, 0, 0.3)'; } else { handsCtx.strokeStyle = colorPicker.value; handsCtx.fillStyle = 'rgba(255, 255, 255, 0.5)'; } handsCtx.lineWidth = 2; handsCtx.arc(x, y, size / 2, 0, Math.PI * 2); handsCtx.fill(); handsCtx.stroke(); // Draw debug info if needed if (DEBUG && handMetrics) { handsCtx.font = '14px Arial'; handsCtx.fillStyle = 'white'; handsCtx.fillText(`Depth: ${handMetrics.depth.toFixed(3)}`, 20, 30); handsCtx.fillText(`Palm Width: ${handMetrics.palmWidth.toFixed(0)}px`, 20, 50); handsCtx.fillText(`Palm Size: ${handMetrics.palmSize.toFixed(0)}px²`, 20, 70); handsCtx.fillText(`Brush Size: ${size.toFixed(1)}px`, 20, 90); } } // Handle hand detection results function onHandResults(results) { // Clear hand canvas handsCtx.clearRect(0, 0, handsCanvas.width, handsCanvas.height); if (results.multiHandLandmarks && results.multiHandLandmarks.length > 0) { const landmarks = results.multiHandLandmarks[0]; // Draw hand landmarks drawConnectors(handsCtx, landmarks, HAND_CONNECTIONS, { color: '#00FF00', lineWidth: 2 }); drawLandmarks(handsCtx, landmarks, { color: '#FF0000', lineWidth: 1, radius: 3 }); // Calculate hand metrics (palm size and depth) handMetrics = calculateHandMetrics(landmarks); // Get index finger tip position (landmark 8) indexFingerTip = landmarks[8]; // Detect hand gestures detectGestures(landmarks); // Handle drawing if index finger is pointing if (handPose === 'index_finger' && indexFingerTip) { const x = indexFingerTip.x * handsCanvas.width; const y = indexFingerTip.y * handsCanvas.height; // Calculate brush size based on hand metrics const dynamicBrushSize = getBrushSize(handMetrics); // Draw pointer circle drawPointer(x, y, false, dynamicBrushSize); if (!isDrawing) { // Start drawing - move to position prevX = x; prevY = y; isDrawing = true; isErasing = false; } else { // Continue drawing - draw line drawLine(prevX, prevY, x, y, dynamicBrushSize); prevX = x; prevY = y; } } else if (handPose === 'open_hand') { // Get palm center (roughly landmark 9 - middle finger MCP) const palmCenter = landmarks[9]; const x = palmCenter.x * handsCanvas.width; const y = palmCenter.y * handsCanvas.height; // Calculate eraser size based on palm const eraserSize = getEraserSize(handMetrics); // Draw eraser circle drawPointer(x, y, true, eraserSize); if (!isErasing) { // Start erasing - move to position prevX = x; prevY = y; isErasing = true; isDrawing = false; } else { // Continue erasing - use palm-sized eraser erase(prevX, prevY, x, y, eraserSize); prevX = x; prevY = y; } } else { // Stop drawing/erasing isDrawing = false; isErasing = false; } } else { // No hands detected isDrawing = false; isErasing = false; indexFingerTip = null; } } // Detect specific hand gestures function detectGestures(landmarks) { // Get key finger landmarks const indexTip = landmarks[8]; const indexDip = landmarks[7]; const middleTip = landmarks[12]; const ringTip = landmarks[16]; const pinkyTip = landmarks[20]; // Calculate if fingers are extended const indexExtended = indexTip.y < indexDip.y; const middleExtended = middleTip.y < landmarks[11].y; const ringExtended = ringTip.y < landmarks[15].y; const pinkyExtended = pinkyTip.y < landmarks[19].y; // Check for index finger pointing if (indexExtended && !middleExtended && !ringExtended && !pinkyExtended) { handPose = 'index_finger'; return; } // Check for open hand if (indexExtended && middleExtended && ringExtended && pinkyExtended) { handPose = 'open_hand'; return; } // Default - no recognized gesture handPose = null; } // Draw a line between two points function drawLine(x1, y1, x2, y2, lineWidth) { drawingCtx.beginPath(); drawingCtx.moveTo(x1, y1); drawingCtx.lineTo(x2, y2); drawingCtx.strokeStyle = colorPicker.value; drawingCtx.lineWidth = lineWidth; drawingCtx.lineCap = 'round'; drawingCtx.stroke(); } // Erase by drawing with composite operation function erase(x1, y1, x2, y2, eraserSize) { drawingCtx.globalCompositeOperation = 'destination-out'; drawingCtx.beginPath(); drawingCtx.moveTo(x1, y1); drawingCtx.lineTo(x2, y2); drawingCtx.strokeStyle = 'rgba(0, 0, 0, 1)'; drawingCtx.lineWidth = eraserSize; drawingCtx.lineCap = 'round'; drawingCtx.stroke(); drawingCtx.globalCompositeOperation = 'source-over'; } // Clear the canvas function clearCanvas() { drawingCtx.clearRect(0, 0, drawingCanvas.width, drawingCanvas.height); } // Save the drawing function saveDrawing() { const link = document.createElement('a'); link.download = 'hand-gesture-drawing.png'; link.href = drawingCanvas.toDataURL(); link.click(); } // Event listeners window.addEventListener('resize', setupCanvas); clearButton.addEventListener('click', clearCanvas); saveButton.addEventListener('click', saveDrawing); // Handle camera selection change cameraSelect.addEventListener('change', async () => { console.log('Camera selection changed to:', cameraSelect.value); const deviceId = cameraSelect.value; if (deviceId) { // Stop current MediaPipe instance await setupCamera(deviceId); setupHands(); } }); // When device permissions change, update camera list navigator.mediaDevices.addEventListener('devicechange', async () => { await populateCameraOptions(); }); // Initialize the application async function init() { // Request camera permissions and populate dropdown try { // Populate camera options (this will request permissions) await populateCameraOptions(); // Setup with selected camera (or default if none selected) const selectedCameraId = cameraSelect.value; await setupCamera(selectedCameraId); setupHands(); // Check for camera changes after a short delay (for devices that might take time to initialize) setTimeout(async () => { await populateCameraOptions(); }, 2000); } catch (err) { console.error('Error initializing:', err); alert('Error accessing webcam. Please make sure you have granted camera permission.'); } } // Start everything when the page is loaded window.addEventListener('load', init);
wonderwhy-er/camera-geasture-drawing
8
web app with webcam that does drawing with hand gestures
JavaScript
wonderwhy-er
Eduard Ruzga
index.html
HTML
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Hand Gesture Drawing</title> <link rel="stylesheet" href="style.css"> </head> <body> <div class="container"> <div class="video-container"> <video id="webcam" autoplay playsinline></video> <canvas id="drawing-canvas"></canvas> <canvas id="hands-canvas"></canvas> </div> <div class="controls"> <div class="control-group"> <label for="camera-select">Camera:</label> <select id="camera-select"></select> </div> <div class="control-group"> <label for="color-picker">Color:</label> <input type="color" id="color-picker" value="#FF0000"> </div> ======= <button id="clear-button">Clear Canvas</button> <button id="save-button">Save Drawing</button> <div class="gesture-help"> <h3>Gesture Guide:</h3> <ul> <li>✋ Open Hand: Erase (palm acts as an eraser)</li> <li>👆 Index Finger: Draw (size changes with distance)</li> </ul> </div> </div> </div> <script src="https://cdn.jsdelivr.net/npm/@mediapipe/camera_utils/camera_utils.js" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/@mediapipe/control_utils/control_utils.js" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/@mediapipe/drawing_utils/drawing_utils.js" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/@mediapipe/hands/hands.js" crossorigin="anonymous"></script> <script src="app.js"></script> </body> </html>
wonderwhy-er/camera-geasture-drawing
8
web app with webcam that does drawing with hand gestures
JavaScript
wonderwhy-er
Eduard Ruzga
style.css
CSS
* { margin: 0; padding: 0; box-sizing: border-box; } body { font-family: Arial, sans-serif; background-color: #121212; color: #fff; overflow: hidden; } .container { display: flex; height: 100vh; } .video-container { position: relative; flex: 1; overflow: hidden; } #webcam { position: absolute; width: 100%; height: 100%; object-fit: cover; transform: scaleX(-1); /* Mirror the video */ } #drawing-canvas, #hands-canvas { position: absolute; width: 100%; height: 100%; transform: scaleX(-1); /* Mirror the canvas */ } #drawing-canvas { z-index: 10; } #hands-canvas { z-index: 20; } .controls { width: 300px; background-color: #1e1e1e; padding: 20px; border-left: 1px solid #333; overflow-y: auto; } .control-group { margin-bottom: 20px; } label { display: block; margin-bottom: 5px; font-weight: bold; } button { background-color: #4CAF50; color: white; border: none; padding: 10px 15px; margin: 5px 0; cursor: pointer; border-radius: 4px; font-size: 14px; width: 100%; } button:hover { background-color: #45a049; } #clear-button { background-color: #f44336; } #clear-button:hover { background-color: #d32f2f; } #save-button { background-color: #2196F3; margin-bottom: 20px; } #save-button:hover { background-color: #0b7dda; } input[type="color"] { width: 100%; height: 40px; cursor: pointer; border: none; } input[type="range"] { width: 80%; cursor: pointer; } .mode-controls { margin-bottom: 20px; } .mode-button { width: 48%; display: inline-block; background-color: #555; } .mode-button.active { background-color: #4CAF50; } .gesture-help { margin-top: 20px; border-top: 1px solid #333; padding-top: 20px; } .gesture-help h3 { margin-bottom: 10px; } .gesture-help ul { list-style-type: none; } .gesture-help li { padding: 5px 0; } #brush-size-value { margin-left: 10px; }
wonderwhy-er/camera-geasture-drawing
8
web app with webcam that does drawing with hand gestures
JavaScript
wonderwhy-er
Eduard Ruzga
index.html
HTML
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>AI News Report | January 2026</title> <link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&family=Space+Grotesk:wght@400;500;600;700&display=swap" rel="stylesheet"> <style> :root { --bg-primary: #0a0a0f; --bg-secondary: #12121a; --bg-card: #1a1a24; --bg-glass: rgba(26, 26, 36, 0.7); --text-primary: #ffffff; --text-secondary: #a0a0b0; --text-muted: #6b6b7b; --accent-blue: #3b82f6; --accent-purple: #8b5cf6; --accent-pink: #ec4899; --accent-cyan: #06b6d4; --accent-green: #10b981; --accent-orange: #f97316; --gradient-1: linear-gradient(135deg, #3b82f6, #8b5cf6); --gradient-2: linear-gradient(135deg, #ec4899, #8b5cf6); --gradient-3: linear-gradient(135deg, #06b6d4, #3b82f6); --border-color: rgba(255, 255, 255, 0.08); --shadow-glow: 0 0 60px rgba(59, 130, 246, 0.15); } * { margin: 0; padding: 0; box-sizing: border-box; } body { font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif; background: var(--bg-primary); color: var(--text-primary); line-height: 1.6; overflow-x: hidden; } /* Animated Background */ .bg-animation { position: fixed; top: 0; left: 0; width: 100%; height: 100%; z-index: -1; overflow: hidden; } .bg-animation::before { content: ''; position: absolute; top: -50%; left: -50%; width: 200%; height: 200%; background: radial-gradient(circle at 20% 80%, rgba(59, 130, 246, 0.08) 0%, transparent 50%), radial-gradient(circle at 80% 20%, rgba(139, 92, 246, 0.08) 0%, transparent 50%), radial-gradient(circle at 40% 40%, rgba(236, 72, 153, 0.05) 0%, transparent 40%); animation: float 30s ease-in-out infinite; } @keyframes float { 0%, 100% { transform: translate(0, 0) rotate(0deg); } 33% { transform: translate(30px, -30px) rotate(5deg); } 66% { transform: translate(-20px, 20px) rotate(-5deg); } } /* Header */ header { position: relative; padding: 80px 20px 60px; text-align: center; border-bottom: 1px solid var(--border-color); background: linear-gradient(180deg, rgba(59, 130, 246, 0.05) 0%, transparent 100%); } .header-badge { display: inline-flex; align-items: center; gap: 8px; padding: 8px 16px; background: var(--bg-glass); border: 1px solid var(--border-color); border-radius: 50px; font-size: 0.85rem; color: var(--text-secondary); margin-bottom: 24px; backdrop-filter: blur(10px); } .header-badge .pulse { width: 8px; height: 8px; background: var(--accent-green); border-radius: 50%; animation: pulse 2s ease-in-out infinite; } @keyframes pulse { 0%, 100% { opacity: 1; transform: scale(1); } 50% { opacity: 0.5; transform: scale(1.2); } } h1 { font-family: 'Space Grotesk', sans-serif; font-size: clamp(2.5rem, 6vw, 4.5rem); font-weight: 700; background: var(--gradient-1); -webkit-background-clip: text; -webkit-text-fill-color: transparent; background-clip: text; margin-bottom: 16px; letter-spacing: -0.02em; } .subtitle { font-size: 1.2rem; color: var(--text-secondary); max-width: 600px; margin: 0 auto; } .date-badge { display: inline-block; margin-top: 24px; padding: 10px 20px; background: var(--bg-card); border: 1px solid var(--border-color); border-radius: 8px; font-size: 0.9rem; color: var(--text-secondary); } /* Main Container */ .container { max-width: 1400px; margin: 0 auto; padding: 60px 20px; } /* Stats Section */ .stats-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 20px; margin-bottom: 60px; } .stat-card { background: var(--bg-glass); border: 1px solid var(--border-color); border-radius: 16px; padding: 24px; text-align: center; backdrop-filter: blur(10px); transition: all 0.3s ease; } .stat-card:hover { transform: translateY(-4px); border-color: rgba(59, 130, 246, 0.3); box-shadow: var(--shadow-glow); } .stat-value { font-family: 'Space Grotesk', sans-serif; font-size: 2.5rem; font-weight: 700; background: var(--gradient-1); -webkit-background-clip: text; -webkit-text-fill-color: transparent; background-clip: text; } .stat-label { color: var(--text-secondary); font-size: 0.9rem; margin-top: 8px; } /* Section Headers */ .section-header { display: flex; align-items: center; gap: 16px; margin-bottom: 32px; } .section-icon { width: 48px; height: 48px; display: flex; align-items: center; justify-content: center; border-radius: 12px; font-size: 1.5rem; } .section-title { font-family: 'Space Grotesk', sans-serif; font-size: 1.8rem; font-weight: 600; } /* Featured Story */ .featured-story { background: linear-gradient(135deg, rgba(59, 130, 246, 0.1), rgba(139, 92, 246, 0.1)); border: 1px solid rgba(59, 130, 246, 0.2); border-radius: 24px; padding: 40px; margin-bottom: 60px; position: relative; overflow: hidden; } .featured-story::before { content: 'FEATURED'; position: absolute; top: 20px; right: 20px; background: var(--gradient-1); padding: 6px 14px; border-radius: 50px; font-size: 0.75rem; font-weight: 600; letter-spacing: 0.05em; } .featured-story h2 { font-family: 'Space Grotesk', sans-serif; font-size: 2rem; margin-bottom: 16px; max-width: 80%; } .featured-story p { color: var(--text-secondary); font-size: 1.1rem; max-width: 800px; margin-bottom: 24px; } .featured-tags { display: flex; flex-wrap: wrap; gap: 10px; } .tag { padding: 6px 14px; background: var(--bg-card); border: 1px solid var(--border-color); border-radius: 50px; font-size: 0.85rem; color: var(--text-secondary); } /* News Grid */ .news-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(350px, 1fr)); gap: 24px; margin-bottom: 60px; } .news-card { background: var(--bg-card); border: 1px solid var(--border-color); border-radius: 20px; padding: 28px; transition: all 0.3s ease; position: relative; overflow: hidden; } .news-card::before { content: ''; position: absolute; top: 0; left: 0; right: 0; height: 3px; background: var(--card-accent, var(--gradient-1)); opacity: 0; transition: opacity 0.3s ease; } .news-card:hover { transform: translateY(-4px); border-color: rgba(255, 255, 255, 0.15); box-shadow: 0 20px 40px rgba(0, 0, 0, 0.3); } .news-card:hover::before { opacity: 1; } .news-card .category { display: inline-block; padding: 4px 12px; border-radius: 50px; font-size: 0.75rem; font-weight: 500; text-transform: uppercase; letter-spacing: 0.05em; margin-bottom: 16px; } .news-card h3 { font-family: 'Space Grotesk', sans-serif; font-size: 1.3rem; font-weight: 600; margin-bottom: 12px; line-height: 1.4; } .news-card p { color: var(--text-secondary); font-size: 0.95rem; line-height: 1.7; } .news-card .source { display: flex; align-items: center; gap: 8px; margin-top: 20px; padding-top: 16px; border-top: 1px solid var(--border-color); font-size: 0.85rem; color: var(--text-muted); } .news-card .source a { color: var(--accent-blue); text-decoration: none; transition: color 0.2s ease; } .news-card .source a:hover { color: var(--accent-purple); } /* Category Colors */ .cat-models { background: rgba(59, 130, 246, 0.2); color: var(--accent-blue); } .cat-agents { background: rgba(139, 92, 246, 0.2); color: var(--accent-purple); } .cat-research { background: rgba(6, 182, 212, 0.2); color: var(--accent-cyan); } .cat-business { background: rgba(16, 185, 129, 0.2); color: var(--accent-green); } .cat-regulation { background: rgba(249, 115, 22, 0.2); color: var(--accent-orange); } .cat-culture { background: rgba(236, 72, 153, 0.2); color: var(--accent-pink); } /* Card Accents */ .accent-blue { --card-accent: linear-gradient(90deg, var(--accent-blue), var(--accent-cyan)); } .accent-purple { --card-accent: linear-gradient(90deg, var(--accent-purple), var(--accent-pink)); } .accent-green { --card-accent: linear-gradient(90deg, var(--accent-green), var(--accent-cyan)); } .accent-orange { --card-accent: linear-gradient(90deg, var(--accent-orange), var(--accent-pink)); } /* Timeline Section */ .timeline-section { margin-bottom: 60px; } .timeline { position: relative; padding-left: 40px; } .timeline::before { content: ''; position: absolute; left: 8px; top: 0; bottom: 0; width: 2px; background: linear-gradient(180deg, var(--accent-blue), var(--accent-purple), var(--accent-pink)); } .timeline-item { position: relative; padding-bottom: 32px; } .timeline-item::before { content: ''; position: absolute; left: -36px; top: 4px; width: 14px; height: 14px; background: var(--bg-primary); border: 3px solid var(--accent-blue); border-radius: 50%; } .timeline-item:nth-child(2)::before { border-color: var(--accent-purple); } .timeline-item:nth-child(3)::before { border-color: var(--accent-cyan); } .timeline-item:nth-child(4)::before { border-color: var(--accent-green); } .timeline-item:nth-child(5)::before { border-color: var(--accent-pink); } .timeline-date { font-size: 0.85rem; color: var(--accent-blue); font-weight: 500; margin-bottom: 8px; } .timeline-content h4 { font-family: 'Space Grotesk', sans-serif; font-size: 1.1rem; margin-bottom: 8px; } .timeline-content p { color: var(--text-secondary); font-size: 0.95rem; } /* Companies Section */ .companies-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(280px, 1fr)); gap: 20px; margin-bottom: 60px; } .company-card { background: var(--bg-card); border: 1px solid var(--border-color); border-radius: 16px; padding: 24px; transition: all 0.3s ease; } .company-card:hover { border-color: rgba(255, 255, 255, 0.15); transform: translateY(-2px); } .company-header { display: flex; align-items: center; gap: 16px; margin-bottom: 16px; } .company-logo { width: 48px; height: 48px; border-radius: 12px; display: flex; align-items: center; justify-content: center; font-size: 1.5rem; font-weight: 700; } .company-name { font-family: 'Space Grotesk', sans-serif; font-size: 1.2rem; font-weight: 600; } .company-revenue { font-size: 0.9rem; color: var(--accent-green); margin-top: 4px; } .company-card p { color: var(--text-secondary); font-size: 0.9rem; } .openai-logo { background: linear-gradient(135deg, #10a37f, #1a7f5a); } .anthropic-logo { background: linear-gradient(135deg, #d4a574, #c49a6c); } .google-logo { background: linear-gradient(135deg, #4285f4, #34a853); } .meta-logo { background: linear-gradient(135deg, #0668e1, #1877f2); } /* Quote Section */ .quote-section { background: var(--bg-glass); border: 1px solid var(--border-color); border-radius: 24px; padding: 48px; margin-bottom: 60px; text-align: center; backdrop-filter: blur(10px); } .quote-section blockquote { font-family: 'Space Grotesk', sans-serif; font-size: 1.5rem; font-weight: 500; font-style: italic; max-width: 800px; margin: 0 auto 24px; line-height: 1.6; } .quote-author { color: var(--text-secondary); } .quote-author strong { color: var(--text-primary); } /* Footer */ footer { text-align: center; padding: 40px 20px; border-top: 1px solid var(--border-color); color: var(--text-muted); } footer a { color: var(--accent-blue); text-decoration: none; } .footer-links { display: flex; justify-content: center; gap: 24px; margin-bottom: 16px; flex-wrap: wrap; } .footer-links a { color: var(--text-secondary); transition: color 0.2s ease; } .footer-links a:hover { color: var(--accent-blue); } /* Responsive */ @media (max-width: 768px) { header { padding: 60px 20px 40px; } .featured-story { padding: 28px; } .featured-story h2 { max-width: 100%; font-size: 1.5rem; } .featured-story::before { position: static; display: inline-block; margin-bottom: 16px; } .news-grid { grid-template-columns: 1fr; } .quote-section { padding: 32px 20px; } .quote-section blockquote { font-size: 1.2rem; } } </style> </head> <body> <div class="bg-animation"></div> <header> <div class="header-badge"> <span class="pulse"></span> Live AI Intelligence Report </div> <h1>AI News Report</h1> <p class="subtitle">Your comprehensive guide to the latest breakthroughs, trends, and developments shaping the future of artificial intelligence</p> <div class="date-badge">January 2026 Edition</div> </header> <main class="container"> <!-- Stats Section --> <section class="stats-grid"> <div class="stat-card"> <div class="stat-value">$200B</div> <div class="stat-label">Projected Agentic AI Market by 2034</div> </div> <div class="stat-card"> <div class="stat-value">$30B</div> <div class="stat-label">OpenAI 2026 Revenue Target</div> </div> <div class="stat-card"> <div class="stat-value">136%</div> <div class="stat-label">Rise in "Analog Hobbies" Searches</div> </div> <div class="stat-card"> <div class="stat-value">7x</div> <div class="stat-label">Falcon-H1R Efficiency Gain</div> </div> </section> <!-- Featured Story --> <article class="featured-story"> <h2>2026: The Year AI Gets Practical</h2> <p>If 2025 was the year AI got a vibe check, 2026 marks the shift from hype to pragmatism. The focus is moving away from building ever-larger language models toward the harder work of making AI actually usable—deploying smaller models where they fit, embedding intelligence into physical devices, and designing systems that integrate cleanly into human workflows.</p> <div class="featured-tags"> <span class="tag">Industry Shift</span> <span class="tag">Efficiency Models</span> <span class="tag">Enterprise AI</span> <span class="tag">Practical Applications</span> </div> </article> <!-- Model Releases Section --> <section> <div class="section-header"> <div class="section-icon" style="background: rgba(59, 130, 246, 0.2);">🚀</div> <h2 class="section-title">Major Model Releases & Advances</h2> </div> <div class="news-grid"> <article class="news-card accent-blue"> <span class="category cat-models">Models</span> <h3>Google Gemini 3 Takes the Lead</h3> <p>Google has officially pulled ahead in the chatbot arms race with the launch of Gemini 3, positioning the company as a leader in conversational AI and challenging OpenAI's dominance.</p> <div class="source"> <span>Source:</span> <a href="https://www.aiapps.com/blog/ai-news-january-2026-breakthroughs-launches-trends/" target="_blank">AI Apps Blog</a> </div> </article> <article class="news-card accent-purple"> <span class="category cat-models">Models</span> <h3>Falcon-H1R 7B: Small but Mighty</h3> <p>Technology Innovation Institute unveiled Falcon-H1R 7B, a compact AI model delivering performance comparable to systems up to 7x its size using a Transformer-Mamba hybrid architecture.</p> <div class="source"> <span>Source:</span> <a href="https://www.humai.blog/ai-news-trends-january-2026-complete-monthly-digest/" target="_blank">Humai Blog</a> </div> </article> <article class="news-card accent-green"> <span class="category cat-models">Models</span> <h3>Claude 5 Expected in Early 2026</h3> <p>Anthropic is expected to release Claude 5 in February or March 2026, taking time to make meaningful improvements. Claude Opus 4.5 can now solve complex problems that take human experts 5 hours.</p> <div class="source"> <span>Source:</span> <a href="https://medium.com/@urano10/the-future-of-ai-models-in-2026-whats-actually-coming-410141f3c979" target="_blank">Medium</a> </div> </article> <article class="news-card accent-orange"> <span class="category cat-models">Models</span> <h3>Meta Superintelligence Labs Delivers</h3> <p>Meta CTO Andrew Bosworth announced at Davos that Meta Superintelligence Labs has delivered its first high-profile AI models internally in January 2026.</p> <div class="source"> <span>Source:</span> <a href="https://www.aiapps.com/blog/ai-news-january-2026-breakthroughs-launches-trends/" target="_blank">AI Apps Blog</a> </div> </article> </div> </section> <!-- Agentic AI Section --> <section> <div class="section-header"> <div class="section-icon" style="background: rgba(139, 92, 246, 0.2);">🤖</div> <h2 class="section-title">Agentic AI & MCP Protocol</h2> </div> <div class="news-grid"> <article class="news-card accent-purple"> <span class="category cat-agents">Agents</span> <h3>MCP Becomes the Industry Standard</h3> <p>Anthropic's Model Context Protocol (MCP)—described as "USB-C for AI"—is quickly becoming the standard. OpenAI, Microsoft, and Google have all embraced it, with Anthropic donating it to the Linux Foundation's Agentic AI Foundation.</p> <div class="source"> <span>Source:</span> <a href="https://techcrunch.com/2026/01/02/in-2026-ai-will-move-from-hype-to-pragmatism/" target="_blank">TechCrunch</a> </div> </article> <article class="news-card accent-blue"> <span class="category cat-agents">Agents</span> <h3>$200B Agentic AI Market Projected</h3> <p>The agentic AI market is projected to grow from $5.2B in 2024 to $200B by 2034. These autonomous systems will integrate across enterprise functions from finance to supply-chain management.</p> <div class="source"> <span>Source:</span> <a href="https://www.trigyn.com/insights/ai-trends-2026-new-era-ai-advancements-and-breakthroughs" target="_blank">Trigyn</a> </div> </article> </div> </section> <!-- Research & Breakthroughs --> <section> <div class="section-header"> <div class="section-icon" style="background: rgba(6, 182, 212, 0.2);">🔬</div> <h2 class="section-title">Research & Scientific Breakthroughs</h2> </div> <div class="news-grid"> <article class="news-card accent-green"> <span class="category cat-research">Research</span> <h3>AlphaEvolve: AI-Designed Algorithms</h3> <p>Google DeepMind revealed AlphaEvolve, combining Gemini LLM with evolutionary algorithms to discover new solutions for unsolved problems, including optimizing data center power consumption.</p> <div class="source"> <span>Source:</span> <a href="https://www.technologyreview.com/2026/01/05/1130662/whats-next-for-ai-in-2026/" target="_blank">MIT Technology Review</a> </div> </article> <article class="news-card accent-blue"> <span class="category cat-research">Research</span> <h3>World Models Go Mainstream</h3> <p>World models are multiplying: LeCun left Meta to start his own world model lab, DeepMind launched Genie for real-time interactive world models, and Fei-Fei Li's World Labs launched Marble commercially.</p> <div class="source"> <span>Source:</span> <a href="https://www.technologyreview.com/2026/01/05/1130662/whats-next-for-ai-in-2026/" target="_blank">MIT Technology Review</a> </div> </article> <article class="news-card accent-orange"> <span class="category cat-research">Research</span> <h3>IBM: Quantum Computing Milestone</h3> <p>IBM states that 2026 will mark the first time a quantum computer outperforms a classical computer, unlocking breakthroughs in drug development, materials science, and financial optimization.</p> <div class="source"> <span>Source:</span> <a href="https://www.ibm.com/think/news/ai-tech-trends-predictions-2026" target="_blank">IBM</a> </div> </article> <article class="news-card accent-purple"> <span class="category cat-research">Research</span> <h3>Mechanistic Interpretability Advances</h3> <p>Anthropic's microscope research maps key features and pathways across AI models, revealing whole sequences of features and tracing the path from prompt to response.</p> <div class="source"> <span>Source:</span> <a href="https://www.technologyreview.com/2026/01/12/1130003/mechanistic-interpretability-ai-research-models-2026-breakthrough-technologies/" target="_blank">MIT Technology Review</a> </div> </article> </div> </section> <!-- Quote Section --> <section class="quote-section"> <blockquote>"AI models would replace the work of all software developers within a year and would reach 'Nobel-level' scientific research in multiple fields within two years."</blockquote> <p class="quote-author">— <strong>Dario Amodei</strong>, CEO of Anthropic, at Davos 2026</p> </section> <!-- Companies Section --> <section> <div class="section-header"> <div class="section-icon" style="background: rgba(16, 185, 129, 0.2);">💼</div> <h2 class="section-title">Industry Leaders & Revenue</h2> </div> <div class="companies-grid"> <div class="company-card"> <div class="company-header"> <div class="company-logo openai-logo">O</div> <div> <div class="company-name">OpenAI</div> <div class="company-revenue">$30B target for 2026</div> </div> </div> <p>Generated $13B+ in 2025, ended with ~$20B ARR. Aiming for $30B revenue in 2026 according to leaked documents.</p> </div> <div class="company-card"> <div class="company-header"> <div class="company-logo anthropic-logo">A</div> <div> <div class="company-name">Anthropic</div> <div class="company-revenue">$15B target for 2026</div> </div> </div> <p>Made ~$10B in 2025 revenue according to CEO Dario Amodei. ARR rose to "almost $7B" by October 2025.</p> </div> <div class="company-card"> <div class="company-header"> <div class="company-logo google-logo">G</div> <div> <div class="company-name">Google DeepMind</div> <div class="company-revenue">Leading with Gemini 3</div> </div> </div> <p>Pulled ahead with Gemini 3 launch. Hassabis says current AI is "nowhere near" human-level AGI.</p> </div> <div class="company-card"> <div class="company-header"> <div class="company-logo meta-logo">M</div> <div> <div class="company-name">Meta AI</div> <div class="company-revenue">Superintelligence Labs</div> </div> </div> <p>Meta Superintelligence Labs delivered first models internally. Aggressive hiring in AI talent wars.</p> </div> </div> </section> <!-- EU & Regulation --> <section> <div class="section-header"> <div class="section-icon" style="background: rgba(249, 115, 22, 0.2);">🏛️</div> <h2 class="section-title">Regulation & Infrastructure</h2> </div> <div class="news-grid"> <article class="news-card accent-orange"> <span class="category cat-regulation">Policy</span> <h3>EU AI Gigafactories Initiative</h3> <p>The Council of the EU adopted an amendment to extend EuroHPC JU to facilitate AI gigafactories creation—world-class AI compute infrastructure to strengthen Europe's industry and competitiveness.</p> <div class="source"> <span>Source:</span> <a href="https://www.consilium.europa.eu/en/press/press-releases/2026/01/16/artificial-intelligence-council-paves-the-way-for-the-creation-of-ai-gigafactories/" target="_blank">EU Council</a> </div> </article> <article class="news-card accent-purple"> <span class="category cat-regulation">Policy</span> <h3>2026: Year of Regulatory Tug-of-War</h3> <p>As AI advances, 2026 will be another year of regulatory battles. Policymakers face mounting pressure to translate abstract principles into enforceable rules.</p> <div class="source"> <span>Source:</span> <a href="https://www.cfr.org/articles/how-2026-could-decide-future-artificial-intelligence" target="_blank">Council on Foreign Relations</a> </div> </article> </div> </section> <!-- Cultural Impact --> <section> <div class="section-header"> <div class="section-icon" style="background: rgba(236, 72, 153, 0.2);">🎨</div> <h2 class="section-title">Cultural Impact & Backlash</h2> </div> <div class="news-grid"> <article class="news-card accent-purple"> <span class="category cat-culture">Culture</span> <h3>The Analog Lifestyle Movement</h3> <p>With AI-powered devices everywhere, a backlash is brewing. "Analog lifestyles" are emerging as an effort to slow down and find tangible ways to complete daily tasks.</p> <div class="source"> <span>Source:</span> <a href="https://www.cnn.com/2026/01/18/business/crafting-soars-ai-analog-wellness" target="_blank">CNN Business</a> </div> </article> <article class="news-card accent-orange"> <span class="category cat-culture">Culture</span> <h3>Crafting Boom: 136% Search Increase</h3> <p>Michael's has seen searches for "analog hobbies" increase by 136% in six months. It's different from a digital detox—it's a long-term commitment to tangible activities.</p> <div class="source"> <span>Source:</span> <a href="https://www.cnn.com/2026/01/18/business/crafting-soars-ai-analog-wellness" target="_blank">CNN Business</a> </div> </article> </div> </section> <!-- Challenges Section --> <section> <div class="section-header"> <div class="section-icon" style="background: rgba(239, 68, 68, 0.2);">⚠️</div> <h2 class="section-title">Challenges & Concerns</h2> </div> <div class="news-grid"> <article class="news-card accent-orange"> <span class="category cat-research">Research</span> <h3>100+ Hallucinated Citations at NeurIPS</h3> <p>GPTZero found at least 100 confirmed hallucinated citations spread across 51 scientific papers accepted at NeurIPS—one of the world's most prestigious AI conferences—despite full peer review.</p> <div class="source"> <span>Source:</span> <a href="https://www.aiapps.com/blog/ai-news-january-2026-breakthroughs-launches-trends/" target="_blank">AI Apps Blog</a> </div> </article> <article class="news-card accent-purple"> <span class="category cat-research">Research</span> <h3>Mathematical Proof of LLM Limits</h3> <p>New research provides mathematical proof that large language models have fundamental limitations, claiming they are "incapable of carrying out computational and agentic tasks beyond a certain complexity."</p> <div class="source"> <span>Source:</span> <a href="https://www.humai.blog/ai-news-trends-january-2026-complete-monthly-digest/" target="_blank">Humai Blog</a> </div> </article> </div> </section> <!-- Timeline --> <section class="timeline-section"> <div class="section-header"> <div class="section-icon" style="background: rgba(59, 130, 246, 0.2);">📅</div> <h2 class="section-title">Key Events Timeline</h2> </div> <div class="timeline"> <div class="timeline-item"> <div class="timeline-date">January 2, 2026</div> <div class="timeline-content"> <h4>TechCrunch Declares "Year of Pragmatism"</h4> <p>Industry shifts focus from model scaling to practical AI applications</p> </div> </div> <div class="timeline-item"> <div class="timeline-date">January 12, 2026</div> <div class="timeline-content"> <h4>MIT Names Mechanistic Interpretability as Breakthrough Tech</h4> <p>Anthropic's research on AI model transparency recognized as top innovation</p> </div> </div> <div class="timeline-item"> <div class="timeline-date">January 16, 2026</div> <div class="timeline-content"> <h4>EU Council Approves AI Gigafactories</h4> <p>European High-Performance Computing Joint Undertaking extended for AI infrastructure</p> </div> </div> <div class="timeline-item"> <div class="timeline-date">January 18, 2026</div> <div class="timeline-content"> <h4>CNN Reports on Analog Lifestyle Trend</h4> <p>Growing backlash against AI-powered devices drives crafting boom</p> </div> </div> <div class="timeline-item"> <div class="timeline-date">January 20-24, 2026</div> <div class="timeline-content"> <h4>Davos 2026: AI Leaders Debate AGI</h4> <p>Amodei, Hassabis, and LeCun share divergent views on AI's future</p> </div> </div> </div> </section> </main> <footer> <div class="footer-links"> <a href="https://techcrunch.com/2026/01/02/in-2026-ai-will-move-from-hype-to-pragmatism/" target="_blank">TechCrunch</a> <a href="https://www.technologyreview.com/2026/01/05/1130662/whats-next-for-ai-in-2026/" target="_blank">MIT Technology Review</a> <a href="https://www.ibm.com/think/news/ai-tech-trends-predictions-2026" target="_blank">IBM</a> <a href="https://www.consilium.europa.eu/en/press/press-releases/2026/01/16/artificial-intelligence-council-paves-the-way-for-the-creation-of-ai-gigafactories/" target="_blank">EU Council</a> </div> <p>Generated by Claude AI on January 27, 2026 • Data sourced from multiple news outlets</p> <p style="margin-top: 8px;">Made with ❤️ using <a href="https://claude.ai" target="_blank">Claude</a></p> </footer> </body> </html>
wonderwhy-er/cowork-news-report
0
AI News Report January 2026 - A beautiful dark-themed webpage summarizing latest AI developments
HTML
wonderwhy-er
Eduard Ruzga
index.html
HTML
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>DevOps Demo - GitHub Actions</title> <link rel="stylesheet" href="styles.css"> </head> <body> <header> <h1>🚀 DevOps Demo Project</h1> <p>Showcasing GitHub Actions CI/CD Pipeline</p> </header> <main> <section class="demo-section"> <h2>Features Demonstrated</h2> <ul> <li>✅ Automated testing on Pull Requests</li> <li>✅ Code linting and validation</li> <li>✅ Automated deployment to GitHub Pages</li> <li>✅ Branch protection rules</li> </ul> </section> <section class="calculator-section"> <h2>Simple Calculator</h2> <div class="calculator"> <input type="number" id="num1" placeholder="First number"> <select id="operation"> <option value="add">+</option> <option value="subtract">-</option> <option value="multiply">×</option> <option value="divide">÷</option> </select> <input type="number" id="num2" placeholder="Second number"> <button onclick="calculate()">Calculate</button> <div id="result"></div> </div> </section> <section class="status-section"> <h2>Build Status</h2> <div id="build-info"> <p>Built with ❤️ using GitHub Actions</p> <p>Last deployed: <span id="deploy-time"></span></p> </div> </section> </main> <footer> <p>&copy; 2025 DevOps Demo Project</p> </footer> <script src="script.js"></script> </body> </html>
wonderwhy-er/devops-demo
1
DevOps demo project with GitHub Actions CI/CD pipeline
JavaScript
wonderwhy-er
Eduard Ruzga
lint.js
JavaScript
// Simple linter to check code quality const fs = require('fs'); console.log('🔍 Running code linting...\n'); let issues = 0; function checkFile(filename, rules) { if (!fs.existsSync(filename)) { console.log(`⚠️ File ${filename} not found`); return; } const content = fs.readFileSync(filename, 'utf8'); console.log(`📄 Checking ${filename}...`); rules.forEach(rule => { const matches = rule.pattern.test(content); if (rule.shouldMatch && !matches) { console.log(`❌ ${rule.message}`); issues++; } else if (!rule.shouldMatch && matches) { console.log(`❌ ${rule.message}`); issues++; } else { console.log(`✅ ${rule.passMessage || rule.message}`); } }); console.log(''); } // HTML file checks checkFile('index.html', [ { pattern: /<!DOCTYPE html>/i, shouldMatch: true, message: 'HTML5 DOCTYPE declaration found' }, { pattern: /<title>/i, shouldMatch: true, message: 'Page title found' }, { pattern: /lang="[a-z]+"/i, shouldMatch: true, message: 'Language attribute found' } ]); // CSS file checks checkFile('styles.css', [ { pattern: /\*\s*{/, shouldMatch: true, message: 'CSS reset/normalize found' }, { pattern: /@media/i, shouldMatch: true, message: 'Responsive design (media queries) found' } ]); // JavaScript file checks checkFile('script.js', [ { pattern: /function\s+\w+\(/, shouldMatch: true, message: 'Function declarations found' }, { pattern: /console\.log\(/, shouldMatch: false, message: 'No console.log statements in production code' } ]); console.log(`\n📊 Linting Results:`); console.log(`🔍 Issues found: ${issues}`); if (issues > 0) { console.log('\n💥 Linting failed! Please fix the issues above.'); process.exit(1); } else { console.log('\n🎉 Code quality checks passed!'); process.exit(0); }
wonderwhy-er/devops-demo
1
DevOps demo project with GitHub Actions CI/CD pipeline
JavaScript
wonderwhy-er
Eduard Ruzga
script.js
JavaScript
// Calculator functionality function calculate() { const num1 = parseFloat(document.getElementById('num1').value); const num2 = parseFloat(document.getElementById('num2').value); const operation = document.getElementById('operation').value; const resultDiv = document.getElementById('result'); // Clear previous classes resultDiv.className = ''; if (isNaN(num1) || isNaN(num2)) { resultDiv.textContent = 'Please enter valid numbers'; resultDiv.classList.add('error'); return; } let result; switch (operation) { case 'add': result = add(num1, num2); break; case 'subtract': result = subtract(num1, num2); break; case 'multiply': result = multiply(num1, num2); break; case 'divide': if (num2 === 0) { resultDiv.textContent = 'Error: Division by zero'; resultDiv.classList.add('error'); return; } result = divide(num1, num2); break; default: resultDiv.textContent = 'Invalid operation'; resultDiv.classList.add('error'); return; } resultDiv.textContent = `Result: ${result}`; resultDiv.classList.add('success'); } // Mathematical operations (these will be tested) function add(a, b) { return a + b; } function subtract(a, b) { return a - b; } function multiply(a, b) { return a * b; } function divide(a, b) { return a / b; } // Set deployment time (only in browser environment) if (typeof document !== 'undefined') { document.addEventListener('DOMContentLoaded', function() { const deployTime = document.getElementById('deploy-time'); deployTime.textContent = new Date().toLocaleString(); }); } // Export functions for testing (Node.js environment) if (typeof module !== 'undefined' && module.exports) { module.exports = { add, subtract, multiply, divide }; }
wonderwhy-er/devops-demo
1
DevOps demo project with GitHub Actions CI/CD pipeline
JavaScript
wonderwhy-er
Eduard Ruzga
styles.css
CSS
* { margin: 0; padding: 0; box-sizing: border-box; } body { font-family: 'Arial', sans-serif; line-height: 1.6; color: #333; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); min-height: 100vh; } header { text-align: center; padding: 2rem; background: rgba(255, 255, 255, 0.1); backdrop-filter: blur(10px); margin-bottom: 2rem; } header h1 { font-size: 2.5rem; color: white; margin-bottom: 0.5rem; text-shadow: 2px 2px 4px rgba(0,0,0,0.3); } header p { font-size: 1.2rem; color: rgba(255, 255, 255, 0.9); } main { max-width: 800px; margin: 0 auto; padding: 0 2rem; } .demo-section, .calculator-section, .status-section { background: white; padding: 2rem; margin-bottom: 2rem; border-radius: 10px; box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1); } .demo-section h2, .calculator-section h2, .status-section h2 { color: #4a5568; margin-bottom: 1rem; font-size: 1.5rem; } .demo-section ul { list-style: none; padding-left: 0; } .demo-section li { padding: 0.5rem 0; font-size: 1.1rem; } .calculator { display: flex; gap: 1rem; align-items: center; flex-wrap: wrap; } .calculator input, .calculator select, .calculator button { padding: 0.75rem; border: 2px solid #e2e8f0; border-radius: 5px; font-size: 1rem; } .calculator input { width: 150px; } .calculator button { background: #667eea; color: white; border: none; cursor: pointer; transition: background 0.3s ease; } .calculator button:hover { background: #5a67d8; } #result { margin-top: 1rem; padding: 1rem; background: #f7fafc; border-radius: 5px; font-weight: bold; min-height: 3rem; display: flex; align-items: center; } #build-info { background: #f0fff4; padding: 1rem; border-radius: 5px; border-left: 4px solid #48bb78; } #deploy-time { font-weight: bold; color: #2d3748; } footer { text-align: center; padding: 2rem; color: rgba(255, 255, 255, 0.8); margin-top: 2rem; } @media (max-width: 768px) { .calculator { flex-direction: column; align-items: stretch; } .calculator input { width: 100%; } main { padding: 0 1rem; } } .error { color: #e53e3e; background: #fed7d7; } .success { color: #38a169; background: #c6f6d5; }
wonderwhy-er/devops-demo
1
DevOps demo project with GitHub Actions CI/CD pipeline
JavaScript
wonderwhy-er
Eduard Ruzga
test.js
JavaScript
// Simple test runner (no external dependencies) const { add, subtract, multiply, divide } = require('./script.js'); console.log('🧪 Running tests...\n'); let passed = 0; let failed = 0; function test(description, actual, expected) { if (actual === expected) { console.log(`✅ ${description}: PASSED`); passed++; } else { console.log(`❌ ${description}: FAILED`); console.log(` Expected: ${expected}, Got: ${actual}`); failed++; } } // Test addition test('Add 2 + 3', add(2, 3), 5); test('Add negative numbers -5 + -3', add(-5, -3), -8); test('Add zero 10 + 0', add(10, 0), 10); // Test subtraction test('Subtract 10 - 5', subtract(10, 5), 5); test('Subtract negative result 3 - 7', subtract(3, 7), -4); test('Subtract zero 15 - 0', subtract(15, 0), 15); // Test multiplication test('Multiply 4 * 5', multiply(4, 5), 20); test('Multiply by zero 7 * 0', multiply(7, 0), 0); test('Multiply negative -3 * 4', multiply(-3, 4), -12); // Test division test('Divide 15 / 3', divide(15, 3), 5); test('Divide with decimal 7 / 2', divide(7, 2), 3.5); test('Divide negative -12 / 4', divide(-12, 4), -3); console.log(`\n📊 Test Results:`); console.log(`✅ Passed: ${passed}`); console.log(`❌ Failed: ${failed}`); console.log(`📈 Success Rate: ${((passed / (passed + failed)) * 100).toFixed(1)}%`); if (failed > 0) { console.log('\n💥 Some tests failed!'); process.exit(1); } else { console.log('\n🎉 All tests passed!'); process.exit(0); }
wonderwhy-er/devops-demo
1
DevOps demo project with GitHub Actions CI/CD pipeline
JavaScript
wonderwhy-er
Eduard Ruzga
index.html
HTML
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>DevOps Demo Project</title> <link rel="stylesheet" href="styles.css"> </head> <body> <header> <h1>🚀 DevOps Demo Project</h1> <p>Demonstrating CI/CD with GitHub Actions</p> </header> <main> <section class="hero"> <h2>Welcome to Our CI/CD Pipeline Demo</h2> <p>This project showcases automated testing, building, and deployment using GitHub Actions.</p> </section> <section class="features"> <div class="feature-card"> <h3>🔧 Continuous Integration</h3> <p>Automated testing runs on every pull request</p> </div> <div class="feature-card"> <h3>📦 Continuous Deployment</h3> <p>Automatic deployment to GitHub Pages on merge</p> </div> <div class="feature-card"> <h3>✅ Quality Checks</h3> <p>Code validation and security scanning</p> </div> </section> <section class="status"> <h3>Project Status</h3> <div id="build-status"> <span class="status-badge">Build: Passing ✅</span> <span class="status-badge">Tests: Passing ✅</span> <span class="status-badge">Deployment: Active 🟢</span> </div> </section> </main> <footer> <p>Built with ❤️ and GitHub Actions</p> <p>Last updated: <span id="last-updated"></span></p> </footer> <script src="script.js"></script> </body> </html>
wonderwhy-er/devops-demo-project
0
A demonstration project showcasing DevOps practices with GitHub Actions
JavaScript
wonderwhy-er
Eduard Ruzga
script.js
JavaScript
// DevOps Demo Project JavaScript document.addEventListener('DOMContentLoaded', function() { // Update the last updated timestamp const lastUpdatedElement = document.getElementById('last-updated'); const now = new Date(); lastUpdatedElement.textContent = now.toLocaleDateString() + ' ' + now.toLocaleTimeString(); // Add some interactive features const featureCards = document.querySelectorAll('.feature-card'); featureCards.forEach(card => { card.addEventListener('click', function() { // Add a pulse animation when clicked this.style.transform = 'scale(0.95)'; setTimeout(() => { this.style.transform = 'translateY(-5px)'; }, 150); }); }); // Simulate build status updates (for demo purposes) function updateBuildStatus() { const statusBadges = document.querySelectorAll('.status-badge'); statusBadges.forEach(badge => { badge.style.animation = 'pulse 2s infinite'; }); } // Add CSS animation for pulse effect const style = document.createElement('style'); style.textContent = ` @keyframes pulse { 0% { opacity: 1; } 50% { opacity: 0.7; } 100% { opacity: 1; } } `; document.head.appendChild(style); // Initialize the animation setTimeout(updateBuildStatus, 1000); }); // Function to validate form inputs (for future use) function validateInput(input) { if (!input || input.trim() === '') { return false; } return true; } // Function to test API connectivity (for future CI/CD demos) async function testAPI() { try { // This would be replaced with actual API calls in a real project console.log('API test passed ✅'); return true; } catch (error) { console.error('API test failed ❌:', error); return false; } } // Export functions for testing if (typeof module !== 'undefined' && module.exports) { module.exports = { validateInput, testAPI }; }
wonderwhy-er/devops-demo-project
0
A demonstration project showcasing DevOps practices with GitHub Actions
JavaScript
wonderwhy-er
Eduard Ruzga
styles.css
CSS
/* DevOps Demo Project Styles */ * { margin: 0; padding: 0; box-sizing: border-box; } body { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; line-height: 1.6; color: #333; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); min-height: 100vh; } header { text-align: center; padding: 2rem 1rem; background: rgba(255, 255, 255, 0.1); backdrop-filter: blur(10px); color: white; margin-bottom: 2rem; } header h1 { font-size: 2.5rem; margin-bottom: 0.5rem; text-shadow: 2px 2px 4px rgba(0,0,0,0.3); } header p { font-size: 1.2rem; opacity: 0.9; } main { max-width: 1200px; margin: 0 auto; padding: 0 1rem; }.hero { text-align: center; background: white; padding: 3rem 2rem; border-radius: 15px; box-shadow: 0 10px 30px rgba(0,0,0,0.2); margin-bottom: 3rem; } .hero h2 { color: #4a5568; font-size: 2rem; margin-bottom: 1rem; } .hero p { color: #718096; font-size: 1.1rem; } .features { display: grid; grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); gap: 2rem; margin-bottom: 3rem; } .feature-card { background: white; padding: 2rem; border-radius: 10px; box-shadow: 0 5px 15px rgba(0,0,0,0.1); text-align: center; transition: transform 0.3s ease; } .feature-card:hover { transform: translateY(-5px); } .feature-card h3 { color: #4a5568; font-size: 1.3rem; margin-bottom: 1rem; } .feature-card p { color: #718096; }.status { background: white; padding: 2rem; border-radius: 10px; box-shadow: 0 5px 15px rgba(0,0,0,0.1); text-align: center; margin-bottom: 3rem; } .status h3 { color: #4a5568; margin-bottom: 1.5rem; font-size: 1.5rem; } #build-status { display: flex; justify-content: center; gap: 1rem; flex-wrap: wrap; } .status-badge { background: #48bb78; color: white; padding: 0.5rem 1rem; border-radius: 25px; font-weight: bold; font-size: 0.9rem; } footer { text-align: center; padding: 2rem; color: white; opacity: 0.8; } footer p { margin-bottom: 0.5rem; } #last-updated { font-weight: bold; } @media (max-width: 768px) { header h1 { font-size: 2rem; } .hero { padding: 2rem 1rem; } .feature-card { padding: 1.5rem; } }
wonderwhy-er/devops-demo-project
0
A demonstration project showcasing DevOps practices with GitHub Actions
JavaScript
wonderwhy-er
Eduard Ruzga
tests/basic.test.js
JavaScript
// Simple test for JavaScript functions // These tests can be run in Node.js environment // Mock the browser environment for testing global.window = { fs: { readFile: jest.fn() } }; global.document = { addEventListener: jest.fn(), getElementById: jest.fn(), querySelectorAll: jest.fn(), createElement: jest.fn(), head: { appendChild: jest.fn() } }; // Import the functions from script.js const { validateInput, testAPI } = require('../script.js'); describe('DevOps Demo Project Tests', () => { test('validateInput should return false for empty input', () => { expect(validateInput('')).toBe(false); expect(validateInput(null)).toBe(false); expect(validateInput(undefined)).toBe(false); expect(validateInput(' ')).toBe(false); }); test('validateInput should return true for valid input', () => { expect(validateInput('hello')).toBe(true); expect(validateInput('test data')).toBe(true); expect(validateInput('123')).toBe(true); }); test('testAPI should return a promise', () => { const result = testAPI(); expect(result).toBeInstanceOf(Promise); }); test('testAPI should resolve to true', async () => { const result = await testAPI(); expect(result).toBe(true); }); }); // Simple HTML structure tests describe('HTML Structure Tests', () => { test('HTML should contain required elements', () => { const fs = require('fs'); const path = require('path'); // Read the HTML file const htmlPath = path.join(__dirname, '../index.html'); const htmlContent = fs.readFileSync(htmlPath, 'utf8'); // Check for required elements expect(htmlContent).toContain('DevOps Demo Project'); expect(htmlContent).toContain('Continuous Integration'); expect(htmlContent).toContain('Continuous Deployment'); expect(htmlContent).toContain('Quality Checks'); }); }); console.log('✅ Test suite loaded successfully');
wonderwhy-er/devops-demo-project
0
A demonstration project showcasing DevOps practices with GitHub Actions
JavaScript
wonderwhy-er
Eduard Ruzga
index.html
HTML
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <!-- SEO Meta Tags --> <title>AI Token Efficiency: JSON vs XML vs YAML vs Markdown - Which Format Saves More Money?</title> <meta name="description" content="Compare token efficiency between JSON, XML, YAML, and Markdown formats. Optimize your OpenAI API costs with real token analysis. See which format saves up to 48% on AI API costs."> <meta name="keywords" content="AI token efficiency, JSON vs XML vs YAML vs Markdown, OpenAI API cost optimization, token count comparison, data format efficiency, GPT tokens, tiktoken analysis, AI cost savings, markdown token cost"> <meta name="author" content="Format Token Comparison Tool"> <meta name="robots" content="index, follow"> <!-- Open Graph Meta Tags --> <meta property="og:type" content="website"> <meta property="og:title" content="AI Token Efficiency: Which Data Format Saves You More Money? JSON vs XML vs YAML"> <meta property="og:description" content="Compare token efficiency between JSON, XML, and YAML formats. Optimize your OpenAI API costs with real token analysis. See which format saves up to 48% on costs."> <meta property="og:url" content="https://wonderwhy-er.github.io/format-token-comparison/"> <meta property="og:site_name" content="AI Token Efficiency Tool"> <meta property="og:locale" content="en_US"> <!-- Twitter Card Meta Tags --> <meta name="twitter:card" content="summary_large_image"> <meta name="twitter:title" content="AI Token Efficiency: Which Data Format Saves You More Money?"> <meta name="twitter:description" content="Compare JSON, XML, and YAML token efficiency. Optimize your OpenAI API costs with real analysis."> <!-- Canonical URL --> <link rel="canonical" href="https://wonderwhy-er.github.io/format-token-comparison/"> <!-- Favicon --> <link rel="icon" type="image/svg+xml" href="data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 100 100'><text y='.9em' font-size='90'>🔢</text></svg>"> <!-- Schema.org JSON-LD --> <script type="application/ld+json"> { "@context": "https://schema.org", "@type": "WebApplication", "name": "Format Token Comparison Tool", "description": "Compare token efficiency between JSON, XML, and YAML formats for OpenAI API cost optimization", "url": "https://wonderwhy-er.github.io/format-token-comparison/", "applicationCategory": "DeveloperApplication", "operatingSystem": "Web Browser", "offers": { "@type": "Offer", "price": "0", "priceCurrency": "USD" }, "author": { "@type": "Organization", "name": "Desktop Commander" } } </script> <style> body { font-family: Arial, sans-serif; max-width: 1200px; margin: 0 auto; padding: 20px; background-color: #f5f5f5; } .container { background: white; padding: 30px; border-radius: 8px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); } h1 { color: #333; text-align: center; margin-bottom: 30px; } .status { margin-bottom: 20px; padding: 10px; border-radius: 4px; font-weight: bold; } .status.loading { background-color: #fff3e0; color: #f57c00; } .status.ready { background-color: #e8f5e8; color: #2e7d32; } .status.failed { background-color: #ffebee; color: #d32f2f; } .formats-container { display: grid; grid-template-columns: 1fr 1fr 1fr 1fr; gap: 20px; margin-bottom: 30px; } .format-section { border: 2px solid #ddd; border-radius: 8px; padding: 15px; background: #fafafa; } .format-section.active { border-color: #4CAF50; background: #f1f8e9; } .format-section h3 { margin: 0 0 15px 0; color: #333; display: flex; align-items: center; gap: 10px; } .format-icon { font-size: 20px; } .format-textarea { width: 100%; height: 300px; padding: 12px; border: 1px solid #ddd; border-radius: 4px; font-family: 'Courier New', monospace; font-size: 12px; resize: vertical; box-sizing: border-box; } .format-textarea:focus { border-color: #4CAF50; outline: none; } .format-textarea[readonly] { background-color: #f8f9fa; color: #495057; border-color: #e9ecef; cursor: default; } .format-textarea[readonly]:focus { border-color: #e9ecef; box-shadow: none; } .controls { display: flex; align-items: center; gap: 20px; margin-bottom: 30px; flex-wrap: wrap; } .control-group { display: flex; align-items: center; gap: 10px; } .control-group label { display: flex; align-items: center; gap: 8px; } .control-group input[type="checkbox"] { margin: 0; transform: scale(1.2); } label { font-weight: bold; color: #555; } select { padding: 8px; border: 2px solid #ddd; border-radius: 4px; font-size: 14px; background: white; } button { background-color: #4CAF50; color: white; padding: 12px 24px; border: none; border-radius: 4px; cursor: pointer; font-size: 16px; font-weight: bold; } button:hover { background-color: #45a049; } button:disabled { background-color: #cccccc; cursor: not-allowed; } .results { margin-top: 30px; } .results-grid { display: grid; grid-template-columns: 1fr 1fr 1fr 1fr; gap: 20px; margin-bottom: 20px; } .result-card { background: #f9f9f9; border-radius: 8px; padding: 20px; border-left: 4px solid #4CAF50; } .result-card h4 { margin: 0 0 15px 0; color: #333; display: flex; align-items: center; gap: 10px; } .metric { display: flex; justify-content: space-between; margin-bottom: 8px; } .metric-label { font-weight: bold; color: #555; } .metric-value { color: #333; } .comparison-table { margin-top: 30px; background: white; border-radius: 8px; overflow: hidden; box-shadow: 0 2px 4px rgba(0,0,0,0.1); } .comparison-table table { width: 100%; border-collapse: collapse; } .comparison-table th, .comparison-table td { padding: 12px; text-align: left; border-bottom: 1px solid #ddd; } .comparison-table th { background-color: #f5f5f5; font-weight: bold; color: #333; } .comparison-table tr:hover { background-color: #f9f9f9; } .best-value { background-color: #e8f5e8; color: #2e7d32; font-weight: bold; } .worst-value { background-color: #ffebee; color: #d32f2f; } .error { color: #d32f2f; background-color: #ffebee; padding: 10px; border-radius: 4px; border-left: 4px solid #d32f2f; margin-bottom: 20px; } .sample-data-btn { background-color: #2196F3; margin-left: 10px; } .sample-data-btn:hover { background-color: #1976D2; } .tokens-visualization { margin-top: 30px; } .tokens-visualization h3 { color: #333; margin-bottom: 20px; border-bottom: 2px solid #4CAF50; padding-bottom: 10px; } .tokens-grid { display: flex; flex-direction: column; gap: 25px; } .token-format-section { background: #f9f9f9; border-radius: 8px; padding: 20px; border-left: 4px solid #4CAF50; } .token-format-section h4 { margin: 0 0 15px 0; color: #333; display: flex; align-items: center; gap: 10px; } .tokens-container { background: white; border: 1px solid #ddd; border-radius: 4px; padding: 15px; max-height: 300px; overflow-y: auto; line-height: 1.6; } .token { display: inline-block; margin: 2px; padding: 3px 7px; background-color: #e7f3ff; border: 1px solid #b3d9ff; border-radius: 4px; font-family: 'Courier New', monospace; font-size: 12px; cursor: pointer; transition: all 0.2s ease; } .token:hover { background-color: #bbdefb; border-color: #90caf9; transform: translateY(-1px); box-shadow: 0 2px 4px rgba(0,0,0,0.1); } .token.special { background-color: #fff3e0; border-color: #ffcc02; color: #ef6c00; } .token.whitespace { background-color: #f3e5f5; border-color: #ce93d8; color: #8e24aa; } .token.number { background-color: #e8f5e8; border-color: #a5d6a7; color: #2e7d32; } .token.string { background-color: #fce4ec; border-color: #f8bbd9; color: #c2185b; } .format-toggle-controls { margin-bottom: 20px; display: flex; gap: 20px; justify-content: center; padding: 15px; background: #f5f5f5; border-radius: 8px; } .format-toggle-controls label { display: flex; align-items: center; gap: 8px; cursor: pointer; padding: 8px 16px; border-radius: 4px; transition: background-color 0.2s; } .format-toggle-controls label:hover { background-color: #e0e0e0; } .format-toggle-controls input[type="radio"] { margin: 0; transform: scale(1.2); } .savings-positive { color: #2e7d32; font-weight: bold; } .savings-none { color: #666; } .rank-1st { background: linear-gradient(135deg, #FFD700, #FFA500) !important; color: #333 !important; font-weight: bold !important; position: relative; } .rank-1st::after { content: "1st"; position: absolute; top: 2px; right: 4px; font-size: 10px; font-weight: bold; color: #333; } .rank-2nd { background: linear-gradient(135deg, #C0C0C0, #A8A8A8) !important; color: #333 !important; font-weight: bold !important; position: relative; } .rank-2nd::after { content: "2nd"; position: absolute; top: 2px; right: 4px; font-size: 10px; font-weight: bold; color: #333; } .rank-3rd { background: linear-gradient(135deg, #CD7F32, #B87333) !important; color: #fff !important; font-weight: bold !important; position: relative; } .rank-3rd::after { content: "3rd"; position: absolute; top: 2px; right: 4px; font-size: 10px; font-weight: bold; color: #fff; } .token-versions { display: grid; grid-template-columns: 1fr 1fr; gap: 20px; margin-top: 15px; } .token-version { background: white; border: 1px solid #ddd; border-radius: 4px; padding: 10px; } .token-version h5 { margin: 0 0 10px 0; color: #555; font-size: 14px; border-bottom: 1px solid #eee; padding-bottom: 5px; } .token-view-toggle { display: flex; align-items: center; gap: 10px; margin-bottom: 10px; padding: 5px; background: #f8f9fa; border-radius: 4px; } .token-view-toggle label { font-size: 12px; color: #666; cursor: pointer; display: flex; align-items: center; gap: 5px; } .token-view-toggle input[type="radio"] { margin: 0; transform: scale(0.9); } .text-view-container { background: white; border: 1px solid #ddd; border-radius: 4px; padding: 15px; max-height: 300px; overflow-y: auto; font-family: 'Courier New', monospace; font-size: 12px; line-height: 1.4; white-space: pre-wrap; color: #333; } .tokens-view-active .text-view-container { display: none; } .text-view-active .tokens-container { display: none; } .footer { margin-top: 50px; padding: 30px 20px; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; text-align: center; } .footer-content { max-width: 800px; margin: 0 auto; } .footer p { margin: 0 0 10px 0; font-size: 16px; } .footer-main { font-size: 18px !important; margin-bottom: 15px !important; text-align: center; } .footer-main strong { font-size: 20px; text-shadow: 0 1px 2px rgba(0,0,0,0.3); } .footer-main a { color: #FFD700 !important; text-decoration: none !important; border-bottom: 2px solid #FFD700 !important; font-weight: 900 !important; padding: 2px 4px; border-radius: 3px; background: rgba(255,215,0,0.1); transition: all 0.3s ease; } .footer-main a:hover { background: rgba(255,215,0,0.2); transform: translateY(-1px); box-shadow: 0 2px 4px rgba(0,0,0,0.2); } .footer-secondary { font-size: 14px !important; opacity: 0.85; text-align: center; } .footer-description { font-size: 14px !important; opacity: 0.9; margin-top: 15px !important; } .footer a { color: #fff; text-decoration: none; font-weight: bold; border-bottom: 1px solid rgba(255,255,255,0.3); transition: all 0.2s ease; } .main-tabs { display: flex; background: #f0f0f0; border-radius: 8px; margin-bottom: 30px; overflow: hidden; } .tab-button { flex: 1; padding: 15px 20px; background: #f0f0f0; border: none; cursor: pointer; font-size: 16px; font-weight: bold; transition: all 0.3s ease; border-bottom: 3px solid transparent; } .tab-button.active { background: white; border-bottom-color: #4CAF50; color: #4CAF50; } .tab-button:hover { background: #e8e8e8; } .tab-button.active:hover { background: white; } .tab-content { display: none; } .tab-content.active { display: block; } .examples-section { background: #f9f9f9; padding: 20px; border-radius: 8px; margin-bottom: 30px; border-left: 4px solid #2196F3; } .examples-section h3 { margin: 0 0 15px 0; color: #333; display: flex; align-items: center; gap: 10px; } .examples-controls { display: flex; align-items: center; gap: 15px; flex-wrap: wrap; } .cross-model-section { background: white; padding: 20px; border-radius: 8px; } .api-keys-section { background: #f9f9f9; padding: 20px; border-radius: 8px; margin-bottom: 30px; border-left: 4px solid #ff9800; } .api-keys-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 20px; margin-top: 15px; } .api-key-group { background: white; padding: 15px; border-radius: 6px; border: 1px solid #ddd; } .api-key-group label { font-size: 14px; font-weight: bold; color: #555; margin-bottom: 8px; display: block; } .api-key-input { width: 100%; padding: 8px; border: 1px solid #ddd; border-radius: 4px; font-size: 14px; box-sizing: border-box; } .model-selection-section { background: #f0f8ff; padding: 20px; border-radius: 8px; margin-bottom: 30px; border-left: 4px solid #2196f3; } .model-selection-grid { display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 20px; margin-top: 15px; } .model-group { background: white; padding: 15px; border-radius: 6px; border: 1px solid #ddd; } .model-group label { font-size: 14px; font-weight: bold; color: #555; margin-bottom: 8px; display: block; } .model-select { width: 100%; padding: 8px; border: 1px solid #ddd; border-radius: 4px; font-size: 14px; } .cross-model-results { margin-top: 30px; } .cross-model-table { width: 100%; border-collapse: collapse; background: white; border-radius: 8px; overflow: hidden; box-shadow: 0 2px 4px rgba(0,0,0,0.1); } .cross-model-table th, .cross-model-table td { padding: 12px; text-align: center; border-bottom: 1px solid #ddd; } .cross-model-table th { background-color: #f5f5f5; font-weight: bold; color: #333; } .cross-model-table tr:hover { background-color: #f9f9f9; } .provider-header { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; font-weight: bold; } .format-header { background: #e8f5e8; font-weight: bold; color: #2e7d32; } .best-provider { background-color: #e8f5e8 !important; color: #2e7d32 !important; font-weight: bold !important; } .status-indicator { display: inline-block; width: 8px; height: 8px; border-radius: 50%; margin-right: 8px; } .status-ready { background-color: #4caf50; } .status-error { background-color: #f44336; } .status-loading { background-color: #ff9800; } </style> </head> <body> <div class="container"> <h1>🔢 AI Token Efficiency: JSON vs XML vs YAML vs Markdown - Which Format Saves You More Money?</h1> <!-- Examples Section - Shared --> <div class="examples-section"> <h3><span class="format-icon">📚</span>Load Example Data</h3> <div class="examples-controls"> <label for="example-select">Choose Example:</label> <select id="example-select" onchange="loadExample()"> <option value="">Choose an example...</option> <optgroup label="Small Examples"> <option value="simple-user">👤 Simple User Profile</option> <option value="product">📦 Product Info</option> <option value="config">⚙️ Basic Config</option> <option value="api-response">🔌 API Response</option> </optgroup> <optgroup label="Medium Examples"> <option value="user-list">👥 User List</option> <option value="order">🛒 E-commerce Order</option> <option value="blog-post">📝 Blog Post</option> <option value="analytics">📊 Analytics Data</option> </optgroup> <optgroup label="Large Examples"> <option value="company-data">🏢 Company Database</option> <option value="survey-response">📋 Survey Response</option> <option value="system-logs">📋 System Logs</option> <option value="complex-config">🔧 Complex Configuration</option> </optgroup> </select> <button onclick="clearAllData()" class="sample-data-btn">🗑️ Clear All</button> </div> </div> <!-- Format Inputs - Shared --> <div class="formats-container"> <div class="format-section" id="json-section"> <h3><span class="format-icon">📄</span>JSON Format</h3> <textarea id="json-input" class="format-textarea" placeholder="Enter or paste JSON data here..." oninput="handleFormatChange('json')" ></textarea> </div> <div class="format-section" id="xml-section"> <h3><span class="format-icon">🏷️</span>XML Format</h3> <textarea id="xml-input" class="format-textarea" placeholder="Enter or paste XML data here..." oninput="handleFormatChange('xml')" ></textarea> </div> <div class="format-section" id="yaml-section"> <h3><span class="format-icon">📝</span>YAML Format</h3> <textarea id="yaml-input" class="format-textarea" placeholder="Enter or paste YAML data here..." oninput="handleFormatChange('yaml')" ></textarea> </div> <div class="format-section" id="markdown-section"> <h3><span class="format-icon">📄</span>Markdown Format</h3> <textarea id="markdown-input" class="format-textarea" placeholder="Generated markdown will appear here (read-only)..." readonly ></textarea> </div> </div> <!-- Main Tabs --> <div class="main-tabs"> <button class="tab-button active" onclick="switchTab('format-analysis')"> 📊 Format Analysis (OpenAI Models) </button> <button class="tab-button" onclick="switchTab('cross-model')"> 🤖 Cross-Model Comparison </button> </div> <!-- Tab 1: Format Analysis (OpenAI Models) --> <div id="format-analysis-tab" class="tab-content active"> <div id="library-status" class="status loading"> ⏳ Initializing js-tiktoken library... </div> <div class="controls"> <div class="control-group"> <label for="encoding-select">OpenAI Encoding:</label> <select id="encoding-select"> <option value="gpt2">GPT-2</option> <option value="r50k_base">GPT-3</option> <option value="p50k_base">Codex</option> <option value="cl100k_base">GPT-3.5/GPT-4</option> <option value="o200k_base" selected>GPT-4o</option> </select> </div> <button id="compare-btn" onclick="compareFormats()" disabled> 🔍 Compare Token Counts </button> </div> <div id="error" class="error" style="display: none;"></div> <div id="results" class="results" style="display: none;"> <div class="comparison-table"> <table> <thead> <tr> <th>Format</th> <th>Formatted Tokens</th> <th>Minified Tokens</th> <th>Formatted Chars</th> <th>Minified Chars</th> </tr> </thead> <tbody> <tr> <td><strong>📄 JSON</strong></td> <td id="table-json-tokens-formatted">-</td> <td id="table-json-tokens-minified">-</td> <td id="table-json-chars-formatted">-</td> <td id="table-json-chars-minified">-</td> </tr> <tr> <td><strong>🏷️ XML</strong></td> <td id="table-xml-tokens-formatted">-</td> <td id="table-xml-tokens-minified">-</td> <td id="table-xml-chars-formatted">-</td> <td id="table-xml-chars-minified">-</td> </tr> <tr> <td><strong>📝 YAML</strong></td> <td id="table-yaml-tokens-formatted">-</td> <td id="table-yaml-tokens-minified">-</td> <td id="table-yaml-chars-formatted">-</td> <td id="table-yaml-chars-minified">-</td> </tr> <tr> <td><strong>📄 Markdown</strong></td> <td id="table-markdown-tokens-formatted">-</td> <td id="table-markdown-tokens-minified">-</td> <td id="table-markdown-chars-formatted">-</td> <td id="table-markdown-chars-minified">-</td> </tr> </tbody> </table> </div> <!-- Token Visualization Section - MOVED TO TAB 1 --> <div class="tokens-visualization"> <h3>🔍 Token Breakdown by Format</h3> <div class="tokens-grid"> <div class="token-format-section" id="json-tokens-section" style="display: none;"> <h4><span class="format-icon">📄</span>JSON Tokens</h4> <div class="token-versions"> <div class="token-version tokens-view-active" id="json-formatted-version"> <h5>Formatted (<span id="json-formatted-count">0</span> tokens)</h5> <div class="token-view-toggle"> <label> <input type="radio" name="json-formatted-view" value="text" onchange="toggleTokenView('json', 'formatted', this.value)"> 📝 Text View </label> <label> <input type="radio" name="json-formatted-view" value="tokens" checked onchange="toggleTokenView('json', 'formatted', this.value)"> 🔍 Token View </label> </div> <div class="text-view-container" id="json-text-formatted-display"></div> <div class="tokens-container" id="json-tokens-formatted-display"></div> </div> <div class="token-version tokens-view-active" id="json-minified-version"> <h5>Minified (<span id="json-minified-count">0</span> tokens)</h5> <div class="token-view-toggle"> <label> <input type="radio" name="json-minified-view" value="text" onchange="toggleTokenView('json', 'minified', this.value)"> 📝 Text View </label> <label> <input type="radio" name="json-minified-view" value="tokens" checked onchange="toggleTokenView('json', 'minified', this.value)"> 🔍 Token View </label> </div> <div class="text-view-container" id="json-text-minified-display"></div> <div class="tokens-container" id="json-tokens-minified-display"></div> </div> </div> </div> <div class="token-format-section" id="xml-tokens-section" style="display: none;"> <h4><span class="format-icon">🏷️</span>XML Tokens</h4> <div class="token-versions"> <div class="token-version tokens-view-active" id="xml-formatted-version"> <h5>Formatted (<span id="xml-formatted-count">0</span> tokens)</h5> <div class="token-view-toggle"> <label> <input type="radio" name="xml-formatted-view" value="text" onchange="toggleTokenView('xml', 'formatted', this.value)"> 📝 Text View </label> <label> <input type="radio" name="xml-formatted-view" value="tokens" checked onchange="toggleTokenView('xml', 'formatted', this.value)"> 🔍 Token View </label> </div> <div class="text-view-container" id="xml-text-formatted-display"></div> <div class="tokens-container" id="xml-tokens-formatted-display"></div> </div> <div class="token-version tokens-view-active" id="xml-minified-version"> <h5>Minified (<span id="xml-minified-count">0</span> tokens)</h5> <div class="token-view-toggle"> <label> <input type="radio" name="xml-minified-view" value="text" onchange="toggleTokenView('xml', 'minified', this.value)"> 📝 Text View </label> <label> <input type="radio" name="xml-minified-view" value="tokens" checked onchange="toggleTokenView('xml', 'minified', this.value)"> 🔍 Token View </label> </div> <div class="text-view-container" id="xml-text-minified-display"></div> <div class="tokens-container" id="xml-tokens-minified-display"></div> </div> </div> </div> <div class="token-format-section" id="yaml-tokens-section" style="display: none;"> <h4><span class="format-icon">📝</span>YAML Tokens</h4> <div class="token-versions"> <div class="token-version tokens-view-active" id="yaml-formatted-version"> <h5>Formatted (<span id="yaml-formatted-count">0</span> tokens)</h5> <div class="token-view-toggle"> <label> <input type="radio" name="yaml-formatted-view" value="text" onchange="toggleTokenView('yaml', 'formatted', this.value)"> 📝 Text View </label> <label> <input type="radio" name="yaml-formatted-view" value="tokens" checked onchange="toggleTokenView('yaml', 'formatted', this.value)"> 🔍 Token View </label> </div> <div class="text-view-container" id="yaml-text-formatted-display"></div> <div class="tokens-container" id="yaml-tokens-formatted-display"></div> </div> <div class="token-version tokens-view-active" id="yaml-minified-version"> <h5>Minified (<span id="yaml-minified-count">0</span> tokens)</h5> <div class="token-view-toggle"> <label> <input type="radio" name="yaml-minified-view" value="text" onchange="toggleTokenView('yaml', 'minified', this.value)"> 📝 Text View </label> <label> <input type="radio" name="yaml-minified-view" value="tokens" checked onchange="toggleTokenView('yaml', 'minified', this.value)"> 🔍 Token View </label> </div> <div class="text-view-container" id="yaml-text-minified-display"></div> <div class="tokens-container" id="yaml-tokens-minified-display"></div> </div> </div> </div> <div class="token-format-section" id="markdown-tokens-section" style="display: none;"> <h4><span class="format-icon">📄</span>Markdown Tokens</h4> <div class="token-versions"> <div class="token-version tokens-view-active" id="markdown-formatted-version"> <h5>Formatted (<span id="markdown-formatted-count">0</span> tokens)</h5> <div class="token-view-toggle"> <label> <input type="radio" name="markdown-formatted-view" value="text" onchange="toggleTokenView('markdown', 'formatted', this.value)"> 📝 Text View </label> <label> <input type="radio" name="markdown-formatted-view" value="tokens" checked onchange="toggleTokenView('markdown', 'formatted', this.value)"> 🔍 Token View </label> </div> <div class="text-view-container" id="markdown-text-formatted-display"></div> <div class="tokens-container" id="markdown-tokens-formatted-display"></div> </div> <div class="token-version tokens-view-active" id="markdown-minified-version"> <h5>Minified (<span id="markdown-minified-count">0</span> tokens)</h5> <div class="token-view-toggle"> <label> <input type="radio" name="markdown-minified-view" value="text" onchange="toggleTokenView('markdown', 'minified', this.value)"> 📝 Text View </label> <label> <input type="radio" name="markdown-minified-view" value="tokens" checked onchange="toggleTokenView('markdown', 'minified', this.value)"> 🔍 Token View </label> </div> <div class="text-view-container" id="markdown-text-minified-display"></div> <div class="tokens-container" id="markdown-tokens-minified-display"></div> </div> </div> </div> </div> </div> </div> </div> <div id="error" class="error" style="display: none;"></div> <div id="results" class="results" style="display: none;"> <!-- Existing results content stays the same --> <div class="comparison-table"> <table> <thead> <tr> <th>Format</th> <th>Formatted Tokens</th> <th>Minified Tokens</th> <th>Formatted Chars</th> <th>Minified Chars</th> </tr> </thead> <tbody> <tr> <td><strong>📄 JSON</strong></td> <td id="table-json-tokens-formatted">-</td> <td id="table-json-tokens-minified">-</td> <td id="table-json-chars-formatted">-</td> <td id="table-json-chars-minified">-</td> </tr> <tr> <td><strong>🏷️ XML</strong></td> <td id="table-xml-tokens-formatted">-</td> <td id="table-xml-tokens-minified">-</td> <td id="table-xml-chars-formatted">-</td> <td id="table-xml-chars-minified">-</td> </tr> <tr> <td><strong>📝 YAML</strong></td> <td id="table-yaml-tokens-formatted">-</td> <td id="table-yaml-tokens-minified">-</td> <td id="table-yaml-chars-formatted">-</td> <td id="table-yaml-chars-minified">-</td> </tr> <tr> <td><strong>📄 Markdown</strong></td> <td id="table-markdown-tokens-formatted">-</td> <td id="table-markdown-tokens-minified">-</td> <td id="table-markdown-chars-formatted">-</td> <td id="table-markdown-chars-minified">-</td> </tr> </tbody> </table> </div> <!-- Rest of existing token visualization content... --> </div> </div> <!-- Tab 2: Cross-Model Comparison --> <div id="cross-model-tab" class="tab-content"> <div class="cross-model-section"> <!-- API Keys Section --> <div class="api-keys-section"> <h3><span class="format-icon">🔑</span>API Keys</h3> <div class="api-keys-grid" style="grid-template-columns: 1fr 1fr;"> <div class="api-key-group"> <label for="gemini-api-key-cross"> <span class="status-indicator status-ready"></span> Google Gemini API Key </label> <input type="password" id="gemini-api-key-cross" class="api-key-input" placeholder="Get from https://ai.google.dev" onchange="saveApiKey('gemini', this.value); loadGeminiModelsCross();"> </div> <div class="api-key-group"> <label for="claude-api-key-cross"> <span class="status-indicator status-ready"></span> Anthropic Claude API Key </label> <input type="password" id="claude-api-key-cross" class="api-key-input" placeholder="Get from https://console.anthropic.com" onchange="saveApiKey('claude', this.value); loadClaudeModelsCross();"> </div> </div> </div> <!-- Model Selection Section --> <div class="model-selection-section"> <h3><span class="format-icon">🤖</span>Model Selection</h3> <!-- Warning Box --> <div style="background: #fff3cd; border: 1px solid #ffeaa7; padding: 15px; border-radius: 6px; margin-bottom: 20px; border-left: 4px solid #fdcb6e;"> <strong>⚠️ Note about Model Selection:</strong><br> In testing, Google Gemini and Anthropic Claude APIs return the <strong>same token counts regardless of which model is selected</strong>. The token counting appears to use a shared tokenizer across models within each provider. Model selection may still be useful for future API updates. </div> <div class="model-selection-grid"> <div class="model-group"> <label for="openai-model-select">OpenAI Model (using tiktoken)</label> <select id="openai-model-select" class="model-select"> <option value="gpt-4o">GPT-4o</option> <option value="gpt-4o-mini">GPT-4o Mini</option> <option value="gpt-4-turbo">GPT-4 Turbo</option> <option value="gpt-3.5-turbo">GPT-3.5 Turbo</option> </select> </div> <div class="model-group"> <label for="gemini-model-select">Google Gemini Model</label> <select id="gemini-model-select" class="model-select"> <option value="">Enter API key to load models</option> </select> </div> <div class="model-group"> <label for="claude-model-select">Anthropic Claude Model</label> <select id="claude-model-select" class="model-select"> <option value="">Enter API key to load models</option> </select> </div> </div> </div> <!-- Compare Button --> <div style="text-align: center; margin: 30px 0;"> <button id="cross-model-compare-btn" onclick="runCrossModelComparison()" style="font-size: 18px; padding: 15px 30px;"> 🚀 Compare Across Models </button> </div> <!-- Cross-Model Results --> <div id="cross-model-results" class="cross-model-results" style="display: none;"> <h3>📊 Cross-Model Token Comparison Results</h3> <table class="cross-model-table"> <thead> <tr> <th rowspan="2">Format</th> <th rowspan="2">Version</th> <th colspan="3" class="provider-header">Token Counts by Provider</th> <th rowspan="2">Best Choice</th> </tr> <tr> <th>🟢 OpenAI</th> <th>🔵 Gemini</th> <th>🟠 Claude</th> </tr> </thead> <tbody> <tr> <td rowspan="2" class="format-header">📄 JSON</td> <td>Formatted</td> <td id="cross-json-formatted-openai">-</td> <td id="cross-json-formatted-gemini">-</td> <td id="cross-json-formatted-claude">-</td> <td id="cross-json-formatted-best">-</td> </tr> <tr> <td>Minified</td> <td id="cross-json-minified-openai">-</td> <td id="cross-json-minified-gemini">-</td> <td id="cross-json-minified-claude">-</td> <td id="cross-json-minified-best">-</td> </tr> <tr> <td rowspan="2" class="format-header">🏷️ XML</td> <td>Formatted</td> <td id="cross-xml-formatted-openai">-</td> <td id="cross-xml-formatted-gemini">-</td> <td id="cross-xml-formatted-claude">-</td> <td id="cross-xml-formatted-best">-</td> </tr> <tr> <td>Minified</td> <td id="cross-xml-minified-openai">-</td> <td id="cross-xml-minified-gemini">-</td> <td id="cross-xml-minified-claude">-</td> <td id="cross-xml-minified-best">-</td> </tr> <tr> <td rowspan="2" class="format-header">📝 YAML</td> <td>Formatted</td> <td id="cross-yaml-formatted-openai">-</td> <td id="cross-yaml-formatted-gemini">-</td> <td id="cross-yaml-formatted-claude">-</td> <td id="cross-yaml-formatted-best">-</td> </tr> <tr> <td>Minified</td> <td id="cross-yaml-minified-openai">-</td> <td id="cross-yaml-minified-gemini">-</td> <td id="cross-yaml-minified-claude">-</td> <td id="cross-yaml-minified-best">-</td> </tr> <tr> <td rowspan="2" class="format-header">📄 Markdown</td> <td>Formatted</td> <td id="cross-markdown-formatted-openai">-</td> <td id="cross-markdown-formatted-gemini">-</td> <td id="cross-markdown-formatted-claude">-</td> <td id="cross-markdown-formatted-best">-</td> </tr> <tr> <td>Minified</td> <td id="cross-markdown-minified-openai">-</td> <td id="cross-markdown-minified-gemini">-</td> <td id="cross-markdown-minified-claude">-</td> <td id="cross-markdown-minified-best">-</td> </tr> </tbody> </table> </div> </div> </div> <!-- Token Visualization Section --> <div class="tokens-visualization"> <h3>🔍 Token Breakdown by Format</h3> <div class="tokens-grid"> <div class="token-format-section" id="json-tokens-section" style="display: none;"> <h4><span class="format-icon">📄</span>JSON Tokens</h4> <div class="token-versions"> <div class="token-version tokens-view-active" id="json-formatted-version"> <h5>Formatted (<span id="json-formatted-count">0</span> tokens)</h5> <div class="token-view-toggle"> <label> <input type="radio" name="json-formatted-view" value="text" onchange="toggleTokenView('json', 'formatted', this.value)"> 📝 Text View </label> <label> <input type="radio" name="json-formatted-view" value="tokens" checked onchange="toggleTokenView('json', 'formatted', this.value)"> 🔍 Token View </label> </div> <div class="text-view-container" id="json-text-formatted-display"></div> <div class="tokens-container" id="json-tokens-formatted-display"></div> </div> <div class="token-version tokens-view-active" id="json-minified-version"> <h5>Minified (<span id="json-minified-count">0</span> tokens)</h5> <div class="token-view-toggle"> <label> <input type="radio" name="json-minified-view" value="text" onchange="toggleTokenView('json', 'minified', this.value)"> 📝 Text View </label> <label> <input type="radio" name="json-minified-view" value="tokens" checked onchange="toggleTokenView('json', 'minified', this.value)"> 🔍 Token View </label> </div> <div class="text-view-container" id="json-text-minified-display"></div> <div class="tokens-container" id="json-tokens-minified-display"></div> </div> </div> </div> <div class="token-format-section" id="xml-tokens-section" style="display: none;"> <h4><span class="format-icon">🏷️</span>XML Tokens</h4> <div class="token-versions"> <div class="token-version tokens-view-active" id="xml-formatted-version"> <h5>Formatted (<span id="xml-formatted-count">0</span> tokens)</h5> <div class="token-view-toggle"> <label> <input type="radio" name="xml-formatted-view" value="text" onchange="toggleTokenView('xml', 'formatted', this.value)"> 📝 Text View </label> <label> <input type="radio" name="xml-formatted-view" value="tokens" checked onchange="toggleTokenView('xml', 'formatted', this.value)"> 🔍 Token View </label> </div> <div class="text-view-container" id="xml-text-formatted-display"></div> <div class="tokens-container" id="xml-tokens-formatted-display"></div> </div> <div class="token-version tokens-view-active" id="xml-minified-version"> <h5>Minified (<span id="xml-minified-count">0</span> tokens)</h5> <div class="token-view-toggle"> <label> <input type="radio" name="xml-minified-view" value="text" onchange="toggleTokenView('xml', 'minified', this.value)"> 📝 Text View </label> <label> <input type="radio" name="xml-minified-view" value="tokens" checked onchange="toggleTokenView('xml', 'minified', this.value)"> 🔍 Token View </label> </div> <div class="text-view-container" id="xml-text-minified-display"></div> <div class="tokens-container" id="xml-tokens-minified-display"></div> </div> </div> </div> <div class="token-format-section" id="yaml-tokens-section" style="display: none;"> <h4><span class="format-icon">📝</span>YAML Tokens</h4> <div class="token-versions"> <div class="token-version tokens-view-active" id="yaml-formatted-version"> <h5>Formatted (<span id="yaml-formatted-count">0</span> tokens)</h5> <div class="token-view-toggle"> <label> <input type="radio" name="yaml-formatted-view" value="text" onchange="toggleTokenView('yaml', 'formatted', this.value)"> 📝 Text View </label> <label> <input type="radio" name="yaml-formatted-view" value="tokens" checked onchange="toggleTokenView('yaml', 'formatted', this.value)"> 🔍 Token View </label> </div> <div class="text-view-container" id="yaml-text-formatted-display"></div> <div class="tokens-container" id="yaml-tokens-formatted-display"></div> </div> <div class="token-version tokens-view-active" id="yaml-minified-version"> <h5>Minified (<span id="yaml-minified-count">0</span> tokens)</h5> <div class="token-view-toggle"> <label> <input type="radio" name="yaml-minified-view" value="text" onchange="toggleTokenView('yaml', 'minified', this.value)"> 📝 Text View </label> <label> <input type="radio" name="yaml-minified-view" value="tokens" checked onchange="toggleTokenView('yaml', 'minified', this.value)"> 🔍 Token View </label> </div> <div class="text-view-container" id="yaml-text-minified-display"></div> <div class="tokens-container" id="yaml-tokens-minified-display"></div> </div> </div> </div> <div class="token-format-section" id="markdown-tokens-section" style="display: none;"> <h4><span class="format-icon">📄</span>Markdown Tokens</h4> <div class="token-versions"> <div class="token-version tokens-view-active" id="markdown-formatted-version"> <h5>Formatted (<span id="markdown-formatted-count">0</span> tokens)</h5> <div class="token-view-toggle"> <label> <input type="radio" name="markdown-formatted-view" value="text" onchange="toggleTokenView('markdown', 'formatted', this.value)"> 📝 Text View </label> <label> <input type="radio" name="markdown-formatted-view" value="tokens" checked onchange="toggleTokenView('markdown', 'formatted', this.value)"> 🔍 Token View </label> </div> <div class="text-view-container" id="markdown-text-formatted-display"></div> <div class="tokens-container" id="markdown-tokens-formatted-display"></div> </div> <div class="token-version tokens-view-active" id="markdown-minified-version"> <h5>Minified (<span id="markdown-minified-count">0</span> tokens)</h5> <div class="token-view-toggle"> <label> <input type="radio" name="markdown-minified-view" value="text" onchange="toggleTokenView('markdown', 'minified', this.value)"> 📝 Text View </label> <label> <input type="radio" name="markdown-minified-view" value="tokens" checked onchange="toggleTokenView('markdown', 'minified', this.value)"> 🔍 Token View </label> </div> <div class="text-view-container" id="markdown-text-minified-display"></div> <div class="tokens-container" id="markdown-tokens-minified-display"></div> </div> </div> </div> </div> </div> </div> </div> <!-- Footer --> <footer class="footer"> <div class="footer-content"> <p class="footer-main"> ⚡ <strong>Built with <a href="https://desktopcommander.app/" target="_blank" rel="noopener noreferrer">Desktop Commander</a></strong> - The ultimate AI-powered development environment </p> <p class="footer-secondary"> 🔢 Powered by <a href="https://github.com/dqbd/tiktoken" target="_blank" rel="noopener noreferrer">js-tiktoken</a> | 📊 Compare JSON, XML & YAML token efficiency | 💻 <a href="https://github.com/wonderwhy-er/format-token-comparison" target="_blank" rel="noopener noreferrer">Source Code on GitHub</a> </p> <p class="footer-description"> Optimize your AI API costs by choosing the most token-efficient data format and provider combination for your applications. </p> </div> </footer> <!-- Load js-yaml library for YAML parsing --> <script src="https://cdn.jsdelivr.net/npm/js-yaml@4.1.0/dist/js-yaml.min.js"></script> <script type="module"> // Import Tiktoken from ESM let Tiktoken; let isConverting = false; // Prevent infinite conversion loops try { // Try importing from esm.sh const module = await import('https://esm.sh/js-tiktoken@1.0.21/lite'); Tiktoken = module.Tiktoken; console.log('Successfully loaded js-tiktoken from esm.sh'); } catch (error) { console.error('Failed to load from esm.sh:', error); try { // Fallback to jsdelivr const module = await import('https://cdn.jsdelivr.net/npm/js-tiktoken@1.0.21/+esm'); Tiktoken = module.Tiktoken; console.log('Successfully loaded js-tiktoken from jsdelivr'); } catch (error2) { console.error('Failed to load from jsdelivr:', error2); updateStatus('failed', '❌ Failed to load js-tiktoken library. Please check your internet connection.'); throw error2; } } // Update status function updateStatus(type, message) { const statusDiv = document.getElementById('library-status'); statusDiv.className = `status ${type}`; statusDiv.textContent = message; } // Cache for loaded encodings const encodingCache = {}; // Encoding to CDN URL mapping const encodingUrls = { 'gpt2': 'https://tiktoken.pages.dev/js/gpt2.json', 'r50k_base': 'https://tiktoken.pages.dev/js/r50k_base.json', 'p50k_base': 'https://tiktoken.pages.dev/js/p50k_base.json', 'cl100k_base': 'https://tiktoken.pages.dev/js/cl100k_base.json', 'o200k_base': 'https://tiktoken.pages.dev/js/o200k_base.json' }; async function loadEncoding(encodingName) { if (encodingCache[encodingName]) { return encodingCache[encodingName]; } try { console.log(`Loading encoding: ${encodingName}`); const response = await fetch(encodingUrls[encodingName]); if (!response.ok) { throw new Error(`Failed to load encoding: ${response.status} ${response.statusText}`); } const encodingData = await response.json(); encodingCache[encodingName] = encodingData; return encodingData; } catch (error) { console.error('Error loading encoding:', error); throw error; } } // Format conversion functions function jsonToXml(obj, rootName = 'root') { function objectToXml(obj, indent = ' ') { let xml = ''; for (const key in obj) { if (obj.hasOwnProperty(key)) { const value = obj[key]; if (Array.isArray(value)) { for (const item of value) { xml += `${indent}<${key}>${typeof item === 'object' ? '\n' + objectToXml(item, indent + ' ') + indent : item}</${key}>\n`; } } else if (typeof value === 'object' && value !== null) { xml += `${indent}<${key}>\n${objectToXml(value, indent + ' ')}${indent}</${key}>\n`; } else { xml += `${indent}<${key}>${value}</${key}>\n`; } } } return xml; } return `<?xml version="1.0" encoding="UTF-8"?>\n<${rootName}>\n${objectToXml(obj)}</${rootName}>`; } function xmlToJson(xmlString) { // Simple XML to JSON converter (basic implementation) const parser = new DOMParser(); const xmlDoc = parser.parseFromString(xmlString, "text/xml"); function xmlNodeToObject(node) { if (node.nodeType === Node.TEXT_NODE) { return node.nodeValue.trim(); } const obj = {}; // Handle attributes if (node.attributes && node.attributes.length > 0) { obj['@attributes'] = {}; for (let i = 0; i < node.attributes.length; i++) { obj['@attributes'][node.attributes[i].name] = node.attributes[i].value; } } // Handle child nodes const children = {}; for (let i = 0; i < node.childNodes.length; i++) { const child = node.childNodes[i]; if (child.nodeType === Node.ELEMENT_NODE) { const childObj = xmlNodeToObject(child); if (children[child.nodeName]) { if (!Array.isArray(children[child.nodeName])) { children[child.nodeName] = [children[child.nodeName]]; } children[child.nodeName].push(childObj); } else { children[child.nodeName] = childObj; } } else if (child.nodeType === Node.TEXT_NODE && child.nodeValue.trim()) { if (!obj['#text']) obj['#text'] = ''; obj['#text'] += child.nodeValue.trim(); } } return Object.keys(children).length > 0 ? { ...obj, ...children } : (obj['#text'] || obj); } return xmlNodeToObject(xmlDoc.documentElement); } // Minification functions - separate from conversion function minifyJson(jsonString) { try { const parsed = JSON.parse(jsonString); return JSON.stringify(parsed); } catch (e) { return jsonString; } } function minifyXml(xmlString) { return xmlString .replace(/>\s+</g, '><') // Remove whitespace between tags .replace(/\n\s*/g, '') // Remove newlines and indentation .replace(/\s+/g, ' ') // Collapse multiple spaces to single space .trim(); } function minifyYaml(yamlString) { try { const parsed = jsyaml.load(yamlString); return jsyaml.dump(parsed, { indent: 2, lineWidth: -1, flowLevel: 2 // Use flow style for arrays/objects when compact }).trim(); } catch (e) { return yamlString; } } // Markdown conversion functions function dataToMarkdown(obj, title = 'Data') { function objectToMarkdown(data, level = 1) { let markdown = ''; const headingPrefix = '#'.repeat(Math.min(level, 6)) + ' '; if (Array.isArray(data)) { data.forEach(item => { if (typeof item === 'object' && item !== null) { markdown += objectToMarkdown(item, level); } else { markdown += `- ${item}\n`; } }); } else if (typeof data === 'object' && data !== null) { Object.entries(data).forEach(([key, value]) => { const formattedKey = key.replace(/([A-Z])/g, ' $1').replace(/^./, str => str.toUpperCase()); if (Array.isArray(value)) { markdown += `\n${headingPrefix}${formattedKey}\n\n`; value.forEach(item => { if (typeof item === 'object' && item !== null) { markdown += objectToMarkdown(item, level + 1); } else { markdown += `- ${item}\n`; } }); markdown += '\n'; } else if (typeof value === 'object' && value !== null) { markdown += `\n${headingPrefix}${formattedKey}\n\n`; markdown += objectToMarkdown(value, level + 1); } else { markdown += `**${formattedKey}:** ${value} \n`; } }); } return markdown; } return `# ${title}\n\n${objectToMarkdown(obj)}`.trim(); } function minifyMarkdown(markdownString) { return markdownString .replace(/\n\s*\n\s*\n/g, '\n\n') // Remove excessive line breaks .replace(/\s*\n\s*/g, '\n') // Normalize line endings .replace(/\s+/g, ' ') // Collapse multiple spaces .trim(); } // Remove the toggleMinification function since we don't need it anymore // Handle format changes and conversions window.handleFormatChange = function(changedFormat) { if (isConverting) return; isConverting = true; try { const jsonInput = document.getElementById('json-input'); const xmlInput = document.getElementById('xml-input'); const yamlInput = document.getElementById('yaml-input'); const markdownInput = document.getElementById('markdown-input'); // Clear active states document.querySelectorAll('.format-section').forEach(section => { section.classList.remove('active'); }); // Mark the changed format as active document.getElementById(`${changedFormat}-section`).classList.add('active'); let data; if (changedFormat === 'json') { const jsonText = jsonInput.value.trim(); if (!jsonText) { xmlInput.value = ''; yamlInput.value = ''; markdownInput.value = ''; return; } try { data = JSON.parse(jsonText); xmlInput.value = jsonToXml(data); yamlInput.value = jsyaml.dump(data, { indent: 2 }); markdownInput.value = dataToMarkdown(data, 'Data Overview'); } catch (e) { // Invalid JSON, clear other formats xmlInput.value = ''; yamlInput.value = ''; markdownInput.value = ''; } } else if (changedFormat === 'xml') { const xmlText = xmlInput.value.trim(); if (!xmlText) { jsonInput.value = ''; yamlInput.value = ''; markdownInput.value = ''; return; } try { data = xmlToJson(xmlText); jsonInput.value = JSON.stringify(data, null, 2); yamlInput.value = jsyaml.dump(data, { indent: 2 }); markdownInput.value = dataToMarkdown(data, 'Data Overview'); } catch (e) { // Invalid XML, clear other formats jsonInput.value = ''; yamlInput.value = ''; markdownInput.value = ''; } } else if (changedFormat === 'yaml') { const yamlText = yamlInput.value.trim(); if (!yamlText) { jsonInput.value = ''; xmlInput.value = ''; markdownInput.value = ''; return; } try { data = jsyaml.load(yamlText); jsonInput.value = JSON.stringify(data, null, 2); xmlInput.value = jsonToXml(data); markdownInput.value = dataToMarkdown(data, 'Data Overview'); } catch (e) { // Invalid YAML, clear other formats jsonInput.value = ''; xmlInput.value = ''; markdownInput.value = ''; } } } catch (error) { console.error('Conversion error:', error); } finally { isConverting = false; } } // Compare formats function window.compareFormats = async function() { const compareBtn = document.getElementById('compare-btn'); const resultsDiv = document.getElementById('results'); const errorDiv = document.getElementById('error'); const jsonText = document.getElementById('json-input').value.trim(); const xmlText = document.getElementById('xml-input').value.trim(); const yamlText = document.getElementById('yaml-input').value.trim(); const markdownText = document.getElementById('markdown-input').value.trim(); if (!jsonText && !xmlText && !yamlText) { showError('Please enter data in JSON, XML, or YAML format.'); return; } compareBtn.disabled = true; compareBtn.textContent = '⏳ Analyzing...'; errorDiv.style.display = 'none'; try { const selectedEncoding = document.getElementById('encoding-select').value; const encodingData = await loadEncoding(selectedEncoding); const encoder = new Tiktoken(encodingData); const results = {}; // Analyze each format - calculate both formatted and minified versions if (jsonText) { const minifiedText = minifyJson(jsonText); // Formatted version const formattedTokens = encoder.encode(jsonText); const formattedDecodedTokens = formattedTokens.map(token => encoder.decode([token])); // Minified version const minifiedTokens = encoder.encode(minifiedText); const minifiedDecodedTokens = minifiedTokens.map(token => encoder.decode([token])); results.json = { formatted: { tokens: formattedTokens.length, chars: jsonText.length, text: jsonText, tokenIds: formattedTokens, decodedTokens: formattedDecodedTokens }, minified: { tokens: minifiedTokens.length, chars: minifiedText.length, text: minifiedText, tokenIds: minifiedTokens, decodedTokens: minifiedDecodedTokens }, savings: formattedTokens.length - minifiedTokens.length }; } if (xmlText) { const minifiedText = minifyXml(xmlText); // Formatted version const formattedTokens = encoder.encode(xmlText); const formattedDecodedTokens = formattedTokens.map(token => encoder.decode([token])); // Minified version const minifiedTokens = encoder.encode(minifiedText); const minifiedDecodedTokens = minifiedTokens.map(token => encoder.decode([token])); results.xml = { formatted: { tokens: formattedTokens.length, chars: xmlText.length, text: xmlText, tokenIds: formattedTokens, decodedTokens: formattedDecodedTokens }, minified: { tokens: minifiedTokens.length, chars: minifiedText.length, text: minifiedText, tokenIds: minifiedTokens, decodedTokens: minifiedDecodedTokens }, savings: formattedTokens.length - minifiedTokens.length }; } if (yamlText) { const minifiedText = minifyYaml(yamlText); // Formatted version const formattedTokens = encoder.encode(yamlText); const formattedDecodedTokens = formattedTokens.map(token => encoder.decode([token])); // Minified version const minifiedTokens = encoder.encode(minifiedText); const minifiedDecodedTokens = minifiedTokens.map(token => encoder.decode([token])); results.yaml = { formatted: { tokens: formattedTokens.length, chars: yamlText.length, text: yamlText, tokenIds: formattedTokens, decodedTokens: formattedDecodedTokens }, minified: { tokens: minifiedTokens.length, chars: minifiedText.length, text: minifiedText, tokenIds: minifiedTokens, decodedTokens: minifiedDecodedTokens }, savings: formattedTokens.length - minifiedTokens.length }; } if (markdownText) { const minifiedText = minifyMarkdown(markdownText); // Formatted version const formattedTokens = encoder.encode(markdownText); const formattedDecodedTokens = formattedTokens.map(token => encoder.decode([token])); // Minified version const minifiedTokens = encoder.encode(minifiedText); const minifiedDecodedTokens = minifiedTokens.map(token => encoder.decode([token])); results.markdown = { formatted: { tokens: formattedTokens.length, chars: markdownText.length, text: markdownText, tokenIds: formattedTokens, decodedTokens: formattedDecodedTokens }, minified: { tokens: minifiedTokens.length, chars: minifiedText.length, text: minifiedText, tokenIds: minifiedTokens, decodedTokens: minifiedDecodedTokens }, savings: formattedTokens.length - minifiedTokens.length }; } displayResults(results); resultsDiv.style.display = 'block'; } catch (error) { console.error('Comparison error:', error); showError(`Error: ${error.message}`); } finally { compareBtn.disabled = false; compareBtn.textContent = '🔍 Compare Token Counts'; } } function displayResults(results) { // Update table rows only Object.keys(results).forEach(format => { const result = results[format]; // Update table rows document.getElementById(`table-${format}-tokens-formatted`).textContent = result.formatted.tokens; document.getElementById(`table-${format}-tokens-minified`).textContent = result.minified.tokens; document.getElementById(`table-${format}-chars-formatted`).textContent = result.formatted.chars; document.getElementById(`table-${format}-chars-minified`).textContent = result.minified.chars; }); // Create ranking system based on token counts (lower is better) const formats = Object.keys(results); const allTokenCounts = []; // Collect all token counts (both formatted and minified) with their cell IDs formats.forEach(format => { const result = results[format]; allTokenCounts.push({ count: result.formatted.tokens, cellId: `table-${format}-tokens-formatted`, format: format, type: 'formatted' }); allTokenCounts.push({ count: result.minified.tokens, cellId: `table-${format}-tokens-minified`, format: format, type: 'minified' }); }); // Sort by token count (ascending - lower is better) allTokenCounts.sort((a, b) => a.count - b.count); // Clear all existing ranking classes allTokenCounts.forEach(item => { const cell = document.getElementById(item.cellId); cell.classList.remove('rank-1st', 'rank-2nd', 'rank-3rd'); }); // Assign rankings to top 3 performers (lowest token counts) if (allTokenCounts.length >= 1) { const firstCell = document.getElementById(allTokenCounts[0].cellId); firstCell.classList.add('rank-1st'); } if (allTokenCounts.length >= 2) { const secondCell = document.getElementById(allTokenCounts[1].cellId); secondCell.classList.add('rank-2nd'); } if (allTokenCounts.length >= 3) { const thirdCell = document.getElementById(allTokenCounts[2].cellId); thirdCell.classList.add('rank-3rd'); } // Store results globally for token visualization window.currentResults = results; // Display both token visualizations side by side displayAllTokenVisualizations(); } function displayAllTokenVisualizations() { if (!window.currentResults) return; Object.keys(window.currentResults).forEach(format => { displayTokenVisualizationBoth(format, window.currentResults[format]); }); } function displayTokenVisualizationBoth(format, result) { const tokenSection = document.getElementById(`${format}-tokens-section`); // Show the section tokenSection.style.display = 'block'; // Update formatted version - both text and token views const formattedContainer = document.getElementById(`${format}-tokens-formatted-display`); const formattedTextContainer = document.getElementById(`${format}-text-formatted-display`); const formattedCount = document.getElementById(`${format}-formatted-count`); formattedCount.textContent = result.formatted.tokens; // Populate text view formattedTextContainer.textContent = result.formatted.text; // Populate token view formattedContainer.innerHTML = ''; result.formatted.decodedTokens.forEach((tokenText, index) => { const tokenSpan = createTokenElement(tokenText, index, result.formatted.tokenIds[index]); formattedContainer.appendChild(tokenSpan); }); // Update minified version - both text and token views const minifiedContainer = document.getElementById(`${format}-tokens-minified-display`); const minifiedTextContainer = document.getElementById(`${format}-text-minified-display`); const minifiedCount = document.getElementById(`${format}-minified-count`); minifiedCount.textContent = result.minified.tokens; // Populate text view minifiedTextContainer.textContent = result.minified.text; // Populate token view minifiedContainer.innerHTML = ''; result.minified.decodedTokens.forEach((tokenText, index) => { const tokenSpan = createTokenElement(tokenText, index, result.minified.tokenIds[index]); minifiedContainer.appendChild(tokenSpan); }); } function createTokenElement(tokenText, index, tokenId) { const tokenSpan = document.createElement('span'); tokenSpan.className = 'token'; // Add special classes based on token content if (tokenText.match(/^\s+$/)) { tokenSpan.classList.add('whitespace'); } else if (tokenText.match(/^[\d\.]+$/)) { tokenSpan.classList.add('number'); } else if (tokenText.match(/^["'].*["']$/)) { tokenSpan.classList.add('string'); } else if (tokenText.match(/^[{}[\](),:;]$/)) { tokenSpan.classList.add('special'); } // Display the token text, replacing whitespace with visible characters let displayText = tokenText .replace(/\n/g, '\\n') .replace(/\t/g, '\\t') .replace(/\r/g, '\\r') .replace(/ /g, '·'); // Use middle dot for spaces // If the token is empty or only whitespace, show the actual whitespace character if (tokenText === ' ') { displayText = 'SPACE'; } else if (tokenText === '\n') { displayText = 'NEWLINE'; } else if (tokenText === '\t') { displayText = 'TAB'; } else if (displayText === '') { displayText = 'EMPTY'; } tokenSpan.textContent = displayText; tokenSpan.title = `Token ${index + 1}: "${tokenText}" (ID: ${tokenId})`; return tokenSpan; } // Toggle between text view and token view window.toggleTokenView = function(format, version, viewType) { const versionContainer = document.getElementById(`${format}-${version}-version`); if (viewType === 'text') { versionContainer.classList.remove('tokens-view-active'); versionContainer.classList.add('text-view-active'); } else { versionContainer.classList.remove('text-view-active'); versionContainer.classList.add('tokens-view-active'); } } // Load sample data window.loadSampleData = function() { const sampleData = { users: [ { id: 1, name: "John Doe", email: "john@example.com", age: 30, address: { street: "123 Main St", city: "New York", zipCode: "10001" }, hobbies: ["reading", "swimming", "coding"], active: true }, { id: 2, name: "Jane Smith", email: "jane@example.com", age: 25, address: { street: "456 Oak Ave", city: "Los Angeles", zipCode: "90210" }, hobbies: ["painting", "hiking", "photography"], active: false } ], metadata: { totalUsers: 2, lastUpdated: "2024-08-19T10:30:00Z", version: "1.0" } }; document.getElementById('json-input').value = JSON.stringify(sampleData, null, 2); handleFormatChange('json'); } // Example data sets const examples = { "simple-user": { id: 123, name: "Alice Johnson", email: "alice@example.com", active: true }, "product": { id: "PROD-001", name: "Wireless Headphones", price: 99.99, category: "Electronics", inStock: true, tags: ["wireless", "bluetooth", "music"] }, "config": { appName: "MyApp", version: "2.1.0", debug: false, maxConnections: 100, timeout: 30 }, "api-response": { status: "success", code: 200, message: "Request processed successfully", data: { userId: 456, sessionId: "sess_abc123", timestamp: "2024-08-19T15:30:00Z" } }, "user-list": { users: [ { id: 1, name: "Emma Davis", email: "emma@company.com", role: "developer", department: "Engineering", skills: ["JavaScript", "Python", "React"], joinDate: "2023-01-15", salary: 85000, active: true }, { id: 2, name: "Michael Wilson", email: "michael@company.com", role: "designer", department: "Creative", skills: ["Figma", "Photoshop", "UI/UX"], joinDate: "2022-09-08", salary: 75000, active: true }, { id: 3, name: "Sarah Chen", email: "sarah@company.com", role: "manager", department: "Product", skills: ["Strategy", "Analytics", "Leadership"], joinDate: "2021-03-22", salary: 95000, active: false } ], pagination: { page: 1, limit: 3, total: 156, hasNext: true } }, "order": { orderId: "ORD-2024-08-001", customerId: "CUST-789", orderDate: "2024-08-19T14:25:00Z", status: "processing", customer: { name: "Robert Miller", email: "robert@email.com", phone: "+1-555-0123", address: { street: "789 Commerce Blvd", city: "Chicago", state: "IL", zipCode: "60601", country: "USA" } }, items: [ { productId: "PROD-101", name: "Gaming Laptop", quantity: 1, unitPrice: 1299.99, total: 1299.99 }, { productId: "PROD-205", name: "Wireless Mouse", quantity: 2, unitPrice: 29.99, total: 59.98 } ], shipping: { method: "express", cost: 15.99, estimatedDelivery: "2024-08-21" }, payment: { method: "credit_card", cardLast4: "4567", transactionId: "TXN-ABC123" }, totals: { subtotal: 1359.97, tax: 108.80, shipping: 15.99, total: 1484.76 } }, "blog-post": { id: "post-456", title: "Understanding Modern Web Development", slug: "understanding-modern-web-development", author: { id: 12, name: "Tech Writer", email: "writer@blog.com", bio: "Passionate about sharing knowledge" }, content: "Modern web development has evolved significantly over the past decade. From simple HTML pages to complex single-page applications, the landscape continues to change rapidly. Frameworks like React, Vue, and Angular have revolutionized how we build user interfaces, while Node.js has enabled JavaScript to run on the server side. The rise of TypeScript has brought static typing to JavaScript, improving code quality and developer experience. Cloud computing and serverless architectures are reshaping how we deploy and scale applications.", tags: ["web-development", "javascript", "react", "technology"], category: "Technology", publishedAt: "2024-08-19T10:00:00Z", updatedAt: "2024-08-19T10:15:00Z", status: "published", featured: true, readTime: 5, views: 1250, likes: 89, comments: [ { id: 1, author: "Dev Reader", content: "Great insights! Really helpful for beginners.", createdAt: "2024-08-19T11:30:00Z" }, { id: 2, author: "Code Enthusiast", content: "Looking forward to more posts like this.", createdAt: "2024-08-19T12:45:00Z" } ] }, "analytics": { reportId: "RPT-2024-08-19", dateRange: { start: "2024-08-01", end: "2024-08-19" }, website: { domain: "example.com", totalPageViews: 45623, uniqueVisitors: 12890, bounceRate: 0.34, avgSessionDuration: 180 }, topPages: [ { path: "/", views: 8934, uniqueViews: 7123, avgTimeOnPage: 145 }, { path: "/products", views: 5678, uniqueViews: 4890, avgTimeOnPage: 210 }, { path: "/about", views: 3456, uniqueViews: 2987, avgTimeOnPage: 95 } ], trafficSources: { organic: 0.45, direct: 0.28, social: 0.15, referral: 0.08, email: 0.04 }, devices: { desktop: 0.52, mobile: 0.41, tablet: 0.07 }, conversions: { goalCompletions: 234, conversionRate: 0.018, revenue: 12450.75 } }, "company-data": { company: { id: "COMP-001", name: "TechCorp Industries", founded: "2015-03-15", headquarters: { address: "123 Innovation Drive", city: "San Francisco", state: "CA", zipCode: "94105", country: "USA" }, industry: "Software Technology", employees: 2847, revenue: 145000000, publiclyTraded: true, stockSymbol: "TECH" }, departments: [ { id: "DEPT-ENG", name: "Engineering", head: "John Smith", employeeCount: 845, budget: 45000000, teams: [ { name: "Frontend", members: 156, lead: "Alice Johnson", technologies: ["React", "Vue", "TypeScript", "Next.js"] }, { name: "Backend", members: 203, lead: "Bob Wilson", technologies: ["Node.js", "Python", "Go", "PostgreSQL"] }, { name: "DevOps", members: 89, lead: "Carol Davis", technologies: ["AWS", "Docker", "Kubernetes", "Terraform"] }, { name: "Mobile", members: 124, lead: "David Brown", technologies: ["React Native", "Swift", "Kotlin", "Flutter"] } ] }, { id: "DEPT-SALES", name: "Sales & Marketing", head: "Emma Martinez", employeeCount: 456, budget: 25000000, regions: [ { name: "North America", revenue: 89000000, salesReps: 178 }, { name: "Europe", revenue: 34000000, salesReps: 134 }, { name: "Asia Pacific", revenue: 22000000, salesReps: 98 } ] } ], products: [ { id: "PROD-CLOUD", name: "CloudSync Pro", category: "SaaS Platform", price: 99.99, customers: 12567, features: [ "Real-time synchronization", "Advanced security", "API integrations", "Custom workflows", "Analytics dashboard" ] }, { id: "PROD-MOBILE", name: "MobileFirst SDK", category: "Developer Tools", price: 299.99, customers: 3456, features: [ "Cross-platform support", "Performance monitoring", "Crash reporting", "A/B testing", "Push notifications" ] } ], financials: { currentQuarter: { revenue: 38500000, expenses: 31200000, profit: 7300000, growthRate: 0.15 }, previousQuarter: { revenue: 33500000, expenses: 29800000, profit: 3700000, growthRate: 0.12 } } }, "survey-response": { surveyId: "SURV-2024-SATISFACTION", title: "Customer Satisfaction Survey", respondent: { id: "RESP-789", demographicData: { age: 32, gender: "female", location: "Denver, CO", income: "75000-100000", education: "bachelor" }, customerSince: "2022-04-15", totalPurchases: 847.50 }, responses: [ { questionId: "Q1", question: "How satisfied are you with our product?", type: "rating", answer: 4, scale: "1-5" }, { questionId: "Q2", question: "Which features do you use most often?", type: "multiple_choice", answer: ["dashboard", "reports", "integrations"], options: ["dashboard", "reports", "integrations", "mobile_app", "api"] }, { questionId: "Q3", question: "What improvements would you like to see?", type: "open_text", answer: "I would love to see better mobile experience and more customization options for the dashboard. The current interface is good but could be more intuitive for new users." }, { questionId: "Q4", question: "How likely are you to recommend us?", type: "nps", answer: 8, scale: "0-10" }, { questionId: "Q5", question: "Rate the importance of each feature", type: "matrix", answer: { "ease_of_use": 5, "performance": 4, "customer_support": 4, "price": 3, "features": 5 } } ], completedAt: "2024-08-19T16:45:00Z", timeSpent: 420, ipAddress: "192.168.1.100", userAgent: "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)", referralSource: "email_campaign" }, "system-logs": { logSession: "LOG-2024-08-19-001", system: { hostname: "web-server-01", environment: "production", version: "2.4.1", region: "us-west-2" }, timeRange: { start: "2024-08-19T14:00:00Z", end: "2024-08-19T15:00:00Z" }, entries: [ { timestamp: "2024-08-19T14:00:15Z", level: "INFO", service: "auth-service", message: "User authentication successful", userId: "user_12345", sessionId: "sess_abcdef", requestId: "req_001", duration: 45 }, { timestamp: "2024-08-19T14:01:22Z", level: "WARN", service: "payment-service", message: "Payment processing delayed due to high volume", orderId: "ord_67890", amount: 299.99, requestId: "req_002", retryCount: 2 }, { timestamp: "2024-08-19T14:03:45Z", level: "ERROR", service: "notification-service", message: "Failed to send email notification", error: "SMTP connection timeout", recipient: "user@example.com", requestId: "req_003", stackTrace: "Error: SMTP timeout\n at SMTPConnection.timeout\n at Socket.emit" }, { timestamp: "2024-08-19T14:05:30Z", level: "INFO", service: "api-gateway", message: "Rate limit applied", clientId: "client_xyz", endpoint: "/api/v1/users", rateLimit: "100 requests/minute", currentCount: 101 } ], metrics: { totalRequests: 15670, errorRate: 0.024, avgResponseTime: 156, p95ResponseTime: 450, uptime: 0.9995 }, alerts: [ { id: "ALERT-001", severity: "medium", message: "CPU usage above 80%", triggeredAt: "2024-08-19T14:15:00Z", resolved: false } ] }, "complex-config": { application: { name: "enterprise-platform", version: "3.2.1", environment: "production", cluster: "cluster-alpha" }, database: { primary: { host: "db-primary.internal", port: 5432, name: "production_db", ssl: true, connectionPool: { min: 5, max: 50, acquireTimeoutMillis: 60000, idleTimeoutMillis: 30000 } }, replicas: [ { host: "db-replica-1.internal", port: 5432, readOnly: true, weight: 0.6 }, { host: "db-replica-2.internal", port: 5432, readOnly: true, weight: 0.4 } ], redis: { host: "redis.internal", port: 6379, ttl: 3600, maxConnections: 100 } }, api: { baseUrl: "https://api.company.com", version: "v2", rateLimit: { requests: 1000, windowMs: 60000, skipSuccessfulRequests: false }, auth: { type: "jwt", secret: "${JWT_SECRET}", expiresIn: "24h", issuer: "api.company.com" }, cors: { origins: [ "https://app.company.com", "https://admin.company.com" ], methods: ["GET", "POST", "PUT", "DELETE"], credentials: true } }, monitoring: { logging: { level: "info", format: "json", destinations: [ { type: "file", path: "/var/log/app.log", maxSize: "100MB", maxFiles: 10 }, { type: "elasticsearch", host: "logs.internal", index: "application-logs" } ] }, metrics: { enabled: true, interval: 30, exporters: ["prometheus", "datadog"], customMetrics: [ "business_transactions_total", "user_registrations_total", "revenue_generated" ] }, healthChecks: [ { name: "database", type: "tcp", target: "db-primary.internal:5432", interval: 30, timeout: 5 }, { name: "external_api", type: "http", target: "https://external-service.com/health", interval: 60, timeout: 10 } ] }, security: { encryption: { algorithm: "AES-256-GCM", keyRotation: "30d" }, firewall: { allowedIPs: [ "10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16" ], blockedCountries: ["XX", "YY"] }, audit: { enabled: true, retentionDays: 365, sensitiveFields: ["password", "ssn", "credit_card"] } }, features: { experimentalFeatures: { newDashboard: { enabled: false, rolloutPercentage: 0 }, aiAssistant: { enabled: true, rolloutPercentage: 25, targetGroups: ["beta_users", "premium_users"] } }, integrations: { salesforce: { enabled: true, apiVersion: "v54.0", syncInterval: "15m" }, slack: { enabled: true, webhook: "${SLACK_WEBHOOK}", channels: ["#alerts", "#deployments"] } } } } }; // Load example function window.loadExample = function(exampleKey) { const selectElement = document.getElementById('example-select'); // If called from dropdown, get the selected value if (!exampleKey) { exampleKey = selectElement.value; } if (!exampleKey) return; const exampleData = examples[exampleKey]; if (exampleData) { document.getElementById('json-input').value = JSON.stringify(exampleData, null, 2); handleFormatChange('json'); // Don't reset the dropdown - keep the selection visible // selectElement.value = ''; // Auto-run comparison after loading example setTimeout(() => { compareFormats(); }, 500); } } // Clear all data function window.clearAllData = function() { document.getElementById('json-input').value = ''; document.getElementById('xml-input').value = ''; document.getElementById('yaml-input').value = ''; document.getElementById('results').style.display = 'none'; // Clear active states document.querySelectorAll('.format-section').forEach(section => { section.classList.remove('active'); }); } function showError(message) { const errorDiv = document.getElementById('error'); errorDiv.textContent = message; errorDiv.style.display = 'block'; } // Enable the button and update status when library is loaded if (Tiktoken) { updateStatus('ready', '✅ Ready to compare formats!'); document.getElementById('compare-btn').disabled = false; // Auto-load a sample example on page load setTimeout(() => { const selectElement = document.getElementById('example-select'); selectElement.value = 'user-list'; // Set the dropdown to show the selection loadExample('user-list'); // Load the user list example by default }, 1000); } // Tab switching functionality window.switchTab = function(tabName) { // Update tab buttons document.querySelectorAll('.tab-button').forEach(btn => { btn.classList.remove('active'); }); event.target.classList.add('active'); // Update tab content document.querySelectorAll('.tab-content').forEach(content => { content.classList.remove('active'); }); document.getElementById(tabName + '-tab').classList.add('active'); // If switching to cross-model tab, check if we need to load models if (tabName === 'cross-model') { setTimeout(() => { // Load models if API keys are already saved if (crossModelApiKeys.gemini) { loadGeminiModelsCross(); } if (crossModelApiKeys.claude) { loadClaudeModelsCross(); } }, 100); } } // Cross-model API key management const crossModelApiKeys = { gemini: '', claude: '' }; window.saveApiKey = function(provider, apiKey) { crossModelApiKeys[provider] = apiKey; localStorage.setItem(`cross_model_${provider}_key`, apiKey); } function loadSavedApiKeys() { Object.keys(crossModelApiKeys).forEach(provider => { const saved = localStorage.getItem(`cross_model_${provider}_key`); if (saved) { crossModelApiKeys[provider] = saved; const inputId = provider === 'gemini' ? 'gemini-api-key-cross' : 'claude-api-key-cross'; const inputElement = document.getElementById(inputId); if (inputElement) { inputElement.value = saved; } } }); } // Load Gemini models for cross-model tab window.loadGeminiModelsCross = async function() { const apiKey = crossModelApiKeys.gemini; const modelSelect = document.getElementById('gemini-model-select'); if (!apiKey) { modelSelect.innerHTML = '<option value="">Enter API key first</option>'; return; } modelSelect.innerHTML = '<option value="">Loading models...</option>'; try { const response = await fetch(`https://generativelanguage.googleapis.com/v1beta/models?key=${apiKey}`); if (!response.ok) { throw new Error(`Failed to load models: ${response.status}`); } const data = await response.json(); const models = data.models || []; modelSelect.innerHTML = ''; const supportedModels = models.filter(model => { return model.supportedGenerationMethods && model.supportedGenerationMethods.includes('generateContent') && model.name && !model.name.includes('embedding'); }); if (supportedModels.length === 0) { modelSelect.innerHTML = '<option value="">No compatible models found</option>'; return; } supportedModels .sort((a, b) => { const nameA = a.displayName || a.name.split('/').pop(); const nameB = b.displayName || b.name.split('/').pop(); return nameB.localeCompare(nameA); }) .forEach(model => { const modelId = model.name.split('/').pop(); const displayName = model.displayName || modelId; const option = document.createElement('option'); option.value = modelId; option.textContent = displayName; modelSelect.appendChild(option); }); } catch (error) { console.error('Error loading Gemini models:', error); modelSelect.innerHTML = '<option value="">Error loading models</option>'; } } // Load Claude models for cross-model tab window.loadClaudeModelsCross = async function() { const apiKey = crossModelApiKeys.claude; const modelSelect = document.getElementById('claude-model-select'); if (!apiKey) { modelSelect.innerHTML = '<option value="">Enter API key first</option>'; return; } modelSelect.innerHTML = '<option value="">Loading models...</option>'; try { const response = await fetch('https://api.anthropic.com/v1/models', { method: 'GET', headers: { 'x-api-key': apiKey, 'anthropic-version': '2023-06-01', 'anthropic-dangerous-direct-browser-access': 'true' } }); if (!response.ok) { throw new Error(`Failed to load models: ${response.status}`); } const data = await response.json(); const models = data.data || []; modelSelect.innerHTML = ''; if (models.length === 0) { modelSelect.innerHTML = '<option value="">No models found</option>'; return; } const modelGroups = {}; models.forEach(model => { let family = 'Other'; if (model.id.includes('claude-4')) { family = 'Claude 4 (Latest)'; } else if (model.id.includes('claude-3-5')) { family = 'Claude 3.5'; } else if (model.id.includes('claude-3')) { family = 'Claude 3'; } if (!modelGroups[family]) { modelGroups[family] = []; } modelGroups[family].push(model); }); const groupOrder = ['Claude 4 (Latest)', 'Claude 3.5', 'Claude 3', 'Other']; groupOrder.forEach(groupName => { if (modelGroups[groupName]) { const group = document.createElement('optgroup'); group.label = groupName; modelGroups[groupName] .sort((a, b) => new Date(b.created_at) - new Date(a.created_at)) .forEach(model => { const option = document.createElement('option'); option.value = model.id; option.textContent = model.display_name || model.id; group.appendChild(option); }); modelSelect.appendChild(group); } }); } catch (error) { console.error('Error loading Claude models:', error); modelSelect.innerHTML = ''; const fallbackModels = [ { id: 'claude-3-5-sonnet-20241022', name: 'Claude 3.5 Sonnet (Fallback)' }, { id: 'claude-3-5-haiku-20241022', name: 'Claude 3.5 Haiku (Fallback)' } ]; fallbackModels.forEach(model => { const option = document.createElement('option'); option.value = model.id; option.textContent = model.name; modelSelect.appendChild(option); }); } } // Cross-model comparison function window.runCrossModelComparison = async function() { const compareBtn = document.getElementById('cross-model-compare-btn'); const resultsDiv = document.getElementById('cross-model-results'); const jsonText = document.getElementById('json-input').value.trim(); const xmlText = document.getElementById('xml-input').value.trim(); const yamlText = document.getElementById('yaml-input').value.trim(); const markdownText = document.getElementById('markdown-input').value.trim(); if (!jsonText && !xmlText && !yamlText) { alert('Please load some example data first using the examples dropdown at the top.'); return; } compareBtn.disabled = true; compareBtn.textContent = '⏳ Comparing across models...'; try { const results = {}; // Get selected models const openaiModel = document.getElementById('openai-model-select').value; const geminiModel = document.getElementById('gemini-model-select').value; const claudeModel = document.getElementById('claude-model-select').value; // Count tokens for each format and model const formats = [ { name: 'json', formatted: jsonText, minified: minifyJson(jsonText) }, { name: 'xml', formatted: xmlText, minified: minifyXml(xmlText) }, { name: 'yaml', formatted: yamlText, minified: minifyYaml(yamlText) }, { name: 'markdown', formatted: markdownText, minified: minifyMarkdown(markdownText) } ].filter(format => format.formatted); for (const format of formats) { results[format.name] = {}; // OpenAI (using tiktoken) if (openaiModel) { const encodingData = await loadEncoding('o200k_base'); // GPT-4o encoding const encoder = new Tiktoken(encodingData); results[format.name].openai = { formatted: encoder.encode(format.formatted).length, minified: encoder.encode(format.minified).length }; } // Gemini if (geminiModel && crossModelApiKeys.gemini) { try { const formattedResp = await fetch(`https://generativelanguage.googleapis.com/v1beta/models/${geminiModel}:countTokens?key=${crossModelApiKeys.gemini}`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ contents: [{ parts: [{ text: format.formatted }] }] }) }); const formattedData = await formattedResp.json(); const minifiedResp = await fetch(`https://generativelanguage.googleapis.com/v1beta/models/${geminiModel}:countTokens?key=${crossModelApiKeys.gemini}`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ contents: [{ parts: [{ text: format.minified }] }] }) }); const minifiedData = await minifiedResp.json(); results[format.name].gemini = { formatted: formattedData.totalTokens || 0, minified: minifiedData.totalTokens || 0 }; } catch (error) { console.error('Gemini error:', error); results[format.name].gemini = { formatted: 'Error', minified: 'Error' }; } } // Claude if (claudeModel && crossModelApiKeys.claude) { try { const formattedResp = await fetch('https://api.anthropic.com/v1/messages/count_tokens', { method: 'POST', headers: { 'Content-Type': 'application/json', 'x-api-key': crossModelApiKeys.claude, 'anthropic-version': '2023-06-01', 'anthropic-dangerous-direct-browser-access': 'true' }, body: JSON.stringify({ model: claudeModel, messages: [{ role: 'user', content: format.formatted }] }) }); const formattedData = await formattedResp.json(); const minifiedResp = await fetch('https://api.anthropic.com/v1/messages/count_tokens', { method: 'POST', headers: { 'Content-Type': 'application/json', 'x-api-key': crossModelApiKeys.claude, 'anthropic-version': '2023-06-01', 'anthropic-dangerous-direct-browser-access': 'true' }, body: JSON.stringify({ model: claudeModel, messages: [{ role: 'user', content: format.minified }] }) }); const minifiedData = await minifiedResp.json(); results[format.name].claude = { formatted: formattedData.input_tokens || 0, minified: minifiedData.input_tokens || 0 }; } catch (error) { console.error('Claude error:', error); results[format.name].claude = { formatted: 'Error', minified: 'Error' }; } } } // Display results displayCrossModelResults(results); resultsDiv.style.display = 'block'; } catch (error) { console.error('Cross-model comparison error:', error); alert(`Error: ${error.message}`); } finally { compareBtn.disabled = false; compareBtn.textContent = '🚀 Compare Across Models'; } } function displayCrossModelResults(results) { Object.keys(results).forEach(format => { const result = results[format]; ['formatted', 'minified'].forEach(version => { const openaiCell = document.getElementById(`cross-${format}-${version}-openai`); const geminiCell = document.getElementById(`cross-${format}-${version}-gemini`); const claudeCell = document.getElementById(`cross-${format}-${version}-claude`); const bestCell = document.getElementById(`cross-${format}-${version}-best`); // Clear previous styling [openaiCell, geminiCell, claudeCell].forEach(cell => { cell.classList.remove('best-provider'); }); const openaiTokens = result.openai ? result.openai[version] : '-'; const geminiTokens = result.gemini ? result.gemini[version] : '-'; const claudeTokens = result.claude ? result.claude[version] : '-'; openaiCell.textContent = openaiTokens; geminiCell.textContent = geminiTokens; claudeCell.textContent = claudeTokens; // Find best (lowest) token count const counts = []; if (typeof openaiTokens === 'number') counts.push({ provider: 'OpenAI', count: openaiTokens, cell: openaiCell }); if (typeof geminiTokens === 'number') counts.push({ provider: 'Gemini', count: geminiTokens, cell: geminiCell }); if (typeof claudeTokens === 'number') counts.push({ provider: 'Claude', count: claudeTokens, cell: claudeCell }); if (counts.length > 0) { const best = counts.reduce((min, current) => current.count < min.count ? current : min); best.cell.classList.add('best-provider'); bestCell.textContent = `${best.provider} (${best.count})`; bestCell.className = 'best-provider'; } else { bestCell.textContent = '-'; } }); }); } // Initialize cross-model functionality setTimeout(() => { loadSavedApiKeys(); }, 500); </script> </body> </html>
wonderwhy-er/format-token-comparison
3
🔢 AI Token Efficiency: Compare JSON, XML, and YAML formats for OpenAI API cost optimization
HTML
wonderwhy-er
Eduard Ruzga
css/style.css
CSS
/* Main styles for GitHub Pages DevOps Demo */ :root { --primary-color: #0366d6; --secondary-color: #24292e; --light-color: #f6f8fa; --text-color: #24292e; --link-color: #0366d6; --border-color: #e1e4e8; } * { box-sizing: border-box; margin: 0; padding: 0; } body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif; line-height: 1.6; color: var(--text-color); background-color: var(--light-color); } .container { max-width: 960px; margin: 0 auto; padding: 2rem; } header { text-align: center; margin-bottom: 3rem; padding-bottom: 2rem; border-bottom: 1px solid var(--border-color); } header h1 { color: var(--primary-color); margin-bottom: 1rem; } main { margin-bottom: 3rem; } section { margin-bottom: 2rem; padding: 1.5rem; background-color: #fff; border-radius: 5px; box-shadow: 0 2px 5px rgb(0 0 0 / 10%); } h2 { color: var(--secondary-color); margin-bottom: 1rem; } ul { list-style-position: inside; margin-left: 1rem; } li { margin-bottom: 0.5rem; } .status { background-color: #f0fff4; border-left: 4px solid #48bb78; } footer { text-align: center; padding-top: 2rem; border-top: 1px solid var(--border-color); font-size: 0.9rem; color: #6a737d; }
wonderwhy-er/github-pages-devops-demo
0
HTML
wonderwhy-er
Eduard Ruzga
index.html
HTML
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>GitHub Pages DevOps Demo</title> <link rel="stylesheet" href="css/style.css"> </head> <body> <div class="container"> <header> <h1>GitHub Pages with GitHub Actions CI/CD</h1> <p>A simple demonstration of DevOps practices using GitHub Actions</p> </header> <main> <section class="features"> <h2>Features Demonstrated:</h2> <ul> <li>Automatic deployment to GitHub Pages</li> <li>HTML validation on pull requests</li> <li>CSS linting on pull requests</li> <li>Link checking</li> <li>Build status badges</li> </ul> </section> <section class="status"> <h2>Current Build Status:</h2> <p>Last deployed: <span id="deploy-date">Loading...</span></p> <p>Build version: <span id="build-version">v1.0.0</span></p> </section> </main> <footer> <p>Created as a DevOps demonstration using GitHub Actions</p> <p>Built during a lightning talk at the DevOps and AI Meetup in Riga in 2025, using <a href="https://desktopcommander.app/" target="_blank">Desktop Commander</a></p> <p id="current-year"></p> </footer> </div> <script src="js/main.js"></script> </body> </html>
wonderwhy-er/github-pages-devops-demo
0
HTML
wonderwhy-er
Eduard Ruzga
js/main.js
JavaScript
// Main JavaScript for GitHub Pages DevOps Demo document.addEventListener('DOMContentLoaded', () => { // Set the current year in the footer const yearElement = document.getElementById('current-year'); if (yearElement) { yearElement.textContent = `© ${new Date().getFullYear()}`; } // Set the current date as the deploy date const deployDateElement = document.getElementById('deploy-date'); if (deployDateElement) { const options = { year: 'numeric', month: 'long', day: 'numeric', hour: '2-digit', minute: '2-digit' }; deployDateElement.textContent = new Date().toLocaleDateString('en-US', options); } // Log a message to the console console.log('GitHub Pages DevOps Demo loaded successfully!'); });
wonderwhy-er/github-pages-devops-demo
0
HTML
wonderwhy-er
Eduard Ruzga
data/methodology.html
HTML
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Methodology - LLM Value Comparison</title> <style> @import url('https://fonts.googleapis.com/css2?family=JetBrains+Mono:wght@300;400;500;600;700&display=swap'); body { background: #0a0a0f; color: #e0e0e0; font-family: 'JetBrains Mono', monospace; line-height: 1.6; padding: 3rem 1rem; max-width: 800px; margin: 0 auto; } h1 { color: #00ff88; border-bottom: 2px solid #00ff88; padding-bottom: 0.5rem; } h2 { color: #ffc800; margin-top: 2rem; } .card { background: rgba(255,255,255,0.03); border: 1px solid rgba(255,255,255,0.1); border-radius: 12px; padding: 1.5rem; margin: 1.5rem 0; } code { background: #1a1a2e; color: #ff6b6b; padding: 0.2rem 0.4rem; border-radius: 4px; } a { color: #88f; text-decoration: none; } a:hover { text-decoration: underline; } .back-link { display: inline-block; margin-bottom: 2rem; color: #00ff88; } table { width: 100%; border-collapse: collapse; margin: 1rem 0; font-size: 0.85rem; } th { background: rgba(0,255,136,0.1); text-align: left; padding: 0.75rem; color: #00ff88; } td { padding: 0.75rem; border-bottom: 1px solid rgba(255,255,255,0.05); } </style> </head> <body> <a href="../index.html" class="back-link">← Back to Calculator</a> <h1>📐 Subscription Estimation Methodology</h1> <p>Because AI providers (OpenAI, Anthropic, Google) do not publish exact daily token budgets for their "unlimited" or "message-capped" plans, this project uses an empirical estimation model based on 2025/2026 research.</p> <div class="card"> <h2>1. The "Turn" Standard (6,400 Tokens)</h2> <p>We standardize a single "message" or "turn" at <strong>6,400 tokens</strong>.</p> <ul> <li><strong>Source:</strong> <a href="https://a16z.com/state-of-ai/" target="_blank">OpenRouter 2025 State of AI Report</a></li> <li><strong>Why:</strong> Based on a study of 100 trillion real-world tokens, the average prompt length has quadrupled to ~6,000 tokens while completions average ~400 tokens. This reflects modern "context-heavy" usage like coding and agentic workflows.</li> </ul> </div> <div class="card"> <h2>2. Capacity Scaling (The 10x Rule)</h2> <p>We use a <strong>10x capacity multiplier</strong> to estimate "Unlimited" or "Pro" tiers compared to "Plus" tiers.</p> <ul> <li><strong>Logic:</strong> OpenAI provides exactly 10x capacity for high-compute features in the Pro tier ($200) compared to Plus ($20).</li> <li><strong>Evidence:</strong> Plus users get 25 Deep Research queries/mo, while Pro users get 250 queries/mo.</li> </ul> </div> <h2>3. Daily Token Limits</h2> <table> <thead> <tr> <th>Subscription</th> <th>Price</th> <th>Daily Tokens</th> <th>Derivation</th> </tr> </thead> <tbody> <tr> <td><strong>ChatGPT Plus</strong></td> <td>$20</td> <td>8,192,000</td> <td>160 msgs/3hr × 8 windows × 6,400 tok</td> </tr> <tr> <td><strong>ChatGPT Pro</strong></td> <td>$200</td> <td>81,920,000</td> <td>Plus Daily Tokens × 10 (Linear scaling)</td> </tr> <tr> <td><strong>Claude Pro</strong></td> <td>$20</td> <td>640,000</td> <td>100 msgs/day × 6,400 tok</td> </tr> <tr> <td><strong>Gemini Advanced</strong></td> <td>$20</td> <td>640,000</td> <td>100 msgs/day × 6,400 tok</td> </tr> <tr> <td><strong>Claude Max 5×</strong></td> <td>$100</td> <td>3,200,000</td> <td>640,000 (Pro base) × 5</td> </tr> <tr> <td><strong>Claude Max 20×</strong></td> <td>$200</td> <td>12,800,000</td> <td>640,000 (Pro base) × 20</td> </tr> </tbody> </table> <div class="card"> <h2>4. Example: Framework Desktop vs ChatGPT</h2> <p>Based on current inputs:</p> <ul> <li><strong>Framework Desktop (128GB):</strong> ~$3,170 USD.</li> <li><strong>GPT-OSS 120B local:</strong> ~33 tok/s on the Framework Desktop (community benchmark).</li> <li><strong>Local value:</strong> ~525K quality tokens per dollar (16h/day, 3 years).</li> <li><strong>ChatGPT Plus/Pro:</strong> ~11M quality tokens per dollar (same period).</li> </ul> <p>That is roughly a ~20x gap in favor of subscription today. If cloud pricing changes or local inference improves, the numbers will shift. That is why the timeline view exists: it is designed to show how value evolves over time.</p> <p>The purpose of this project is simple: compare how much intelligence you get per dollar across local, API, and subscription options.</p> </div> <footer style="margin-top: 4rem; font-size: 0.7rem; color: #666; text-align: center;"> Last Updated: February 2, 2026 • LLM Value Comparison Project </footer> </body> </html>
wonderwhy-er/llm-value-comparison
1
Interactive calculator comparing local LLM vs cloud subscription value
HTML
wonderwhy-er
Eduard Ruzga
index.html
HTML
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>LLM Value Comparison: Local vs Subscription vs API</title> <script src="https://cdn.jsdelivr.net/npm/chart.js"></script> <script src="https://cdn.jsdelivr.net/npm/chartjs-adapter-date-fns"></script> <style> @import url('https://fonts.googleapis.com/css2?family=JetBrains+Mono:wght@300;400;500;600;700&display=swap'); * { box-sizing: border-box; margin: 0; padding: 0; } body { min-height: 100vh; background: linear-gradient(135deg, #0a0a0f 0%, #1a1a2e 50%, #0f0f1a 100%); color: #e0e0e0; font-family: 'JetBrains Mono', monospace; padding: 2rem; line-height: 1.6; } h1 { text-align: center; font-size: 2rem; margin-bottom: 0.5rem; background: linear-gradient(90deg, #00ff88, #7c3aed, #ff6b6b); -webkit-background-clip: text; -webkit-text-fill-color: transparent; } .subtitle { text-align: center; color: #888; margin-bottom: 1.5rem; font-size: 0.9rem; } .container { max-width: 1400px; margin: 0 auto; } /* Tabs */ .tabs { display: flex; gap: 0; margin-bottom: 1.5rem; border-bottom: 1px solid rgba(255,255,255,0.1); } .tab { padding: 0.75rem 1.5rem; cursor: pointer; color: #888; border-bottom: 2px solid transparent; transition: all 0.2s; } .tab:hover { color: #e0e0e0; } .tab.active { color: #00ff88; border-bottom-color: #00ff88; } .tab-content { display: none; } .tab-content.active { display: block; } .oss-banner { background: linear-gradient(90deg, rgba(0,255,136,0.1), rgba(124,58,237,0.1)); border: 1px solid rgba(255,255,255,0.1); border-radius: 8px; padding: 0.75rem 1.5rem; margin-bottom: 1.5rem; text-align: center; font-size: 0.8rem; } .oss-banner a { color: #00ff88; } .warning-box { background: rgba(255,100,100,0.15); border: 1px solid rgba(255,100,100,0.4); border-radius: 8px; padding: 0.75rem 1rem; margin-bottom: 1.5rem; font-size: 0.75rem; color: #ffaaaa; } .warning-box strong { color: #ff6b6b; } .global-settings { background: rgba(255, 200, 0, 0.1); border: 1px solid rgba(255, 200, 0, 0.3); border-radius: 12px; padding: 1rem 1.5rem; margin-bottom: 2rem; } .global-settings h3 { color: #ffc800; margin-bottom: 0.75rem; font-size: 0.9rem; } .settings-row { display: flex; gap: 1.5rem; flex-wrap: wrap; align-items: flex-end; } .setting-group label { display: block; font-size: 0.7rem; color: #999; margin-bottom: 0.25rem; } .global-settings select, .global-settings input { background: rgba(0,0,0,0.3); border: 1px solid rgba(255, 200, 0, 0.4); color: #ffc800; padding: 0.4rem 0.8rem; border-radius: 6px; font-family: inherit; font-size: 0.85rem; } .chart-section { background: rgba(255, 255, 255, 0.03); border: 1px solid rgba(255, 255, 255, 0.08); border-radius: 16px; padding: 1.5rem; margin-bottom: 2rem; } .chart-section h2 { text-align: center; margin-bottom: 1rem; } .chart-controls { display: flex; gap: 1rem; justify-content: center; margin-bottom: 1rem; flex-wrap: wrap; } .chart-controls select { background: rgba(255,255,255,0.05); border: 1px solid rgba(255,255,255,0.15); color: #e0e0e0; padding: 0.4rem 0.8rem; border-radius: 6px; font-family: inherit; font-size: 0.85rem; } .chart-wrapper { position: relative; height: 500px; } /* Data Tables */ .data-table-section { margin-bottom: 2rem; } .data-table-section h3 { color: #00ff88; margin-bottom: 1rem; font-size: 1rem; display: flex; align-items: center; gap: 0.5rem; } .data-table { width: 100%; border-collapse: collapse; font-size: 0.75rem; background: rgba(255,255,255,0.02); border-radius: 8px; overflow: hidden; } .data-table th { background: rgba(255,255,255,0.05); padding: 0.75rem; text-align: left; color: #888; font-weight: 500; border-bottom: 1px solid rgba(255,255,255,0.1); } .data-table td { padding: 0.6rem 0.75rem; border-bottom: 1px solid rgba(255,255,255,0.03); } .data-table tr:hover td { background: rgba(255,255,255,0.03); } .data-table a { color: #88f; text-decoration: none; } .data-table a:hover { text-decoration: underline; } .confidence-low { color: #ff6b6b; } .confidence-medium { color: #ffc800; } .confidence-high { color: #00ff88; } .edit-link { font-size: 0.65rem; color: #666; margin-left: 0.5rem; } .edit-link:hover { color: #00ff88; } /* Calculator explanation cards */ .calc-grid { display: grid; grid-template-columns: repeat(3, 1fr); gap: 1rem; margin-bottom: 1.5rem; } @media (max-width: 900px) { .calc-grid { grid-template-columns: 1fr; } } .calc-card { background: rgba(255,255,255,0.03); border: 1px solid rgba(255,255,255,0.08); border-radius: 10px; padding: 1rem; } .calc-card h4 { margin-bottom: 0.75rem; font-size: 0.85rem; } .calc-card.local { border-color: rgba(0,255,136,0.3); } .calc-card.local h4 { color: #00ff88; } .calc-card.api { border-color: rgba(255,107,107,0.3); } .calc-card.api h4 { color: #ff6b6b; } .calc-card.sub { border-color: rgba(124,58,237,0.3); } .calc-card.sub h4 { color: #7c3aed; } .calc-card select { width: 100%; background: rgba(0,0,0,0.3); border: 1px solid rgba(255,255,255,0.1); color: #e0e0e0; padding: 0.4rem; border-radius: 4px; font-size: 0.75rem; margin-bottom: 0.75rem; } .calc-steps { font-size: 0.7rem; line-height: 1.8; } .calc-step { color: #888; } .calc-step .num { color: #ffc800; } .calc-step .result { color: #fff; } .calc-final { margin-top: 0.75rem; padding-top: 0.75rem; border-top: 1px solid rgba(255,255,255,0.1); text-align: center; } .calc-final .value { font-size: 1.25rem; font-weight: 700; } .calc-final .label { font-size: 0.6rem; color: #666; } /* Results ranking */ .results-section { margin-top: 1.5rem; } .results-section h3 { margin-bottom: 1rem; font-size: 0.9rem; color: #888; } .calc-row { position: relative; } .calc-row[data-tooltip]:hover::after { content: attr(data-tooltip); position: absolute; left: 0; top: 100%; margin-top: 6px; z-index: 10; max-width: 520px; padding: 0.6rem 0.75rem; border-radius: 8px; background: rgba(10, 10, 15, 0.95); border: 1px solid rgba(255,255,255,0.15); color: #cfcfcf; font-size: 0.65rem; line-height: 1.5; white-space: pre-line; box-shadow: 0 8px 20px rgba(0,0,0,0.5); } .calc-row[data-tooltip]:hover::before { content: ''; position: absolute; left: 16px; top: 100%; margin-top: -4px; border-width: 6px; border-style: solid; border-color: transparent transparent rgba(10, 10, 15, 0.95) transparent; z-index: 11; } </style> </head> <body> <div class="container"> <h1>⚡ LLM Value Comparison</h1> <p class="subtitle">Quality-Adjusted Tokens per Dollar — Local vs Subscription vs API</p> <div class="oss-banner"> 📖 <strong>Open Source (MIT)</strong> — <a href="https://github.com/wonderwhy-er/llm-value-comparison" target="_blank">GitHub</a> | Contribute model data via Pull Request </div> <!-- TABS --> <div class="tabs"> <div class="tab active" data-tab="calculator">📊 Calculator</div> <div class="tab" data-tab="chart">📈 Timeline Chart</div> <div class="tab" data-tab="data">📋 Raw Data</div> </div> <!-- TAB: CALCULATOR --> <div id="tab-calculator" class="tab-content active"> <div class="warning-box"> <strong>⚠️ Subscription data is estimated!</strong> Providers don't publish exact token limits. <a href="data/methodology.html" style="color:#ff6b6b; text-decoration:underline;" target="_blank">Learn how we estimate these limits.</a> </div> <div class="global-settings"> <h3>⚙️ Settings</h3> <div class="settings-row"> <div class="setting-group"> <label>Hardware (for Local)</label> <select id="hardware"></select> </div> <div class="setting-group"> <label>Hours/day (Local)</label> <input type="number" id="hoursPerDay" value="16" min="1" max="24" style="width: 70px;"> </div> <div class="setting-group"> <label>Comparison Period</label> <select id="periodYears"> <option value="1">1 Year</option> <option value="2">2 Years</option> <option value="3" selected>3 Years</option> <option value="5">5 Years</option> </select> </div> <div class="setting-group"> <label>Quality Benchmark</label> <select id="benchmark"></select> </div> </div> </div> <!-- Methodology explanation --> <div style="background:rgba(255,255,255,0.02);border:1px solid rgba(255,255,255,0.08);border-radius:10px;padding:1rem;margin-bottom:1.5rem;font-size:0.75rem;line-height:1.7"> <h3 style="color:#ffc800;margin-bottom:0.75rem;font-size:0.85rem">📐 Methodology: Quality-Adjusted Tokens per Dollar</h3> <p style="color:#aaa;margin-bottom:1rem">Not all tokens are equal — a token from a smarter model is worth more than one from a weaker model. We calculate <strong style="color:#fff">"quality tokens"</strong> by multiplying raw token counts by model quality (from benchmarks). Then we divide by cost to get <strong style="color:#fff">quality-adjusted tokens per dollar</strong> — a fair way to compare completely different pricing models.</p> <div style="display:grid;grid-template-columns:repeat(3,1fr);gap:1rem;margin-top:1rem"> <div style="border-left:2px solid #00ff88;padding-left:0.75rem"> <div style="color:#00ff88;font-weight:600;margin-bottom:0.5rem">🖥️ Local</div> <div style="color:#888;font-size:0.65rem"> Take tokens/second → calculate tokens/day you can generate → multiply by years of usage → multiply by quality score → divide by one-time hardware cost. </div> </div> <div style="border-left:2px solid #7c3aed;padding-left:0.75rem"> <div style="color:#7c3aed;font-weight:600;margin-bottom:0.5rem">💳 Subscription</div> <div style="color:#888;font-size:0.65rem"> Estimate average tokens/day from usage limits → multiply by years → multiply by quality score → divide by total subscription cost over that period. </div> </div> <div style="border-left:2px solid #ff6b6b;padding-left:0.75rem"> <div style="color:#ff6b6b;font-weight:600;margin-bottom:0.5rem">🔌 API</div> <div style="color:#888;font-size:0.65rem"> Calculate weighted average price (75% input + 25% output, typical usage ratio) → tokens per dollar (1M ÷ weighted price) → multiply by quality score. </div> </div> </div> <p style="color:#666;margin-top:1rem;font-size:0.65rem"><strong>Quality scores:</strong> Percentage benchmarks (Aider, LiveBench) use the score directly. ELO rankings are normalized to 0-100% where 1000 ELO = 0% and 1500 ELO = 100%.</p> <p style="color:#666;margin-top:0.5rem;font-size:0.65rem"><strong>API pricing:</strong> Uses weighted average of input (75%) and output (25%) prices to reflect typical usage patterns where prompts are longer than responses.</p> </div> <!-- Calculation explanation cards --> <div class="calc-grid"> <div class="calc-card local"> <h4>🖥️ Local</h4> <select id="calcLocal"></select> <div class="calc-steps" id="calcLocalSteps"></div> <div class="calc-final"> <div class="value" style="color:#00ff88" id="calcLocalValue">-</div> <div class="label">quality-adjusted tokens per $</div> </div> </div> <div class="calc-card sub"> <h4>💳 Subscription ⚠️</h4> <select id="calcSub"></select> <div class="calc-steps" id="calcSubSteps"></div> <div class="calc-final"> <div class="value" style="color:#7c3aed" id="calcSubValue">-</div> <div class="label">quality-adjusted tokens per $</div> </div> </div> <div class="calc-card api"> <h4>🔌 API</h4> <select id="calcApi"></select> <div class="calc-steps" id="calcApiSteps"></div> <div class="calc-final"> <div class="value" style="color:#ff6b6b" id="calcApiValue">-</div> <div class="label">quality-adjusted tokens per $</div> </div> </div> </div> <div class="results-section"> <h3>📊 All Options Ranked</h3> <div id="calculatorContent">Loading data...</div> </div> </div> <!-- TAB: CHART --> <div id="tab-chart" class="tab-content"> <div class="chart-section"> <h2>Value Over Time by Provider</h2> <div class="chart-controls"> <select id="chartBenchmark"></select> <select id="chartType"> <option value="all">All Types</option> <option value="api">API Only</option> <option value="local">Local Only</option> <option value="subscription">Subscription Only</option> </select> <select id="chartProvider"> <option value="all">All Providers</option> </select> </div> <div class="chart-wrapper"> <canvas id="valueChart"></canvas> </div> </div> </div> <!-- TAB: DATA --> <div id="tab-data" class="tab-content"> <div class="data-table-section"> <h3>🤖 Models <a href="https://github.com/wonderwhy-er/llm-value-comparison/tree/main/data/models" class="edit-link" target="_blank">[Edit on GitHub]</a></h3> <table class="data-table" id="tableModels"> <thead><tr><th>Model</th><th>Provider</th><th>Release</th><th>Model Card</th></tr></thead> <tbody></tbody> </table> </div> <div class="data-table-section"> <h3>📊 Benchmark Scores <a href="https://github.com/wonderwhy-er/llm-value-comparison/tree/main/data/models" class="edit-link" target="_blank">[Edit on GitHub]</a></h3> <table class="data-table" id="tableBenchmarks"> <thead><tr><th>Model</th><th>Arena ELO</th><th>Aider</th><th>LiveBench</th><th>MMLU</th></tr></thead> <tbody></tbody> </table> </div> <div class="data-table-section"> <h3>🔌 API Pricing <a href="https://github.com/wonderwhy-er/llm-value-comparison/tree/main/data/models" class="edit-link" target="_blank">[Edit on GitHub]</a></h3> <table class="data-table" id="tableApi"> <thead><tr><th>Model</th><th>Input $/M</th><th>Output $/M</th><th>Source</th></tr></thead> <tbody></tbody> </table> </div> <div class="data-table-section"> <h3>🖥️ Local Performance <a href="https://github.com/wonderwhy-er/llm-value-comparison/tree/main/data/models" class="edit-link" target="_blank">[Edit on GitHub]</a></h3> <table class="data-table" id="tableLocal"> <thead><tr><th>Model</th><th>Hardware</th><th>Tok/s</th><th>Quant</th><th>VRAM</th><th>Source</th></tr></thead> <tbody></tbody> </table> </div> <div class="data-table-section"> <h3>💳 Subscriptions <span style="color:#ff6b6b">(⚠️ Estimated)</span> <a href="https://github.com/wonderwhy-er/llm-value-comparison/tree/main/data/models" class="edit-link" target="_blank">[Edit on GitHub]</a></h3> <table class="data-table" id="tableSubs"> <thead><tr><th>Model</th><th>Subscription</th><th>$/mo</th><th>Tok/day</th><th>Confidence</th><th>Notes</th><th>Source</th></tr></thead> <tbody></tbody> </table> </div> <div class="data-table-section"> <h3>🔧 Hardware <a href="https://github.com/wonderwhy-er/llm-value-comparison/blob/main/data/hardware.json" class="edit-link" target="_blank">[Edit on GitHub]</a></h3> <table class="data-table" id="tableHardware"> <thead><tr><th>Hardware</th><th>Price</th><th>VRAM</th><th>Year</th><th>Source</th></tr></thead> <tbody></tbody> </table> </div> </div> </div> <script> // Global state let DATA = { models: {}, hardware: {}, benchmarks: {} }; let chart = null; const PROVIDER_COLORS = { 'OpenAI': '#10a37f', 'Anthropic': '#d4a574', 'Google': '#4285f4', 'DeepSeek': '#ff6b6b', 'Meta': '#0668E1', 'Alibaba': '#ff6a00', 'Mistral': '#ff7000', 'Microsoft': '#00bcf2', 'Z.ai': '#00b3ff', }; function formatNum(n) { if (n === null || n === undefined) return '-'; if (n >= 1e9) return (n / 1e9).toFixed(1) + 'B'; if (n >= 1e6) return (n / 1e6).toFixed(1) + 'M'; if (n >= 1e3) return (n / 1e3).toFixed(0) + 'K'; return n.toFixed(0); } function escapeAttr(value) { return String(value) .replace(/&/g, '&amp;') .replace(/"/g, '&quot;') .replace(/</g, '&lt;') .replace(/>/g, '&gt;'); } // Load all data from JSON files async function loadData() { try { // Load all 3 files in parallel const [modelsRes, hwRes, bmRes] = await Promise.all([ fetch('data/models.json'), fetch('data/hardware.json'), fetch('data/benchmarks.json') ]); DATA.models = await modelsRes.json(); DATA.hardware = await hwRes.json(); DATA.benchmarks = await bmRes.json(); console.log('Data loaded:', DATA); init(); } catch (err) { console.error('Failed to load data:', err); document.getElementById('calculatorContent').innerHTML = `<div class="warning-box">Error loading data: ${err.message}</div>`; } } function init() { // Populate hardware dropdown const hwSelect = document.getElementById('hardware'); Object.entries(DATA.hardware).forEach(([id, hw]) => { const opt = document.createElement('option'); opt.value = id; opt.textContent = `${hw.name} ($${hw.price})`; hwSelect.appendChild(opt); }); // Populate benchmark dropdown (only recommended ones) const bmSelect = document.getElementById('benchmark'); const chartBmSelect = document.getElementById('chartBenchmark'); // Add combined option first const combinedOpt = document.createElement('option'); combinedOpt.value = '_combined'; combinedOpt.textContent = '⚡ Combined (Average All)'; bmSelect.appendChild(combinedOpt); const combinedOpt2 = document.createElement('option'); combinedOpt2.value = '_combined'; combinedOpt2.textContent = '⚡ Combined (Average All)'; chartBmSelect.appendChild(combinedOpt2); Object.entries(DATA.benchmarks).filter(([,b]) => b.recommended).forEach(([id, bm]) => { const opt = document.createElement('option'); opt.value = id; opt.textContent = bm.name; bmSelect.appendChild(opt); const opt2 = document.createElement('option'); opt2.value = id; opt2.textContent = bm.name; chartBmSelect.appendChild(opt2); }); // Populate calculator dropdowns populateCalcDropdowns(); // Populate provider filter const providers = new Set(); Object.values(DATA.models).forEach(m => providers.add(m.provider)); const provSelect = document.getElementById('chartProvider'); providers.forEach(p => { const opt = document.createElement('option'); opt.value = p; opt.textContent = p; provSelect.appendChild(opt); }); // Render data tables renderDataTables(); // Setup tab switching document.querySelectorAll('.tab').forEach(tab => { tab.addEventListener('click', () => { document.querySelectorAll('.tab').forEach(t => t.classList.remove('active')); document.querySelectorAll('.tab-content').forEach(c => c.classList.remove('active')); tab.classList.add('active'); document.getElementById('tab-' + tab.dataset.tab).classList.add('active'); if (tab.dataset.tab === 'chart') updateChart(); }); }); // Event listeners document.querySelectorAll('select, input').forEach(el => { el.addEventListener('change', updateAll); el.addEventListener('input', updateAll); }); // Hardware change repopulates local models dropdown document.getElementById('hardware').addEventListener('change', () => { populateCalcDropdowns(); updateAll(); }); // Chart-specific controls document.getElementById('chartBenchmark').addEventListener('change', updateChart); document.getElementById('chartType').addEventListener('change', updateChart); document.getElementById('chartProvider').addEventListener('change', updateChart); updateAll(); } function populateCalcDropdowns() { const hwId = document.getElementById('hardware').value; // Local models (that have perf data for this hardware) const localSelect = document.getElementById('calcLocal'); localSelect.innerHTML = ''; Object.entries(DATA.models).forEach(([id, m]) => { if (m.local && m.local[hwId]) { const opt = document.createElement('option'); opt.value = id; opt.textContent = `${m.name} (${m.local[hwId].tokensPerSec} tok/s)`; localSelect.appendChild(opt); } }); // Subscriptions const subSelect = document.getElementById('calcSub'); subSelect.innerHTML = ''; Object.entries(DATA.models).forEach(([id, m]) => { if (m.subscriptions) { Object.entries(m.subscriptions).forEach(([subId, sub]) => { const opt = document.createElement('option'); opt.value = `${id}|${subId}`; opt.textContent = `${sub.name} → ${m.name} ($${sub.monthlyPrice}/mo)`; subSelect.appendChild(opt); }); } }); // API models const apiSelect = document.getElementById('calcApi'); apiSelect.innerHTML = ''; Object.entries(DATA.models).forEach(([id, m]) => { if (m.api) { const opt = document.createElement('option'); opt.value = id; const provider = m.api.provider ? ` via ${m.api.provider}` : ''; opt.textContent = `${m.name}${provider} ($${m.api.inputPer1M}/M)`; apiSelect.appendChild(opt); } }); } function renderDataTables() { // Models table let html = ''; Object.values(DATA.models).forEach(m => { html += `<tr> <td><strong>${m.name}</strong></td> <td>${m.provider}</td> <td>${m.releaseDate}</td> <td><a href="${m.modelCard}" target="_blank">Link</a></td> </tr>`; }); document.querySelector('#tableModels tbody').innerHTML = html; // Benchmarks table html = ''; Object.values(DATA.models).forEach(m => { const bm = m.benchmarks || {}; html += `<tr> <td>${m.name}</td> <td>${bm.arena_elo ? `<a href="${bm.arena_elo.source}" target="_blank">${bm.arena_elo.score}</a>` : '-'}</td> <td>${bm.aider_polyglot ? `<a href="${bm.aider_polyglot.source}" target="_blank">${bm.aider_polyglot.score}%</a>` : '-'}</td> <td>${bm.livebench ? `<a href="${bm.livebench.source}" target="_blank">${bm.livebench.score}%</a>` : '-'}</td> <td>${bm.mmlu ? `<a href="${bm.mmlu.source}" target="_blank">${bm.mmlu.score}%</a>` : '-'}</td> </tr>`; }); document.querySelector('#tableBenchmarks tbody').innerHTML = html; // API table html = ''; Object.values(DATA.models).filter(m => m.api).forEach(m => { html += `<tr> <td>${m.name}</td> <td>$${m.api.inputPer1M}</td> <td>$${m.api.outputPer1M}</td> <td><a href="${m.api.source}" target="_blank">Link</a></td> </tr>`; }); document.querySelector('#tableApi tbody').innerHTML = html; // Local performance table html = ''; Object.values(DATA.models).filter(m => m.local).forEach(m => { Object.entries(m.local).forEach(([hwId, perf]) => { const hw = DATA.hardware[hwId]; html += `<tr> <td>${m.name}</td> <td>${hw ? hw.name : hwId}</td> <td>${perf.tokensPerSec}</td> <td>${perf.quantization || '-'}</td> <td>${perf.vramRequired || '-'}GB</td> <td><a href="${perf.source}" target="_blank">Link</a></td> </tr>`; }); }); document.querySelector('#tableLocal tbody').innerHTML = html; // Subscriptions table html = ''; Object.values(DATA.models).filter(m => m.subscriptions).forEach(m => { Object.entries(m.subscriptions).forEach(([subId, sub]) => { const confClass = sub.confidence === 'low' ? 'confidence-low' : sub.confidence === 'medium' ? 'confidence-medium' : 'confidence-high'; html += `<tr> <td>${m.name}</td> <td>${sub.name}</td> <td>$${sub.monthlyPrice}</td> <td>${sub.tokensPerDay ? formatNum(sub.tokensPerDay) : '?'}</td> <td class="${confClass}">${sub.confidence || 'low'}</td> <td style="max-width:200px;font-size:0.65rem">${sub.notes || ''}</td> <td><a href="${sub.source}" target="_blank">Link</a></td> </tr>`; }); }); document.querySelector('#tableSubs tbody').innerHTML = html; // Hardware table html = ''; Object.entries(DATA.hardware).forEach(([id, hw]) => { html += `<tr> <td>${hw.name}</td> <td>$${hw.price}</td> <td>${hw.vram}GB</td> <td>${hw.year}</td> <td><a href="${hw.source}" target="_blank">Link</a></td> </tr>`; }); document.querySelector('#tableHardware tbody').innerHTML = html; } function getScore(model, benchmarkId) { if (!model.benchmarks) return null; // Handle combined benchmark - average all normalized scores if (benchmarkId === '_combined') { const recommendedBenchmarks = Object.entries(DATA.benchmarks) .filter(([,b]) => b.recommended) .map(([id]) => id); let total = 0; let count = 0; recommendedBenchmarks.forEach(bmId => { if (model.benchmarks[bmId]) { const rawScore = model.benchmarks[bmId].score; const normalized = normalizeScore(rawScore, bmId); total += normalized; count++; } }); if (count === 0) return null; return total / count; // Return average normalized score (0-100) } if (!model.benchmarks[benchmarkId]) return null; return model.benchmarks[benchmarkId].score; } // Normalize score to 0-100 range based on benchmark type function normalizeScore(score, benchmarkId) { // Combined scores are already normalized if (benchmarkId === '_combined') return score; const bm = DATA.benchmarks[benchmarkId]; if (!bm) return score; if (bm.type === 'elo') { // Normalize ELO: 1000 = 0%, 1500 = 100% return Math.max(0, Math.min(100, (score - 1000) / 5)); } // Percentage benchmarks are already 0-100 return score; } function getDisplayScore(score, benchmarkId) { // Combined scores show as percentage if (benchmarkId === '_combined') { return `${score.toFixed(1)}% avg`; } const bm = DATA.benchmarks[benchmarkId]; if (!bm) return `${score}`; if (bm.type === 'elo') { return `${score} ELO`; } return `${score}%`; } // Calculate weighted average API price (3:1 input:output ratio) function getWeightedApiPrice(api) { const inputWeight = 0.75; // 75% of tokens are typically input const outputWeight = 0.25; // 25% of tokens are typically output return (api.inputPer1M * inputWeight) + (api.outputPer1M * outputWeight); } function updateAll() { updateCalcCards(); renderCalculator(); // Chart updates only when tab is visible } function updateCalcCards() { const hwId = document.getElementById('hardware').value; const hours = parseFloat(document.getElementById('hoursPerDay').value) || 16; const years = parseInt(document.getElementById('periodYears').value); const benchmarkId = document.getElementById('benchmark').value; const hw = DATA.hardware[hwId]; if (!hw) return; // LOCAL calculation const localId = document.getElementById('calcLocal').value; const localModel = DATA.models[localId]; if (localModel && localModel.local && localModel.local[hwId]) { const perf = localModel.local[hwId]; const score = getScore(localModel, benchmarkId) || 0; const tokPerDay = perf.tokensPerSec * 3600 * hours; const tokTotal = tokPerDay * 365 * years; const adjusted = tokTotal * (normalizeScore(score, benchmarkId) / 100); const value = adjusted / hw.price; document.getElementById('calcLocalSteps').innerHTML = ` <div class="calc-step"><span class="num">${perf.tokensPerSec}</span> tok/s × 3600 × <span class="num">${hours}</span>h = <span class="result">${formatNum(tokPerDay)}</span> tok/day</div> <div class="calc-step"><span class="num">${formatNum(tokPerDay)}</span> × 365 × <span class="num">${years}</span>y = <span class="result">${formatNum(tokTotal)}</span> total</div> <div class="calc-step"><span class="num">${formatNum(tokTotal)}</span> × <span class="num">${getDisplayScore(score, benchmarkId)}</span> quality = <span class="result">${formatNum(adjusted)}</span></div> <div class="calc-step"><span class="num">${formatNum(adjusted)}</span> ÷ $<span class="num">${hw.price}</span> = <span class="result">${formatNum(value)}</span></div> `; document.getElementById('calcLocalValue').textContent = formatNum(value); } // SUBSCRIPTION calculation const subVal = document.getElementById('calcSub').value; if (subVal) { const [modelId, subId] = subVal.split('|'); const model = DATA.models[modelId]; const sub = model?.subscriptions?.[subId]; if (sub && sub.tokensPerDay) { const score = getScore(model, benchmarkId) || 0; const tokTotal = sub.tokensPerDay * 365 * years; const totalCost = sub.monthlyPrice * 12 * years; const adjusted = tokTotal * (normalizeScore(score, benchmarkId) / 100); const value = adjusted / totalCost; document.getElementById('calcSubSteps').innerHTML = ` <div class="calc-step"><span class="num">${formatNum(sub.tokensPerDay)}</span> tok/day × 365 × <span class="num">${years}</span>y = <span class="result">${formatNum(tokTotal)}</span></div> <div class="calc-step"><span class="num">${formatNum(tokTotal)}</span> × <span class="num">${getDisplayScore(score, benchmarkId)}</span> quality = <span class="result">${formatNum(adjusted)}</span></div> <div class="calc-step">$<span class="num">${sub.monthlyPrice}</span>/mo × 12 × <span class="num">${years}</span>y = $<span class="result">${totalCost}</span></div> <div class="calc-step"><span class="num">${formatNum(adjusted)}</span> ÷ $<span class="num">${totalCost}</span> = <span class="result">${formatNum(value)}</span></div> `; document.getElementById('calcSubValue').textContent = formatNum(value); } } // API calculation const apiId = document.getElementById('calcApi').value; const apiModel = DATA.models[apiId]; if (apiModel && apiModel.api) { const score = getScore(apiModel, benchmarkId) || 0; const weightedPrice = getWeightedApiPrice(apiModel.api); const tokPerDollar = 1000000 / weightedPrice; const value = tokPerDollar * (normalizeScore(score, benchmarkId) / 100); document.getElementById('calcApiSteps').innerHTML = ` <div class="calc-step">Weighted price: $<span class="num">${apiModel.api.inputPer1M}</span>×75% + $<span class="num">${apiModel.api.outputPer1M}</span>×25% = $<span class="result">${weightedPrice.toFixed(2)}</span>/M</div> <div class="calc-step">1,000,000 ÷ $<span class="num">${weightedPrice.toFixed(2)}</span> = <span class="result">${formatNum(tokPerDollar)}</span> tok/$</div> <div class="calc-step"><span class="num">${formatNum(tokPerDollar)}</span> × <span class="num">${getDisplayScore(score, benchmarkId)}</span> quality = <span class="result">${formatNum(value)}</span></div> `; document.getElementById('calcApiValue').textContent = formatNum(value); } } function renderCalculator() { const hwId = document.getElementById('hardware').value; const hours = parseFloat(document.getElementById('hoursPerDay').value) || 16; const years = parseInt(document.getElementById('periodYears').value); const benchmarkId = document.getElementById('benchmark').value; const hw = DATA.hardware[hwId]; if (!hw) return; // Calculate values for all models let results = []; Object.values(DATA.models).forEach(model => { const score = getScore(model, benchmarkId); if (!score) return; // API value if (model.api) { const weightedPrice = getWeightedApiPrice(model.api); const tokPerDollar = 1000000 / weightedPrice; const normalizedPct = normalizeScore(score, benchmarkId); const value = tokPerDollar * (normalizedPct / 100); const apiProvider = model.api.provider ? ` (${model.api.provider})` : ''; results.push({ model: model.name + apiProvider, type: 'api', value: value, score: score, displayScore: getDisplayScore(score, benchmarkId), details: `$${weightedPrice.toFixed(2)}/M avg`, tooltip: [ `Weighted price: $${model.api.inputPer1M}×75% + $${model.api.outputPer1M}×25% = $${weightedPrice.toFixed(2)}/M`, `Tokens per $: 1,000,000 ÷ $${weightedPrice.toFixed(2)} = ${formatNum(tokPerDollar)}`, `Quality-adjusted: ${formatNum(tokPerDollar)} × ${normalizedPct.toFixed(1)}% = ${formatNum(value)} tok/$` ].join('\n') }); } // Local value if (model.local && model.local[hwId]) { const perf = model.local[hwId]; const tokPerDay = perf.tokensPerSec * 3600 * hours; const tokTotal = tokPerDay * 365 * years; const normalizedPct = normalizeScore(score, benchmarkId); const value = (tokTotal / hw.price) * (normalizedPct / 100); results.push({ model: model.name, type: 'local', value: value, score: score, displayScore: getDisplayScore(score, benchmarkId), details: `${perf.tokensPerSec} tok/s on ${hw.name}`, tooltip: [ `Tokens/day: ${perf.tokensPerSec} tok/s × ${hours}h = ${formatNum(tokPerDay)}`, `Total tokens: ${formatNum(tokPerDay)} × 365 × ${years}y = ${formatNum(tokTotal)}`, `Quality-adjusted: ${formatNum(tokTotal)} × ${normalizedPct.toFixed(1)}% = ${formatNum(value * hw.price)}`, `Per $ (hw $${hw.price}): ${formatNum(value * hw.price)} ÷ $${hw.price} = ${formatNum(value)} tok/$` ].join('\n') }); } // Subscription values if (model.subscriptions) { Object.values(model.subscriptions).forEach(sub => { if (!sub.tokensPerDay) return; const tokTotal = sub.tokensPerDay * 365 * years; const cost = sub.monthlyPrice * 12 * years; const normalizedPct = normalizeScore(score, benchmarkId); const value = (tokTotal / cost) * (normalizedPct / 100); results.push({ model: model.name, type: 'subscription', subName: sub.name, value: value, score: score, displayScore: getDisplayScore(score, benchmarkId), confidence: sub.confidence, details: `$${sub.monthlyPrice}/mo`, tooltip: [ `Tokens/day: ${formatNum(sub.tokensPerDay)} (limit)`, `Total tokens: ${formatNum(sub.tokensPerDay)} × 365 × ${years}y = ${formatNum(tokTotal)}`, `Total cost: $${sub.monthlyPrice}/mo × 12 × ${years}y = $${cost}`, `Quality-adjusted: ${formatNum(tokTotal)} × ${normalizedPct.toFixed(1)}% = ${formatNum(value * cost)}`, `Per $: ${formatNum(value * cost)} ÷ $${cost} = ${formatNum(value)} tok/$` ].join('\n') }); }); } }); // Sort by value results.sort((a, b) => b.value - a.value); // Render const maxVal = results[0]?.value || 1; let html = '<div style="display:flex;flex-direction:column;gap:0.5rem">'; results.forEach((r, i) => { const pct = (r.value / maxVal) * 100; const typeColor = r.type === 'api' ? '#ff6b6b' : r.type === 'local' ? '#00ff88' : '#7c3aed'; const typeIcon = r.type === 'api' ? '🔌' : r.type === 'local' ? '🖥️' : '💳'; const typeLabel = r.type === 'api' ? 'API' : r.type === 'local' ? 'Local' : 'Sub'; const confWarn = r.confidence === 'low' ? ' ⚠️' : ''; const label = r.subName ? `${r.subName} → ${r.model}` : r.model; const tooltipAttr = r.tooltip ? ` data-tooltip="${escapeAttr(r.tooltip)}"` : ''; html += ` <div class="calc-row"${tooltipAttr} style="display:flex;align-items:center;gap:1rem"> <div style="width:60px;font-size:0.65rem;color:${typeColor};font-weight:600">${typeIcon} ${typeLabel}</div> <div style="width:220px;font-size:0.75rem">${label}${confWarn}</div> <div style="flex:1;background:rgba(255,255,255,0.05);border-radius:4px;height:24px;overflow:hidden"> <div style="width:${pct}%;height:100%;background:${typeColor};display:flex;align-items:center;justify-content:flex-end;padding-right:8px;font-size:0.7rem;font-weight:600"> ${formatNum(r.value)} </div> </div> <div style="width:150px;font-size:0.65rem;color:#888">${r.details} (${r.displayScore})</div> </div>`; }); html += '</div>'; document.getElementById('calculatorContent').innerHTML = html; } function updateChart() { const hwId = document.getElementById('hardware').value; const hours = parseFloat(document.getElementById('hoursPerDay').value) || 16; const years = parseInt(document.getElementById('periodYears').value); const benchmarkId = document.getElementById('chartBenchmark').value; const typeFilter = document.getElementById('chartType').value; const providerFilter = document.getElementById('chartProvider').value; const hw = DATA.hardware[hwId]; if (!hw) return; let dataPoints = []; Object.values(DATA.models).forEach(model => { if (providerFilter !== 'all' && model.provider !== providerFilter) return; const score = getScore(model, benchmarkId); if (!score) return; const date = new Date(model.releaseDate); // API if (model.api && (typeFilter === 'all' || typeFilter === 'api')) { const weightedPrice = getWeightedApiPrice(model.api); const tokPerDollar = 1000000 / weightedPrice; const normalizedPct = normalizeScore(score, benchmarkId); const value = tokPerDollar * (normalizedPct / 100); dataPoints.push({ name: model.name, provider: model.provider, type: 'api', date: date, value: value, calc: { step1: `Weighted price: $${model.api.inputPer1M}×75% + $${model.api.outputPer1M}×25% = $${weightedPrice.toFixed(2)}/M`, step2: `Tokens per $: 1M ÷ $${weightedPrice.toFixed(2)} = ${formatNum(tokPerDollar)}`, step3: `Quality-adjusted: ${formatNum(tokPerDollar)} × ${normalizedPct.toFixed(1)}% = ${formatNum(value)} tok/$` } }); } // Local if (model.local && model.local[hwId] && (typeFilter === 'all' || typeFilter === 'local')) { const perf = model.local[hwId]; const tokPerDay = perf.tokensPerSec * 3600 * hours; const tokTotal = tokPerDay * 365 * years; const normalizedPct = normalizeScore(score, benchmarkId); const adjusted = tokTotal * (normalizedPct / 100); const value = adjusted / hw.price; dataPoints.push({ name: `${model.name} (local)`, provider: model.provider, type: 'local', date: date, value: value, calc: { step1: `Tokens/day: ${perf.tokensPerSec} tok/s × ${hours}h = ${formatNum(tokPerDay)}`, step2: `Total tokens: ${formatNum(tokPerDay)} × 365 × ${years}y = ${formatNum(tokTotal)}`, step3: `Quality-adjusted: ${formatNum(tokTotal)} × ${normalizedPct.toFixed(1)}% = ${formatNum(adjusted)}`, step4: `Per $ (hw $${hw.price}): ${formatNum(adjusted)} ÷ $${hw.price} = ${formatNum(value)} tok/$` } }); } // Subscriptions if (model.subscriptions && (typeFilter === 'all' || typeFilter === 'subscription')) { Object.values(model.subscriptions).forEach(sub => { if (!sub.tokensPerDay) return; const tokTotal = sub.tokensPerDay * 365 * years; const cost = sub.monthlyPrice * 12 * years; const normalizedPct = normalizeScore(score, benchmarkId); const adjusted = tokTotal * (normalizedPct / 100); const value = adjusted / cost; dataPoints.push({ name: `${sub.name} → ${model.name}`, provider: model.provider, type: 'subscription', date: date, value: value, estimated: sub.confidence === 'low', calc: { step1: `Tokens/day: ${formatNum(sub.tokensPerDay)} (limit)`, step2: `Total tokens: ${formatNum(sub.tokensPerDay)} × 365 × ${years}y = ${formatNum(tokTotal)}`, step3: `Total cost: $${sub.monthlyPrice}/mo × 12 × ${years}y = $${cost}`, step4: `Quality-adjusted: ${formatNum(tokTotal)} × ${normalizedPct.toFixed(1)}% = ${formatNum(adjusted)}`, step5: `Per $: ${formatNum(adjusted)} ÷ $${cost} = ${formatNum(value)} tok/$` } }); }); } }); // Group by provider+type const groups = {}; dataPoints.forEach(d => { const key = `${d.provider}-${d.type}`; if (!groups[key]) groups[key] = { provider: d.provider, type: d.type, points: [] }; groups[key].points.push(d); }); Object.values(groups).forEach(g => g.points.sort((a, b) => a.date - b.date)); const datasets = Object.values(groups).map(g => { const color = PROVIDER_COLORS[g.provider] || '#888'; const typeLabel = g.type === 'api' ? '' : g.type === 'local' ? ' (Local)' : ' (Sub)'; return { label: g.provider + typeLabel, data: g.points.map(p => ({ x: p.date, y: p.value, ...p })), backgroundColor: color, borderColor: color, borderWidth: 2, pointRadius: 7, showLine: true, tension: 0.2, borderDash: g.type === 'subscription' ? [5, 5] : [], pointStyle: g.type === 'local' ? 'rect' : g.type === 'subscription' ? 'triangle' : 'circle', }; }); if (chart) chart.destroy(); chart = new Chart(document.getElementById('valueChart'), { type: 'scatter', data: { datasets }, options: { responsive: true, maintainAspectRatio: false, scales: { x: { type: 'time', time: { unit: 'quarter' }, title: { display: true, text: 'Release Date', color: '#888' }, ticks: { color: '#888' }, grid: { color: 'rgba(255,255,255,0.05)' } }, y: { type: 'logarithmic', title: { display: true, text: 'Quality-Adjusted Tokens per $', color: '#888' }, ticks: { color: '#888', callback: v => formatNum(v) }, grid: { color: 'rgba(255,255,255,0.05)' } } }, plugins: { tooltip: { callbacks: { title: ctx => { const d = ctx[0].raw; const typeIcon = d.type === 'api' ? '🔌 API' : d.type === 'local' ? '🖥️ Local' : '💳 Subscription'; const warn = d.estimated ? ' ⚠️' : ''; return `${typeIcon}: ${d.name}${warn}`; }, label: ctx => { const d = ctx.raw; const lines = [`Value: ${formatNum(d.value)} tok/$`]; if (d.calc) { lines.push('─────────'); Object.values(d.calc).forEach(step => lines.push(step)); } return lines; } } }, legend: { display: true, labels: { color: '#888', usePointStyle: true } } } } }); } // Start loading loadData(); </script> </body> </html>
wonderwhy-er/llm-value-comparison
1
Interactive calculator comparing local LLM vs cloud subscription value
HTML
wonderwhy-er
Eduard Ruzga
index.html
HTML
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="description" content="Compare images generated by OpenAI's DALL-E 2, DALL-E 3, and GPT-image-1 models side by side using the same prompt."> <meta property="og:title" content="OpenAI Image Model Comparison"> <meta property="og:description" content="Compare images generated by OpenAI's DALL-E 2, DALL-E 3, and GPT-image-1 models side by side."> <meta property="og:type" content="website"> <link rel="icon" href="data:image/svg+xml,<svg xmlns=%22http://www.w3.org/2000/svg%22 viewBox=%220 0 100 100%22><text y=%22.9em%22 font-size=%2290%22>🖼️</text></svg>"> <title>OpenAI Image Model Comparison</title> <style> body { font-family: Arial, sans-serif; max-width: 1200px; margin: 0 auto; padding: 20px; } h1 { text-align: center; margin-bottom: 30px; } .form-container { display: flex; flex-direction: column; gap: 15px; margin-bottom: 30px; } .input-group { display: flex; flex-direction: column; gap: 5px; } textarea { width: 100%; height: 100px; padding: 10px; font-family: inherit; } button { padding: 10px 15px; background-color: #0066cc; color: white; border: none; border-radius: 4px; cursor: pointer; font-size: 16px; align-self: flex-start; } button:hover { background-color: #0052a3; } .loading { display: flex; justify-content: center; margin: 30px 0; } .spinner { border: 5px solid #f3f3f3; border-top: 5px solid #0066cc; border-radius: 50%; width: 30px; height: 30px; animation: spin 1s linear infinite; } @keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } } .results-container { display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 20px; } .model-result { display: flex; flex-direction: column; gap: 15px; padding: 20px; border: 1px solid #ddd; border-radius: 8px; } .model-title { display: flex; justify-content: space-between; align-items: center; } .model-tag { font-size: 14px; padding: 4px 8px; border-radius: 4px; background-color: #f0f0f0; } .image-container { display: flex; flex-direction: column; gap: 15px; justify-content: center; align-items: center; } .image-box { display: flex; flex-direction: column; gap: 5px; width: 100%; } .image-box img { width: 100%; height: auto; border-radius: 4px; object-fit: contain; } .info { font-size: 14px; color: #666; } .error { color: #cc0000; font-weight: bold; } .hidden { display: none; } @media (max-width: 992px) { .results-container { grid-template-columns: 1fr; } } </style> </head> <body> <h1>OpenAI Image Model Comparison</h1> <div class="form-container"> <div class="input-group"> <label for="api-key">OpenAI API Key</label> <input type="password" id="api-key" placeholder="Enter your OpenAI API key"> <p class="info" style="margin-top: 5px;">You can get your API key from <a href="https://platform.openai.com/api-keys" target="_blank">https://platform.openai.com/api-keys</a></p> </div> <div class="note" style="padding: 10px; background-color: #f8f9fa; border-radius: 4px; margin-bottom: 15px; border-left: 4px solid #6c757d;"> <p style="margin: 0;"><strong>Note:</strong> This application uses your own OpenAI API key. Standard OpenAI usage charges will apply for any images generated.</p> </div> <div class="input-group"> <label for="prompt">Image Prompt</label> <textarea id="prompt" placeholder="Enter your image generation prompt here...">Poster of Dalí in robotic form drawing text on canvas "AI Image Evolution" in digital art style</textarea> </div> <div class="input-group"> <label for="size">Image Size</label> <select id="size"> <option value="1024x1024">1024x1024</option> <option value="1024x1792">1024x1792 (DALL-E 3/GPT-4V only)</option> <option value="1792x1024">1792x1024 (DALL-E 3/GPT-4V only)</option> <option value="512x512">512x512 (DALL-E 2 only)</option> <option value="256x256">256x256 (DALL-E 2 only)</option> </select> </div> <div class="input-group"> <label for="num-images">Number of Images Per Model (1-3)</label> <input type="number" id="num-images" min="1" max="3" value="1"> </div> <button id="generate-btn">Generate Images</button> </div> <div id="loading" class="loading hidden"> <div class="spinner"></div> </div> <div id="results-container" class="results-container"> <!-- Model results will be appended here --> </div> <footer style="margin-top: 50px; text-align: center; padding: 20px; border-top: 1px solid #eee; color: #666; font-size: 14px;"> <p>View on <a href="https://github.com/wonderwhy-er/openai-image-compare" target="_blank">GitHub</a> | MIT License</p> <p>This tool uses the OpenAI API to compare image generation models.</p> <p style="margin-top: 15px; font-style: italic;">Fully Vibe Coded with <a href="https://desktopcommander.app/" target="_blank">Desktop Commander</a> and Claude<br> </footer> <script> document.addEventListener('DOMContentLoaded', () => { const apiKeyInput = document.getElementById('api-key'); const promptInput = document.getElementById('prompt'); const sizeSelect = document.getElementById('size'); const numImagesInput = document.getElementById('num-images'); const generateBtn = document.getElementById('generate-btn'); const loadingEl = document.getElementById('loading'); const resultsContainer = document.getElementById('results-container'); // Check for saved API key in localStorage const savedApiKey = localStorage.getItem('openai_api_key'); if (savedApiKey) { apiKeyInput.value = savedApiKey; } generateBtn.addEventListener('click', async () => { const apiKey = apiKeyInput.value.trim(); const prompt = promptInput.value.trim(); const size = sizeSelect.value; const numImages = parseInt(numImagesInput.value); // Validate inputs if (!apiKey) { alert('Please enter your OpenAI API key'); return; } if (!prompt) { alert('Please enter an image prompt'); return; } // Save API key to localStorage localStorage.setItem('openai_api_key', apiKey); // Clear previous results and show loading resultsContainer.innerHTML = ''; loadingEl.classList.remove('hidden'); // Create model result containers const models = [ { id: 'dall-e-2', name: 'DALL-E 2', description: 'The second generation model (2022)', endpoint: 'https://api.openai.com/v1/images/generations' }, { id: 'dall-e-3', name: 'DALL-E 3', description: 'The third generation model (2023)', endpoint: 'https://api.openai.com/v1/images/generations' }, { id: 'gpt-image-1', name: 'GPT-4 Images', description: 'The newest image generation model (2025)', endpoint: 'https://api.openai.com/v1/images/generations' } ]; // Create containers for each model models.forEach(model => { const modelContainer = document.createElement('div'); modelContainer.className = 'model-result'; modelContainer.id = `result-${model.id}`; const titleDiv = document.createElement('div'); titleDiv.className = 'model-title'; const title = document.createElement('h2'); title.textContent = model.name; const modelTag = document.createElement('span'); modelTag.className = 'model-tag'; modelTag.textContent = model.id; titleDiv.appendChild(title); titleDiv.appendChild(modelTag); const description = document.createElement('p'); description.textContent = model.description; const imageContainer = document.createElement('div'); imageContainer.className = 'image-container'; imageContainer.innerHTML = '<p class="info">Loading images...</p>'; modelContainer.appendChild(titleDiv); modelContainer.appendChild(description); modelContainer.appendChild(imageContainer); resultsContainer.appendChild(modelContainer); }); // Generate images for each model try { await Promise.all(models.map(model => generateImages(model, apiKey, prompt, size, numImages))); } catch (error) { console.error('Error generating images:', error); } loadingEl.classList.add('hidden'); }); async function generateImages(model, apiKey, prompt, size, numImages) { const imageContainer = document.querySelector(`#result-${model.id} .image-container`); imageContainer.innerHTML = '<p class="info">Generating images...</p>'; try { // Adjust size based on model compatibility let actualSize = size; if (model.id === 'dall-e-2' && (size === '1024x1792' || size === '1792x1024')) { actualSize = '1024x1024'; } // Prepare the request payload const payload = { prompt: prompt, n: numImages, size: actualSize }; // Add model-specific parameters if (model.id === 'dall-e-3') { payload.model = 'dall-e-3'; payload.quality = 'standard'; payload.style = 'vivid'; } else if (model.id === 'dall-e-2') { payload.model = 'dall-e-2'; } else if (model.id === 'gpt-image-1') { payload.model = 'gpt-image-1'; } // Make the API request const response = await fetch(model.endpoint, { method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${apiKey}` }, body: JSON.stringify(payload) }); const data = await response.json(); if (!response.ok) { throw new Error(data.error?.message || 'Unknown error'); } // Display the generated images imageContainer.innerHTML = ''; console.log(`Response for ${model.id}:`, data); // Check response format if (data.data && data.data.length > 0) { if (data.data[0].url) { console.log(`${model.id} returned URL format images`); } else if (data.data[0].b64_json) { console.log(`${model.id} returned base64 format images`); const b64Preview = data.data[0].b64_json.substring(0, 50) + '...'; console.log(`Base64 preview: ${b64Preview}`); } else { console.warn(`${model.id} returned unknown format:`, data.data[0]); } } data.data.forEach((item, index) => { const imageBox = document.createElement('div'); imageBox.className = 'image-box'; const img = document.createElement('img'); if (item.url) { img.src = item.url; } else if (item.b64_json) { // For base64 data, try multiple image formats if needed img.onerror = function() { // If PNG doesn't work, try JPEG if (this.src.startsWith('data:image/png')) { this.src = `data:image/jpeg;base64,${item.b64_json}`; } }; img.src = `data:image/png;base64,${item.b64_json}`; } img.alt = `${model.name} generated image ${index + 1}`; img.loading = 'lazy'; const infoContainer = document.createElement('div'); infoContainer.style.display = 'flex'; infoContainer.style.justifyContent = 'space-between'; infoContainer.style.alignItems = 'center'; const info = document.createElement('p'); info.className = 'info'; info.textContent = `Image ${index + 1} - ${actualSize}`; const downloadBtn = document.createElement('button'); downloadBtn.textContent = 'Save'; downloadBtn.style.fontSize = '12px'; downloadBtn.style.padding = '4px 8px'; downloadBtn.onclick = function() { const a = document.createElement('a'); a.href = img.src; a.download = `${model.id}-image-${index+1}.png`; a.click(); }; infoContainer.appendChild(info); infoContainer.appendChild(downloadBtn); imageBox.appendChild(img); imageBox.appendChild(infoContainer); imageContainer.appendChild(imageBox); }); } catch (error) { console.error(`Error with ${model.name}:`, error); imageContainer.innerHTML = `<p class="error">Error: ${error.message || 'Failed to generate images'}</p>`; } } }); </script> </body> </html>
wonderwhy-er/openai-image-compare
1
HTML
wonderwhy-er
Eduard Ruzga
decode.ts
TypeScript
interface Result { index: number; rpcId: number; data: any; } export function parseBatchExecuteResponse(raw: string): Result[] { // Trim the first 2 lines // ")]}'" and an empty line const envelopesRaw = raw.split("\n").slice(2).join(""); // Load all envelopes JSON (list of envelopes) const envelopes: any[] = JSON.parse(envelopesRaw); const results: Result[] = []; for (const envelope of envelopes) { // Ignore envelopes that don't have 'wrb.fr' at [0] // (they're not RPC responses but analytics etc.) if (envelope[0] !== "wrb.fr") { continue; } // Index (at [6], string) // Index is 1-based // Index is "generic" if the response contains a single envelope let index: number; if (envelope[6] === "generic") { index = 1; } else { index = parseInt(envelope[6], 10); } // Rpcid (at [1]) // Rpcid's response (at [2], a JSON string) const rpcid = envelope[1]; const data = JSON.parse(envelope[2]); results.push({ index, rpcId: rpcid, data }); } return results; }
wong2/batchexecute
14
TypeScript package to ease interactions with Google's batchexecute batch RPC system
TypeScript
wong2
wong2
encode.ts
TypeScript
interface RpcRequest { id: string; args: string[]; } interface Params { host: string; app: string; rpcs: RpcRequest[]; } interface Result { url: URL; headers: Headers; body: URLSearchParams; } function generateReqId() { return Math.floor(Math.random() * 900000) + 100000; } function buildFreqList(rpcs: RpcRequest[]) { function envelope(rpc: RpcRequest, index: number) { return [rpc.id, JSON.stringify(rpc.args), null, index > 0 ? index.toString() : "generic"]; } if (rpcs.length === 1) { return [envelope(rpcs[0], 0)]; } const freq = []; for (let i = 0; i < rpcs.length; i++) { freq.push(envelope(rpcs[i], i + 1)); } return freq; } export function preparedBatchExecute(params: Params): Result { const url = new URL(`https://${params.host}/_/${params.app}/data/batchexecute`); url.searchParams.append("rpcids", params.rpcs.map((rpc) => rpc.id).join(",")); url.searchParams.append("_reqid", generateReqId().toString()); const headers = new Headers({ "content-type": "application/x-www-form-urlencoded;charset=utf-8", }); const body = new URLSearchParams({ "f.req": JSON.stringify([buildFreqList(params.rpcs)]), }); return { url, headers, body }; }
wong2/batchexecute
14
TypeScript package to ease interactions with Google's batchexecute batch RPC system
TypeScript
wong2
wong2
example.ts
TypeScript
import { parseBatchExecuteResponse, preparedBatchExecute } from "./mod.ts"; const encoded = preparedBatchExecute({ host: "chromewebstore.google.com", app: "ChromeWebStoreConsumerFeUi", rpcs: [{ id: "xY2Ddd", args: ["jjplpolfahlhoodebebfjdbpcbopcmlk"] }], }); console.log(encoded); const response = await fetch(encoded.url, { method: "POST", headers: encoded.headers, body: encoded.body, }); const raw = await response.text(); const results = parseBatchExecuteResponse(raw); console.log(results);
wong2/batchexecute
14
TypeScript package to ease interactions with Google's batchexecute batch RPC system
TypeScript
wong2
wong2
mod.ts
TypeScript
export { preparedBatchExecute } from "./encode.ts"; export { parseBatchExecuteResponse } from "./decode.ts";
wong2/batchexecute
14
TypeScript package to ease interactions with Google's batchexecute batch RPC system
TypeScript
wong2
wong2
.eslintrc.cjs
JavaScript
module.exports = { extends: ["eslint:recommended", "plugin:@typescript-eslint/recommended", "preact"], parser: "@typescript-eslint/parser", plugins: ["@typescript-eslint"], env: { browser: true, }, root: true, rules: { "jest/no-deprecated-functions": 0, }, };
wong2/browser-firewall
44
Block any extension or website from accessing network
TypeScript
wong2
wong2
manifest.config.ts
TypeScript
import { defineManifest } from "@crxjs/vite-plugin"; export default defineManifest(() => { return { manifest_version: 3, name: "Browser Firewall", description: "Block any extension or website from accessing network", version: "1.0.0", icons: { 16: "src/assets/icon.png", 32: "src/assets/icon.png", 48: "src/assets/icon.png", 128: "src/assets/icon.png", }, action: {}, background: { service_worker: "src/background.ts", type: "module", }, permissions: ["management", "declarativeNetRequest"], options_ui: { page: "options.html", open_in_tab: true, }, }; });
wong2/browser-firewall
44
Block any extension or website from accessing network
TypeScript
wong2
wong2
options.html
HTML
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Browser Firewall</title> </head> <body> <div id="app"></div> <script type="module" src="/src/main.tsx"></script> </body> </html>
wong2/browser-firewall
44
Block any extension or website from accessing network
TypeScript
wong2
wong2
postcss.config.js
JavaScript
export default { plugins: { tailwindcss: {}, autoprefixer: {}, }, }
wong2/browser-firewall
44
Block any extension or website from accessing network
TypeScript
wong2
wong2
src/background.ts
TypeScript
import Browser from "webextension-polyfill"; Browser.action.onClicked.addListener(() => { Browser.runtime.openOptionsPage(); }); Browser.runtime.onInstalled.addListener((details) => { if (details.reason === "install") { Browser.runtime.openOptionsPage(); } });
wong2/browser-firewall
44
Block any extension or website from accessing network
TypeScript
wong2
wong2
src/components/BlockForm.tsx
TypeScript (TSX)
import { block } from "@/lib/rules"; import { Extension } from "@/types"; import { useSignal } from "@preact/signals"; import { FC, useEffect } from "preact/compat"; import ExtensionSelect from "./ExtensionSelect"; import { Button } from "./ui/button"; import { Input } from "./ui/input"; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "./ui/select"; interface Props { extensions: Extension[]; } const BlockForm: FC<Props> = (props) => { const itemType = useSignal("extension"); const itemValue = useSignal(""); const blocking = useSignal(false); useEffect(() => { itemValue.value = ""; }, [itemType.value]); const submit = async () => { console.log(itemType.value, itemValue.value); if (!itemValue.value) { return; } // check format blocking.value = true; await block(itemValue.value); blocking.value = false; location.reload(); }; return ( <div className="flex flex-col gap-3"> <div className="grid grid-cols-7 gap-3"> <Select defaultValue="extension" value={itemType.value} onValueChange={(v) => (itemType.value = v)} > <SelectTrigger className="col-span-2"> <SelectValue /> </SelectTrigger> <SelectContent> <SelectItem value="extension">Extension</SelectItem> <SelectItem value="domain">Domain</SelectItem> </SelectContent> </Select> <div className="col-span-5"> {itemType.value === "extension" ? ( <ExtensionSelect extensions={props.extensions} onSelected={(id) => (itemValue.value = id)} /> ) : ( <Input placeholder="twitter.com" onChange={(e) => (itemValue.value = e.target.value)} /> )} </div> </div> <div className="flex flex-row justify-end"> <Button size="sm" className="w-fit px-5" onClick={submit}> Block </Button> </div> </div> ); }; export default BlockForm;
wong2/browser-firewall
44
Block any extension or website from accessing network
TypeScript
wong2
wong2
src/components/BlockedItemCard.tsx
TypeScript (TSX)
import { BlockedItem, unblock } from "@/lib/rules"; import { getFaviconUrl } from "@/lib/utils"; import { Unlock } from "lucide-react"; import { useMemo } from "preact/hooks"; import { Badge } from "./ui/badge"; import { Card, CardContent, CardHeader, CardTitle } from "./ui/card"; const BlockedItemCard = ({ item }: { item: BlockedItem }) => { const [name, icon] = useMemo(() => { if (item.type === "domain") { return [item.value, getFaviconUrl(item.value)]; } return [item.name, item.icon]; }, [item]); const unblockItem = () => { unblock(item.value); location.reload(); }; return ( <Card> <CardHeader className="flex flex-row items-center justify-between"> <CardTitle className="text-sm font-medium flex flex-row justify-between items-center w-full"> <Badge variant="secondary">{item.type}</Badge> <Unlock size={13} className="cursor-pointer" title="Unblock" onClick={unblockItem} /> </CardTitle> </CardHeader> <CardContent> <div className="flex flex-row items-center gap-4"> <div className="border border-solid border-gray-200 rounded-sm p-1"> <img className="w-6 h-6" src={icon} /> </div> <span className="text-xl font-bold leading-none">{name}</span> </div> </CardContent> </Card> ); }; export default BlockedItemCard;
wong2/browser-firewall
44
Block any extension or website from accessing network
TypeScript
wong2
wong2
src/components/ExtensionSelect.tsx
TypeScript (TSX)
import { cn } from "@/lib/utils"; import { Extension } from "@/types"; import { useSignal } from "@preact/signals"; import { Check, ChevronsUpDown } from "lucide-react"; import { FC, useState } from "preact/compat"; import { Button } from "./ui/button"; import { Command, CommandEmpty, CommandGroup, CommandInput, CommandItem } from "./ui/command"; import { Popover, PopoverContent, PopoverTrigger } from "./ui/popover"; import { ScrollArea } from "./ui/scroll-area"; interface Props { extensions: Extension[]; onSelected: (id: string) => void; } const ExtensionSelect: FC<Props> = (props) => { const [open, setOpen] = useState(false); const selected = useSignal(""); // selected extension id return ( <Popover open={open} onOpenChange={setOpen}> <PopoverTrigger asChild> <Button variant="outline" role="combobox" className="w-full justify-between"> <span className="truncate"> {props.extensions.find((ext) => ext.id === selected.value)?.name || "Select extension..."} </span> <ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" /> </Button> </PopoverTrigger> <PopoverContent className="p-0"> <Command> <CommandInput placeholder="Search extension..." /> <CommandEmpty>No extension found.</CommandEmpty> <CommandGroup> <ScrollArea className="h-[300px]"> {props.extensions.map((ext) => ( <CommandItem value={ext.name} key={ext.id} onSelect={() => { selected.value = ext.id; props.onSelected(ext.id); setOpen(false); }} className="flex flex-row items-center gap-1" > <Check className={cn( "h-4 w-4 shrink-0", selected.value === ext.id ? "opacity-100" : "opacity-0" )} /> <span className="truncate">{ext.name}</span> </CommandItem> ))} </ScrollArea> </CommandGroup> </Command> </PopoverContent> </Popover> ); }; export default ExtensionSelect;
wong2/browser-firewall
44
Block any extension or website from accessing network
TypeScript
wong2
wong2
src/components/ui/badge.tsx
TypeScript (TSX)
import * as React from "react" import { cva, type VariantProps } from "class-variance-authority" import { cn } from "@/lib/utils" const badgeVariants = cva( "inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2", { variants: { variant: { default: "border-transparent bg-primary text-primary-foreground hover:bg-primary/80", secondary: "border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80", destructive: "border-transparent bg-destructive text-destructive-foreground hover:bg-destructive/80", outline: "text-foreground", }, }, defaultVariants: { variant: "default", }, } ) export interface BadgeProps extends React.HTMLAttributes<HTMLDivElement>, VariantProps<typeof badgeVariants> {} function Badge({ className, variant, ...props }: BadgeProps) { return ( <div className={cn(badgeVariants({ variant }), className)} {...props} /> ) } export { Badge, badgeVariants }
wong2/browser-firewall
44
Block any extension or website from accessing network
TypeScript
wong2
wong2
src/components/ui/button.tsx
TypeScript (TSX)
import * as React from "react" import { Slot } from "@radix-ui/react-slot" import { cva, type VariantProps } from "class-variance-authority" import { cn } from "@/lib/utils" const buttonVariants = cva( "inline-flex items-center justify-center rounded-md text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50", { variants: { variant: { default: "bg-primary text-primary-foreground hover:bg-primary/90", destructive: "bg-destructive text-destructive-foreground hover:bg-destructive/90", outline: "border border-input bg-background hover:bg-accent hover:text-accent-foreground", secondary: "bg-secondary text-secondary-foreground hover:bg-secondary/80", ghost: "hover:bg-accent hover:text-accent-foreground", link: "text-primary underline-offset-4 hover:underline", }, size: { default: "h-10 px-4 py-2", sm: "h-9 rounded-md px-3", lg: "h-11 rounded-md px-8", icon: "h-10 w-10", }, }, defaultVariants: { variant: "default", size: "default", }, } ) export interface ButtonProps extends React.ButtonHTMLAttributes<HTMLButtonElement>, VariantProps<typeof buttonVariants> { asChild?: boolean } const Button = React.forwardRef<HTMLButtonElement, ButtonProps>( ({ className, variant, size, asChild = false, ...props }, ref) => { const Comp = asChild ? Slot : "button" return ( <Comp className={cn(buttonVariants({ variant, size, className }))} ref={ref} {...props} /> ) } ) Button.displayName = "Button" export { Button, buttonVariants }
wong2/browser-firewall
44
Block any extension or website from accessing network
TypeScript
wong2
wong2
src/components/ui/card.tsx
TypeScript (TSX)
import * as React from "react" import { cn } from "@/lib/utils" const Card = React.forwardRef< HTMLDivElement, React.HTMLAttributes<HTMLDivElement> >(({ className, ...props }, ref) => ( <div ref={ref} className={cn( "rounded-lg border bg-card text-card-foreground shadow-sm", className )} {...props} /> )) Card.displayName = "Card" const CardHeader = React.forwardRef< HTMLDivElement, React.HTMLAttributes<HTMLDivElement> >(({ className, ...props }, ref) => ( <div ref={ref} className={cn("flex flex-col space-y-1.5 p-6", className)} {...props} /> )) CardHeader.displayName = "CardHeader" const CardTitle = React.forwardRef< HTMLParagraphElement, React.HTMLAttributes<HTMLHeadingElement> >(({ className, ...props }, ref) => ( <h3 ref={ref} className={cn( "text-2xl font-semibold leading-none tracking-tight", className )} {...props} /> )) CardTitle.displayName = "CardTitle" const CardDescription = React.forwardRef< HTMLParagraphElement, React.HTMLAttributes<HTMLParagraphElement> >(({ className, ...props }, ref) => ( <p ref={ref} className={cn("text-sm text-muted-foreground", className)} {...props} /> )) CardDescription.displayName = "CardDescription" const CardContent = React.forwardRef< HTMLDivElement, React.HTMLAttributes<HTMLDivElement> >(({ className, ...props }, ref) => ( <div ref={ref} className={cn("p-6 pt-0", className)} {...props} /> )) CardContent.displayName = "CardContent" const CardFooter = React.forwardRef< HTMLDivElement, React.HTMLAttributes<HTMLDivElement> >(({ className, ...props }, ref) => ( <div ref={ref} className={cn("flex items-center p-6 pt-0", className)} {...props} /> )) CardFooter.displayName = "CardFooter" export { Card, CardHeader, CardFooter, CardTitle, CardDescription, CardContent }
wong2/browser-firewall
44
Block any extension or website from accessing network
TypeScript
wong2
wong2
src/components/ui/command.tsx
TypeScript (TSX)
import * as React from "react" import { DialogProps } from "@radix-ui/react-dialog" import { Command as CommandPrimitive } from "cmdk" import { Search } from "lucide-react" import { cn } from "@/lib/utils" import { Dialog, DialogContent } from "@/components/ui/dialog" const Command = React.forwardRef< React.ElementRef<typeof CommandPrimitive>, React.ComponentPropsWithoutRef<typeof CommandPrimitive> >(({ className, ...props }, ref) => ( <CommandPrimitive ref={ref} className={cn( "flex h-full w-full flex-col overflow-hidden rounded-md bg-popover text-popover-foreground", className )} {...props} /> )) Command.displayName = CommandPrimitive.displayName interface CommandDialogProps extends DialogProps {} const CommandDialog = ({ children, ...props }: CommandDialogProps) => { return ( <Dialog {...props}> <DialogContent className="overflow-hidden p-0 shadow-lg"> <Command className="[&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground [&_[cmdk-group]:not([hidden])_~[cmdk-group]]:pt-0 [&_[cmdk-group]]:px-2 [&_[cmdk-input-wrapper]_svg]:h-5 [&_[cmdk-input-wrapper]_svg]:w-5 [&_[cmdk-input]]:h-12 [&_[cmdk-item]]:px-2 [&_[cmdk-item]]:py-3 [&_[cmdk-item]_svg]:h-5 [&_[cmdk-item]_svg]:w-5"> {children} </Command> </DialogContent> </Dialog> ) } const CommandInput = React.forwardRef< React.ElementRef<typeof CommandPrimitive.Input>, React.ComponentPropsWithoutRef<typeof CommandPrimitive.Input> >(({ className, ...props }, ref) => ( <div className="flex items-center border-b px-3" cmdk-input-wrapper=""> <Search className="mr-2 h-4 w-4 shrink-0 opacity-50" /> <CommandPrimitive.Input ref={ref} className={cn( "flex h-11 w-full rounded-md bg-transparent py-3 text-sm outline-none placeholder:text-muted-foreground disabled:cursor-not-allowed disabled:opacity-50", className )} {...props} /> </div> )) CommandInput.displayName = CommandPrimitive.Input.displayName const CommandList = React.forwardRef< React.ElementRef<typeof CommandPrimitive.List>, React.ComponentPropsWithoutRef<typeof CommandPrimitive.List> >(({ className, ...props }, ref) => ( <CommandPrimitive.List ref={ref} className={cn("max-h-[300px] overflow-y-auto overflow-x-hidden", className)} {...props} /> )) CommandList.displayName = CommandPrimitive.List.displayName const CommandEmpty = React.forwardRef< React.ElementRef<typeof CommandPrimitive.Empty>, React.ComponentPropsWithoutRef<typeof CommandPrimitive.Empty> >((props, ref) => ( <CommandPrimitive.Empty ref={ref} className="py-6 text-center text-sm" {...props} /> )) CommandEmpty.displayName = CommandPrimitive.Empty.displayName const CommandGroup = React.forwardRef< React.ElementRef<typeof CommandPrimitive.Group>, React.ComponentPropsWithoutRef<typeof CommandPrimitive.Group> >(({ className, ...props }, ref) => ( <CommandPrimitive.Group ref={ref} className={cn( "overflow-hidden p-1 text-foreground [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:text-xs [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground", className )} {...props} /> )) CommandGroup.displayName = CommandPrimitive.Group.displayName const CommandSeparator = React.forwardRef< React.ElementRef<typeof CommandPrimitive.Separator>, React.ComponentPropsWithoutRef<typeof CommandPrimitive.Separator> >(({ className, ...props }, ref) => ( <CommandPrimitive.Separator ref={ref} className={cn("-mx-1 h-px bg-border", className)} {...props} /> )) CommandSeparator.displayName = CommandPrimitive.Separator.displayName const CommandItem = React.forwardRef< React.ElementRef<typeof CommandPrimitive.Item>, React.ComponentPropsWithoutRef<typeof CommandPrimitive.Item> >(({ className, ...props }, ref) => ( <CommandPrimitive.Item ref={ref} className={cn( "relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none aria-selected:bg-accent aria-selected:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50", className )} {...props} /> )) CommandItem.displayName = CommandPrimitive.Item.displayName const CommandShortcut = ({ className, ...props }: React.HTMLAttributes<HTMLSpanElement>) => { return ( <span className={cn( "ml-auto text-xs tracking-widest text-muted-foreground", className )} {...props} /> ) } CommandShortcut.displayName = "CommandShortcut" export { Command, CommandDialog, CommandInput, CommandList, CommandEmpty, CommandGroup, CommandItem, CommandShortcut, CommandSeparator, }
wong2/browser-firewall
44
Block any extension or website from accessing network
TypeScript
wong2
wong2
src/components/ui/dialog.tsx
TypeScript (TSX)
import * as React from "react" import * as DialogPrimitive from "@radix-ui/react-dialog" import { X } from "lucide-react" import { cn } from "@/lib/utils" const Dialog = DialogPrimitive.Root const DialogTrigger = DialogPrimitive.Trigger const DialogPortal = ({ className, ...props }: DialogPrimitive.DialogPortalProps) => ( <DialogPrimitive.Portal className={cn(className)} {...props} /> ) DialogPortal.displayName = DialogPrimitive.Portal.displayName const DialogOverlay = React.forwardRef< React.ElementRef<typeof DialogPrimitive.Overlay>, React.ComponentPropsWithoutRef<typeof DialogPrimitive.Overlay> >(({ className, ...props }, ref) => ( <DialogPrimitive.Overlay ref={ref} className={cn( "fixed inset-0 z-50 bg-background/80 backdrop-blur-sm data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0", className )} {...props} /> )) DialogOverlay.displayName = DialogPrimitive.Overlay.displayName const DialogContent = React.forwardRef< React.ElementRef<typeof DialogPrimitive.Content>, React.ComponentPropsWithoutRef<typeof DialogPrimitive.Content> >(({ className, children, ...props }, ref) => ( <DialogPortal> <DialogOverlay /> <DialogPrimitive.Content ref={ref} className={cn( "fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg md:w-full", className )} {...props} > {children} <DialogPrimitive.Close className="absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground"> <X className="h-4 w-4" /> <span className="sr-only">Close</span> </DialogPrimitive.Close> </DialogPrimitive.Content> </DialogPortal> )) DialogContent.displayName = DialogPrimitive.Content.displayName const DialogHeader = ({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) => ( <div className={cn( "flex flex-col space-y-1.5 text-center sm:text-left", className )} {...props} /> ) DialogHeader.displayName = "DialogHeader" const DialogFooter = ({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) => ( <div className={cn( "flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2", className )} {...props} /> ) DialogFooter.displayName = "DialogFooter" const DialogTitle = React.forwardRef< React.ElementRef<typeof DialogPrimitive.Title>, React.ComponentPropsWithoutRef<typeof DialogPrimitive.Title> >(({ className, ...props }, ref) => ( <DialogPrimitive.Title ref={ref} className={cn( "text-lg font-semibold leading-none tracking-tight", className )} {...props} /> )) DialogTitle.displayName = DialogPrimitive.Title.displayName const DialogDescription = React.forwardRef< React.ElementRef<typeof DialogPrimitive.Description>, React.ComponentPropsWithoutRef<typeof DialogPrimitive.Description> >(({ className, ...props }, ref) => ( <DialogPrimitive.Description ref={ref} className={cn("text-sm text-muted-foreground", className)} {...props} /> )) DialogDescription.displayName = DialogPrimitive.Description.displayName export { Dialog, DialogTrigger, DialogContent, DialogHeader, DialogFooter, DialogTitle, DialogDescription, }
wong2/browser-firewall
44
Block any extension or website from accessing network
TypeScript
wong2
wong2
src/components/ui/input.tsx
TypeScript (TSX)
import * as React from "react" import { cn } from "@/lib/utils" export interface InputProps extends React.InputHTMLAttributes<HTMLInputElement> {} const Input = React.forwardRef<HTMLInputElement, InputProps>( ({ className, type, ...props }, ref) => { return ( <input type={type} className={cn( "flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50", className )} ref={ref} {...props} /> ) } ) Input.displayName = "Input" export { Input }
wong2/browser-firewall
44
Block any extension or website from accessing network
TypeScript
wong2
wong2
src/components/ui/label.tsx
TypeScript (TSX)
import * as React from "react" import * as LabelPrimitive from "@radix-ui/react-label" import { cva, type VariantProps } from "class-variance-authority" import { cn } from "@/lib/utils" const labelVariants = cva( "text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70" ) const Label = React.forwardRef< React.ElementRef<typeof LabelPrimitive.Root>, React.ComponentPropsWithoutRef<typeof LabelPrimitive.Root> & VariantProps<typeof labelVariants> >(({ className, ...props }, ref) => ( <LabelPrimitive.Root ref={ref} className={cn(labelVariants(), className)} {...props} /> )) Label.displayName = LabelPrimitive.Root.displayName export { Label }
wong2/browser-firewall
44
Block any extension or website from accessing network
TypeScript
wong2
wong2
src/components/ui/popover.tsx
TypeScript (TSX)
import * as React from "react" import * as PopoverPrimitive from "@radix-ui/react-popover" import { cn } from "@/lib/utils" const Popover = PopoverPrimitive.Root const PopoverTrigger = PopoverPrimitive.Trigger const PopoverContent = React.forwardRef< React.ElementRef<typeof PopoverPrimitive.Content>, React.ComponentPropsWithoutRef<typeof PopoverPrimitive.Content> >(({ className, align = "center", sideOffset = 4, ...props }, ref) => ( <PopoverPrimitive.Portal> <PopoverPrimitive.Content ref={ref} align={align} sideOffset={sideOffset} className={cn( "z-50 w-72 rounded-md border bg-popover p-4 text-popover-foreground shadow-md outline-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2", className )} {...props} /> </PopoverPrimitive.Portal> )) PopoverContent.displayName = PopoverPrimitive.Content.displayName export { Popover, PopoverTrigger, PopoverContent }
wong2/browser-firewall
44
Block any extension or website from accessing network
TypeScript
wong2
wong2
src/components/ui/scroll-area.tsx
TypeScript (TSX)
import * as React from "react" import * as ScrollAreaPrimitive from "@radix-ui/react-scroll-area" import { cn } from "@/lib/utils" const ScrollArea = React.forwardRef< React.ElementRef<typeof ScrollAreaPrimitive.Root>, React.ComponentPropsWithoutRef<typeof ScrollAreaPrimitive.Root> >(({ className, children, ...props }, ref) => ( <ScrollAreaPrimitive.Root ref={ref} className={cn("relative overflow-hidden", className)} {...props} > <ScrollAreaPrimitive.Viewport className="h-full w-full rounded-[inherit]"> {children} </ScrollAreaPrimitive.Viewport> <ScrollBar /> <ScrollAreaPrimitive.Corner /> </ScrollAreaPrimitive.Root> )) ScrollArea.displayName = ScrollAreaPrimitive.Root.displayName const ScrollBar = React.forwardRef< React.ElementRef<typeof ScrollAreaPrimitive.ScrollAreaScrollbar>, React.ComponentPropsWithoutRef<typeof ScrollAreaPrimitive.ScrollAreaScrollbar> >(({ className, orientation = "vertical", ...props }, ref) => ( <ScrollAreaPrimitive.ScrollAreaScrollbar ref={ref} orientation={orientation} className={cn( "flex touch-none select-none transition-colors", orientation === "vertical" && "h-full w-2.5 border-l border-l-transparent p-[1px]", orientation === "horizontal" && "h-2.5 border-t border-t-transparent p-[1px]", className )} {...props} > <ScrollAreaPrimitive.ScrollAreaThumb className="relative flex-1 rounded-full bg-border" /> </ScrollAreaPrimitive.ScrollAreaScrollbar> )) ScrollBar.displayName = ScrollAreaPrimitive.ScrollAreaScrollbar.displayName export { ScrollArea, ScrollBar }
wong2/browser-firewall
44
Block any extension or website from accessing network
TypeScript
wong2
wong2
src/components/ui/select.tsx
TypeScript (TSX)
import * as React from "react" import * as SelectPrimitive from "@radix-ui/react-select" import { Check, ChevronDown } from "lucide-react" import { cn } from "@/lib/utils" const Select = SelectPrimitive.Root const SelectGroup = SelectPrimitive.Group const SelectValue = SelectPrimitive.Value const SelectTrigger = React.forwardRef< React.ElementRef<typeof SelectPrimitive.Trigger>, React.ComponentPropsWithoutRef<typeof SelectPrimitive.Trigger> >(({ className, children, ...props }, ref) => ( <SelectPrimitive.Trigger ref={ref} className={cn( "flex h-10 w-full items-center justify-between rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50", className )} {...props} > {children} <SelectPrimitive.Icon asChild> <ChevronDown className="h-4 w-4 opacity-50" /> </SelectPrimitive.Icon> </SelectPrimitive.Trigger> )) SelectTrigger.displayName = SelectPrimitive.Trigger.displayName const SelectContent = React.forwardRef< React.ElementRef<typeof SelectPrimitive.Content>, React.ComponentPropsWithoutRef<typeof SelectPrimitive.Content> >(({ className, children, position = "popper", ...props }, ref) => ( <SelectPrimitive.Portal> <SelectPrimitive.Content ref={ref} className={cn( "relative z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2", position === "popper" && "data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1", className )} position={position} {...props} > <SelectPrimitive.Viewport className={cn( "p-1", position === "popper" && "h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]" )} > {children} </SelectPrimitive.Viewport> </SelectPrimitive.Content> </SelectPrimitive.Portal> )) SelectContent.displayName = SelectPrimitive.Content.displayName const SelectLabel = React.forwardRef< React.ElementRef<typeof SelectPrimitive.Label>, React.ComponentPropsWithoutRef<typeof SelectPrimitive.Label> >(({ className, ...props }, ref) => ( <SelectPrimitive.Label ref={ref} className={cn("py-1.5 pl-8 pr-2 text-sm font-semibold", className)} {...props} /> )) SelectLabel.displayName = SelectPrimitive.Label.displayName const SelectItem = React.forwardRef< React.ElementRef<typeof SelectPrimitive.Item>, React.ComponentPropsWithoutRef<typeof SelectPrimitive.Item> >(({ className, children, ...props }, ref) => ( <SelectPrimitive.Item ref={ref} className={cn( "relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50", className )} {...props} > <span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center"> <SelectPrimitive.ItemIndicator> <Check className="h-4 w-4" /> </SelectPrimitive.ItemIndicator> </span> <SelectPrimitive.ItemText>{children}</SelectPrimitive.ItemText> </SelectPrimitive.Item> )) SelectItem.displayName = SelectPrimitive.Item.displayName const SelectSeparator = React.forwardRef< React.ElementRef<typeof SelectPrimitive.Separator>, React.ComponentPropsWithoutRef<typeof SelectPrimitive.Separator> >(({ className, ...props }, ref) => ( <SelectPrimitive.Separator ref={ref} className={cn("-mx-1 my-1 h-px bg-muted", className)} {...props} /> )) SelectSeparator.displayName = SelectPrimitive.Separator.displayName export { Select, SelectGroup, SelectValue, SelectTrigger, SelectContent, SelectLabel, SelectItem, SelectSeparator, }
wong2/browser-firewall
44
Block any extension or website from accessing network
TypeScript
wong2
wong2
src/components/ui/separator.tsx
TypeScript (TSX)
import * as React from "react" import * as SeparatorPrimitive from "@radix-ui/react-separator" import { cn } from "@/lib/utils" const Separator = React.forwardRef< React.ElementRef<typeof SeparatorPrimitive.Root>, React.ComponentPropsWithoutRef<typeof SeparatorPrimitive.Root> >( ( { className, orientation = "horizontal", decorative = true, ...props }, ref ) => ( <SeparatorPrimitive.Root ref={ref} decorative={decorative} orientation={orientation} className={cn( "shrink-0 bg-border", orientation === "horizontal" ? "h-[1px] w-full" : "h-full w-[1px]", className )} {...props} /> ) ) Separator.displayName = SeparatorPrimitive.Root.displayName export { Separator }
wong2/browser-firewall
44
Block any extension or website from accessing network
TypeScript
wong2
wong2
src/global.css
CSS
@tailwind base; @tailwind components; @tailwind utilities; @layer base { :root { --background: 0 0% 100%; --foreground: 222.2 84% 4.9%; --card: 0 0% 100%; --card-foreground: 222.2 84% 4.9%; --popover: 0 0% 100%; --popover-foreground: 222.2 84% 4.9%; --primary: 222.2 47.4% 11.2%; --primary-foreground: 210 40% 98%; --secondary: 210 40% 96.1%; --secondary-foreground: 222.2 47.4% 11.2%; --muted: 210 40% 96.1%; --muted-foreground: 215.4 16.3% 46.9%; --accent: 210 40% 96.1%; --accent-foreground: 222.2 47.4% 11.2%; --destructive: 0 84.2% 60.2%; --destructive-foreground: 210 40% 98%; --border: 214.3 31.8% 91.4%; --input: 214.3 31.8% 91.4%; --ring: 222.2 84% 4.9%; --radius: 0.5rem; } .dark { --background: 222.2 84% 4.9%; --foreground: 210 40% 98%; --card: 222.2 84% 4.9%; --card-foreground: 210 40% 98%; --popover: 222.2 84% 4.9%; --popover-foreground: 210 40% 98%; --primary: 210 40% 98%; --primary-foreground: 222.2 47.4% 11.2%; --secondary: 217.2 32.6% 17.5%; --secondary-foreground: 210 40% 98%; --muted: 217.2 32.6% 17.5%; --muted-foreground: 215 20.2% 65.1%; --accent: 217.2 32.6% 17.5%; --accent-foreground: 210 40% 98%; --destructive: 0 62.8% 30.6%; --destructive-foreground: 210 40% 98%; --border: 217.2 32.6% 17.5%; --input: 217.2 32.6% 17.5%; --ring: 212.7 26.8% 83.9%; } } @layer base { * { @apply border-border; } body { @apply bg-background text-foreground; } }
wong2/browser-firewall
44
Block any extension or website from accessing network
TypeScript
wong2
wong2
src/lib/rules.ts
TypeScript
import Browser from "webextension-polyfill"; import { last } from "remeda"; const RULE_ID = 1; const EXT_ID_REGEX = /[a-p0-9]{32}/; async function getBlockedDomains() { const rules = await Browser.declarativeNetRequest.getDynamicRules(); return rules.flatMap((rule) => { return rule.condition.initiatorDomains || []; }); } async function updateRules(blockedDomains: string[]) { if (blockedDomains.length === 0) { return Browser.declarativeNetRequest.updateDynamicRules({ removeRuleIds: [RULE_ID], }); } return Browser.declarativeNetRequest.updateDynamicRules({ removeRuleIds: [RULE_ID], addRules: [ { id: RULE_ID, action: { type: "block" }, condition: { initiatorDomains: blockedDomains, resourceTypes: [ "main_frame", "sub_frame", "stylesheet", "script", "image", "object", "xmlhttprequest", "font", "media", "websocket", "csp_report", "other", ], }, }, ], }); } export async function block(domain: string) { const blockedDomains = new Set(await getBlockedDomains()); blockedDomains.add(domain); await updateRules(Array.from(blockedDomains)); } export async function unblock(domain: string) { const blockedDomains = new Set(await getBlockedDomains()); blockedDomains.delete(domain); await updateRules(Array.from(blockedDomains)); } export type BlockedItem = | { type: "domain"; value: string; } | { type: "extension"; value: string; name: string; icon?: string; }; export async function getBlockedItems(): Promise<BlockedItem[]> { const rules = await Browser.declarativeNetRequest.getDynamicRules(); const rawsItems = rules.flatMap((rule) => { const initiatorDomains = rule.condition.initiatorDomains || []; return initiatorDomains.map((domain) => ({ type: EXT_ID_REGEX.test(domain) ? "extension" : "domain", value: domain, })); }); return Promise.all( rawsItems.map(async (item) => { if (item.type === "domain") { return { type: "domain", value: item.value }; } const ext = await Browser.management.get(item.value); return { type: "extension", value: ext.id, name: ext.name, icon: ext.icons && last(ext.icons)?.url, }; }) ); }
wong2/browser-firewall
44
Block any extension or website from accessing network
TypeScript
wong2
wong2
src/lib/utils.ts
TypeScript
import { type ClassValue, clsx } from "clsx"; import { twMerge } from "tailwind-merge"; export function cn(...inputs: ClassValue[]) { return twMerge(clsx(inputs)); } export function getFaviconUrl(domain: string) { return `https://www.google.com/s2/favicons?domain=${domain}&sz=${128}`; }
wong2/browser-firewall
44
Block any extension or website from accessing network
TypeScript
wong2
wong2
src/main.tsx
TypeScript (TSX)
import { render } from "preact"; import { RouterProvider, createHashRouter } from "react-router-dom"; import "./global.css"; import OptionsPage, { loadAll as loadOptionsData } from "./routes/Options"; const router = createHashRouter([ { path: "/", element: <OptionsPage />, loader: () => loadOptionsData(), }, ]); render(<RouterProvider router={router} />, document.getElementById("app")!);
wong2/browser-firewall
44
Block any extension or website from accessing network
TypeScript
wong2
wong2
src/routes/Options.tsx
TypeScript (TSX)
import BlockForm from "@/components/BlockForm"; import icon from "@/assets/icon.png"; import BlockedItemCard from "@/components/BlockedItemCard"; import { Card, CardContent } from "@/components/ui/card"; import { Separator } from "@/components/ui/separator"; import { BlockedItem, getBlockedItems } from "@/lib/rules"; import { useLoaderData } from "react-router-dom"; import Browser from "webextension-polyfill"; import { Extension } from "../types"; type LoaderData = { extensions: Extension[]; blockedItems: BlockedItem[]; }; export async function loadAll(): Promise<LoaderData> { const [exts, blockedItems] = await Promise.all([Browser.management.getAll(), getBlockedItems()]); return { extensions: exts.filter((ext) => ext.installType === "normal" && ext.enabled), blockedItems, }; } function OptionsPage() { const { extensions, blockedItems } = useLoaderData() as LoaderData; return ( <div className="px-10 py-5 container"> <div className="flex flex-row items-center gap-4 pb-8"> <img src={icon} className="w-6 h-6 rounded" /> <h1 className="font-black text-2xl">Browser Firewall</h1> </div> {blockedItems.length > 0 && ( <> <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4"> {blockedItems.map((item) => ( <BlockedItemCard item={item} key={item.value} /> ))} </div> <Separator className="my-8" /> </> )} <Card className="max-w-[500px] pt-8"> <CardContent> <BlockForm extensions={extensions} /> </CardContent> </Card> </div> ); } export default OptionsPage;
wong2/browser-firewall
44
Block any extension or website from accessing network
TypeScript
wong2
wong2
src/types.ts
TypeScript
import type Browser from "webextension-polyfill"; export type Extension = Browser.Management.ExtensionInfo;
wong2/browser-firewall
44
Block any extension or website from accessing network
TypeScript
wong2
wong2
src/vite-env.d.ts
TypeScript
/// <reference types="vite/client" />
wong2/browser-firewall
44
Block any extension or website from accessing network
TypeScript
wong2
wong2
tailwind.config.js
JavaScript
/** @type {import('tailwindcss').Config} */ module.exports = { darkMode: ["class"], content: [ './pages/**/*.{ts,tsx}', './components/**/*.{ts,tsx}', './app/**/*.{ts,tsx}', './src/**/*.{ts,tsx}', ], theme: { container: { center: true, padding: "2rem", screens: { "2xl": "1400px", }, }, extend: { colors: { border: "hsl(var(--border))", input: "hsl(var(--input))", ring: "hsl(var(--ring))", background: "hsl(var(--background))", foreground: "hsl(var(--foreground))", primary: { DEFAULT: "hsl(var(--primary))", foreground: "hsl(var(--primary-foreground))", }, secondary: { DEFAULT: "hsl(var(--secondary))", foreground: "hsl(var(--secondary-foreground))", }, destructive: { DEFAULT: "hsl(var(--destructive))", foreground: "hsl(var(--destructive-foreground))", }, muted: { DEFAULT: "hsl(var(--muted))", foreground: "hsl(var(--muted-foreground))", }, accent: { DEFAULT: "hsl(var(--accent))", foreground: "hsl(var(--accent-foreground))", }, popover: { DEFAULT: "hsl(var(--popover))", foreground: "hsl(var(--popover-foreground))", }, card: { DEFAULT: "hsl(var(--card))", foreground: "hsl(var(--card-foreground))", }, }, borderRadius: { lg: "var(--radius)", md: "calc(var(--radius) - 2px)", sm: "calc(var(--radius) - 4px)", }, keyframes: { "accordion-down": { from: { height: 0 }, to: { height: "var(--radix-accordion-content-height)" }, }, "accordion-up": { from: { height: "var(--radix-accordion-content-height)" }, to: { height: 0 }, }, }, animation: { "accordion-down": "accordion-down 0.2s ease-out", "accordion-up": "accordion-up 0.2s ease-out", }, }, }, plugins: [require("tailwindcss-animate")], }
wong2/browser-firewall
44
Block any extension or website from accessing network
TypeScript
wong2
wong2
vite.config.ts
TypeScript
import { defineConfig } from "vite"; import preact from "@preact/preset-vite"; import { crx } from "@crxjs/vite-plugin"; import tsconfigPaths from "vite-tsconfig-paths"; import manifest from "./manifest.config"; // https://vitejs.dev/config/ export default defineConfig(({ mode }) => { return { plugins: [tsconfigPaths(), preact(), crx({ manifest })], esbuild: { drop: mode === "production" ? ["console", "debugger"] : [], }, server: { strictPort: true, port: 5174, hmr: { clientPort: 5174, }, }, }; });
wong2/browser-firewall
44
Block any extension or website from accessing network
TypeScript
wong2
wong2
example.ts
TypeScript
import { z } from "zod"; import { LiteMCP } from "./src/index.js"; const server = new LiteMCP("my-mcp", "1.0.0"); server.addTool({ name: "add", description: "Add two numbers", parameters: z.object({ a: z.number(), b: z.number(), }), execute: async (args) => { server.logger.debug("Adding two numbers", args); return args.a + args.b; }, }); server.addResource({ uri: "file:///logs/app.log", name: "Application Logs", mimeType: "text/plain", async load() { return { text: "Example log content", }; }, }); server.addPrompt({ name: "git-commit", description: "Generate a Git commit message", arguments: [ { name: "changes", description: "Git diff or description of changes", required: true, }, ], load: async (args) => { return `Generate a concise but descriptive commit message for these changes:\n\n${args.changes}`; }, }); server.start();
wong2/litemcp
185
A TypeScript framework for building MCP servers elegantly
TypeScript
wong2
wong2
src/cli/dev.ts
TypeScript
import { defineCommand } from "citty"; import { $ } from "execa"; export default defineCommand({ meta: { name: "dev", description: "Run server with mcp-cli", }, args: { script: { type: "positional", description: "The JavaScript or TypeScript script to run", valueHint: "server.js or server.ts", required: true, }, }, async run({ args }) { const command = args.script.endsWith(".ts") ? ["npx", "tsx", args.script] : ["node", args.script]; await $({ stdin: "inherit", stdout: "inherit", stderr: "inherit", })`npx @wong2/mcp-cli ${command}`; }, });
wong2/litemcp
185
A TypeScript framework for building MCP servers elegantly
TypeScript
wong2
wong2
src/cli/index.ts
TypeScript
#!/usr/bin/env node import { defineCommand, runMain } from "citty"; import dev from "./dev.js"; import inspect from "./inspect.js"; const main = defineCommand({ meta: { name: "litemcp", }, subCommands: { dev, inspect, }, }); runMain(main);
wong2/litemcp
185
A TypeScript framework for building MCP servers elegantly
TypeScript
wong2
wong2
src/cli/inspect.ts
TypeScript
import { defineCommand } from "citty"; import { execa } from "execa"; export default defineCommand({ meta: { name: "inspect", description: "Run server with MCP inspector", }, args: { script: { type: "positional", description: "The js script to run", valueHint: "server.js", required: true, }, }, async run({ args }) { await execa({ stdout: "inherit", stderr: "inherit", })`npx @modelcontextprotocol/inspector node ${args.script}`; }, });
wong2/litemcp
185
A TypeScript framework for building MCP servers elegantly
TypeScript
wong2
wong2
src/index.ts
TypeScript
import { Server } from "@modelcontextprotocol/sdk/server/index.js"; import { startSSEServer, type SSEServer } from "mcp-proxy"; import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"; import { CallToolRequestSchema, ErrorCode, GetPromptRequestSchema, ListPromptsRequestSchema, ListResourcesRequestSchema, ListToolsRequestSchema, McpError, ReadResourceRequestSchema, ServerCapabilities, } from "@modelcontextprotocol/sdk/types.js"; import { zodToJsonSchema } from "zod-to-json-schema"; import { Logger } from "./logger.js"; import { Prompt, PromptArgument, Resource, Tool, ToolParameters } from "./types.js"; export class LiteMCP { public logger: Logger; #tools: Tool[]; #resources: Resource[]; #prompts: Prompt[]; constructor(public name: string, public version: string) { this.logger = new Logger(); this.#tools = []; this.#resources = []; this.#prompts = []; } private setupHandlers(server: Server) { this.setupErrorHandling(server); if (this.#tools.length) { this.setupToolHandlers(server); } if (this.#resources.length) { this.setupResourceHandlers(server); } if (this.#prompts.length) { this.setupPromptHandlers(server); } } private setupErrorHandling(server: Server) { server.onerror = (error) => { console.error("[MCP Error]", error); }; process.on("SIGINT", async () => { await server.close(); process.exit(0); }); } private setupToolHandlers(server: Server) { server.setRequestHandler(ListToolsRequestSchema, async () => { return { tools: this.#tools.map((tool) => { return { name: tool.name, description: tool.description, inputSchema: tool.parameters ? zodToJsonSchema(tool.parameters) : undefined, }; }), }; }); server.setRequestHandler(CallToolRequestSchema, async (request) => { const tool = this.#tools.find((tool) => tool.name === request.params.name); if (!tool) { throw new McpError(ErrorCode.MethodNotFound, `Unknown tool: ${request.params.name}`); } let args: any = undefined; if (tool.parameters) { const parsed = tool.parameters.safeParse(request.params.arguments); if (!parsed.success) { throw new McpError(ErrorCode.InvalidRequest, `Invalid ${request.params.name} arguments`); } args = parsed.data; } let result: any; try { result = await tool.execute(args); } catch (error) { return { content: [{ type: "text", text: `Error: ${error}` }], isError: true, }; } if (typeof result === "string") { return { content: [{ type: "text", text: result }], }; } return { content: [{ type: "text", text: JSON.stringify(result, null, 2) }], }; }); } private setupResourceHandlers(server: Server) { server.setRequestHandler(ListResourcesRequestSchema, async () => { return { resources: this.#resources.map((resource) => { return { uri: resource.uri, name: resource.name, mimeType: resource.mimeType, }; }), }; }); server.setRequestHandler(ReadResourceRequestSchema, async (request) => { const resource = this.#resources.find((resource) => resource.uri === request.params.uri); if (!resource) { throw new McpError(ErrorCode.MethodNotFound, `Unknown resource: ${request.params.uri}`); } let result: Awaited<ReturnType<Resource["load"]>>; try { result = await resource.load(); } catch (error) { throw new McpError(ErrorCode.InternalError, `Error reading resource: ${error}`, { uri: resource.uri, }); } return { contents: [ { uri: resource.uri, mimeType: resource.mimeType, ...result, }, ], }; }); } private setupPromptHandlers(server: Server) { server.setRequestHandler(ListPromptsRequestSchema, async () => { return { prompts: this.#prompts.map((prompt) => { return { name: prompt.name, description: prompt.description, arguments: prompt.arguments, }; }), }; }); server.setRequestHandler(GetPromptRequestSchema, async (request) => { const prompt = this.#prompts.find((prompt) => prompt.name === request.params.name); if (!prompt) { throw new McpError(ErrorCode.MethodNotFound, `Unknown prompt: ${request.params.name}`); } const args = request.params.arguments; if (prompt.arguments) { for (const arg of prompt.arguments) { if (arg.required && !(args && arg.name in args)) { throw new McpError(ErrorCode.InvalidRequest, `Missing required argument: ${arg.name}`); } } } let result: Awaited<ReturnType<Prompt["load"]>>; try { result = await prompt.load(args as Record<string, string | undefined>); } catch (error) { throw new McpError(ErrorCode.InternalError, `Error loading prompt: ${error}`); } return { description: prompt.description, messages: [ { role: "user", content: { type: "text", text: result }, }, ], }; }); } public addTool<Params extends ToolParameters>(tool: Tool<Params>) { this.#tools.push(tool as unknown as Tool); } public addResource(resource: Resource) { this.#resources.push(resource); } public addPrompt<const Args extends PromptArgument[]>(prompt: Prompt<Args>) { this.#prompts.push(prompt); } public async start( opts: | { transportType: "stdio" } | { transportType: "sse"; sse: { endpoint: `/${string}`; port: number }; } = { transportType: "stdio", } ) { const capabilities: ServerCapabilities = { logging: {} }; if (this.#tools.length) { capabilities.tools = {}; } if (this.#resources.length) { capabilities.resources = {}; } if (this.#prompts.length) { capabilities.prompts = {}; } const server = new Server({ name: this.name, version: this.version }, { capabilities }); this.logger.setServer(server); this.setupHandlers(server); if (opts.transportType === "stdio") { const transport = new StdioServerTransport(); await server.connect(transport); console.error(`${this.name} server running on stdio`); } else if (opts.transportType === "sse") { await startSSEServer({ endpoint: opts.sse.endpoint as `/${string}`, port: opts.sse.port, createServer: async () => { return server; }, }); console.error(`${this.name} server running on SSE`); } } }
wong2/litemcp
185
A TypeScript framework for building MCP servers elegantly
TypeScript
wong2
wong2
src/logger.ts
TypeScript
import type { Jsonifiable, JsonValue } from "type-fest"; import type { Server } from "@modelcontextprotocol/sdk/server/index.js"; export class Logger { #server?: Server; private sendLoggingMessage(level: "debug" | "info" | "warning" | "error", data: Jsonifiable) { this.#server?.sendLoggingMessage({ level, data, }); } public setServer(server: Server) { this.#server = server; } public debug(message: string, context?: JsonValue) { this.sendLoggingMessage("debug", { message, context }); } public info(message: string, context?: JsonValue) { this.sendLoggingMessage("info", { message, context }); } public warn(message: string, context?: JsonValue) { this.sendLoggingMessage("warning", { message, context }); } public error(message: string, context?: JsonValue) { this.sendLoggingMessage("error", { message, context }); } }
wong2/litemcp
185
A TypeScript framework for building MCP servers elegantly
TypeScript
wong2
wong2
src/types.ts
TypeScript
import type { z } from "zod"; export type ToolParameters = z.ZodTypeAny; export interface Tool<Params extends ToolParameters = ToolParameters> { name: string; description?: string; parameters?: Params; execute: (args: z.infer<Params>) => Promise<any>; } export interface Resource { uri: string; name: string; description?: string; mimeType?: string; load: () => Promise<{ text: string } | { blob: string }>; } export type PromptArgument = Readonly<{ name: string; description?: string; required?: boolean; }>; type ArgumentsToObject<T extends PromptArgument[]> = { [K in T[number]["name"]]: Extract<T[number], { name: K }>["required"] extends true ? string : string | undefined; }; export interface Prompt< Arguments extends PromptArgument[] = PromptArgument[], Args = ArgumentsToObject<Arguments> > { name: string; description?: string; arguments?: Arguments; load: (args: Args) => Promise<string>; }
wong2/litemcp
185
A TypeScript framework for building MCP servers elegantly
TypeScript
wong2
wong2
src/errors.ts
TypeScript
export class MoltbookError extends Error { readonly name = "MoltbookError"; readonly status: number; readonly statusText: string; readonly method: string; readonly url: string; readonly body: unknown; constructor(args: { message: string; status: number; statusText: string; method: string; url: string; body: unknown; }) { super(args.message); this.status = args.status; this.statusText = args.statusText; this.method = args.method; this.url = args.url; this.body = args.body; } }
wong2/moltbook-ts
4
Moltbook TypeScript SDK
TypeScript
wong2
wong2
src/index.ts
TypeScript
export { Moltbook } from "./moltbook"; export { MoltbookError } from "./errors"; export type { MoltbookOptions } from "./moltbook"; export type { AddCommentRequest, AgentOwner, AgentProfile, AgentProfileResponse, AgentStatusResponse, ApiSuccess, ClaimStatus, Comment, CreateAnyPostRequest, CreateLinkPostRequest, CreatePostRequest, CreateSubmoltRequest, GetCommentsParams, GetFeedParams, GetPostsParams, ISODateString, JsonObject, JsonPrimitive, JsonValue, Post, SearchParams, SearchResponse, SearchResult, SearchType, SortComments, SortFeed, SortPosts, Submolt, SubmoltRef, UpdateAgentRequest, UploadData, UploadFileInput, VoteResponse, } from "./types";
wong2/moltbook-ts
4
Moltbook TypeScript SDK
TypeScript
wong2
wong2
src/moltbook.ts
TypeScript
import { MoltbookError } from "./errors"; import type { AddCommentRequest, AgentProfileResponse, AgentStatusResponse, ApiSuccess, Comment, CreateLinkPostRequest, CreateAnyPostRequest, CreatePostRequest, CreateSubmoltRequest, GetCommentsParams, GetFeedParams, GetPostsParams, JsonObject, Post, SearchParams, SearchResponse, Submolt, UpdateAgentRequest, UploadFileInput, VoteResponse, } from "./types"; type QueryValue = string | number | boolean | null | undefined; type QueryRecord = Record<string, QueryValue>; export interface MoltbookOptions { apiKey: string; } function toQueryString(query: QueryRecord | undefined): string { if (!query) return ""; const params = new URLSearchParams(); for (const [k, v] of Object.entries(query)) { if (v === undefined || v === null) continue; params.set(k, String(v)); } const s = params.toString(); return s ? `?${s}` : ""; } function isBlob(value: unknown): value is Blob { return typeof Blob !== "undefined" && value instanceof Blob; } function toArrayBufferCopy(u8: Uint8Array): ArrayBuffer { const ab = new ArrayBuffer(u8.byteLength); new Uint8Array(ab).set(u8); return ab; } function toBlob(data: ArrayBuffer | Uint8Array, contentType?: string): Blob { if (typeof Blob === "undefined") { throw new Error( "Blob is not available in this runtime. Use Node 18+ / modern browsers, or pass a Blob directly." ); } const blobPart: ArrayBuffer = data instanceof Uint8Array ? toArrayBufferCopy(data) : data; return new Blob([blobPart], contentType ? { type: contentType } : undefined); } function toFormData(file: UploadFileInput | Blob): FormData { if (typeof FormData === "undefined") { throw new Error( "FormData is not available in this runtime. Use Node 18+ / modern browsers, or provide a fetch/FormData polyfill." ); } const fd = new FormData(); if (isBlob(file)) { // Some servers accept missing filename; we provide a stable default. fd.append("file", file, "avatar"); return fd; } const blob = isBlob(file.data) ? file.data : toBlob(file.data, file.contentType); fd.append("file", blob, file.filename); return fd; } export class Moltbook { private readonly apiKey: string; private readonly baseUrl: string; private readonly fetchImpl: typeof fetch; constructor(opts: MoltbookOptions) { this.apiKey = opts.apiKey; this.baseUrl = "https://www.moltbook.com/api/v1"; this.fetchImpl = globalThis.fetch; if (!this.fetchImpl) { throw new Error( "No fetch implementation found. Use a runtime that provides global fetch (Node 18+ / modern browsers)." ); } } private async request<T>(args: { method: string; path: string; query?: QueryRecord; body?: JsonObject | unknown; formData?: FormData; }): Promise<T> { const url = `${this.baseUrl}${args.path}${toQueryString(args.query)}`; const headers = new Headers(); headers.set("Authorization", `Bearer ${this.apiKey}`); let body: BodyInit | undefined = undefined; if (args.formData) { body = args.formData; // Let fetch set multipart boundary automatically. } else if (args.body !== undefined) { body = JSON.stringify(args.body); if (!headers.has("Content-Type")) headers.set("Content-Type", "application/json"); } const res = await this.fetchImpl(url, { method: args.method, headers, body, }); if (res.status === 204) return undefined as T; const contentType = res.headers.get("content-type") ?? ""; const isJson = contentType.includes("application/json"); const parsedBody = isJson ? await res.json().catch(() => undefined) : await res.text().catch(() => undefined); if (!res.ok) { const msg = `Moltbook API error ${res.status} ${res.statusText}`; throw new MoltbookError({ message: msg, status: res.status, statusText: res.statusText, method: args.method, url, body: parsedBody, }); } return parsedBody as T; } // Agents getMe(): Promise<AgentProfileResponse> { return this.getProfile(); } getProfile(): Promise<AgentProfileResponse> { return this.request({ method: "GET", path: "/agents/me" }); } getClaimStatus(): Promise<AgentStatusResponse> { return this.request({ method: "GET", path: "/agents/status" }); } getAgentProfile(name: string): Promise<AgentProfileResponse> { return this.request({ method: "GET", path: "/agents/profile", query: { name } }); } updateProfile(body: UpdateAgentRequest): Promise<AgentProfileResponse> { return this.request({ method: "PATCH", path: "/agents/me", body: body as JsonObject }); } uploadAvatar(file: UploadFileInput | Blob): Promise<ApiSuccess> { return this.request({ method: "POST", path: "/agents/me/avatar", formData: toFormData(file), }); } removeAvatar(): Promise<ApiSuccess> { return this.request({ method: "DELETE", path: "/agents/me/avatar" }); } followAgent(name: string): Promise<ApiSuccess> { return this.request({ method: "POST", path: `/agents/${encodeURIComponent(name)}/follow` }); } unfollowAgent(name: string): Promise<ApiSuccess> { return this.request({ method: "DELETE", path: `/agents/${encodeURIComponent(name)}/follow`, }); } // Posts createTextPost(body: CreatePostRequest): Promise<Post> { return this.createPost(body); } createLinkPost(body: CreateLinkPostRequest): Promise<Post> { return this.createPost(body); } createPost(body: CreateAnyPostRequest): Promise<Post> { return this.request({ method: "POST", path: "/posts", body: body as unknown as JsonObject }); } getPosts(params?: GetPostsParams): Promise<Post[]> { return this.request({ method: "GET", path: "/posts", query: params ? { sort: params.sort, limit: params.limit, submolt: params.submolt } : undefined, }); } getSubmoltFeed( submoltName: string, params?: Omit<GetPostsParams, "submolt"> ): Promise<Post[]> { return this.request({ method: "GET", path: `/submolts/${encodeURIComponent(submoltName)}/feed`, query: params ? { sort: params.sort, limit: params.limit } : undefined, }); } getPost(postId: string): Promise<Post> { return this.request({ method: "GET", path: `/posts/${encodeURIComponent(postId)}` }); } deletePost(postId: string): Promise<ApiSuccess> { return this.request({ method: "DELETE", path: `/posts/${encodeURIComponent(postId)}` }); } // Comments addComment(postId: string, body: AddCommentRequest): Promise<Comment> { return this.request({ method: "POST", path: `/posts/${encodeURIComponent(postId)}/comments`, body: body as unknown as JsonObject, }); } getComments(postId: string, params?: GetCommentsParams): Promise<Comment[]> { return this.request({ method: "GET", path: `/posts/${encodeURIComponent(postId)}/comments`, query: params ? { sort: params.sort } : undefined, }); } // Voting upvotePost(postId: string): Promise<VoteResponse> { return this.request({ method: "POST", path: `/posts/${encodeURIComponent(postId)}/upvote` }); } downvotePost(postId: string): Promise<VoteResponse> { return this.request({ method: "POST", path: `/posts/${encodeURIComponent(postId)}/downvote`, }); } upvoteComment(commentId: string): Promise<VoteResponse> { return this.request({ method: "POST", path: `/comments/${encodeURIComponent(commentId)}/upvote`, }); } // Submolts createSubmolt(body: CreateSubmoltRequest): Promise<{ success: true; submolt: Submolt } | ApiSuccess> { return this.request({ method: "POST", path: "/submolts", body: body as unknown as JsonObject, }); } listSubmolts(): Promise<{ success: true; submolts: Submolt[] } | Submolt[] | ApiSuccess> { return this.request({ method: "GET", path: "/submolts" }); } getSubmolt(name: string): Promise<{ success: true; submolt: Submolt } | Submolt | ApiSuccess> { return this.request({ method: "GET", path: `/submolts/${encodeURIComponent(name)}` }); } subscribeToSubmolt(name: string): Promise<ApiSuccess> { return this.request({ method: "POST", path: `/submolts/${encodeURIComponent(name)}/subscribe`, }); } unsubscribeFromSubmolt(name: string): Promise<ApiSuccess> { return this.request({ method: "DELETE", path: `/submolts/${encodeURIComponent(name)}/subscribe`, }); } // Personalized feed getFeed(params?: GetFeedParams): Promise<Post[]> { return this.request({ method: "GET", path: "/feed", query: params ? { sort: params.sort, limit: params.limit } : undefined, }); } // Semantic search search(params: SearchParams): Promise<SearchResponse> { return this.request({ method: "GET", path: "/search", query: { q: params.q, type: params.type, limit: params.limit }, }); } }
wong2/moltbook-ts
4
Moltbook TypeScript SDK
TypeScript
wong2
wong2
src/types.ts
TypeScript
export type ISODateString = string; export type SortPosts = "hot" | "new" | "top" | "rising"; export type SortFeed = "hot" | "new" | "top"; export type SortComments = "top" | "new" | "controversial"; export type ClaimStatus = "pending_claim" | "claimed"; export type SearchType = "posts" | "comments" | "all"; export type JsonPrimitive = string | number | boolean | null; export type JsonValue = JsonPrimitive | JsonObject | JsonValue[]; export type JsonObject = { [key: string]: JsonValue }; export interface ApiSuccess { success: boolean; message?: string; } export interface AuthorRef { name: string; } export interface SubmoltRef { name: string; display_name?: string; } export interface AgentOwner { x_handle?: string; x_name?: string; x_avatar?: string; x_bio?: string; x_follower_count?: number; x_following_count?: number; x_verified?: boolean; } export interface AgentProfile { name: string; description?: string | null; karma?: number; follower_count?: number; following_count?: number; is_claimed?: boolean; is_active?: boolean; created_at?: ISODateString; last_active?: ISODateString; owner?: AgentOwner; } export interface Post { id: string; title: string; content?: string | null; url?: string | null; upvotes?: number; downvotes?: number; created_at?: ISODateString; author?: AuthorRef; submolt?: SubmoltRef; // Allow forward-compatible fields without losing type safety for known ones. [key: string]: unknown; } export interface Comment { id: string; content: string; post_id?: string; parent_id?: string | null; upvotes?: number; downvotes?: number; created_at?: ISODateString; author?: AuthorRef; [key: string]: unknown; } export interface Submolt { name: string; display_name?: string; description?: string; created_at?: ISODateString; [key: string]: unknown; } export interface AgentStatusResponse { status: ClaimStatus; } export interface AgentProfileResponse extends ApiSuccess { agent: AgentProfile; recentPosts?: Post[]; } export interface VoteResponse extends ApiSuccess { author?: AuthorRef; already_following?: boolean; suggestion?: string; } export interface CreatePostRequest { submolt: string; title: string; content: string; } export interface CreateLinkPostRequest { submolt: string; title: string; url: string; } export type CreateAnyPostRequest = CreatePostRequest | CreateLinkPostRequest; export interface AddCommentRequest { content: string; parent_id?: string; } export interface CreateSubmoltRequest { name: string; display_name: string; description: string; } export interface UpdateAgentRequest { description?: string; metadata?: JsonObject; } export type UploadData = Blob | ArrayBuffer | Uint8Array; export interface UploadFileInput { data: UploadData; filename: string; contentType?: string; } export interface GetPostsParams { sort?: SortPosts; limit?: number; submolt?: string; } export interface GetCommentsParams { sort?: SortComments; } export interface GetFeedParams { sort?: SortFeed; limit?: number; } export interface SearchParams { q: string; type?: SearchType; limit?: number; } export type SearchResult = | { id: string; type: "post"; title: string; content?: string | null; upvotes?: number; downvotes?: number; created_at?: ISODateString; similarity: number; author?: AuthorRef; submolt?: SubmoltRef; post_id: string; [key: string]: unknown; } | { id: string; type: "comment"; title: null; content: string; upvotes?: number; downvotes?: number; created_at?: ISODateString; similarity: number; author?: AuthorRef; post?: { id: string; title: string }; post_id: string; [key: string]: unknown; }; export interface SearchResponse extends ApiSuccess { query: string; type: SearchType; results: SearchResult[]; count: number; }
wong2/moltbook-ts
4
Moltbook TypeScript SDK
TypeScript
wong2
wong2
tsdown.config.ts
TypeScript
import { defineConfig } from "tsdown"; export default defineConfig({ entry: ["src/index.ts"], format: ["esm", "cjs"], outDir: "dist", sourcemap: true, dts: true, clean: true, exports: true, });
wong2/moltbook-ts
4
Moltbook TypeScript SDK
TypeScript
wong2
wong2
build.rs
Rust
use std::env; use std::process::Command; fn main() { let mut version = String::from(env!("CARGO_PKG_VERSION")); if let Some(commit_hash) = commit_hash() { version = format!("{version} ({commit_hash})"); } println!("cargo:rustc-env=KBS2_BUILD_VERSION={version}"); } // Cribbed from Alacritty: // https://github.com/alacritty/alacritty/blob/8ea6c3b/alacritty/build.rs fn commit_hash() -> Option<String> { Command::new("git") .args(["rev-parse", "--short", "HEAD"]) .output() .ok() .filter(|output| output.status.success()) .and_then(|output| String::from_utf8(output.stdout).ok()) .map(|hash| hash.trim().into()) }
woodruffw/kbs2
126
A secret manager backed by age
Rust
woodruffw
William Woodruff
astral-sh