Skip to content

Build your personal knowledge base with Trilium Notes

feat(import): resolve OneNote page-to-page links to Trilium note links

Elian Doran35473ad33c9f
diff --git a/apps/server/src/services/import/onenote/graph.ts b/apps/server/src/services/import/onenote/graph.ts
index 29976bf629..71e0a2ec4b 100644
--- a/apps/server/src/services/import/onenote/graph.ts
+++ b/apps/server/src/services/import/onenote/graph.ts
@@ -5,6 +5,8 @@
* Graph reference: https://learn.microsoft.com/en-us/graph/api/resources/onenote-api-overview
*/
+import { extractPageId } from "./links.js";
+
const GRAPH_BASE = "https://graph.microsoft.com/v1.0";
export interface GraphAccount {
@@ -28,6 +30,8 @@ export interface OneNotePage {
title: string;
createdDateTime?: string;
lastModifiedDateTime?: string;
+ /** The page-id GUID OneNote uses in `onenote:` links to this page; used to resolve cross-page links. */
+ pageId?: string;
}
export async function getAccount(accessToken: string): Promise<GraphAccount> {
@@ -58,13 +62,16 @@ export async function listNotebooks(accessToken: string): Promise<OneNoteNoteboo
}
export async function listPages(accessToken: string, sectionId: string): Promise<OneNotePage[]> {
- const url = `/me/onenote/sections/${sectionId}/pages?$select=id,title,createdDateTime,lastModifiedDateTime&$orderby=order&pagelevel=true`;
+ // `links` carries the page's own `onenote:` client URL, from which we recover the page-id GUID that
+ // cross-page links reference (see links.ts).
+ const url = `/me/onenote/sections/${sectionId}/pages?$select=id,title,createdDateTime,lastModifiedDateTime,links&$orderby=order&pagelevel=true`;
const raw = await graphGetAll<RawPage>(accessToken, url);
return raw.map((p) => ({
id: p.id,
title: p.title || "Untitled",
createdDateTime: p.createdDateTime,
- lastModifiedDateTime: p.lastModifiedDateTime
+ lastModifiedDateTime: p.lastModifiedDateTime,
+ pageId: extractPageId(p.links?.oneNoteClientUrl?.href) ?? undefined
}));
}
@@ -144,6 +151,7 @@ interface RawPage {
title?: string;
createdDateTime?: string;
lastModifiedDateTime?: string;
+ links?: { oneNoteClientUrl?: { href?: string } };
}
async function graphGet<T>(accessToken: string, path: string): Promise<T> {
diff --git a/apps/server/src/services/import/onenote/importer.ts b/apps/server/src/services/import/onenote/importer.ts
index 31f2ba85d3..886d7cbc77 100644
--- a/apps/server/src/services/import/onenote/importer.ts
+++ b/apps/server/src/services/import/onenote/importer.ts
@@ -5,13 +5,14 @@
* client-side import toasts apply unchanged.
*/
-import { becca, type BNote, binary_utils, getLog, imageService, note_service as noteService, protected_session as protectedSession, TaskContext } from "@triliumnext/core";
+import { becca, binary_utils, type BNote, getLog, imageService, note_service as noteService, protected_session as protectedSession, TaskContext } from "@triliumnext/core";
import { parse } from "node-html-parser";
import sql from "../../sql.js";
import converter, { ONENOTE_ATTACHMENT_CLASS } from "./converter.js";
import graph, { type OneNotePage } from "./graph.js";
import { inkmlToSvg } from "./inkml.js";
+import { rewritePageLinks } from "./links.js";
export interface SectionSelection {
id: string;
@@ -21,6 +22,8 @@ export interface SectionSelection {
interface FetchedPage {
title: string;
+ /** The OneNote page-id GUID, used to resolve cross-page links to the note created for this page. */
+ pageId?: string;
html: string;
/** The unmodified HTML returned by the Graph API, kept only when debug mode is on. */
rawHtml: string;
@@ -69,7 +72,7 @@ export async function importSelection({ accessToken, parentNoteId, sections, tas
const { html: rawHtml, inkml } = await graph.getPageContent(accessToken, page.id);
const html = converter.convertPageHtml(rawHtml);
const resources = await downloadPageResources(accessToken, html);
- fetchedPages.push({ title: page.title, html, rawHtml, rawInkml: inkml, inkSvg: inkmlToSvg(inkml), resources });
+ fetchedPages.push({ title: page.title, pageId: page.pageId, html, rawHtml, rawInkml: inkml, inkSvg: inkmlToSvg(inkml), resources });
taskContext.increaseProgressCount();
}
fetched.push({ title: section.title, notebookTitle: section.notebookTitle, pages: fetchedPages });
@@ -92,6 +95,11 @@ function createNotes(parentNoteId: string, sections: FetchedSection[], debug: bo
const rootNote = createFolder(parentNoteId, "OneNote import");
+ // Created page notes with their content-so-far (resources/ink applied), plus a map from each
+ // page's OneNote page-id GUID to the note created for it — both feed the link-resolution pass.
+ const createdPages: { note: BNote; original: string; content: string }[] = [];
+ const noteIdByPageId = new Map<string, string>();
+
// Group selected sections under a note per notebook so the original hierarchy is preserved.
const notebookNotes = new Map<string, string>();
for (const section of sections) {
@@ -114,8 +122,9 @@ function createNotes(parentNoteId: string, sections: FetchedSection[], debug: bo
});
// Resources and ink both need the page note to exist (attachments hang off it), so build
- // the final content once: swap Graph URLs for local attachment references, then append the
- // page's handwriting/drawing as an inline SVG image.
+ // the per-page content now: swap Graph URLs for local attachment references, then append
+ // the page's handwriting/drawing as an inline SVG image. Cross-page links are deferred to a
+ // second pass below, once every page has a note to point at.
let content = page.html;
if (page.resources.length > 0) {
content = rewritePageResources(pageNote, content, page.resources);
@@ -123,9 +132,10 @@ function createNotes(parentNoteId: string, sections: FetchedSection[], debug: bo
if (page.inkSvg) {
content += renderInkFigure(pageNote, page.inkSvg);
}
- if (content !== page.html) {
- pageNote.setContent(content);
- void noteService.asyncPostProcessContent(pageNote, content);
+
+ createdPages.push({ note: pageNote, original: page.html, content });
+ if (page.pageId) {
+ noteIdByPageId.set(page.pageId, pageNote.noteId);
}
// Debug aid: keep the unmodified Graph HTML (and InkML, when present) alongside the
@@ -149,6 +159,16 @@ function createNotes(parentNoteId: string, sections: FetchedSection[], debug: bo
}
}
+ // Second pass: now that every page has a note, resolve cross-page `onenote:` links and persist the
+ // final content. Done once per page (rather than re-saving for resources, then again for links).
+ for (const { note, original, content } of createdPages) {
+ const finalContent = rewritePageLinks(content, (pageId) => noteIdByPageId.get(pageId) ?? null);
+ if (finalContent !== original) {
+ note.setContent(finalContent);
+ void noteService.asyncPostProcessContent(note, finalContent);
+ }
+ }
+
return rootNote.noteId;
}
diff --git a/apps/server/src/services/import/onenote/links.spec.ts b/apps/server/src/services/import/onenote/links.spec.ts
new file mode 100644
index 0000000000..ef7af46889
--- /dev/null
+++ b/apps/server/src/services/import/onenote/links.spec.ts
@@ -0,0 +1,87 @@
+import { parse } from "node-html-parser";
+import { describe, expect, it } from "vitest";
+
+import converter from "./converter.js";
+import { extractPageId, rewritePageLinks } from "./links.js";
+
+// Real OneNote source (debug-captured): the "First page" links to "Second page" with an internal
+// `onenote:` link (carrying page-id) immediately followed by an external "Web view" https link.
+const FIRST_PAGE_SOURCE = `<html lang="en-US">
+ <body data-absolute-enabled="true" style="font-family:Calibri;font-size:11pt">
+ <div style="position:absolute;left:48px;top:115px;width:624px">
+ <p style="margin-top:0pt;margin-bottom:0pt">Go to <a href="onenote:#Second%20page&amp;section-id={4d9d9af6-7f91-4f16-956a-8bf2c330f6ab}&amp;page-id={eb2c4f67-8d3f-4fdb-a93b-32d6b3ba780d}&amp;end">Second page</a> (<a href="https://onedrive.live.com/personal/9b3de8eeb5fefd37/_layouts/15/Doc.aspx?sourcedoc=%7Bb9c20b8c%7D&amp;wd=target%28Link%20test.one%7C4d9d9af6%2FSecond%20page%7Ceb2c4f67-8d3f-4fdb-a93b-32d6b3ba780d%2F%29">Web view</a>)</p>
+ </div>
+ </body>
+</html>`;
+
+// The same page-id GUID appears in the page's own client URL (the bridge the importer uses to map a
+// page-id to a Graph page) and in a link targeting it.
+const SECOND_PAGE_GUID = "eb2c4f67-8d3f-4fdb-a93b-32d6b3ba780d";
+const SECOND_PAGE_CLIENT_URL = `onenote:https://d.docs.live.net/abc/Documents/Link%20test/Link%20test.one#Second%20page&section-id={4d9d9af6-7f91-4f16-956a-8bf2c330f6ab}&page-id={${SECOND_PAGE_GUID.toUpperCase()}}&end`;
+
+describe("extractPageId", () => {
+ it("pulls the lowercased page-id GUID from an internal link and from a client URL", () => {
+ expect(extractPageId(`onenote:#Second%20page&page-id={${SECOND_PAGE_GUID}}&end`)).toBe(SECOND_PAGE_GUID);
+ // A client URL carrying the GUID upper-cased is normalized to lowercase.
+ expect(extractPageId(SECOND_PAGE_CLIENT_URL)).toBe(SECOND_PAGE_GUID);
+ });
+
+ it("returns null when there is no page-id (web-view URL, external link, empty input)", () => {
+ // The "Web view" onedrive URL embeds the GUID inside wd=target(...), not as a page-id= param.
+ expect(extractPageId("https://onedrive.live.com/...wd=target%28Link.one%7Csec%2FSecond%7Ceb2c4f67-8d3f-4fdb-a93b-32d6b3ba780d%2F%29")).toBeNull();
+ expect(extractPageId("https://example.com")).toBeNull();
+ expect(extractPageId(null)).toBeNull();
+ expect(extractPageId(undefined)).toBeNull();
+ });
+});
+
+describe("rewritePageLinks", () => {
+ const linkHtml = (href: string, text: string) => `<p><a href="${href}">${text}</a></p>`;
+
+ it("rewrites an internal link whose target was imported into a Trilium note link, keeping the text", () => {
+ const html = linkHtml(`onenote:#Second%20page&page-id={${SECOND_PAGE_GUID}}&end`, "Second page");
+ const out = rewritePageLinks(html, (pageId) => (pageId === SECOND_PAGE_GUID ? "noteABC123" : null));
+
+ const anchor = parse(out).querySelector("a");
+ expect(anchor?.getAttribute("href")).toBe("#root/noteABC123");
+ expect(anchor?.textContent).toBe("Second page");
+ });
+
+ it("leaves a link untouched when its target was not imported", () => {
+ const html = linkHtml(`onenote:#Other&page-id={${SECOND_PAGE_GUID}}&end`, "Other");
+ // resolve always returns null -> nothing changes, and the input is returned verbatim.
+ expect(rewritePageLinks(html, () => null)).toBe(html);
+ });
+
+ it("never touches non-onenote links (external / web-view) or link-free content", () => {
+ const webView = linkHtml("https://onedrive.live.com/...", "Web view");
+ expect(rewritePageLinks(webView, () => "noteABC123")).toBe(webView);
+ expect(rewritePageLinks("<p>no links here</p>", () => "noteABC123")).toBe("<p>no links here</p>");
+ });
+
+ it("resolves each link independently in mixed content", () => {
+ const html =
+ linkHtml(`onenote:#A&page-id={11111111-1111-1111-1111-111111111111}&end`, "A") +
+ linkHtml(`onenote:#B&page-id={22222222-2222-2222-2222-222222222222}&end`, "B") +
+ linkHtml("https://example.com", "external");
+ const out = rewritePageLinks(html, (pageId) => (pageId.startsWith("11111111") ? "noteA" : null));
+
+ const hrefs = parse(out).querySelectorAll("a").map((a) => a.getAttribute("href"));
+ expect(hrefs).toEqual(["#root/noteA", "onenote:#B&page-id={22222222-2222-2222-2222-222222222222}&end", "https://example.com"]);
+ });
+});
+
+// Guards the load-bearing assumption that the sanitizer keeps the `onenote:` href (the scheme is in
+// ALLOWED_PROTOCOLS): the importer rewrites links on the *converted* HTML, so if conversion dropped
+// the href, cross-page links would silently never resolve.
+describe("convertPageHtml + rewritePageLinks (end to end)", () => {
+ it("preserves the onenote link through conversion so it can be resolved afterwards", () => {
+ const converted = converter.convertPageHtml(FIRST_PAGE_SOURCE);
+ expect(extractPageId(parse(converted).querySelector("a")?.getAttribute("href"))).toBe(SECOND_PAGE_GUID);
+
+ const out = rewritePageLinks(converted, (pageId) => (pageId === SECOND_PAGE_GUID ? "noteABC123" : null));
+ const anchors = parse(out).querySelectorAll("a");
+ expect(anchors[0]?.getAttribute("href")).toBe("#root/noteABC123"); // internal link resolved
+ expect(anchors[1]?.getAttribute("href")).toContain("onedrive.live.com"); // web-view link untouched
+ });
+});
diff --git a/apps/server/src/services/import/onenote/links.ts b/apps/server/src/services/import/onenote/links.ts
new file mode 100644
index 0000000000..c93535051f
--- /dev/null
+++ b/apps/server/src/services/import/onenote/links.ts
@@ -0,0 +1,49 @@
+/**
+ * Resolves OneNote page-to-page hyperlinks against the notes created by an import.
+ *
+ * OneNote stores an internal link as an `onenote:` anchor carrying the target's identity in a
+ * `page-id={GUID}` query parameter, e.g.
+ * `onenote:#Second%20page&section-id={…}&page-id={eb2c4f67-…}&end`
+ * That GUID is NOT the Graph page `id` (a composite like `0-{guid}!{n}-{guid}`); the bridge between the
+ * two is the page's own `links.oneNoteClientUrl`, which embeds the same `page-id={GUID}`. So the
+ * importer builds a `page-id GUID → noteId` map from each imported page's client URL, then rewrites
+ * every `onenote:` link whose target was imported into a Trilium internal link.
+ *
+ * Both pure functions here (extractPageId, rewritePageLinks) are deliberately free of any DB/Graph
+ * dependency so the two-pass resolution can be unit-tested with a plain resolver callback.
+ */
+
+import { parse } from "node-html-parser";
+
+/** Pulls the OneNote page-id GUID out of a link/URL, lowercased; null if there is none. */
+export function extractPageId(url: string | null | undefined): string | null {
+ const match = url?.match(/page-id=\{?([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\}?/i);
+ return match ? match[1].toLowerCase() : null;
+}
+
+/**
+ * Rewrites the page's `onenote:` internal links: a link whose target page-id resolves (via `resolve`)
+ * to an imported note becomes a Trilium internal link (`#root/{noteId}`) with its original text kept;
+ * links to pages outside the import — and all non-`onenote:` links (e.g. the "Web view" https link) —
+ * are left untouched. Returns the input unchanged when nothing was rewritten, so callers can cheaply
+ * detect a no-op.
+ */
+export function rewritePageLinks(html: string, resolve: (pageId: string) => string | null): string {
+ const root = parse(html);
+ let changed = false;
+
+ for (const anchor of root.querySelectorAll("a")) {
+ const href = anchor.getAttribute("href") ?? "";
+ if (!href.startsWith("onenote:")) {
+ continue;
+ }
+ const pageId = extractPageId(href);
+ const noteId = pageId ? resolve(pageId) : null;
+ if (noteId) {
+ anchor.setAttribute("href", `#root/${noteId}`);
+ changed = true;
+ }
+ }
+
+ return changed ? root.toString() : html;
+}