-
Notifications
You must be signed in to change notification settings - Fork 22
/
loader.ts
67 lines (63 loc) · 2.03 KB
/
loader.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
// Adapted from deno_graph
// https://github.com/denoland/deno_graph/blob/main/lib/loader.ts
export interface LoadResponseModule {
/** A module with code has been loaded. */
kind: "module";
/** The string URL of the resource. If there were redirects, the final
* specifier should be set here, otherwise the requested specifier. */
specifier: string;
/** For remote resources, a record of headers should be set, where the key's
* have been normalized to be lower case values. */
headers?: Record<string, string>;
/** The string value of the loaded resources. */
content: string;
}
export interface LoadResponseExternalBuiltIn {
/** The loaded module is either _external_ or _built-in_ to the runtime. */
kind: "external" | "builtIn";
/** The strung URL of the resource. If there were redirects, the final
* specifier should be set here, otherwise the requested specifier. */
specifier: string;
}
export type LoadResponse = LoadResponseModule | LoadResponseExternalBuiltIn;
export async function load(
specifier: string,
): Promise<LoadResponse | undefined> {
const url = new URL(specifier);
try {
switch (url.protocol) {
case "file:": {
const content = await Deno.readTextFile(url);
return {
kind: "module",
specifier,
content,
};
}
case "http:":
case "https:": {
const response = await fetch(String(url), { redirect: "follow" });
if (response.status !== 200) {
// ensure the body is read as to not leak resources
await response.arrayBuffer();
return undefined;
}
const content = await response.text();
const headers: Record<string, string> = {};
for (const [key, value] of response.headers) {
headers[key.toLowerCase()] = value;
}
return {
kind: "module",
specifier: response.url,
headers,
content,
};
}
default:
return undefined;
}
} catch {
return undefined;
}
}