🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
import { beforeEach, describe, expect, it, vi } from 'vitest';
import {
NetworkConnectionError,
PageNotFoundError,
TimeoutError,
UnsupportedContentError,
} from '../../utils/errorType';
import { naive } from '../naive';
// Mock dependencies
vi.mock('../../utils/htmlToMarkdown', () => ({
htmlToMarkdown: vi.fn(),
}));
vi.mock('../../utils/withTimeout', () => ({
DEFAULT_TIMEOUT: 30000,
withTimeout: vi.fn(),
}));
vi.mock('@lobechat/ssrf-safe-fetch', () => ({
ssrfSafeFetch: vi.fn(),
}));
describe('naive crawler', () => {
beforeEach(() => {
vi.clearAllMocks();
});
it('should return content for normal pages', async () => {
const mockResponse = {
status: 200,
ok: true,
headers: new Map([['content-type', 'text/html']]),
text: vi.fn().mockResolvedValue('<html><body>Test content</body></html>'),
};
const { withTimeout } = await import('../../utils/withTimeout');
vi.mocked(withTimeout).mockResolvedValue(mockResponse as any);
const { htmlToMarkdown } = await import('../../utils/htmlToMarkdown');
vi.mocked(htmlToMarkdown).mockReturnValue({
content: 'Test content'.padEnd(101, ' '),
title: 'Normal Page Title',
description: 'Test description',
siteName: 'Test Site',
length: 101,
});
const result = await naive('https://example.com', { filterOptions: {} });
expect(result).toEqual({
content: 'Test content'.padEnd(101, ' '),
contentType: 'text',
description: 'Test description',
length: 101,
siteName: 'Test Site',
title: 'Normal Page Title',
url: 'https://example.com',
});
});
it('should throw UnsupportedContentError for non-document content types', async () => {
const { withTimeout } = await import('../../utils/withTimeout');
const { htmlToMarkdown } = await import('../../utils/htmlToMarkdown');
for (const contentType of ['image/png', 'image/svg+xml', 'font/woff2', 'video/mp4']) {
vi.mocked(withTimeout).mockResolvedValue({
status: 200,
ok: true,
headers: new Map([['content-type', contentType]]),
text: vi.fn().mockResolvedValue('binary'),
} as any);
await expect(naive('https://example.com/asset', { filterOptions: {} })).rejects.toThrow(
UnsupportedContentError,
);
}
expect(htmlToMarkdown).not.toHaveBeenCalled();
});
it('should skip PDF responses without downloading or parsing them as HTML', async () => {
const { withTimeout } = await import('../../utils/withTimeout');
const { htmlToMarkdown } = await import('../../utils/htmlToMarkdown');
const text = vi.fn().mockResolvedValue('%PDF-1.7\n...');
vi.mocked(withTimeout).mockResolvedValue({
status: 200,
ok: true,
headers: new Map([['content-type', 'application/pdf; qs=0.001']]),
text,
} as any);
const result = await naive('https://example.com/report.pdf', { filterOptions: {} });
expect(result).toBeUndefined();
expect(text).not.toHaveBeenCalled();
expect(htmlToMarkdown).not.toHaveBeenCalled();
});
it('should skip binary bodies served under a text or missing content type', async () => {
const { withTimeout } = await import('../../utils/withTimeout');
const { htmlToMarkdown } = await import('../../utils/htmlToMarkdown');
const cases: [string | undefined, string][] = [
['text/html', '%PDF-1.4\n%âãÏÓ\n1 0 obj'],
[undefined, '<html>\u0000\u0001\u0002 stream bytes'],
];
for (const [contentType, body] of cases) {
vi.mocked(withTimeout).mockResolvedValue({
status: 200,
ok: true,
headers: new Map(contentType ? [['content-type', contentType]] : []),
text: vi.fn().mockResolvedValue(body),
} as any);
const result = await naive('https://example.com/download', { filterOptions: {} });
expect(result).toBeUndefined();
}
expect(htmlToMarkdown).not.toHaveBeenCalled();
});
it('should throw PageNotFoundError with status for 410 Gone', async () => {
const { withTimeout } = await import('../../utils/withTimeout');
vi.mocked(withTimeout).mockResolvedValue({
status: 410,
ok: false,
statusText: 'Gone',
headers: new Map(),
text: vi.fn().mockResolvedValue(''),
} as any);
await expect(naive('https://example.com/removed', { filterOptions: {} })).rejects.toMatchObject(
{ name: 'PageNotFoundError', status: 410 },
);
});
it('should successfully crawl JSON content', async () => {
const mockJsonData = { message: 'Hello world', data: [1, 2, 3] };
const mockResponse = {
status: 200,
ok: true,
headers: new Map([['content-type', 'application/json']]),
clone: () => ({
json: vi.fn().mockResolvedValue(mockJsonData),
}),
text: vi.fn().mockResolvedValue(JSON.stringify(mockJsonData)),
};
const { withTimeout } = await import('../../utils/withTimeout');
vi.mocked(withTimeout).mockResolvedValue(mockResponse as any);
const result = await naive('https://api.example.com/data', { filterOptions: {} });
expect(result).toEqual({
content: JSON.stringify(mockJsonData, null, 2),
contentType: 'json',
length: JSON.stringify(mockJsonData, null, 2).length,
url: 'https://api.example.com/data',
});
});
it('should handle malformed JSON by falling back to text', async () => {
const mockText = '{"invalid": json}';
const mockResponse = {
status: 200,
ok: true,
headers: new Map([['content-type', 'application/json']]),
clone: () => ({
json: vi.fn().mockRejectedValue(new Error('Invalid JSON')),
}),
text: vi.fn().mockResolvedValue(mockText),
};
const { withTimeout } = await import('../../utils/withTimeout');
vi.mocked(withTimeout).mockResolvedValue(mockResponse as any);
const result = await naive('https://api.example.com/data', { filterOptions: {} });
expect(result).toEqual({
content: mockText,
contentType: 'json',
length: mockText.length,
url: 'https://api.example.com/data',
});
});
it('should return undefined for short content', async () => {
const mockResponse = {
status: 200,
ok: true,
headers: new Map([['content-type', 'text/html']]),
text: vi.fn().mockResolvedValue('<html><body>Short</body></html>'),
};
const { withTimeout } = await import('../../utils/withTimeout');
vi.mocked(withTimeout).mockResolvedValue(mockResponse as any);
const { htmlToMarkdown } = await import('../../utils/htmlToMarkdown');
vi.mocked(htmlToMarkdown).mockReturnValue({
content: 'Short', // Length < 100
title: 'Test Page',
length: 5,
});
const result = await naive('https://example.com', { filterOptions: {} });
expect(result).toBeUndefined();
});
it('should return undefined when blocked by Cloudflare', async () => {
const mockResponse = {
status: 200,
ok: true,
headers: new Map([['content-type', 'text/html']]),
text: vi.fn().mockResolvedValue('<html><body>Normal content</body></html>'),
};
const { withTimeout } = await import('../../utils/withTimeout');
vi.mocked(withTimeout).mockResolvedValue(mockResponse as any);
const { htmlToMarkdown } = await import('../../utils/htmlToMarkdown');
vi.mocked(htmlToMarkdown).mockReturnValue({
content: 'Test content'.padEnd(101, ' '),
title: 'Just a moment...', // Cloudflare blocking page
description: 'Test description',
siteName: 'Test Site',
length: 101,
});
const result = await naive('https://example.com', { filterOptions: {} });
expect(result).toBeUndefined();
});
it('should throw error for non-ok status codes', async () => {
const mockResponse = {
status: 500,
ok: false,
statusText: 'Internal Server Error',
text: vi.fn().mockResolvedValue('Server Error'),
};
const { withTimeout } = await import('../../utils/withTimeout');
vi.mocked(withTimeout).mockResolvedValue(mockResponse as any);
await expect(naive('https://example.com', { filterOptions: {} })).rejects.toThrow(/500/);
});
it('should throw PageNotFoundError for 404 status', async () => {
const mockResponse = {
status: 404,
statusText: 'Not Found',
};
const { withTimeout } = await import('../../utils/withTimeout');
vi.mocked(withTimeout).mockResolvedValue(mockResponse as any);
await expect(naive('https://example.com/notfound', { filterOptions: {} })).rejects.toThrow(
PageNotFoundError,
);
});
it('should throw NetworkConnectionError for fetch failures', async () => {
const { withTimeout } = await import('../../utils/withTimeout');
vi.mocked(withTimeout).mockRejectedValue(new TypeError('fetch failed'));
await expect(naive('https://example.com', { filterOptions: {} })).rejects.toThrow(
NetworkConnectionError,
);
});
it('should throw TimeoutError when request times out', async () => {
const timeoutError = new TimeoutError('Request timeout');
const { withTimeout } = await import('../../utils/withTimeout');
vi.mocked(withTimeout).mockRejectedValue(timeoutError);
await expect(naive('https://example.com', { filterOptions: {} })).rejects.toThrow(TimeoutError);
});
it('should rethrow unknown errors', async () => {
const unknownError = new Error('Unknown error');
const { withTimeout } = await import('../../utils/withTimeout');
vi.mocked(withTimeout).mockRejectedValue(unknownError);
await expect(naive('https://example.com', { filterOptions: {} })).rejects.toThrow(
'Unknown error',
);
});
it('should return undefined when HTML processing fails', async () => {
const mockResponse = {
status: 200,
ok: true,
headers: new Map([['content-type', 'text/html']]),
text: vi.fn().mockRejectedValue(new Error('Failed to read text')),
};
const { withTimeout } = await import('../../utils/withTimeout');
vi.mocked(withTimeout).mockResolvedValue(mockResponse as any);
const result = await naive('https://example.com', { filterOptions: {} });
expect(result).toBeUndefined();
});
it('should pass filter options to htmlToMarkdown', async () => {
const mockResponse = {
status: 200,
ok: true,
headers: new Map([['content-type', 'text/html']]),
text: vi.fn().mockResolvedValue('<html><body>Test content</body></html>'),
};
const { withTimeout } = await import('../../utils/withTimeout');
vi.mocked(withTimeout).mockResolvedValue(mockResponse as any);
const { htmlToMarkdown } = await import('../../utils/htmlToMarkdown');
vi.mocked(htmlToMarkdown).mockReturnValue({
content: 'Test content'.padEnd(101, ' '),
title: 'Test Page',
length: 101,
});
const filterOptions = { enableReadability: true, pureText: false };
await naive('https://example.com', { filterOptions });
expect(htmlToMarkdown).toHaveBeenCalledWith('<html><body>Test content</body></html>', {
filterOptions,
url: 'https://example.com',
});
});
});