forked from esm-dev/esm.sh
-
Notifications
You must be signed in to change notification settings - Fork 0
/
hot.ts
368 lines (323 loc) · 9.64 KB
/
hot.ts
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
/*! 🔥 esm.sh/hot
* Docs: https://docs.esm.sh/hot
*/
/// <reference lib="dom" />
/// <reference lib="dom.iterable" />
/// <reference lib="webworker" />
import type {
FetchHandler,
HotCore,
ImportMap,
IncomingTest,
Plugin,
VFile,
} from "./server/embed/types/hot.d.ts";
const VERSION = 135;
const doc: Document | undefined = globalThis.document;
const loc = location;
const parse = JSON.parse;
const localhosts = new Set(["localhost", "127.0.0.1", "[::1]"]);
const kHot = "esm.sh/hot";
const kSkipWaiting = "SKIP_WAITING";
const kMessage = "message";
const kVfs = "vfs";
/** A virtual file system using indexed database. */
class VFS {
#dbPromise: Promise<IDBDatabase>;
constructor(scope: string, version: number) {
const req = indexedDB.open(scope, version);
req.onupgradeneeded = () => {
const db = req.result;
if (!db.objectStoreNames.contains(kVfs)) {
db.createObjectStore(kVfs, { keyPath: "name" });
}
};
this.#dbPromise = waitIDBRequest<IDBDatabase>(req);
}
async #begin(readonly = false) {
const db = await this.#dbPromise;
return db.transaction(kVfs, readonly ? "readonly" : "readwrite")
.objectStore(kVfs);
}
async get(name: string) {
const tx = await this.#begin(true);
return waitIDBRequest<VFile | undefined>(tx.get(name));
}
async put(name: string, data: VFile["data"], meta?: VFile["meta"]) {
const record: VFile = { name, data };
if (meta) {
record.meta = meta;
}
const tx = await this.#begin();
return waitIDBRequest<string>(tx.put(record));
}
async delete(name: string) {
const tx = await this.#begin();
return waitIDBRequest<void>(tx.delete(name));
}
}
/** Hot class implements the `HotCore` interface. */
class Hot implements HotCore {
#cache: Cache | null = null;
#importMap: Required<ImportMap> | null = null;
#fetchListeners: { test: IncomingTest; handler: FetchHandler }[] = [];
#fireListeners: ((sw: ServiceWorker) => void)[] = [];
#isDev = localhosts.has(location.hostname);
#promises: Promise<any>[] = [];
#vfs = new VFS(kHot, VERSION);
#registeredSW: URL | null = null;
#activatedSW: ServiceWorker | null = null;
get cache() {
return this.#cache ?? (this.#cache = createCacheProxy(kHot + VERSION));
}
get importMap() {
return this.#importMap ?? (this.#importMap = parseImportMap());
}
get isDev() {
return this.#isDev;
}
get vfs() {
return this.#vfs;
}
onFetch(test: IncomingTest, handler: FetchHandler) {
if (!doc) {
this.#fetchListeners.push({ test, handler });
}
return this;
}
onFire(handler: (reg: ServiceWorker) => void) {
if (doc) {
if (this.#activatedSW) {
handler(this.#activatedSW);
} else {
this.#fireListeners.push(handler);
}
}
return this;
}
waitUntil(promise: Promise<void>) {
this.#promises.push(promise);
}
async fire(swScript = "/sw.js") {
const sw = navigator.serviceWorker;
if (!sw) {
throw new Error("Service Worker not supported.");
}
if (this.#registeredSW) {
return;
}
this.#registeredSW = new URL(swScript, loc.href);
const reg = await sw.register(this.#registeredSW, {
type: "module",
updateViaCache: this.#isDev ? undefined : "all",
});
// detect Service Worker update available and wait for it to become installed
let isFirstInstall = false;
reg.onupdatefound = () => {
const { installing } = reg;
if (installing) {
installing.onstatechange = () => {
const { waiting } = reg;
if (waiting) {
waiting.postMessage(kSkipWaiting);
if (!sw.controller) {
// it's first install
waiting.onstatechange = () => {
if (reg.active) {
isFirstInstall = true;
this.#fireApp(reg.active);
}
};
}
}
};
}
};
// detect controller change and refresh the page
sw.oncontrollerchange, () => {
!isFirstInstall && loc.reload();
};
// if there's a waiting, send skip waiting message
reg.waiting?.postMessage(kSkipWaiting)
// fire immediately if there's an active Service Worker
if (reg.active) {
this.#fireApp(reg.active);
}
}
async #fireApp(sw: ServiceWorker) {
// update importmap in Service Worker
sw.postMessage(this.importMap);
// wait until all promises resolved
await Promise.all(this.#promises);
// fire all `fire` listeners
for (const handler of this.#fireListeners) {
handler(sw);
}
this.#activatedSW = sw;
// apply "[type=hot/module]" script tags
queryElements<HTMLScriptElement>("script[type='hot/module']", (el) => {
const copy = el.cloneNode(true) as HTMLScriptElement;
copy.type = "module";
el.replaceWith(copy);
});
}
use(...plugins: Plugin[]) {
plugins.forEach((plugin) => plugin.setup(this));
return this;
}
listen() {
// @ts-expect-error missing dts
if (typeof clients === "undefined") {
throw new Error("Service Worker scope not found.");
}
const vfs = this.#vfs;
const serveVFS = async (name: string) => {
const file = await vfs.get(name);
if (!file) {
return createResponse("Not Found", {}, 404);
}
const headers: HeadersInit = {
"content-type": file.meta?.contentType ?? "binary/octet-stream",
};
return createResponse(file.data, headers);
};
const fetchWithCache = async (req: Request) => {
const cache = this.cache;
const cachedReq = await cache.match(req);
if (cachedReq) {
return cachedReq;
}
const res = await fetch(req.url);
if (res.status !== 200) {
return res;
}
await cache.put(req, res.clone());
return res;
};
// @ts-expect-error missing dts
self.oninstall = (evt) => evt.waitUntil(Promise.all(this.#promises));
// @ts-expect-error missing dts
self.onactivate = (evt) => evt.waitUntil(clients.claim());
// @ts-expect-error missing dts
self.onfetch = (evt: FetchEvent) => {
const { request } = evt;
const respondWith = evt.respondWith.bind(evt);
const url = new URL(request.url);
const { pathname } = url;
const fetchListeners = this.#fetchListeners;
if (fetchListeners.length > 0) {
for (const { test, handler } of fetchListeners) {
if (test(url, request)) {
return respondWith(handler(request));
}
}
}
if (
url.hostname === "esm.sh" && /\w@\d+.\d+\.\d+(-|\/|\?|$)/.test(pathname)
) {
return respondWith(fetchWithCache(request));
}
if (isSameOrigin(url) && pathname.startsWith("/@hot/")) {
respondWith(serveVFS(pathname.slice(1)));
}
};
// listen to SW `message` event for `skipWaiting` control on renderer process
// and importmap update
self.onmessage = ({ data }) => {
if (data === kSkipWaiting) {
// @ts-expect-error missing dts
self.skipWaiting();
} else if (isObject(data) && data.imports) {
this.#importMap = data as Required<ImportMap>;
}
};
}
}
/** query all elements by the given selectors. */
function queryElements<T extends Element>(
selectors: string,
callback: (value: T) => void,
) {
// @ts-expect-error throw error if document is not available
doc.querySelectorAll(selectors).forEach(callback);
}
/** parse importmap from <script> with `type=importmap` */
function parseImportMap() {
const importMap: Required<ImportMap> = {
$support: HTMLScriptElement.supports?.("importmap"),
imports: {},
scopes: {},
};
if (!doc) {
return importMap;
}
const script = doc.querySelector("script[type=importmap]");
if (script) {
try {
const json = parse(script.textContent!);
if (isObject(json)) {
const { imports, scopes } = json;
if (isObject(imports)) {
validateImports(imports);
importMap.imports = imports;
}
if (isObject(scopes)) {
validateScopes(scopes);
importMap.scopes = scopes;
}
}
} catch (err) {
console.error("Invalid importmap", err[kMessage]);
}
}
return importMap;
}
function validateScopes(imports: Record<string, unknown>) {
for (const [k, v] of Object.entries(imports)) {
if (isObject(v)) {
validateImports(v);
} else {
delete imports[k];
}
}
}
function validateImports(imports: Record<string, unknown>) {
for (const [k, v] of Object.entries(imports)) {
if (!v || typeof v !== "string") {
delete imports[k];
}
}
}
/** create a cache proxy object. */
function createCacheProxy(cacheName: string) {
const cachePromise = caches.open(cacheName);
return new Proxy({}, {
get: (_, name) => async (...args: unknown[]) => {
return (await cachePromise as any)[name](...args);
},
}) as Cache;
}
/** create a response object. */
function createResponse(
body: BodyInit | null,
headers: HeadersInit = {},
status = 200,
): Response {
return new Response(body, { headers, status });
}
/** check if the given value is an object. */
function isObject(v: unknown): v is Record<string, any> {
return typeof v === "object" && v !== null && !Array.isArray(v);
}
/** check if the given url has the same origin with current loc. */
function isSameOrigin(url: URL) {
return url.origin === loc.origin;
}
/** wait for the given IDBRequest. */
function waitIDBRequest<T>(req: IDBRequest): Promise<T> {
return new Promise((resolve, reject) => {
req.onsuccess = () => resolve(req.result);
req.onerror = () => reject(req.error);
});
}
export default new Hot();