A self-hostable bookmark-everything app (links, notes and images) with AI-based automatic tagging and full text search
feat(api): add an api for fetching readable content of a bookmark. #2660
Mohamed Bassemf39111390e6a
diff --git a/packages/api/routes/bookmarks.ts b/packages/api/routes/bookmarks.tsindex d0fd03c3..990b0a74 100644--- a/packages/api/routes/bookmarks.ts+++ b/packages/api/routes/bookmarks.ts@@ -4,7 +4,10 @@ import { z } from "zod";import {BookmarkTypes,+ DEFAULT_READABLE_CONTENT_MAX_CHARS,+ MAX_READABLE_CONTENT_MAX_CHARS,zAssetSchema,+ zBookmarkReadableContentFormatSchema,zManipulatedTagSchema,zNewBookmarkRequestSchema,zUpdateBookmarksRequestSchema,@@ -13,6 +16,10 @@ import {import { apiKeyScopeMiddleware } from "../middlewares/apiKeyScopes";import { authMiddleware } from "../middlewares/auth";import { adaptPagination, zPagination } from "../utils/pagination";+import {+ chunkReadableContent,+ decodeReadableContentCursor,+} from "../utils/readableContent";import {zGetBookmarkQueryParamsSchema,zGetBookmarkSearchParamsSchema,@@ -202,6 +209,94 @@ const app = new Hono()},)+ // GET /bookmarks/[bookmarkId]/content+ .get(+ "/:bookmarkId/content",+ zValidator(+ "query",+ z.object({+ format: zBookmarkReadableContentFormatSchema.optional(),+ maxChars: z.coerce+ .number()+ .int()+ .min(1)+ .max(MAX_READABLE_CONTENT_MAX_CHARS)+ .optional()+ .default(DEFAULT_READABLE_CONTENT_MAX_CHARS),+ cursor: z.string().optional(),+ }),+ ),+ async (c) => {+ const bookmarkId = c.req.param("bookmarkId");+ const query = c.req.valid("query");+ const cursor = query.cursor+ ? decodeReadableContentCursor(query.cursor)+ : null;++ if (query.cursor && !cursor) {+ return c.json(+ { code: "INVALID_CURSOR", message: "The cursor is invalid." },+ 400,+ );+ }++ const format = query.format ?? cursor?.format ?? "markdown";+ if (+ cursor &&+ (cursor.bookmarkId !== bookmarkId || cursor.format !== format)+ ) {+ return c.json(+ {+ code: "INVALID_CURSOR",+ message: "The cursor does not match this bookmark or format.",+ },+ 400,+ );+ }++ const readableContent =+ await c.var.api.bookmarks.getBookmarkReadableContent({+ bookmarkId,+ format,+ });++ if (cursor && cursor.contentVersion !== readableContent.contentVersion) {+ return c.json(+ {+ code: "CONTENT_CHANGED",+ message:+ "The bookmark content changed after this cursor was issued. Restart from the first page.",+ },+ 409,+ );+ }++ const chunk = chunkReadableContent({+ bookmarkId,+ content: readableContent.content,+ contentVersion: readableContent.contentVersion,+ format,+ maxChars: query.maxChars,+ start: cursor?.offset,+ });+ if (!chunk) {+ return c.json(+ {+ code: "INVALID_CURSOR",+ message: "The cursor points beyond the bookmark content.",+ },+ 400,+ );+ }++ c.header("ETag", `"${readableContent.contentVersion}"`);+ return c.json({+ ...readableContent,+ ...chunk,+ });+ },+ )+// GET /bookmarks/[bookmarkId].get("/:bookmarkId",diff --git a/packages/api/utils/readableContent.test.ts b/packages/api/utils/readableContent.test.tsnew file mode 100644index 00000000..affe8fb9--- /dev/null+++ b/packages/api/utils/readableContent.test.ts@@ -0,0 +1,61 @@+import { describe, expect, it } from "vitest";++import {+ chunkReadableContent,+ decodeReadableContentCursor,+} from "./readableContent";++describe("readable content chunking", () => {+ it("ends a chunk at a nearby paragraph boundary", () => {+ const firstParagraph = "a".repeat(80);+ const secondParagraph = "b".repeat(80);+ const page = chunkReadableContent({+ bookmarkId: "bookmark_1",+ content: `${firstParagraph}\n\n${secondParagraph}`,+ contentVersion: "sha256:version",+ format: "markdown",+ maxChars: 100,+ });++ expect(page).not.toBeNull();+ expect(page!.content).toBe(`${firstParagraph}\n\n`);+ expect(page!.range).toEqual({ start: 0, end: 82, total: 162 });+ expect(page!.truncated).toBe(true);++ const cursor = decodeReadableContentCursor(page!.nextCursor!);+ expect(cursor).toEqual({+ version: 1,+ bookmarkId: "bookmark_1",+ format: "markdown",+ contentVersion: "sha256:version",+ offset: 82,+ });+ });++ it("uses Unicode character offsets without splitting surrogate pairs", () => {+ const page = chunkReadableContent({+ bookmarkId: "bookmark_1",+ content: "πππ",+ contentVersion: "sha256:version",+ format: "text",+ maxChars: 2,+ });++ expect(page?.content).toBe("ππ");+ expect(page?.range).toEqual({ start: 0, end: 2, total: 3 });+ });++ it("rejects malformed cursors and offsets beyond the content", () => {+ expect(decodeReadableContentCursor("not-a-cursor")).toBeNull();+ expect(+ chunkReadableContent({+ bookmarkId: "bookmark_1",+ content: "short",+ contentVersion: "sha256:version",+ format: "text",+ maxChars: 10,+ start: 6,+ }),+ ).toBeNull();+ });+});diff --git a/packages/api/utils/readableContent.ts b/packages/api/utils/readableContent.tsnew file mode 100644index 00000000..28ef64b9--- /dev/null+++ b/packages/api/utils/readableContent.ts@@ -0,0 +1,111 @@+import { z } from "zod";++import type { ZBookmarkReadableContentFormat } from "@karakeep/shared/types/bookmarks";++const zReadableContentCursor = z.object({+ version: z.literal(1),+ bookmarkId: z.string(),+ format: z.enum(["markdown", "text"]),+ contentVersion: z.string(),+ offset: z.number().int().nonnegative(),+});++export type ReadableContentCursor = z.infer<typeof zReadableContentCursor>;++export function encodeReadableContentCursor(+ cursor: ReadableContentCursor,+): string {+ return Buffer.from(JSON.stringify(cursor)).toString("base64url");+}++export function decodeReadableContentCursor(+ cursor: string,+): ReadableContentCursor | null {+ try {+ return zReadableContentCursor.parse(+ JSON.parse(Buffer.from(cursor, "base64url").toString("utf8")),+ );+ } catch {+ return null;+ }+}++function findChunkLength(+ characters: string[],+ maxChars: number,+ hasMore: boolean,+): number {+ if (!hasMore) {+ return characters.length;+ }++ const earliestBoundary = Math.floor(maxChars * 0.8);++ for (let index = characters.length - 1; index >= earliestBoundary; index--) {+ if (characters[index] === "\n" && characters[index - 1] === "\n") {+ return index + 1;+ }+ }+ for (let index = characters.length - 1; index >= earliestBoundary; index--) {+ if (characters[index] === "\n") {+ return index + 1;+ }+ }+ return characters.length;+}++export function chunkReadableContent({+ bookmarkId,+ content,+ contentVersion,+ format,+ maxChars,+ start = 0,+}: {+ bookmarkId: string;+ content: string;+ contentVersion: string;+ format: ZBookmarkReadableContentFormat;+ maxChars: number;+ start?: number;+}) {+ const characters: string[] = [];+ let total = 0;+ for (const character of content) {+ if (total >= start && characters.length < maxChars) {+ characters.push(character);+ }+ total++;+ }+ if (start > total) {+ return null;+ }++ const chunkLength = findChunkLength(+ characters,+ maxChars,+ start + characters.length < total,+ );+ const end = start + chunkLength;+ const nextCursor =+ end < total+ ? encodeReadableContentCursor({+ version: 1,+ bookmarkId,+ format,+ contentVersion,+ offset: end,+ })+ : null;++ return {+ content: characters.slice(0, chunkLength).join(""),+ range: {+ start,+ end,+ total,+ },+ nextCursor,+ truncated: nextCursor !== null,+ };+}diff --git a/packages/e2e_tests/tests/api/bookmarks.test.ts b/packages/e2e_tests/tests/api/bookmarks.test.tsindex 3b867774..da326a5f 100644--- a/packages/e2e_tests/tests/api/bookmarks.test.ts+++ b/packages/e2e_tests/tests/api/bookmarks.test.ts@@ -71,6 +71,67 @@ describe("Bookmarks API", () => {expect(retrievedBookmark!.content.text).toBe("This is a test bookmark");});+ it("should page through readable bookmark content and reject stale cursors", async () => {+ const firstParagraph = "a".repeat(80);+ const secondParagraph = "b".repeat(80);+ const text = `${firstParagraph}\n\n${secondParagraph}`;+ const { data: bookmark } = await client.POST("/bookmarks", {+ body: {+ type: "text",+ text,+ },+ });++ const { data: firstPage, response: firstResponse } = await client.GET(+ "/bookmarks/{bookmarkId}/content",+ {+ params: {+ path: { bookmarkId: bookmark!.id },+ query: { maxChars: 100 },+ },+ },+ );++ expect(firstResponse.status).toBe(200);+ expect(firstPage?.format).toBe("markdown");+ expect(firstPage?.content).toBe(`${firstParagraph}\n\n`);+ expect(firstPage?.range).toEqual({ start: 0, end: 82, total: 162 });+ expect(firstPage?.nextCursor).not.toBeNull();++ const { data: secondPage } = await client.GET(+ "/bookmarks/{bookmarkId}/content",+ {+ params: {+ path: { bookmarkId: bookmark!.id },+ query: {+ maxChars: 100,+ cursor: firstPage!.nextCursor!,+ },+ },+ },+ );+ expect(firstPage!.content + secondPage!.content).toBe(text);+ expect(secondPage?.nextCursor).toBeNull();++ await client.PATCH("/bookmarks/{bookmarkId}", {+ params: { path: { bookmarkId: bookmark!.id } },+ body: { text: `${text}\nchanged` },+ });+ const { response: staleResponse, error } = await client.GET(+ "/bookmarks/{bookmarkId}/content",+ {+ params: {+ path: { bookmarkId: bookmark!.id },+ query: {+ cursor: firstPage!.nextCursor!,+ },+ },+ },+ );+ expect(staleResponse.status).toBe(409);+ expect(error).toEqual(expect.objectContaining({ code: "CONTENT_CHANGED" }));+ });+it("should update a bookmark", async () => {// Create a new bookmarkconst { data: createdBookmark, error: createError } = await client.POST(diff --git a/packages/open-api/karakeep-openapi-spec.json b/packages/open-api/karakeep-openapi-spec.jsonindex 5d24dd84..387a50e0 100644--- a/packages/open-api/karakeep-openapi-spec.json+++ b/packages/open-api/karakeep-openapi-spec.json@@ -479,6 +479,77 @@"message"]},+ "BookmarkReadableContent": {+ "type": "object",+ "properties": {+ "bookmarkId": {+ "type": "string"+ },+ "bookmarkType": {+ "type": "string",+ "enum": [+ "link",+ "text",+ "asset"+ ]+ },+ "format": {+ "type": "string",+ "enum": [+ "markdown",+ "text"+ ]+ },+ "content": {+ "type": "string"+ },+ "contentVersion": {+ "type": "string",+ "description": "A hash identifying the rendered content version used by this cursor."+ },+ "range": {+ "type": "object",+ "properties": {+ "start": {+ "type": "integer",+ "description": "Zero-based start offset in Unicode characters, inclusive."+ },+ "end": {+ "type": "integer",+ "description": "Zero-based end offset in Unicode characters, exclusive."+ },+ "total": {+ "type": "integer",+ "description": "Total number of Unicode characters in the rendered content."+ }+ },+ "required": [+ "start",+ "end",+ "total"+ ]+ },+ "nextCursor": {+ "type": "string",+ "nullable": true,+ "description": "Cursor for the next chunk, or null when all content has been returned."+ },+ "truncated": {+ "type": "boolean",+ "description": "Whether more readable content remains after this chunk."+ }+ },+ "required": [+ "bookmarkId",+ "bookmarkType",+ "format",+ "content",+ "contentVersion",+ "range",+ "nextCursor",+ "truncated"+ ]+ },"List": {"type": "object","properties": {@@ -1588,6 +1659,116 @@}}},+ "/bookmarks/{bookmarkId}/content": {+ "get": {+ "operationId": "getBookmarkReadableContent",+ "description": "Retrieve a bounded chunk of an agent-readable bookmark representation. Link content is rendered from extracted HTML; text and media bookmarks use their stored or extracted text. Continue reading by passing the opaque `nextCursor` from the previous response.",+ "summary": "Get readable bookmark content",+ "tags": [+ "Bookmarks"+ ],+ "security": [+ {+ "bearerAuth": []+ }+ ],+ "parameters": [+ {+ "$ref": "#/components/parameters/BookmarkId"+ },+ {+ "schema": {+ "type": "string",+ "enum": [+ "markdown",+ "text"+ ],+ "description": "The readable representation. If omitted with a cursor, the cursor's format is used; otherwise defaults to markdown."+ },+ "required": false,+ "description": "The readable representation. If omitted with a cursor, the cursor's format is used; otherwise defaults to markdown.",+ "name": "format",+ "in": "query"+ },+ {+ "schema": {+ "type": "integer",+ "minimum": 1,+ "maximum": 50000,+ "default": 12000,+ "description": "Maximum number of Unicode characters to return. The chunk may end earlier at a paragraph or line boundary."+ },+ "required": false,+ "description": "Maximum number of Unicode characters to return. The chunk may end earlier at a paragraph or line boundary.",+ "name": "maxChars",+ "in": "query"+ },+ {+ "schema": {+ "type": "string",+ "description": "Opaque continuation cursor returned as `nextCursor` by a previous response."+ },+ "required": false,+ "description": "Opaque continuation cursor returned as `nextCursor` by a previous response.",+ "name": "cursor",+ "in": "query"+ }+ ],+ "responses": {+ "200": {+ "description": "A bounded chunk of readable bookmark content.",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/BookmarkReadableContent"+ }+ }+ }+ },+ "400": {+ "description": "Bad request β the cursor is malformed, mismatched, or outside the content.",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/Error"+ }+ }+ }+ },+ "401": {+ "description": "Unauthorized β the Bearer token is missing, invalid, or expired.",+ "content": {+ "text/plain": {+ "schema": {+ "type": "string",+ "example": "Unauthorized"+ }+ }+ }+ },+ "404": {+ "description": "Bookmark not found.",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/Error"+ }+ }+ }+ },+ "409": {+ "description": "The bookmark content changed after the supplied cursor was issued.",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/Error"+ }+ }+ }+ }+ }+ }+ },"/bookmarks/{bookmarkId}/summarize": {"post": {"operationId": "summarizeBookmark",diff --git a/packages/open-api/lib/bookmarks.ts b/packages/open-api/lib/bookmarks.tsindex 336b4af2..ce65a84e 100644--- a/packages/open-api/lib/bookmarks.ts+++ b/packages/open-api/lib/bookmarks.ts@@ -2,9 +2,13 @@ import { OpenAPIRegistry } from "@asteasolutions/zod-to-openapi";import * as z from "zod";import {+ BookmarkTypes,+ DEFAULT_READABLE_CONTENT_MAX_CHARS,+ MAX_READABLE_CONTENT_MAX_CHARS,zAssetSchema,zAssetTypesSchema,zBareBookmarkSchema,+ zBookmarkReadableContentFormatSchema,zManipulatedTagSchema,zNewBookmarkRequestSchema,zSortOrder,@@ -233,6 +237,129 @@ registry.registerPath({},});+registry.registerPath({+ operationId: "getBookmarkReadableContent",+ method: "get",+ path: "/bookmarks/{bookmarkId}/content",+ description:+ "Retrieve a bounded chunk of an agent-readable bookmark representation. " ++ "Link content is rendered from extracted HTML; text and media bookmarks use their stored or extracted text. " ++ "Continue reading by passing the opaque `nextCursor` from the previous response.",+ summary: "Get readable bookmark content",+ tags: ["Bookmarks"],+ security: [{ [BearerAuth.name]: [] }],+ request: {+ params: z.object({ bookmarkId: BookmarkIdSchema }),+ query: z.object({+ format: zBookmarkReadableContentFormatSchema+ .optional()+ .describe(+ "The readable representation. If omitted with a cursor, the cursor's format is used; otherwise defaults to markdown.",+ ),+ maxChars: z+ .number()+ .int()+ .min(1)+ .max(MAX_READABLE_CONTENT_MAX_CHARS)+ .optional()+ .default(DEFAULT_READABLE_CONTENT_MAX_CHARS)+ .describe(+ "Maximum number of Unicode characters to return. The chunk may end earlier at a paragraph or line boundary.",+ ),+ cursor: z+ .string()+ .optional()+ .describe(+ "Opaque continuation cursor returned as `nextCursor` by a previous response.",+ ),+ }),+ },+ responses: {+ 200: {+ description: "A bounded chunk of readable bookmark content.",+ content: {+ "application/json": {+ schema: z+ .object({+ bookmarkId: z.string(),+ bookmarkType: z.enum([+ BookmarkTypes.LINK,+ BookmarkTypes.TEXT,+ BookmarkTypes.ASSET,+ ]),+ format: zBookmarkReadableContentFormatSchema,+ content: z.string(),+ contentVersion: z+ .string()+ .describe(+ "A hash identifying the rendered content version used by this cursor.",+ ),+ range: z.object({+ start: z+ .number()+ .int()+ .describe(+ "Zero-based start offset in Unicode characters, inclusive.",+ ),+ end: z+ .number()+ .int()+ .describe(+ "Zero-based end offset in Unicode characters, exclusive.",+ ),+ total: z+ .number()+ .int()+ .describe(+ "Total number of Unicode characters in the rendered content.",+ ),+ }),+ nextCursor: z+ .string()+ .nullable()+ .describe(+ "Cursor for the next chunk, or null when all content has been returned.",+ ),+ truncated: z+ .boolean()+ .describe(+ "Whether more readable content remains after this chunk.",+ ),+ })+ .openapi("BookmarkReadableContent"),+ },+ },+ },+ 400: {+ description:+ "Bad request β the cursor is malformed, mismatched, or outside the content.",+ content: {+ "application/json": {+ schema: ErrorSchema,+ },+ },+ },+ 401: UnauthorizedResponse,+ 409: {+ description:+ "The bookmark content changed after the supplied cursor was issued.",+ content: {+ "application/json": {+ schema: ErrorSchema,+ },+ },+ },+ 404: {+ description: "Bookmark not found.",+ content: {+ "application/json": {+ schema: ErrorSchema,+ },+ },+ },+ },+});+registry.registerPath({operationId: "deleteBookmark",method: "delete",diff --git a/packages/sdk/src/karakeep-api.d.ts b/packages/sdk/src/karakeep-api.d.tsindex bf042423..6883c59e 100644--- a/packages/sdk/src/karakeep-api.d.ts+++ b/packages/sdk/src/karakeep-api.d.ts@@ -96,6 +96,26 @@ export interface paths {patch: operations["updateBookmark"];trace?: never;};+ "/bookmarks/{bookmarkId}/content": {+ parameters: {+ query?: never;+ header?: never;+ path?: never;+ cookie?: never;+ };+ /**+ * Get readable bookmark content+ * @description Retrieve a bounded chunk of an agent-readable bookmark representation. Link content is rendered from extracted HTML; text and media bookmarks use their stored or extracted text. Continue reading by passing the opaque `nextCursor` from the previous response.+ */+ get: operations["getBookmarkReadableContent"];+ put?: never;+ post?: never;+ delete?: never;+ options?: never;+ head?: never;+ patch?: never;+ trace?: never;+ };"/bookmarks/{bookmarkId}/summarize": {parameters: {query?: never;@@ -919,6 +939,28 @@ export interface components {/** @description A human-readable error message. */message: string;};+ BookmarkReadableContent: {+ bookmarkId: string;+ /** @enum {string} */+ bookmarkType: "link" | "text" | "asset";+ /** @enum {string} */+ format: "markdown" | "text";+ content: string;+ /** @description A hash identifying the rendered content version used by this cursor. */+ contentVersion: string;+ range: {+ /** @description Zero-based start offset in Unicode characters, inclusive. */+ start: number;+ /** @description Zero-based end offset in Unicode characters, exclusive. */+ end: number;+ /** @description Total number of Unicode characters in the rendered content. */+ total: number;+ };+ /** @description Cursor for the next chunk, or null when all content has been returned. */+ nextCursor: string | null;+ /** @description Whether more readable content remains after this chunk. */+ truncated: boolean;+ };List: {id: string;name: string;@@ -1424,6 +1466,72 @@ export interface operations {};};};+ getBookmarkReadableContent: {+ parameters: {+ query?: {+ /** @description The readable representation. If omitted with a cursor, the cursor's format is used; otherwise defaults to markdown. */+ format?: "markdown" | "text";+ /** @description Maximum number of Unicode characters to return. The chunk may end earlier at a paragraph or line boundary. */+ maxChars?: number;+ /** @description Opaque continuation cursor returned as `nextCursor` by a previous response. */+ cursor?: string;+ };+ header?: never;+ path: {+ /** @description The unique identifier of the bookmark. */+ bookmarkId: components["parameters"]["BookmarkId"];+ };+ cookie?: never;+ };+ requestBody?: never;+ responses: {+ /** @description A bounded chunk of readable bookmark content. */+ 200: {+ headers: {+ [name: string]: unknown;+ };+ content: {+ "application/json": components["schemas"]["BookmarkReadableContent"];+ };+ };+ /** @description Bad request β the cursor is malformed, mismatched, or outside the content. */+ 400: {+ headers: {+ [name: string]: unknown;+ };+ content: {+ "application/json": components["schemas"]["Error"];+ };+ };+ /** @description Unauthorized β the Bearer token is missing, invalid, or expired. */+ 401: {+ headers: {+ [name: string]: unknown;+ };+ content: {+ "text/plain": string;+ };+ };+ /** @description Bookmark not found. */+ 404: {+ headers: {+ [name: string]: unknown;+ };+ content: {+ "application/json": components["schemas"]["Error"];+ };+ };+ /** @description The bookmark content changed after the supplied cursor was issued. */+ 409: {+ headers: {+ [name: string]: unknown;+ };+ content: {+ "application/json": components["schemas"]["Error"];+ };+ };+ };+ };summarizeBookmark: {parameters: {query?: never;diff --git a/packages/shared/types/bookmarks.ts b/packages/shared/types/bookmarks.tsindex 3d0b47f8..b9ce5277 100644--- a/packages/shared/types/bookmarks.ts+++ b/packages/shared/types/bookmarks.ts@@ -5,6 +5,8 @@ import { zCursorV2 } from "./pagination";import { zAttachedByEnumSchema, zBookmarkTagSchema } from "./tags";export const MAX_BOOKMARK_TITLE_LENGTH = 1000;+export const DEFAULT_READABLE_CONTENT_MAX_CHARS = 12_000;+export const MAX_READABLE_CONTENT_MAX_CHARS = 50_000;// Zod's url() accepts any scheme (javascript:, data:, ...), so restrict// bookmark links to schemes that are safe to reflect in exports and feeds.@@ -22,6 +24,29 @@ export const enum BookmarkTypes {UNKNOWN = "unknown",}+export const zBookmarkReadableContentFormatSchema = z.enum([+ "markdown",+ "text",+]);+export type ZBookmarkReadableContentFormat = z.infer<+ typeof zBookmarkReadableContentFormatSchema+>;++export const zBookmarkReadableContentSchema = z.object({+ bookmarkId: z.string(),+ bookmarkType: z.enum([+ BookmarkTypes.LINK,+ BookmarkTypes.TEXT,+ BookmarkTypes.ASSET,+ ]),+ format: zBookmarkReadableContentFormatSchema,+ content: z.string(),+ contentVersion: z.string(),+});+export type ZBookmarkReadableContent = z.infer<+ typeof zBookmarkReadableContentSchema+>;+export const zSortOrder = z.enum(["asc", "desc", "relevance"]);export type ZSortOrder = z.infer<typeof zSortOrder>;diff --git a/packages/trpc/models/bookmarks.ts b/packages/trpc/models/bookmarks.tsindex f546de04..797910dd 100644--- a/packages/trpc/models/bookmarks.ts+++ b/packages/trpc/models/bookmarks.ts@@ -1,3 +1,5 @@+import { createHash } from "node:crypto";+import { TRPCError } from "@trpc/server";import {and,@@ -14,6 +16,7 @@ import {SQL,} from "drizzle-orm";import invariant from "tiny-invariant";+import TurndownService from "turndown";import { z } from "zod";import { db as DONT_USE_db } from "@karakeep/db";@@ -37,13 +40,17 @@ import { getAlignedExpiry } from "@karakeep/shared/signedTokens";import {BookmarkTypes,DEFAULT_NUM_BOOKMARKS_PER_PAGE,+ zGetBookmarksRequestSchema,+} from "@karakeep/shared/types/bookmarks";+import type {ZBareBookmark,ZBookmark,ZBookmarkContent,- zGetBookmarksRequestSchema,+ ZBookmarkReadableContent,+ ZBookmarkReadableContentFormat,ZPublicBookmark,} from "@karakeep/shared/types/bookmarks";-import { ZCursor } from "@karakeep/shared/types/pagination";+import type { ZCursor } from "@karakeep/shared/types/pagination";import {getBookmarkLinkAssetIdOrUrl,getBookmarkTitle,@@ -79,6 +86,11 @@ type BookmarkQueryReturnType = Awaited<ReturnType<typeof dummyDrizzleReturnType>>;+const turndownService = new TurndownService({+ bulletListMarker: "-",+ headingStyle: "atx",+});+export class BareBookmark {protected constructor(protected ctx: AuthedContext,@@ -766,6 +778,48 @@ export class Bookmark extends BareBookmark {};}+ asReadableContent(+ format: ZBookmarkReadableContentFormat,+ ): ZBookmarkReadableContent {+ let content: string;+ switch (this.bookmark.content.type) {+ case BookmarkTypes.LINK: {+ const htmlContent = this.bookmark.content.htmlContent ?? "";+ content =+ format === "markdown"+ ? turndownService.turndown(htmlContent)+ : htmlToPlainText(htmlContent);+ break;+ }+ case BookmarkTypes.TEXT:+ content = this.bookmark.content.text;+ break;+ case BookmarkTypes.ASSET:+ content = this.bookmark.content.content ?? "";+ break;+ default:+ throw new TRPCError({+ code: "INTERNAL_SERVER_ERROR",+ message: "Bookmark has an unknown content type",+ });+ }++ content = content.replace(/\r\n?/g, "\n").trim();+ const contentVersion = `sha256:${createHash("sha256")+ .update(format)+ .update("\0")+ .update(content)+ .digest("hex")}`;++ return {+ bookmarkId: this.bookmark.id,+ bookmarkType: this.bookmark.content.type,+ format,+ content,+ contentVersion,+ };+ }+asPublicBookmark(): ZPublicBookmark {const getPublicSignedAssetUrl = (assetId: string) => {// Tokens will expire in 1 hour and will have a grace period of 15minsdiff --git a/packages/trpc/package.json b/packages/trpc/package.jsonindex e1b7db5e..bff74d49 100644--- a/packages/trpc/package.json+++ b/packages/trpc/package.json@@ -25,6 +25,7 @@"stripe": "^20.3.1","superjson": "^2.2.1","tiny-invariant": "^1.3.3",+ "turndown": "^7.2.0","zod": "^4.0.0"},"devDependencies": {@@ -32,6 +33,7 @@"@types/bcryptjs": "^2.4.6","@types/deep-equal": "^1.0.4","@types/nodemailer": "^6.4.17",+ "@types/turndown": "^5.0.5","vite-tsconfig-paths": "^6.1.1","vitest": "^3.2.4"}diff --git a/packages/trpc/routers/bookmarks.test.ts b/packages/trpc/routers/bookmarks.test.tsindex d6f6823b..f54768d4 100644--- a/packages/trpc/routers/bookmarks.test.ts+++ b/packages/trpc/routers/bookmarks.test.ts@@ -74,6 +74,44 @@ describe("Bookmark Routes", () => {expect(res.content.type).toEqual(BookmarkTypes.LINK);});+ test<CustomTestContext>("get readable bookmark content as markdown or text", async ({+ apiCallers,+ db,+ }) => {+ const api = apiCallers[0].bookmarks;+ const bookmark = await api.createBookmark({+ url: "https://example.com/article",+ type: BookmarkTypes.LINK,+ });+ await db+ .update(bookmarkLinks)+ .set({+ htmlContent:+ '<h1>Hello</h1><p>Read <a href="https://example.com/docs">the docs</a>.</p>',+ })+ .where(eq(bookmarkLinks.id, bookmark.id));++ const markdown = await api.getBookmarkReadableContent({+ bookmarkId: bookmark.id,+ format: "markdown",+ });+ expect(markdown).toMatchObject({+ bookmarkId: bookmark.id,+ bookmarkType: BookmarkTypes.LINK,+ format: "markdown",+ content: "# Hello\n\nRead [the docs](https://example.com/docs).",+ });+ expect(markdown.contentVersion).toMatch(/^sha256:[a-f0-9]{64}$/);++ const text = await api.getBookmarkReadableContent({+ bookmarkId: bookmark.id,+ format: "text",+ });+ expect(text.content).toContain("HELLO");+ expect(text.content).toContain("Read the docs");+ expect(text.contentVersion).not.toBe(markdown.contentVersion);+ });+test<CustomTestContext>("api key with read scope can read bookmarks but not write", async ({apiCallers,db,@@ -91,6 +129,12 @@ describe("Bookmark Routes", () => {const bookmarks = await apiKeyCaller.bookmarks.getBookmarks({});expect(bookmarks.bookmarks).toHaveLength(1);+ await expect(+ apiKeyCaller.bookmarks.getBookmarkReadableContent({+ bookmarkId: bookmarks.bookmarks[0].id,+ format: "markdown",+ }),+ ).resolves.toMatchObject({ content: "seed bookmark" });await expect(() =>apiKeyCaller.bookmarks.createBookmark({diff --git a/packages/trpc/routers/bookmarks.ts b/packages/trpc/routers/bookmarks.tsindex ea628489..e13a11a7 100644--- a/packages/trpc/routers/bookmarks.ts+++ b/packages/trpc/routers/bookmarks.ts@@ -41,6 +41,8 @@ import {BookmarkTypes,DEFAULT_NUM_BOOKMARKS_PER_PAGE,zBookmarkSchema,+ zBookmarkReadableContentFormatSchema,+ zBookmarkReadableContentSchema,zGetBookmarksRequestSchema,zGetBookmarksResponseSchema,zManipulatedTagSchema,@@ -813,6 +815,21 @@ export const bookmarksAppRouter = router({await Bookmark.fromId(ctx, input.bookmarkId, input.includeContent)).asZBookmark();}),+ getBookmarkReadableContent: bookmarksProcedure+ .use(createBookmarksQueriedMiddleware())+ .input(+ z.object({+ bookmarkId: z.string(),+ format: zBookmarkReadableContentFormatSchema.default("markdown"),+ }),+ )+ .output(zBookmarkReadableContentSchema)+ .use(ensureBookmarkAccess)+ .query(async ({ input, ctx }) => {+ return (+ await Bookmark.fromId(ctx, input.bookmarkId, /* includeContent: */ true)+ ).asReadableContent(input.format);+ }),searchBookmarks: bookmarksProcedure.use(createBookmarksQueriedMiddleware()).use(createEventLogMiddleware("search.query"))diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex b71aac4d..9e4f3752 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -1580,6 +1580,9 @@ importers:tiny-invariant:specifier: ^1.3.3version: 1.3.3+ turndown:+ specifier: ^7.2.0+ version: 7.2.0zod:specifier: ^4.0.0version: 4.3.6@@ -1596,6 +1599,9 @@ importers:'@types/nodemailer':specifier: ^6.4.17version: 6.4.17+ '@types/turndown':+ specifier: ^5.0.5+ version: 5.0.5vite-tsconfig-paths:specifier: ^6.1.1version: 6.1.1([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))