重构为Monorepo:拆分xhs/xhh应用与core包并完成双服务部署改造

This commit is contained in:
2026-03-03 16:06:16 +08:00
parent ed7fbdd5c2
commit 2cbd6b28b2
84 changed files with 6332 additions and 7678 deletions
+160
View File
@@ -0,0 +1,160 @@
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import fs from 'node:fs/promises';
import os from 'node:os';
import path from 'node:path';
import crypto from 'node:crypto';
// ---------------------------------------------------------------------------
// Mocks
// ---------------------------------------------------------------------------
// We need to mock config BEFORE importing CookieStore, because the module
// reads config.cookieDir at import time.
let testDir: string;
vi.mock('../src/config/index.js', () => ({
config: {
get cookieDir() {
return testDir;
},
},
}));
vi.mock('../src/utils/logger.js', () => ({
logger: {
error: vi.fn(),
warn: vi.fn(),
info: vi.fn(),
debug: vi.fn(),
child: vi.fn(() => ({
error: vi.fn(),
warn: vi.fn(),
info: vi.fn(),
debug: vi.fn(),
})),
},
}));
// Import AFTER mocks are declared.
import { CookieStore, type StorageState } from '../src/cookie/store.js';
// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------
function makeStorageState(cookieCount = 1): StorageState {
const cookies = Array.from({ length: cookieCount }, (_, i) => ({
name: `cookie_${i}`,
value: `value_${i}`,
domain: '.example.com',
path: '/',
expires: Date.now() / 1000 + 3600,
httpOnly: true,
secure: true,
sameSite: 'Lax' as const,
}));
return {
cookies,
origins: [],
};
}
// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------
describe('CookieStore', () => {
let store: CookieStore;
beforeEach(async () => {
testDir = path.join(os.tmpdir(), `cookie-store-test-${crypto.randomUUID()}`);
await fs.mkdir(testDir, { recursive: true });
store = new CookieStore();
});
afterEach(async () => {
await fs.rm(testDir, { recursive: true, force: true });
});
// -- save ---------------------------------------------------------------
it('save creates the platform directory', async () => {
const state = makeStorageState();
await store.save('twitter', state);
const dirStat = await fs.stat(path.join(testDir, 'twitter'));
expect(dirStat.isDirectory()).toBe(true);
});
it('save writes the cookie file with restricted permissions (0o600)', async () => {
const state = makeStorageState();
await store.save('twitter', state);
const filePath = store.getPath('twitter');
const fileStat = await fs.stat(filePath);
// On Unix-like systems the mode includes the file type bits; mask to
// the permission bits only.
const perms = fileStat.mode & 0o777;
expect(perms).toBe(0o600);
});
// -- load ---------------------------------------------------------------
it('load returns saved data', async () => {
const state = makeStorageState(3);
await store.save('instagram', state);
const loaded = await store.load('instagram');
expect(loaded).not.toBeNull();
expect(loaded!.cookies).toHaveLength(3);
expect(loaded!.cookies[0]!.name).toBe('cookie_0');
});
it('load returns null for non-existent platform', async () => {
const loaded = await store.load('nonexistent');
expect(loaded).toBeNull();
});
// -- delete -------------------------------------------------------------
it('delete removes the cookie file', async () => {
const state = makeStorageState();
await store.save('weibo', state);
// Verify the file exists first.
const filePath = store.getPath('weibo');
await expect(fs.access(filePath)).resolves.toBeUndefined();
await store.delete('weibo');
// After deletion the file should no longer exist.
await expect(fs.access(filePath)).rejects.toThrow();
});
it('delete succeeds silently for a non-existent file', async () => {
// Should not throw even though no file was ever saved.
await expect(store.delete('ghost')).resolves.toBeUndefined();
});
// -- atomic write -------------------------------------------------------
it('save uses atomic write (temp file renamed to final path)', async () => {
const state = makeStorageState();
// Spy on fs.rename to verify it is called.
const renameSpy = vi.spyOn(fs, 'rename');
await store.save('atomic-test', state);
expect(renameSpy).toHaveBeenCalledTimes(1);
const [tmpArg, finalArg] = renameSpy.mock.calls[0]!;
expect(String(tmpArg)).toContain('.tmp.');
expect(String(finalArg)).toBe(store.getPath('atomic-test'));
renameSpy.mockRestore();
});
});
+156
View File
@@ -0,0 +1,156 @@
import { describe, it, expect, vi } from 'vitest';
// Mock the logger before importing the module under test.
vi.mock('../src/utils/logger.js', () => ({
logger: {
error: vi.fn(),
warn: vi.fn(),
info: vi.fn(),
debug: vi.fn(),
child: vi.fn(() => ({
error: vi.fn(),
warn: vi.fn(),
info: vi.fn(),
debug: vi.fn(),
})),
},
}));
import {
classifyError,
sanitizeErrorMessage,
withErrorHandling,
ErrorCategory,
} from '../src/utils/errors.js';
// ---------------------------------------------------------------------------
// classifyError
// ---------------------------------------------------------------------------
describe('classifyError', () => {
it('returns TIMEOUT when error name is "TimeoutError"', () => {
const err = new Error('something happened');
err.name = 'TimeoutError';
expect(classifyError(err)).toBe(ErrorCategory.TIMEOUT);
});
it('returns TIMEOUT when message contains "timeout"', () => {
const err = new Error('Connection timeout after 30s');
expect(classifyError(err)).toBe(ErrorCategory.TIMEOUT);
});
it('returns PLATFORM_ERROR when message contains "net::err_"', () => {
const err = new Error('net::err_connection_refused');
expect(classifyError(err)).toBe(ErrorCategory.PLATFORM_ERROR);
});
it('returns CAPTCHA_REQUIRED when message contains captcha keyword', () => {
const err = new Error('show_captcha');
expect(classifyError(err)).toBe(ErrorCategory.CAPTCHA_REQUIRED);
});
it('returns AUTH_REQUIRED when message contains "login"', () => {
const err = new Error('Please login to continue');
expect(classifyError(err)).toBe(ErrorCategory.AUTH_REQUIRED);
});
it('returns AUTH_REQUIRED when message contains Chinese login word', () => {
const err = new Error('请先登录');
expect(classifyError(err)).toBe(ErrorCategory.AUTH_REQUIRED);
});
it('returns SELECTOR_NOT_FOUND when message contains "waiting for selector"', () => {
const err = new Error('Timeout waiting for selector "#submit-btn"');
expect(classifyError(err)).toBe(ErrorCategory.SELECTOR_NOT_FOUND);
});
it('returns INTERNAL for unrecognised errors', () => {
const err = new Error('Something unexpected happened');
expect(classifyError(err)).toBe(ErrorCategory.INTERNAL);
});
});
// ---------------------------------------------------------------------------
// sanitizeErrorMessage
// ---------------------------------------------------------------------------
describe('sanitizeErrorMessage', () => {
it('replaces absolute file-system paths with [path]', () => {
const msg = 'Failed to read /home/user/data/secrets.json';
const result = sanitizeErrorMessage(msg);
expect(result).toContain('[path]');
expect(result).not.toContain('/home/user/data/secrets.json');
});
it('replaces URLs with [url]', () => {
const msg = 'Fetch failed for https://api.example.com/v1/token';
const result = sanitizeErrorMessage(msg);
expect(result).toContain('[url]');
expect(result).not.toContain('https://api.example.com');
});
it('replaces long hex strings (>=32 chars) with [hash]', () => {
const hex = 'a'.repeat(32);
const msg = `Invalid session id: ${hex}`;
const result = sanitizeErrorMessage(msg);
expect(result).toContain('[hash]');
expect(result).not.toContain(hex);
});
it('truncates messages longer than 200 characters', () => {
const msg = 'x'.repeat(300);
const result = sanitizeErrorMessage(msg);
expect(result.length).toBe(200);
});
it('leaves short plain messages unchanged', () => {
const msg = 'Something went wrong';
expect(sanitizeErrorMessage(msg)).toBe(msg);
});
});
// ---------------------------------------------------------------------------
// withErrorHandling
// ---------------------------------------------------------------------------
describe('withErrorHandling', () => {
it('passes through successful results', async () => {
const expected = {
content: [{ type: 'text' as const, text: 'ok' }],
};
const result = await withErrorHandling('test_tool', async () => expected);
expect(result).toEqual(expected);
expect(result.isError).toBeUndefined();
});
it('returns isError:true with classified error JSON on failure', async () => {
const result = await withErrorHandling('publish_post', async () => {
throw new Error('Connection timeout after 30s');
});
expect(result.isError).toBe(true);
expect(result.content).toHaveLength(1);
const payload = JSON.parse(result.content[0]!.text);
expect(payload.success).toBe(false);
expect(payload.error.tool).toBe('publish_post');
expect(payload.error.code).toBe(ErrorCategory.TIMEOUT);
expect(typeof payload.error.message).toBe('string');
});
it('wraps non-Error throws into an Error', async () => {
const result = await withErrorHandling('my_tool', async () => {
throw 'raw string error';
});
expect(result.isError).toBe(true);
const payload = JSON.parse(result.content[0]!.text);
expect(payload.success).toBe(false);
expect(payload.error.tool).toBe('my_tool');
expect(payload.error.code).toBe(ErrorCategory.INTERNAL);
expect(payload.error.message).toContain('raw string error');
});
});