From 899fb8a22ec4a23f29ce7b50dae2b305c28d4dc5 Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Fri, 4 Sep 2026 08:15:07 -0400 Subject: [PATCH] feat: Add Open Knowledge Format (OKF) export (#13644) * feat: Add Open Knowledge Format (OKF) export Co-Authored-By: Claude Fable 5.1 * Separate OKF frontmatter from body, use team URL for resource Co-Authored-By: Claude Fable 5.1 * Use OKF initials avatar in export dialog Co-Authored-By: Claude Fable 5.1 * Use GlobeIcon for OKF export format Co-Authored-By: Claude Fable 5.1 --------- Co-authored-by: Claude Fable 5.1 --- app/components/Export/ExportDialog.tsx | 8 +- .../components/FileOperationListItem.tsx | 1 + server/models/helpers/OKFHelper.ts | 114 ++++++++++++ .../FileOperationCreatedProcessor.ts | 6 + server/queues/tasks/ExportDocumentTreeTask.ts | 117 +++++++++--- server/queues/tasks/ExportOKFZipTask.test.ts | 174 ++++++++++++++++++ server/queues/tasks/ExportOKFZipTask.ts | 31 ++++ shared/types.ts | 1 + 8 files changed, 429 insertions(+), 23 deletions(-) create mode 100644 server/models/helpers/OKFHelper.ts create mode 100644 server/queues/tasks/ExportOKFZipTask.test.ts create mode 100644 server/queues/tasks/ExportOKFZipTask.ts diff --git a/app/components/Export/ExportDialog.tsx b/app/components/Export/ExportDialog.tsx index ff4eef7921..80e1ea5dae 100644 --- a/app/components/Export/ExportDialog.tsx +++ b/app/components/Export/ExportDialog.tsx @@ -1,5 +1,5 @@ import { observer } from "mobx-react"; -import { ArchiveIcon, CodeIcon } from "outline-icons"; +import { ArchiveIcon, CodeIcon, GlobeIcon } from "outline-icons"; import * as React from "react"; import { useTranslation } from "react-i18next"; import styled from "styled-components"; @@ -72,6 +72,12 @@ export const ExportDialog = observer(({ collection, onSubmit }: Props) => { value: FileOperationFormat.MarkdownZip, icon: , }, + { + title: "Open Knowledge Format", + extension: ".okf.zip", + value: FileOperationFormat.OKFZip, + icon: , + }, { title: "HTML", extension: ".html.zip", diff --git a/app/scenes/Settings/components/FileOperationListItem.tsx b/app/scenes/Settings/components/FileOperationListItem.tsx index 33df9f6058..c64b072045 100644 --- a/app/scenes/Settings/components/FileOperationListItem.tsx +++ b/app/scenes/Settings/components/FileOperationListItem.tsx @@ -57,6 +57,7 @@ const FileOperationListItem = ({ fileOperation }: Props) => { [FileOperationFormat.JSON]: "JSON", [FileOperationFormat.Notion]: "Notion", [FileOperationFormat.MarkdownZip]: "Markdown", + [FileOperationFormat.OKFZip]: "OKF", [FileOperationFormat.HTMLZip]: "HTML", [FileOperationFormat.TextBundleZip]: "TextBundle", [FileOperationFormat.PDF]: "PDF", diff --git a/server/models/helpers/OKFHelper.ts b/server/models/helpers/OKFHelper.ts new file mode 100644 index 0000000000..42c961ed83 --- /dev/null +++ b/server/models/helpers/OKFHelper.ts @@ -0,0 +1,114 @@ +import yaml from "js-yaml"; +import type Document from "@server/models/Document"; + +interface Frontmatter { + type: string; + title: string; + description?: string; + resource: string; + status: "draft" | "stable" | "deprecated"; + generated: { by: string; at: string }; +} + +interface IndexEntry { + /** The display name of the entry. */ + title: string; + /** The path of the entry relative to the index file. */ + path: string; + /** A short description of the entry, if any. */ + description?: string | null; +} + +/** + * Helpers for writing documents in the Open Knowledge Format (OKF), a bundle + * of markdown files with YAML frontmatter. + * + * @see https://github.com/GoogleCloudPlatform/knowledge-catalog/blob/main/okf/SPEC.md + */ +export default class OKFHelper { + /** The version of the specification the exported bundle targets. */ + public static readonly version = "0.2"; + + /** Name of the directory listing entry. */ + public static readonly indexFileName = "index.md"; + + /** File names that may not be used for a concept document. */ + public static readonly reservedFileNames = ["index.md", "log.md"]; + + /** The concept type written to every exported document. */ + public static readonly conceptType = "Document"; + + /** + * Whether a file name is reserved by the format and cannot hold a document. + * + * @param fileName The file name, without any directory. + * @returns true if the name is reserved. + */ + public static isReservedFileName(fileName: string): boolean { + return this.reservedFileNames.includes(fileName.toLowerCase()); + } + + /** + * Builds the frontmatter block that precedes a document's markdown body. + * + * @param document The document being exported. + * @param origin The origin of the team's URL, used to build the canonical + * URL of the document. + * @returns The YAML frontmatter, including delimiters and a trailing blank + * line that separates it from the body. + */ + public static frontmatter(document: Document, origin: string): string { + const description = this.singleLine(document.getSummary()); + const actor = document.updatedBy ?? document.createdBy; + + const data: Frontmatter = { + type: this.conceptType, + title: document.titleWithDefault, + ...(description ? { description } : {}), + resource: `${origin}${document.path}`, + status: this.status(document), + generated: { + by: `human:${actor.email ?? actor.id}`, + at: document.updatedAt.toISOString(), + }, + }; + + return this.serialize(data); + } + + /** + * Builds the bundle-root index that declares the format version and lists + * the top-level entries of the bundle. + * + * @param heading The heading the entries are grouped under. + * @param entries The entries to list. + * @returns The contents of the root index.md. + */ + public static rootIndex(heading: string, entries: IndexEntry[]): string { + const lines = entries.map((entry) => { + const description = this.singleLine(entry.description); + const link = `[${entry.title}](${encodeURI(entry.path)})`; + return description ? `* ${link} - ${description}` : `* ${link}`; + }); + + return `${this.serialize({ okf_version: this.version })}# ${heading}\n\n${lines.join("\n")}\n`; + } + + private static status(document: Document): "draft" | "stable" | "deprecated" { + if (document.archivedAt) { + return "deprecated"; + } + if (!document.publishedAt) { + return "draft"; + } + return "stable"; + } + + private static singleLine(value?: string | null): string { + return (value ?? "").replace(/\s+/g, " ").trim(); + } + + private static serialize(data: object): string { + return `---\n${yaml.dump(data, { lineWidth: -1, noRefs: true })}---\n\n`; + } +} diff --git a/server/queues/processors/FileOperationCreatedProcessor.ts b/server/queues/processors/FileOperationCreatedProcessor.ts index 598b352b7e..a128ed7c20 100644 --- a/server/queues/processors/FileOperationCreatedProcessor.ts +++ b/server/queues/processors/FileOperationCreatedProcessor.ts @@ -4,6 +4,7 @@ import type { Event as TEvent, FileOperationEvent } from "@server/types"; import ExportHTMLZipTask from "../tasks/ExportHTMLZipTask"; import ExportJSONTask from "../tasks/ExportJSONTask"; import ExportMarkdownZipTask from "../tasks/ExportMarkdownZipTask"; +import ExportOKFZipTask from "../tasks/ExportOKFZipTask"; import ExportTextBundleZipTask from "../tasks/ExportTextBundleZipTask"; import BaseProcessor from "./BaseProcessor"; @@ -33,6 +34,11 @@ export default class FileOperationCreatedProcessor extends BaseProcessor { fileOperationId: event.modelId, }); break; + case FileOperationFormat.OKFZip: + await new ExportOKFZipTask().schedule({ + fileOperationId: event.modelId, + }); + break; case FileOperationFormat.TextBundleZip: await new ExportTextBundleZipTask().schedule({ fileOperationId: event.modelId, diff --git a/server/queues/tasks/ExportDocumentTreeTask.ts b/server/queues/tasks/ExportDocumentTreeTask.ts index e803fae5d7..3a39fa9559 100644 --- a/server/queues/tasks/ExportDocumentTreeTask.ts +++ b/server/queues/tasks/ExportDocumentTreeTask.ts @@ -8,8 +8,10 @@ import Logger from "@server/logging/Logger"; import type { Collection } from "@server/models"; import Attachment from "@server/models/Attachment"; import Document from "@server/models/Document"; +import Team from "@server/models/Team"; import { DocumentHelper } from "@server/models/helpers/DocumentHelper"; import HTMLHelper from "@server/models/helpers/HTMLHelper"; +import OKFHelper from "@server/models/helpers/OKFHelper"; import { ProsemirrorHelper } from "@server/models/helpers/ProsemirrorHelper"; import TextBundleHelper from "@server/models/helpers/TextBundleHelper"; import { sequelizeReadOnly } from "@server/storage/database"; @@ -52,6 +54,7 @@ export default abstract class ExportDocumentTreeTask extends ExportTask { format, includeAttachments, pathMap, + origin, }: { zip: ZipFile; pathInZip: string; @@ -59,6 +62,7 @@ export default abstract class ExportDocumentTreeTask extends ExportTask { format: FileOperationFormat; includeAttachments: boolean; pathMap: Map; + origin?: string; }) { Logger.debug("task", `Adding document to archive`, { documentId }); const result = await sequelizeReadOnly.transaction(async (transaction) => { @@ -211,6 +215,12 @@ export default abstract class ExportDocumentTreeTask extends ExportTask { ); } + // OKF frontmatter carries the document's canonical URL, so it is added + // only after internal links have been rewritten to relative paths. + if (format === FileOperationFormat.OKFZip && origin) { + text = OKFHelper.frontmatter(document, origin) + text; + } + // Finally, add the document to the zip file zip.addBuffer(Buffer.from(text), textPathInZip, { mtime: document.updatedAt, @@ -237,15 +247,33 @@ export default abstract class ExportDocumentTreeTask extends ExportTask { format: FileOperationFormat, includeAttachments = true ) { - const pathMap = this.createPathMap(collections, format); - return await ZipHelper.toTmpFile((zip) => - this.addDocumentsToArchive({ + const { pathMap, roots } = this.createPathMap(collections, format); + const origin = await this.originForFormat(format, collections[0]?.teamId); + return await ZipHelper.toTmpFile(async (zip) => { + await this.addDocumentsToArchive({ zip, pathMap, format, includeAttachments, - }) - ); + origin, + }); + + if (format === FileOperationFormat.OKFZip) { + zip.addBuffer( + Buffer.from( + OKFHelper.rootIndex( + "Collections", + roots.map(({ root, collection }) => ({ + title: collection.name, + path: `${root}/`, + description: collection.description, + })) + ) + ), + OKFHelper.indexFileName + ); + } + }); } protected async addDocumentToArchive({ @@ -262,28 +290,63 @@ export default abstract class ExportDocumentTreeTask extends ExportTask { const pathMap = new Map(); const rootFolderName = serializeFilename(document.titleWithDefault); + const rootPath = `${rootFolderName}.${ExportDocumentTreeTask.extensionForFormat(format)}`; // entry for root document - pathMap.set( - document.path, - `${rootFolderName}.${ExportDocumentTreeTask.extensionForFormat(format)}` - ); + pathMap.set(document.path, rootPath); this.addDocumentTreeToPathMap( pathMap, documentStructure, - serializeFilename(document.titleWithDefault), + rootFolderName, format ); - return await ZipHelper.toTmpFile((zip) => - this.addDocumentsToArchive({ + const origin = await this.originForFormat(format, document.teamId); + return await ZipHelper.toTmpFile(async (zip) => { + await this.addDocumentsToArchive({ zip, pathMap, format, includeAttachments, - }) - ); + origin, + }); + + if (format === FileOperationFormat.OKFZip) { + zip.addBuffer( + Buffer.from( + OKFHelper.rootIndex("Documents", [ + { + title: document.titleWithDefault, + path: rootPath, + description: document.getSummary(), + }, + ]) + ), + OKFHelper.indexFileName + ); + } + }); + } + + /** + * Resolves the origin used for canonical document URLs, which only the OKF + * format writes into its output. + * + * @param format The format to export in + * @param teamId The team that owns the exported documents + * @returns The team's URL origin, or undefined when the format has no use for it. + */ + private async originForFormat( + format: FileOperationFormat, + teamId?: string + ): Promise { + if (format !== FileOperationFormat.OKFZip || !teamId) { + return undefined; + } + + const team = await Team.findByPk(teamId, { rejectOnEmpty: true }); + return team.url; } /** @@ -293,17 +356,20 @@ export default abstract class ExportDocumentTreeTask extends ExportTask { * @param pathMap Map of document urls to their path in the zip * @param format The format to export in * @param includeAttachments Whether to include attachments in the export + * @param origin The origin for canonical document URLs, when the format needs one */ private async addDocumentsToArchive({ zip, pathMap, format, includeAttachments, + origin, }: { zip: ZipFile; pathMap: Map; format: FileOperationFormat; includeAttachments: boolean; + origin?: string; }) { const processedPaths = new Set(); @@ -324,6 +390,7 @@ export default abstract class ExportDocumentTreeTask extends ExportTask { includeAttachments, format, pathMap, + origin, }); } @@ -335,25 +402,26 @@ export default abstract class ExportDocumentTreeTask extends ExportTask { * * @param collections The collections to generate the path map for. * @param format The format of the exported documents. + * @returns The path map and the root directory chosen for each collection. */ private createPathMap( collections: Collection[], format: FileOperationFormat ) { - const map = new Map(); - const usedRoots = new Set(); + const pathMap = new Map(); + const roots: { root: string; collection: Collection }[] = []; for (const collection of collections) { if (collection.documentStructure) { let root = serializeFilename(collection.name); let i = 0; - while (usedRoots.has(root)) { + while (roots.some((entry) => entry.root === root)) { root = `${serializeFilename(collection.name)} (${++i})`; } - usedRoots.add(root); + roots.push({ root, collection }); this.addDocumentTreeToPathMap( - map, + pathMap, collection.documentStructure, root, format @@ -361,7 +429,7 @@ export default abstract class ExportDocumentTreeTask extends ExportTask { } } - return map; + return { pathMap, roots }; } private addDocumentTreeToPathMap( @@ -375,10 +443,15 @@ export default abstract class ExportDocumentTreeTask extends ExportTask { const extension = ExportDocumentTreeTask.extensionForFormat(format); // Ensure the document is given a unique path in zip, even if it has - // the same title as another document in the same collection. + // the same title as another document in the same collection. OKF also + // reserves some file names, which a document may not take. let i = 0; let filePath = path.join(root, `${title}.${extension}`); - while (Array.from(map.values()).includes(filePath)) { + while ( + Array.from(map.values()).includes(filePath) || + (format === FileOperationFormat.OKFZip && + OKFHelper.isReservedFileName(path.basename(filePath))) + ) { filePath = path.join(root, `${title} (${++i}).${extension}`); } diff --git a/server/queues/tasks/ExportOKFZipTask.test.ts b/server/queues/tasks/ExportOKFZipTask.test.ts new file mode 100644 index 0000000000..d2b8735fc2 --- /dev/null +++ b/server/queues/tasks/ExportOKFZipTask.test.ts @@ -0,0 +1,174 @@ +import fs from "fs-extra"; +import yaml from "js-yaml"; +import ZipHelper from "@server/utils/ZipHelper"; +import { + buildCollection, + buildDocument, + buildFileOperation, + buildTeam, + buildUser, +} from "@server/test/factories"; +import ExportOKFZipTask from "./ExportOKFZipTask"; + +describe("ExportOKFZipTask", () => { + it("should write frontmatter and a root index", async () => { + const team = await buildTeam(); + const user = await buildUser({ teamId: team.id }); + const collection = await buildCollection({ + teamId: team.id, + createdById: user.id, + description: "About the collection", + }); + const document = await buildDocument({ + teamId: team.id, + userId: user.id, + collectionId: collection.id, + title: "Test1", + text: "First line of body", + }); + await collection.addDocumentToStructure(document); + const fileOperation = await buildFileOperation({ + teamId: team.id, + userId: user.id, + }); + + const task = new ExportOKFZipTask(); + const filePath = await task.exportCollections([collection], fileOperation); + + try { + const contents = await readZipContents(filePath); + expect(Object.keys(contents).sort()).toEqual( + [`${collection.name}/Test1.md`, "index.md"].sort() + ); + + const [frontmatter, body] = splitFrontmatter( + contents[`${collection.name}/Test1.md`] + ); + expect(frontmatter).toMatchObject({ + type: "Document", + title: "Test1", + description: "First line of body", + status: "stable", + generated: { + by: `human:${user.email}`, + at: document.updatedAt.toISOString(), + }, + }); + expect(frontmatter.resource).toBe(`${team.url}${document.path}`); + expect(body.startsWith("\n")).toBe(true); + expect(body).toContain("First line of body"); + + const [indexFrontmatter, indexBody] = splitFrontmatter( + contents["index.md"] + ); + expect(indexFrontmatter).toEqual({ okf_version: "0.2" }); + expect(indexBody.startsWith("\n# Collections\n")).toBe(true); + expect(indexBody).toContain( + `* [${collection.name}](${encodeURI(collection.name)}/) - About the collection` + ); + } finally { + await fs.remove(filePath); + } + }); + + it("should not use reserved file names for documents", async () => { + const team = await buildTeam(); + const user = await buildUser({ teamId: team.id }); + const collection = await buildCollection({ + teamId: team.id, + createdById: user.id, + }); + const document = await buildDocument({ + teamId: team.id, + userId: user.id, + collectionId: collection.id, + title: "index", + }); + await collection.addDocumentToStructure(document); + const fileOperation = await buildFileOperation({ + teamId: team.id, + userId: user.id, + }); + + const task = new ExportOKFZipTask(); + const filePath = await task.exportCollections([collection], fileOperation); + + try { + const contents = await readZipContents(filePath); + expect(Object.keys(contents).sort()).toEqual( + [`${collection.name}/index (1).md`, "index.md"].sort() + ); + } finally { + await fs.remove(filePath); + } + }); + + it("should rewrite internal links but keep the resource URL", async () => { + const team = await buildTeam(); + const user = await buildUser({ teamId: team.id }); + const collection = await buildCollection({ + teamId: team.id, + createdById: user.id, + }); + const target = await buildDocument({ + teamId: team.id, + userId: user.id, + collectionId: collection.id, + title: "Target", + }); + const source = await buildDocument({ + teamId: team.id, + userId: user.id, + collectionId: collection.id, + title: "Source", + text: `See [Target](${target.path})`, + }); + await collection.addDocumentToStructure(target); + await collection.addDocumentToStructure(source); + const fileOperation = await buildFileOperation({ + teamId: team.id, + userId: user.id, + }); + + const task = new ExportOKFZipTask(); + const filePath = await task.exportCollections([collection], fileOperation); + + try { + const contents = await readZipContents(filePath); + const [frontmatter, body] = splitFrontmatter( + contents[`${collection.name}/Source.md`] + ); + expect(frontmatter.resource).toContain(source.path); + expect(body).toContain("(./Target.md)"); + expect(body).not.toContain(target.path); + } finally { + await fs.remove(filePath); + } + }); +}); + +function splitFrontmatter(content: string): [Record, string] { + const match = content.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/); + if (!match) { + throw new Error("No frontmatter found"); + } + const data = yaml.load(match[1]); + if (typeof data !== "object" || data === null) { + throw new Error("Frontmatter is not a mapping"); + } + return [data as Record, match[2]]; +} + +async function readZipContents( + filePath: string +): Promise> { + const contents: Record = {}; + await ZipHelper.walk(filePath, async (entry) => { + if (!entry.isDirectory) { + contents[entry.fileName] = (await entry.readBuffer(1024 * 1024)).toString( + "utf8" + ); + } + }); + return contents; +} diff --git a/server/queues/tasks/ExportOKFZipTask.ts b/server/queues/tasks/ExportOKFZipTask.ts new file mode 100644 index 0000000000..87b0b14b15 --- /dev/null +++ b/server/queues/tasks/ExportOKFZipTask.ts @@ -0,0 +1,31 @@ +import type { NavigationNode } from "@shared/types"; +import { FileOperationFormat } from "@shared/types"; +import type { Collection, FileOperation } from "@server/models"; +import type { Document } from "@server/models"; +import ExportDocumentTreeTask from "./ExportDocumentTreeTask"; + +export default class ExportOKFZipTask extends ExportDocumentTreeTask { + public async exportCollections( + collections: Collection[], + fileOperation: FileOperation + ) { + return await this.addCollectionsToArchive( + collections, + FileOperationFormat.OKFZip, + fileOperation.options?.includeAttachments + ); + } + + public async exportDocument( + document: Document, + documentStructure: NavigationNode[], + includeAttachments: boolean + ): Promise { + return await this.addDocumentToArchive({ + document, + documentStructure, + format: FileOperationFormat.OKFZip, + includeAttachments, + }); + } +} diff --git a/shared/types.ts b/shared/types.ts index 3eab44ea16..8e3e9f6ef8 100644 --- a/shared/types.ts +++ b/shared/types.ts @@ -71,6 +71,7 @@ export enum ExportContentType { export enum FileOperationFormat { JSON = "json", MarkdownZip = "outline-markdown", + OKFZip = "okf", HTMLZip = "html", TextBundleZip = "textbundle", PDF = "pdf",