@capyclaw/publisher 0.1.0 → 0.1.4
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 +77 -2
- package/client/client.js +717 -0
- package/cordis.patch.yml +4 -15
- package/icon.svg +6 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +26 -14
- package/plugin.mjs +113 -0
- package/server/archive.mjs +289 -0
- package/server/drop.mjs +504 -0
- package/server/impl.mjs +269 -87
- package/server/routes.mjs +339 -0
- package/server/tools.mjs +1 -1
- package/lib/host.mjs +0 -27
- package/server/relay.mjs +0 -70
package/server/drop.mjs
ADDED
|
@@ -0,0 +1,504 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 拖拽发布引擎:压缩包 → 解包目录 → 版本规划 → npm publish。
|
|
3
|
+
*
|
|
4
|
+
* 与 impl.mjs 的分工:impl.mjs 面向「仓库工作区」,按发现集批量发布,负责闸门/顺序/漂移;
|
|
5
|
+
* 这里面向「一个从浏览器拖进来的包」,只有一条路径:预检 → 定版本 → 发布 → 复核。
|
|
6
|
+
* 复数实现(release CLI)不重复:发布闸、密钥扫描直接复用 impl.mjs 的导出。
|
|
7
|
+
*/
|
|
8
|
+
import fs from 'node:fs'
|
|
9
|
+
import path from 'node:path'
|
|
10
|
+
import { spawn } from 'node:child_process'
|
|
11
|
+
|
|
12
|
+
import { publishGateErrors } from './impl.mjs'
|
|
13
|
+
import { inspectArchive, materialize, storeRoot, unpack } from './archive.mjs'
|
|
14
|
+
|
|
15
|
+
export const MAX_ARCHIVE_BYTES = 32 * 1024 * 1024
|
|
16
|
+
export const MAX_ENTRIES = 4096
|
|
17
|
+
|
|
18
|
+
const NPM_CLI = path.join(path.dirname(process.execPath), 'node_modules', 'npm', 'bin', 'npm-cli.js')
|
|
19
|
+
const SEMVER_RE = /^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/
|
|
20
|
+
|
|
21
|
+
/* 密钥扫描:只扫「作者自己的文件」,跳过 node_modules 与 .git。
|
|
22
|
+
* dist 产物里带着 139 个第三方包,扫它们既慢又会把别人的测试夹具当成本包泄漏。 */
|
|
23
|
+
const SECRET_PATTERNS = [
|
|
24
|
+
[/sk-[A-Za-z0-9]{20,}/, 'API key 形态(sk-…)'],
|
|
25
|
+
[/npm_[A-Za-z0-9]{20,}/, 'npm token 形态(npm_…)'],
|
|
26
|
+
[new RegExp('_auth' + 'Token', 'i'), 'npmrc 认证令牌字段'],
|
|
27
|
+
[/[A-Za-z]:\\Users\\/i, '本机绝对路径(盘符 \\Users\\)'],
|
|
28
|
+
[/\/(home|Users)\/[A-Za-z0-9._-]+\//, '本机绝对路径(/home/ 或 /Users/)'],
|
|
29
|
+
]
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* 跑一次 npm(异步);优先用当前 Node 自带的 npm-cli.js,找不到再退回 PATH 上的 npm。
|
|
33
|
+
*
|
|
34
|
+
* 必须是异步的:npm 一次调用要几百毫秒起步,网络差时能挂十几秒。用 spawnSync 会把宿主
|
|
35
|
+
* 整个事件循环钉住——插件页、聊天流、健康探活全部一起卡死。超时会杀掉子进程,返回
|
|
36
|
+
* status -2,调用方按普通失败处理。
|
|
37
|
+
*/
|
|
38
|
+
export function npmRun(args, options = {}) {
|
|
39
|
+
const { timeout = 180000, cwd, env } = options
|
|
40
|
+
const command = fs.existsSync(NPM_CLI)
|
|
41
|
+
? { file: process.execPath, args: [NPM_CLI, ...args], shell: false }
|
|
42
|
+
: { file: 'npm', args, shell: process.platform === 'win32' }
|
|
43
|
+
|
|
44
|
+
return new Promise((resolve) => {
|
|
45
|
+
let stdout = ''
|
|
46
|
+
let stderr = ''
|
|
47
|
+
let settled = false
|
|
48
|
+
let timer = null
|
|
49
|
+
let child = null
|
|
50
|
+
|
|
51
|
+
const finish = (status) => {
|
|
52
|
+
if (settled) return
|
|
53
|
+
settled = true
|
|
54
|
+
if (timer) clearTimeout(timer)
|
|
55
|
+
resolve({ status, stdout, stderr })
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
try {
|
|
59
|
+
child = spawn(command.file, command.args, {
|
|
60
|
+
cwd,
|
|
61
|
+
env: { ...process.env, ...env },
|
|
62
|
+
shell: command.shell,
|
|
63
|
+
windowsHide: true,
|
|
64
|
+
stdio: ['ignore', 'pipe', 'pipe'],
|
|
65
|
+
})
|
|
66
|
+
} catch (error) {
|
|
67
|
+
/* 先赋值再 finish:finish 会立刻 resolve Promise,后赋值 stderr 就丢了。 */
|
|
68
|
+
stderr = messageOf(error)
|
|
69
|
+
finish(-1)
|
|
70
|
+
return
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
child.stdout?.setEncoding('utf8')
|
|
74
|
+
child.stderr?.setEncoding('utf8')
|
|
75
|
+
child.stdout?.on('data', (chunk) => { stdout += chunk })
|
|
76
|
+
child.stderr?.on('data', (chunk) => { stderr += chunk })
|
|
77
|
+
child.on('error', (error) => {
|
|
78
|
+
stderr += messageOf(error)
|
|
79
|
+
finish(-1)
|
|
80
|
+
})
|
|
81
|
+
child.on('close', (code) => finish(typeof code === 'number' ? code : -1))
|
|
82
|
+
|
|
83
|
+
timer = setTimeout(() => {
|
|
84
|
+
stderr += `npm 调用超过 ${Math.round(timeout / 1000)}s,已终止。`
|
|
85
|
+
try { child.kill() } catch { /* 已经退出 */ }
|
|
86
|
+
finish(-2)
|
|
87
|
+
}, timeout)
|
|
88
|
+
})
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/* 与 routes.mjs 的 messageOf 同形:spawn 同步抛错与 child 'error' 事件都要用它。 */
|
|
92
|
+
function messageOf(error) {
|
|
93
|
+
return error instanceof Error ? error.message : String(error)
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
const delay = (ms) => new Promise((resolve) => { setTimeout(resolve, ms) })
|
|
97
|
+
|
|
98
|
+
// ---------------------------------------------------------------------------
|
|
99
|
+
// 版本
|
|
100
|
+
// ---------------------------------------------------------------------------
|
|
101
|
+
|
|
102
|
+
/** 解析 x.y.z[-pre];非严格语义版本返回 null(预发布段不比较,直接按需升 patch)。 */
|
|
103
|
+
export function parseVersion(value) {
|
|
104
|
+
const match = SEMVER_RE.exec(String(value || '').trim())
|
|
105
|
+
if (!match) return null
|
|
106
|
+
return {
|
|
107
|
+
major: Number(match[1]),
|
|
108
|
+
minor: Number(match[2]),
|
|
109
|
+
patch: Number(match[3]),
|
|
110
|
+
prerelease: match[4] || '',
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** 只比较 x.y.z 三段;预发布段不参与(发布场景只需要「谁更新」)。 */
|
|
115
|
+
export function compareVersions(left, right) {
|
|
116
|
+
const a = parseVersion(left)
|
|
117
|
+
const b = parseVersion(right)
|
|
118
|
+
if (!a || !b) return 0
|
|
119
|
+
for (const key of ['major', 'minor', 'patch']) {
|
|
120
|
+
if (a[key] !== b[key]) return a[key] > b[key] ? 1 : -1
|
|
121
|
+
}
|
|
122
|
+
return 0
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/** 补丁位 +1 并丢掉预发布段:0.1.1 → 0.1.2,1.0.0-rc.1 → 1.0.1。 */
|
|
126
|
+
export function bumpPatch(version) {
|
|
127
|
+
const parsed = parseVersion(version)
|
|
128
|
+
if (!parsed) throw new Error(`无法递增版本:${version} 不是 x.y.z 形态。`)
|
|
129
|
+
return `${parsed.major}.${parsed.minor}.${parsed.patch + 1}`
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
export function maxVersion(versions) {
|
|
133
|
+
let best = null
|
|
134
|
+
for (const version of versions) {
|
|
135
|
+
if (!parseVersion(version)) continue
|
|
136
|
+
if (!best || compareVersions(version, best) > 0) best = version
|
|
137
|
+
}
|
|
138
|
+
return best
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/**
|
|
142
|
+
* 本次要发布的版本。
|
|
143
|
+
* first —— npm 上还没有这个包:按包内版本直接发
|
|
144
|
+
* ahead —— 包内版本已经比 npm 最新版更新:按包内版本发
|
|
145
|
+
* bump —— 包内版本 ≤ npm 最新版(重复发布同一版本会被 npm 拒):latest 的 patch + 1
|
|
146
|
+
*/
|
|
147
|
+
export function planVersion(manifestVersion, published) {
|
|
148
|
+
const versions = Array.isArray(published?.versions) ? published.versions : []
|
|
149
|
+
const latest = published?.latest || maxVersion(versions)
|
|
150
|
+
if (versions.length === 0) return { mode: 'first', version: manifestVersion, latest: null }
|
|
151
|
+
if (compareVersions(manifestVersion, latest) > 0) return { mode: 'ahead', version: manifestVersion, latest }
|
|
152
|
+
return { mode: 'bump', version: bumpPatch(latest), latest }
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/**
|
|
156
|
+
* registry 版本查询缓存。
|
|
157
|
+
*
|
|
158
|
+
* 一次「拖入 → 预检 → 发布」会两次问 npm(prepare 里规划版本,publish 前重跑闸门),
|
|
159
|
+
* 每次 `npm view` 在 Windows 上要 1–3 秒。缓存 15 秒既让第二次几乎瞬回,又短到
|
|
160
|
+
* 不会把「刚发的版本」藏住;发布成功与失败都会主动失效该包。
|
|
161
|
+
*/
|
|
162
|
+
const PUBLISHED_TTL_MS = 15000
|
|
163
|
+
const publishedCache = new Map()
|
|
164
|
+
|
|
165
|
+
/** 清掉某个包(或全部)的版本缓存;发布前后各调一次。 */
|
|
166
|
+
export function forgetPublished(name) {
|
|
167
|
+
if (name) publishedCache.delete(name)
|
|
168
|
+
else publishedCache.clear()
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/** 读 npm 上的版本集合;包不存在不算错误(第一次发布)。 */
|
|
172
|
+
export async function readPublished(name, { timeout = 60000, npm = npmRun, cacheTtlMs = PUBLISHED_TTL_MS } = {}) {
|
|
173
|
+
const cached = publishedCache.get(name)
|
|
174
|
+
if (cached && Date.now() - cached.at < cacheTtlMs) return cached.value
|
|
175
|
+
|
|
176
|
+
const value = await queryPublished(name, { timeout, npm })
|
|
177
|
+
if (value.ok) publishedCache.set(name, { at: Date.now(), value })
|
|
178
|
+
return value
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
async function queryPublished(name, { timeout, npm }) {
|
|
182
|
+
const result = await npm(['view', name, 'versions', 'dist-tags', '--json'], { timeout })
|
|
183
|
+
if (result.status === 0) {
|
|
184
|
+
try {
|
|
185
|
+
const parsed = JSON.parse(String(result.stdout || '{}'))
|
|
186
|
+
const versions = Array.isArray(parsed?.versions)
|
|
187
|
+
? parsed.versions
|
|
188
|
+
: parsed?.versions
|
|
189
|
+
? [parsed.versions]
|
|
190
|
+
: []
|
|
191
|
+
const latest = parsed?.['dist-tags']?.latest || null
|
|
192
|
+
return { ok: true, found: true, versions, latest }
|
|
193
|
+
} catch {
|
|
194
|
+
return { ok: false, found: false, versions: [], latest: null, message: 'npm view 输出不可解析。' }
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
const stderr = String(result.stderr || result.stdout || '')
|
|
198
|
+
if (/E404|404 Not Found|is not in this registry/i.test(stderr)) {
|
|
199
|
+
return { ok: true, found: false, versions: [], latest: null }
|
|
200
|
+
}
|
|
201
|
+
return { ok: false, found: false, versions: [], latest: null, message: firstLine(stderr) }
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
// ---------------------------------------------------------------------------
|
|
205
|
+
// staging
|
|
206
|
+
// ---------------------------------------------------------------------------
|
|
207
|
+
|
|
208
|
+
/** 上传字节 → 解包 → 落到本机 staging,返回包目录与事实。 */
|
|
209
|
+
export async function stageUpload(buffer, filename) {
|
|
210
|
+
const entries = unpack(buffer, filename)
|
|
211
|
+
if (entries.length === 0) throw new Error('压缩包里没有任何文件。')
|
|
212
|
+
if (entries.length > MAX_ENTRIES) {
|
|
213
|
+
throw new Error(`压缩包里的文件太多(${entries.length} 个),上限 ${MAX_ENTRIES}。`)
|
|
214
|
+
}
|
|
215
|
+
const fact = inspectArchive(entries)
|
|
216
|
+
const dir = await materialize(entries, fact.dir)
|
|
217
|
+
try {
|
|
218
|
+
/* package.json 能解析、能读出来,才算一次成功的 prepare;
|
|
219
|
+
* 读失败就地回收,否则 staging 会变成一个没人认领的目录。 */
|
|
220
|
+
return { dir, entries, manifest: readManifest(dir), name: fact.name }
|
|
221
|
+
} catch (error) {
|
|
222
|
+
cleanupStage({ dir })
|
|
223
|
+
throw error
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
export function readManifest(dir) {
|
|
228
|
+
const file = path.join(dir, 'package.json')
|
|
229
|
+
if (!fs.existsSync(file)) throw new Error('解包后找不到 package.json。')
|
|
230
|
+
return JSON.parse(fs.readFileSync(file, 'utf8'))
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
/** 读 staging 目录的事实与预检结果(不改文件)。 */
|
|
234
|
+
export async function previewStage(stage, { npm = npmRun, cacheTtlMs } = {}) {
|
|
235
|
+
const pkg = readManifest(stage.dir)
|
|
236
|
+
const published = await readPublished(pkg.name, cacheTtlMs === undefined ? { npm } : { npm, cacheTtlMs })
|
|
237
|
+
if (!published.ok) {
|
|
238
|
+
return {
|
|
239
|
+
ok: false,
|
|
240
|
+
error: 'registry-unreachable',
|
|
241
|
+
message: `读不到 npm 上 ${pkg.name} 的版本:${published.message || '未知错误'}`,
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
const plan = planVersion(String(pkg.version || ''), published)
|
|
246
|
+
const blocking = publishGateErrors(pkg, stage.dir)
|
|
247
|
+
const warnings = []
|
|
248
|
+
|
|
249
|
+
if (plan.mode === 'bump') {
|
|
250
|
+
warnings.push(`包内版本 ${pkg.version} 与 npm 最新版相同或更旧,本次按 ${plan.version} 发布(patch +1)。`)
|
|
251
|
+
}
|
|
252
|
+
if (compareVersions(plan.version, published.latest || '0.0.0') <= 0 && plan.mode !== 'first') {
|
|
253
|
+
blocking.push(`目标版本 ${plan.version} 不高于 npm 最新版 ${published.latest},npm 会拒绝重复发布。`)
|
|
254
|
+
}
|
|
255
|
+
const hasNodeModules = fs.existsSync(path.join(stage.dir, 'node_modules'))
|
|
256
|
+
if (!hasNodeModules && pkg.dependencies && Object.keys(pkg.dependencies).length > 0) {
|
|
257
|
+
warnings.push('压缩包里没有 node_modules:发布后使用方安装时会从 registry 解析依赖(不是自包含产物)。')
|
|
258
|
+
}
|
|
259
|
+
for (const hit of scanOwnFiles(stage.dir)) blocking.push(`疑似密钥/本机信息:${hit}`)
|
|
260
|
+
|
|
261
|
+
return {
|
|
262
|
+
ok: true,
|
|
263
|
+
token: stage.token,
|
|
264
|
+
name: pkg.name,
|
|
265
|
+
version: String(pkg.version || ''),
|
|
266
|
+
plan,
|
|
267
|
+
latest: published.latest || null,
|
|
268
|
+
versions: published.versions.length,
|
|
269
|
+
files: stage.entries.filter((entry) => !entry.dir).length,
|
|
270
|
+
private: pkg.private === true,
|
|
271
|
+
hasNodeModules,
|
|
272
|
+
blocking,
|
|
273
|
+
warnings,
|
|
274
|
+
description: typeof pkg.description === 'string' ? pkg.description : '',
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
/**
|
|
279
|
+
* 落地并规划:浏览器一次拖拽 = 一次 prepare。
|
|
280
|
+
* token 是后续 publish 的唯一句柄,客户端不需要知道本机路径。
|
|
281
|
+
*/
|
|
282
|
+
export async function prepareUpload({ token, buffer, filename }, { npm = npmRun, cacheTtlMs } = {}) {
|
|
283
|
+
const stage = await stageUpload(buffer, filename)
|
|
284
|
+
stage.token = token
|
|
285
|
+
try {
|
|
286
|
+
const preview = await previewStage(stage, cacheTtlMs === undefined ? { npm } : { npm, cacheTtlMs })
|
|
287
|
+
return { stage, preview }
|
|
288
|
+
} catch (error) {
|
|
289
|
+
cleanupStage(stage)
|
|
290
|
+
throw error
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
/** 写回目标版本(只改 version 字段,保留其余字段与缩进风格)。 */
|
|
295
|
+
export function applyVersion(dir, version) {
|
|
296
|
+
const pkg = readManifest(dir)
|
|
297
|
+
pkg.version = version
|
|
298
|
+
fs.writeFileSync(path.join(dir, 'package.json'), `${JSON.stringify(pkg, null, 2)}\n`, 'utf8')
|
|
299
|
+
return pkg
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
/**
|
|
303
|
+
* 真发布:写版本 → npm publish → 回读 registry 复核。
|
|
304
|
+
* 不可撤销,所以任何一步失败都原样带回 npm 的 stderr 尾巴。
|
|
305
|
+
*/
|
|
306
|
+
export async function publishStage(stage, {
|
|
307
|
+
version, tag = 'latest', dryRun = false, npm = npmRun, verifyAttempts = 10, verifyDelayMs = 1500,
|
|
308
|
+
} = {}) {
|
|
309
|
+
const pkg = applyVersion(stage.dir, version)
|
|
310
|
+
forgetPublished(pkg.name)
|
|
311
|
+
const args = ['publish', '--tag', tag, '--json']
|
|
312
|
+
if (String(pkg.name).startsWith('@') || pkg.publishConfig?.access) args.push('--access', pkg.publishConfig?.access || 'public')
|
|
313
|
+
if (dryRun) args.push('--dry-run')
|
|
314
|
+
|
|
315
|
+
const startedAt = Date.now()
|
|
316
|
+
const result = await npm(args, { cwd: stage.dir })
|
|
317
|
+
if (result.status !== 0) {
|
|
318
|
+
const raw = String(result.stderr || result.stdout || '')
|
|
319
|
+
const friendly = friendlyNpmFailure(raw)
|
|
320
|
+
return {
|
|
321
|
+
ok: false,
|
|
322
|
+
error: dryRun ? 'dry-run-failed' : (friendly?.error || 'publish-failed'),
|
|
323
|
+
message: friendly?.message || firstLine(raw) || `npm publish 退出码 ${result.status}`,
|
|
324
|
+
detail: tailLines(raw, 12),
|
|
325
|
+
elapsedMs: Date.now() - startedAt,
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
if (dryRun) {
|
|
330
|
+
return {
|
|
331
|
+
ok: true,
|
|
332
|
+
dryRun: true,
|
|
333
|
+
name: pkg.name,
|
|
334
|
+
version,
|
|
335
|
+
tag,
|
|
336
|
+
elapsedMs: Date.now() - startedAt,
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
for (let attempt = 0; attempt < verifyAttempts; attempt += 1) {
|
|
341
|
+
const check = await npm(['view', `${pkg.name}@${version}`, 'version'], { timeout: 30000 })
|
|
342
|
+
/* 精确匹配:startsWith 会把 1.0.10 当成 1.0.1 回读成功(与 impl.mjs alreadyPublished 同形)。 */
|
|
343
|
+
if (check.status === 0 && String(check.stdout).trim() === version) {
|
|
344
|
+
forgetPublished(pkg.name)
|
|
345
|
+
return {
|
|
346
|
+
ok: true,
|
|
347
|
+
name: pkg.name,
|
|
348
|
+
version,
|
|
349
|
+
tag,
|
|
350
|
+
verified: true,
|
|
351
|
+
url: `https://www.npmjs.com/package/${pkg.name}/v/${version}`,
|
|
352
|
+
elapsedMs: Date.now() - startedAt,
|
|
353
|
+
}
|
|
354
|
+
}
|
|
355
|
+
await delay(verifyDelayMs)
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
/*
|
|
359
|
+
* npm 退出码 0 = registry 已经收下这个 tarball。回读只是「顺手复核」,
|
|
360
|
+
* 节点同步慢时查不到并不代表发布失败——所以这里报成功 + 未核实,别吓用户。
|
|
361
|
+
*/
|
|
362
|
+
forgetPublished(pkg.name)
|
|
363
|
+
return {
|
|
364
|
+
ok: true,
|
|
365
|
+
name: pkg.name,
|
|
366
|
+
version,
|
|
367
|
+
tag,
|
|
368
|
+
verified: false,
|
|
369
|
+
url: `https://www.npmjs.com/package/${pkg.name}/v/${version}`,
|
|
370
|
+
warning: `${pkg.name}@${version} 已提交发布,但 registry 暂时还查不到(同步通常要几十秒)。稍后用 npm view 复核即可。`,
|
|
371
|
+
elapsedMs: Date.now() - startedAt,
|
|
372
|
+
}
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
/**
|
|
376
|
+
* 发布完成(成功或彻底失败)后回收 staging 目录。
|
|
377
|
+
*
|
|
378
|
+
* 包目录可能只是 staging 的子目录(压缩包里带一层 `pkg/` 时就是这样),
|
|
379
|
+
* 所以这里删的是「staging 根下那一次上传」而不是包目录本身,否则时间戳目录会留下来。
|
|
380
|
+
*/
|
|
381
|
+
export function cleanupStage(stage) {
|
|
382
|
+
const target = stage?.base || stageBaseOf(stage?.dir)
|
|
383
|
+
if (!target) return
|
|
384
|
+
try {
|
|
385
|
+
fs.rmSync(target, { recursive: true, force: true })
|
|
386
|
+
} catch { /* 回收失败不影响结论 */ }
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
/** 沿着 dir 往上找,直到父目录就是 staging 根;返回那一次上传的目录。 */
|
|
390
|
+
function stageBaseOf(dir) {
|
|
391
|
+
if (!dir) return null
|
|
392
|
+
const root = path.resolve(storeRoot())
|
|
393
|
+
let current = path.resolve(dir)
|
|
394
|
+
if (current !== root && !current.startsWith(root + path.sep)) return current
|
|
395
|
+
while (current !== root && path.dirname(current) !== root) {
|
|
396
|
+
const parent = path.dirname(current)
|
|
397
|
+
if (parent === current) break
|
|
398
|
+
current = parent
|
|
399
|
+
}
|
|
400
|
+
return current === root ? null : current
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
/**
|
|
404
|
+
* 回收「进程里已经没有记录」的 staging 目录。
|
|
405
|
+
*
|
|
406
|
+
* 崩溃或重启之后 stages 这张表是空的,磁盘上那些时间戳目录就再也没人认领,
|
|
407
|
+
* 会一直堆在 %LOCALAPPDATA%\capyclaw-publisher\drop 里。这里按目录 mtime 判断年龄,
|
|
408
|
+
* 只删超过 ttl 且不在 keep 列表里的。
|
|
409
|
+
*/
|
|
410
|
+
export async function sweepOrphans(keep = new Set(), ttlMs = 2 * 60 * 60 * 1000) {
|
|
411
|
+
const root = path.resolve(storeRoot())
|
|
412
|
+
const keepSet = new Set([...keep].map((item) => path.resolve(item)))
|
|
413
|
+
let names
|
|
414
|
+
try {
|
|
415
|
+
names = await fs.promises.readdir(root)
|
|
416
|
+
} catch {
|
|
417
|
+
return 0
|
|
418
|
+
}
|
|
419
|
+
const cutoff = Date.now() - ttlMs
|
|
420
|
+
let removed = 0
|
|
421
|
+
for (const name of names) {
|
|
422
|
+
const full = path.join(root, name)
|
|
423
|
+
if (keepSet.has(full)) continue
|
|
424
|
+
let stat
|
|
425
|
+
try {
|
|
426
|
+
stat = await fs.promises.stat(full)
|
|
427
|
+
} catch {
|
|
428
|
+
continue
|
|
429
|
+
}
|
|
430
|
+
if (stat.mtimeMs > cutoff) continue
|
|
431
|
+
try {
|
|
432
|
+
await fs.promises.rm(full, { recursive: true, force: true })
|
|
433
|
+
removed += 1
|
|
434
|
+
} catch { /* 删不掉就算了,下次再说 */ }
|
|
435
|
+
}
|
|
436
|
+
return removed
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
function scanOwnFiles(root) {
|
|
440
|
+
const hits = []
|
|
441
|
+
const skip = new Set(['node_modules', '.git'])
|
|
442
|
+
const walk = (dir, depth) => {
|
|
443
|
+
if (depth > 8) return
|
|
444
|
+
let entries = []
|
|
445
|
+
try { entries = fs.readdirSync(dir, { withFileTypes: true }) } catch { return }
|
|
446
|
+
for (const entry of entries) {
|
|
447
|
+
if (entry.isDirectory()) {
|
|
448
|
+
if (skip.has(entry.name)) continue
|
|
449
|
+
walk(path.join(dir, entry.name), depth + 1)
|
|
450
|
+
continue
|
|
451
|
+
}
|
|
452
|
+
const file = path.join(dir, entry.name)
|
|
453
|
+
let text = null
|
|
454
|
+
try { text = fs.readFileSync(file, 'utf8') } catch { continue }
|
|
455
|
+
for (const [pattern, label] of SECRET_PATTERNS) {
|
|
456
|
+
if (pattern.test(text)) hits.push(`${path.relative(root, file)}: ${label}`)
|
|
457
|
+
}
|
|
458
|
+
}
|
|
459
|
+
}
|
|
460
|
+
walk(root, 0)
|
|
461
|
+
return [...new Set(hits)]
|
|
462
|
+
}
|
|
463
|
+
|
|
464
|
+
function firstLine(text) {
|
|
465
|
+
return String(text || '').trim().split(/\r?\n/).filter(Boolean)[0] || ''
|
|
466
|
+
}
|
|
467
|
+
|
|
468
|
+
/*
|
|
469
|
+
* npm 的原始报错对用户太吵:几种最常见的失败换成能直接照做的话,
|
|
470
|
+
* 其余保持原样(stderr 首行 + detail 里的尾巴仍然给出来)。
|
|
471
|
+
*/
|
|
472
|
+
function friendlyNpmFailure(raw) {
|
|
473
|
+
const text = String(raw || '')
|
|
474
|
+
if (/cannot publish over the previously published versions|previously published version/i.test(text)) {
|
|
475
|
+
return {
|
|
476
|
+
error: 'version-exists',
|
|
477
|
+
message: '这个版本号已经在 npm 上了。把包里的 version 改高一点,或重新拖进来让发布器自动 +1。',
|
|
478
|
+
}
|
|
479
|
+
}
|
|
480
|
+
if (/one-time password|EOTP|two-factor/i.test(text)) {
|
|
481
|
+
return {
|
|
482
|
+
error: 'otp-required',
|
|
483
|
+
message: 'npm 要求两步验证码。到 npm 账号设置里开启 2FA 后,用带 OTP 的终端发布,或先关掉该包的 2FA 要求。',
|
|
484
|
+
}
|
|
485
|
+
}
|
|
486
|
+
if (/ENEEDAUTH|need auth|not authenticated/i.test(text)) {
|
|
487
|
+
return {
|
|
488
|
+
error: 'not-authenticated',
|
|
489
|
+
message: 'npm 不认当前身份。在宿主机执行 npm login,或设置 NODE_AUTH_TOKEN 后重启 DSH。',
|
|
490
|
+
}
|
|
491
|
+
}
|
|
492
|
+
if (/EPUBLISHCONFLICT/i.test(text)) {
|
|
493
|
+
return {
|
|
494
|
+
error: 'version-exists',
|
|
495
|
+
message: '这个版本号已经被占用(可能是别人刚发的)。换一个更高的版本再试。',
|
|
496
|
+
}
|
|
497
|
+
}
|
|
498
|
+
return null
|
|
499
|
+
}
|
|
500
|
+
|
|
501
|
+
function tailLines(text, count) {
|
|
502
|
+
const lines = String(text || '').trim().split(/\r?\n/).filter(Boolean)
|
|
503
|
+
return lines.slice(-count).join('\n')
|
|
504
|
+
}
|