UNPKG

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