-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathsimport.js
85 lines (61 loc) · 2.02 KB
/
simport.js
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
'use strict';
const {pathToFileURL} = require('url');
const readjson = require('readjson');
const tryToCatch = require('try-to-catch');
const {assign} = Object;
const isFn = (a) => typeof a === 'function';
const isObject = (a) => typeof a === 'object';
const maybeFrozenFunction = (a) => !isFn(a) ? a : function(...args) {
return a.apply(this, args);
};
const maybeFrozenObject = (a) => !isObject(a) ? a : assign({}, a);
const importWithExt = async (a, ext = '') => await import(`${a}${ext}`);
const extensions = [
'.js',
'.cjs',
'.mjs',
];
module.exports.createSimport = (url) => {
if (!url.includes('file://'))
url = pathToFileURL(url);
return async (name) => {
let resolved = name;
const isRelative = /^\./.test(name);
if (isRelative) {
resolved = new URL(name, url);
}
if (/\.json$/.test(resolved))
return await readjson(resolved);
if (/\.(js|mjs|cjs)$/.test(name)) {
const processed = resolved.href || `file://${resolved}`;
const imported = await import(processed);
return buildExports(imported);
}
let imported;
let error;
if (/^[@a-z]/.test(name)) {
imported = await importWithExt(resolved);
}
if (!imported)
[error, imported] = await importAbsolute(resolved);
if (error)
throw error;
return buildExports(imported);
};
};
async function importAbsolute(resolved) {
let error;
let imported;
for (const ext of extensions) {
[error, imported] = await tryToCatch(importWithExt, resolved, ext);
if (imported)
break;
}
return [error, imported];
}
function buildExports(imported) {
let {default: exports = {}} = imported;
exports = maybeFrozenFunction(exports);
exports = maybeFrozenObject(exports);
return assign(exports, imported);
}