import { createServer } from 'http' import { readFile, readdir, writeFile } from 'fs/promises' import { existsSync } from 'fs' import { join, extname } from 'path' import { fileURLToPath } from 'url' import { dirname } from 'path' const __dirname = dirname(fileURLToPath(import.meta.url)) const ROOT = '/data/data/com.termux/files/home/.openclaw/workspace/SmallClawViewer' const WORKSPACE = '/data/data/com.termux/files/home/.openclaw/workspace' const PORT = 3001 const MIME = { '.html': 'text/html', '.js': 'application/javascript', '.css': 'text/css', '.json': 'application/json', '.md': 'text/markdown', '.png': 'image/png', '.jpg': 'image/jpeg', } const server = createServer(async (req, res) => { const url = req.url.split('?')[0] // API: list projects from workspace PROJECTS.md if (url === '/api/projects') { res.setHeader('Content-Type', 'application/json') try { const content = await readFile(join(WORKSPACE, 'PROJECTS.md'), 'utf-8') res.end(JSON.stringify(parseProjects(content))) } catch { res.end(JSON.stringify([])) } return } // API: list workspace files if (url.startsWith('/api/files')) { const qs = new URLSearchParams(req.url.split('?')[1] || '') const dir = qs.get('dir') || '' const targetDir = dir ? join(WORKSPACE, decodeURIComponent(dir)) : WORKSPACE if (!targetDir.startsWith(WORKSPACE)) { res.statusCode = 403 res.setHeader('Content-Type', 'application/json') res.end(JSON.stringify({ error: 'Forbidden' })) return } res.setHeader('Content-Type', 'application/json') try { res.end(JSON.stringify(await listFiles(targetDir, decodeURIComponent(dir) || ''))) } catch { res.statusCode = 404 res.end(JSON.stringify({ error: 'Directory not found' })) } return } // API: read a file const fileMatch = url.match(/^\/api\/file\/(.+)$/) if (fileMatch && req.method === 'GET') { const filePath = join(WORKSPACE, decodeURIComponent(fileMatch[1])) if (!filePath.startsWith(WORKSPACE)) { res.statusCode = 403 res.end('Forbidden') return } try { const content = await readFile(filePath, 'utf-8') res.setHeader('Content-Type', 'text/plain') res.end(content) } catch { res.statusCode = 404 res.end('Not found') } return } // API: write a file if (fileMatch && req.method === 'PUT') { const filePath = join(WORKSPACE, decodeURIComponent(fileMatch[1])) if (!filePath.startsWith(WORKSPACE)) { res.statusCode = 403 res.end('Forbidden') return } let body = '' req.on('data', chunk => body += chunk) req.on('end', async () => { try { await writeFile(filePath, body, 'utf-8') res.setHeader('Content-Type', 'application/json') res.end(JSON.stringify({ ok: true })) } catch (e) { res.statusCode = 500 res.setHeader('Content-Type', 'application/json') res.end(JSON.stringify({ ok: false, error: e.message })) } }) return } // Serve static files let filePath = url === '/' ? 'index.html' : url filePath = join(ROOT, filePath) const ext = extname(filePath) const contentType = MIME[ext] || 'text/plain' try { const content = await readFile(filePath) res.setHeader('Content-Type', contentType) res.end(content) } catch { // Fallback to index.html for SPA routing try { const content = await readFile(join(ROOT, 'index.html')) res.setHeader('Content-Type', 'text/html') res.end(content) } catch { res.statusCode = 404 res.end('Not found') } } }) async function listFiles(dir, base = '') { if (!existsSync(dir)) return [] const entries = await readdir(dir, { withFileTypes: true }) const files = [] for (const entry of entries) { if (entry.name === 'node_modules' || entry.name.startsWith('.')) continue const rel = base ? base + '/' + entry.name : entry.name files.push({ name: entry.name, type: entry.isDirectory() ? 'dir' : 'file', path: rel, ext: entry.isDirectory() ? null : extname(entry.name) }) } return files.sort((a, b) => { if (a.type !== b.type) return a.type === 'dir' ? -1 : 1 return a.name.localeCompare(b.name) }) } function parseProjects(content) { const projects = [] let headerSeen = false for (const line of content.split('\n')) { if (!line.includes('|') || line.startsWith('#')) continue // Skip header separator lines like |---|---|---| if (/^\|[- :]+\|/.test(line)) continue const cells = line.split('|').map(c => c.trim()).filter(Boolean) if (cells.length < 3) continue // Skip the actual header row (first row with 3+ cells after any separator) if (!headerSeen) { headerSeen = true continue } const name = cells[0].replace(/^\*+|\*+$/g, '').replace(/`/g, '').trim() const path = cells[1].replace(/^\*+|\*+$/g, '').replace(/`/g, '').trim() const status = cells[2].replace(/^\*+|\*+$/g, '').replace(/`/g, '').trim() projects.push({ name, path, status }) } return projects } server.on('error', (e) => { if (e.code === 'EADDRINUSE') { console.error(`Port ${PORT} is in use, waiting 5s before retry...`) setTimeout(() => { server.listen(PORT, '127.0.0.1') }, 5000) } }) server.listen(PORT, '127.0.0.1', () => { console.log(`SmallClawViewer running at http://127.0.0.1:${PORT}`) })