forked from dualshock-tools/dualshock-tools.github.io
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdev-server.js
More file actions
183 lines (159 loc) · 5.74 KB
/
dev-server.js
File metadata and controls
183 lines (159 loc) · 5.74 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
#!/usr/bin/env node
import https from 'https';
import http from 'http';
import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
// Configuration
const config = {
port: process.env.PORT || 8443,
httpPort: process.env.HTTP_PORT || 8080,
host: process.env.HOST || 'localhost',
distDir: path.join(__dirname, 'dist'),
certFile: path.join(__dirname, 'server.crt'),
keyFile: path.join(__dirname, 'server.key'),
useHttps: process.env.HTTPS === 'true'
};
// MIME types
const mimeTypes = {
'.html': 'text/html',
'.js': 'text/javascript',
'.css': 'text/css',
'.json': 'application/json',
'.png': 'image/png',
'.jpg': 'image/jpeg',
'.gif': 'image/gif',
'.svg': 'image/svg+xml',
'.ico': 'image/x-icon',
'.webmanifest': 'application/manifest+json'
};
function getMimeType(filePath) {
const ext = path.extname(filePath).toLowerCase();
return mimeTypes[ext] || 'application/octet-stream';
}
function requestHandler(req, res) {
// Parse URL and remove query parameters
let urlPath = new URL(req.url, `http://${req.headers.host}`).pathname;
// Default to index.html for root requests
if (urlPath === '/') {
urlPath = '/index.html';
}
const filePath = path.join(config.distDir, urlPath);
const mimeType = getMimeType(filePath);
// Security check - ensure file is within dist directory
if (!filePath.startsWith(config.distDir)) {
res.writeHead(403, { 'Content-Type': 'text/plain' });
res.end('Forbidden');
return;
}
// Set CORS headers for development
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
// Disable caching for development
res.setHeader('Cache-Control', 'no-cache, no-store, must-revalidate');
res.setHeader('Pragma', 'no-cache');
res.setHeader('Expires', '0');
// Handle OPTIONS requests
if (req.method === 'OPTIONS') {
res.writeHead(200);
res.end();
return;
}
fs.readFile(filePath, (err, data) => {
if (err) {
if (err.code === 'ENOENT') {
// Try to serve index.html for SPA routing
const indexPath = path.join(config.distDir, 'index.html');
fs.readFile(indexPath, (indexErr, indexData) => {
if (indexErr) {
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end('Not Found');
} else {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end(indexData);
}
});
} else {
res.writeHead(500, { 'Content-Type': 'text/plain' });
res.end('Internal Server Error');
}
} else {
res.writeHead(200, { 'Content-Type': mimeType });
res.end(data);
}
});
}
function startServer() {
// Check if dist directory exists
if (!fs.existsSync(config.distDir)) {
console.error(`❌ Dist directory not found: ${config.distDir}`);
console.log('💡 Run "npm run build" first to build the application');
process.exit(1);
}
if (config.useHttps) {
// Check if SSL certificates exist
if (!fs.existsSync(config.certFile) || !fs.existsSync(config.keyFile)) {
console.error('❌ SSL certificates not found');
console.log('💡 SSL certificates are required for WebHID API');
console.log(' Make sure server.crt and server.key exist in the project root');
process.exit(1);
}
// Read SSL certificates
const options = {
key: fs.readFileSync(config.keyFile),
cert: fs.readFileSync(config.certFile)
};
// Create HTTPS server
const server = https.createServer(options, requestHandler);
server.listen(config.port, config.host, () => {
console.log('🚀 Development server started!');
console.log(`📱 App running at: https://${config.host}:${config.port}`);
console.log('🔒 HTTPS enabled (required for WebHID API)');
console.log('💡 Press Ctrl+C to stop the server');
console.log('');
console.log('📝 Note: You may need to accept the self-signed certificate in your browser');
});
server.on('error', (err) => {
if (err.code === 'EADDRINUSE') {
console.error(`❌ Port ${config.port} is already in use`);
console.log('💡 Try using a different port: PORT=8444 npm run serve:https');
} else {
console.error('❌ Server error:', err.message);
}
process.exit(1);
});
} else {
// Create HTTP server (for testing only - WebHID won't work)
const server = http.createServer(requestHandler);
server.listen(config.httpPort, config.host, () => {
console.log('🚀 Development server started!');
console.log(`📱 App running at: http://${config.host}:${config.httpPort}`);
console.log('⚠️ HTTP mode - WebHID API will only work on localhost');
console.log('💡 Use "npm run serve:https" to enable WebHID support to other clients on the local network');
console.log('💡 Press Ctrl+C to stop the server');
});
server.on('error', (err) => {
if (err.code === 'EADDRINUSE') {
console.error(`❌ Port ${config.httpPort} is already in use`);
console.log('💡 Try using a different port: HTTP_PORT=8081 npm run serve');
} else {
console.error('❌ Server error:', err.message);
}
process.exit(1);
});
}
}
// Handle graceful shutdown
process.on('SIGINT', () => {
console.log('\n👋 Shutting down development server...');
process.exit(0);
});
process.on('SIGTERM', () => {
console.log('\n👋 Shutting down development server...');
process.exit(0);
});
// Start the server
startServer();