github-overview 0.1.2 → 0.1.3
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 +8 -1
- package/bin/cli.mjs +44 -13
- package/docs/screenshot-dark.png +0 -0
- package/docs/screenshot-light.png +0 -0
- package/package.json +1 -1
- package/public/index.html +140 -27
- package/src/config.mjs +29 -0
- package/src/server.mjs +197 -68
- package/src/store.mjs +45 -19
- package/src/summary.mjs +7 -3
package/README.md
CHANGED
|
@@ -9,10 +9,13 @@
|
|
|
9
9
|
## 用法
|
|
10
10
|
|
|
11
11
|
```bash
|
|
12
|
+
npx github-overview init --user 你的GitHub用户名 # 绑定账号下全部仓库
|
|
12
13
|
npx github-overview init --repo owner/repo --npm 包名
|
|
13
14
|
npx github-overview start # http://127.0.0.1:4317
|
|
14
15
|
```
|
|
15
16
|
|
|
17
|
+
- `--user` 会把账号下自己拥有的仓库都绑上;页面顶部可以切到「全部仓库」看合计,也可以切单个仓库。只要一部分就写 `--repo a/b,c/d`。
|
|
18
|
+
- `--npm` 按同一个顺序对应仓库,不写就用仓库名当包名。
|
|
16
19
|
- 首次同步把 14 天内的流量存到本地,之后每 6 小时自动刷新(`--refresh` 可改),页面上的「刷新」随时手动同步。
|
|
17
20
|
- AI 摘要:`npx github-overview config --apikey KEY --baseurl URL`,只存本机 `~/.config/github-overview/config.json`。
|
|
18
21
|
- 没配 AI 也能用,摘要走内置模板。
|
|
@@ -35,6 +38,7 @@ GitHub 自带的 traffic 只给 14 天,而且只有浏览和克隆,看不到
|
|
|
35
38
|
- 浏览和克隆是两个指标,不相加。
|
|
36
39
|
- 页面构成是浏览落在哪些页面,来源是从哪个站进来,两者分开。
|
|
37
40
|
- 预估真实用户只取访客人数,克隆数不参与人数估算。
|
|
41
|
+
- 多仓合计时浏览、克隆、下载、star 相加;访客不去重跨仓相加,沿用的是各仓 API 给的人数。
|
|
38
42
|
|
|
39
43
|
## 数据源
|
|
40
44
|
|
|
@@ -49,7 +53,9 @@ GitHub 自带的 traffic 只给 14 天,而且只有浏览和克隆,看不到
|
|
|
49
53
|
|
|
50
54
|
## 14 天窗口
|
|
51
55
|
|
|
52
|
-
GitHub 的 traffic 只保留最近 14 天,所以第一次运行就要开始存快照。30 天、90
|
|
56
|
+
GitHub 的 traffic 只保留最近 14 天,所以第一次运行就要开始存快照。30 天、90 天视图读本地存储,只画有记录的那段,不会把空缺画成 0。
|
|
57
|
+
|
|
58
|
+
访客是 14 天窗口内去重的人数,GitHub 不提供更长范围的人数,所以 30 天、90 天视图显示同一个值,并在访客下面标出「覆盖 N 天」,不会因为切了范围就变少。
|
|
53
59
|
|
|
54
60
|
## 路线
|
|
55
61
|
|
|
@@ -58,6 +64,7 @@ GitHub 的 traffic 只保留最近 14 天,所以第一次运行就要开始存
|
|
|
58
64
|
- [x] 定时刷新与手动刷新
|
|
59
65
|
- [x] 面板内配置(AI 的 base URL 与 key)
|
|
60
66
|
- [x] AI 摘要,未配置时用模板
|
|
67
|
+
- [x] 绑定 GitHub 账号,多仓切换与合计
|
|
61
68
|
|
|
62
69
|
## License
|
|
63
70
|
|
package/bin/cli.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import { readConfig, writeConfig, parseRepo, CONFIG_PATH } from "./../src/config.mjs";
|
|
2
|
+
import { readConfig, writeConfig, parseRepo, normalizeConfig, resolveToken, CONFIG_PATH } from "./../src/config.mjs";
|
|
3
3
|
import { createApp } from "./../src/server.mjs";
|
|
4
4
|
|
|
5
5
|
const argv = process.argv.slice(2);
|
|
@@ -13,6 +13,7 @@ const flag = (...names) => {
|
|
|
13
13
|
};
|
|
14
14
|
|
|
15
15
|
const repoArg = flag("--repo", "-r");
|
|
16
|
+
const userArg = flag("--user", "-u");
|
|
16
17
|
const port = Number(flag("--port", "-p") || process.env.PORT || 4317);
|
|
17
18
|
const npmArg = flag("--npm");
|
|
18
19
|
const days = Number(flag("--days") || 7);
|
|
@@ -21,20 +22,47 @@ const intervalHours = Number(flag("--refresh") || 6);
|
|
|
21
22
|
function usage() {
|
|
22
23
|
console.log(`github-overview
|
|
23
24
|
|
|
24
|
-
github-overview init --
|
|
25
|
+
github-overview init --user 用户名 [--npm 包名,...]
|
|
26
|
+
github-overview init --repo owner/repo[,owner/repo2] [--npm 包名,...]
|
|
25
27
|
github-overview start [--port 4317] [--days 7] [--refresh 6]
|
|
26
28
|
github-overview sync
|
|
27
29
|
github-overview config --apikey KEY --baseurl URL
|
|
28
30
|
`);
|
|
29
31
|
}
|
|
30
32
|
|
|
33
|
+
// 账号绑定:列出该账号名下仓库;有 token 时能拿到私有仓库的 traffic
|
|
34
|
+
async function listUserRepos(user) {
|
|
35
|
+
const token = resolveToken(readConfig());
|
|
36
|
+
const headers = { accept: "application/vnd.github+json", "user-agent": "github-overview" };
|
|
37
|
+
if (token) headers.authorization = `Bearer ${token}`;
|
|
38
|
+
const who = await fetch("https://api.github.com/user", { headers }).then((r) => (r.ok ? r.json() : null)).catch(() => null);
|
|
39
|
+
const path = who?.login === user ? "/user/repos?affiliation=owner&per_page=100&sort=pushed" : `/users/${encodeURIComponent(user)}/repos?per_page=100&sort=pushed`;
|
|
40
|
+
const res = await fetch("https://api.github.com" + path, { headers });
|
|
41
|
+
if (!res.ok) throw new Error(`拉取 ${user} 的仓库失败:${res.status}`);
|
|
42
|
+
const rows = await res.json();
|
|
43
|
+
return rows.filter((r) => !r.fork && (r.permissions ? r.permissions.push : true)).map((r) => ({ repo: r.full_name, npm: r.name }));
|
|
44
|
+
}
|
|
45
|
+
|
|
31
46
|
try {
|
|
32
47
|
if (cmd === "init") {
|
|
33
|
-
|
|
34
|
-
|
|
48
|
+
let repos = [];
|
|
49
|
+
let user = userArg;
|
|
50
|
+
if (user) repos = await listUserRepos(user);
|
|
51
|
+
else if (repoArg) repos = repoArg.split(",").map((s) => s.trim()).filter(Boolean).map((s) => parseRepo(s)).map((r) => ({ repo: `${r.owner}/${r.name}`, npm: r.name }));
|
|
52
|
+
else {
|
|
53
|
+
usage();
|
|
54
|
+
throw new Error("给个账号或仓库:--user 用户名 或 --repo owner/repo");
|
|
55
|
+
}
|
|
56
|
+
if (!repos.length) throw new Error(`${user || repoArg} 下没有可绑定的仓库`);
|
|
57
|
+
const npmList = npmArg ? npmArg.split(",").map((s) => s.trim()) : [];
|
|
58
|
+
repos = repos.map((r, i) => ({ ...r, npm: npmList[i] || r.npm }));
|
|
59
|
+
const next = { ...readConfig(), user: user || repos[0].repo.split("/")[0], repos };
|
|
60
|
+
delete next.repo;
|
|
61
|
+
delete next.npm;
|
|
35
62
|
writeConfig(next);
|
|
36
63
|
console.log(`已写入 ${CONFIG_PATH}`);
|
|
37
|
-
console.log(
|
|
64
|
+
console.log(`绑定 ${next.user},${repos.length} 个仓库`);
|
|
65
|
+
console.log(repos.slice(0, 8).map((r) => ` ${r.repo}${r.npm !== r.repo.split("/")[1] ? " → npm " + r.npm : ""}`).join("\n") + (repos.length > 8 ? `\n …共 ${repos.length} 个` : ""));
|
|
38
66
|
console.log("下一步:github-overview start");
|
|
39
67
|
process.exit(0);
|
|
40
68
|
}
|
|
@@ -50,29 +78,32 @@ try {
|
|
|
50
78
|
process.exit(0);
|
|
51
79
|
}
|
|
52
80
|
|
|
53
|
-
const cfg = readConfig();
|
|
54
|
-
const
|
|
55
|
-
if (!
|
|
81
|
+
const cfg = normalizeConfig(readConfig());
|
|
82
|
+
const repos = cfg.repos;
|
|
83
|
+
if (!repos.length) {
|
|
56
84
|
usage();
|
|
57
|
-
console.log("还没有配置仓库,先跑:github-overview init --
|
|
85
|
+
console.log("还没有配置仓库,先跑:github-overview init --user 用户名");
|
|
58
86
|
process.exit(1);
|
|
59
87
|
}
|
|
60
88
|
|
|
61
89
|
if (cmd === "sync") {
|
|
62
|
-
const app = createApp({
|
|
90
|
+
const app = createApp({ repos, days, cfg });
|
|
63
91
|
const out = await app.sync();
|
|
92
|
+
for (const r of out.results) console.log(`${r.ok ? "同步" : "失败"} ${r.repo}${r.error ? ":" + r.error : ""}`);
|
|
64
93
|
console.log(`同步完成 ${out.syncedAt}`);
|
|
65
|
-
process.exit(0);
|
|
94
|
+
process.exit(out.ok ? 0 : 1);
|
|
66
95
|
}
|
|
67
96
|
|
|
68
97
|
if (cmd === "start") {
|
|
69
|
-
const app = createApp({
|
|
98
|
+
const app = createApp({ repos, days, cfg });
|
|
70
99
|
const addr = await app.listen(port);
|
|
71
100
|
console.log(`github-overview 在 http://127.0.0.1:${addr.port}`);
|
|
101
|
+
console.log(`已绑定 ${cfg.user},${repos.length} 个仓库`);
|
|
72
102
|
const tick = async () => {
|
|
73
103
|
try {
|
|
74
104
|
const out = await app.sync();
|
|
75
|
-
|
|
105
|
+
const failed = out.results.filter((r) => !r.ok);
|
|
106
|
+
console.log(`同步 ${out.syncedAt}${failed.length ? `,${failed.length} 个失败` : ""}`);
|
|
76
107
|
} catch (e) {
|
|
77
108
|
console.log(`同步失败:${e.message}`);
|
|
78
109
|
}
|
package/docs/screenshot-dark.png
CHANGED
|
Binary file
|
|
Binary file
|
package/package.json
CHANGED
package/public/index.html
CHANGED
|
@@ -28,7 +28,7 @@
|
|
|
28
28
|
--label-primary: #12161d;
|
|
29
29
|
--label-secondary: #5c6472;
|
|
30
30
|
--brand: #2b62d9;
|
|
31
|
-
--machine: #
|
|
31
|
+
--machine: #5f6873;
|
|
32
32
|
--event: #a8761b;
|
|
33
33
|
--success: #1a7f37;
|
|
34
34
|
--shadow: 0 8px 28px rgba(16,24,40,.12);
|
|
@@ -62,6 +62,14 @@
|
|
|
62
62
|
.repo { font-size: 16px; font-weight: 600; white-space: nowrap; }
|
|
63
63
|
.repo span { color: var(--label-secondary); font-weight: 400; }
|
|
64
64
|
.caret { color: var(--label-secondary); font-weight: 400; }
|
|
65
|
+
.repo-wrap { position: relative; }
|
|
66
|
+
.repo-wrap > .repo { border: 0; background: none; padding: 0; font: inherit; font-weight: 600; color: var(--label-primary); cursor: pointer; }
|
|
67
|
+
.repo-wrap > .repo:hover { color: var(--label-secondary); }
|
|
68
|
+
.repo-menu { position: absolute; top: 26px; left: -8px; z-index: 20; min-width: 200px; max-height: 260px; overflow: auto;
|
|
69
|
+
padding: 6px; background: var(--bg-layer-2); border: 1px solid var(--border-l2); border-radius: 8px; }
|
|
70
|
+
.repo-menu button { display: flex; width: 100%; height: 30px; align-items: center; border: 0; border-radius: 8px; padding: 0 8px;
|
|
71
|
+
background: none; color: var(--label-primary); font-size: 12px; text-align: left; }
|
|
72
|
+
.repo-menu button:hover, .repo-menu button.on { background: var(--border-l1); }
|
|
65
73
|
.spacer { flex: 1; }
|
|
66
74
|
.seg { display: inline-flex; border: 1px solid var(--border-l2); border-radius: 8px; overflow: hidden; height: 28px; }
|
|
67
75
|
.seg button { border: 0; border-radius: 0; height: 26px; margin: 1px; padding: 0 10px; color: var(--label-secondary); }
|
|
@@ -101,6 +109,7 @@
|
|
|
101
109
|
.donut-legend span { display: inline-flex; align-items: center; gap: 6px; color: var(--label-secondary); white-space: nowrap; }
|
|
102
110
|
.donut-legend i { width: 8px; height: 8px; border-radius: 2px; flex: none; }
|
|
103
111
|
.donut-legend b { font-weight: 500; }
|
|
112
|
+
.empty { font-size: 12px; color: var(--label-secondary); }
|
|
104
113
|
.ranks { display: grid; gap: 16px; }
|
|
105
114
|
.ranks h3 { margin: 0 0 8px; font-size: 12px; font-weight: 500; color: var(--label-secondary); }
|
|
106
115
|
.ranks ul { list-style: none; margin: 0; padding: 0; display: grid; gap: 7px; }
|
|
@@ -183,7 +192,10 @@
|
|
|
183
192
|
<header>
|
|
184
193
|
<span class="brand">github-overview</span>
|
|
185
194
|
<span class="sep"></span>
|
|
186
|
-
<div class="repo
|
|
195
|
+
<div class="repo-wrap">
|
|
196
|
+
<button class="repo" id="repo-pick" aria-haspopup="true" aria-expanded="false"><span id="repo-owner"></span><span id="repo-name">全部仓库</span> <span class="caret">▾</span></button>
|
|
197
|
+
<div class="repo-menu" id="repo-menu" hidden></div>
|
|
198
|
+
</div>
|
|
187
199
|
<div class="spacer"></div>
|
|
188
200
|
<div class="seg" id="seg">
|
|
189
201
|
<button data-r="7" class="on">7 天</button>
|
|
@@ -343,7 +355,9 @@ let LAST = dayIdx(DATA[DATA.length - 1].d);
|
|
|
343
355
|
|
|
344
356
|
function domain(days) {
|
|
345
357
|
const out = [];
|
|
346
|
-
|
|
358
|
+
// 只画有记录的那段,别把 14 天数据摊在 30 天轴上
|
|
359
|
+
const start = Math.max(LAST - days + 1, FIRST == null ? -Infinity : FIRST);
|
|
360
|
+
for (let i = LAST - start; i >= 0; i--) {
|
|
347
361
|
const dt = new Date((LAST - i) * 864e5);
|
|
348
362
|
const label = String(dt.getUTCMonth() + 1).padStart(2, "0") + "-" + String(dt.getUTCDate()).padStart(2, "0");
|
|
349
363
|
out.push({ label, rec: DATA.find(r => r.d === label) });
|
|
@@ -356,6 +370,7 @@ function flowChart(node, days) {
|
|
|
356
370
|
const dom = domain(days);
|
|
357
371
|
const W = Math.max(300, Math.round(node.clientWidth || 720)), H = 196, P = { l: 42, r: 42, t: 12, b: 22 };
|
|
358
372
|
const iw = W - P.l - P.r, ih = H - P.t - P.b, ticks = 4;
|
|
373
|
+
if (!DATA.some(r => (r.v || 0) > 0 || (r.c || 0) > 0)) return emptyInto(node, "还没有流量数据");
|
|
359
374
|
const L = scale(Math.max(...DATA.map(r => r.v)) * 1.06, ticks);
|
|
360
375
|
const R = scale(Math.max(...DATA.map(r => r.c)) * 1.06, ticks);
|
|
361
376
|
const x = i => P.l + (i * iw) / (dom.length - 1);
|
|
@@ -414,7 +429,10 @@ function npmChart(node, days) {
|
|
|
414
429
|
const dom = domain(days);
|
|
415
430
|
const W = Math.max(300, Math.round(node.clientWidth || 720)), H = 122, P = { l: 44, r: 10, t: 14, b: 20 };
|
|
416
431
|
const iw = W - P.l - P.r, ih = H - P.t - P.b, ticks = 2;
|
|
417
|
-
const
|
|
432
|
+
const nvals = DATA.map(r => r.n).filter(v => typeof v === "number" && isFinite(v) && v > 0);
|
|
433
|
+
if (!nvals.length) return emptyInto(node, "还没有下载数据");
|
|
434
|
+
const NMAX = Math.max(...nvals);
|
|
435
|
+
const S = scale(NMAX * 1.02, ticks);
|
|
418
436
|
const bw = Math.max(4, Math.min(24, (iw / dom.length) * 0.5));
|
|
419
437
|
const cx = i => P.l + (i + .5) * (iw / dom.length);
|
|
420
438
|
const y = v => P.t + ih - (v / S.max) * ih;
|
|
@@ -431,11 +449,13 @@ function npmChart(node, days) {
|
|
|
431
449
|
const v = d.rec.n;
|
|
432
450
|
const pending = i >= dom.length - 2;
|
|
433
451
|
if (v == null || (pending && v === 0)) {
|
|
452
|
+
if (!pending) return; // 早期缺失的数据不画桩,免得整排虚线像归零
|
|
434
453
|
svg.appendChild(el("rect", { x: cx(i) - bw / 2, y: P.t + ih - 7, width: bw, height: 7, rx: 2, fill: "none", stroke: c.machine, opacity: .55, "stroke-dasharray": "2 3" }));
|
|
435
454
|
return;
|
|
436
455
|
}
|
|
456
|
+
if (v === 0) return; // 0 下载不画成一条线
|
|
437
457
|
svg.appendChild(el("rect", { x: cx(i) - bw / 2, y: y(v), width: bw, height: Math.max(2, P.t + ih - y(v)), rx: 2, fill: c.human, opacity: .85 }));
|
|
438
|
-
if (v > 0 && bw > 12 && (iw / dom.length > 46 || v ===
|
|
458
|
+
if (v > 0 && bw > 12 && (iw / dom.length > 46 || v === NMAX)) svg.appendChild(el("text", { x: cx(i), y: y(v) - 6, "text-anchor": "middle", class: "val-label" }, fmt(v)));
|
|
439
459
|
});
|
|
440
460
|
const step = Math.max(1, Math.ceil(dom.length / 6));
|
|
441
461
|
dom.forEach((d, i) => {
|
|
@@ -449,24 +469,38 @@ let RANKS = [
|
|
|
449
469
|
["看了哪些页面", [["仓库主页", 397], ["issues 列表", 15], ["README", 2], ["actions 页", 1]]]
|
|
450
470
|
];
|
|
451
471
|
let PATHS = null;
|
|
472
|
+
let FIRST = null;
|
|
473
|
+
let LIVE_SET = false;
|
|
474
|
+
|
|
475
|
+
const emptyInto = (node, text) => {
|
|
476
|
+
node.textContent = "";
|
|
477
|
+
const d = document.createElement("div");
|
|
478
|
+
d.className = "empty";
|
|
479
|
+
d.textContent = text;
|
|
480
|
+
node.appendChild(d);
|
|
481
|
+
};
|
|
452
482
|
let REFS = null;
|
|
453
483
|
|
|
454
|
-
const shortPath = p =>
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
484
|
+
const shortPath = p => {
|
|
485
|
+
const q = String(p).replace(/^\/+/, "");
|
|
486
|
+
return q === "仓库主页" ? "仓库主页"
|
|
487
|
+
: /^issues\/\d+$/.test(q) ? "issue 页"
|
|
488
|
+
: /^issues/.test(q) ? "issues 列表"
|
|
489
|
+
: /^readme/i.test(q) ? "README"
|
|
490
|
+
: /^actions/.test(q) ? "actions 页"
|
|
491
|
+
: /^blob\//.test(q) ? "文件页"
|
|
492
|
+
: p;
|
|
493
|
+
};
|
|
461
494
|
|
|
462
495
|
function donut(node) {
|
|
463
496
|
node.textContent = "";
|
|
464
497
|
const cs = getComputedStyle(document.documentElement);
|
|
465
498
|
let parts = PATHS ? PATHS : [];
|
|
466
|
-
if (!parts.length) parts = [["0.6.14", 320, "--brand"], ["旧版本", 1137, "--machine"]];
|
|
499
|
+
if (!parts.length && !LIVE_SET) parts = [["0.6.14", 320, "--brand"], ["旧版本", 1137, "--machine"]];
|
|
500
|
+
if (!parts.length) return emptyInto(node, "还没有页面数据");
|
|
467
501
|
const total = parts.reduce((s, p) => s + p[1], 0);
|
|
468
502
|
const R = 40, ST = 13, CIRC = 2 * Math.PI * R;
|
|
469
|
-
const svg = el("svg", { viewBox: "0 0 104 104", role: "img", "aria-label": "
|
|
503
|
+
const svg = el("svg", { viewBox: "0 0 104 104", role: "img", "aria-label": "页面访问占比" });
|
|
470
504
|
svg.appendChild(el("circle", { cx: 52, cy: 52, r: R, fill: "none", stroke: cs.getPropertyValue("--border-l1").trim(), "stroke-width": ST }));
|
|
471
505
|
let off = 0;
|
|
472
506
|
parts.forEach(p => {
|
|
@@ -504,6 +538,10 @@ function donut(node) {
|
|
|
504
538
|
|
|
505
539
|
function ranks(node) {
|
|
506
540
|
node.textContent = "";
|
|
541
|
+
if (!RANKS.length) return;
|
|
542
|
+
// 只有一两个来源时别把数字推到半屏外
|
|
543
|
+
const thin = RANKS.length === 1 && RANKS[0][1].length <= 2;
|
|
544
|
+
node.style.maxWidth = thin ? "320px" : "";
|
|
507
545
|
RANKS.forEach(([group, rows]) => {
|
|
508
546
|
const box = document.createElement("div");
|
|
509
547
|
const h3 = document.createElement("h3");
|
|
@@ -553,11 +591,12 @@ function render(days) {
|
|
|
553
591
|
const tv = recs.reduce((s, r) => s + r.v, 0);
|
|
554
592
|
const tu = recs.reduce((s, r) => s + r.u, 0);
|
|
555
593
|
// 访客只能用 API 窗口去重值;超过 14 天没有该值就退回日均
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
if (uniq == null) uniq = recs.length ?
|
|
594
|
+
// 7 天取 API 去重值,更长范围按覆盖期逐日合计
|
|
595
|
+
let uniq = LIVE.totals.uniques != null ? LIVE.totals.uniques : null;
|
|
596
|
+
if (uniq == null) uniq = recs.length ? tu : null;
|
|
559
597
|
kUniq.textContent = uniq == null ? "—" : fmt(uniq);
|
|
560
|
-
|
|
598
|
+
const covered = LIVE.range && LIVE.range.covered;
|
|
599
|
+
kViewsSub.textContent = fmt(tv) + " 次浏览" + (covered && covered < days ? `,覆盖 ${covered} 天` : "");
|
|
561
600
|
rangeNote.textContent = dom[0].label + " → " + dom[dom.length - 1].label;
|
|
562
601
|
flowChart(document.getElementById("c-flow"), days);
|
|
563
602
|
npmChart(document.getElementById("c-npm"), days);
|
|
@@ -614,9 +653,14 @@ const mmdd = iso => label(iso);
|
|
|
614
653
|
|
|
615
654
|
function applyLive(json) {
|
|
616
655
|
Object.assign(LIVE, json);
|
|
656
|
+
LIVE_SET = true;
|
|
657
|
+
PATHS = null;
|
|
658
|
+
RANKS = [];
|
|
617
659
|
if (Array.isArray(json.series) && json.series.length) {
|
|
618
660
|
DATA = json.series.map(r => ({ d: label(r.d), v: r.v ?? 0, u: r.u ?? 0, c: r.c ?? 0, cu: r.cu ?? 0, n: r.n }));
|
|
619
661
|
LAST = dayIdx(json.series[json.series.length - 1].d);
|
|
662
|
+
FIRST = json.range?.first ? dayIdx(json.range.first) : null;
|
|
663
|
+
if (FIRST != null && FIRST < 0) FIRST = null;
|
|
620
664
|
RELEASE = {};
|
|
621
665
|
for (const rel of json.releases || []) {
|
|
622
666
|
const k = label(rel.at);
|
|
@@ -624,17 +668,26 @@ function applyLive(json) {
|
|
|
624
668
|
}
|
|
625
669
|
}
|
|
626
670
|
if (Array.isArray(json.paths) && json.paths.length) {
|
|
627
|
-
const
|
|
628
|
-
const
|
|
629
|
-
|
|
671
|
+
const merged = new Map();
|
|
672
|
+
for (const p of json.paths) merged.set(shortPath(p.p), (merged.get(shortPath(p.p)) || 0) + p.n);
|
|
673
|
+
const rows = [...merged.entries()].sort((a, b) => b[1] - a[1]).slice(0, 3);
|
|
674
|
+
const rest = [...merged.values()].reduce((s, n) => s + n, 0) - rows.reduce((s, r) => s + r[1], 0);
|
|
675
|
+
PATHS = rows.map(([k, n], i) => [k, n, i === 0 ? "--brand" : i === 1 ? "--machine" : "--event"]);
|
|
630
676
|
if (rest > 0) PATHS.push(["其他页面", rest, "--border-l2"]);
|
|
631
677
|
}
|
|
632
678
|
if (Array.isArray(json.referrers) && json.referrers.length) {
|
|
633
679
|
RANKS = [["从哪来", json.referrers.slice(0, 4).map(r => [r.from.replace(/^www\./, ""), r.n])]];
|
|
634
680
|
}
|
|
635
681
|
const repo = json.repo || {};
|
|
636
|
-
|
|
637
|
-
|
|
682
|
+
const ownerEl = document.getElementById("repo-owner");
|
|
683
|
+
const nameEl = document.getElementById("repo-name");
|
|
684
|
+
if (repo.fullName === "全部仓库") {
|
|
685
|
+
ownerEl.textContent = "";
|
|
686
|
+
nameEl.textContent = "全部仓库";
|
|
687
|
+
} else {
|
|
688
|
+
ownerEl.textContent = repo.owner ? repo.owner + " /" : "";
|
|
689
|
+
nameEl.textContent = repo.name || "";
|
|
690
|
+
}
|
|
638
691
|
const c = json.contributions || { issues: [], pulls: [] };
|
|
639
692
|
const ic = c.issues.length, pc = c.pulls.length;
|
|
640
693
|
document.getElementById("k-contrib").textContent = ic + pc;
|
|
@@ -644,7 +697,7 @@ function applyLive(json) {
|
|
|
644
697
|
const rels = (json.releases || []).filter(r => DATA.some(x => x.d === label(r.at)));
|
|
645
698
|
document.getElementById("k-rel").textContent = rels.length;
|
|
646
699
|
document.getElementById("k-rel-sub").textContent = rels.length
|
|
647
|
-
? rels[rels.length - 1].tag + " → " + rels[0].tag
|
|
700
|
+
? (repo.fullName === "全部仓库" ? "最近 " + label(rels[0].at) : rels[rels.length - 1].tag + " → " + rels[0].tag)
|
|
648
701
|
: "本窗口无发版";
|
|
649
702
|
const iss = c.issues[0];
|
|
650
703
|
document.getElementById("s-issues").textContent = ic + " 个";
|
|
@@ -673,9 +726,69 @@ function applyLive(json) {
|
|
|
673
726
|
}
|
|
674
727
|
}
|
|
675
728
|
|
|
729
|
+
let REPOS = [];
|
|
730
|
+
let currentRepo = "all";
|
|
731
|
+
const PICK = document.getElementById("repo-pick");
|
|
732
|
+
const MENU = document.getElementById("repo-menu");
|
|
733
|
+
|
|
734
|
+
function closeMenu() {
|
|
735
|
+
MENU.hidden = true;
|
|
736
|
+
PICK.setAttribute("aria-expanded", "false");
|
|
737
|
+
}
|
|
738
|
+
|
|
739
|
+
function paintRepos() {
|
|
740
|
+
MENU.innerHTML = "";
|
|
741
|
+
const add = (key, label) => {
|
|
742
|
+
const b = document.createElement("button");
|
|
743
|
+
b.type = "button";
|
|
744
|
+
b.textContent = label;
|
|
745
|
+
b.dataset.key = key;
|
|
746
|
+
b.classList.toggle("on", key === currentRepo);
|
|
747
|
+
MENU.appendChild(b);
|
|
748
|
+
};
|
|
749
|
+
add("all", "全部仓库");
|
|
750
|
+
for (const r of REPOS) add(r.key, r.label.replace(/^[^/]+\//, ""));
|
|
751
|
+
closeMenu();
|
|
752
|
+
}
|
|
753
|
+
|
|
754
|
+
async function loadRepos() {
|
|
755
|
+
try {
|
|
756
|
+
const res = await fetch("/api/repos", { cache: "no-store" });
|
|
757
|
+
if (!res.ok) return;
|
|
758
|
+
const data = await res.json();
|
|
759
|
+
REPOS = data.repos || [];
|
|
760
|
+
if (currentRepo !== "all" && !REPOS.some((r) => r.key === currentRepo)) currentRepo = "all";
|
|
761
|
+
paintRepos();
|
|
762
|
+
const cur = REPOS.find((r) => r.key === currentRepo);
|
|
763
|
+
document.getElementById("repo-name").textContent = cur ? cur.key.replace(/^[^/]+\//, "") : "全部仓库";
|
|
764
|
+
document.getElementById("repo-owner").textContent = cur ? cur.key.split("/")[0] + " /" : "";
|
|
765
|
+
} catch (e) {}
|
|
766
|
+
}
|
|
767
|
+
|
|
768
|
+
PICK.addEventListener("click", (e) => {
|
|
769
|
+
e.stopPropagation();
|
|
770
|
+
const open = MENU.hidden;
|
|
771
|
+
MENU.hidden = !open;
|
|
772
|
+
PICK.setAttribute("aria-expanded", String(open));
|
|
773
|
+
});
|
|
774
|
+
|
|
775
|
+
MENU.addEventListener("click", (e) => {
|
|
776
|
+
const b = e.target.closest("button");
|
|
777
|
+
if (!b) return;
|
|
778
|
+
currentRepo = b.dataset.key;
|
|
779
|
+
[...MENU.children].forEach((x) => x.classList.toggle("on", x === b));
|
|
780
|
+
paintRepos();
|
|
781
|
+
const cur = REPOS.find((r) => r.key === currentRepo);
|
|
782
|
+
document.getElementById("repo-name").textContent = b.textContent;
|
|
783
|
+
document.getElementById("repo-owner").textContent = cur ? cur.key.split("/")[0] + " /" : "";
|
|
784
|
+
pull(currentRange, true);
|
|
785
|
+
});
|
|
786
|
+
|
|
787
|
+
document.addEventListener("click", () => closeMenu());
|
|
788
|
+
|
|
676
789
|
async function pull(days, force) {
|
|
677
790
|
try {
|
|
678
|
-
const res = await fetch("/api/data?days=" + days, { cache: "no-store" });
|
|
791
|
+
const res = await fetch("/api/data?days=" + days + "&repo=" + encodeURIComponent(currentRepo), { cache: "no-store" });
|
|
679
792
|
if (!res.ok) throw new Error(res.status);
|
|
680
793
|
const json = await res.json();
|
|
681
794
|
if (json.repo && !json.repo.stars && !force) { /* 未同步过也照常渲染 */ }
|
|
@@ -692,7 +805,7 @@ async function pull(days, force) {
|
|
|
692
805
|
|
|
693
806
|
async function loadSummary(days) {
|
|
694
807
|
try {
|
|
695
|
-
const res = await fetch("/api/summary?days=" + days, { cache: "no-store" });
|
|
808
|
+
const res = await fetch("/api/summary?days=" + days + "&repo=" + encodeURIComponent(currentRepo), { cache: "no-store" });
|
|
696
809
|
if (!res.ok) return;
|
|
697
810
|
const data = await res.json();
|
|
698
811
|
const lines = data.lines || [];
|
|
@@ -715,7 +828,7 @@ document.querySelector(".ask button").addEventListener("click", async () => {
|
|
|
715
828
|
});
|
|
716
829
|
|
|
717
830
|
|
|
718
|
-
pull(7);
|
|
831
|
+
loadRepos().then(() => pull(7));
|
|
719
832
|
let rzT;
|
|
720
833
|
addEventListener("resize", () => { clearTimeout(rzT); rzT = setTimeout(() => render(currentRange), 160); });
|
|
721
834
|
</script>
|
package/src/config.mjs
CHANGED
|
@@ -39,3 +39,32 @@ export function parseRepo(spec) {
|
|
|
39
39
|
if (!m) throw new Error(`仓库写法应为 owner/repo,收到:${spec}`);
|
|
40
40
|
return { owner: m[1], name: m[2] };
|
|
41
41
|
}
|
|
42
|
+
|
|
43
|
+
// 统一成 { user, repos: [{ repo, npm }] },并兼容旧的单仓库字段
|
|
44
|
+
export function normalizeConfig(raw = {}) {
|
|
45
|
+
const cfg = { ...raw };
|
|
46
|
+
let repos = cfg.repos;
|
|
47
|
+
if (!Array.isArray(repos) || !repos.length) {
|
|
48
|
+
repos = cfg.repo ? [{ repo: cfg.repo, npm: cfg.npm }] : [];
|
|
49
|
+
}
|
|
50
|
+
cfg.repos = repos
|
|
51
|
+
.map((r) => (typeof r === "string" ? { repo: r } : r))
|
|
52
|
+
.filter((r) => r && r.repo)
|
|
53
|
+
.map((r) => {
|
|
54
|
+
const { owner, name } = parseRepo(r.repo);
|
|
55
|
+
return { repo: `${owner}/${name}`, npm: r.npm || name };
|
|
56
|
+
});
|
|
57
|
+
if (!cfg.user && cfg.repos.length) cfg.user = cfg.repos[0].repo.split("/")[0];
|
|
58
|
+
return cfg;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export function parseRepos(spec) {
|
|
62
|
+
return String(spec || "")
|
|
63
|
+
.split(",")
|
|
64
|
+
.map((s) => s.trim())
|
|
65
|
+
.filter(Boolean)
|
|
66
|
+
.map((s) => {
|
|
67
|
+
const { owner, name } = parseRepo(s);
|
|
68
|
+
return { repo: `${owner}/${name}`, npm: name };
|
|
69
|
+
});
|
|
70
|
+
}
|
package/src/server.mjs
CHANGED
|
@@ -3,105 +3,226 @@ import { readFile } from "node:fs/promises";
|
|
|
3
3
|
import { existsSync } from "node:fs";
|
|
4
4
|
import { join, extname, dirname } from "node:path";
|
|
5
5
|
import { fileURLToPath } from "node:url";
|
|
6
|
-
import { readConfig, writeConfig, resolveToken, parseRepo } from "./config.mjs";
|
|
6
|
+
import { readConfig, writeConfig, resolveToken, parseRepo, normalizeConfig } from "./config.mjs";
|
|
7
7
|
import { makeGithub } from "./github.mjs";
|
|
8
8
|
import { makeNpm } from "./npm.mjs";
|
|
9
|
-
import { loadStore, saveStore, mergeTraffic, mergeNpm, series, storedDays } from "./store.mjs";
|
|
10
|
-
import { aiSummary, readAiConfig
|
|
9
|
+
import { loadStore, saveStore, repoStore, mergeTraffic, mergeNpm, series, storedDays } from "./store.mjs";
|
|
10
|
+
import { aiSummary, readAiConfig } from "./summary.mjs";
|
|
11
11
|
|
|
12
12
|
const ROOT = join(dirname(fileURLToPath(import.meta.url)), "..");
|
|
13
13
|
const PUBLIC = join(ROOT, "public");
|
|
14
14
|
const MIME = { ".html": "text/html; charset=utf-8", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png", ".json": "application/json" };
|
|
15
|
+
const ALL = "all";
|
|
15
16
|
|
|
16
|
-
export function createApp({ repo, days = 7 } = {}) {
|
|
17
|
-
const cfg = readConfig();
|
|
18
|
-
const
|
|
19
|
-
|
|
20
|
-
const selfLogins = cfg.selfLogins || [];
|
|
17
|
+
export function createApp({ repo, repos, days = 7, cfg: cfgIn } = {}) {
|
|
18
|
+
const cfg = cfgIn || readConfig();
|
|
19
|
+
const list = repos || normalizeConfig(cfg).repos || (repo ? [{ repo, npm: cfg.npm }] : []);
|
|
20
|
+
if (!list.length) throw new Error("还没有配置仓库");
|
|
21
21
|
const token = resolveToken(cfg);
|
|
22
|
-
const
|
|
23
|
-
const
|
|
22
|
+
const self = [...new Set([cfg.user, ...(cfg.selfLogins || [])].filter(Boolean))];
|
|
23
|
+
const targets = list.map((r) => {
|
|
24
|
+
const item = typeof r === "string" ? { repo: r } : r;
|
|
25
|
+
const { owner, name } = parseRepo(item.repo);
|
|
26
|
+
const npmPkg = item.npm || name;
|
|
27
|
+
return { key: `${owner}/${name}`, owner, name, npmPkg, gh: makeGithub(token, { owner, name }), npm: makeNpm(npmPkg) };
|
|
28
|
+
});
|
|
24
29
|
let store = loadStore();
|
|
25
30
|
let lastSync = null;
|
|
26
|
-
let lastActivity = null;
|
|
27
31
|
|
|
28
|
-
async function
|
|
29
|
-
const
|
|
32
|
+
async function syncOne(t) {
|
|
33
|
+
const s = repoStore(store, t.key);
|
|
30
34
|
const [views, clones, paths, referrers, repoInfo, releases, activity, alerts] = await Promise.all([
|
|
31
|
-
gh.views().catch(() => null),
|
|
32
|
-
gh.clones().catch(() => null),
|
|
33
|
-
gh.paths().catch(() => []),
|
|
34
|
-
gh.referrers().catch(() => []),
|
|
35
|
-
gh.repo().catch(() => null),
|
|
36
|
-
gh.releases().catch(() => []),
|
|
37
|
-
gh.activity(
|
|
38
|
-
gh.alerts().catch(() => null),
|
|
35
|
+
t.gh.views().catch(() => null),
|
|
36
|
+
t.gh.clones().catch(() => null),
|
|
37
|
+
t.gh.paths().catch(() => []),
|
|
38
|
+
t.gh.referrers().catch(() => []),
|
|
39
|
+
t.gh.repo().catch(() => null),
|
|
40
|
+
t.gh.releases().catch(() => []),
|
|
41
|
+
t.gh.activity(new Date(Date.now() - 90 * 864e5).toISOString().slice(0, 10), self).catch(() => ({ issues: [], pulls: [], selfCount: 0 })),
|
|
42
|
+
t.gh.alerts().catch(() => null),
|
|
39
43
|
]);
|
|
40
|
-
if (views || clones) mergeTraffic(
|
|
41
|
-
const
|
|
42
|
-
if (Array.isArray(
|
|
43
|
-
const week = await npm.week().catch(() => null);
|
|
44
|
-
if (Number.isFinite(week))
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
n: p.count,
|
|
51
|
-
|
|
52
|
-
}));
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
const
|
|
58
|
-
const
|
|
59
|
-
for (const v of published) {
|
|
60
|
-
|
|
44
|
+
if (views || clones) mergeTraffic(s, views, clones);
|
|
45
|
+
const npmRange = await t.npm.range(new Date(Date.now() - 400 * 864e5), new Date());
|
|
46
|
+
if (Array.isArray(npmRange)) mergeNpm(s, npmRange);
|
|
47
|
+
const week = await t.npm.week().catch(() => null);
|
|
48
|
+
if (Number.isFinite(week)) s.meta.npmWeek = week;
|
|
49
|
+
const prefix = `/${t.owner}/${t.name}`;
|
|
50
|
+
s.meta.repo = repoInfo || s.meta.repo || { owner: t.owner, name: t.name };
|
|
51
|
+
s.meta.paths = (paths || []).map((p) => {
|
|
52
|
+
const raw = String(p.path || "");
|
|
53
|
+
const page = raw === prefix || raw === prefix + "/" ? "仓库主页" : raw.replace(prefix, "");
|
|
54
|
+
return { p: page || "仓库主页", n: p.count, u: p.uniques };
|
|
55
|
+
});
|
|
56
|
+
s.meta.referrers = (referrers || []).map((r) => ({ from: r.referrer, n: r.count, u: r.uniques }));
|
|
57
|
+
s.meta.alerts = alerts;
|
|
58
|
+
s.meta.npmVers = await t.npm.perVersion().catch(() => []);
|
|
59
|
+
s.meta.activity = activity;
|
|
60
|
+
const published = await t.npm.versions().catch(() => []);
|
|
61
|
+
const merged = new Map();
|
|
62
|
+
for (const r of releases || []) merged.set(r.tag_name, { tag: r.tag_name, at: r.published_at, url: r.html_url });
|
|
63
|
+
for (const v of published) if (!merged.has(v.version)) merged.set(v.version, { tag: v.version, at: v.at, url: null });
|
|
64
|
+
s.releases = [...merged.values()]
|
|
65
|
+
.filter((r) => r.at)
|
|
66
|
+
.sort((a, b) => String(b.at).localeCompare(String(a.at)))
|
|
67
|
+
.slice(0, 30);
|
|
68
|
+
s.meta.syncedAt = new Date().toISOString();
|
|
69
|
+
s.meta.error = null;
|
|
70
|
+
return { repo: t.key, ok: true };
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
async function sync() {
|
|
74
|
+
const results = [];
|
|
75
|
+
for (const t of targets) {
|
|
76
|
+
try {
|
|
77
|
+
results.push(await syncOne(t));
|
|
78
|
+
} catch (e) {
|
|
79
|
+
const s = repoStore(store, t.key);
|
|
80
|
+
s.meta.error = String(e.message || e);
|
|
81
|
+
s.meta.syncedAt = new Date().toISOString();
|
|
82
|
+
results.push({ repo: t.key, ok: false, error: s.meta.error });
|
|
83
|
+
}
|
|
61
84
|
}
|
|
62
|
-
merged.sort((x, y) => Date.parse(y.at || 0) - Date.parse(x.at || 0));
|
|
63
|
-
store.releases = merged.slice(0, 30);
|
|
64
85
|
saveStore(store);
|
|
65
|
-
lastActivity = activity;
|
|
66
86
|
lastSync = new Date().toISOString();
|
|
67
|
-
return { ok:
|
|
87
|
+
return { ok: results.every((r) => r.ok), syncedAt: lastSync, results };
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
// GitHub 只回 14 天去重访客,更长范围沿用这段窗口并说明覆盖天数
|
|
91
|
+
const coveredDays = (s) => Object.values(s.days || {}).filter((d) => d.u != null).length;
|
|
92
|
+
const firstDay = (s) => Object.values(s.days || {})
|
|
93
|
+
.filter((d) => d.v != null || d.u != null).map((d) => d.d).sort()[0] || null;
|
|
94
|
+
|
|
95
|
+
const sumOf = (get) => {
|
|
96
|
+
let has = false;
|
|
97
|
+
let v = 0;
|
|
98
|
+
for (const t of targets) {
|
|
99
|
+
const x = get(repoStore(store, t.key));
|
|
100
|
+
if (x != null) {
|
|
101
|
+
has = true;
|
|
102
|
+
v += x;
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
return has ? v : null;
|
|
106
|
+
};
|
|
107
|
+
|
|
108
|
+
function aggregate(windowDays) {
|
|
109
|
+
const slices = targets.map((t) => ({ t, s: repoStore(store, t.key) }));
|
|
110
|
+
const allSeries = slices.map(({ s }) => series(s, windowDays, s.npm || {}));
|
|
111
|
+
const rows = [];
|
|
112
|
+
for (let i = 0; i < windowDays; i++) {
|
|
113
|
+
const cell = { d: allSeries[0]?.[i]?.d, v: null, u: null, c: null, cu: null, n: null };
|
|
114
|
+
for (const sr of allSeries) {
|
|
115
|
+
const r = sr[i];
|
|
116
|
+
if (!r) continue;
|
|
117
|
+
for (const k of ["v", "u", "c", "cu", "n"]) if (r[k] != null) cell[k] = (cell[k] ?? 0) + r[k];
|
|
118
|
+
}
|
|
119
|
+
rows.push(cell);
|
|
120
|
+
}
|
|
121
|
+
const paths = new Map();
|
|
122
|
+
const referrers = new Map();
|
|
123
|
+
const releases = [];
|
|
124
|
+
const issues = [];
|
|
125
|
+
const pulls = [];
|
|
126
|
+
const npmVersions = [];
|
|
127
|
+
const alertKeys = ["dependabot", "codeScanning", "secretScanning"];
|
|
128
|
+
const alerts = { dependabot: { available: false, open: 0 }, codeScanning: { available: false, open: 0 }, secretScanning: { available: false, open: 0 } };
|
|
129
|
+
for (const { t, s } of slices) {
|
|
130
|
+
const m = s.meta || {};
|
|
131
|
+
for (const p of m.paths || []) {
|
|
132
|
+
const cur = paths.get(p.p) || { p: p.p, n: 0, u: 0 };
|
|
133
|
+
cur.n += p.n || 0;
|
|
134
|
+
cur.u += p.u || 0;
|
|
135
|
+
paths.set(p.p, cur);
|
|
136
|
+
}
|
|
137
|
+
for (const r of m.referrers || []) {
|
|
138
|
+
const cur = referrers.get(r.from) || { from: r.from, n: 0, u: 0 };
|
|
139
|
+
cur.n += r.n || 0;
|
|
140
|
+
cur.u += r.u || 0;
|
|
141
|
+
referrers.set(r.from, cur);
|
|
142
|
+
}
|
|
143
|
+
for (const rel of s.releases || []) releases.push({ ...rel, repo: t.key });
|
|
144
|
+
for (const i of m.activity?.issues || []) issues.push({ ...i, repo: t.key });
|
|
145
|
+
for (const p of m.activity?.pulls || []) pulls.push({ ...p, repo: t.key });
|
|
146
|
+
for (const v of m.npmVers || []) npmVersions.push({ ...v, repo: t.key });
|
|
147
|
+
for (const k of alertKeys) if (m.alerts?.[k]?.available) alerts[k] = { available: true, open: (alerts[k].open || 0) + (m.alerts[k].open || 0) };
|
|
148
|
+
}
|
|
149
|
+
const anyAlert = alertKeys.some((k) => alerts[k].available);
|
|
150
|
+
const repoInfo = slices.reduce(
|
|
151
|
+
(acc, { s }) => ({
|
|
152
|
+
stars: acc.stars + (s.meta?.repo?.stars || 0),
|
|
153
|
+
forks: acc.forks + (s.meta?.repo?.forks || 0),
|
|
154
|
+
openIssues: acc.openIssues + (s.meta?.repo?.openIssues || 0),
|
|
155
|
+
}),
|
|
156
|
+
{ stars: 0, forks: 0, openIssues: 0 },
|
|
157
|
+
);
|
|
158
|
+
return {
|
|
159
|
+
repo: { fullName: "全部仓库", owner: "", name: "全部仓库", stars: repoInfo.stars, forks: repoInfo.forks, openIssues: repoInfo.openIssues, count: targets.length },
|
|
160
|
+
range: { days: windowDays, from: rows[0]?.d, to: rows.at(-1)?.d, storedDays: Math.max(...slices.map(({ s }) => storedDays(s)), 0), covered: Math.max(...slices.map(({ s }) => coveredDays(s)), 0), first: slices.map(({ s }) => firstDay(s)).filter(Boolean).sort()[0] || null },
|
|
161
|
+
series: rows,
|
|
162
|
+
totals: {
|
|
163
|
+
views: sumOf((s) => s.meta?.views?.total),
|
|
164
|
+
uniques: sumOf((s) => s.meta?.views?.uniques),
|
|
165
|
+
clones: sumOf((s) => s.meta?.clones?.total),
|
|
166
|
+
cloneUniques: sumOf((s) => s.meta?.clones?.uniques),
|
|
167
|
+
npmWeek: sumOf((s) => s.meta?.npmWeek),
|
|
168
|
+
},
|
|
169
|
+
paths: [...paths.values()].sort((a, b) => b.n - a.n),
|
|
170
|
+
referrers: [...referrers.values()].sort((a, b) => b.n - a.n),
|
|
171
|
+
releases: releases.sort((a, b) => String(b.at).localeCompare(String(a.at))).slice(0, 30),
|
|
172
|
+
npmVersions,
|
|
173
|
+
contributions: { issues, pulls, alerts: anyAlert ? alerts : null },
|
|
174
|
+
updatedAt: lastSync,
|
|
175
|
+
};
|
|
68
176
|
}
|
|
69
177
|
|
|
70
|
-
function
|
|
71
|
-
const
|
|
72
|
-
const rows = series(
|
|
73
|
-
const
|
|
74
|
-
const meta = store.meta || {};
|
|
178
|
+
function buildRepo(windowDays, t) {
|
|
179
|
+
const s = repoStore(store, t.key);
|
|
180
|
+
const rows = series(s, windowDays, s.npm || {});
|
|
181
|
+
const meta = s.meta || {};
|
|
75
182
|
const views = meta.views || {};
|
|
76
183
|
const clones = meta.clones || {};
|
|
77
|
-
const covers = storedDays(store);
|
|
78
|
-
// 访客用 API 自己的窗口去重值;窗口长于覆盖天数时退回日均估算
|
|
79
|
-
const uniques = windowDays <= 14 && views.uniques != null ? views.uniques : null;
|
|
80
184
|
return {
|
|
81
|
-
repo:
|
|
82
|
-
range: { days: windowDays, from: rows[0]?.d, to: rows.at(-1)?.d, storedDays:
|
|
185
|
+
repo: { owner: t.owner, name: t.name, npmPkg: t.npmPkg, ...(meta.repo || {}) },
|
|
186
|
+
range: { days: windowDays, from: rows[0]?.d, to: rows.at(-1)?.d, storedDays: storedDays(s), covered: coveredDays(s), first: firstDay(s) },
|
|
83
187
|
series: rows,
|
|
84
188
|
totals: {
|
|
85
189
|
views: views.total ?? null,
|
|
86
|
-
uniques,
|
|
190
|
+
uniques: views.uniques ?? null,
|
|
87
191
|
clones: clones.total ?? null,
|
|
88
192
|
cloneUniques: clones.uniques ?? null,
|
|
89
193
|
npmWeek: meta.npmWeek ?? null,
|
|
90
194
|
},
|
|
91
195
|
paths: meta.paths || [],
|
|
92
196
|
referrers: meta.referrers || [],
|
|
93
|
-
releases:
|
|
94
|
-
npmVersions:
|
|
95
|
-
contributions: {
|
|
96
|
-
|
|
97
|
-
pulls: activity.pulls || [],
|
|
98
|
-
selfCount: activity.selfCount || 0,
|
|
99
|
-
alerts: meta.alerts || null,
|
|
100
|
-
},
|
|
101
|
-
updatedAt: lastSync,
|
|
197
|
+
releases: s.releases || [],
|
|
198
|
+
npmVersions: meta.npmVers || [],
|
|
199
|
+
contributions: { issues: meta.activity?.issues || [], pulls: meta.activity?.pulls || [], alerts: meta.alerts || null },
|
|
200
|
+
updatedAt: meta.syncedAt || lastSync,
|
|
102
201
|
};
|
|
103
202
|
}
|
|
104
203
|
|
|
204
|
+
function build(windowDays, key = ALL) {
|
|
205
|
+
if (key === ALL) return aggregate(windowDays);
|
|
206
|
+
const t = targets.find((x) => x.key === key);
|
|
207
|
+
return t ? buildRepo(windowDays, t) : aggregate(windowDays);
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
const repoRows = () => ({
|
|
211
|
+
repos: targets.map((t) => {
|
|
212
|
+
const s = repoStore(store, t.key);
|
|
213
|
+
return {
|
|
214
|
+
key: t.key,
|
|
215
|
+
label: t.key,
|
|
216
|
+
npmPkg: t.npmPkg,
|
|
217
|
+
stars: s.meta?.repo?.stars ?? null,
|
|
218
|
+
storedDays: storedDays(s),
|
|
219
|
+
syncedAt: s.meta?.syncedAt ?? null,
|
|
220
|
+
error: s.meta?.error ?? null,
|
|
221
|
+
};
|
|
222
|
+
}),
|
|
223
|
+
default: ALL,
|
|
224
|
+
});
|
|
225
|
+
|
|
105
226
|
const server = createServer(async (req, res) => {
|
|
106
227
|
const url = new URL(req.url, "http://localhost");
|
|
107
228
|
const send = (code, body, type = "application/json; charset=utf-8") => {
|
|
@@ -109,23 +230,30 @@ export function createApp({ repo, days = 7 } = {}) {
|
|
|
109
230
|
res.end(typeof body === "string" || Buffer.isBuffer(body) ? body : JSON.stringify(body));
|
|
110
231
|
};
|
|
111
232
|
try {
|
|
233
|
+
if (url.pathname === "/api/repos") {
|
|
234
|
+
return send(200, repoRows());
|
|
235
|
+
}
|
|
112
236
|
if (url.pathname === "/api/data") {
|
|
113
|
-
|
|
237
|
+
const windowDays = Number(url.searchParams.get("days") || days);
|
|
238
|
+
return send(200, build(windowDays, url.searchParams.get("repo") || ALL));
|
|
114
239
|
}
|
|
115
240
|
if (url.pathname === "/api/sync" && req.method === "POST") {
|
|
116
241
|
return send(200, await sync());
|
|
117
242
|
}
|
|
118
243
|
if (url.pathname === "/api/summary") {
|
|
119
244
|
const windowDays = Number(url.searchParams.get("days") || days);
|
|
120
|
-
const
|
|
245
|
+
const key = url.searchParams.get("repo") || ALL;
|
|
246
|
+
const data = build(windowDays, key);
|
|
121
247
|
const ai = await aiSummary({
|
|
122
248
|
days: windowDays,
|
|
249
|
+
covered: data.range.covered,
|
|
123
250
|
uniques: data.totals.uniques,
|
|
124
251
|
views: data.totals.views,
|
|
125
252
|
external: data.contributions,
|
|
126
253
|
stars: data.repo.stars,
|
|
127
254
|
npmWeek: data.totals.npmWeek,
|
|
128
255
|
paths: data.paths,
|
|
256
|
+
scope: key === ALL ? `你的 ${targets.length} 个仓库` : key,
|
|
129
257
|
});
|
|
130
258
|
return send(200, ai);
|
|
131
259
|
}
|
|
@@ -153,6 +281,7 @@ export function createApp({ repo, days = 7 } = {}) {
|
|
|
153
281
|
return {
|
|
154
282
|
server,
|
|
155
283
|
sync,
|
|
284
|
+
build,
|
|
156
285
|
listen(port = 4317, host = "127.0.0.1") {
|
|
157
286
|
return new Promise((resolve) => server.listen(port, host, () => resolve(server.address())));
|
|
158
287
|
},
|
package/src/store.mjs
CHANGED
|
@@ -3,49 +3,75 @@ import { dirname } from "node:path";
|
|
|
3
3
|
import { STORE_PATH } from "./config.mjs";
|
|
4
4
|
|
|
5
5
|
// GitHub traffic only keeps 14 rolling days, so every sync appends today's row.
|
|
6
|
-
const
|
|
6
|
+
const emptySlice = () => ({ days: {}, npm: {}, releases: [], meta: {} });
|
|
7
|
+
const emptyStore = () => ({ version: 2, repos: {} });
|
|
7
8
|
|
|
8
9
|
export function loadStore(path = STORE_PATH) {
|
|
9
|
-
if (!existsSync(path)) return
|
|
10
|
+
if (!existsSync(path)) return emptyStore();
|
|
10
11
|
try {
|
|
11
12
|
const data = JSON.parse(readFileSync(path, "utf8"));
|
|
12
|
-
return {
|
|
13
|
+
if (data.version === 2 && data.repos) return { version: 2, repos: data.repos };
|
|
14
|
+
return migrateV1(data);
|
|
13
15
|
} catch {
|
|
14
|
-
return
|
|
16
|
+
return emptyStore();
|
|
15
17
|
}
|
|
16
18
|
}
|
|
17
19
|
|
|
20
|
+
// 旧版是单仓库平铺结构,升级时按 meta.repo.fullName 挂到仓库键下
|
|
21
|
+
function migrateV1(data) {
|
|
22
|
+
const store = emptyStore();
|
|
23
|
+
const key = data?.meta?.repo?.fullName;
|
|
24
|
+
if (key) {
|
|
25
|
+
store.repos[key] = {
|
|
26
|
+
days: data.days || {},
|
|
27
|
+
npm: data.npm || {},
|
|
28
|
+
releases: data.releases || [],
|
|
29
|
+
meta: data.meta || {},
|
|
30
|
+
};
|
|
31
|
+
}
|
|
32
|
+
return store;
|
|
33
|
+
}
|
|
34
|
+
|
|
18
35
|
export function saveStore(store, path = STORE_PATH) {
|
|
19
36
|
mkdirSync(dirname(path), { recursive: true });
|
|
20
37
|
writeFileSync(path, JSON.stringify(store, null, 2) + "\n");
|
|
21
38
|
return store;
|
|
22
39
|
}
|
|
23
40
|
|
|
41
|
+
export function repoStore(store, key) {
|
|
42
|
+
if (!store.repos[key]) store.repos[key] = emptySlice();
|
|
43
|
+
return store.repos[key];
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export function hasRepo(store, key) {
|
|
47
|
+
return Boolean(store.repos[key]);
|
|
48
|
+
}
|
|
49
|
+
|
|
24
50
|
const keyOf = (iso) => String(iso).slice(0, 10);
|
|
25
51
|
|
|
26
|
-
export function mergeTraffic(
|
|
52
|
+
export function mergeTraffic(slice, views, clones) {
|
|
27
53
|
const rows = [...(views?.views || []), ...(clones?.clones || [])];
|
|
28
54
|
for (const v of views?.views || []) {
|
|
29
55
|
const k = keyOf(v.timestamp);
|
|
30
|
-
|
|
56
|
+
slice.days[k] = { ...(slice.days[k] || {}), d: k, v: v.count, u: v.uniques };
|
|
31
57
|
}
|
|
32
58
|
for (const c of clones?.clones || []) {
|
|
33
59
|
const k = keyOf(c.timestamp);
|
|
34
|
-
|
|
60
|
+
slice.days[k] = { ...(slice.days[k] || {}), d: k, c: c.count, cu: c.uniques };
|
|
35
61
|
}
|
|
36
62
|
// API window totals are the only correct unique counts; daily uniques must never be summed
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
return {
|
|
63
|
+
slice.meta.views = { total: views?.count ?? null, uniques: views?.uniques ?? null, at: new Date().toISOString() };
|
|
64
|
+
slice.meta.clones = { total: clones?.count ?? null, uniques: clones?.uniques ?? null, at: new Date().toISOString() };
|
|
65
|
+
return { slice, rows: rows.length };
|
|
40
66
|
}
|
|
41
67
|
|
|
42
|
-
export function mergeNpm(
|
|
43
|
-
if (!Array.isArray(daily)) return
|
|
44
|
-
for (const r of daily)
|
|
45
|
-
return
|
|
68
|
+
export function mergeNpm(slice, daily) {
|
|
69
|
+
if (!Array.isArray(daily)) return slice;
|
|
70
|
+
for (const r of daily) slice.npm[r.d] = r.n;
|
|
71
|
+
return slice;
|
|
46
72
|
}
|
|
47
73
|
|
|
48
|
-
export function series(
|
|
74
|
+
export function series(slice, days, npmDaily = {}) {
|
|
49
75
|
const out = [];
|
|
50
76
|
const today = new Date();
|
|
51
77
|
today.setUTCHours(0, 0, 0, 0);
|
|
@@ -53,19 +79,19 @@ export function series(store, days, npmDaily = {}) {
|
|
|
53
79
|
const d = new Date(today);
|
|
54
80
|
d.setUTCDate(d.getUTCDate() - i);
|
|
55
81
|
const k = d.toISOString().slice(0, 10);
|
|
56
|
-
const row =
|
|
82
|
+
const row = slice.days[k] || {};
|
|
57
83
|
out.push({
|
|
58
84
|
d: k,
|
|
59
85
|
v: row.v ?? null,
|
|
60
86
|
u: row.u ?? null,
|
|
61
87
|
c: row.c ?? null,
|
|
62
88
|
cu: row.cu ?? null,
|
|
63
|
-
n: npmDaily[k] ??
|
|
89
|
+
n: npmDaily[k] ?? slice.npm[k] ?? null,
|
|
64
90
|
});
|
|
65
91
|
}
|
|
66
92
|
return out;
|
|
67
93
|
}
|
|
68
94
|
|
|
69
|
-
export function storedDays(
|
|
70
|
-
return Object.keys(
|
|
95
|
+
export function storedDays(slice) {
|
|
96
|
+
return Object.keys(slice.days).length;
|
|
71
97
|
}
|
package/src/summary.mjs
CHANGED
|
@@ -3,12 +3,16 @@ import { readConfig, writeConfig } from "./config.mjs";
|
|
|
3
3
|
const DEFAULT_MODEL = "deepseek-chat";
|
|
4
4
|
|
|
5
5
|
export function templateSummary(ctx) {
|
|
6
|
-
const { uniques, external, stars, npmWeek, days } = ctx;
|
|
6
|
+
const { uniques, external, stars, npmWeek, days, covered } = ctx;
|
|
7
7
|
const lines = [];
|
|
8
|
-
|
|
8
|
+
// 覆盖期短于所选范围时按实际天数说,不把 14 天的数说成 30 天
|
|
9
|
+
const span = covered && covered < days ? covered : days;
|
|
10
|
+
if (uniques == null) lines.push(`这 ${span} 天还没有访问记录。`);
|
|
11
|
+
else if (uniques === 0) lines.push(`这 ${span} 天还没有访客。`);
|
|
12
|
+
else lines.push(`近 ${span} 天约 ${uniques} 人来看过仓库。`);
|
|
9
13
|
const ic = external.issues.length, pc = external.pulls.length;
|
|
10
14
|
lines.push(ic || pc ? `外部提了 ${ic} 个 issue、${pc} 个 PR。` : `这段时间没有外部 issue 或 PR。`);
|
|
11
|
-
if (stars
|
|
15
|
+
if (stars) lines.push(`Star 到 ${stars}${npmWeek ? `,npm 周下载 ${fmt(npmWeek)}` : ""}。`);
|
|
12
16
|
return lines;
|
|
13
17
|
}
|
|
14
18
|
|