import { isAbsolute, relative, resolve } from 'path';
function formatTarget(target) {
    return Array.isArray(target) ? target.join('/') : target;
}
export default function safeResolveWithin(rootPath, target, label, { allowRoot = false } = {}) {
    const root = resolve(rootPath);
    const resolvedTarget = Array.isArray(target)
        ? resolve(root, ...target)
        : resolve(root, target);
    const targetLabel = formatTarget(target);
    const relativePath = relative(root, resolvedTarget);
    if (relativePath === '') {
        if (allowRoot) {
            return resolvedTarget;
        }
        throw new Error(`${label} "${targetLabel}" resolves to the expected root "${root}", but a path inside the root is required.`);
    }
    if (relativePath.startsWith('..') || isAbsolute(relativePath)) {
        throw new Error(`${label} "${targetLabel}" resolves to "${resolvedTarget}", which is outside the expected root "${root}".`);
    }
    return resolvedTarget;
}
