Skip to content

Conversation

@haet
Copy link

@haet haet commented Dec 8, 2024

internal links from one imported notion page to another are converted to Markdown like
[link text](/XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX) for inline links and
[link text](XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX) for pages linked as separate block
whrer XXXX... are the page ids.

In this pull request I extract the page ids, check if they belong to a synced page and replace by /posts/

Summary by CodeRabbit

  • New Features

    • Enhanced functionality for processing Notion posts, including internal link conversion in markdown.
    • Introduced a new method for converting internal links to URLs based on a provided pages array.
  • Bug Fixes

    • Improved URL sanitization process, including normalization and removal of diacritical marks.
  • Documentation

    • Updated declarations for newly added and modified methods in the relevant modules.

@netlify
Copy link

netlify bot commented Dec 8, 2024

👷 Deploy request for musical-croissant-a0db2d pending review.

Visit the deploys page to approve it

Name Link
🔨 Latest commit d5dd038

@vercel
Copy link

vercel bot commented Dec 8, 2024

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
astronot ❌ Failed (Inspect) Dec 8, 2024 8:50am

@coderabbitai
Copy link

coderabbitai bot commented Dec 8, 2024

Walkthrough

The changes in this pull request involve enhancements to the functionality of processing Notion posts in the src/astronot.js file, with the introduction of a new helper function for converting internal links in markdown content. A new file, src/helpers/links.mjs, contains the convertInternalLinks function, which updates internal links based on a pages array. Additionally, the sanitizeUrl function in src/helpers/sanitize.mjs has been modified to improve URL sanitization by normalizing strings and removing diacritical marks.

Changes

File Change Summary
src/astronot.js Added import for convertInternalLinks. Updated logic for converting Notion pages to markdown, allowing modification of mdString.
src/helpers/links.mjs Introduced convertInternalLinks(mdString, pages) function for processing markdown internal links.
src/helpers/sanitize.mjs Updated sanitizeUrl(str) function to enhance URL sanitization with normalization and diacritical mark removal. sanitizeImageString(str) remains unchanged.

Sequence Diagram(s)

sequenceDiagram
    participant A as Notion Database
    participant B as astronot.js
    participant C as links.mjs
    participant D as sanitize.mjs
    participant E as File System

    A->>B: Fetch posts
    B->>B: Transform blocks to markdown
    B->>C: Convert internal links
    C->>B: Return modified markdown
    B->>D: Sanitize URLs
    D->>B: Return sanitized URLs
    B->>E: Write markdown to file system
Loading

🐰 "In the land of Notion, where links do reside,
A function was crafted, to help them abide.
With a hop and a skip, internal links shine,
Sanitized and ready, oh how they align!
So let’s celebrate changes, both big and small,
For a rabbit's new journey, we welcome them all!" 🐇✨


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 4

🧹 Outside diff range and nitpick comments (2)
src/helpers/sanitize.mjs (1)

6-9: Consider using a comprehensive character mapping for special characters

The current implementation only handles a few German characters. Consider using a more comprehensive mapping object for better maintainability and coverage of other languages.

+const SPECIAL_CHARS_MAP = {
+  'ä': 'ae', 'ö': 'oe', 'ü': 'ue', 'ß': 'ss',
+  'á': 'a', 'é': 'e', 'í': 'i', 'ó': 'o', 'ú': 'u',
+  'à': 'a', 'è': 'e', 'ì': 'i', 'ò': 'o', 'ù': 'u',
+  // Add more mappings as needed
+};
+
 export function sanitizeUrl(str) {
   return str
     .normalize('NFD')
-    .replace(/[\u0300-\u036f]/g, "")
+    .replace(/([^\u0300-\u036f]|\n)/g, "$1")
     .toLowerCase()
-    .replace('ä', 'ae')
-    .replace('ö', 'oe')
-    .replace('ü', 'ue')
-    .replace('ß', 'ss')
+    .replace(/[äöüßáéíóúàèìòù]/g, char => SPECIAL_CHARS_MAP[char] || char)
     .replace(/[^a-z0-9]+/g, "-")
     .replace(/(^-|-$)+/g, "");
 }
src/helpers/links.mjs (1)

39-48: Add logging for unmatched internal links

Consider adding debug logging when internal links can't be matched to help diagnose issues.

         // find the page id in the pages array
         const page = pages.find(page => page.id === targetPageId);
         // if the page exists, replace the link with the page url
         if (page) {
             // this seems to be a bug in the original code. Some links have the title "link_to_page"
             if (title === "link_to_page") {
                 title = page.title;
             }
             mdString = mdString.replace(link, `[${title}](/posts/${page.slug})`);
+        } else if (targetPageId) {
+            console.warn(`No matching page found for internal link: ${targetPageId}`);
         }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 7d14630 and d5dd038.

📒 Files selected for processing (3)
  • src/astronot.js (2 hunks)
  • src/helpers/links.mjs (1 hunks)
  • src/helpers/sanitize.mjs (1 hunks)
🧰 Additional context used
🪛 Biome (1.9.4)
src/helpers/sanitize.mjs

[error] 4-4: A character class cannot match a character and a combining character.

A character and a combining character forms a new character. Replace the character class with an alternation.

(lint/suspicious/noMisleadingCharacterClass)

Comment on lines +3 to +4
.normalize('NFD') // decompose combined graphemes into base characters and diacritical marks
.replace(/[\u0300-\u036f]/g, "") // remove diacritical marks
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Fix the character class regex for diacritical marks removal

The current regex /[\u0300-\u036f]/g for removing diacritical marks has a potential issue with matching combined characters. Consider using a more robust approach.

-    .normalize('NFD') // decompose combined graphemes into base characters and diacritical marks
-    .replace(/[\u0300-\u036f]/g, "") // remove diacritical marks
+    .normalize('NFD')
+    .replace(/([^\u0300-\u036f]|\n)/g, "$1") // preserve base characters while removing combining marks

Committable suggestion skipped: line range outside the PR's diff.

🧰 Tools
🪛 Biome (1.9.4)

[error] 4-4: A character class cannot match a character and a combining character.

A character and a combining character forms a new character. Replace the character class with an alternation.

(lint/suspicious/noMisleadingCharacterClass)

Comment on lines +30 to +37
if (slug.startsWith("/") && slug.length === 33) {
// remove the leading "/" from the slug and add "-" like XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
targetPageId = slug.substring(1, 9) + "-" + slug.substring(9, 13) + "-" + slug.substring(13, 17) + "-" + slug.substring(17, 21) + "-" + slug.substring(21);
}
// block links are like XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX without the leading "/"
else if (slug.length === 36) {
targetPageId = slug;
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Simplify UUID formatting logic using regex

The current implementation manually formats the UUID string. Consider using regex for a more maintainable solution.

-        if (slug.startsWith("/") && slug.length === 33) {
-            // remove the leading "/" from the slug and add "-" like XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
-            targetPageId = slug.substring(1, 9) + "-" + slug.substring(9, 13) + "-" + slug.substring(13, 17) + "-" + slug.substring(17, 21) + "-" + slug.substring(21);
-        }
-        // block links are like XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX without the leading "/"
-        else if (slug.length === 36) {
-            targetPageId = slug;
-        }
+        const uuidPattern = /^(?:\/)?([0-9a-f]{8})([0-9a-f]{4})([0-9a-f]{4})([0-9a-f]{4})([0-9a-f]{12})$/i;
+        const match = slug.match(uuidPattern);
+        if (match) {
+            targetPageId = match.slice(1).join('-');
+        }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if (slug.startsWith("/") && slug.length === 33) {
// remove the leading "/" from the slug and add "-" like XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
targetPageId = slug.substring(1, 9) + "-" + slug.substring(9, 13) + "-" + slug.substring(13, 17) + "-" + slug.substring(17, 21) + "-" + slug.substring(21);
}
// block links are like XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX without the leading "/"
else if (slug.length === 36) {
targetPageId = slug;
}
const uuidPattern = /^(?:\/)?([0-9a-f]{8})([0-9a-f]{4})([0-9a-f]{4})([0-9a-f]{4})([0-9a-f]{12})$/i;
const match = slug.match(uuidPattern);
if (match) {
targetPageId = match.slice(1).join('-');
}

Comment on lines +12 to +15
const links = mdString.match(/\[.*?\]\(.*?\)/g);
if (!links) {
return mdString;
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Add error handling for malformed markdown links

The current regex pattern might fail with malformed markdown links. Consider adding error handling and using a more robust pattern.

 export function convertInternalLinks(mdString, pages) {
+    if (!mdString || typeof mdString !== 'string') {
+        throw new Error('mdString must be a non-empty string');
+    }
+    if (!Array.isArray(pages)) {
+        throw new Error('pages must be an array');
+    }
+
     // find all link url in markdown
-    const links = mdString.match(/\[.*?\]\(.*?\)/g);
+    const links = mdString.match(/\[([^\]]*)\]\(([^)]+)\)/g);
     if (!links) {
         return mdString;
     }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const links = mdString.match(/\[.*?\]\(.*?\)/g);
if (!links) {
return mdString;
}
if (!mdString || typeof mdString !== 'string') {
throw new Error('mdString must be a non-empty string');
}
if (!Array.isArray(pages)) {
throw new Error('pages must be an array');
}
// find all link url in markdown
const links = mdString.match(/\[([^\]]*)\]\(([^)]+)\)/g);
if (!links) {
return mdString;
}

Comment on lines +127 to +131
let { parent: mdString } = n2m.toMarkdownString(mdblocks);

const estimatedReadingTime = readingTime(mdString || '').text;

mdString = convertInternalLinks(mdString, pages);
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Add error handling for link conversion and update reading time calculation

The reading time should be calculated after converting internal links, and error handling should be added for the conversion process.

   const mdblocks = await n2m.pageToMarkdown(page.id);
   let { parent: mdString } = n2m.toMarkdownString(mdblocks);
 
-  const estimatedReadingTime = readingTime(mdString || '').text;
+  try {
+    mdString = convertInternalLinks(mdString, pages);
+  } catch (error) {
+    console.error(`Error converting internal links for page ${page.id}:`, error);
+    // Continue with original mdString
+  }
 
-  mdString = convertInternalLinks(mdString, pages);
+  const estimatedReadingTime = readingTime(mdString || '').text;
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
let { parent: mdString } = n2m.toMarkdownString(mdblocks);
const estimatedReadingTime = readingTime(mdString || '').text;
mdString = convertInternalLinks(mdString, pages);
let { parent: mdString } = n2m.toMarkdownString(mdblocks);
try {
mdString = convertInternalLinks(mdString, pages);
} catch (error) {
console.error(`Error converting internal links for page ${page.id}:`, error);
// Continue with original mdString
}
const estimatedReadingTime = readingTime(mdString || '').text;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant