@@ -17,6 +17,10 @@ if (isProduction && !fs.existsSync(STATIC_DIR)) throw new Error(`Serve directory
1717const PORT = process . env . PORT || 3000 ;
1818const wsClients = new Set ( ) ;
1919
20+ const LOG_DIR = path . join ( __dirname , 'logs' ) ;
21+ const LOG_FILE = path . join ( LOG_DIR , 'events.jsonl' ) ;
22+ if ( ! fs . existsSync ( LOG_DIR ) ) fs . mkdirSync ( LOG_DIR , { recursive : true } ) ;
23+
2024const mimeTypes = {
2125 '.html' : 'text/html' , '.js' : 'text/javascript' , '.css' : 'text/css' ,
2226 '.json' : 'application/json' , '.png' : 'image/png' , '.jpg' : 'image/jpeg' ,
@@ -32,7 +36,45 @@ function serveFile(filePath, res) {
3236 } ) ;
3337}
3438
39+ function readBody ( req ) {
40+ return new Promise ( ( resolve , reject ) => {
41+ let body = '' ;
42+ req . on ( 'data' , chunk => { body += chunk . toString ( ) ; } ) ;
43+ req . on ( 'end' , ( ) => {
44+ try { resolve ( JSON . parse ( body ) ) ; }
45+ catch ( e ) { reject ( e ) ; }
46+ } ) ;
47+ req . on ( 'error' , reject ) ;
48+ } ) ;
49+ }
50+
51+ async function handleLogRequest ( req , res ) {
52+ try {
53+ const data = await readBody ( req ) ;
54+ const entries = data . entries ;
55+ if ( ! Array . isArray ( entries ) || entries . length === 0 ) {
56+ res . writeHead ( 400 , { 'Content-Type' : 'application/json' } ) ;
57+ res . end ( JSON . stringify ( { error : 'entries array is required' } ) ) ;
58+ return ;
59+ }
60+ const lines = entries . map ( e => JSON . stringify ( e ) ) . join ( '\n' ) + '\n' ;
61+ fs . appendFile ( LOG_FILE , lines , ( err ) => {
62+ if ( err ) console . error ( 'Failed to write log:' , err ) ;
63+ } ) ;
64+ res . writeHead ( 200 , { 'Content-Type' : 'application/json' } ) ;
65+ res . end ( JSON . stringify ( { ok : true , count : entries . length } ) ) ;
66+ } catch ( error ) {
67+ res . writeHead ( 400 , { 'Content-Type' : 'application/json' } ) ;
68+ res . end ( JSON . stringify ( { error : 'Invalid JSON' } ) ) ;
69+ }
70+ }
71+
3572function handlePostRequest ( req , res , parsedUrl ) {
73+ if ( parsedUrl . pathname === '/api/log' ) {
74+ handleLogRequest ( req , res ) ;
75+ return ;
76+ }
77+
3678 if ( parsedUrl . pathname === '/message' ) {
3779 let body = '' ;
3880 req . on ( 'data' , c => { body += c . toString ( ) ; } ) ;
0 commit comments