feat: Add Open Knowledge Format (OKF) export (#13644)

* feat: Add Open Knowledge Format (OKF) export

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* Separate OKF frontmatter from body, use team URL for resource

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* Use OKF initials avatar in export dialog

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* Use GlobeIcon for OKF export format

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
This commit is contained in:
Tom MoorandClaude Fable 5.1 authored and GitHub committed 2026-09-04 08:15:07 -04:00
1 parent 1c3d1ed0a9
commit 899fb8a22e
8 files changed
+429 -23

No files matched your search

+7 -1
View File
@@ -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: <MarkdownIcon />,
},
{
title: "Open Knowledge Format",
extension: ".okf.zip",
value: FileOperationFormat.OKFZip,
icon: <GlobeIcon />,
},
{
title: "HTML",
extension: ".html.zip",
@@ -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",
+114
View File
@@ -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`;
}
}
@@ -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,
+95 -22
View File
@@ -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<string, string>;
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<string, string>();
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<string | undefined> {
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<string, string>;
format: FileOperationFormat;
includeAttachments: boolean;
origin?: string;
}) {
const processedPaths = new Set<string>();
@@ -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<string, string>();
const usedRoots = new Set<string>();
const pathMap = new Map<string, string>();
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}`);
}
@@ -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, unknown>, 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<string, unknown>, match[2]];
}
async function readZipContents(
filePath: string
): Promise<Record<string, string>> {
const contents: Record<string, string> = {};
await ZipHelper.walk(filePath, async (entry) => {
if (!entry.isDirectory) {
contents[entry.fileName] = (await entry.readBuffer(1024 * 1024)).toString(
"utf8"
);
}
});
return contents;
}
+31
View File
@@ -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<string> {
return await this.addDocumentToArchive({
document,
documentStructure,
format: FileOperationFormat.OKFZip,
includeAttachments,
});
}
}
+1
View File
@@ -71,6 +71,7 @@ export enum ExportContentType {
export enum FileOperationFormat {
JSON = "json",
MarkdownZip = "outline-markdown",
OKFZip = "okf",
HTMLZip = "html",
TextBundleZip = "textbundle",
PDF = "pdf",