@vitex/tcm-cli 0.1.0 → 0.3.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/README.md CHANGED
@@ -97,11 +97,22 @@ tcm logout
97
97
  | 退出码 | 含义 |
98
98
  | --- | --- |
99
99
  | `0` | 成功 |
100
- | `1` | 业务/网络/授权错误(`ApiError`) |
100
+ | `1` | 业务/网络/授权错误(`ApiError`),或本地工具执行失败(`ToolError`,见下) |
101
101
  | `2` | 参数或用法错误(`UsageError`) |
102
102
 
103
103
  业务失败(HTTP 200 但 `code !== 1`)与 HTTP 非 2xx 都会被视为失败。触发限流时后端返回 `HTTP 429`,错误的 `data.retryAfterMs` 给出建议重试等待毫秒数。
104
104
 
105
+ `tool` 分组下的命令在本地直接抓第三方页面(不经过 TCM 后端),失败时 `type` 为具体原因:
106
+
107
+ ```json
108
+ { "error": { "type": "FetchError", "message": "抓取抖音页面失败(…):HTTP 404", "status": 404 } }
109
+ ```
110
+
111
+ | `type` | 含义 |
112
+ | --- | --- |
113
+ | `FetchError` | 网络失败 / 超时 / HTTP 非 2xx,带 `status` |
114
+ | `ParseError` | 页面结构不符(视频不存在、被风控、抖音改版) |
115
+
105
116
  ## 参数约定
106
117
 
107
118
  - 标量:`--pageNum 1`、`--status NORMAL`
@@ -114,6 +125,7 @@ tcm logout
114
125
  - `--input @input.json`
115
126
  - 文件上传(multipart):传本地路径,如 `--file ./a.png`
116
127
  - 布尔筛选:出现即为 `true`,例如 `--verified`
128
+ - 必填布尔值:显式写 `true` / `false`,例如 `tcm comment update --folded false`(`--folded` 这种开关写法表达不了 `false`)
117
129
 
118
130
  ## 命令一览
119
131
 
@@ -127,11 +139,9 @@ tcm logout
127
139
 
128
140
  - `tcm user list` — 分页查询用户(管理员)
129
141
  - `tcm user me` — 当前登录用户
130
- - `tcm user create` — 新建用户(返回仅此一次可见的明文密码)
142
+ - `tcm user create` — 新建用户
131
143
  - `tcm user update` — 编辑用户
132
- - `tcm user reset-password` — 重置用户密码
133
144
  - `tcm user api-key` — 获取当前用户 API Key(旧 Key 立即失效)
134
- - `tcm user change-password` — 修改当前用户密码
135
145
 
136
146
  ### workbench — 工作台统计
137
147
 
@@ -146,6 +156,8 @@ tcm logout
146
156
 
147
157
  `list`、`get`、`create`、`update`、`status`、`names`、`summary`、`logs`、`statistics`
148
158
 
159
+ 机器对象带两个 IP 字段:`ip` 是内网 IP,`publicIp` 是 Agent 心跳时探测的公网出口 IP(探测失败为 `null`,不携带该字段的旧 Agent 也是 `null`)。`machine list` / `machine get` 与工作台 `workbench machine-cards` 都返回 `publicIp`;`--keyword` 只匹配 `ip`(内网)等文本字段,不能按 `publicIp` 搜索。
160
+
149
161
  ### account — 账号
150
162
 
151
163
  `list`、`get`、`update`、`status`、`toggle-verify`、`brief`、`summary`、`logs`、`cookies`
@@ -170,8 +182,9 @@ tcm logout
170
182
 
171
183
  - `author`:`list`、`get`、`create`、`update`、`status`、`profile`
172
184
  - `aweme`:`list`、`get`、`analysis`
173
- - `comment`:`list`、`get`
185
+ - `comment`:`list`、`get`、`refresh`、`update`
174
186
  - `comment-candidate`:`list`、`discard`
187
+ - `comment-strategy`(仅管理员):`list`、`get`、`create`、`update`、`delete`
175
188
  - `hot-comment`:`list`
176
189
 
177
190
  ### material / draft / item — 素材 / 草稿 / 作品
@@ -180,6 +193,26 @@ tcm logout
180
193
  - `draft`:`list`、`create`、`create-urls`、`discard`
181
194
  - `item`:`list`
182
195
 
196
+ ### tool — 本地取数工具
197
+
198
+ 本地执行、直接抓第三方公开页面,**不经过 TCM 后端、不需要登录、不写库**。
199
+
200
+ - `tcm tool seo_video_detail --id <awemeId>` — 按视频 ID 取抖音 SEO 版视频页:视频(文案 / 封面 / 发布时间 / 时长 / 点赞 / 评论 / 收藏 / 分享)、达人(昵称 / secUid / 获赞 / 粉丝)、首屏 10 条评论
201
+ - 也支持 `--url <链接或分享文案>`(短链会自动跟随跳转)与 `--html <本地文件>`(离线解析已保存的页面)
202
+ - 点赞 / 收藏 / 分享来自页面展示文本(`5.4万` → `54000`),是**近似值**;评论数取 ld+json 的精确值
203
+ - 只有首屏 10 条一级评论,没有视频直链 / 音乐 / 弹幕
204
+
205
+ ```bash
206
+ # 按 ID
207
+ tcm tool seo_video_detail --id 7701278853448142120 --compact
208
+
209
+ # 按链接(分享文案也行)
210
+ tcm tool seo_video_detail --url https://www.douyin.com/video/7701278853448142120
211
+
212
+ # 离线重放(排查页面改版用)
213
+ tcm tool seo_video_detail --html ./page.html --compact
214
+ ```
215
+
183
216
  每个命令都支持 `--help` 查看完整参数,例如:
184
217
 
185
218
  ```bash
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vitex/tcm-cli",
3
- "version": "0.1.0",
3
+ "version": "0.3.0",
4
4
  "description": "TCM 控制台命令行工具(面向 agent,JSON 输入输出)",
5
5
  "type": "module",
6
6
  "bin": {
package/src/args.js CHANGED
@@ -53,6 +53,14 @@ function coerce(name, spec, raw) {
53
53
  }
54
54
  case 'boolean':
55
55
  return raw === true || raw === 'true'
56
+ case 'flag': {
57
+ // 值必须显式给出:flag 用字符串选项承接,--x false 才能真的传 false。
58
+ const text = String(raw).trim().toLowerCase()
59
+ if (text !== 'true' && text !== 'false') {
60
+ throw new UsageError(`--${name} 需要是 true 或 false`)
61
+ }
62
+ return text === 'true'
63
+ }
56
64
  default:
57
65
  return String(raw)
58
66
  }
@@ -0,0 +1,65 @@
1
+ import { pick, post, string, number, flag, array, json, pageNum, pageSize, id } from './common.js'
2
+
3
+ /** 创建 / 编辑共用的请求体:windows 是 [{begin,end,limit}] 的 JSON 数组,不传的字段按覆盖语义处理。 */
4
+ const strategyBody = (p) =>
5
+ pick(p, ['id', 'name', 'description', 'tags', 'windows', 'interval', 'weight', 'enabled'])
6
+
7
+ export default {
8
+ summary: '评论策略(仅管理员)',
9
+ commands: {
10
+ list: {
11
+ summary: '分页查询评论策略',
12
+ params: {
13
+ keyword: string('关键词(策略名称)'),
14
+ enabled: flag('只看启用 / 停用:true / false'),
15
+ pageNum: pageNum(1),
16
+ pageSize: pageSize(20),
17
+ },
18
+ build: (p) =>
19
+ post('/api/comment/strategy/page', pick(p, ['keyword', 'enabled', 'pageNum', 'pageSize'])),
20
+ },
21
+ get: {
22
+ summary: '评论策略详情',
23
+ params: { id: id('策略 ID') },
24
+ build: (p) => post('/api/comment/strategy/detail', pick(p, ['id'])),
25
+ },
26
+ create: {
27
+ summary: '创建评论策略',
28
+ params: {
29
+ name: string('策略名称', { required: true }),
30
+ description: string('策略描述'),
31
+ tags: array('命中哪些账号标签,可重复/逗号分隔;不传表示不限账号'),
32
+ windows: json(
33
+ '时间窗口 JSON 数组,如 \'[{"begin":9,"end":12,"limit":5}]\'(小时整点,0≤begin<end≤24,limit 0~30)',
34
+ { required: true },
35
+ ),
36
+ interval: number('评论间隔(分钟,1~240)', { required: true }),
37
+ weight: number('策略权重(0~100,必填;同账号命中多条时取最大)', { required: true }),
38
+ enabled: flag('是否启用,true / false(不传默认启用)'),
39
+ },
40
+ build: (p) => post('/api/comment/strategy/create', strategyBody(p)),
41
+ },
42
+ update: {
43
+ summary: '编辑评论策略(整体覆盖)',
44
+ params: {
45
+ id: id('策略 ID'),
46
+ name: string('策略名称', { required: true }),
47
+ description: string('策略描述'),
48
+ tags: array('命中哪些账号标签,可重复/逗号分隔;不传会清空'),
49
+ windows: json(
50
+ '时间窗口 JSON 数组,如 \'[{"begin":9,"end":12,"limit":5}]\'(小时整点,0≤begin<end≤24,limit 0~30)',
51
+ { required: true },
52
+ ),
53
+ interval: number('评论间隔(分钟,1~240)', { required: true }),
54
+ weight: number('策略权重(0~100)', { required: true }),
55
+ enabled: flag('是否启用,true / false(不传默认启用)'),
56
+ },
57
+ build: (p) => post('/api/comment/strategy/update', strategyBody(p)),
58
+ },
59
+ delete: {
60
+ summary: '删除评论策略',
61
+ params: { id: id('策略 ID') },
62
+ build: (p) => post('/api/comment/strategy/delete', pick(p, ['id'])),
63
+ },
64
+ },
65
+ }
@@ -1,4 +1,4 @@
1
- import { pick, post, string, date, pageNum, pageSize, id } from './common.js'
1
+ import { pick, post, string, date, pageNum, pageSize, id, number, flag } from './common.js'
2
2
 
3
3
  export default {
4
4
  summary: '评论',
@@ -10,8 +10,11 @@ export default {
10
10
  platformAwemeId: string('平台作品 ID'),
11
11
  accountSecUid: string('账号 secUid'),
12
12
  keyword: string('关键词'),
13
- startDate: date('开始日期'),
14
- endDate: date('结束日期'),
13
+ startDate: date('开始日期(发布时间)'),
14
+ endDate: date('结束日期(发布时间)'),
15
+ refreshStartDate: date('刷新开始日期'),
16
+ refreshEndDate: date('刷新结束日期'),
17
+ minDiggCount: number('最小点赞数'),
15
18
  pageNum: pageNum(1),
16
19
  pageSize: pageSize(20),
17
20
  },
@@ -25,6 +28,9 @@ export default {
25
28
  'keyword',
26
29
  'startDate',
27
30
  'endDate',
31
+ 'refreshStartDate',
32
+ 'refreshEndDate',
33
+ 'minDiggCount',
28
34
  'pageNum',
29
35
  'pageSize',
30
36
  ]),
@@ -35,5 +41,26 @@ export default {
35
41
  params: { id: id('评论 ID') },
36
42
  build: (p) => post('/api/comment/comment/detail', pick(p, ['id'])),
37
43
  },
44
+ refresh: {
45
+ summary: '刷新评论(实时拉抖音最新数据,点赞没变大就不改)',
46
+ params: { id: id('评论 ID') },
47
+ build: (p) => post('/api/comment/comment/refresh', pick(p, ['id'])),
48
+ },
49
+ update: {
50
+ summary: '直接更新评论数据(整体覆盖)',
51
+ params: {
52
+ id: id('评论 ID'),
53
+ diggCount: number('点赞数(不能小于当前值)', { required: true }),
54
+ replyCount: number('回复数', { required: true }),
55
+ folded: flag('是否折叠', { required: true }),
56
+ hot: flag('是否热评', { required: true }),
57
+ authorDigged: flag('作者是否点赞', { required: true }),
58
+ },
59
+ build: (p) =>
60
+ post(
61
+ '/api/comment/comment/update',
62
+ pick(p, ['id', 'diggCount', 'replyCount', 'folded', 'hot', 'authorDigged']),
63
+ ),
64
+ },
38
65
  },
39
66
  }
@@ -24,6 +24,8 @@ export const get = (path) => ({ method: 'GET', path })
24
24
  export const string = (desc, extra = {}) => ({ type: 'string', desc, ...extra })
25
25
  export const number = (desc, extra = {}) => ({ type: 'number', desc, ...extra })
26
26
  export const boolean = (desc, extra = {}) => ({ type: 'boolean', desc, ...extra })
27
+ /** 必须显式写 true / false 的布尔参数:boolean 选项只能表达「开了」,没法表达 false。 */
28
+ export const flag = (desc, extra = {}) => ({ type: 'flag', desc, ...extra })
27
29
  export const array = (desc, extra = {}) => ({ type: 'array', desc, ...extra })
28
30
  export const json = (desc, extra = {}) => ({ type: 'json', desc, ...extra })
29
31
 
@@ -11,10 +11,12 @@ import author from './author.js'
11
11
  import aweme from './aweme.js'
12
12
  import comment from './comment.js'
13
13
  import commentCandidate from './comment-candidate.js'
14
+ import commentStrategy from './comment-strategy.js'
14
15
  import hotComment from './hot-comment.js'
15
16
  import material from './material.js'
16
17
  import draft from './draft.js'
17
18
  import item from './item.js'
19
+ import tool from './tool.js'
18
20
  import { topCommands } from './auth.js'
19
21
 
20
22
  export const groups = {
@@ -31,10 +33,12 @@ export const groups = {
31
33
  aweme,
32
34
  comment,
33
35
  'comment-candidate': commentCandidate,
36
+ 'comment-strategy': commentStrategy,
34
37
  'hot-comment': hotComment,
35
38
  material,
36
39
  draft,
37
40
  item,
41
+ tool,
38
42
  }
39
43
 
40
44
  export { topCommands }
@@ -6,7 +6,7 @@ export default {
6
6
  list: {
7
7
  summary: '分页查询机器',
8
8
  params: {
9
- keyword: string('关键词'),
9
+ keyword: string('关键词(匹配名称/备注/主机名/用户名/内网 IP/MAC)'),
10
10
  os: string('操作系统:MAC / WINDOWS / LINUX'),
11
11
  statuses: array('状态多选:INIT / NORMAL / HIDDEN'),
12
12
  health: string('健康状态:ONLINE / OFFLINE'),
@@ -0,0 +1,47 @@
1
+ import { UsageError } from '../args.js'
2
+ import { DEFAULT_TIMEOUT_MS } from '../config.js'
3
+ import { seoVideoDetail } from '../seo-video.js'
4
+ import { string } from './common.js'
5
+
6
+ function timeoutMs(global) {
7
+ const raw = global?.timeout
8
+ if (raw === undefined) return DEFAULT_TIMEOUT_MS
9
+ const value = Number(raw)
10
+ if (!Number.isFinite(value) || value <= 0) {
11
+ throw new UsageError('--timeout 需要是正整数(毫秒)')
12
+ }
13
+ return value
14
+ }
15
+
16
+ export default {
17
+ summary: '本地取数工具(抓第三方公开页面,不写 TCM)',
18
+ commands: {
19
+ seo_video_detail: {
20
+ summary: '按视频 ID 取抖音视频详情:视频 / 达人 / 首屏评论',
21
+ auth: false,
22
+ params: {
23
+ id: string('视频 ID(awemeId,按字符串传,19 位数字)'),
24
+ url: string('视频链接(也接受分享文案;短链会自动跟随跳转)'),
25
+ html: string('解析本地已保存的 HTML(离线调试,忽略 --id / --url)'),
26
+ },
27
+ examples: [
28
+ 'tcm tool seo_video_detail --id 7701278853448142120',
29
+ 'tcm tool seo_video_detail --url https://www.douyin.com/video/7701278853448142120',
30
+ 'tcm tool seo_video_detail --url "7.43 复制打开抖音… https://v.douyin.com/xxxx/" --compact',
31
+ 'tcm tool seo_video_detail --html ./page.html --compact',
32
+ ],
33
+ async run({ values, global }) {
34
+ const id = values.id?.trim()
35
+ const url = values.url?.trim()
36
+ const htmlPath = values.html?.trim()
37
+
38
+ if (!htmlPath) {
39
+ if (!id && !url) throw new UsageError('需要 --id 或 --url(--html 用于解析本地文件)')
40
+ if (id && url) throw new UsageError('--id 和 --url 只能传一个')
41
+ }
42
+
43
+ return seoVideoDetail({ id, url, htmlPath, timeoutMs: timeoutMs(global) })
44
+ },
45
+ },
46
+ },
47
+ }
@@ -18,38 +18,30 @@ export default {
18
18
  build: () => get('/api/user/me'),
19
19
  },
20
20
  create: {
21
- summary: '新建用户(返回仅此一次可见的明文密码)',
21
+ summary: '新建用户',
22
22
  params: {
23
23
  name: string('用户名', { required: true }),
24
+ email: string('登录邮箱', { required: true }),
24
25
  description: string('备注'),
25
26
  roles: array('角色,例如 ADMIN', { items: 'string' }),
26
27
  },
27
- build: (p) => post('/api/user/create', pick(p, ['name', 'description', 'roles'])),
28
+ build: (p) => post('/api/user/create', pick(p, ['name', 'email', 'description', 'roles'])),
28
29
  },
29
30
  update: {
30
31
  summary: '编辑用户',
31
32
  params: {
32
33
  id: id('用户 ID'),
33
34
  name: string('用户名', { required: true }),
35
+ email: string('登录邮箱', { required: true }),
34
36
  description: string('备注'),
35
37
  roles: array('角色,例如 ADMIN', { items: 'string' }),
36
38
  },
37
- build: (p) => post('/api/user/update', pick(p, ['id', 'name', 'description', 'roles'])),
38
- },
39
- 'reset-password': {
40
- summary: '重置用户密码(返回仅此一次可见的明文密码)',
41
- params: { id: id('用户 ID') },
42
- build: (p) => post('/api/user/resetpassword', pick(p, ['id'])),
39
+ build: (p) => post('/api/user/update', pick(p, ['id', 'name', 'email', 'description', 'roles'])),
43
40
  },
44
41
  'api-key': {
45
42
  summary: '获取当前用户 API Key(旧 Key 立即失效)',
46
43
  params: {},
47
44
  build: () => post('/api/user/apikey'),
48
45
  },
49
- 'change-password': {
50
- summary: '修改当前用户密码',
51
- params: { password: string('新密码', { required: true }) },
52
- build: (p) => post('/api/user/changepassword', pick(p, ['password'])),
53
- },
54
46
  },
55
47
  }
package/src/index.js CHANGED
@@ -7,6 +7,7 @@ import {
7
7
  parseCommandArgs,
8
8
  } from './args.js'
9
9
  import { groups, topCommands } from './commands/index.js'
10
+ import { ToolError } from './tool-error.js'
10
11
 
11
12
  const GLOBAL_OPTIONS = {
12
13
  help: { type: 'boolean', short: 'h' },
@@ -133,6 +134,13 @@ function handleError(error, compact) {
133
134
  if (error instanceof UsageError) {
134
135
  type = 'UsageError'
135
136
  exitCode = 2
137
+ } else if (error instanceof ToolError) {
138
+ type = error.type || 'ToolError'
139
+ body = {
140
+ message: error.message,
141
+ ...(error.status !== null && error.status !== undefined ? { status: error.status } : {}),
142
+ ...(error.data ? { data: error.data } : {}),
143
+ }
136
144
  } else if (error instanceof ApiError) {
137
145
  type = 'ApiError'
138
146
  body = { message: error.message, code: error.code, status: error.status, data: error.data }
@@ -146,8 +154,14 @@ function handleError(error, compact) {
146
154
 
147
155
  function typeLabel(spec) {
148
156
  const base =
149
- { string: 'string', number: 'number', boolean: 'boolean', array: 'array', json: 'json' }[spec.type] ||
150
- 'string'
157
+ {
158
+ string: 'string',
159
+ number: 'number',
160
+ boolean: 'boolean',
161
+ flag: 'true / false',
162
+ array: 'array',
163
+ json: 'json'
164
+ }[spec.type] || 'string'
151
165
  return spec.type === 'array' ? `${base}(可重复/逗号分隔)` : base
152
166
  }
153
167
 
@@ -0,0 +1,229 @@
1
+ /**
2
+ * 抖音 SEO 版视频页解析(本地执行,不经 TCM 后端)。
3
+ *
4
+ * 原理:用搜索引擎 UA 直接 GET 视频页,抖音会回一份带 SEO 数据的 SSR HTML:
5
+ * - `<script type="application/ld+json">` 里的 VideoObject:文案、封面、发布时间、时长、
6
+ * 评论总数、达人信息、首屏 10 条评论;
7
+ * - 首屏 DOM 里的统计块:点赞 / 评论 / 收藏 / 分享(`5.4万` 这种缩写,文本展示值)。
8
+ * 两者合起来就是一条视频的完整公开快照。不需要 Cookie,也没有签名接口。
9
+ */
10
+ import fs from 'node:fs'
11
+ import { UsageError } from './args.js'
12
+ import { ToolError } from './tool-error.js'
13
+
14
+ export const SEO_UA = 'Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)'
15
+ const VIDEO_PAGE = 'https://www.douyin.com/video/'
16
+ const BASE_URL = 'https://www.douyin.com'
17
+
18
+ /** 从视频链接 / 分享文案里抠出 awemeId。 */
19
+ export function videoIdFrom(text) {
20
+ if (!text) return null
21
+ const value = String(text)
22
+ const match = value.match(/\/(?:video|share\/video|note)\/(\d{10,25})/) || value.match(/^\s*(\d{10,25})\s*$/)
23
+ return match ? match[1] : null
24
+ }
25
+
26
+ /** 抖音缩写数字 -> 整数:'5.4万' -> 54000、'4587' -> 4587、'1.2亿' -> 120000000。 */
27
+ export function abbrevToInt(text) {
28
+ if (text === null || text === undefined) return null
29
+ const match = String(text).replace(/,/g, '').trim().match(/^([\d.]+)\s*([万亿wWkK]?)$/)
30
+ if (!match) return null
31
+ const unit = { 万: 10000, w: 10000, W: 10000, 亿: 100000000, k: 1000, K: 1000, '': 1 }[match[2]]
32
+ return Math.round(Number(match[1]) * unit)
33
+ }
34
+
35
+ /** ISO 8601 时长 -> 秒:'PT0H1M8S' -> 68。 */
36
+ export function isoDurationSeconds(value) {
37
+ const match = String(value || '').match(/^PT(?:(\d+)H)?(?:(\d+)M)?(?:(\d+(?:\.\d+)?)S)?$/)
38
+ if (!match) return null
39
+ const [h, m, s] = match.slice(1).map((part) => (part ? Number(part) : 0))
40
+ return Math.floor(h * 3600 + m * 60 + s)
41
+ }
42
+
43
+ /** 修掉抖音在带时区的时间后面多写的 Z:'2026-10-27T17:35:19+08:00Z' -> '…+08:00'。 */
44
+ export function normalizeIsoTime(value) {
45
+ if (!value) return null
46
+ const text = String(value)
47
+ return /[+-]\d{2}:\d{2}Z$/.test(text) ? text.slice(0, -1) : text
48
+ }
49
+
50
+ export function absoluteUrl(url, base = BASE_URL) {
51
+ if (!url) return null
52
+ const text = String(url)
53
+ if (/^https?:\/\//i.test(text)) return text
54
+ return text.startsWith('/') ? `${base}${text}` : text
55
+ }
56
+
57
+ export function secUidFrom(url) {
58
+ const match = String(url || '').match(/\/user\/(MS4wLjABAAAA[\w-]+)/)
59
+ return match ? match[1] : null
60
+ }
61
+
62
+ /** interactionStatistic 里的动作类型可能是字符串、{ '@type' } 对象或 { value },统一成字符串。 */
63
+ function interactionName(item) {
64
+ const type = item?.interactionType
65
+ if (!type) return ''
66
+ if (typeof type === 'string') return type
67
+ return String(type['@type'] ?? type.value ?? JSON.stringify(type))
68
+ }
69
+
70
+ /** interactionStatistic 里按 LikeAction / FollowAction 取数,兼容单个对象与数组。 */
71
+ function counterOf(statistic, action) {
72
+ const items = Array.isArray(statistic) ? statistic : statistic ? [statistic] : []
73
+ for (const item of items) {
74
+ if (interactionName(item).includes(action)) {
75
+ return item?.userInteractionCount ?? null
76
+ }
77
+ }
78
+ return null
79
+ }
80
+
81
+ /** 取出 ld+json 里的 VideoObject(页面里可能有多段 ld+json)。 */
82
+ export function parseVideoObject(html) {
83
+ const text = String(html || '')
84
+ const blocks = text.matchAll(/<script[^>]*application\/ld\+json[^>]*>([\s\S]*?)<\/script>/gi)
85
+ for (const block of blocks) {
86
+ let parsed
87
+ try {
88
+ parsed = JSON.parse(block[1])
89
+ } catch {
90
+ continue
91
+ }
92
+ if (parsed && typeof parsed === 'object' && parsed['@type'] === 'VideoObject') return parsed
93
+ }
94
+ const message = /VideoObject/.test(text)
95
+ ? '页面里的 ld+json VideoObject 不是合法 JSON(抖音可能改版)'
96
+ : '页面里没有 ld+json VideoObject:可能不是搜索引擎 UA 返回的页面、视频不存在/已删除,或抖音改版'
97
+ throw new ToolError(message, { type: 'ParseError' })
98
+ }
99
+
100
+ /**
101
+ * 首屏统计块里的四个数——ld+json 里没有。
102
+ * 结构固定:前三格是 `<span class="hIpNkUXt">`(赞 / 评 / 藏),
103
+ * 分享格是 `data-e2e="video-share-icon-container"` 里的 `<span class="sB3y0d3B">`。
104
+ */
105
+ export function domStats(html) {
106
+ const block = String(html || '').match(/<div class="pWR86eZK">([\s\S]*?)<div class="o9W_EAcI">/)
107
+ if (!block) return {}
108
+ const seg = block[1]
109
+ const shorts = [...seg.matchAll(/<span class="hIpNkUXt">([^<]+)<\/span>/g)].map((m) => m[1])
110
+ const share = [...seg.matchAll(/<span class="sB3y0d3B">([^<]+)<\/span>/g)].map((m) => m[1])
111
+ const stats = {}
112
+ const keys = ['like_count', 'comment_count', 'collect_count']
113
+ keys.forEach((key, index) => {
114
+ if (shorts[index] !== undefined) stats[key] = abbrevToInt(shorts[index])
115
+ })
116
+ if (share[0] !== undefined) stats.share_count = abbrevToInt(share[0])
117
+ return stats
118
+ }
119
+
120
+ /** 把 VideoObject + DOM 统计转成对外输出结构。 */
121
+ export function buildSnapshot({ videoObject, videoId, html }) {
122
+ const vo = videoObject || {}
123
+ const creator = vo.creator || {}
124
+ const stats = domStats(html)
125
+
126
+ // description 只从 name 解析:去掉站名尾巴「- 抖音」和 #话题
127
+ const name = String(vo.name || '')
128
+ const head = name.replace(/\s+-\s+抖音$/, '').trim()
129
+ const description = head.replace(/#[^\s#]+/g, ' ').replace(/\s{2,}/g, ' ').trim() || head || null
130
+
131
+ const comments = (Array.isArray(vo.comment) ? vo.comment : []).map((comment) => {
132
+ const user = comment?.creator || {}
133
+ return {
134
+ text: comment?.text ?? null,
135
+ user: {
136
+ name: user.name ?? null,
137
+ sec_uid: secUidFrom(user.url),
138
+ profile_url: absoluteUrl(user.url),
139
+ },
140
+ like_count: counterOf(comment?.interactionStatistic, 'LikeAction'),
141
+ }
142
+ })
143
+
144
+ return {
145
+ video: {
146
+ id: videoId,
147
+ description,
148
+ cover_urls: Array.isArray(vo.thumbnailUrl) ? vo.thumbnailUrl : [],
149
+ publish_time: normalizeIsoTime(vo.uploadDate),
150
+ duration_seconds: isoDurationSeconds(vo.duration),
151
+ // 点赞/收藏/分享只能从 DOM 展示文本解析(万/亿 缩写 -> 整数,近似值);
152
+ // 评论数优先用 ld+json 的精确值,缺失时回退 DOM
153
+ like_count: stats.like_count ?? null,
154
+ comment_count: vo.commentCount ?? stats.comment_count ?? null,
155
+ collect_count: stats.collect_count ?? null,
156
+ share_count: stats.share_count ?? null,
157
+ },
158
+ creator: {
159
+ name: creator.name ?? null,
160
+ sec_uid: secUidFrom(creator.url),
161
+ profile_url: absoluteUrl(creator.url),
162
+ like_count: counterOf(creator.interactionStatistic, 'LikeAction'),
163
+ follower_count: counterOf(creator.interactionStatistic, 'FollowAction'),
164
+ },
165
+ comments,
166
+ }
167
+ }
168
+
169
+ async function fetchHtml(url, timeoutMs) {
170
+ const headers = {
171
+ 'User-Agent': SEO_UA,
172
+ Accept: 'text/html,application/xhtml+xml',
173
+ 'Accept-Language': 'zh-CN,zh;q=0.9',
174
+ }
175
+ let response
176
+ try {
177
+ response = await fetch(url, { headers, redirect: 'follow', signal: AbortSignal.timeout(timeoutMs) })
178
+ } catch (error) {
179
+ const reason =
180
+ error?.name === 'TimeoutError' || error?.name === 'AbortError'
181
+ ? `请求超时(${timeoutMs}ms)`
182
+ : error?.message || '网络请求失败'
183
+ throw new ToolError(`抓取抖音页面失败(${url}):${reason}`, { type: 'FetchError' })
184
+ }
185
+ const html = await response.text().catch(() => '')
186
+ if (!response.ok) {
187
+ throw new ToolError(`抓取抖音页面失败(${url}):HTTP ${response.status}`, {
188
+ type: 'FetchError',
189
+ status: response.status,
190
+ })
191
+ }
192
+ return { html, finalUrl: response.url || url }
193
+ }
194
+
195
+ /**
196
+ * 主入口:按视频 ID / 链接 / 本地 HTML 返回 { video, creator, comments }。
197
+ * 失败抛 ToolError(FetchError / ParseError)或 UsageError(参数问题)。
198
+ */
199
+ export async function seoVideoDetail({ id, url, htmlPath, timeoutMs = 30000 }) {
200
+ if (htmlPath) {
201
+ try {
202
+ const html = fs.readFileSync(htmlPath, 'utf8')
203
+ const videoId =
204
+ html.match(/rel="canonical"[^>]*href="[^"]*\/video\/(\d+)"/)?.[1] ||
205
+ videoIdFrom(url) ||
206
+ (id ? String(id) : null)
207
+ return buildSnapshot({ videoObject: parseVideoObject(html), videoId, html })
208
+ } catch (error) {
209
+ if (error instanceof ToolError) throw error
210
+ throw new UsageError(`读取 --html 失败:${error.message}`)
211
+ }
212
+ }
213
+
214
+ const target = id
215
+ ? `${VIDEO_PAGE}${encodeURIComponent(String(id).trim())}`
216
+ : /^https?:\/\//i.test(String(url))
217
+ ? String(url).trim()
218
+ : `https://${String(url).trim()}`
219
+ const { html, finalUrl } = await fetchHtml(target, timeoutMs)
220
+ const videoId =
221
+ html.match(/rel="canonical"[^>]*href="[^"]*\/video\/(\d+)"/)?.[1] ||
222
+ videoIdFrom(finalUrl) ||
223
+ videoIdFrom(id) ||
224
+ videoIdFrom(url)
225
+ if (!videoId) {
226
+ throw new ToolError('无法确定视频 ID(页面没有 canonical,入参也解析不到)', { type: 'ParseError' })
227
+ }
228
+ return buildSnapshot({ videoObject: parseVideoObject(html), videoId, html })
229
+ }
@@ -0,0 +1,15 @@
1
+ /**
2
+ * 非 TCM 后端类错误(例如本地 `tool` 命令抓取第三方页面失败)。
3
+ *
4
+ * 与 ApiError 区分开:ApiError 表示「服务端返回了错误」,ToolError 表示
5
+ * 「本地工具执行失败」,输出里 type 保留具体原因(FetchError / ParseError)。
6
+ */
7
+ export class ToolError extends Error {
8
+ constructor(message, { type = 'ToolError', status = null, data = null } = {}) {
9
+ super(message)
10
+ this.name = type
11
+ this.type = type
12
+ this.status = status
13
+ this.data = data
14
+ }
15
+ }