UNPKG

3.53 kBJavaScriptView Raw
1const _ = require('lodash');
2const { createFilter } = require('rollup-pluginutils');
3const { walk } = require('estree-walker');
4const MagicString = require('magic-string');
5const utils = require('./translation-utils');
6
7const removeProperty = (code, magicString, start, end) => {
8 magicString.remove(start, end);
9 for (let i = end; i < code.length - 1; i += 1) {
10 const ch = code[i];
11 if (ch === ',') {
12 magicString.remove(i, i + 1);
13 break;
14 } else if (/\w|}/.test(ch)) {
15 break;
16 }
17 }
18};
19
20module.exports = (opts = {}) => {
21 const include = opts.include || '**/*.js';
22 const { exclude } = opts;
23 const filter = createFilter(include, exclude);
24 const sourcemap = opts.sourcemap !== false;
25 const subdirectory = opts.subdirectory || './';
26 const filtering = opts.filtering !== false;
27 return {
28 name: 'translation-ui-router',
29 transform(code, id) {
30 if (filtering && !filter(id)) return null;
31 const ast = this.parse(code);
32 const magicString = new MagicString(code);
33 walk(ast, {
34 enter(node) {
35 if (sourcemap) {
36 magicString.addSourcemapLocation(node.start);
37 magicString.addSourcemapLocation(node.end);
38 }
39 if (_.get(node, 'callee.property.name') === 'state') {
40 const props = _.chain(node)
41 .get('arguments')
42 .last()
43 .get('properties')
44 .value();
45 const translations = _.chain(props)
46 .filter({ key: { name: 'translations' }, type: 'Property' })
47 .head();
48
49 if (translations.value()) {
50 let format;
51 let value;
52
53 if (translations.has('value.elements').value()) {
54 value = translations.get('value.elements')
55 .map('value')
56 .value();
57 } else {
58 const myObj = translations.get('value.properties');
59 format = _.chain(myObj)
60 .filter(({ key }) => key.name === 'format')
61 .head()
62 .get('value.value')
63 .value();
64 value = _.chain(myObj)
65 .filter(({ key }) => key.name === 'value')
66 .head()
67 .get('value.elements')
68 .map('value')
69 .value();
70 }
71
72 const resolve = _.chain(props)
73 .filter({ key: { name: 'resolve' }, type: 'Property' })
74 .head()
75 .get('value.properties')
76 .last()
77 .value();
78
79 let inject = utils.injectTranslationImports(
80 value,
81 id,
82 subdirectory,
83 format,
84 );
85
86 inject = `translations: ($q, $translate, asyncLoader) => { ${inject} }`;
87
88 removeProperty(code, magicString,
89 translations.value().start, translations.value().end);
90
91 if (resolve) {
92 magicString.appendRight(resolve.end, `,${inject}`);
93 } else {
94 const firstProp = _(node).get('arguments[1].properties[0]');
95 inject = `resolve: { ${inject} },`;
96 magicString.appendLeft(firstProp.start, inject);
97 }
98 }
99 }
100 },
101 });
102 return {
103 code: magicString.toString(),
104 map: sourcemap ? magicString.generateMap({ hires: true }) : null,
105 };
106 },
107 };
108};