github-overview 0.0.0-stage → 0.1.1

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/src/config.mjs ADDED
@@ -0,0 +1,41 @@
1
+ import { readFileSync, writeFileSync, mkdirSync, existsSync } from "node:fs";
2
+ import { homedir } from "node:os";
3
+ import { join, dirname } from "node:path";
4
+ import { execFileSync } from "node:child_process";
5
+
6
+ export const CONFIG_DIR = process.env.GITHUB_OVERVIEW_HOME || join(homedir(), ".config", "github-overview");
7
+ export const CONFIG_PATH = join(CONFIG_DIR, "config.json");
8
+ export const STORE_PATH = join(CONFIG_DIR, "store.json");
9
+
10
+ export function readConfig() {
11
+ if (!existsSync(CONFIG_PATH)) return {};
12
+ try {
13
+ return JSON.parse(readFileSync(CONFIG_PATH, "utf8"));
14
+ } catch {
15
+ return {};
16
+ }
17
+ }
18
+
19
+ export function writeConfig(next) {
20
+ mkdirSync(dirname(CONFIG_PATH), { recursive: true });
21
+ writeFileSync(CONFIG_PATH, JSON.stringify(next, null, 2) + "\n");
22
+ return next;
23
+ }
24
+
25
+ // Token order: env → config → gh CLI (most people already have gh logged in)
26
+ export function resolveToken(cfg = readConfig()) {
27
+ if (process.env.GITHUB_TOKEN) return process.env.GITHUB_TOKEN;
28
+ if (process.env.GH_TOKEN) return process.env.GH_TOKEN;
29
+ if (cfg.token) return cfg.token;
30
+ try {
31
+ return execFileSync("gh", ["auth", "token"], { encoding: "utf8" }).trim();
32
+ } catch {
33
+ return "";
34
+ }
35
+ }
36
+
37
+ export function parseRepo(spec) {
38
+ const m = /^([\w.-]+)\/([\w.-]+)$/.exec(String(spec || "").trim());
39
+ if (!m) throw new Error(`仓库写法应为 owner/repo,收到:${spec}`);
40
+ return { owner: m[1], name: m[2] };
41
+ }
package/src/github.mjs ADDED
@@ -0,0 +1,113 @@
1
+ const API = "https://api.github.com";
2
+
3
+ export function makeGithub(token, { owner, name }) {
4
+ async function gh(path, { method = "GET", body } = {}) {
5
+ const res = await fetch(API + path, {
6
+ method,
7
+ headers: {
8
+ accept: "application/vnd.github+json",
9
+ "x-github-api-version": "2022-11-28",
10
+ "user-agent": "github-overview",
11
+ ...(token ? { authorization: `Bearer ${token}` } : {}),
12
+ ...(body ? { "content-type": "application/json" } : {}),
13
+ },
14
+ body: body ? JSON.stringify(body) : undefined,
15
+ });
16
+ const text = await res.text();
17
+ let data = null;
18
+ try {
19
+ data = text ? JSON.parse(text) : null;
20
+ } catch {
21
+ data = text;
22
+ }
23
+ if (!res.ok) {
24
+ const err = new Error(`${method} ${path} → ${res.status} ${data?.message || ""}`.trim());
25
+ err.status = res.status;
26
+ throw err;
27
+ }
28
+ return data;
29
+ }
30
+
31
+ const repoPath = `/repos/${owner}/${name}`;
32
+
33
+ return {
34
+ owner,
35
+ name,
36
+ gh,
37
+ async repo() {
38
+ const r = await gh(repoPath);
39
+ return {
40
+ owner, name,
41
+ fullName: r.full_name,
42
+ stars: r.stargazers_count,
43
+ forks: r.forks_count,
44
+ watchers: r.subscribers_count,
45
+ openIssues: r.open_issues_count,
46
+ createdAt: r.created_at,
47
+ pushedAt: r.pushed_at,
48
+ htmlUrl: r.html_url,
49
+ description: r.description || "",
50
+ };
51
+ },
52
+ // traffic endpoints need push access, and only keep 14 rolling days
53
+ async views() { return gh(`${repoPath}/traffic/views?per=day`); },
54
+ async clones() { return gh(`${repoPath}/traffic/clones?per=day`); },
55
+ async referrers() { return gh(`${repoPath}/traffic/popular/referrers`); },
56
+ async paths() { return gh(`${repoPath}/traffic/popular/paths`); },
57
+ async releases() { return gh(`${repoPath}/releases?per_page=100`); },
58
+ // external-only: everything not authored by the repo owner (or self aliases)
59
+ async activity(sinceIso, selfLogins = []) {
60
+ const self = new Set([owner.toLowerCase(), ...selfLogins.map(s => String(s).toLowerCase())]);
61
+ const out = { issues: [], pulls: [], selfCount: 0 };
62
+ for (let page = 1; page <= 5; page++) {
63
+ const rows = await gh(
64
+ `/search/issues?q=${encodeURIComponent(`repo:${owner}/${name} created:>=${sinceIso}`)}&per_page=100&page=${page}`
65
+ );
66
+ const items = rows.items || [];
67
+ for (const it of items) {
68
+ const kind = it.pull_request ? "pulls" : "issues";
69
+ const author = it.user?.login || "ghost";
70
+ if (self.has(author.toLowerCase())) { out.selfCount++; continue; }
71
+ out[kind].push({
72
+ number: it.number,
73
+ title: it.title,
74
+ author,
75
+ state: it.state,
76
+ createdAt: it.created_at,
77
+ closedAt: it.closed_at,
78
+ merged: Boolean(it.pull_request?.merged_at),
79
+ mergedAt: it.pull_request?.merged_at || null,
80
+ comments: it.comments,
81
+ url: it.html_url,
82
+ });
83
+ }
84
+ if (items.length < 100) break;
85
+ }
86
+ for (const pr of out.pulls) {
87
+ try {
88
+ const detail = await gh(`${repoPath}/pulls/${pr.number}`);
89
+ pr.additions = detail.additions;
90
+ pr.deletions = detail.deletions;
91
+ } catch { /* older PRs can 404 on details; keep the row */ }
92
+ }
93
+ return out;
94
+ },
95
+ async alerts() {
96
+ const probe = async (path) => {
97
+ try {
98
+ const rows = await gh(`${path}?state=open&per_page=100`);
99
+ return { available: true, open: Array.isArray(rows) ? rows.length : 0 };
100
+ } catch (e) {
101
+ // 403/404 means the feature is off or the token lacks scope: report, never throw
102
+ return { available: false, open: null, reason: e.status === 404 ? "no-analysis" : "disabled" };
103
+ }
104
+ };
105
+ const [dependabot, codeScanning, secretScanning] = await Promise.all([
106
+ probe(`${repoPath}/dependabot/alerts`),
107
+ probe(`${repoPath}/code-scanning/alerts`),
108
+ probe(`${repoPath}/secret-scanning/alerts`),
109
+ ]);
110
+ return { dependabot, codeScanning, secretScanning };
111
+ },
112
+ };
113
+ }
package/src/npm.mjs ADDED
@@ -0,0 +1,67 @@
1
+ const POINT = "https://api.npmjs.org/downloads/point";
2
+ const RANGE = "https://api.npmjs.org/downloads/range";
3
+ const REGISTRY = "https://registry.npmjs.org";
4
+
5
+ const day = (d) => d.toISOString().slice(0, 10);
6
+ export const shiftDays = (n, from = new Date()) => {
7
+ const d = new Date(from);
8
+ d.setUTCDate(d.getUTCDate() + n);
9
+ return d;
10
+ };
11
+
12
+ async function getJson(url) {
13
+ const res = await fetch(url, { headers: { "user-agent": "github-overview" } });
14
+ if (!res.ok) {
15
+ const e = new Error(`npm ${url} → ${res.status}`);
16
+ e.status = res.status;
17
+ throw e;
18
+ }
19
+ return res.json();
20
+ }
21
+
22
+ export function makeNpm(pkg) {
23
+ const safe = encodeURIComponent(pkg);
24
+ return {
25
+ pkg,
26
+ async week() {
27
+ try {
28
+ return (await getJson(`${POINT}/last-week/${safe}`)).downloads ?? null;
29
+ } catch {
30
+ return null;
31
+ }
32
+ },
33
+ // range keeps ~18 months; anything older has no daily series
34
+ async range(fromIso, toIso) {
35
+ try {
36
+ const data = await getJson(`${RANGE}/${day(new Date(fromIso))}:${day(new Date(toIso))}/${safe}`);
37
+ return (data.downloads || []).map((r) => ({ d: r.day, n: r.downloads }));
38
+ } catch (e) {
39
+ return { error: e.status || 0, rows: [] };
40
+ }
41
+ },
42
+ async versions() {
43
+ try {
44
+ const meta = await getJson(`${REGISTRY}/${safe}`);
45
+ const times = meta.time || {};
46
+ return Object.keys(times)
47
+ .filter((v) => !["created", "modified"].includes(v))
48
+ .map((v) => ({ version: v, at: times[v] }))
49
+ .sort((a, b) => String(b.at).localeCompare(String(a.at)));
50
+ } catch {
51
+ return [];
52
+ }
53
+ },
54
+ async perVersion() {
55
+ const list = await this.versions();
56
+ const recent = list.slice(0, 3);
57
+ const out = [];
58
+ for (const v of recent) {
59
+ try {
60
+ const r = await getJson(`${POINT}/last-week/${encodeURIComponent(safe + "@" + v.version)}`);
61
+ out.push({ version: v.version, downloads: r.downloads ?? 0 });
62
+ } catch { /* unpublished or scoped edge case */ }
63
+ }
64
+ return out;
65
+ },
66
+ };
67
+ }
package/src/server.mjs ADDED
@@ -0,0 +1,160 @@
1
+ import { createServer } from "node:http";
2
+ import { readFile } from "node:fs/promises";
3
+ import { existsSync } from "node:fs";
4
+ import { join, extname, dirname } from "node:path";
5
+ import { fileURLToPath } from "node:url";
6
+ import { readConfig, writeConfig, resolveToken, parseRepo } from "./config.mjs";
7
+ import { makeGithub } from "./github.mjs";
8
+ import { makeNpm } from "./npm.mjs";
9
+ import { loadStore, saveStore, mergeTraffic, mergeNpm, series, storedDays } from "./store.mjs";
10
+ import { aiSummary, readAiConfig, saveAiConfig } from "./summary.mjs";
11
+
12
+ const ROOT = join(dirname(fileURLToPath(import.meta.url)), "..");
13
+ const PUBLIC = join(ROOT, "public");
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
+
16
+ export function createApp({ repo, days = 7 } = {}) {
17
+ const cfg = readConfig();
18
+ const target = parseRepo(repo || cfg.repo || "");
19
+ const npmPkg = cfg.npm || target.name;
20
+ const selfLogins = cfg.selfLogins || [];
21
+ const token = resolveToken(cfg);
22
+ const gh = makeGithub(token, target);
23
+ const npm = makeNpm(npmPkg);
24
+ let store = loadStore();
25
+ let lastSync = null;
26
+ let lastActivity = null;
27
+
28
+ async function sync() {
29
+ const from = new Date(Date.now() - 14 * 864e5).toISOString();
30
+ 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(from, selfLogins).catch(() => ({ issues: [], pulls: [], selfCount: 0 })),
38
+ gh.alerts().catch(() => null),
39
+ ]);
40
+ if (views || clones) mergeTraffic(store, views, clones);
41
+ const range = await npm.range(new Date(Date.now() - 400 * 864e5), new Date());
42
+ if (Array.isArray(range)) mergeNpm(store, range);
43
+ const week = await npm.week().catch(() => null);
44
+ if (week && Number.isFinite(week.downloads)) store.meta.npmWeek = week.downloads;
45
+ store.meta.repo = repoInfo || store.meta.repo || null;
46
+ const prefix = `/${target.owner}/${target.name}`;
47
+ store.meta.paths = (paths || []).map((p) => ({
48
+ p: p.path === prefix ? "仓库主页"
49
+ : (p.path.startsWith(prefix + "/") ? p.path.slice(prefix.length + 1) : p.path),
50
+ n: p.count,
51
+ u: p.uniques,
52
+ }));
53
+ store.meta.referrers = (referrers || []).map((r) => ({ from: r.referrer, n: r.count, u: r.uniques }));
54
+ store.meta.alerts = alerts;
55
+ store.meta.npmVers = await npm.perVersion().catch(() => []);
56
+ // 发版时间优先用 npm 发布时间:GitHub 上很多仓库只打 tag 而不建 Release
57
+ const published = await npm.versions().catch(() => []);
58
+ const merged = (releases || []).map((r) => ({ tag: r.tag_name, at: r.published_at, url: r.html_url }));
59
+ for (const v of published) {
60
+ if (!merged.some((r) => r.tag === v.version)) merged.push({ tag: v.version, at: v.at, url: null });
61
+ }
62
+ merged.sort((x, y) => Date.parse(y.at || 0) - Date.parse(x.at || 0));
63
+ store.releases = merged.slice(0, 30);
64
+ saveStore(store);
65
+ lastActivity = activity;
66
+ lastSync = new Date().toISOString();
67
+ return { ok: true, syncedAt: lastSync };
68
+ }
69
+
70
+ function build(windowDays) {
71
+ const npmDaily = store.npm || {};
72
+ const rows = series(store, windowDays, npmDaily);
73
+ const activity = lastActivity || { issues: [], pulls: [], selfCount: 0 };
74
+ const meta = store.meta || {};
75
+ const views = meta.views || {};
76
+ const clones = meta.clones || {};
77
+ const covers = storedDays(store);
78
+ // 访客用 API 自己的窗口去重值;窗口长于覆盖天数时退回日均估算
79
+ const uniques = windowDays <= 14 && views.uniques != null ? views.uniques : null;
80
+ return {
81
+ repo: meta.repo ? { ...meta.repo, npmPkg } : { owner: target.owner, name: target.name, npmPkg },
82
+ range: { days: windowDays, from: rows[0]?.d, to: rows.at(-1)?.d, storedDays: covers },
83
+ series: rows,
84
+ totals: {
85
+ views: views.total ?? null,
86
+ uniques,
87
+ clones: clones.total ?? null,
88
+ cloneUniques: clones.uniques ?? null,
89
+ npmWeek: meta.npmWeek ?? null,
90
+ },
91
+ paths: meta.paths || [],
92
+ referrers: meta.referrers || [],
93
+ releases: store.releases || [],
94
+ npmVersions: (store.meta && store.meta.npmVers) || [],
95
+ contributions: {
96
+ issues: activity.issues || [],
97
+ pulls: activity.pulls || [],
98
+ selfCount: activity.selfCount || 0,
99
+ alerts: meta.alerts || null,
100
+ },
101
+ updatedAt: lastSync,
102
+ };
103
+ }
104
+
105
+ const server = createServer(async (req, res) => {
106
+ const url = new URL(req.url, "http://localhost");
107
+ const send = (code, body, type = "application/json; charset=utf-8") => {
108
+ res.writeHead(code, { "content-type": type, "cache-control": "no-store" });
109
+ res.end(typeof body === "string" || Buffer.isBuffer(body) ? body : JSON.stringify(body));
110
+ };
111
+ try {
112
+ if (url.pathname === "/api/data") {
113
+ return send(200, build(Number(url.searchParams.get("days") || days)));
114
+ }
115
+ if (url.pathname === "/api/sync" && req.method === "POST") {
116
+ return send(200, await sync());
117
+ }
118
+ if (url.pathname === "/api/summary") {
119
+ const windowDays = Number(url.searchParams.get("days") || days);
120
+ const data = build(windowDays);
121
+ const ai = await aiSummary({
122
+ days: windowDays,
123
+ uniques: data.totals.uniques,
124
+ views: data.totals.views,
125
+ external: data.contributions,
126
+ stars: data.repo.stars,
127
+ npmWeek: data.totals.npmWeek,
128
+ paths: data.paths,
129
+ });
130
+ return send(200, ai);
131
+ }
132
+ if (url.pathname === "/api/config") {
133
+ if (req.method === "POST") {
134
+ let raw = "";
135
+ for await (const chunk of req) raw += chunk;
136
+ const body = JSON.parse(raw || "{}");
137
+ const next = { ...readConfig(), ...body };
138
+ writeConfig(next);
139
+ return send(200, { ...readAiConfig(), apikey: next.apikey ? "已保存" : "" });
140
+ }
141
+ const ai = readAiConfig();
142
+ return send(200, { ...ai, apikey: ai.apikey ? "已保存" : "" });
143
+ }
144
+ let file = url.pathname === "/" ? "/index.html" : url.pathname;
145
+ const full = join(PUBLIC, file);
146
+ if (!full.startsWith(PUBLIC) || !existsSync(full)) return send(404, "not found", "text/plain");
147
+ return send(200, await readFile(full), MIME[extname(full)] || "application/octet-stream");
148
+ } catch (e) {
149
+ return send(500, { error: String(e.message || e) });
150
+ }
151
+ });
152
+
153
+ return {
154
+ server,
155
+ sync,
156
+ listen(port = 4317, host = "127.0.0.1") {
157
+ return new Promise((resolve) => server.listen(port, host, () => resolve(server.address())));
158
+ },
159
+ };
160
+ }
package/src/store.mjs ADDED
@@ -0,0 +1,71 @@
1
+ import { readFileSync, writeFileSync, mkdirSync, existsSync } from "node:fs";
2
+ import { dirname } from "node:path";
3
+ import { STORE_PATH } from "./config.mjs";
4
+
5
+ // GitHub traffic only keeps 14 rolling days, so every sync appends today's row.
6
+ const EMPTY = { version: 1, days: {}, npm: {}, releases: [], meta: {} };
7
+
8
+ export function loadStore(path = STORE_PATH) {
9
+ if (!existsSync(path)) return structuredClone(EMPTY);
10
+ try {
11
+ const data = JSON.parse(readFileSync(path, "utf8"));
12
+ return { ...structuredClone(EMPTY), ...data, days: data.days || {} };
13
+ } catch {
14
+ return structuredClone(EMPTY);
15
+ }
16
+ }
17
+
18
+ export function saveStore(store, path = STORE_PATH) {
19
+ mkdirSync(dirname(path), { recursive: true });
20
+ writeFileSync(path, JSON.stringify(store, null, 2) + "\n");
21
+ return store;
22
+ }
23
+
24
+ const keyOf = (iso) => String(iso).slice(0, 10);
25
+
26
+ export function mergeTraffic(store, views, clones) {
27
+ const rows = [...(views?.views || []), ...(clones?.clones || [])];
28
+ for (const v of views?.views || []) {
29
+ const k = keyOf(v.timestamp);
30
+ store.days[k] = { ...(store.days[k] || {}), d: k, v: v.count, u: v.uniques };
31
+ }
32
+ for (const c of clones?.clones || []) {
33
+ const k = keyOf(c.timestamp);
34
+ store.days[k] = { ...(store.days[k] || {}), d: k, c: c.count, cu: c.uniques };
35
+ }
36
+ // API window totals are the only correct unique counts; daily uniques must never be summed
37
+ store.meta.views = { total: views?.count ?? null, uniques: views?.uniques ?? null, at: new Date().toISOString() };
38
+ store.meta.clones = { total: clones?.count ?? null, uniques: clones?.uniques ?? null, at: new Date().toISOString() };
39
+ return { store, rows: rows.length };
40
+ }
41
+
42
+ export function mergeNpm(store, daily) {
43
+ if (!Array.isArray(daily)) return store;
44
+ for (const r of daily) store.npm[r.d] = r.n;
45
+ return store;
46
+ }
47
+
48
+ export function series(store, days, npmDaily = {}) {
49
+ const out = [];
50
+ const today = new Date();
51
+ today.setUTCHours(0, 0, 0, 0);
52
+ for (let i = days - 1; i >= 0; i--) {
53
+ const d = new Date(today);
54
+ d.setUTCDate(d.getUTCDate() - i);
55
+ const k = d.toISOString().slice(0, 10);
56
+ const row = store.days[k] || {};
57
+ out.push({
58
+ d: k,
59
+ v: row.v ?? null,
60
+ u: row.u ?? null,
61
+ c: row.c ?? null,
62
+ cu: row.cu ?? null,
63
+ n: npmDaily[k] ?? store.npm[k] ?? null,
64
+ });
65
+ }
66
+ return out;
67
+ }
68
+
69
+ export function storedDays(store) {
70
+ return Object.keys(store.days).length;
71
+ }
@@ -0,0 +1,70 @@
1
+ import { readConfig, writeConfig } from "./config.mjs";
2
+
3
+ const DEFAULT_MODEL = "deepseek-chat";
4
+
5
+ export function templateSummary(ctx) {
6
+ const { uniques, external, stars, npmWeek, days } = ctx;
7
+ const lines = [];
8
+ if (uniques != null) lines.push(`近 ${days} 天约 ${uniques} 人来看过仓库。`);
9
+ const ic = external.issues.length, pc = external.pulls.length;
10
+ lines.push(ic || pc ? `外部提了 ${ic} 个 issue、${pc} 个 PR。` : `这段时间没有外部 issue 或 PR。`);
11
+ if (stars != null) lines.push(`Star 到 ${stars}${npmWeek ? `,npm 周下载 ${fmt(npmWeek)}` : ""}。`);
12
+ return lines;
13
+ }
14
+
15
+ const fmt = (n) => (n >= 10000 ? `${(n / 10000).toFixed(2).replace(/0$/, "")} 万` : String(n));
16
+
17
+ // AI 配置就两样:apikey 和 baseurl,存在本机配置里,不进仓库
18
+ export function readAiConfig() {
19
+ const cfg = readConfig();
20
+ return { apikey: cfg.apikey || "", baseurl: cfg.baseurl || "", model: cfg.model || DEFAULT_MODEL };
21
+ }
22
+
23
+ export function saveAiConfig({ apikey, baseurl, model }) {
24
+ const cfg = readConfig();
25
+ return writeConfig({ ...cfg, apikey: apikey ?? cfg.apikey ?? "", baseurl: baseurl ?? cfg.baseurl ?? "", model: model || cfg.model || DEFAULT_MODEL });
26
+ }
27
+
28
+ export async function aiSummary(ctx) {
29
+ const { apikey, baseurl, model } = readAiConfig();
30
+ if (!apikey || !baseurl) return { source: "template", lines: templateSummary(ctx) };
31
+ const url = baseurl.replace(/\/$/, "") + "/chat/completions";
32
+ const facts = [
33
+ `窗口:近 ${ctx.days} 天`,
34
+ `访客:${ctx.uniques ?? "未知"} 人,浏览 ${ctx.views ?? "未知"} 次`,
35
+ `外部 issue ${ctx.external.issues.length} 个,外部 PR ${ctx.external.pulls.length} 个`,
36
+ `stars ${ctx.stars},npm 周下载 ${ctx.npmWeek ?? "未知"}`,
37
+ `最热页面:${(ctx.paths || []).slice(0, 3).map((p) => `${p.p}(${p.n})`).join("、")}`,
38
+ ].join("\n");
39
+ const body = {
40
+ model,
41
+ temperature: 0.3,
42
+ max_tokens: 180,
43
+ messages: [
44
+ {
45
+ role: "system",
46
+ content:
47
+ "你在给一个 GitHub 仓库的数据看板写摘要。只写 2 到 3 句话,每句不超过 26 个汉字。" +
48
+ "只讲结论和事实:大概多少人来看、外部给了什么反馈、仓库涨了多少。" +
49
+ "不要解释流量为什么涨,不要提机器、机器人、镜像、CI、发版带来的流量,不要用「图 1」这种编号引用。" +
50
+ "不要重复用户已经看到的数字之外的分析;不要用「独立」「重复」这类词。直接输出正文,不要列表,不要标题。",
51
+ },
52
+ { role: "user", content: facts },
53
+ ],
54
+ };
55
+ try {
56
+ const res = await fetch(url, {
57
+ method: "POST",
58
+ headers: { "content-type": "application/json", authorization: `Bearer ${apikey}` },
59
+ body: JSON.stringify(body),
60
+ });
61
+ if (!res.ok) throw new Error(`${res.status}`);
62
+ const data = await res.json();
63
+ const text = data?.choices?.[0]?.message?.content?.trim();
64
+ if (!text) throw new Error("empty");
65
+ const lines = text.split(/\n+/).map((s) => s.replace(/^[-*\d.、\s]+/, "").trim()).filter(Boolean).slice(0, 3);
66
+ return { source: "ai", lines, model };
67
+ } catch (e) {
68
+ return { source: "template", lines: templateSummary(ctx), error: String(e.message || e) };
69
+ }
70
+ }