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

sync-engine-lib

v2.0.1

Published

Biblioteca TypeScript para sincronização bidirecional offline-first em React Native/Expo

Readme

📦 Sync Engine Lib

npm version License: MIT TypeScript React Native Expo SDK

Biblioteca TypeScript para sincronização bidirecional offline-first em React Native/Expo com SQLite.

🚀 Características

  • Sincronização bidirecional automática entre app e servidor
  • 📱 100% offline-first - todas operações funcionam sem internet
  • 🔄 Fila persistente com SQLite para garantir entrega
  • Resolução de conflitos configurável
  • 🔁 Retry automático com backoff exponencial
  • 📊 Monitoramento de conexão em tempo real
  • 🎯 TypeScript com tipos completos
  • 🧪 Testado em produção

📦 Instalação

npm install sync-engine-lib
# ou
yarn add sync-engine-lib

Dependências necessárias

npm install expo-sqlite @react-native-community/netinfo
# ou
yarn add expo-sqlite @react-native-community/netinfo

Dependências opcionais (para sincronização em background)

npm install expo-background-task expo-task-manager
# ou
yarn add expo-background-task expo-task-manager

🎯 Uso Rápido

import { SyncEngineFactory, SyncEngineUtils } from 'sync-engine-lib';

// Criar instância do SyncEngine
const syncEngine = SyncEngineFactory.createForProduction(
  'https://api.exemplo.com'
);

// Inicializar e começar sincronização
await syncEngine.initialize();
await syncEngine.start();

// Adicionar item à fila (funciona offline)
await syncEngine.addToQueue(
  SyncEngineUtils.generateId(),
  'todo',
  {
    text: 'Minha tarefa',
    done: false,
    createdAt: Date.now(),
    updatedAt: Date.now()
  }
);

// Monitorar status
syncEngine.on('sync_completed', (event) => {
  console.log('Sincronização concluída!', event.data);
});

📊 APIs Principais

| Classe/Módulo | Descrição | |---------------|------------| | SyncEngine | Motor principal de sincronização | | OfflineFirstDB | Banco de dados SQLite com suporte offline | | OfflineFirstEngine | Engine completo com DB + Sync integrados | | BackgroundSyncWorker | Worker para sincronização em background | | ConflictResolver | Estratégias de resolução de conflitos | | NetMonitor | Monitor de conectividade de rede | | QueueStorage | Armazenamento persistente da fila | | RetryPolicy | Políticas de retry configuráveis |

Factories e Utilitários

// Factories pré-configurados
SyncEngineFactory.createForDevelopment(url)  // Config para dev
SyncEngineFactory.createForProduction(url)   // Config para prod
SyncEngineFactory.createConservative(url)    // Baixo consumo
SyncEngineFactory.createAggressive(url)      // Alta performance

// Utilitários
SyncEngineUtils.generateId()                 // Gerar ID único
SyncEngineUtils.validateConfig(config)       // Validar configuração
SyncEngineUtils.createOptimizedConfig(url, preset)

Estratégias de Conflito

import { ConflictStrategies } from 'sync-engine-lib';

// Estratégias disponíveis
ConflictStrategies.clientWins()    // Cliente sempre vence
ConflictStrategies.serverWins()    // Servidor sempre vence
ConflictStrategies.timestampWins() // Mais recente vence
ConflictStrategies.manual()        // Resolução manual
ConflictStrategies.merge()         // Merge automático

🔧 Configuração Avançada

import { SyncEngine, ConflictStrategies } from 'sync-engine-lib';

const syncEngine = new SyncEngine({
  config: {
    serverUrl: 'https://api.exemplo.com',
    batchSize: 25,
    syncInterval: 30000,
    maxRetries: 3,
    initialRetryDelay: 1000,
    backoffMultiplier: 1.8,
    requestTimeout: 15000,
    maxConcurrentRequests: 4,
    enableBatchSync: true,
    cacheExpiration: 30000,
    headers: {
      'Authorization': 'Bearer token'
    }
  },
  conflictStrategy: ConflictStrategies.timestampWins(),
  hooks: {
    onBeforeSync: async (items) => {
      console.log('Preparando para sincronizar', items.length, 'itens');
    },
    onSyncSuccess: async (items) => {
      console.log('Sincronização bem-sucedida!');
    },
    onSyncError: async (error, items) => {
      console.error('Erro na sincronização:', error);
    }
  },
  debug: true
});

🌐 Modo Offline

// Forçar modo offline (útil para testes)
syncEngine.setForcedOnline(false);

// Voltar ao modo automático
syncEngine.setForcedOnline(null);

// Verificar status
const status = await syncEngine.getStatus();
console.log({
  online: status.isOnline,
  pendentes: status.pendingItems,
  erros: status.errorItems
});

📱 Background Sync (React Native)

import { addBackgroundSyncToEngine } from 'sync-engine-lib';

// Adicionar suporte a background sync
const engineWithBg = addBackgroundSyncToEngine(syncEngine, {
  taskName: 'SYNC_TASK',
  interval: 900, // 15 minutos
  options: {
    minimumInterval: 900,
    stopOnTerminate: false,
    startOnBoot: true
  }
});

// Registrar e iniciar
await engineWithBg.registerBackgroundTask();

📋 Requisitos

  • React Native: 0.73+
  • Expo SDK: 50+ (se usando Expo)
  • TypeScript: 5.0+
  • Plataformas: iOS, Android

🔗 Links

📄 Licença

MIT © LuizHGodoy


Nota: Esta biblioteca faz parte do Sync Engine Monorepo. Para exemplos completos e servidor de demonstração, visite o repositório principal.