2026-02-10 00:42:48 +01:00
|
|
|
import { createServer } from 'http'
|
|
|
|
|
import express from 'express'
|
|
|
|
|
import { WebSocketServer } from 'ws'
|
2026-06-21 00:36:02 +02:00
|
|
|
import { fileURLToPath, pathToFileURL } from 'url'
|
2026-02-10 00:42:48 +01:00
|
|
|
import { dirname, join } from 'path'
|
2026-02-10 09:53:46 +01:00
|
|
|
import { setupWebSocketHandler } from './src/websocket-handler.js'
|
|
|
|
|
import { printServerInfo } from './src/server-utils.js'
|
2026-05-12 14:08:06 +02:00
|
|
|
import { loadState, saveState } from './src/persist.js'
|
2026-02-10 00:42:48 +01:00
|
|
|
|
|
|
|
|
const __filename = fileURLToPath(import.meta.url)
|
|
|
|
|
const __dirname = dirname(__filename)
|
|
|
|
|
|
2026-06-21 00:36:02 +02:00
|
|
|
const DIST_DIR = join(__dirname, 'dist')
|
|
|
|
|
|
|
|
|
|
// Crea l'app Express (asset statici + route display/controller) senza avviare il
|
|
|
|
|
// listen né il WebSocket: così il routing è testabile in isolamento.
|
|
|
|
|
export function createApp(distDir = DIST_DIR) {
|
|
|
|
|
const app = express()
|
|
|
|
|
|
|
|
|
|
app.use(express.static(distDir, { index: false }))
|
|
|
|
|
|
|
|
|
|
app.get(['/', '/display', '/display/*splat'], (_req, res) => {
|
|
|
|
|
res.sendFile(join(distDir, 'index.html'))
|
|
|
|
|
})
|
|
|
|
|
|
|
|
|
|
app.get(['/controller', '/controller/*splat'], (_req, res) => {
|
|
|
|
|
res.sendFile(join(distDir, 'controller.html'))
|
|
|
|
|
})
|
|
|
|
|
|
|
|
|
|
return app
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Avvia HTTP + WebSocket. Lo stato viene caricato da disco e ripersistito ad ogni azione.
|
|
|
|
|
export function startServer(port = process.env.PORT || 3000) {
|
|
|
|
|
const app = createApp()
|
|
|
|
|
const server = createServer(app)
|
|
|
|
|
const wss = new WebSocketServer({ noServer: true })
|
|
|
|
|
setupWebSocketHandler(wss, { initialState: loadState(), onStateChange: saveState })
|
|
|
|
|
|
|
|
|
|
server.on('upgrade', (request, socket, head) => {
|
|
|
|
|
const pathname = new URL(request.url, `http://${request.headers.host}`).pathname
|
|
|
|
|
if (pathname === '/ws') {
|
|
|
|
|
wss.handleUpgrade(request, socket, head, (ws) => {
|
|
|
|
|
wss.emit('connection', ws, request)
|
|
|
|
|
})
|
|
|
|
|
} else {
|
|
|
|
|
socket.destroy()
|
|
|
|
|
}
|
|
|
|
|
})
|
|
|
|
|
|
|
|
|
|
server.listen(port, '0.0.0.0', () => {
|
|
|
|
|
printServerInfo(port)
|
|
|
|
|
})
|
|
|
|
|
|
|
|
|
|
return server
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Avvia solo se eseguito direttamente (`node server.js`), non quando importato nei test.
|
|
|
|
|
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
|
|
|
|
|
startServer()
|
|
|
|
|
}
|