UNPKG

@vrerv/md-to-notion

Version:

An upload of markdown files to a hierarchy of Notion pages.

64 lines 2.87 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.removeMarkdownLinks = exports.replaceInternalMarkdownLinks = exports.MARKDOWN_LINK_REGEX = exports.MARKDOWN_LINK_KEEP_ANCHOR_REGEX = void 0; // Regular expression to match markdown links: [text](link) const logging_1 = require("./logging"); exports.MARKDOWN_LINK_KEEP_ANCHOR_REGEX = /\[([^\]]+)]\(((?!(#|https?:\/\/))[^)]+)\)/g; exports.MARKDOWN_LINK_REGEX = /\[([^\]]+)]\(((?!(https?:\/\/))[^)]+)\)/g; const logger = (0, logging_1.makeConsoleLogger)("replace-links"); function replaceInternalMarkdownLinks(markdownContent, linkMap, filePathFromRoot, replacer) { // Replace markdown links with corresponding URLs from linkMap return markdownContent.replace(exports.MARKDOWN_LINK_REGEX, (match, text, link) => { // Resolve the link path based on filePathFromRoot const resolvedLinkPath = resolveLinkPath(filePathFromRoot, link); const key = "./" + resolvedLinkPath.replace(".md", ""); // Remove the .md extension const url = linkMap.get(key); logger(logging_1.LogLevel.DEBUG, "try to replace link", { key, filePathFromRoot, url: url, }); if (url) { return `[${text}](${url})`; } if (replacer) { return replacer(text, resolvedLinkPath); } // If no match in the map, return the original match return match; }); } exports.replaceInternalMarkdownLinks = replaceInternalMarkdownLinks; /** * Removes internal Markdown links from the content for Notion. * * @param content - The content to process. * @param keepAnchor * @returns The content with links removed. */ function removeMarkdownLinks(content, keepAnchor = false) { return content.replace(keepAnchor ? exports.MARKDOWN_LINK_KEEP_ANCHOR_REGEX : exports.MARKDOWN_LINK_REGEX, "$1"); } exports.removeMarkdownLinks = removeMarkdownLinks; // Helper function to resolve link paths based on the filePathFromRoot and relative links function resolveLinkPath(filePathFromRoot, link) { // Create an array from the file path and resolve the relative link const filePathSegments = filePathFromRoot.split("/"); const linkSegments = link.split("/"); // If the link starts with "..", navigate up the directories while (linkSegments[0] === "..") { linkSegments.shift(); // Remove the ".." filePathSegments.pop(); // Navigate up the parent directory } // Remove file name filePathSegments.pop(); if (linkSegments[0] === ".") { linkSegments.shift(); // Remove the "." } if (filePathSegments[0] === ".") { filePathSegments.shift(); // Remove the "." } // Combine the remaining segments return [...filePathSegments, ...linkSegments].join("/"); } //# sourceMappingURL=replace-links.js.map