/** * Post-upload mention pass — convert text_run links into native `mention_doc` elements. * * Feishu only populates the backlinks panel and the graph view when a doc * references another via a `mention_doc` block element. Markdown links * uploaded through `lark-cli docs +create` become `text_run` elements * with a link style, which are clickable but invisible to the backlink * machinery. This module fetches the uploaded blocks, rewrites any * text_run whose URL is known, and PATCHes each affected block. * * Idempotent: already-converted mention_doc elements are left alone * because we only match text_run elements with a link URL. */ import { execSync } from "node:child_process"; import { readFileSync } from "node:fs"; import type { LarkCli } from "../cli.js"; // ─── Types ────────────────────────────────────────────────────────────── export interface MentionTarget { obj_token: string; /** Feishu object type — defaults to 22 (docx) when omitted. */ obj_type?: number; /** Optional display override. When absent, the original text_run content is preserved. */ title?: string; } export type MentionMap = Record; type Block = Record; type Element = Record; export interface MentionPatch { blockId: string; newElements: Element[]; changedCount: number; } export interface ApplyMentionsResult { plannedBlocks: number; ok: number; fail: number; } // block_type → content-key for blocks that carry `elements[]`. const CONTENT_KEY: Record = { 2: "text", 3: "heading1", 4: "heading2", 5: "heading3", 6: "heading4", 7: "heading5", 8: "heading6", 9: "heading7", 10: "heading8", 11: "heading9", 12: "bullet", 13: "ordered", 14: "code", 15: "quote", 17: "todo", 19: "callout", 34: "quote_container", }; const OBJ_TYPE_DOCX = 22; const DEFAULT_SLEEP_MS = 200; // ─── Load ─────────────────────────────────────────────────────────────── /** * Load a mention-map JSON file. Keys are doc URLs; values carry obj_token * and optional obj_type/title overrides. */ export function loadMentionMap(path: string): MentionMap { let raw: string; try { raw = readFileSync(path, "utf-8"); } catch (err) { throw new Error(`mention-map: cannot read ${path}: ${(err as Error).message}`); } let parsed: unknown; try { parsed = JSON.parse(raw); } catch (err) { throw new Error(`mention-map: invalid JSON in ${path}: ${(err as Error).message}`); } if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) { throw new Error(`mention-map: ${path} must be a JSON object keyed by URL`); } const out: MentionMap = {}; for (const [url, value] of Object.entries(parsed as Record)) { if (!value || typeof value !== "object" || Array.isArray(value)) { throw new Error(`mention-map: entry for "${url}" must be an object`); } const entry = value as Record; const objToken = entry.obj_token; if (typeof objToken !== "string" || objToken === "") { throw new Error(`mention-map: entry for "${url}" is missing obj_token`); } const target: MentionTarget = { obj_token: objToken }; if (typeof entry.obj_type === "number") target.obj_type = entry.obj_type; if (typeof entry.title === "string") target.title = entry.title; out[url] = target; } return out; } // ─── Planning (pure) ──────────────────────────────────────────────────── function elementsOf(block: Block): Element[] | null { const bt = block.block_type as number | undefined; if (bt === undefined) return null; const key = CONTENT_KEY[bt]; if (!key) return null; const content = block[key] as Block | undefined; if (!content) return null; const elements = content.elements as Element[] | undefined; return elements ?? null; } /** * Given already-fetched blocks and a URL map, compute the PATCH plan. * Pure function — testable without network calls. */ export function planMentions(blocks: Block[], map: MentionMap): MentionPatch[] { const patches: MentionPatch[] = []; for (const block of blocks) { const elements = elementsOf(block); if (!elements || elements.length === 0) continue; let changedCount = 0; const next: Element[] = elements.map((el) => { if (el.mention_doc) return el; // already a mention — leave alone const tr = el.text_run as Block | undefined; if (!tr) return el; const style = tr.text_element_style as Block | undefined; const link = style?.link as Block | undefined; const url = link?.url as string | undefined; if (!url) return el; const target = map[url]; if (!target) return el; changedCount++; const content = (tr.content as string) ?? ""; return { mention_doc: { token: target.obj_token, obj_type: target.obj_type ?? OBJ_TYPE_DOCX, url, title: target.title ?? content, text_element_style: {}, }, }; }); if (changedCount > 0) { patches.push({ blockId: block.block_id as string, newElements: next, changedCount, }); } } return patches; } // ─── Apply (I/O) ──────────────────────────────────────────────────────── function sleep(ms: number): void { if (ms <= 0) return; execSync(`sleep ${(ms / 1000).toFixed(3)}`); } /** * Fetch blocks, compute PATCH plan, and apply. Returns counts. * * Non-fatal on per-block PATCH failure — logs and continues. */ export function applyMentions( cli: LarkCli, docId: string, map: MentionMap, opts: { sleepMs?: number; verbose?: boolean } = {} ): ApplyMentionsResult { const sleepMs = opts.sleepMs ?? DEFAULT_SLEEP_MS; const blocks = cli.getBlocks(docId); const patches = planMentions(blocks, map); let ok = 0; let fail = 0; for (const p of patches) { const success = cli.updateBlockElements(docId, p.blockId, p.newElements as Record[]); if (success) ok++; else { fail++; if (opts.verbose) { console.error(`mention PATCH failed for block ${p.blockId} (${p.changedCount} link→mention)`); } } sleep(sleepMs); } return { plannedBlocks: patches.length, ok, fail }; }