"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.stripOptionalBom = stripOptionalBom;
exports.normalizeMarkdownText = normalizeMarkdownText;
exports.parseMarkdownFrontmatter = parseMarkdownFrontmatter;
const yaml_1 = __importDefault(require("yaml"));
function isRecord(value) {
    return typeof value === 'object' && value !== null && !Array.isArray(value);
}
function stripOptionalBom(text) {
    if (text.charCodeAt(0) === 0xfeff) {
        return text.slice(1);
    }
    return text;
}
function normalizeMarkdownText(text) {
    return stripOptionalBom(text).replace(/\r\n/g, '\n');
}
function parseMarkdownFrontmatter(raw, sourceLabel = 'markdown') {
    const normalized = normalizeMarkdownText(raw);
    if (!normalized.startsWith('---\n')) {
        return { body: normalized, frontmatter: {} };
    }
    const endWithBody = normalized.indexOf('\n---\n', 4);
    const endAtEof = normalized.endsWith('\n---') ? normalized.length - '\n---'.length : -1;
    const end = endWithBody >= 0 ? endWithBody : endAtEof;
    if (end < 0) {
        return { body: normalized, frontmatter: {} };
    }
    const frontmatterText = normalized.slice(4, end);
    const body = endWithBody >= 0
        ? normalized.slice(end + '\n---\n'.length)
        : normalized.slice(end + '\n---'.length);
    try {
        const parsed = yaml_1.default.parse(frontmatterText);
        return { body, frontmatter: isRecord(parsed) ? parsed : {} };
    }
    catch (error) {
        throw new Error(`Invalid ${sourceLabel} frontmatter: ${error instanceof Error ? error.message : String(error)}`);
    }
}
