dsh-git-push 2.9.4 → 2.10.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +42 -39
- package/lib/app/apply.js +8 -1
- package/lib/app/audit-api.js +4 -1
- package/lib/app/command-registry.js +18 -11
- package/lib/app/handlers/meta.js +38 -0
- package/lib/app/handlers/repo-actions.js +3 -1
- package/lib/app/handlers/repos.js +18 -2
- package/lib/app/handlers/settings.js +0 -0
- package/lib/app/http-handlers.js +3 -1
- package/lib/app/schema.js +0 -0
- package/lib/app/settings-bridge.js +0 -0
- package/lib/app/tool-call.js +32 -23
- package/lib/ast/brace.js +15 -0
- package/lib/ast/control-flow.js +12 -3
- package/lib/ast/size.js +73 -3
- package/lib/audit/audit-file.js +4 -2
- package/lib/audit/collector.js +13 -4
- package/lib/audit/file-context.js +89 -0
- package/lib/audit/finding.js +16 -2
- package/lib/audit/ignore-blind.js +5 -4
- package/lib/audit/index.js +2 -2
- package/lib/audit/orchestrate.js +2 -1
- package/lib/audit-rules/audit-rules-frontend.yml +4 -4
- package/lib/checks/button-bind.js +84 -13
- package/lib/checks/dispatch.js +1 -1
- package/lib/checks/private.js +2 -1
- package/lib/checks/structural.js +10 -3
- package/lib/client-parts/{10-account.js → account.js} +1 -1
- package/lib/client-parts/{41-actions.js → actions.js} +3 -2
- package/lib/client-parts/{99-apply.js → apply.js} +2 -1
- package/lib/client-parts/{21-audit.js → audit.js} +5 -5
- package/lib/client-parts/{11-browser.js → browser.js} +15 -4
- package/lib/client-parts/{01-const.js → const.js} +11 -5
- package/lib/client-parts/{40-controller.js → controller.js} +4 -4
- package/lib/client-parts/{03-icons.js → icons.js} +1 -1
- package/lib/client-parts/{00-loader.js → loader.js} +1 -0
- package/lib/client-parts/{23-npm.js → npm.js} +3 -2
- package/lib/client-parts/{30-page.js → page.js} +1 -1
- package/lib/client-parts/{20-repo.js → repo.js} +2 -2
- package/lib/client-parts/{22-settings.js → settings.js} +1 -1
- package/lib/client-parts/{02-utils.js → utils.js} +1 -1
- package/lib/client.js +51 -30
- package/lib/commit-push.js +20 -2
- package/lib/context/index.js +2 -1
- package/lib/core/atomic-json.js +1 -1
- package/lib/core/exec.js +6 -4
- package/lib/exempt/index.js +7 -2
- package/lib/exempt/tool.js +198 -0
- package/lib/git/clone-history-mode.js +24 -5
- package/lib/git/index-format.js +182 -0
- package/lib/git/index.js +1 -0
- package/lib/git/push.js +28 -13
- package/lib/git/repo-index.js +41 -30
- package/lib/git/scan-runner.js +1 -1
- package/lib/git/transport.js +49 -17
- package/lib/git/visibility.js +93 -9
- package/lib/npm/publish.js +30 -1
- package/lib/npm/registry.js +5 -2
- package/lib/self/index.js +1 -1
- package/package.json +2 -4
- package/scripts/build-client.mjs +19 -14
- package/scripts/picker-repro.mjs +115 -0
- package/skills/dev/dsh-git-push.md +1 -2
- package/skills/dsh-repo-index.md +1 -1
- package/skills/guide/guide-audit.md +77 -3
- package/skills/guide/guide-cli-scripts.md +4 -4
- package/skills/guide/guide-clone-repos.md +2 -2
- package/skills/guide/guide-inject-ui.md +6 -6
- package/skills/workflow/README.md +1 -1
- package/assets/minihost.sh +0 -35
- package/assets/preview.html +0 -36703
- package/lib/fs/edit-after-read.js +0 -142
- package/scripts/frontend-preview-check.mjs +0 -124
- package/scripts/preview-gen.mjs +0 -489
- package/scripts/preview-local-runner.mjs +0 -55
- package/scripts/preview-server-direct.mjs +0 -116
- package/scripts/preview-server.mjs +0 -305
- package/scripts/preview-slot-data.mjs +0 -123
- package/scripts/sync-plugin-install.mjs +0 -286
- package/scripts/sync-plugin.mjs +0 -284
package/lib/git/push.js
CHANGED
|
@@ -10,7 +10,7 @@ import { existsSync } from 'node:fs';
|
|
|
10
10
|
import { join } from 'node:path';
|
|
11
11
|
import { autoTagDSHProject, ensureAuxSshRemote, readPkgVersion, updateRemoteTrackingRef } from './post-push.js';
|
|
12
12
|
import { loadRequirements } from './config.js';
|
|
13
|
-
import { resolveSshKeys } from './credentials.js';
|
|
13
|
+
import { resolveSshKeys, resolveToken } from './credentials.js';
|
|
14
14
|
import { runGit } from './exec.js';
|
|
15
15
|
import { buildWrappedGitEnv } from './wrapped-git.js';
|
|
16
16
|
import { buildCommitMessage } from './commit-message.js';
|
|
@@ -44,7 +44,7 @@ function resolveRepoIdentity(repoPath) {
|
|
|
44
44
|
import { fetchRemoteHeads, dispatchPush, liveRemoteHead } from './transport.js';
|
|
45
45
|
// 推送后「远端 sha 硬校验」用(假成功防线:远端空仓/未落地时必须判失败,见 enhanceAfterPushSuccess)
|
|
46
46
|
import { githubFetch } from './api.js';
|
|
47
|
-
import { resolveRepoVisibility } from './visibility.js';
|
|
47
|
+
import { resolveRepoVisibility, cachedVisibility } from './visibility.js';
|
|
48
48
|
|
|
49
49
|
/**
|
|
50
50
|
* 统一提交推送:预检 → 敏感文件 .gitignore → add → commit → push。
|
|
@@ -54,7 +54,7 @@ import { resolveRepoVisibility } from './visibility.js';
|
|
|
54
54
|
* customIgnorePatterns:逗号/换行分隔的 gitignore pattern,追加进 .gitignore(幂等)
|
|
55
55
|
* @returns {{ok, steps: string[], commitSha?, pushed?, push?, remoteHeads?, error?}}
|
|
56
56
|
*/
|
|
57
|
-
export async function commitAndPush({ repoPath = '', message = '', messageItems = null, push = true, dryRun = false, token = '', customIgnorePatterns = '', requirementsConfirmed = false, force = false, pushMethod = 'ssh', pushGate = false, pushConfirmed = false, paths = '' } = {}) {
|
|
57
|
+
export async function commitAndPush({ repoPath = '', message = '', messageItems = null, push = true, dryRun = false, token = '', customIgnorePatterns = '', requirementsConfirmed = false, force = false, pushMethod = 'ssh', pushGate = false, pushConfirmed = false, paths = '', remote = '' } = {}) {
|
|
58
58
|
const steps = [];
|
|
59
59
|
if (!repoPath || !existsSync(join(repoPath, '.git'))) return { ok: false, steps: ['预检'], error: `非 git 仓库: ${repoPath || '(空)'}` };
|
|
60
60
|
// message 支持三种形态(字符串 / 数组 / {subject,items}):在预检处**单点**组装成规范提交信息,
|
|
@@ -199,7 +199,7 @@ export async function commitAndPush({ repoPath = '', message = '', messageItems
|
|
|
199
199
|
steps.push('push');
|
|
200
200
|
// 通道由 dispatchPush 单点决策(默认 SSH:推本地 HEAD、远端 sha 与本地一致;无密钥才回落 API)。
|
|
201
201
|
// ⚠️ dispatchPush 是 async:必须 await(旧 bug:同步调用导致 pr.ok 恒 undefined,推送从未成功)
|
|
202
|
-
const pr = await dispatchPush({ repoPath, token, force, pushMethod });
|
|
202
|
+
const pr = await dispatchPush({ repoPath, token, force, pushMethod, remote });
|
|
203
203
|
if (pr.ok) {
|
|
204
204
|
// D24:pr.pushed=false(内容级短路「远端已是最新」)→ 如实 pushed:false(commitPushDoPush 语义)
|
|
205
205
|
// committed 必须如实带上:cleanSkipCommit 时本次**没有产生新提交**。
|
|
@@ -209,7 +209,7 @@ export async function commitAndPush({ repoPath = '', message = '', messageItems
|
|
|
209
209
|
// 原先只有 API 分支做这些,SSH 分支只拉 heads → 走 SSH 时本地 origin/<branch> 引用不更新,
|
|
210
210
|
// 下次 ahead/behind 判断就会错位。
|
|
211
211
|
steps.push(`pushed-via-${pr.method || 'unknown'}`);
|
|
212
|
-
const enhanced = await enhanceAfterPushSuccess({ repoPath, pr, token, steps, commitSha });
|
|
212
|
+
const enhanced = await enhanceAfterPushSuccess({ repoPath, pr, token, steps, commitSha, remote });
|
|
213
213
|
// 假成功防线(用户实测事故):远端为空仓时推送动作不报错,但提交根本没上去。
|
|
214
214
|
// verified===false 表示「API 查到了远端分支,但 sha 与本地提交不一致 / 查不到该分支」
|
|
215
215
|
// ⇒ 必须返回 ok:false,让调用方与用户看到真实状态,而不是「commit+push done」。
|
|
@@ -267,7 +267,7 @@ async function fetchRemoteBranchRef(repoPath, branch, owner, repo) {
|
|
|
267
267
|
* 结果记入 push.remoteRef / push.auxRemote / autoTag。
|
|
268
268
|
* @returns {Promise<{push, autoTag, heads?}>}
|
|
269
269
|
*/
|
|
270
|
-
async function enhanceAfterPushSuccess({ repoPath, pr, token, steps, commitSha }) {
|
|
270
|
+
async function enhanceAfterPushSuccess({ repoPath, pr, token, steps, commitSha, remote = '' }) {
|
|
271
271
|
const pushSlot = pr;
|
|
272
272
|
const branchRef = pr.branch;
|
|
273
273
|
const localHead = runGit(['rev-parse', 'HEAD'], { cwd: repoPath }).stdout;
|
|
@@ -289,13 +289,20 @@ async function enhanceAfterPushSuccess({ repoPath, pr, token, steps, commitSha }
|
|
|
289
289
|
} catch (e) {
|
|
290
290
|
pushSlot.auxRemote = `ensure-aux-remote 异常: ${e?.message || e}`;
|
|
291
291
|
}
|
|
292
|
+
// 核验用 token:调用方没显式传时从插件凭据兜底。
|
|
293
|
+
// 为什么必须有:pushViaSsh 成功时 pr.token 为空,若这里直接用 token(默认 ''),
|
|
294
|
+
// 后面的 API 核验会以空 token 请求 → 404/401 → 明明推成功了却报「未能核验远端」。
|
|
295
|
+
const verifyToken = String(token || '').trim() || resolveToken({ workspaceRoot: repoPath }).token;
|
|
296
|
+
// 统一前置判断:先确定仓库可见性并填缓存——后续 ls-remote 探针据此决定要不要试 origin(https):
|
|
297
|
+
// 私有库经 https/镜像必然失败,试它只会把「未核验」的原因带偏。
|
|
298
|
+
try { await resolveRepoVisibility(repoPath, verifyToken); } catch { /* 判定失败按 unknown 处理 */ }
|
|
292
299
|
let autoTag = null;
|
|
293
300
|
try {
|
|
294
|
-
autoTag = await autoTagDSHProject({ repoPath, version: readPkgVersion(repoPath), commitSha: pr.commitSha, owner: pr.owner, repo: pr.repo, token: pr.token ||
|
|
301
|
+
autoTag = await autoTagDSHProject({ repoPath, version: readPkgVersion(repoPath), commitSha: pr.commitSha, owner: pr.owner, repo: pr.repo, token: pr.token || verifyToken });
|
|
295
302
|
} catch (e) {
|
|
296
303
|
autoTag = { ok: false, skipped: 'auto-tag-error', error: String(e?.message || e) };
|
|
297
304
|
}
|
|
298
|
-
const heads = await fetchRemoteHeads({ owner: pr.owner, repo: pr.repo, branch: pr.branch, token: pr.token ||
|
|
305
|
+
const heads = await fetchRemoteHeads({ owner: pr.owner, repo: pr.repo, branch: pr.branch, token: pr.token || verifyToken }).catch(() => null);
|
|
299
306
|
// 推送成功后的**硬校验**:远端该分支的 sha 必须等于本次提交 sha。
|
|
300
307
|
// 事故(用户实测):远端仓库为空(API 409 Conflict)时插件仍回「commit+push done」——
|
|
301
308
|
// 成功判定只看「推送动作有没有报错」,没看「远端到底有没有这个提交」,属**假成功**。
|
|
@@ -321,6 +328,13 @@ async function enhanceAfterPushSuccess({ repoPath, pr, token, steps, commitSha }
|
|
|
321
328
|
*/
|
|
322
329
|
const lsRemoteProbe = () => {
|
|
323
330
|
try {
|
|
331
|
+
// 通道 1:SSH(与推送同源)。推送走 ssh:443 时核验也必须走同一条——
|
|
332
|
+
// origin 常是 https 而本机 https 通道不通,只跑 origin 会让探针永远「失明」,
|
|
333
|
+
// 于是明明推送成功却报「未能核验远端」(实测就是这个现象)。
|
|
334
|
+
const ssh = liveRemoteHead({ repoPath, branch: branchRef, remote });
|
|
335
|
+
if (ssh.ok && ssh.sha) return { ok: true, sha: ssh.sha, via: ssh.via };
|
|
336
|
+
// 通道 2:origin(https + 凭据 env)。私有库跳过——镜像/直连都看不到私有库,试了只会多一条失败。
|
|
337
|
+
if (cachedVisibility(repoPath) === 'private') return { ok: false, sha: '', err: '私有库跳过 origin(https) 通道(统一前置判断)' };
|
|
324
338
|
// ⚠️ 必须带**凭据 env**:私有库上不带凭据的 ls-remote 会静默返回空(HTTPS 下等同 404)——
|
|
325
339
|
// 那会让「第二路证据」失明。故这一路必须复用插件自己的凭据装配(SSH 私钥 / HTTPS askpass):
|
|
326
340
|
// exec.js 的 runGit 是裸 git,只有 wrapped-git.js 的 buildWrappedGitEnv 会注入凭据。
|
|
@@ -338,7 +352,7 @@ async function enhanceAfterPushSuccess({ repoPath, pr, token, steps, commitSha }
|
|
|
338
352
|
const lsRemoteSha = () => lsRemoteProbe().sha;
|
|
339
353
|
try {
|
|
340
354
|
const br = await githubFetch(`/repos/${pr.owner}/${pr.repo}/branches/${encodeURIComponent(branchRef)}`,
|
|
341
|
-
{ token: pr.token ||
|
|
355
|
+
{ token: pr.token || verifyToken, method: 'GET' });
|
|
342
356
|
const remoteSha = String(br?.json?.commit?.sha || '');
|
|
343
357
|
// 比对对象是**本次推送所报的 sha**(pr.commitSha):API 通道会在远端新建提交对象,
|
|
344
358
|
// 其 sha 与本地 HEAD 本来就不同(设计如此,见 fetchRemoteBranchRef 注释),
|
|
@@ -422,14 +436,15 @@ export function readmeCheckHint(repoPath) {
|
|
|
422
436
|
* @param {{repoPath?:string, pushMethod?:string}} opts
|
|
423
437
|
* @returns {{ok:boolean, branch?, ahead?, behind?, changed?, pushed?, push?, error?}}
|
|
424
438
|
*/
|
|
425
|
-
export async function pushCurrentBranch({ repoPath = '', pushMethod = 'ssh' } = {}) {
|
|
439
|
+
export async function pushCurrentBranch({ repoPath = '', pushMethod = 'ssh', remote = '' } = {}) {
|
|
426
440
|
if (!repoPath || !existsSync(join(repoPath, '.git'))) return { ok: false, error: `非 git 仓库: ${repoPath || '(空)'}` };
|
|
427
441
|
const branch = runGit(['rev-parse', '--abbrev-ref', 'HEAD'], { cwd: repoPath }).stdout.trim() || '';
|
|
428
442
|
const status = runGit(['status', '--porcelain'], { cwd: repoPath }).stdout;
|
|
429
443
|
const changed = status ? status.split('\n').filter(Boolean).length : 0;
|
|
430
444
|
const up = runGit(['rev-parse', '--abbrev-ref', '--symbolic-full-name', '@{u}'], { cwd: repoPath });
|
|
431
445
|
const upstream = up.ok && up.stdout.trim() ? up.stdout.trim() : '';
|
|
432
|
-
|
|
446
|
+
// 指定 remote 时以它为基准(多 remote / fork 场景);否则沿用 origin
|
|
447
|
+
const originUrl = runGit(['remote', 'get-url', remote || 'origin'], { cwd: repoPath }).stdout.trim();
|
|
433
448
|
// 放宽「必须已 -u 建立上游」——无 @{u} 但有远端同样可推
|
|
434
449
|
// (dispatchPush 走 `git push <远端> HEAD:refs/heads/<分支>`,不依赖上游跟踪)。
|
|
435
450
|
// 领先比较基准 = @{u},否则 origin/<当前分支>;本地无该 ref(未 fetch 过)时
|
|
@@ -438,7 +453,7 @@ export async function pushCurrentBranch({ repoPath = '', pushMethod = 'ssh' } =
|
|
|
438
453
|
let ahead = 0, behind = 0, remoteMissing = false, compareFailed = false;
|
|
439
454
|
// 优先 live ls-remote:origin 是 https 时本地 fetch 常失败,origin/<branch> 缓存过期
|
|
440
455
|
// 会把「远端已前走」显示成「领先 N」,点 push 才报分叉。
|
|
441
|
-
const live = originUrl ? liveRemoteHead({ repoPath, branch }) : { ok: false, sha: '' };
|
|
456
|
+
const live = originUrl ? liveRemoteHead({ repoPath, branch, remote }) : { ok: false, sha: '' };
|
|
442
457
|
if (live.ok && live.sha) {
|
|
443
458
|
const rcLive = runGit(['rev-list', '--left-right', '--count', `HEAD...${live.sha}`], { cwd: repoPath });
|
|
444
459
|
if (rcLive.ok) {
|
|
@@ -471,6 +486,6 @@ export async function pushCurrentBranch({ repoPath = '', pushMethod = 'ssh' } =
|
|
|
471
486
|
if (compareFailed) return { ok: false, ahead, behind, changed, error: '无法确认远端状态(本地未 fetch 且 ls-remote 失败)——请先 git fetch 或检查网络' };
|
|
472
487
|
if (ahead <= 0) return { ok: false, ahead, behind, changed, error: '当前分支未领先远端(没有可推送的新提交)' };
|
|
473
488
|
if (behind > 0) return { ok: false, ahead, behind, changed, error: `本地与远端分叉(本地领先 ${ahead},远端领先 ${behind})——先 pull 合并远端提交再推送` };
|
|
474
|
-
const push = await dispatchPush({ repoPath, branch, pushMethod });
|
|
489
|
+
const push = await dispatchPush({ repoPath, branch, pushMethod, remote });
|
|
475
490
|
return { ok: push.ok === true, branch, ahead, behind, changed, pushed: push.pushed, push, error: push.error || push.reason };
|
|
476
491
|
}
|
package/lib/git/repo-index.js
CHANGED
|
@@ -16,15 +16,17 @@
|
|
|
16
16
|
* 自持、不入 git;与 dsh-repo-index skill 权威位置一致)。失败全部静默降级,
|
|
17
17
|
* 不阻塞扫描/推送。
|
|
18
18
|
*/
|
|
19
|
-
import {
|
|
19
|
+
import { existsSync } from 'node:fs';
|
|
20
20
|
import { readFile, readdir, stat, access } from 'node:fs/promises';
|
|
21
21
|
import { join, basename, dirname } from 'node:path';
|
|
22
22
|
|
|
23
23
|
import { scanRepos, parseGithubOwnerRepo, githubFetch } from './index.js';
|
|
24
24
|
import { credentialsDir } from './credentials.js';
|
|
25
|
-
import { writeTextAtomic
|
|
26
|
-
|
|
27
|
-
|
|
25
|
+
import { writeTextAtomic } from './atomic-json.js';
|
|
26
|
+
import {
|
|
27
|
+
INDEX_FILE, serializeIndex, parseIndex,
|
|
28
|
+
readIndexFile, writeIndexFile, findIndexPath,
|
|
29
|
+
} from './index-format.js';
|
|
28
30
|
const VIS_CHECK_TIMEOUT_MS = 10_000; // GitHub 可见性查询超时
|
|
29
31
|
const AUTO_GEN_NOTE = 'auto-generated by dsh-git-push: DO NOT EDIT MANUALLY'; // 索引文件防手工编辑标记
|
|
30
32
|
|
|
@@ -36,8 +38,8 @@ const AUTO_GEN_NOTE = 'auto-generated by dsh-git-push: DO NOT EDIT MANUALLY'; //
|
|
|
36
38
|
* 凭据/索引收敛插件自持;workspaceRoot 保留作兼容入参,不再参与路径解析)。
|
|
37
39
|
*/
|
|
38
40
|
export function locateRepoIndex(workspaceRoot) {
|
|
39
|
-
|
|
40
|
-
return
|
|
41
|
+
// JSONL 优先,旧 .json 回退(迁移期两种都在时以 .jsonl 为准;写侧会把旧文件移入 .trash)
|
|
42
|
+
return findIndexPath(credentialsDir({ workspaceRoot: workspaceRoot || '' }));
|
|
41
43
|
}
|
|
42
44
|
|
|
43
45
|
/** 读索引:{ name → {owner, repo, repoUrl, visibility} };无索引/损坏 → null。 */
|
|
@@ -45,7 +47,7 @@ export function readRepoIndexMap(workspaceRoot) {
|
|
|
45
47
|
const p = locateRepoIndex(workspaceRoot);
|
|
46
48
|
if (!p) return null;
|
|
47
49
|
try {
|
|
48
|
-
const parsed =
|
|
50
|
+
const parsed = readIndexFile(dirname(p)).index;
|
|
49
51
|
const map = {};
|
|
50
52
|
for (const r of Array.isArray(parsed.repos) ? parsed.repos : []) {
|
|
51
53
|
if (!r || !r.name) continue;
|
|
@@ -256,7 +258,8 @@ export async function buildRepoIndex({ workspaceRoot, depth = 20, extraRepos = [
|
|
|
256
258
|
'# 3) 恢复后按插件安装三要素装回主环境(测试实例先行 + 接管式重启)',
|
|
257
259
|
].join('\n'),
|
|
258
260
|
};
|
|
259
|
-
|
|
261
|
+
// 输出 JSONL(每仓一行):流式可读、单行损坏不废整份
|
|
262
|
+
return serializeIndex(index);
|
|
260
263
|
}
|
|
261
264
|
|
|
262
265
|
/**
|
|
@@ -268,20 +271,25 @@ export function syncRepoIndex({ content, workspaceRoot = '', owner = 'EIGHTfs',
|
|
|
268
271
|
// 不变量「索引只存本地仓库」:写入前**剔除云端-only 残留条目**(cloudOnly=true 或
|
|
269
272
|
// path 为空的旧数据)——此前 merge 曾把本地无副本的云仓库登记进索引,这些条目既违反新语义,
|
|
270
273
|
// 又让前端列表出现空 path 行(React 同 key 警告)。写侧统一过滤,读到的旧索引入口即自愈。
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
274
|
+
// 调用方可能传 JSONL(buildRepoIndex 的输出),也可能传旧整份 JSON(历史调用方未全部收敛)
|
|
275
|
+
const parsed = parseIndex(content);
|
|
276
|
+
if (!parsed || !Array.isArray(parsed.repos)) {
|
|
277
|
+
// 无法解析 = 调用方传了非索引文本:原样落盘(保持旧行为,不静默丢内容)
|
|
278
|
+
const wr = writeTextAtomic(target, content);
|
|
279
|
+
return wr.ok ? { ok: true, written: [target] } : { ok: false, written: [] };
|
|
280
|
+
}
|
|
281
|
+
// 不变量「索引只存本地仓库」:写入前剔除云端-only 残留(cloudOnly=true 或 path 为空),
|
|
282
|
+
// 这些条目既违反语义,又让前端列表出现空 path 行(React 同 key 警告)。
|
|
283
|
+
parsed.repos = parsed.repos.filter((r) => r && !r.cloudOnly && String(r.path || '').trim());
|
|
284
|
+
// 显式 syncTarget 时按该路径写;否则统一走 writeIndexFile(写 .jsonl + 迁移旧 .json)
|
|
285
|
+
if (syncTarget) {
|
|
286
|
+
const wr = writeTextAtomic(syncTarget, serializeIndex(parsed));
|
|
287
|
+
return wr.ok ? { ok: true, written: [syncTarget] } : { ok: false, written: [] };
|
|
288
|
+
}
|
|
289
|
+
const wr = writeIndexFile(dirname(target), parsed);
|
|
290
|
+
return wr.ok
|
|
291
|
+
? { ok: true, written: [wr.path], ...(wr.migratedFrom ? { legacyMoved: wr.migratedFrom } : {}) }
|
|
292
|
+
: { ok: false, written: [] };
|
|
285
293
|
}
|
|
286
294
|
|
|
287
295
|
/**
|
|
@@ -299,7 +307,7 @@ export function syncRepoIndex({ content, workspaceRoot = '', owner = 'EIGHTfs',
|
|
|
299
307
|
*/
|
|
300
308
|
function mergeFreshIntoExisting(existing, freshContent) {
|
|
301
309
|
let fresh = null;
|
|
302
|
-
try { fresh =
|
|
310
|
+
try { fresh = parseIndex(freshContent); } catch { fresh = null; }
|
|
303
311
|
if (!fresh || !Array.isArray(fresh.repos)) {
|
|
304
312
|
// 新结果不可用(损坏/空)→ 保留现有索引原样
|
|
305
313
|
return { index: existing || { name: 'dsh-repo-index', version: 1, generatedAt: new Date().toISOString(), repos: [], localOnly: [] }, updated: 0 };
|
|
@@ -374,8 +382,11 @@ export async function updateRepoIndex({ workspaceRoot = '', token = '', owner =
|
|
|
374
382
|
// rebuild(默认):全量重建 → 与现有索引合并(不全量覆盖)
|
|
375
383
|
const target = syncTarget || locateRepoIndex(workspaceRoot) || join(credentialsDir({ workspaceRoot: workspaceRoot || '' }), INDEX_FILE);
|
|
376
384
|
let existing = null;
|
|
377
|
-
try {
|
|
378
|
-
|
|
385
|
+
try {
|
|
386
|
+
if (existsSync(target)) existing = readIndexFile(dirname(target)).index;
|
|
387
|
+
} catch { existing = null; }
|
|
388
|
+
// parseManualVisibility 入参是「索引文本」:统一用 JSONL 序列化(每行仍是合法 JSON 片段)
|
|
389
|
+
const manualVisibility = parseManualVisibility(existing ? serializeIndex(existing) : '');
|
|
379
390
|
// offline=true(账号卡片「扫描」)时纯离线重建——owner 过滤来自本地 remote
|
|
380
391
|
// 解析(不联网),可见性回退既有标注,不给 buildRepoIndex 传 token 即不触发可见性网络。
|
|
381
392
|
const fresh = await buildRepoIndex({
|
|
@@ -383,7 +394,7 @@ export async function updateRepoIndex({ workspaceRoot = '', token = '', owner =
|
|
|
383
394
|
token: offline ? '' : token, manualVisibility, owner, offline, maxRepos,
|
|
384
395
|
});
|
|
385
396
|
const { index, updated } = mergeFreshIntoExisting(existing, fresh);
|
|
386
|
-
const sync = syncRepoIndex({ content:
|
|
397
|
+
const sync = syncRepoIndex({ content: serializeIndex(index), workspaceRoot, owner, syncTarget });
|
|
387
398
|
return { ok: sync.ok, target: sync.written[0] || '', indexUpdated: sync.ok === true, updated };
|
|
388
399
|
} catch (e) {
|
|
389
400
|
return { ok: false, error: String(e?.message || e) };
|
|
@@ -418,7 +429,7 @@ export function mergeCloudReposIntoIndex({ workspaceRoot = '', owner = 'EIGHTfs'
|
|
|
418
429
|
const target = syncTarget || locateRepoIndex(workspaceRoot) || join(credentialsDir({ workspaceRoot: workspaceRoot || '' }), INDEX_FILE);
|
|
419
430
|
let existing = null;
|
|
420
431
|
try {
|
|
421
|
-
if (existsSync(target)) existing =
|
|
432
|
+
if (existsSync(target)) existing = readIndexFile(dirname(target)).index;
|
|
422
433
|
} catch { existing = null; }
|
|
423
434
|
// 保底结构:老索引/坏 JSON → 空容器,合并后写回
|
|
424
435
|
const index = existing && typeof existing === 'object' && Array.isArray(existing.repos) ? existing : {
|
|
@@ -461,7 +472,7 @@ export function mergeCloudReposIntoIndex({ workspaceRoot = '', owner = 'EIGHTfs'
|
|
|
461
472
|
index.repos = [...byName.values()].sort((a, b) => String(a.name).localeCompare(String(b.name)));
|
|
462
473
|
index.generatedAt = new Date().toISOString();
|
|
463
474
|
index.owner = owner;
|
|
464
|
-
const written = syncRepoIndex({ content:
|
|
475
|
+
const written = syncRepoIndex({ content: serializeIndex(index), workspaceRoot, owner, syncTarget });
|
|
465
476
|
return { ok: true, updated, ...written };
|
|
466
477
|
} catch (e) {
|
|
467
478
|
return { ok: false, error: String(e?.message || e) };
|
|
@@ -488,7 +499,7 @@ export function updateRepoRemoteStateInIndex({ workspaceRoot = '', repoName = ''
|
|
|
488
499
|
const target = syncTarget || locateRepoIndex(workspaceRoot) || join(credentialsDir({ workspaceRoot: workspaceRoot || '' }), INDEX_FILE);
|
|
489
500
|
let index = null;
|
|
490
501
|
try {
|
|
491
|
-
if (existsSync(target)) index =
|
|
502
|
+
if (existsSync(target)) index = readIndexFile(dirname(target)).index;
|
|
492
503
|
} catch { index = null; }
|
|
493
504
|
if (!index || !Array.isArray(index.repos) || !repoName) return { ok: false, error: '索引缺失/仓库名缺失' };
|
|
494
505
|
const hit = index.repos.find((r) => r.name === repoName);
|
|
@@ -504,7 +515,7 @@ export function updateRepoRemoteStateInIndex({ workspaceRoot = '', repoName = ''
|
|
|
504
515
|
if (visibility) hit.visibility = visibility;
|
|
505
516
|
hit.remoteStateAt = new Date().toISOString();
|
|
506
517
|
index.generatedAt = new Date().toISOString();
|
|
507
|
-
const written = syncRepoIndex({ content:
|
|
518
|
+
const written = syncRepoIndex({ content: serializeIndex(index), workspaceRoot, owner: index.owner || 'EIGHTfs', syncTarget });
|
|
508
519
|
return { ok: true, ...written };
|
|
509
520
|
} catch (e) {
|
|
510
521
|
return { ok: false, error: String(e?.message || e) };
|
package/lib/git/scan-runner.js
CHANGED
|
@@ -7,7 +7,7 @@
|
|
|
7
7
|
* 三要素:
|
|
8
8
|
* 1) spawn 独立进程跑 scripts/scan-repos.mjs(系统级后台,不卡宿主/主进程);
|
|
9
9
|
* 2) 进程每扫到一个 author(owner) 一致的仓库 → 增量写 scan-live.json
|
|
10
|
-
* (version 递增 + found 追加),并同步把该仓库并入 dsh-repo-index.
|
|
10
|
+
* (version 递增 + found 追加),并同步把该仓库并入 dsh-repo-index.jsonl;
|
|
11
11
|
* 3) 宿主用 fs.watchFile 监听 scan-live.json 变化,变化即唤醒 waiters——
|
|
12
12
|
* 前端「等待新版本」请求挂起,直到 version > 已见数或扫描结束才返回新增
|
|
13
13
|
* (非轮询:有新数据才返回,前端只追加变化部分,不全量重读)。
|
package/lib/git/transport.js
CHANGED
|
@@ -19,6 +19,7 @@ import { gitRaw, runGit, runGitAsync } from './exec.js';
|
|
|
19
19
|
import { resolveGithubRemote, parseGithubUrl } from './remote-resolve.js';
|
|
20
20
|
// 推送失败诊断(分类 + 置信度 + 下一步):把原文事实与推断分开返回
|
|
21
21
|
import { classifyPushFailure } from './push-diagnose.js';
|
|
22
|
+
import { cachedVisibility } from './visibility.js';
|
|
22
23
|
|
|
23
24
|
/* ───────── 推送通道常量 ───────── */
|
|
24
25
|
const COMMITS_FETCH_TIMEOUT_MS = 20_000; // 远端 commits 查询超时
|
|
@@ -74,12 +75,12 @@ export async function fetchRemoteHeads({ owner = '', repo = '', branch = '', tok
|
|
|
74
75
|
* @param {object} p { repoPath, branch?, token?, force?, pushMethod? }
|
|
75
76
|
* @returns {Promise<{ok, pushed, method?, reason?, fallbackReason?, key?, ...}>}
|
|
76
77
|
*/
|
|
77
|
-
export async function dispatchPush({ repoPath = '', branch = '', token = '', force = false, pushMethod = 'ssh' } = {}) {
|
|
78
|
+
export async function dispatchPush({ repoPath = '', branch = '', token = '', force = false, pushMethod = 'ssh', remote = '' } = {}) {
|
|
78
79
|
const mode = String(pushMethod || 'ssh').toLowerCase();
|
|
79
80
|
const hasKey = resolveSshKeys().length > 0;
|
|
80
81
|
|
|
81
|
-
const trySsh = () => pushViaSsh({ repoPath, branch, force });
|
|
82
|
-
const tryApi = () => pushViaApi({ repoPath, branch, token, force });
|
|
82
|
+
const trySsh = () => pushViaSsh({ repoPath, branch, force, remote });
|
|
83
|
+
const tryApi = () => pushViaApi({ repoPath, branch, token, force, remote });
|
|
83
84
|
|
|
84
85
|
if (mode === 'api') {
|
|
85
86
|
const apiRes = await tryApi();
|
|
@@ -100,7 +101,7 @@ export async function dispatchPush({ repoPath = '', branch = '', token = '', for
|
|
|
100
101
|
const localHead = runGit(['rev-parse', 'HEAD'], { cwd: repoPath }).stdout;
|
|
101
102
|
const cur = branch || runGit(['branch', '--show-current'], { cwd: repoPath }).stdout || 'master';
|
|
102
103
|
const cached = runGit(['rev-parse', `refs/remotes/origin/${cur}`], { cwd: repoPath }).stdout;
|
|
103
|
-
const live = liveRemoteHead({ repoPath, branch: cur });
|
|
104
|
+
const live = liveRemoteHead({ repoPath, branch: cur, remote });
|
|
104
105
|
const remoteHead = live.sha || cached || '';
|
|
105
106
|
return {
|
|
106
107
|
ok: false, pushed: false, method: 'ssh', diverged: true,
|
|
@@ -187,12 +188,17 @@ function buildLsRemoteSshCmd(keyPath, known, { mux = true } = {}) {
|
|
|
187
188
|
* origin 是 https 时本地 fetch 常失败,账号卡片会把「远端已前走」显示成「领先 N」。
|
|
188
189
|
* @returns {{ok:boolean, sha:string, via?:string}}
|
|
189
190
|
*/
|
|
190
|
-
export function liveRemoteHead({ repoPath = '', branch = '' } = {}) {
|
|
191
|
+
export function liveRemoteHead({ repoPath = '', branch = '', remote = '' } = {}) {
|
|
191
192
|
// 离线开关(单测/无外网)——直接失败,不触发 SSH/网络 ls-remote(防挂起)
|
|
192
193
|
if (process.env.DSH_GIT_PUSH_OFFLINE === '1') return { ok: false, sha: '', via: 'offline' };
|
|
193
|
-
// 自动指定正确的 remote(与推送同源判定:归属 + ssh:443 形态 +
|
|
194
|
+
// 自动指定正确的 remote(与推送同源判定:归属 + ssh:443 形态 + 名字优先级);
|
|
195
|
+
// 指定 remote 时以它为核验目标(与 pushViaSsh/pushViaApi 的 remote 同源)。
|
|
194
196
|
const rr = resolveGithubRemote({ repoPath });
|
|
195
|
-
|
|
197
|
+
let url = rr.ok && rr.url ? rr.url : '';
|
|
198
|
+
if (remote) {
|
|
199
|
+
url = String(runGit(['remote', 'get-url', remote], { cwd: repoPath }).stdout || '').trim() || url;
|
|
200
|
+
}
|
|
201
|
+
const pr = (url ? parseGithubUrl(url) : null)
|
|
196
202
|
|| parseGithubOwnerRepo(runGit(['remote', 'get-url', 'origin'], { cwd: repoPath }).stdout);
|
|
197
203
|
const target = branch || runGit(['branch', '--show-current'], { cwd: repoPath }).stdout;
|
|
198
204
|
if (!pr || !target) return { ok: false, sha: '' };
|
|
@@ -213,21 +219,38 @@ export function liveRemoteHead({ repoPath = '', branch = '' } = {}) {
|
|
|
213
219
|
if (sha) return { ok: true, sha, via: kind };
|
|
214
220
|
}
|
|
215
221
|
}
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
222
|
+
// 统一前置判断:私有库不试 origin(https) 回退——镜像/直连都看不到私有库,试了只会多一条失败。
|
|
223
|
+
// unknown 时保留回退(可能是公开库,https 直连/镜像仍有机会成功)。
|
|
224
|
+
if (cachedVisibility(repoPath) !== 'private') {
|
|
225
|
+
const lr = runGit(['ls-remote', rr.remote || 'origin', `${REFS_HEADS_PREFIX}${target}`], { cwd: repoPath, timeoutMs: LS_TIMEOUT });
|
|
226
|
+
if (lr.ok) {
|
|
227
|
+
const sha = (lr.stdout || '').trim().split(/\s+/)[0] || '';
|
|
228
|
+
if (sha) return { ok: true, sha, via: rr.remote || 'origin' };
|
|
229
|
+
}
|
|
220
230
|
}
|
|
221
231
|
return { ok: false, sha: '' };
|
|
222
232
|
}
|
|
223
233
|
|
|
224
234
|
/** SSH 回退:ssh.github.com:443(token 401 时)。force=true 时 --force(覆盖远端历史)。 */
|
|
225
|
-
|
|
235
|
+
/** 解析指定 remote 的目标(owner/repo);remote 不存在或不是 GitHub 地址返回 null。 */
|
|
236
|
+
export function resolveRemoteTarget(repoPath = '', remote = '') {
|
|
237
|
+
const url = String(runGit(['remote', 'get-url', remote], { cwd: repoPath }).stdout || '').trim();
|
|
238
|
+
if (!url) return null;
|
|
239
|
+
return parseGithubUrl(url) || parseGithubOwnerRepo(url) || null;
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
export function pushViaSsh({ repoPath = '', branch = '', force = false, remote = '' }) {
|
|
226
243
|
const keys = resolveSshKeys();
|
|
227
244
|
if (!keys.length) return { ok: false, pushed: false, reason: '无 SSH 私钥(配置目录 id_rsa/id_ed25519/id_ecdsa)' };
|
|
228
245
|
// 自动指定正确的 remote(归属 + 本机可用形态 ssh:443 + 名字优先级;必要时 set-url)——不再写死 origin
|
|
246
|
+
// 指定 remote 时以它为推送目标(多 remote / fork 场景),核验同源(liveRemoteHead 同参数)。
|
|
229
247
|
const rr = resolveGithubRemote({ repoPath });
|
|
230
|
-
|
|
248
|
+
let picked = rr.ok && rr.url ? parseGithubUrl(rr.url) : null;
|
|
249
|
+
if (remote) {
|
|
250
|
+
const byRemote = resolveRemoteTarget(repoPath, remote);
|
|
251
|
+
if (!byRemote) return { ok: false, pushed: false, reason: `指定的 remote「${remote}」不存在或不是 GitHub 地址` };
|
|
252
|
+
picked = byRemote;
|
|
253
|
+
}
|
|
231
254
|
const originUrl = runGit(['remote', 'get-url', 'origin'], { cwd: repoPath }).stdout;
|
|
232
255
|
const pr = picked || parseGithubOwnerRepo(originUrl);
|
|
233
256
|
if (!pr) {
|
|
@@ -276,10 +299,16 @@ async function apiOrFallback(api, repoPath, branch, res) {
|
|
|
276
299
|
* token 401 → pushViaSsh 回退。
|
|
277
300
|
* @returns {{ok, pushed, method?, commitSha?, reason?, branchAdjusted?}}
|
|
278
301
|
*/
|
|
279
|
-
export async function pushViaApi({ repoPath = '', branch = '', token = '', force = false } = {}) {
|
|
302
|
+
export async function pushViaApi({ repoPath = '', branch = '', token = '', force = false, remote = '' } = {}) {
|
|
280
303
|
const rr = resolveGithubRemote({ repoPath });
|
|
281
304
|
const origin = runGit(['remote', 'get-url', 'origin'], { cwd: repoPath }).stdout;
|
|
282
|
-
|
|
305
|
+
let pr = (rr.ok && rr.url ? parseGithubUrl(rr.url) : null) || parseGithubOwnerRepo(origin);
|
|
306
|
+
// 指定 remote 时以它为准(多 remote / fork 场景):推送目标与核验目标同源
|
|
307
|
+
if (remote) {
|
|
308
|
+
const remoteUrl = String(runGit(['remote', 'get-url', remote], { cwd: repoPath }).stdout || '').trim();
|
|
309
|
+
const byRemote = remoteUrl ? (parseGithubUrl(remoteUrl) || parseGithubOwnerRepo(remoteUrl)) : null;
|
|
310
|
+
if (byRemote) pr = byRemote;
|
|
311
|
+
}
|
|
283
312
|
if (!pr) {
|
|
284
313
|
return {
|
|
285
314
|
ok: false, pushed: false,
|
|
@@ -401,9 +430,12 @@ async function uploadBlobsAndBuildTree({ repoPath, entries, remoteBlobShas, api
|
|
|
401
430
|
* (ControlMaster)把 N 仓总耗时压到接近单仓。
|
|
402
431
|
* @returns {Promise<{ok:boolean, sha:string, via?:string}>}
|
|
403
432
|
*/
|
|
404
|
-
export async function liveRemoteHeadAsync({ repoPath = '', branch = '' } = {}) {
|
|
433
|
+
export async function liveRemoteHeadAsync({ repoPath = '', branch = '', remote = '' } = {}) {
|
|
405
434
|
if (process.env.DSH_GIT_PUSH_OFFLINE === '1') return { ok: false, sha: '', via: 'offline' };
|
|
406
|
-
|
|
435
|
+
// 指定 remote 时核验它(与推送同源);否则沿用 origin
|
|
436
|
+
const origin = remote
|
|
437
|
+
? (await runGitAsync(['remote', 'get-url', remote], { cwd: repoPath })).stdout
|
|
438
|
+
: (await runGitAsync(['remote', 'get-url', 'origin'], { cwd: repoPath })).stdout;
|
|
407
439
|
const pr = parseGithubOwnerRepo(origin);
|
|
408
440
|
const target = branch || (await runGitAsync(['branch', '--show-current'], { cwd: repoPath })).stdout;
|
|
409
441
|
if (!pr || !target) return { ok: false, sha: '' };
|
package/lib/git/visibility.js
CHANGED
|
@@ -3,32 +3,116 @@
|
|
|
3
3
|
// 抽出原因:同一职责(可见性判定)此前在
|
|
4
4
|
// push.js 与 commit-push.js 各写一份,违反「同一职责单一入口」的设计,故抽成独立模块。
|
|
5
5
|
//
|
|
6
|
-
//
|
|
6
|
+
// 为什么独立成模块:可见性判定有**多个消费方**,各自实现(`resolveToken` +
|
|
7
7
|
// `detectRepoVisibility` 两处复制)会造成口径漂移(token 来源、探测失败兜底不一致):
|
|
8
8
|
// ① `lib/git/push.js` —— 私有库敏感文件豁免(private → 只扫描报告、不写 .gitignore)
|
|
9
9
|
// ② `lib/commit-push.js` —— 审计门禁豁免(private → 审计只报告不拦截)
|
|
10
|
-
//
|
|
11
|
-
|
|
10
|
+
// ③ 克隆 / ls-remote 探针 / 推送核验 —— 私有库**不走第三方镜像**(见 accessPlan)
|
|
11
|
+
// 统一走本入口后,各消费方拿到同一形状、同一兜底口径。
|
|
12
|
+
import { detectRepoVisibility, parseGithubOwnerRepo, githubFetch } from './api.js';
|
|
12
13
|
import { resolveToken } from './credentials.js';
|
|
14
|
+
import { runGit } from '../core/exec.js';
|
|
13
15
|
|
|
14
|
-
//
|
|
16
|
+
// 可见性缓存:按 repoPath 键化,默认 5 分钟——避免每次 git 操作都多打一次 API
|
|
17
|
+
const cache = new Map();
|
|
18
|
+
const DEFAULT_TTL_MS = 5 * 60 * 1000;
|
|
19
|
+
|
|
20
|
+
/** 清空缓存(测试用,或凭据变化后强制重查)。 */
|
|
21
|
+
export function clearVisibilityCache() {
|
|
22
|
+
cache.clear();
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** 读缓存(同步;未命中返回 'unknown')。 */
|
|
26
|
+
export function cachedVisibility(repoPath = '') {
|
|
27
|
+
const hit = cache.get(repoPath);
|
|
28
|
+
return hit ? hit.value.visibility : 'unknown';
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* 访问计划:把可见性翻译成「走哪条通道」。
|
|
33
|
+
* public → 可以走镜像(gh-proxy 加速)
|
|
34
|
+
* private / unknown / 其他 → 不走镜像,改 SSH(本机 ssh.github.com:443 可用)
|
|
35
|
+
* 为什么 unknown 也当私有:镜像对私有库无意义(必然 404/认证失败),
|
|
36
|
+
* 而「失败后才发现」正是过去克隆失败、探针失明、核验未完成的根因。
|
|
37
|
+
* @returns {{visibility:string, useMirror:boolean, transport:'https'|'ssh'}}
|
|
38
|
+
*/
|
|
39
|
+
export function accessPlan(visibility = 'unknown') {
|
|
40
|
+
if (visibility === 'public') return { visibility, useMirror: true, transport: 'https' };
|
|
41
|
+
return { visibility, useMirror: false, transport: 'ssh' };
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** SSH 形态的仓库 URL(走 ssh.github.com:443,绕开本机不通的 github.com:443)。 */
|
|
45
|
+
export function sshGitUrl(owner = '', repo = '') {
|
|
46
|
+
return `ssh://git@ssh.github.com:443/${owner}/${repo}.git`;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** 从仓库路径解析 GitHub 坐标(解析不到返回 null)。 */
|
|
50
|
+
export function ownerRepoOf(repoPath = '') {
|
|
51
|
+
try {
|
|
52
|
+
const url = runGit(['remote', 'get-url', 'origin'], { cwd: repoPath }).stdout;
|
|
53
|
+
return parseGithubOwnerRepo(url);
|
|
54
|
+
} catch {
|
|
55
|
+
return null;
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* 按 owner/repo 判断可见性(克隆场景用:目标目录还是空的,没有 origin 可解析)。
|
|
61
|
+
* 与 resolveRepoVisibility 共用缓存(键前缀 gh: 区分)。
|
|
62
|
+
* @returns {Promise<{visibility:'private'|'public'|'unknown', owner?:string, repo?:string, reason?:string, cached?:boolean}>}
|
|
63
|
+
*/
|
|
64
|
+
export async function resolveOwnerVisibility({ owner = '', repo = '', token = '', ttlMs = DEFAULT_TTL_MS } = {}) {
|
|
65
|
+
if (!owner || !repo) return { visibility: 'unknown', reason: '缺少 owner/repo' };
|
|
66
|
+
const key = `gh:${owner}/${repo}`;
|
|
67
|
+
const hit = cache.get(key);
|
|
68
|
+
if (hit && Date.now() - hit.at < ttlMs) return { ...hit.value, cached: true };
|
|
69
|
+
|
|
70
|
+
let tok = token;
|
|
71
|
+
if (!tok) {
|
|
72
|
+
try { tok = resolveToken({}).token; } catch { tok = ''; }
|
|
73
|
+
}
|
|
74
|
+
if (!tok) return { visibility: 'unknown', reason: '无可用 token' };
|
|
75
|
+
try {
|
|
76
|
+
const r = await githubFetch(`/repos/${owner}/${repo}`, { token: tok, timeout: 10_000 });
|
|
77
|
+
if (r.status === 200) {
|
|
78
|
+
const j = r.json || {};
|
|
79
|
+
const value = { visibility: j.private ? 'private' : 'public', owner, repo };
|
|
80
|
+
cache.set(key, { value, at: Date.now() });
|
|
81
|
+
return value;
|
|
82
|
+
}
|
|
83
|
+
// 404:GitHub 对「私有但无权限」与「不存在」返回同一个码 ⇒ 按私有处理(不走镜像更安全)
|
|
84
|
+
const value = { visibility: r.status === 404 ? 'private' : 'unknown', owner, repo, reason: `API ${r.status}` };
|
|
85
|
+
if (r.status === 404) cache.set(key, { value, at: Date.now() });
|
|
86
|
+
return value;
|
|
87
|
+
} catch (e) {
|
|
88
|
+
return { visibility: 'unknown', reason: String((e && e.message) || e) };
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
// 解析仓库远端可见性(统一收口,带缓存)。
|
|
15
93
|
//
|
|
16
94
|
// 兜底口径:token 缺失 / 非 GitHub origin / API 失败 → 一律 `unknown`
|
|
17
|
-
// (调用方对 unknown 按保守处理:push
|
|
95
|
+
// (调用方对 unknown 按保守处理:push 不豁免、审计门禁仍拦截、不走镜像)。
|
|
18
96
|
// 边界:resolveToken 自身抛错也吞成「无 token」(探测失败不该中断调用方流程)。
|
|
19
97
|
//
|
|
20
98
|
// @param {string} repoPath 仓库绝对路径
|
|
21
99
|
// @param {string} [token] 显式 token(缺省按仓库解析:仓库 token 文件 → 插件配置)
|
|
22
|
-
// @
|
|
23
|
-
//
|
|
24
|
-
export async function resolveRepoVisibility(repoPath, token = '') {
|
|
100
|
+
// @param {{ttlMs?:number}} [opts] 缓存有效期
|
|
101
|
+
// @returns {Promise<{visibility: 'private'|'public'|'unknown', owner?: string, repo?: string, reason?: string, cached?: boolean}>}
|
|
102
|
+
export async function resolveRepoVisibility(repoPath, token = '', { ttlMs = DEFAULT_TTL_MS } = {}) {
|
|
103
|
+
const hit = cache.get(repoPath);
|
|
104
|
+
if (hit && Date.now() - hit.at < ttlMs) return { ...hit.value, cached: true };
|
|
105
|
+
|
|
25
106
|
let tok = token;
|
|
26
107
|
if (!tok) {
|
|
27
108
|
try { tok = resolveToken({ repoPath }).token; } catch { tok = ''; }
|
|
28
109
|
}
|
|
29
110
|
if (!tok) return { visibility: 'unknown', reason: '无可用 token' };
|
|
30
111
|
try {
|
|
31
|
-
|
|
112
|
+
const r = await detectRepoVisibility({ repoPath, token: tok });
|
|
113
|
+
// 只缓存确定结果:unknown 可能是临时网络失败,缓存它会让后续操作一直走 SSH
|
|
114
|
+
if (r.visibility !== 'unknown') cache.set(repoPath, { value: r, at: Date.now() });
|
|
115
|
+
return r;
|
|
32
116
|
} catch (e) {
|
|
33
117
|
return { visibility: 'unknown', reason: String((e && e.message) || e) };
|
|
34
118
|
}
|
package/lib/npm/publish.js
CHANGED
|
@@ -16,6 +16,14 @@ import { npmArgs, writeNpmrc } from './npmrc.js';
|
|
|
16
16
|
|
|
17
17
|
export const PUBLISH_LOG_FILE = 'npm-publish.log';
|
|
18
18
|
export const PUBLISH_TIMEOUT_MS = 300_000;
|
|
19
|
+
/** 真发后轮询 registry 确认版本可见:每分钟 1 次、最多 5 次(远端更新即返回,超时输出原结果)。 */
|
|
20
|
+
export const PUBLISH_POLL_MAX = 5;
|
|
21
|
+
export const PUBLISH_POLL_INTERVAL_MS = 60_000;
|
|
22
|
+
|
|
23
|
+
/** 等待(轮询间隔)。 */
|
|
24
|
+
function sleep(ms) {
|
|
25
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
26
|
+
}
|
|
19
27
|
/** tag 白名单(防把非法值透传给 npm)。 */
|
|
20
28
|
export const PUBLISH_TAGS = ['latest', 'beta', 'next', 'alpha', 'rc', 'dev', 'canary'];
|
|
21
29
|
|
|
@@ -109,6 +117,8 @@ function appendPublishLog(line, { workspaceRoot = '' } = {}) {
|
|
|
109
117
|
export async function publishPackage({
|
|
110
118
|
dir = '', registry = DEFAULT_REGISTRY, workspaceRoot = '',
|
|
111
119
|
dryRun = true, tag = 'latest', otp = '', confirm = false, timeoutMs = PUBLISH_TIMEOUT_MS,
|
|
120
|
+
// 可选:发布成功后等待 registry 可见。默认 false —— 上传成功即为成功(可见延迟是已知现象)
|
|
121
|
+
waitVisible = false,
|
|
112
122
|
} = {}) {
|
|
113
123
|
const info = readPackageInfo(dir);
|
|
114
124
|
if (!info.ok) return { ok: false, error: info.error };
|
|
@@ -148,6 +158,20 @@ export async function publishPackage({
|
|
|
148
158
|
// 否则会去发布宿主 cwd 下的包(或不存在的包)—— 这是发包类操作里最危险的一种错。
|
|
149
159
|
const r = runNpm(args, { timeoutMs, env: { NO_UPDATE_NOTIFIER: '1' }, cwd: info.dir });
|
|
150
160
|
appendPublishLog(`publish END dryRun=${dryRun} ok=${r.ok} code=${r.code} err=${String(r.error || '').slice(0, 200)}`, { workspaceRoot });
|
|
161
|
+
// 成功判定 = npm publish 上传成功(返回码 0),不看 registry 是否已可见——
|
|
162
|
+
// 发布后 registry 可见常有几分钟延迟(已知现象,不是失败)。
|
|
163
|
+
// 轮询只作**附加信息**:若提前可见就记 visible=true,让调用方知道「已可安装」。
|
|
164
|
+
let visible = false;
|
|
165
|
+
let polled = 0;
|
|
166
|
+
if (r.ok && !dryRun && waitVisible) {
|
|
167
|
+
for (let i = 0; i < PUBLISH_POLL_MAX; i += 1) {
|
|
168
|
+
await sleep(PUBLISH_POLL_INTERVAL_MS);
|
|
169
|
+
polled += 1;
|
|
170
|
+
const now = await fetchPublishedVersions({ name: info.name, registry: reg, timeoutMs: NPM_TIMEOUT_MS });
|
|
171
|
+
if (now.ok && now.versions.includes(info.version)) { visible = true; break; }
|
|
172
|
+
}
|
|
173
|
+
appendPublishLog(`publish POLL visible=${visible} polled=${polled}`, { workspaceRoot });
|
|
174
|
+
}
|
|
151
175
|
return {
|
|
152
176
|
ok: !!r.ok,
|
|
153
177
|
dryRun: !!dryRun,
|
|
@@ -158,7 +182,12 @@ export async function publishPackage({
|
|
|
158
182
|
packList: pack.files,
|
|
159
183
|
packSize: pack.size,
|
|
160
184
|
tarball: pack.filename,
|
|
161
|
-
published: !dryRun && !!r.ok,
|
|
185
|
+
published: !dryRun && !!r.ok, // 成功判定:npm 上传成功即为成功(不要求 registry 已可见)
|
|
186
|
+
// 附加信息(不影响 published):registry 是否已能看到新版本;发布延迟(几分钟)是已知现象
|
|
187
|
+
visible,
|
|
188
|
+
polled,
|
|
189
|
+
visibleNote: visible ? 'registry 已可见'
|
|
190
|
+
: (waitVisible ? 'registry 暂未可见(发布延迟属正常,不是失败)' : '发布成功(registry 可见可能有几分钟延迟,属正常现象)'),
|
|
162
191
|
registryQuery: { ok: pub.ok, error: pub.error || '' },
|
|
163
192
|
stdout: String(r.stdout || '').slice(-4000),
|
|
164
193
|
stderr: String(r.stderr || '').slice(-4000),
|