Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
refactor(docs): point the help consumers at the generated tree
Elian Doranad4c8b12308f
diff --git a/apps/client/src/services/in_app_help.spec.ts b/apps/client/src/services/in_app_help.spec.tsindex c11abdbefb..16ca1dd0d6 100644--- a/apps/client/src/services/in_app_help.spec.ts+++ b/apps/client/src/services/in_app_help.spec.ts@@ -1,7 +1,7 @@import { describe, expect, it } from "vitest";import { byBookType, byNoteType, getHelpUrlForNote } from "./in_app_help.js";import fs from "fs";-import type { HiddenSubtreeItem } from "@triliumnext/commons";+import type { HelpMetaItem, HiddenSubtreeItem } from "@triliumnext/commons";import path from "path";import { buildNote } from "../test/easy-froca.js";import type FNote from "../entities/fnote.js";@@ -27,9 +27,7 @@ describe("Help button", () => {...Object.values(byBookType)].filter((noteId) => noteId) as string[];- const metaPath = path.resolve(path.join(__dirname, "../../../server/src/assets/doc_notes/en/User Guide/!!!meta.json"));- const meta: HiddenSubtreeItem[] = JSON.parse(fs.readFileSync(metaPath, "utf-8"));- const allNoteIds = new Set(getNoteIds(meta));+ const allNoteIds = new Set(getNoteIds(readHelpMeta() as unknown as HiddenSubtreeItem[]));for (const helpNote of allHelpNotes) {if (!allNoteIds.has(`_help_${helpNote}`)) {@@ -38,108 +36,92 @@ describe("Help button", () => {}});- // The in-app help client (doc_renderer.ts) requests `doc_notes/<lang>/<docName>.html`, and the- // server filesystem is case-sensitive. A doc whose title casing was changed on a case-insensitive- // OS (Windows/macOS) can be committed with a stale-cased filename that git's core.ignorecase hides,- // so the meta points at one casing while the file on disk has another → 404 in production.- it("Every docName resolves to an on-disk file with exact casing", () => {- const docNotesEnRoot = path.resolve(path.join(__dirname, "../../../server/src/assets/doc_notes/en"));- const meta: HiddenSubtreeItem[] = JSON.parse(fs.readFileSync(path.join(docNotesEnRoot, "User Guide/!!!meta.json"), "utf-8"));-- const problems: string[] = [];- for (const docName of collectDocNames(meta)) {- if (!existsWithExactCase(docNotesEnRoot, `${docName}.html`)) {- problems.push(docName);- }- }+ // Every help note is built from the markdown file its `source` names, and the server filesystem+ // is case-sensitive. A page whose title casing was changed on a case-insensitive OS+ // (Windows/macOS) can be committed with a stale-cased filename that git's core.ignorecase hides,+ // so the meta points at one casing while the file on disk has another → the page ships empty.+ it("Every source resolves to an on-disk file with exact casing", () => {+ const problems = collectSources(readHelpMeta())+ .filter((source) => !existsWithExactCase(DOCS_ROOT, source));if (problems.length) {expect.fail(- `The following help docNames do not resolve to an on-disk .html file with exact casing ` ++ `The following help sources do not resolve to an on-disk file with exact casing ` +`(the meta and the committed filename disagree — likely a case-only rename dropped by git core.ignorecase):\n` +problems.map((p) => ` - ${p}`).join("\n"));}});- // Internal help links are `href="#root/<notePath>/_help_<noteId>"`. If the target `_help_` note is- // not exported into the in-app help (e.g. a link into the Technical Guide subtree, which lives in- // docs/ but is not shipped as doc_notes), the link dead-ends — the export renders it as- // "[missing note]". Links whose last segment is NOT a `_help_` note (e.g. `#root/_hidden/_options/…`)- // are intentional runtime deep-links to real system notes and are deliberately not validated here.- it("Every internal help link points to an existing help note", () => {- const docNotesEnRoot = path.resolve(path.join(__dirname, "../../../server/src/assets/doc_notes/en"));- const meta: HiddenSubtreeItem[] = JSON.parse(fs.readFileSync(path.join(docNotesEnRoot, "User Guide/!!!meta.json"), "utf-8"));- const definedIds = new Set(collectHelpIds(meta));+ // Help pages link to each other by relative markdown path. If the target is not part of the+ // in-app help (e.g. a link into the Technical Guide subtree, which lives in docs/ but is not+ // shipped), the link dead-ends once the pages are rendered. `#root/…` hrefs are intentional+ // runtime deep-links to real system notes and are deliberately not validated here.+ it("Every internal help link points to a page that ships with the help", () => {+ const meta = readHelpMeta();+ const shipped = new Set(collectSources(meta).map(normalizeSourcePath));const broken: string[] = [];- for (const htmlFile of collectHtmlFiles(docNotesEnRoot)) {- const html = fs.readFileSync(htmlFile, "utf-8");- const relFile = path.relative(docNotesEnRoot, htmlFile);- // Match anchors so the failure message can quote the link text (often "[missing note]").- for (const match of html.matchAll(/<a\b[^>]*href="#root\/([^"]+)"[^>]*>(.*?)<\/a>/gs)) {- const notePath = match[1].split(/[#?]/)[0];- const target = notePath.split("/").pop() ?? "";- if (target.startsWith("_help_") && !definedIds.has(target)) {- broken.push(`${relFile}: "${match[2].trim()}" -> ${target}`);+ for (const source of collectSources(meta)) {+ const markdown = fs.readFileSync(path.join(DOCS_ROOT, source), "utf-8");+ for (const match of markdown.matchAll(/<a\b[^>]*class="reference-link"[^>]*href="([^"]+)"[^>]*>(.*?)<\/a>/gs)) {+ const href = decodeURIComponent(match[1].split(/[#?]/)[0]);+ if (href.startsWith("#root/")) {+ continue;+ }++ const target = normalizeSourcePath(path.posix.join(path.posix.dirname(toPosix(source)), href));++ // Markdown targets must be pages of the guide; anything else (an attachment such as+ // a .dat or .js file, or a folder) only has to exist on disk.+ const resolves = href.endsWith(".md")+ ? shipped.has(target)+ : existsWithExactCase(DOCS_ROOT, target) || existsWithExactCase(DOCS_ROOT, `${target}.md`);++ if (!resolves) {+ broken.push(`${source}: "${match[2].trim()}" -> ${href}`);}}}if (broken.length) {expect.fail(- `The following in-app help links point to notes that are not part of the in-app help ` +- `(the target is not in !!!meta.json, so it renders as "[missing note]"). Either export the ` +- `target page into the help tree or remove/repoint the link:\n` ++ `The following in-app help links point to pages that are not part of the in-app help. ` ++ `Either bring the target page into the help tree or remove/repoint the link:\n` +broken.map((b) => ` - ${b}`).join("\n"));}});});-/** Collects every `_help_*` note id defined in the help meta tree. */-function collectHelpIds(items: HiddenSubtreeItem[]): string[] {- const ids: string[] = [];- for (const item of items) {- if (item.id) {- ids.push(item.id);- }- if (item.children) {- ids.push(...collectHelpIds(item.children as HiddenSubtreeItem[]));- }- }- return ids;-}+/** Root of the markdown the in-app help is built from. */+const DOCS_ROOT = path.resolve(path.join(__dirname, "../../../../docs/User Guide"));-/** Recursively lists every `.html` file under `dir`. */-function collectHtmlFiles(dir: string): string[] {- const files: string[] = [];- for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {- const full = path.join(dir, entry.name);- if (entry.isDirectory()) {- files.push(...collectHtmlFiles(full));- } else if (entry.name.endsWith(".html")) {- files.push(full);- }- }- return files;+/** The help tree as `edit-docs` writes it. */+function readHelpMeta(): HelpMetaItem[] {+ const metaPath = path.resolve(path.join(__dirname, "../../../server/src/assets/help/help_meta.json"));+ return JSON.parse(fs.readFileSync(metaPath, "utf-8"));}-/** Collects every `docName` label value from the help meta tree. */-function collectDocNames(items: HiddenSubtreeItem[]): string[] {- const docNames: string[] = [];+/** Collects the source file of every help page that has one. */+function collectSources(items: HelpMetaItem[]): string[] {+ const sources: string[] = [];for (const item of items) {- const docName = item.attributes?.find((a) => a.name === "docName")?.value;- if (docName) {- docNames.push(docName);+ if (item.source) {+ sources.push(item.source);}if (item.children) {- docNames.push(...collectDocNames(item.children as HiddenSubtreeItem[]));+ sources.push(...collectSources(item.children));}}- return docNames;+ return sources;}+const toPosix = (filePath: string) => filePath.split(path.sep).join("/");++/** Sources are compared as posix paths so link targets and meta entries line up on Windows too. */+const normalizeSourcePath = (filePath: string) => path.posix.normalize(toPosix(filePath));+/*** Resolves `relativePath` under `rootDir` one segment at a time via `readdirSync`, which reports the* real on-disk names regardless of filesystem case sensitivity. `fs.existsSync` alone would wronglydiff --git a/apps/edit-docs/package.json b/apps/edit-docs/package.jsonindex afd40dec12..0f00478b33 100644--- a/apps/edit-docs/package.json+++ b/apps/edit-docs/package.json@@ -19,6 +19,6 @@"test": "vitest","test-build": "vitest --config vitest.build.config.mts","edit-docs": "cross-env TRILIUM_PORT=37741 TRILIUM_DATA_DIR=data TRILIUM_INTEGRATION_TEST=memory-no-store tsx ../../scripts/electron-start.mts src/edit-docs.ts",- "edit-demo": "cross-env TRILIUM_PORT=37744 TRILIUM_DATA_DIR=data TRILIUM_INTEGRATION_TEST=memory-no-store DOCS_ROOT=../../../docs USER_GUIDE_ROOT=\"../../server/src/assets/doc_notes/en/User Guide\" tsx ../../scripts/electron-start.mts src/edit-demo.ts"+ "edit-demo": "cross-env TRILIUM_PORT=37744 TRILIUM_DATA_DIR=data TRILIUM_INTEGRATION_TEST=memory-no-store DOCS_ROOT=../../../docs tsx ../../scripts/electron-start.mts src/edit-demo.ts"}}\ No newline at end of filediff --git a/apps/server/src/in_app_help_provider.ts b/apps/server/src/in_app_help_provider.tsindex 1a5299100a..978e893fa1 100644--- a/apps/server/src/in_app_help_provider.ts+++ b/apps/server/src/in_app_help_provider.ts@@ -8,8 +8,8 @@ import { RESOURCE_DIR } from "./services/resource_dir.js";export default class NodejsInAppHelpProvider extends InAppHelpProvider {getHelpHiddenSubtreeData(): HiddenSubtreeItem[] {- const helpDir = path.join(RESOURCE_DIR, "doc_notes", "en", "User Guide");- const metaFilePath = path.join(helpDir, "!!!meta.json");+ // Written by edit-docs from the User Guide's markdown export; see apps/edit-docs.+ const metaFilePath = path.join(RESOURCE_DIR, "help", "help_meta.json");try {return JSON.parse(fs.readFileSync(metaFilePath).toString("utf-8"));diff --git a/apps/standalone/vite.config.mts b/apps/standalone/vite.config.mtsindex bab636e230..9f99d73166 100644--- a/apps/standalone/vite.config.mts+++ b/apps/standalone/vite.config.mts@@ -130,9 +130,7 @@ let plugins: any = [targets: [{src: [- "../../server/src/assets/**/*",- // Exclude the User Guide (~20 MB) since it's not needed in standalone mode.- "!../../server/src/assets/doc_notes/en/User Guide/**"+ "../../server/src/assets/**/*"],dest: "server-assets",rename: { stripBase: 3 }