-
Notifications
You must be signed in to change notification settings - Fork 0
/
createResolveLinkRelations.mjs
195 lines (168 loc) · 5.85 KB
/
createResolveLinkRelations.mjs
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
// @ts-check
import path from "node:path";
import { access, readFile } from "node:fs/promises";
import { parse } from "es-module-lexer";
import parseFromString from "./resolve-import-map/parseFromString.mjs";
import resolveImportMap from "./resolve-import-map/resolveImportMap.mjs";
/**
* @typedef {object} AsyncMap
* @property {(key: any) => Promise<any>} get A function that takes a key as an argument and returns a promise that resolves to a value.
* @property {(key: any, value: any) => Promise<void>} set A function that takes a key and a value as arguments and returns a promise.
*/
/** @typedef {Map<any, any> | AsyncMap} AsyncMapLike */
// The import map parser requries a base url. We don't require one for our purposes,
// but it allows us to use the parser without modifying the source. One quirk is that it will try map
// this url to files locally if it's specified, but no one should do that.
const DUMMY_HOSTNAME = "example.com";
/**
* Reads a file if possible.
* @param {string} filePath The path to the file.
* @returns The file contents, or otherwise `undefined`.
*/
async function tryReadFile(filePath) {
try {
return await readFile(filePath, "utf-8");
} catch {
// Do nothing.
}
}
/**
* Checks if a file exists.
* @param {string} filePath The path to the file.
* @returns Does the file exist.
*/
async function exists(filePath) {
try {
await access(filePath);
return true;
} catch {
return false;
}
}
/**
* Recursively parses and resolves a module's imports.
* @param {string} module The path to the module.
* @param {object} options Options.
* @param {string} options.url The module URL to resolve.
* @param {object} [options.parsedImportMap] A parsed import map.
* @param {boolean} [root] Whether the module is the root module.
* @returns An array containing paths to modules that can be preloaded.
*/
async function resolveImports(module, { url, parsedImportMap }, root = true) {
/** @type {Array<string>} */
let modules = [];
const source = await tryReadFile(module);
if (source === undefined) {
return modules;
}
const [imports] = parse(source);
await Promise.all(
imports.map(async ({ n: specifier, d }) => {
const dynamic = d > -1;
if (specifier && !dynamic) {
let importMapResolved = null;
// If an import map is supplied, everything resolves through it.
if (parsedImportMap) {
importMapResolved = resolveImportMap(
specifier,
parsedImportMap,
new URL(url, `https://${DUMMY_HOSTNAME}`),
);
}
let resolvedModule;
// Are we resolving with an import map?
if (importMapResolved !== null) {
// It will match if it's a local module.
if (importMapResolved.hostname === DUMMY_HOSTNAME) {
resolvedModule = path.resolve(
path.dirname(module),
`.${importMapResolved.pathname}`,
);
}
} else {
resolvedModule = path.resolve(path.dirname(module), specifier);
}
// If the module has resolved to a local file (and it exists), then it's preloadable.
if (resolvedModule && (await exists(resolvedModule))) {
if (!root) {
modules.push(resolvedModule);
}
const graph = await resolveImports(
resolvedModule,
{ parsedImportMap, url },
false,
);
if (graph.length > 0) {
graph.forEach((module) => modules.push(module));
}
}
}
}),
);
return modules;
}
/**
* Resolves the imports for a given module and caches the result.
* @param {string} module The path to the module.
* @param {object} options Options.
* @param {AsyncMapLike} options.cache Resolved imports cache.
* @param {string} options.url The module URL to resolve.
* @param {object} [options.parsedImportMap] A parsed import map.
* @returns An array containing paths to modules that can be preloaded, or otherwise `undefined`.
*/
async function resolveImportsCached(module, { cache, url, parsedImportMap }) {
const paths = await cache.get(module);
if (paths) {
return paths;
} else {
const graph = await resolveImports(module, { parsedImportMap, url });
if (graph.length > 0) {
await cache.set(module, graph);
return graph;
}
}
}
/**
* Creates a function that resolves the link relations for a given module URL.
* @param {string} appPath Path to the application root from where files can be read.
* @param {object} [options] Options.
* @param {string} [options.importMap] An import map.
* @param {AsyncMapLike} [options.cache] Specify a cache for resolved imports.
* @returns A function that resolves the link relations for a given module URL.
*/
export default function createResolveLinkRelations(
appPath,
{ importMap: importMapString, cache = new Map() } = {},
) {
/**
* Resolves link relations for a given URL.
* @param {string} url The module URL to resolve.
* @returns An array containing relative paths to modules that can be preloaded, or otherwise `undefined`.
*/
return async function resolveLinkRelations(url) {
let parsedImportMap;
if (importMapString !== undefined) {
parsedImportMap = parseFromString(
importMapString,
`https://${DUMMY_HOSTNAME}`,
);
}
const rootPath = path.resolve(appPath);
const resolvedFile = path.join(rootPath, url);
if (resolvedFile.startsWith(rootPath)) {
const modules = await resolveImportsCached(resolvedFile, {
cache,
url,
parsedImportMap,
});
if (Array.isArray(modules) && modules.length > 0) {
const resolvedModules = modules.map((module) => {
return "/" + path.relative(rootPath, module);
});
if (resolvedModules.length > 0) {
return resolvedModules;
}
}
}
};
}