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

@apollo-vault/core

v1.0.2

Published

Apollo Client que funciona 100% offline com entrega eventual, orquestração e cache persistido

Readme

Apollo Vault

npm version npm downloads npm bundle size License: MIT GitHub stars

Apollo Vault Core

Apollo Client 100% offline-first com entrega eventual de mutações, orquestração de operações, cache persistido (IndexedDB), sincronização inteligente e suporte completo a autenticação/refreshes.

Ideal para:

  • Next.js 14/15 (app router & pages router)
  • React Native / Expo
  • PWAs
  • Aplicações com rede instável
  • Sistemas críticos onde nenhum dado pode ser perdido

Instalação

npm install @apollo-vault/core @apollo/client graphql localforage nanoid
# ou
yarn add @apollo-vault/core @apollo/client graphql localforage nanoid
# ou
pnpm add @apollo-vault/core @apollo/client graphql localforage nanoid
**Apollo Vault** is an advanced extension for [Apollo Client](https://www.apollographql.com/docs/react/) designed to enhance GraphQL applications with offline support, eventual consistency for mutations, query orchestration, intelligent caching, authentication handling, and synchronization mechanisms. It is particularly suited for applications requiring resilience in unstable network conditions, such as mobile or web apps with offline capabilities.

Key capabilities include:
- **Eventual Delivery**: Queue mutations for automatic retry when the network recovers.
- **Orchestration Trees**: Compose and execute hierarchical GraphQL operations (queries/mutations) in parallel or sequentially, with support for breakers, subscriptions, and linked nodes.
- **Caching with Policies**: Configurable TTL, health checks, and cache control for queries.
- **Authentication Integration**: Automatic retries on unauthenticated errors, token refresh timers, and event listeners.
- **Offline Synchronization**: Manage and sync offline data/mutations via customizable groups and engines.
- **Incremental Queries**: Stream partial results for large datasets.
- **Custom Apollo Links**: Chainable links for transport, auth, caching, binary parsing, monitoring, orchestration, and eventual delivery.
- **Event Pub/Sub**: Subscribe to events like 'unauthenticated', 'healthy', or orchestration lifecycle events.
- **Secure Utilities**: SHA-256 hashing for deterministic keys and serialization.

Apollo Vault integrates seamlessly with React hooks, Apollo Client, and external services like authentication providers, health checkers, and notifiers.

## Features

- **Offline Mutation Handling**: Store and retry mutations using LocalForage-backed queues.
- **Orchestration Registry**: Register and execute complex operation trees with dynamic resolvers.
- **Synchronization Engine**: Group-based syncing for offline data, with progress tracking and abort controls.
- **Auth Refresh Service**: Timer-based and event-driven token refreshes, integrated with Vault events.
- **Health-Aware Operations**: Skip or queue operations based on network health.
- **React Hooks Integration**: Easy access via `useApolloVault`, `useOrchestration`, `useIncrementalQuery`, etc.
- **Type-Safe Generics**: Supports custom identity (`ID`) and authorization (`AUTH`) types.
- **Debug Utilities**: Print orchestration trees, hash objects for keys, and serialize data.

## Installation

```bash
npm install apollo-vault @apollo/client graphql localforage nanoid crypto

Or with Yarn:

yarn add apollo-vault @apollo/client graphql localforage nanoid crypto

Dependencies:

  • @apollo/client: Core GraphQL client.
  • graphql: GraphQL utilities.
  • localforage: Persistent storage for offline data.
  • nanoid: Unique ID generation.
  • crypto: Hashing (Node.js built-in; polyfill for browsers).
  • Optional: react, moment, uuid for advanced usage.

Quick Start

1. Create the Vault Instance

import { CreateApolloVault } from 'apollo-vault';

const vault = CreateApolloVault<Partial<AuthIdentity>, Partial<Authorization>>(1, { // SCHEMA_VERSION
  transport: { uri: '/graphql', credentials: 'include' },
  handlers: {
    isHealthy: async () => navigator.onLine, // Custom health check
    notifier: (message, level) => console.log(`[${level}] ${message}`),
    requestAuthentication: () => { /* Trigger auth flow */ },
  },
  healthPolicyTTL: 30000, // 30s TTL for health
  UseIdentity: 'token_uid', // Identity key for auth
  WaitAuthentication: { timeout: 5000, attempts: 3 }, // Auth retry config
});

2. Provide the Vault in React

Use ApolloVaultProvider to make the vault available:

import { ApolloVaultProvider } from 'apollo-vault';
import { ApolloVaultController } from './path/to/provider'; // Custom wrapper if needed

function App() {
  return (
    <ApolloVaultController>
      {/* Your app components */}
    </ApolloVaultController>
  );
}

In a custom provider (e.g., provider.tsx):

export function ApolloVaultController({ children }) {
  // Use hooks for env, snackbar, health
  // Update vault with transport, handlers, etc.
  return (
    <ApolloVaultProvider vault={vault}>
      {children}
    </ApolloVaultProvider>
  );
}

Configuration

CreateApolloVaultOptions<ID, AUTH>:

  • transport: HttpLink options (e.g., uri, credentials).
  • handlers: Custom functions for health checks (isHealthy), notifications (notifier), and auth requests.
  • healthPolicyTTL: Cache duration for health status (ms).
  • UseIdentity: Key for identity in auth headers.
  • WaitAuthentication: Config for auth retry (timeout, attempts).
  • auth: Initial authorization context.

Update vault dynamically with vault.update({ ... }).

Usage Examples

Authentication Integration

Integrate with auth providers for token refresh and event handling.

In AuthenticationProvider.tsx:

import { AuthenticationProvider } from './path/to/AuthenticationProvider';

function App() {
  return (
    <AuthenticationProvider>
      {/* App content */}
    </AuthenticationProvider>
  );
}

Hooks like useAuthRefresh listen to Vault's 'unauthenticated' event:

useEffect(() => {
  const unsub = vault.subscribe('unauthenticated', () => {
    setNeedRefresh({ message: 'unauthenticated', code: nanoid(4) });
  });
  return unsub;
}, [vault]);

AuthRefreshService handles API calls for refresh:

AuthRefreshService.refresh('unauthenticated', health).then(refreshed => {
  if (refreshed.refreshed) {
    storeAuthorization(/* updated auth */);
  }
});

Orchestration Setup and Execution

Define and register orchestration trees for complex operations, e.g., creating inspections with attachments.

In orchestration.ts:

import { orchestrate, registry } from 'apollo-vault';
import { MUTATION_SETS_INSPECTION_WITH_ATTACHES } from './SetsInspections';

const { root, fn, node } = orchestrate<{ /* Inputs */ }>();

export const INSPECTION_ORCHESTRATION_REGISTRY = registry(/* URL details */, 'INSPECTION_ORCHESTRATION');
export const INSPECTION_ORCHESTRATION = root({
  registry: INSPECTION_ORCHESTRATION_REGISTRY,
  operation: MUTATION_SETS_INSPECTION_WITH_ATTACHES,
  variables: (initials) => initials?.SetsInspections,
  context: (initial) => ({
    EventualDelivery: { eventual: 'always', message: 'Bind attach...', retry: 10 },
  }),
  linked: {
    AttachFiles: fn((initials) => {
      return initials?.FilesUploads?.map(file => node({
        operation: BIND_ATTACHES_INTO_INSPECTIONS,
        variables: { /* file details */ },
      })) ?? [];
    }),
  },
  subscription: (listener) => {
    listener.subscribe('started', (node) => printOrchestrationTree(node));
    listener.subscribe('finalized', (response) => printOrchestrationTree(response));
  },
});

Register in a hook:

import { useRegistryOrchestrationService } from './useRegistryOrchestration';

useRegistryOrchestrationService(); // Registers INSPECTION_ORCHESTRATION

Execute with useOrchestration:

const { execute, data, error, executing } = useOrchestration(INSPECTION_ORCHESTRATION_REGISTRY, INSPECTION_ORCHESTRATION);
execute({ variables: { /* inputs */ } });

Form and Mutation Handling

Use in forms with offline support, e.g., useSetsInspection.ts:

const { submit } = useSetsInspection(/* options */);

submit(async (values) => {
  const response = await execute({
    SetsInspections: { data: {/* form data */} },
    FilesUploads: files,
  });
  // Handle response
});

Offline Synchronization

Use SynchronizeProvider for managing offline sync groups, like mutations.

In SynchronizeProvider.tsx:

import { SynchronizeProvider } from './SynchronizeProvider';

function App() {
  return (
    <SynchronizeProvider>
      {/* App content */}
    </SynchronizeProvider>
  );
}

Define groups, e.g., MutationSyncGroup.ts:

export function createMutationSyncGroup(sync) {
  return {
    id: 'MUTATION_SYNC',
    handler: async (entry) => {
      const response = await sync.apolloVaultInstance.deliveryEntries([key]);
      // Handle errors
    },
  };
}

Trigger sync with useSynchronize:

const { synchronize } = useSynchronize();
synchronize(); // Runs engine with groups

The SynchronizerEngine processes groups, tracking progress and handling aborts.

API Reference

Core

  • CreateApolloVault<ID, AUTH>(schemaVersion, options): Creates vault instance.
  • vault.update(fields): Update configurable fields (e.g., transport, handlers).
  • vault.executeOrchestration(resolver, args): Run orchestration tree.
  • vault.registry(registry, resolver): Register orchestration.
  • vault.deliveryEntries(keys): Process queued mutations.
  • vault.subscribe(event, handler): Listen to events (e.g., 'unauthenticated').
  • vault.publishResponse({ operation, response }): Broadcast results.

Hooks

  • useApolloVault<ID, AUTH>(): Access vault.
  • useOrchestration(registry, resolver): Execute registered orchestration.
  • useIncrementalQuery(query, options): Stream query results.
  • useSynchronize(): Trigger and monitor sync.

Utils

  • orchestrate<Inputs>(): Build orchestration trees (root, node, fn).
  • registry(baseUrl, metaUrl, name): Generate registry key.
  • printOrchestrationTree(node): Debug tree structure.
  • generateSha256Hash(content): Hash for keys.
  • serializeObject(obj): Safe serialization.

Contributing

Fork, branch, commit, push, PR. See CONTRIBUTING.md.

License

MIT. See LICENSE.