@dsh-workbench/module-tools 1.0.0-beta.0 → 1.0.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/src/release.mjs CHANGED
@@ -1,8 +1,8 @@
1
- import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
2
- import { homedir, tmpdir } from 'node:os';
3
- import { dirname, join, relative, resolve, sep } from 'node:path';
1
+ import { existsSync, readFileSync, writeFileSync } from 'node:fs';
2
+ import { join } from 'node:path';
4
3
  import { fileURLToPath } from 'node:url';
5
4
  import { isDeepStrictEqual } from 'node:util';
5
+ import semver from 'semver';
6
6
 
7
7
  import { DESIGN_FILE, acceptanceOf } from './design.mjs';
8
8
  import {
@@ -18,10 +18,38 @@ import {
18
18
  } from './release-journal.mjs';
19
19
  import { emit, installOf, marketInstallOf, stateOf } from './release-report.mjs';
20
20
  import { authorChangeOf, changelogGateOf } from './release-changelog.mjs';
21
- import { NeedsUser, ReleaseError, ResumableError, defaultExec, tailOf } from './release-util.mjs';
21
+ import {
22
+ NeedsUser,
23
+ ReleaseError,
24
+ ResumableError,
25
+ argValue,
26
+ defaultExec,
27
+ dshHomeOf,
28
+ hasFlag,
29
+ tailOf,
30
+ } from './release-util.mjs';
31
+ import {
32
+ TARGETS,
33
+ checkLogin,
34
+ licenseOf,
35
+ repositoryOf,
36
+ targetInfoOf,
37
+ targetOf,
38
+ } from './release-target.mjs';
39
+ import {
40
+ checkGitFiles,
41
+ checkPublished,
42
+ localFiles,
43
+ packTarball,
44
+ publishRegistry,
45
+ registryExists,
46
+ verifyRegistry,
47
+ } from './release-publish.mjs';
22
48
  import {
23
49
  MarketIndexError,
50
+ identityOf,
24
51
  marketVersionExists,
52
+ refreshMarketEntry,
25
53
  resolveIndexPlan,
26
54
  updateMarketIndex,
27
55
  verifyMarketArtifact,
@@ -31,35 +59,6 @@ export { NeedsUser, ReleaseError, ResumableError };
31
59
 
32
60
  const CLI = fileURLToPath(new URL('../bin/dsh-wb-module.mjs', import.meta.url));
33
61
  const SCRIPTS = ['typecheck', 'test', 'selfcheck'];
34
- const TARGETS = ['team', 'public', 'tarball', 'git', 'market', 'local'];
35
- const PUBLIC_REGISTRIES = ['https://registry.npmjs.org/', 'https://registry.npmmirror.com/'];
36
- const SEMVER = /^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?$/;
37
- const REQUIRED_FILES = ['dist/host.js', 'client.js', 'cordis.patch.yml', 'package.json', 'CHANGELOG.md'];
38
-
39
- function argValue(args, flag) {
40
- const at = args.indexOf(flag);
41
- return at === -1 ? undefined : args[at + 1];
42
- }
43
-
44
- function hasFlag(args, flag) {
45
- return args.includes(flag);
46
- }
47
-
48
- function parseJson(text) {
49
- const raw = String(text ?? '');
50
- const start = raw.search(/[[{]/);
51
- if (start === -1) return undefined;
52
- try {
53
- return JSON.parse(raw.slice(start));
54
- } catch {
55
- return undefined;
56
- }
57
- }
58
-
59
- function quote(value) {
60
- const text = String(value);
61
- return /[\s"'$`\\]/.test(text) ? `'${text.replace(/'/g, `'\\''`)}'` : text;
62
- }
63
62
 
64
63
  function readManifest(root) {
65
64
  const file = join(root, 'package.json');
@@ -80,130 +79,16 @@ function writeManifest(root, manifest) {
80
79
  writeFileSync(join(root, 'package.json'), `${JSON.stringify(manifest, null, 2)}\n`);
81
80
  }
82
81
 
83
- function dshHomeOf(home) {
84
- return home ?? process.env.DSH_HOME?.trim() ?? join(homedir(), '.dsh');
85
- }
86
-
87
- function artifactsDirOf(home, unit) {
88
- return join(dshHomeOf(home), 'workbench', 'artifacts', unit);
89
- }
90
-
91
- function normalizeRegistry(url) {
92
- const value = String(url ?? '').trim();
93
- if (value === '') return '';
94
- return value.endsWith('/') ? value : `${value}/`;
95
- }
96
-
97
- function isPublicRegistry(registry) {
98
- return PUBLIC_REGISTRIES.includes(normalizeRegistry(registry));
99
- }
100
-
101
- function findNpmrc(root) {
102
- let dir = resolve(root);
103
- for (;;) {
104
- const file = join(dir, '.npmrc');
105
- if (existsSync(file)) return file;
106
- const parent = dirname(dir);
107
- if (parent === dir) return undefined;
108
- dir = parent;
109
- }
110
- }
111
-
112
- function hasAuth(file) {
113
- if (file === undefined) return false;
114
- try {
115
- return /(_authToken|_auth\s*=|always-auth)/i.test(readFileSync(file, 'utf8'));
116
- } catch {
117
- return false;
118
- }
119
- }
120
-
121
- function registryInNpmrc(file, name) {
122
- if (file === undefined) return '';
123
- let general = '';
124
- const scope = name.startsWith('@') ? name.slice(0, name.indexOf('/')) : '';
125
- for (const raw of readFileSync(file, 'utf8').split('\n')) {
126
- const line = raw.trim();
127
- if (line === '' || line.startsWith('#') || line.startsWith(';')) continue;
128
- const at = line.indexOf('=');
129
- if (at === -1) continue;
130
- const key = line.slice(0, at).trim();
131
- const value = normalizeRegistry(line.slice(at + 1).trim());
132
- if (value === '') continue;
133
- if (scope !== '' && key === `${scope}:registry`) return value;
134
- if (key === 'registry') general = value;
135
- }
136
- return general;
137
- }
138
-
139
- function configuredRegistry(root, manifest) {
140
- const npmrc = findNpmrc(root);
141
- return (
142
- normalizeRegistry(process.env.DSH_WB_PUBLISH_REGISTRY) ||
143
- normalizeRegistry(manifest.publishConfig?.registry) ||
144
- registryInNpmrc(npmrc, String(manifest.name ?? ''))
145
- );
146
- }
147
-
148
- function targetOf(root, manifest, args, indexPlan) {
149
- const asked = argValue(args, '--target');
150
- if (asked !== undefined) {
151
- if (!TARGETS.includes(asked)) throw new ReleaseError(`--target 只认 ${TARGETS.join(' / ')}`);
152
- return asked;
153
- }
154
- if (hasFlag(args, '--public')) return 'public';
155
- if (hasFlag(args, '--git') || argValue(args, '--git') !== undefined) return 'git';
156
- if (argValue(args, '--out') !== undefined) return 'tarball';
157
- const flagged = normalizeRegistry(argValue(args, '--registry'));
158
- if (flagged !== '') return isPublicRegistry(flagged) ? 'public' : 'team';
159
- if (indexPlan?.policy === 'artifacts-in-repo') return 'market';
160
- const configured = configuredRegistry(root, manifest);
161
- if (configured !== '') return isPublicRegistry(configured) ? 'public' : 'team';
162
- return 'tarball';
163
- }
164
-
165
- function licenseFileOf(root) {
166
- for (const name of ['LICENSE', 'LICENSE.md', 'LICENSE.txt', 'COPYING']) {
167
- if (existsSync(join(root, name))) return name;
168
- }
169
- return undefined;
170
- }
171
-
172
- function licenseOf(root, manifest, target, args) {
173
- const given = argValue(args, '--license') ?? manifest.license;
174
- if (typeof given === 'string' && given.trim() !== '') return given.trim();
175
- const file = licenseFileOf(root);
176
- if (file !== undefined) return `SEE LICENSE IN ${file}`;
177
- if (target === 'public') {
178
- throw new NeedsUser('license', '公开发布需要一个许可证。用 MIT、Apache-2.0,还是仓库里已有的 LICENSE?', undefined, {
179
- target,
180
- });
181
- }
182
- if (target === 'team') return 'UNLICENSED';
183
- return undefined;
184
- }
185
-
186
- function repositoryOf(root, exec) {
187
- const result = exec('git', ['-C', root, 'remote', 'get-url', 'origin'], { capture: true, allowFailure: true });
188
- const url = result.status === 0 ? result.stdout.trim() : '';
189
- return url === '' ? undefined : { type: 'git', url };
190
- }
191
-
192
82
  function bumpVersion(version, kind) {
193
- const match = /^(\d+)\.(\d+)\.(\d+)/.exec(String(version));
194
- if (match === null) throw new ReleaseError(`当前版本号读不出来:${String(version)}`);
195
- const major = Number(match[1]);
196
- const minor = Number(match[2]);
197
- const patch = Number(match[3]);
198
- if (kind === 'major') return `${major + 1}.0.0`;
199
- if (kind === 'minor') return `${major}.${minor + 1}.0`;
200
- return `${major}.${minor}.${patch + 1}`;
83
+ const next = semver.inc(String(version), kind);
84
+ if (next === null) throw new ReleaseError(`当前版本号读不出来:${String(version)}`);
85
+ return next;
201
86
  }
202
87
 
203
88
  function nextVersion(current, asked, exists) {
204
89
  if (asked !== undefined) {
205
90
  const version = /^(major|minor|patch)$/.test(asked) ? bumpVersion(current, asked) : asked;
206
- if (!SEMVER.test(version)) {
91
+ if (semver.valid(version) === null) {
207
92
  throw new ReleaseError(`--version 只认 patch / minor / major / x.y.z(收到「${asked}」)`);
208
93
  }
209
94
  if (exists(version)) throw new ReleaseError(`${version} 已经被占了 —— 换一个版本`);
@@ -217,160 +102,6 @@ function nextVersion(current, asked, exists) {
217
102
  throw new ReleaseError('版本号没法自动加 —— 手动给 --version');
218
103
  }
219
104
 
220
- function loginCommandOf(registry) {
221
- return `npm login --registry ${registry}`;
222
- }
223
-
224
- function npmrcArgs(npmrc) {
225
- return npmrc === undefined ? [] : ['--userconfig', npmrc];
226
- }
227
-
228
- function checkLogin(exec, info) {
229
- const argv = ['whoami', '--registry', info.registry, ...npmrcArgs(info.npmrc)];
230
- const result = exec('npm', argv, { capture: true, allowFailure: true });
231
- if (result.status === 0) return;
232
- const text = `${result.stdout}\n${result.stderr}`;
233
- if (/E404|404|not found/i.test(text)) return;
234
- if (/ENEEDAUTH|not logged in|401|Unauthorized|E401|E403|403/i.test(text)) {
235
- throw new NeedsUser(
236
- 'login',
237
- `${info.target === 'public' ? 'npm' : '团队源'}还没登录。请在终端跑 \`${loginCommandOf(info.registry)}\`,走完登录/验证器再跟我说「好了」,我接着发。`,
238
- loginCommandOf(info.registry),
239
- { target: info.target, registry: info.registry },
240
- );
241
- }
242
- throw new ReleaseError(`连不上源(${info.registry}):${tailOf(text)}`);
243
- }
244
-
245
- function registryInfoOf(root, manifest, args, target, fallbackRegistry) {
246
- const name = String(manifest.name ?? '');
247
- const askedNpmrc = argValue(args, '--npmrc');
248
- const sourceNpmrc = askedNpmrc === undefined ? findNpmrc(root) : resolve(askedNpmrc);
249
- if (askedNpmrc !== undefined && !existsSync(sourceNpmrc)) {
250
- throw new ReleaseError(`--npmrc 指的文件不存在:${sourceNpmrc}`);
251
- }
252
- const npmrc = askedNpmrc !== undefined ? sourceNpmrc : hasAuth(sourceNpmrc) ? sourceNpmrc : undefined;
253
- const flagged = normalizeRegistry(argValue(args, '--registry'));
254
- let registry;
255
- if (target === 'public') {
256
- registry = flagged || 'https://registry.npmjs.org/';
257
- if (!isPublicRegistry(registry)) {
258
- throw new ReleaseError('public 目标要公网源;团队私有源用 --target team');
259
- }
260
- } else {
261
- registry =
262
- flagged ||
263
- normalizeRegistry(process.env.DSH_WB_PUBLISH_REGISTRY) ||
264
- normalizeRegistry(manifest.publishConfig?.registry) ||
265
- normalizeRegistry(fallbackRegistry) ||
266
- registryInNpmrc(sourceNpmrc, name);
267
- if (registry === '') {
268
- throw new NeedsUser(
269
- 'registry',
270
- '这个工坊还没配团队源。让公司把 registry 和 token 写进 `.npmrc`;或者我先给你打一个安装包。',
271
- undefined,
272
- { target },
273
- );
274
- }
275
- if (isPublicRegistry(registry)) {
276
- throw new ReleaseError('这个源是公共 npm —— 用 --target public 明确公开发布');
277
- }
278
- }
279
- const access = argValue(args, '--access') ?? manifest.publishConfig?.access ?? (target === 'public' ? 'public' : 'restricted');
280
- if (access !== 'restricted' && access !== 'public') {
281
- throw new ReleaseError(`--access 只认 restricted / public(收到「${access}」)`);
282
- }
283
- if (target === 'public' && access !== 'public') throw new ReleaseError('public 目标只接受 --access public');
284
- return { target, kind: 'registry', name, registry, access, npmrc };
285
- }
286
-
287
- function tarballInfoOf(root, manifest, args, home) {
288
- const out = resolve(argValue(args, '--out') ?? artifactsDirOf(home, String(manifest.dsh?.workbench?.unit ?? '')));
289
- const fileNameOf = (version) => `${String(manifest.name).replace(/^@/, '').replace(/[/\\]/g, '-')}-${version}.tgz`;
290
- const fileOf = (version) => join(out, fileNameOf(version));
291
- return {
292
- target: 'tarball',
293
- kind: 'tarball',
294
- out,
295
- fileNameOf,
296
- fileOf,
297
- exists: (version) => existsSync(fileOf(version)),
298
- };
299
- }
300
-
301
- function gitInfoOf(root, manifest, args, exec) {
302
- const unit = String(manifest.dsh?.workbench?.unit ?? '');
303
- const top = exec('git', ['-C', root, 'rev-parse', '--show-toplevel'], { capture: true, allowFailure: true });
304
- if (top.status !== 0) {
305
- throw new NeedsUser(
306
- 'git-remote',
307
- '这个模块目录还不是 git 仓库。先给它一个仓库/配好权限,或改打一个安装包。',
308
- undefined,
309
- { target: 'git' },
310
- );
311
- }
312
- const toplevel = top.stdout.trim();
313
- const branchResult = exec('git', ['-C', toplevel, 'rev-parse', '--abbrev-ref', 'HEAD'], {
314
- capture: true,
315
- allowFailure: true,
316
- });
317
- const branch = branchResult.status === 0 ? branchResult.stdout.trim() : '';
318
- if (branch === '' || branch === 'HEAD') {
319
- throw new NeedsUser('git-branch', '这个仓库现在不在一个分支上(detached HEAD)。先切回一个分支,再发。', undefined, {
320
- target: 'git',
321
- });
322
- }
323
- const remote = argValue(args, '--git') ?? 'origin';
324
- const remoteResult = exec('git', ['-C', toplevel, 'remote', 'get-url', remote], { capture: true, allowFailure: true });
325
- if (remoteResult.status !== 0 || remoteResult.stdout.trim() === '') {
326
- throw new NeedsUser('git-remote', `这个仓库没有可推送的远端 ${remote}。先加一个远端,或改打一个安装包。`, undefined, {
327
- target: 'git',
328
- remote,
329
- });
330
- }
331
- const url = remoteResult.stdout.trim();
332
- const packagePath = relative(toplevel, root).split(sep).join('/') || '.';
333
- const status = exec('git', ['-C', toplevel, 'status', '--porcelain', '--untracked-files=all'], {
334
- capture: true,
335
- allowFailure: true,
336
- });
337
- if (status.status !== 0) throw new ReleaseError(`读不了 git 状态:${tailOf(status.stderr)}`);
338
- const prefix = packagePath === '.' ? '' : `${packagePath}/`;
339
- const allowed = ['dist', 'client.js', 'cordis.patch.yml', 'package.json', 'README.md', 'CHANGELOG.md', 'design.json'];
340
- const dirty = status.stdout
341
- .trim()
342
- .split('\n')
343
- .filter((line) => line.trim() !== '')
344
- .map((line) => line.slice(3).trim())
345
- .filter((path) => {
346
- if (!path.startsWith(prefix)) return true;
347
- const rel = path.slice(prefix.length);
348
- return !allowed.some((one) => rel === one || rel.startsWith(`${one}/`));
349
- });
350
- if (dirty.length > 0) {
351
- throw new NeedsUser(
352
- 'git-dirty',
353
- `工作区还有别的未提交改动(${dirty.slice(0, 3).join('、')})。先提交/暂存,再发;或改用安装包。`,
354
- undefined,
355
- { target: 'git', paths: dirty.slice(0, 3) },
356
- );
357
- }
358
- const tagOf = (version) => `${unit}@${version}`;
359
- const exists = (version) =>
360
- exec('git', ['-C', toplevel, 'rev-parse', '-q', '--verify', `refs/tags/${tagOf(version)}`], {
361
- capture: true,
362
- allowFailure: true,
363
- }).status === 0;
364
- return { target: 'git', kind: 'git', toplevel, branch, remote, url, packagePath, tagOf, exists };
365
- }
366
-
367
- function targetInfoOf(root, manifest, args, home, exec, target, fallbackRegistry) {
368
- if (target === 'team' || target === 'public') return registryInfoOf(root, manifest, args, target, fallbackRegistry);
369
- if (target === 'tarball') return tarballInfoOf(root, manifest, args, home);
370
- if (target === 'git') return gitInfoOf(root, manifest, args, exec);
371
- return { target: 'local', kind: 'local' };
372
- }
373
-
374
105
  function stage(exec, command, argv, { cwd, capture, err, label }) {
375
106
  const result = exec(command, argv, { cwd, capture, allowFailure: true });
376
107
  if (result.status === 0) return result;
@@ -397,163 +128,55 @@ function runGate(exec, root, options) {
397
128
  for (const script of SCRIPTS) runScriptStage(exec, root, script, options);
398
129
  }
399
130
 
400
- function localFiles(exec, root) {
401
- const result = exec(
402
- 'npm',
403
- ['pack', '--dry-run', '--json', '--ignore-scripts', '--cache', join(tmpdir(), 'dsh-wb-npm-cache')],
404
- { cwd: root, capture: true, allowFailure: true },
405
- );
406
- if (result.status !== 0) throw new ReleaseError(`核不了本地包内容:${tailOf(`${result.stdout}\n${result.stderr}`)}`);
407
- const parsed = parseJson(result.stdout);
408
- const first = Array.isArray(parsed) ? parsed[0] : parsed;
409
- const files = Array.isArray(first?.files) ? first.files.map((one) => String(one.path ?? one)) : [];
410
- if (files.length === 0) throw new ReleaseError('npm pack 没列出包内容');
411
- return files;
412
- }
413
-
414
- function checkPublished(files) {
415
- const missing = REQUIRED_FILES.filter((one) => !files.includes(one));
416
- if (missing.length > 0) throw new ReleaseError(`包里少了 ${missing.join(' / ')} —— 装上会起不来`);
417
- const leaked = files.filter(
418
- (one) => one.startsWith('src/') || one.endsWith('.npmrc') || one.startsWith('template') || one.includes('.env'),
419
- );
420
- if (leaked.length > 0) throw new ReleaseError(`包里混进了不该发的:${leaked.slice(0, 3).join('、')}`);
421
- }
422
-
423
- function checkGitFiles(files) {
424
- const missing = REQUIRED_FILES.filter((one) => !files.includes(one));
425
- if (missing.length > 0) throw new ReleaseError(`tag 里少了 ${missing.join(' / ')} —— 装上会起不来`);
426
- const leaked = files.filter((one) => one.endsWith('.npmrc') || one.includes('.env'));
427
- if (leaked.length > 0) throw new ReleaseError(`tag 里混进了凭据文件:${leaked.slice(0, 3).join('、')}`);
131
+ function gitPathsOf(info) {
132
+ const prefix = info.packagePath === '.' ? '' : `${info.packagePath}/`;
133
+ return ['dist', 'client.js', 'cordis.patch.yml', 'package.json', 'README.md', 'CHANGELOG.md', 'design.json']
134
+ .map((one) => `${prefix}${one}`)
135
+ .filter((one) => existsSync(join(info.toplevel, one)));
428
136
  }
429
137
 
430
- function registryExists(exec, info, name, version) {
431
- const argv = ['view', `${name}@${version}`, 'version', '--json', '--registry', info.registry, ...npmrcArgs(info.npmrc)];
432
- const result = exec('npm', argv, { capture: true, allowFailure: true });
433
- if (result.status === 0) return true;
434
- const text = `${result.stdout}\n${result.stderr}`;
435
- if (/E404|404|No matching version|not found|不存在/i.test(text)) return false;
436
- throw new ReleaseError(`查团队源失败(${info.registry}):${tailOf(text)}`);
437
- }
138
+ const MESSAGE_FILES = ['src/messages.ts', 'src/messages.tsx', 'src/messages.mjs', 'src/messages.js'];
438
139
 
439
- function publishArgsOf(info) {
440
- return [
441
- 'publish',
442
- '--registry',
443
- info.registry,
444
- '--access',
445
- info.access,
446
- '--ignore-scripts',
447
- ...npmrcArgs(info.npmrc),
448
- ];
140
+ function titleIn(segment, key) {
141
+ const quoted = `['"\`]${key.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}['"\`]`;
142
+ const match = new RegExp(`${quoted}\\s*:\\s*['"\`]([^'"\`]*)['"\`]`).exec(segment);
143
+ return match === null ? '' : match[1].trim();
449
144
  }
450
145
 
451
- function otpCommandOf(root, info) {
452
- return [
453
- `cd ${quote(root)}`,
454
- '&&',
455
- 'npm',
456
- 'publish',
457
- '--registry',
458
- info.registry,
459
- '--access',
460
- info.access,
461
- '--ignore-scripts',
462
- ...npmrcArgs(info.npmrc),
463
- ].join(' ');
464
- }
465
-
466
- function publishRegistry(exec, root, info, manifest, version) {
467
- const result = exec('npm', publishArgsOf(info), { cwd: root, capture: true, allowFailure: true });
468
- if (result.status === 0) return;
469
- const text = `${result.stdout}\n${result.stderr}`;
470
- if (/EOTP|one-time password|OTP/i.test(text)) {
471
- throw new NeedsUser(
472
- 'otp',
473
- '源要求一次性验证码。构建和门禁都过了,请在终端跑下面这条,按提示输入验证码;完了跟我说「好了」,我来核对。',
474
- otpCommandOf(root, info),
475
- { target: info.target, name: manifest.name, version, registry: info.registry },
476
- );
477
- }
478
- if (info.target === 'public' && /E403|403|taken|already exists|Forbidden|cannot publish over/i.test(text)) {
479
- throw new NeedsUser('name', '这个名字在 npm 上已经被占了。换一个:`@<user>/<name>` 或加一个后缀?', undefined, {
480
- target: info.target,
481
- name: manifest.name,
482
- version,
483
- });
484
- }
485
- if (/E403|403|already exists|Forbidden/i.test(text)) {
486
- throw new NeedsUser('scope', '团队源不让发这个包名(可能被占了,或没有权限)。让管理员确认 scope / 权限后跟我说。', undefined, {
487
- target: info.target,
488
- name: manifest.name,
489
- version,
490
- });
491
- }
492
- if (/E402|402|E404|404|scope|payment|not found/i.test(text)) {
493
- throw new NeedsUser('scope', '团队源要求包名带 scope。用 `@<scope>/<name>` 吗?', undefined, {
494
- target: info.target,
495
- name: manifest.name,
496
- version,
497
- });
498
- }
499
- throw new ReleaseError(`npm publish 没过:${tailOf(text)}`);
500
- }
501
-
502
- function verifyRegistry(exec, info, name, version) {
503
- const view = exec(
504
- 'npm',
505
- ['view', `${name}@${version}`, 'version', 'dist.tarball', '--json', '--registry', info.registry, ...npmrcArgs(info.npmrc)],
506
- { capture: true, allowFailure: true },
507
- );
508
- if (view.status !== 0) {
509
- throw new ReleaseError(`发完了,但在源上查不到 ${name}@${version} —— 去 registry 确认一下`);
146
+ export function cardTitleFromMessages(root, unit) {
147
+ if (unit === '') return undefined;
148
+ const key = `${unit}.cardTitle`;
149
+ for (const file of MESSAGE_FILES) {
150
+ let text;
151
+ try {
152
+ text = readFileSync(join(root, file), 'utf8');
153
+ } catch {
154
+ continue;
155
+ }
156
+ const zhAt = text.search(/\bzh\s*:/);
157
+ const enAt = text.search(/\ben\s*:/);
158
+ const zh = zhAt === -1 ? '' : titleIn(text.slice(zhAt, enAt === -1 ? text.length : enAt), key);
159
+ const en = enAt === -1 ? '' : titleIn(text.slice(enAt), key);
160
+ if (zh === '' && en === '') continue;
161
+ return { ...(zh === '' ? {} : { zh }), ...(en === '' ? {} : { en }) };
510
162
  }
511
- const packed = exec(
512
- 'npm',
513
- ['pack', `${name}@${version}`, '--dry-run', '--json', '--ignore-scripts', '--registry', info.registry, ...npmrcArgs(info.npmrc)],
514
- { capture: true, allowFailure: true },
515
- );
516
- if (packed.status !== 0) throw new ReleaseError(`发完了,但核不了包:${tailOf(`${packed.stdout}\n${packed.stderr}`)}`);
517
- const parsed = parseJson(packed.stdout);
518
- const first = Array.isArray(parsed) ? parsed[0] : parsed;
519
- const files = Array.isArray(first?.files) ? first.files.map((one) => String(one.path ?? one)) : [];
520
- if (files.length === 0) throw new ReleaseError('发完了,但 npm pack 没列出包内容');
521
- checkPublished(files);
522
- return files;
523
- }
524
-
525
- function packTarball(exec, info, version) {
526
- mkdirSync(info.out, { recursive: true });
527
- const result = exec(
528
- 'npm',
529
- ['pack', '--json', '--ignore-scripts', '--pack-destination', info.out],
530
- { capture: true, allowFailure: true },
531
- );
532
- if (result.status !== 0) throw new ReleaseError(`npm pack 没过:${tailOf(`${result.stdout}\n${result.stderr}`)}`);
533
- const parsed = parseJson(result.stdout);
534
- const first = Array.isArray(parsed) ? parsed[0] : parsed;
535
- const filename = typeof first?.filename === 'string' ? first.filename : info.fileNameOf(version);
536
- const file = join(info.out, filename);
537
- if (!existsSync(file)) throw new ReleaseError(`npm pack 说生成了 ${filename},但文件不在 ${info.out}`);
538
- return file;
539
- }
540
-
541
- function gitPathsOf(info) {
542
- const prefix = info.packagePath === '.' ? '' : `${info.packagePath}/`;
543
- return ['dist', 'client.js', 'cordis.patch.yml', 'package.json', 'README.md', 'CHANGELOG.md', 'design.json']
544
- .map((one) => `${prefix}${one}`)
545
- .filter((one) => existsSync(join(info.toplevel, one)));
163
+ return undefined;
546
164
  }
547
165
 
548
- function gitCommitOf(exec, info, version, capture, progress = {}) {
166
+ function gitCommitOf(exec, info, version, capture, progress = {}, identity) {
549
167
  const add = exec('git', ['-C', info.toplevel, 'add', '-f', '--', ...gitPathsOf(info)], {
550
168
  capture,
551
169
  allowFailure: true,
552
170
  });
553
171
  if (add.status !== 0) throw new ReleaseError(`git add 没过:${tailOf(`${add.stdout}\n${add.stderr}`)}`);
172
+ const who = [];
173
+ if (identity !== undefined) {
174
+ who.push('-c', `user.name=${identity.name}`);
175
+ if (identity.email !== undefined) who.push('-c', `user.email=${identity.email}`);
176
+ }
554
177
  const commit = exec(
555
178
  'git',
556
- ['-C', info.toplevel, 'commit', '-m', `chore(release): ${info.tagOf(version)}`],
179
+ ['-C', info.toplevel, ...who, 'commit', '-m', `chore(release): ${info.tagOf(version)}`],
557
180
  { capture, allowFailure: true },
558
181
  );
559
182
  if (commit.status !== 0) throw new ReleaseError(`git commit 没过:${tailOf(`${commit.stdout}\n${commit.stderr}`)}`);
@@ -682,6 +305,40 @@ export async function runRelease({
682
305
  throw new ReleaseError('这个索引源是 catalog-only:它只收目录、不放产物。用 --index-policy artifacts-in-repo 或换一个可写仓库');
683
306
  }
684
307
  }
308
+ if (hasFlag(args, '--refresh')) {
309
+ if (dryRun) throw new ReleaseError('--refresh 没有预览:它只改索引里的标题 / 作者 / 说明');
310
+ if (target !== 'market') throw new ReleaseError('--refresh 只对市场索引有意义(--target market)');
311
+ if (indexPlan === undefined) {
312
+ throw new ReleaseError('没有可写的 git 索引源 —— 用 --index <仓库> 指定,或先在「模块市场 → 发现」里初始化索引');
313
+ }
314
+ const cardTitle = cardTitleFromMessages(root, unit);
315
+ const titled = cardTitle === undefined ? manifest : { ...manifest, title: cardTitle };
316
+ const result = refreshMarketEntry({ plan: indexPlan, exec, home, manifest: titled });
317
+ if (result.updated !== true && result.reason !== undefined) {
318
+ throw new ReleaseError(`刷新市集元数据没走通:${result.reason}`);
319
+ }
320
+ const summary = {
321
+ ok: true,
322
+ target: 'market',
323
+ refresh: true,
324
+ name: manifest.name,
325
+ version: result.version ?? manifest.version,
326
+ refreshed: result.updated === true,
327
+ market: {
328
+ url: indexPlan.source.url,
329
+ ...(result.branch === undefined ? {} : { branch: result.branch }),
330
+ ...(result.commit === undefined ? {} : { commit: result.commit }),
331
+ },
332
+ changes: result.updated === true ? ['市集元数据已刷新'] : [],
333
+ install: '',
334
+ text:
335
+ result.updated === true
336
+ ? `已刷新 ${manifest.name} 的市集元数据(版本 ${result.version ?? manifest.version} 不变)`
337
+ : `${manifest.name} 的市集元数据本来就是这样,没动`,
338
+ };
339
+ emit(out, json, summary);
340
+ return summary;
341
+ }
685
342
  const authored = authorChangeOf(root, manifest, exec);
686
343
  const authorChange = authored.change;
687
344
  if (!verify && !dryRun && authored.author !== undefined) {
@@ -972,10 +629,12 @@ export async function runRelease({
972
629
  if (!resumeMatchesTree) runCliStage(exec, root, ['check'], stageOptions);
973
630
  if (tracking) advanceRun(home, unit, { phase: 'version', version });
974
631
  const next = { ...manifest, version };
632
+ const cardTitle = cardTitleFromMessages(root, unit);
633
+ const titled = cardTitle === undefined ? next : { ...next, title: cardTitle };
975
634
  const index = updateMarketIndex({
976
635
  plan: indexPlan,
977
636
  root,
978
- manifest: next,
637
+ manifest: titled,
979
638
  unit,
980
639
  version,
981
640
  publish: {},
@@ -1103,7 +762,7 @@ export async function runRelease({
1103
762
  writeState(home, unit, stateOf(info, next, version, 'intent'));
1104
763
  const progress = { committed: false };
1105
764
  try {
1106
- const commit = gitCommitOf(exec, info, version, capture, progress);
765
+ const commit = gitCommitOf(exec, info, version, capture, progress, identityOf(next));
1107
766
  writeState(home, unit, { ...stateOf(info, next, version, 'committed'), commit });
1108
767
  gitPushOf(exec, info, version, capture);
1109
768
  const checked = verifyGit(exec, info, version);