npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@phygitallabs/statistics

v6.1.0

Published

A comprehensive statistics package that provides React hooks for analytics data, built on top of OpenAPI-generated services and React Query.

Readme

Statistics Package

A comprehensive statistics package that provides React hooks for analytics data, built on top of OpenAPI-generated services and React Query.

Features

  • 🚀 Auto-generated hooks from OpenAPI specification
  • 🔧 Configurable API client with authentication support
  • React Query integration with optimized caching
  • 🔄 Dynamic configuration updates without page reload
  • 🛡️ TypeScript support with full type safety
  • 📊 Comprehensive analytics endpoints for various statistics

Installation

npm install statistics
# or
yarn add statistics

Quick Start

1. Basic Setup

import { StatisticsProvider } from 'statistics';

function App() {
  const config = {
    baseUrl: 'https://api.statistics.example.com',
    apiKey: 'your-api-key',
  };

  return (
    <StatisticsProvider config={config}>
      <YourAppComponents />
    </StatisticsProvider>
  );
}

2. Advanced Setup with Token Refresh (Similar to QueryProvider)

import { StatisticsProvider, type StatisticsConfig } from 'statistics';

const memoizedRefreshToken = async () => {
  const refreshToken = localStorage.getItem('refreshToken');
  const response = await fetch('/api/auth/refresh', {
    method: 'POST',
    body: JSON.stringify({ refreshToken }),
  });
  return response.json();
};

function App() {
  const config: StatisticsConfig = {
    baseUrl: 'https://api.statistics.com/v1',
    accessTokenKey: 'accessToken',
    refreshTokenKey: 'refreshToken',
    httpMaxRetries: 3,
    onTokenRefresh: memoizedRefreshToken,
    onAuthError: () => window.location.href = '/login',
  };

  const queryClientConfig = {
    defaultOptions: {
      queries: {
        refetchOnWindowFocus: false,
        staleTime: 1000 * 60 * 5,
      },
    },
  };

  const responseInterceptors = {
    onFulfilled: (response) => response,
    onRejected: async (error) => {
      // Auto token refresh logic
      // ... (handled automatically by provider)
      return Promise.reject(error);
    },
  };

  return (
    <StatisticsProvider 
      config={config}
      queryClientConfig={queryClientConfig}
      responseInterceptors={responseInterceptors}
    >
      <YourAppComponents />
    </StatisticsProvider>
  );
}

3. Use statistics hooks in your components

import { useV1AnalyticsServiceGetV1AnalyticsActiveChipCount } from 'statistics';

function Dashboard() {
  const { data, isLoading, error } = useV1AnalyticsServiceGetV1AnalyticsActiveChipCount({
    organizationId: 'org-123',
    projectId: 'project-456',
    startDate: '2024-01-01',
    endDate: '2024-12-31',
  });

  if (isLoading) return <div>Loading...</div>;
  if (error) return <div>Error: {error.message}</div>;

  return <div>Active Chips: {data?.data?.total}</div>;
}

Configuration

StatisticsConfig Options

interface StatisticsConfig {
  baseUrl: string;              // Required: API base URL
  apiKey?: string;              // Optional: API key for authentication
  token?: string;               // Optional: Bearer token for authentication
  headers?: Record<string, string>; // Optional: Additional headers
  withCredentials?: boolean;    // Optional: Include credentials (default: false)
  credentials?: 'include' | 'omit' | 'same-origin'; // Optional: Credentials mode
  
  // Advanced token management
  accessTokenKey?: string;      // Optional: Storage key for access token (default: 'accessToken')
  refreshTokenKey?: string;     // Optional: Storage key for refresh token (default: 'refreshToken')
  userInfoKey?: string;         // Optional: Storage key for user info (default: 'userInfo')
  retryAttemptsKey?: string;    // Optional: Storage key for retry attempts (default: 'retryAttemptsRefreshToken')
  httpMaxRetries?: number;      // Optional: Max retry attempts (default: 3)
  
  // Token refresh callback
  onTokenRefresh?: () => Promise<{ accessToken: string; refreshToken: string } | null>;
  onAuthError?: () => void;     // Optional: Called when auth fails
  
  // Custom storage functions (default: localStorage)
  getFromStorage?: (key: string) => string | null;
  setToStorage?: (key: string, value: string) => void;
  removeFromStorage?: (key: string) => void;
}

Authentication Methods

API Key Authentication

const config = {
  baseUrl: 'https://api.statistics.example.com',
  apiKey: 'your-api-key',
};

Bearer Token Authentication

const config = {
  baseUrl: 'https://api.statistics.example.com',
  token: 'your-bearer-token',
};

Custom Headers

const config = {
  baseUrl: 'https://api.statistics.example.com',
  headers: {
    'Authorization': 'Custom your-token',
    'X-Custom-Header': 'value',
  },
};

Available Hooks

Provider Hooks

  • useStatisticsConfig - Get full provider context
  • useStatisticsApiConfig - Get current API configuration
  • useUpdateStatisticsConfig - Update configuration dynamically
  • useStatisticsQueryClient - Get React Query client instance
  • useStatisticsToken - Get current access token from storage
  • useStatisticsRefreshToken - Manually refresh token
  • useStatisticsClearAuth - Clear all authentication data

Analytics Hooks

  • useV1AnalyticsServiceGetV1AnalyticsActiveChipCount - Get active chip count
  • useV1AnalyticsServiceGetV1AnalyticsChipCount - Get chip count with filters
  • useV1AnalyticsServiceGetV1AnalyticsUserCount - Get user count statistics
  • useV1AnalyticsServiceGetV1AnalyticsScanCount - Get scan count analytics
  • useV1AnalyticsServiceGetV1AnalyticsLeadCount - Get lead count statistics

Project Hooks

  • useV1ProjectsServiceGetV1ProjectsStatistics - Get project statistics
  • useV1ProjectsServiceGetV1ProjectsByProjectIdItemStatistics - Get item statistics for a project

Campaign Hooks

  • useV1CampaignsServiceGetV1CampaignsByCampaignIdLocationsStatisticsCheckIn - Get location check-in statistics
  • useV1CampaignsServiceGetV1CampaignsByCampaignIdRankingUserCheckIn - Get user ranking statistics

Reward Hooks

  • useV1AdminUserRewardsServiceGetV1AdminUserRewardsStatistic - Get user reward statistics
  • useV1RewardModelsServiceGetV1ProjectsByProjectIdRewardModelsStatistics - Get reward model statistics

Advanced Usage

Dynamic Configuration Updates

import { useUpdateStatisticsConfig, useStatisticsApiConfig } from 'statistics';

function ConfigComponent() {
  const config = useStatisticsApiConfig();
  const updateConfig = useUpdateStatisticsConfig();

  const switchEnvironment = () => {
    updateConfig({
      baseUrl: 'https://staging-api.statistics.example.com',
      apiKey: 'staging-api-key',
    });
  };

  return (
    <div>
      <p>Current API: {config.baseUrl}</p>
      <button onClick={switchEnvironment}>Switch to Staging</button>
    </div>
  );
}

Custom Query Client

import { QueryClient } from '@tanstack/react-query';
import { StatisticsProvider } from 'statistics';

const customQueryClient = new QueryClient({
  defaultOptions: {
    queries: {
      staleTime: 1000 * 60 * 10, // 10 minutes
      gcTime: 1000 * 60 * 60,    // 1 hour
      retry: 3,
      refetchOnWindowFocus: false,
    },
  },
});

function App() {
  return (
    <StatisticsProvider 
      config={config}
      queryClient={customQueryClient}
    >
      <YourApp />
    </StatisticsProvider>
  );
}

Error Handling

function StatisticsComponent() {
  const { 
    data, 
    isLoading, 
    error, 
    refetch,
    failureCount,
    isError 
  } = useV1AnalyticsServiceGetV1AnalyticsActiveChipCount({
    organizationId: 'org-123',
  });

  if (isLoading) return <div>Loading...</div>;
  
  if (isError) {
    return (
      <div className="error-state">
        <p>Failed to load data (Attempt {failureCount})</p>
        <p>Error: {error?.message}</p>
        <button onClick={() => refetch()}>Retry</button>
      </div>
    );
  }

  return <div>Data: {JSON.stringify(data)}</div>;
}

Environment Variables

You can use environment variables for configuration:

const config = {
  baseUrl: process.env.NEXT_PUBLIC_STATISTICS_API_URL || 'https://api.statistics.example.com',
  apiKey: process.env.STATISTICS_API_KEY,
};

TypeScript Support

The package provides full TypeScript support with auto-generated types:

import type { 
  StatisticsConfig,
  V1AnalyticsServiceGetV1AnalyticsActiveChipCountDefaultResponse 
} from 'statistics';

function TypedComponent() {
  const { data }: { data?: V1AnalyticsServiceGetV1AnalyticsActiveChipCountDefaultResponse } = 
    useV1AnalyticsServiceGetV1AnalyticsActiveChipCount();
  
  // data is fully typed
  const total = data?.data?.total;
}

Development

Regenerating API Hooks

When the OpenAPI specification is updated:

npm run codegen

This will regenerate all hooks and types from the statistic.yaml file.

License

ISC