// Copyright (c) 2026 Modelware. All rights reserved.
import { parseYamlMap } from './md-yaml.js';
export function stripLeadingFrontMatter(markdown) {
    const normalized = markdown.replace(/^\uFEFF/, '');
    const frontMatter = extractLeadingFrontMatter(normalized);
    if (!frontMatter) {
        return normalized;
    }
    return normalized.slice(frontMatter.raw.length);
}
export function extractLeadingFrontMatter(markdown) {
    const normalized = markdown.replace(/^\uFEFF/, '');
    const yamlMatch = /^(---[ \t]*\r?\n[\s\S]*?\r?\n---[ \t]*(?:\r?\n|$))/.exec(normalized);
    if (yamlMatch) {
        const yamlBody = yamlMatch[1]
            .replace(/^---[ \t]*\r?\n/, '')
            .replace(/\r?\n---[ \t]*(?:\r?\n|$)$/, '');
        const yamlData = parseYamlMap(yamlBody);
        return {
            raw: yamlMatch[1],
            contextOntologyIri: extractContextIriFromData(yamlData) ?? extractContextIri(yamlMatch[1]),
            data: yamlData,
        };
    }
    const tomlMatch = /^(\+\+\+[ \t]*\r?\n[\s\S]*?\r?\n\+\+\+[ \t]*(?:\r?\n|$))/.exec(normalized);
    if (tomlMatch) {
        return {
            raw: tomlMatch[1],
            contextOntologyIri: extractContextIri(tomlMatch[1])
        };
    }
    return undefined;
}
export function extractContextIri(frontMatterRaw) {
    const match = /^ontologyIri\s*:\s*(.+)$/m.exec(frontMatterRaw)
        ?? /^ontology\s*:\s*(.+)$/m.exec(frontMatterRaw);
    if (!match) {
        return undefined;
    }
    return match[1].trim().replace(/^['"]|['"]$/g, '');
}
function extractContextIriFromData(data) {
    if (!data) {
        return undefined;
    }
    const value = typeof data.ontologyIri === 'string'
        ? data.ontologyIri
        : typeof data.ontology === 'string'
            ? data.ontology
            : undefined;
    return typeof value === 'string' ? value : undefined;
}
//# sourceMappingURL=md-frontmatter.js.map