"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.transformRequest = void 0;
const fs_1 = require("fs");
const path_1 = __importDefault(require("path"));
const etag_1 = __importDefault(require("etag"));
const convertSourceMap = __importStar(require("convert-source-map"));
const chalk_1 = __importDefault(require("chalk"));
const utils_1 = require("../utils");
const debugLoad = utils_1.createDebugger('vite:load');
const debugTransform = utils_1.createDebugger('vite:transform');
const debugCache = utils_1.createDebugger('vite:cache');
const isDebug = !!process.env.DEBUG;
async function transformRequest(url, { config: { root }, pluginContainer, moduleGraph, watcher }) {
    var _a, _b, _c;
    url = utils_1.removeTimestampQuery(url);
    const prettyUrl = isDebug ? utils_1.prettifyUrl(url, root) : '';
    // check if we have a fresh cache
    const cached = (_a = (await moduleGraph.getModuleByUrl(url))) === null || _a === void 0 ? void 0 : _a.transformResult;
    if (cached) {
        isDebug && debugCache(`[memory] ${prettyUrl}`);
        return cached;
    }
    // resolve
    const id = ((_b = (await pluginContainer.resolveId(url))) === null || _b === void 0 ? void 0 : _b.id) || url;
    const file = utils_1.cleanUrl(id);
    let code = null;
    let map = null;
    // load
    const loadStart = Date.now();
    const loadResult = await pluginContainer.load(id);
    if (loadResult == null) {
        // try fallback loading it from fs as string
        // if the file is a binary, there should be a plugin that already loaded it
        // as string
        try {
            code = await fs_1.promises.readFile(file, 'utf-8');
            isDebug && debugLoad(`${utils_1.timeFrom(loadStart)} [fs] ${prettyUrl}`);
        }
        catch (e) {
            if (e.code !== 'ENOENT') {
                throw e;
            }
        }
        if (code) {
            map = (_c = (convertSourceMap.fromSource(code) ||
                convertSourceMap.fromMapFileSource(code, path_1.default.dirname(file)))) === null || _c === void 0 ? void 0 : _c.toObject();
        }
    }
    else {
        isDebug && debugLoad(`${utils_1.timeFrom(loadStart)} [plugin] ${prettyUrl}`);
        if (typeof loadResult === 'object') {
            code = loadResult.code;
            map = loadResult.map;
        }
        else {
            code = loadResult;
        }
    }
    if (code == null) {
        throw new Error(`Failed to load url ${url}. Does the file exist?`);
    }
    // ensure module in graph after successful load
    const mod = await moduleGraph.ensureEntryFromUrl(url);
    // file is out of root, add it to the watch list
    if (mod.file && !mod.file.startsWith(root + '/')) {
        watcher.add(mod.file);
    }
    // transform
    const transformStart = Date.now();
    const transformResult = await pluginContainer.transform(code, id, map);
    if (transformResult == null ||
        (typeof transformResult === 'object' && transformResult.code == null)) {
        // no transform applied, keep code as-is
        isDebug &&
            debugTransform(utils_1.timeFrom(transformStart) + chalk_1.default.dim(` [skipped] ${prettyUrl}`));
    }
    else {
        isDebug && debugTransform(`${utils_1.timeFrom(transformStart)} ${prettyUrl}`);
        if (typeof transformResult === 'object') {
            code = transformResult.code;
            map = transformResult.map;
        }
        else {
            code = transformResult;
        }
    }
    return (mod.transformResult = {
        code,
        map,
        etag: etag_1.default(code, { weak: true })
    });
}
exports.transformRequest = transformRequest;
//# sourceMappingURL=transformRequest.js.map