Fetches download statistics for Highcharts

by stitot

JavaScript

const BASES = {
  jsDelivr: "https://data.jsdelivr.com/v1/stats/packages/npm",
  npmRange: "https://api.npmjs.org/downloads/range",
  npmRegistry: "https://registry.npmjs.org",
};
const PACKAGE = "highcharts";


async function fetchDownloadStats(from, to) {


  const fetchPublishDates = async () => {
    const url = `${BASES.npmRegistry}/${encodeURIComponent(PACKAGE)}`;
    const res = await fetch(url);
    const data = await res.json();
    //const data = await fetchJson(url, "npm registry");
    return Object.entries(data.time)
      .filter(([k]) => k !== "created" && k !== "modified")
      .reduce((acc, [ver, date]) => ({ ...acc, [ver]: date.slice(0, 10) }), {});
  };

  const versions = await fetchPublishDates();
  console.log(versions);



  const fromDate = new Date(from);
  const toDate = new Date(to);

  const getYearPeriods = () => {
    const years = [];
    for (let y = fromDate.getFullYear(); y <= toDate.getFullYear(); y++) {
      years.push(y === new Date().getFullYear() ? 'year' : y.toString());
    }
    return years;
  };

  const fetchStats = async (source) => {
    const result = [];

    if (source === 'jsdelivr') {
      for (const period of getYearPeriods()) {
        const url = `https://data.jsdelivr.com/v1/stats/packages/npm/highcharts?period=${period}`;
        console.log(`[jsDelivr] Fetching: ${url}`);
        const res = await fetch(url);
        const json = await res.json();
        for (const [day, hits] of Object.entries(json.hits?.dates || {})) {
          const d = new Date(day);
          if (d >= fromDate && d <= toDate) result.push([day, hits]);
        }
      }
    }

    if (source === 'npm') {
      let start = new Date(fromDate);
      while (start <= toDate) {
        const end = new Date(Math.min(toDate, new Date(start.getFullYear() + 1, start.getMonth(), start.getDate())));
        const range = `${start.toISOString().slice(0, 10)}:${end.toISOString().slice(0,...