Files
gitmost/packages/mcp/test/unit/outline.test.mjs
T
agent_coder 4b2af3d34a refactor(mcp): дедупликация конвертер-смежных хелперов (node-ops форк, footnote-*, parse-node-arg)
Аудит при подготовке #413 нашёл дрейфующие дубли между packages/mcp и
packages/prosemirror-markdown. Четыре дедупа (поведение тулов не меняется):

1. node-ops: форк ~960 строк сведён в ОДНУ копию в prosemirror-markdown (живая
   mcp-версия — строгое надмножество замороженного #293-seed'а пакета; сверено по
   git-истории, новая пакет-копия байт-в-байт == прежней mcp-копии). Barrel-экспорт
   полной поверхности; mcp/client.ts/page-search.ts/transforms.ts/collaboration.ts
   импортируют из пакета; тесты переехали. node-ops тянет stripInlineMarkdown ->
   пакет-локальная text-normalize.ts несёт только этот примитив (mcp-версия —
   домен #408; заголовок документирует дубликацию + источник истины).
2. footnote-lex/footnote-analyze (vestigial legacy [^id]: диагностика): сведены к
   одному fence-aware предупреждению 'reference-style footnotes -> use ^[...]'
   (полезно для класса #410); footnote-lex удалён.
3. footnote-authoring -> примитивы (footnoteContentKey/makeFootnoteDefinition/
   generateFootnoteId) перенесены в пакетный footnote.ts, одна реализация конвенции.
4. parse-node-arg -> перенесён в prosemirror-markdown (не mcp: сервер CommonJS не
   импортирует ESM-only @docmost/mcp, но нативно импортирует пакет), обе копии
   удалены, консьюмеры перенаправлены.

canonicalizeFootnotes/ENFORCEMENT RULE #228 и comment-anchor/json-edit/text-normalize
(mcp) не тронуты. API-поверхность node-ops оставлена чистой для #409/#413.

closes #414

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-10 01:06:31 +03:00

110 lines
3.3 KiB
JavaScript

import { test } from "node:test";
import assert from "node:assert/strict";
import { buildOutline, getNodeByRef } from "@docmost/prosemirror-markdown";
// Helpers to build the small fixture doc.
const textNode = (text) => ({ type: "text", text });
const paragraph = (id, text) => ({
type: "paragraph",
attrs: { id },
content: [textNode(text)],
});
// A table cell holds a paragraph; cells/rows/table carry NO attrs.id.
const cell = (text) => ({
type: "tableCell",
content: [{ type: "paragraph", content: [textNode(text)] }],
});
const row = (...texts) => ({
type: "tableRow",
content: texts.map(cell),
});
const listItem = (text) => ({
type: "listItem",
content: [{ type: "paragraph", content: [textNode(text)] }],
});
// A long paragraph to exercise truncation (>100 chars).
const longText = "x".repeat(150);
const buildDoc = () => ({
type: "doc",
content: [
{ type: "heading", attrs: { id: "h1", level: 2 }, content: [textNode("Title")] },
paragraph("p1", longText),
{
type: "table",
content: [row("A", "B", "C"), row("1", "2", "3")],
},
{
type: "bulletList",
attrs: { id: "list1" },
content: [listItem("one"), listItem("two")],
},
],
});
test("buildOutline returns one compact entry per top-level block", () => {
const outline = buildOutline(buildDoc());
assert.equal(outline.length, 4);
// Heading: level + id + firstText.
assert.equal(outline[0].type, "heading");
assert.equal(outline[0].level, 2);
assert.equal(outline[0].id, "h1");
assert.equal(outline[0].firstText, "Title");
// Long paragraph text is truncated to 100 chars + ellipsis.
assert.equal(outline[1].id, "p1");
assert.equal(outline[1].firstText, "x".repeat(100) + "…");
assert.equal(outline[1].firstText.length, 101);
// Table: rows/cols/header from the first row; no id on the table itself.
assert.equal(outline[2].type, "table");
assert.equal(outline[2].rows, 2);
assert.equal(outline[2].cols, 3);
assert.deepEqual(outline[2].header, ["A", "B", "C"]);
assert.equal(outline[2].id, null);
// List: item count.
assert.equal(outline[3].type, "bulletList");
assert.equal(outline[3].items, 2);
});
test("buildOutline is null-safe", () => {
assert.deepEqual(buildOutline(undefined), []);
assert.deepEqual(buildOutline({ type: "doc" }), []);
assert.deepEqual(buildOutline(42), []);
});
test("getNodeByRef resolves a block id to its node and path", () => {
const doc = buildDoc();
const hit = getNodeByRef(doc, "h1");
assert.ok(hit);
assert.equal(hit.type, "heading");
assert.deepEqual(hit.path, [0]);
assert.equal(hit.node.attrs.id, "h1");
});
test("getNodeByRef resolves #<index> to a top-level block (table)", () => {
const doc = buildDoc();
const hit = getNodeByRef(doc, "#2");
assert.ok(hit);
assert.equal(hit.type, "table");
assert.deepEqual(hit.path, [2]);
});
test("getNodeByRef returns null for an unknown ref", () => {
assert.equal(getNodeByRef(buildDoc(), "nope"), null);
});
test("getNodeByRef returns a clone (mutating it does not change the input)", () => {
const doc = buildDoc();
const hit = getNodeByRef(doc, "h1");
hit.node.attrs.id = "MUTATED";
hit.node.content[0].text = "changed";
// Original doc is untouched.
assert.equal(doc.content[0].attrs.id, "h1");
assert.equal(doc.content[0].content[0].text, "Title");
});