Spaces:
Paused
Paused
| const WebSocket = require('ws'); | |
| const pty = require('node-pty'); | |
| const http = require('http'); | |
| const express = require('express'); | |
| const path = require('path'); | |
| console.log('===== Application Startup ====='); | |
| // Initialize Express for serving static files and health check | |
| const app = express(); | |
| // Serve static files from the public directory | |
| app.use(express.static(path.join(__dirname, '../public'))); | |
| // Health check endpoint | |
| app.get('/health', (req, res) => { | |
| res.status(200).json({ status: 'OK', timestamp: new Date().toISOString() }); | |
| }); | |
| // Create HTTP server | |
| const server = http.createServer(app); | |
| // Initialize WebSocket server | |
| const wss = new WebSocket.Server({ server }); | |
| wss.on('connection', (ws) => { | |
| console.log('New WebSocket client connected'); | |
| try { | |
| // Spawn a new shell (bash) for the connection | |
| const shell = pty.spawn('bash', [], { | |
| name: 'xterm-color', | |
| env: process.env, | |
| }); | |
| // Relay terminal output to the client | |
| shell.onData((data) => { | |
| ws.send(data); | |
| }); | |
| // Handle input from the client | |
| ws.on('message', (message) => { | |
| shell.write(message.toString()); | |
| }); | |
| // Handle terminal exit | |
| shell.onExit(({ exitCode }) => { | |
| console.log(`Shell exited with code ${exitCode}`); | |
| ws.close(); | |
| }); | |
| // Handle WebSocket close | |
| ws.on('close', () => { | |
| shell.kill(); | |
| console.log('WebSocket client disconnected'); | |
| }); | |
| } catch (error) { | |
| console.error('Error spawning shell:', error.message); | |
| ws.send(`Error: Failed to spawn shell - ${error.message}\r\n`); | |
| ws.close(); | |
| } | |
| }); | |
| wss.on('error', (error) => { | |
| console.error('WebSocket server error:', error.message); | |
| }); | |
| // Start the server on port 7860 | |
| const PORT = process.env.PORT || 7860; | |
| server.listen(PORT, () => { | |
| console.log(`Server running on port ${PORT}`); | |
| console.log(`Health check available at http://localhost:${PORT}/health`); | |
| }); | |
| server.on('error', (error) => { | |
| console.error('HTTP server error:', error.message); | |
| }); | |
| // Log Node.js and dependency versions for debugging | |
| console.log(`Node.js version: ${process.version}`); | |
| try { | |
| console.log(`ws version: ${require('ws/package.json').version}`); | |
| console.log(`node-pty version: ${require('node-pty/package.json').version}`); | |
| console.log(`express version: ${require('express/package.json').version}`); | |
| } catch (error) { | |
| console.error('Error loading dependency versions:', error.message); | |
| }; |