cladogram 0.4.0 → 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.
- package/README.md +59 -108
- package/bin/clado.js +73 -101
- package/package.json +11 -8
- package/skills/clado/SKILL.md +170 -53
- package/src/core/links.js +37 -0
- package/src/core/media-links.js +99 -0
- package/src/core/parse.js +65 -77
- package/src/html/app-css.js +10 -20
- package/src/html/canvas-card.js +1 -2
- package/src/html/canvas-chain.js +64 -36
- package/src/html/canvas-focus.js +81 -81
- package/src/html/canvas-ui.css +22 -5
- package/src/html/canvas-ui.js +3 -1
- package/src/html/canvas-wires.js +28 -11
- package/src/html/media-anchors.js +212 -0
- package/src/html/mindmap-connectors.js +33 -12
- package/src/html/page.js +8 -5
- package/src/html/runtime-api.js +7 -18
- package/src/html/runtime-fixes.js +0 -9
- package/src/html/runtime.js +156 -131
- package/src/server/assets/library-canvas.js +18 -12
- package/src/server/assets/library.html +2 -2
- package/src/server/assets/library.js +56 -23
- package/src/server/assets/tree.js +1 -1
- package/src/server/export.js +1 -1
- package/src/server/mcp.js +108 -0
- package/src/server/workspace.js +26 -37
- package/src/skill/install.js +16 -18
- package/src/skill/targets.js +17 -10
- package/src/skill/templates.js +60 -0
- package/src/util/version.js +3 -0
- package/src/workspace/content.js +72 -0
- package/src/workspace/documents.js +4 -82
- package/src/workspace/references.js +101 -0
- package/src/workspace/service.js +457 -0
- package/src/workspace/storage.js +169 -0
- package/src/workspace/tree.js +66 -0
- package/templates/business-flow.mdc +29 -0
- package/templates/call-chain.mdc +62 -0
- package/templates/data-design.mdc +35 -0
- package/templates/mind-expansion.mdc +52 -0
- package/templates/requirement-overview.mdc +29 -0
- package/templates/system-state.mdc +29 -0
- package/examples/showcase/README.md +0 -117
- package/examples/showcase/baseline.md +0 -365
- package/examples/showcase/build.sh +0 -48
- package/examples/showcase/calls.md +0 -136
- package/examples/showcase/fulfill-cn.md +0 -351
- package/examples/showcase/fulfill.md +0 -271
- package/examples/showcase/index.md +0 -187
- package/examples/showcase/order.md +0 -195
- package/examples/showcase/promo.md +0 -580
- package/examples/showcase/refund.md +0 -966
- package/examples/showcase/seckill.md +0 -787
- package/skills/clado/examples/01-/351/234/200/346/261/202/346/240/221.md +0 -32
- package/skills/clado/examples/02-/346/225/260/346/215/256/350/241/250.md +0 -44
- package/skills/clado/examples/03-/346/216/245/345/217/243/346/270/205/345/215/225.md +0 -51
- package/skills/clado/examples/04-/346/226/271/346/263/225/351/223/276.md +0 -70
- package/skills/clado/examples/05-/346/216/245/345/217/243/350/260/203/347/224/250.md +0 -58
- package/skills/clado/examples/06-/350/260/203/347/224/250/351/223/276.md +0 -49
- package/skills/clado/examples/07-/346/213/206/346/226/207/346/241/243/index.md +0 -38
- package/skills/clado/examples/07-/346/213/206/346/226/207/346/241/243/refund.md +0 -33
- package/skills/clado/examples/07-/346/213/206/346/226/207/346/241/243/seckill.md +0 -56
- 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
- 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
- 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
- package/skills/clado/examples/09-/345/215/217/344/275/234/347/224/273/345/270/203/backend.md +0 -80
- package/skills/clado/examples/09-/345/215/217/344/275/234/347/224/273/345/270/203/data.md +0 -53
- package/skills/clado/examples/09-/345/215/217/344/275/234/347/224/273/345/270/203/interaction.md +0 -70
- package/skills/clado/examples/09-/345/215/217/344/275/234/347/224/273/345/270/203/overview.md +0 -30
- package/skills/clado/examples/09-/345/215/217/344/275/234/347/224/273/345/270/203/verify.md +0 -35
- package/skills/clado/examples/10-/346/235/203/351/231/220/347/224/263/350/257/267/approval.md +0 -69
- package/skills/clado/examples/10-/346/235/203/351/231/220/347/224/263/350/257/267/data-verify.md +0 -49
- package/skills/clado/examples/10-/346/235/203/351/231/220/347/224/263/350/257/267/interaction.md +0 -47
- package/skills/clado/examples/10-/346/235/203/351/231/220/347/224/263/350/257/267/overview.md +0 -39
- package/skills/clado/examples/11-/344/272/213/346/225/205/345/223/215/345/272/224/evidence.md +0 -42
- package/skills/clado/examples/11-/344/272/213/346/225/205/345/223/215/345/272/224/overview.md +0 -26
- package/skills/clado/examples/11-/344/272/213/346/225/205/345/223/215/345/272/224/response.md +0 -64
- package/skills/clado/examples/12-/346/216/245/345/217/243/345/210/260/344/273/243/347/240/201/api.md +0 -127
- package/skills/clado/examples/12-/346/216/245/345/217/243/345/210/260/344/273/243/347/240/201/caller.md +0 -50
- package/skills/clado/examples/12-/346/216/245/345/217/243/345/210/260/344/273/243/347/240/201/calls.md +0 -185
- package/skills/clado/examples/12-/346/216/245/345/217/243/345/210/260/344/273/243/347/240/201/code.md +0 -249
- package/skills/clado/examples/12-/346/216/245/345/217/243/345/210/260/344/273/243/347/240/201/consumer.md +0 -93
- package/skills/clado/examples/12-/346/216/245/345/217/243/345/210/260/344/273/243/347/240/201/contracts.md +0 -89
- package/skills/clado/examples/12-/346/216/245/345/217/243/345/210/260/344/273/243/347/240/201/data.md +0 -237
- package/skills/clado/examples/12-/346/216/245/345/217/243/345/210/260/344/273/243/347/240/201/overview.md +0 -75
- package/skills/clado/examples/12-/346/216/245/345/217/243/345/210/260/344/273/243/347/240/201/publisher.md +0 -175
- package/skills/clado/examples/12-/346/216/245/345/217/243/345/210/260/344/273/243/347/240/201/verify.md +0 -53
- package/skills/clado/examples/13-/346/216/245/345/217/243/346/226/271/346/263/225/345/210/260SQL/01-/347/224/263/350/257/267/350/275/254/345/215/225.md +0 -499
- package/skills/clado/examples/13-/346/216/245/345/217/243/346/226/271/346/263/225/345/210/260SQL/02-/345/267/262/346/234/211/350/256/242/345/215/225/346/216/245/345/217/243.md +0 -46
- package/skills/clado/examples/13-/346/216/245/345/217/243/346/226/271/346/263/225/345/210/260SQL/03-/350/241/250/347/273/223/346/236/204.md +0 -100
- package/skills/clado/examples/13-/346/216/245/345/217/243/346/226/271/346/263/225/345/210/260SQL/overview.md +0 -47
- package/skills/clado/examples/build.sh +0 -47
- package/skills/clado/references/content-patterns.md +0 -61
- package/skills/clado/references/data.md +0 -37
- package/skills/clado/references/delivery.md +0 -57
- package/skills/clado/references/diagnostics.md +0 -26
- package/skills/clado/references/editing.md +0 -49
- package/skills/clado/references/engineering.md +0 -167
- package/skills/clado/references/flows.md +0 -53
- package/skills/clado/references/interactions.md +0 -46
- package/skills/clado/references/operations.md +0 -39
- package/skills/clado/references/requirements.md +0 -37
- package/skills/clado/references/verification.md +0 -27
- package/src/html/mindmap-motion.js +0 -69
- package/src/server/assets/editor.css +0 -1
- package/src/server/assets/editor.js +0 -79
- package/src/workspace/commands.js +0 -42
|
@@ -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,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
|
+
}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { readFileSync,
|
|
1
|
+
import { readFileSync, existsSync, statSync, readdirSync, realpathSync } from 'node:fs';
|
|
2
2
|
import { resolve, dirname, relative, basename, extname, sep } from 'node:path';
|
|
3
|
-
import { createHash
|
|
3
|
+
import { createHash } from 'node:crypto';
|
|
4
4
|
import { parseDocument, headingOf, fenceOf, splitFrontMatter } from '../core/parse.js';
|
|
5
5
|
|
|
6
6
|
export class DocumentError extends Error {
|
|
@@ -32,84 +32,6 @@ export function inspectSource(source, file = '') {
|
|
|
32
32
|
return { source, version: versionOf(source), doc, diagnostics, sections };
|
|
33
33
|
}
|
|
34
34
|
export function readDocument(file) { return inspectSource(readFileSync(file, 'utf8'), file); }
|
|
35
|
-
export function validateSource(source, file) {
|
|
36
|
-
const result = inspectSource(source, file);
|
|
37
|
-
if (result.diagnostics.some(d => d.severity === 'error')) throw new DocumentError('Markdown 解析失败,未写入。', 422, result.diagnostics);
|
|
38
|
-
return result;
|
|
39
|
-
}
|
|
40
|
-
export function writeDocument(file, source, { create = false, version } = {}) {
|
|
41
|
-
if (typeof source !== 'string') throw new DocumentError('Markdown 源文必须是字符串。');
|
|
42
|
-
if (!/\.md$/i.test(file)) throw new DocumentError('文档必须使用 .md 扩展名。');
|
|
43
|
-
const initial = existsSync(file) ? versionOf(readFileSync(file,'utf8')) : null;
|
|
44
|
-
const expected = version || initial;
|
|
45
|
-
const result = validateSource(source, file);
|
|
46
|
-
mkdirSync(dirname(file), { recursive: true });
|
|
47
|
-
const lock = resolve(dirname(file), '.' + basename(file) + '.clado-lock');
|
|
48
|
-
let descriptor;
|
|
49
|
-
try { descriptor = openSync(lock,'wx',0o600); }
|
|
50
|
-
catch(error) {
|
|
51
|
-
if (error.code !== 'EEXIST') throw error;
|
|
52
|
-
let stale = false;
|
|
53
|
-
try { const owner=JSON.parse(readFileSync(lock,'utf8')); try { process.kill(owner.pid,0); } catch(e) { stale=e.code==='ESRCH'; } } catch {}
|
|
54
|
-
if (stale) { try { unlinkSync(lock); descriptor=openSync(lock,'wx',0o600); } catch {} }
|
|
55
|
-
if (descriptor === undefined) throw new DocumentError('文档正在被另一个写入者保存,请重新读取后重试。',409);
|
|
56
|
-
}
|
|
57
|
-
const temporary = resolve(dirname(file), '.' + basename(file) + '.' + randomBytes(6).toString('hex') + '.tmp');
|
|
58
|
-
try {
|
|
59
|
-
writeFileSync(descriptor, JSON.stringify({pid:process.pid}));
|
|
60
|
-
if (create && existsSync(file)) throw new DocumentError('文档已经存在,未覆盖。',409);
|
|
61
|
-
if (!create && !existsSync(file)) throw new DocumentError('找不到要修改的文档。',404);
|
|
62
|
-
if (!create && expected !== versionOf(readFileSync(file,'utf8'))) throw new DocumentError('文件已被其他编辑修改,请重新读取后再保存。',409);
|
|
63
|
-
writeFileSync(temporary, source, { flag:'wx', mode:existsSync(file) ? statSync(file).mode & 0o777 : 0o644 });
|
|
64
|
-
if (!create && expected !== versionOf(readFileSync(file,'utf8'))) throw new DocumentError('文件已变化,请重新读取。',409);
|
|
65
|
-
renameSync(temporary,file);
|
|
66
|
-
} finally {
|
|
67
|
-
if (existsSync(temporary)) unlinkSync(temporary);
|
|
68
|
-
closeSync(descriptor); unlinkSync(lock);
|
|
69
|
-
}
|
|
70
|
-
return result;
|
|
71
|
-
}
|
|
72
|
-
|
|
73
|
-
export function mutateNode(file, action, { parent, target, title, content = '', version } = {}) {
|
|
74
|
-
if (typeof content !== 'string') throw new DocumentError('节点正文必须是字符串。');
|
|
75
|
-
const current = readDocument(file), lines = current.source.split(/\r?\n/);
|
|
76
|
-
if (version && version !== current.version) throw new DocumentError('文件版本冲突,请重新读取。', 409);
|
|
77
|
-
// 节点正文可以含围栏示例,不能偷偷引入其他节点。
|
|
78
|
-
if (inspectSource('# 正文\n\n' + content).sections.length !== 1) throw new DocumentError('节点正文含标题。新增节点请用 node add,改整篇结构请用 doc update。');
|
|
79
|
-
const find = path => {
|
|
80
|
-
const hits = current.sections.filter(s => s.path === path);
|
|
81
|
-
if (hits.length !== 1) throw new DocumentError(hits.length ? '节点路径不唯一,请先调整重名。' : '找不到节点,请用 doc read 查看完整路径。', 404);
|
|
82
|
-
return hits[0];
|
|
83
|
-
};
|
|
84
|
-
if (action === 'add') {
|
|
85
|
-
if (!title || /[\r\n]/.test(title)) throw new DocumentError('新增节点需要单行 --title。');
|
|
86
|
-
const p = parent ? find(parent) : null, level = p ? p.level + 1 : 1;
|
|
87
|
-
if (level > 6) throw new DocumentError('最深为 L6,请新建文档并用 .md 链接关联。');
|
|
88
|
-
const path = p ? p.path + '.' + title : title;
|
|
89
|
-
if (current.sections.some(s => s.path === path)) throw new DocumentError('这个父节点下已有同名标题。', 409);
|
|
90
|
-
lines.splice(p ? p.end : lines.length, 0, '', '#'.repeat(level) + ' ' + title, '', content.trim(), '');
|
|
91
|
-
} else if (action === 'update') {
|
|
92
|
-
const s = find(target);
|
|
93
|
-
lines.splice(s.start + 1, s.bodyEnd - s.start - 1, '', content.trim(), '');
|
|
94
|
-
} else throw new DocumentError('node 只支持 add / update。');
|
|
95
|
-
const candidate = lines.join('\n');
|
|
96
|
-
const next = inspectSource(candidate,file);
|
|
97
|
-
const signature = s => s.path + ':' + s.level;
|
|
98
|
-
const before = current.sections.map(signature);
|
|
99
|
-
const after = next.sections.map(signature);
|
|
100
|
-
if (action === 'add') {
|
|
101
|
-
const addedPath = parent ? parent + '.' + title : title;
|
|
102
|
-
const index = next.sections.findIndex(s=>s.path===addedPath);
|
|
103
|
-
if (index >= 0) after.splice(index,1);
|
|
104
|
-
if (index < 0 || next.sections.length !== current.sections.length + 1) throw new DocumentError('新增内容改变了其他节点结构,请检查标题或未闭合围栏。');
|
|
105
|
-
}
|
|
106
|
-
if (JSON.stringify(before) !== JSON.stringify(after)) throw new DocumentError('正文改变了已有节点结构,可能含未闭合围栏;未写入。');
|
|
107
|
-
// 即使位于最后一个节点,未闭合围栏也不能保存为正文。
|
|
108
|
-
let fence = null;
|
|
109
|
-
for (const line of content.split(/\r?\n/)) { const f=fenceOf(line); if(f) { if(!fence)fence=f[1];else if(f[1][0]===fence[0]&&f[1].length>=fence.length)fence=null; } }
|
|
110
|
-
if (fence) throw new DocumentError('正文代码围栏未闭合,未写入。');
|
|
111
|
-
return writeDocument(file, candidate, { version: current.version });
|
|
112
|
-
}
|
|
113
35
|
export function scanDirectory(root) {
|
|
114
36
|
const documents = [], skipped = [], parsed = new Map();
|
|
115
37
|
const walk = directory => {
|
|
@@ -117,7 +39,7 @@ export function scanDirectory(root) {
|
|
|
117
39
|
if (entry.name.startsWith('.') || ['node_modules','dist'].includes(entry.name)) continue;
|
|
118
40
|
const full = resolve(directory, entry.name);
|
|
119
41
|
if (entry.isDirectory()) { walk(full); continue; }
|
|
120
|
-
if (!entry.isFile() || !/\.
|
|
42
|
+
if (!entry.isFile() || !/\.mdc?$/i.test(entry.name)) continue;
|
|
121
43
|
const file = relative(root, full).split(sep).join('/');
|
|
122
44
|
try {
|
|
123
45
|
const item = readDocument(full);
|
|
@@ -131,7 +53,7 @@ export function scanDirectory(root) {
|
|
|
131
53
|
walk(root); return { documents, skipped, parsed };
|
|
132
54
|
}
|
|
133
55
|
export function workspacePath(root, file, create = false, resource = false) {
|
|
134
|
-
if (typeof file !== 'string' || !file || (!resource && !/\.
|
|
56
|
+
if (typeof file !== 'string' || !file || (!resource && !/\.mdc?$/i.test(file)) || file.includes('\0')) throw new DocumentError('需要目录内的 .mdc 或 .md 相对路径。');
|
|
135
57
|
const path = resolve(root, file), prefix = realpathSync(root) + sep;
|
|
136
58
|
if (!path.startsWith(resolve(root) + sep)) throw new DocumentError('路径超出当前目录。', 403);
|
|
137
59
|
let check = path;
|
|
@@ -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
|
+
}
|