const NPM_SEARCH_URL = 'https://registry.npmjs.org/-/v1/search';
const NPM_DOWNLOADS_URL = 'https://api.npmjs.org/downloads/point/last-week';
const GITHUB_SEARCH_URL = 'https://api.github.com/search/repositories';
const TIMEOUT_MS = 5000;
function withTimeout(promise, ms) {
    return Promise.race([
        promise,
        new Promise((_, reject) => setTimeout(() => {
            reject(new Error('timeout'));
        }, ms)),
    ]);
}
async function fetchJson(url) {
    const response = await withTimeout(fetch(url), TIMEOUT_MS);
    if (!response.ok) {
        throw new Error(`HTTP ${response.status}`);
    }
    return response.json();
}
async function getWeeklyDownloads(name) {
    try {
        const data = (await fetchJson(`${NPM_DOWNLOADS_URL}/${encodeURIComponent(name)}`));
        return data.downloads;
    }
    catch {
        return undefined;
    }
}
export async function searchNpmRegistry(keywords) {
    const targets = keywords.slice(0, 3);
    const results = [];
    for (const keyword of targets) {
        try {
            const url = `${NPM_SEARCH_URL}?text=keywords:${encodeURIComponent(keyword)}&size=5`;
            const data = (await fetchJson(url));
            const packages = data.objects ?? [];
            for (const obj of packages) {
                const pkg = obj.package;
                const downloads = await getWeeklyDownloads(pkg.name);
                results.push({
                    name: pkg.name,
                    description: pkg.description ?? '',
                    url: pkg.links?.npm ?? `https://www.npmjs.com/package/${pkg.name}`,
                    source: 'npm',
                    publishedAt: pkg.date,
                    weeklyDownloads: downloads,
                });
            }
        }
        catch {
            // best-effort: skip failed keyword
        }
    }
    return results;
}
export async function searchGitHubTopics(topics) {
    const targets = topics.slice(0, 2);
    const results = [];
    for (const topic of targets) {
        try {
            const query = `topic:${encodeURIComponent(topic)}+stars:>500`;
            const url = `${GITHUB_SEARCH_URL}?q=${query}&sort=stars&per_page=5`;
            const data = (await fetchJson(url));
            const items = data.items ?? [];
            for (const item of items) {
                results.push({
                    name: item.full_name,
                    description: item.description ?? '',
                    url: item.html_url,
                    source: 'github',
                    stars: item.stargazers_count,
                    pushedAt: item.pushed_at,
                });
            }
        }
        catch {
            // best-effort: skip failed topic
        }
    }
    return results;
}
//# sourceMappingURL=registry-search.js.map