"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.findCodeFragment = findCodeFragment;
exports.patchCodeAtFragment = patchCodeAtFragment;
exports.patchCodeAtFragments = patchCodeAtFragments;
exports.updateCode = updateCode;
const tslib_1 = require("tslib");
const is_1 = tslib_1.__importDefault(require("@sindresorhus/is"));
const parser_1 = require("./parser");
function findCodeFragment(input, path) {
    const parsed = (0, parser_1.parse)(input);
    if (!parsed) {
        return null;
    }
    const [ruleIndex, ...restPath] = path;
    let fragment = parsed[ruleIndex];
    for (let pathIndex = 0; pathIndex < restPath.length; pathIndex += 1) {
        if (!fragment) {
            break;
        }
        const key = restPath[pathIndex];
        if (fragment.type === 'array' && is_1.default.number(key)) {
            fragment = fragment.children[key];
        }
        if (fragment.type === 'record' && is_1.default.string(key)) {
            fragment = fragment.children[key];
        }
    }
    return fragment ?? null;
}
function patchCodeAtFragment(input, fragment, updater) {
    const { value, offset } = fragment;
    const left = input.slice(0, offset);
    const right = input.slice(offset + value.length);
    return is_1.default.string(updater)
        ? `${left}${updater}${right}`
        : `${left}${updater(value)}${right}`;
}
function patchCodeAtFragments(input, fragments, updater) {
    const sortedFragments = fragments.sort(({ offset: a }, { offset: b }) => b - a);
    let result = input;
    for (const fragment of sortedFragments) {
        result = patchCodeAtFragment(result, fragment, updater);
    }
    return result;
}
function updateCode(input, path, updater) {
    const fragment = findCodeFragment(input, path);
    if (!fragment) {
        return input;
    }
    return patchCodeAtFragment(input, fragment, updater);
}
//# sourceMappingURL=common.js.map