1 | const globalShortcuts = new Map;
|
2 | const localShortcuts = new Map;
|
3 |
|
4 | const {escapePipeValue, pipesToString} = require("./parser");
|
5 |
|
6 | function add(source, name, expand) {
|
7 | let localMap = localShortcuts.get(source);
|
8 | if (!localMap) {
|
9 | localMap = new Map;
|
10 | localShortcuts.set(source, localMap);
|
11 | }
|
12 | localMap.set(name, {name, expand});
|
13 | }
|
14 |
|
15 | function addGlobal(shortcut) {
|
16 | globalShortcuts.set(shortcut.name, shortcut);
|
17 | }
|
18 |
|
19 | function expand(source, pipes) {
|
20 | const shortcut = getShortcut(source, pipes[0].name);
|
21 | let expanded;
|
22 | if (typeof shortcut.expand == "function") {
|
23 | expanded = shortcut.expand(source, ...pipes[0].args);
|
24 | } else if (typeof shortcut.expand == "string") {
|
25 | expanded = shortcut.expand.replace(/\$(\d+|&)/g, (match, n) => {
|
26 | if (n == "&") {
|
27 | return pipes[0].args.map(escapePipeValue).join(",");
|
28 | }
|
29 | return pipes[0].args[n - 1];
|
30 | });
|
31 | } else {
|
32 | throw new Error("shortcut.expand must be a string or a function");
|
33 | }
|
34 | if (pipes.length === 1) {
|
35 | return expanded;
|
36 | }
|
37 | return `${expanded}|${pipesToString(pipes.slice(1))}`;
|
38 | }
|
39 |
|
40 | function has(source, name) {
|
41 | return localShortcuts.has(source) && localShortcuts.get(source).has(name) ||
|
42 | globalShortcuts.has(name);
|
43 | }
|
44 |
|
45 | function remove(source) {
|
46 | localShortcuts.delete(source);
|
47 | }
|
48 |
|
49 | function getShortcut(file, name) {
|
50 | if (localShortcuts.has(file) && localShortcuts.get(file).has(name)) {
|
51 | return localShortcuts.get(file).get(name);
|
52 | }
|
53 | if (globalShortcuts.has(name)) {
|
54 | return globalShortcuts.get(name);
|
55 | }
|
56 | return null;
|
57 | }
|
58 |
|
59 | module.exports = {add, addGlobal, expand, remove, has};
|