UNPKG

2 kBJavaScriptView Raw
1function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
2
3function _sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }
4
5function _slicedToArray(arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return _sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }
6
7const L = require('lodash');
8
9const before = (_, lines) => L.findIndex(lines, l => l.match(_));
10
11const locations = {
12 at_line: _ => _,
13 prepend: _ => 1,
14 append: (_, lines) => lines.length - 1,
15 before,
16 after: (_, lines) => before(_, lines) + 1
17};
18
19const indexByLocation = (attributes, lines) => {
20 const pair = L.find(L.toPairs(attributes), ([k, v]) => locations[k]);
21
22 if (pair) {
23 const _pair = _slicedToArray(pair, 2),
24 k = _pair[0],
25 v = _pair[1];
26
27 return locations[k](v, lines);
28 }
29
30 return -1;
31};
32
33const inject = (action, intoText) => {
34 const attributes = action.attributes,
35 body = action.body;
36 const lines = intoText.split('\n');
37 const shouldSkip = attributes.skip_if && !!L.find(lines, _ => _.match(attributes.skip_if));
38
39 if (!shouldSkip) {
40 const idx = indexByLocation(attributes, lines);
41
42 if (idx >= 0) {
43 lines.splice(idx, 0, body);
44 }
45 }
46
47 const injected = lines.join('\n');
48 return _extends({}, action, {
49 body: injected
50 });
51};
52
53module.exports = inject;
\No newline at end of file