import express from 'express'; import { chromium } from 'playwright-extra'; import stealth from 'playwright-extra/plugins/stealth'; import cluster from 'cluster'; import { cpus } from 'os'; import sharp from 'sharp'; chromium.use(stealth()); const BROWSERS_COUNT = cpus().length; const PORT = process.env.PORT || 7860; class FastBratGenerator { constructor() { this.browsers = []; this.pages = []; } async init() { const promises = Array(BROWSERS_COUNT).fill().map(async () => { const browser = await chromium.launch({ headless: true }); const context = await browser.newContext({ viewport: { width: 1920, height: 1080 } }); const page = await context.newPage(); await page.goto('https://www.bratgenerator.com/', { waitUntil: 'domcontentloaded' }); this.browsers.push(browser); this.pages.push(page); }); await Promise.all(promises); } async generate(text) { const page = this.pages[Math.floor(Math.random() * this.pages.length)]; await page.fill('#textInput', text); const screenshot = await page.locator('#textOverlay').screenshot({ type: 'png', timeout: 2000 }); return sharp(screenshot) .webp({ quality: 85, speed: 6 }) .toBuffer(); } async close() { await Promise.all(this.browsers.map(b => b.close())); } } const bratGenerator = new FastBratGenerator(); async function startServer() { const app = express(); app.use(express.json()); app.get('/', async (req, res) => { try { const { q } = req.query; if (!q) return res.status(400).send('Text required'); const imageBuffer = await bratGenerator.generate(q); res.contentType('image/webp'); res.send(imageBuffer); } catch (error) { res.status(500).send('Generation failed'); } }); await bratGenerator.init(); app.listen(PORT, () => console.log(`Running on ${PORT}`)); } if (cluster.isPrimary) { cpus().forEach(() => cluster.fork()); cluster.on('exit', (worker) => cluster.fork()); } else { startServer(); } process.on('SIGINT', async () => { await bratGenerator.close(); process.exit(0); });