-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhttpserve
More file actions
executable file
·831 lines (727 loc) · 23.1 KB
/
Copy pathhttpserve
File metadata and controls
executable file
·831 lines (727 loc) · 23.1 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
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
#!/usr/bin/env -S deno run -RN --allow-run
import { parseArgs } from "@std/cli";
import { join, resolve, normalize } from "@std/path";
import { contentType } from "@std/media-types";
interface Config {
directory: string;
port: number;
ignorePatterns: string[];
enableDirectoryListing: boolean;
logLevel: "info" | "debug" | "error";
enableLiveReload: boolean;
restartOnChange: boolean;
}
interface FileEntry {
name: string;
isDirectory: boolean;
url: string;
}
const DEFAULT_CONFIG: Config = {
directory: import.meta.dirname ?? ".",
port: 8080,
ignorePatterns: [".git", "node_modules", ".DS_Store"],
enableDirectoryListing: true,
logLevel: "info",
enableLiveReload: true,
restartOnChange: false,
};
let debounceTimeout: number | null = null;
let isProcessingChange = false;
const liveReloadClients = new Set<WebSocket>();
const parseArguments = (args: string[]): Config => {
const parsed = parseArgs(args, {
string: ["dir", "port", "ignore", "log"],
boolean: ["no-listing", "help", "no-live-reload", "restart-on-change"],
default: {
dir: DEFAULT_CONFIG.directory,
port: DEFAULT_CONFIG.port.toString(),
ignore: DEFAULT_CONFIG.ignorePatterns.join(","),
log: DEFAULT_CONFIG.logLevel,
"no-listing": false,
"no-live-reload": false,
"restart-on-change": false,
},
alias: {
d: "dir",
p: "port",
i: "ignore",
h: "help",
},
});
if (parsed.help) {
console.log(`
Static File Server with Auto-Reload
Usage: httpreload [OPTIONS]
Options:
-d, --dir <directory> Directory to serve (default: current directory)
-p, --port <port> Port to listen on (default: 8080)
-i, --ignore <patterns> Comma-separated patterns to ignore (default: .git,node_modules,.DS_Store)
--no-listing Disable directory listing
--no-live-reload Disable live reload feature
--restart-on-change Restart server process on file changes (default: browser reload only)
--log <level> Log level: info, debug, error (default: info)
-h, --help Show this help message
Examples:
httpreload # Smart mode: browser reload for HTML/CSS/JS, server restart for config
httpreload --dir ./public --port 3000 # Serve from ./public on port 3000
httpreload --restart-on-change # Legacy mode: always restart server on any file change
httpreload --no-live-reload # Disable all live reload features
httpreload --ignore "*.log,temp*" --no-listing
`);
Deno.exit(0);
}
const port = parseInt(parsed.port);
if (isNaN(port) || port < 1 || port > 65535) {
throw new Error("Port must be a valid number between 1 and 65535");
}
return {
directory: resolve(parsed.dir),
port,
ignorePatterns: parsed.ignore.split(",").map((pattern) => pattern.trim()),
enableDirectoryListing: !parsed["no-listing"],
logLevel: parsed.log as Config["logLevel"],
enableLiveReload: !parsed["no-live-reload"],
restartOnChange: parsed["restart-on-change"],
};
};
/**
* Logs a message to the console.
* @param message - The message to log
* @param level - The log level (info, debug, error)
* @returns void
*/
const log = (message: string, level: Config["logLevel"] = "info"): void => {
const timestamp = new Date().toISOString();
const prefix = level.toUpperCase().padEnd(5);
console.log(`[${timestamp}] ${prefix} ${message}`);
};
/**
* Checks if a file change event should be ignored based on ignore patterns.
* @param event - The file system event
* @param ignorePatterns - Patterns to ignore
* @returns True if the event should be ignored, false otherwise
*/
const shouldIgnoreEvent = (
event: Deno.FsEvent,
ignorePatterns: string[]
): boolean =>
event.paths.some((path) =>
ignorePatterns.some(
(pattern) => path.includes(pattern) || path.endsWith(pattern)
)
);
/**
* Determines if the server should be restarted based on changed file paths.
* @param filePaths - The list of changed file paths
* @returns True if the server should be restarted, false otherwise
*/
const shouldRestartServer = (filePaths: string[]): boolean => {
// Files that should trigger server restart (server configuration, executable changes)
const serverRestartPatterns = [
/\.ts$/, // TypeScript server files
/\.js$/, // JavaScript server files (if server code)
/\.mjs$/, // ES modules
/\.json$/, // Configuration files
/\.toml$/, // Configuration files
/\.yaml$/, // Configuration files
/\.yml$/, // Configuration files
/deno\.json/, // Deno config
/deno\.lock/, // Deno lock file
/package\.json/, // Node package file
];
return filePaths.some((path) =>
serverRestartPatterns.some((pattern) => pattern.test(path))
);
};
/**
* Checks if the server should trigger a browser reload based on changed file paths.
* @param filePaths - The list of changed file paths
* @returns True if the server should trigger a browser reload, false otherwise
*/
const shouldTriggerBrowserReload = (filePaths: string[]): boolean => {
// Files that should trigger browser reload (frontend assets)
const browserReloadPatterns = [
/\.html?$/, // HTML files
/\.css$/, // CSS files
/\.s[ac]ss$/, // Sass/SCSS files
/\.less$/, // Less files
/\.js$/, // JavaScript files (frontend)
/\.jsx$/, // React JSX files
/\.ts$/, // TypeScript files (frontend)
/\.tsx$/, // React TSX files
/\.vue$/, // Vue files
/\.svelte$/, // Svelte files
/\.md$/, // Markdown files
/\.(png|jpe?g|gif|svg|webp|ico)$/, // Images
/\.(woff2?|ttf|eot)$/, // Fonts
/\.json$/, // JSON data files (could be frontend data)
];
return filePaths.some((path) =>
browserReloadPatterns.some((pattern) => pattern.test(path))
);
};
/**
* Debounces a function call to prevent rapid successive calls.
* @param ms - The debounce delay in milliseconds
* @returns A promise that resolves after the delay
*/
const debounce = (ms: number): Promise<void> => {
return new Promise((resolve) => {
// Clear any existing timeout
if (debounceTimeout !== null) {
clearTimeout(debounceTimeout);
debounceTimeout = null;
}
// Set new timeout
debounceTimeout = setTimeout(() => {
debounceTimeout = null;
resolve();
}, ms);
});
};
/**
* Resolves a safe path within the base directory, preventing directory traversal attacks.
* @param baseDir - The base directory to resolve against
* @param requestPath - The requested path
* @returns The resolved path or null if it's outside the base directory
*/
const resolveSafePath = (
baseDir: string,
requestPath: string
): string | null => {
try {
const normalizedPath = normalize(requestPath);
const fullPath = join(baseDir, normalizedPath);
const resolvedPath = resolve(fullPath);
const resolvedBase = resolve(baseDir);
// Ensure the resolved path is within the base directory
if (!resolvedPath.startsWith(resolvedBase)) {
return null;
}
return resolvedPath;
} catch {
return null;
}
};
/**
* Gets the MIME type for a file based on its extension.
* @param filePath - The path of the file to get the MIME type for
* @returns The MIME type of the file
*/
const getMimeType = (filePath: string): string =>
contentType(filePath.split(".").at(-1) || "") || "application/octet-stream";
/**
* Generates the live reload script for the client.
* @param port - The port number for the WebSocket connection
* @returns The live reload script as a string
*/
const getLiveReloadScript = (port: number): string => {
return /*html*/`
<script>
(() => {
const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
const wsUrl = \`\${protocol}//\${window.location.hostname}:\${${port}}/livereload\`;
const connect = () => {
const ws = new WebSocket(wsUrl);
ws.onopen = () => {
console.log('[Live Reload] Connected');
};
ws.onmessage = (event) => {
if (event.data === 'reload') {
console.log('[Live Reload] Reloading page...');
window.location.reload();
}
};
ws.onclose = () => {
console.log('[Live Reload] Connection closed, attempting to reconnect...');
setTimeout(connect, 1000);
};
ws.onerror = () => {
console.log('[Live Reload] Connection error, attempting to reconnect...');
setTimeout(connect, 1000);
};
};
connect();
})();
</script>`;
};
/**
* Injects the live reload script into an HTML document.
* @param html - The original HTML content
* @param port - The port number for the WebSocket connection
* @returns The modified HTML content with the live reload script injected
*/
const injectLiveReloadScript = (html: string, port: number): string => {
const script = getLiveReloadScript(port);
if (html.includes("</body>")) {
return html.replace("</body>", `${script}\n</body>`);
} else if (html.includes("</html>")) {
return html.replace("</html>", `${script}\n</html>`);
} else {
return html + script;
}
};
const getCSSStyles = (): string =>
/*css*/ `
:root {
--bg-page: #f2f2f2;
--bg-article: #bbc3db;
--color-title: #333;
--color-paragraph: #333;
--link-color: #1a0dab;
--link-hover-color: #d93025;
--toggle-color: #0f172b;
--fill-icons: white;
}
:root:has(#dark:checked) {
--bg-page: #333;
--bg-article: #444;
--color-title: #eee;
--color-paragraph: #ddd;
--link-color: #bb86fc;
--link-hover-color: #ff79c6;
--toggle-color: #0f172b;
--fill-icons: white;
}
body {
font-family: monospace;
font-size: 1.3em;
margin: 0.5em;
padding: 1em;
background-color: var(--bg-page);
color: var(--color-paragraph);
&:has(#dark:checked) {
background-color: var(--bg-article);
color: var(--color-title);
}
}
h1 {
font-size: 2em;
margin-bottom: 0.5em;
}
a {
text-decoration: none;
color: var(--link-color);
&:hover {
text-decoration: underline;
color: var(--link-hover-color);
}
}
.toggle {
--width: 3em;
--height: calc(var(--width) / 2);
--border-radius: calc(var(--height) / 2);
display: inline-block;
cursor: pointer;
.toggle__input {
display: none;
&:checked + .toggle__fill {
background: #009578;
}
&:checked + .toggle__fill::after {
transform: translateX(var(--height));
}
}
.toggle__fill {
position: relative;
width: var(--width);
height: var(--height);
border-radius: var(--border-radius);
background-color: var(--toggle-color);
transition: background-color 0.3s ease-in-out;
&::after {
content: "";
position: absolute;
top: 0;
left: 0;
width: var(--height);
height: var(--height);
border-radius: var(--border-radius);
background-color: var(--fill-icons);
box-shadow: 0 0 0.2em rgba(0, 0, 0, 0.2);
transition: transform 0.3s ease-in-out;
}
}
}
`.trim();
/**
* Generates the HTML for a directory listing.
* @param entries - The list of file entries in the directory
* @param urlPath - The URL path for the directory
* @returns The HTML string for the directory listing
*/
const generateDirectoryListingHTML = (
entries: FileEntry[],
urlPath: string
): string => {
const parentDir = urlPath === "/" ? "" : `<a href="../">../</a><br>`;
const entryLinks = entries
.sort((a, b) => {
if (a.isDirectory && !b.isDirectory) return -1;
if (!a.isDirectory && b.isDirectory) return 1;
return a.name.localeCompare(b.name);
})
.map((entry) => {
const icon = entry.isDirectory ? "📁" : "📄";
const href = entry.url === "/" ? `/${entry.name}` : `${entry.url}`;
return `<a href="${href}">${icon} ${entry.name}</a>`;
})
.join("<br>");
// Theme toggle radio buttons and labels (no JS, pure CSS)
const themeToggle = /*html*/ `
<label class="toggle" for="dark">
<input type="checkbox" name="toggle" id="dark" class="toggle__input" checked>
<span class="toggle__fill"></span>
</label>
`;
return /*html*/ `
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Directory listing for ${urlPath}</title>
<style>
${getCSSStyles()}
</style>
</head>
<body>
${themeToggle}
<h1>Directory listing for ${urlPath}</h1>
${parentDir}
${entryLinks}
</body>
</html>
`.trim();
};
/**
* Handles WebSocket connections for live reload.
* @param request - The incoming WebSocket upgrade request
* @returns The WebSocket response
*/
const handleWebSocket = (request: Request): Response => {
const { socket, response } = Deno.upgradeWebSocket(request);
socket.onopen = () => {
liveReloadClients.add(socket);
log(
`Live reload client connected. Total clients: ${liveReloadClients.size}`,
"debug"
);
};
socket.onclose = () => {
liveReloadClients.delete(socket);
log(
`Live reload client disconnected. Total clients: ${liveReloadClients.size}`,
"debug"
);
};
socket.onerror = () => {
liveReloadClients.delete(socket);
log(
`Live reload client error. Total clients: ${liveReloadClients.size}`,
"debug"
);
};
return response;
};
const notifyLiveReloadClients = (reason = "file change"): void => {
if (liveReloadClients.size === 0) {
log(`No live reload clients connected`, "debug");
return;
}
let successCount = 0;
let clientsToRemove: WebSocket[] = [];
for (const client of liveReloadClients) {
try {
if (client.readyState === WebSocket.OPEN) {
client.send("reload");
successCount++;
} else {
// Client is not in OPEN state, mark for removal
clientsToRemove = [...clientsToRemove, client];
}
} catch (error) {
// Client connection failed, mark for removal
clientsToRemove = [...clientsToRemove, client];
log(`Failed to send reload signal to client: ${error}`, "debug");
}
}
// Remove stale clients
clientsToRemove.forEach((client) => liveReloadClients.delete(client));
log(`Sent reload signal to ${successCount} clients (${reason})`, "info");
if (clientsToRemove.length > 0) {
log(`Removed ${clientsToRemove.length} stale client connections`, "debug");
}
};
/**
* Serves a file from the filesystem.
* @param filePath - The path of the file to serve
* @param config - The server configuration
* @returns The HTTP response for the file
*/
const serveFile = async (
filePath: string,
config: Config
): Promise<Response> => {
const file = await Deno.open(filePath, { read: true });
const mimeType = getMimeType(filePath);
// If it's an HTML file and live reload is enabled, inject the script
if (config.enableLiveReload && mimeType.includes("text/html")) {
const content = await file.readable.getReader().read();
file.close();
if (content.value) {
const html = new TextDecoder().decode(content.value);
const modifiedHtml = injectLiveReloadScript(html, config.port);
return new Response(modifiedHtml, {
headers: {
"content-type": mimeType,
"cache-control": "no-cache",
},
});
}
}
return new Response(file.readable, {
headers: {
"content-type": mimeType,
"cache-control": "no-cache",
},
});
};
/**
* Serves a directory listing as HTML.
* @param dirPath - The path of the directory to list
* @param urlPath - The URL path for the directory
* @param config - The server configuration
* @returns The HTTP response with the directory listing
*/
const serveDirectory = async (
dirPath: string,
urlPath: string,
config: Config
): Promise<Response> => {
const entries: FileEntry[] = (await Array.fromAsync(Deno.readDir(dirPath)))
.filter(
(entry) =>
!config.ignorePatterns.some((pattern) => entry.name.includes(pattern))
)
.map((entry) => ({
name: entry.name,
isDirectory: entry.isDirectory,
url: urlPath === "/" ? `/${entry.name}` : `${urlPath}/${entry.name}`,
}));
let html = generateDirectoryListingHTML(entries, urlPath);
if (config.enableLiveReload) {
html = injectLiveReloadScript(html, config.port);
}
return new Response(html, {
headers: { "content-type": "text/html; charset=utf-8" },
});
};
/**
* Creates a request handler for serving files and directories.
* @param config - The server configuration
* @returns The request handler function
*/
const createRequestHandler =
(config: Config) =>
async (request: Request): Promise<Response> => {
const url = new URL(request.url);
const pathname = decodeURIComponent(url.pathname);
log(`${request.method} ${pathname}`, "debug");
// Handle WebSocket upgrade for live reload
if (
config.enableLiveReload &&
pathname === "/livereload" &&
request.headers.get("upgrade") === "websocket"
) {
return handleWebSocket(request);
}
// Security: Prevent directory traversal
const safePath = resolveSafePath(config.directory, pathname);
if (!safePath) {
log(`Forbidden access attempt: ${pathname}`, "error");
return new Response("Forbidden", { status: 403 });
}
try {
const fileInfo = await Deno.stat(safePath);
if (fileInfo.isFile) {
return await serveFile(safePath, config);
} else if (fileInfo.isDirectory) {
if (config.enableDirectoryListing) {
return await serveDirectory(safePath, pathname, config);
} else {
// Try to serve index.html
const indexPath = join(safePath, "index.html");
try {
await Deno.stat(indexPath);
return await serveFile(indexPath, config);
} catch {
return new Response("Directory listing disabled", { status: 403 });
}
}
}
} catch (error) {
if (error instanceof Deno.errors.NotFound) {
log(`File not found: ${pathname}`, "error");
return new Response("Not Found", { status: 404 });
}
log(`Server error: ${(error as Error).message}`, "error");
return new Response("Internal Server Error", { status: 500 });
}
return new Response("Bad Request", { status: 400 });
};
/**
* Starts the file watcher to monitor changes in the specified directory.
* @param config - The server configuration
* @param abortController - The AbortController to handle graceful shutdown
* @returns A promise that resolves when the watcher is started
*/
const startFileWatcher = async (
config: Config,
abortController: AbortController
): Promise<void> => {
const watcher = Deno.watchFs(config.directory);
log(`Watching for file changes in: ${config.directory}`);
if (config.restartOnChange) {
log("Mode: Server restart on file changes");
} else {
log("Mode: Browser reload on file changes (server stays alive)");
}
for await (const event of watcher) {
if (abortController.signal.aborted) break;
if (shouldIgnoreEvent(event, config.ignorePatterns)) continue;
// Skip if we're already processing a change
if (isProcessingChange) {
log(
`Skipping duplicate file change event: ${
event.kind
} - ${event.paths.join(", ")}`,
"debug"
);
continue;
}
log(`File change detected: ${event.kind} - ${event.paths.join(", ")}`);
// Set processing flag to prevent duplicate events
isProcessingChange = true;
try {
// Debounce rapid changes
await debounce(500);
if (abortController.signal.aborted) continue;
// Determine action based on configuration and file types
if (config.restartOnChange) {
// Legacy mode: always restart server
log("Legacy mode: Restarting server for any file change");
if (config.enableLiveReload) {
notifyLiveReloadClients("server restart");
await new Promise((resolve) => setTimeout(resolve, 100));
}
reloadServer();
} else {
// Smart mode: decide based on file types
const shouldRestart = shouldRestartServer(event.paths);
const shouldReload = shouldTriggerBrowserReload(event.paths);
log(
`File analysis: restart=${shouldRestart}, reload=${shouldReload}`,
"debug"
);
if (shouldRestart) {
log("Server configuration files changed, restarting server...");
if (config.enableLiveReload) {
notifyLiveReloadClients("server restart");
await new Promise((resolve) => setTimeout(resolve, 100));
}
reloadServer();
} else if (shouldReload && config.enableLiveReload) {
log("Frontend files changed, triggering browser reload...");
notifyLiveReloadClients("frontend change");
// Note: Server stays alive, only browsers reload
} else {
log(
"File change detected but no action taken (not a monitored file type)"
);
}
}
} finally {
// Reset processing flag after a delay to allow for any remaining events to be ignored
setTimeout(() => {
isProcessingChange = false;
}, 1000);
}
}
};
/**
* Starts the HTTP server to serve files and directories.
* @param config - The server configuration
* @param abortController - The AbortController to handle graceful shutdown
* @returns A promise that resolves when the server is started
*/
const startHttpServer = async (
config: Config,
abortController: AbortController
): Promise<void> => {
const handler = createRequestHandler(config);
log(`Starting server on http://localhost:${config.port}`);
log(`Serving directory: ${config.directory}`);
await Deno.serve({
port: config.port,
signal: abortController.signal,
handler,
}).finished;
};
const reloadServer = (): void => {
log("Reloading server...");
// Create new process with same arguments
const command = new Deno.Command(Deno.execPath(), {
args: ["run", "-NR", "--allow-run", import.meta.url, ...Deno.args],
});
// Start new process
command.spawn();
// Exit current process
Deno.exit(0);
};
/**
* Sets up signal handlers for graceful shutdown.
* @param abortController - The AbortController to handle shutdown
* @returns void
*/
const setupSignalHandlers = (abortController: AbortController): void => {
const signals = ["SIGINT", "SIGTERM"] as const;
signals.forEach((signal) => {
Deno.addSignalListener(signal, () => {
log(`Received ${signal}, shutting down gracefully...`);
abortController.abort();
Deno.exit(0);
});
});
};
const main = async (): Promise<void> => {
try {
const config = parseArguments(Deno.args);
// Validate directory exists
try {
const dirInfo = await Deno.stat(config.directory);
if (!dirInfo.isDirectory) {
throw new Error(`${config.directory} is not a directory`);
}
} catch (error) {
if (error instanceof Deno.errors.NotFound) {
throw new Error(`Directory not found: ${config.directory}`);
}
throw error;
}
const abortController = new AbortController();
// Setup graceful shutdown
setupSignalHandlers(abortController);
// Start file watcher and HTTP server concurrently
await Promise.race([
startFileWatcher(config, abortController),
startHttpServer(config, abortController),
]);
} catch (error) {
log(`Error: ${(error as Error).message}`, "error");
Deno.exit(1);
}
};
// Run the server
if (import.meta.main) {
await main();
}