# All files / gogocode-core/src/js-core core.js

82.86% Statements 232/280
78.75% Branches 189/240
78.38% Functions 29/37
83.33% Lines 230/276

Press n or j to go to the next uncovered block, b, p or k for the previous block.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    282
    283
    284
    285
    286
    287
    288
    289
    290
    291
    292
    293
    294
    295
    296
    297
    298
    299
    300
    301
    302
    303
    304
    305
    306
    307
    308
    309
    310
    311
    312
    313
    314
    315
    316
    317
    318
    319
    320
    321
    322
    323
    324
    325
    326
    327
    328
    329
    330
    331
    332
    333
    334
    335
    336
    337
    338
    339
    340
    341
    342
    343
    344
    345
    346
    347
    348
    349
    350
    351
    352
    353
    354
    355
    356
    357
    358
    359
    360
    361
    362
    363
    364
    365
    366
    367
    368
    369
    370
    371
    372
    373
    374
    375
    376
    377
    378
    379
    380
    381
    382
    383
    384
    385
    386
    387
    388
    389
    390
    391
    392
    393
    394
    395
    396
    397
    398
    399
    400
    401
    402
    403
    404
    405
    406
    407
    408
    409
    410
    411
    412
    413
    414
    415
    416
    417
    418
    419
    420
    421
    422
    423
    424
    425
    426
    427
    428
    429
    430
    431
    432
    433
    434
    435
    436
    437
    438
    439
    440
    441
    442
    443
    444
    445
    446
    447
    448
    449
    450
    451
    452
    453
    454
    455
    456
    457
    458
    459
    460
    461
    462
    463
    464
    465
    466
    467
    468
    469
    470
    471
    472
    473
    474
    475
    476
    477
    478
    479
    480
    481
    482
    483
    484
    485
    486
    487
    488
    489
    490
    491
    49237x
    37x
    37x
    37x
    37x
    37x

    37x

    345x
    335x

    345x
    345x
    345x
    345x
    354x
    354x
    354x
    373x

    373x

    345x
    345x
    373x
    373x
    474x
    474x
    473x
    473x
    473x

    345x

    133x
    133x
    708x
    708x

    133x

    1x
    1x

    1x
    1x
    1x
    1x
    1x

    2x
    2x

    2x
    2x
    2x
    2x
    1x
    1x

    1x
    1x
    4x
    1x

    3x
    3x
    3x
    1x

    635x

    635x
    635x
    608x
    608x
    608x
    416x

    192x
    6x
    186x
    180x
    6x
    2x
    4x

    2x

    2x

    27x
    8x

    2x

    6x

    7x
    19x

    10x
    10x
    9x

    2x
    2x

    7x

    8x

    609x
    4x
    4x

    4x
    3x

    609x

    116x
    1x
    1x
    1x
    1x

    115x

    115x
    7x

    108x

    139x
    139x
    139x
    107x
    107x
    107x
    12x
    12x
    1x

    106x
    87x
    87x
    127x
    42x
    42x
    42x

    42x
    45x
    45x

    45x
    41x
    41x

    45x
    45x

    42x

    85x
    85x
    85x
    65x
    70x

    20x
    20x

    20x

    87x
    2x

    85x
    85x
    85x

    85x
    13x
    13x
    12x

    85x

    85x
    35x

    85x

    19x
    4x
    15x
    15x
    15x

    15x
    11x

    15x

    2x
    2x

    2x
    2x
    2x
    2x
    2x
    2x

    2x

    2x
    2x

    2x
    2x
    2x
    2x
    2x
    2x

    2x

    7x
    1x

    6x
    1x

    5x

    5x

    8x
    1x

    7x

    7x
    7x

    1x

    21x
    6x

    15x

    5x
    1x

    4x
    2x

    2x
    2x
    2x

    2x
    2x
    2x
    2x

    2x

    1x

    20x
    1x

    19x
    1x

    18x

    18x
    18x

    18x
    127x
    127x
    117x
    6x
    6x
    6x
    6x
    6x
    6x

    111x
    11x

    1x
    1x
    1x
    1x
    1x
    2x
    2x
    2x

    1x
    1x

    37xconst getSelector = require('./get-selector');
    const { find, visit } = require('./find/general');
    const parse = require('./parse');
    const generate = require('./generate');
    const nodeLinkMap = require('./node-link-map');
    const buildMap = require('./build-map');

    const core = {
        // 通过选择器获取，返回ast片段
        getAstsBySelector(ast, selector, { strictSequence, deep, parseOptions, expando = 'g123o456g789o' } = {}) {
            //strictSequence作用：
            // 有的时候数组不要求顺序，如{a:$_$}匹配{b:1, a:2}
            // 有的时候需要，如function($_$, $_$)匹配function(a, b) {}

            if (!Array.isArray(selector)) {
                selector = [selector];
            }
            let nodePathList = [];
            let matchWildCardList = [];
            const selectorAst = [];
            selector.forEach(item => {
                let sels = getSelector(item, this.parseOptions || parseOptions, expando);
                !Array.isArray(sels) && (sels = [sels])
                sels.forEach(sel => {
                    Iif (!sel.nodeType) {
                        throw new Error('语句类型缺失，请在 https://github.com/thx/gogocode/issues 上提供您的代码样例')
                    }
                    selectorAst.push(sel);
                })
            })
            const posStrList = [];
            selectorAst.forEach(item => {
                const res = find.call(ast, item.nodeType, item.structure, strictSequence, deep, expando);
                res.nodePathList.forEach((p, i) => {
                    const posStr = `${p.node.start},${p.node.end}`;
                    if (posStrList.indexOf(posStr) == -1 || item.nodeType.match('Comment')) { // 去重
                        nodePathList.push(p);
                        matchWildCardList.push(res.matchWildCardList[i]);
                        posStrList.push(posStr);
                    }
                });
            });
            return {
                nodePathList,
                matchWildCardList,
                pathList: nodePathList,
                extraDataList: matchWildCardList
            };
        },
        getParentListByAst(path) {
            const list = [];
            while(path && path.parentPath) {
                list.push(path.parentPath);
                path = path.parentPath;
            }
            return list
        },
        getPrevAst(path) {
            let parent = path.parentPath;
            while(parent.value && !Array.isArray(parent.value)) {
                path = parent;
                parent = parent.parentPath;
            }
            parent = parent.value;
            Eif (parent) {
                const index = parent.indexOf(path.node);
                Eif (index > 0) {
                    return parent[index - 1];
                } else return null;
            }
            return null;
        },
        getNextAst(path) {
            let parent = path.parentPath;
            while(parent.value && !Array.isArray(parent.value)) {
                path = parent;
                parent = parent.parentPath;
            }
            parent = parent.value;
            Eif (parent) {
                const index = parent.indexOf(path.node);
                if (parent[index + 1]) {
                    return parent[index + 1];
                } else return null;
            }
            return null;
        },
        hasChildrenSelector(path, childSelector, expando) {
            const childCache = path.__childCache || {};
            for (const childKey in childCache) {
                if (['type', 'directives'].indexOf(childKey) > -1) {
                    continue;
                }
                const child = childCache[childKey];
                const { nodePathList } = core.getAstsBySelector(child, childSelector, { deep: 'nn', expando });
                if (nodePathList.length > 0) {
                    return true;
                }
            }
        },
        buildAstByAstStr(str, astPatialMap = {}, { isProgram = false, parseOptions } = {}) {
            try {
                let ast;
                try {
                    ast = parse(str, parseOptions);
                    const program = core.replaceStrByAst(ast, astPatialMap);
                    Eif (program) {
                        if (isProgram) {
                            return program;
                        } else {
                            if (program.program.body.length > 1) {
                                return program.program.body
                            } else if (program.program.body.length == 1) {
                                return program.program.body[0];
                            } else if (program.program.comments && program.program.comments[0]) {
                                return program.program.comments[0];
                            } else if (program.program.directives
                                && program.program.directives[0]
                                && program.program.directives[0].value
                                && program.program.directives[0].value.value) {
                                return {
                                    type: 'StringLiteral',
                                    value: program.program.directives[0].value.value
                                }
                            } else {
                                return program.program
                            }
                        }
                    } else {
                        return null;
                    }
                } catch(e) {
                    if (str.match(/^{(\s|.)+\}$/)) {
                        if (str.match('...') && str.match('=')) {
                            // 解构入参
                            ast = buildMap.DestructuringParam(str)
                        } else {
                            // 对象字面量
                            ast = buildMap.ObjectExpression(str)
                        }
                        return ast;
                    } else if (e.message.match('Missing semicolon')) {
                        // 可能是对象属性
                        ast = buildMap.ObjectProperty(str)
                        return ast
                    } else if (e.message.match('Leading decorators must be attached to a class declaration')) {
                        // 是decorator
                        ast = buildMap.Decorators(str)
                        return ast
                    } else {
                        throw new Error(`buildAstByAstStr failed:${str}`)
                    }
                }
            } catch(error) {
                throw new Error(`buildAstByAstStr failed:${str}`)
            }
        },
        replaceStrByAst(ast, astPatialMap = {}) {
            for (let key in astPatialMap) {
                const valueAst = astPatialMap[key];
                const { nodePathList } = core.getAstsBySelector(ast, [
                    { type: 'Identifier', name: `$_$${key}$_$` },
                    { type: 'StringLiteral', value: `$_$${key}$_$` }
                ]);
                if (nodePathList.length > 0) {
                    nodePathList[0].replace(valueAst)
                }
            }
            return ast;
        },
        replaceAstByAst(oldAst, newAst) {
            if (Array.isArray(newAst)) {
                const { arrPath = {}, index } = getArrPath(oldAst);
                Eif (Array.isArray(arrPath.value) && index > -1) {
                    arrPath.value.splice(index, 1, ...newAst);
                    return;
                }
            }
            Iif (newAst.type == 'BlockStatement' && Array.isArray(oldAst.parentPath.value)) {
                const parentNode = oldAst.parentPath.value;
                const oldIndex = parentNode.indexOf(oldAst.node);
                parentNode.splice(oldIndex, 1);
                newAst.body.forEach((replacer, index) => {
                    oldAst.parentPath.value.splice(oldIndex + index, 0, replacer)
                })
            } else if (!oldAst.parent && oldAst.node.type == 'File' ) {
                oldAst.node.program.body = [ newAst ]
            } else {
                oldAst.replace(newAst)
            }
        },
        replaceSelBySel(ast, selector, replacer, strictSequence, parseOptions, expando = 'g123o456g789o') {
            // 用于结构不一致的，整体替换
            const { nodePathList, matchWildCardList } = core.getAstsBySelector(ast, selector, { strictSequence, deep: 'nn', parseOptions: this.parseOptions || parseOptions, expando });
            const originReplacer = replacer
            nodePathList.forEach((path, i) => {
                const extra = matchWildCardList[i];
                replacer = originReplacer
                if (typeof replacer == 'function') {
                    replacer = replacer(extra, path);
                    if (replacer === null) {
                        return;
                    }
                }
                if (Object.keys(extra).length > 0 && typeof replacer == 'string') {
                    let newReplacer = replacer;
                    for(let key in extra) {
                        if (key.match(/\$\$\$/)) {
                            let key$$$ = key.replace(/\$\$\$/, '');
                            key$$$ == '$' && (key$$$ = '');
                            let join = '\n'

                            let wildCardCode = extra[key].map(item => {
                                let codeStr = generate(item);
                                try {
                                    // 嵌套replace
                                    const childAst = core.buildAstByAstStr(codeStr);
                                    core.replaceSelBySel(childAst, selector, replacer, strictSequence, parseOptions, expando);
                                    codeStr = generate(childAst)
                                } catch(e) { //
                                }
                                nodeLinkMap[item.type] && (join = nodeLinkMap[item.type])
                                return codeStr
                                //
                            }).join(join)
                            // 不能都用,连接，还是需要找到$_$

                            newReplacer = newReplacer.replace('$$$' + key$$$, wildCardCode.replace(/\$/g,'$$$$'));
                            // 如果wildCardCode存在`$'`，会被命中替换，因此对$进行处理(https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace)
                        } else {
                            let realKey = key == '0' ? '' : key;
                            const matchLength = (newReplacer.match(new RegExp(`\\$_\\$${realKey}`, 'g')) || []).length;
                            if (matchLength == extra[key].length) {
                                extra[key].forEach(ext => {
                                    newReplacer = newReplacer
                                        .replace(`'$_$${realKey}'`, ext.raw || ext.value)
                                        .replace(`"$_$${realKey}"`, ext.raw || ext.value)
                                        .replace('$_$' + realKey, ext.raw || ext.value);
                                })
                            } else {

                                // 删除代码块外部{},find里前置处理了，不需要在这里做了
                                let wildCardCode = extra[key].map(item =>
                                    typeof item.value !== 'object' ? (item.raw || item.value) : ``
                                ).join(', ')

                                newReplacer = newReplacer
                                    .replace(new RegExp(`'\\$_\\$${realKey}'`, 'g'), wildCardCode.replace(/\$/g,'$$$$'))
                                    .replace(new RegExp(`"\\$_\\$${realKey}"`, 'g'), wildCardCode.replace(/\$/g,'$$$$'))
                                    .replace(new RegExp(`\\$_\\$${realKey}`, 'g'), wildCardCode.replace(/\$/g,'$$$$'));
                                // 通过选择器替换ast，返回完整ast
                                // 如果wildCardCode存在`$'`，会被命中替换，因此对$进行处理(https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace)
                            }
                        }
                    }
                    if (!replacer) {
                        core.removePathSafe(path)
                    } else {
                        let replacerAst = null;
                        try {
                            replacerAst = core.buildAstByAstStr(newReplacer);
                        } catch(e) {
                            //
                        }
                        if (buildMap[path.node.type]) {
                            try {
                                Eif (buildMap[path.node.type](newReplacer)) {
                                    replacerAst = buildMap[path.node.type](newReplacer)
                                }
                            } catch(e) {
                                //
                            }
                        }
                        Iif (!replacerAst) {
                            throw new Error(`replace failed: ${newReplacer} cannot be parsed!`)
                        }
                        if (replacerAst.expression && replacerAst.expression.type != 'AssignmentExpression' && path.parentPath.name != 'body') {
                            replacerAst = replacerAst.expression
                        }
                        path && core.replaceAstByAst(path, replacerAst);
                    }
                } else {
                    if (!replacer) {
                        core.removePathSafe(path);
                    } else Eif (typeof replacer == 'string') {
                        let replacerAst = replacer.type ? replacer : core.buildAstByAstStr(replacer);
                        Iif (!replacer.type && buildMap[path.node.type]) {
                            try {
                                if (buildMap[path.node.type](replacer)) {
                                    replacerAst = buildMap[path.node.type](replacer)
                                }
                            } catch(e) {
                                //
                            }
                        }
                        if (replacerAst.expression && replacerAst.expression.type != 'AssignmentExpression' && path.parentPath.name != 'body') {
                            replacerAst = replacerAst.expression
                        }
                        path && core.replaceAstByAst(path, replacerAst);
                    } else {
                        if (replacer[0] && replacer[0].nodePath) {
                            path.replace(replacer[0].nodePath.node)
                        } else {
                            core.replaceAstByAst(path, replacer);
                        }
                    }
                }
            });
        },
        insertAstListBefore(path, nodeList) {
            Eif (!Array.isArray(nodeList)) {
                nodeList = [nodeList]
            }
            for (let i = 0; i< 3; i++) {
                const pNode = path.parentPath;
                Eif (pNode && pNode.value && Array.isArray(pNode.value)) {
                    const index = pNode.value.indexOf(path.value);
                    nodeList.reverse().forEach(item => {
                        pNode.value.splice(index, 0, item);
                    });
                    i = 3
                } else {
                    path = pNode;
                }
            }
        },
        insertAstListAfter(path, nodeList) {
            Eif (!Array.isArray(nodeList)) {
                nodeList = [nodeList]
            }
            for (let i = 0; i< 3; i++) {
                const pNode = path.parentPath;
                Eif (pNode && pNode.value && Array.isArray(pNode.value)) {
                    const index = pNode.value.indexOf(path.value) + 1;
                    nodeList.reverse().forEach(item => {
                        pNode.value.splice(index, 0, item);
                    });
                    i = 3
                } else {
                    path = pNode;
                }
            }
        },
        removeAst(ast, selector, { strictSequence, parseOptions, expando } = {}) {
            if (!ast || typeof ast !== 'object') {
                throw new Error('remove failed! first argument mast be object')
            }
            if (!selector || (typeof selector !== 'object' && typeof selector !== 'string' && !Array.isArray(selector))) {
                throw new Error('remove failed! first argument mast be object、string or string array')
            }
            // const selectorAst = getSelector(selector, this.parseOptions);
            // console.log(selectorAst)
            const { nodePathList } = core.getAstsBySelector(ast, selector, { strictSequence, parseOptions, expando })
            // const { nodePathList } = find.call(ast, selectorAst.nodeType, selectorAst.structure, true, 'nn');
            // console.log(nodePathList)
            nodePathList.forEach(path => {
                // 多条语句逗号分割的话，只删除一个；一条语句的话，删除父节点
                if ((!path.parentPath.value.length) || path.parentPath.value.length == 1) {
                    core.removePathSafe(path.parent);
                } else {
                    core.removePathSafe(path)
                }
            });
        },
        remove(path) {
            try {
                core.removePathSafe(path)
            } catch(e) {
                throw `remove failed: ${e}`
            }
        },
        removePathSafe(path) {
            // 对于expression 删除之后，父节点 expressionStatement 还在，输出会多个分号。所以应该删除 expressionStatement
            if (path.name == 'expression') {
                path.parent.replace();
            } else {
                path.replace();
            }
        },
        appendJsxAttr(ast, obj) {
            if (!ast || typeof ast !== 'object') {
                throw new Error('appendJsxAttr failed! first argument mast be object')
            }
            if (!obj || typeof obj !== 'object') {
                throw new Error('appendJsxAttr failed! second argument mast be object')
            }
            const attrs = [];
            for (let o in obj) {
                attrs.push(`${o}=${obj[o]}`.replace(/'\$'/g, "$"));
            }
            try {
                const jsxPartial = core.buildAstByAstStr(`<div ${attrs.join(' ')}></div>`);
                const newAttrs = jsxPartial.expression.openingElement.attributes;
                Iif (ast.value) {
                    ast.value.openingElement.attributes = ast.value.openingElement.attributes.concat(newAttrs);
                } else {
                    ast.expression.openingElement.attributes = ast.expression.openingElement.attributes.concat(newAttrs);
                }

            } catch(e) {
                throw new Error('appendJsxAttr failed!' + e)
            }

        },
        visit() {
            visit.call(this, ...Array.from(arguments));
        },
        traverse(node, cb, parentNode) {
            if(!node || typeof node !== 'object'){
                throw new Error('traverse failed! first argument mast be object')
            }
            if(!cb || typeof cb !== 'function'){
                throw new Error('traverse failed! second argument mast be function')
            }
            Eif (node.type && typeof node.type == 'string') {
                // 是一个ast节点,且不是token
                Eif (['File', 'Program'].indexOf(node.type) == -1) {
                    cb(node, { parentNode });
                }
                for (let attr in node) {
                    const child = node[attr];
                    if (child) {
                        if (Array.isArray(child)) {
                            let i = 0;
                            while(child[i]) {
                                const c = child[i];
                                core.traverse(c, cb, child);
                                i = child.indexOf(c);
                                i++
                            }
                            // child.forEach(c => core.traverse(c, cb, node));
                        } else if (child.type) {
                            core.traverse(child, cb, node);
                        }
                    }
                }
            }
        },
        initComment(ast) {
            core.traverse(ast, ((node, {parentNode}) => {
                if (Array.isArray(parentNode)) {
                    const index = parentNode.indexOf(node);
                    if (index == parentNode.length - 1) {
                        if (node.trailingComments) {
                            node.trailingComments.forEach(comment => {
                                parentNode.push(comment);
                            })
                        }
                    }
                    if (node.leadingComments) {
                        node.leadingComments.reverse().forEach(comment => {
                            parentNode.splice(index, 0, comment);
                        })
                    }
                }
            }))
        },
        removeComments(ast) {
            core.traverse(ast, ((node, {parentNode}) => {
                if (Array.isArray(parentNode)) {
                    if (!parentNode.every(item => typeof item.type == 'string' && item.type.match('Comment'))) {
                        let i = 0;
                        while (parentNode[i]) {
                            const node = parentNode[i];
                            if (node && typeof node.type == 'string' && node.type.match('Comment')) {
                                parentNode.splice(i, 1);
                                i--
                            }
                            i++
                        }
                    }
                }
            }))
        }
    }
    function getArrPath(path) {
        let arrPath = path
        Iif (!arrPath) return;
        let lastNode = path.node;
        let i = 0;
        while(!Array.isArray(arrPath.value) && i < 3) {
            lastNode = arrPath.node;
            arrPath = arrPath.parentPath;
            i++
        }
        Eif (Array.isArray(arrPath.value)) {
            return { arrPath: arrPath, index : arrPath.value.indexOf(lastNode) }
        } else {
            return { arrPath: {}, index: -1 };
        }
    }
    module.exports = core;