"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.resolveModuleName = resolveModuleName;
const path_browserify_1 = require("path-browserify");
function resolveModuleName(ts, languageServiceHost, fileName, moduleName, allowNonExistent) {
    const compilerOptions = languageServiceHost.getCompilationSettings();
    const ext = moduleName.split('.').pop();
    const result = ts.resolveModuleName(moduleName, fileName, {
        ...compilerOptions,
        allowArbitraryExtensions: true,
    }, {
        fileExists(fileName) {
            return languageServiceHost.fileExists(transformFileName(fileName, ext));
        },
        readFile: languageServiceHost.readFile.bind(languageServiceHost),
    });
    const resolved = result.resolvedModule?.resolvedFileName;
    if (resolved) {
        return transformFileName(resolved, ext);
    }
    if (allowNonExistent && 'failedLookupLocations' in result) {
        const alternative = result.failedLookupLocations?.[0];
        if (alternative) {
            return path_browserify_1.posix.join(alternative, '..', path_browserify_1.posix.basename(moduleName));
        }
    }
}
function transformFileName(fileName, ext) {
    if (ext && fileName.endsWith(`.d.${ext}.ts`)) {
        return fileName.slice(0, -`.d.${ext}.ts`.length) + `.${ext}`;
    }
    return fileName;
}
//# sourceMappingURL=resolveModuleName.js.map