UNPKG

3.01 kBJavaScriptView Raw
1const noop = () => null;
2function matches(pattern, importee) {
3 if (pattern instanceof RegExp) {
4 return pattern.test(importee);
5 }
6 if (importee.length < pattern.length) {
7 return false;
8 }
9 if (importee === pattern) {
10 return true;
11 }
12 const importeeStartsWithKey = importee.indexOf(pattern) === 0;
13 const importeeHasSlashAfterKey = importee.substring(pattern.length)[0] === '/';
14 return importeeStartsWithKey && importeeHasSlashAfterKey;
15}
16function normalizeId(id) {
17 return id;
18}
19function getEntries({ entries }) {
20 if (!entries) {
21 return [];
22 }
23 if (Array.isArray(entries)) {
24 return entries;
25 }
26 return Object.entries(entries).map(([key, value]) => {
27 return { find: key, replacement: value };
28 });
29}
30function getCustomResolver({ customResolver }, options) {
31 if (typeof customResolver === 'function') {
32 return customResolver;
33 }
34 if (customResolver && typeof customResolver.resolveId === 'function') {
35 return customResolver.resolveId;
36 }
37 if (typeof options.customResolver === 'function') {
38 return options.customResolver;
39 }
40 if (options.customResolver && typeof options.customResolver.resolveId === 'function') {
41 return options.customResolver.resolveId;
42 }
43 return null;
44}
45function alias(options = {}) {
46 const entries = getEntries(options);
47 if (entries.length === 0) {
48 return {
49 name: 'alias',
50 resolveId: noop
51 };
52 }
53 return {
54 name: 'alias',
55 buildStart(inputOptions) {
56 return Promise.all([...entries, options].map(({ customResolver }) => customResolver &&
57 typeof customResolver === 'object' &&
58 typeof customResolver.buildStart === 'function' &&
59 customResolver.buildStart.call(this, inputOptions))).then(() => {
60 // enforce void return value
61 });
62 },
63 resolveId(importee, importer) {
64 const importeeId = normalizeId(importee);
65 const importerId = normalizeId(importer);
66 // First match is supposed to be the correct one
67 const matchedEntry = entries.find((entry) => matches(entry.find, importeeId));
68 if (!matchedEntry || !importerId) {
69 return null;
70 }
71 const updatedId = normalizeId(importeeId.replace(matchedEntry.find, matchedEntry.replacement));
72 const customResolver = getCustomResolver(matchedEntry, options);
73 if (customResolver) {
74 return customResolver.call(this, updatedId, importerId, {});
75 }
76 return this.resolve(updatedId, importer, { skipSelf: true }).then((resolved) => {
77 let finalResult = resolved;
78 if (!finalResult) {
79 finalResult = { id: updatedId };
80 }
81 return finalResult;
82 });
83 }
84 };
85}
86
87export default alias;