Files
jackwener__opencli/clis/douban/download.test.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

197 lines
6.8 KiB
TypeScript

import { beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
import path from 'node:path';
import type { CliCommand } from '@jackwener/opencli/registry';
import { getRegistry } from '@jackwener/opencli/registry';
import type { IPage } from '@jackwener/opencli/types';
const { mockHttpDownload, mockLoadDoubanSubjectPhotos, mockMkdirSync } = vi.hoisted(() => ({
mockHttpDownload: vi.fn(),
mockLoadDoubanSubjectPhotos: vi.fn(),
mockMkdirSync: vi.fn(),
}));
vi.mock('@jackwener/opencli/download', () => ({
httpDownload: mockHttpDownload,
sanitizeFilename: vi.fn((value: string) => value.replace(/\s+/g, '_')),
}));
vi.mock('./utils.js', async () => {
const actual = await vi.importActual<typeof import('./utils.js')>('./utils.js');
return {
...actual,
loadDoubanSubjectPhotos: mockLoadDoubanSubjectPhotos,
};
});
vi.mock('@jackwener/opencli/download/progress', () => ({
formatBytes: vi.fn((size: number) => `${size} B`),
}));
vi.mock('node:fs', () => ({
mkdirSync: mockMkdirSync,
}));
await import('./download.js');
let cmd: CliCommand;
beforeAll(() => {
cmd = getRegistry().get('douban/download')!;
expect(cmd?.func).toBeTypeOf('function');
});
function toPosixPath(value: string): string {
return value.replaceAll(path.sep, '/');
}
describe('douban download', () => {
beforeEach(() => {
mockHttpDownload.mockReset();
mockLoadDoubanSubjectPhotos.mockReset();
mockMkdirSync.mockReset();
});
it('downloads douban poster images and merges metadata into the result', async () => {
const page = {} as IPage;
mockLoadDoubanSubjectPhotos.mockResolvedValue({
subjectId: '30382501',
subjectTitle: 'The Wandering Earth 2',
type: 'Rb',
photos: [
{
index: 1,
photoId: '2913450214',
title: 'Main poster',
imageUrl: 'https://img1.doubanio.com/view/photo/l/public/p2913450214.webp',
thumbUrl: 'https://img1.doubanio.com/view/photo/m/public/p2913450214.webp',
detailUrl: 'https://movie.douban.com/photos/photo/2913450214/',
page: 1,
},
{
index: 2,
photoId: '2913450215',
title: 'Character poster',
imageUrl: 'https://img1.doubanio.com/view/photo/l/public/p2913450215.jpg',
thumbUrl: 'https://img1.doubanio.com/view/photo/m/public/p2913450215.jpg',
detailUrl: 'https://movie.douban.com/photos/photo/2913450215/',
page: 1,
},
],
});
mockHttpDownload
.mockResolvedValueOnce({ success: true, size: 1200 })
.mockResolvedValueOnce({ success: true, size: 980 });
const result = await cmd.func!(page, {
id: '30382501',
type: 'Rb',
limit: 20,
output: '/tmp/douban-test',
}) as Array<Record<string, unknown>>;
expect(mockLoadDoubanSubjectPhotos).toHaveBeenCalledWith(page, '30382501', {
type: 'Rb',
limit: 20,
});
expect(mockMkdirSync).toHaveBeenCalledTimes(1);
expect(toPosixPath(mockMkdirSync.mock.calls[0][0])).toBe('/tmp/douban-test/30382501');
expect(mockMkdirSync.mock.calls[0][1]).toEqual({ recursive: true });
expect(mockHttpDownload).toHaveBeenCalledTimes(2);
expect(mockHttpDownload.mock.calls[0]?.[0]).toBe('https://img1.doubanio.com/view/photo/l/public/p2913450214.webp');
expect(toPosixPath(mockHttpDownload.mock.calls[0]?.[1])).toBe('/tmp/douban-test/30382501/30382501_001_2913450214_Main_poster.webp');
expect(mockHttpDownload.mock.calls[0]?.[2]).toEqual(expect.objectContaining({
headers: { Referer: 'https://movie.douban.com/photos/photo/2913450214/' },
timeout: 60000,
}));
expect(mockHttpDownload.mock.calls[1]?.[0]).toBe('https://img1.doubanio.com/view/photo/l/public/p2913450215.jpg');
expect(toPosixPath(mockHttpDownload.mock.calls[1]?.[1])).toBe('/tmp/douban-test/30382501/30382501_002_2913450215_Character_poster.jpg');
expect(mockHttpDownload.mock.calls[1]?.[2]).toEqual(expect.objectContaining({
headers: { Referer: 'https://movie.douban.com/photos/photo/2913450215/' },
timeout: 60000,
}));
expect(result).toEqual([
{
index: 1,
title: 'Main poster',
photo_id: '2913450214',
image_url: 'https://img1.doubanio.com/view/photo/l/public/p2913450214.webp',
detail_url: 'https://movie.douban.com/photos/photo/2913450214/',
status: 'success',
size: '1200 B',
},
{
index: 2,
title: 'Character poster',
photo_id: '2913450215',
image_url: 'https://img1.doubanio.com/view/photo/l/public/p2913450215.jpg',
detail_url: 'https://movie.douban.com/photos/photo/2913450215/',
status: 'success',
size: '980 B',
},
]);
});
it('downloads only the requested photo when photo-id is provided', async () => {
const page = {} as IPage;
mockLoadDoubanSubjectPhotos.mockResolvedValue({
subjectId: '30382501',
subjectTitle: 'The Wandering Earth 2',
type: 'Rb',
photos: [
{
index: 2,
photoId: '2913450215',
title: 'Character poster',
imageUrl: 'https://img1.doubanio.com/view/photo/l/public/p2913450215.jpg',
thumbUrl: 'https://img1.doubanio.com/view/photo/m/public/p2913450215.jpg',
detailUrl: 'https://movie.douban.com/photos/photo/2913450215/',
page: 1,
},
],
});
mockHttpDownload.mockResolvedValueOnce({ success: true, size: 980 });
const result = await cmd.func!(page, {
id: '30382501',
type: 'Rb',
'photo-id': '2913450215',
output: '/tmp/douban-test',
}) as Array<Record<string, unknown>>;
expect(mockLoadDoubanSubjectPhotos).toHaveBeenCalledWith(page, '30382501', {
type: 'Rb',
targetPhotoId: '2913450215',
});
expect(mockHttpDownload).toHaveBeenCalledTimes(1);
expect(mockHttpDownload.mock.calls[0]?.[0]).toBe('https://img1.doubanio.com/view/photo/l/public/p2913450215.jpg');
expect(toPosixPath(mockHttpDownload.mock.calls[0]?.[1])).toBe('/tmp/douban-test/30382501/30382501_002_2913450215_Character_poster.jpg');
expect(mockHttpDownload.mock.calls[0]?.[2]).toEqual(expect.objectContaining({
headers: { Referer: 'https://movie.douban.com/photos/photo/2913450215/' },
timeout: 60000,
}));
expect(result).toEqual([
{
index: 2,
title: 'Character poster',
photo_id: '2913450215',
image_url: 'https://img1.doubanio.com/view/photo/l/public/p2913450215.jpg',
detail_url: 'https://movie.douban.com/photos/photo/2913450215/',
status: 'success',
size: '980 B',
},
]);
});
it('rejects invalid subject ids before attempting browser work', async () => {
await expect(
cmd.func!({} as IPage, { id: 'movie-30382501' }),
).rejects.toThrow('Invalid Douban subject ID');
expect(mockHttpDownload).not.toHaveBeenCalled();
});
});