| const express = require('express'); | |
| const { chromium, devices } = require('playwright'); | |
| const cors = require('cors'); | |
| const fs = require('fs').promises; | |
| const path = require('path'); | |
| const app = express(); | |
| const PORT = process.env.PORT || 7860; | |
| app.use(cors()); | |
| app.use(express.json({ limit: '50mb' })); | |
| app.use('/files', express.static('public')); | |
| const publicDir = path.join(__dirname, 'public'); | |
| fs.mkdir(publicDir, { recursive: true }).catch(console.error); | |
| app.post('/api/s-playwright', async (req, res) => { | |
| const { code, lang } = req.body; | |
| if (!code || !lang) { | |
| return res.status(400).json({ | |
| success: false, | |
| error: 'Missing required fields: code and lang' | |
| }); | |
| } | |
| const supportedLangs = ['javascript']; | |
| const normalizedLang = lang.toLowerCase(); | |
| if (!supportedLangs.includes(normalizedLang)) { | |
| return res.status(400).json({ | |
| success: false, | |
| error: `Unsupported language: "${lang}". Supported: ${supportedLangs.join(', ')}` | |
| }); | |
| } | |
| try { | |
| const AsyncFunction = Object.getPrototypeOf(async function(){}).constructor; | |
| const executableCode = new AsyncFunction('chromium', 'devices', 'publicDir', 'path', code); | |
| const result = await executableCode(chromium, devices, publicDir, path); | |
| const timestamp = Date.now(); | |
| const baseUrl = `${req.protocol}://${req.get('host')}`; | |
| const screenshotFiles = await fs.readdir(publicDir); | |
| const recentFiles = screenshotFiles | |
| .filter(f => f.startsWith('screenshot-') && f.endsWith('.png')) | |
| .map(f => ({ | |
| name: f, | |
| publicURL: `${baseUrl}/files/${f}` | |
| })); | |
| res.json({ | |
| success: true, | |
| data: { | |
| result: result, | |
| files: recentFiles, | |
| timestamp: timestamp | |
| } | |
| }); | |
| } catch (error) { | |
| res.status(500).json({ | |
| success: false, | |
| error: error.message, | |
| stack: error.stack | |
| }); | |
| } | |
| }); | |
| app.get('/', (req, res) => { | |
| res.json({ | |
| message: 'Playwright API is running', | |
| endpoints: { | |
| 'POST /api/s-playwright': 'Execute playwright code' | |
| } | |
| }); | |
| }); | |
| app.listen(PORT, '0.0.0.0', () => { | |
| console.log(`Server running on port ${PORT}`); | |
| }); |