How can I get all links from a post which are both external and internal

I am trying to add a “References” section at the bottom of each post. This would include a list of all the links which are external and internal (pointing to other blog posts on the same domain) but excluding any links that are linked to different sections in the current post.

Given a markdown as follows:

// in file first.md
+++
title = "First post"
+++

The second post can be found [here](@/second.md).

# Section1
Some text
Link to [section2](@/first.md#section2) of this post.

# Section2
Some text

Should render:

<main id="main" tabindex="-1">
   <article class="post">
      ....
      <h1>References</h1>
      <details>
          <summary style="display: list-item">View all references</summary>
          <ol>
            <li>
              <a href="/second">Second Post</a>
            </li>
         </ol>
      </details>
   </article>
</main>

As of right now, I have to manually add all references in the front-matter like this:

+++
[extra]
references = ["some-link-url", ...]
+++

And I have a macro that generates the HTML:

{%- macro references(page) %}
  {% if page.extra.references %}
  <h1>References</h1>
  <details>
    <summary style="display: list-item">View all references</summary>
    <ol>
      {% for reference in page.extra.references %}
        <li>
          <a href="{{reference.link}}">{{ reference.title }}</a>
        </li>
      {% endfor %}
    </ol>
  </details>
  {% endif %}
{%- endmacro references %}

We don’t keep track of that so your solution is likely the best

Great thanks.