源码索引 / CURRENT IMPLEMENTATION
site/scripts/excerpts.mjs
35 行 · 点击行号可定位;函数链接随声明位置更新,不手填行号。
// Extract once, after ordinary Markdown links are rewritten. Never re-parse
// a marker that happens to occur inside the source code being displayed.
const marker = /<!-- source: ([^\n]+):(\d+)-(\d+) -->/g;
const linesOf = code => code.replace(/\n$/, '').split('\n');
export function expandExcerpts(body, sources, used) {
if (/<!--\s*source:/.test(body.replace(marker, ''))) throw new Error('Malformed source marker');
return body.replace(marker, (_whole, name, first, last) => {
const source = sources.get(name);
if (!source) throw new Error(`Unlisted teaching source: ${name}`);
const lines = linesOf(source.code), start = Number(first), end = Number(last);
if (start < 1 || end < start || end > lines.length) throw new Error(`Invalid source range: ${name}:${start}-${end} (file has ${lines.length})`);
const seen = used.get(name) || new Set();
for (let n = start; n <= end; n++) seen.add(n);
used.set(name, seen);
const code = lines.slice(start - 1, end).join('\n');
const longest = Math.max(2, ...(code.match(/`+/g) || []).map(s=>s.length));
const fence = '`'.repeat(longest + 1);
const notice = source.redacted && (start === 1 || code.includes('[REDACTED:')) ? '\n> 此文件的私有运行环境规则已在公开展示中隐藏;行号保持对应本机源码。\n' : '';
return `\n**\`${name}\` · L${start}–L${end}** · [打开完整源码](/code/${source.id}/#L${start})\n${notice}\n<div class="code-excerpt" style="--line-start:${start-1}">\n\n${fence}${source.lang}\n${code}\n${fence}\n\n</div>\n`;
});
}
// This checks displayed source coverage, not the semantic quality of prose.
export function verifyCoverage(sources, expected, used) {
return [...new Set(expected)].map(name => {
const source = sources.get(name);
if (!source) throw new Error(`Unlisted coverage target: ${name}`);
const lines = linesOf(source.code), seen = used.get(name) || new Set();
const meaningful = lines.map((text,i)=>text.trim() ? i+1 : 0).filter(Boolean);
const missing = meaningful.filter(n=>!seen.has(n));
if (missing.length) throw new Error(`Uncovered source lines: ${name}: ${missing.join(', ')}`);
return {name, lines:lines.length, covered:meaningful.length};
});
}