Note: After saving, you have to bypass your browser's cache to see the changes. Google Chrome, Firefox, Microsoft Edge and Safari: Hold down the ⇧ Shift key and click the Reload toolbar button. For details and instructions about other browsers, see Wikipedia:Bypass your cache.
// [[Category:Wikipedia scripts]]
// <nowiki>
(function (exports) {
    'use strict';

    /******************************************************************************
    Copyright (c) Microsoft Corporation.

    Permission to use, copy, modify, and/or distribute this software for any
    purpose with or without fee is hereby granted.

    THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
    REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
    AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
    INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
    LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
    OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
    PERFORMANCE OF THIS SOFTWARE.
    ***************************************************************************** */
    /* global Reflect, Promise, SuppressedError, Symbol, Iterator */


    var __assign = function() {
        __assign = Object.assign || function __assign(t) {
            for (var s, i = 1, n = arguments.length; i < n; i++) {
                s = arguments[i];
                for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
            }
            return t;
        };
        return __assign.apply(this, arguments);
    };

    function __awaiter(thisArg, _arguments, P, generator) {
        function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
        return new (P || (P = Promise))(function (resolve, reject) {
            function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
            function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
            function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
            step((generator = generator.apply(thisArg, _arguments || [])).next());
        });
    }

    function __generator(thisArg, body) {
        var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
        return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
        function verb(n) { return function (v) { return step([n, v]); }; }
        function step(op) {
            if (f) throw new TypeError("Generator is already executing.");
            while (g && (g = 0, op[0] && (_ = 0)), _) try {
                if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
                if (y = 0, t) op = [op[0] & 2, t.value];
                switch (op[0]) {
                    case 0: case 1: t = op; break;
                    case 4: _.label++; return { value: op[1], done: false };
                    case 5: _.label++; y = op[1]; op = [0]; continue;
                    case 7: op = _.ops.pop(); _.trys.pop(); continue;
                    default:
                        if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                        if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                        if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                        if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                        if (t[2]) _.ops.pop();
                        _.trys.pop(); continue;
                }
                op = body.call(thisArg, _);
            } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
            if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
        }
    }

    function __spreadArray(to, from, pack) {
        if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
            if (ar || !(i in from)) {
                if (!ar) ar = Array.prototype.slice.call(from, 0, i);
                ar[i] = from[i];
            }
        }
        return to.concat(ar || Array.prototype.slice.call(from));
    }

    typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
        var e = new Error(message);
        return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
    };

    var SEE_ALSO_HEADING_REGEX = /^\s*==\s*See\s+also\s*==\s*$/im;
    var CONFIG = {
        API_BATCH_SIZE: 50,
        TIMEOUT_DELAY: 100,
    };
    var STATS = {
        sectionLinksFormatted: 0,
        regularLinksFormatted: 0,
        manualDescriptionsReformatted: 0,
        linesUnprocessable: 0,
        linksSkippedRedirects: 0,
        linksSkippedMissing: 0,
        linksSkippedDisambiguation: 0,
        linksSkippedNamespaced: 0,
        linksSkippedEmptyDescription: 0,
        reset: function () {
            this.sectionLinksFormatted = 0;
            this.regularLinksFormatted = 0;
            this.manualDescriptionsReformatted = 0;
            this.linesUnprocessable = 0;
            this.linksSkippedRedirects = 0;
            this.linksSkippedMissing = 0;
            this.linksSkippedDisambiguation = 0;
            this.linksSkippedNamespaced = 0;
            this.linksSkippedEmptyDescription = 0;
        }
    };
    var REGEX_PATTERNS = {
        WIKILINK: /\[\[([^\]|]+)(?:\|[^\]]+)?\]\]/g,
        SIMPLE_LINK: /^\[\[([^\]]+)\]\]$/,
        AGGLUTINATED_LINK: /^\[\[([^\]]+)\]\]([a-zA-Z]+)$/,
        LINK_WITH_DESCRIPTION: /^((?:''+|")?)\[\[([^\]]+)\]\](\1)(?:\s*([,–—:\--]|\{\{(?:Spaced en dash|dash|snd|spnd|sndash|spndash)\}\})\s*(.*?)|\s+(.+))?\s*$/i,
        LIST_ITEM: /^(\s*\*+\s*)(.*)/,
        TEMPLATE_WITH_DESCRIPTION: /^(\s*\*+\s*)(\{\{(?:Section link|seclink|slink|anl|Annotated link|anli)[^}]+\}\})(?:\s*([,–—:\--])\s*(.+))?$/,
        SPACED_EN_DASH_TEMPLATES: /\{\{(?:Spaced en dash|dash|snd|spnd|sndash|spndash)\}\}/gi,
        VALID_ABBREVIATION: /^[A-Z]+(\.[A-Z]+)*\.?$/,
    };

    function throttle(func, delay) {
        var timeoutId = null;
        return function () {
            var _this = this;
            var args = [];
            for (var _i = 0; _i < arguments.length; _i++) {
                args[_i] = arguments[_i];
            }
            if (timeoutId !== null) {
                clearTimeout(timeoutId);
            }
            timeoutId = setTimeout(function () {
                func.apply(_this, args);
                timeoutId = null;
            }, delay);
        };
    }
    function capitalizeFirstLetter(str) {
        if (!str)
            return str;
        if (str[0] && str[0].match(/[a-z]/)) {
            return str[0].toUpperCase() + str.slice(1);
        }
        return str;
    }
    function isDisambiguationPage(pageTitle) {
        return pageTitle.substring(pageTitle.length - 16) === "(disambiguation)";
    }
    function isDisambiguationDescription(description) {
        return description === "Topics referred to by the same term";
    }
    function shouldSkipLinkForReason(pageTitle, skipInfo, selectedRedirects) {
        if (selectedRedirects === void 0) { selectedRedirects = []; }
        if (isDisambiguationPage(pageTitle)) {
            return "disambiguation";
        }
        if (!skipInfo) {
            return null;
        }
        if (skipInfo.disambiguationDescPages &&
            skipInfo.disambiguationDescPages[pageTitle]) {
            return "disambiguation";
        }
        if (skipInfo.redirectPages && skipInfo.redirectPages[pageTitle]) {
            var redirectInfo = skipInfo.redirectTargets && skipInfo.redirectTargets[pageTitle];
            if (!redirectInfo) {
                return "empty-description";
            }
            if (isDisambiguationPage(redirectInfo.target) ||
                (skipInfo.disambiguationDescPages && skipInfo.disambiguationDescPages[redirectInfo.target])) {
                return "disambiguation";
            }
            if (!redirectInfo.hasUsableDescription) {
                return "empty-description";
            }
            if (redirectInfo.shouldAutoSelect) {
                return null;
            }
            if (selectedRedirects.indexOf(pageTitle) === -1) {
                return "redirect-not-selected";
            }
            else {
                return null;
            }
        }
        if (!isSectionLink(pageTitle)) {
            if (skipInfo.namespacedPages && skipInfo.namespacedPages[pageTitle]) {
                return "namespaced";
            }
            if (skipInfo.missingPages && skipInfo.missingPages[pageTitle]) {
                return "missing";
            }
            if (skipInfo.emptyDescriptionPages &&
                skipInfo.emptyDescriptionPages[pageTitle]) {
                return "empty-description";
            }
        }
        return null;
    }
    function replaceSpacedEnDashTemplates(str) {
        if (!str)
            return str;
        return str.replace(REGEX_PATTERNS.SPACED_EN_DASH_TEMPLATES, " – ");
    }
    function generateSuccessMessage() {
        var parts = [];
        if (STATS.sectionLinksFormatted > 0) {
            var slinkText = STATS.sectionLinksFormatted === 1 ? "section link" : "section links";
            parts.push("Formatted " + STATS.sectionLinksFormatted + " " + slinkText);
        }
        if (STATS.regularLinksFormatted > 0) {
            var linkText = STATS.regularLinksFormatted === 1 ? "link" : "links";
            parts.push("Formatted " + STATS.regularLinksFormatted + " " + linkText);
        }
        if (STATS.manualDescriptionsReformatted > 0) {
            var descText = STATS.manualDescriptionsReformatted === 1
                ? "manual description"
                : "manual descriptions";
            parts.push("Reformatted " + STATS.manualDescriptionsReformatted + " " + descText);
        }
        if (STATS.linesUnprocessable > 0) {
            var lineText = STATS.linesUnprocessable === 1 ? "line" : "lines";
            parts.push("Skipped " +
                STATS.linesUnprocessable +
                " " +
                lineText +
                " (unprocessable)");
        }
        var skipReasons = [];
        if (STATS.linksSkippedRedirects > 0) {
            var redirectText = STATS.linksSkippedRedirects === 1 ? "redirect" : "redirects";
            skipReasons.push(STATS.linksSkippedRedirects + " " + redirectText);
        }
        if (STATS.linksSkippedMissing > 0) {
            var missingText = STATS.linksSkippedMissing === 1 ? "missing page" : "missing pages";
            skipReasons.push(STATS.linksSkippedMissing + " " + missingText);
        }
        if (STATS.linksSkippedDisambiguation > 0) {
            var disambigText = STATS.linksSkippedDisambiguation === 1
                ? "disambiguation page"
                : "disambiguation pages";
            skipReasons.push(STATS.linksSkippedDisambiguation + " " + disambigText);
        }
        if (STATS.linksSkippedNamespaced > 0) {
            var namespaceText = STATS.linksSkippedNamespaced === 1
                ? "namespaced page"
                : "namespaced pages";
            skipReasons.push(STATS.linksSkippedNamespaced + " " + namespaceText);
        }
        if (STATS.linksSkippedEmptyDescription > 0) {
            var emptyDescText = STATS.linksSkippedEmptyDescription === 1
                ? "page without description"
                : "pages without descriptions";
            skipReasons.push(STATS.linksSkippedEmptyDescription + " " + emptyDescText);
        }
        if (skipReasons.length > 0) {
            var totalSkipped = STATS.linksSkippedRedirects +
                STATS.linksSkippedMissing +
                STATS.linksSkippedDisambiguation +
                STATS.linksSkippedNamespaced +
                STATS.linksSkippedEmptyDescription;
            var skippedText = totalSkipped === 1 ? "link" : "links";
            parts.push("Skipped " +
                totalSkipped +
                " " +
                skippedText +
                ": " +
                skipReasons.join(", "));
        }
        if (parts.length === 0) {
            return "No changes made to See also section";
        }
        return parts.join(" • ");
    }
    function classifyRedirects(redirectInfo) {
        var autoApprovedRedirects = [];
        var autoRejectedRedirects = [];
        var minorDifferenceRedirects = [];
        var needsConfirmationRedirects = [];
        Object.keys(redirectInfo).forEach(function (title) {
            var info = redirectInfo[title];
            if (!info)
                return;
            var isTargetSection = isSectionLink(info.target);
            var hasUsableDescription = false;
            if (isTargetSection) {
                hasUsableDescription = Boolean(info.redirectOwnDescription &&
                    info.redirectOwnDescription.trim() !== "");
            }
            else {
                hasUsableDescription = Boolean((info.redirectOwnDescription &&
                    info.redirectOwnDescription.trim() !== "") ||
                    (info.targetDescription && info.targetDescription.trim() !== ""));
            }
            if (!hasUsableDescription) {
                return;
            }
            if (info.redirectOwnDescription &&
                info.redirectOwnDescription.trim() !== "") {
                autoApprovedRedirects.push(title);
                return;
            }
            if (isTargetSection) {
                return;
            }
            if (isMinorDifferenceRedirect(title, info.target)) {
                minorDifferenceRedirects.push(title);
            }
            else {
                needsConfirmationRedirects.push(title);
            }
        });
        return {
            autoApprovedRedirects: autoApprovedRedirects,
            autoRejectedRedirects: autoRejectedRedirects,
            minorDifferenceRedirects: minorDifferenceRedirects,
            needsConfirmationRedirects: needsConfirmationRedirects
        };
    }
    function promptForRedirectSelection(redirectInfo) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                return [2, new Promise(function (resolve) {
                        var _a = classifyRedirects(redirectInfo), autoApprovedRedirects = _a.autoApprovedRedirects, autoRejectedRedirects = _a.autoRejectedRedirects, minorDifferenceRedirects = _a.minorDifferenceRedirects, needsConfirmationRedirects = _a.needsConfirmationRedirects;
                        if (needsConfirmationRedirects.length === 0) {
                            resolve(__spreadArray(__spreadArray([], autoApprovedRedirects, true), minorDifferenceRedirects, true));
                            return;
                        }
                        var redirectTitles = needsConfirmationRedirects;
                        var $overlay = $("<div>").css({
                            position: "fixed",
                            top: "0",
                            left: "0",
                            width: "100%",
                            height: "100%",
                            "background-color": "rgba(0,0,0,0.5)",
                            "z-index": "9999",
                            display: "flex",
                            "align-items": "center",
                            "justify-content": "center",
                        });
                        var $dialog = $("<div>").css({
                            background: "var(--background-color-base, white)",
                            "border-radius": "var(--border-radius-base, 4px)",
                            "max-width": "600px",
                            "max-height": "80vh",
                            overflow: "auto",
                            padding: "var(--spacing-125, 20px)",
                            "box-shadow": "0 4px 12px rgba(0,0,0,0.3)",
                        });
                        var titleText = "Review redirect links";
                        var messageText = "These redirects need your confirmation for annotation. ";
                        if (autoApprovedRedirects.length > 0 || autoRejectedRedirects.length > 0) {
                            var autoHandledParts = [];
                            if (autoApprovedRedirects.length > 0) {
                                var count = autoApprovedRedirects.length;
                                var redirectText = count === 1 ? "redirect" : "redirects";
                                autoHandledParts.push("".concat(count, " ").concat(redirectText, " with own descriptions automatically selected"));
                            }
                            if (autoRejectedRedirects.length > 0) {
                                var count = autoRejectedRedirects.length;
                                var redirectText = count === 1 ? "redirect" : "redirects";
                                autoHandledParts.push("".concat(count, " ").concat(redirectText, " to article sections automatically skipped"));
                            }
                            messageText += autoHandledParts.join(", ") + ". ";
                        }
                        var $title = $("<h3>").text(titleText).css({
                            "margin-top": "0",
                            "margin-bottom": "var(--spacing-100, 16px)",
                            "line-height": "1.4",
                        });
                        var $message = $("<p>").text(messageText).css({
                            "margin-bottom": "var(--spacing-100, 16px)",
                            "line-height": "1.5",
                        });
                        var $table = $("<table>").css({
                            width: "100%",
                            "border-collapse": "collapse",
                        });
                        var $thead = $("<thead>");
                        var $headerRow = $("<tr>");
                        var $selectAllCell = $("<th>").css({
                            padding: "var(--spacing-75, 12px)",
                            "border-bottom": "1px solid var(--border-color-subtle, #ccc)",
                            "text-align": "center",
                            "vertical-align": "middle",
                            width: "var(--spacing-200, 32px)",
                            cursor: "pointer",
                            "user-select": "none",
                        });
                        var $selectAllCheckbox = $("<input>")
                            .attr("type", "checkbox")
                            .attr("id", "selectAll")
                            .css({
                            width: "var(--spacing-100, 16px)",
                            height: "var(--spacing-100, 16px)",
                            cursor: "pointer",
                        });
                        var $linkTextHeader = $("<th>")
                            .css({
                            padding: "var(--spacing-75, 12px)",
                            "border-bottom": "1px solid var(--border-color-subtle, #ccc)",
                            "text-align": "left",
                            "line-height": "1.4",
                        })
                            .text("Link text");
                        var $descriptionHeader = $("<th>")
                            .css({
                            padding: "var(--spacing-75, 12px)",
                            "border-bottom": "1px solid var(--border-color-subtle, #ccc)",
                            "text-align": "left",
                            "line-height": "1.4",
                        })
                            .text("Description");
                        $selectAllCell.hover(function () {
                            $(this).css("background-color", "var(--background-color-interactive, #f8f9fa)");
                        }, function () {
                            $(this).css("background-color", "");
                        });
                        $selectAllCell.on("click", function (e) {
                            if (e.target !== $selectAllCheckbox[0]) {
                                $selectAllCheckbox
                                    .prop("checked", !$selectAllCheckbox.prop("checked"))
                                    .trigger("change");
                            }
                        });
                        $selectAllCell.append($selectAllCheckbox);
                        $headerRow
                            .append($selectAllCell)
                            .append($linkTextHeader)
                            .append($descriptionHeader);
                        $thead.append($headerRow);
                        var $tbody = $("<tbody>");
                        var checkboxes = [];
                        var _loop_1 = function (i) {
                            var title = redirectTitles[i];
                            if (!title)
                                return "continue";
                            var info = redirectInfo[title];
                            if (!info)
                                return "continue";
                            var $row = $("<tr>");
                            var $checkboxCell = $("<td>").css({
                                padding: "var(--spacing-75, 12px)",
                                "border-bottom": "1px solid var(--border-color-subtle, #eee)",
                                "text-align": "center",
                                "vertical-align": "middle",
                                width: "var(--spacing-200, 32px)",
                                cursor: "pointer",
                                "user-select": "none",
                            });
                            var $checkbox = $("<input>")
                                .attr("type", "checkbox")
                                .attr("value", title)
                                .attr("id", "redirect-" + i)
                                .css({
                                width: "var(--spacing-100, 16px)",
                                height: "var(--spacing-100, 16px)",
                                cursor: "pointer",
                            });
                            var $linkTextCell = $("<td>").css({
                                padding: "var(--spacing-75, 12px)",
                                "border-bottom": "1px solid var(--border-color-subtle, #eee)",
                                "line-height": "1.4",
                            });
                            var displayTextToShow = info.originalDisplayText
                                ? stripWikitextForDisplay(info.originalDisplayText, title)
                                : title;
                            var $linkTextLink = $("<a>")
                                .attr({
                                href: "https://en.wikipedia.org/wiki/" +
                                    encodeURIComponent(title.replace(/ /g, "_")) + "?redirect=no",
                                target: "_blank",
                            })
                                .text(displayTextToShow);
                            $linkTextCell.append($linkTextLink);
                            var $descriptionCell = $("<td>").css({
                                padding: "var(--spacing-75, 12px)",
                                "border-bottom": "1px solid var(--border-color-subtle, #eee)",
                                "line-height": "1.4",
                            });
                            var hasRedirectDesc = info.redirectOwnDescription &&
                                info.redirectOwnDescription.trim() !== "";
                            var hasTargetDesc = info.targetDescription && info.targetDescription.trim() !== "";
                            if (hasRedirectDesc) {
                                var $redirectDescText = $("<div>").text(info.redirectOwnDescription);
                                var $redirectSource = $("<div>")
                                    .css({
                                    "font-size": "0.85em",
                                    color: "var(--color-progressive, #36c)",
                                    "font-weight": "bold",
                                    "margin-bottom": "var(--spacing-50, 8px)",
                                })
                                    .text("From redirect page");
                                $descriptionCell.append($redirectDescText).append($redirectSource);
                                if (hasTargetDesc &&
                                    info.targetDescription !== info.redirectOwnDescription) {
                                    var $targetDescText = $("<div>")
                                        .css({
                                        "margin-top": "var(--spacing-75, 12px)",
                                        "font-size": "0.95em",
                                        color: "var(--color-subtle, #666)",
                                    })
                                        .text(info.targetDescription);
                                    var $targetSource = $("<div>").css({
                                        "font-size": "0.85em",
                                        color: "var(--color-subtle, #666)",
                                        "margin-top": "var(--spacing-25, 4px)",
                                    });
                                    var $targetSourceText = $("<span>").text("From target: ");
                                    var $targetLink = $("<a>")
                                        .attr({
                                        href: "https://en.wikipedia.org/wiki/" +
                                            encodeURIComponent(info.target.replace(/ /g, "_")),
                                        target: "_blank",
                                    })
                                        .text(info.target);
                                    $targetSource.append($targetSourceText).append($targetLink);
                                    $descriptionCell.append($targetDescText).append($targetSource);
                                }
                                else if (hasTargetDesc) {
                                    var $targetSource = $("<div>").css({
                                        "font-size": "0.85em",
                                        color: "var(--color-subtle, #666)",
                                        "margin-top": "var(--spacing-25, 4px)",
                                    });
                                    var $targetSourceText = $("<span>").text("(target: ");
                                    var $targetLink = $("<a>")
                                        .attr({
                                        href: "https://en.wikipedia.org/wiki/" +
                                            encodeURIComponent(info.target.replace(/ /g, "_")),
                                        target: "_blank",
                                    })
                                        .text(info.target);
                                    var $targetSourceEnd = $("<span>").text(")");
                                    $targetSource
                                        .append($targetSourceText)
                                        .append($targetLink)
                                        .append($targetSourceEnd);
                                    $descriptionCell.append($targetSource);
                                }
                            }
                            else if (hasTargetDesc) {
                                var $targetDescText = $("<div>").text(info.targetDescription);
                                var $targetSource = $("<div>").css({
                                    "font-size": "0.85em",
                                    color: "var(--color-subtle, #666)",
                                    "margin-top": "var(--spacing-25, 4px)",
                                });
                                var $targetSourceText = $("<span>").text("From target: ");
                                var $targetLink = $("<a>")
                                    .attr({
                                    href: "https://en.wikipedia.org/wiki/" +
                                        encodeURIComponent(info.target.replace(/ /g, "_")),
                                    target: "_blank",
                                })
                                    .text(info.target);
                                $targetSource.append($targetSourceText).append($targetLink);
                                $descriptionCell.append($targetDescText).append($targetSource);
                            }
                            else {
                                var $noDescText = $("<div>")
                                    .css({
                                    color: "var(--color-subtle, #666)",
                                    "font-style": "italic",
                                })
                                    .text("No description available");
                                $descriptionCell.append($noDescText);
                            }
                            $checkboxCell.hover(function () {
                                $(this).css("background-color", "var(--background-color-interactive, #f8f9fa)");
                            }, function () {
                                $(this).css("background-color", "");
                            });
                            $checkboxCell.on("click", function (e) {
                                if (e.target !== $checkbox[0]) {
                                    $checkbox
                                        .prop("checked", !$checkbox.prop("checked"))
                                        .trigger("change");
                                }
                            });
                            $checkboxCell.append($checkbox);
                            $row.append($checkboxCell).append($linkTextCell).append($descriptionCell);
                            $tbody.append($row);
                            checkboxes.push($checkbox);
                        };
                        for (var i = 0; i < redirectTitles.length; i++) {
                            _loop_1(i);
                        }
                        $table.append($thead).append($tbody);
                        $tbody.find("tr:last-child td").css("border-bottom", "none");
                        var $tableContainer = $("<div>").css({
                            "max-height": "400px",
                            "overflow-y": "auto",
                            border: "1px solid var(--border-color-subtle, #ccc)",
                            "margin-bottom": "var(--spacing-100, 16px)",
                        });
                        $tableContainer.append($table);
                        var $actionContainer = $("<div>").css("text-align", "right");
                        var $formatBtn = $("<button>")
                            .text("Annotate selected")
                            .css({
                            "margin-right": "var(--spacing-75, 12px)",
                            background: "var(--color-progressive, #36c)",
                            color: "var(--color-inverted, #fff)",
                            border: "1px solid var(--color-progressive, #36c)",
                            "border-radius": "4px",
                            padding: "var(--spacing-50, 8px) var(--spacing-100, 16px)",
                            cursor: "pointer",
                        })
                            .hover(function () {
                            if (!$(this).prop("disabled")) {
                                $(this).css("background", "var(--color-progressive--hover, #3056a9)");
                            }
                        }, function () {
                            if (!$(this).prop("disabled")) {
                                $(this).css("background", "var(--color-progressive, #36c)");
                            }
                        });
                        var $skipBtn = $("<button>")
                            .text("Skip all")
                            .css({
                            "margin-right": "var(--spacing-75, 12px)",
                            background: "var(--background-color-interactive, transparent)",
                            border: "1px solid var(--border-color-base, #a2a9b1)",
                            "border-radius": "4px",
                            padding: "var(--spacing-50, 8px) var(--spacing-100, 16px)",
                            cursor: "pointer",
                        })
                            .hover(function () {
                            $(this).css("background", "var(--background-color-interactive--hover, #dadde3)");
                        }, function () {
                            $(this).css("background", "");
                        });
                        var $cancelBtn = $("<button>")
                            .text("Cancel")
                            .css({
                            background: "var(--background-color-interactive, transparent)",
                            border: "1px solid var(--border-color-base, #a2a9b1)",
                            "border-radius": "4px",
                            padding: "var(--spacing-50, 8px) var(--spacing-100, 16px)",
                            cursor: "pointer",
                        })
                            .hover(function () {
                            $(this).css("background", "var(--background-color-interactive--hover, #dadde3)");
                        }, function () {
                            $(this).css("background", "");
                        });
                        function updateSelectAllState() {
                            var checkedCount = 0;
                            for (var j = 0; j < checkboxes.length; j++) {
                                if (checkboxes[j].prop("checked")) {
                                    checkedCount++;
                                }
                            }
                            if (checkedCount === 0) {
                                $selectAllCheckbox.prop("checked", false).prop("indeterminate", false);
                                $formatBtn.prop("disabled", true).css({
                                    background: "var(--background-color-disabled, #c8ccd1)",
                                    "border-color": "var(--border-color-disabled, #c8ccd1)",
                                    color: "var(--color-disabled, #72777d)",
                                    cursor: "not-allowed",
                                });
                            }
                            else if (checkedCount === checkboxes.length) {
                                $selectAllCheckbox.prop("checked", true).prop("indeterminate", false);
                                $formatBtn.prop("disabled", false).css({
                                    background: "var(--color-progressive, #36c)",
                                    "border-color": "var(--color-progressive, #36c)",
                                    color: "var(--color-inverted, #fff)",
                                    cursor: "pointer",
                                });
                            }
                            else {
                                $selectAllCheckbox.prop("checked", false).prop("indeterminate", true);
                                $formatBtn.prop("disabled", false).css({
                                    background: "var(--color-progressive, #36c)",
                                    "border-color": "var(--color-progressive, #36c)",
                                    color: "var(--color-inverted, #fff)",
                                    cursor: "pointer",
                                });
                            }
                        }
                        $selectAllCheckbox.on("change", function () {
                            var isChecked = $selectAllCheckbox.prop("checked");
                            for (var j = 0; j < checkboxes.length; j++) {
                                checkboxes[j].prop("checked", isChecked);
                            }
                            updateSelectAllState();
                        });
                        for (var k = 0; k < checkboxes.length; k++) {
                            checkboxes[k].on("change", updateSelectAllState);
                        }
                        updateSelectAllState();
                        $formatBtn.on("click", function () {
                            var selected = [];
                            for (var k = 0; k < checkboxes.length; k++) {
                                if (checkboxes[k].prop("checked")) {
                                    var value = checkboxes[k].attr("value");
                                    if (value) {
                                        selected.push(value);
                                    }
                                }
                            }
                            var allSelected = __spreadArray(__spreadArray(__spreadArray([], autoApprovedRedirects, true), minorDifferenceRedirects, true), selected, true);
                            $overlay.remove();
                            resolve(allSelected);
                        });
                        $skipBtn.on("click", function () {
                            $overlay.remove();
                            resolve(__spreadArray(__spreadArray([], autoApprovedRedirects, true), minorDifferenceRedirects, true));
                        });
                        $cancelBtn.on("click", function () {
                            $overlay.remove();
                            resolve(null);
                        });
                        $(document).on("keydown.redirectModal", function (e) {
                            if (e.keyCode === 27) {
                                $(document).off("keydown.redirectModal");
                                $overlay.remove();
                                resolve(null);
                            }
                        });
                        $overlay.on("click", function (e) {
                            if (e.target === $overlay[0]) {
                                $overlay.remove();
                                resolve(null);
                            }
                        });
                        $actionContainer.append($formatBtn).append($skipBtn).append($cancelBtn);
                        $dialog
                            .append($title)
                            .append($message)
                            .append($tableContainer)
                            .append($actionContainer);
                        $overlay.append($dialog);
                        $(document.body).append($overlay);
                    })];
            });
        });
    }
    function promptForSorting() {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                return [2, new Promise(function (resolve) {
                        var $overlay = $("<div>").css({
                            position: "fixed",
                            top: "0",
                            left: "0",
                            width: "100%",
                            height: "100%",
                            "background-color": "rgba(0,0,0,0.5)",
                            "z-index": "9999",
                            display: "flex",
                            "align-items": "center",
                            "justify-content": "center",
                        });
                        var $dialog = $("<div>").css({
                            background: "var(--background-color-base, white)",
                            "border-radius": "var(--border-radius-base, 4px)",
                            "max-width": "400px",
                            padding: "var(--spacing-125, 20px)",
                            "box-shadow": "0 4px 12px rgba(0,0,0,0.3)",
                        });
                        var $title = $("<h3>").text("Sort links").css({
                            "margin-top": "0",
                            "margin-bottom": "var(--spacing-100, 16px)",
                            "line-height": "1.4",
                        });
                        var $message = $("<p>")
                            .text("Sort the links alphabetically by their display text?")
                            .css({
                            "margin-bottom": "var(--spacing-125, 20px)",
                            "line-height": "1.5",
                        });
                        var $actionContainer = $("<div>").css("text-align", "right");
                        var $yesBtn = $("<button>")
                            .text("Yes")
                            .css({
                            "margin-right": "var(--spacing-75, 12px)",
                            background: "var(--color-progressive, #36c)",
                            color: "var(--color-inverted, #fff)",
                            border: "1px solid var(--color-progressive, #36c)",
                            "border-radius": "4px",
                            padding: "var(--spacing-50, 8px) var(--spacing-100, 16px)",
                            cursor: "pointer",
                        })
                            .hover(function () {
                            $(this).css("background", "var(--color-progressive--hover, #3056a9)");
                        }, function () {
                            $(this).css("background", "var(--color-progressive, #36c)");
                        });
                        var $noBtn = $("<button>")
                            .text("No")
                            .css({
                            background: "var(--background-color-interactive, transparent)",
                            border: "1px solid var(--border-color-base, #a2a9b1)",
                            "border-radius": "4px",
                            padding: "var(--spacing-50, 8px) var(--spacing-100, 16px)",
                            cursor: "pointer",
                        })
                            .hover(function () {
                            $(this).css("background", "var(--background-color-interactive--hover, #dadde3)");
                        }, function () {
                            $(this).css("background", "");
                        });
                        $yesBtn.on("click", function () {
                            $overlay.remove();
                            resolve(true);
                        });
                        $noBtn.on("click", function () {
                            $overlay.remove();
                            resolve(false);
                        });
                        $(document).on("keydown.sortModal", function (e) {
                            if (e.keyCode === 27) {
                                $(document).off("keydown.sortModal");
                                $overlay.remove();
                                resolve(null);
                            }
                        });
                        $overlay.on("click", function (e) {
                            if (e.target === $overlay[0]) {
                                $overlay.remove();
                                resolve(null);
                            }
                        });
                        $actionContainer.append($yesBtn).append($noBtn);
                        $dialog.append($title).append($message).append($actionContainer);
                        $overlay.append($dialog);
                        $(document.body).append($overlay);
                    })];
            });
        });
    }
    function extractOuterFormatting(content) {
        var quoteMatch = content.match(/^"(\[\[[^\]]+\]\][a-zA-Z]*)"$/);
        if (quoteMatch) {
            return {
                formatting: '"',
                stripped: quoteMatch[1],
            };
        }
        var formatMatch = content.match(/^(''+)(\[\[[^\]]+\]\][a-zA-Z]*)\1$/);
        if (formatMatch) {
            return {
                formatting: formatMatch[1],
                stripped: formatMatch[2],
            };
        }
        var quoteLinkOnlyMatch = content.match(/^"(\[\[[^\]]+\]\])"$/);
        if (quoteLinkOnlyMatch) {
            return {
                formatting: '"',
                stripped: quoteLinkOnlyMatch[1],
            };
        }
        var formatLinkOnlyMatch = content.match(/^(''+)(\[\[[^\]]+\]\])\1$/);
        if (formatLinkOnlyMatch) {
            return {
                formatting: formatLinkOnlyMatch[1],
                stripped: formatLinkOnlyMatch[2],
            };
        }
        var quoteTextMatch = content.match(/^"(.+)"$/);
        if (quoteTextMatch) {
            return {
                formatting: '"',
                stripped: quoteTextMatch[1],
            };
        }
        var formatTextMatch = content.match(/^(''+)(.+)\1$/);
        if (formatTextMatch) {
            return {
                formatting: formatTextMatch[1],
                stripped: formatTextMatch[2],
            };
        }
        return {
            formatting: "",
            stripped: content,
        };
    }
    function handlePipeTrick(pageTitle, formatting) {
        var displayText = pageTitle.replace(/\s*\([^)]+\)$/, "");
        return formatting ? formatting + displayText + formatting : displayText;
    }
    function shouldSkipLine(line) {
        var trimmedLine = line.trim();
        if (trimmedLine === "") {
            return true;
        }
        if (trimmedLine.substring(0, 2) === "==") {
            return true;
        }
        if (trimmedLine.substring(0, 2) === "{{" &&
            trimmedLine.substring(trimmedLine.length - 2) === "}}") {
            return true;
        }
        return false;
    }
    function createBatches(items, batchSize) {
        var batches = [];
        for (var i = 0; i < items.length; i += batchSize) {
            batches.push(items.slice(i, i + batchSize));
        }
        return batches;
    }
    function createEmptySkipInfo() {
        return {
            redirectPages: {},
            namespacedPages: {},
            missingPages: {},
            emptyDescriptionPages: {},
            disambiguationDescPages: {},
            redirectTargets: {},
        };
    }
    function analyzeLine(line) {
        var _a;
        if (shouldSkipLine(line)) {
            return {
                isProcessable: false,
                isAnnotatable: false,
                lineType: "unprocessable",
            };
        }
        var listMatch = line.match(REGEX_PATTERNS.LIST_ITEM);
        if (!listMatch) {
            return {
                isProcessable: false,
                isAnnotatable: false,
                lineType: "unprocessable",
            };
        }
        var content = ((_a = listMatch[2]) === null || _a === void 0 ? void 0 : _a.trim()) || '';
        var templateMatch = line.match(REGEX_PATTERNS.TEMPLATE_WITH_DESCRIPTION);
        if (templateMatch) {
            return {
                isProcessable: true,
                isAnnotatable: false,
                lineType: "template-with-desc",
                listMatch: listMatch,
                content: content,
                templateMatch: templateMatch,
            };
        }
        var descMatch = content.match(REGEX_PATTERNS.LINK_WITH_DESCRIPTION) || undefined;
        if (descMatch && (descMatch[5] || descMatch[6])) {
            return {
                isProcessable: true,
                isAnnotatable: false,
                lineType: "manual-desc",
                listMatch: listMatch,
                content: content,
                descMatch: descMatch,
            };
        }
        var quoteMatch = content.match(/^"(\[\[[^\]]+\]\][a-zA-Z]*)"$/) ||
            content.match(/^"(\[\[[^\]]+\]\])"$/);
        if (quoteMatch) {
            return {
                isProcessable: true,
                isAnnotatable: true,
                lineType: "quoted-link",
                listMatch: listMatch,
                content: content,
                descMatch: descMatch,
            };
        }
        return {
            isProcessable: true,
            isAnnotatable: true,
            lineType: "annotatable",
            listMatch: listMatch,
            content: content,
            descMatch: descMatch,
        };
    }
    function shouldSkipColonPrefixedLink(linkContent) {
        return linkContent.charAt(0) === ":";
    }
    function isMinorDifferenceRedirect(redirectTitle, targetTitle) {
        var normalizeTitle = function (title) {
            return title.toLowerCase().replace(/[\s\-\u2000-\u206F\u2E00-\u2E7F\u3000-\u303F\u2190-\u21FF\u2460-\u24FF\u2500-\u257F\u2600-\u26FF\u2700-\u27BF\u2980-\u29FF\u2B00-\u2BFF]/g, "").replace(/[\u2E80-\u2EFF\u3040-\u309F\u30A0-\u30FF\u3100-\u312F\u3130-\u318F\u3190-\u319F\u31A0-\u31BF\u3200-\u32FF\u3300-\u33FF]/g, "").replace(/[\uFE00-\uFE0F\uFE30-\uFE4F\uFE50-\uFE6F\uFF00-\uFFEF]/g, "");
        };
        var normalizedRedirect = normalizeTitle(redirectTitle);
        var normalizedTarget = normalizeTitle(targetTitle);
        return normalizedRedirect === normalizedTarget;
    }
    function detectPreferredTemplate$1(sectionContent, templateConfig) {
        var templateCounts = {};
        Object.keys(templateConfig.templates).forEach(function (key) {
            templateCounts[key] = 0;
        });
        Object.keys(templateConfig.templates).forEach(function (key) {
            var pattern = new RegExp("\\{\\{".concat(key.replace(/[.*+?^${}()|[\\]/g, '\\$&'), "\\|"), 'gi');
            var matches = sectionContent.match(pattern);
            if (matches) {
                templateCounts[key] = matches.length;
            }
        });
        var maxCount = Math.max.apply(Math, Object.values(templateCounts));
        if (maxCount === 0) {
            return templateConfig.defaultTemplate;
        }
        for (var _i = 0, _a = Object.keys(templateConfig.templates); _i < _a.length; _i++) {
            var key = _a[_i];
            if (templateCounts[key] === maxCount) {
                return templateConfig.templates[key] || templateConfig.defaultTemplate;
            }
        }
        return templateConfig.defaultTemplate;
    }
    function isSectionLink(pageTitle) {
        var hashIndex = pageTitle.indexOf("#");
        if (hashIndex === -1) {
            return false;
        }
        if (hashIndex === pageTitle.length - 1) {
            return false;
        }
        if (hashIndex === 0) {
            return true;
        }
        return true;
    }
    function syncFromWikEd() {
        if (typeof window.wikEd !== "undefined" &&
            typeof window.wikEd.useWikEd !== "undefined") {
            if (window.wikEd.useWikEd == true) {
                wikEd.UpdateTextarea();
            }
        }
    }
    function syncToWikEd() {
        if (typeof window.wikEd !== "undefined" &&
            typeof window.wikEd.useWikEd !== "undefined") {
            if (window.wikEd.useWikEd == true) {
                wikEd.UpdateFrame();
            }
        }
    }
    function getTextareaValue(textarea) {
        syncFromWikEd();
        return textarea.value;
    }
    function setTextareaValue(textarea, value) {
        textarea.value = value;
        syncToWikEd();
    }
    function isValidAbbreviation(text) {
        if (!text)
            return false;
        if (text === "disambiguation")
            return false;
        if (/^(19|20)\d{2}$/.test(text))
            return false;
        return REGEX_PATTERNS.VALID_ABBREVIATION.test(text);
    }
    function extractAbbreviation(text) {
        var match = text.match(/^\s*\(([^)]+)\)(.*)/);
        if (!match)
            return { abbreviation: null, remainder: text };
        var potentialAbbr = match[1];
        if (potentialAbbr && isValidAbbreviation(potentialAbbr)) {
            return { abbreviation: potentialAbbr, remainder: match[2] || '' };
        }
        return { abbreviation: null, remainder: text };
    }
    function processTrailingContent(text) {
        var abbrevResult = extractAbbreviation(text);
        if (abbrevResult.abbreviation) {
            var remainder = abbrevResult.remainder.trim();
            if (remainder.match(/^[,–—:-]/)) {
                var description = remainder.replace(/^[,–—:-]\s*/, "");
                return {
                    abbreviation: abbrevResult.abbreviation,
                    description: description || null,
                };
            }
            else if (remainder) {
                return { abbreviation: null, description: null };
            }
            else {
                return { abbreviation: abbrevResult.abbreviation, description: null };
            }
        }
        else {
            if (text.trim().match(/^[,–—:-]/)) {
                var description = text.replace(/^[,–—:-]\s*/, "");
                return { abbreviation: null, description: description || null };
            }
            else {
                return { abbreviation: null, description: null };
            }
        }
    }
    function stripWikitextForDisplay(text, fallbackTitle) {
        if (!text || typeof text !== 'string') {
            return fallbackTitle;
        }
        var cleanText = text.trim();
        if (!cleanText) {
            return fallbackTitle;
        }
        var previousText = '';
        while (cleanText !== previousText) {
            previousText = cleanText;
            var formatInfo = extractOuterFormatting(cleanText);
            cleanText = formatInfo.stripped;
        }
        var linkMatch = cleanText.match(/^\\\[\[([^\]|]+)(?:\|([^\\]*))?\\\]\]$/);
        if (linkMatch) {
            var displayText = linkMatch[2] ? linkMatch[2].trim() : '';
            cleanText = displayText || linkMatch[1].trim();
        }
        cleanText = cleanText
            .replace(/'{2,5}/g, '')
            .replace(/\{\{[^}]+\}\\}/g, '')
            .replace(/\\\[\[([^\]|]+)(?:\|([^\\]*))?\\\]\]/g, function (_, title, displayText) {
            var text = displayText ? displayText.trim() : title.trim();
            return text || title.trim();
        })
            .replace(/^\\\[\[?/, '')
            .replace(/\\]\\]?$/, '')
            .replace(/\s+/g, ' ')
            .trim();
        if (!cleanText) {
            return fallbackTitle;
        }
        return cleanText;
    }
    function collectMissingDescriptions(skipInfo, sectionContent) {
        var missingDescriptions = {
            redirectsToSectionsMissingDesc: [],
            redirectsToTopLevelMissingDesc: [],
            articlesMissingDesc: [],
        };
        for (var pageTitle in skipInfo.emptyDescriptionPages) {
            if (!skipInfo.emptyDescriptionPages[pageTitle])
                continue;
            var lines = sectionContent.split("\n");
            var appearsInRelevantLines = false;
            for (var _i = 0, lines_1 = lines; _i < lines_1.length; _i++) {
                var line = lines_1[_i];
                var analysis = analyzeLine(line);
                var isRelevantLine = analysis.isAnnotatable || analysis.lineType === 'template-with-desc';
                if (isRelevantLine && line.includes(pageTitle)) {
                    appearsInRelevantLines = true;
                    break;
                }
            }
            if (!appearsInRelevantLines) {
                continue;
            }
            var isRedirect = skipInfo.redirectPages && skipInfo.redirectPages[pageTitle];
            if (isRedirect) {
                var redirectInfo = skipInfo.redirectTargets && skipInfo.redirectTargets[pageTitle];
                if (!redirectInfo) {
                    continue;
                }
            }
            else {
                var skipReason = shouldSkipLinkForReason(pageTitle, skipInfo, []);
                if (skipReason && skipReason !== "empty-description") {
                    continue;
                }
            }
            if (isRedirect) {
                var redirectInfo = skipInfo.redirectTargets && skipInfo.redirectTargets[pageTitle];
                if (redirectInfo) {
                    if (isDisambiguationPage(redirectInfo.target) ||
                        (skipInfo.disambiguationDescPages && skipInfo.disambiguationDescPages[redirectInfo.target])) {
                        continue;
                    }
                    if (redirectInfo.isSection) {
                        if (!redirectInfo.redirectOwnDescription ||
                            redirectInfo.redirectOwnDescription.trim() === "") {
                            missingDescriptions.redirectsToSectionsMissingDesc.push({
                                pageTitle: pageTitle,
                                target: redirectInfo.target,
                                reason: "redirect-missing-description",
                            });
                        }
                    }
                    else {
                        var redirectMissing = !redirectInfo.redirectOwnDescription ||
                            redirectInfo.redirectOwnDescription.trim() === "";
                        var targetMissing = !redirectInfo.targetDescription ||
                            redirectInfo.targetDescription.trim() === "";
                        if (redirectMissing || targetMissing) {
                            var reason = redirectMissing && targetMissing
                                ? "both-redirect-and-target-missing-description"
                                : redirectMissing
                                    ? "redirect-missing-description"
                                    : "target-missing-description";
                            missingDescriptions.redirectsToTopLevelMissingDesc.push({
                                pageTitle: pageTitle,
                                target: redirectInfo.target,
                                reason: reason,
                            });
                        }
                    }
                }
            }
            else {
                missingDescriptions.articlesMissingDesc.push({
                    pageTitle: pageTitle,
                    reason: "article-missing-description",
                });
            }
        }
        return missingDescriptions;
    }
    function promptForMissingDescriptions(missingDescriptions) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                return [2, new Promise(function (resolve) {
                        var totalMissing = missingDescriptions.redirectsToSectionsMissingDesc.length +
                            missingDescriptions.redirectsToTopLevelMissingDesc.length +
                            missingDescriptions.articlesMissingDesc.length;
                        if (totalMissing === 0) {
                            resolve();
                            return;
                        }
                        var $overlay = $("<div>").css({
                            position: "fixed",
                            top: "0",
                            left: "0",
                            width: "100%",
                            height: "100%",
                            "background-color": "var(--background-color-backdrop, rgba(0,0,0,0.5))",
                            "z-index": "var(--z-index-overlay, 9999)",
                            display: "flex",
                            "align-items": "center",
                            "justify-content": "center",
                        });
                        var $dialog = $("<div>").css({
                            background: "var(--background-color-base, #fff)",
                            "border-radius": "var(--border-radius-sharp, 4px)",
                            "max-width": "600px",
                            "max-height": "80vh",
                            padding: "var(--spacing-150, 24px)",
                            "box-shadow": "var(--box-shadow-drop-large, 0 4px 16px rgba(0,0,0,0.2))",
                            "overflow-y": "auto",
                            position: "relative",
                        });
                        var $title = $("<h3>").text("Links missing descriptions").css({
                            "margin-top": "0",
                            "margin-bottom": "var(--spacing-100, 16px)",
                            "line-height": "var(--line-height-base, 1.4)",
                            "font-size": "var(--font-size-x-large, 1.25em)",
                            "font-weight": "var(--font-weight-bold, 700)",
                            color: "var(--color-base, #222)",
                        });
                        var $intro = $("<p>")
                            .text("The following links are missing descriptions. Consider adding descriptions now so they can be annotated:")
                            .css({
                            "line-height": "var(--line-height-medium, 1.5)",
                            color: "var(--color-base, #222)",
                            "font-size": "var(--font-size-medium, 1em)",
                        });
                        var $content = $("<div>");
                        function createSection(title, items, explanation, boldBothLinks, isLastSection) {
                            if (boldBothLinks === void 0) { boldBothLinks = false; }
                            if (isLastSection === void 0) { isLastSection = false; }
                            if (items.length === 0)
                                return;
                            var $section = $("<div>").css(__assign({ "padding-top": "var(--spacing-100, 16px)", "padding-bottom": "var(--spacing-50, 8px)" }, (!isLastSection && {
                                "border-bottom": "var(--border-width-base, 1px) solid var(--border-color-muted, #c8ccd1)",
                            })));
                            var $sectionTitle = $("<h4>").text(title).css({
                                "margin-top": "0",
                                "margin-bottom": "var(--spacing-75, 12px)",
                                color: "var(--color-base, #222)",
                                "font-size": "var(--font-size-medium, 1.1em)",
                                "font-weight": "var(--font-weight-semibold, 600)",
                            });
                            var $explanation = $("<p>").text(explanation).css({
                                "margin-bottom": "var(--spacing-75, 12px)",
                                "font-size": "var(--font-size-small, 0.9em)",
                                color: "var(--color-subtle, #54595d)",
                                "line-height": "var(--line-height-medium, 1.4)",
                            });
                            var $list = $("<ul>").css({
                                "margin-bottom": "var(--spacing-75, 12px)",
                                "padding-left": "var(--spacing-125, 20px)",
                            });
                            items.forEach(function (item) {
                                var $listItem = $("<li>").css({
                                    "margin-bottom": "var(--spacing-50, 8px)",
                                    "line-height": "1.4",
                                });
                                var $linkContainer = $("<div>");
                                var isRedirect = item.target !== undefined;
                                var redirectParam = isRedirect ? "?redirect=no" : "";
                                var $pageLink = $("<a>")
                                    .attr({
                                    href: "https://en.wikipedia.org/wiki/" +
                                        encodeURIComponent(item.pageTitle.replace(/ /g, "_")) +
                                        redirectParam,
                                    target: "_blank",
                                })
                                    .text(item.pageTitle)
                                    .css({
                                    "font-weight": "bold",
                                    "text-decoration": "none",
                                    color: "var(--color-progressive, #36c)",
                                })
                                    .hover(function () {
                                    $(this).css("text-decoration", "underline");
                                }, function () {
                                    $(this).css("text-decoration", "none");
                                });
                                $linkContainer.append($pageLink);
                                if (item.target) {
                                    var $targetInfo = $("<span>").text(" → ").css({
                                        color: "var(--color-subtle, #666)",
                                        "margin-left": "var(--spacing-25, 4px)",
                                        "margin-right": "var(--spacing-25, 4px)",
                                    });
                                    var $targetLink = $("<a>")
                                        .attr({
                                        href: "https://en.wikipedia.org/wiki/" +
                                            encodeURIComponent(item.target.replace(/ /g, "_")),
                                        target: "_blank",
                                    })
                                        .text(item.target)
                                        .css(__assign({ "text-decoration": "none", color: "var(--color-progressive, #36c)" }, (boldBothLinks && { "font-weight": "bold" })))
                                        .hover(function () {
                                        $(this).css("text-decoration", "underline");
                                    }, function () {
                                        $(this).css("text-decoration", "none");
                                    });
                                    $linkContainer.append($targetInfo).append($targetLink);
                                }
                                $listItem.append($linkContainer);
                                $list.append($listItem);
                            });
                            $section.append($sectionTitle).append($explanation).append($list);
                            $content.append($section);
                        }
                        var sections = [
                            {
                                title: "Articles",
                                items: missingDescriptions.articlesMissingDesc,
                                explanation: "These articles need short descriptions to be annotated.",
                                boldBothLinks: false
                            },
                            {
                                title: "Redirects to articles",
                                items: missingDescriptions.redirectsToTopLevelMissingDesc,
                                explanation: "Either the redirect page or its target article needs a description to be annotated.",
                                boldBothLinks: true
                            },
                            {
                                title: "Redirects to sections",
                                items: missingDescriptions.redirectsToSectionsMissingDesc,
                                explanation: "These redirect pages need their own descriptions to be annotated.",
                                boldBothLinks: false
                            }
                        ];
                        var nonEmptySections = sections.filter(function (section) { return section.items.length > 0; });
                        nonEmptySections.forEach(function (section, index) {
                            var isLast = index === nonEmptySections.length - 1;
                            createSection(section.title, section.items, section.explanation, section.boldBothLinks, isLast);
                        });
                        var $actionContainer = $("<div>").css({
                            "text-align": "right",
                            "border-top": "var(--border-width-base, 1px) solid var(--border-color-subtle, #eaecf0)",
                            "padding-top": "var(--spacing-100, 16px)",
                        });
                        var $okBtn = $("<button>")
                            .text("Continue")
                            .css({
                            background: "var(--background-color-progressive, #36c)",
                            color: "var(--color-inverted, #fff)",
                            border: "var(--border-width-base, 1px) solid var(--border-color-progressive, #36c)",
                            "border-radius": "var(--border-radius-base, 4px)",
                            padding: "var(--spacing-50, 8px) var(--spacing-100, 16px)",
                            cursor: "pointer",
                            "min-width": "80px",
                            "font-size": "var(--font-size-medium, 1em)",
                            "font-weight": "var(--font-weight-medium, 500)",
                        })
                            .hover(function () {
                            $(this).css("background", "var(--color-progressive--hover, #3056a9)");
                        }, function () {
                            $(this).css("background", "var(--color-progressive, #36c)");
                        });
                        $okBtn.on("click", function () {
                            $overlay.remove();
                            resolve();
                        });
                        $(document).on("keydown.missingDescModal", function (e) {
                            if (e.keyCode === 27) {
                                $(document).off("keydown.missingDescModal");
                                $overlay.remove();
                                resolve();
                            }
                        });
                        $overlay.on("click", function (e) {
                            if (e.target === $overlay[0]) {
                                $overlay.remove();
                                resolve();
                            }
                        });
                        $actionContainer.append($okBtn);
                        $dialog
                            .append($title)
                            .append($intro)
                            .append($content)
                            .append($actionContainer);
                        $overlay.append($dialog);
                        $(document.body).append($overlay);
                    })];
            });
        });
    }

    function extractPageTitleFromAnnotatedLinkTemplate(line) {
        var match = line.match(/\{\{(?:anl|anli|Annotated link)\|([^|}]+)/i);
        return match ? match[1].trim() : null;
    }
    function extractUniquePageTitles(sectionContent) {
        var _a;
        var pageTitles = [];
        var uniqueTitles = {};
        var lines = sectionContent.split('\n');
        for (var _i = 0, lines_1 = lines; _i < lines_1.length; _i++) {
            var line = lines_1[_i];
            var analysis = analyzeLine(line);
            if (analysis.isAnnotatable) {
                var match = void 0;
                var regex = new RegExp(REGEX_PATTERNS.WIKILINK);
                while ((match = regex.exec(line)) !== null) {
                    var title = ((_a = match[1]) === null || _a === void 0 ? void 0 : _a.trim()) || '';
                    if (!uniqueTitles[title] && title.indexOf("#") === -1) {
                        uniqueTitles[title] = true;
                        pageTitles.push(title);
                    }
                }
            }
            if (analysis.lineType === 'template-with-desc') {
                var templatePageTitle = extractPageTitleFromAnnotatedLinkTemplate(line);
                if (templatePageTitle && !uniqueTitles[templatePageTitle] && templatePageTitle.indexOf("#") === -1) {
                    uniqueTitles[templatePageTitle] = true;
                    pageTitles.push(templatePageTitle);
                }
            }
        }
        return pageTitles;
    }
    function extractLinksWithDisplayText(sectionContent) {
        var _a, _b;
        var linkMap = {};
        var lines = sectionContent.split('\n');
        for (var _i = 0, lines_2 = lines; _i < lines_2.length; _i++) {
            var line = lines_2[_i];
            var analysis = analyzeLine(line);
            if (!analysis.isAnnotatable) {
                continue;
            }
            var match = void 0;
            var linkRegex = /\[\[([^\]|]+)(?:\|([^\]]+))?\]\]/g;
            while ((match = linkRegex.exec(line)) !== null) {
                var title = ((_a = match[1]) === null || _a === void 0 ? void 0 : _a.trim()) || '';
                var displayText = match[2] ? ((_b = match[2]) === null || _b === void 0 ? void 0 : _b.trim()) || '' : title;
                if (title.indexOf("#") === -1) {
                    if (!linkMap[title]) {
                        linkMap[title] = displayText;
                    }
                }
            }
        }
        return linkMap;
    }

    function categorizePageInfo(page, skipInfo) {
        if (page.redirect) {
            skipInfo.redirectPages[page.title] = true;
        }
        if (page.ns !== undefined && page.ns !== 0) {
            skipInfo.namespacedPages[page.title] = true;
        }
        if (page.missing) {
            skipInfo.missingPages[page.title] = true;
        }
        var shortDesc = page.pageprops && page.pageprops["wikibase-shortdesc"];
        if (!shortDesc || shortDesc === "") {
            skipInfo.emptyDescriptionPages[page.title] = true;
        }
        else if (isDisambiguationDescription(shortDesc)) {
            skipInfo.disambiguationDescPages[page.title] = true;
        }
    }
    function checkLinksToSkip(sectionContent) {
        return __awaiter(this, void 0, void 0, function () {
            var pageTitles, linkDisplayTextMap, batches, skipInfo, batchPromises, error_1;
            var _this = this;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        pageTitles = extractUniquePageTitles(sectionContent);
                        linkDisplayTextMap = extractLinksWithDisplayText(sectionContent);
                        if (pageTitles.length === 0) {
                            return [2, createEmptySkipInfo()];
                        }
                        batches = createBatches(pageTitles, CONFIG.API_BATCH_SIZE);
                        skipInfo = {
                            redirectPages: {},
                            namespacedPages: {},
                            missingPages: {},
                            emptyDescriptionPages: {},
                            disambiguationDescPages: {},
                            redirectTargets: {},
                        };
                        _a.label = 1;
                    case 1:
                        _a.trys.push([1, 3, , 4]);
                        batchPromises = batches.map(function (batch) { return __awaiter(_this, void 0, void 0, function () {
                            var _a, firstApiData, secondApiData, i, page, _loop_1, i;
                            var _b, _c, _d, _e;
                            return __generator(this, function (_f) {
                                switch (_f.label) {
                                    case 0: return [4, Promise.all([
                                            new mw.Api().get({
                                                action: "query",
                                                prop: "info|pageprops",
                                                ppprop: "wikibase-shortdesc",
                                                titles: batch.join("|"),
                                                formatversion: 2,
                                            }),
                                            new mw.Api().get({
                                                action: "query",
                                                prop: "info|pageprops",
                                                ppprop: "wikibase-shortdesc",
                                                titles: batch.join("|"),
                                                redirects: 1,
                                                formatversion: 2,
                                            })
                                        ])];
                                    case 1:
                                        _a = _f.sent(), firstApiData = _a[0], secondApiData = _a[1];
                                        if (firstApiData.query && firstApiData.query.pages) {
                                            for (i = 0; i < firstApiData.query.pages.length; i++) {
                                                page = firstApiData.query.pages[i];
                                                if (page) {
                                                    categorizePageInfo(page, skipInfo);
                                                }
                                            }
                                        }
                                        if (secondApiData.query && secondApiData.query.redirects) {
                                            _loop_1 = function (i) {
                                                var redirect_1 = secondApiData.query.redirects[i];
                                                var fromTitle_1 = redirect_1.from;
                                                var toTitle_1 = redirect_1.tofragment && redirect_1.tofragment.trim() !== ""
                                                    ? redirect_1.to + "#" + redirect_1.tofragment
                                                    : redirect_1.to;
                                                skipInfo.redirectPages[fromTitle_1] = true;
                                                var redirectPage = (_c = (_b = firstApiData.query) === null || _b === void 0 ? void 0 : _b.pages) === null || _c === void 0 ? void 0 : _c.find(function (p) { return p.title === fromTitle_1; });
                                                var redirectOwnDescription = redirectPage && redirectPage.pageprops && redirectPage.pageprops["wikibase-shortdesc"]
                                                    ? redirectPage.pageprops["wikibase-shortdesc"]
                                                    : "";
                                                var targetPage = (_e = (_d = secondApiData.query) === null || _d === void 0 ? void 0 : _d.pages) === null || _e === void 0 ? void 0 : _e.find(function (p) { return p.title === toTitle_1; });
                                                var targetDescription = targetPage && targetPage.pageprops && targetPage.pageprops["wikibase-shortdesc"]
                                                    ? targetPage.pageprops["wikibase-shortdesc"]
                                                    : "";
                                                var targetIsDisambiguation = isDisambiguationPage(toTitle_1);
                                                var targetHasDisambiguationDescription = isDisambiguationDescription(targetDescription);
                                                if (targetHasDisambiguationDescription || targetIsDisambiguation) {
                                                    skipInfo.disambiguationDescPages[toTitle_1] = true;
                                                }
                                                if (targetHasDisambiguationDescription || targetIsDisambiguation) {
                                                    targetDescription = "";
                                                }
                                                var preferredDescription = "";
                                                var descriptionSource = 'none';
                                                var isSection = isSectionLink(toTitle_1);
                                                if (redirectOwnDescription && redirectOwnDescription.trim() !== '') {
                                                    preferredDescription = redirectOwnDescription;
                                                    descriptionSource = 'redirect';
                                                }
                                                else if (!isSection && targetDescription && targetDescription.trim() !== '') {
                                                    preferredDescription = targetDescription;
                                                    descriptionSource = 'target';
                                                }
                                                if (preferredDescription.trim() !== '') {
                                                    delete skipInfo.emptyDescriptionPages[fromTitle_1];
                                                }
                                                var originalDisplayText = linkDisplayTextMap[fromTitle_1];
                                                var hasUsableDescription = preferredDescription.trim() !== '';
                                                skipInfo.redirectTargets[fromTitle_1] = {
                                                    target: toTitle_1,
                                                    description: preferredDescription,
                                                    redirectOwnDescription: redirectOwnDescription,
                                                    targetDescription: targetDescription,
                                                    preferredDescription: preferredDescription,
                                                    descriptionSource: descriptionSource,
                                                    originalDisplayText: originalDisplayText !== fromTitle_1 ? originalDisplayText : undefined,
                                                    isSection: isSection,
                                                    shouldAutoSelect: descriptionSource === 'redirect' && redirectOwnDescription.trim() !== '',
                                                    hasUsableDescription: hasUsableDescription
                                                };
                                            };
                                            for (i = 0; i < secondApiData.query.redirects.length; i++) {
                                                _loop_1(i);
                                            }
                                        }
                                        return [2];
                                }
                            });
                        }); });
                        return [4, Promise.all(batchPromises)];
                    case 2:
                        _a.sent();
                        return [2, skipInfo];
                    case 3:
                        error_1 = _a.sent();
                        console.error("Failed to check links to skip:", error_1);
                        return [2, createEmptySkipInfo()];
                    case 4: return [2];
                }
            });
        });
    }
    function parseApiResponseForDisplayText(parsed, indices, displayTextMap) {
        var _a, _b, _c, _d;
        var tempDiv = document.createElement("div");
        tempDiv.innerHTML = parsed;
        var listElements = tempDiv.querySelectorAll("li");
        for (var j = 0; j < listElements.length && j < indices.length; j++) {
            var itemText = ((_a = listElements[j]) === null || _a === void 0 ? void 0 : _a.textContent) || ((_b = listElements[j]) === null || _b === void 0 ? void 0 : _b.innerText) || "";
            var clonedElement = (_c = listElements[j]) === null || _c === void 0 ? void 0 : _c.cloneNode(true);
            var nestedLists = clonedElement === null || clonedElement === void 0 ? void 0 : clonedElement.querySelectorAll("ul, ol");
            if (nestedLists) {
                for (var n = 0; n < nestedLists.length; n++) {
                    (_d = nestedLists[n]) === null || _d === void 0 ? void 0 : _d.remove();
                }
            }
            itemText = (clonedElement === null || clonedElement === void 0 ? void 0 : clonedElement.textContent) || (clonedElement === null || clonedElement === void 0 ? void 0 : clonedElement.innerText) || "";
            itemText = itemText.replace(/\s+/g, " ").trim();
            var originalLineIndex = indices[j];
            displayTextMap[originalLineIndex] = itemText;
        }
    }
    function checkForShortDescriptionNone(pageTitles) {
        return __awaiter(this, void 0, void 0, function () {
            var batches, results, batchPromises, error_2;
            var _this = this;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (pageTitles.length === 0) {
                            return [2, {}];
                        }
                        batches = createBatches(pageTitles, CONFIG.API_BATCH_SIZE);
                        results = {};
                        _a.label = 1;
                    case 1:
                        _a.trys.push([1, 3, , 4]);
                        batchPromises = batches.map(function (batch) { return __awaiter(_this, void 0, void 0, function () {
                            var apiData, i, page, title, revision, wikitext, hasShortDescNone;
                            return __generator(this, function (_a) {
                                switch (_a.label) {
                                    case 0: return [4, new mw.Api().get({
                                            action: "query",
                                            prop: "revisions",
                                            titles: batch.join("|"),
                                            rvslots: "main",
                                            rvprop: "content",
                                            formatversion: 2,
                                        })];
                                    case 1:
                                        apiData = _a.sent();
                                        if (apiData.query && apiData.query.pages) {
                                            for (i = 0; i < apiData.query.pages.length; i++) {
                                                page = apiData.query.pages[i];
                                                title = page.title;
                                                if (page.revisions && page.revisions.length > 0) {
                                                    revision = page.revisions[0];
                                                    if (revision) {
                                                        wikitext = revision.slots.main.content;
                                                        hasShortDescNone = /\{\{\s*Short\s+description\s*\|\s*none\s*\}\}/i.test(wikitext);
                                                        results[title] = hasShortDescNone;
                                                    }
                                                    else {
                                                        results[title] = false;
                                                    }
                                                }
                                                else {
                                                    results[title] = false;
                                                }
                                            }
                                        }
                                        return [2];
                                }
                            });
                        }); });
                        return [4, Promise.all(batchPromises)];
                    case 2:
                        _a.sent();
                        return [2, results];
                    case 3:
                        error_2 = _a.sent();
                        console.error("Failed to check for {{Short description|none}}:", error_2);
                        return [2, {}];
                    case 4: return [2];
                }
            });
        });
    }

    var ARTICLE_TEMPLATE_CONFIG = {
        templates: {
            "anl": "anl",
            "annotated link": "Annotated link",
            "anli": "anli"
        },
        defaultTemplate: "anl"
    };
    var SECTION_TEMPLATE_CONFIG = {
        templates: {
            "slink": "slink",
            "seclink": "seclink",
            "section link": "Section link"
        },
        defaultTemplate: "slink"
    };
    function detectPreferredTemplate(sectionContent) {
        return detectPreferredTemplate$1(sectionContent, ARTICLE_TEMPLATE_CONFIG);
    }
    function detectPreferredSectionTemplate(sectionContent) {
        return detectPreferredTemplate$1(sectionContent, SECTION_TEMPLATE_CONFIG);
    }
    function shouldSkipLink(pageTitle, skipInfo, selectedRedirects) {
        if (selectedRedirects === void 0) { selectedRedirects = []; }
        var skipReason = shouldSkipLinkForReason(pageTitle, skipInfo, selectedRedirects);
        if (skipReason) {
            switch (skipReason) {
                case 'disambiguation':
                    STATS.linksSkippedDisambiguation++;
                    break;
                case 'redirect-not-selected':
                    STATS.linksSkippedRedirects++;
                    break;
                case 'namespaced':
                    STATS.linksSkippedNamespaced++;
                    break;
                case 'missing':
                    STATS.linksSkippedMissing++;
                    break;
                case 'empty-description':
                    STATS.linksSkippedEmptyDescription++;
                    break;
            }
            return true;
        }
        return false;
    }
    function createTemplateCall(pageTitle, displayText, templateName, isQuoted, abbreviation, skipInfo, _selectedRedirects) {
        if (isQuoted === void 0) { isQuoted = false; }
        if (abbreviation === void 0) { abbreviation = null; }
        var template = "{{" + templateName + "|" + pageTitle;
        if (displayText) {
            template += "|" + displayText;
        }
        if (isQuoted) {
            template += "|quote=yes";
        }
        if (abbreviation) {
            template += "|abbr=" + abbreviation;
        }
        STATS.regularLinksFormatted++;
        return template + "}}";
    }
    function createSlinkTemplateCall(pageTitle, displayText, templateName) {
        var template = "{{" + templateName + "|" + pageTitle;
        if (displayText) {
            template += "|" + displayText;
        }
        STATS.sectionLinksFormatted++;
        return template + "}}";
    }
    function createSimpleFormattedLink(pageTitle, outerFormatting, templateName, sectionTemplateName, skipInfo, selectedRedirects, abbreviation) {
        if (abbreviation === void 0) { abbreviation = null; }
        var isQuoted = outerFormatting === '"';
        if (isSectionLink(pageTitle)) {
            if (isQuoted) {
                return null;
            }
            else if (outerFormatting) {
                var displayWithFormatting = outerFormatting + pageTitle + outerFormatting;
                return createSlinkTemplateCall(pageTitle, displayWithFormatting, sectionTemplateName);
            }
            else {
                return createSlinkTemplateCall(pageTitle, null, sectionTemplateName);
            }
        }
        else {
            if (isQuoted) {
                return createTemplateCall(pageTitle, null, templateName, true, abbreviation);
            }
            else if (outerFormatting) {
                var displayWithFormatting = outerFormatting + pageTitle + outerFormatting;
                return createTemplateCall(pageTitle, displayWithFormatting, templateName, false, abbreviation);
            }
            else {
                return createTemplateCall(pageTitle, null, templateName, false, abbreviation);
            }
        }
    }
    function createFormattedLinkWithDisplay(pipeParts, outerFormatting, templateName, sectionTemplateName, skipInfo, selectedRedirects, abbreviation) {
        var _a, _b;
        if (abbreviation === void 0) { abbreviation = null; }
        var pageTitle = ((_a = pipeParts[0]) === null || _a === void 0 ? void 0 : _a.trim()) || '';
        var displayText = ((_b = pipeParts[1]) === null || _b === void 0 ? void 0 : _b.trim()) || '';
        var isQuoted = outerFormatting === '"';
        if (displayText === "") {
            displayText = handlePipeTrick(pageTitle, outerFormatting);
        }
        else if (outerFormatting &&
            !isQuoted &&
            !displayText.match(/^''+/) &&
            !displayText.match(/^<[^>]+>/)) {
            displayText = outerFormatting + displayText + outerFormatting;
        }
        if (isSectionLink(pageTitle)) {
            if (isQuoted) {
                return null;
            }
            else if (displayText === pageTitle) {
                return createSlinkTemplateCall(pageTitle, null, sectionTemplateName);
            }
            else {
                return null;
            }
        }
        else {
            if (displayText === pageTitle) {
                return createTemplateCall(pageTitle, null, templateName, isQuoted, abbreviation);
            }
            else {
                return createTemplateCall(pageTitle, displayText, templateName, isQuoted, abbreviation);
            }
        }
    }
    function createFormattedLink(pipeParts, pageTitle, outerFormatting, templateName, sectionTemplateName, skipInfo, selectedRedirects, abbreviation) {
        if (selectedRedirects === void 0) { selectedRedirects = []; }
        if (abbreviation === void 0) { abbreviation = null; }
        if (pipeParts.length === 1) {
            var result = createSimpleFormattedLink(pageTitle, outerFormatting, templateName, sectionTemplateName, skipInfo, selectedRedirects, abbreviation);
            return result;
        }
        else if (pipeParts.length === 2) {
            var result = createFormattedLinkWithDisplay(pipeParts, outerFormatting, templateName, sectionTemplateName, skipInfo, selectedRedirects, abbreviation);
            return result;
        }
        else {
            return null;
        }
    }
    function processTemplateWithDescription(line, templateMatch) {
        var listMarker = templateMatch[1];
        var template = templateMatch[2];
        var description = templateMatch[4];
        if (description) {
            return listMarker + template + " – " + capitalizeFirstLetter(replaceSpacedEnDashTemplates(description));
        }
        return line;
    }
    function processLinkWithDescription(line, listMarker, descMatch, skipInfo, templateName, sectionTemplateName, selectedRedirects) {
        var _a;
        if (templateName === void 0) { templateName = "anl"; }
        if (sectionTemplateName === void 0) { sectionTemplateName = "slink"; }
        if (selectedRedirects === void 0) { selectedRedirects = []; }
        var outerFormatting = descMatch[1] || '';
        var fullLinkContent = descMatch[2];
        var description = descMatch[5];
        var trailingContent = descMatch[6];
        if (shouldSkipColonPrefixedLink(fullLinkContent)) {
            return line;
        }
        var pipeParts = fullLinkContent.split("|");
        var pageTitle = ((_a = pipeParts[0]) === null || _a === void 0 ? void 0 : _a.trim()) || '';
        if (description || trailingContent) {
            if (description) {
                var linkPart = outerFormatting + "[[" + fullLinkContent + "]]" + outerFormatting;
                var result = listMarker + linkPart + " – " + capitalizeFirstLetter(replaceSpacedEnDashTemplates(description));
                STATS.manualDescriptionsReformatted++;
                return result;
            }
            if (trailingContent) {
                var contentAnalysis = processTrailingContent(trailingContent);
                if (contentAnalysis.abbreviation && !contentAnalysis.description) {
                    if (isSectionLink(pageTitle)) {
                        var formattedLink_1 = createFormattedLink(pipeParts, pageTitle, outerFormatting, templateName, sectionTemplateName, skipInfo, selectedRedirects);
                        if (formattedLink_1) {
                            return listMarker + formattedLink_1 + " (" + contentAnalysis.abbreviation + ")";
                        }
                    }
                    else {
                        if (!skipInfo || !shouldSkipLink(pageTitle, skipInfo, selectedRedirects)) {
                            var formattedLink_2 = createFormattedLink(pipeParts, pageTitle, outerFormatting, templateName, sectionTemplateName, skipInfo, selectedRedirects, contentAnalysis.abbreviation);
                            if (formattedLink_2) {
                                return listMarker + formattedLink_2;
                            }
                        }
                    }
                }
                else if (contentAnalysis.abbreviation && contentAnalysis.description) {
                    var linkPart = outerFormatting + "[[" + fullLinkContent + "]]" + outerFormatting;
                    var abbrevPart = "(" + contentAnalysis.abbreviation + ")";
                    var result = listMarker + linkPart + " " + abbrevPart + " – " + capitalizeFirstLetter(contentAnalysis.description);
                    STATS.manualDescriptionsReformatted++;
                    return result;
                }
                return line;
            }
        }
        if (skipInfo && shouldSkipLink(pageTitle, skipInfo, selectedRedirects)) {
            return line;
        }
        var formattedLink = createFormattedLink(pipeParts, pageTitle, outerFormatting, templateName, sectionTemplateName, skipInfo, selectedRedirects);
        if (!formattedLink) {
            return line;
        }
        return listMarker + formattedLink;
    }
    function processAgglutinatedLink(line, listMarker, content, skipInfo, templateName, sectionTemplateName, selectedRedirects) {
        var _a, _b;
        if (templateName === void 0) { templateName = "anl"; }
        if (sectionTemplateName === void 0) { sectionTemplateName = "slink"; }
        if (selectedRedirects === void 0) { selectedRedirects = []; }
        var formatInfo = extractOuterFormatting(content);
        var agglutinatedMatch = formatInfo.stripped.match(REGEX_PATTERNS.AGGLUTINATED_LINK);
        if (!agglutinatedMatch) {
            return line;
        }
        var linkContent = agglutinatedMatch[1];
        var agglutinatedText = agglutinatedMatch[2];
        if (shouldSkipColonPrefixedLink(linkContent)) {
            return line;
        }
        var pipeParts = linkContent.split("|");
        var pageTitle = ((_a = pipeParts[0]) === null || _a === void 0 ? void 0 : _a.trim()) || '';
        if (skipInfo && shouldSkipLink(pageTitle, skipInfo, selectedRedirects)) {
            return line;
        }
        var displayText;
        if (pipeParts.length === 1) {
            displayText = pageTitle + agglutinatedText;
        }
        else {
            displayText = (((_b = pipeParts[1]) === null || _b === void 0 ? void 0 : _b.trim()) || '') + agglutinatedText;
        }
        if (formatInfo.formatting && formatInfo.formatting !== '"') {
            displayText = formatInfo.formatting + displayText + formatInfo.formatting;
        }
        if (isSectionLink(pageTitle)) {
            var isQuoted = formatInfo.formatting === '"';
            if (isQuoted) {
                return line;
            }
            else {
                return listMarker + createSlinkTemplateCall(pageTitle, displayText, sectionTemplateName);
            }
        }
        else {
            var isQuoted = formatInfo.formatting === '"';
            return listMarker + createTemplateCall(pageTitle, displayText, templateName, isQuoted, null);
        }
    }
    function processSimpleLink(line, listMarker, content, skipInfo, templateName, sectionTemplateName, selectedRedirects) {
        var _a;
        if (templateName === void 0) { templateName = "anl"; }
        if (sectionTemplateName === void 0) { sectionTemplateName = "slink"; }
        if (selectedRedirects === void 0) { selectedRedirects = []; }
        var formatInfo = extractOuterFormatting(content);
        var linkMatch = formatInfo.stripped.match(REGEX_PATTERNS.SIMPLE_LINK);
        if (!linkMatch) {
            return line;
        }
        var linkContent = linkMatch[1];
        if (shouldSkipColonPrefixedLink(linkContent)) {
            return line;
        }
        var pipeParts = linkContent.split("|");
        var pageTitle = ((_a = pipeParts[0]) === null || _a === void 0 ? void 0 : _a.trim()) || '';
        if (skipInfo && shouldSkipLink(pageTitle, skipInfo, selectedRedirects)) {
            return line;
        }
        var formattedLink = createFormattedLink(pipeParts, pageTitle, formatInfo.formatting, templateName, sectionTemplateName, skipInfo, selectedRedirects);
        if (!formattedLink) {
            return line;
        }
        return listMarker + formattedLink;
    }

    function buildListTree(lines) {
        var tree = { lists: [], nonListContent: [] };
        var currentList = null;
        var inHtmlComment = false;
        for (var i = 0; i < lines.length; i++) {
            var line = lines[i];
            if (line.includes('<!--')) {
                inHtmlComment = true;
            }
            var listMatch = !inHtmlComment && line.match(/^(\s*)(\*+)\s*(.*)/);
            if (line.includes('-->')) {
                inHtmlComment = false;
            }
            if (listMatch) {
                var indent = listMatch[1];
                var stars = listMatch[2];
                var content = listMatch[3];
                var level = stars.length;
                var item = {
                    lineIndex: i,
                    level: level,
                    indent: indent,
                    content: content,
                    children: [],
                };
                if (!currentList) {
                    currentList = { items: [], startIndex: i };
                    tree.lists.push(currentList);
                }
                addToListStructure(currentList.items, item, level);
            }
            else {
                if (currentList) {
                    currentList.endIndex = i - 1;
                    currentList = null;
                }
                tree.nonListContent.push({ lineIndex: i, content: line });
            }
        }
        if (currentList && !currentList.endIndex) {
            currentList.endIndex = lines.length - 1;
        }
        return tree;
    }
    function addToListStructure(items, newItem, targetLevel) {
        if (targetLevel === 1) {
            items.push(newItem);
            return;
        }
        var lastItem = items[items.length - 1];
        if (!lastItem)
            return;
        if (targetLevel === 2) {
            lastItem.children.push(newItem);
        }
        else {
            addToListStructure(lastItem.children, newItem, targetLevel - 1);
        }
    }
    function normalizeTextForSorting(text) {
        var normalized = text;
        normalized = normalized.replace(/^"(.*)"$/, '$1');
        if (normalized === text) {
            normalized = normalized.replace(/^"([^"]*)"/, '$1');
        }
        normalized = normalized.replace(/^'(.*)'$/, '$1');
        if (normalized === text.replace(/^"([^"]*)"/, '$1')) {
            normalized = normalized.replace(/^'([^']*)'/, '$1');
        }
        return normalized;
    }
    function sortListItems(items, displayTextMap) {
        items.sort(function (a, b) {
            var textA = displayTextMap[a.lineIndex] || "";
            var textB = displayTextMap[b.lineIndex] || "";
            var normalizedA = normalizeTextForSorting(textA);
            var normalizedB = normalizeTextForSorting(textB);
            return normalizedA.localeCompare(normalizedB, "en", {
                numeric: true,
                sensitivity: "base",
            });
        });
        for (var i = 0; i < items.length; i++) {
            var item = items[i];
            if (item && item.children && item.children.length > 0) {
                sortListItems(item.children, displayTextMap);
            }
        }
    }
    function sortTree(tree, displayTextMap) {
        for (var i = 0; i < tree.lists.length; i++) {
            sortListItems(tree.lists[i].items, displayTextMap);
        }
    }
    function buildListLines(items) {
        var lines = [];
        for (var i = 0; i < items.length; i++) {
            var item = items[i];
            var stars = "";
            for (var j = 0; j < item.level; j++) {
                stars += "*";
            }
            var line = item.indent + stars + " " + item.content;
            lines.push(line);
            if (item && item.children && item.children.length > 0) {
                var childLines = buildListLines(item.children);
                for (var k = 0; k < childLines.length; k++) {
                    lines.push(childLines[k]);
                }
            }
        }
        return lines;
    }
    function rebuildSection(tree) {
        var result = [];
        var processedIndices = {};
        var allContent = [];
        for (var i = 0; i < tree.lists.length; i++) {
            var list = tree.lists[i];
            if (list) {
                allContent.push({
                    type: "list",
                    data: list,
                    startIndex: list.startIndex,
                });
            }
        }
        for (var j = 0; j < tree.nonListContent.length; j++) {
            var nonList = tree.nonListContent[j];
            var nonListItem = nonList;
            allContent.push({
                type: "nonList",
                data: nonListItem,
                startIndex: nonListItem.lineIndex,
            });
        }
        allContent.sort(function (a, b) {
            return a.startIndex - b.startIndex;
        });
        for (var k = 0; k < allContent.length; k++) {
            var content = allContent[k];
            if (content && content.type === "list") {
                var listData = content.data;
                var listLines = buildListLines(listData.items);
                for (var m = 0; m < listLines.length; m++) {
                    var line = listLines[m];
                    if (line) {
                        result.push(line);
                    }
                }
                var endIndex = listData.endIndex || listData.startIndex;
                for (var n = listData.startIndex; n <= endIndex; n++) {
                    processedIndices[n] = true;
                }
            }
            else if (content) {
                var nonListData = content.data;
                if (!processedIndices[nonListData.lineIndex]) {
                    result.push(nonListData.content);
                    processedIndices[nonListData.lineIndex] = true;
                }
            }
        }
        return result.join("\n");
    }
    function collectListLinesForSorting(items, lines, listLines, lineIndices) {
        for (var i = 0; i < items.length; i++) {
            var item = items[i];
            if (item) {
                var line = lines[item.lineIndex];
                if (line && line.match(/^\s*\*+\s*/)) {
                    var cleanLine = line.replace(/<ref.*?>.*?<\/ref>/g, "");
                    listLines.push(cleanLine);
                    lineIndices.push(item.lineIndex);
                }
                if (item.children && item.children.length > 0) {
                    collectListLinesForSorting(item.children, lines, listLines, lineIndices);
                }
            }
        }
    }

    function processLine(line, skipInfo, templateName, sectionTemplateName, selectedRedirects) {
        if (templateName === void 0) { templateName = "anl"; }
        if (sectionTemplateName === void 0) { sectionTemplateName = "slink"; }
        if (selectedRedirects === void 0) { selectedRedirects = []; }
        var analysis = analyzeLine(line);
        if (!analysis.isProcessable) {
            return line;
        }
        var hasLinkContent = line.match(/\[\[[^\]]+\]\]/) ||
            line.match(/\{\{(?:anl|anli|annotated link|slink|seclink|section link)\|/i);
        var originalLine = line;
        if (analysis.lineType === 'template-with-desc' && analysis.templateMatch) {
            var result_1 = processTemplateWithDescription(line, analysis.templateMatch);
            return result_1;
        }
        var listMatch = analysis.listMatch;
        var content = analysis.content;
        var listMarker = listMatch[1];
        var descMatch = analysis.descMatch;
        if (descMatch) {
            var skipCountsBefore_1 = {
                redirects: STATS.linksSkippedRedirects,
                missing: STATS.linksSkippedMissing,
                disambiguation: STATS.linksSkippedDisambiguation,
                namespaced: STATS.linksSkippedNamespaced,
                emptyDescription: STATS.linksSkippedEmptyDescription
            };
            var result_2 = processLinkWithDescription(line, listMarker, descMatch, skipInfo, templateName, sectionTemplateName, selectedRedirects);
            var contentSkipOccurred_1 = STATS.linksSkippedRedirects > skipCountsBefore_1.redirects ||
                STATS.linksSkippedMissing > skipCountsBefore_1.missing ||
                STATS.linksSkippedDisambiguation > skipCountsBefore_1.disambiguation ||
                STATS.linksSkippedNamespaced > skipCountsBefore_1.namespaced ||
                STATS.linksSkippedEmptyDescription > skipCountsBefore_1.emptyDescription;
            if (result_2 === originalLine && hasLinkContent && !descMatch[5] && !contentSkipOccurred_1) {
                STATS.linesUnprocessable++;
            }
            return result_2;
        }
        var skipCountsBefore = {
            redirects: STATS.linksSkippedRedirects,
            missing: STATS.linksSkippedMissing,
            disambiguation: STATS.linksSkippedDisambiguation,
            namespaced: STATS.linksSkippedNamespaced,
            emptyDescription: STATS.linksSkippedEmptyDescription
        };
        var result = processAgglutinatedLink(line, listMarker, content, skipInfo, templateName, sectionTemplateName, selectedRedirects);
        if (result === line) {
            result = processSimpleLink(line, listMarker, content, skipInfo, templateName, sectionTemplateName, selectedRedirects);
        }
        var contentSkipOccurred = STATS.linksSkippedRedirects > skipCountsBefore.redirects ||
            STATS.linksSkippedMissing > skipCountsBefore.missing ||
            STATS.linksSkippedDisambiguation > skipCountsBefore.disambiguation ||
            STATS.linksSkippedNamespaced > skipCountsBefore.namespaced ||
            STATS.linksSkippedEmptyDescription > skipCountsBefore.emptyDescription;
        if (result === originalLine && hasLinkContent && !contentSkipOccurred) {
            STATS.linesUnprocessable++;
        }
        return result;
    }
    function formatWikitextLinks(input, skipInfo, selectedRedirects) {
        if (selectedRedirects === void 0) { selectedRedirects = []; }
        var preferredTemplate = detectPreferredTemplate(input);
        var preferredSectionTemplate = detectPreferredSectionTemplate(input);
        var lines = input.split("\n");
        var result = lines
            .map(function (line) {
            return processLine(line, skipInfo, preferredTemplate, preferredSectionTemplate, selectedRedirects);
        })
            .join("\n");
        return result;
    }
    function findSeeAlsoSection(fullText) {
        var seeAlsoMatch = fullText.match(SEE_ALSO_HEADING_REGEX);
        if (!seeAlsoMatch) {
            return null;
        }
        var sectionStart = seeAlsoMatch.index;
        var sectionHeader = seeAlsoMatch[0];
        var afterHeader = sectionStart + sectionHeader.length;
        var restOfText = fullText.substring(afterHeader);
        var nextSectionMatch = restOfText.match(/^==[^=]/m);
        var sectionEnd;
        if (nextSectionMatch && nextSectionMatch.index !== undefined) {
            sectionEnd = afterHeader + nextSectionMatch.index;
        }
        else {
            sectionEnd = fullText.length;
        }
        return {
            sectionStart: sectionStart,
            sectionEnd: sectionEnd,
            sectionHeader: sectionHeader,
        };
    }
    function extractSectionContent(fullText, sectionStart, sectionEnd) {
        var sectionContent = fullText.substring(sectionStart, sectionEnd || fullText.length);
        return sectionContent;
    }
    function processApiCallsForSorting(apiCalls, sectionContent, tree, displayTextMap, callback) {
        if (apiCalls.length === 0) {
            callback(sectionContent);
            return;
        }
        $.when
            .apply($, apiCalls)
            .done(function () {
            sortTree(tree, displayTextMap);
            var sortedSection = rebuildSection(tree);
            callback(sortedSection);
        })
            .fail(function (error) {
            console.error("API call failed:", error);
            mw.notify("Could not sort links (API error), but formatting was applied.", { type: "warn" });
            callback(sectionContent);
        });
    }
    function sortFormattedSection(sectionContent) {
        return new Promise(function (resolve) {
            var sortFormattedSectionInternal = function (callback) {
                var lines = sectionContent.split("\n");
                var tree = buildListTree(lines);
                if (!tree || tree.lists.length === 0) {
                    callback(sectionContent);
                    return;
                }
                var displayTextMap = {};
                var apiCalls = [];
                for (var listIdx = 0; listIdx < tree.lists.length; listIdx++) {
                    var list = tree.lists[listIdx];
                    var listLines = [];
                    var lineIndices = [];
                    collectListLinesForSorting(list.items, lines, listLines, lineIndices);
                    if (listLines.length === 0)
                        continue;
                    (function (lines, indices) {
                        var wikitext = lines.join("\n");
                        var promise = new mw.Api()
                            .post({
                            action: 'parse',
                            text: wikitext,
                            contentmodel: 'wikitext',
                            disablelimitreport: true,
                            format: 'json'
                        })
                            .done(function (data) {
                            var _a;
                            var apiData = data;
                            if (!apiData.parse) {
                                return;
                            }
                            var parsed = typeof apiData.parse.text === 'string'
                                ? apiData.parse.text
                                : ((_a = apiData.parse.text) === null || _a === void 0 ? void 0 : _a['*']) || '';
                            parseApiResponseForDisplayText(parsed, indices, displayTextMap);
                        });
                        apiCalls.push(promise);
                    })(listLines, lineIndices);
                }
                processApiCallsForSorting(apiCalls, sectionContent, tree, displayTextMap, callback);
            };
            sortFormattedSectionInternal(resolve);
        });
    }

    function shouldInitializeScript() {
        var wgAction = mw.config.get("wgAction");
        var wgNamespace = mw.config.get("wgCanonicalNamespace");
        if (wgAction !== "edit" && wgAction !== "submit") {
            return false;
        }
        if (wgNamespace !== "" &&
            wgNamespace !== "User" &&
            wgNamespace !== "Draft") {
            return false;
        }
        var txtarea = document.getElementById("wpTextbox1");
        if (!txtarea) {
            return false;
        }
        var fullText = txtarea.value;
        if (!SEE_ALSO_HEADING_REGEX.test(fullText)) {
            return false;
        }
        return true;
    }
    function setupToolbarButton(formatSeeAlso, revertSeeAlso) {
        return new Promise(function (resolve) {
            mw.loader.using("user.options").then(function () {
                if (mw.user.options.get("usebetatoolbar") !== 1) {
                    resolve();
                    return;
                }
                $.when(mw.loader.using("ext.wikiEditor"), $.ready).then(function () {
                    $("#wpTextbox1").wikiEditor("addToToolbar", {
                        section: "main",
                        group: "insert",
                        tools: {
                            formatSeeAlso: {
                                label: "Format See Also",
                                type: "button",
                                icon: "//upload.wikimedia.org/wikipedia/en/c/c9/FormatSeeAlsoButton.png",
                                action: {
                                    type: "callback",
                                    execute: formatSeeAlso,
                                },
                            },
                            revertSeeAlso: {
                                label: "Revert See Also",
                                type: "button",
                                icon: "//upload.wikimedia.org/wikipedia/en/c/cb/FormatSeeAlsoUndo.png",
                                action: {
                                    type: "callback",
                                    execute: revertSeeAlso,
                                },
                            },
                        },
                    });
                    $(".tool[rel='revertSeeAlso']").hide();
                    resolve();
                });
            });
        });
    }
    function showRevertButton(_revertSeeAlso) {
        $(".tool[rel='revertSeeAlso']").show();
    }
    function hideRevertButton() {
        $(".tool[rel='revertSeeAlso']").hide();
    }

    var originalContent = null;
    var changeMonitor = null;
    function processFormattingResults(formattedSection, fullText, sectionStart, sectionEnd, txtarea, shouldSort, _revertSeeAlso, _skipInfo, _originalSectionContent) {
        return __awaiter(this, void 0, void 0, function () {
            var formattedLinks;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        formattedLinks = (formattedSection.match(/\{\{(?:Annotated link|anl|anli|section link|seclink|slink)/gi) || []).length;
                        if (!(formattedLinks > 0)) return [3, 2];
                        return [4, handleFormattedLinks(fullText, sectionStart, sectionEnd || fullText.length, formattedSection, txtarea, shouldSort)];
                    case 1:
                        _a.sent();
                        return [3, 4];
                    case 2: return [4, handleNoFormatting(fullText, sectionStart, sectionEnd || fullText.length, formattedSection, txtarea, shouldSort)];
                    case 3:
                        _a.sent();
                        _a.label = 4;
                    case 4: return [2];
                }
            });
        });
    }
    function handleFormattedLinks(fullText, sectionStart, sectionEnd, formattedSection, txtarea, shouldSort, _revertSeeAlso, _skipInfo, _originalSectionContent) {
        return __awaiter(this, void 0, void 0, function () {
            var sortedSection, newSectionEnd, docWithForm, newSectionEnd, docWithForm;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (!shouldSort) return [3, 2];
                        return [4, sortFormattedSection(formattedSection)];
                    case 1:
                        sortedSection = _a.sent();
                        setTextareaValue(txtarea, fullText.substring(0, sectionStart) +
                            sortedSection +
                            fullText.substring(sectionEnd));
                        newSectionEnd = sectionStart + sortedSection.length;
                        txtarea.setSelectionRange(newSectionEnd, newSectionEnd);
                        txtarea.focus();
                        checkForSectionChanges();
                        mw.notify(generateSuccessMessage());
                        docWithForm = document;
                        if (docWithForm.editform && docWithForm.editform.wpSummary) {
                            docWithForm.editform.wpSummary.value =
                                "Format [[#See also|See also]] section per [[MOS:ALSO]] ([[User:Anne drew/FormatSeeAlso|FormatSeeAlso]])";
                        }
                        return [3, 3];
                    case 2:
                        setTextareaValue(txtarea, fullText.substring(0, sectionStart) +
                            formattedSection +
                            fullText.substring(sectionEnd));
                        newSectionEnd = sectionStart + formattedSection.length;
                        txtarea.setSelectionRange(newSectionEnd, newSectionEnd);
                        txtarea.focus();
                        checkForSectionChanges();
                        mw.notify(generateSuccessMessage());
                        docWithForm = document;
                        if (docWithForm.editform && docWithForm.editform.wpSummary) {
                            docWithForm.editform.wpSummary.value =
                                "Format [[#See also|See also]] section per [[MOS:ALSO]] ([[User:Anne drew/FormatSeeAlso|FormatSeeAlso]])";
                        }
                        _a.label = 3;
                    case 3: return [2];
                }
            });
        });
    }
    function handleNoFormatting(fullText, sectionStart, sectionEnd, formattedSection, txtarea, shouldSort, _revertSeeAlso, _skipInfo, _originalSectionContent) {
        return __awaiter(this, void 0, void 0, function () {
            var sortedSection, newSectionEnd, docWithForm, newSectionEnd;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (!shouldSort) return [3, 2];
                        return [4, sortFormattedSection(formattedSection)];
                    case 1:
                        sortedSection = _a.sent();
                        setTextareaValue(txtarea, fullText.substring(0, sectionStart) +
                            sortedSection +
                            fullText.substring(sectionEnd));
                        newSectionEnd = sectionStart + sortedSection.length;
                        txtarea.setSelectionRange(newSectionEnd, newSectionEnd);
                        txtarea.focus();
                        checkForSectionChanges();
                        mw.notify(generateSuccessMessage());
                        docWithForm = document;
                        if (docWithForm.editform && docWithForm.editform.wpSummary) {
                            docWithForm.editform.wpSummary.value =
                                "Sort [[#See also|See also]] section per [[MOS:ALSO]] ([[User:Anne drew/FormatSeeAlso|FormatSeeAlso]])";
                        }
                        return [3, 3];
                    case 2:
                        setTextareaValue(txtarea, fullText.substring(0, sectionStart) +
                            formattedSection +
                            fullText.substring(sectionEnd));
                        newSectionEnd = sectionStart + formattedSection.length;
                        txtarea.setSelectionRange(newSectionEnd, newSectionEnd);
                        txtarea.focus();
                        checkForSectionChanges();
                        mw.notify(generateSuccessMessage());
                        _a.label = 3;
                    case 3: return [2];
                }
            });
        });
    }
    function showMissingDescriptionsDialog(skipInfo, sectionContent) {
        return __awaiter(this, void 0, void 0, function () {
            var missingDescriptions, potentialShortDescNonePages, shortDescNoneResults_1, filteredMissingDescriptions, error_1;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        _a.trys.push([0, 3, , 4]);
                        missingDescriptions = collectMissingDescriptions(skipInfo, sectionContent);
                        potentialShortDescNonePages = __spreadArray(__spreadArray(__spreadArray(__spreadArray([], missingDescriptions.redirectsToSectionsMissingDesc.map(function (item) { return item.pageTitle; }), true), missingDescriptions.redirectsToTopLevelMissingDesc.map(function (item) { return item.pageTitle; }), true), missingDescriptions.redirectsToTopLevelMissingDesc
                            .map(function (item) { return item.target; })
                            .filter(function (target) { return target; }), true), missingDescriptions.articlesMissingDesc.map(function (item) { return item.pageTitle; }), true);
                        if (potentialShortDescNonePages.length === 0) {
                            return [2];
                        }
                        return [4, checkForShortDescriptionNone(potentialShortDescNonePages)];
                    case 1:
                        shortDescNoneResults_1 = _a.sent();
                        filteredMissingDescriptions = {
                            redirectsToSectionsMissingDesc: missingDescriptions.redirectsToSectionsMissingDesc.filter(function (item) {
                                return !shortDescNoneResults_1[item.pageTitle];
                            }),
                            redirectsToTopLevelMissingDesc: missingDescriptions.redirectsToTopLevelMissingDesc.filter(function (item) {
                                return !shortDescNoneResults_1[item.pageTitle] &&
                                    (!item.target || !shortDescNoneResults_1[item.target]);
                            }),
                            articlesMissingDesc: missingDescriptions.articlesMissingDesc.filter(function (item) { return !shortDescNoneResults_1[item.pageTitle]; }),
                        };
                        return [4, promptForMissingDescriptions(filteredMissingDescriptions)];
                    case 2:
                        _a.sent();
                        return [3, 4];
                    case 3:
                        error_1 = _a.sent();
                        console.error("Error showing missing descriptions dialog:", error_1);
                        return [3, 4];
                    case 4: return [2];
                }
            });
        });
    }
    function formatSeeAlso() {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                STATS.reset();
                setTimeout(function () {
                    return __awaiter(this, void 0, void 0, function () {
                        var txtarea, fullText, sectionInfo, sectionStart, sectionEnd, sectionContent, initialSkipInfo, skipInfo_1, selectedRedirects, redirectTitles, autoSelectedRedirects_1, manualSelectionRedirects_1, redirectSelectionResult, shouldSort, shouldSortNonNull, formattedSection, e_1;
                        return __generator(this, function (_a) {
                            switch (_a.label) {
                                case 0:
                                    _a.trys.push([0, 8, , 9]);
                                    txtarea = document.getElementById("wpTextbox1");
                                    if (!txtarea) {
                                        mw.notify("Could not find editor textarea!", { type: "error" });
                                        return [2];
                                    }
                                    fullText = getTextareaValue(txtarea);
                                    sectionInfo = findSeeAlsoSection(fullText);
                                    if (!sectionInfo) {
                                        mw.notify('No "See also" section found!', { type: "warn" });
                                        return [2];
                                    }
                                    sectionStart = sectionInfo.sectionStart;
                                    sectionEnd = sectionInfo.sectionEnd;
                                    sectionContent = extractSectionContent(fullText, sectionStart, sectionEnd);
                                    if (!originalContent) {
                                        originalContent = {
                                            sectionStart: sectionStart,
                                            sectionEnd: sectionEnd,
                                            sectionContent: sectionContent,
                                        };
                                    }
                                    return [4, checkLinksToSkip(sectionContent)];
                                case 1:
                                    initialSkipInfo = _a.sent();
                                    return [4, showMissingDescriptionsDialog(initialSkipInfo, sectionContent)];
                                case 2:
                                    _a.sent();
                                    return [4, checkLinksToSkip(sectionContent)];
                                case 3:
                                    skipInfo_1 = _a.sent();
                                    selectedRedirects = [];
                                    redirectTitles = Object.keys(skipInfo_1.redirectTargets);
                                    autoSelectedRedirects_1 = [];
                                    manualSelectionRedirects_1 = {};
                                    redirectTitles.forEach(function (title) {
                                        var redirectInfo = skipInfo_1.redirectTargets[title];
                                        if (redirectInfo === null || redirectInfo === void 0 ? void 0 : redirectInfo.shouldAutoSelect) {
                                            autoSelectedRedirects_1.push(title);
                                        }
                                        else if (redirectInfo) {
                                            manualSelectionRedirects_1[title] = redirectInfo;
                                        }
                                    });
                                    selectedRedirects = __spreadArray([], autoSelectedRedirects_1, true);
                                    if (!(Object.keys(manualSelectionRedirects_1).length > 0)) return [3, 5];
                                    return [4, promptForRedirectSelection(manualSelectionRedirects_1)];
                                case 4:
                                    redirectSelectionResult = _a.sent();
                                    if (redirectSelectionResult === null) {
                                        mw.notify("Operation cancelled by user.", { type: "info" });
                                        return [2];
                                    }
                                    selectedRedirects = __spreadArray(__spreadArray([], autoSelectedRedirects_1, true), redirectSelectionResult, true);
                                    _a.label = 5;
                                case 5: return [4, promptForSorting()];
                                case 6:
                                    shouldSort = _a.sent();
                                    if (shouldSort === null) {
                                        mw.notify("Operation cancelled by user.", { type: "info" });
                                        return [2];
                                    }
                                    shouldSortNonNull = shouldSort;
                                    formattedSection = formatWikitextLinks(sectionContent, skipInfo_1, selectedRedirects);
                                    return [4, processFormattingResults(formattedSection, fullText, sectionStart, sectionEnd, txtarea, shouldSortNonNull)];
                                case 7:
                                    _a.sent();
                                    return [3, 9];
                                case 8:
                                    e_1 = _a.sent();
                                    console.error(e_1);
                                    mw.notify("Failed to format links! See console for details.", {
                                        type: "error",
                                    });
                                    return [3, 9];
                                case 9: return [2];
                            }
                        });
                    });
                }, CONFIG.TIMEOUT_DELAY);
                return [2];
            });
        });
    }
    function revertSeeAlso() {
        return __awaiter(this, void 0, void 0, function () {
            var txtarea, currentFullText, currentSectionInfo, beforeSection, afterSection, newSectionEnd, docWithForm;
            return __generator(this, function (_a) {
                if (!originalContent) {
                    mw.notify("No original content available to revert!", { type: "warn" });
                    return [2];
                }
                try {
                    txtarea = document.getElementById("wpTextbox1");
                    if (!txtarea) {
                        mw.notify("Could not find editor textarea!", { type: "error" });
                        return [2];
                    }
                    currentFullText = getTextareaValue(txtarea);
                    currentSectionInfo = findSeeAlsoSection(currentFullText);
                    if (!currentSectionInfo) {
                        mw.notify("Could not find current 'See also' section to revert!", {
                            type: "error",
                        });
                        return [2];
                    }
                    beforeSection = currentFullText.substring(0, currentSectionInfo.sectionStart);
                    afterSection = currentFullText.substring(currentSectionInfo.sectionEnd);
                    setTextareaValue(txtarea, beforeSection + originalContent.sectionContent + afterSection);
                    newSectionEnd = currentSectionInfo.sectionStart + originalContent.sectionContent.length;
                    txtarea.setSelectionRange(newSectionEnd, newSectionEnd);
                    txtarea.focus();
                    mw.notify('Reverted "See also" section to original content.', {
                        type: "success",
                    });
                    storeInitialContent().then(function () {
                        checkForSectionChanges();
                    });
                    docWithForm = document;
                    if (docWithForm.editform && docWithForm.editform.wpSummary) {
                        docWithForm.editform.wpSummary.value = "";
                    }
                }
                catch (e) {
                    console.error(e);
                    mw.notify("Failed to revert! See console for details.", {
                        type: "error",
                    });
                }
                return [2];
            });
        });
    }
    function fetchOriginalSectionFromArticle() {
        var pageTitle = mw.config.get("wgPageName");
        return new Promise(function (resolve) {
            if (!pageTitle) {
                resolve(null);
                return;
            }
            new mw.Api()
                .get({
                action: "query",
                prop: "revisions",
                titles: pageTitle,
                rvslots: "main",
                rvprop: "content",
                formatversion: 2,
            })
                .done(function (data) {
                if (!data.query || !data.query.pages || data.query.pages.length === 0) {
                    resolve(null);
                    return;
                }
                var page = data.query.pages[0];
                if (page.missing || !page.revisions || page.revisions.length === 0) {
                    resolve(null);
                    return;
                }
                var revision = page.revisions[0];
                if (!revision) {
                    resolve(null);
                    return;
                }
                var articleContent = revision.slots.main.content;
                var sectionInfo = findSeeAlsoSection(articleContent);
                if (!sectionInfo) {
                    resolve(null);
                    return;
                }
                var sectionContent = extractSectionContent(articleContent, sectionInfo.sectionStart, sectionInfo.sectionEnd);
                resolve(sectionContent);
            })
                .fail(function (error) {
                console.error("Failed to fetch original article content:", error);
                resolve(null);
            });
        });
    }
    function storeInitialContent() {
        return __awaiter(this, void 0, void 0, function () {
            var articleSectionContent, txtarea, fullText, sectionInfo, textareaSectionContent;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4, fetchOriginalSectionFromArticle()];
                    case 1:
                        articleSectionContent = _a.sent();
                        txtarea = document.getElementById("wpTextbox1");
                        if (!txtarea) {
                            return [2];
                        }
                        fullText = getTextareaValue(txtarea);
                        sectionInfo = findSeeAlsoSection(fullText);
                        if (!sectionInfo) {
                            return [2];
                        }
                        textareaSectionContent = extractSectionContent(fullText, sectionInfo.sectionStart, sectionInfo.sectionEnd);
                        if (articleSectionContent && articleSectionContent.trim() !== "") {
                            originalContent = {
                                sectionStart: sectionInfo.sectionStart,
                                sectionEnd: sectionInfo.sectionEnd,
                                sectionContent: articleSectionContent,
                            };
                        }
                        else {
                            originalContent = {
                                sectionStart: sectionInfo.sectionStart,
                                sectionEnd: sectionInfo.sectionEnd,
                                sectionContent: textareaSectionContent,
                            };
                        }
                        return [2];
                }
            });
        });
    }
    function checkForSectionChanges() {
        if (!originalContent)
            return;
        var txtarea = document.getElementById("wpTextbox1");
        if (!txtarea)
            return;
        var currentFullText = getTextareaValue(txtarea);
        var currentSectionInfo = findSeeAlsoSection(currentFullText);
        if (!currentSectionInfo) {
            if (originalContent.sectionContent.trim() !== "") {
                showRevertButton();
            }
            else {
                hideRevertButton();
            }
            return;
        }
        var currentSectionContent = extractSectionContent(currentFullText, currentSectionInfo.sectionStart, currentSectionInfo.sectionEnd);
        if (currentSectionContent.trim() !== originalContent.sectionContent.trim()) {
            showRevertButton();
        }
        else {
            hideRevertButton();
        }
    }
    function setupChangeMonitoring() {
        var txtarea = document.getElementById("wpTextbox1");
        if (!txtarea)
            return;
        changeMonitor = throttle(checkForSectionChanges, 300);
        txtarea.addEventListener("input", changeMonitor);
        txtarea.addEventListener("change", changeMonitor);
    }
    function initialize() {
        return __awaiter(this, void 0, void 0, function () {
            var error_2;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (!shouldInitializeScript()) {
                            return [2];
                        }
                        _a.label = 1;
                    case 1:
                        _a.trys.push([1, 4, , 5]);
                        return [4, storeInitialContent()];
                    case 2:
                        _a.sent();
                        return [4, setupToolbarButton(formatSeeAlso, revertSeeAlso)];
                    case 3:
                        _a.sent();
                        setupChangeMonitoring();
                        checkForSectionChanges();
                        return [3, 5];
                    case 4:
                        error_2 = _a.sent();
                        console.error("Error during FormatSeeAlso initialization:", error_2);
                        return [3, 5];
                    case 5: return [2];
                }
            });
        });
    }
    $(initialize);

    exports.showMissingDescriptionsDialog = showMissingDescriptionsDialog;

    return exports;

})({});
// </nowiki>