-
Notifications
You must be signed in to change notification settings - Fork 1
/
cache.ts
135 lines (127 loc) · 3.47 KB
/
cache.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
import { ensureDir } from "https://deno.land/[email protected]/fs/ensure_dir.ts";
import { join } from "https://deno.land/[email protected]/path/mod.ts";
/** download and cache remote contents */
export async function cache(
url: string,
): Promise<{ content: Uint8Array; contentType: string | null }> {
const { protocol, hostname, port, pathname, search } = new URL(url);
const isLocalhost = ["0.0.0.0", "127.0.0.1", "localhost"].includes(hostname);
const cacheDir = join(
await getDenoDir(),
"deps",
protocol.replace(":", ""),
hostname + (port ? "_PORT" + port : ""),
);
const hashname = toHex(
await crypto.subtle.digest(
"sha-256",
new TextEncoder().encode(pathname + search),
),
);
const contentFilepath = join(cacheDir, hashname);
const metaFilepath = join(cacheDir, hashname + ".metadata.json");
if (
!isLocalhost &&
await existsFile(contentFilepath) &&
await existsFile(metaFilepath)
) {
const [content, meta] = await Promise.all([
Deno.readFile(contentFilepath),
Deno.readTextFile(metaFilepath),
]);
try {
const { headers = {} } = JSON.parse(meta);
return {
content,
contentType: headers["content-type"] || null,
};
} catch (_e) {
// ignore
}
}
const retryTimes = 3;
let err = new Error("Unknown");
for (let i = 0; i < retryTimes; i++) {
try {
const resp = await fetch(url);
if (resp.status >= 400) {
err = new Error(resp.statusText);
continue;
}
const buffer = await resp.arrayBuffer();
const content = new Uint8Array(buffer);
if (!isLocalhost) {
const headers: Record<string, string> = {};
resp.headers.forEach((val, key) => {
headers[key] = val;
});
await ensureDir(cacheDir);
await Promise.all([
Deno.writeFile(contentFilepath, content),
Deno.writeTextFile(
metaFilepath,
JSON.stringify(
{ headers, url, createdAt: Date.now() },
undefined,
2,
),
),
]);
}
return {
content,
contentType: resp.headers.get("content-type"),
};
} catch (e) {
err = e;
}
}
return Promise.reject(err);
}
function toHex(buffer: ArrayBuffer) {
const bytes = new Uint8Array(buffer);
return [...bytes].map((b) => b.toString(16).padStart(2, "0")).join("");
}
/** get the deno cache dir. */
async function getDenoDir() {
const p = new Deno.Command(Deno.execPath(), {
args: ["info", "--json"],
stdout: "piped",
stderr: "null",
});
const { denoDir } = await (new Response(p.spawn().stdout).json());
if (denoDir === undefined || !await existsDir(denoDir)) {
throw new Error(`can"t find the deno dir`);
}
return denoDir;
}
/* check whether or not the given path exists as a directory. */
async function existsDir(path: string): Promise<boolean> {
try {
const fi = await Deno.lstat(path);
if (fi.isDirectory) {
return true;
}
return false;
} catch (err) {
if (err instanceof Deno.errors.NotFound) {
return false;
}
throw err;
}
}
/* check whether or not the given path exists as regular file. */
async function existsFile(path: string): Promise<boolean> {
try {
const fi = await Deno.lstat(path);
if (fi.isFile) {
return true;
}
return false;
} catch (err) {
if (err instanceof Deno.errors.NotFound) {
return false;
}
throw err;
}
}