-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.ts
More file actions
222 lines (183 loc) Β· 5.74 KB
/
main.ts
File metadata and controls
222 lines (183 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
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
import { handleBlastemUPWebSocket } from './blastemup.server.ts';
// Configuration
const CONFIG = {
port: 8000,
publicDir: './static',
buildOutput: './static/js'
} as const;
// MIME types for file serving
const MIME_TYPES: Record<string, string> = {
'.html': 'text/html',
'.js': 'application/javascript',
'.css': 'text/css',
'.json': 'application/json',
'.png': 'image/png',
'.jpg': 'image/jpeg',
'.jpeg': 'image/jpeg',
'.gif': 'image/gif',
'.svg': 'image/svg+xml',
'.ico': 'image/x-icon',
'.txt': 'text/plain',
'.pdf': 'application/pdf',
'.zip': 'application/zip',
'.woff': 'font/woff',
'.woff2': 'font/woff2',
'.ttf': 'font/ttf',
'.otf': 'font/otf',
} as const;
interface ReloadResponse {
success: boolean;
clients: number;
}
// Global state
const reloadConnections = new Set<WebSocket>();
// Utility functions
function getContentType(filePath: string): string {
const ext = filePath.substring(filePath.lastIndexOf('.'));
return MIME_TYPES[ext] || 'application/octet-stream';
}
function isPathSecure(pathname: string): boolean {
return !pathname.includes('..') && !pathname.startsWith('/');
}
function normalizePath(pathname: string): string {
// Remove leading slash and decode URI
pathname = decodeURIComponent(pathname.slice(1));
// Default to index.html if no path or path ends with /
if (!pathname || pathname.endsWith('/')) {
pathname = pathname + 'index.html';
}
return pathname;
}
// File serving
async function serveFile(filePath: string): Promise<Response> {
try {
const file = await Deno.open(filePath, { read: true });
const fileInfo = await file.stat();
const body = file.readable;
return new Response(body, {
headers: {
'Content-Type': getContentType(filePath),
'Content-Length': fileInfo.size.toString()
},
});
} catch (error) {
if (error instanceof Deno.errors.NotFound) {
return new Response('File not found', { status: 404 });
}
console.error('Error serving file:', error);
return new Response('Internal server error', { status: 500 });
}
}
// WebSocket handling for live reload
function handleWebSocket(request: Request): Response {
if (request.headers.get('upgrade') !== 'websocket') {
return new Response(null, { status: 501 });
}
const { socket, response } = Deno.upgradeWebSocket(request);
socket.onopen = () => {
console.log('π€ Live reload client connected');
reloadConnections.add(socket);
};
socket.onclose = () => {
console.log('π Live reload client disconnected');
reloadConnections.delete(socket);
};
socket.onerror = (error) => {
console.error('π€· Live reload WebSocket error:', error);
reloadConnections.delete(socket);
};
return response;
}
// API handlers
function handleReloadApi(_request: Request): Response {
console.log(`π Triggering reload for ${reloadConnections.size} clients`);
reloadConnections.forEach((ws) => {
try {
ws.send('reload');
} catch (error) {
console.error(`π© Error sending reload signal: ${error}`);
reloadConnections.delete(ws);
}
});
const response: ReloadResponse = {
success: true,
clients: reloadConnections.size,
};
return new Response(JSON.stringify(response), {
status: 200,
headers: { 'Content-Type': 'application/json' },
});
}
async function triggerReload(): Promise<void> {
try {
const response = await fetch(`http://localhost:${CONFIG.port}/api/reload`, {
method: 'GET',
});
if (response.ok) {
const data = await response.json();
console.log(`π Reload triggered for ${data.clients} clients`);
}
} catch (_error) {
// Server might not be running yet, ignore the error
console.log('π€·ββοΈ Could not trigger reload (server not ready)');
}
}
// Watch mode
async function startWatchMode(): Promise<void> {
console.log('π Starting watch mode...');
try { await Deno.mkdir(CONFIG.buildOutput) } catch { ()=>{} } // do nothing if dir doesn't exist
// Watch for file changes
const watcher = Deno.watchFs([CONFIG.buildOutput], { recursive: true });
for await (const event of watcher) {
const isTypeScriptFile = event.paths.some((path) => path.endsWith('.js'));
if (event.kind === 'modify' && isTypeScriptFile) {
console.log('π File changed:', event.paths);
await triggerReload();
}
}
}
// Main request handler
async function requestHandler(request: Request): Promise<Response> {
const url = new URL(request.url);
let pathname = url.pathname;
// Handle WebSocket upgrade for live reload
if (pathname === '/ws/reload') {
return handleWebSocket(request);
}
if (pathname == '/ws/blastemup') {
return handleBlastemUPWebSocket(request);
}
// Handle reload API
if (pathname === '/api/reload') {
return handleReloadApi(request);
}
// Normalize and validate file path
pathname = normalizePath(pathname);
// Security: prevent directory traversal
if (!isPathSecure(pathname)) {
return new Response('Forbidden', { status: 403 });
}
// Construct file path
const filePath = `${CONFIG.publicDir}/${pathname}`;
// For debug only
// console.log(`Serving: ${filePath}`);
return await serveFile(filePath);
}
// Main execution
async function main(): Promise<void> {
try {
// Start watch mode (includes initial build)
startWatchMode();
console.log('Place your index.html and other files to serve in the public directory');
console.log(`π Server running at http://localhost:${CONFIG.port}`);
// Start the HTTP server
await Deno.serve({ port: CONFIG.port }, requestHandler);
} catch (error) {
console.error('β Failed to start server:', error);
Deno.exit(1);
}
}
// Start the application
if (import.meta.main) {
main();
}