dsh-commit-journal 0.0.0-stage → 0.3.0

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/lib/index.js ADDED
@@ -0,0 +1,3031 @@
1
+ import { existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, realpathSync, statSync, unlinkSync, writeFileSync } from "fs";
2
+ import { homedir, hostname } from "os";
3
+ import { basename, delimiter, join, relative, resolve, sep } from "path";
4
+ import { v4 } from "uuid";
5
+ import { createCipheriv, createDecipheriv, createHash, randomBytes, scryptSync } from "crypto";
6
+ import dayjs from "dayjs";
7
+ import http from "node:http";
8
+ import https from "node:https";
9
+ import { execFile } from "child_process";
10
+ import { promisify } from "util";
11
+ import { defineTool } from "@deepseek-ai/dsh-tools";
12
+ import isoWeek from "dayjs/plugin/isoWeek.js";
13
+ import { createServer } from "http";
14
+ // src/core/types.ts
15
+ const DEFAULT_UI_PORT = 39282;
16
+ // src/core/settings.ts
17
+ const defaults = {
18
+ exportsPath: "",
19
+ syncIntervalMinutes: 30,
20
+ syncLookbackDays: 90,
21
+ uiPort: DEFAULT_UI_PORT
22
+ };
23
+ function load$1() {
24
+ const path = settingsPath();
25
+ if (!existsSync(path)) return { ...defaults };
26
+ try {
27
+ return {
28
+ ...defaults,
29
+ ...JSON.parse(readFileSync(path, "utf8"))
30
+ };
31
+ } catch {
32
+ return { ...defaults };
33
+ }
34
+ }
35
+ function save$1(settings) {
36
+ writeFileSync(settingsPath(), JSON.stringify(settings, null, 2), "utf8");
37
+ }
38
+ function updateSettings(patch) {
39
+ const next = {
40
+ ...load$1(),
41
+ ...patch
42
+ };
43
+ if (next.syncIntervalMinutes < 5) next.syncIntervalMinutes = 5;
44
+ if (next.syncLookbackDays < 1) next.syncLookbackDays = 1;
45
+ if (next.uiPort < 1024 || next.uiPort > 65535) next.uiPort = DEFAULT_UI_PORT;
46
+ save$1(next);
47
+ return next;
48
+ }
49
+ function getExportsPathSetting() {
50
+ return (load$1().exportsPath || "").trim();
51
+ }
52
+ function getSyncIntervalMinutes() {
53
+ return load$1().syncIntervalMinutes || 30;
54
+ }
55
+ function getSyncLookbackDays() {
56
+ return load$1().syncLookbackDays || 90;
57
+ }
58
+ function getUiPort() {
59
+ return load$1().uiPort || 39282;
60
+ }
61
+ function describeSettings() {
62
+ const s = load$1();
63
+ return {
64
+ ...s,
65
+ resolvedExportsPath: s.exportsPath?.trim() || defaultExportsDir(),
66
+ defaultExportsPath: defaultExportsDir()
67
+ };
68
+ }
69
+ // src/core/paths.ts
70
+ function getDataRoot() {
71
+ const root = process.env.DSH_COMMIT_JOURNAL_HOME?.trim() || join(homedir(), ".dsh-commit-journal");
72
+ mkdirSync(root, { recursive: true });
73
+ mkdirSync(join(root, "secrets"), { recursive: true });
74
+ return root;
75
+ }
76
+ function defaultExportsDir() {
77
+ return join(getDataRoot(), "exports");
78
+ }
79
+ function exportsDir() {
80
+ const root = getExportsPathSetting() || defaultExportsDir();
81
+ mkdirSync(root, { recursive: true });
82
+ mkdirSync(join(root, "reports"), { recursive: true });
83
+ return root;
84
+ }
85
+ function reportsDir() {
86
+ const dir = join(exportsDir(), "reports");
87
+ mkdirSync(dir, { recursive: true });
88
+ return dir;
89
+ }
90
+ function accountsPath() {
91
+ return join(getDataRoot(), "accounts.json");
92
+ }
93
+ function settingsPath() {
94
+ return join(getDataRoot(), "settings.json");
95
+ }
96
+ function secretPath(name) {
97
+ return join(getDataRoot(), "secrets", `${name}.bin`);
98
+ }
99
+ function dbPath() {
100
+ return join(getDataRoot(), "data.json");
101
+ }
102
+ function holidayCacheDir() {
103
+ const dir = join(getDataRoot(), "holiday-cache");
104
+ mkdirSync(dir, { recursive: true });
105
+ return dir;
106
+ }
107
+ function ensureDataLayout() {
108
+ getDataRoot();
109
+ if (!existsSync(exportsDir())) mkdirSync(exportsDir(), { recursive: true });
110
+ }
111
+ // src/core/commitText.ts
112
+ function commitFullText(commit) {
113
+ const message = (commit.message || "").trim();
114
+ const title = (commit.title || "").trim();
115
+ if (message) return message;
116
+ return title;
117
+ }
118
+ function commitTitleLine(commit) {
119
+ const title = (commit.title || "").trim();
120
+ if (title) return title.split("\n").find((l) => l.trim())?.trim() || title;
121
+ const full = commitFullText(commit);
122
+ return full.split("\n").find((l) => l.trim())?.trim() || full;
123
+ }
124
+ // src/core/repoDisplay.ts
125
+ function shortRepoPath(pathWithNamespace, organizationId) {
126
+ const raw = (pathWithNamespace || "").trim();
127
+ if (!raw) return "";
128
+ const parts = raw.split("/").filter(Boolean);
129
+ if (parts.length <= 1) return raw;
130
+ if (organizationId && parts[0] === organizationId) return parts.slice(1).join("/");
131
+ if (/^[a-f0-9]{24}$/i.test(parts[0])) return parts.slice(1).join("/") || raw;
132
+ return raw;
133
+ }
134
+ // src/core/vault.ts
135
+ const MAGIC = Buffer.from("DCJ1");
136
+ function machineKey() {
137
+ const material = `${hostname()}|${homedir()}|dsh-commit-journal-v1`;
138
+ return scryptSync(material, "dsh-commit-journal-salt", 32);
139
+ }
140
+ function saveSecret(name, value) {
141
+ const key = machineKey();
142
+ const iv = randomBytes(12);
143
+ const cipher = createCipheriv("aes-256-gcm", key, iv);
144
+ const enc = Buffer.concat([cipher.update(value, "utf8"), cipher.final()]);
145
+ const tag = cipher.getAuthTag();
146
+ writeFileSync(secretPath(name), Buffer.concat([
147
+ MAGIC,
148
+ iv,
149
+ tag,
150
+ enc
151
+ ]));
152
+ }
153
+ function loadSecret(name) {
154
+ const path = secretPath(name);
155
+ if (!existsSync(path)) return null;
156
+ const raw = readFileSync(path);
157
+ try {
158
+ if (raw.length > 4 && raw.subarray(0, 4).equals(MAGIC)) {
159
+ const iv = raw.subarray(4, 16);
160
+ const tag = raw.subarray(16, 32);
161
+ const data = raw.subarray(32);
162
+ const decipher = createDecipheriv("aes-256-gcm", machineKey(), iv);
163
+ decipher.setAuthTag(tag);
164
+ return Buffer.concat([decipher.update(data), decipher.final()]).toString("utf8");
165
+ }
166
+ return raw.toString("utf8");
167
+ } catch {
168
+ return null;
169
+ }
170
+ }
171
+ function deleteSecret(name) {
172
+ const path = secretPath(name);
173
+ if (existsSync(path)) unlinkSync(path);
174
+ }
175
+ function saveToken(accountId, token) {
176
+ saveSecret(accountId, token);
177
+ }
178
+ function loadToken(accountId) {
179
+ return loadSecret(accountId);
180
+ }
181
+ function deleteToken(accountId) {
182
+ deleteSecret(accountId);
183
+ }
184
+ // src/core/db.ts
185
+ const empty = {
186
+ repos: [],
187
+ commits: [],
188
+ syncState: [],
189
+ syncLogs: []
190
+ };
191
+ function migrateCommit(raw) {
192
+ return {
193
+ ...raw,
194
+ repoId: String(raw.repoId)
195
+ };
196
+ }
197
+ function migrateRepo(raw) {
198
+ return {
199
+ accountId: String(raw.accountId),
200
+ id: String(raw.id),
201
+ name: String(raw.name || ""),
202
+ fullName: String(raw.fullName || raw.pathWithNamespace || raw.name || ""),
203
+ webUrl: String(raw.webUrl || ""),
204
+ lastActivityAt: raw.lastActivityAt,
205
+ defaultBranch: raw.defaultBranch,
206
+ accessLevel: raw.accessLevel,
207
+ visibility: raw.visibility,
208
+ starred: raw.starred,
209
+ participating: raw.participating
210
+ };
211
+ }
212
+ function migrateSyncState(raw) {
213
+ return {
214
+ accountId: String(raw.accountId),
215
+ repoId: String(raw.repoId),
216
+ lastSyncedAt: String(raw.lastSyncedAt || ""),
217
+ lookbackDays: raw.lookbackDays
218
+ };
219
+ }
220
+ function load() {
221
+ const path = dbPath();
222
+ if (!existsSync(path)) return structuredClone(empty);
223
+ try {
224
+ const raw = JSON.parse(readFileSync(path, "utf8"));
225
+ return {
226
+ repos: (raw.repos || []).map(migrateRepo),
227
+ commits: (raw.commits || []).map(migrateCommit),
228
+ syncState: (raw.syncState || []).map(migrateSyncState),
229
+ syncLogs: raw.syncLogs || []
230
+ };
231
+ } catch {
232
+ return structuredClone(empty);
233
+ }
234
+ }
235
+ function save(data) {
236
+ writeFileSync(dbPath(), JSON.stringify(data, null, 2), "utf8");
237
+ }
238
+ const ACTIVITY_MAX_YEARS = 8;
239
+ function mondayOf(d) {
240
+ return d.subtract((d.day() + 6) % 7, "day");
241
+ }
242
+ function resolveActivityRange(year) {
243
+ const today = dayjs().startOf("day");
244
+ if (year != null && Number.isFinite(year)) {
245
+ const start = dayjs(`${year}-01-01`).startOf("day");
246
+ const end = dayjs(`${year}-12-31`).endOf("day");
247
+ return {
248
+ from: start,
249
+ to: end.isAfter(today) ? today : end
250
+ };
251
+ }
252
+ return {
253
+ from: mondayOf(today).subtract(52, "week"),
254
+ to: today
255
+ };
256
+ }
257
+ const db = {
258
+ upsertRepos(accountId, repos) {
259
+ const data = load();
260
+ data.repos = [...data.repos.filter((r) => r.accountId !== accountId), ...repos.map((r) => ({
261
+ ...r,
262
+ accountId
263
+ }))];
264
+ save(data);
265
+ },
266
+ listRepos(accountId) {
267
+ return load().repos.filter((r) => r.accountId === accountId);
268
+ },
269
+ listReposWithCommits(accountId) {
270
+ const data = load();
271
+ const nameById = /* @__PURE__ */ new Map();
272
+ for (const c of data.commits) {
273
+ if (c.accountId !== accountId) continue;
274
+ if (!nameById.has(c.repoId)) nameById.set(c.repoId, c.repoName);
275
+ }
276
+ if (nameById.size === 0) return [];
277
+ const byId = new Map(data.repos.filter((r) => r.accountId === accountId).map((r) => [r.id, r]));
278
+ const list = [];
279
+ for (const [id, repoName] of nameById) {
280
+ const existing = byId.get(id);
281
+ if (existing) list.push(existing);
282
+ else list.push({
283
+ accountId,
284
+ id,
285
+ name: repoName,
286
+ fullName: repoName,
287
+ webUrl: ""
288
+ });
289
+ }
290
+ list.sort((a, b) => (a.fullName || a.name).localeCompare(b.fullName || b.name));
291
+ return list;
292
+ },
293
+ getSyncState(accountId, repoId) {
294
+ return load().syncState.find((s) => s.accountId === accountId && s.repoId === repoId);
295
+ },
296
+ setSyncState(state) {
297
+ const data = load();
298
+ const idx = data.syncState.findIndex((s) => s.accountId === state.accountId && s.repoId === state.repoId);
299
+ if (idx >= 0) data.syncState[idx] = state;
300
+ else data.syncState.push(state);
301
+ save(data);
302
+ },
303
+ insertCommits(commits) {
304
+ if (commits.length === 0) return 0;
305
+ const data = load();
306
+ const index = new Map(data.commits.map((c, i) => [`${c.accountId}:${c.sha}`, i]));
307
+ let inserted = 0;
308
+ let updated = 0;
309
+ for (const c of commits) {
310
+ const key = `${c.accountId}:${c.sha}`;
311
+ const idx = index.get(key);
312
+ if (idx == null) {
313
+ data.commits.push(c);
314
+ index.set(key, data.commits.length - 1);
315
+ inserted++;
316
+ continue;
317
+ }
318
+ const prev = data.commits[idx];
319
+ const nextMsg = (c.message || "").trim();
320
+ const prevMsg = (prev.message || "").trim();
321
+ if (nextMsg && nextMsg.length > prevMsg.length) {
322
+ data.commits[idx] = {
323
+ ...prev,
324
+ title: c.title || prev.title,
325
+ message: nextMsg,
326
+ webUrl: c.webUrl || prev.webUrl,
327
+ syncedAt: c.syncedAt || prev.syncedAt
328
+ };
329
+ updated++;
330
+ }
331
+ }
332
+ if (inserted > 0 || updated > 0) save(data);
333
+ return inserted;
334
+ },
335
+ queryCommits(opts) {
336
+ let items = load().commits.filter((c) => c.accountId === opts.accountId);
337
+ if (opts.repoId != null) items = items.filter((c) => c.repoId === opts.repoId);
338
+ if (opts.from) {
339
+ const from = opts.from;
340
+ items = items.filter((c) => c.committedAt >= from);
341
+ }
342
+ if (opts.to) {
343
+ const to = opts.to.endsWith("Z") || opts.to.includes("T") ? opts.to : `${opts.to}T23:59:59.999Z`;
344
+ items = items.filter((c) => c.committedAt <= to);
345
+ }
346
+ if (opts.keyword) {
347
+ const kw = opts.keyword.toLowerCase();
348
+ items = items.filter((c) => c.title.toLowerCase().includes(kw) || c.message.toLowerCase().includes(kw) || c.repoName.toLowerCase().includes(kw));
349
+ }
350
+ items.sort((a, b) => b.committedAt.localeCompare(a.committedAt));
351
+ const total = items.length;
352
+ const offset = opts.offset ?? 0;
353
+ const limit = opts.limit ?? 200;
354
+ return {
355
+ items: items.slice(offset, offset + limit),
356
+ total
357
+ };
358
+ },
359
+ getActivity(accountId, year) {
360
+ const data = load();
361
+ const { from, to } = resolveActivityRange(year);
362
+ const today = dayjs().startOf("day");
363
+ const yearSet = /* @__PURE__ */ new Set([today.year()]);
364
+ const byDay = /* @__PURE__ */ new Map();
365
+ for (const c of data.commits) {
366
+ if (c.accountId !== accountId) continue;
367
+ const at = dayjs(c.committedAt);
368
+ if (!at.isValid()) continue;
369
+ yearSet.add(at.year());
370
+ if (at.isBefore(from, "day") || at.isAfter(to, "day")) continue;
371
+ const key = at.format("YYYY-MM-DD");
372
+ byDay.set(key, (byDay.get(key) ?? 0) + 1);
373
+ }
374
+ const days = Array.from(byDay.entries()).map(([date, count]) => ({
375
+ date,
376
+ count
377
+ })).sort((a, b) => a.date.localeCompare(b.date));
378
+ let longestStreak = 0;
379
+ let streak = 0;
380
+ let maxDayCount = 0;
381
+ let maxDayDate = null;
382
+ for (let cur = from, guard = 0; !cur.isAfter(to, "day") && guard < 1e3; guard++) {
383
+ const count = byDay.get(cur.format("YYYY-MM-DD")) ?? 0;
384
+ if (count > 0) {
385
+ streak++;
386
+ if (streak > longestStreak) longestStreak = streak;
387
+ if (count > maxDayCount) {
388
+ maxDayCount = count;
389
+ maxDayDate = cur.format("YYYY-MM-DD");
390
+ }
391
+ } else streak = 0;
392
+ cur = cur.add(1, "day");
393
+ }
394
+ return {
395
+ years: Array.from(yearSet).sort((a, b) => b - a).slice(0, ACTIVITY_MAX_YEARS),
396
+ from: from.format("YYYY-MM-DD"),
397
+ to: to.format("YYYY-MM-DD"),
398
+ days,
399
+ stats: {
400
+ totalCommits: days.reduce((sum, d) => sum + d.count, 0),
401
+ activeDays: days.length,
402
+ longestStreak,
403
+ maxDayCount,
404
+ maxDayDate
405
+ }
406
+ };
407
+ },
408
+ listDayCommits(accountId, date) {
409
+ const target = dayjs(date);
410
+ if (!target.isValid()) return [];
411
+ const key = target.format("YYYY-MM-DD");
412
+ return load().commits.filter((c) => c.accountId === accountId && dayjs(c.committedAt).format("YYYY-MM-DD") === key).sort((a, b) => b.committedAt.localeCompare(a.committedAt));
413
+ },
414
+ addSyncLog(log) {
415
+ const data = load();
416
+ data.syncLogs.unshift(log);
417
+ data.syncLogs = data.syncLogs.slice(0, 500);
418
+ save(data);
419
+ },
420
+ listSyncLogs(accountId, limit = 20, offset = 0) {
421
+ const all = load().syncLogs.filter((l) => l.accountId === accountId);
422
+ return {
423
+ items: all.slice(offset, offset + limit),
424
+ total: all.length
425
+ };
426
+ },
427
+ clearSyncLogs(accountId) {
428
+ const data = load();
429
+ const before = data.syncLogs.length;
430
+ data.syncLogs = accountId ? data.syncLogs.filter((l) => l.accountId !== accountId) : [];
431
+ const deleted = before - data.syncLogs.length;
432
+ if (deleted > 0) save(data);
433
+ return deleted;
434
+ },
435
+ deleteAccountData(accountId) {
436
+ const data = load();
437
+ data.repos = data.repos.filter((r) => r.accountId !== accountId);
438
+ data.commits = data.commits.filter((c) => c.accountId !== accountId);
439
+ data.syncState = data.syncState.filter((s) => s.accountId !== accountId);
440
+ data.syncLogs = data.syncLogs.filter((l) => l.accountId !== accountId);
441
+ save(data);
442
+ },
443
+ clearCommits(accountId, repoId) {
444
+ const data = load();
445
+ const before = data.commits.length;
446
+ if (repoId != null) {
447
+ data.commits = data.commits.filter((c) => !(c.accountId === accountId && c.repoId === repoId));
448
+ data.syncState = data.syncState.filter((s) => !(s.accountId === accountId && s.repoId === repoId));
449
+ } else {
450
+ data.commits = data.commits.filter((c) => c.accountId !== accountId);
451
+ data.syncState = data.syncState.filter((s) => s.accountId !== accountId);
452
+ }
453
+ const deletedCommits = before - data.commits.length;
454
+ save(data);
455
+ return { deletedCommits };
456
+ }
457
+ };
458
+ // src/core/accounts.ts
459
+ function normalizeRepoIds(ids) {
460
+ return (ids ?? []).map((id) => String(id));
461
+ }
462
+ function normalizeBranches(map) {
463
+ if (!map) return {};
464
+ const out = {};
465
+ for (const [k, v] of Object.entries(map)) out[String(k)] = v;
466
+ return out;
467
+ }
468
+ function normalizeRoots(roots) {
469
+ const seen = /* @__PURE__ */ new Set();
470
+ const out = [];
471
+ for (const raw of roots || []) {
472
+ let trimmed = String(raw || "").trim().replace(/^["']+|["']+$/g, "").trim().replace(/[\\/]+$/, "");
473
+ if (!trimmed) continue;
474
+ let abs = trimmed;
475
+ try {
476
+ abs = resolve(trimmed);
477
+ } catch {
478
+ abs = trimmed;
479
+ }
480
+ const key = abs.toLowerCase();
481
+ if (seen.has(key)) continue;
482
+ seen.add(key);
483
+ out.push(abs);
484
+ }
485
+ return out;
486
+ }
487
+ function normalizeMode(raw) {
488
+ return raw === "local" ? "local" : "remote";
489
+ }
490
+ function migrateAccount(raw) {
491
+ const watched = Array.isArray(raw.watchedRepoIds) ? raw.watchedRepoIds.map((id) => String(id)) : [];
492
+ const mode = normalizeMode(raw.mode);
493
+ return {
494
+ id: String(raw.id),
495
+ name: String(raw.name || ""),
496
+ mode,
497
+ provider: mode === "local" ? "local" : raw.provider || "codeup",
498
+ edition: mode === "remote" ? raw.edition : void 0,
499
+ organizationId: mode === "remote" ? raw.organizationId : void 0,
500
+ apiBaseUrl: mode === "remote" ? raw.apiBaseUrl : void 0,
501
+ insecureSsl: mode === "remote" ? Boolean(raw.insecureSsl) : void 0,
502
+ localRoots: mode === "local" ? normalizeRoots(raw.localRoots) : void 0,
503
+ authorFilters: Array.isArray(raw.authorFilters) ? raw.authorFilters : [],
504
+ defaultBranch: raw.defaultBranch || "master",
505
+ watchedRepoIds: watched,
506
+ repoBranches: normalizeBranches(raw.repoBranches),
507
+ createdAt: raw.createdAt || (/* @__PURE__ */ new Date()).toISOString(),
508
+ updatedAt: raw.updatedAt || (/* @__PURE__ */ new Date()).toISOString()
509
+ };
510
+ }
511
+ function loadStore() {
512
+ const path = accountsPath();
513
+ if (!existsSync(path)) return {
514
+ accounts: [],
515
+ activeAccountId: null
516
+ };
517
+ try {
518
+ const raw = JSON.parse(readFileSync(path, "utf8"));
519
+ return {
520
+ accounts: (raw.accounts || []).map(migrateAccount),
521
+ activeAccountId: raw.activeAccountId ?? null
522
+ };
523
+ } catch {
524
+ return {
525
+ accounts: [],
526
+ activeAccountId: null
527
+ };
528
+ }
529
+ }
530
+ function saveStore(store) {
531
+ writeFileSync(accountsPath(), JSON.stringify(store, null, 2), "utf8");
532
+ }
533
+ function listAccounts() {
534
+ return loadStore().accounts;
535
+ }
536
+ function getActiveAccountId() {
537
+ return loadStore().activeAccountId;
538
+ }
539
+ function setActiveAccountId(id) {
540
+ const store = loadStore();
541
+ store.activeAccountId = id;
542
+ saveStore(store);
543
+ }
544
+ function getAccount(id) {
545
+ return loadStore().accounts.find((a) => a.id === id);
546
+ }
547
+ function buildAccountFields(input, prev) {
548
+ const mode = normalizeMode(input.mode ?? prev?.mode ?? "remote");
549
+ const provider = input.provider || prev?.provider || "codeup";
550
+ if (mode === "local") return {
551
+ name: (input.name ?? prev?.name ?? "").trim(),
552
+ mode: "local",
553
+ provider: "local",
554
+ localRoots: normalizeRoots(input.localRoots !== void 0 ? input.localRoots : prev?.localRoots),
555
+ insecureSsl: void 0,
556
+ authorFilters: (input.authorFilters !== void 0 ? input.authorFilters : prev?.authorFilters || []).map((s) => s.trim()).filter(Boolean),
557
+ defaultBranch: (input.defaultBranch ?? prev?.defaultBranch)?.trim() || "master",
558
+ watchedRepoIds: input.watchedRepoIds !== void 0 ? normalizeRepoIds(input.watchedRepoIds) : prev?.watchedRepoIds || [],
559
+ repoBranches: input.repoBranches !== void 0 ? normalizeBranches(input.repoBranches) : prev?.repoBranches || {}
560
+ };
561
+ return {
562
+ name: (input.name ?? prev?.name ?? "").trim(),
563
+ mode: "remote",
564
+ provider,
565
+ edition: provider === "codeup" ? input.edition ?? prev?.edition ?? "central" : void 0,
566
+ organizationId: input.organizationId !== void 0 ? input.organizationId.trim() || void 0 : prev?.organizationId,
567
+ apiBaseUrl: input.apiBaseUrl !== void 0 ? input.apiBaseUrl.trim().replace(/\/$/, "") || void 0 : prev?.apiBaseUrl,
568
+ insecureSsl: input.insecureSsl !== void 0 ? Boolean(input.insecureSsl) : Boolean(prev?.insecureSsl),
569
+ authorFilters: (input.authorFilters !== void 0 ? input.authorFilters : prev?.authorFilters || []).map((s) => s.trim()).filter(Boolean),
570
+ defaultBranch: (input.defaultBranch ?? prev?.defaultBranch)?.trim() || "master",
571
+ watchedRepoIds: input.watchedRepoIds !== void 0 ? normalizeRepoIds(input.watchedRepoIds) : prev?.watchedRepoIds || [],
572
+ repoBranches: input.repoBranches !== void 0 ? normalizeBranches(input.repoBranches) : prev?.repoBranches || {}
573
+ };
574
+ }
575
+ function createAccount(input) {
576
+ const now = (/* @__PURE__ */ new Date()).toISOString();
577
+ const fields = buildAccountFields(input);
578
+ const account = {
579
+ id: v4(),
580
+ ...fields,
581
+ createdAt: now,
582
+ updatedAt: now
583
+ };
584
+ validateAccount(account, input.token || "");
585
+ if (account.mode === "remote") saveToken(account.id, (input.token || "").trim());
586
+ const store = loadStore();
587
+ store.accounts.push(account);
588
+ if (!store.activeAccountId) store.activeAccountId = account.id;
589
+ saveStore(store);
590
+ return account;
591
+ }
592
+ function updateAccount(input) {
593
+ const store = loadStore();
594
+ const idx = store.accounts.findIndex((a) => a.id === input.id);
595
+ if (idx < 0) {
596
+ const mode = normalizeMode(input.mode);
597
+ if (mode === "remote" && !input.token?.trim()) throw new Error("账号不存在,请先 upsert_account 并填写 token");
598
+ if (mode === "local" && !(input.localRoots && input.localRoots.length)) throw new Error("账号不存在,请先 upsert_account 并填写 localRoots");
599
+ return createAccount({
600
+ name: input.name || "未命名账号",
601
+ mode,
602
+ provider: mode === "local" ? "local" : input.provider || "codeup",
603
+ edition: input.edition || "central",
604
+ organizationId: input.organizationId,
605
+ apiBaseUrl: input.apiBaseUrl,
606
+ insecureSsl: input.insecureSsl,
607
+ localRoots: input.localRoots,
608
+ token: input.token,
609
+ authorFilters: input.authorFilters || [],
610
+ defaultBranch: input.defaultBranch,
611
+ watchedRepoIds: input.watchedRepoIds,
612
+ repoBranches: input.repoBranches
613
+ });
614
+ }
615
+ const prev = store.accounts[idx];
616
+ const fields = buildAccountFields(input, prev);
617
+ const next = {
618
+ ...prev,
619
+ ...fields,
620
+ id: prev.id,
621
+ createdAt: prev.createdAt,
622
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString()
623
+ };
624
+ validateAccount(next, next.mode === "local" ? "" : input.token ?? loadToken(next.id) ?? "");
625
+ if (next.mode === "remote" && input.token?.trim()) saveToken(next.id, input.token.trim());
626
+ if (next.mode === "local") deleteToken(next.id);
627
+ store.accounts[idx] = next;
628
+ saveStore(store);
629
+ return next;
630
+ }
631
+ function deleteAccount(id) {
632
+ const store = loadStore();
633
+ store.accounts = store.accounts.filter((a) => a.id !== id);
634
+ if (store.activeAccountId === id) store.activeAccountId = store.accounts[0]?.id ?? null;
635
+ saveStore(store);
636
+ deleteToken(id);
637
+ db.deleteAccountData(id);
638
+ }
639
+ function getAccountToken(id) {
640
+ if (getAccount(id)?.mode === "local") return "";
641
+ const token = loadToken(id);
642
+ if (!token) throw new Error("未找到该账号的访问令牌,请重新填写 PAT");
643
+ return token;
644
+ }
645
+ function validateAccount(account, token) {
646
+ if (!account.name) throw new Error("请填写账号名称");
647
+ if (account.mode === "local") {
648
+ if (!account.localRoots || account.localRoots.length === 0) throw new Error("本地模式请至少填写一个扫描根目录");
649
+ const missing = account.localRoots.filter((p) => !existsSync(p));
650
+ if (missing.length === account.localRoots.length) throw new Error(`扫描根目录均不存在:${missing.join(", ")}`);
651
+ return;
652
+ }
653
+ if (!token.trim()) throw new Error("请填写个人访问令牌");
654
+ if (account.provider === "codeup") {
655
+ if (account.edition === "central" && !account.organizationId) throw new Error("中心版需填写 organizationId");
656
+ if (account.edition === "region" && !account.apiBaseUrl) throw new Error("Region 版需填写 API Base URL");
657
+ }
658
+ }
659
+ // src/providers/codeup/index.ts
660
+ function baseUrl(account) {
661
+ if (account.edition === "region") {
662
+ if (!account.apiBaseUrl) throw new Error("缺少 API Base URL");
663
+ return account.apiBaseUrl.replace(/\/$/, "");
664
+ }
665
+ return "https://openapi-rdc.aliyuncs.com";
666
+ }
667
+ function orgPrefix(account) {
668
+ if (account.edition === "central") {
669
+ if (!account.organizationId) throw new Error("缺少 organizationId");
670
+ return `/oapi/v1/codeup/organizations/${account.organizationId}`;
671
+ }
672
+ return "/oapi/v1/codeup";
673
+ }
674
+ async function request$2(account, token, path, query, options) {
675
+ const url = new URL(`${baseUrl(account)}${orgPrefix(account)}${path}`);
676
+ if (query) for (const [k, v] of Object.entries(query)) {
677
+ if (v === void 0 || v === "") continue;
678
+ url.searchParams.set(k, String(v));
679
+ }
680
+ const res = await fetch(url.toString(), {
681
+ method: "GET",
682
+ headers: {
683
+ "Content-Type": "application/json",
684
+ "x-yunxiao-token": token
685
+ }
686
+ });
687
+ if (!res.ok) {
688
+ const body = await res.text().catch(() => "");
689
+ if (options?.soft) throw new Error(`${res.status} ${body.includes("no permission") ? "Forbidden" : res.statusText}`);
690
+ if (res.status === 403 || body.includes("no permission")) throw new Error(`令牌无 API 权限(403)。请到云效「个人设置 → 个人访问令牌」删除后重建,代码管理里至少将「代码仓库」「提交」设为只读;并确认账号选的是中心版还是 Region 版。 原始信息: ${body || res.statusText}`);
691
+ throw new Error(`Codeup API ${res.status}: ${body || res.statusText}`);
692
+ }
693
+ return {
694
+ data: await res.json(),
695
+ headers: res.headers
696
+ };
697
+ }
698
+ function mapRepo$2(item, participating) {
699
+ return {
700
+ id: String(item.id),
701
+ name: String(item.name || ""),
702
+ fullName: String(item.pathWithNamespace || item.path_with_namespace || item.name || ""),
703
+ webUrl: String(item.webUrl || item.web_url || ""),
704
+ lastActivityAt: item.lastActivityAt || item.last_activity_at,
705
+ defaultBranch: item.defaultBranch || item.default_branch,
706
+ accessLevel: item.accessLevel != null ? Number(item.accessLevel) : item.access_level != null ? Number(item.access_level) : void 0,
707
+ visibility: item.visibility != null ? String(item.visibility) : item.visibility_level != null ? Number(item.visibility_level) === 0 ? "private" : "internal" : void 0,
708
+ starred: Boolean(item.starred || item.star),
709
+ participating
710
+ };
711
+ }
712
+ function isParticipatingRepoHeuristic(repo) {
713
+ if (repo.participating) return true;
714
+ if (repo.starred) return true;
715
+ if ((repo.accessLevel ?? 0) >= 20) return true;
716
+ if (repo.visibility === "private") return true;
717
+ return false;
718
+ }
719
+ async function listParticipatingIdsFromUserResources(account, token) {
720
+ const ids = /* @__PURE__ */ new Set();
721
+ let page = 1;
722
+ const perPage = 20;
723
+ while (true) {
724
+ const { data, headers } = await request$2(account, token, "/users/vision/user_resources", {
725
+ page,
726
+ per_page: perPage
727
+ }, { soft: true });
728
+ const rows = Array.isArray(data) ? data : [];
729
+ for (const row of rows) for (const item of row?.repository_infos || row?.repositoryInfos || []) {
730
+ const id = (item?.repository_info || item?.repositoryInfo || item)?.id ?? item?.source_id ?? item?.sourceId;
731
+ if (id != null) ids.add(String(id));
732
+ }
733
+ const totalPages = Number(headers.get("x-total-pages") || 1);
734
+ if (page >= totalPages || rows.length === 0) break;
735
+ page++;
736
+ if (page > 50) break;
737
+ }
738
+ return ids;
739
+ }
740
+ async function enrichParticipatingFlags(account, token, repos) {
741
+ const ids = /* @__PURE__ */ new Set();
742
+ try {
743
+ for (const id of await listParticipatingIdsFromUserResources(account, token)) ids.add(id);
744
+ } catch {}
745
+ if (ids.size > 0) for (const repo of repos) repo.participating = ids.has(repo.id);
746
+ if (repos.filter((r) => r.participating === true).length === 0) for (const repo of repos) repo.participating = isParticipatingRepoHeuristic(repo);
747
+ }
748
+ const MAX_COMMIT_PAGES$2 = 200;
749
+ const MAX_COMMIT_WINDOWS = 20;
750
+ const COMMIT_PER_PAGE$2 = 100;
751
+ function apiTime(ms) {
752
+ return new Date(ms).toISOString().replace(/\.\d{3}Z$/, "Z");
753
+ }
754
+ function asRows(data) {
755
+ if (Array.isArray(data)) return data;
756
+ if (Array.isArray(data?.result)) return data.result;
757
+ if (Array.isArray(data?.list)) return data.list;
758
+ return [];
759
+ }
760
+ /**
761
+ * 云效 Codeup VCS 适配器
762
+ */
763
+ const codeupProvider = {
764
+ id: "codeup",
765
+ async testConnection(account, token) {
766
+ const { data, headers } = await request$2(account, token, "/repositories", {
767
+ page: 1,
768
+ perPage: 1,
769
+ archived: false
770
+ });
771
+ return { repoCount: Number(headers.get("x-total") || data.length || 0) };
772
+ },
773
+ async listRepos(account, token) {
774
+ const all = [];
775
+ let page = 1;
776
+ const perPage = 100;
777
+ while (true) {
778
+ const { data, headers } = await request$2(account, token, "/repositories", {
779
+ page,
780
+ perPage,
781
+ archived: false,
782
+ orderBy: "last_activity_at",
783
+ sort: "desc"
784
+ });
785
+ for (const item of data || []) {
786
+ const mapped = mapRepo$2(item);
787
+ if ((mapped.accessLevel ?? 0) >= 20) mapped.participating = true;
788
+ all.push(mapped);
789
+ }
790
+ const totalPages = Number(headers.get("x-total-pages") || 1);
791
+ if (page >= totalPages || !data?.length) break;
792
+ page++;
793
+ }
794
+ await enrichParticipatingFlags(account, token, all);
795
+ return all;
796
+ },
797
+ async listBranches(account, token, repoId, search) {
798
+ const all = [];
799
+ let page = 1;
800
+ const perPage = 100;
801
+ while (true) {
802
+ const { data, headers } = await request$2(account, token, `/repositories/${repoId}/branches`, {
803
+ page,
804
+ perPage,
805
+ sort: "name_asc",
806
+ search: search || void 0
807
+ });
808
+ for (const item of data || []) {
809
+ const name = String(item.name || "");
810
+ if (!name) continue;
811
+ all.push({
812
+ name,
813
+ defaultBranch: Boolean(item.defaultBranch),
814
+ protected: Boolean(item.protected)
815
+ });
816
+ }
817
+ const totalPages = Number(headers.get("x-total-pages") || 1);
818
+ if (page >= totalPages || !data?.length) break;
819
+ page++;
820
+ if (page > 20) break;
821
+ }
822
+ return all;
823
+ },
824
+ async listCommitsSince(account, token, repoId, opts) {
825
+ const all = [];
826
+ const seen = /* @__PURE__ */ new Set();
827
+ const maxPages = Math.max(1, opts.maxPages ?? MAX_COMMIT_PAGES$2);
828
+ const since = opts.since;
829
+ const sinceMs = since ? Date.parse(since) : NaN;
830
+ let pages = 0;
831
+ let capped = false;
832
+ let until;
833
+ for (let window = 0; window < MAX_COMMIT_WINDOWS; window++) {
834
+ let page = 1;
835
+ let windowOldestMs = Infinity;
836
+ let hitBudget = false;
837
+ while (true) {
838
+ if (pages >= maxPages) {
839
+ capped = true;
840
+ hitBudget = true;
841
+ break;
842
+ }
843
+ const { data } = await request$2(account, token, `/repositories/${repoId}/commits`, {
844
+ refName: opts.ref,
845
+ since,
846
+ until,
847
+ page,
848
+ perPage: COMMIT_PER_PAGE$2
849
+ });
850
+ pages++;
851
+ const rows = asRows(data);
852
+ if (rows.length === 0) break;
853
+ let added = 0;
854
+ for (const item of rows) {
855
+ const id = String(item.id || item.sha || "");
856
+ if (!id || seen.has(id)) continue;
857
+ seen.add(id);
858
+ added++;
859
+ const message = String(item.message || item.commitMessage || "");
860
+ const title = String(item.title || message.split("\n").find((l) => l.trim()) || "");
861
+ const committedDate = String(item.committedDate || item.authoredDate || "");
862
+ const ms = Date.parse(committedDate);
863
+ if (Number.isFinite(ms) && ms < windowOldestMs) windowOldestMs = ms;
864
+ all.push({
865
+ sha: id,
866
+ shortId: String(item.shortId || id.slice(0, 8)),
867
+ title,
868
+ message: message || title,
869
+ authorName: String(item.authorName || ""),
870
+ authorEmail: String(item.authorEmail || ""),
871
+ authoredAt: String(item.authoredDate || committedDate || ""),
872
+ committedAt: committedDate,
873
+ webUrl: String(item.webUrl || "")
874
+ });
875
+ }
876
+ if (added === 0) {
877
+ capped = true;
878
+ hitBudget = true;
879
+ break;
880
+ }
881
+ page++;
882
+ }
883
+ if (hitBudget) break;
884
+ if (!Number.isFinite(sinceMs)) break;
885
+ if (!Number.isFinite(windowOldestMs)) break;
886
+ if (windowOldestMs <= sinceMs + 1e3) break;
887
+ until = apiTime(windowOldestMs - 1e3);
888
+ }
889
+ return {
890
+ commits: all,
891
+ capped,
892
+ pages
893
+ };
894
+ }
895
+ };
896
+ // src/providers/fetch.ts
897
+ const USER_AGENT = "dsh-commit-journal";
898
+ function shouldInsecureTls(account) {
899
+ if (account?.insecureSsl) return true;
900
+ const env = String(process.env.DSH_COMMIT_JOURNAL_TLS_INSECURE || "").trim();
901
+ return env === "1" || /^true$/i.test(env);
902
+ }
903
+ function formatFetchCause(err) {
904
+ const e = err;
905
+ const cause = e?.cause;
906
+ const code = cause?.code || e?.code;
907
+ const msg = cause?.message || e?.message || String(err);
908
+ if (code) return `${code}: ${msg}`;
909
+ return msg;
910
+ }
911
+ function isCertError(err) {
912
+ const detail = formatFetchCause(err);
913
+ const code = err?.cause?.code || err?.code || "";
914
+ return code === "UNABLE_TO_VERIFY_LEAF_SIGNATURE" || code === "CERT_HAS_EXPIRED" || code === "DEPTH_ZERO_SELF_SIGNED_CERT" || code === "SELF_SIGNED_CERT_IN_CHAIN" || /certificate|SSL|TLS|unable to verify/i.test(detail);
915
+ }
916
+ function wrapFetchError(url, err) {
917
+ const detail = formatFetchCause(err);
918
+ const code = err?.cause?.code || err?.code || "";
919
+ if (isCertError(err)) return /* @__PURE__ */ new Error(`连接失败(证书校验):${url}\n${detail}\n常见于公司代理 / HTTPS 解密 / 自签证书。可在账号中勾选「跳过 TLS 证书校验」,或设置环境变量 DSH_COMMIT_JOURNAL_TLS_INSECURE=1 后重启 DSH;更稳妥是把公司根证书路径设到 NODE_EXTRA_CA_CERTS。`);
920
+ if (code === "ENOTFOUND" || code === "EAI_AGAIN") return /* @__PURE__ */ new Error(`连接失败(DNS):${url}\n${detail}`);
921
+ if (code === "ECONNREFUSED" || code === "ETIMEDOUT" || code === "ECONNRESET") return /* @__PURE__ */ new Error(`连接失败(网络):${url}\n${detail}`);
922
+ return /* @__PURE__ */ new Error(`连接失败:${url}\n${detail}`);
923
+ }
924
+ function headersToObject(headers) {
925
+ const out = { "User-Agent": USER_AGENT };
926
+ if (!headers) return out;
927
+ if (headers instanceof Headers) {
928
+ headers.forEach((v, k) => {
929
+ out[k] = v;
930
+ });
931
+ return out;
932
+ }
933
+ if (Array.isArray(headers)) {
934
+ for (const [k, v] of headers) out[k] = v;
935
+ return out;
936
+ }
937
+ for (const [k, v] of Object.entries(headers)) {
938
+ if (v == null) continue;
939
+ out[k] = String(v);
940
+ }
941
+ return out;
942
+ }
943
+ function insecureRequest(urlStr, headers) {
944
+ return new Promise((resolve, reject) => {
945
+ const u = new URL(urlStr);
946
+ const req = (u.protocol === "http:" ? http : https).request(u, {
947
+ method: "GET",
948
+ headers,
949
+ rejectUnauthorized: false
950
+ }, (res) => {
951
+ const chunks = [];
952
+ res.on("data", (c) => chunks.push(c));
953
+ res.on("end", () => {
954
+ const headerInit = {};
955
+ for (const [k, v] of Object.entries(res.headers)) {
956
+ if (v == null) continue;
957
+ headerInit[k] = Array.isArray(v) ? v.join(", ") : v;
958
+ }
959
+ resolve(new Response(Buffer.concat(chunks), {
960
+ status: res.statusCode || 0,
961
+ statusText: res.statusMessage || "",
962
+ headers: headerInit
963
+ }));
964
+ });
965
+ });
966
+ req.on("error", reject);
967
+ req.end();
968
+ });
969
+ }
970
+ /**
971
+ * VCS HTTP GET:统一 User-Agent、证书错误提示;可选跳过 TLS 校验
972
+ * 公司代理导致证书失败时自动降级重试一次(无需先勾选 insecureSsl)
973
+ */
974
+ async function vcsFetch(url, init) {
975
+ const headers = headersToObject(init.headers);
976
+ if (shouldInsecureTls(init.account)) try {
977
+ return await insecureRequest(url, headers);
978
+ } catch (err) {
979
+ throw wrapFetchError(url, err);
980
+ }
981
+ try {
982
+ return await fetch(url, {
983
+ method: "GET",
984
+ headers
985
+ });
986
+ } catch (err) {
987
+ if (!isCertError(err)) throw wrapFetchError(url, err);
988
+ try {
989
+ return await insecureRequest(url, headers);
990
+ } catch (err2) {
991
+ throw wrapFetchError(url, err2);
992
+ }
993
+ }
994
+ }
995
+ // src/providers/github/index.ts
996
+ const MAX_COMMIT_PAGES$1 = 200;
997
+ const COMMIT_PER_PAGE$1 = 100;
998
+ function parseGithubComLogin(raw) {
999
+ const m = raw.trim().replace(/\/$/, "").match(/^(?:https?:\/\/)?(?:www\.)?github\.com\/([^/?#]+)/i);
1000
+ if (!m) return void 0;
1001
+ const login = decodeURIComponent(m[1]);
1002
+ if (!login || /^(settings|orgs|marketplace|explore|topics|about|login|signup)$/i.test(login)) return;
1003
+ return login;
1004
+ }
1005
+ function apiBase$1(account) {
1006
+ const raw = (account.apiBaseUrl || "").trim().replace(/\/$/, "");
1007
+ if (!raw) return "https://api.github.com";
1008
+ if (/^(https?:\/\/)?(www\.)?github\.com(\/|$)/i.test(raw)) return "https://api.github.com";
1009
+ if (/api\.github\.com$/i.test(raw)) return "https://api.github.com";
1010
+ if (/\/api\/v3$/i.test(raw)) return raw;
1011
+ return `${raw}/api/v3`;
1012
+ }
1013
+ function ownerLogin(account) {
1014
+ const raw = (account.organizationId || "").trim();
1015
+ if (!raw) return account.apiBaseUrl ? parseGithubComLogin(account.apiBaseUrl) : void 0;
1016
+ const fromUrl = parseGithubComLogin(raw);
1017
+ if (fromUrl) return fromUrl;
1018
+ return raw.replace(/^@/, "");
1019
+ }
1020
+ function parseLinkNext(linkHeader) {
1021
+ if (!linkHeader) return null;
1022
+ for (const part of linkHeader.split(",")) {
1023
+ const m = part.trim().match(/<([^>]+)>\s*;\s*rel="next"/i);
1024
+ if (m) return m[1];
1025
+ }
1026
+ return null;
1027
+ }
1028
+ async function request$1(account, token, pathOrUrl, query) {
1029
+ const url = pathOrUrl.startsWith("http") ? new URL(pathOrUrl) : new URL(`${apiBase$1(account)}${pathOrUrl}`);
1030
+ if (query) for (const [k, v] of Object.entries(query)) {
1031
+ if (v === void 0 || v === "") continue;
1032
+ url.searchParams.set(k, String(v));
1033
+ }
1034
+ const res = await vcsFetch(url.toString(), {
1035
+ account,
1036
+ headers: {
1037
+ Accept: "application/vnd.github+json",
1038
+ Authorization: `Bearer ${token}`,
1039
+ "X-GitHub-Api-Version": "2022-11-28"
1040
+ }
1041
+ });
1042
+ if (!res.ok) {
1043
+ const body = await res.text().catch(() => "");
1044
+ if (res.status === 401 || res.status === 403) throw new Error(`GitHub 令牌无效或权限不足(${res.status})。请确认 PAT 至少具备 repo(私有仓)或 public_repo 只读权限。 原始信息: ${body || res.statusText}`);
1045
+ throw new Error(`GitHub API ${res.status}: ${body || res.statusText}`);
1046
+ }
1047
+ return {
1048
+ data: await res.json(),
1049
+ headers: res.headers,
1050
+ status: res.status
1051
+ };
1052
+ }
1053
+ async function requestSoft(account, token, path, query) {
1054
+ try {
1055
+ const res = await request$1(account, token, path, query);
1056
+ return {
1057
+ data: res.data,
1058
+ status: res.status
1059
+ };
1060
+ } catch (e) {
1061
+ const msg = String(e?.message || e);
1062
+ if (/\b404\b/.test(msg)) return null;
1063
+ throw e;
1064
+ }
1065
+ }
1066
+ function mapRepo$1(item) {
1067
+ const fullName = String(item.full_name || `${item.owner?.login || ""}/${item.name || ""}`);
1068
+ return {
1069
+ id: fullName,
1070
+ name: String(item.name || ""),
1071
+ fullName,
1072
+ webUrl: String(item.html_url || ""),
1073
+ lastActivityAt: item.pushed_at || item.updated_at || void 0,
1074
+ defaultBranch: item.default_branch || void 0,
1075
+ visibility: item.private ? "private" : "public",
1076
+ starred: Boolean(item.starred),
1077
+ participating: true
1078
+ };
1079
+ }
1080
+ function mapCommit$1(item) {
1081
+ const sha = String(item.sha || "");
1082
+ const commit = item.commit || {};
1083
+ const message = String(commit.message || "");
1084
+ const title = message.split("\n").find((l) => l.trim()) || "";
1085
+ const author = commit.author || {};
1086
+ const committer = commit.committer || {};
1087
+ const authoredAt = String(author.date || committer.date || "");
1088
+ const committedAt = String(committer.date || author.date || "");
1089
+ return {
1090
+ sha,
1091
+ shortId: sha.slice(0, 8),
1092
+ title,
1093
+ message: message || title,
1094
+ authorName: String(author.name || item.author?.login || ""),
1095
+ authorEmail: String(author.email || ""),
1096
+ authoredAt,
1097
+ committedAt,
1098
+ webUrl: String(item.html_url || "")
1099
+ };
1100
+ }
1101
+ async function paginateRepos(account, token, firstPath, query) {
1102
+ const all = [];
1103
+ let nextUrl = null;
1104
+ let page = 1;
1105
+ while (true) {
1106
+ const { data, headers } = nextUrl ? await request$1(account, token, nextUrl) : await request$1(account, token, firstPath, {
1107
+ ...query,
1108
+ page,
1109
+ per_page: 100
1110
+ });
1111
+ const rows = Array.isArray(data) ? data : [];
1112
+ for (const item of rows) all.push(mapRepo$1(item));
1113
+ nextUrl = parseLinkNext(headers.get("link"));
1114
+ if (!nextUrl || rows.length === 0) break;
1115
+ page++;
1116
+ if (page > 100) break;
1117
+ }
1118
+ return all;
1119
+ }
1120
+ async function listReposForOwner(account, token, login) {
1121
+ if (await requestSoft(account, token, `/orgs/${encodeURIComponent(login)}`)) return paginateRepos(account, token, `/orgs/${encodeURIComponent(login)}/repos`, {
1122
+ type: "all",
1123
+ sort: "pushed",
1124
+ direction: "desc"
1125
+ });
1126
+ if (!await requestSoft(account, token, `/users/${encodeURIComponent(login)}`)) throw new Error(`GitHub 找不到组织或用户「${login}」。Organization 请填 org login 或个人 login(不要填完整主页 URL 以外的无效路径);也可留空列出令牌可见的全部仓库。`);
1127
+ return paginateRepos(account, token, `/users/${encodeURIComponent(login)}/repos`, {
1128
+ type: "all",
1129
+ sort: "pushed",
1130
+ direction: "desc"
1131
+ });
1132
+ }
1133
+ /**
1134
+ * GitHub / GitHub Enterprise VCS 适配器
1135
+ */
1136
+ const githubProvider = {
1137
+ id: "github",
1138
+ async testConnection(account, token) {
1139
+ const login = ownerLogin(account);
1140
+ if (login) {
1141
+ if (await requestSoft(account, token, `/orgs/${encodeURIComponent(login)}`)) {
1142
+ const { data } = await request$1(account, token, `/orgs/${encodeURIComponent(login)}/repos`, {
1143
+ per_page: 1,
1144
+ type: "all"
1145
+ });
1146
+ return { repoCount: Array.isArray(data) ? data.length : 0 };
1147
+ }
1148
+ if (!await requestSoft(account, token, `/users/${encodeURIComponent(login)}`)) throw new Error(`GitHub 找不到组织或用户「${login}」`);
1149
+ const { data } = await request$1(account, token, `/users/${encodeURIComponent(login)}/repos`, {
1150
+ per_page: 1,
1151
+ type: "all"
1152
+ });
1153
+ return { repoCount: Array.isArray(data) ? data.length : 0 };
1154
+ }
1155
+ const { data } = await request$1(account, token, "/user/repos", {
1156
+ per_page: 1,
1157
+ affiliation: "owner,collaborator,organization_member"
1158
+ });
1159
+ return { repoCount: Array.isArray(data) ? data.length : 0 };
1160
+ },
1161
+ async listRepos(account, token) {
1162
+ const login = ownerLogin(account);
1163
+ if (login) return listReposForOwner(account, token, login);
1164
+ return paginateRepos(account, token, "/user/repos", {
1165
+ affiliation: "owner,collaborator,organization_member",
1166
+ sort: "pushed",
1167
+ direction: "desc"
1168
+ });
1169
+ },
1170
+ async listBranches(account, token, repoId, search) {
1171
+ const all = [];
1172
+ let nextUrl = null;
1173
+ let page = 1;
1174
+ const path = `/repos/${repoId}/branches`;
1175
+ while (true) {
1176
+ const { data, headers } = nextUrl ? await request$1(account, token, nextUrl) : await request$1(account, token, path, {
1177
+ page,
1178
+ per_page: 100
1179
+ });
1180
+ const rows = Array.isArray(data) ? data : [];
1181
+ for (const item of rows) {
1182
+ const name = String(item.name || "");
1183
+ if (!name) continue;
1184
+ if (search && !name.toLowerCase().includes(search.toLowerCase())) continue;
1185
+ all.push({
1186
+ name,
1187
+ protected: Boolean(item.protected)
1188
+ });
1189
+ }
1190
+ nextUrl = parseLinkNext(headers.get("link"));
1191
+ if (!nextUrl || rows.length === 0) break;
1192
+ page++;
1193
+ if (page > 20) break;
1194
+ }
1195
+ return all;
1196
+ },
1197
+ async listCommitsSince(account, token, repoId, opts) {
1198
+ const all = [];
1199
+ const seen = /* @__PURE__ */ new Set();
1200
+ const maxPages = Math.max(1, opts.maxPages ?? MAX_COMMIT_PAGES$1);
1201
+ let pages = 0;
1202
+ let capped = false;
1203
+ let nextUrl = null;
1204
+ let page = 1;
1205
+ const path = `/repos/${repoId}/commits`;
1206
+ while (true) {
1207
+ if (pages >= maxPages) {
1208
+ capped = true;
1209
+ break;
1210
+ }
1211
+ const { data, headers } = nextUrl ? await request$1(account, token, nextUrl) : await request$1(account, token, path, {
1212
+ sha: opts.ref,
1213
+ since: opts.since,
1214
+ page,
1215
+ per_page: COMMIT_PER_PAGE$1
1216
+ });
1217
+ pages++;
1218
+ const rows = Array.isArray(data) ? data : [];
1219
+ if (rows.length === 0) break;
1220
+ for (const item of rows) {
1221
+ const mapped = mapCommit$1(item);
1222
+ if (!mapped.sha || seen.has(mapped.sha)) continue;
1223
+ seen.add(mapped.sha);
1224
+ all.push(mapped);
1225
+ }
1226
+ nextUrl = parseLinkNext(headers.get("link"));
1227
+ if (!nextUrl) break;
1228
+ }
1229
+ return {
1230
+ commits: all,
1231
+ capped,
1232
+ pages
1233
+ };
1234
+ }
1235
+ };
1236
+ // src/providers/gitlab/index.ts
1237
+ const MAX_COMMIT_PAGES = 200;
1238
+ const COMMIT_PER_PAGE = 100;
1239
+ function apiBase(account) {
1240
+ let base = (account.apiBaseUrl || "https://gitlab.com").replace(/\/$/, "");
1241
+ if (!/\/api\/v4$/i.test(base)) base = `${base}/api/v4`;
1242
+ return base;
1243
+ }
1244
+ async function request(account, token, path, query) {
1245
+ const url = new URL(`${apiBase(account)}${path}`);
1246
+ if (query) for (const [k, v] of Object.entries(query)) {
1247
+ if (v === void 0 || v === "") continue;
1248
+ url.searchParams.set(k, String(v));
1249
+ }
1250
+ const res = await vcsFetch(url.toString(), {
1251
+ account,
1252
+ headers: {
1253
+ "Content-Type": "application/json",
1254
+ "PRIVATE-TOKEN": token
1255
+ }
1256
+ });
1257
+ if (!res.ok) {
1258
+ const body = await res.text().catch(() => "");
1259
+ if (res.status === 401 || res.status === 403) throw new Error(`GitLab 令牌无效或权限不足(${res.status})。请确认 PAT 至少具备 read_api / read_repository。 原始信息: ${body || res.statusText}`);
1260
+ throw new Error(`GitLab API ${res.status}: ${body || res.statusText}`);
1261
+ }
1262
+ return {
1263
+ data: await res.json(),
1264
+ headers: res.headers
1265
+ };
1266
+ }
1267
+ function mapRepo(item) {
1268
+ return {
1269
+ id: String(item.id),
1270
+ name: String(item.name || ""),
1271
+ fullName: String(item.path_with_namespace || item.name || ""),
1272
+ webUrl: String(item.web_url || ""),
1273
+ lastActivityAt: item.last_activity_at || void 0,
1274
+ defaultBranch: item.default_branch || void 0,
1275
+ visibility: item.visibility != null ? String(item.visibility) : void 0,
1276
+ starred: Boolean(item.starred),
1277
+ participating: true
1278
+ };
1279
+ }
1280
+ function mapCommit(item) {
1281
+ const id = String(item.id || item.sha || "");
1282
+ const message = String(item.message || "");
1283
+ const title = String(item.title || message.split("\n").find((l) => l.trim()) || "");
1284
+ const committedAt = String(item.committed_date || item.authored_date || "");
1285
+ return {
1286
+ sha: id,
1287
+ shortId: String(item.short_id || id.slice(0, 8)),
1288
+ title,
1289
+ message: message || title,
1290
+ authorName: String(item.author_name || ""),
1291
+ authorEmail: String(item.author_email || ""),
1292
+ authoredAt: String(item.authored_date || committedAt || ""),
1293
+ committedAt,
1294
+ webUrl: String(item.web_url || "")
1295
+ };
1296
+ }
1297
+ function projectsPath(account) {
1298
+ const group = account.organizationId?.trim();
1299
+ if (group) return `/groups/${encodeURIComponent(group)}/projects`;
1300
+ return "/projects";
1301
+ }
1302
+ function projectsQuery(account, page, perPage) {
1303
+ const group = account.organizationId?.trim();
1304
+ const base = {
1305
+ page,
1306
+ per_page: perPage,
1307
+ order_by: "last_activity_at",
1308
+ sort: "desc",
1309
+ archived: false
1310
+ };
1311
+ if (!group) base.membership = true;
1312
+ return base;
1313
+ }
1314
+ /**
1315
+ * GitLab(含自建)VCS 适配器
1316
+ */
1317
+ const gitlabProvider = {
1318
+ id: "gitlab",
1319
+ async testConnection(account, token) {
1320
+ const { data, headers } = await request(account, token, projectsPath(account), projectsQuery(account, 1, 1));
1321
+ return { repoCount: Number(headers.get("x-total") || (Array.isArray(data) ? data.length : 0)) };
1322
+ },
1323
+ async listRepos(account, token) {
1324
+ const all = [];
1325
+ let page = 1;
1326
+ const perPage = 100;
1327
+ while (true) {
1328
+ const { data, headers } = await request(account, token, projectsPath(account), projectsQuery(account, page, perPage));
1329
+ const rows = Array.isArray(data) ? data : [];
1330
+ for (const item of rows) all.push(mapRepo(item));
1331
+ const totalPages = Number(headers.get("x-total-pages") || 1);
1332
+ if (page >= totalPages || rows.length === 0) break;
1333
+ page++;
1334
+ if (page > 100) break;
1335
+ }
1336
+ return all;
1337
+ },
1338
+ async listBranches(account, token, repoId, search) {
1339
+ const all = [];
1340
+ let page = 1;
1341
+ const perPage = 100;
1342
+ while (true) {
1343
+ const { data, headers } = await request(account, token, `/projects/${encodeURIComponent(repoId)}/repository/branches`, {
1344
+ page,
1345
+ per_page: perPage,
1346
+ search: search || void 0
1347
+ });
1348
+ const rows = Array.isArray(data) ? data : [];
1349
+ for (const item of rows) {
1350
+ const name = String(item.name || "");
1351
+ if (!name) continue;
1352
+ all.push({
1353
+ name,
1354
+ defaultBranch: Boolean(item.default),
1355
+ protected: Boolean(item.protected)
1356
+ });
1357
+ }
1358
+ const totalPages = Number(headers.get("x-total-pages") || 1);
1359
+ if (page >= totalPages || rows.length === 0) break;
1360
+ page++;
1361
+ if (page > 20) break;
1362
+ }
1363
+ return all;
1364
+ },
1365
+ async listCommitsSince(account, token, repoId, opts) {
1366
+ const all = [];
1367
+ const seen = /* @__PURE__ */ new Set();
1368
+ const maxPages = Math.max(1, opts.maxPages ?? MAX_COMMIT_PAGES);
1369
+ let pages = 0;
1370
+ let capped = false;
1371
+ let page = 1;
1372
+ while (true) {
1373
+ if (pages >= maxPages) {
1374
+ capped = true;
1375
+ break;
1376
+ }
1377
+ const { data, headers } = await request(account, token, `/projects/${encodeURIComponent(repoId)}/repository/commits`, {
1378
+ ref_name: opts.ref,
1379
+ since: opts.since,
1380
+ page,
1381
+ per_page: COMMIT_PER_PAGE
1382
+ });
1383
+ pages++;
1384
+ const rows = Array.isArray(data) ? data : [];
1385
+ if (rows.length === 0) break;
1386
+ for (const item of rows) {
1387
+ const mapped = mapCommit(item);
1388
+ if (!mapped.sha || seen.has(mapped.sha)) continue;
1389
+ seen.add(mapped.sha);
1390
+ all.push(mapped);
1391
+ }
1392
+ const nextPage = headers.get("x-next-page");
1393
+ if (!nextPage) break;
1394
+ page = Number(nextPage);
1395
+ if (!Number.isFinite(page) || page <= 0) break;
1396
+ }
1397
+ return {
1398
+ commits: all,
1399
+ capped,
1400
+ pages
1401
+ };
1402
+ }
1403
+ };
1404
+ // src/providers/local/index.ts
1405
+ const execFileAsync = promisify(execFile);
1406
+ const MAX_DEPTH = 5;
1407
+ const SKIP_DIRS = /* @__PURE__ */ new Set([
1408
+ "node_modules",
1409
+ ".git",
1410
+ "dist",
1411
+ "build",
1412
+ ".next",
1413
+ "target",
1414
+ ".turbo",
1415
+ "coverage",
1416
+ ".cache"
1417
+ ]);
1418
+ let cachedGitBin;
1419
+ const WIN_GIT_CANDIDATES = [
1420
+ "C:\\Program Files\\Git\\cmd\\git.exe",
1421
+ "C:\\Program Files\\Git\\bin\\git.exe",
1422
+ "C:\\Program Files (x86)\\Git\\cmd\\git.exe",
1423
+ "C:\\Program Files (x86)\\Git\\bin\\git.exe"
1424
+ ];
1425
+ const pathByRepoId = /* @__PURE__ */ new Map();
1426
+ function normalizePath(p) {
1427
+ return resolve(p).replace(/[\\/]+$/, "");
1428
+ }
1429
+ function resolveGitBin() {
1430
+ if (cachedGitBin !== void 0) {
1431
+ if (!cachedGitBin) throw new Error("未找到 git 可执行文件。请安装 Git for Windows,或把 git 加入系统 PATH 后重启 DSH。");
1432
+ return cachedGitBin;
1433
+ }
1434
+ const fromEnv = process.env.DSH_COMMIT_JOURNAL_GIT?.trim();
1435
+ if (fromEnv && existsSync(fromEnv)) {
1436
+ cachedGitBin = fromEnv;
1437
+ return cachedGitBin;
1438
+ }
1439
+ const pathDirs = (process.env.PATH || process.env.Path || "").split(delimiter).filter(Boolean);
1440
+ for (const dir of pathDirs) {
1441
+ const unix = join(dir, "git");
1442
+ const win = join(dir, "git.exe");
1443
+ if (process.platform === "win32" && existsSync(win)) {
1444
+ cachedGitBin = win;
1445
+ return cachedGitBin;
1446
+ }
1447
+ if (existsSync(unix)) {
1448
+ cachedGitBin = unix;
1449
+ return cachedGitBin;
1450
+ }
1451
+ }
1452
+ if (process.platform === "win32") {
1453
+ for (const cand of WIN_GIT_CANDIDATES) if (existsSync(cand)) {
1454
+ cachedGitBin = cand;
1455
+ return cachedGitBin;
1456
+ }
1457
+ }
1458
+ cachedGitBin = null;
1459
+ throw new Error("未找到 git 可执行文件。请安装 Git for Windows,或把 git 加入系统 PATH 后重启 DSH。");
1460
+ }
1461
+ function repoIdForPath(absPath) {
1462
+ return `local:${createHash("sha1").update(normalizePath(absPath).toLowerCase()).digest("hex").slice(0, 16)}`;
1463
+ }
1464
+ function isGitDir(gitPath) {
1465
+ try {
1466
+ const st = lstatSync(gitPath);
1467
+ if (st.isDirectory()) return existsSync(join(gitPath, "HEAD")) || existsSync(join(gitPath, "refs"));
1468
+ if (st.isFile()) {
1469
+ const text = readFileSync(gitPath, "utf8");
1470
+ return /^gitdir:\s+/i.test(text.trim());
1471
+ }
1472
+ } catch {
1473
+ return false;
1474
+ }
1475
+ return false;
1476
+ }
1477
+ function safeRealPath(p) {
1478
+ try {
1479
+ return realpathSync(p);
1480
+ } catch {
1481
+ return normalizePath(p);
1482
+ }
1483
+ }
1484
+ function walkRepos(dir, root, depth, out) {
1485
+ if (depth > MAX_DEPTH) return;
1486
+ let entries;
1487
+ try {
1488
+ entries = readdirSync(dir);
1489
+ } catch {
1490
+ return;
1491
+ }
1492
+ if (entries.includes(".git") && isGitDir(join(dir, ".git"))) {
1493
+ const abs = safeRealPath(dir);
1494
+ const id = repoIdForPath(abs);
1495
+ if (!out.has(id)) out.set(id, abs);
1496
+ return;
1497
+ }
1498
+ for (const name of entries) {
1499
+ if (SKIP_DIRS.has(name)) continue;
1500
+ if (name.startsWith(".") && name !== ".git") continue;
1501
+ const child = join(dir, name);
1502
+ let st;
1503
+ try {
1504
+ st = lstatSync(child);
1505
+ } catch {
1506
+ continue;
1507
+ }
1508
+ if (!st.isDirectory() || st.isSymbolicLink()) continue;
1509
+ walkRepos(child, root, depth + 1, out);
1510
+ }
1511
+ }
1512
+ function discoverRepos(account) {
1513
+ const found = /* @__PURE__ */ new Map();
1514
+ const roots = account.localRoots || [];
1515
+ for (const root of roots) {
1516
+ if (!existsSync(root)) continue;
1517
+ let st;
1518
+ try {
1519
+ st = statSync(root);
1520
+ } catch {
1521
+ continue;
1522
+ }
1523
+ if (!st.isDirectory()) continue;
1524
+ const absRoot = safeRealPath(root);
1525
+ walkRepos(absRoot, absRoot, 0, found);
1526
+ }
1527
+ const repos = [];
1528
+ pathByRepoId.clear();
1529
+ for (const [id, abs] of found) {
1530
+ pathByRepoId.set(id, abs);
1531
+ const name = basename(abs);
1532
+ let fullName = abs;
1533
+ for (const root of roots) {
1534
+ if (!existsSync(root)) continue;
1535
+ const absRoot = safeRealPath(root);
1536
+ const rel = relative(absRoot, abs);
1537
+ if (rel && !rel.startsWith("..") && !rel.includes(`..${sep}`)) {
1538
+ fullName = join(basename(absRoot), rel).split(sep).join("/");
1539
+ break;
1540
+ }
1541
+ if (normalizePath(absRoot).toLowerCase() === normalizePath(abs).toLowerCase()) {
1542
+ fullName = basename(abs);
1543
+ break;
1544
+ }
1545
+ }
1546
+ repos.push({
1547
+ id,
1548
+ name,
1549
+ fullName,
1550
+ webUrl: "",
1551
+ defaultBranch: void 0
1552
+ });
1553
+ }
1554
+ repos.sort((a, b) => a.fullName.localeCompare(b.fullName));
1555
+ return repos;
1556
+ }
1557
+ function resolveWorkTree(account, repoId) {
1558
+ const cached = pathByRepoId.get(repoId);
1559
+ if (cached && existsSync(cached)) return cached;
1560
+ discoverRepos(account);
1561
+ const again = pathByRepoId.get(repoId);
1562
+ if (!again || !existsSync(again)) throw new Error(`未找到本地仓库 ${repoId},请先刷新仓库列表`);
1563
+ return again;
1564
+ }
1565
+ async function git(cwd, args) {
1566
+ const bin = resolveGitBin();
1567
+ try {
1568
+ const { stdout } = await execFileAsync(bin, [
1569
+ "-C",
1570
+ cwd,
1571
+ ...args
1572
+ ], {
1573
+ encoding: "utf8",
1574
+ maxBuffer: 20971520,
1575
+ windowsHide: true
1576
+ });
1577
+ return stdout;
1578
+ } catch (e) {
1579
+ if (e?.code === "ENOENT") {
1580
+ cachedGitBin = void 0;
1581
+ throw new Error(`无法启动 git(${bin})。请确认已安装 Git,或设置环境变量 DSH_COMMIT_JOURNAL_GIT 指向 git.exe。`);
1582
+ }
1583
+ const msg = e?.stderr || e?.message || String(e);
1584
+ throw new Error(`git ${args.join(" ")} 失败: ${String(msg).trim()}`);
1585
+ }
1586
+ }
1587
+ async function defaultBranchName(cwd) {
1588
+ try {
1589
+ const m = (await git(cwd, ["symbolic-ref", "refs/remotes/origin/HEAD"])).trim().match(/refs\/remotes\/origin\/(.+)$/);
1590
+ if (m?.[1]) return m[1];
1591
+ } catch {}
1592
+ try {
1593
+ const cur = (await git(cwd, [
1594
+ "rev-parse",
1595
+ "--abbrev-ref",
1596
+ "HEAD"
1597
+ ])).trim();
1598
+ if (cur && cur !== "HEAD") return cur;
1599
+ } catch {}
1600
+ }
1601
+ /**
1602
+ * 本机 git 扫描适配器:按账号 localRoots 发现仓库并拉取提交
1603
+ */
1604
+ const localGitProvider = {
1605
+ id: "local",
1606
+ async testConnection(account) {
1607
+ resolveGitBin();
1608
+ return { repoCount: discoverRepos(account).length };
1609
+ },
1610
+ async listRepos(account) {
1611
+ const repos = discoverRepos(account);
1612
+ for (const r of repos) {
1613
+ const cwd = pathByRepoId.get(r.id);
1614
+ if (!cwd) continue;
1615
+ try {
1616
+ r.defaultBranch = await defaultBranchName(cwd);
1617
+ } catch {}
1618
+ }
1619
+ return repos;
1620
+ },
1621
+ async listBranches(account, _token, repoId) {
1622
+ const cwd = resolveWorkTree(account, repoId);
1623
+ const def = await defaultBranchName(cwd);
1624
+ const names = (await git(cwd, [
1625
+ "for-each-ref",
1626
+ "--format=%(refname:short)",
1627
+ "refs/heads"
1628
+ ])).split(/\r?\n/).map((s) => s.trim()).filter(Boolean);
1629
+ const unique = Array.from(new Set(names));
1630
+ if (def && !unique.includes(def)) unique.unshift(def);
1631
+ return unique.map((name) => ({
1632
+ name,
1633
+ defaultBranch: name === def
1634
+ }));
1635
+ },
1636
+ async listCommitsSince(account, _token, repoId, opts) {
1637
+ const cwd = resolveWorkTree(account, repoId);
1638
+ const args = [
1639
+ "log",
1640
+ opts.ref || "HEAD",
1641
+ "--no-merges",
1642
+ "--date=iso-strict",
1643
+ "--format=%H%x1f%h%x1f%s%x1f%b%x1f%an%x1f%ae%x1f%aI%x1f%cI%x1e"
1644
+ ];
1645
+ if (opts.since) args.push(`--since=${opts.since}`);
1646
+ const max = Math.max(1, (opts.maxPages ?? 20) * 100);
1647
+ args.push(`-n${max}`);
1648
+ let raw = "";
1649
+ try {
1650
+ raw = await git(cwd, args);
1651
+ } catch (e) {
1652
+ const msg = String(e?.message || e);
1653
+ if (/unknown revision|bad revision|ambiguous argument/i.test(msg)) return {
1654
+ commits: [],
1655
+ capped: false,
1656
+ pages: 0
1657
+ };
1658
+ throw e;
1659
+ }
1660
+ const commits = [];
1661
+ const records = raw.split("").map((s) => s.trim()).filter(Boolean);
1662
+ for (const rec of records) {
1663
+ const parts = rec.split("");
1664
+ if (parts.length < 8) continue;
1665
+ const [sha, shortId, title, messageBody, authorName, authorEmail, authoredAt, committedAt] = parts;
1666
+ const message = [title, messageBody].filter(Boolean).join("\n").trim();
1667
+ commits.push({
1668
+ sha,
1669
+ shortId: shortId || sha.slice(0, 7),
1670
+ title: title || sha.slice(0, 7),
1671
+ message: message || title || "",
1672
+ authorName: authorName || "",
1673
+ authorEmail: authorEmail || "",
1674
+ authoredAt: authoredAt || committedAt || (/* @__PURE__ */ new Date()).toISOString(),
1675
+ committedAt: committedAt || authoredAt || (/* @__PURE__ */ new Date()).toISOString(),
1676
+ webUrl: ""
1677
+ });
1678
+ }
1679
+ return {
1680
+ commits,
1681
+ capped: commits.length >= max,
1682
+ pages: Math.ceil(commits.length / 100) || (commits.length ? 1 : 0)
1683
+ };
1684
+ }
1685
+ };
1686
+ // src/providers/index.ts
1687
+ const providers = {
1688
+ codeup: codeupProvider,
1689
+ local: localGitProvider,
1690
+ gitlab: gitlabProvider,
1691
+ github: githubProvider
1692
+ };
1693
+ function getProvider(providerId) {
1694
+ if (typeof providerId !== "string" && providerId.mode === "local") return localGitProvider;
1695
+ const id = typeof providerId === "string" ? providerId : providerId.provider;
1696
+ const provider = providers[id];
1697
+ if (!provider) throw new Error(`未知 VCS provider「${id}」。支持 codeup / gitlab / github / local。`);
1698
+ return provider;
1699
+ }
1700
+ // src/core/sync.ts
1701
+ const timers = /* @__PURE__ */ new Map();
1702
+ const syncing = /* @__PURE__ */ new Set();
1703
+ const DAY_MS = 864e5;
1704
+ const INCREMENTAL_OVERLAP_MS = 2 * DAY_MS;
1705
+ function toApiTime(iso) {
1706
+ const t = Date.parse(iso);
1707
+ return (Number.isFinite(t) ? new Date(t) : new Date(iso)).toISOString().replace(/\.\d{3}Z$/, "Z");
1708
+ }
1709
+ function matchAuthor(account, name, email) {
1710
+ if (!account.authorFilters.length) return true;
1711
+ const hay = `${name} ${email}`.toLowerCase();
1712
+ return account.authorFilters.some((f) => hay.includes(f.toLowerCase()));
1713
+ }
1714
+ function writeDailyExports(accountId, commits) {
1715
+ if (!commits.length) return;
1716
+ const root = exportsDir();
1717
+ const byDay = /* @__PURE__ */ new Map();
1718
+ for (const c of commits) {
1719
+ const day = c.committedAt.slice(0, 10);
1720
+ if (!byDay.has(day)) byDay.set(day, []);
1721
+ byDay.get(day).push(c);
1722
+ }
1723
+ for (const [day, list] of byDay) {
1724
+ const dir = join(root, accountId);
1725
+ if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
1726
+ const path = join(dir, `${day}.md`);
1727
+ const existing = existsSync(path) ? readFileSync(path, "utf8") : `# ${day} 提交材料\n\n`;
1728
+ const lines = [];
1729
+ for (const c of list) {
1730
+ if (existing.includes(c.sha)) continue;
1731
+ const [first, ...rest] = commitFullText(c).split("\n");
1732
+ lines.push(`- **[${c.repoName}]** ${first}`);
1733
+ for (const line of rest) lines.push(` ${line}`);
1734
+ lines.push(` - 时间: ${c.committedAt}`);
1735
+ lines.push(` - 作者: ${c.authorName} <${c.authorEmail}>`);
1736
+ lines.push(` - SHA: \`${c.shortId}\` (${c.sha})`);
1737
+ if (c.webUrl) lines.push(` - 链接: ${c.webUrl}`);
1738
+ lines.push("");
1739
+ }
1740
+ if (lines.length) writeFileSync(path, existing + lines.join("\n"), "utf8");
1741
+ }
1742
+ }
1743
+ async function syncAccount(accountId, repoIds) {
1744
+ if (syncing.has(accountId)) return {
1745
+ accountId,
1746
+ fetched: 0,
1747
+ inserted: 0,
1748
+ errors: ["同步进行中,请稍后再试"]
1749
+ };
1750
+ syncing.add(accountId);
1751
+ const errors = [];
1752
+ let fetched = 0;
1753
+ let inserted = 0;
1754
+ let matched = 0;
1755
+ let truncated = 0;
1756
+ try {
1757
+ const account = getAccount(accountId);
1758
+ if (!account) throw new Error("账号不存在");
1759
+ const token = account.mode === "local" ? "" : getAccountToken(accountId);
1760
+ const provider = getProvider(account);
1761
+ const isLocal = account.mode === "local";
1762
+ const onlyIds = repoIds && repoIds.length > 0 ? Array.from(new Set(repoIds.map(String))) : null;
1763
+ db.addSyncLog({
1764
+ id: v4(),
1765
+ accountId,
1766
+ at: (/* @__PURE__ */ new Date()).toISOString(),
1767
+ level: "info",
1768
+ message: onlyIds ? `${isLocal ? "开始扫描指定仓库" : "开始同步指定仓库"}(${onlyIds.length} 个)` : isLocal ? "开始扫描关注的本地仓库" : "开始同步全部关注仓库"
1769
+ });
1770
+ let repos = db.listRepos(accountId);
1771
+ if (!onlyIds || onlyIds.some((id) => !repos.find((r) => r.id === id))) {
1772
+ const latest = await provider.listRepos(account, token);
1773
+ db.upsertRepos(accountId, latest);
1774
+ repos = db.listRepos(accountId);
1775
+ }
1776
+ const targets = onlyIds ? repos.filter((r) => onlyIds.includes(r.id)) : account.watchedRepoIds.length > 0 ? repos.filter((r) => account.watchedRepoIds.includes(r.id)) : repos;
1777
+ if (onlyIds && targets.length === 0) throw new Error("未找到要同步的仓库,请先刷新仓库列表");
1778
+ const newCommits = [];
1779
+ for (const repo of targets) try {
1780
+ const branch = account.repoBranches[repo.id] || repo.defaultBranch || account.defaultBranch || "master";
1781
+ const state = db.getSyncState(accountId, repo.id);
1782
+ const lookbackDays = getSyncLookbackDays();
1783
+ const fullFromMs = Date.now() - lookbackDays * DAY_MS;
1784
+ const needBackfill = !state?.lastSyncedAt || lookbackDays > (state.lookbackDays ?? 0);
1785
+ const lastMs = state?.lastSyncedAt ? Date.parse(state.lastSyncedAt) : NaN;
1786
+ const sinceMs = needBackfill ? fullFromMs : Number.isFinite(lastMs) ? lastMs - INCREMENTAL_OVERLAP_MS : fullFromMs;
1787
+ const since = toApiTime(new Date(sinceMs).toISOString());
1788
+ const { commits, capped, pages } = await provider.listCommitsSince(account, token, repo.id, {
1789
+ ref: branch,
1790
+ since
1791
+ });
1792
+ fetched += commits.length;
1793
+ if (capped) {
1794
+ truncated++;
1795
+ const msg = `仓库 ${shortRepoPath(repo.fullName || repo.name, account.organizationId)}: 提交过多,本次只取到 ${commits.length} 条(${pages} 页上限),更早的提交可能未同步`;
1796
+ db.addSyncLog({
1797
+ id: v4(),
1798
+ accountId,
1799
+ at: (/* @__PURE__ */ new Date()).toISOString(),
1800
+ level: "warn",
1801
+ message: msg
1802
+ });
1803
+ }
1804
+ const now = (/* @__PURE__ */ new Date()).toISOString();
1805
+ for (const c of commits) {
1806
+ if (!matchAuthor(account, c.authorName, c.authorEmail)) continue;
1807
+ matched++;
1808
+ newCommits.push({
1809
+ id: v4(),
1810
+ accountId,
1811
+ repoId: repo.id,
1812
+ repoName: shortRepoPath(repo.fullName || repo.name, account.organizationId),
1813
+ sha: c.sha,
1814
+ shortId: c.shortId,
1815
+ title: c.title,
1816
+ message: c.message,
1817
+ authorName: c.authorName,
1818
+ authorEmail: c.authorEmail,
1819
+ committedAt: c.committedAt || c.authoredAt,
1820
+ webUrl: c.webUrl,
1821
+ syncedAt: now
1822
+ });
1823
+ }
1824
+ db.setSyncState({
1825
+ accountId,
1826
+ repoId: repo.id,
1827
+ lastSyncedAt: now,
1828
+ lookbackDays
1829
+ });
1830
+ } catch (e) {
1831
+ const msg = `仓库 ${shortRepoPath(repo.fullName || repo.name, account.organizationId)}: ${e?.message || e}`;
1832
+ errors.push(msg);
1833
+ db.addSyncLog({
1834
+ id: v4(),
1835
+ accountId,
1836
+ at: (/* @__PURE__ */ new Date()).toISOString(),
1837
+ level: "error",
1838
+ message: msg
1839
+ });
1840
+ }
1841
+ inserted = db.insertCommits(newCommits);
1842
+ writeDailyExports(accountId, newCommits);
1843
+ db.addSyncLog({
1844
+ id: v4(),
1845
+ accountId,
1846
+ at: (/* @__PURE__ */ new Date()).toISOString(),
1847
+ level: errors.length || truncated ? "warn" : "info",
1848
+ message: `同步完成:拉取 ${fetched}(匹配作者 ${matched}),新增 ${inserted}${truncated ? `,${truncated} 个仓库触及分页上限` : ""}${errors.length ? `,失败 ${errors.length}` : ""}`
1849
+ });
1850
+ return {
1851
+ accountId,
1852
+ fetched,
1853
+ inserted,
1854
+ errors,
1855
+ truncated
1856
+ };
1857
+ } catch (e) {
1858
+ const msg = e?.message || String(e);
1859
+ errors.push(msg);
1860
+ db.addSyncLog({
1861
+ id: v4(),
1862
+ accountId,
1863
+ at: (/* @__PURE__ */ new Date()).toISOString(),
1864
+ level: "error",
1865
+ message: msg
1866
+ });
1867
+ return {
1868
+ accountId,
1869
+ fetched,
1870
+ inserted,
1871
+ errors
1872
+ };
1873
+ } finally {
1874
+ syncing.delete(accountId);
1875
+ }
1876
+ }
1877
+ function scheduleAccount(accountId) {
1878
+ clearAccountSchedule(accountId);
1879
+ if (!getAccount(accountId)) return;
1880
+ const ms = getSyncIntervalMinutes() * 60 * 1e3;
1881
+ const timer = setInterval(() => {
1882
+ syncAccount(accountId);
1883
+ }, ms);
1884
+ timers.set(accountId, timer);
1885
+ }
1886
+ function clearAccountSchedule(accountId) {
1887
+ const t = timers.get(accountId);
1888
+ if (t) clearInterval(t);
1889
+ timers.delete(accountId);
1890
+ }
1891
+ function rescheduleAll() {
1892
+ for (const id of [...timers.keys()]) clearAccountSchedule(id);
1893
+ for (const a of listAccounts()) scheduleAccount(a.id);
1894
+ }
1895
+ function stopAllSchedules() {
1896
+ for (const id of [...timers.keys()]) clearAccountSchedule(id);
1897
+ }
1898
+ // src/core/cnWorkdays.ts
1899
+ dayjs.extend(isoWeek);
1900
+ const memory = /* @__PURE__ */ new Map();
1901
+ const inflight = /* @__PURE__ */ new Map();
1902
+ const CACHE_MAX_AGE_MS = 2592e6;
1903
+ function cachePath(year) {
1904
+ const dir = holidayCacheDir();
1905
+ mkdirSync(dir, { recursive: true });
1906
+ return join(dir, `${year}.json`);
1907
+ }
1908
+ function parseTimor(json) {
1909
+ if (json.code !== 0 || !json.holiday || typeof json.holiday !== "object") return null;
1910
+ const holidays = [];
1911
+ const makeupWorkdays = [];
1912
+ for (const item of Object.values(json.holiday)) {
1913
+ const date = (item.date || "").trim();
1914
+ if (!/^\d{4}-\d{2}-\d{2}$/.test(date)) continue;
1915
+ if (item.holiday) holidays.push(date);
1916
+ else makeupWorkdays.push(date);
1917
+ }
1918
+ if (holidays.length === 0 && makeupWorkdays.length === 0) return null;
1919
+ return {
1920
+ holidays,
1921
+ makeupWorkdays,
1922
+ source: "api"
1923
+ };
1924
+ }
1925
+ function readDiskCache(year) {
1926
+ const path = cachePath(year);
1927
+ if (!existsSync(path)) return null;
1928
+ try {
1929
+ const raw = JSON.parse(readFileSync(path, "utf8"));
1930
+ if (!Array.isArray(raw.holidays) || !Array.isArray(raw.makeupWorkdays)) return null;
1931
+ return {
1932
+ days: {
1933
+ holidays: raw.holidays,
1934
+ makeupWorkdays: raw.makeupWorkdays,
1935
+ source: "cache"
1936
+ },
1937
+ mtimeMs: statSync(path).mtimeMs
1938
+ };
1939
+ } catch {
1940
+ return null;
1941
+ }
1942
+ }
1943
+ function writeDiskCache(year, days) {
1944
+ writeFileSync(cachePath(year), JSON.stringify({
1945
+ holidays: days.holidays,
1946
+ makeupWorkdays: days.makeupWorkdays
1947
+ }, null, 2), "utf8");
1948
+ }
1949
+ function weekdayFallback(year) {
1950
+ return {
1951
+ holidays: [],
1952
+ makeupWorkdays: [],
1953
+ source: "fallback"
1954
+ };
1955
+ }
1956
+ async function fetchYear(year) {
1957
+ if (memory.has(year)) return memory.get(year);
1958
+ const cached = readDiskCache(year);
1959
+ if (cached && Date.now() - cached.mtimeMs < CACHE_MAX_AGE_MS) {
1960
+ memory.set(year, cached.days);
1961
+ return cached.days;
1962
+ }
1963
+ if (inflight.has(year)) return inflight.get(year);
1964
+ const task = (async () => {
1965
+ try {
1966
+ const res = await fetch(`https://timor.tech/api/holiday/year/${year}/`);
1967
+ if (!res.ok) throw new Error(`timor ${res.status}`);
1968
+ const parsed = parseTimor(await res.json());
1969
+ if (!parsed) throw new Error("timor parse failed");
1970
+ writeDiskCache(year, parsed);
1971
+ memory.set(year, parsed);
1972
+ return parsed;
1973
+ } catch {
1974
+ if (cached) {
1975
+ memory.set(year, cached.days);
1976
+ return cached.days;
1977
+ }
1978
+ const fb = weekdayFallback(year);
1979
+ memory.set(year, fb);
1980
+ return fb;
1981
+ } finally {
1982
+ inflight.delete(year);
1983
+ }
1984
+ })();
1985
+ inflight.set(year, task);
1986
+ return task;
1987
+ }
1988
+ function isWorkday(d, yearDays) {
1989
+ const key = d.format("YYYY-MM-DD");
1990
+ if (yearDays.holidays.includes(key)) return false;
1991
+ if (yearDays.makeupWorkdays.includes(key)) return true;
1992
+ const dow = d.day();
1993
+ return dow >= 1 && dow <= 5;
1994
+ }
1995
+ async function countWorkdays(from, to) {
1996
+ const years = /* @__PURE__ */ new Set();
1997
+ for (let cur = from; !cur.isAfter(to, "day"); cur = cur.add(1, "day")) years.add(cur.year());
1998
+ const byYear = /* @__PURE__ */ new Map();
1999
+ for (const y of years) byYear.set(y, await fetchYear(y));
2000
+ let count = 0;
2001
+ for (let cur = from; !cur.isAfter(to, "day"); cur = cur.add(1, "day")) if (isWorkday(cur, byYear.get(cur.year()))) count++;
2002
+ return count;
2003
+ }
2004
+ async function resolveStatutoryWorkdays(kind, date) {
2005
+ if (kind !== "week" && kind !== "month") return void 0;
2006
+ const d = dayjs(date || dayjs().format("YYYY-MM-DD"));
2007
+ if (kind === "week") return countWorkdays(d.startOf("isoWeek"), d.endOf("isoWeek"));
2008
+ return countWorkdays(d.startOf("month"), d.endOf("month"));
2009
+ }
2010
+ // src/core/reportRange.ts
2011
+ dayjs.extend(isoWeek);
2012
+ function rangeFor(kind, date, from, to) {
2013
+ if (kind === "custom") {
2014
+ if (!from || !to) throw new Error("自定义区间需提供起止日期");
2015
+ return {
2016
+ from: `${from}T00:00:00.000Z`,
2017
+ to: `${to}T23:59:59.999Z`,
2018
+ title: `自定义汇报 ${from} ~ ${to}`,
2019
+ fileName: `custom-${from}_${to}.md`,
2020
+ period: `${from} ~ ${to}`,
2021
+ kindLabel: "自定义汇报"
2022
+ };
2023
+ }
2024
+ const d = dayjs(date || dayjs().format("YYYY-MM-DD"));
2025
+ if (kind === "day") {
2026
+ const day = d.format("YYYY-MM-DD");
2027
+ return {
2028
+ from: `${day}T00:00:00.000Z`,
2029
+ to: `${day}T23:59:59.999Z`,
2030
+ title: `日报 ${day}`,
2031
+ fileName: `day-${day}.md`,
2032
+ period: day,
2033
+ kindLabel: "日报"
2034
+ };
2035
+ }
2036
+ if (kind === "week") {
2037
+ const start = d.startOf("isoWeek");
2038
+ const end = d.endOf("isoWeek");
2039
+ const week = d.isoWeek();
2040
+ const year = d.isoWeekYear();
2041
+ const label = `${year}-W${String(week).padStart(2, "0")}(${start.format("MM-DD")} ~ ${end.format("MM-DD")})`;
2042
+ return {
2043
+ from: start.toISOString(),
2044
+ to: end.toISOString(),
2045
+ title: `周报 ${label}`,
2046
+ fileName: `week-${year}-W${String(week).padStart(2, "0")}.md`,
2047
+ period: label,
2048
+ kindLabel: "周报"
2049
+ };
2050
+ }
2051
+ const start = d.startOf("month");
2052
+ const end = d.endOf("month");
2053
+ const ym = d.format("YYYY-MM");
2054
+ return {
2055
+ from: start.toISOString(),
2056
+ to: end.toISOString(),
2057
+ title: `月报 ${ym}`,
2058
+ fileName: `month-${ym}.md`,
2059
+ period: ym,
2060
+ kindLabel: "月报"
2061
+ };
2062
+ }
2063
+ // src/core/reportMarkdown.ts
2064
+ function buildReportHeader(title, accountName, commitCount) {
2065
+ return [
2066
+ `# ${title}`,
2067
+ "",
2068
+ `- 账号:${accountName}`,
2069
+ `- 提交数:${commitCount}`,
2070
+ `- 生成时间:${dayjs().format("YYYY-MM-DD HH:mm:ss")}`,
2071
+ ""
2072
+ ].join("\n");
2073
+ }
2074
+ function buildCommitDetailsMarkdown(commits) {
2075
+ const byRepo = /* @__PURE__ */ new Map();
2076
+ for (const c of commits) {
2077
+ if (!byRepo.has(c.repoName)) byRepo.set(c.repoName, []);
2078
+ byRepo.get(c.repoName).push(c);
2079
+ }
2080
+ const lines = [];
2081
+ const repos = Array.from(byRepo.entries()).sort((a, b) => a[0].localeCompare(b[0]));
2082
+ for (const [repo, list] of repos) {
2083
+ lines.push(`### ${repo}`);
2084
+ lines.push("");
2085
+ for (const c of list) {
2086
+ const time = dayjs(c.committedAt).format("MM-DD HH:mm");
2087
+ const [first, ...rest] = commitFullText(c).split("\n");
2088
+ lines.push(`- [${time}] ${first}`);
2089
+ for (const line of rest) lines.push(` ${line}`);
2090
+ }
2091
+ lines.push("");
2092
+ }
2093
+ return lines.join("\n").trimEnd();
2094
+ }
2095
+ function buildCommitSubjectListMarkdown(commits) {
2096
+ const byRepo = /* @__PURE__ */ new Map();
2097
+ for (const c of commits) {
2098
+ if (!byRepo.has(c.repoName)) byRepo.set(c.repoName, []);
2099
+ byRepo.get(c.repoName).push(c);
2100
+ }
2101
+ const lines = [];
2102
+ const repos = Array.from(byRepo.entries()).sort((a, b) => a[0].localeCompare(b[0]));
2103
+ for (const [repo, list] of repos) {
2104
+ lines.push(`### ${repo}`);
2105
+ lines.push("");
2106
+ for (const c of list) {
2107
+ const time = dayjs(c.committedAt).format("MM-DD HH:mm");
2108
+ lines.push(`- [${time}] ${commitTitleLine(c)}`);
2109
+ }
2110
+ lines.push("");
2111
+ }
2112
+ return lines.join("\n").trimEnd();
2113
+ }
2114
+ // src/core/reports.ts
2115
+ function buildTemplateMarkdown(title, accountName, commits, statutoryWorkdays) {
2116
+ const titleLine = statutoryWorkdays != null ? `${title} · ${commits.length} 条 · 法定工作日:${statutoryWorkdays} 天` : title;
2117
+ const lines = [];
2118
+ lines.push(buildReportHeader(titleLine, accountName, commits.length));
2119
+ lines.push("## 工作摘要(草稿)");
2120
+ lines.push("");
2121
+ lines.push("> 以下按项目列出完整提交说明,可据此改写成汇报用语。");
2122
+ lines.push("");
2123
+ lines.push(buildCommitDetailsMarkdown(commits));
2124
+ lines.push("");
2125
+ return lines.join("\n");
2126
+ }
2127
+ async function generateReport(req, exportFile = true) {
2128
+ const account = getAccount(req.accountId);
2129
+ if (!account) throw new Error("账号不存在");
2130
+ const { from, to, title, fileName } = rangeFor(req.kind, req.date, req.from, req.to);
2131
+ const { items } = db.queryCommits({
2132
+ accountId: req.accountId,
2133
+ from,
2134
+ to,
2135
+ limit: 5e3
2136
+ });
2137
+ const statutoryWorkdays = await resolveStatutoryWorkdays(req.kind, req.date);
2138
+ const markdown = buildTemplateMarkdown(title, account.name, items, statutoryWorkdays);
2139
+ let filePath;
2140
+ if (exportFile) {
2141
+ const dir = join(reportsDir(), req.accountId);
2142
+ if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
2143
+ filePath = join(dir, fileName);
2144
+ writeFileSync(filePath, markdown, "utf8");
2145
+ }
2146
+ return {
2147
+ title,
2148
+ markdown,
2149
+ filePath,
2150
+ commitCount: items.length,
2151
+ statutoryWorkdays
2152
+ };
2153
+ }
2154
+ // src/tools/resolveAccount.ts
2155
+ function resolveAccountId(accountId) {
2156
+ const accounts = listAccounts();
2157
+ if (accountId?.trim()) {
2158
+ const found = accounts.find((a) => a.id === accountId.trim());
2159
+ if (!found) throw new Error(`账号不存在:${accountId}`);
2160
+ return found.id;
2161
+ }
2162
+ const activeId = getActiveAccountId();
2163
+ if (activeId && accounts.some((a) => a.id === activeId)) return activeId;
2164
+ if (accounts.length === 1) return accounts[0].id;
2165
+ if (accounts.length === 0) throw new Error(`本地无账号。请先调用 upsert_account(mode=remote 或 local)。数据目录:${getDataRoot()}`);
2166
+ throw new Error("存在多个账号,请先调用 list_accounts 后传入 accountId");
2167
+ }
2168
+ function accountSummary() {
2169
+ const accounts = listAccounts();
2170
+ const activeAccountId = getActiveAccountId();
2171
+ return accounts.map((a) => ({
2172
+ id: a.id,
2173
+ name: a.name,
2174
+ mode: a.mode,
2175
+ provider: a.provider,
2176
+ edition: a.edition,
2177
+ organizationId: a.organizationId,
2178
+ apiBaseUrl: a.apiBaseUrl,
2179
+ localRoots: a.localRoots,
2180
+ authorFilters: a.authorFilters,
2181
+ defaultBranch: a.defaultBranch,
2182
+ watchedRepoCount: a.watchedRepoIds.length,
2183
+ active: a.id === activeAccountId
2184
+ }));
2185
+ }
2186
+ // src/tools/registerTools.ts
2187
+ function textOut(text) {
2188
+ return text;
2189
+ }
2190
+ /**
2191
+ * 注册 commit-journal 相关 agent 工具
2192
+ */
2193
+ function registerTools(ctx) {
2194
+ ctx.tools.register(defineTool({
2195
+ name: "list_accounts",
2196
+ description: "列出 Commit Journal 账号(id、名称、mode=local|remote、provider、localRoots、是否当前活跃)。总结工作前可先调用以确认 accountId。",
2197
+ parameters: {},
2198
+ output: {
2199
+ schema: { type: "string" },
2200
+ render: (_args, value) => [{
2201
+ type: "text",
2202
+ text: String(value)
2203
+ }]
2204
+ },
2205
+ async execute() {
2206
+ const list = accountSummary();
2207
+ if (list.length === 0) return textOut([
2208
+ "本地无账号。",
2209
+ `数据目录:${getDataRoot()}`,
2210
+ "请先调用 upsert_account。"
2211
+ ].join("\n"));
2212
+ return textOut(JSON.stringify({
2213
+ accounts: list,
2214
+ dataRoot: getDataRoot()
2215
+ }, null, 2));
2216
+ }
2217
+ }));
2218
+ ctx.tools.register(defineTool({
2219
+ name: "upsert_account",
2220
+ description: "创建或更新账号。mode=remote(默认)按 provider 用 PAT 拉提交(codeup / gitlab / github);mode=local 扫描 localRoots 下的本机 git 仓(无需 token)。创建时不要传 id;更新时传 id。",
2221
+ parameters: {
2222
+ id: {
2223
+ type: "string",
2224
+ description: "已有账号 id;省略则新建"
2225
+ },
2226
+ name: {
2227
+ type: "string",
2228
+ required: true,
2229
+ description: "账号显示名"
2230
+ },
2231
+ mode: {
2232
+ type: "string",
2233
+ description: "remote | local;默认 remote"
2234
+ },
2235
+ provider: {
2236
+ type: "string",
2237
+ description: "remote 时 codeup | gitlab | github;local 固定 local"
2238
+ },
2239
+ edition: {
2240
+ type: "string",
2241
+ description: "central | region(仅 Codeup)"
2242
+ },
2243
+ organizationId: {
2244
+ type: "string",
2245
+ description: "Codeup 中心版 organizationId;GitHub 可选 org login;GitLab 可选 group path/id"
2246
+ },
2247
+ apiBaseUrl: {
2248
+ type: "string",
2249
+ description: "Codeup Region API Base;自建 GitLab / GHE 主机(可省略 /api/v4 或 /api/v3);gitlab.com / github.com 可留空"
2250
+ },
2251
+ insecureSsl: {
2252
+ type: "boolean",
2253
+ description: "跳过 TLS 证书校验(公司代理 / 自签证书)。也可用环境变量 DSH_COMMIT_JOURNAL_TLS_INSECURE=1"
2254
+ },
2255
+ localRoots: {
2256
+ type: "array",
2257
+ items: { type: "string" },
2258
+ description: "local 模式扫描根目录列表"
2259
+ },
2260
+ token: {
2261
+ type: "string",
2262
+ description: "remote PAT;更新时可省略表示不改;local 不需要"
2263
+ },
2264
+ authorFilters: {
2265
+ type: "array",
2266
+ items: { type: "string" },
2267
+ description: "作者邮箱/姓名过滤"
2268
+ },
2269
+ defaultBranch: { type: "string" },
2270
+ setActive: {
2271
+ type: "boolean",
2272
+ description: "设为当前活跃账号"
2273
+ },
2274
+ test: {
2275
+ type: "boolean",
2276
+ description: "保存前测试连接/扫描,默认 true"
2277
+ }
2278
+ },
2279
+ output: {
2280
+ schema: { type: "string" },
2281
+ render: (_a, v) => [{
2282
+ type: "text",
2283
+ text: String(v)
2284
+ }]
2285
+ },
2286
+ async execute(args) {
2287
+ const mode = args.mode === "local" ? "local" : "remote";
2288
+ const provider = mode === "local" ? "local" : args.provider || "codeup";
2289
+ const token = args.token?.trim();
2290
+ const localRoots = Array.isArray(args.localRoots) ? args.localRoots.map(String) : void 0;
2291
+ let account;
2292
+ if (args.id) account = updateAccount({
2293
+ id: String(args.id),
2294
+ name: args.name,
2295
+ mode,
2296
+ provider,
2297
+ edition: args.edition,
2298
+ organizationId: args.organizationId,
2299
+ apiBaseUrl: args.apiBaseUrl,
2300
+ insecureSsl: args.insecureSsl,
2301
+ localRoots,
2302
+ token,
2303
+ authorFilters: args.authorFilters,
2304
+ defaultBranch: args.defaultBranch
2305
+ });
2306
+ else {
2307
+ if (mode === "remote" && !token) throw new Error("远程账号新建必须提供 token");
2308
+ if (mode === "local" && !(localRoots && localRoots.length)) throw new Error("本地账号新建必须提供 localRoots");
2309
+ account = createAccount({
2310
+ name: args.name,
2311
+ mode,
2312
+ provider,
2313
+ edition: args.edition || "central",
2314
+ organizationId: args.organizationId,
2315
+ apiBaseUrl: args.apiBaseUrl,
2316
+ insecureSsl: args.insecureSsl,
2317
+ localRoots,
2318
+ token,
2319
+ authorFilters: args.authorFilters || [],
2320
+ defaultBranch: args.defaultBranch
2321
+ });
2322
+ }
2323
+ if (args.setActive !== false) setActiveAccountId(account.id);
2324
+ let testResult;
2325
+ if (args.test !== false) {
2326
+ const t = account.mode === "local" ? "" : getAccountToken(account.id);
2327
+ testResult = await getProvider(account).testConnection(account, t);
2328
+ }
2329
+ return textOut(JSON.stringify({
2330
+ ok: true,
2331
+ account: {
2332
+ id: account.id,
2333
+ name: account.name,
2334
+ mode: account.mode,
2335
+ provider: account.provider,
2336
+ edition: account.edition,
2337
+ localRoots: account.localRoots
2338
+ },
2339
+ test: testResult
2340
+ }, null, 2));
2341
+ }
2342
+ }));
2343
+ ctx.tools.register(defineTool({
2344
+ name: "remove_account",
2345
+ description: "删除本地账号及其提交缓存(不会删除远端仓库)。",
2346
+ parameters: { accountId: {
2347
+ type: "string",
2348
+ required: true
2349
+ } },
2350
+ output: {
2351
+ schema: { type: "string" },
2352
+ render: (_a, v) => [{
2353
+ type: "text",
2354
+ text: String(v)
2355
+ }]
2356
+ },
2357
+ async execute(args) {
2358
+ deleteAccount(String(args.accountId));
2359
+ return textOut(JSON.stringify({
2360
+ ok: true,
2361
+ removed: args.accountId
2362
+ }));
2363
+ }
2364
+ }));
2365
+ ctx.tools.register(defineTool({
2366
+ name: "sync_commits",
2367
+ description: "增量同步指定账号的提交到本地缓存。remote=Codeup/GitLab/GitHub API;local=扫描根目录下 git log。可先 upsert_account。",
2368
+ parameters: {
2369
+ accountId: { type: "string" },
2370
+ repoIds: {
2371
+ type: "array",
2372
+ items: { type: "string" },
2373
+ description: "可选,限制仓库"
2374
+ }
2375
+ },
2376
+ output: {
2377
+ schema: { type: "string" },
2378
+ render: (_a, v) => [{
2379
+ type: "text",
2380
+ text: String(v)
2381
+ }]
2382
+ },
2383
+ async execute(args) {
2384
+ const result = await syncAccount(resolveAccountId(args.accountId), args.repoIds);
2385
+ return textOut(JSON.stringify(result, null, 2));
2386
+ }
2387
+ }));
2388
+ ctx.tools.register(defineTool({
2389
+ name: "list_repos",
2390
+ description: "列出某账号下已有提交记录的仓库(或缓存的全部仓库)。refresh=true 时 remote 拉 API / local 重扫根目录。",
2391
+ parameters: {
2392
+ accountId: { type: "string" },
2393
+ withCommitsOnly: {
2394
+ type: "boolean",
2395
+ description: "默认 true,仅返回已有提交的仓库"
2396
+ },
2397
+ refresh: {
2398
+ type: "boolean",
2399
+ description: "是否先刷新仓库列表(remote API 或 local 扫描)"
2400
+ }
2401
+ },
2402
+ output: {
2403
+ schema: { type: "string" },
2404
+ render: (_a, v) => [{
2405
+ type: "text",
2406
+ text: String(v)
2407
+ }]
2408
+ },
2409
+ async execute(args) {
2410
+ const id = resolveAccountId(args.accountId);
2411
+ if (args.refresh) {
2412
+ const account = getAccount(id);
2413
+ const token = getAccountToken(id);
2414
+ const repos = await getProvider(account).listRepos(account, token);
2415
+ db.upsertRepos(id, repos);
2416
+ }
2417
+ const list = args.withCommitsOnly === false ? db.listRepos(id) : db.listReposWithCommits(id);
2418
+ return textOut(JSON.stringify({
2419
+ accountId: id,
2420
+ repos: list.map((r) => ({
2421
+ id: r.id,
2422
+ name: r.name,
2423
+ fullName: r.fullName,
2424
+ webUrl: r.webUrl,
2425
+ defaultBranch: r.defaultBranch
2426
+ }))
2427
+ }, null, 2));
2428
+ }
2429
+ }));
2430
+ ctx.tools.register(defineTool({
2431
+ name: "query_commits",
2432
+ description: "按日期/仓库/关键词查询本地已同步的提交。",
2433
+ parameters: {
2434
+ accountId: { type: "string" },
2435
+ repoId: { type: "string" },
2436
+ from: {
2437
+ type: "string",
2438
+ description: "YYYY-MM-DD 或 ISO"
2439
+ },
2440
+ to: {
2441
+ type: "string",
2442
+ description: "YYYY-MM-DD 或 ISO"
2443
+ },
2444
+ keyword: { type: "string" },
2445
+ limit: { type: "number" },
2446
+ subjectOnly: {
2447
+ type: "boolean",
2448
+ description: "仅提交首行"
2449
+ }
2450
+ },
2451
+ output: {
2452
+ schema: { type: "string" },
2453
+ render: (_a, v) => [{
2454
+ type: "text",
2455
+ text: String(v)
2456
+ }]
2457
+ },
2458
+ async execute(args) {
2459
+ const id = resolveAccountId(args.accountId);
2460
+ const account = getAccount(id);
2461
+ const { items, total } = db.queryCommits({
2462
+ accountId: id,
2463
+ repoId: args.repoId,
2464
+ from: args.from,
2465
+ to: args.to,
2466
+ keyword: args.keyword,
2467
+ limit: args.limit ?? 200
2468
+ });
2469
+ const body = args.subjectOnly ? buildCommitSubjectListMarkdown(items) : buildCommitDetailsMarkdown(items);
2470
+ return textOut([
2471
+ `# 提交查询结果`,
2472
+ "",
2473
+ `- 账号:${account.name}`,
2474
+ `- 返回:${items.length} / 共 ${total} 条`,
2475
+ `- 生成时间:${dayjs().format("YYYY-MM-DD HH:mm:ss")}`,
2476
+ "",
2477
+ body || "(无提交)"
2478
+ ].join("\n"));
2479
+ }
2480
+ }));
2481
+ ctx.tools.register(defineTool({
2482
+ name: "get_period_report",
2483
+ description: "按日/周/月/自定义区间生成报告 Markdown 材料(含法定工作日天数)。",
2484
+ parameters: {
2485
+ accountId: { type: "string" },
2486
+ kind: {
2487
+ type: "string",
2488
+ required: true,
2489
+ description: "day | week | month | custom"
2490
+ },
2491
+ date: {
2492
+ type: "string",
2493
+ description: "锚点日期 YYYY-MM-DD"
2494
+ },
2495
+ from: {
2496
+ type: "string",
2497
+ description: "custom 起始"
2498
+ },
2499
+ to: {
2500
+ type: "string",
2501
+ description: "custom 结束"
2502
+ },
2503
+ exportFile: {
2504
+ type: "boolean",
2505
+ description: "是否落盘,默认 true"
2506
+ }
2507
+ },
2508
+ output: {
2509
+ schema: { type: "string" },
2510
+ render: (_a, v) => [{
2511
+ type: "text",
2512
+ text: String(v)
2513
+ }]
2514
+ },
2515
+ async execute(args) {
2516
+ const result = await generateReport({
2517
+ accountId: resolveAccountId(args.accountId),
2518
+ kind: args.kind,
2519
+ date: args.date,
2520
+ from: args.from,
2521
+ to: args.to
2522
+ }, args.exportFile !== false);
2523
+ return textOut([
2524
+ result.markdown,
2525
+ "",
2526
+ result.filePath ? `已落盘:${result.filePath}` : "",
2527
+ result.statutoryWorkdays != null ? `法定工作日:${result.statutoryWorkdays} 天` : ""
2528
+ ].filter(Boolean).join("\n"));
2529
+ }
2530
+ }));
2531
+ ctx.tools.register(defineTool({
2532
+ name: "get_activity_heatmap",
2533
+ description: "获取提交活跃热力图数据:按本地自然日聚合。可指定 year,或不传表示近一年。传 date 时返回该日提交明细。",
2534
+ parameters: {
2535
+ accountId: { type: "string" },
2536
+ year: {
2537
+ type: "number",
2538
+ description: "自然年;省略=近一年"
2539
+ },
2540
+ date: {
2541
+ type: "string",
2542
+ description: "YYYY-MM-DD,返回当日明细"
2543
+ }
2544
+ },
2545
+ output: {
2546
+ schema: { type: "string" },
2547
+ render: (_a, v) => [{
2548
+ type: "text",
2549
+ text: String(v)
2550
+ }]
2551
+ },
2552
+ async execute(args) {
2553
+ const id = resolveAccountId(args.accountId);
2554
+ if (args.date) {
2555
+ const items = db.listDayCommits(id, args.date);
2556
+ return textOut(JSON.stringify({
2557
+ accountId: id,
2558
+ date: args.date,
2559
+ count: items.length,
2560
+ commits: items.map((c) => ({
2561
+ time: c.committedAt,
2562
+ repo: c.repoName,
2563
+ title: c.title,
2564
+ sha: c.shortId,
2565
+ webUrl: c.webUrl
2566
+ }))
2567
+ }, null, 2));
2568
+ }
2569
+ const data = db.getActivity(id, args.year);
2570
+ return textOut(JSON.stringify({
2571
+ accountId: id,
2572
+ ...data
2573
+ }, null, 2));
2574
+ }
2575
+ }));
2576
+ ctx.tools.register(defineTool({
2577
+ name: "update_journal_settings",
2578
+ description: "更新本地同步/导出/热力图 UI 端口等设置。",
2579
+ parameters: {
2580
+ exportsPath: { type: "string" },
2581
+ syncIntervalMinutes: { type: "number" },
2582
+ syncLookbackDays: { type: "number" },
2583
+ uiPort: { type: "number" }
2584
+ },
2585
+ output: {
2586
+ schema: { type: "string" },
2587
+ render: (_a, v) => [{
2588
+ type: "text",
2589
+ text: String(v)
2590
+ }]
2591
+ },
2592
+ async execute(args) {
2593
+ const next = updateSettings(args);
2594
+ return textOut(JSON.stringify({
2595
+ ok: true,
2596
+ settings: describeSettings(),
2597
+ saved: next
2598
+ }, null, 2));
2599
+ }
2600
+ }));
2601
+ }
2602
+ // src/ui/server.ts
2603
+ let server = null;
2604
+ let listenPort = null;
2605
+ function corsHeaders() {
2606
+ return {
2607
+ "Access-Control-Allow-Origin": "*",
2608
+ "Access-Control-Allow-Methods": "GET,POST,PUT,PATCH,DELETE,OPTIONS",
2609
+ "Access-Control-Allow-Headers": "Content-Type"
2610
+ };
2611
+ }
2612
+ function sendJson(res, status, body) {
2613
+ const raw = JSON.stringify(body);
2614
+ res.writeHead(status, {
2615
+ "Content-Type": "application/json; charset=utf-8",
2616
+ ...corsHeaders()
2617
+ });
2618
+ res.end(raw);
2619
+ }
2620
+ function readBody(req) {
2621
+ return new Promise((resolve, reject) => {
2622
+ const chunks = [];
2623
+ req.on("data", (c) => chunks.push(Buffer.isBuffer(c) ? c : Buffer.from(c)));
2624
+ req.on("end", () => resolve(Buffer.concat(chunks).toString("utf8")));
2625
+ req.on("error", reject);
2626
+ });
2627
+ }
2628
+ async function readJson(req) {
2629
+ const raw = await readBody(req);
2630
+ if (!raw.trim()) return {};
2631
+ return JSON.parse(raw);
2632
+ }
2633
+ function accountPublic(a, activeId) {
2634
+ return {
2635
+ id: a.id,
2636
+ name: a.name,
2637
+ mode: a.mode,
2638
+ provider: a.provider,
2639
+ edition: a.edition,
2640
+ organizationId: a.organizationId,
2641
+ apiBaseUrl: a.apiBaseUrl,
2642
+ insecureSsl: Boolean(a.insecureSsl),
2643
+ localRoots: a.localRoots || [],
2644
+ authorFilters: a.authorFilters,
2645
+ defaultBranch: a.defaultBranch,
2646
+ watchedRepoIds: a.watchedRepoIds,
2647
+ repoBranches: a.repoBranches,
2648
+ createdAt: a.createdAt,
2649
+ updatedAt: a.updatedAt,
2650
+ active: a.id === activeId
2651
+ };
2652
+ }
2653
+ function matchRoute(pathname, pattern) {
2654
+ const pp = pattern.split("/").filter(Boolean);
2655
+ const ap = pathname.split("/").filter(Boolean);
2656
+ if (pp.length !== ap.length) return null;
2657
+ const params = {};
2658
+ for (let i = 0; i < pp.length; i++) if (pp[i].startsWith(":")) params[pp[i].slice(1)] = decodeURIComponent(ap[i]);
2659
+ else if (pp[i] !== ap[i]) return null;
2660
+ return params;
2661
+ }
2662
+ async function handler(req, res) {
2663
+ const url = new URL(req.url || "/", `http://127.0.0.1`);
2664
+ const method = req.method || "GET";
2665
+ if (method === "OPTIONS") {
2666
+ res.writeHead(204, corsHeaders());
2667
+ res.end();
2668
+ return;
2669
+ }
2670
+ try {
2671
+ if (method === "GET" && (url.pathname === "/" || url.pathname === "/api/health")) {
2672
+ sendJson(res, 200, {
2673
+ ok: true,
2674
+ port: listenPort,
2675
+ dataRoot: getDataRoot()
2676
+ });
2677
+ return;
2678
+ }
2679
+ if (method === "GET" && url.pathname === "/api/accounts") {
2680
+ const activeId = getActiveAccountId();
2681
+ sendJson(res, 200, {
2682
+ dataRoot: getDataRoot(),
2683
+ activeAccountId: activeId,
2684
+ accounts: listAccounts().map((a) => accountPublic(a, activeId))
2685
+ });
2686
+ return;
2687
+ }
2688
+ if (method === "POST" && url.pathname === "/api/accounts") {
2689
+ const body = await readJson(req);
2690
+ const mode = body.mode === "local" ? "local" : "remote";
2691
+ const account = createAccount({
2692
+ name: body.name,
2693
+ mode,
2694
+ provider: mode === "local" ? "local" : body.provider || "codeup",
2695
+ edition: body.edition || "central",
2696
+ organizationId: body.organizationId,
2697
+ apiBaseUrl: body.apiBaseUrl,
2698
+ insecureSsl: body.insecureSsl,
2699
+ localRoots: Array.isArray(body.localRoots) ? body.localRoots : typeof body.localRootsText === "string" ? String(body.localRootsText).split(/\r?\n/) : void 0,
2700
+ token: body.token,
2701
+ authorFilters: body.authorFilters || [],
2702
+ defaultBranch: body.defaultBranch,
2703
+ watchedRepoIds: body.watchedRepoIds,
2704
+ repoBranches: body.repoBranches
2705
+ });
2706
+ if (body.setActive !== false) setActiveAccountId(account.id);
2707
+ let test;
2708
+ if (body.test !== false) {
2709
+ const token = account.mode === "local" ? "" : getAccountToken(account.id);
2710
+ test = await getProvider(account).testConnection(account, token);
2711
+ }
2712
+ sendJson(res, 200, {
2713
+ account: accountPublic(account, getActiveAccountId()),
2714
+ test
2715
+ });
2716
+ return;
2717
+ }
2718
+ {
2719
+ const m = matchRoute(url.pathname, "/api/accounts/:id");
2720
+ if (m) {
2721
+ if (method === "PATCH" || method === "PUT") {
2722
+ const body = await readJson(req);
2723
+ sendJson(res, 200, { account: accountPublic(updateAccount({
2724
+ id: m.id,
2725
+ name: body.name,
2726
+ mode: body.mode,
2727
+ provider: body.provider,
2728
+ edition: body.edition,
2729
+ organizationId: body.organizationId,
2730
+ apiBaseUrl: body.apiBaseUrl,
2731
+ insecureSsl: body.insecureSsl,
2732
+ localRoots: Array.isArray(body.localRoots) ? body.localRoots : typeof body.localRootsText === "string" ? String(body.localRootsText).split(/\r?\n/) : void 0,
2733
+ token: body.token,
2734
+ authorFilters: body.authorFilters,
2735
+ defaultBranch: body.defaultBranch,
2736
+ watchedRepoIds: body.watchedRepoIds,
2737
+ repoBranches: body.repoBranches
2738
+ }), getActiveAccountId()) });
2739
+ return;
2740
+ }
2741
+ if (method === "DELETE") {
2742
+ deleteAccount(m.id);
2743
+ sendJson(res, 200, {
2744
+ ok: true,
2745
+ removed: m.id
2746
+ });
2747
+ return;
2748
+ }
2749
+ }
2750
+ }
2751
+ {
2752
+ const m = matchRoute(url.pathname, "/api/accounts/:id/activate");
2753
+ if (m && method === "POST") {
2754
+ if (!getAccount(m.id)) return sendJson(res, 404, { error: "账号不存在" });
2755
+ setActiveAccountId(m.id);
2756
+ sendJson(res, 200, {
2757
+ ok: true,
2758
+ activeAccountId: m.id
2759
+ });
2760
+ return;
2761
+ }
2762
+ }
2763
+ {
2764
+ const m = matchRoute(url.pathname, "/api/accounts/:id/test");
2765
+ if (m && method === "POST") {
2766
+ const account = getAccount(m.id);
2767
+ if (!account) return sendJson(res, 404, { error: "账号不存在" });
2768
+ const token = account.mode === "local" ? "" : getAccountToken(m.id);
2769
+ sendJson(res, 200, {
2770
+ ok: true,
2771
+ ...await getProvider(account).testConnection(account, token)
2772
+ });
2773
+ return;
2774
+ }
2775
+ }
2776
+ if (method === "GET" && url.pathname === "/api/repos") {
2777
+ const accountId = url.searchParams.get("accountId") || getActiveAccountId() || "";
2778
+ if (!accountId) return sendJson(res, 400, { error: "accountId required" });
2779
+ const account = getAccount(accountId);
2780
+ if (!account) return sendJson(res, 404, { error: "账号不存在" });
2781
+ const list = url.searchParams.get("withCommitsOnly") === "1" ? db.listReposWithCommits(accountId) : db.listRepos(accountId);
2782
+ sendJson(res, 200, {
2783
+ accountId,
2784
+ watchedRepoIds: account.watchedRepoIds,
2785
+ repoBranches: account.repoBranches,
2786
+ repos: list.map((r) => {
2787
+ const displayName = shortRepoPath(r.fullName || r.name, account.organizationId);
2788
+ return {
2789
+ id: r.id,
2790
+ name: r.name,
2791
+ fullName: displayName,
2792
+ displayName,
2793
+ webUrl: r.webUrl,
2794
+ defaultBranch: r.defaultBranch,
2795
+ lastActivityAt: r.lastActivityAt,
2796
+ participating: r.participating,
2797
+ watched: account.watchedRepoIds.length === 0 || account.watchedRepoIds.includes(r.id),
2798
+ branchOverride: account.repoBranches[r.id] || ""
2799
+ };
2800
+ })
2801
+ });
2802
+ return;
2803
+ }
2804
+ if (method === "GET" && url.pathname === "/api/repo-branches") {
2805
+ const accountId = url.searchParams.get("accountId") || getActiveAccountId() || "";
2806
+ const repoId = String(url.searchParams.get("repoId") || "").trim();
2807
+ const account = getAccount(accountId);
2808
+ if (!account) return sendJson(res, 404, { error: "账号不存在" });
2809
+ if (!repoId) return sendJson(res, 400, { error: "缺少 repoId" });
2810
+ const token = getAccountToken(accountId);
2811
+ sendJson(res, 200, {
2812
+ repoId,
2813
+ branches: (await getProvider(account).listBranches(account, token, repoId)).map((b) => ({
2814
+ name: b.name,
2815
+ defaultBranch: b.defaultBranch,
2816
+ protected: b.protected
2817
+ }))
2818
+ });
2819
+ return;
2820
+ }
2821
+ {
2822
+ const branchPath = url.pathname.match(/^\/api\/repos\/(.+)\/branches\/?$/);
2823
+ if (branchPath && method === "GET") {
2824
+ const accountId = url.searchParams.get("accountId") || getActiveAccountId() || "";
2825
+ const repoId = decodeURIComponent(branchPath[1]);
2826
+ const account = getAccount(accountId);
2827
+ if (!account) return sendJson(res, 404, { error: "账号不存在" });
2828
+ const token = getAccountToken(accountId);
2829
+ sendJson(res, 200, {
2830
+ repoId,
2831
+ branches: (await getProvider(account).listBranches(account, token, repoId)).map((b) => ({
2832
+ name: b.name,
2833
+ defaultBranch: b.defaultBranch,
2834
+ protected: b.protected
2835
+ }))
2836
+ });
2837
+ return;
2838
+ }
2839
+ }
2840
+ if (method === "POST" && url.pathname === "/api/repos/refresh") {
2841
+ const body = await readJson(req);
2842
+ const accountId = String(body.accountId || getActiveAccountId() || "");
2843
+ const account = getAccount(accountId);
2844
+ if (!account) return sendJson(res, 404, { error: "账号不存在" });
2845
+ const token = getAccountToken(accountId);
2846
+ const repos = await getProvider(account).listRepos(account, token);
2847
+ db.upsertRepos(accountId, repos);
2848
+ sendJson(res, 200, {
2849
+ accountId,
2850
+ count: repos.length,
2851
+ repos: db.listRepos(accountId)
2852
+ });
2853
+ return;
2854
+ }
2855
+ if (method === "PUT" && url.pathname === "/api/repos/watch") {
2856
+ const body = await readJson(req);
2857
+ const accountId = String(body.accountId || "");
2858
+ if (!getAccount(accountId)) return sendJson(res, 404, { error: "账号不存在" });
2859
+ const account = updateAccount({
2860
+ id: accountId,
2861
+ watchedRepoIds: Array.isArray(body.watchedRepoIds) ? body.watchedRepoIds.map(String) : [],
2862
+ repoBranches: body.repoBranches || {}
2863
+ });
2864
+ sendJson(res, 200, {
2865
+ ok: true,
2866
+ watchedRepoIds: account.watchedRepoIds,
2867
+ repoBranches: account.repoBranches
2868
+ });
2869
+ return;
2870
+ }
2871
+ if (method === "POST" && url.pathname === "/api/sync") {
2872
+ const body = await readJson(req);
2873
+ const accountId = String(body.accountId || getActiveAccountId() || "");
2874
+ if (!accountId) return sendJson(res, 400, { error: "accountId required" });
2875
+ sendJson(res, 200, await syncAccount(accountId, Array.isArray(body.repoIds) ? body.repoIds.map(String) : void 0));
2876
+ return;
2877
+ }
2878
+ if (method === "GET" && url.pathname === "/api/commits") {
2879
+ const accountId = url.searchParams.get("accountId") || getActiveAccountId() || "";
2880
+ if (!accountId) return sendJson(res, 400, { error: "accountId required" });
2881
+ const limit = Number(url.searchParams.get("limit") || 20);
2882
+ const offset = Number(url.searchParams.get("offset") || 0);
2883
+ sendJson(res, 200, db.queryCommits({
2884
+ accountId,
2885
+ repoId: url.searchParams.get("repoId") || void 0,
2886
+ from: url.searchParams.get("from") || void 0,
2887
+ to: url.searchParams.get("to") || void 0,
2888
+ keyword: url.searchParams.get("keyword") || void 0,
2889
+ limit,
2890
+ offset
2891
+ }));
2892
+ return;
2893
+ }
2894
+ if (method === "POST" && url.pathname === "/api/commits/clear") {
2895
+ const body = await readJson(req);
2896
+ const accountId = String(body.accountId || "");
2897
+ if (!accountId) return sendJson(res, 400, { error: "accountId required" });
2898
+ sendJson(res, 200, db.clearCommits(accountId, body.repoId ? String(body.repoId) : void 0));
2899
+ return;
2900
+ }
2901
+ if (method === "GET" && url.pathname === "/api/activity") {
2902
+ const accountId = url.searchParams.get("accountId") || getActiveAccountId() || "";
2903
+ const yearRaw = url.searchParams.get("year");
2904
+ const year = yearRaw ? Number(yearRaw) : void 0;
2905
+ if (!accountId) return sendJson(res, 400, { error: "accountId required" });
2906
+ sendJson(res, 200, db.getActivity(accountId, year));
2907
+ return;
2908
+ }
2909
+ if (method === "GET" && url.pathname === "/api/activity/day") {
2910
+ const accountId = url.searchParams.get("accountId") || getActiveAccountId() || "";
2911
+ const date = url.searchParams.get("date") || "";
2912
+ if (!accountId || !date) return sendJson(res, 400, { error: "accountId/date required" });
2913
+ sendJson(res, 200, { commits: db.listDayCommits(accountId, date).map((c) => ({
2914
+ id: c.id,
2915
+ time: c.committedAt,
2916
+ repo: c.repoName,
2917
+ title: c.title,
2918
+ message: c.message,
2919
+ authorName: c.authorName,
2920
+ sha: c.shortId,
2921
+ webUrl: c.webUrl
2922
+ })) });
2923
+ return;
2924
+ }
2925
+ if (method === "GET" && url.pathname === "/api/logs") {
2926
+ const accountId = url.searchParams.get("accountId") || getActiveAccountId() || "";
2927
+ if (!accountId) return sendJson(res, 400, { error: "accountId required" });
2928
+ const limit = Number(url.searchParams.get("limit") || 50);
2929
+ const offset = Number(url.searchParams.get("offset") || 0);
2930
+ sendJson(res, 200, db.listSyncLogs(accountId, limit, offset));
2931
+ return;
2932
+ }
2933
+ if (method === "DELETE" && url.pathname === "/api/logs") {
2934
+ const accountId = url.searchParams.get("accountId") || await readJson(req).then((b) => b.accountId).catch(() => "") || "";
2935
+ sendJson(res, 200, { deleted: db.clearSyncLogs(accountId || void 0) });
2936
+ return;
2937
+ }
2938
+ if (method === "GET" && url.pathname === "/api/settings") {
2939
+ sendJson(res, 200, {
2940
+ ...describeSettings(),
2941
+ listenPort,
2942
+ apiBase: listenPort ? `http://127.0.0.1:${listenPort}` : null
2943
+ });
2944
+ return;
2945
+ }
2946
+ if ((method === "PUT" || method === "PATCH") && url.pathname === "/api/settings") {
2947
+ const body = await readJson(req);
2948
+ const next = updateSettings({
2949
+ exportsPath: body.exportsPath,
2950
+ syncIntervalMinutes: body.syncIntervalMinutes,
2951
+ syncLookbackDays: body.syncLookbackDays,
2952
+ uiPort: body.uiPort
2953
+ });
2954
+ sendJson(res, 200, {
2955
+ ok: true,
2956
+ settings: describeSettings(),
2957
+ saved: next
2958
+ });
2959
+ return;
2960
+ }
2961
+ sendJson(res, 404, { error: "not found" });
2962
+ } catch (e) {
2963
+ sendJson(res, 500, { error: e?.message || String(e) });
2964
+ }
2965
+ }
2966
+ function getHeatmapUrl() {
2967
+ return listenPort ? `http://127.0.0.1:${listenPort}/` : null;
2968
+ }
2969
+ async function startUiServer(port = getUiPort()) {
2970
+ if (server && listenPort) return `http://127.0.0.1:${listenPort}/`;
2971
+ server = createServer((req, res) => {
2972
+ handler(req, res);
2973
+ });
2974
+ await new Promise((resolve, reject) => {
2975
+ server.once("error", reject);
2976
+ server.listen(port, "127.0.0.1", () => resolve());
2977
+ });
2978
+ listenPort = port;
2979
+ return `http://127.0.0.1:${port}/`;
2980
+ }
2981
+ async function stopUiServer() {
2982
+ if (!server) return;
2983
+ const s = server;
2984
+ server = null;
2985
+ listenPort = null;
2986
+ await new Promise((resolve) => s.close(() => resolve()));
2987
+ }
2988
+ // src/index.ts
2989
+ const name = "commit-journal";
2990
+ const inject = ["tools"];
2991
+ /**
2992
+ * Commit Journal dsh 插件:同步 VCS 提交与活跃热力图面板
2993
+ */
2994
+ function apply(ctx) {
2995
+ ensureDataLayout();
2996
+ registerTools(ctx);
2997
+ ctx.tools.register(defineTool({
2998
+ name: "open_activity_heatmap",
2999
+ description: "返回本机 Commit Journal API 基址(侧栏面板数据源)。",
3000
+ parameters: {},
3001
+ output: {
3002
+ schema: { type: "string" },
3003
+ render: (_a, v) => [{
3004
+ type: "text",
3005
+ text: String(v)
3006
+ }]
3007
+ },
3008
+ async execute() {
3009
+ const url = await startUiServer();
3010
+ return JSON.stringify({
3011
+ url,
3012
+ dataRoot: getDataRoot()
3013
+ }, null, 2);
3014
+ }
3015
+ }));
3016
+ ctx.effect(() => {
3017
+ startUiServer().catch((e) => {
3018
+ ctx.logger?.warn?.(`[commit-journal] ui server: ${e?.message || e}`);
3019
+ });
3020
+ try {
3021
+ rescheduleAll();
3022
+ } catch {}
3023
+ return () => {
3024
+ stopAllSchedules();
3025
+ stopUiServer();
3026
+ };
3027
+ });
3028
+ }
3029
+ export { apply, getDataRoot, getHeatmapUrl, inject, name, startUiServer, stopUiServer };
3030
+
3031
+ //# sourceMappingURL=index.js.map