Test Failed
Push — main ( 7e560b...7b5171 )
by Eric D
02:36 queued 28s
created

src/index.js   D

Complexity

Total Complexity 58
Complexity/F 1.61

Size

Lines of Code 255
Function Count 36

Duplication

Duplicated Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
wmc 58
eloc 159
mnd 22
bc 22
fnc 36
dl 0
loc 255
rs 4.5599
bpm 0.6111
cpm 1.6111
noi 24
c 0
b 0
f 0

How to fix   Complexity   

Complexity

Complex classes like src/index.js often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

1
/* eslint-disable no-use-before-define, camelcase */
2
var __assign = (this && this.__assign) || function () {
3
    __assign = Object.assign || function(t) {
4
        for (var s, i = 1, n = arguments.length; i < n; i++) {
5
            s = arguments[i];
6
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
7
                t[p] = s[p];
8
        }
9
        return t;
10
    };
11
    return __assign.apply(this, arguments);
12
};
13
var __spreadArray = (this && this.__spreadArray) || function (to, from) {
14
    for (var i = 0, il = from.length, j = to.length; i < il; i++, j++)
15
        to[j] = from[i];
16
    return to;
17
};
18
var __importDefault = (this && this.__importDefault) || function (mod) {
19
    return (mod && mod.__esModule) ? mod : { "default": mod };
20
};
21
(function (factory) {
22
    if (typeof module === "object" && typeof module.exports === "object") {
23
        var v = factory(require, exports);
24
        if (v !== undefined) module.exports = v;
25
    }
26
    else if (typeof define === "function" && define.amd) {
27
        define(["require", "exports", "path", "crypto", "hast-util-select"], factory);
28
    }
29
})(function (require, exports) {
30
    "use strict";
31
    Object.defineProperty(exports, "__esModule", { value: true });
32
    exports.attacher = exports.localResolve = void 0;
33
    var path_1 = __importDefault(require("path"));
34
    var crypto_1 = require("crypto");
35
    var hast_util_select_1 = require("hast-util-select");
36
    var isArray = Array.isArray;
37
    /**
38
     * Resolve
39
     * @summary Merge path segments together
40
     * @description Take in path segments,
41
     * intelligibly  merge them together to form one path.
42
     * @todo the up path
43
     */
44
    var localResolve = function () {
45
        var paths = [];
46
        for (var _i = 0; _i < arguments.length; _i++) {
47
            paths[_i] = arguments[_i];
48
        }
49
        var withDotsButNoSlashes = paths.map(function (c, i, a) {
50
            c = c.startsWith('/') ? c.slice(1) : c;
51
            c = c.endsWith('/') ? c.slice(0, -1) : c;
52
            return c;
53
        });
54
        var noDotDotnoSlashes = withDotsButNoSlashes.reduce(function (p, c) {
55
            if (c === '' || c === ' ') {
56
                return p;
57
            }
58
            if (c.startsWith('..')) {
59
                return exports.localResolve.apply(void 0, __spreadArray(__spreadArray([], p.slice(0, -1)), [c.slice(2)])).split('/');
60
            }
61
            else {
62
                return __spreadArray(__spreadArray([], p), [c]);
63
            }
64
        }, []);
65
        return noDotDotnoSlashes.join('/');
66
    };
67
    exports.localResolve = localResolve;
68
    /**
69
     * Trimmed Hash
70
     * @private
71
     * @description Take in a Buffer and return a sting with length specified via N
72
     * @param n - length of the hash to return
73
     */
74
    var trimmedHash = function (n) { return function (b) { return function () { return crypto_1.createHash('sha256').update(b).digest('hex').slice(0, n); }; }; };
75
    /**
76
     * Merge
77
     * @private
78
     */
79
    var merge = function (paths, fallback, obj) {
80
        return Object.entries(paths)
81
            .reduce(function (acc, _a) {
82
            var _b;
83
            var prop = _a[0], prepFn = _a[1];
84
            return prop in obj
85
                ? prepFn(acc, obj[prop])
86
                : prop in fallback
87
                    ? __assign(__assign({}, acc), (_b = {}, _b[prop] = fallback[prop], _b)) : acc;
88
        }, {});
89
    };
90
    /**
91
     * Map Builder: Parse String And Swap Path
92
     * @private
93
     * @description A builder function returning a key to ƒ.transform map.
94
     * The 'look-up-key'º is mapped to a merge function.
95
     * The ƒ.merge returns a new merged object,
96
     * where the 'look-up-key'º is replaced with the writePath during merge, and the val is parsed
97
    */
98
    var parseStringsAndSwapPath = function (readPath, writePath) {
99
        var _a;
100
        return (_a = {}, _a[readPath] = function (a, s) {
101
            var _a;
102
            return (__assign(__assign({}, a), (_a = {}, _a[writePath] = JSON.parse(s), _a)));
103
        }, _a);
104
    };
105
    /**
106
     * Map Builder: Swap Path
107
     * @private
108
     * @description A builder function returning a key to ƒ.transform map.
109
     * The 'look-up-key'º (aka: readPath) is mapped to a merge function.
110
     * The ƒ.merge function is given an accumulating merge object, and a value from one of 2 target objects depending on if its found.
111
     * The ƒ.merge returns a merged object, and all it does it replce the look-up-keyº with the writePath
112
     * and the val stays unchanged
113
     * @example
114
     * const mergeMeIn = noChange('lookForThis', 'butEventuallyMakeItThis')
115
     * console.log(mergeMeIn) // { lookForThis: (all, val) => ({...all, butEventuallyMakeItThis: val}) }
116
     */
117
    var noChangeJustSwapPath = function (readPath, writePath) {
118
        var _a;
119
        return (_a = {}, _a[readPath] = function (a, s) {
120
            var _a;
121
            return (__assign(__assign({}, a), (_a = {}, _a[writePath] = s, _a)));
122
        }, _a);
123
    };
124
    /**
125
     * Map Builder: Indetity
126
     * @private
127
     * @description A builder function returning a key to ƒ.transform map.
128
     * The look-up-key maps to a ƒ.merge.
129
     * The ƒ.merge (inputs: (accum obj, val)) returns a merged object where the 'look-up-key'º maps to the unchanged val
130
     */
131
    var noChange = function (spath) {
132
        var _a;
133
        return (_a = {}, _a[spath] = function (a, s) {
134
            var _a;
135
            return (__assign(__assign({}, a), (_a = {}, _a[spath] = s, _a)));
136
        }, _a);
137
    };
138
    /**
139
     * Map Builder: Parse The Val
140
     * @private
141
     * @description  A builder function returning a key to ƒ.transform map.
142
     * The returned object is merged into a configuration object used for merging objects.
143
     * The `lookup-key` maps to a ƒ.merge.
144
     */
145
    var parseIfString = function (spath) {
146
        var _a;
147
        return (_a = {},
148
            _a[spath] = function (a, maybeS) {
149
                var _a, _b;
150
                return typeof maybeS === 'string'
151
                    ? __assign(__assign({}, a), (_a = {}, _a[spath] = JSON.parse(maybeS), _a))
152
                    : __assign(__assign({}, a), (_b = {}, _b[spath] = maybeS, _b));
153
            },
154
            _a);
155
    };
156
    var HASTpaths = __assign(__assign(__assign(__assign(__assign(__assign(__assign(__assign(__assign(__assign(__assign({}, noChange('selectedBy')), noChangeJustSwapPath('dataSourceprefix', 'sourcePrefix')), noChangeJustSwapPath('dataDestbasepath', 'destBasePath')), noChangeJustSwapPath('dataPrefix', 'prefix')), noChangeJustSwapPath('dataSuffix', 'suffix')), parseStringsAndSwapPath('dataHashlen', 'hashlen')), parseStringsAndSwapPath('dataClean', 'clean')), parseStringsAndSwapPath('dataWidths', 'widths')), parseStringsAndSwapPath('dataBreaks', 'breaks')), { dataAddclassnames: function (a, sa) { return (__assign(__assign({}, a), { addclassnames: sa.split(' ') })); } }), { dataTypes: function (a, s) { return (__assign(__assign({}, a), { types: s.split(',').reduce(function (p, c) {
157
                var _a;
158
                return (__assign(__assign({}, p), (_a = {}, _a[c] = {}, _a)));
159
            }, {}) })); } });
160
    var NORMpaths = __assign(__assign(__assign(__assign(__assign(__assign(__assign(__assign(__assign(__assign(__assign({}, noChange('selectedBy')), noChange('sourcePrefix')), noChange('destBasePath')), noChange('prefix')), noChange('suffix')), noChange('hashlen')), noChange('clean')), noChange('addclassnames')), parseIfString('widths')), parseIfString('breaks')), parseIfString('types'));
161
    /**
162
     *
163
     * @param fallback - ConfigMap
164
     * @param ob - object with a `properties` key with a ConfigMap type
165
     */
166
    var mergeNode = function (fallback, ob) { return merge(HASTpaths, fallback, ob.properties); };
167
    /**
168
     *
169
     * @param fallback - a config map
170
     * @param ob - also a config map
171
     */
172
    var mergeConfig = function (fallback, ob) {
173
        if (ob === void 0) { ob = {}; }
174
        return merge(NORMpaths, fallback, ob);
175
    };
176
    /**
177
     * @exports rehype-all-the-thumbs-curate
178
     * @description the `rehype-all-the-thumbs-curate` plugin adds a transformer to the pipeline.
179
     * @param { InboundConfig } [config] - Instructions for a Resizer Algorithm to understand the types of thumbnails desired.
180
     */
181
    var attacher = function (config) {
182
        var select = !config || !config.select
183
            ? 'picture[thumbnails="true"]>img'
184
            : typeof config.select === 'function'
185
                ? config.select()
186
                : config.select;
187
        var defaults = {
188
            selectedBy: select,
189
            sourcePrefix: '/',
190
            destBasePath: '/',
191
            hashlen: 8,
192
            clean: true,
193
            types: { webp: {}, jpg: {} },
194
            breaks: [640, 980, 1020],
195
            widths: [100, 250, 450, 600],
196
            addclassnames: ['all-thumbed'],
197
            prefix: 'optim/',
198
            suffix: '-{{width}}w-{{hash}}.{{ext}}'
199
        };
200
        var cfg = mergeConfig(defaults, config);
201
        // console.log({select})
202
        // console.log(0, {cfg})
203
        // transformer
204
        return function (tree, vfile, next) {
205
            // console.log(1,  JSON.stringify({ vfile1: vfile }, null, 2))
206
            // console.log(2,  JSON.stringify({ cfg }, null, 2))
207
            var selected = hast_util_select_1.selectAll(select, tree);
208
            // console.log( JSON.stringify({ selected }, null, 2))
209
            var srcsCompact = selected
210
                .map(function (node) { return ({ node: node, src: node.properties.src }); })
211
                .map(function (_a) {
212
                var src = _a.src, node = _a.node;
213
                return (__assign({ 
214
                    // makes a compact config
215
                    src: src }, mergeConfig(cfg, mergeNode(cfg, node))));
216
            });
217
            // console.log('plugin:curate--', {srcsCompact})
218
            var srcs = srcsCompact.reduce(function (p, _s) {
219
                var s = _s;
220
                var partOfSet = {
221
                    breaks: s.breaks,
222
                    types: s.types,
223
                    widths: s.widths
224
                };
225
                var accSimpleConfig = [];
226
                Object.entries(s.types).forEach(function (_a) {
227
                    var format = _a[0], opts = _a[1];
228
                    s.widths.forEach(function (width) {
229
                        var _a;
230
                        var ext = path_1.default.extname(s.src).slice(1); // no dot prefix
231
                        var fileName = path_1.default.basename(s.src, "." + ext);
232
                        accSimpleConfig.push({
233
                            selectedBy: s.selectedBy,
234
                            addclassnames: s.addclassnames,
235
                            input: {
236
                                ext: ext,
237
                                fileName: fileName,
238
                                pathPrefix: s.sourcePrefix
239
                            },
240
                            output: {
241
                                width: width,
242
                                format: (_a = {}, _a[format] = opts, _a),
243
                                hashlen: s.hashlen,
244
                                hash: trimmedHash(s.hashlen)
245
                            },
246
                            getReadPath: function (i) { return !i
247
                                ? exports.localResolve(s.sourcePrefix, fileName + "." + ext)
248
                                : i.render(path_1.default.resolve(s.sourcePrefix, s.src), i.data); },
249
                            getWritePath: function (i) { return !i
250
                                ? exports.localResolve(s.destBasePath, "" + s.prefix + fileName + s.suffix)
251
                                : i.render(path_1.default.resolve(s.destBasePath, "" + s.prefix + fileName + s.suffix), i.data); },
252
                            partOfSet: partOfSet
253
                        });
254
                    });
255
                });
256
                return __spreadArray(__spreadArray([], p), accSimpleConfig);
257
            }, []);
258
            // prettyPrint(0, 'plugin:curate--', {srcs})
259
            var vfile_srcs = isArray(vfile.srcs) ? __spreadArray(__spreadArray([], vfile.srcs), srcs) : srcs;
260
            // prettyPrint(1, 'plugin:curate--', {vfile})
261
            vfile.srcs = vfile_srcs;
262
            // return vfile
263
            next(null, tree, vfile);
264
        };
265
    };
266
    exports.attacher = attacher;
267
    exports.default = exports.attacher;
268
});
269
// #endregion interfaces
270