"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.transformer = void 0;
const fs_1 = require("fs");
const path_1 = require("path");
const utils_1 = require("../modules/utils");
let sass;
function getResultForResolve(result) {
    var _a;
    return {
        code: result.css.toString(),
        map: (_a = result.map) === null || _a === void 0 ? void 0 : _a.toString(),
        dependencies: result.stats.includedFiles,
    };
}
const tildeImporter = (url, prev) => {
    if (!url.startsWith('~')) {
        return null;
    }
    // not sure why this ends up here, but let's remove it
    prev = prev.replace('http://localhost', '');
    // on windows, path comes encoded
    if (process.platform === 'win32') {
        prev = decodeURIComponent(prev);
    }
    const modulePath = path_1.join('node_modules', ...url.slice(1).split(/[\\/]/g));
    const foundPath = utils_1.findUp({ what: modulePath, from: prev });
    // istanbul ignore if
    if (foundPath == null) {
        return null;
    }
    const contents = fs_1.readFileSync(foundPath).toString();
    return { contents };
};
const transformer = async ({ content, filename, options = {}, }) => {
    var _a;
    let implementation = (_a = options === null || options === void 0 ? void 0 : options.implementation) !== null && _a !== void 0 ? _a : sass;
    if (implementation == null) {
        const mod = await utils_1.importAny('sass', 'node-sass');
        // eslint-disable-next-line no-multi-assign
        implementation = sass = mod.default;
    }
    const { renderSync, prependData, ...restOptions } = {
        ...options,
        includePaths: utils_1.getIncludePaths(filename, options.includePaths),
        outFile: `${filename}.css`,
        omitSourceMapUrl: true, // return sourcemap only in result.map
    };
    const sassOptions = {
        ...restOptions,
        file: filename,
        data: content,
    };
    if (Array.isArray(sassOptions.importer)) {
        sassOptions.importer = [tildeImporter, ...sassOptions.importer];
    }
    else if (sassOptions.importer == null) {
        sassOptions.importer = [tildeImporter];
    }
    else {
        sassOptions.importer = [sassOptions.importer, tildeImporter];
    }
    // scss errors if passed an empty string
    if (sassOptions.data.length === 0) {
        return { code: '' };
    }
    if (renderSync) {
        return getResultForResolve(implementation.renderSync(sassOptions));
    }
    return new Promise((resolve, reject) => {
        implementation.render(sassOptions, (err, result) => {
            if (err)
                return reject(err);
            resolve(getResultForResolve(result));
        });
    });
};
exports.transformer = transformer;
