commit 3f4920a68f9441d017af8de53e4e4dde8e5356ae Author: Jakub Zych Date: Sat Mar 7 23:51:53 2026 +0100 Project Browsers 1.0 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..b8ffe08 --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ +node_modules/ +package-lock.json + diff --git a/lib/centrifugo.js b/lib/centrifugo.js new file mode 100644 index 0000000..197e381 --- /dev/null +++ b/lib/centrifugo.js @@ -0,0 +1,52 @@ +const crypto = require('crypto'); +const http = require('http'); + +const HMAC_SECRET = 'f6aeeb774a009d7b2a2bea348ea23c5f82de55ca38f3f3a2263ecc3cca1314b1'; +const API_KEY = 'f176d279faef1256d209d921e85cd5e27c19ec3b6f057c6829c9ccb18be9af85'; +const CENTRIFUGO_PORT = 8787; +const CHANNEL = 'projects-browser'; + +function createJWT(sub, expSeconds = 86400) { + const header = { alg: 'HS256', typ: 'JWT' }; + const payload = { sub, exp: Math.floor(Date.now() / 1000) + expSeconds }; + const b64 = (obj) => Buffer.from(JSON.stringify(obj)).toString('base64url'); + const h = b64(header); + const p = b64(payload); + const sig = crypto.createHmac('sha256', HMAC_SECRET).update(`${h}.${p}`).digest('base64url'); + return `${h}.${p}.${sig}`; +} + +function publish(data) { + const body = JSON.stringify({ method: 'publish', params: { channel: CHANNEL, data } }); + + const req = http.request({ + hostname: '127.0.0.1', + port: CENTRIFUGO_PORT, + path: '/api', + method: 'POST', + headers: { + 'Content-Type': 'application/json', + 'Authorization': `apikey ${API_KEY}`, + }, + }, (res) => { + // drain response + res.resume(); + }); + + req.on('error', (err) => { + console.error('Centrifugo publish error:', err.message); + }); + + req.write(body); + req.end(); +} + +function publishStatus(slug, status, extra = {}) { + publish({ type: 'status', slug, status, ...extra }); +} + +function publishScreenshot(slug) { + publish({ type: 'screenshot', slug, url: `/screenshots/${slug}.png?t=${Date.now()}` }); +} + +module.exports = { createJWT, publish, publishStatus, publishScreenshot, CHANNEL }; diff --git a/lib/env-parser.js b/lib/env-parser.js new file mode 100644 index 0000000..d912e5c --- /dev/null +++ b/lib/env-parser.js @@ -0,0 +1,30 @@ +const fs = require('fs'); +const path = require('path'); + +function parseEnvFile(filePath) { + const result = {}; + if (!fs.existsSync(filePath)) return result; + + const content = fs.readFileSync(filePath, 'utf8'); + for (const line of content.split('\n')) { + const trimmed = line.trim(); + if (!trimmed || trimmed.startsWith('#')) continue; + + const eqIndex = trimmed.indexOf('='); + if (eqIndex === -1) continue; + + const key = trimmed.slice(0, eqIndex).trim(); + let value = trimmed.slice(eqIndex + 1).trim(); + + // Strip surrounding quotes + if ((value.startsWith('"') && value.endsWith('"')) || + (value.startsWith("'") && value.endsWith("'"))) { + value = value.slice(1, -1); + } + + result[key] = value; + } + return result; +} + +module.exports = { parseEnvFile }; diff --git a/lib/process-manager.js b/lib/process-manager.js new file mode 100644 index 0000000..461637f --- /dev/null +++ b/lib/process-manager.js @@ -0,0 +1,241 @@ +const { spawn, execSync } = require('child_process'); +const net = require('net'); +const EventEmitter = require('events'); + +const processes = new Map(); +const events = new EventEmitter(); + +function key(slug, type) { return `${slug}:${type}`; } + +function createEntry() { + return { child: null, status: 'stopped', logs: [], port: null }; +} + +function getStatus(slug) { + const api = processes.get(key(slug, 'api')); + const frontend = processes.get(key(slug, 'frontend')); + return { + api: api + ? { status: api.status, pid: api.child?.pid || null, logs: api.logs } + : { status: 'stopped', pid: null, logs: [] }, + frontend: frontend + ? { status: frontend.status, pid: frontend.child?.pid || null, logs: frontend.logs } + : null, + }; +} + +function combinedStatus(slug, hasFrontend) { + const s = getStatus(slug); + if (!hasFrontend) return s.api.status; + // Both must be running for "running"; if either is error, "error"; else worst state + const apiSt = s.api.status; + const feSt = s.frontend?.status || 'stopped'; + if (apiSt === 'running' && feSt === 'running') return 'running'; + if (apiSt === 'error' || feSt === 'error') return 'error'; + if (apiSt === 'starting' || feSt === 'starting') return 'starting'; + if (apiSt === 'stopping' || feSt === 'stopping') return 'stopping'; + return 'stopped'; +} + +function setStatus(entry, slug, subtype, status) { + if (entry.status === status) return; + entry.status = status; + events.emit('status', slug, subtype, status); +} + +function pushLog(entry, line) { + entry.logs.push(line); + if (entry.logs.length > 50) entry.logs.shift(); +} + +function spawnProcess(slug, subtype, cmd, args, cwd) { + const k = key(slug, subtype); + const existing = processes.get(k); + if (existing && (existing.status === 'running' || existing.status === 'starting')) { + return existing; + } + + const entry = createEntry(); + processes.set(k, entry); + + const label = `[${slug}:${subtype}]`; + console.log(`${label} Spawning: ${cmd} ${args.join(' ')} (cwd: ${cwd})`); + + const child = spawn(cmd, args, { + cwd, + stdio: ['ignore', 'pipe', 'pipe'], + detached: true, + }); + + entry.child = child; + entry.status = 'starting'; + events.emit('status', slug, subtype, 'starting'); + + child.stdout.on('data', (data) => { + for (const line of data.toString().split('\n').filter(Boolean)) { + pushLog(entry, `[out] ${line}`); + } + }); + + child.stderr.on('data', (data) => { + for (const line of data.toString().split('\n').filter(Boolean)) { + pushLog(entry, `[err] ${line}`); + console.log(`${label} [err] ${line}`); + } + }); + + child.on('error', (err) => { + console.error(`${label} Spawn error: ${err.message}`); + setStatus(entry, slug, subtype, 'error'); + pushLog(entry, `[sys] Error: ${err.message}`); + }); + + child.on('exit', (code, signal) => { + console.log(`${label} Exited code=${code} signal=${signal}`); + setStatus(entry, slug, subtype, 'stopped'); + pushLog(entry, `[sys] Exited code=${code} signal=${signal}`); + entry.child = null; + }); + + return entry; +} + +function start(slug, projectPath, port, frontend) { + // Start API + const apiEntry = spawnProcess(slug, 'api', 'php', + ['artisan', 'serve', `--port=${port}`, '--host=0.0.0.0'], + projectPath + ); + apiEntry.port = port; + healthCheck(slug, 'api', port, apiEntry); + + let feResult = null; + // Start frontend if present + if (frontend) { + const isExisting = processes.get(key(slug, 'frontend')); + if (isExisting && (isExisting.status === 'running' || isExisting.status === 'starting')) { + feResult = { status: isExisting.status, message: 'Already running' }; + } else { + let cmd, args; + if (frontend.packageManager === 'pnpm') { + cmd = 'pnpm'; + args = ['dev', '--port', String(frontend.port), '--host', '0.0.0.0']; + } else { + cmd = 'npm'; + args = ['run', 'dev', '--', '--port', String(frontend.port), '--host', '0.0.0.0']; + } + + const feEntry = spawnProcess(slug, 'frontend', cmd, args, frontend.fullPath); + feEntry.port = frontend.port; + healthCheck(slug, 'frontend', frontend.port, feEntry); + feResult = { status: 'starting', pid: feEntry.child?.pid }; + } + } + + return { + api: { status: apiEntry.status, pid: apiEntry.child?.pid }, + frontend: feResult, + }; +} + +function healthCheck(slug, subtype, port, entry, attempt = 0) { + const maxAttempts = subtype === 'frontend' ? 60 : 15; + const interval = subtype === 'frontend' ? 3000 : 1000; + + if (attempt > maxAttempts) { + if (entry.status === 'starting') setStatus(entry, slug, subtype, 'error'); + pushLog(entry, '[sys] Health check timed out'); + return; + } + + setTimeout(() => { + if (entry.status !== 'starting') return; + + // Use TCP connect check instead of HTTP — avoids socket pool exhaustion + const sock = net.connect(port, '127.0.0.1'); + sock.setTimeout(2000); + sock.on('connect', () => { + sock.destroy(); + setStatus(entry, slug, subtype, 'running'); + pushLog(entry, `[sys] Port ${port} responding`); + }); + sock.on('error', () => { + sock.destroy(); + healthCheck(slug, subtype, port, entry, attempt + 1); + }); + sock.on('timeout', () => { + sock.destroy(); + healthCheck(slug, subtype, port, entry, attempt + 1); + }); + }, interval); +} + +function stopEntry(k, slug, subtype) { + const entry = processes.get(k); + if (!entry || !entry.child) { + processes.delete(k); + return Promise.resolve({ status: 'stopped' }); + } + + return new Promise((resolve) => { + const child = entry.child; + setStatus(entry, slug, subtype, 'stopping'); + + child.on('exit', () => { + setStatus(entry, slug, subtype, 'stopped'); + entry.child = null; + resolve({ status: 'stopped' }); + }); + + try { process.kill(-child.pid, 'SIGTERM'); } catch {} + + setTimeout(() => { + if (entry.child) { + try { process.kill(-child.pid, 'SIGKILL'); } catch {} + } + }, 3000); + }); +} + +function stop(slug) { + return Promise.all([ + stopEntry(key(slug, 'api'), slug, 'api'), + stopEntry(key(slug, 'frontend'), slug, 'frontend'), + ]); +} + +function stopAll() { + const slugsSeen = new Set(); + for (const [k] of processes) { + const slug = k.split(':')[0]; + slugsSeen.add(slug); + } + return Promise.all([...slugsSeen].map(s => stop(s))); +} + +function getAllStatuses() { + const result = {}; + for (const [k] of processes) { + const slug = k.split(':')[0]; + if (!result[slug]) result[slug] = getStatus(slug); + } + return result; +} + +function killAllSync() { + for (const [, entry] of processes) { + if (entry.child) { + try { process.kill(-entry.child.pid, 'SIGTERM'); } catch {} + } + } + // Brief wait then SIGKILL any survivors + try { execSync('sleep 1'); } catch {} + for (const [, entry] of processes) { + if (entry.child) { + try { process.kill(-entry.child.pid, 'SIGKILL'); } catch {} + } + } + processes.clear(); +} + +module.exports = { start, stop, stopAll, getStatus, combinedStatus, getAllStatuses, events, killAllSync }; diff --git a/lib/scanner.js b/lib/scanner.js new file mode 100644 index 0000000..c19f87e --- /dev/null +++ b/lib/scanner.js @@ -0,0 +1,132 @@ +const fs = require('fs'); +const path = require('path'); +const { parseEnvFile } = require('./env-parser'); + +const BASE_DIR = path.resolve(__dirname, '../../'); +const SKIP_DIRS = new Set([ + 'backups', 'varia', 'wn-golem-starter', 'summercms.io', 'docs', 'projects-browser' +]); + +function extractPortFromUrl(url) { + if (!url) return null; + try { + const u = new URL(url); + const port = parseInt(u.port, 10); + return port || null; + } catch { + return null; + } +} + +function detectFrontend(dirPath) { + try { + const entries = fs.readdirSync(dirPath, { withFileTypes: true }); + for (const entry of entries) { + if (!entry.isDirectory() || !entry.name.startsWith('vue-')) continue; + const frontendDir = path.join(dirPath, entry.name); + const pkgPath = path.join(frontendDir, 'package.json'); + if (!fs.existsSync(pkgPath)) continue; + + try { + const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf8')); + if (!pkg.scripts?.dev) continue; + } catch { continue; } + + const hasPnpmLock = fs.existsSync(path.join(frontendDir, 'pnpm-lock.yaml')); + return { + dir: entry.name, + fullPath: frontendDir, + packageManager: hasPnpmLock ? 'pnpm' : 'npm', + }; + } + } catch {} + return null; +} + +function scanProjects() { + const projects = []; + const entries = fs.readdirSync(BASE_DIR, { withFileTypes: true }); + + for (const entry of entries) { + if (!entry.isDirectory() || SKIP_DIRS.has(entry.name) || entry.name.startsWith('.')) continue; + + const dirPath = path.join(BASE_DIR, entry.name); + + // Check if artisan exists directly + if (fs.existsSync(path.join(dirPath, 'artisan'))) { + projects.push(buildProjectMeta(dirPath, entry.name)); + continue; + } + + // Check one level deeper + try { + const subEntries = fs.readdirSync(dirPath, { withFileTypes: true }); + for (const sub of subEntries) { + if (!sub.isDirectory() || sub.name.startsWith('.')) continue; + const subPath = path.join(dirPath, sub.name); + if (fs.existsSync(path.join(subPath, 'artisan'))) { + projects.push(buildProjectMeta(subPath, entry.name)); + } + } + } catch {} + } + + // Sort by slug for deterministic port assignment + projects.sort((a, b) => a.slug.localeCompare(b.slug)); + + // Assign API ports to projects without one + let nextPort = 8100; + const usedPorts = new Set(projects.filter(p => p.port).map(p => p.port)); + + for (const project of projects) { + if (!project.port) { + while (usedPorts.has(nextPort)) nextPort++; + project.port = nextPort; + project.portSource = 'assigned'; + usedPorts.add(nextPort); + nextPort++; + } + } + + // Assign frontend ports deterministically from 3010+ + let nextFrontendPort = 3010; + for (const project of projects) { + if (project.frontend) { + project.frontend.port = nextFrontendPort++; + } + } + + return projects; +} + +function buildProjectMeta(dirPath, slug) { + const envPath = path.join(dirPath, '.env'); + const hasEnv = fs.existsSync(envPath); + const env = hasEnv ? parseEnvFile(envPath) : {}; + + const port = extractPortFromUrl(env.APP_URL); + + // Make SQLite path relative if it starts with the project path + let dbName = env.DB_DATABASE || null; + if (dbName && dbName.startsWith(dirPath)) { + dbName = path.relative(dirPath, dbName); + } + + const frontend = detectFrontend(dirPath); + const hasDocs = fs.existsSync(path.join(dirPath, 'docs')); + + return { + slug, + name: slug, + path: dirPath, + port: port, + portSource: port ? '.env' : null, + hasEnv, + dbType: env.DB_CONNECTION || null, + dbName, + frontend, + hasDocs, + }; +} + +module.exports = { scanProjects }; diff --git a/lib/screenshotter.js b/lib/screenshotter.js new file mode 100644 index 0000000..ac47aa2 --- /dev/null +++ b/lib/screenshotter.js @@ -0,0 +1,33 @@ +const { execFile } = require('child_process'); +const path = require('path'); +const fs = require('fs'); + +const SCREENSHOTS_DIR = path.join(__dirname, '../public/screenshots'); + +function takeScreenshot(slug, port, useLocalhost = false) { + return new Promise((resolve, reject) => { + const outPath = path.join(SCREENSHOTS_DIR, `${slug}.png`); + const host = useLocalhost ? 'localhost' : '127.0.0.1'; + const url = `http://${host}:${port}`; + + const args = [ + 'screenshot', + '--viewport-size', '1280,800', + '--wait-for-timeout', '3000', + url, + outPath, + ]; + + execFile('/usr/bin/playwright', args, { timeout: 30000 }, (err, stdout, stderr) => { + if (err) { + reject(new Error(`Screenshot failed: ${err.message}\n${stderr}`)); + } else if (fs.existsSync(outPath)) { + resolve(`/screenshots/${slug}.png`); + } else { + reject(new Error('Screenshot file not created')); + } + }); + }); +} + +module.exports = { takeScreenshot }; diff --git a/package.json b/package.json new file mode 100644 index 0000000..0f33f8d --- /dev/null +++ b/package.json @@ -0,0 +1,13 @@ +{ + "name": "projects-browser", + "version": "1.0.0", + "private": true, + "description": "Local dashboard for browsing and managing WinterCMS projects", + "main": "server.js", + "scripts": { + "start": "node server.js" + }, + "dependencies": { + "express": "^4.21.0" + } +} diff --git a/public/app.js b/public/app.js new file mode 100644 index 0000000..1c4509b --- /dev/null +++ b/public/app.js @@ -0,0 +1,341 @@ +(() => { + const grid = document.getElementById('grid'); + const searchInput = document.getElementById('search'); + const statsEl = document.getElementById('stats'); + const screenshotAllBtn = document.getElementById('screenshot-all'); + const logsModal = document.getElementById('logs-modal'); + const logsTitle = document.getElementById('logs-title'); + const logsBody = document.getElementById('logs-body'); + const logsClose = document.getElementById('logs-close'); + + let projects = []; + let filter = 'all'; + let searchTerm = ''; + + // -- Helpers -- + + function slugColor(slug) { + let hash = 0; + for (let i = 0; i < slug.length; i++) hash = slug.charCodeAt(i) + ((hash << 5) - hash); + return `hsl(${Math.abs(hash) % 360}, 45%, 25%)`; + } + + function projectHash(p) { + return `${p.status || 'stopped'}|${p.apiStatus || 'stopped'}|${p.frontendStatus || ''}|${p._hasScreenshot ? 1 : 0}|${p._screenshotTs || 0}|${p.hasDocs ? 1 : 0}`; + } + + function shouldShow(p) { + const status = p.status || 'stopped'; + if (filter === 'running' && status !== 'running') return false; + if (filter === 'stopped' && status !== 'stopped') return false; + if (searchTerm && !p.name.toLowerCase().includes(searchTerm) && !p.slug.toLowerCase().includes(searchTerm)) return false; + return true; + } + + // -- Card rendering -- + + function cardHTML(p) { + const status = p.status || 'stopped'; + const isRunning = status === 'running'; + const isBusy = status === 'starting' || status === 'stopping'; + const screenshotSrc = `/screenshots/${p.slug}.png?t=${p._screenshotTs || 0}`; + const hasFrontend = !!p.frontend; + + const imgInner = p._hasScreenshot + ? `${p.name}` + : `
${p.name[0]}
`; + + const imgHtml = `
+ ${imgInner} + +
`; + + // Status dots: show API + Frontend for frontend projects + let statusDots; + if (hasFrontend) { + const apiSt = p.apiStatus || 'stopped'; + const feSt = p.frontendStatus || 'stopped'; + statusDots = `
+
+
+
`; + } else { + statusDots = `
`; + } + + // Open link: frontend port for frontend projects, API port otherwise + const openPort = hasFrontend ? p.frontend.port : p.port; + + // DB badge with relative path + const dbBadge = p.dbType ? `${p.dbType}${p.dbName ? ` (${p.dbName})` : ''}` : ''; + + return ` + ${imgHtml} +
+
+ ${statusDots} +
${p.name}
+
+
+
+ :${p.port} + ${dbBadge} + ${!p.hasEnv ? 'no .env' : ''} +
+ ${hasFrontend ? `
+ :${p.frontend.port} + ${p.frontend.dir} +
` : ''} +
+
${p.path}
+
+ ${isRunning + ? `` + : `` + } + ${p.hasDocs ? `Docs` : ''} + ${isRunning + ? `Open` + : `` + } +
+
`; + } + + // -- Smart DOM update -- + + const cardHashes = new Map(); + + function render() { + const running = projects.filter(p => p.status === 'running').length; + statsEl.textContent = `(${projects.length} projects, ${running} running)`; + + const visible = projects.filter(shouldShow); + const visibleSlugs = new Set(visible.map(p => p.slug)); + + // Remove cards no longer visible + for (const card of [...grid.children]) { + if (!visibleSlugs.has(card.dataset.slug)) { + card.remove(); + cardHashes.delete(card.dataset.slug); + } + } + + // Add or update visible cards in order + let prevCard = null; + for (const p of visible) { + const hash = projectHash(p); + let card = grid.querySelector(`[data-slug="${p.slug}"]`); + + if (!card) { + // New card + card = document.createElement('div'); + card.className = 'card'; + card.dataset.slug = p.slug; + card.innerHTML = cardHTML(p); + cardHashes.set(p.slug, hash); + + if (prevCard && prevCard.nextSibling) { + grid.insertBefore(card, prevCard.nextSibling); + } else if (prevCard) { + grid.appendChild(card); + } else if (grid.firstChild) { + grid.insertBefore(card, grid.firstChild); + } else { + grid.appendChild(card); + } + } else if (cardHashes.get(p.slug) !== hash) { + // Changed - update innerHTML only for this card + card.innerHTML = cardHTML(p); + cardHashes.set(p.slug, hash); + } + + prevCard = card; + } + } + + // -- Data fetching -- + + async function fetchProjects() { + try { + const res = await fetch('/api/projects'); + const data = await res.json(); + + // Probe screenshots for new projects + const checks = data.map(async (p) => { + const old = projects.find(o => o.slug === p.slug); + if (old) { + p._hasScreenshot = old._hasScreenshot; + p._screenshotTs = old._screenshotTs || 0; + } else { + p._hasScreenshot = await imageExists(`/screenshots/${p.slug}.png`); + p._screenshotTs = p._hasScreenshot ? Date.now() : 0; + } + }); + await Promise.all(checks); + + projects = data; + render(); + } catch (err) { + console.error('Failed to fetch projects:', err); + } + } + + function imageExists(url) { + return new Promise(resolve => { + const img = new Image(); + img.onload = () => resolve(true); + img.onerror = () => resolve(false); + img.src = url; + }); + } + + // -- Centrifugo real-time updates -- + + async function connectCentrifugo() { + try { + const res = await fetch('/api/centrifugo/token'); + const { token } = await res.json(); + + const client = new Centrifuge(`ws://${location.hostname}:8787/connection/websocket`, { + token, + }); + + const sub = client.newSubscription('projects-browser'); + + sub.on('publication', (ctx) => { + const msg = ctx.data; + + if (msg.type === 'status') { + const p = projects.find(p => p.slug === msg.slug); + if (p) { + if (msg.subtype === 'api') { + p.apiStatus = msg.status; + } else if (msg.subtype === 'frontend') { + p.frontendStatus = msg.status; + } + // Recompute combined status + const hasFe = !!p.frontend; + if (!hasFe) { + p.status = p.apiStatus || msg.status; + } else { + const apiSt = p.apiStatus || 'stopped'; + const feSt = p.frontendStatus || 'stopped'; + if (apiSt === 'running' && feSt === 'running') p.status = 'running'; + else if (apiSt === 'error' || feSt === 'error') p.status = 'error'; + else if (apiSt === 'starting' || feSt === 'starting') p.status = 'starting'; + else if (apiSt === 'stopping' || feSt === 'stopping') p.status = 'stopping'; + else p.status = 'stopped'; + } + render(); + } + } + + if (msg.type === 'screenshot') { + const p = projects.find(p => p.slug === msg.slug); + if (p) { + p._hasScreenshot = true; + p._screenshotTs = Date.now(); + render(); + } + } + }); + + sub.subscribe(); + + client.on('connected', () => { + console.log('Centrifugo connected'); + }); + + client.on('disconnected', (ctx) => { + console.log('Centrifugo disconnected:', ctx.reason); + }); + + client.connect(); + } catch (err) { + console.error('Centrifugo setup failed, falling back to polling:', err); + setInterval(fetchProjects, 5000); + } + } + + // -- Actions -- + + window.actions = { + async start(slug) { + await fetch(`/api/projects/${slug}/start`, { method: 'POST' }); + // Status updates come via Centrifugo + }, + + async stop(slug) { + await fetch(`/api/projects/${slug}/stop`, { method: 'POST' }); + }, + + async screenshot(slug) { + const btn = grid.querySelector(`[data-slug="${slug}"] .btn-screenshot-icon`); + if (btn) { btn.disabled = true; btn.textContent = '⏳'; } + + try { + await fetch(`/api/projects/${slug}/screenshot`, { method: 'POST' }); + // Screenshot update comes via Centrifugo + } catch (err) { + console.error('Screenshot failed:', err); + } + }, + + async logs(slug) { + const res = await fetch(`/api/projects/${slug}/logs`); + const data = await res.json(); + logsTitle.textContent = `Logs: ${slug}`; + // Show both API and frontend logs + let text = ''; + if (data.api?.length) { + text += '--- API ---\n' + data.api.join('\n'); + } + if (data.frontend?.length) { + if (text) text += '\n\n'; + text += '--- Frontend ---\n' + data.frontend.join('\n'); + } + logsBody.textContent = text || '(no logs)'; + logsModal.classList.add('open'); + } + }; + + // -- Filter buttons -- + + document.querySelectorAll('.filter-btn').forEach(btn => { + btn.addEventListener('click', () => { + document.querySelectorAll('.filter-btn').forEach(b => b.classList.remove('active')); + btn.classList.add('active'); + filter = btn.dataset.filter; + render(); + }); + }); + + // Search + searchInput.addEventListener('input', () => { + searchTerm = searchInput.value.toLowerCase().trim(); + render(); + }); + + // Screenshot all + screenshotAllBtn.addEventListener('click', async () => { + screenshotAllBtn.disabled = true; + screenshotAllBtn.textContent = 'Taking screenshots...'; + try { + await fetch('/api/screenshot-all', { method: 'POST' }); + // Updates come via Centrifugo + } finally { + screenshotAllBtn.disabled = false; + screenshotAllBtn.textContent = 'Screenshot All'; + } + }); + + // Logs modal close + logsClose.addEventListener('click', () => logsModal.classList.remove('open')); + logsModal.addEventListener('click', (e) => { + if (e.target === logsModal) logsModal.classList.remove('open'); + }); + + // -- Init -- + fetchProjects().then(connectCentrifugo); +})(); diff --git a/public/favicon-32.png b/public/favicon-32.png new file mode 100644 index 0000000..9402a86 Binary files /dev/null and b/public/favicon-32.png differ diff --git a/public/favicon.ico b/public/favicon.ico new file mode 100644 index 0000000..fbc2a3a Binary files /dev/null and b/public/favicon.ico differ diff --git a/public/index.html b/public/index.html new file mode 100644 index 0000000..e929491 --- /dev/null +++ b/public/index.html @@ -0,0 +1,38 @@ + + + + + + Projects Browser + + + + + +
+

Projects Browser

+
+ + + + + +
+
+ +
+ + + + + + + diff --git a/public/screenshots/api.jakubzych.com.png b/public/screenshots/api.jakubzych.com.png new file mode 100644 index 0000000..7d12e5a Binary files /dev/null and b/public/screenshots/api.jakubzych.com.png differ diff --git a/public/screenshots/autoliberda.com.png b/public/screenshots/autoliberda.com.png new file mode 100644 index 0000000..0c59afd Binary files /dev/null and b/public/screenshots/autoliberda.com.png differ diff --git a/public/screenshots/cytatybiblijne.online.png b/public/screenshots/cytatybiblijne.online.png new file mode 100644 index 0000000..5b0eabc Binary files /dev/null and b/public/screenshots/cytatybiblijne.online.png differ diff --git a/public/screenshots/drzewo.net.png b/public/screenshots/drzewo.net.png new file mode 100644 index 0000000..0f5da14 Binary files /dev/null and b/public/screenshots/drzewo.net.png differ diff --git a/public/screenshots/figs.org.pl.png b/public/screenshots/figs.org.pl.png new file mode 100644 index 0000000..1628be1 Binary files /dev/null and b/public/screenshots/figs.org.pl.png differ diff --git a/public/screenshots/getaround.world.png b/public/screenshots/getaround.world.png new file mode 100644 index 0000000..522f183 Binary files /dev/null and b/public/screenshots/getaround.world.png differ diff --git a/public/screenshots/golem15.com.png b/public/screenshots/golem15.com.png new file mode 100644 index 0000000..a8e9f47 Binary files /dev/null and b/public/screenshots/golem15.com.png differ diff --git a/public/screenshots/golemxv.com.png b/public/screenshots/golemxv.com.png new file mode 100644 index 0000000..6e481dd Binary files /dev/null and b/public/screenshots/golemxv.com.png differ diff --git a/public/screenshots/grzybyfunkcjonalne.pl.png b/public/screenshots/grzybyfunkcjonalne.pl.png new file mode 100644 index 0000000..b7bd4bb Binary files /dev/null and b/public/screenshots/grzybyfunkcjonalne.pl.png differ diff --git a/public/screenshots/horoskopia.eu.png b/public/screenshots/horoskopia.eu.png new file mode 100644 index 0000000..02f7be9 Binary files /dev/null and b/public/screenshots/horoskopia.eu.png differ diff --git a/public/screenshots/keios.eu.png b/public/screenshots/keios.eu.png new file mode 100644 index 0000000..a564d8c Binary files /dev/null and b/public/screenshots/keios.eu.png differ diff --git a/public/screenshots/langol.pl.png b/public/screenshots/langol.pl.png new file mode 100644 index 0000000..9ae488b Binary files /dev/null and b/public/screenshots/langol.pl.png differ diff --git a/public/screenshots/portal.golem15.com.png b/public/screenshots/portal.golem15.com.png new file mode 100644 index 0000000..c9340a5 Binary files /dev/null and b/public/screenshots/portal.golem15.com.png differ diff --git a/public/screenshots/queststream.online.png b/public/screenshots/queststream.online.png new file mode 100644 index 0000000..5807c42 Binary files /dev/null and b/public/screenshots/queststream.online.png differ diff --git a/public/screenshots/quotify.pro.png b/public/screenshots/quotify.pro.png new file mode 100644 index 0000000..a3779da Binary files /dev/null and b/public/screenshots/quotify.pro.png differ diff --git a/public/screenshots/sklep.figs.org.pl.png b/public/screenshots/sklep.figs.org.pl.png new file mode 100644 index 0000000..99b2498 Binary files /dev/null and b/public/screenshots/sklep.figs.org.pl.png differ diff --git a/public/screenshots/taxiwnamyslowie.pl.png b/public/screenshots/taxiwnamyslowie.pl.png new file mode 100644 index 0000000..0188b81 Binary files /dev/null and b/public/screenshots/taxiwnamyslowie.pl.png differ diff --git a/public/screenshots/wn-opoltax-app.png b/public/screenshots/wn-opoltax-app.png new file mode 100644 index 0000000..78de4b3 Binary files /dev/null and b/public/screenshots/wn-opoltax-app.png differ diff --git a/public/style.css b/public/style.css new file mode 100644 index 0000000..e968acd --- /dev/null +++ b/public/style.css @@ -0,0 +1,350 @@ +*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; } + +:root { + --bg: #0f1117; + --surface: #1a1d27; + --surface-hover: #222632; + --border: #2a2e3a; + --text: #e4e6ed; + --text-dim: #8b8fa3; + --accent: #6c8cff; + --green: #34d399; + --amber: #fbbf24; + --red: #f87171; + --radius: 10px; +} + +body { + font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; + background: var(--bg); + color: var(--text); + min-height: 100vh; +} + +header { + padding: 24px 32px; + display: flex; + align-items: center; + justify-content: space-between; + border-bottom: 1px solid var(--border); + flex-wrap: wrap; + gap: 16px; +} + +header h1 { + font-size: 20px; + font-weight: 600; + letter-spacing: -0.02em; +} + +header h1 span { + color: var(--text-dim); + font-weight: 400; +} + +.controls { + display: flex; + gap: 10px; + align-items: center; + flex-wrap: wrap; +} + +.search-input { + background: var(--surface); + border: 1px solid var(--border); + border-radius: 6px; + padding: 7px 12px; + color: var(--text); + font-size: 14px; + width: 200px; + outline: none; + transition: border-color .2s; +} + +.search-input:focus { border-color: var(--accent); } + +.filter-btn, .action-btn { + background: var(--surface); + border: 1px solid var(--border); + border-radius: 6px; + padding: 7px 14px; + color: var(--text-dim); + font-size: 13px; + cursor: pointer; + transition: all .15s; +} + +.filter-btn:hover, .action-btn:hover { + background: var(--surface-hover); + color: var(--text); +} + +.filter-btn.active { + background: var(--accent); + color: #fff; + border-color: var(--accent); +} + +.action-btn { + background: var(--accent); + color: #fff; + border-color: var(--accent); + font-weight: 500; +} + +.action-btn:hover { opacity: .85; } + +.grid { + display: grid; + grid-template-columns: repeat(auto-fill, minmax(300px, 1fr)); + gap: 20px; + padding: 24px 32px; +} + +.card { + background: var(--surface); + border: 1px solid var(--border); + border-radius: var(--radius); + overflow: hidden; + transition: transform .15s, box-shadow .15s; + display: flex; + flex-direction: column; +} + +.card:hover { + transform: translateY(-2px); + box-shadow: 0 8px 24px rgba(0,0,0,.3); +} + +.card-img { + width: 100%; + height: 180px; + object-fit: cover; + object-position: top; + display: block; + background: var(--border); +} + +.card-placeholder { + width: 100%; + height: 180px; + display: flex; + align-items: center; + justify-content: center; + font-size: 48px; + font-weight: 700; + color: rgba(255,255,255,.15); +} + +/* Screenshot hover icon */ +.card-visual { + position: relative; +} + +.btn-screenshot-icon { + position: absolute; + top: 8px; + right: 8px; + width: 28px; + height: 28px; + border: none; + border-radius: 6px; + background: rgba(0,0,0,.55); + color: #fff; + font-size: 14px; + cursor: pointer; + opacity: 0; + transition: opacity .15s, background .15s; + display: flex; + align-items: center; + justify-content: center; + padding: 0; + line-height: 1; +} + +.card:hover .btn-screenshot-icon { opacity: 1; } +.btn-screenshot-icon:hover { background: rgba(0,0,0,.8); } +.btn-screenshot-icon:disabled { opacity: 0 !important; cursor: not-allowed; } +.card:hover .btn-screenshot-icon:disabled { opacity: .3 !important; } + +.card-body { + padding: 16px; + display: flex; + flex-direction: column; + flex: 1; +} + +.card-header { + display: flex; + align-items: center; + gap: 8px; + margin-bottom: 10px; +} + +.status-dots { + display: flex; + gap: 4px; + flex-shrink: 0; +} + +.status-dot { + width: 8px; + height: 8px; + border-radius: 50%; + flex-shrink: 0; +} + +.status-dot.running { background: var(--green); box-shadow: 0 0 6px var(--green); } +.status-dot.stopped { background: var(--text-dim); } +.status-dot.starting { background: var(--amber); animation: pulse 1s infinite; } +.status-dot.stopping { background: var(--amber); } +.status-dot.error { background: var(--red); } + +@keyframes pulse { 0%,100% { opacity: 1; } 50% { opacity: .4; } } + +.card-name { + font-size: 15px; + font-weight: 600; + flex: 1; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; +} + +.badges-wrap { + display: flex; + flex-direction: column; + gap: 4px; + margin-bottom: 12px; +} + +.badges { + display: flex; + gap: 6px; + flex-wrap: wrap; +} + +.badge { + font-size: 11px; + padding: 2px 8px; + border-radius: 4px; + background: rgba(108,140,255,.15); + color: var(--accent); + font-weight: 500; +} + +.badge.db { background: rgba(52,211,153,.12); color: var(--green); } +.badge.fe { background: rgba(251,191,36,.12); color: var(--amber); } + +.card-path { + font-size: 11px; + color: var(--text-dim); + margin-bottom: 12px; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; +} + +.card-actions { + display: flex; + gap: 8px; + margin-top: auto; +} + +.card-actions button, .card-actions a { + flex: 1; + padding: 7px 0; + border: 1px solid var(--border); + border-radius: 6px; + background: transparent; + color: var(--text-dim); + font-size: 12px; + font-weight: 500; + cursor: pointer; + text-align: center; + text-decoration: none; + transition: all .15s; + display: inline-block; +} + +.card-actions button:hover, .card-actions a:hover { + background: var(--surface-hover); + color: var(--text); +} + +.card-actions .btn-start { color: var(--green); border-color: rgba(52,211,153,.3); } +.card-actions .btn-start:hover { background: rgba(52,211,153,.1); } +.card-actions .btn-stop { color: var(--red); border-color: rgba(248,113,113,.3); } +.card-actions .btn-stop:hover { background: rgba(248,113,113,.1); } +.card-actions .btn-docs { color: var(--accent); border-color: rgba(108,140,255,.3); } +.card-actions .btn-docs:hover { background: rgba(108,140,255,.1); } +.card-actions .btn-open { color: var(--amber); border-color: rgba(251,191,36,.3); } +.card-actions .btn-open:hover { background: rgba(251,191,36,.1); } + +.card-actions button:disabled { + opacity: .4; + cursor: not-allowed; +} + +.stats { + color: var(--text-dim); + font-size: 13px; +} + +/* Logs modal */ +.modal-overlay { + display: none; + position: fixed; + inset: 0; + background: rgba(0,0,0,.6); + z-index: 100; + align-items: center; + justify-content: center; +} + +.modal-overlay.open { display: flex; } + +.modal { + background: var(--surface); + border: 1px solid var(--border); + border-radius: var(--radius); + width: 90%; + max-width: 700px; + max-height: 80vh; + display: flex; + flex-direction: column; +} + +.modal-header { + padding: 16px; + border-bottom: 1px solid var(--border); + display: flex; + justify-content: space-between; + align-items: center; + font-weight: 600; +} + +.modal-close { + background: none; + border: none; + color: var(--text-dim); + font-size: 20px; + cursor: pointer; +} + +.modal-body { + padding: 16px; + overflow-y: auto; + font-family: 'SF Mono', 'Fira Code', monospace; + font-size: 12px; + line-height: 1.6; + color: var(--text-dim); + white-space: pre-wrap; + word-break: break-all; +} + +@media (max-width: 640px) { + header { padding: 16px; } + .grid { padding: 16px; gap: 14px; } + .grid { grid-template-columns: 1fr; } +} diff --git a/server.js b/server.js new file mode 100644 index 0000000..7260977 --- /dev/null +++ b/server.js @@ -0,0 +1,200 @@ +const fs = require('fs'); +const express = require('express'); +const path = require('path'); +const { scanProjects } = require('./lib/scanner'); +const pm = require('./lib/process-manager'); +const { takeScreenshot } = require('./lib/screenshotter'); +const centro = require('./lib/centrifugo'); + +const app = express(); +const PORT = 3000; + +// Scan projects on startup +let projects = scanProjects(); +const projectsBySlug = new Map(projects.map(p => [p.slug, p])); + +console.log(`Found ${projects.length} projects:`); +projects.forEach(p => { + const fe = p.frontend ? ` + frontend(${p.frontend.dir} :${p.frontend.port} ${p.frontend.packageManager})` : ''; + console.log(` ${p.slug} :${p.port} (${p.portSource || 'assigned'})${fe}`); +}); + +// Publish status changes to Centrifugo +pm.events.on('status', (slug, subtype, status) => { + centro.publishStatus(slug, status, { subtype }); +}); + +// Static files +app.use(express.static(path.join(__dirname, 'public'))); +app.use(express.json()); + +// Serve project docs folders with directory listing +app.use('/docs/:slug', (req, res, next) => { + const project = projectsBySlug.get(req.params.slug); + if (!project) return res.status(404).send('Project not found'); + + const docsRoot = path.join(project.path, 'docs'); + const reqPath = decodeURIComponent(req.path).replace(/\.\./g, ''); + const fullPath = path.join(docsRoot, reqPath); + + if (!fullPath.startsWith(docsRoot)) return res.status(403).send('Forbidden'); + + let stat; + try { stat = fs.statSync(fullPath); } catch { return res.status(404).send('Not found'); } + + if (stat.isFile()) return res.sendFile(fullPath); + + // Directory listing + const entries = fs.readdirSync(fullPath, { withFileTypes: true }); + const basePath = `/docs/${project.slug}${reqPath}`.replace(/\/$/, ''); + const dirs = entries.filter(e => e.isDirectory()).sort((a, b) => a.name.localeCompare(b.name)); + const files = entries.filter(e => e.isFile()).sort((a, b) => a.name.localeCompare(b.name)); + + const items = [ + ...dirs.map(e => `
  • ${e.name}/
  • `), + ...files.map(e => `
  • ${e.name}
  • `), + ].join('\n'); + + res.send(` + docs/${project.slug}${reqPath} + +

    docs/${project.slug}${reqPath}/

    + ${reqPath !== '/' && reqPath !== '' ? '← back' : ''} + `); +}); + +// Centrifugo connection token +app.get('/api/centrifugo/token', (req, res) => { + const token = centro.createJWT('projects-browser'); + res.json({ token }); +}); + +// List all projects with live status +app.get('/api/projects', (req, res) => { + const statuses = pm.getAllStatuses(); + const result = projects.map(p => { + const s = statuses[p.slug]; + const hasFrontend = !!p.frontend; + return { + ...p, + status: s ? pm.combinedStatus(p.slug, hasFrontend) : 'stopped', + apiStatus: s?.api?.status || 'stopped', + frontendStatus: hasFrontend ? (s?.frontend?.status || 'stopped') : null, + pid: s?.api?.pid || null, + }; + }); + res.json(result); +}); + +// Start a project +app.post('/api/projects/:slug/start', (req, res) => { + const project = projectsBySlug.get(req.params.slug); + if (!project) return res.status(404).json({ error: 'Project not found' }); + + const result = pm.start(project.slug, project.path, project.port, project.frontend || null); + res.json(result); +}); + +// Stop a project +app.post('/api/projects/:slug/stop', async (req, res) => { + const project = projectsBySlug.get(req.params.slug); + if (!project) return res.status(404).json({ error: 'Project not found' }); + + const result = await pm.stop(project.slug); + res.json(result); +}); + +// Screenshot a project +app.post('/api/projects/:slug/screenshot', async (req, res) => { + const project = projectsBySlug.get(req.params.slug); + if (!project) return res.status(404).json({ error: 'Project not found' }); + + const s = pm.getStatus(project.slug); + const hasFrontend = !!project.frontend; + + // For frontend projects, prefer frontend being up; otherwise check API + if (hasFrontend) { + if (s.frontend?.status !== 'running') { + return res.status(400).json({ error: 'Frontend must be running to take screenshot' }); + } + } else { + if (s.api.status !== 'running') { + return res.status(400).json({ error: 'Project must be running to take screenshot' }); + } + } + + // Screenshot the frontend port if available, otherwise API port + const screenshotPort = hasFrontend ? project.frontend.port : project.port; + + try { + const imgPath = await takeScreenshot(project.slug, screenshotPort, hasFrontend); + centro.publishScreenshot(project.slug); + res.json({ screenshot: imgPath }); + } catch (err) { + res.status(500).json({ error: err.message }); + } +}); + +// Screenshot all running projects +app.post('/api/screenshot-all', async (req, res) => { + const statuses = pm.getAllStatuses(); + const results = {}; + + for (const p of projects) { + const s = statuses[p.slug]; + if (!s) continue; + + const hasFrontend = !!p.frontend; + const combined = pm.combinedStatus(p.slug, hasFrontend); + if (combined !== 'running') continue; + + const screenshotPort = hasFrontend ? p.frontend.port : p.port; + try { + results[p.slug] = await takeScreenshot(p.slug, screenshotPort, hasFrontend); + centro.publishScreenshot(p.slug); + } catch (err) { + results[p.slug] = { error: err.message }; + } + } + res.json(results); +}); + +// Get logs for a project +app.get('/api/projects/:slug/logs', (req, res) => { + const project = projectsBySlug.get(req.params.slug); + if (!project) return res.status(404).json({ error: 'Project not found' }); + + const s = pm.getStatus(project.slug); + res.json({ + api: s.api.logs, + frontend: s.frontend?.logs || [], + }); +}); + +// Rescan projects +app.post('/api/rescan', (req, res) => { + projects = scanProjects(); + projectsBySlug.clear(); + projects.forEach(p => projectsBySlug.set(p.slug, p)); + res.json({ count: projects.length }); +}); + +// Graceful shutdown +let shuttingDown = false; +function shutdown() { + if (shuttingDown) return; + shuttingDown = true; + console.log('\nShutting down, stopping all child processes...'); + pm.killAllSync(); + console.log('All processes killed.'); + process.exit(0); +} + +process.on('SIGINT', shutdown); +process.on('SIGTERM', shutdown); + +app.listen(PORT, '0.0.0.0', () => { + console.log(`Projects Browser running at http://0.0.0.0:${PORT}`); +});