Files
jackwener__opencli/clis/xiaohongshu/creator-stats.ts
jakevin 4fe9a73ebc refactor: migrate adapter imports to package exports (#795)
* refactor: migrate adapter imports to package exports

Replace all relative imports (../../src/registry.js, ../../browser/cdp.js, etc.)
with package exports (@jackwener/opencli/registry, @jackwener/opencli/errors, etc.)
across all 484 adapter files.

This decouples adapter import resolution from directory structure:
- User CLIs in ~/.opencli/clis/ resolve via node_modules symlink
- Internal adapters resolve via Node.js self-referencing
- No more shim files needed for import resolution

Changes:
- package.json: add sub-path exports for all public modules
- clis/**: replace relative imports with @jackwener/opencli/...
- discovery.ts: simplify ensureUserCliCompatShims to symlink-only
- registry-api.ts: export CommandArgs type
- Remove root-level shim directories (browser/, download/, pipeline/)
- Remove shim entries from tsconfig.json include and package.json files

* test: add regression tests for package exports

Prevents regressions like #788/#791 by:
1. Scanning all adapter files for forbidden relative imports
   (../../src/, ../../browser/, etc.) — fails if any remain
2. Verifying every package.json export maps to an existing source file

18 new test cases.

* fix: use junction on Windows + broaden test patterns

- discovery.ts: use 'junction' symlink type on Windows (no admin required)
- package-exports.test.ts: generalize forbidden patterns to catch any
  depth of ../ traversal (not just ../../ and ../../../)

* fix: update stale vi.mock/importActual paths in adapter tests

Test files still used old relative paths for vi.mock() and
vi.importActual() calls. Updated 5 test files to use package exports.
Also broadened regression test patterns to catch mock/importActual paths.

* fix: use rm instead of unlink for symlink cleanup, add warn on failure

Addresses review feedback from Astro-Han:
- rm() handles both symlinks and stale directories (unlink fails on dirs)
- Log a warning when symlink creation fails instead of silent catch

* docs: update import examples to use package exports

Update all documentation, contributing guides, and skills to use
@jackwener/opencli/registry instead of ../../src/registry.js.

Without this, users following the docs would write adapters with
broken imports since the old shim files are no longer created.
2026-04-05 16:02:17 +08:00

81 lines
3.0 KiB
TypeScript

/**
* Xiaohongshu Creator Analytics — account-level metrics overview.
*
* Uses the creator.xiaohongshu.com internal API (cookie auth).
* Returns 7-day and 30-day aggregate stats: views, likes, collects,
* comments, shares, new followers, and daily trend data.
*
* Requires: logged into creator.xiaohongshu.com in Chrome.
*/
import { cli, Strategy } from '@jackwener/opencli/registry';
cli({
site: 'xiaohongshu',
name: 'creator-stats',
description: '小红书创作者数据总览 (观看/点赞/收藏/评论/分享/涨粉,含每日趋势)',
domain: 'creator.xiaohongshu.com',
strategy: Strategy.COOKIE,
browser: true,
args: [
{
name: 'period',
type: 'string',
default: 'seven',
help: 'Stats period: seven or thirty',
choices: ['seven', 'thirty'],
},
],
columns: ['metric', 'total', 'trend'],
func: async (page, kwargs) => {
const period: string = kwargs.period || 'seven';
// Navigate to creator center for cookie context
await page.goto('https://creator.xiaohongshu.com/new/home');
const data = await page.evaluate(`
async () => {
try {
const resp = await fetch('/api/galaxy/creator/data/note_detail_new', {
credentials: 'include',
});
if (!resp.ok) return { error: 'HTTP ' + resp.status };
return await resp.json();
} catch (e) {
return { error: e.message };
}
}
`);
if (data?.error) {
throw new Error(data.error + '. Are you logged into creator.xiaohongshu.com?');
}
if (!data?.data) {
throw new Error('Unexpected response structure');
}
const stats = data.data[period];
if (!stats) {
throw new Error(`No data for period "${period}". Available: ${Object.keys(data.data).join(', ')}`);
}
// Format daily trend as sparkline-like summary
const formatTrend = (list: any[]): string => {
if (!list || !list.length) return '-';
return list.map((d: any) => d.count).join(' → ');
};
return [
{ metric: '观看数 (views)', total: stats.view_count ?? 0, trend: formatTrend(stats.view_list) },
{ metric: '平均观看时长 (avg view time ms)', total: stats.view_time_avg ?? 0, trend: formatTrend(stats.view_time_list) },
{ metric: '主页访问 (home views)', total: stats.home_view_count ?? 0, trend: formatTrend(stats.home_view_list) },
{ metric: '点赞数 (likes)', total: stats.like_count ?? 0, trend: formatTrend(stats.like_list) },
{ metric: '收藏数 (collects)', total: stats.collect_count ?? 0, trend: formatTrend(stats.collect_list) },
{ metric: '评论数 (comments)', total: stats.comment_count ?? 0, trend: formatTrend(stats.comment_list) },
{ metric: '弹幕数 (danmaku)', total: stats.danmaku_count ?? 0, trend: '-' },
{ metric: '分享数 (shares)', total: stats.share_count ?? 0, trend: formatTrend(stats.share_list) },
{ metric: '涨粉数 (new followers)', total: stats.rise_fans_count ?? 0, trend: formatTrend(stats.rise_fans_list) },
];
},
});