@namewta/skills-hub 0.1.47 → 0.1.48
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 +1 -1
- package/THIRD_PARTY_NOTICES.md +3 -3
- package/package.json +1 -1
- package/scripts/persistence/home.md +1 -0
- package/skills/dev/dev-archive/references/change-closure.md +4 -0
- package/skills/home/home-project-changelog/SKILL.md +2 -2
- package/skills/home/home-project-changelog/references/tools.md +8 -0
- package/skills/home/home-project-changelog/references/workflow.md +3 -0
- package/skills/home/home-project-changelog/scripts/storage.mjs +8 -2
- package/skills/home/home-setup/SKILL.md +1 -1
- package/skills/home/home-setup/references/registry.md +4 -0
- package/skills/home/home-setup/scripts/git.mjs +2 -0
- package/skills/home/home-website/SKILL.md +20 -0
- package/skills/home/home-website/assets/website/gitignore.tmpl +4 -0
- package/skills/home/home-website/assets/website/package-lock.json +2376 -0
- package/skills/home/home-website/assets/website/package.json +11 -0
- package/skills/home/home-website/assets/website/scripts/artifact.mjs +84 -0
- package/skills/home/home-website/assets/website/scripts/inputs.mjs +209 -0
- package/skills/home/home-website/assets/website/scripts/preview.mjs +50 -0
- package/skills/home/home-website/assets/website/scripts/render.mjs +92 -0
- package/skills/home/home-website/assets/website/scripts/site.mjs +173 -0
- package/skills/home/home-website/assets/website/site/.vitepress/theme/index.js +3 -0
- package/skills/home/home-website/assets/website/site/public/home-assets/app.js +292 -0
- package/skills/home/home-website/assets/website/site/public/home-assets/site.css +337 -0
- package/skills/home/home-website/assets/website/site/public/home-assets/start.js +7 -0
- package/skills/home/home-website/assets/website/site/templates/layout.mjs +81 -0
- package/skills/home/home-website/assets/website/site/templates/ledger.mjs +53 -0
- package/skills/home/home-website/assets/website/site/templates/model.mjs +66 -0
- package/skills/home/home-website/assets/website/site/templates/pages.mjs +93 -0
- package/skills/home/home-website/assets/website/site/templates/project-logs.mjs +114 -0
- package/skills/home/home-website/assets/website/site.config.json +6 -0
- package/skills/home/home-website/references/website.md +85 -0
- package/skills/home/home-website/scripts/init.mjs +57 -0
- package/skills/home/home-workflow/SKILL.md +1 -0
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "home-website",
|
|
3
|
+
"private": true,
|
|
4
|
+
"type": "module",
|
|
5
|
+
"engines": {"node": ">=22.14.0"},
|
|
6
|
+
"scripts": {
|
|
7
|
+
"build": "node scripts/site.mjs refresh",
|
|
8
|
+
"preview": "node scripts/site.mjs preview"
|
|
9
|
+
},
|
|
10
|
+
"devDependencies": {"vitepress": "1.6.4"}
|
|
11
|
+
}
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { createHash } from 'node:crypto';
|
|
4
|
+
import { directory, read } from './inputs.mjs';
|
|
5
|
+
|
|
6
|
+
export function files(root, relative = '') {
|
|
7
|
+
const here = path.join(root,relative);
|
|
8
|
+
if (!directory(here)) throw Error('缺少目录:'+path.basename(here));
|
|
9
|
+
return fs.readdirSync(here,{withFileTypes:true}).sort((a,b) => a.name.localeCompare(b.name,'en')).flatMap(entry => {
|
|
10
|
+
const name = relative ? relative+'/'+entry.name : entry.name;
|
|
11
|
+
if (entry.isDirectory()) return files(root,name);
|
|
12
|
+
if (!entry.isFile()) throw Error('目录含非普通文件:'+name);
|
|
13
|
+
return [name];
|
|
14
|
+
});
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export function fingerprint(website, model) {
|
|
18
|
+
const source = [...files(website,'scripts'),...files(website,'site'),'package.json','package-lock.json'];
|
|
19
|
+
const hash = createHash('sha256').update(JSON.stringify(model));
|
|
20
|
+
for (const name of source) {
|
|
21
|
+
const bytes = read(path.join(website,name));
|
|
22
|
+
if (!bytes) throw Error('缺少网站工程文件:'+name);
|
|
23
|
+
hash.update(JSON.stringify([name,createHash('sha256').update(bytes).digest('hex')]));
|
|
24
|
+
}
|
|
25
|
+
return hash.digest('hex');
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export function manifest(root, names = files(root)) {
|
|
29
|
+
return names.map(name => {
|
|
30
|
+
const bytes = read(path.join(root,name));
|
|
31
|
+
if (!bytes) throw Error('制品在核对时发生变化:'+name);
|
|
32
|
+
return [name,createHash('sha256').update(bytes).digest('hex')];
|
|
33
|
+
});
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
const isOutputFile = name => /^(?:index\.html|404\.html|changelog\/index\.html|projects\/(?:index\.html|[a-z0-9][a-z0-9-]*\/(?:changelog\/)?index\.html)|data\/(?:catalog\.json|projects\/[a-z0-9][a-z0-9-]*\.json)|home-assets\/(?:app\.js|search-index\.js|start\.js|site\.css)|assets\/[A-Za-z0-9_./-]+\.(?:js|css|map|woff2?)|hashmap\.json|vp-icons\.css)$/u.test(name);
|
|
37
|
+
|
|
38
|
+
function publicPath(url,base) {
|
|
39
|
+
const [pathname,anchor] = url.split('#');
|
|
40
|
+
const name = pathname.slice(base.length);
|
|
41
|
+
return [!name || name.endsWith('/') ? name+'index.html' : name, anchor];
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export function validateArtifact(candidate, base) {
|
|
45
|
+
const {dist,urls,expectedData,index} = candidate;
|
|
46
|
+
const output = files(dist);
|
|
47
|
+
const found = new Set(output);
|
|
48
|
+
const required = new Set([...urls,...expectedData.keys(),'home-assets/site.css','home-assets/app.js','home-assets/start.js']);
|
|
49
|
+
for (const name of output) {
|
|
50
|
+
if (!isOutputFile(name) || (/^(?:projects|data)\//u.test(name) && !required.has(name))) throw Error('静态制品含未声明文件:'+name);
|
|
51
|
+
}
|
|
52
|
+
for (const name of required) {
|
|
53
|
+
if (!found.has(name)) throw Error('静态制品缺少:'+name);
|
|
54
|
+
}
|
|
55
|
+
const bodies = new Map(urls.map(name => [name, fs.readFileSync(path.join(dist,name),'utf8')]));
|
|
56
|
+
const namedTargets = new Map();
|
|
57
|
+
for (const [name,html] of bodies) {
|
|
58
|
+
const ids = [...html.matchAll(/\sid="([^"]+)"/gu)].map(([,id]) => id);
|
|
59
|
+
const targets = new Set(ids);
|
|
60
|
+
if (targets.size !== ids.length) throw Error(name+' 含重复的页面锚点。');
|
|
61
|
+
namedTargets.set(name,targets);
|
|
62
|
+
}
|
|
63
|
+
const origin = 'http://localhost';
|
|
64
|
+
for (const [name, html] of bodies) {
|
|
65
|
+
if (!html.includes('class="home-site"') || !html.includes('id="main"')) throw Error(name+' 缺少服务器渲染的正文。');
|
|
66
|
+
for (const [,url] of html.matchAll(/\b(?:href|src)="([^"]+)"/gu)) {
|
|
67
|
+
const location = new URL(url, origin+base+name);
|
|
68
|
+
if (url.startsWith('//') || location.origin === origin && !location.pathname.startsWith(base)) {
|
|
69
|
+
throw Error(name+' 的链接超出站点前缀:'+url);
|
|
70
|
+
}
|
|
71
|
+
if (location.origin !== origin) continue;
|
|
72
|
+
const [target,anchor] = publicPath(location.pathname+location.hash,base);
|
|
73
|
+
if (!found.has(target) || (anchor && !namedTargets.get(target)?.has(anchor))) throw Error(name+' 中的链接无法定位:'+url);
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
for (const item of index) {
|
|
77
|
+
const [target,anchor] = publicPath(base+item.url,base);
|
|
78
|
+
if (!bodies.has(target) || (anchor && !namedTargets.get(target).has(anchor))) throw Error('搜索目标不存在:'+item.url);
|
|
79
|
+
}
|
|
80
|
+
for (const [name,expected] of expectedData) {
|
|
81
|
+
if (fs.readFileSync(path.join(dist,name),'utf8') !== expected) throw Error(name+' 的公开数据与本轮不一致。');
|
|
82
|
+
}
|
|
83
|
+
return output;
|
|
84
|
+
}
|
|
@@ -0,0 +1,209 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { createHash } from 'node:crypto';
|
|
4
|
+
import { parseMarkdown, validDay } from '../site/templates/project-logs.mjs';
|
|
5
|
+
|
|
6
|
+
const idPattern = /^[a-z0-9][a-z0-9-]*$/u;
|
|
7
|
+
const plain = value => !!value && typeof value === 'object' && !Array.isArray(value);
|
|
8
|
+
const line = value => typeof value === 'string' && value.trim() && !/[\x00-\x1f\x7f]/u.test(value);
|
|
9
|
+
const decode = value => new TextDecoder('utf-8', { fatal: true }).decode(value);
|
|
10
|
+
const colors = ['amber', 'teal', 'blue', 'plum', 'coral', 'moss'];
|
|
11
|
+
const marks = ['layers', 'signal', 'code', 'folio', 'route', 'book'];
|
|
12
|
+
|
|
13
|
+
export function directory(filename) {
|
|
14
|
+
const stat = fs.lstatSync(filename, {throwIfNoEntry:false});
|
|
15
|
+
if (stat && !stat.isDirectory()) throw Error('须使用普通目录:' + path.basename(filename));
|
|
16
|
+
return !!stat;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export function read(filename) {
|
|
20
|
+
const stat = fs.lstatSync(filename, {throwIfNoEntry:false});
|
|
21
|
+
if (!stat) return null;
|
|
22
|
+
if (!stat.isFile()) throw Error('须使用普通文件:' + path.basename(filename));
|
|
23
|
+
const fd = fs.openSync(filename, fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW ?? 0));
|
|
24
|
+
try {
|
|
25
|
+
const opened = fs.fstatSync(fd);
|
|
26
|
+
// Windows Node 22 may report an unavailable volume identifier as zero from lstat.
|
|
27
|
+
const sameDevice = opened.dev === stat.dev || process.platform === 'win32' && (!opened.dev || !stat.dev);
|
|
28
|
+
if (!opened.isFile() || opened.ino !== stat.ino || !sameDevice) throw Error('读取期间输入发生变化:' + path.basename(filename));
|
|
29
|
+
return fs.readFileSync(fd);
|
|
30
|
+
} finally {
|
|
31
|
+
fs.closeSync(fd);
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function checkKeys(value, allowed, label) {
|
|
36
|
+
if (!plain(value) || Object.keys(value).some(key => !allowed.includes(key))) throw Error(label + ' 含未知设置或格式错误。');
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function https(value) {
|
|
40
|
+
if (!line(value)) throw Error('公开链接须为单行 HTTPS URL。');
|
|
41
|
+
const url = new URL(value);
|
|
42
|
+
if (url.protocol !== 'https:' || url.username || url.password) throw Error('公开链接须为没有凭据的 HTTPS URL。');
|
|
43
|
+
return url.href;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function config(value) {
|
|
47
|
+
checkKeys(value, ['title', 'base', 'scope', 'publicGroups', 'overrides'], 'site.config.json');
|
|
48
|
+
const {title, base, scope = 'all', publicGroups = [], overrides = {}} = value;
|
|
49
|
+
if (!line(title) || typeof base !== 'string' || !/^\/(?:[a-zA-Z0-9_-][a-zA-Z0-9._-]*\/)*$/u.test(base) || scope !== 'all') {
|
|
50
|
+
throw Error('设置需要 title、以 / 包围的 base、scope 为 all。');
|
|
51
|
+
}
|
|
52
|
+
if (!Array.isArray(publicGroups) || !publicGroups.every(line) || !plain(overrides)) throw Error('publicGroups 或 overrides 格式错误。');
|
|
53
|
+
const byId = new Map();
|
|
54
|
+
for (const [id, item] of Object.entries(overrides)) {
|
|
55
|
+
if (!idPattern.test(id)) throw Error('overrides 使用登记项目 ID。');
|
|
56
|
+
checkKeys(item, ['hidden','showChangelog','displayName','summary','docsUrl','repoUrl'], id);
|
|
57
|
+
for (const key of ['hidden','showChangelog']) {
|
|
58
|
+
if (Object.hasOwn(item,key) && typeof item[key] !== 'boolean') throw Error(id+' 的 '+key+' 应为布尔值。');
|
|
59
|
+
}
|
|
60
|
+
for (const key of ['displayName','summary']) {
|
|
61
|
+
if (Object.hasOwn(item,key) && !line(item[key])) throw Error(id+' 的 '+key+' 应为单行文字。');
|
|
62
|
+
}
|
|
63
|
+
byId.set(id, {...item, ...(item.docsUrl !== undefined ? {docsUrl:https(item.docsUrl)} : {}), ...(item.repoUrl !== undefined ? {repoUrl:https(item.repoUrl)} : {})});
|
|
64
|
+
}
|
|
65
|
+
return {title, base, publicGroups, byId};
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
function records(value) {
|
|
69
|
+
if (!plain(value) || ![1,2].includes(value.formatVersion) || !Array.isArray(value.repos)) throw Error('repos.json 只支持 v1/v2 的 repos 数组。');
|
|
70
|
+
const seen = new Set();
|
|
71
|
+
for (const repo of value.repos) {
|
|
72
|
+
if (!plain(repo) || typeof repo.id !== 'string' || !idPattern.test(repo.id) || seen.has(repo.id) || !line(repo.purpose)) {
|
|
73
|
+
throw Error('repos.json 含无效或重复的项目 ID,或缺少单行用途。');
|
|
74
|
+
}
|
|
75
|
+
if (repo.groups !== undefined && (!Array.isArray(repo.groups) || !repo.groups.every(line))) throw Error(repo.id+' 的登记分组格式错误。');
|
|
76
|
+
seen.add(repo.id);
|
|
77
|
+
}
|
|
78
|
+
return value.repos;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
function readState(value) {
|
|
82
|
+
if (value === undefined) return {};
|
|
83
|
+
if (!plain(value) || value.formatVersion !== 1 || !plain(value.projects)) throw Error('changelogs/state.json 格式错误,请用 home-project-changelog 核对。');
|
|
84
|
+
for (const [id, project] of Object.entries(value.projects)) {
|
|
85
|
+
if (!idPattern.test(id) || !plain(project) || !plain(project.initialization) || !Array.isArray(project.ranges)
|
|
86
|
+
|| project.lastSuccessfulRangeId !== (project.ranges.at(-1)?.rangeId ?? null)
|
|
87
|
+
|| (Object.hasOwn(project,'pending') && !plain(project.pending))
|
|
88
|
+
|| !project.ranges.length && !project.pending) {
|
|
89
|
+
throw Error('changelogs/state.json 中 '+id+' 的记录无效,请用 home-project-changelog 核对。');
|
|
90
|
+
}
|
|
91
|
+
const ids = new Set();
|
|
92
|
+
let previous = null;
|
|
93
|
+
for (const range of project.ranges) {
|
|
94
|
+
const dates = range?.displayDates;
|
|
95
|
+
const commits = range?.stats?.rangeCommitCount;
|
|
96
|
+
const baseline = ['baseline','rebaseline'].includes(range?.kind);
|
|
97
|
+
if (!plain(range) || !line(range.rangeId) || ids.has(range.rangeId) || range.previousRangeId !== previous
|
|
98
|
+
|| typeof range.savedAt !== 'string' || !Number.isFinite(Date.parse(range.savedAt))
|
|
99
|
+
|| !['full-history','delta','baseline','rebaseline'].includes(range.kind)
|
|
100
|
+
|| !plain(dates) || !validDay(dates.to) || (dates.from !== null && (!validDay(dates.from) || dates.from > dates.to))
|
|
101
|
+
|| !Number.isSafeInteger(commits) || commits < 0 || (baseline && (dates.from !== null || commits !== 0))) {
|
|
102
|
+
throw Error('changelogs/state.json 中 '+id+' 的成功区间无效,请用 home-project-changelog 核对。');
|
|
103
|
+
}
|
|
104
|
+
ids.add(range.rangeId);
|
|
105
|
+
previous = range.rangeId;
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
return value.projects;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
function publicText(value, privateValues) {
|
|
112
|
+
let text = value
|
|
113
|
+
.replace(/!?\[([^\]\n]*)\]\([^\n)]*\)/gu, '$1')
|
|
114
|
+
.replace(/^[ \t]*\[[^\]\n]+\]:[^\n]*$/gmu, '〔链接定义〕');
|
|
115
|
+
for (const hidden of privateValues) text = text.replaceAll(hidden, '〔本地资料〕');
|
|
116
|
+
return text.replace(/(?:https?:\/\/|git:\/\/|ssh:\/\/|file:\/\/|ftp:\/\/|mailto:|www\.)[^\s<>,。;、))]+/giu, '〔链接〕')
|
|
117
|
+
.replace(/[\w.-]+@[\w.-]+:[^\s<>,。;、]+/gu,'〔链接〕')
|
|
118
|
+
.replace(/(?:\b[A-Za-z]:[\\/]|(?:\.\.?[\\/])+|(?<![\p{L}\d/])\/(?=[\w.-]+\/)|\\\\(?=[\w.-]+\\))[^\s<>,。;、)]+/gu, '〔本地路径〕')
|
|
119
|
+
.replace(/[\u0000-\u0009\u000b-\u001f\u007f]/gu, ' ');
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
function savedPeriods(id, parsed, saved, warnings) {
|
|
123
|
+
const oldest = [...parsed.periods].reverse();
|
|
124
|
+
function matches(period, range) {
|
|
125
|
+
const {from,to} = range.displayDates;
|
|
126
|
+
const legacyStart = range.kind === 'full-history' && from === null;
|
|
127
|
+
const baseline = range.kind === 'baseline' || range.kind === 'rebaseline';
|
|
128
|
+
return period.verified && period.to === to && (legacyStart || period.from === from)
|
|
129
|
+
&& period.commits === range.stats.rangeCommitCount && period.baseline === baseline;
|
|
130
|
+
}
|
|
131
|
+
function ordered(ranges, periods) {
|
|
132
|
+
const found = [];
|
|
133
|
+
let index = 0;
|
|
134
|
+
for (const range of ranges) {
|
|
135
|
+
while (index < periods.length && !matches(periods[index],range)) index += 1;
|
|
136
|
+
if (index === periods.length) throw Error(id+' 的成功区间无法核对 Markdown 日期、提交数或统计:'+range.displayDates.to+'。');
|
|
137
|
+
found.push(periods[index++]);
|
|
138
|
+
}
|
|
139
|
+
return found;
|
|
140
|
+
}
|
|
141
|
+
// 两个方向分别找最早和最晚的配对。两者都相同时,已保存区间的有序配对才唯一。
|
|
142
|
+
const forward = ordered(saved.ranges,oldest);
|
|
143
|
+
const backward = ordered([...saved.ranges].reverse(),parsed.periods).reverse();
|
|
144
|
+
if (forward.some((period,index) => period !== backward[index])) throw Error(id+' 的成功区间与 Markdown 有多种配对,请先核对原文。');
|
|
145
|
+
if (forward.length !== parsed.periods.length) warnings.push(id+' 有未匹配的日期段,保留在 Home。');
|
|
146
|
+
if (parsed.legacy) warnings.push(id+' 含历史补记,保留在单仓页。');
|
|
147
|
+
for (const period of forward) {
|
|
148
|
+
if (period.notes.some(note => /^### |^[-*+] /u.test(note))) warnings.push(id+' '+period.key+' 含额外正文,保留在区间说明。');
|
|
149
|
+
}
|
|
150
|
+
return forward.reverse();
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
export function inputs(website) {
|
|
154
|
+
const home = path.dirname(website);
|
|
155
|
+
const sources = [];
|
|
156
|
+
function take(filename, required = false) {
|
|
157
|
+
const bytes = read(filename);
|
|
158
|
+
if (required && !bytes) {
|
|
159
|
+
if (filename.endsWith('repos.json')) throw Error('缺少 repos.json,请先通过 home-setup 登记项目。');
|
|
160
|
+
throw Error('缺少 '+path.basename(filename)+'。');
|
|
161
|
+
}
|
|
162
|
+
sources.push([filename,bytes ? createHash('sha256').update(bytes).digest('hex') : null]);
|
|
163
|
+
return bytes;
|
|
164
|
+
}
|
|
165
|
+
const parse = (bytes, name) => {
|
|
166
|
+
try { return JSON.parse(decode(bytes)); } catch { throw Error(name+' 无法读取为 UTF-8 JSON。'); }
|
|
167
|
+
};
|
|
168
|
+
const settings = config(parse(take(path.join(website,'site.config.json'),true),'site.config.json'));
|
|
169
|
+
const registered = records(parse(take(path.join(home,'repos.json'),true),'repos.json'));
|
|
170
|
+
const logs = path.join(home,'changelogs');
|
|
171
|
+
directory(logs);
|
|
172
|
+
const stateBytes = take(path.join(logs,'state.json'));
|
|
173
|
+
const state = readState(stateBytes ? parse(stateBytes,'state.json') : undefined);
|
|
174
|
+
const warnings = [], excluded = [];
|
|
175
|
+
const privateValues = [...new Set(registered.flatMap(repo => [
|
|
176
|
+
repo.localPath, repo.remote, repo.backgroundRef,
|
|
177
|
+
...(Array.isArray(repo.remotes) ? repo.remotes.flatMap(remote => [...(remote?.urls ?? []), ...(remote?.pushUrls ?? [])]) : []),
|
|
178
|
+
]).filter(value => typeof value === 'string' && value.length >= 3))].sort((a,b) => b.length-a.length);
|
|
179
|
+
const text = value => publicText(value, privateValues);
|
|
180
|
+
const projects = [];
|
|
181
|
+
for (const repo of registered) {
|
|
182
|
+
const {id} = repo;
|
|
183
|
+
const override = settings.byId.get(id) ?? {};
|
|
184
|
+
if (override.hidden) { excluded.push({id, reason:'hidden'}); continue; }
|
|
185
|
+
if (override.showChangelog === false) { excluded.push({id,reason:'changelog-disabled'}); continue; }
|
|
186
|
+
const saved = Object.hasOwn(state,id) ? state[id] : undefined;
|
|
187
|
+
if (!saved) { excluded.push({id,reason:'no-state'}); continue; }
|
|
188
|
+
if (saved.pending) throw Error(id+' 的日志有待确认写入,请先用 home-project-changelog 恢复。');
|
|
189
|
+
const bytes = take(path.join(logs,id+'.md'));
|
|
190
|
+
if (!bytes) throw Error(id+' 的日志正文缺失,请先恢复 Markdown。');
|
|
191
|
+
let parsed;
|
|
192
|
+
try { parsed = parseMarkdown(decode(bytes)); } catch { throw Error(id+' 的日志正文需要可读的 UTF-8 Markdown。'); }
|
|
193
|
+
const periods = savedPeriods(id,parsed,saved,warnings).map(period => ({
|
|
194
|
+
...period, items:period.items.map(([type, value, tags]) => [type,text(value),tags]),
|
|
195
|
+
notes:period.notes.map(text), note:period.notes.map(text).join('\n'),
|
|
196
|
+
}));
|
|
197
|
+
const index = projects.length;
|
|
198
|
+
projects.push({
|
|
199
|
+
id, name:text(override.displayName ?? id), purpose:text(override.summary ?? repo.purpose),
|
|
200
|
+
groups:(repo.groups ?? []).filter(group => settings.publicGroups.includes(group)).map(text),
|
|
201
|
+
color:colors[index % colors.length], mark:marks[index % marks.length], repoUrl:override.repoUrl, docsUrl:override.docsUrl,
|
|
202
|
+
periods, legacy:text(parsed.legacy),
|
|
203
|
+
});
|
|
204
|
+
}
|
|
205
|
+
return {
|
|
206
|
+
model:{title:text(settings.title),base:settings.base,projects},
|
|
207
|
+
inputRevision:JSON.stringify(sources), hasState:Boolean(stateBytes), warnings, excluded
|
|
208
|
+
};
|
|
209
|
+
}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import http from 'node:http';
|
|
2
|
+
import fs from 'node:fs';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
|
|
5
|
+
const types = {
|
|
6
|
+
'.html':'text/html; charset=utf-8', '.css':'text/css; charset=utf-8',
|
|
7
|
+
'.js':'text/javascript; charset=utf-8', '.json':'application/json; charset=utf-8',
|
|
8
|
+
'.woff':'font/woff', '.woff2':'font/woff2',
|
|
9
|
+
};
|
|
10
|
+
|
|
11
|
+
export function preview(dist,base,value) {
|
|
12
|
+
if (!/^\d+$/u.test(value) || Number(value) > 65535) throw Error('端口须为 0 至 65535 的整数。');
|
|
13
|
+
const server = http.createServer((request,response) => {
|
|
14
|
+
if (!['GET','HEAD'].includes(request.method)) {
|
|
15
|
+
response.writeHead(405,{Allow:'GET, HEAD'}).end();
|
|
16
|
+
return;
|
|
17
|
+
}
|
|
18
|
+
const url = new URL(request.url,'http://localhost');
|
|
19
|
+
const address = url.pathname;
|
|
20
|
+
if (base !== '/' && (address === '/' || address === base.slice(0,-1))) {
|
|
21
|
+
response.writeHead(302,{Location:base+url.search}).end();
|
|
22
|
+
return;
|
|
23
|
+
}
|
|
24
|
+
const relative = address.startsWith(base) ? address.slice(base.length) : null;
|
|
25
|
+
const valid = relative !== null && /^[a-zA-Z0-9_./-]*$/u.test(relative)
|
|
26
|
+
&& relative.split('/').every(segment => !segment.startsWith('.'));
|
|
27
|
+
let file = valid ? path.join(dist, !relative || relative.endsWith('/') ? relative+'index.html' : relative) : null;
|
|
28
|
+
if (file && fs.lstatSync(file,{throwIfNoEntry:false})?.isDirectory()) {
|
|
29
|
+
response.writeHead(308,{Location:address+'/'+url.search}).end();
|
|
30
|
+
return;
|
|
31
|
+
}
|
|
32
|
+
if (file && !path.extname(file)) file += '.html';
|
|
33
|
+
const exists = file && fs.lstatSync(file,{throwIfNoEntry:false})?.isFile() && types[path.extname(file)];
|
|
34
|
+
if (!exists) file = path.join(dist,'404.html');
|
|
35
|
+
const stat = fs.lstatSync(file,{throwIfNoEntry:false});
|
|
36
|
+
if (!stat?.isFile()) { response.writeHead(404).end(); return; }
|
|
37
|
+
response.writeHead(exists ? 200 : 404, {
|
|
38
|
+
'Content-Type':types[path.extname(file)],
|
|
39
|
+
'Content-Length':stat.size,
|
|
40
|
+
'Cache-Control':'no-store',
|
|
41
|
+
});
|
|
42
|
+
if (request.method === 'HEAD') response.end();
|
|
43
|
+
else fs.createReadStream(file).on('error',()=>response.destroy()).pipe(response);
|
|
44
|
+
});
|
|
45
|
+
server.on('error',error => {
|
|
46
|
+
console.error('预览启动失败:'+error.message);
|
|
47
|
+
process.exitCode = 1;
|
|
48
|
+
});
|
|
49
|
+
server.listen(Number(value),'127.0.0.1',() => console.log('http://127.0.0.1:'+server.address().port+base));
|
|
50
|
+
}
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { frame, logPath, projectPath } from '../site/templates/layout.mjs';
|
|
4
|
+
import { itemId, observationWindows, periodTitle, rangeLabel, statistics } from '../site/templates/model.mjs';
|
|
5
|
+
import { overview, catalog, detail, repositoryLog } from '../site/templates/pages.mjs';
|
|
6
|
+
import { changelog } from '../site/templates/ledger.mjs';
|
|
7
|
+
import { publicProject } from '../site/templates/project-logs.mjs';
|
|
8
|
+
|
|
9
|
+
const json = value => JSON.stringify(value, null, 2) + '\n';
|
|
10
|
+
|
|
11
|
+
function transformHtml(html, page, base, notFound) {
|
|
12
|
+
// The HTTP server may return the 404 page at a URL of any depth.
|
|
13
|
+
if (page === '404.md') return html.replace('<div id="app"></div>', () => notFound);
|
|
14
|
+
const depth = page.split('/').length - 1;
|
|
15
|
+
const relativeRoot = '../'.repeat(depth) || './';
|
|
16
|
+
return html.replace(/(<(?:link|script)\b[^>]*?\s(?:href|src)=")(\/[^"#?]+)"/gu, (tag, attribute, url) =>
|
|
17
|
+
url.startsWith(base) && !url.startsWith('//') ? attribute + relativeRoot + url.slice(base.length) + '"' : tag);
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export function render(website, run, model) {
|
|
21
|
+
const {title,base,projects} = model;
|
|
22
|
+
const windows = observationWindows(projects);
|
|
23
|
+
const stats = statistics(projects.flatMap(project => project.periods));
|
|
24
|
+
const source = path.join(run,'src');
|
|
25
|
+
const dist = path.join(run,'dist');
|
|
26
|
+
fs.cpSync(path.join(website,'site/.vitepress'),path.join(source,'.vitepress'),{recursive:true});
|
|
27
|
+
fs.cpSync(path.join(website,'site/public'),path.join(source,'public'),{recursive:true});
|
|
28
|
+
const shape = {
|
|
29
|
+
title, base, outDir:dist, lang:'zh-CN', cleanUrls:true, appearance:false, lastUpdated:false, mpa:true,
|
|
30
|
+
head:[
|
|
31
|
+
['link',{rel:'icon',href:'data:,'}],
|
|
32
|
+
['link',{rel:'stylesheet',href:base+'home-assets/site.css'}],
|
|
33
|
+
['script',{src:base+'home-assets/start.js'}],
|
|
34
|
+
['script',{defer:'',src:base+'home-assets/search-index.js'}],
|
|
35
|
+
['script',{defer:'',src:base+'home-assets/app.js'}],
|
|
36
|
+
]
|
|
37
|
+
};
|
|
38
|
+
// VitePress reserves 404.md and emits an empty app shell for it.
|
|
39
|
+
const notFound = frame({base,title,section:'',content:'<h1>页面不存在</h1><p><a href="'+base+'">返回项目总览</a></p>'});
|
|
40
|
+
fs.writeFileSync(path.join(source,'.vitepress/config.mjs'),
|
|
41
|
+
'const config = '+json(shape)
|
|
42
|
+
+transformHtml.toString()+'\n'
|
|
43
|
+
+'config.transformHtml = (html, _filename, {page}) => transformHtml(html, page, config.base, '+JSON.stringify(notFound)+');\n'
|
|
44
|
+
+'export default config;\n');
|
|
45
|
+
const urls = [];
|
|
46
|
+
function write(relative,data) {
|
|
47
|
+
const filename = path.join(source,relative);
|
|
48
|
+
fs.mkdirSync(path.dirname(filename),{recursive:true});
|
|
49
|
+
fs.writeFileSync(filename,data);
|
|
50
|
+
}
|
|
51
|
+
function page(route, pageTitle, section, content) {
|
|
52
|
+
const stem = route.endsWith('/') || !route ? route+'index' : route;
|
|
53
|
+
const name = path.posix.basename(stem);
|
|
54
|
+
const markup = frame({base,title,section,content});
|
|
55
|
+
// Only markup from the controlled renderers enters Vue. Source text is already escaped.
|
|
56
|
+
write(stem+'.content.json',json({markup}));
|
|
57
|
+
write(stem+'.md','---\n'+JSON.stringify({title:pageTitle})+'\n---\n\n'
|
|
58
|
+
+'<script setup>\nimport page from "./'+name+'.content.json";\n</script>\n\n<div v-html="page.markup"></div>\n');
|
|
59
|
+
urls.push(stem+'.html');
|
|
60
|
+
}
|
|
61
|
+
page('',title,'home',overview(base,projects,windows,stats));
|
|
62
|
+
page('projects/','项目目录','projects',catalog(base,projects));
|
|
63
|
+
page('changelog/','变更时间线','changelog',changelog(base,projects,windows,stats));
|
|
64
|
+
urls.push('404.html');
|
|
65
|
+
const index = [];
|
|
66
|
+
const catalogData = {schemaVersion:1,stats,projects:[],windows:windows.map(({from,to,groups,rangeCount,stats}) => ({
|
|
67
|
+
from, to, projects:groups.map(({project}) => project.id), rangeCount, stats,
|
|
68
|
+
}))};
|
|
69
|
+
const expectedData = new Map();
|
|
70
|
+
for (const project of projects) {
|
|
71
|
+
const {id,name,purpose,groups,periods,legacy} = project;
|
|
72
|
+
const data = 'projects/'+id+'.json';
|
|
73
|
+
const projected = publicProject(project);
|
|
74
|
+
page(projectPath(project),name,'projects',detail(base,project,projected.stats));
|
|
75
|
+
index.push({kind:'项目',name,id,title:name,text:purpose,group:groups.join(' '),url:projectPath(project)});
|
|
76
|
+
page(logPath(project),name+' 变更日志','projects',repositoryLog(base,project,projected.stats));
|
|
77
|
+
for (const period of periods) {
|
|
78
|
+
const date = rangeLabel(period);
|
|
79
|
+
if (!period.items.length) index.push({kind:'区间',name,id,title:periodTitle(period),text:period.note,date,url:logPath(project,period)});
|
|
80
|
+
period.items.forEach(([category,text,markers],i) => {
|
|
81
|
+
index.push({kind:'变更',name,id,title:text,text:[category,...markers].join(' · '),date,url:logPath(project)+'#'+itemId(period,i)});
|
|
82
|
+
});
|
|
83
|
+
}
|
|
84
|
+
if (legacy) index.push({kind:'补记',name,id,title:'历史补记',text:legacy,url:logPath(project)+'#legacy'});
|
|
85
|
+
expectedData.set('data/'+data,json(projected));
|
|
86
|
+
catalogData.projects.push({id,name,purpose,ranges:periods.length,entries:projected.stats.changes,data});
|
|
87
|
+
}
|
|
88
|
+
expectedData.set('data/catalog.json',json(catalogData));
|
|
89
|
+
expectedData.set('home-assets/search-index.js','window.homeSearchIndex = '+JSON.stringify(index).replaceAll('<','\\u003c')+';\n');
|
|
90
|
+
for (const [name,bytes] of expectedData) write('public/'+name,bytes);
|
|
91
|
+
return {source,dist,urls,expectedData,index};
|
|
92
|
+
}
|
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import os from 'node:os';
|
|
4
|
+
import { spawnSync } from 'node:child_process';
|
|
5
|
+
import { parseArgs } from 'node:util';
|
|
6
|
+
import { fileURLToPath } from 'node:url';
|
|
7
|
+
import { directory, inputs, read } from './inputs.mjs';
|
|
8
|
+
import { fingerprint, manifest, validateArtifact } from './artifact.mjs';
|
|
9
|
+
import { render } from './render.mjs';
|
|
10
|
+
import { preview } from './preview.mjs';
|
|
11
|
+
import { statistics } from '../site/templates/model.mjs';
|
|
12
|
+
|
|
13
|
+
const website = fileURLToPath(new URL('../', import.meta.url));
|
|
14
|
+
const cache = path.join(website,'.cache');
|
|
15
|
+
const dist = path.join(website,'dist');
|
|
16
|
+
const previous = path.join(cache,'previous-dist');
|
|
17
|
+
const previousMeta = path.join(cache,'previous.json');
|
|
18
|
+
const lock = path.join(website,'.refresh.lock');
|
|
19
|
+
const meta = path.join(cache,'current.json');
|
|
20
|
+
const retry = 'node .agents/home/website/scripts/site.mjs refresh';
|
|
21
|
+
|
|
22
|
+
function mkdir(target) {
|
|
23
|
+
if (!directory(target)) fs.mkdirSync(target);
|
|
24
|
+
}
|
|
25
|
+
function pidState() {
|
|
26
|
+
const bytes = read(path.join(lock,'owner.json'));
|
|
27
|
+
const owner = bytes && JSON.parse(bytes);
|
|
28
|
+
if (owner?.host !== os.hostname() || !Number.isInteger(owner.pid) || owner.pid <= 0) return 'unknown';
|
|
29
|
+
try { process.kill(owner.pid,0); return 'running'; }
|
|
30
|
+
catch (error) { return error.code === 'ESRCH' ? 'stopped' : 'unknown'; }
|
|
31
|
+
}
|
|
32
|
+
function acquire(wait) {
|
|
33
|
+
const deadline = Date.now() + wait;
|
|
34
|
+
for (;;) {
|
|
35
|
+
try { fs.mkdirSync(lock); break; }
|
|
36
|
+
catch (error) {
|
|
37
|
+
if (error.code !== 'EEXIST') throw error;
|
|
38
|
+
if (!directory(lock)) continue;
|
|
39
|
+
if (Date.now() >= deadline) throw Error('另有刷新在运行或上次异常退出。确认旧进程已结束后可运行 recover。');
|
|
40
|
+
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,100);
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
try { fs.writeFileSync(path.join(lock,'owner.json'),JSON.stringify({host:os.hostname(),pid:process.pid}),{flag:'wx'}); }
|
|
44
|
+
catch (error) { fs.rmdirSync(lock); throw error; }
|
|
45
|
+
}
|
|
46
|
+
function release() {
|
|
47
|
+
fs.unlinkSync(path.join(lock,'owner.json'));
|
|
48
|
+
fs.rmdirSync(lock);
|
|
49
|
+
}
|
|
50
|
+
function restoreDist() {
|
|
51
|
+
if (!directory(previous) || directory(dist)) return;
|
|
52
|
+
const record = read(previousMeta);
|
|
53
|
+
if (record) fs.renameSync(previousMeta,meta);
|
|
54
|
+
fs.renameSync(previous,dist);
|
|
55
|
+
}
|
|
56
|
+
function current() {
|
|
57
|
+
const bytes = read(meta);
|
|
58
|
+
if (!bytes) return null;
|
|
59
|
+
try { return JSON.parse(bytes); } catch { return null; }
|
|
60
|
+
}
|
|
61
|
+
function artifactMatches(fingerprintValue, record) {
|
|
62
|
+
if (record?.fingerprint !== fingerprintValue || !Array.isArray(record.files) || !directory(dist)) return false;
|
|
63
|
+
return JSON.stringify(manifest(dist)) === JSON.stringify(record.files);
|
|
64
|
+
}
|
|
65
|
+
function hadSavedLogs(record) {
|
|
66
|
+
if (record?.hasState !== undefined) return record.hasState;
|
|
67
|
+
if (!directory(dist)) return false;
|
|
68
|
+
const catalog = read(path.join(dist,'data','catalog.json'));
|
|
69
|
+
return catalog && JSON.parse(catalog).projects.some(project => project.ranges > 0);
|
|
70
|
+
}
|
|
71
|
+
function publish(candidate, record, run) {
|
|
72
|
+
const tempMeta = path.join(run,'current.json');
|
|
73
|
+
fs.writeFileSync(tempMeta,JSON.stringify(record)+'\n');
|
|
74
|
+
if (directory(previous)) fs.rmSync(previous,{recursive:true});
|
|
75
|
+
const displaced = directory(dist);
|
|
76
|
+
if (displaced) {
|
|
77
|
+
const metadata = read(meta);
|
|
78
|
+
if (metadata) {
|
|
79
|
+
const tempPrevious = path.join(run,'previous.json');
|
|
80
|
+
fs.writeFileSync(tempPrevious,metadata);
|
|
81
|
+
fs.renameSync(tempPrevious,previousMeta);
|
|
82
|
+
} else if (read(previousMeta)) fs.unlinkSync(previousMeta);
|
|
83
|
+
fs.renameSync(dist,previous);
|
|
84
|
+
}
|
|
85
|
+
let swapped = false;
|
|
86
|
+
try {
|
|
87
|
+
fs.renameSync(candidate,dist);
|
|
88
|
+
swapped = true;
|
|
89
|
+
fs.renameSync(tempMeta,meta);
|
|
90
|
+
} catch (error) {
|
|
91
|
+
if (swapped) fs.renameSync(dist,candidate);
|
|
92
|
+
if (displaced) fs.renameSync(previous,dist);
|
|
93
|
+
throw error;
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
function refresh(force) {
|
|
98
|
+
mkdir(cache);
|
|
99
|
+
// Acquire before reading sources so a waiting refresh always builds from the newest Home state.
|
|
100
|
+
acquire(60_000);
|
|
101
|
+
let run;
|
|
102
|
+
try {
|
|
103
|
+
restoreDist();
|
|
104
|
+
const snapshot = inputs(website);
|
|
105
|
+
const {model,warnings,excluded} = snapshot;
|
|
106
|
+
const before = current();
|
|
107
|
+
if (!snapshot.hasState && hadSavedLogs(before)) throw Error('已构建的网站缺少 changelogs/state.json,请先核对 Home 或恢复状态文件。');
|
|
108
|
+
const key = fingerprint(website,model);
|
|
109
|
+
const projectIds = model.projects.map(project=>project.id);
|
|
110
|
+
const stats = statistics(model.projects.flatMap(project=>project.periods));
|
|
111
|
+
const summary = {base:model.base,projects:projectIds.length,entries:stats.changes,stats,warnings,excluded,dist};
|
|
112
|
+
if (!force && artifactMatches(key,before)) return {status:'unchanged', ...summary};
|
|
113
|
+
const cli = path.join(website,'node_modules','vitepress','bin','vitepress.js');
|
|
114
|
+
if (!fs.existsSync(cli)) throw Error('网站尚未安装依赖,请在网站目录运行 npm ci,再重试。');
|
|
115
|
+
run = fs.mkdtempSync(path.join(cache,'build-'));
|
|
116
|
+
const candidate = render(website,run,model);
|
|
117
|
+
const result = spawnSync(process.execPath,[cli,'build',candidate.source],{
|
|
118
|
+
cwd:website,env:{...process.env,FORCE_COLOR:'0'},encoding:'utf8',maxBuffer:8*1024*1024,windowsHide:true,
|
|
119
|
+
});
|
|
120
|
+
if (result.error || result.status !== 0) throw Error('VitePress 构建失败:'+(result.error?.message ?? result.stderr.trim() ?? '未知错误')+'\n'+(result.stdout ?? '').trim());
|
|
121
|
+
// VitePress MPA builds leave a Node ESM marker in their output directory.
|
|
122
|
+
const marker = path.join(candidate.dist,'package.json');
|
|
123
|
+
const markerBytes = read(marker);
|
|
124
|
+
if (markerBytes && JSON.stringify(JSON.parse(markerBytes)) === '{"private":true,"type":"module"}') fs.unlinkSync(marker);
|
|
125
|
+
const publishedFiles = manifest(candidate.dist,validateArtifact(candidate,model.base));
|
|
126
|
+
const after = inputs(website);
|
|
127
|
+
if (after.inputRevision !== snapshot.inputRevision || fingerprint(website,after.model) !== key) {
|
|
128
|
+
throw Error('构建时 Home 或网站源文件已变化,保留上次版本,请重试。');
|
|
129
|
+
}
|
|
130
|
+
publish(candidate.dist,{fingerprint:key,base:model.base,projects:projectIds,hasState:snapshot.hasState,files:publishedFiles},run);
|
|
131
|
+
return {status:'built', ...summary,
|
|
132
|
+
added:projectIds.filter(id=>!before?.projects?.includes(id)),
|
|
133
|
+
removed:(before?.projects ?? []).filter(id=>!projectIds.includes(id)),
|
|
134
|
+
};
|
|
135
|
+
} finally {
|
|
136
|
+
try { if (run) fs.rmSync(run,{recursive:true}); }
|
|
137
|
+
finally { release(); }
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
function recover() {
|
|
142
|
+
const guard = path.join(cache,'recover.lock');
|
|
143
|
+
fs.mkdirSync(guard);
|
|
144
|
+
try {
|
|
145
|
+
if (directory(lock)) {
|
|
146
|
+
if (pidState() !== 'stopped') throw Error('刷新锁的原进程未证实已结束。请核对锁中的主机和 PID。');
|
|
147
|
+
fs.renameSync(lock,path.join(guard,'owner'));
|
|
148
|
+
}
|
|
149
|
+
acquire(0);
|
|
150
|
+
try { restoreDist(); return {status:'ready',dist,refresh:retry}; }
|
|
151
|
+
finally { release(); }
|
|
152
|
+
} finally {
|
|
153
|
+
fs.rmSync(guard,{recursive:true});
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
const [command = 'refresh', ...args] = process.argv.slice(2);
|
|
158
|
+
try {
|
|
159
|
+
const {values} = parseArgs({args,options:{force:{type:'boolean'},port:{type:'string'},help:{type:'boolean'}}});
|
|
160
|
+
if (values.help) console.log('用法:node scripts/site.mjs refresh [--force] | preview [--port 4173] | recover');
|
|
161
|
+
else if (command === 'refresh' && values.port === undefined) console.log(JSON.stringify(refresh(values.force),null,2));
|
|
162
|
+
else if (command === 'recover' && values.port === undefined && !values.force) {
|
|
163
|
+
mkdir(cache);
|
|
164
|
+
console.log(JSON.stringify(recover(),null,2));
|
|
165
|
+
} else if (command === 'preview' && !values.force) {
|
|
166
|
+
const record = current();
|
|
167
|
+
if (!record || !directory(dist)) throw Error('还没有可预览的构建,请先运行 refresh。');
|
|
168
|
+
preview(dist,record.base,values.port ?? '4173');
|
|
169
|
+
} else throw Error('未知操作,请查看 --help。');
|
|
170
|
+
} catch (error) {
|
|
171
|
+
console.error(JSON.stringify({status:'failed',message:error.message,retry}));
|
|
172
|
+
process.exitCode = 1;
|
|
173
|
+
}
|