Skip to content

Modular Packages

Jashan Randhawa edited this page Sep 28, 2026 · 1 revision

📦 Modular Packages & Ecosystem

FitTrack AI maintains 7 decoupled, production-grade, fully typed npm packages published under the @jashan-randhawa/ scope on GitHub Packages (https://npm.pkg.github.com).

These packages encapsulate the foundational building blocks of the platform—ranging from resilient LLM communication and multi-tier rate limiting to interactive heatmaps and headless workout session management.


🧭 Packages Catalog at a Glance

Package Version Registry Location Target & Ecosystem
@jashan-randhawa/openrouter-resilient-client 0.1.0 GitHub Packages Universal / Node.js (Zero deps)
@jashan-randhawa/express-ai-guard 0.1.0 GitHub Packages Express 4 & 5 / Node.js
@jashan-randhawa/react-calendar-heatmap-streaks 0.1.0 GitHub Packages React 18 & 19
@jashan-randhawa/react-workout-tracker 0.1.0 GitHub Packages React 18 & 19 (Headless & UI)
@jashan-randhawa/react-motion-presets 0.1.0 GitHub Packages React 18 & 19 (Framer Motion)
@jashan-randhawa/fitness-utils 0.1.0 GitHub Packages Multi-entrypoint: ., ./react, ./pdf
@jashan-randhawa/ai-nutrition-estimator 0.1.0 GitHub Packages Universal / Node.js

🛠️ Installation & Setup via GitHub Packages

Because these packages are hosted on GitHub Packages, configure your project's .npmrc to route the @jashan-randhawa scope to GitHub's registry:

1. Configure .npmrc

Create or edit .npmrc in your project root:

@jashan-randhawa:registry=https://npm.pkg.github.com
//npm.pkg.github.com/:_authToken=${GITHUB_TOKEN}

Note

GITHUB_TOKEN requires read:packages scope to install packages from GitHub Packages.

2. Install Packages

# Install individual packages as needed
npm install @jashan-randhawa/openrouter-resilient-client
npm install @jashan-randhawa/express-ai-guard
npm install @jashan-randhawa/react-calendar-heatmap-streaks
npm install @jashan-randhawa/react-workout-tracker
npm install @jashan-randhawa/react-motion-presets
npm install @jashan-randhawa/fitness-utils
npm install @jashan-randhawa/ai-nutrition-estimator

📖 Deep Dive & Package References

1. @jashan-randhawa/openrouter-resilient-client

A dependency-free, high-reliability client for OpenRouter LLM APIs designed for production conversational and extraction workloads.

  • Automated Model Failover: Switches seamlessly from primary model (e.g. openai/gpt-4o-mini) to secondary fallback (e.g. google/gemini-2.0-flash-001) if the primary model fails or experiences an outage.
  • Exponential Backoff with Jitter: Automatically retries 429 (rate limited), 5xx (server error), and network timeouts with randomized full jitter.
  • Structured JSON Extractor: Includes extractCleanJson utility to strip Markdown fences (```json) and sanitize LLM output for schema validation.
  • Zero Runtime Dependencies: Uses Node 20+ native global fetch.
import { createOpenRouterClient } from '@jashan-randhawa/openrouter-resilient-client';

const client = createOpenRouterClient({
  apiKey: process.env.OPENROUTER_API_KEY!,
  model: 'openai/gpt-4o-mini',
  fallbackModel: 'google/gemini-2.0-flash-001',
  maxRetries: 2,
  timeoutMs: 20000,
});

const response = await client.chat({
  messages: [
    { role: 'system', content: 'You are a nutrition coach.' },
    { role: 'user', content: 'Suggest a post-workout snack.' }
  ]
});

console.log(response.text);

2. @jashan-randhawa/express-ai-guard

A security and rate-limiting middleware suite tailored for Express backends exposing generative AI endpoints.

  • Dual-Tier Rate Limiting:
    • createAiLimiter: Global IP-based rate limiting (default 30 req/min).
    • createAiUserLimiter: Per-authenticated-user rate limiting (default 20 req/min keyed on req.user.id) to prevent NAT starvation in shared WiFi/office networks.
  • Request Correlation Tracing: createRequestIdMiddleware assigns a persistent UUID X-Request-Id header to every incoming and outgoing response.
  • Secret Scrubbing: scrubSecrets utility automatically redacts JWT tokens, passwords, and API keys from error payloads and logs.
  • Production Error Masking: createErrorHandlerMiddleware strictly masks Mongoose and database internals in production (NODE_ENV === 'production') with generic client messages.
const express = require('express');
const {
  createAiLimiter,
  createAiUserLimiter,
  createRequestIdMiddleware,
  createErrorHandlerMiddleware
} = require('@jashan-randhawa/express-ai-guard');

const app = express();

app.use(createRequestIdMiddleware());
app.use('/api/ai', createAiLimiter({ max: 30, windowMs: 60000 }));
app.use('/api/ai', createAiUserLimiter({ max: 20, windowMs: 60000 }));

// Production-safe error handler
app.use(createErrorHandlerMiddleware({ logger: console }));

3. @jashan-randhawa/react-calendar-heatmap-streaks

A generic, contribution-style activity and nutrition calendar heatmap component for React.

  • Generic Accessors: Accepts any object array T[] with getDate: (item: T) => string | Date and getValue: (item: T) => number.
  • 4-Level Theme Presets: Built-in color scales for emerald, orange, blue, purple, and slate, plus custom CSS theme overrides.
  • Timezone-Safe Calculation: Evaluates dates using local calendar days (YYYY-MM-DD) so late-night logs (e.g. 11:30 PM) land on the correct date.
  • Streak Walker (computeStreaks): Pure utility that computes currentStreak, bestStreak, and totalActiveDays with yesterday-grace-period support.
import { Heatmap, computeStreaks } from '@jashan-randhawa/react-calendar-heatmap-streaks';

interface WorkoutLog {
  id: string;
  createdAt: string;
  caloriesBurned: number;
}

export function ActivityHeatmap({ logs }: { logs: WorkoutLog[] }) {
  const streaks = computeStreaks(logs.map(l => l.createdAt));

  return (
    <div>
      <p>Current Streak: {streaks.currentStreak} days</p>
      <Heatmap<WorkoutLog>
        data={logs}
        getDate={log => log.createdAt}
        getValue={log => log.caloriesBurned}
        thresholds={[100, 300, 500, 800]}
        theme="emerald"
        days={90}
        onSelectDate={dateStr => console.log('Selected:', dateStr)}
      />
    </div>
  );
}

4. @jashan-randhawa/react-workout-tracker

Live strength training tracker featuring headless session management and modular UI components.

  • Headless useWorkoutSession Hook: Manages active exercises, completed sets, weight, reps, RPE, volume math, and rest intervals without enforcing UI layout.
  • UI Components:
    • WorkoutTracker: Complete multi-exercise session tracker.
    • WorkoutSetRow: Individual set logging row with completion checkmark.
    • RestCountdownTimer: Circular animated countdown timer with chime notification.
    • LiveWorkoutTrackerModal: Full-screen workout modal with optional canvas-confetti celebrations upon completion.
import { useWorkoutSession, RestCountdownTimer } from '@jashan-randhawa/react-workout-tracker';

export function GymLogger() {
  const {
    exercises,
    activeExerciseIndex,
    isResting,
    restRemaining,
    logSet,
    totalVolumeKg
  } = useWorkoutSession({
    initialExercises: [
      { id: '1', name: 'Barbell Bench Press', targetSets: 4, targetReps: 8 }
    ],
    restSeconds: 90
  });

  return (
    <div>
      <h3>Total Volume: {totalVolumeKg} kg</h3>
      {isResting && <RestCountdownTimer secondsRemaining={restRemaining} />}
      <button onClick={() => logSet(0, { weightKg: 80, reps: 8 })}>
        Complete Set
      </button>
    </div>
  );
}

5. @jashan-randhawa/react-motion-presets

Accessible Framer Motion micro-interactions and animation primitives.

  • 6 Stagger Variants: container, fast, item, slideLeft, slideRight, and scaleUp.
  • AnimatedNumber: Smooth count-up integer and decimal display with spring physics.
  • StreamingWordReveal: ChatGPT-style progressive word-by-word streaming effect without re-render stutter on historical chat items.
  • CollapsibleCard: Accessible accordion plan card with smooth height animation.
  • Accessibility: Automatic fallback when user enables prefers-reduced-motion at the OS level.
import {
  AnimatedNumber,
  StreamingWordReveal,
  CollapsibleCard
} from '@jashan-randhawa/react-motion-presets';

export function ChatReply({ text, calories }: { text: string; calories: number }) {
  return (
    <div>
      <h3>
        Estimated Burn: <AnimatedNumber value={calories} /> kcal
      </h3>
      <StreamingWordReveal text={text} wordsPerSecond={15} />
      <CollapsibleCard title="View Exercise Breakdown">
        <p>3 sets of squats, 3 sets of lunges.</p>
      </CollapsibleCard>
    </div>
  );
}

6. @jashan-randhawa/fitness-utils

Isomorphic fitness calculation formulas, browser speech/audio hooks, and PDF report export with a multi-entrypoint architecture:

  • Root (@jashan-randhawa/fitness-utils):
    • calculateBMI(weightKg, heightCm) & getBMICategory(bmi)
    • calculateBMR(gender, weightKg, heightCm, age) (Harris-Benedict formula)
    • calculateTDEE(bmr, activityLevel)
    • calculateMacroDistribution(calories, goal) (Protein, Carbs, Fat)
    • estimateMETCalories(met, weightKg, durationMinutes)
    • exportToCSV(data, filename) (RFC 4180 compliant with Blob & ObjectURL)
  • React Subpath (@jashan-randhawa/fitness-utils/react):
    • useAudioChime(): Web Audio API synthesized completion tone with mute control.
    • useSpeechRecognition(): Web Speech API speech-to-text dictation hook.
    • useSpeechSynthesis(): Web Speech API text-to-speech read-aloud playback hook.
  • PDF Subpath (@jashan-randhawa/fitness-utils/pdf):
    • generateFitnessPDFReport(summaryData): Multi-page branded PDF report generator with stats, charts, and tables.
// Core math
import { calculateBMI, estimateMETCalories, exportToCSV } from '@jashan-randhawa/fitness-utils';

const bmi = calculateBMI(75, 180); // 23.15 (Normal weight)
const burn = estimateMETCalories(8.0, 75, 45); // 450 kcal

// React Hooks
import { useAudioChime, useSpeechRecognition } from '@jashan-randhawa/fitness-utils/react';

// PDF Export
import { generateFitnessPDFReport } from '@jashan-randhawa/fitness-utils/pdf';

7. @jashan-randhawa/ai-nutrition-estimator

Nutrition analysis engine supporting text descriptions, multimodal meal photos, and exercise burn calculations.

  • Multimodal Image Recognition: Accepts base64 image data and prompts vision LLMs to identify dishes and estimate macronutrients.
  • NLP Text Estimation: Parses natural language meal descriptions into structured calorie, protein, carbohydrate, and fat objects.
  • 5-Minute In-Memory TTL Cache: Automatically caches repeated queries to save API tokens and reduce latency.
  • Medical Disclaimers: Automatically appends FDA/medical disclaimers stating that AI calculations are estimates and not clinical medical advice.
import { createEstimator } from '@jashan-randhawa/ai-nutrition-estimator';
import { createOpenRouterClient } from '@jashan-randhawa/openrouter-resilient-client';

const ai = createOpenRouterClient({ apiKey: process.env.OPENROUTER_API_KEY! });
const estimator = createEstimator({ chat: ai.chat });

// Text estimate
const mealData = await estimator.estimateNutritionFromText(
  '2 scrambled eggs, whole wheat toast with butter, and an orange'
);
console.log(mealData);
// Output: { dish: '...', calories: 340, protein: 16, carbs: 28, fat: 18 }

// Exercise estimate
const exerciseData = await estimator.estimateExerciseCalories({
  activity: 'HIIT kettlebell swings',
  durationMinutes: 30,
  weightKg: 80
});
console.log(exerciseData.estimatedCaloriesBurned);

🧪 Quality Gates & Packaging Standards

All packages in the @jashan-randhawa/ ecosystem adhere to strict quality standards:

  • Dual Module Targets: Every package emits both modern ESM (dist/index.js) and CommonJS (dist/index.cjs).
  • Complete Type Definitions: Bundled with .d.ts and .d.cts declaration maps generated directly from strict TypeScript sources.
  • Comprehensive Unit Testing: 56 Vitest unit tests verifying backoff progression, cache expiration, fallback failover, and boundary conditions with zero network mocking leaks.
  • Minimal Tarball Footprint: Configured with files: ["dist", "README.md", "LICENSE"] ensuring no internal tests, source maps, or credentials are published.
  • Automated CI/CD: Packaged and published automatically with provenance via GitHub Actions on GitHub Packages.

Clone this wiki locally