/
ImportMap.ts
77 lines (67 loc) · 2.19 KB
/
ImportMap.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
import * as parser from "./reference-implementation/parser.js";
import * as resolver from "./reference-implementation/resolver.js";
import * as utils from "./reference-implementation/utils.js";
import * as apply from "./reference-implementation/apply.ts";
import { join, posix, toFileUrl } from "https://deno.land/std@0.141.0/path/mod.ts";
function toURL(base: string | URL) {
if (base instanceof URL) return base;
try {
return new URL(base);
} catch {
// TODO: handle absolute URL "/"
return toFileUrl(join(Deno.cwd(), base));
}
}
export default class ImportMap {
#importMap: any;
#baseURL: URL;
constructor(
importMap:
| {
imports?: Record<string, string>;
scope?: Record<string, Record<string, string>>;
}
| string,
baseURL: string | URL = "./",
) {
this.#baseURL = toURL(baseURL);
this.#importMap = parser.parseFromString(
typeof importMap === "string" ? importMap : JSON.stringify(importMap),
this.#baseURL,
);
}
resolve(specifier: string, referrer: string | URL): string {
const referrerURL = toURL(referrer);
const url = resolver.resolve(specifier, this.#importMap, referrerURL);
// Prefer relative path, for readability
if (url.protocol === "file:" && referrerURL.protocol === "file:") {
const relativePath = posix.relative(
posix.dirname(referrerURL.pathname),
url.pathname,
);
if (relativePath.startsWith("../")) {
return relativePath;
} else {
return "./" + relativePath;
}
}
return url.href;
}
apply(specifier: string, referrer: string | URL): string {
if (specifier.startsWith("./") || specifier.startsWith("../")) {
return specifier;
}
const referrerURL = toURL(referrer);
const result = apply.apply(specifier, this.#importMap, referrerURL);
const url = utils.tryURLParse(result);
if (url && url.protocol === "file:" && referrerURL.protocol === "file:") {
const relativePath = posix.relative(this.#baseURL.pathname, url.pathname);
if (relativePath.startsWith("../")) {
return relativePath;
} else {
return "./" + relativePath;
}
}
return result;
}
}