dsh-plugin-publish-check 0.0.0-stage → 0.1.3

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 dsh-plugin-e2e contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,177 @@
1
- # Temporary Holding Version
1
+ # dsh-plugin-publish-check
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ English | [简体中文](./README.zh-CN.md)
4
+
5
+ Publish-readiness check for a plugin package: metadata, entry targets that actually exist, and — with `--pack` — whether those entry targets really make it into the tarball.
6
+
7
+ ## Install
8
+
9
+ ```bash
10
+ npm i -D dsh-plugin-publish-check
11
+ ```
12
+
13
+ ## Quick start
14
+
15
+ ```bash
16
+ # human-readable
17
+ npx dsh-plugin-publish-check check --dir packages/my-plugin
18
+
19
+ # machine-readable
20
+ npx dsh-plugin-publish-check check --dir packages/my-plugin --json
21
+
22
+ # also verify the npm tarball actually contains the entry points
23
+ npx dsh-plugin-publish-check check --dir packages/my-plugin --pack
24
+ ```
25
+
26
+ Sample output:
27
+
28
+ ```text
29
+ release check: packages/my-plugin
30
+ ✓ name my-plugin
31
+ ✓ version 0.1.0
32
+ ✓ private 不是 private
33
+ ✓ license MIT
34
+ ✓ repository git+https://github.com/you/repo.git
35
+ ✓ description
36
+ ✓ main ./index.js
37
+ ✓ exports/./client ./client.js
38
+ ✓ files: index.js
39
+ ✓ dsh.bundle
40
+ ✓ dsh.bundle.patch ./cordis.patch.yml
41
+ ✓ client 产物 client.js
42
+ ✓ 运行时 dependencies 无
43
+ ✓ npm pack --dry-run 可打包,6 个文件
44
+ ✓ tarball 含入口文件 exports/bin/main/types 均被打包
45
+
46
+ === ✓ 通过 ===
47
+ ```
48
+
49
+ Each line is one check: `✓` ok, `⚠` warning, `✗` error. Errors carry a `→ fix` hint. (The tool's own output is in Chinese.)
50
+
51
+ ## Usage / API
52
+
53
+ ### CLI
54
+
55
+ | Command | What it does |
56
+ |---|---|
57
+ | `check --dir <dir>` | Run the checks against `<dir>` |
58
+
59
+ `check` is **required** — omitting it is a usage error (exit `2`).
60
+
61
+ ### Options
62
+
63
+ | Option | Default | Meaning |
64
+ |---|---|---|
65
+ | `--dir <dir>` | `.` | Package directory to inspect. Must be a **separate token**: `--dir path`, not `--dir=path` |
66
+ | `--json` | off | Print the full `{ dir, checks, errors, warnings }` object |
67
+ | `--pack` | off | Also run `npm pack --dry-run --json` and verify entry targets landed in the tarball |
68
+ | `--help`, `-h` | — | Print usage and exit `0` |
69
+
70
+ ### Exit codes
71
+
72
+ | Code | Meaning |
73
+ |---|---|
74
+ | `0` | No errors (warnings allowed) |
75
+ | `1` | At least one error |
76
+ | `2` | Usage error: missing/unknown subcommand, `--dir` missing its value |
77
+
78
+ ### Programmatic API
79
+
80
+ ```js
81
+ import { checkPublish, entriesMissingFromTarball, expandGlob } from 'dsh-plugin-publish-check'
82
+
83
+ const r = checkPublish('packages/my-plugin', { pack: true })
84
+ ```
85
+
86
+ | Export | Signature | Returns |
87
+ |---|---|---|
88
+ | `checkPublish` | `checkPublish(dir, { pack = false })` | `{ dir, checks, errors, warnings }` |
89
+ | `entriesMissingFromTarball` | `entriesMissingFromTarball(targets, packedPaths, dir?)` | `[[label, missingPath], …]` |
90
+ | `expandGlob` | `expandGlob(dir, pattern)` | Relative paths (forward slashes) matching the pattern |
91
+
92
+ `checks` is an array of `{ status, name, detail, fix }` where `status` is `'ok' | 'warn' | 'error'`. `errors` and `warnings` are arrays of check **names** only.
93
+
94
+ ## What gets checked
95
+
96
+ ### package.json metadata
97
+
98
+ | Check | Result |
99
+ |---|---|
100
+ | `name` | error if missing |
101
+ | `version` | error if missing; **warn** if it is exactly `0.0.0` |
102
+ | `private` | error if `true` (npm refuses to publish it) |
103
+ | `license` | ok if the `license` field exists **or** a `LICENSE` / `LICENSE.md` / `LICENSE.txt` file exists; warn otherwise |
104
+ | `repository` | warn if missing; **warn if it still looks like a placeholder** (`<…>`, `your-org`, `example.com`) |
105
+ | `description` | warn if missing |
106
+
107
+ ### Entry targets actually exist
108
+
109
+ These fields are collected and each target is resolved on disk:
110
+
111
+ - `main` (string)
112
+ - `types` (string)
113
+ - `bin` — string, or every value of the object form
114
+ - `exports` — walked recursively; only string values whose target looks like a source file (`*.js`, `*.mjs`, `*.cjs`, `*.json`, `*.d.ts`, `*.ts`) or contains `*` are collected
115
+
116
+ For a literal path: ok if it exists, **error** if not. For a wildcard path: expanded against the directory; ok with a match count, **error** if the glob matches nothing (`检查 glob 路径 / 先 build`).
117
+
118
+ ### Cross-platform `bin` contract
119
+
120
+ For every `.js` / `.mjs` / `.cjs` command target, two additional **errors** are checked without network access:
121
+
122
+ - the path must **not** start with `./` — npm can classify `./bin/x.mjs` as invalid and remove the command while publishing;
123
+ - the first line must be exactly `#!/usr/bin/env node` — on POSIX, `npx` executes the bin symlink directly, so a JavaScript file without a shebang is interpreted as a shell script.
124
+
125
+ This catches failures that a disk-existence check and a successful tarball alone cannot detect.
126
+
127
+ ### `files` entries
128
+
129
+ Every non-wildcard entry must exist on disk; a missing one is a **warning** (delete the entry or add the directory). Wildcard entries are skipped here.
130
+
131
+ ### DSH bundle
132
+
133
+ | Check | Result |
134
+ |---|---|
135
+ | `dsh.bundle` present | ok; the package is treated as a DSH plugin |
136
+ | `dsh.bundle.patch` | if it is a string, the file must exist — error otherwise |
137
+ | client artifact | if `dsh.client` or `exports['./client']` is set, `client.js` must exist — error otherwise (`UI 不显示`) |
138
+
139
+ **No `dsh.bundle` means "library / tooling package", not a broken plugin.** In that case the bundle checks are skipped and a `包类型 非 DSH 插件包` ok line is recorded instead — no false positives.
140
+
141
+ ### Runtime dependencies
142
+
143
+ - Plugin package (has `dsh.bundle`) with any `dependencies`: **warning** — confirm they are installable, or bundle them at build time.
144
+ - Library/tooling package: dependencies are reported as normal.
145
+
146
+ ### `--pack`: does the tarball actually contain the entry points?
147
+
148
+ This is the check that catches a real publish blind spot: everything on disk can look fine while `files` silently excludes the entry point, so the published package is unusable.
149
+
150
+ With `--pack` the tool runs `npm pack --dry-run --json` in the package directory and:
151
+
152
+ 1. reports whether packing succeeded and how many files it produced;
153
+ 2. compares the collected `main` / `types` / `bin` / `exports` targets against the packed file list, **expanding wildcard exports** to their concrete matches first;
154
+ 3. emits one **error per missing target** (`tarball 缺少 <label>`), with the hint to add the file to `files` or fix the entry field.
155
+
156
+ Example — `files: ["dist/"]` while `main` points at `src/index.mjs`:
157
+
158
+ ```text
159
+ ✓ main ./src/index.mjs
160
+ ✓ npm pack --dry-run 可打包,4 个文件
161
+ ✗ tarball 缺少 main src/index.mjs → 把该文件纳入 files(或修正 exports/bin/main/types)
162
+ ✗ tarball 缺少 exports/. src/index.mjs → …
163
+ ```
164
+
165
+ Without `--pack` that defect is invisible. Use `--pack` in CI before publishing.
166
+
167
+ ## Notes
168
+
169
+ - Requires a working `npm` on `PATH` for `--pack`; the check shells out with `shell: true`.
170
+ - `--pack` only does a **dry run** — nothing is written to the registry and no tarball is kept.
171
+ - Both `--dir` and `--pack` are read positionally from `argv`; `--dir=value` is not recognised and silently falls back to the current directory. Always pass `--dir <dir>` as two tokens.
172
+ - Warnings never fail the build. If you need a strict gate, check `errors.length` via the API or parse `--json`.
173
+ - A missing `package.json` produces a single `package.json` error and stops early.
174
+
175
+ ## License
176
+
177
+ MIT
@@ -0,0 +1,177 @@
1
+ # dsh-plugin-publish-check
2
+
3
+ [English](./README.md) | 简体中文
4
+
5
+ 插件包的发布体检:查元数据、查入口目标是否真实存在,并在 `--pack` 下查这些入口**是否真进了 tarball**。
6
+
7
+ ## 安装
8
+
9
+ ```bash
10
+ npm i -D dsh-plugin-publish-check
11
+ ```
12
+
13
+ ## 快速开始
14
+
15
+ ```bash
16
+ # 人读
17
+ npx dsh-plugin-publish-check check --dir packages/my-plugin
18
+
19
+ # 机读
20
+ npx dsh-plugin-publish-check check --dir packages/my-plugin --json
21
+
22
+ # 额外校验 npm tarball 里真的有入口文件
23
+ npx dsh-plugin-publish-check check --dir packages/my-plugin --pack
24
+ ```
25
+
26
+ 输出示例:
27
+
28
+ ```text
29
+ release check: packages/my-plugin
30
+ ✓ name my-plugin
31
+ ✓ version 0.1.0
32
+ ✓ private 不是 private
33
+ ✓ license MIT
34
+ ✓ repository git+https://github.com/you/repo.git
35
+ ✓ description
36
+ ✓ main ./index.js
37
+ ✓ exports/./client ./client.js
38
+ ✓ files: index.js
39
+ ✓ dsh.bundle
40
+ ✓ dsh.bundle.patch ./cordis.patch.yml
41
+ ✓ client 产物 client.js
42
+ ✓ 运行时 dependencies 无
43
+ ✓ npm pack --dry-run 可打包,6 个文件
44
+ ✓ tarball 含入口文件 exports/bin/main/types 均被打包
45
+
46
+ === ✓ 通过 ===
47
+ ```
48
+
49
+ 每行一项检查:`✓` 通过、`⚠` 警告、`✗` 错误。错误行会带 `→ fix` 修复建议。
50
+
51
+ ## 用法 / API
52
+
53
+ ### CLI
54
+
55
+ | 命令 | 作用 |
56
+ |---|---|
57
+ | `check --dir <dir>` | 对 `<dir>` 跑检查 |
58
+
59
+ `check` **不能省**——省掉是用法错误(退出 `2`)。
60
+
61
+ ### 选项
62
+
63
+ | 选项 | 默认值 | 含义 |
64
+ |---|---|---|
65
+ | `--dir <dir>` | `.` | 要检查的包目录。必须是**独立的两个 token**:`--dir path`,不是 `--dir=path` |
66
+ | `--json` | 关 | 打印完整的 `{ dir, checks, errors, warnings }` 对象 |
67
+ | `--pack` | 关 | 额外跑 `npm pack --dry-run --json`,校验入口目标是否真进了 tarball |
68
+ | `--help`、`-h` | — | 打印用法并退出 `0` |
69
+
70
+ ### 退出码
71
+
72
+ | 码 | 含义 |
73
+ |---|---|
74
+ | `0` | 无错误(允许有警告) |
75
+ | `1` | 至少一个错误 |
76
+ | `2` | 用法错误:缺/未知子命令、`--dir` 缺值 |
77
+
78
+ ### 编程接口
79
+
80
+ ```js
81
+ import { checkPublish, entriesMissingFromTarball, expandGlob } from 'dsh-plugin-publish-check'
82
+
83
+ const r = checkPublish('packages/my-plugin', { pack: true })
84
+ ```
85
+
86
+ | 导出 | 签名 | 返回 |
87
+ |---|---|---|
88
+ | `checkPublish` | `checkPublish(dir, { pack = false })` | `{ dir, checks, errors, warnings }` |
89
+ | `entriesMissingFromTarball` | `entriesMissingFromTarball(targets, packedPaths, dir?)` | `[[label, missingPath], …]` |
90
+ | `expandGlob` | `expandGlob(dir, pattern)` | 匹配该模式的相对路径(正斜杠) |
91
+
92
+ `checks` 是 `{ status, name, detail, fix }` 数组,`status` 取 `'ok' | 'warn' | 'error'`。`errors` / `warnings` 里只有检查项的**名字**。
93
+
94
+ ## 检查哪些东西
95
+
96
+ ### package.json 元数据
97
+
98
+ | 检查 | 结果 |
99
+ |---|---|
100
+ | `name` | 缺失即错误 |
101
+ | `version` | 缺失即错误;恰好是 `0.0.0` 记**警告** |
102
+ | `private` | 为 `true` 即错误(npm 拒绝发布) |
103
+ | `license` | 有 `license` 字段**或**有 `LICENSE` / `LICENSE.md` / `LICENSE.txt` 文件即通过;否则警告 |
104
+ | `repository` | 缺失记警告;**仍是占位符**(`<…>`、`your-org`、`example.com`)也记警告 |
105
+ | `description` | 缺失记警告 |
106
+
107
+ ### 入口目标是否真实存在
108
+
109
+ 会收集这些字段并逐个在磁盘上解析:
110
+
111
+ - `main`(字符串)
112
+ - `types`(字符串)
113
+ - `bin`——字符串形式,或对象形式的每一个值
114
+ - `exports`——递归遍历,只收「目标像源文件」(`*.js`、`*.mjs`、`*.cjs`、`*.json`、`*.d.ts`、`*.ts`)或含 `*` 的字符串值
115
+
116
+ 字面路径:存在即通过,不存在记**错误**。通配路径:在目录下展开,有匹配则通过并报匹配数,**一个都匹配不到记错误**(`检查 glob 路径 / 先 build`)。
117
+
118
+ ### `bin` 的跨平台执行契约
119
+
120
+ 对每个 `.js` / `.mjs` / `.cjs` 命令目标,额外做两项零网络检查,违反即**错误**:
121
+
122
+ - 路径**不能以 `./` 开头**——npm 可能把 `./bin/x.mjs` 判为 invalid,并在发布时移除这个命令;
123
+ - 首行必须恰好是 `#!/usr/bin/env node`——POSIX 下 `npx` 会直接执行 bin 软链,没有 shebang 的 JavaScript 文件会被当成 shell 脚本。
124
+
125
+ 这两项专门补「文件存在、tarball 也正常,但装到 Linux/macOS 后命令仍不能跑」的盲区。
126
+
127
+ ### `files` 条目
128
+
129
+ 每个非通配条目都必须在磁盘上存在;不存在记**警告**(删掉该条或补上目录)。通配条目在这一步跳过。
130
+
131
+ ### DSH bundle
132
+
133
+ | 检查 | 结果 |
134
+ |---|---|
135
+ | 有 `dsh.bundle` | 通过;该包按 DSH 插件对待 |
136
+ | `dsh.bundle.patch` | 若是字符串,文件必须存在,否则错误 |
137
+ | client 产物 | 若设了 `dsh.client` 或 `exports['./client']`,则 `client.js` 必须存在,否则错误(`UI 不显示`) |
138
+
139
+ **没有 `dsh.bundle` 表示「库/工具包」,不是「插件坏了」。** 这种情况跳过 bundle 相关检查,改记一行 `包类型 非 DSH 插件包` 的通过项——不误报。
140
+
141
+ ### 运行时依赖
142
+
143
+ - 插件包(有 `dsh.bundle`)带任何 `dependencies`:记**警告**——确认可安装,或改为构建时 bundle。
144
+ - 库/工具包:有依赖按正常处理。
145
+
146
+ ### `--pack`:tarball 里到底有没有入口文件
147
+
148
+ 这一项专抓真实发布盲区:磁盘上一切看起来都对,但 `files` 悄悄把入口排除在外,发出去的包直接用不了。
149
+
150
+ 带 `--pack` 时,工具在包目录跑 `npm pack --dry-run --json`,然后:
151
+
152
+ 1. 报打包是否成功、产出几个文件;
153
+ 2. 把收集到的 `main` / `types` / `bin` / `exports` 目标与打包文件清单比对,**通配 exports 先展开成具体文件**;
154
+ 3. 每个缺失目标单独记一条**错误**(`tarball 缺少 <label>`),提示把文件纳入 `files` 或修正入口字段。
155
+
156
+ 例子——`files: ["dist/"]`,而 `main` 指向 `src/index.mjs`:
157
+
158
+ ```text
159
+ ✓ main ./src/index.mjs
160
+ ✓ npm pack --dry-run 可打包,4 个文件
161
+ ✗ tarball 缺少 main src/index.mjs → 把该文件纳入 files(或修正 exports/bin/main/types)
162
+ ✗ tarball 缺少 exports/. src/index.mjs → …
163
+ ```
164
+
165
+ 不带 `--pack` 时这个缺陷完全看不见。CI 里发布前建议一律带 `--pack`。
166
+
167
+ ## 注意事项
168
+
169
+ - `--pack` 需要 `PATH` 上有可用的 `npm`;检查通过 `shell: true` 调外部命令。
170
+ - `--pack` 只做 **dry run**——不往 registry 写任何东西,也不留下 tarball。
171
+ - `--dir` 与 `--pack` 都是按位置从 `argv` 里读的;`--dir=value` 不被识别,会静默退回当前目录。务必用 `--dir <dir>` 两个 token。
172
+ - 警告永远不会让构建失败。需要严格门禁时,用 API 判 `errors.length`,或解析 `--json`。
173
+ - 没有 `package.json` 时只报一条 `package.json` 错误并提前结束。
174
+
175
+ ## License
176
+
177
+ MIT
@@ -0,0 +1,38 @@
1
+ #!/usr/bin/env node
2
+ import { checkPublish } from '../src/index.mjs'
3
+
4
+ const USAGE = '用法: dsh-plugin-publish-check check --dir <pluginDir> [--json] [--pack]'
5
+ const args = process.argv.slice(2)
6
+ if (args.includes('--help') || args.includes('-h')) {
7
+ console.log(USAGE)
8
+ process.exit(0)
9
+ }
10
+ const sub = args[0] && !args[0].startsWith('--') ? args[0] : null
11
+ if (sub !== 'check') {
12
+ console.error(USAGE)
13
+ process.exit(2)
14
+ }
15
+ const opt = (n, d) => {
16
+ // 同时支持 `--dir X` 和 `--dir=X`:此前只认空格写法,等号写法会静默退回默认值。
17
+ const eq = args.find((a) => a.startsWith('--' + n + '='))
18
+ if (eq !== undefined) return eq.slice(n.length + 3)
19
+ const i = args.indexOf('--' + n)
20
+ return i >= 0 ? args[i + 1] : d
21
+ }
22
+ const dir = opt('dir', '.')
23
+ if (dir === undefined || String(dir).startsWith('-')) {
24
+ console.error('--dir 缺值\n' + USAGE)
25
+ process.exit(2)
26
+ }
27
+ const r = checkPublish(dir, { pack: args.includes('--pack') })
28
+ if (args.includes('--json')) {
29
+ console.log(JSON.stringify(r, null, 2))
30
+ } else {
31
+ console.log('release check: ' + r.dir)
32
+ for (const c of r.checks) {
33
+ const mark = c.status === 'ok' ? '✓' : c.status === 'warn' ? '⚠' : '✗'
34
+ console.log(' ' + mark + ' ' + c.name + (c.detail ? ' ' + c.detail : '') + (c.fix ? ' → ' + c.fix : ''))
35
+ }
36
+ console.log('\n=== ' + (r.errors.length ? '✗ ' + r.errors.length + ' 错误' : '✓ 通过') + (r.warnings.length ? ' ⚠ ' + r.warnings.length + ' 警告' : '') + ' ===')
37
+ }
38
+ process.exit(r.errors.length ? 1 : 0)
package/package.json CHANGED
@@ -1,6 +1,37 @@
1
1
  {
2
2
  "name": "dsh-plugin-publish-check",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.3",
4
+ "private": false,
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "description": "Publish-readiness check for DSH plugins: package.json metadata (name/version/private/license/repository), entry/bin/files targets exist, dsh.bundle + patch + client.js, runtime deps, and optional npm pack dry-run.",
8
+ "bin": {
9
+ "dsh-plugin-publish-check": "bin/dsh-plugin-publish-check.mjs"
10
+ },
11
+ "exports": {
12
+ ".": "./src/index.mjs"
13
+ },
14
+ "files": [
15
+ "bin/",
16
+ "src/",
17
+ "README.md",
18
+ "README.zh-CN.md"
19
+ ],
20
+ "repository": {
21
+ "type": "git",
22
+ "url": "git+https://github.com/metal-huang/dsh-devtools.git",
23
+ "directory": "packages/dsh-plugin-publish-check"
24
+ },
25
+ "publishConfig": {
26
+ "access": "public",
27
+ "registry": "https://registry.npmjs.org/"
28
+ },
29
+ "engines": {
30
+ "dsh": ">=0.2.2-rc.5",
31
+ "node": ">=22.15.0"
32
+ },
33
+ "dshTestedOn": [
34
+ "0.2.2-rc.5",
35
+ "0.2.3-alpha.2"
36
+ ]
37
+ }
package/src/index.mjs ADDED
@@ -0,0 +1,254 @@
1
+ // 发布体检:读包目录,检查"能不能发/发得好不好"。返回 {checks, errors, warnings}。
2
+ import { readFileSync, existsSync, readdirSync } from 'node:fs'
3
+ import { join } from 'node:path'
4
+ import { spawnSync } from 'node:child_process'
5
+
6
+ const readJson = (p) => {
7
+ try {
8
+ return JSON.parse(readFileSync(p, 'utf8'))
9
+ } catch {
10
+ return null
11
+ }
12
+ }
13
+ const ARTICLE_EXT = /\.(js|mjs|cjs|json|d\.ts|ts)$/
14
+ const JS_BIN_EXT = /\.(js|mjs|cjs)$/
15
+
16
+ /** 返回 bin 的 [命令名, 相对路径];兼容字符串与对象两种 package.json 写法。 */
17
+ export function binEntries(pkg) {
18
+ if (!pkg?.bin) return []
19
+ if (typeof pkg.bin === 'string')
20
+ return [
21
+ [
22
+ String(pkg.name || 'bin')
23
+ .split('/')
24
+ .pop(),
25
+ pkg.bin,
26
+ ],
27
+ ]
28
+ return Object.entries(pkg.bin)
29
+ }
30
+
31
+ /**
32
+ * 检查 bin 的跨平台可执行性。仅“文件存在且进了 tarball”不够:
33
+ * - POSIX 下 npx 的 .bin 软链直接执行目标,JS 文件没有 node shebang 会被当成 shell 脚本。
34
+ * - npm 会把 `./bin/x.mjs` 判为 invalid 并在发布时移除,导致包装好后没有命令。
35
+ */
36
+ export function checkBinContracts(dir, pkg, add) {
37
+ for (const [name, rel] of binEntries(pkg)) {
38
+ const label = 'bin:' + name
39
+ if (typeof rel !== 'string' || !rel.trim()) {
40
+ add('error', label + ' 路径为空', '', 'bin 必须指向实际 JS 文件')
41
+ continue
42
+ }
43
+ if (rel.startsWith('./')) {
44
+ add(
45
+ 'error',
46
+ label + ' 路径不应以 ./ 开头',
47
+ rel,
48
+ '改为 ' + rel.slice(2) + '(否则 npm 发布时会移除该 bin)',
49
+ )
50
+ }
51
+ const file = join(dir, rel)
52
+ if (!existsSync(file) || !JS_BIN_EXT.test(rel)) continue
53
+ const firstLine = readFileSync(file, 'utf8')
54
+ .replace(/^\uFEFF/, '')
55
+ .split(/\r?\n/, 1)[0]
56
+ if (firstLine !== '#!/usr/bin/env node') {
57
+ add(
58
+ 'error',
59
+ label + ' 缺少 node shebang',
60
+ rel,
61
+ '首行加 #!/usr/bin/env node(否则 POSIX 的 .bin 无法执行)',
62
+ )
63
+ } else {
64
+ add('ok', label + ' shebang', firstLine)
65
+ }
66
+ }
67
+ }
68
+
69
+ /** glob -> 正则(支持 * 与 **),用于校验通配 exports 是否真的有匹配文件。 */
70
+ function globToRegExp(g) {
71
+ const esc = String(g)
72
+ .replace(/[.+^${}()|[\]\\]/g, '\\$&')
73
+ .replace(/\*\*/g, '\u0000')
74
+ .replace(/\*/g, '[^/]*')
75
+ .replace(/\u0000/g, '.*')
76
+ return new RegExp('^' + esc + '$')
77
+ }
78
+
79
+ /** 在 dir 下递归展开 glob(相对路径,正斜杠)。 */
80
+ export function expandGlob(dir, pattern) {
81
+ const rel = String(pattern).replace(/^\.\//, '').replace(/\\/g, '/')
82
+ const re = globToRegExp(rel)
83
+ let all
84
+ try {
85
+ all = readdirSync(dir, { recursive: true })
86
+ } catch {
87
+ return []
88
+ }
89
+ return all.map((p) => String(p).replace(/\\/g, '/')).filter((p) => re.test(p))
90
+ }
91
+
92
+ /** 返回 targets([label, rel],rel 可为 glob)里未被打进 tarball 的项;用于 --pack 拦"发布缺入口"。 */
93
+ export function entriesMissingFromTarball(targets, packedPaths, dir) {
94
+ const norm = (p) => String(p).replace(/^\.\//, '').replace(/\\/g, '/')
95
+ const packed = new Set((packedPaths || []).map(norm))
96
+ const missing = []
97
+ for (const [label, rel] of targets) {
98
+ if (!rel) continue
99
+ const matches = String(rel).includes('*') ? (dir ? expandGlob(dir, rel) : []) : [norm(rel)]
100
+ if (matches.length === 0) {
101
+ missing.push([label, rel + '(无匹配文件)'])
102
+ continue
103
+ }
104
+ for (const m of matches) {
105
+ const want = norm(m)
106
+ if (!packed.has(want)) missing.push([label, want])
107
+ }
108
+ }
109
+ return missing
110
+ }
111
+
112
+ export function checkPublish(dir, { pack = false } = {}) {
113
+ const checks = []
114
+ const errors = []
115
+ const warnings = []
116
+ const add = (status, name, detail = '', fix = '') => {
117
+ checks.push({ status, name, detail, fix })
118
+ if (status === 'error') errors.push(name)
119
+ if (status === 'warn') warnings.push(name)
120
+ }
121
+ const pjPath = join(dir, 'package.json')
122
+ const pkg = readJson(pjPath)
123
+ if (!pkg) {
124
+ add('error', 'package.json', '读不到 ' + pjPath)
125
+ return { dir, checks, errors, warnings }
126
+ }
127
+ if (pkg.name) add('ok', 'name', pkg.name)
128
+ else add('error', 'name', '缺失')
129
+ if (pkg.version) {
130
+ if (pkg.version === '0.0.0') add('warn', 'version', '0.0.0(建议语义版本)', '改 0.1.0 起')
131
+ else add('ok', 'version', pkg.version)
132
+ } else add('error', 'version', '缺失')
133
+ if (pkg.private === true)
134
+ add('error', 'private', 'private:true 会阻止发布', '去掉 private 或设 false')
135
+ else add('ok', 'private', '不是 private')
136
+ const hasLicense =
137
+ !!pkg.license || ['LICENSE', 'LICENSE.md', 'LICENSE.txt'].some((f) => existsSync(join(dir, f)))
138
+ if (hasLicense) add('ok', 'license', pkg.license || 'LICENSE 文件')
139
+ else add('warn', 'license', '无 license 字段/文件', '加 license 字段与 LICENSE')
140
+ if (pkg.repository) {
141
+ const url = typeof pkg.repository === 'string' ? pkg.repository : pkg.repository.url || ''
142
+ if (/<[^>]*>|your-org|example\.com/i.test(url))
143
+ add('warn', 'repository', '仍是占位符: ' + url, '发布前换真实仓库地址')
144
+ else add('ok', 'repository', url)
145
+ } else add('warn', 'repository', '缺失', '补 repository 与 directory')
146
+ if (pkg.description) add('ok', 'description')
147
+ else add('warn', 'description', '缺失')
148
+
149
+ // 入口目标是否存在
150
+ const targets = []
151
+ if (typeof pkg.main === 'string') targets.push(['main', pkg.main])
152
+ if (typeof pkg.types === 'string') targets.push(['types', pkg.types])
153
+ if (pkg.bin) {
154
+ for (const [name, rel] of binEntries(pkg)) targets.push(['bin:' + name, rel])
155
+ }
156
+ if (pkg.exports) {
157
+ const walk = (v, path) => {
158
+ if (typeof v === 'string') {
159
+ if (ARTICLE_EXT.test(v) || v.includes('*')) targets.push(['exports' + path, v])
160
+ } else if (v && typeof v === 'object') {
161
+ for (const k of Object.keys(v)) walk(v[k], path + '/' + k)
162
+ }
163
+ }
164
+ walk(pkg.exports, '')
165
+ }
166
+ for (const [label, rel] of targets) {
167
+ if (String(rel).includes('*')) {
168
+ const m = expandGlob(dir, rel)
169
+ if (m.length) add('ok', label, rel + '(' + m.length + ' 个)')
170
+ else add('error', label + ' 通配无匹配文件', rel, '检查 glob 路径 / 先 build')
171
+ } else if (existsSync(join(dir, rel))) add('ok', label, rel)
172
+ else add('error', label + ' 目标不存在', rel, '检查路径 / 先 build')
173
+ }
174
+ checkBinContracts(dir, pkg, add)
175
+
176
+ // files 项存在性
177
+ if (Array.isArray(pkg.files)) {
178
+ for (const f of pkg.files) {
179
+ if (f.includes('*')) continue
180
+ if (existsSync(join(dir, f.replace(/\/$/, '')))) add('ok', 'files: ' + f)
181
+ else add('warn', 'files 项不存在: ' + f, '', '删掉该条或补目录')
182
+ }
183
+ }
184
+
185
+ // DSH bundle
186
+ const dsh = pkg.dsh || {}
187
+ const bundle = dsh.bundle
188
+ if (bundle) {
189
+ add('ok', 'dsh.bundle')
190
+ const patch = typeof bundle.patch === 'string' ? bundle.patch : null
191
+ if (patch) {
192
+ if (existsSync(join(dir, patch))) add('ok', 'dsh.bundle.patch', patch)
193
+ else add('error', 'dsh.bundle.patch 文件缺失', patch)
194
+ }
195
+ const client = dsh.client || (pkg.exports && pkg.exports['./client'])
196
+ if (client) {
197
+ if (existsSync(join(dir, 'client.js'))) add('ok', 'client 产物 client.js')
198
+ else add('error', 'client.js 缺失(UI 不显示)', '', '在插件目录 build')
199
+ }
200
+ } else {
201
+ // 没有 dsh.bundle:属库/工具包(非 DSH 插件),不按插件规则要求 bundle。
202
+ add('ok', '包类型', '非 DSH 插件包(无 dsh.bundle,按库/工具处理)')
203
+ }
204
+
205
+ // 运行时依赖:插件包要求无运行时依赖(bundle);库/工具包有依赖是正常的。
206
+ const deps = Object.keys(pkg.dependencies || {})
207
+ if (bundle) {
208
+ if (deps.length)
209
+ add(
210
+ 'warn',
211
+ '运行时 dependencies',
212
+ deps.length + ' 个: ' + deps.join(','),
213
+ '确认可安装,或改为 build 时 bundle',
214
+ )
215
+ else add('ok', '运行时 dependencies', '无')
216
+ } else {
217
+ add('ok', '运行时 dependencies', deps.length ? deps.length + ' 个(库/工具包,正常)' : '无')
218
+ }
219
+
220
+ if (pack) {
221
+ const r = spawnSync('npm pack --dry-run --json', { cwd: dir, encoding: 'utf8', shell: true })
222
+ if (r.status === 0) {
223
+ let n = 0
224
+ let packed = []
225
+ try {
226
+ const arr = JSON.parse(r.stdout)
227
+ n = arr[0]?.files?.length ?? 0
228
+ packed = (arr[0]?.files || []).map((f) => f.path)
229
+ } catch {}
230
+ add('ok', 'npm pack --dry-run', '可打包' + (n ? ',' + n + ' 个文件' : ''))
231
+ const missing = entriesMissingFromTarball(targets, packed, dir)
232
+ if (missing.length) {
233
+ for (const [label, want] of missing)
234
+ add(
235
+ 'error',
236
+ 'tarball 缺少 ' + label,
237
+ want,
238
+ '把该文件纳入 files(或修正 exports/bin/main/types)',
239
+ )
240
+ } else {
241
+ add('ok', 'tarball 含入口文件', 'exports/bin/main/types 均被打包')
242
+ }
243
+ } else {
244
+ add(
245
+ 'error',
246
+ 'npm pack --dry-run',
247
+ (String(r.stderr || r.stdout || '').split('\n')[0] || 'failed').trim(),
248
+ '先修打包错误',
249
+ )
250
+ }
251
+ }
252
+
253
+ return { dir, checks, errors, warnings }
254
+ }