@vocmarket/voc-skill 0.3.15

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.
Files changed (82) hide show
  1. package/.claude-plugin/plugin.json +8 -0
  2. package/.mcp.json +11 -0
  3. package/README.md +334 -0
  4. package/bin/claude-voc.js +790 -0
  5. package/docs/boss-prompt-templates.md +682 -0
  6. package/docs/capability-map.md +195 -0
  7. package/docs/claude-code-troubleshooting-playbook.md +136 -0
  8. package/docs/context-budget-implementation-plan.md +491 -0
  9. package/docs/customer-quickstart.md +43 -0
  10. package/docs/deliverables/competitor-map-report.md +43 -0
  11. package/docs/deliverables/seven-day-content-plan.md +45 -0
  12. package/docs/deliverables/single-problem-action-plan.md +49 -0
  13. package/docs/deliverables/trend-insight-report.md +41 -0
  14. package/docs/deliverables/voc-issue-pool-report.md +42 -0
  15. package/docs/demo-runbook.md +31 -0
  16. package/docs/live-manual-acceptance-checklist.md +63 -0
  17. package/docs/npm-packaging-notes.md +93 -0
  18. package/docs/payment-package-links.md +86 -0
  19. package/install.js +208 -0
  20. package/mcp/src/core/credentials.js +113 -0
  21. package/mcp/src/core/evidence-quality.js +106 -0
  22. package/mcp/src/core/memory-store.js +31 -0
  23. package/mcp/src/core/payment-links.js +117 -0
  24. package/mcp/src/core/result-envelope.js +31 -0
  25. package/mcp/src/features/douyin-trend/live-collector.js +396 -0
  26. package/mcp/src/features/douyin-trend/preference-memory.js +130 -0
  27. package/mcp/src/features/douyin-trend/report.js +318 -0
  28. package/mcp/src/features/douyin-trend/sample-data.js +103 -0
  29. package/mcp/src/features/douyin-trend/signal-extractor.js +79 -0
  30. package/mcp/src/features/douyin-trend/topic-builder.js +1 -0
  31. package/mcp/src/features/voc-business-workflow/business-workflow.js +214 -0
  32. package/mcp/src/features/voc-competitor-map/competitor-map.js +198 -0
  33. package/mcp/src/features/voc-content-plan/content-plan.js +359 -0
  34. package/mcp/src/features/voc-issue-pool/issue-pool.js +488 -0
  35. package/mcp/src/features/voc-problem-deep-dive/deep-dive.js +662 -0
  36. package/mcp/src/features/voc-speaking-script/speaking-script.js +293 -0
  37. package/mcp/src/features/xiaohongshu-trend/assets.js +158 -0
  38. package/mcp/src/features/xiaohongshu-trend/industry-presets.js +335 -0
  39. package/mcp/src/features/xiaohongshu-trend/live-collector.js +337 -0
  40. package/mcp/src/features/xiaohongshu-trend/preference-memory.js +130 -0
  41. package/mcp/src/features/xiaohongshu-trend/report.js +319 -0
  42. package/mcp/src/features/xiaohongshu-trend/sample-data.js +79 -0
  43. package/mcp/src/features/xiaohongshu-trend/signal-extractor.js +77 -0
  44. package/mcp/src/features/xiaohongshu-trend/topic-builder.js +84 -0
  45. package/mcp/src/providers/douyin-api.js +170 -0
  46. package/mcp/src/providers/xiaohongshu-api.js +102 -0
  47. package/mcp/src/server.js +621 -0
  48. package/mcp/src/tools/douyin-preference-update.js +70 -0
  49. package/mcp/src/tools/douyin-trend-run.js +464 -0
  50. package/mcp/src/tools/voc-business-workflow-run.js +52 -0
  51. package/mcp/src/tools/voc-competitor-map-run.js +59 -0
  52. package/mcp/src/tools/voc-content-plan-run.js +59 -0
  53. package/mcp/src/tools/voc-issue-pool-run.js +59 -0
  54. package/mcp/src/tools/voc-problem-deep-dive-run.js +59 -0
  55. package/mcp/src/tools/voc-speaking-script-run.js +59 -0
  56. package/mcp/src/tools/xiaohongshu-preference-update.js +85 -0
  57. package/mcp/src/tools/xiaohongshu-trend-run.js +404 -0
  58. package/memory-templates/douyin-trend-profile.json +33 -0
  59. package/memory-templates/xiaohongshu-trend-profile.json +33 -0
  60. package/package.json +65 -0
  61. package/scripts/smoke-cross-industry.js +126 -0
  62. package/scripts/smoke-mcp.js +302 -0
  63. package/scripts/smoke-package.js +1005 -0
  64. package/skill-package-manifest.json +62 -0
  65. package/skills/douyin-trend-intelligence/SKILL.md +78 -0
  66. package/skills/douyin-trend-intelligence/references/live-mode.md +52 -0
  67. package/skills/douyin-trend-intelligence/references/output-format.md +32 -0
  68. package/skills/douyin-trend-intelligence/references/user-workflow.md +24 -0
  69. package/skills/voc-business-workflow/SKILL.md +61 -0
  70. package/skills/voc-competitor-map/SKILL.md +60 -0
  71. package/skills/voc-competitor-map/references/restaurant-competitor-framework.md +25 -0
  72. package/skills/voc-competitor-map/references/restaurant-differentiation-patterns.md +44 -0
  73. package/skills/voc-content-plan/SKILL.md +63 -0
  74. package/skills/voc-content-plan/references/restaurant-content-framework.md +41 -0
  75. package/skills/voc-content-plan/references/restaurant-speaking-script-patterns.md +34 -0
  76. package/skills/voc-issue-pool/SKILL.md +81 -0
  77. package/skills/voc-problem-deep-dive/SKILL.md +86 -0
  78. package/skills/voc-speaking-script/SKILL.md +99 -0
  79. package/skills/xiaohongshu-trend-intelligence/SKILL.md +61 -0
  80. package/skills/xiaohongshu-trend-intelligence/references/live-mode.md +65 -0
  81. package/skills/xiaohongshu-trend-intelligence/references/output-format.md +71 -0
  82. package/skills/xiaohongshu-trend-intelligence/references/user-workflow.md +60 -0
@@ -0,0 +1,106 @@
1
+ function asArray(value) {
2
+ return Array.isArray(value) ? value : [];
3
+ }
4
+
5
+ function hasSourceUrl(item) {
6
+ return Boolean(item && (item.sourceUrl || item.webUrl || item.url));
7
+ }
8
+
9
+ function hasImage(item) {
10
+ return Boolean(
11
+ item &&
12
+ (item.localCoverPath ||
13
+ item.coverUrl ||
14
+ (Array.isArray(item.imageUrls) && item.imageUrls.length))
15
+ );
16
+ }
17
+
18
+ function hasText(item) {
19
+ return Boolean(
20
+ item &&
21
+ String(item.contentExcerpt || item.rawExcerpt || item.content || item.desc || item.title || '').trim()
22
+ );
23
+ }
24
+
25
+ function assessEvidenceQuality({ items, comments, itemLabel = '样本', collectionMode = 'sample' }) {
26
+ const rows = asArray(items);
27
+ const commentRows = asArray(comments);
28
+ const sourceUrlCount = rows.filter(hasSourceUrl).length;
29
+ const imageCount = rows.filter(hasImage).length;
30
+ const textCount = rows.filter(hasText).length;
31
+ const highLikeCommentCount = commentRows.filter(comment => Number(comment.likeCount || 0) > 0).length;
32
+
33
+ let score = 0;
34
+ if (rows.length >= 8) score += 2;
35
+ else if (rows.length >= 3) score += 1;
36
+ if (commentRows.length >= 50) score += 2;
37
+ else if (commentRows.length >= 10) score += 1;
38
+ if (sourceUrlCount >= Math.min(rows.length, 3)) score += 1;
39
+ if (imageCount >= Math.min(rows.length, 3)) score += 1;
40
+ if (highLikeCommentCount >= 3) score += 1;
41
+ if (textCount >= Math.min(rows.length, 3)) score += 1;
42
+
43
+ const grade = score >= 7 ? 'A' : score >= 4 ? 'B' : 'C';
44
+ const canMakeBusinessDecision = grade === 'A' || (grade === 'B' && collectionMode === 'live');
45
+ const recommendation = canMakeBusinessDecision
46
+ ? '可以作为第一轮经营判断依据,但仍建议结合门店/销售/私域反馈校准。'
47
+ : '只适合作为初步机会假设,不建议直接当最终经营结论。';
48
+
49
+ return {
50
+ grade,
51
+ itemLabel,
52
+ itemCount: rows.length,
53
+ commentCount: commentRows.length,
54
+ sourceUrlCount,
55
+ imageCount,
56
+ textCount,
57
+ highLikeCommentCount,
58
+ canMakeBusinessDecision,
59
+ recommendation
60
+ };
61
+ }
62
+
63
+ function buildEvidenceQualitySection(quality) {
64
+ return [
65
+ '## 证据质量门槛',
66
+ '',
67
+ `- 本轮证据质量:${quality.grade}`,
68
+ `- ${quality.itemLabel}数量:${quality.itemCount}`,
69
+ `- 评论数量:${quality.commentCount}`,
70
+ `- 含原文/原视频链接:${quality.sourceUrlCount}`,
71
+ `- 含图片/封面:${quality.imageCount}`,
72
+ `- 含文本摘录:${quality.textCount}`,
73
+ `- 含点赞评论:${quality.highLikeCommentCount}`,
74
+ `- 是否适合直接做经营判断:${quality.canMakeBusinessDecision ? '适合第一轮判断' : '仅适合初步假设'}`,
75
+ `- 使用建议:${quality.recommendation}`
76
+ ];
77
+ }
78
+
79
+ function buildNoSampleFallbackMessage({ platformLabel, profile, examples = [] }) {
80
+ const keywords = asArray(profile && profile.keywords).slice(0, 5).join('、') || '当前关键词';
81
+ const exampleLines = examples.length ? examples.map(item => `- ${item}`) : [
82
+ '- 换成更具体的品类词、场景词或城市词',
83
+ '- 从产品词扩展到用户真实说法',
84
+ '- 先用 sample 模式演示完整流程,但明确标注非真实采集'
85
+ ];
86
+
87
+ return [
88
+ `本次 live 模式没有采到可用于分析的${platformLabel}样本。`,
89
+ '',
90
+ '这不代表行业没有机会,更可能是关键词过窄、平台内容表达不一样,或本轮上游没有返回可用内容。',
91
+ '',
92
+ '建议按这三步继续:',
93
+ `1. 先保留当前方向:${keywords}`,
94
+ '2. 自动换一组更贴近用户说法的关键词再试一次',
95
+ '3. 如果仍然没有样本,降级到相关大词做第一轮机会假设,并明确标注“非真实采集/待验证”',
96
+ '',
97
+ '可尝试的关键词方向:',
98
+ ...exampleLines
99
+ ].join('\n');
100
+ }
101
+
102
+ module.exports = {
103
+ assessEvidenceQuality,
104
+ buildEvidenceQualitySection,
105
+ buildNoSampleFallbackMessage
106
+ };
@@ -0,0 +1,31 @@
1
+ const fs = require('fs');
2
+ const path = require('path');
3
+
4
+ function ensureDir(dirPath) {
5
+ fs.mkdirSync(dirPath, { recursive: true });
6
+ }
7
+
8
+ function readJson(filePath, fallback = {}) {
9
+ try {
10
+ if (!filePath || !fs.existsSync(filePath)) return fallback;
11
+ return JSON.parse(fs.readFileSync(filePath, 'utf8'));
12
+ } catch {
13
+ return fallback;
14
+ }
15
+ }
16
+
17
+ function writeJson(filePath, data) {
18
+ ensureDir(path.dirname(filePath));
19
+ fs.writeFileSync(filePath, JSON.stringify(data, null, 2), 'utf8');
20
+ }
21
+
22
+ function defaultMemoryPath(name) {
23
+ return path.resolve('memory', name);
24
+ }
25
+
26
+ module.exports = {
27
+ readJson,
28
+ writeJson,
29
+ defaultMemoryPath
30
+ };
31
+
@@ -0,0 +1,117 @@
1
+ const VOC_SOCIAL_APIG_ID = 'Vo3ROWEvDy';
2
+ const VOC_RECHARGE_FUN_ID = 'HOkkX72PMF';
3
+ const VOC_RECHARGE_BASE_URL = 'https://app.fmode.cn/dev/apig-pay/';
4
+ const PARSE_USERS_ME_URL = 'https://server.fmode.cn/parse/users/me';
5
+ const DEFAULT_WORKSHOP_PACKAGE_SLUG = '99';
6
+ const VOC_WORKSHOP_PACKAGE_SLUGS = {
7
+ trial199: '19-9',
8
+ trial299: '29-9',
9
+ selfPractice: '99',
10
+ onsiteTraining: '299',
11
+ teamDelivery: '699'
12
+ };
13
+
14
+ function buildVocRechargeUrl(options = {}) {
15
+ const url = new URL(VOC_RECHARGE_BASE_URL);
16
+ if (options.userId) {
17
+ url.searchParams.set('user', String(options.userId));
18
+ }
19
+ url.searchParams.set('apigid', VOC_SOCIAL_APIG_ID);
20
+ url.searchParams.set('fun_id', VOC_RECHARGE_FUN_ID);
21
+ return url.toString();
22
+ }
23
+
24
+ function buildVocWorkshopUrl(options = {}) {
25
+ const url = new URL(VOC_RECHARGE_BASE_URL);
26
+ if (options.userId) {
27
+ url.searchParams.set('user', String(options.userId));
28
+ }
29
+ const slug = options.slug ? String(options.slug) : '';
30
+ url.hash = slug ? `/workshop/${slug}` : '/workshop';
31
+ return url.toString();
32
+ }
33
+
34
+ async function resolveVocUserId(token) {
35
+ if (!token) return '';
36
+ try {
37
+ const response = await fetch(PARSE_USERS_ME_URL, {
38
+ method: 'GET',
39
+ headers: {
40
+ 'X-Parse-Application-Id': 'ncloudmaster',
41
+ 'X-Parse-Session-Token': token,
42
+ Accept: 'application/json'
43
+ }
44
+ });
45
+ if (!response.ok) return '';
46
+ const json = await response.json();
47
+ return json && json.objectId ? String(json.objectId) : '';
48
+ } catch {
49
+ return '';
50
+ }
51
+ }
52
+
53
+ async function buildVocRechargeInfo(options = {}) {
54
+ const userId = await resolveVocUserId(options.token);
55
+ const workshopUrl = buildVocWorkshopUrl({ userId });
56
+ const recommendedPackageUrl = buildVocWorkshopUrl({
57
+ userId,
58
+ slug: options.packageSlug || DEFAULT_WORKSHOP_PACKAGE_SLUG
59
+ });
60
+ return {
61
+ paymentUrl: buildVocRechargeUrl({ userId }),
62
+ fallbackPaymentUrl: buildVocRechargeUrl(),
63
+ workshopUrl,
64
+ recommendedPackageUrl,
65
+ packageUrls: {
66
+ trial199: buildVocWorkshopUrl({ userId, slug: VOC_WORKSHOP_PACKAGE_SLUGS.trial199 }),
67
+ trial299: buildVocWorkshopUrl({ userId, slug: VOC_WORKSHOP_PACKAGE_SLUGS.trial299 }),
68
+ selfPractice: buildVocWorkshopUrl({ userId, slug: VOC_WORKSHOP_PACKAGE_SLUGS.selfPractice }),
69
+ onsiteTraining: buildVocWorkshopUrl({ userId, slug: VOC_WORKSHOP_PACKAGE_SLUGS.onsiteTraining }),
70
+ teamDelivery: buildVocWorkshopUrl({ userId, slug: VOC_WORKSHOP_PACKAGE_SLUGS.teamDelivery })
71
+ },
72
+ apigId: VOC_SOCIAL_APIG_ID,
73
+ funId: VOC_RECHARGE_FUN_ID,
74
+ personalized: Boolean(userId)
75
+ };
76
+ }
77
+
78
+ function buildMissingTokenMessage(paymentUrl, recharge = {}, options = {}) {
79
+ const platformLabel = options.platformLabel || '小红书';
80
+ const packageUrl = recharge.recommendedPackageUrl || recharge.workshopUrl || paymentUrl;
81
+ return [
82
+ `还没有检测到 VOC-AI 数据服务 token,暂时不能进行真实 ${platformLabel} 采集。`,
83
+ '',
84
+ `请先打开充值/开通链接:${paymentUrl}`,
85
+ '',
86
+ `课程或工作坊用户也可以打开套餐入口:${packageUrl}`,
87
+ '',
88
+ '完成充值或开通后,把服务方提供的 session token 配置到当前工作区 `.env.local` 或 `~/.claude/voc-credentials.json`,再重新运行 live 采集。',
89
+ '',
90
+ '系统只会用 token 发起请求,不会在报告、日志或聊天输出里回显 token。'
91
+ ].join('\n');
92
+ }
93
+
94
+ function buildRechargeRequiredMessage(paymentUrl, recharge = {}, options = {}) {
95
+ const platformLabel = options.platformLabel || '小红书';
96
+ const packageUrl = recharge.recommendedPackageUrl || recharge.workshopUrl || paymentUrl;
97
+ return [
98
+ `VOC-AI 数据服务余额不足,暂时不能继续真实 ${platformLabel} 采集。`,
99
+ '',
100
+ `请先打开充值链接补充额度:${paymentUrl}`,
101
+ '',
102
+ `课程或工作坊用户也可以打开套餐入口:${packageUrl}`,
103
+ '',
104
+ `我已经隐藏了底层接口权限/余额报错,不会把真实 ${platformLabel} 接口 403 或权限信息直接展示给用户。`
105
+ ].join('\n');
106
+ }
107
+
108
+ module.exports = {
109
+ VOC_SOCIAL_APIG_ID,
110
+ VOC_RECHARGE_FUN_ID,
111
+ VOC_WORKSHOP_PACKAGE_SLUGS,
112
+ buildVocRechargeInfo,
113
+ buildVocRechargeUrl,
114
+ buildVocWorkshopUrl,
115
+ buildMissingTokenMessage,
116
+ buildRechargeRequiredMessage
117
+ };
@@ -0,0 +1,31 @@
1
+ function okResult(payload = {}) {
2
+ return {
3
+ status: 'ok',
4
+ assistantMessage: payload.assistantMessage || '',
5
+ summary: payload.summary || {},
6
+ data: payload.data || {},
7
+ files: payload.files || [],
8
+ nextActions: payload.nextActions || [],
9
+ warnings: payload.warnings || [],
10
+ errors: payload.errors || []
11
+ };
12
+ }
13
+
14
+ function errorResult(message, payload = {}) {
15
+ return {
16
+ status: 'error',
17
+ assistantMessage: message,
18
+ summary: payload.summary || {},
19
+ data: payload.data || {},
20
+ files: payload.files || [],
21
+ nextActions: payload.nextActions || [],
22
+ warnings: payload.warnings || [],
23
+ errors: payload.errors || [{ message }]
24
+ };
25
+ }
26
+
27
+ module.exports = {
28
+ okResult,
29
+ errorResult
30
+ };
31
+
@@ -0,0 +1,396 @@
1
+ const { DouyinApi } = require('../../providers/douyin-api');
2
+
3
+ function normalizeCount(value) {
4
+ if (value === undefined || value === null || value === '') return 0;
5
+ if (typeof value === 'number') return Number.isFinite(value) ? value : 0;
6
+ const text = String(value).trim().toLowerCase();
7
+ const match = text.match(/([\d.]+)/);
8
+ if (!match) return 0;
9
+ const base = Number.parseFloat(match[1]);
10
+ if (!Number.isFinite(base)) return 0;
11
+ if (text.includes('w') || text.includes('万')) return Math.round(base * 10000);
12
+ if (text.includes('k') || text.includes('千')) return Math.round(base * 1000);
13
+ return Math.round(base);
14
+ }
15
+
16
+ const MAX_SEARCH_KEYWORD_LENGTH = 60;
17
+
18
+ function normalizeSearchKeyword(value) {
19
+ if (typeof value !== 'string') return '';
20
+ return value
21
+ .replace(/[\r\n\t]+/g, ' ')
22
+ .replace(/([\u4e00-\u9fff])(\d)/g, '$1 $2')
23
+ .replace(/(\d)([\u4e00-\u9fff])/g, '$1$2 ')
24
+ .replace(/\s+/g, ' ')
25
+ .trim();
26
+ }
27
+
28
+ function keywordValidationIssue(value) {
29
+ if (typeof value !== 'string') return '关键词需要是文本';
30
+ const keyword = normalizeSearchKeyword(value);
31
+ if (!keyword) return '关键词为空';
32
+ if (!/[\p{L}\p{N}]/u.test(keyword)) return '关键词缺少可搜索的文字或数字';
33
+ if (keyword.length > MAX_SEARCH_KEYWORD_LENGTH) return `关键词过长,建议控制在 ${MAX_SEARCH_KEYWORD_LENGTH} 个字符以内`;
34
+ return '';
35
+ }
36
+
37
+ function isUsableKeyword(value) {
38
+ return !keywordValidationIssue(value);
39
+ }
40
+
41
+ function videoScore(video) {
42
+ return normalizeCount(video.likeCount) +
43
+ normalizeCount(video.commentCount) * 3 +
44
+ normalizeCount(video.shareCount) * 2 +
45
+ normalizeCount(video.playCount) * 0.02;
46
+ }
47
+
48
+ function pickFirstString(...values) {
49
+ return values
50
+ .flat()
51
+ .filter(value => typeof value === 'string')
52
+ .map(value => value.trim())
53
+ .find(Boolean) || '';
54
+ }
55
+
56
+ function nestedValue(object, path) {
57
+ return path.split('.').reduce((current, key) => (
58
+ current && typeof current === 'object' ? current[key] : undefined
59
+ ), object);
60
+ }
61
+
62
+ function collectUrls(value, result = []) {
63
+ if (!value) return result;
64
+ if (typeof value === 'string') {
65
+ if (/^https?:\/\//i.test(value) && !result.includes(value)) result.push(value);
66
+ return result;
67
+ }
68
+ if (Array.isArray(value)) {
69
+ value.forEach(item => collectUrls(item, result));
70
+ return result;
71
+ }
72
+ if (typeof value !== 'object') return result;
73
+
74
+ ['url', 'url_default', 'url_pre', 'original_url', 'large', 'middle', 'thumbnail', 'image_url', 'imageUrl']
75
+ .forEach(key => collectUrls(value[key], result));
76
+
77
+ ['url_list', 'urlList', 'info_list', 'infoList', 'images', 'image_list', 'imageList']
78
+ .forEach(key => collectUrls(value[key], result));
79
+
80
+ return result;
81
+ }
82
+
83
+ function extractImageUrls(video = {}, raw = {}) {
84
+ const result = [];
85
+ [
86
+ video.cover,
87
+ video.origin_cover,
88
+ video.dynamic_cover,
89
+ video.video && video.video.cover,
90
+ video.video && video.video.origin_cover,
91
+ video.video && video.video.dynamic_cover,
92
+ raw.cover,
93
+ raw.origin_cover,
94
+ raw.dynamic_cover,
95
+ raw.video && raw.video.cover,
96
+ raw.video && raw.video.origin_cover,
97
+ raw.video && raw.video.dynamic_cover
98
+ ].forEach(value => collectUrls(value, result));
99
+ return result;
100
+ }
101
+
102
+ function pickSourceUrl(video = {}, raw = {}) {
103
+ const id = video.aweme_id || video.id || raw.aweme_id || raw.id || '';
104
+ const candidates = [
105
+ nestedValue(video, 'share_info.link'),
106
+ nestedValue(raw, 'share_info.link'),
107
+ nestedValue(video, 'share_info.share_url'),
108
+ nestedValue(raw, 'share_info.share_url'),
109
+ video.share_url,
110
+ raw.share_url,
111
+ video.web_url,
112
+ raw.web_url,
113
+ video.url,
114
+ raw.url,
115
+ id ? `https://www.douyin.com/video/${id}` : ''
116
+ ].filter(Boolean);
117
+ return pickFirstString(candidates);
118
+ }
119
+
120
+ function sourceUrlVerified(url = '') {
121
+ return /douyin\.com|v\.douyin\.com|aweme/i.test(String(url || ''));
122
+ }
123
+
124
+ function normalizeVideo(raw = {}, keyword = '', detail) {
125
+ const video = detail && (detail.aweme_detail || detail.aweme_info || detail.id) ? (detail.aweme_detail || detail.aweme_info || detail) : raw;
126
+ const item = video.aweme_info || raw.aweme_info || video;
127
+ const author = item.author || raw.author || {};
128
+ const sourceUrl = pickSourceUrl(item, raw);
129
+ const imageUrls = extractImageUrls(item, raw);
130
+ const stats = item.statistics || raw.statistics || {};
131
+ const desc = item.desc || item.title || raw.desc || raw.title || '';
132
+ const id = item.aweme_id || item.id || raw.aweme_id || raw.id || '';
133
+ const tags = [];
134
+ (Array.isArray(item.cha_list) ? item.cha_list : []).forEach(tag => {
135
+ const text = tag?.cha_name || tag?.desc || tag?.title || tag?.name || '';
136
+ if (text) tags.push(String(text));
137
+ });
138
+ const textExtra = Array.isArray(item.text_extra) ? item.text_extra : [];
139
+ textExtra.forEach(extra => {
140
+ const text = extra?.hashtag_name || extra?.name || extra?.text || '';
141
+ if (text) tags.push(String(text));
142
+ });
143
+
144
+ return {
145
+ id,
146
+ videoId: id,
147
+ platform: 'douyin',
148
+ keyword,
149
+ title: desc,
150
+ desc,
151
+ content: desc,
152
+ contentExcerpt: String(desc || '').replace(/\s+/g, ' ').trim(),
153
+ rawExcerpt: String(desc || '').replace(/\s+/g, ' ').trim(),
154
+ author: author.nickname || author.name || '',
155
+ authorId: author.uid || author.id || '',
156
+ authorSecUid: author.sec_uid || author.secUid || '',
157
+ likeCount: normalizeCount(stats.digg_count || item.like_count || item.digg_count),
158
+ collectCount: normalizeCount(stats.collect_count || item.collect_count || item.favorite_count),
159
+ commentCount: normalizeCount(stats.comment_count || item.comment_count),
160
+ shareCount: normalizeCount(stats.share_count || item.share_count),
161
+ playCount: normalizeCount(stats.play_count || item.play_count),
162
+ timestamp: item.create_time || raw.create_time || '',
163
+ url: sourceUrl,
164
+ webUrl: sourceUrl,
165
+ shareUrl: sourceUrl,
166
+ sourceUrl,
167
+ sourceUrlVerified: sourceUrlVerified(sourceUrl),
168
+ fallbackUrl: id ? `https://www.douyin.com/video/${id}` : '',
169
+ coverUrl: imageUrls[0] || '',
170
+ imageUrls,
171
+ tags: [...new Set(tags)].filter(Boolean)
172
+ };
173
+ }
174
+
175
+ function normalizeComment(raw = {}, videoId, keyword) {
176
+ const user = raw.user_info || raw.user || {};
177
+ return {
178
+ id: raw.cid || raw.id || raw.comment_id || `${videoId}-${Math.random().toString(36).slice(2, 8)}`,
179
+ cid: raw.cid || raw.comment_id || raw.id || '',
180
+ noteId: videoId,
181
+ videoId,
182
+ platform: 'douyin',
183
+ keyword,
184
+ text: raw.text || raw.content || '',
185
+ likeCount: normalizeCount(raw.digg_count || raw.like_count || raw.likeCount),
186
+ author: user.nickname || user.name || '',
187
+ authorId: user.uid || user.user_id || user.id || '',
188
+ createTime: raw.create_time || '',
189
+ ipLocation: raw.ip_label || raw.ip_location || '',
190
+ replyCommentTotal: normalizeCount(raw.reply_comment_total || raw.reply_count || 0)
191
+ };
192
+ }
193
+
194
+ function extractSearchVideos(data = {}) {
195
+ const cards = data.business_data || data.cards || data.items || [];
196
+ if (!Array.isArray(cards)) return [];
197
+ return cards
198
+ .map(card => card?.data?.aweme_info || card?.data?.aweme_detail?.aweme_info || card?.data?.aweme_info || card?.aweme_info || card)
199
+ .filter(item => item && (item.aweme_id || item.id));
200
+ }
201
+
202
+ function extractComments(data = {}) {
203
+ const comments = data.comments || data.comment_list || [];
204
+ return Array.isArray(comments) ? comments : [];
205
+ }
206
+
207
+ function isSearchRepairableError(error = {}) {
208
+ const kind = String(error.kind || error.errorKind || '');
209
+ const status = Number(error.httpStatus || 0);
210
+ return ['request', 'upstream_search', 'invalid_keyword'].includes(kind) ||
211
+ [400, 422].includes(status) ||
212
+ status >= 500;
213
+ }
214
+
215
+ function firstTargetAudience(profile = {}) {
216
+ const audience = Array.isArray(profile.targetAudience) ? profile.targetAudience[0] : profile.targetAudience;
217
+ return normalizeSearchKeyword(String(audience || ''));
218
+ }
219
+
220
+ function buildKeywordRepairCandidates(keyword, profile = {}) {
221
+ const current = normalizeSearchKeyword(keyword);
222
+ const industry = normalizeSearchKeyword(String(profile.industry || ''));
223
+ const audience = firstTargetAudience(profile);
224
+ const withoutPrice = normalizeSearchKeyword(current.replace(/\d+(?:\.\d+)?\s*(?:元|块|rmb|RMB)?/g, ' '));
225
+ const base = industry || current.split(' ')[0] || current;
226
+ return [
227
+ withoutPrice,
228
+ normalizeSearchKeyword([base, '性价比', audience].filter(Boolean).join(' ')),
229
+ normalizeSearchKeyword([base, '套餐', '点单'].join(' ')),
230
+ normalizeSearchKeyword([base, '避坑', audience].filter(Boolean).join(' '))
231
+ ]
232
+ .filter(candidate => candidate && candidate !== current && isUsableKeyword(candidate))
233
+ .filter((candidate, index, list) => list.indexOf(candidate) === index)
234
+ .slice(0, 2);
235
+ }
236
+
237
+ async function searchTopVideos(api, keyword, options, videosPerKeyword) {
238
+ const search = await api.searchVideos({
239
+ keyword,
240
+ cursor: 0,
241
+ sortType: options.sortType || options.sort || '1',
242
+ publishTime: options.publishTime || options.publish_time || '7',
243
+ filterDuration: options.filterDuration || options.filter_duration || '0',
244
+ contentType: options.contentType || options.content_type || '1',
245
+ searchId: options.searchId || options.search_id || '',
246
+ backtrace: options.backtrace || ''
247
+ });
248
+ return extractSearchVideos(search.data)
249
+ .map(raw => normalizeVideo(raw, keyword))
250
+ .sort((a, b) => videoScore(b) - videoScore(a))
251
+ .slice(0, videosPerKeyword);
252
+ }
253
+
254
+ async function searchTopVideosWithRepair({ api, keyword, profile, options, videosPerKeyword, warnings }) {
255
+ try {
256
+ return {
257
+ keyword,
258
+ videos: await searchTopVideos(api, keyword, options, videosPerKeyword)
259
+ };
260
+ } catch (error) {
261
+ if (options.disableKeywordRepair || !isSearchRepairableError(error)) {
262
+ throw error;
263
+ }
264
+ let lastError = error;
265
+ for (const retryKeyword of buildKeywordRepairCandidates(keyword, profile)) {
266
+ warnings.push({
267
+ stage: 'search_videos_retry',
268
+ kind: 'auto_keyword_repair',
269
+ keyword,
270
+ retryKeyword,
271
+ message: '抖音搜索入参或上游请求失败,已自动换成更稳的短关键词重试。',
272
+ httpStatus: error.httpStatus || 0
273
+ });
274
+ try {
275
+ return {
276
+ keyword: retryKeyword,
277
+ videos: await searchTopVideos(api, retryKeyword, options, videosPerKeyword)
278
+ };
279
+ } catch (retryError) {
280
+ lastError = retryError;
281
+ }
282
+ }
283
+ throw lastError;
284
+ }
285
+ }
286
+
287
+ async function collectLiveDataset({ profile, token, options = {} }) {
288
+ const api = new DouyinApi({ token, baseUrl: options.baseUrl });
289
+ const keywordLimit = Math.max(1, Number(options.keywordLimit || 1));
290
+ const videosPerKeyword = Math.max(1, Number(options.videosPerKeyword || options.notesPerKeyword || 1));
291
+ const maxCommentPages = Math.max(0, Number(options.maxCommentPages ?? 1));
292
+ const rawKeywords = Array.isArray(profile.keywords) ? profile.keywords : [];
293
+ const videos = [];
294
+ const comments = [];
295
+ const warnings = [];
296
+ const errors = [];
297
+ const keywords = [];
298
+ const effectiveKeywords = [];
299
+
300
+ for (const rawKeyword of rawKeywords) {
301
+ const issue = keywordValidationIssue(rawKeyword);
302
+ if (issue) {
303
+ warnings.push({
304
+ stage: 'keyword_normalize',
305
+ kind: 'invalid_keyword',
306
+ keyword: typeof rawKeyword === 'string' ? normalizeSearchKeyword(rawKeyword).slice(0, MAX_SEARCH_KEYWORD_LENGTH) : '',
307
+ message: issue,
308
+ httpStatus: 0
309
+ });
310
+ continue;
311
+ }
312
+ const keyword = normalizeSearchKeyword(rawKeyword);
313
+ if (!keywords.includes(keyword)) keywords.push(keyword);
314
+ if (keywords.length >= keywordLimit) break;
315
+ }
316
+
317
+ if (!keywords.length) {
318
+ errors.push({
319
+ stage: 'search_videos',
320
+ kind: 'invalid_keyword',
321
+ message: '请提供至少一个可用于抖音搜索的关键词,例如“茶饮 18元 22元”或“茶饮 性价比 新客”。',
322
+ httpStatus: 0
323
+ });
324
+ return { videos, comments, warnings, errors, keywords };
325
+ }
326
+
327
+ for (const keyword of keywords) {
328
+ try {
329
+ const result = await searchTopVideosWithRepair({
330
+ api,
331
+ keyword,
332
+ profile,
333
+ options,
334
+ videosPerKeyword,
335
+ warnings
336
+ });
337
+ const rawVideos = result.videos;
338
+ const effectiveKeyword = result.keyword;
339
+ if (!effectiveKeywords.includes(effectiveKeyword)) effectiveKeywords.push(effectiveKeyword);
340
+
341
+ for (const video of rawVideos) {
342
+ videos.push(video);
343
+ let cursor = 0;
344
+ for (let page = 0; page < maxCommentPages; page++) {
345
+ try {
346
+ const commentResult = await api.getVideoComments({ awemeId: video.id, cursor, count: 20 });
347
+ extractComments(commentResult.data).forEach(rawComment => {
348
+ comments.push(normalizeComment(rawComment, video.id, effectiveKeyword));
349
+ });
350
+ cursor = Number(commentResult.data.cursor || 0);
351
+ if (!commentResult.data.has_more || !cursor) break;
352
+ } catch (error) {
353
+ warnings.push({
354
+ stage: 'video_comments',
355
+ keyword,
356
+ videoId: video.id,
357
+ message: error.message,
358
+ httpStatus: error.httpStatus
359
+ });
360
+ break;
361
+ }
362
+ }
363
+ }
364
+ } catch (error) {
365
+ errors.push({
366
+ stage: 'search_videos',
367
+ keyword,
368
+ kind: error.kind || error.errorKind || '',
369
+ message: error.message,
370
+ httpStatus: error.httpStatus
371
+ });
372
+ }
373
+ }
374
+
375
+ return {
376
+ videos,
377
+ comments,
378
+ warnings,
379
+ errors,
380
+ keywords: effectiveKeywords.length ? effectiveKeywords : keywords
381
+ };
382
+ }
383
+
384
+ module.exports = {
385
+ collectLiveDataset,
386
+ normalizeVideo,
387
+ normalizeComment,
388
+ extractSearchVideos,
389
+ extractComments,
390
+ pickSourceUrl,
391
+ sourceUrlVerified,
392
+ normalizeSearchKeyword,
393
+ keywordValidationIssue,
394
+ buildKeywordRepairCandidates,
395
+ isUsableKeyword
396
+ };