-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcache.ts
40 lines (32 loc) · 1.29 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
import {DenoDir} from 'deno_cache/deno_dir.ts';
import {join as joinPath} from 'std/path/join.ts';
import {ensureDirSync} from 'std/fs/ensure_dir.ts';
import {existsSync} from 'std/fs/exists.ts';
import {encodeHex} from 'std/encoding/hex.ts';
const wincompileCacheDir = joinPath(new DenoDir().root, 'wincompile');
ensureDirSync(wincompileCacheDir);
const txtEnc = new TextEncoder();
async function cache(url: URL, opts = {refresh: false}): Promise<string> {
const filename = await makePath(url.href);
if (opts.refresh || !await getPathFromCache(url.href))
Deno.writeFileSync(filename, new Uint8Array(await (await fetch(url)).arrayBuffer()));
return filename;
}
async function getDataFromCache(url: URL): Promise<Uint8Array | null> {
const path = await getPathFromCache(url.href);
if (!path) return null;
return await Deno.readFile(path);
}
async function getPathFromCache(url: string): Promise<string> {
const path = await makePath(url);
if (!existsSync(path)) return '';
return path;
}
async function makePath(url: string): Promise<string> {
return joinPath(wincompileCacheDir, await hashUrl(url.toString()));
}
async function hashUrl(url: string): Promise<string> {
return encodeHex(await crypto.subtle.digest('sha-256', txtEnc.encode(url)));
}
export default cache;
export {getDataFromCache};