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