-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathindex.mjs
More file actions
81 lines (78 loc) · 2.03 KB
/
Copy pathindex.mjs
File metadata and controls
81 lines (78 loc) · 2.03 KB
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
import __dirname from './dirname';
import util from 'util';
const {promisify} = util;
import fs from 'fs';
const asyncStat = promisify(fs.stat);
const asyncReadFile = promisify(fs.readFile);
import url from 'url';
const {URL} = url;
const dirHref = `file://${__dirname}/`;
const overloadsHref = `${dirHref}overloads/`;
// you can do any global mutation here
// setup async_hooks etc.
console.error('initializing loader... (do setup here)');
// this will find the package.json URL associated with a given file URL
const grabPackage = async (url) => {
try {
return JSON.parse(
await asyncReadFile(new URL('./package.json', url)));
} catch (e) {
if (e.code !== 'ENOENT') {
throw e;
}
}
const parent = new URL('../', url);
if (parent.href === url) {
return undefined;
}
return grabPackage(parent.href);
}
const skipPackageSearch = new Set(['fs']);
const overloads = {
__proto__: null,
fs() {
return new URL(
`./fs.mjs`,
overloadsHref
).href;
},
foo({url: resolved}, pkg) {
if (pkg.version === '0.0.0') {
return new URL(
`./foo@0.0.0.mjs`,
overloadsHref
).href;
} if (pkg.version === '1.0.0') {
return new URL(
`./foo@1.0.0.mjs`,
overloadsHref
).href;
} else {
return resolved;
}
}
}
export async function resolve(specifier, parentModuleURL, defaultResolver) {
if (
new URL(parentModuleURL).href.indexOf(overloadsHref) == 0) {
return defaultResolver(specifier, parentModuleURL);
}
try {
const overload = overloads[specifier];
if (overload) {
if (skipPackageSearch.has(specifier)) {
return defaultResolver(overload(), parentModuleURL);
} else {
const resolved = await defaultResolver(
specifier,
parentModuleURL
);
const pkg = await grabPackage(resolved.url);
return defaultResolver(overload(resolved, pkg), parentModuleURL);
}
}
} catch (e) {
console.trace(e);
}
return defaultResolver(specifier, parentModuleURL);
}