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 🙏

© 2025 – Pkg Stats / Ryan Hefner

offline-data-sync

v1.0.6

Published

Offline-first data synchronization library with conflict resolution

Readme

Offline-First Data Sync Library

A robust, TypeScript-based library for managing offline-first data synchronization in web applications. This library provides seamless data persistence and synchronization capabilities, ensuring your application works flawlessly regardless of network connectivity.

Version License TypeScript

🚀 Features

  • Offline-First Architecture

    • Seamless offline data persistence
    • Automatic synchronization when online
    • Background sync with configurable batching
    • Real-time connectivity monitoring
    • Immediate UI updates with offline changes
  • Advanced Conflict Resolution

    • Multiple resolution strategies (client-wins, server-wins, last-write-wins)
    • Custom merge support
    • Manual conflict resolution with UI support
    • Version tracking and management
    • ETag-based conflict detection
  • Robust Error Handling

    • Exponential backoff with jitter
    • Configurable retry mechanisms
    • Failure recovery strategies
    • Detailed error reporting
    • Graceful offline deletion handling
  • Flexible Configuration

    • Customizable sync endpoints
    • Adjustable batch sizes
    • Configurable retry policies
    • Custom merge strategies
    • Custom API adapters

📋 Prerequisites

Node.js >= 14.0.0
npm >= 6.0.0

🔧 Installation

npm install offline-data-sync

🚦 Quick Start

import { SyncManager } from "offline-data-sync";

// Create a custom API adapter
class TodoApiAdapter implements ApiAdapter {
  constructor(private baseUrl: string) {
    this.apiUrl = baseUrl.replace(/\/$/, "");
  }

  async create(record: SyncRecord): Promise<Response> {
    return fetch(`${this.apiUrl}/${record.id}`, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        "If-Match": record.version?.toString() || "*",
      },
      body: JSON.stringify(record.data),
    });
  }

  // Implement other methods...
}

// Initialize SyncManager
const syncManager = new SyncManager({
  storeName: "todos",
  apiAdapter: new TodoApiAdapter("http://localhost:3001/api/todos"),
  conflictResolution: "server-wins",
  batchSize: 50,
});

// Create a todo
await syncManager.create({
  title: "New Todo",
  completed: false,
});

// Update a todo
await syncManager.update("todo-id", {
  title: "Updated Todo",
  completed: true,
});

// Delete a todo
await syncManager.delete("todo-id");

// Get processed records (with UI-ready format)
const records = await syncManager.getProcessedRecords();

// Monitor sync status
syncManager.onSyncStatusChange((status) => {
  console.log("Sync status:", status);
});

⚙️ Configuration

interface SyncConfig {
  storeName: string;
  primaryKey?: string;
  syncEndpoint?: string;
  apiAdapter?: ApiAdapter;
  conflictResolution?:
    | "client-wins"
    | "server-wins"
    | "manual"
    | "last-write-wins"
    | "merge";
  batchSize?: number;
  maxRetries?: number;
  retryDelay?: number;
  mergeStrategy?: (clientData: any, serverData: any) => any;
}

interface ApiAdapter {
  create(record: SyncRecord): Promise<Response>;
  update(record: SyncRecord): Promise<Response>;
  delete(record: SyncRecord): Promise<Response>;
  handleResponse(response: Response): Promise<Record<string, unknown> | null>;
}

🔄 Conflict Resolution

Server Wins (Default)

const syncManager = new SyncManager({
  conflictResolution: "server-wins",
});

Client Wins

const syncManager = new SyncManager({
  conflictResolution: "client-wins",
});

Manual Resolution

const syncManager = new SyncManager({
  conflictResolution: "manual",
});

// Later, when conflict occurs:
await syncManager.resolveConflict(
  "record-id",
  "accept-server", // or "accept-client" or "custom"
  customData // optional, for custom resolution
);

🔌 Offline Behavior

  • Records are immediately updated in IndexedDB
  • UI reflects changes instantly
  • Changes are queued for sync when online
  • Deletions are handled gracefully
  • Conflicts are detected and resolved on sync

🛠 Development

# Install dependencies
npm install

# Build library
npm run build

# Run example app
cd example/ods-sample-app
npm install
npm run dev

# Run test server
cd example/test-server
npm install
npm run dev

📚 API Reference

SyncManager Methods

class SyncManager {
  async create(data: any): Promise<void>;
  async update(id: string, data: any): Promise<void>;
  async delete(id: string): Promise<void>;
  async get(id: string): Promise<SyncRecord>;
  async getAll(): Promise<SyncRecord[]>;
  async getProcessedRecords(): Promise<any[]>;
  async resolveConflict(
    id: string,
    resolution: string,
    customData?: any
  ): Promise<void>;
  onSyncStatusChange(callback: (status: SyncStatus) => void): () => void;
}

🔒 Security

  • Secure local data storage using IndexedDB
  • Version control with ETags
  • Data integrity validation
  • Protected sync operations
  • Conflict detection and resolution

📈 Performance

  • Efficient batch processing
  • Optimized IndexedDB operations
  • Minimal memory footprint
  • Smart conflict resolution
  • Background sync operations