All files / scripts serve-website.js

0% Statements 0/291
0% Branches 0/1
0% Functions 0/1
0% Lines 0/291

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       
#!/usr/bin/env node
import http from 'node:http';
import fs from 'node:fs/promises';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { spawn } from 'node:child_process';
import { createRequire } from 'node:module';

// Lazy imports for optional dev-only deps (ws, chokidar)
let WebSocketServer = null;
let chokidar = null;
const req = createRequire(import.meta.url);

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const repoRoot = path.resolve(__dirname, '..');
const DIST_DIR = path.join(repoRoot, 'website', 'dist');
const SRC_DIR = path.join(repoRoot, 'src');
const EXAMPLES_DIR = path.join(repoRoot, 'examples');
const WEBSITE_SRC_DIR = path.join(repoRoot, 'website', 'src');

const PORT = Number(process.env.PORT || 8081);
const HOST = process.env.HOST || '127.0.0.1';

const MIME = {
  '.html': 'text/html; charset=UTF-8',
  '.css': 'text/css; charset=UTF-8',
  '.js': 'application/javascript; charset=UTF-8',
  '.mjs': 'application/javascript; charset=UTF-8',
  '.json': 'application/json; charset=UTF-8',
  '.svg': 'image/svg+xml',
  '.png': 'image/png',
  '.jpg': 'image/jpeg',
  '.jpeg': 'image/jpeg',
  '.gif': 'image/gif',
  '.webp': 'image/webp',
  '.ico': 'image/x-icon',
  '.map': 'application/json; charset=UTF-8'
};

function safeJoin(base, target) {
  const sanitized = path.normalize(target).replace(/^\/+/, '');
  const p = path.join(base, sanitized);
  if (!p.startsWith(base)) return base; // prevent path traversal
  return p;
}

async function exists(p) {
  try { await fs.access(p); return true; } catch { return false; }
}

function injectHMR(html) {
  try {
    // Only inject once
    if (html.includes('__coherent_hmr_initialized')) return html;
    const tag = '\n<script type="module" src="/__coherent/hmr.js"></script>\n';
    if (html.includes('</body>')) return html.replace('</body>', `${tag}</body>`);
    return html + tag;
  } catch {
    return html;
  }
}

async function handlePlaygroundRun(req, res) {
  try {
    if (req.method !== 'POST') {
      res.statusCode = 405; res.setHeader('Content-Type', 'application/json');
      res.end(JSON.stringify({ error: 'Method Not Allowed' }));
      return;
    }
    let body = '';
    for await (const chunk of req) body += chunk;
    let data = {};
    try { data = JSON.parse(body || '{}'); } catch {}
    const runtime = String(data.runtime || 'node');
    const userCode = String(data.code || '');

    // Minimal validation and limits
    const MAX_CODE = 50_000; // 50KB
    if (userCode.length > MAX_CODE) {
      res.statusCode = 400; res.setHeader('Content-Type', 'application/json');
      res.end(JSON.stringify({ error: 'Code too large' }));
      return;
    }

    const tmpDir = path.join(repoRoot, '.playground-tmp');
    await fs.mkdir(tmpDir, { recursive: true });

    const coherentFileUrl = `file://${  path.join(repoRoot, 'src', 'coherent.js')}`;
    const headerStart = `// Auto-generated by Playground\n` +
      `(async () => {\n` +
      `  const mod = await import(${JSON.stringify(coherentFileUrl)});\n` +
      `  const coherent = mod.coherent;\n`;
    const headerEnd = `\n})();\n`;

    const defaultCode = `// Example: Hello World with Coherent.js\n` +
      `const html = coherent.render({ div: { text: 'Hello, Coherent.js! šŸ‘‹' } });\n` +
      `console.log(html);\n`;

    const fullCode = headerStart + (userCode.trim() ? userCode : defaultCode) + headerEnd;
    const fileName = `play-${  Date.now()  }-${  Math.random().toString(36).slice(2)  }.mjs`;
    const filePath = path.join(tmpDir, fileName);
    await fs.writeFile(filePath, fullCode, 'utf8');

    let cmd = 'node';
    let args = [filePath];
    if (runtime === 'deno') {
      cmd = 'deno';
      args = ['run', '--quiet', '--allow-read', filePath];
    } else if (runtime === 'bun') {
      cmd = 'bun';
      args = [filePath];
    }

    const child = spawn(cmd, args, { cwd: repoRoot });
    let stdout = '';
    let stderr = '';
    const MAX_OUTPUT = 200_000; // 200KB cap
    child.stdout.on('data', (d) => { if ((stdout.length + d.length) < MAX_OUTPUT) stdout += d.toString(); });
    child.stderr.on('data', (d) => { if ((stderr.length + d.length) < MAX_OUTPUT) stderr += d.toString(); });

    const timeoutMs = Number(process.env.PLAYGROUND_TIMEOUT_MS || 5000);
    const killer = setTimeout(() => {
      try { child.kill('SIGKILL'); } catch {}
    }, timeoutMs);

    child.on('exit', async (code) => {
      clearTimeout(killer);
      // best effort cleanup
      try { await fs.unlink(filePath); } catch {}
      res.statusCode = 200;
      res.setHeader('Content-Type', 'application/json; charset=UTF-8');
      res.end(JSON.stringify({ code, stdout, stderr, runtime }));
    });
  } catch (e) {
    res.statusCode = 500;
    res.setHeader('Content-Type', 'application/json; charset=UTF-8');
    res.end(JSON.stringify({ error: 'Playground execution failed', details: String(e && e.message || e) }));
  }
}

const server = http.createServer(async (req, res) => {
  try {
    let urlPath = decodeURIComponent((req.url || '/').split('?')[0]);
    if (urlPath === '') urlPath = '/';

    // Playground execution API
    if (urlPath === '/__playground/run') {
      await handlePlaygroundRun(req, res);
      return;
    }

    // Serve HMR client from source during dev
    if (urlPath === '/__coherent/hmr.js') {
      const hmrPath = path.join(SRC_DIR, 'client', 'hmr.js');
      try {
        const buf = await fs.readFile(hmrPath);
        res.statusCode = 200;
        res.setHeader('Content-Type', 'application/javascript; charset=UTF-8');
        res.end(buf);
        return;
      } catch {}
    }

    let filePath = safeJoin(DIST_DIR, urlPath);
    let statIsDir = false;

    try {
      const s = await fs.stat(filePath);
      statIsDir = s.isDirectory();
    } catch {}

    if (statIsDir) {
      // Append trailing slash and serve index.html
      if (!urlPath.endsWith('/')) {
        res.statusCode = 301;
        res.setHeader('Location', `${urlPath  }/`);
        res.end();
        return;
      }
      filePath = path.join(filePath, 'index.html');
    } else {
      // If path has no extension and no direct file, try directory index
      if (!path.extname(filePath)) {
        const asDir = `${filePath  }/`;
        if (await exists(asDir)) {
          res.statusCode = 301;
          res.setHeader('Location', `${urlPath  }/`);
          res.end();
          return;
        }
        const indexHtml = path.join(filePath, 'index.html');
        if (await exists(indexHtml)) filePath = indexHtml;
      }
    }

    if (!(await exists(filePath))) {
      res.statusCode = 404;
      res.setHeader('Content-Type', 'text/plain; charset=UTF-8');
      res.end('Not Found');
      return;
    }

    const ext = path.extname(filePath).toLowerCase();
    const type = MIME[ext] || 'application/octet-stream';
    const content = await fs.readFile(filePath);
    res.statusCode = 200;
    res.setHeader('Content-Type', type);
    if (type.startsWith('text/html')) {
      res.end(injectHMR(content.toString('utf8')));
    } else {
      res.end(content);
    }
  } catch (_err) {
    res.statusCode = 500;
    res.setHeader('Content-Type', 'text/plain; charset=UTF-8');
    res.end('Internal Server Error');
  }
});

// Start server first; then attach WS and watcher
server.listen(PORT, HOST, () => {
  console.log(`Serving website from ${DIST_DIR}`);
  console.log(`→ http://${HOST}:${PORT}/`);

  // Dynamically require dev-only dependencies if available
  try {
    WebSocketServer = req('ws').WebSocketServer;
  } catch {}
  try {
    chokidar = req('chokidar');
  } catch {}

  if (!WebSocketServer || !chokidar) {
    console.log('HMR disabled (install dev deps to enable): pnpm add -D ws chokidar');
    return;
  }

  const wss = new WebSocketServer({ server });
  const clients = new Set();
  wss.on('connection', (ws) => {
    clients.add(ws);
    ws.on('close', () => clients.delete(ws));
    ws.send(JSON.stringify({ type: 'connected' }));
  });

  let building = false;
  let pending = false;
  function triggerBuild(reason, file) {
    if (building) {
      pending = true;
      return;
    }
    building = true;
    const args = ['run', 'website:build'];
    console.log(`ā™»ļø  Change detected (${reason}): ${file || ''}\nšŸ”Ø Rebuilding...`);
    const proc = spawn('pnpm', args, { stdio: 'inherit' });
    proc.on('exit', (code) => {
      building = false;
      if (code === 0) {
        // Notify clients a full reload is safest for now
        for (const ws of clients) {
          try { ws.send(JSON.stringify({ type: 'reload' })); } catch {}
        }
        console.log('āœ… Rebuilt. Notified clients to reload.');
        if (pending) {
          pending = false;
          // debounce chain
          setTimeout(() => triggerBuild('pending'), 50);
        }
      } else {
        console.error('āŒ Rebuild failed');
      }
    });
  }

  // Watch source and content; ignore dist to prevent loops
  const watcher = chokidar.watch([
    SRC_DIR,
    EXAMPLES_DIR,
    WEBSITE_SRC_DIR,
    path.join(repoRoot, 'docs')
  ], {
    ignored: [DIST_DIR, path.join(repoRoot, 'node_modules'), '**/.git/**'],
    ignoreInitial: true,
  });

  watcher.on('add', (f) => triggerBuild('add', f));
  watcher.on('change', (f) => triggerBuild('change', f));
  watcher.on('unlink', (f) => triggerBuild('unlink', f));
});