All files plugin.ts

90.7% Statements 39/43
74.19% Branches 23/31
100% Functions 6/6
90.24% Lines 37/41

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  1x 1x   1x     2x   1x       1x             1x                 1x     1x   1x               1x     3x         3x           7x 7x                   36x 18x       3x           14x   7x           6x     6x 6x         6x 6x                   8x     4x 3x   1x   1x   1x 1x   1x   1x   1x 1x           1x  
import * as babel from "@babel/core";
import * as fsextra from "fs-extra";
import * as path from "path";
 
const generateOutputFilename = (
    extractTo: string,
    // In test env then opts.file isn't available
    Efilename: string = "test.jsx"
) => {
    const basename = path.basename(filename, path.extname(filename));
 
    // Make sure the relative path is "absolute" before
    // joining it with the `messagesDir`.
    let relativePath = path.join(
        path.sep,
        path.relative(process.cwd(), filename)
    );
    // Solve when the window user has symlink on the directory, because
    // process.cwd on windows returns the symlink root,
    // and filename (from babel) returns the original root
    Iif (process.platform === "win32") {
        const { name } = path.parse(process.cwd());
        if (relativePath.includes(name)) {
            relativePath = relativePath.slice(
                relativePath.indexOf(name) + name.length
            );
        }
    }
 
    return path.join(extractTo, path.dirname(relativePath), basename + ".json");
};
 
const TEST_IDS = Symbol("TEST_IDS");
 
const DEFAULT_MAGIC_OBJECT = "$TestId";
 
export interface PluginOpts {
    extractTo?: string;
    magicObject?: string;
    fs?: Pick<typeof fsextra, "mkdirpSync" | "writeFileSync">; // Here sp we can inject a mock in tests
}
 
export function plugin(
    this: { opts: PluginOpts },
    {
        types: t
    }: {
        types: typeof babel.types;
    }
): babel.PluginObj<{ file: any; opts: PluginOpts }> {
    return {
        /**
         * Create a Set on the file to hold collected ids. Attaching it to the file
         * means there is no issue of shared mutable state across different files
         */
        pre(file) {
            Eif (!file.has(TEST_IDS)) {
                file.set(TEST_IDS, new Set());
            }
        },
        visitor: {
            /**
             *
             * Prevent referring to the naked magicObject identifier, e.g.
             * { x: $TestId }
             */
            Identifier(path) {
                const { magicObject = DEFAULT_MAGIC_OBJECT } = this.opts;
                if (
                    path.node.name === magicObject &&
                    !t.isMemberExpression(path.container)
                ) {
                    throw path.buildCodeFrameError(
                        `Cannot refer to '${magicObject}' as a literal value. Use dot access to produce testIds e.g. '${magicObject}.myTestId'`
                    );
                }
            },
            MemberExpression(path, state) {
                const { magicObject = DEFAULT_MAGIC_OBJECT } = this.opts;
 
                if (
                    t.isIdentifier(path.node.object) &&
                    path.node.object.name === magicObject &&
                    t.isIdentifier(path.node.property)
                ) {
                    // The testid is the name of that property
                    const testId = path.node.property.name;
 
                    // Get existing ids, and as long as there's no dupe, add this one
                    const ids: Set<string> = state.file.get(TEST_IDS);
                    Iif (ids.has(testId)) {
                        throw path.buildCodeFrameError(
                            `Duplicate test id: ${testId}}`
                        );
                    }
                    ids.add(testId);
                    path.replaceWith(t.stringLiteral(testId));
                }
            }
        },
        /**
         * Once we've traversed the file, if we have found any ids then write
         * them to a json file, with a path that corresponds to the original
         * location of the file, but relative the the `testIdsDir`
         */
        post(file) {
            const { extractTo, fs = fsextra } = this.opts || {
                extractTo: false
            };
            if (!extractTo) {
                return;
            }
            const ids: Set<string> = file.get(TEST_IDS);
 
            const foundKeys = ids.size;
 
            Eif (foundKeys > 0) {
                const output = JSON.stringify([...ids.values()], null, 2);
 
                const { filename } = file.opts;
 
                const idFileName = generateOutputFilename(extractTo, filename);
 
                fs.mkdirpSync(path.dirname(idFileName));
                fs.writeFileSync(idFileName, output);
            }
        }
    };
}
 
export default plugin;