cladogram 0.3.1 → 0.5.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (70) hide show
  1. package/README.md +57 -365
  2. package/bin/clado.js +126 -72
  3. package/package.json +11 -8
  4. package/skills/clado/SKILL.md +123 -747
  5. package/src/core/links.js +37 -0
  6. package/src/core/media-links.js +99 -0
  7. package/src/core/parse.js +81 -82
  8. package/src/html/app-css.js +51 -75
  9. package/src/html/canvas-card.js +65 -0
  10. package/src/html/canvas-chain.js +231 -0
  11. package/src/html/canvas-focus.js +175 -0
  12. package/src/html/canvas-ui.css +38 -0
  13. package/src/html/canvas-ui.js +40 -0
  14. package/src/html/canvas-wires.js +73 -0
  15. package/src/html/media-anchors.js +212 -0
  16. package/src/html/mindmap-connectors.js +78 -0
  17. package/src/html/mindmap-media.js +39 -0
  18. package/src/html/page.js +23 -4
  19. package/src/html/runtime-api.js +51 -0
  20. package/src/html/runtime-fixes.js +32 -0
  21. package/src/html/runtime.js +322 -272
  22. package/src/server/assets/library-canvas.js +96 -0
  23. package/src/server/assets/library.css +9 -0
  24. package/src/server/assets/library.html +20 -0
  25. package/src/server/assets/library.js +127 -0
  26. package/src/server/assets/tree.js +26 -0
  27. package/src/server/export.js +53 -0
  28. package/src/server/mcp.js +108 -0
  29. package/src/server/workspace.js +84 -0
  30. package/src/skill/install.js +16 -18
  31. package/src/skill/targets.js +28 -12
  32. package/src/skill/templates.js +60 -0
  33. package/src/util/version.js +3 -0
  34. package/src/workspace/content.js +72 -0
  35. package/src/workspace/documents.js +65 -0
  36. package/src/workspace/references.js +101 -0
  37. package/src/workspace/service.js +457 -0
  38. package/src/workspace/storage.js +169 -0
  39. package/src/workspace/tree.js +66 -0
  40. package/templates/business-flow.mdc +29 -0
  41. package/templates/call-chain.mdc +62 -0
  42. package/templates/data-design.mdc +35 -0
  43. package/templates/mind-expansion.mdc +52 -0
  44. package/templates/requirement-overview.mdc +29 -0
  45. package/templates/system-state.mdc +29 -0
  46. package/examples/showcase/README.md +0 -115
  47. package/examples/showcase/baseline.md +0 -365
  48. package/examples/showcase/build.sh +0 -48
  49. package/examples/showcase/calls.md +0 -136
  50. package/examples/showcase/fulfill-cn.md +0 -351
  51. package/examples/showcase/fulfill.md +0 -271
  52. package/examples/showcase/index.md +0 -187
  53. package/examples/showcase/order.md +0 -195
  54. package/examples/showcase/promo.md +0 -580
  55. package/examples/showcase/refund.md +0 -966
  56. package/examples/showcase/seckill.md +0 -787
  57. package/skills/clado/examples/01-/351/234/200/346/261/202/346/240/221.md +0 -32
  58. package/skills/clado/examples/02-/346/225/260/346/215/256/350/241/250.md +0 -44
  59. package/skills/clado/examples/03-/346/216/245/345/217/243/346/270/205/345/215/225.md +0 -51
  60. package/skills/clado/examples/04-/346/226/271/346/263/225/351/223/276.md +0 -70
  61. package/skills/clado/examples/05-/346/216/245/345/217/243/350/260/203/347/224/250.md +0 -58
  62. package/skills/clado/examples/06-/350/260/203/347/224/250/351/223/276.md +0 -49
  63. package/skills/clado/examples/07-/346/213/206/346/226/207/346/241/243/index.md +0 -38
  64. package/skills/clado/examples/07-/346/213/206/346/226/207/346/241/243/refund.md +0 -33
  65. package/skills/clado/examples/07-/346/213/206/346/226/207/346/241/243/seckill.md +0 -56
  66. package/skills/clado/examples/08-/347/234/237/345/256/236/350/247/204/346/250/241//346/216/245/345/217/243/345/245/221/347/272/246.md +0 -122
  67. package/skills/clado/examples/08-/347/234/237/345/256/236/350/247/204/346/250/241//346/225/205/351/232/234/345/244/215/347/233/230.md +0 -99
  68. package/skills/clado/examples/08-/347/234/237/345/256/236/350/247/204/346/250/241//350/260/203/347/224/250/351/223/276.md +0 -219
  69. package/skills/clado/examples/build.sh +0 -44
  70. package/skills/clado/references/diagnostics.md +0 -129
@@ -6,18 +6,16 @@
6
6
  * ② 让用户勾
7
7
  * ③ 装。已经装过的**先整个删掉再拷**,所以升级之后不会留上一个版本的文件。
8
8
  *
9
- * ★ 为什么重装是「删了再拷」而不是「覆盖着拷」:bundle 的文件清单**每个版本都在变**
10
- * (`references/diagnostics.md` 改过、例子改过名)。只覆盖同名文件的话,上个版本
11
- * 多出来的那些会永远留在用户项目里,而且没有任何提示 —— 用户看到的是一份两个版本
12
- * 混在一起的 skill。整个目录换掉是唯一能保证「装上之后 = 这个版本」的做法。
9
+ * 重装清理受管理目录的旧附件,再写入唯一的 SKILL.md,避免遗留其它版本的资料。
13
10
  */
14
11
 
15
- import { existsSync, statSync, readFileSync, writeFileSync, mkdirSync, rmSync, cpSync, readdirSync } from 'node:fs';
16
- import { resolve, join, dirname, basename, relative, sep } from 'node:path';
12
+ import { existsSync, statSync, readFileSync, writeFileSync, mkdirSync, rmSync, readdirSync } from 'node:fs';
13
+ import { resolve, join, dirname, relative, sep } from 'node:path';
17
14
  import { fileURLToPath } from 'node:url';
18
15
 
19
16
  import { c } from '../util/term.js';
20
17
  import { TARGETS, SKILL_NAME, BUNDLE_REL, MARK_BEGIN, MARK_END, findTarget, ruleBody } from './targets.js';
18
+ import { installUserTemplates } from './templates.js';
21
19
 
22
20
  const HERE = dirname(fileURLToPath(import.meta.url));
23
21
  const PKG_ROOT = resolve(HERE, '..', '..');
@@ -29,10 +27,7 @@ export class UsageError extends Error {}
29
27
  // ---------------------------------------------------------------- 文件小工具
30
28
 
31
29
  /**
32
- * 拷 bundle 时要跳过的目录名。
33
- * ★ `out` 是 `examples/build.sh` 编出来的产物(三模式 36 个页面、50 多 MB),
34
- * `.gitignore` 里是有的,但 `cpSync` 不读 `.gitignore` —— 跟着 bundle 一起搬过去
35
- * 会把用户的项目撑爆。
30
+ * 统计旧安装时忽略构建产物、依赖及本机元数据。
36
31
  */
37
32
  const SKIP = new Set(['out', 'node_modules', '.git', '.DS_Store']);
38
33
 
@@ -213,15 +208,18 @@ export function pick(entries) {
213
208
  export function installTo(cwd, ids, opts = {}) {
214
209
  const { dryRun = false, force = false } = opts;
215
210
 
216
- // `--to all` = 全都装。12 个 id 敲一遍太长了。
211
+ // `--to all` = 全都装,不必逐个填写 id。
217
212
  if (ids.includes('all')) ids = TARGETS.map((t) => t.id);
218
213
 
219
214
  for (const id of ids) if (!findTarget(id)) throw new UsageError(`不认识这个工具:"${id}"`);
220
215
 
221
- if (!existsSync(BUNDLE)) {
222
- throw new UsageError(`包里找不到 skill 目录:${BUNDLE}\n 装的时候是不是漏了 skills/?`);
216
+ const entry = join(BUNDLE, 'SKILL.md');
217
+ if (!existsSync(entry)) {
218
+ throw new UsageError(`包里找不到 Skill 入口:${entry}`);
223
219
  }
224
- const files = listFiles(BUNDLE);
220
+ // 安装清单固定为一个入口,旧包即使仍有 references/examples 也不会整包复制。
221
+ const skillSource = readFileSync(entry, 'utf8');
222
+ const files = ['SKILL.md'];
225
223
 
226
224
  // 规则型的正文要指向一份真实存在的 SKILL.md。
227
225
  // 优先指本次已经装好的目录型目标(省一份重复的拷贝),一个都没选才落到 `.clado/`。
@@ -257,9 +255,8 @@ export function installTo(cwd, ids, opts = {}) {
257
255
  }
258
256
  if (!dryRun) {
259
257
  rmSync(destAbs, { recursive: true, force: true });
260
- mkdirSync(dirname(destAbs), { recursive: true });
261
- // filter 里也要挡一道:listFiles 只是用来数数的,真正搬文件的是 cpSync。
262
- cpSync(BUNDLE, destAbs, { recursive: true, filter: (src) => !SKIP.has(basename(src)) });
258
+ mkdirSync(destAbs, { recursive: true });
259
+ writeFileSync(join(destAbs, 'SKILL.md'), skillSource);
263
260
  }
264
261
  results.push({
265
262
  id: t.id,
@@ -303,7 +300,8 @@ export function installTo(cwd, ids, opts = {}) {
303
300
  });
304
301
  }
305
302
 
306
- return { results, files: files.length, anchor, dryRun };
303
+ const userTemplates = installUserTemplates({ dryRun });
304
+ return { results, files: files.length, anchor, dryRun, userTemplates };
307
305
  }
308
306
 
309
307
  /**
@@ -6,7 +6,7 @@
6
6
  * 所以新增一条之前先去翻文档,把链接填进 `doc`。
7
7
  *
8
8
  * 三种落点:
9
- * dir 自家的 skills 目录,整个 bundle(15 个文件)拷成 `<dest>/`
9
+ * dir 自家的 skills 目录,仅安装 `<dest>/SKILL.md`
10
10
  * own 自家独占的规则文件,直接覆写
11
11
  * append 和别人共用的规则文件(AGENTS.md 之类),往里写一段**带标记**的内容,
12
12
  * 重装时替换那一段而不是再追加一段
@@ -62,6 +62,14 @@ export const TARGETS = [
62
62
  marker: '.lingma',
63
63
  doc: 'https://docs.qoder.cn/user-guide/skills',
64
64
  },
65
+ {
66
+ id: 'zcode',
67
+ name: 'ZCode(智谱)',
68
+ kind: 'dir',
69
+ dest: '.zcode/skills/clado',
70
+ marker: '.zcode',
71
+ doc: 'https://www.zcode.network/cn/docs/qa/',
72
+ },
65
73
  {
66
74
  id: 'root',
67
75
  name: `项目根目录(丢一个 ${SKILL_NAME}/ 让 AI 自己去搬)`,
@@ -142,27 +150,35 @@ export function findTarget(id) {
142
150
  /**
143
151
  * 规则文件里的正文。
144
152
  *
145
- * ★ 只写「指针」不抄正文:SKILL.md 有 33 KB,塞进 AGENTS.md 会把每次对话的
146
- * 上下文都撑爆,而且升级之后两边就对不上了。指过去,让工具按需去读。
153
+ * 规则文件只保留指针,详细操作统一放在 SKILL.md。
147
154
  *
148
155
  * @param {string} skillPath bundle 在本项目里的相对路径(正斜杠)
149
156
  */
150
157
  export function ruleBody(skillPath) {
151
- return `# clado —— 拿 Markdown 画图
158
+ return `# clado —— Markdown 三视图工作区
152
159
 
153
- 这个项目用 [clado](https://www.npmjs.com/package/cladogram) 把一份 Markdown 编译成一个**自包含**的网页:
154
- 同一份 \`.md\` 能长成 **文档 / 卡片 / 脑图** 三种模式,双击就能离线打开。
160
+ 这个项目用 Clado 维护 Markdown 画布,在脑图、卡片和文档视图中讨论与迭代,也可打包成单个离线 HTML。
155
161
 
156
- 要写或改这类文档之前,**先把这份技能完整读一遍**(它是这个工具的全部用法):
162
+ 写或改画布前,先读 Skill 入口:
157
163
 
158
164
  ${skillPath}/SKILL.md
159
165
 
160
- 里面写了:标题怎么当卡片、层级怎么嵌套、**边怎么画**(正文里写一个 \`[目标](目标)\` 就够,
161
- 目标对不上就当普通链接、不报错)、表格 / 代码块 / Mermaid 怎么摆、八种诊断码各是什么意思。
166
+ 指南列出常用命令与 MCP 工具;具体场景通过 clado_templates read 读取模板 prompt。用户模板在 ~/.clado/templates/,项目副本在 .clado/templates/,文档在 .clado/doc/。
167
+
168
+ 先确认 CLI 版本与能力:
169
+
170
+ clado version
171
+ clado help
172
+
173
+ 使用源码时先 npm install,再用 node /Clado源码路径/bin/clado.js serve。
174
+
175
+ 从项目根开始:
176
+
177
+ clado serve
178
+
179
+ 连接输出的 Streamable HTTP MCP。每次调用提供输出的 workspace,先 clado_workspace inspect,再 clado_templates read 提示词,用 clado_documents create 按模板初始化 .mdc;节点、链接与批量操作也用MCP。正文直接传多行字符串,项目写入带 expectedWorkspaceVersion。模板可在项目 create/update,用 pull 从用户库复制,用 push 同步到用户库;push 同时带 expectedUserTemplateVersion。
162
180
 
163
- 跑起来:
181
+ 网页只展示脑图/卡片/文档,保存后自动更新。交付可用 clado build --entry overview.mdc --mode cards;默认生成只读 clado.html。工具不执行文档里的SQL、脚本或发布任务。
164
182
 
165
- npm install -g cladogram
166
- clado build 你的文档.md --mode=cards
167
183
  `;
168
184
  }
@@ -0,0 +1,60 @@
1
+ /** 用户模板的首次安装。只使用 Node 内置模块,Skill 安装无需 YAML 或 MCP 依赖。 */
2
+ import { existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, renameSync, statSync, unlinkSync, writeFileSync } from 'node:fs';
3
+ import { createHash, randomUUID } from 'node:crypto';
4
+ import { dirname, join, resolve } from 'node:path';
5
+ import { homedir } from 'node:os';
6
+ import { fileURLToPath } from 'node:url';
7
+
8
+ export const BUILTIN_TEMPLATES = fileURLToPath(new URL('../../templates/', import.meta.url));
9
+ export const templateName = /^[a-zA-Z0-9][\w-]{0,63}\.mdc$/;
10
+
11
+ // 发布过的未修改官方副本可随 install 升级。其它内容一律按用户定制保留。
12
+ const previousOfficial = {
13
+ 'business-flow.mdc': 'ad0c8620bb479de586656767e6d8de654dd416210b60c52f936f7ebcd2f093e8',
14
+ 'call-chain.mdc': '6881ec0c1f79b3e6233324d5a39394f19c09d810c05b06362159a20c629bc120',
15
+ 'data-design.mdc': '2d1f90b379bb979efea2bcdc9cbfda9efa72079364d17a9da7f091faa3aa29b7',
16
+ 'mind-expansion.mdc': '6daa35763c8105ffe8ad41fd8f829d467592de4e9e0a3e453290e76506354685',
17
+ 'requirement-overview.mdc': '53cc706e7d21927b66e57ef0adacaba90ed5dcd820e3531102021dc8742b1ff3',
18
+ 'system-state.mdc': '6d3c43ad034def26e11230611144b01ba7c28fdcabcdf6fbc3c003de9f046c25'
19
+ };
20
+
21
+ export function userTemplatePaths() {
22
+ const state = resolve(process.env.CLADO_HOME || join(homedir(), '.clado'));
23
+ return { state, templates: join(state, 'templates') };
24
+ }
25
+
26
+ export function installUserTemplates({ dryRun = false, onlyIfMissing = false } = {}) {
27
+ const { state, templates } = userTemplatePaths();
28
+ const marker = join(state, '.templates-initialized.json');
29
+ if (existsSync(templates) && !statSync(templates).isDirectory()) throw new Error(`用户模板路径不是目录:${templates}`);
30
+ if (onlyIfMissing && existsSync(marker) && existsSync(templates)) return { state, templates, added: 0, updated: 0 };
31
+ const files = readdirSync(BUILTIN_TEMPLATES).filter(name => templateName.test(name));
32
+ let added = 0, updated = 0;
33
+ if (!dryRun) mkdirSync(templates, { recursive: true });
34
+ for (const name of files) {
35
+ const target = join(templates, name);
36
+ const current = lstatSync(target, { throwIfNoEntry: false });
37
+ if (current) {
38
+ if (onlyIfMissing || !current.isFile() || createHash('sha256').update(readFileSync(target)).digest('hex') !== previousOfficial[name]) continue;
39
+ if (!dryRun) {
40
+ const temp = join(templates, '.' + randomUUID() + '.tmp');
41
+ writeFileSync(temp, readFileSync(join(BUILTIN_TEMPLATES, name)), { flag: 'wx', mode: current.mode & 0o777 });
42
+ try { renameSync(temp, target); }
43
+ finally { if (existsSync(temp)) unlinkSync(temp); }
44
+ }
45
+ updated++;
46
+ continue;
47
+ }
48
+ if (!dryRun) {
49
+ try { writeFileSync(target, readFileSync(join(BUILTIN_TEMPLATES, name)), { flag: 'wx' }); }
50
+ catch (error) { if (error.code === 'EEXIST') continue; throw error; }
51
+ }
52
+ added++;
53
+ }
54
+ if (!dryRun && !existsSync(marker)) {
55
+ mkdirSync(dirname(marker), { recursive: true });
56
+ try { writeFileSync(marker, JSON.stringify({ initialized: true }) + '\n', { flag: 'wx' }); }
57
+ catch (error) { if (error.code !== 'EEXIST') throw error; }
58
+ }
59
+ return { state, templates, added, updated };
60
+ }
@@ -0,0 +1,3 @@
1
+ import { readFileSync } from 'node:fs';
2
+
3
+ export const VERSION = JSON.parse(readFileSync(new URL('../../package.json', import.meta.url), 'utf8')).version;
@@ -0,0 +1,72 @@
1
+ import { fenceOf } from '../core/parse.js';
2
+ import { DocumentError } from './documents.js';
3
+
4
+ /** 1-based 正文块:空行分段,代码围栏(包括内部空行)始终为一个完整块。 */
5
+ export function paragraphs(content) {
6
+ const result = [], lines = content.split('\n');
7
+ let offset = 0, start = null, end = null, fence = null, kind = 'text';
8
+ const flush = () => {
9
+ if (start !== null) result.push({ index: result.length + 1, kind, start, end, text: content.slice(start, end) });
10
+ start = end = null; kind = 'text';
11
+ };
12
+ for (const line of lines) {
13
+ const marker = fenceOf(line);
14
+ if (fence) {
15
+ end = offset + line.length;
16
+ if (marker && marker[1][0] === fence[0] && marker[1].length >= fence.length) { fence = null; flush(); }
17
+ } else if (marker) {
18
+ flush(); start = offset; end = offset + line.length; fence = marker[1]; kind = 'code';
19
+ } else if (!line.trim()) flush();
20
+ else { if (start === null) start = offset; end = offset + line.length; }
21
+ offset += line.length + 1;
22
+ }
23
+ flush(); return result;
24
+ }
25
+
26
+ export function editContent(content, text, position = { mode: 'append' }) {
27
+ if (typeof text !== 'string') throw new DocumentError('插入内容必须为文字。');
28
+ const { mode, paragraph, anchor } = position;
29
+ let start, end, prefix = '', suffix = '';
30
+ if (mode === 'append' || mode === 'prepend') {
31
+ if (paragraph !== undefined || anchor !== undefined) throw new DocumentError('append/prepend 不接受段落或锚点;定位插入请用 before/after/replace。');
32
+ start = end = mode === 'append' ? content.length : 0;
33
+ if (content) { if (mode === 'append') prefix = '\n\n'; else suffix = '\n\n'; }
34
+ } else if (['before','after','replace'].includes(mode)) {
35
+ if ((paragraph !== undefined) === (anchor !== undefined)) throw new DocumentError('定位时只指定 paragraph(从1开始)或唯一 anchor 文字中的一个。');
36
+ if (paragraph !== undefined) {
37
+ const blocks = paragraphs(content), block = blocks[paragraph - 1];
38
+ if (!Number.isInteger(paragraph) || paragraph < 1 || !block) throw new DocumentError(`paragraph 超出范围,当前正文有 ${blocks.length} 段,从1开始。`);
39
+ start = block.start; end = block.end;
40
+ if (mode === 'before') { end = start; suffix = '\n\n'; }
41
+ if (mode === 'after') { start = end; prefix = '\n\n'; }
42
+ } else {
43
+ if (typeof anchor !== 'string' || !anchor) throw new DocumentError('anchor 需要非空、唯一的原文。');
44
+ const at = content.indexOf(anchor);
45
+ if (at < 0) throw new DocumentError('anchor 未找到,请重新读取节点正文。', 404);
46
+ if (content.indexOf(anchor, at + 1) >= 0) throw new DocumentError('anchor 不唯一,请提供更完整的原文,或用段落编号定位。', 409);
47
+ start = mode === 'after' ? at + anchor.length : at;
48
+ end = mode === 'replace' ? at + anchor.length : start;
49
+ }
50
+ } else throw new DocumentError('position.mode 支持 append/prepend/before/after/replace。');
51
+ const raw = content.slice(0, start) + prefix + text + suffix + content.slice(end);
52
+ const trim = raw.length - raw.trimStart().length;
53
+ return { content: raw.trim(), start: start + prefix.length - trim, text: text.trim(), mode };
54
+ }
55
+
56
+ export function paragraphLocations(content, bodyStartLine) {
57
+ return paragraphs(content).map(block => ({
58
+ index: block.index, kind: block.kind,
59
+ startLine: bodyStartLine + content.slice(0, block.start).split('\n').length - 1,
60
+ endLine: bodyStartLine + content.slice(0, block.end).split('\n').length - 1,
61
+ preview: block.text.slice(0, 100),
62
+ }));
63
+ }
64
+
65
+ export function contentLocation(content, start, end, bodyStartLine) {
66
+ const blocks = paragraphs(content).filter(block => block.end > start && block.start < end);
67
+ return {
68
+ paragraph: blocks[0]?.index ?? null, endParagraph: blocks.at(-1)?.index ?? null,
69
+ startLine: bodyStartLine + content.slice(0, start).split('\n').length - 1,
70
+ endLine: bodyStartLine + content.slice(0, end).split('\n').length - 1,
71
+ };
72
+ }
@@ -0,0 +1,65 @@
1
+ import { readFileSync, existsSync, statSync, readdirSync, realpathSync } from 'node:fs';
2
+ import { resolve, dirname, relative, basename, extname, sep } from 'node:path';
3
+ import { createHash } from 'node:crypto';
4
+ import { parseDocument, headingOf, fenceOf, splitFrontMatter } from '../core/parse.js';
5
+
6
+ export class DocumentError extends Error {
7
+ constructor(message, status = 400, diagnostics = []) { super(message); this.status = status; this.diagnostics = diagnostics; }
8
+ }
9
+ export const versionOf = source => createHash('sha256').update(source).digest('hex');
10
+ export function inspectSource(source, file = '') {
11
+ const { doc, diagnostics } = parseDocument(source, { path: file, fileBase: basename(file, extname(file)) });
12
+ const sections = [], clean = source.replace(/^\uFEFF/, ''), fm = splitFrontMatter(clean);
13
+ const lines = source.split(/\r?\n/), bodyLines = fm.body.split(/\r?\n/);
14
+ const offset = clean.slice(0, clean.length - fm.body.length).split(/\r?\n/).length - 1, stack = [];
15
+ let fence = null;
16
+ for (let j = 0; j < bodyLines.length; j++) {
17
+ const i = j + offset, f = fenceOf(bodyLines[j]);
18
+ if (f) { if (!fence) fence = f[1]; else if (f[1][0] === fence[0] && f[1].length >= fence.length) fence = null; continue; }
19
+ if (fence) continue;
20
+ const heading = headingOf(bodyLines[j]); if (!heading) continue;
21
+ const { level, title } = heading;
22
+ while (stack.length && stack.at(-1).level >= level) stack.pop();
23
+ const path = [...stack.map(s => s.title), title].join('.');
24
+ const section = { path, title, level, line: i + 1, start: i, end: lines.length, bodyEnd: lines.length };
25
+ sections.push(section); stack.push(section);
26
+ }
27
+ sections.forEach((s, i) => {
28
+ s.bodyEnd = sections[i + 1]?.start ?? lines.length;
29
+ s.end = sections.slice(i + 1).find(n => n.level <= s.level)?.start ?? lines.length;
30
+ s.content = lines.slice(s.start + 1, s.bodyEnd).join('\n').trim();
31
+ });
32
+ return { source, version: versionOf(source), doc, diagnostics, sections };
33
+ }
34
+ export function readDocument(file) { return inspectSource(readFileSync(file, 'utf8'), file); }
35
+ export function scanDirectory(root) {
36
+ const documents = [], skipped = [], parsed = new Map();
37
+ const walk = directory => {
38
+ for (const entry of readdirSync(directory, { withFileTypes: true }).sort((a,b) => a.name.localeCompare(b.name))) {
39
+ if (entry.name.startsWith('.') || ['node_modules','dist'].includes(entry.name)) continue;
40
+ const full = resolve(directory, entry.name);
41
+ if (entry.isDirectory()) { walk(full); continue; }
42
+ if (!entry.isFile() || !/\.mdc?$/i.test(entry.name)) continue;
43
+ const file = relative(root, full).split(sep).join('/');
44
+ try {
45
+ const item = readDocument(full);
46
+ const summary = { file, title: item.doc.title, version: item.version, cards: item.doc.cards.length,
47
+ warnings: item.diagnostics.filter(d => d.severity === 'warn').length, modified: statSync(full).mtime.toISOString() };
48
+ if (item.diagnostics.some(d => d.severity === 'error')) { skipped.push({ file, diagnostics: item.diagnostics }); continue; }
49
+ documents.push(summary); parsed.set(file, { ...item, ...summary });
50
+ } catch (error) { skipped.push({ file, diagnostics: [{severity:'error',code:'READ_FAILED',message:error.message}] }); }
51
+ }
52
+ };
53
+ walk(root); return { documents, skipped, parsed };
54
+ }
55
+ export function workspacePath(root, file, create = false, resource = false) {
56
+ if (typeof file !== 'string' || !file || (!resource && !/\.mdc?$/i.test(file)) || file.includes('\0')) throw new DocumentError('需要目录内的 .mdc 或 .md 相对路径。');
57
+ const path = resolve(root, file), prefix = realpathSync(root) + sep;
58
+ if (!path.startsWith(resolve(root) + sep)) throw new DocumentError('路径超出当前目录。', 403);
59
+ let check = path;
60
+ while (!existsSync(check)) check = dirname(check);
61
+ const actual = realpathSync(check);
62
+ if (actual !== realpathSync(root) && !actual.startsWith(prefix)) throw new DocumentError('路径指向当前目录之外。', 403);
63
+ if (!create && !existsSync(path)) throw new DocumentError('文档不存在。', 404);
64
+ return path;
65
+ }
@@ -0,0 +1,101 @@
1
+ import { posix } from 'node:path';
2
+ import { markdownLinks } from '../core/links.js';
3
+ import { mediaLinkLocations } from '../core/media-links.js';
4
+ import { treeOf, records, samePath, insidePath, serializeTree } from './tree.js';
5
+ import { fail } from './storage.js';
6
+
7
+ const decode = value => { try { return decodeURIComponent(value); } catch { return value; } };
8
+ export function resolveReference(target, sourceFile, documents) {
9
+ if (/^(?:[a-z][a-z0-9+.-]*:|\/\/|\/)/i.test(target)) return null;
10
+ let file = sourceFile, wanted = target;
11
+ const match = /^(.*?\.mdc?)(?:#(.*))?$/i.exec(target);
12
+ if (match) { file = posix.normalize(posix.join(posix.dirname(sourceFile), decode(match[1]))); wanted = match[2] ?? ''; }
13
+ else if (/\.(?:png|jpe?g|gif|webp|svg|pdf|txt|json|csv)(?:#|$)/i.test(target)) return null;
14
+ if (file.startsWith('../') || !documents.has(file)) return { file, path: null, missing: true };
15
+ wanted = decode(wanted); if (wanted.startsWith('#')) wanted = wanted.slice(1);
16
+ if (!wanted) return { file, path: null };
17
+ const all = records(treeOf(documents.get(file), file));
18
+ let hits = all.filter(r => r.path.join('.') === wanted);
19
+ if (!hits.length) hits = all.filter(r => r.node.title === wanted);
20
+ if (!hits.length) hits = all.filter(r => r.path.slice(1).some((_, i) => r.path.slice(i + 1).join('.') === wanted));
21
+ if (!hits.length) {
22
+ for (let cut = wanted.indexOf('#'); cut > 0; cut = wanted.indexOf('#', cut + 1)) {
23
+ const head = wanted.slice(0, cut), tail = wanted.slice(cut + 1);
24
+ const owners = all.filter(r => r.node.title === head || r.path.join('.') === head);
25
+ if (!owners.length) continue;
26
+ hits = all.filter(r => owners.some(o => insidePath(r.path, o.path) && r.path.length > o.path.length) && (r.node.title === tail || r.path.slice(1).join('.') === tail));
27
+ break;
28
+ }
29
+ }
30
+ return hits.length === 1 ? { file, path: hits[0].path } : { file, path: null, missing: true, ambiguous: hits.length > 1 };
31
+ }
32
+ export function linkHref(sourceFile, targetFile, targetPath) {
33
+ const path = targetPath?.join('.') || '';
34
+ const encoded = encodeURIComponent(path).replace(/[!'()*]/g, ch => '%' + ch.charCodeAt(0).toString(16).toUpperCase());
35
+ if (sourceFile === targetFile && path) return encoded;
36
+ const file = posix.relative(posix.dirname(sourceFile), targetFile).split('/').map(encodeURIComponent).join('/');
37
+ return file + (path ? '#' + encoded : '');
38
+ }
39
+ export function allReferences(documents) {
40
+ const result = [];
41
+ for (const [file, source] of documents) {
42
+ for (const record of records(treeOf(source, file))) {
43
+ const links = markdownLinks(record.node.content), media = mediaLinkLocations(record.node.content, links);
44
+ for (const link of links) {
45
+ const target = resolveReference(link.target, file, documents);
46
+ if (target) result.push({ file, node: record.path, target, label: link.label, link, ...(media.has(link.start) ? { media: media.get(link.start) } : {}) });
47
+ }
48
+ }
49
+ }
50
+ return result;
51
+ }
52
+ /** Rewrite inbound references and relative outbound links after a structural change. */
53
+ export function rewriteReferences(before, after, mapping, unlink = false) {
54
+ function map(file, path) {
55
+ if (file !== mapping.file) return { file, path };
56
+ if (mapping.path && (!path || !insidePath(path, mapping.path))) return { file, path };
57
+ if (mapping.deleted) return null;
58
+ return { file: mapping.newFile || file, path: mapping.path ? [...mapping.newPath, ...path.slice(mapping.path.length)] : path };
59
+ }
60
+ const patches = new Map();
61
+ for (const ref of allReferences(before)) {
62
+ if (mapping.copy && ref.file !== mapping.file) continue;
63
+ if (ref.target.missing) continue;
64
+ const source = map(ref.file, ref.node), target = map(ref.target.file, ref.target.path);
65
+ if (!source) continue;
66
+ if (!target && !unlink) fail('目标仍被引用;先断开引用,或显式使用 unlink。', 409, { code: 'REFERENCED', references: [{ file: ref.file, node: ref.node, label: ref.label }] });
67
+ if (target && source.file === ref.file && target.file === ref.target.file && samePath(target.path, ref.target.path)) continue;
68
+ const key = JSON.stringify(source);
69
+ if (!patches.has(key)) patches.set(key, { ...source, edits: [] });
70
+ const label = target?.path && ref.target.path && ref.label === ref.target.path.at(-1) ? target.path.at(-1) : ref.label;
71
+ const title = ref.link.title?.startsWith('clado:') ? ' "' + ref.link.title + '"' : '';
72
+ patches.get(key).edits.push({ start: ref.link.start, end: ref.link.end, text: target ? '[' + label + '](<' + linkHref(source.file, target.file, target.path) + '>' + title + ')' : ref.media ? '' : ref.label });
73
+ }
74
+ // 文件或子树跨目录后,图片、附件及原本未解析的文件链接也保持原目标。
75
+ for (const [file, text] of before) for (const record of records(treeOf(text, file))) {
76
+ const source = map(file, record.path);
77
+ if (!source || source.file === file) continue;
78
+ for (const link of markdownLinks(record.node.content, { includeImages: true })) {
79
+ if (/^(?:[a-z][a-z0-9+.-]*:|\/\/|\/|#)/i.test(link.target)) continue;
80
+ const target = resolveReference(link.target, file, before);
81
+ if (!link.image && target && !target.missing) continue;
82
+ const parts = /^([^?#]+)([?#][\s\S]*)?$/.exec(link.target);
83
+ if (!parts || !link.image && !parts[1].includes('/') && !/\.(?:mdc?|png|jpe?g|gif|webp|svg|pdf|txt|json|csv)$/i.test(parts[1])) continue;
84
+ const absolute = posix.normalize(posix.join(posix.dirname(file), decode(parts[1])));
85
+ const relative = posix.relative(posix.dirname(source.file), absolute) || '.';
86
+ const href = relative.split('/').map(encodeURIComponent).join('/') + (parts[2] || '');
87
+ if (href === link.target) continue;
88
+ const key = JSON.stringify(source);
89
+ if (!patches.has(key)) patches.set(key, { ...source, edits: [] });
90
+ patches.get(key).edits.push({ start: link.targetStart, end: link.targetEnd, text: href });
91
+ }
92
+ }
93
+ const trees = new Map();
94
+ for (const patch of patches.values()) {
95
+ if (!trees.has(patch.file)) trees.set(patch.file, treeOf(after.get(patch.file), patch.file));
96
+ const tree = trees.get(patch.file), record = records(tree).find(r => samePath(r.path, patch.path));
97
+ if (!record) fail('修改后找不到引用所在节点。', 409);
98
+ for (const edit of patch.edits.sort((a, b) => b.start - a.start)) record.node.content = record.node.content.slice(0, edit.start) + edit.text + record.node.content.slice(edit.end);
99
+ }
100
+ for (const [file, tree] of trees) after.set(file, serializeTree(tree));
101
+ }