1 |
|
2 | import getClosestVariable from './get-closest-variable';
|
3 | import manageUnresolved from './manage-unresolved';
|
4 |
|
5 |
|
6 | export default function getReplacedString(string, node, opts) {
|
7 | const replacedString = string.replace(
|
8 | matchVariables,
|
9 | (match, before, name1, name2, name3) => {
|
10 |
|
11 | if (before === '\\') {
|
12 | return match.slice(1);
|
13 | }
|
14 |
|
15 |
|
16 | const name = name1 || name2 || name3;
|
17 |
|
18 |
|
19 | const value = getClosestVariable(name, node.parent, opts);
|
20 |
|
21 |
|
22 | if (undefined === value) {
|
23 | manageUnresolved(node, opts, name, `Could not resolve the variable "$${name}" within "${string}"`);
|
24 |
|
25 | return match;
|
26 | }
|
27 |
|
28 |
|
29 | const stringifiedValue = `${before}${stringify(value)}`;
|
30 |
|
31 | return stringifiedValue;
|
32 | }
|
33 | );
|
34 |
|
35 | return replacedString;
|
36 | }
|
37 |
|
38 |
|
39 | const matchVariables = /(.?)(?:\$([A-z][\w-]*)|\$\(([A-z][\w-]*)\)|#\{\$([A-z][\w-]*)\})/g;
|
40 |
|
41 |
|
42 | const stringify = object => Array.isArray(object)
|
43 | ? `(${object.map(stringify).join(',')})`
|
44 | : Object(object) === object
|
45 | ? `(${Object.keys(object).map(
|
46 | key => `${key}:${stringify(object[key])}`
|
47 | ).join(',')})`
|
48 | : String(object);
|