All files / src es6.js

99.24% Statements 131/132
93.85% Branches 61/65
100% Functions 11/11
99.24% Lines 130/131

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    1x 1x 1x   1x             1x             1x           1x 31x   31x 31x 31x 31x 31x   31x       31x 31x 31x   31x 63x     63x   27x       27x     27x       2x     2x       25x 16x 16x         9x     9x   9x 13x                           27x       63x   8x     8x 8x 8x     8x 2x 2x   8x 2x   2x 1x 1x           1x 1x       1x     1x       8x 7x           7x               63x 12x   12x 12x     12x 7x       7x       7x 2x 2x   2x           2x       7x 4x 4x   4x           4x       7x 1x 1x   1x           1x           5x 8x   8x 5x     8x           8x     5x           63x 1x 1x     1x           1x     1x   1x           1x           31x     30x     18x                       18x   10x                 8x         18x     30x                       30x 30x                 30x 5x   5x   5x         25x             30x 30x   30x 2x 3x 3x         3x 3x 3x   3x 2x 2x           30x 1x 8x 8x 4x   4x       4x 4x       30x         27x             25x               12x                       23x            
"use strict";
 
const template = require("@babel/template").default;
const path = require("path");
const {getBasePath, generateModuleName, toBasePath} = require("./util");
 
const buildAnonymousModule = template(`
define(IMPORT_PATHS, function(IMPORT_VARS) {
  "use strict";
	NAMED_IMPORTS;
	BODY;
});
`);
const buildNamedModule = template(`
define(MODULE_NAME, IMPORT_PATHS, function(IMPORT_VARS) {
  "use strict";
	NAMED_IMPORTS;
	BODY;
});
`);
const forInTemplate = template(`
for (var _key in IMPORT_VAR) {
    EXPORT_VAR[ _key ] = IMPORT_VAR[ _key ];
}
`);
 
module.exports.onEs6Module = function onEs6Module(t, programPath, meta) {
    const bodyPaths = programPath.get("body");
 
    const importPaths = [];
    const importVars = [];
    const namedImports = [];
    const options = meta.opts || {};
    const basePath = getBasePath(options);
 
    Iif ( options.moduleName && !basePath ) {
        throw new Error("moduleName should be boolean or object like are: {basePath: '...'}");
    }
        
    const exportsVariableName = programPath.scope.generateUidIdentifier("exports");
    let hasExport = false;
    let isOnlyDefaultExport = true;
 
    for (let i = 0; i < bodyPaths.length; i++) {
        const bodyStatementPath = bodyPaths[i];
 
        // import
        if ( t.isImportDeclaration(bodyStatementPath) ) {
            // save import path
            importPaths.push(
                bodyStatementPath.node.source
            );
 
            const importNode = bodyStatementPath.node;
 
            // import "some"
            if ( isAnonymousImport(importNode) ) {
                // importVars.length
                // should be equal 
                // importPaths.length 
                const tmpImportVariableName = bodyStatementPath.scope.generateUidIdentifier(
                    bodyStatementPath.node.source.value
                );
                importVars.push( tmpImportVariableName );
            }
            // import some from "some"
            // import * as some from "some"
            else if ( isImportDefault(importNode) || isImportAllAs(importNode) ) {
                const asName = importNode.specifiers[0].local;
                importVars.push( asName );
            }
            // import {x, y, z} from "xyz"
            else {
                // convert "/path/to/a"  to   _pathToA
                const asName = bodyStatementPath.scope.generateUidIdentifier(
                    bodyStatementPath.node.source.value
                );
                importVars.push( asName );
 
                importNode.specifiers.forEach(({imported, local}) => {
                    namedImports.push(
                        t.variableDeclaration("var", [
                            t.variableDeclarator(
                                t.identifier(local.name),
                                t.memberExpression(
                                    t.identifier(asName.name), 
                                    t.identifier(imported.name)
                                )
                            )
                        ])
                    );
                });
            }
 
            bodyStatementPath.remove();
        }
 
        // export default
        if ( t.isExportDefaultDeclaration(bodyStatementPath) ) {
            // need return at end file
            hasExport = true;
 
            // expression after keyword default
            const declaration = bodyStatementPath.get("declaration");
            let exportValue = declaration.node;
            let needExportExpression = true;
 
 
            if ( t.isFunctionDeclaration(declaration) ) {
                const funcNode = exportValue;
                exportValue = t.toExpression(funcNode);
            }
            if ( t.isClassDeclaration(declaration) ) {
                const classNode = exportValue;
 
                if ( classNode.id ) {
                    const className = t.identifier(classNode.id.name);
                    const exportDefault = exportStatement({
                        t, exportsVariableName,
                        key: "default",
                        value: className
                    });
 
                    bodyStatementPath.replaceWith(classNode);
                    programPath.pushContainer("body", [
                        exportDefault
                    ]);
 
                    needExportExpression = false;
                }
                else {
                    exportValue = t.toExpression(classNode);
                }
            }
 
            if ( needExportExpression ) {
                const statement = exportStatement({
                    t, exportsVariableName,
                    key: "default",
                    value: exportValue
                });
 
                bodyStatementPath.replaceWith(statement);
            }
        }
 
        // export {x as y}
        // export var a = 1;
        // export function test() {};
        // export class Test {};
        if ( t.isExportNamedDeclaration(bodyStatementPath) ) {
            hasExport = true;
 
            const {specifiers} = bodyStatementPath.node;
            const declaration = bodyStatementPath.get("declaration");
 
            // export var a = 1;
            if ( !specifiers.length ) {
                isOnlyDefaultExport = false;
 
                // replace "export <expression>"
                // to "<expression>"
                bodyStatementPath.replaceWith( declaration );
                    
 
                // export var a = 1;
                if ( t.isVariableDeclaration( declaration ) ) {
                    const varNode = declaration.node;
                    const asName = varNode.declarations[0].id.name;
 
                    const statement = exportStatement({
                        t, exportsVariableName,
                        key: asName,
                        value: t.identifier(asName)
                    });
                        
                    programPath.pushContainer("body", [statement]);
                }
 
                // export function x() {}
                if ( t.isFunctionDeclaration(declaration) ) {
                    const funcNode = declaration.node;
                    const asName = funcNode.id.name;
 
                    const statement = exportStatement({
                        t, exportsVariableName,
                        key: asName,
                        value: t.identifier(asName)
                    });
                        
                    programPath.pushContainer("body", [statement]);
                }
 
                // export class Test {}
                if ( t.isClassDeclaration(declaration) ) {
                    const classNode = declaration.node;
                    const asName = classNode.id.name;
 
                    const statement = exportStatement({
                        t, exportsVariableName,
                        key: asName,
                        value: t.identifier(asName)
                    });
                        
                    programPath.pushContainer("body", [statement]);
                }
                    
            }
            // export {x as y}
            else {
                specifiers.forEach(specifier => {
                    const asName = specifier.exported.name;
 
                    if ( asName != "default" ) {
                        isOnlyDefaultExport = false;
                    }
 
                    const statement = exportStatement({
                        t, exportsVariableName,
                        key: asName,
                        value: specifier.local
                    });
                        
                    programPath.pushContainer("body", [statement]);
                });
 
                bodyStatementPath.remove();
            }
        }
 
 
        // export * from "module"
        if ( t.isExportAllDeclaration(bodyStatementPath) ) {
            isOnlyDefaultExport = false;
            hasExport = true;
 
            // save import path
            importPaths.push(
                bodyStatementPath.node.source
            );
            // importVars.length
            // should be equal 
            // importPaths.length 
            const tmpImportVariableName = bodyStatementPath.scope.generateUidIdentifier(
                bodyStatementPath.node.source.value
            );
            importVars.push( tmpImportVariableName );
                
            const forIn = forInTemplate({
                IMPORT_VAR: tmpImportVariableName,
                EXPORT_VAR: exportsVariableName
            });
 
 
            bodyStatementPath.replaceWith(forIn);
        }
    }
 
 
    // adding define wrapper
    if ( importPaths.length || hasExport ) {
 
            
        if ( hasExport ) {
 
            // var _exports = {};
            programPath.unshiftContainer("body", [
                t.variableDeclaration("var", [
                    t.variableDeclarator(
                        exportsVariableName,
                        t.objectExpression([])
                    )
                ])
            ]);
 
            // return <expression>;
            let returnStatement;
 
            if ( isOnlyDefaultExport ) {
                // return _exports.default;
                returnStatement = t.returnStatement(
                    t.memberExpression(
                        exportsVariableName, 
                        t.identifier("default")
                    )
                );
            }
            else {
                // return _exports;
                returnStatement = t.returnStatement(
                    exportsVariableName
                );
            }
 
            programPath.pushContainer("body", [returnStatement]);
        }
 
        buildModule({
            t, programPath, meta,
            importPaths, importVars, namedImports
        });
    }
};
 
function buildModule({
    t, programPath, meta,
    importPaths, importVars, 
    namedImports
}) {
    const options = meta.opts || {};
    const templateValues = {
        IMPORT_PATHS: prepareImportPaths(
            t, meta, importPaths
        ),
        IMPORT_VARS: importVars,
        BODY: programPath.node.body,
        NAMED_IMPORTS: namedImports
    };
        
    if ( options.moduleName ) {
        const moduleName = generateModuleName(meta);
 
        templateValues.MODULE_NAME = t.stringLiteral(moduleName);
 
        programPath.node.body = [
            buildNamedModule( templateValues )
        ];
    }
    else {
        programPath.node.body = [
            buildAnonymousModule( templateValues )
        ];
    }
}
 
function prepareImportPaths(t, meta, importPaths) {
    const options = meta.opts || {};
    const basePath = getBasePath(options);
 
    if ( options.paths ) {
        importPaths.forEach(importNode => {
            const importPath = importNode.value;
            const absolutePath = path.resolve(
                meta.file.opts.filename, 
                "../" + importPath
            );
 
            for (const moduleName in options.paths) {
                const modulePath = options.paths[ moduleName ];
                const fullModulePath = path.resolve(basePath, modulePath);
 
                if ( absolutePath == fullModulePath ) {
                    importNode.value = moduleName;
                    break;
                }
            }
        });
    }
 
    if ( options.relativeImportToBasePath ) {
        importPaths.forEach(importNode => {
            const importPath = importNode.value;
            if ( importPath[0] !== "." ) {
                return;
            }
            const absolutePath = path.resolve(
                meta.file.opts.filename, 
                "../" + importPath
            );
            const normalPath = toBasePath(basePath, absolutePath);
            importNode.value = normalPath;
        });
    }
 
    return t.arrayExpression(importPaths);
}
 
function isAnonymousImport(importNode) {
    // import "some"
    return (
        importNode.specifiers.length === 0
    );
}
 
function isImportDefault(importNode) {
    // import some from "some"
    return (
        importNode.specifiers.length === 1 &&
        importNode.specifiers[0].type === "ImportDefaultSpecifier"
    );
}
 
function isImportAllAs(importNode) {
    // import * as some from "some"
    return (
        importNode.specifiers.length === 1 &&
        importNode.specifiers[0].type !== "ImportDefaultSpecifier" &&
        !importNode.specifiers[0].imported
    );
}
 
function exportStatement({
    t, exportsVariableName,
    key,
    value
}) {
    return t.toStatement( t.assignmentExpression(
        "=", 
        t.memberExpression(exportsVariableName, t.identifier(key)), 
        value
    ) );
}