@capyclaw/publisher 0.1.3 → 0.1.5

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/server/impl.mjs CHANGED
@@ -9,10 +9,12 @@
9
9
  * - root(要发布的仓库 checkout)是调用参数,不再是模块常量;
10
10
  * - npm view / npm pack 的缓存挂在每次调用的 context 上(服务进程长驻,避免跨调用串味);
11
11
  * - 新增轻量 pack 闸(npm pack --dry-run 断言 package.json/main/patch 必在包内),
12
- * 顶替原 scripts/verify-publishable.mjs 的核心保护。
12
+ * 顶替原 scripts/verify-publishable.mjs 的核心保护;
13
+ * - npm/tar 子进程全部异步 spawn(spawnSync 会把宿主事件循环钉死,
14
+ * 与 README「npm 调用全部异步」的承诺矛盾),结果结构与 spawnSync 同形。
13
15
  */
14
16
 
15
- import { spawnSync } from 'node:child_process'
17
+ import { spawn } from 'node:child_process'
16
18
  import crypto from 'node:crypto'
17
19
  import fs from 'node:fs'
18
20
  import os from 'node:os'
@@ -153,39 +155,96 @@ export function pkgOf(dir) {
153
155
 
154
156
  /** npm 直调(node npm-cli.js,不走 shell):含空格的临时/用户目录不会被拆词。 */
155
157
  const NPM_CLI = path.join(path.dirname(process.execPath), 'node_modules', 'npm', 'bin', 'npm-cli.js')
156
- function rawNpmRun(args, options = {}) {
158
+
159
+ /** 异步 spawn + 收集 stdout/stderr,resolve 与 spawnSync 同形的结果
160
+ * ({ status, signal, stdout, stderr, error? },stdout/stderr 恒为 utf8 字符串)。
161
+ * 子进程运行期间事件循环不被阻塞——健康探活/聊天流/插件页照常响应。
162
+ * spawn 同步抛错或 child 'error' 事件都不 reject:与 spawnSync 一样返回
163
+ * status: null + error,调用方统一按 status !== 0 判失败,错误文案不变。
164
+ * options.timeout(若传入)与 spawnSync 等价:到点 kill 子进程,返回 ETIMEDOUT;
165
+ * 现有调用点都不传 timeout,不引入新行为。 */
166
+ function spawnCapture(command, args, options = {}) {
167
+ const { timeout, killSignal = 'SIGTERM', encoding, ...spawnOptions } = options
168
+ return new Promise((resolve) => {
169
+ let stdout = ''
170
+ let stderr = ''
171
+ let settled = false
172
+ let timedOut = false
173
+ let timer = null
174
+ let child = null
175
+ const finish = (result) => {
176
+ if (settled) return
177
+ settled = true
178
+ if (timer) clearTimeout(timer)
179
+ resolve(result)
180
+ }
181
+ try {
182
+ child = spawn(command, args, { stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true, ...spawnOptions })
183
+ } catch (error) {
184
+ /* 先构造结果再 finish:finish 会立刻 resolve Promise,后赋值就丢了。 */
185
+ finish({ status: null, signal: null, stdout, stderr, error })
186
+ return
187
+ }
188
+ child.stdout?.setEncoding('utf8')
189
+ child.stderr?.setEncoding('utf8')
190
+ child.stdout?.on('data', (chunk) => { stdout += chunk })
191
+ child.stderr?.on('data', (chunk) => { stderr += chunk })
192
+ child.on('error', (error) => {
193
+ finish({ status: null, signal: null, stdout, stderr, error })
194
+ })
195
+ /* 'close' 在 stdio 流结束后才触发,此时 stdout/stderr 已收集完整。 */
196
+ child.on('close', (code, signal) => {
197
+ if (timedOut) {
198
+ const error = Object.assign(new Error(`spawn ${command} ETIMEDOUT`), { code: 'ETIMEDOUT' })
199
+ finish({ status: null, signal: signal || killSignal, stdout, stderr, error })
200
+ return
201
+ }
202
+ finish({ status: code, signal, stdout, stderr })
203
+ })
204
+ if (typeof timeout === 'number' && timeout > 0) {
205
+ timer = setTimeout(() => {
206
+ timedOut = true
207
+ try { child.kill(killSignal) } catch { /* 已经退出 */ }
208
+ }, timeout)
209
+ }
210
+ })
211
+ }
212
+
213
+ /** 异步 npm 直调:返回 Promise,结果与 spawnSync 同形(status/stdout/stderr/error)。 */
214
+ export async function rawNpmRun(args, options = {}) {
157
215
  if (fs.existsSync(NPM_CLI)) {
158
- return spawnSync(process.execPath, [NPM_CLI, ...args], { encoding: 'utf8', stdio: 'pipe', ...options })
216
+ return spawnCapture(process.execPath, [NPM_CLI, ...args], options)
159
217
  }
160
- return spawnSync('npm', args, { encoding: 'utf8', stdio: 'pipe', shell: process.platform === 'win32', ...options })
218
+ return spawnCapture('npm', args, { shell: process.platform === 'win32', ...options })
161
219
  }
162
220
 
163
221
  function createNpmContext() {
164
- /** npm view 结果缓存:同一次运行里同一 specifier 只查一次。 */
222
+ /** npm view 结果缓存:同一次运行里同一 specifier 只查一次。
223
+ * 缓存的是 Promise:并发调用共享同一次查询,语义与同步版一致。 */
165
224
  const viewCache = new Map()
166
225
  const npmView = (spec, field) => {
167
226
  const key = `${spec}|${field}`
168
227
  if (!viewCache.has(key)) viewCache.set(key, rawNpmRun(['view', spec, field]))
169
228
  return viewCache.get(key)
170
229
  }
171
- const alreadyPublished = (name, version) => {
172
- const r = npmView(`${name}@${version}`, 'version')
230
+ const alreadyPublished = async (name, version) => {
231
+ const r = await npmView(`${name}@${version}`, 'version')
173
232
  if (r.status !== 0) return false
174
233
  return String(r.stdout).trim() === version
175
234
  }
176
235
  /** registry 上已发布 tarball 的 sha1(拿不到返回 null,网络闪断降级为警告)。 */
177
- const npmShasumOf = (name, version) => {
178
- const r = npmView(`${name}@${version}`, 'dist.shasum')
236
+ const npmShasumOf = async (name, version) => {
237
+ const r = await npmView(`${name}@${version}`, 'dist.shasum')
179
238
  if (r.status !== 0) return null
180
239
  return String(r.stdout).trim() || null
181
240
  }
182
241
  /** 本地 npm pack 产物的 sha1(npm pack 确定性:同内容同哈希)。结果按目录缓存。 */
183
242
  const localShasumCache = new Map()
184
- const localShasumOf = (dir) => {
243
+ const localShasumOf = async (dir) => {
185
244
  if (localShasumCache.has(dir)) return localShasumCache.get(dir)
186
245
  const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'pub-sha-'))
187
246
  try {
188
- const pack = rawNpmRun(['pack', '--pack-destination', tmp], { cwd: dir })
247
+ const pack = await rawNpmRun(['pack', '--pack-destination', tmp], { cwd: dir })
189
248
  if (pack.status !== 0) return null
190
249
  const tgz = path.join(tmp, String(pack.stdout).trim().split(/\r?\n/).pop())
191
250
  const sha = crypto.createHash('sha1').update(fs.readFileSync(tgz)).digest('hex')
@@ -204,7 +263,7 @@ function createNpmContext() {
204
263
  * 自包含例外:列在 bundledDependencies 里的依赖**已经实体在 tarball 内**,
205
264
  * 安装时 npm/pnpm 用包内副本、根本不会去 registry 解析。这类依赖不该被本闸拦下
206
265
  * ——否则「全自包含」的包反而会因为成员尚未上架而发不出去。 */
207
- export function orderGate(pkg, localMap, batch, npm) {
266
+ export async function orderGate(pkg, localMap, batch, npm) {
208
267
  const errors = []
209
268
  const warnings = []
210
269
  const bundled = new Set([
@@ -223,7 +282,7 @@ export function orderGate(pkg, localMap, batch, npm) {
223
282
  if (local) queue.push(local.pkg) /* 闭包继续沿本仓包展开 */
224
283
  /* 已随包携带:安装侧不查 registry,无需顺序约束。 */
225
284
  if (bundled.has(name)) continue
226
- const resolvable = npm.npmView(`${name}@${range}`, 'version')
285
+ const resolvable = await npm.npmView(`${name}@${range}`, 'version')
227
286
  if (resolvable.status === 0) continue /* ① registry 已可解析 */
228
287
  if (batch.has(name)) {
229
288
  warnings.push(`${name}@${range} registry 暂不可解析,依赖同批发布(确认批次包含它)`)
@@ -240,26 +299,14 @@ export function orderGate(pkg, localMap, batch, npm) {
240
299
  * 认证令牌字段的模式用拼接构造,注释里也不写整串,
241
300
  * 否则扫描器会把自己的源码当成泄漏(自噬假阳性)。) */
242
301
  const AUTH_TOKEN_RE = new RegExp('_auth' + 'Token', 'i')
243
- /* ownOnly=true 的模式只查「我们自己的代码」(包根文件 + node_modules/@capyclaw 成员)。
244
- * 第三方 vendored 依赖(playwright/@types/pptxgenjs 等)的上游源码天然带构建机目录路径,
245
- * 那不是本机凭据泄漏,不该拦发布;凭据形态(API key / npm 令牌 / npmrc 令牌字段)则对所有文件一律查。
246
- * 注意:本文件自身也会被扫描,注释里切勿写出任何完整的凭据或路径模式字面量(自噬假阳性)。 */
247
302
  const SECRET_PATTERNS = [
248
- [/sk-[A-Za-z0-9]{20,}/, 'API key 形态(sk-…)', false],
249
- [/npm_[A-Za-z0-9]{20,}/, 'npm token 形态(npm_…)', false],
250
- [AUTH_TOKEN_RE, 'npmrc 认证令牌字段', false],
251
- [/[A-Za-z]:\\Users\\/i, '本机绝对路径(盘符:\\Users\\)', true],
252
- [/\/(home|Users)\/[A-Za-z0-9._-]+\//, '本机绝对路径(/home/ / /Users/)', true],
303
+ [/sk-[A-Za-z0-9]{20,}/, 'API key 形态(sk-…)'],
304
+ [/npm_[A-Za-z0-9]{20,}/, 'npm token 形态(npm_…)'],
305
+ [AUTH_TOKEN_RE, 'npmrc 认证令牌字段'],
306
+ [/[A-Za-z]:\\Users\\/i, '本机绝对路径(盘符:\\Users\\)'],
307
+ [/\/(home|Users)\/[A-Za-z0-9._-]+\//, '本机绝对路径(/home/ / /Users/)'],
253
308
  ]
254
309
 
255
- /** 相对路径是否落在第三方 vendored 依赖里(最后一个 node_modules 段之后非 @capyclaw)。 */
256
- function isThirdPartyVendored(rel) {
257
- const parts = rel.split(/[\\/]/)
258
- const i = parts.lastIndexOf('node_modules')
259
- if (i === -1) return false
260
- return parts[i + 1] !== '@capyclaw'
261
- }
262
-
263
310
  /** 扫描目录内全部文本文件,返回命中的密钥/本机信息描述串。 */
264
311
  export function scanDirForSecrets(root) {
265
312
  const hits = []
@@ -271,11 +318,8 @@ export function scanDirForSecrets(root) {
271
318
  if (entry.isDirectory()) { walk(file); continue }
272
319
  let text = null
273
320
  try { text = fs.readFileSync(file, 'utf8') } catch { continue } /* 二进制/不可读跳过 */
274
- const rel = path.relative(root, file)
275
- const thirdParty = isThirdPartyVendored(rel)
276
- for (const [pattern, label, ownOnly] of SECRET_PATTERNS) {
277
- if (ownOnly && thirdParty) continue
278
- if (pattern.test(text)) hits.push(`${rel}: ${label}`)
321
+ for (const [pattern, label] of SECRET_PATTERNS) {
322
+ if (pattern.test(text)) hits.push(`${path.relative(root, file)}: ${label}`)
279
323
  }
280
324
  }
281
325
  }
@@ -286,21 +330,26 @@ export function scanDirForSecrets(root) {
286
330
  /** 轻量 pack 闸:① npm pack --dry-run 断言分发必需文件真的会进包;
287
331
  * ② 真实 pack + 解包 + 逐文件扫密钥/本机信息(凭据绝不上 npm)。
288
332
  * (顶替原 verify-publishable 的核心断言;干净目录安装级检查不在这里重复。) */
289
- export function packGateErrors(pkg, dir, npm) {
333
+ export async function packGateErrors(pkg, dir, npm) {
290
334
  const mustHave = ['package.json']
291
335
  if (pkg.main) mustHave.push(String(pkg.main).replace(/^\.\//, ''))
292
336
  const patch = pkg.dsh?.bundle?.patch
293
337
  for (const rel of Array.isArray(patch) ? patch : patch ? [patch] : []) {
294
338
  mustHave.push(String(rel).replace(/^\.\//, ''))
295
339
  }
340
+ /* dsh.client 的浏览器半入口以 package.json 的 `./client` export 为准(DSH 就是这么
341
+ * 解析的);只有没声明 export 时才回落约定的 client/client.js。
342
+ * 旧断言硬编码 client/client.js,把 skin-aurora(./client.js)、plugin-drop
343
+ * (./client.js)、my-works(./lib/client.js)这类合法布局误判成 pack-incomplete。 */
296
344
  if (pkg.dsh?.client) {
297
- /* client 入口由包 exports["./client"] 声明(各包不一:client/client.js、根 client.js、lib/client.js),
298
- * 不能硬编码 client/client.js;无 exports 时回退约定默认值。 */
299
- const clientEntry = pkg.exports?.['./client'] || 'client/client.js'
300
- mustHave.push(String(clientEntry).replace(/^\.\//, ''))
345
+ const declared = pkg.exports?.['./client']
346
+ const entry = typeof declared === 'string'
347
+ ? declared
348
+ : declared?.default || declared?.import || declared?.require
349
+ mustHave.push(String(entry || 'client/client.js').replace(/^\.\//, ''))
301
350
  }
302
351
  if (pkg.dsh?.suite) mustHave.push(String(pkg.dsh.suite).replace(/^\.\//, ''))
303
- const r = npm.rawNpmRun(['pack', '--dry-run', '--json'], { cwd: dir })
352
+ const r = await npm.rawNpmRun(['pack', '--dry-run', '--json'], { cwd: dir })
304
353
  if (r.status !== 0) return [`npm pack --dry-run 失败: ${String(r.stderr || r.stdout || '').trim().slice(0, 200)}`]
305
354
  let packed = []
306
355
  try {
@@ -314,10 +363,10 @@ export function packGateErrors(pkg, dir, npm) {
314
363
  /* 真实 pack + 解包 + 密钥扫描:发布产物里不该有任何凭据/本机信息。 */
315
364
  const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'pub-scan-'))
316
365
  try {
317
- const pack = npm.rawNpmRun(['pack', '--pack-destination', tmp], { cwd: dir })
366
+ const pack = await npm.rawNpmRun(['pack', '--pack-destination', tmp], { cwd: dir })
318
367
  if (pack.status !== 0) return [...errors, 'npm pack 失败(无法做密钥扫描)']
319
368
  const tgz = String(pack.stdout).trim().split(/\r?\n/).pop()
320
- const extract = spawnSync('tar', ['-xzf', tgz, '-C', tmp], { cwd: tmp, encoding: 'utf8' })
369
+ const extract = await spawnCapture('tar', ['-xzf', tgz, '-C', tmp], { cwd: tmp })
321
370
  if (extract.status !== 0) return [...errors, 'tarball 解包失败(无法做密钥扫描)']
322
371
  const extracted = path.join(tmp, 'package')
323
372
  if (fs.existsSync(extracted)) {
@@ -330,8 +379,8 @@ export function packGateErrors(pkg, dir, npm) {
330
379
  }
331
380
 
332
381
  /** 发布预检:npm 凭据状态(ambient:宿主已登录或 NODE_AUTH_TOKEN)。 */
333
- export function npmWhoami() {
334
- const r = rawNpmRun(['whoami'])
382
+ export async function npmWhoami() {
383
+ const r = await rawNpmRun(['whoami'])
335
384
  if (r.status !== 0) {
336
385
  return { ok: false, hint: 'npm whoami 失败——在宿主机 npm login,或设置 NODE_AUTH_TOKEN' }
337
386
  }
@@ -355,24 +404,21 @@ function isRealSuite(dir, pkg) {
355
404
  }
356
405
  }
357
406
 
358
- /** 在 A/artifacts/suites/<bridge>/package(npm run assemble 的产物,首选)
359
- * 或旧版 dist/suites/<bridge>/package 里找同名同版本的自包含拼装产物。 */
407
+ /** 在 dist/suites/<bridge>/package 里找同名同版本的自包含拼装产物。 */
360
408
  function findAssembledSuite(root, name, version) {
361
- const bases = [path.join(root, 'A', 'artifacts', 'suites'), path.join(root, 'dist', 'suites')]
362
- for (const suitesDir of bases) {
363
- if (!fs.existsSync(suitesDir)) continue
364
- let entries = []
365
- try { entries = fs.readdirSync(suitesDir, { withFileTypes: true }) } catch { continue }
366
- for (const entry of entries) {
367
- if (!entry.isDirectory()) continue
368
- const candidate = path.join(suitesDir, entry.name, 'package')
369
- const pkgFile = path.join(candidate, 'package.json')
370
- if (!fs.existsSync(pkgFile)) continue
371
- try {
372
- const p = JSON.parse(fs.readFileSync(pkgFile, 'utf8'))
373
- if (p.name === name && p.version === version) return candidate
374
- } catch { /* 坏包跳过 */ }
375
- }
409
+ const suitesDir = path.join(root, 'dist', 'suites')
410
+ if (!fs.existsSync(suitesDir)) return null
411
+ let entries = []
412
+ try { entries = fs.readdirSync(suitesDir, { withFileTypes: true }) } catch { return null }
413
+ for (const entry of entries) {
414
+ if (!entry.isDirectory()) continue
415
+ const candidate = path.join(suitesDir, entry.name, 'package')
416
+ const pkgFile = path.join(candidate, 'package.json')
417
+ if (!fs.existsSync(pkgFile)) continue
418
+ try {
419
+ const p = JSON.parse(fs.readFileSync(pkgFile, 'utf8'))
420
+ if (p.name === name && p.version === version) return candidate
421
+ } catch { /* 坏包跳过 */ }
376
422
  }
377
423
  return null
378
424
  }
@@ -397,7 +443,7 @@ export function preparePublishDir(dir, root, pkg) {
397
443
  const assembled = findAssembledSuite(root, pkg.name, pkg.version)
398
444
  if (!assembled) {
399
445
  return {
400
- error: `找不到自包含拼装产物:${pkg.name}@${pkg.version} 不在 A/artifacts/suites/*/package(或旧版 dist/suites/*/package)里。`
446
+ error: `找不到自包含拼装产物:${pkg.name}@${pkg.version} 不在 dist/suites/*/package 里。`
401
447
  + '先跑 npm run assemble,否则发出去的 suite 里没有成员,安装后要回 registry 拉取。',
402
448
  }
403
449
  }
@@ -444,7 +490,21 @@ async function publishOne(dir, { kind, localMap, batch, only, tag, skipTests, dr
444
490
  }
445
491
  }
446
492
 
447
- const exists = npm.alreadyPublished(pkg.name, pkg.version)
493
+ if (await npm.alreadyPublished(pkg.name, pkg.version)) {
494
+ /* 同版本漂移闸:npm pack 确定性 ⇒ 本地 sha1 == registry dist.shasum 当且仅当内容一致。
495
+ * 注意这里比的是**源码树**,语义是「源码有没有偷偷改过而没 bump 版本」,
496
+ * 与下面发布时使用的自包含产物无关。 */
497
+ const remoteSha = await npm.npmShasumOf(pkg.name, pkg.version)
498
+ const localSha = remoteSha ? await npm.localShasumOf(dir) : null
499
+ if (remoteSha && localSha && remoteSha !== localSha) {
500
+ log(`✗ ${label} — 同版本内容漂移:registry ${remoteSha.slice(0, 8)} ≠ 本地 ${localSha.slice(0, 8)}`)
501
+ log(' npm 不允许同版本重发,请 bump 版本后再发布')
502
+ return { label, status: 'version-drift', detail: `shasum ${localSha} != ${remoteSha}` }
503
+ }
504
+ if (!remoteSha) log(`! ${label} — 无法获取 registry shasum(网络?),跳过漂移对比`)
505
+ log(`· ${label} — registry 上已存在,跳过`)
506
+ return { label, status: 'skipped-exists' }
507
+ }
448
508
 
449
509
  /* 自包含产物:npm/pnpm 会剥离 node_modules,必须发布「依赖已实体化且写进
450
510
  * bundledDependencies」的那一份,否则装出来是瘦包、要回 registry 拉依赖。 */
@@ -456,26 +516,10 @@ async function publishOne(dir, { kind, localMap, batch, only, tag, skipTests, dr
456
516
  }
457
517
 
458
518
  try {
459
- if (exists) {
460
- /* 同版本漂移闸:npm pack 确定性 ⇒ 本地 sha1 == registry dist.shasum 当且仅当内容一致。
461
- * 对比对象是**真正会发布的自包含产物**而非源码树:bundledDependencies 与 vendored
462
- * 依赖只存在于产物里,直接比源码树会在每次续跑时误报漂移;源码改动若影响产物,
463
- * 在这里同样会被抓住。 */
464
- const remoteSha = npm.npmShasumOf(pkg.name, pkg.version)
465
- const localSha = remoteSha ? npm.localShasumOf(prepared.publishDir) : null
466
- if (remoteSha && localSha && remoteSha !== localSha) {
467
- log(`✗ ${label} — 同版本内容漂移:registry ${remoteSha.slice(0, 8)} ≠ 本地 ${localSha.slice(0, 8)}`)
468
- log(' npm 不允许同版本重发,请 bump 版本后再发布')
469
- return { label, status: 'version-drift', detail: `shasum ${localSha} != ${remoteSha}` }
470
- }
471
- if (!remoteSha) log(`! ${label} — 无法获取 registry shasum(网络?),跳过漂移对比`)
472
- log(`· ${label} — registry 上已存在,跳过`)
473
- return { label, status: 'skipped-exists' }
474
- }
475
519
  /* pack 闸只对「真要发布」的包跑(真实 pack + 解包扫描很重,已发布的包由漂移闸把关)。
476
520
  * 校验对象是自包含产物——那才是真正上 registry 的内容。 */
477
521
  if (kind === 'plugin') {
478
- const packErrors = packGateErrors(pkg, prepared.publishDir, npm)
522
+ const packErrors = await packGateErrors(pkg, prepared.publishDir, npm)
479
523
  if (packErrors.length) {
480
524
  log(`✗ ${label} — pack 闸未过`)
481
525
  for (const item of packErrors) log(` - ${item}`)
@@ -486,7 +530,7 @@ async function publishOne(dir, { kind, localMap, batch, only, tag, skipTests, dr
486
530
  /* 发布顺序闸(发布成功 ≠ 用户能装上):依赖闭包须 registry 可解析或同批发布。
487
531
  * 用**自包含产物**的清单判定:bundledDependencies 在源码树里没有,
488
532
  * 只有 staging/拼装产物里才有,拿错清单会把已随包携带的依赖误判成必须上架。 */
489
- const order = orderGate(pkgOf(prepared.publishDir), localMap, batch, npm)
533
+ const order = await orderGate(pkgOf(prepared.publishDir), localMap, batch, npm)
490
534
  if (order.errors.length) {
491
535
  log(`✗ ${label} — 发布顺序闸未过(发布后用户 npm install 会失败)`)
492
536
  for (const item of order.errors) log(` - ${item}`)
@@ -495,7 +539,7 @@ async function publishOne(dir, { kind, localMap, batch, only, tag, skipTests, dr
495
539
  for (const w of order.warnings) log(`! ${label} — ${w}`)
496
540
 
497
541
  if (!skipTests && pkg.scripts?.test) {
498
- const t = npm.rawNpmRun(['test'], { cwd: dir })
542
+ const t = await npm.rawNpmRun(['test'], { cwd: dir })
499
543
  if (t.status !== 0) {
500
544
  log(`✗ ${label} — npm test 失败,跳过发布`)
501
545
  return { label, status: 'test-failed', detail: (t.stdout || '') + (t.stderr || '') }
@@ -508,8 +552,8 @@ async function publishOne(dir, { kind, localMap, batch, only, tag, skipTests, dr
508
552
  }
509
553
 
510
554
  const access = pkg.publishConfig?.access || 'public'
511
- const expectedSha = npm.localShasumOf(prepared.publishDir)
512
- const pub = npm.rawNpmRun(['publish', '--access', access, '--tag', tag], { cwd: prepared.publishDir })
555
+ const expectedSha = await npm.localShasumOf(prepared.publishDir)
556
+ const pub = await npm.rawNpmRun(['publish', '--access', access, '--tag', tag], { cwd: prepared.publishDir })
513
557
  if (pub.status !== 0) {
514
558
  log(`✗ ${label} — npm publish 失败`)
515
559
  log(String(pub.stderr || pub.stdout || '').trim().slice(0, 500))
@@ -518,8 +562,9 @@ async function publishOne(dir, { kind, localMap, batch, only, tag, skipTests, dr
518
562
  /* 发布后复核:registry 收到的 tarball 必须与本地 pack 逐字节一致(shasum)。 */
519
563
  let remoteSha = null
520
564
  for (let i = 0; i < 5 && !remoteSha; i++) {
521
- if (i) Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 3000)
522
- remoteSha = npm.npmShasumOf(pkg.name, pkg.version)
565
+ /* publishOne 是 async:用 await 睡,别用 Atomics.wait 同步钉住宿主事件循环。 */
566
+ if (i) await new Promise((resolve) => { setTimeout(resolve, 3000) })
567
+ remoteSha = await npm.npmShasumOf(pkg.name, pkg.version)
523
568
  }
524
569
  if (remoteSha && expectedSha && remoteSha !== expectedSha) {
525
570
  log(`✗ ${label} — 发布后复核失败:registry ${remoteSha.slice(0, 8)} ≠ 本地 ${expectedSha.slice(0, 8)}(registry 可能收到脏产物,bump 后重发)`)
@@ -576,13 +621,14 @@ export async function runPublish(options = {}) {
576
621
  const pkg = pkgOf(dir)
577
622
  localMap.set(pkg.name, { pkg, dir })
578
623
  }
579
- const batch = new Set(
580
- [...usableLibDirs, ...pluginDirs]
581
- .map((dir) => pkgOf(dir))
582
- .filter((pkg) => !only || pkg.name === only)
583
- .filter((pkg) => !npm.alreadyPublished(pkg.name, pkg.version))
584
- .map((pkg) => pkg.name),
585
- )
624
+ /* alreadyPublished 是异步的:filter 回调里不能 await,改逐包顺序判定
625
+ * (npm view 缓存保证同一 specifier 只查一次,语义与原 filter 链一致)。 */
626
+ const batch = new Set()
627
+ for (const dir of [...usableLibDirs, ...pluginDirs]) {
628
+ const pkg = pkgOf(dir)
629
+ if (only && pkg.name !== only) continue
630
+ if (!(await npm.alreadyPublished(pkg.name, pkg.version))) batch.add(pkg.name)
631
+ }
586
632
 
587
633
  const shared = { localMap, batch, only, tag, skipTests, dryRun, npm, log, root }
588
634
  // 先库后插件:plugin-kit 等支撑库必须先上 registry,插件发布时依赖才可解析
package/server/tools.mjs CHANGED
@@ -31,7 +31,7 @@ const whoamiTool = defineTool({
31
31
  description: 'npm 凭据预检:宿主环境是否已登录(npm whoami / NODE_AUTH_TOKEN)。发布前先调用。',
32
32
  inputSchema: { type: 'object', additionalProperties: false, properties: {} },
33
33
  kind: 'read',
34
- handler: () => text(npmWhoami()),
34
+ handler: () => npmWhoami().then(text),
35
35
  })
36
36
 
37
37
  const previewTool = defineTool({