import { arrayJoin, stringSplit } from "ts-extras";
import { ruleCreator } from "../_internal/rule-creator.js";
const splitLines = (sourceText) => stringSplit(sourceText.replaceAll(/\r\n?/gu, "\n"), "\n");
const collapseEmptyLines = (sourceText) => {
    const lines = splitLines(sourceText);
    let output = [];
    let emptyRun = 0;
    for (const line of lines) {
        const isEmpty = line.trim().length === 0;
        if (!isEmpty) {
            emptyRun = 0;
            output = [...output, line];
            continue;
        }
        if (emptyRun < 1) {
            output = [...output, line];
        }
        emptyRun += 1;
    }
    return arrayJoin(output, "\n");
};
const hasTooManyEmptyLines = (sourceText) => {
    let emptyRun = 0;
    for (const line of splitLines(sourceText)) {
        if (line.trim().length === 0) {
            emptyRun += 1;
            if (emptyRun >= 2) {
                return true;
            }
        }
        else {
            emptyRun = 0;
        }
    }
    return false;
};
/**
 * Enforce at most one consecutive empty line.
 */
const rule = ruleCreator({
    create: (context) => ({
        Program: (node) => {
            const sourceText = context.sourceCode.getText();
            if (!hasTooManyEmptyLines(sourceText)) {
                return;
            }
            context.report({
                fix: (fixer) => fixer.replaceTextRange([0, sourceText.length], collapseEmptyLines(sourceText)),
                messageId: "inconsistent",
                node,
            });
        },
    }),
    defaultOptions: [],
    meta: {
        deprecated: false,
        docs: {
            deprecated: false,
            description: "enforce at most one consecutive empty line.",
            frozen: false,
            recommended: false,
            url: "https://nick2bad4u.github.io/eslint-plugin-etc-misc/docs/rules/consistent-empty-lines",
        },
        fixable: "whitespace",
        hasSuggestions: false,
        messages: {
            inconsistent: "Consecutive empty lines should be collapsed to a single blank line.",
        },
        schema: [],
        type: "layout",
    },
    name: "consistent-empty-lines",
});
export default rule;
//# sourceMappingURL=consistent-empty-lines.js.map