@soham20/smart-offline-sdk
v1.0.1
Published
Smart offline-first JavaScript SDK with intelligent caching for web applications
Maintainers
Readme
SmartOffline SDK
A complete, reliable offline-first caching SDK for web applications. Provides intelligent priority-based caching with configurable algorithms.
Features
- 🚀 Easy Setup - Single function call to initialize
- 🎯 Priority-Based Caching - Intelligent frequency and recency scoring
- 🌐 Network Aware - Adapts caching strategy based on connection quality
- 📊 Usage Tracking - Tracks access patterns to optimize caching
- 🔧 Highly Configurable - Customize every aspect of the caching algorithm
- 📝 TypeScript Support - Full type definitions included
- 🧪 Test Utilities - Built-in testing and inspection tools
Installation
npm install @soham20/smart-offline-sdkOr directly from GitHub:
npm install git+https://github.com/OwaisShaikh1/Hackvision2026.gitQuick Start
import { setupSmartOffline } from "@soham20/smart-offline-sdk";
// Initialize early in your app
await setupSmartOffline({
pages: ["/dashboard/*", "/products/*"],
apis: ["/api/v1/*"],
debug: true,
});Configuration Options
| Option | Type | Default | Description |
| -------------------- | --------------------------------- | ------------------------ | ------------------------------------------------------- |
| pages | string[] | [] | URL patterns for pages to cache (supports * wildcard) |
| apis | string[] | [] | URL patterns for API endpoints to cache |
| debug | boolean | false | Enable debug logging in console |
| frequencyThreshold | number | 3 | Number of accesses before URL is high priority |
| recencyThreshold | number | 86400000 | Time in ms for "recent" access (default: 24h) |
| maxResourceSize | number | 10485760 | Max bytes to cache per resource (default: 10MB) |
| networkQuality | 'auto' \| 'slow' \| 'fast' | 'auto' | Network quality detection mode |
| significance | Record<string, 'high' \| 'low'> | {} | Priority overrides for URL patterns |
| weights | { frequency, recency, size } | { 1, 1, 1 } | Weights for priority calculation |
| customPriorityFn | Function | null | Custom priority function (0-100) |
| enableDetailedLogs | boolean | false | Enable detailed event logging |
| onCacheEvent | Function | undefined | Callback for cache events |
| serviceWorkerPath | string | '/smart-offline-sw.js' | Path to service worker file |
| serviceWorkerScope | string | '/' | Service worker scope |
Complete Example
import { setupSmartOffline, SmartOffline } from "@soham20/smart-offline-sdk";
// Full configuration example
const result = await setupSmartOffline({
// URL patterns to cache
pages: ["/admin/*", "/dashboard", "/products/*"],
apis: ["/api/v1/*", "/graphql"],
// Enable debug logging
debug: true,
// Priority tuning
frequencyThreshold: 5, // 5 accesses = high priority
recencyThreshold: 12 * 60 * 60 * 1000, // 12 hours
maxResourceSize: 5 * 1024 * 1024, // 5MB max
// Network detection
networkQuality: "auto",
// Manual priority overrides
significance: {
"/api/critical/*": "high", // Always cache
"/api/logs/*": "low", // Never cache
},
// Weight configuration
weights: {
frequency: 2, // Frequency is 2x more important
recency: 1,
size: 1,
},
// Custom priority function
customPriorityFn: (usage, url, config) => {
if (url.includes("vip")) return 100;
if (!usage) return 0;
return usage.count >= 5 ? 100 : 25;
},
// Event callback
onCacheEvent: (event) => {
console.log(`Cache event: ${event.type}`, event.url);
},
});
if (result.success) {
console.log("SmartOffline ready!");
}API Reference
Main Functions
import {
setupSmartOffline, // Initialize SDK (async)
updateConfig, // Update config at runtime
getConfig, // Get current configuration
isSmartOfflineReady, // Check if initialized
clearAllCache, // Clear all cached data
getCacheStats, // Get cache statistics
forceUpdate, // Force SW update
uninstall, // Uninstall SDK
} from "@soham20/smart-offline-sdk";Event Handling
import { on, off } from "@soham20/smart-offline-sdk";
// Listen for cache events
on("cache", (event) => console.log("Cached:", event.url));
on("skip", (event) => console.log("Skipped:", event.url));
on("serve", (event) => console.log("Served from cache:", event.url));
on("error", (event) => console.log("Error:", event.url));
// Remove listener
off("cache", myCallback);SmartOffline Object
import { SmartOffline } from "@soham20/smart-offline-sdk";
// All methods available on SmartOffline object
SmartOffline.setup(config); // setupSmartOffline
SmartOffline.updateConfig(cfg); // Update configuration
SmartOffline.getConfig(); // Get current config
SmartOffline.isReady(); // Check if ready
SmartOffline.clearCache(); // Clear all cache
SmartOffline.getStats(); // Get cache stats
SmartOffline.forceUpdate(); // Force SW update
SmartOffline.uninstall(); // Clean uninstallTest Utilities
import {
SmartOfflineTestSuite,
runSmartOfflineTests,
CacheInspector,
} from "@soham20/smart-offline-sdk";
// Run all tests
const results = await runSmartOfflineTests();
// Or use the test suite directly
const suite = new SmartOfflineTestSuite({ pages: ["/test/*"] });
await suite.runAll();
suite.printResults();
// Inspect cache
const inspector = new CacheInspector();
await inspector.showAll();
const data = await inspector.getAllData();Browser Console Testing
// After SDK is loaded, these are available globally:
await runSmartOfflineTests();
await SmartOffline.getStats();
new CacheInspector().showAll();How the Algorithm Works
- URL Pattern Matching: Caches pages/APIs matching configured patterns
- Frequency Scoring: URLs accessed >=
frequencyThresholdtimes get higher score - Recency Scoring: URLs accessed within
recencyThresholdget higher score - Weighted Calculation:
frequencyScore = min(100, (accessCount / threshold) * 100)recencyScore = max(0, 100 - (timeSinceAccess / threshold) * 100)weightedScore = (freqScore * freqWeight + recencyScore * recencyWeight) / totalWeight- HIGH priority if
weightedScore > 50
- Network Awareness: On slow networks, only HIGH priority resources are cached
- Size Limits: Resources exceeding
maxResourceSizeare skipped
Service Worker Setup
Copy smart-offline-sw.js to your public directory:
cp node_modules/@soham20/smart-offline-sdk/smart-offline-sw.js public/TypeScript
Full TypeScript support with exported types:
import type {
SmartOfflineConfig,
CacheEvent,
UsageData,
SetupResult,
CacheStats,
} from "@soham20/smart-offline-sdk";License
MIT
