-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.ts
More file actions
149 lines (124 loc) · 3.74 KB
/
index.ts
File metadata and controls
149 lines (124 loc) · 3.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
import { mergeReadableStreams } from 'https://deno.land/std@0.126.0/streams/merge.ts';
import { createArgumentMap, html, log } from './utils.ts';
import {
WebSocketClient,
WebSocketServer,
} from 'https://deno.land/x/websocket@v0.1.4/mod.ts';
import { serve } from 'https://deno.land/std@0.141.0/http/server.ts';
const args = createArgumentMap();
const PORT = args['-p'] ?? 3000;
const HOSTNAME = args['--host'] ?? '0.0.0.0';
const [SOCKET_PORT, REFRESH_MESSAGE] = [Number(PORT) + 1, 'refresh'];
const DIR_TO_WATCH = args['-d'] ?? '';
if (args['-h']) {
log.help();
Deno.exit(0);
}
serve(handler, {
port: Number(PORT),
hostname: HOSTNAME,
onListen({ hostname, port }) {
console.clear();
log.info(
`Server is running, see ${
log.Colors.underline(`http://${hostname}:${port}`)
}`,
);
},
});
async function handler(request: Request) {
const url = new URL(request.url);
const filepath = decodeURIComponent(url.pathname);
let file, filename;
try {
[file, filename] = await readFile(`./${DIR_TO_WATCH}${filepath}`);
} catch {
const notFoundResponse = new Response('404 Not Found', {
status: 404,
});
return notFoundResponse;
}
let fileStream;
if (filename.endsWith('.html')) {
fileStream = createFileResponseStream(file, INJECT_SCRIPT);
} else {
fileStream = file.readable;
}
const fileResponse = new Response(fileStream);
return fileResponse;
}
async function readFile(filepath: string): Promise<[Deno.FsFile, string]> {
const stat = await Deno.stat(filepath);
if (stat.isDirectory) {
filepath += '/index.html';
}
const file = await Deno.open(filepath, { read: true });
return [file, filepath];
}
function createFileResponseStream(
file: Deno.FsFile,
htmlSlice: string,
): ReadableStream<Uint8Array> {
const textEncoderStream = new TextEncoderStream();
const textWriter = textEncoderStream.writable.getWriter();
textWriter.ready
.then(() => textWriter.write(htmlSlice))
.then(() => textWriter.close());
return mergeReadableStreams(textEncoderStream.readable, file.readable);
}
const INJECT_SCRIPT = html`
<script>
function connectSocket(timeoutId, onOpen) {
const socket = new WebSocket('ws://${HOSTNAME}:${SOCKET_PORT}')
clearInterval(timeoutId)
socket.addEventListener('open', onOpen)
const onMessage = (event) => {
if(event.data === '${REFRESH_MESSAGE}'){
window.location.reload();
}
}
socket.addEventListener('message', onMessage);
const onClose = () => {
const timeoutId = setTimeout(() => {
connectSocket(timeoutId, () => window.location.reload())
}, 1000);
}
socket.addEventListener('close', onClose)
}
connectSocket()
</script>
`;
const webSocket = new WebSocketServer(SOCKET_PORT);
webSocket.on('connection', function (ws: WebSocketClient) {
const unsub = fsUpdateStore.addNotifier(() => ws.send(REFRESH_MESSAGE));
ws.on('close', unsub);
});
const fsUpdateStore = {
_debounceId: null as number | null,
_notifiers: [] as (() => void)[],
addNotifier(newNotifier: () => void) {
this._notifiers.push(newNotifier);
return () => {
this._notifiers = this._notifiers.filter((notifier) =>
notifier !== newNotifier
);
};
},
notify() {
if (this._debounceId) {
clearTimeout(this._debounceId);
}
this._debounceId = setTimeout(() =>
this._notifiers.forEach((notify) => notify())
);
},
};
(async () => {
const directory = `${Deno.cwd()}/${DIR_TO_WATCH}`;
const watcher = Deno.watchFs(directory);
log.info(`Watching for file changes in ${log.Colors.underline(directory)}`);
for await (const event of watcher) {
log.fsEvent(event);
fsUpdateStore.notify();
}
})();