"use strict";
var __rest = (this && this.__rest) || function (s, e) {
    var t = {};
    for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
        t[p] = s[p];
    if (s != null && typeof Object.getOwnPropertySymbols === "function")
        for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
            if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
                t[p[i]] = s[p[i]];
        }
    return t;
};
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
    result["default"] = mod;
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
const babel = __importStar(require("@babel/core"));
const console_utils_1 = require("./console_utils");
const fs_extra_1 = require("fs-extra");
const loader_utils_1 = require("loader-utils");
function getBabelConfig(reactIntlOptions, extraBabelOptions = {}) {
    return Object.assign({ babelrc: false, configFile: false, parserOpts: {
            plugins: [
                'asyncGenerators',
                'bigInt',
                'classPrivateMethods',
                'classPrivateProperties',
                'classProperties',
                'decorators-legacy',
                'doExpressions',
                'dynamicImport',
                'exportDefaultFrom',
                'functionBind',
                'functionSent',
                'importMeta',
                'jsx',
                'logicalAssignment',
                'nullishCoalescingOperator',
                'numericSeparator',
                'objectRestSpread',
                'optionalCatchBinding',
                'optionalChaining',
                'partialApplication',
                'placeholders',
                'throwExpressions',
                'topLevelAwait',
                'typescript',
            ],
        }, 
        // We need to use require.resolve here, or otherwise the lookup is based on the current working
        // directory of the CLI.
        plugins: [[require.resolve('babel-plugin-react-intl'), reactIntlOptions]], highlightCode: true, 
        // Extraction of string messages does not output the transformed JavaScript.
        sourceMaps: false }, extraBabelOptions);
}
async function extract(files, _a) {
    var { idInterpolationPattern, throws, readFromStdin } = _a, babelOpts = __rest(_a, ["idInterpolationPattern", "throws", "readFromStdin"]);
    if (readFromStdin) {
        // Read from stdin
        if (process.stdin.isTTY) {
            console_utils_1.warn('Reading source file from TTY.');
        }
        if (!babelOpts.overrideIdFn && idInterpolationPattern) {
            babelOpts = Object.assign(Object.assign({}, babelOpts), { overrideIdFn: (id, defaultMessage, description) => id ||
                    loader_utils_1.interpolateName({
                        resourcePath: 'dummy',
                    }, idInterpolationPattern, { content: defaultMessage + (description ? '#' + description : '') }) });
        }
        const stdinSource = await console_utils_1.getStdinAsString();
        const babelResult = babel.transformSync(stdinSource, getBabelConfig(babelOpts));
        return [
            babelResult.metadata['react-intl'],
        ];
    }
    const results = await Promise.all(files.map(filename => {
        if (!babelOpts.overrideIdFn && idInterpolationPattern) {
            babelOpts = Object.assign(Object.assign({}, babelOpts), { overrideIdFn: (id, defaultMessage, description) => id ||
                    loader_utils_1.interpolateName({
                        resourcePath: filename,
                    }, idInterpolationPattern, { content: `${defaultMessage}#${description}` }) });
        }
        const promise = babel.transformFileAsync(filename, getBabelConfig(babelOpts, { filename: filename }));
        return throws ? promise : promise.catch(e => console_utils_1.warn(e));
    }));
    return results
        .filter(r => r && r.metadata)
        .map(r => r.metadata['react-intl']);
}
exports.extract = extract;
async function extractAndWrite(files, opts) {
    const { outFile } = opts, extractOpts = __rest(opts, ["outFile"]);
    if (outFile) {
        extractOpts.messagesDir = undefined;
    }
    const extractionResults = await extract(files, extractOpts);
    const printMessagesToStdout = extractOpts.messagesDir == null && !outFile;
    const extractedMessages = extractionResults
        .map(m => m.messages)
        .filter(Boolean)
        .reduce((all, messages) => [...all, ...messages], []);
    if (outFile) {
        fs_extra_1.outputJSONSync(outFile, extractedMessages, {
            spaces: 2,
        });
    }
    if (printMessagesToStdout) {
        process.stdout.write(JSON.stringify(extractedMessages, null, 2));
        process.stdout.write('\n');
    }
}
exports.default = extractAndWrite;
//# sourceMappingURL=extract.js.map