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

@supercat1337/persist-core

v1.0.0

Published

Generic persistence engine with cross-tab sync, versioning, TTL and validation. Framework-agnostic.

Readme

@supercat1337/persist-core

Framework-agnostic persistence engine with cross-tab sync, versioning, TTL and validation.

npm version License: MIT Bundle Size


Why persist-core?

persist-core is the persistence layer behind @supercat1337/store2-persist. It knows nothing about store2, MobX, Vue, Svelte, or any specific reactivity model — it only knows a three-method ReactiveSource contract. That makes it usable with any state container, or with none at all (plain objects in tests, in-memory adapters in SSR, etc.).

What it provides:

  • Storage backends — localStorage, sessionStorage, IndexedDB, in-memory, or custom.
  • Cross-tab sync — BroadcastChannel with automatic fallback to storage events. Optional Web Locks serialise writes across tabs.
  • Debounced auto-save — coalesce rapid mutations into one write.
  • Versioning & migrations — stored version field plus a migrate(storedData, storedVersion) hook.
  • Validation — duck-typed support for Zod, Yup, Valibot, ArkType (Standard Schema) and plain functions.
  • Selective persistence — pick / omit with dot-path notation for nested data.
  • Transforms & middleware — round-trip hooks (in / out) and beforeSave / afterLoad middlewares for compression, encryption, timestamps, etc.
  • TTL — expired records are removed on load.
  • Zero dependencies — nothing to audit beyond the package itself.

Installation

npm install @supercat1337/persist-core

Quick start

import { createPersistence, LocalStorageAdapter } from '@supercat1337/persist-core';

// 1. Define a reactive source. Any object with these three methods works.
let state = { count: 0 };
const subscribers = new Set();

const source = {
    subscribe(fn) {
        subscribers.add(fn);
        return () => subscribers.delete(fn);
    },
    getSnapshot: () => state,
    applySnapshot(data) {
        state = data;
        subscribers.forEach(fn => fn());
    },
};

// 2. Persist it.
const persistence = createPersistence(source, {
    key: 'my-app:counter',
    adapter: new LocalStorageAdapter(),
    debounce: 300,
    syncTabs: true,
});

await persistence.ready(); // initial hydration is complete

// 3. Mutate normally — persistence happens automatically.
state = { count: 1 };
subscribers.forEach(fn => fn());

// Cleanup on teardown.
persistence.destroy();

If you are using store2, you do not need to write ReactiveSource by hand — see @supercat1337/store2-persist, which wraps createPersistence for atoms, computeds, collections, stores, and deepReactive proxies.


Storage adapters

Built-in

import {
    LocalStorageAdapter,
    SessionStorageAdapter,
    IndexedDBAdapter,
    MemoryAdapter,
} from '@supercat1337/persist-core';

const ls = new LocalStorageAdapter();
const ss = new SessionStorageAdapter();
const mem = new MemoryAdapter(); // SSR, tests
const idb = new IndexedDBAdapter('my-db', 'state', 1);

IndexedDBAdapter.isAvailable() detects Safari Private Browsing and cross-origin restrictions where the indexedDB global exists but is unusable:

const adapter = IndexedDBAdapter.isAvailable()
    ? new IndexedDBAdapter('my-db')
    : new LocalStorageAdapter();

Custom

Implement the StorageAdapter interface — three required methods plus optional close():

class TauriAdapter {
    async load(key) {
        /* return parsed data or null */
    }
    async save(key, v) {
        /* write v under key */
    }
    async remove(key) {
        /* delete key */
    }
    async clear() {
        /* wipe the store */
    }
    close() {
        /* optional: release handles */
    }
}

All methods may be asynchronous. close() is called by persistence.destroy().

No prefixing. Adapters use keys verbatim. Namespace them yourself ('my-app:counter', 'my-app:todos') so multiple apps on the same origin don't collide.


Cross-tab synchronisation

createPersistence(source, {
    key: 'shared:todos',
    adapter: new LocalStorageAdapter(),
    syncTabs: true,
});
  • Uses BroadcastChannel where available.
  • Falls back to storage events for localStorage / sessionStorage when BroadcastChannel is not available. Note: sessionStorage does not generate storage events between tabs — BroadcastChannel is the only cross-tab path for it.
  • IndexedDB without BroadcastChannel cannot sync cross-tab; a warning is logged.
  • Optional: locks: true serialises concurrent writes through navigator.locks (Web Locks API), preventing lost updates when two tabs save at the same moment.

Versioning and migrations

createPersistence(source, {
    key: 'my-app:settings',
    adapter: new LocalStorageAdapter(),
    version: 2,
    migrate: (storedData, storedVersion) => {
        if (storedVersion < 2) {
            return { ...storedData, theme: storedData.theme ?? 'dark' };
        }
        return storedData;
    },
});

migrate receives the raw stored payload and the version it was written with. Return the upgraded payload. If migrate throws, hydration is aborted, the current in-memory state is preserved, and the error goes to onError.


Validation

Validation runs after migration and transform-out, before the snapshot is applied to the source.

import { z } from 'zod';

const schema = z.object({
    name: z.string().min(2),
    age: z.number().positive(),
});

createPersistence(source, {
    key: 'user',
    adapter: new LocalStorageAdapter(),
    schema,
    onError: err => console.warn('Invalid data in storage', err),
});

Supported shapes (duck-typed, no hard dependency on any schema library):

| Shape | Example | | :-------------- | :------------------------------------------------- | | Standard Schema | Zod 3.24+, Valibot, ArkType (~standard.validate) | | .parse() | Zod, Yup | | Function | (data) => validatedData |


Selective persistence

createPersistence(source, {
    key: 'settings',
    adapter: new LocalStorageAdapter(),
    pick: ['user.name', 'user.address.city', 'theme'],
    // or
    // omit: ['user.password', 'cache'],
});

Paths use dot notation. pick keeps only the listed paths; omit removes them. Both support arbitrary depth. If both are set, pick wins.


Transforms and middleware

transform.in / transform.out

Round-trip hooks. in runs on the payload before writing; out runs on it after reading. Use them for compression, encryption, or adding a checksum.

import { compress, decompress } from 'lz-string';

createPersistence(source, {
    key: 'compressed',
    adapter: new LocalStorageAdapter(),
    transform: {
        in: data => compress(JSON.stringify(data)),
        out: raw => JSON.parse(decompress(raw)),
    },
});

middlewares

Same idea, but composable across multiple hooks.

createPersistence(source, {
    key: 'k',
    adapter: new LocalStorageAdapter(),
    middlewares: [
        {
            beforeSave: data => ({ ...data, _savedAt: Date.now() }),
            afterLoad: data => {
                delete data._savedAt;
                return data;
            },
        },
    ],
});

Execution order on save:

getSnapshot → transform.in → middlewares[].beforeSave → pick/omit → packEnvelope → adapter.save

On load:

adapter.load → unpackEnvelope → migrate → validate → transform.out → middlewares[].afterLoad → applySnapshot

TTL

createPersistence(source, {
    key: 'session',
    adapter: new SessionStorageAdapter(),
    ttl: 60 * 60 * 1000, // 1 hour
});

Expired records are removed from the adapter on load. The savedAt and expires fields live in the envelope, not in the payload — transform / middlewares never see them.


Lifecycle

const p = createPersistence(source, { ... });

await p.ready();     // initial hydration complete
p.pause();          // stop auto-saving (save() still works)
p.resume();         // re-enable auto-saving
await p.save();     // force save, cancelling pending debounce
await p.load();     // force read from storage and apply
await p.clear();    // delete the record for this key
p.destroy();        // unsubscribe, close channel, release adapter

destroy() is idempotent. After destroy(), save() and load() are silent no-ops.


Envelope format

Every record is wrapped in a JSON-safe envelope:

{
    __s2p: 1,              // format marker (distinguishes from app data)
    version: 0,            // user-facing data version (for migrations)
    savedAt: 1718000000000,
    expires: 1718003600000, // only when ttl is set
    data: { ... },         // the payload
}

The __s2p marker prevents collisions with user keys and makes the format forward-compatible. Records without __s2p: 1 are ignored with a console.warn — the source's current state is preserved.

If you are migrating from @supercat1337/[email protected], which used { __v, value } / { __v, ...data } envelopes, wrap your adapter with LegacyEnvelopeAdapter (see @supercat1337/store2-persist).


Error handling

All errors — storage I/O, migration, validation, applySnapshot — go through a single path:

createPersistence(source, {
    key: 'k',
    adapter: new LocalStorageAdapter(),
    onError: err => {
        Sentry.captureException(err);
    },
});

If onError is not set, the default is console.error('[persist-core]', err). Errors are never re-thrown to the caller — save() / load() resolve normally. This is deliberate: a transient I/O error should not crash the app or leave the reactive graph in an inconsistent state.


SSR

persist-core is safe in Node, Deno, Bun, and edge runtimes. On the server:

import { createPersistence, MemoryAdapter } from '@supercat1337/persist-core';

// Use MemoryAdapter in tests / SSR. `createPersistence` never touches
// `window`, `localStorage`, or `indexedDB` unless the adapter does.
const persistence = createPersistence(source, {
    key: 'k',
    adapter: new MemoryAdapter(serializedFromClient),
});

CrossTabSync and IndexedDBAdapter guard against missing globals. MemoryAdapter is the recommended backend for server-side execution.

For the store2-specific SSR flow (hydrating on the client with server-rendered state), see the store2-persist README.


API

Full surface is defined in dist/types.d.ts and etc/persist-core.api.md. Summary:

createPersistence(source, options)

| Option | Type | Description | | :------------ | :----------------------------------- | :------------------------------------------------ | | key | string | Required. Storage key. | | adapter | StorageAdapter | Required. Storage backend. | | version | number | User-facing data version. Default: 0. | | migrate | (storedData, storedVersion) => any | Runs when versions differ. | | debounce | number | Auto-save delay in ms. Default: 0. | | syncTabs | boolean | Enable cross-tab sync. Default: false. | | locks | boolean | Serialise writes via Web Locks. Default: false. | | schema | ValidatorLike | Validation on load. | | pick | string[] | Paths to keep. | | omit | string[] | Paths to drop. | | transform | { in, out } | Round-trip transforms. | | middlewares | Array<{ beforeSave, afterLoad }> | Composable hooks. | | ttl | number | Time-to-live in ms. | | onError | (error: Error) => void | Error handler. |

PersistInstance

ready(), pause(), resume(), save(), load(), clear(), destroy().

ReactiveSource

subscribe(fn) => unsub, getSnapshot(), applySnapshot(data).

Adapters

LocalStorageAdapter, SessionStorageAdapter, IndexedDBAdapter, MemoryAdapter — all implement StorageAdapter.


Examples

Four self-contained browser demos in examples/. They use an import map so the code matches production usage (import from '@supercat1337/persist-core') while resolving to ../../src/index.js — no build step needed.

| # | Folder | Shows | | --- | --------------------------------------------------- | ----------------------------------------------------------------------------- | | 01 | 01-simple-counter | LocalStorageAdapter, debounce, pause/resume, save/load/clear. | | 02 | 02-all-adapters | All four built-in adapters with a live switcher. | | 03 | 03-cross-tab | syncTabs: true + locks: true. Two tabs stay in sync. | | 04 | 04-advanced | pick/omit, schema, transform, middleware, version+migrate, ttl. |

Run: npx serve from the repo root, then open http://localhost:3000/examples/01-simple-counter/.

Live examples for the store2 integration live in store2-examples.


Related


For AI assistants

If you are generating code that integrates with persist-core, read AGENTS.md first. It documents the pipeline order, the envelope format, the concurrency guards, and the invariants that must not be broken.

The public type surface is in dist/types.d.ts. A machine-readable snapshot is kept in etc/persist-core.api.md.


License

MIT © 2025–2026 Albert Bazaleev