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

ai-state-store

v0.1.0

Published

AI-powered state management for React — dispatch natural language, AI handles the rest

Downloads

13

Readme

ai-state-store

AI-powered state management for React.
Dispatch natural language. AI handles the rest.

npm install ai-state-store zod

Why ai-store?

| Traditional Redux | ai-store | |---|---| | Write action types, reducers, selectors, thunks | Write one English sentence | | Junior devs need 2–4 weeks to learn | Productive on day one | | Business logic trapped in code | Audit log readable by PMs, QA, compliance | | Cross-feature updates = saga chains | One dispatch touches any fields | | Debugging = reading reducer code | Debugging = reading plain English log |


Quick Start

// 1. Define your schema with Zod
import { z } from 'zod'
import { AIStoreProvider, useAIStore } from 'ai-state-store'

const storeConfig = {
  domains: {
    cart: {
      schema: z.object({
        items: z.number(),
        total: z.number(),
        promoApplied: z.boolean(),
      }),
      initialState: { items: 0, total: 0, promoApplied: false },
      instructions: 'Never allow negative item counts or totals.',
    },
    user: {
      schema: z.object({
        name: z.string(),
        loggedIn: z.boolean(),
        role: z.enum(['guest', 'member', 'admin']),
      }),
      initialState: { name: 'Guest', loggedIn: false, role: 'guest' },
    },
  },
  ai: {
    provider: 'anthropic',
    apiKey: process.env.ANTHROPIC_API_KEY,
    // Uses claude-haiku by default — fastest & cheapest
  },
}

// 2. Wrap your app
export default function App() {
  return (
    <AIStoreProvider config={storeConfig}>
      <ShoppingCart />
    </AIStoreProvider>
  )
}

// 3. Use it — dispatch plain English
function ShoppingCart() {
  const { state, dispatch, loading } = useAIStore()

  return (
    <div>
      <p>Items: {state.cart.items} | Total: ${state.cart.total}</p>
      <button
        onClick={() => dispatch('add 2 items worth $15 each to cart')}
        disabled={loading}
      >
        Add Items
      </button>
      <button onClick={() => dispatch('apply promo SAVE20, reduce total by 20%')}>
        Apply Promo
      </button>
      <button onClick={() => dispatch('log in as Alice with admin role')}>
        Login
      </button>
    </div>
  )
}

Providers

// Anthropic (default — recommended)
ai: { provider: 'anthropic', apiKey: '...', model: 'claude-haiku-4-5-20251001' }

// OpenAI
ai: { provider: 'openai', apiKey: '...', model: 'gpt-4o-mini' }

// Ollama — fully offline, free, no API key
ai: { provider: 'ollama', model: 'llama3.2', baseURL: 'http://localhost:11434' }

// Any OpenAI-compatible endpoint
ai: { provider: 'custom', apiKey: '...', baseURL: 'https://your-endpoint/v1' }

Domain Partitioning (for large apps)

Break state into domains. Each domain has its own schema and optional rules.
Dispatch only touches the domains it needs — keeps AI context small and fast.

const config = {
  domains: {
    cart:     { schema: CartSchema,     initialState: cartInit },
    user:     { schema: UserSchema,     initialState: userInit },
    payments: { schema: PaymentSchema,  initialState: payInit,
                instructions: 'Never store raw card numbers.' },
    ui:       { schema: UISchema,       initialState: uiInit },
  },
  // ...
}

// Scope a dispatch to specific domains — cheaper and faster
await dispatch('mark payment as processing', { domains: ['payments'] })

Scoped Hook — useDomain

function CartWidget() {
  const { state, dispatch, loading } = useDomain('cart')
  // state is TState['cart'] only — no access to other domains
}

Optimistic Updates

const config = {
  // ...
  optimisticUpdate: (state, action) => {
    if (action.includes('add') && action.includes('cart')) {
      return { cart: { ...state.cart, items: state.cart.items + 1 } }
    }
    return null // let AI handle it normally
  },
}
// UI updates instantly. AI reconciles in the background.

Middleware

import {
  composeMiddleware, rateLimiter, actionBatcher, offlineQueue, logger
} from 'ai-state-store'

// Compose middleware around your dispatch
const store = createAIStore(config)
const enhancedDispatch = composeMiddleware(
  rateLimiter(300),       // max 1 AI call per 300ms
  actionBatcher(100),     // batch rapid dispatches into one call
  offlineQueue(),         // queue when offline, flush when back online
  logger(),               // console.log every dispatch
)(store.dispatch)

Redux / Zustand Migration

import { createReduxBridge } from 'ai-state-store/redux-adapter'

// Step 1: Bridge your existing Redux store (zero changes to Redux code)
const bridge = createReduxBridge(existingReduxStore)

const config = {
  domains: {
    // Only the slices you've migrated to ai-store
    cart: { schema: CartSchema, initialState: cartInit },
  },
  legacyStore: bridge,
  ai: { ... },
}

// Step 2: Migrate one slice per sprint. Everything else stays in Redux.
// Step 3: Use createSliceMigrationHelper to generate dispatch mappings.
import { createSliceMigrationHelper } from 'ai-state-store/redux-adapter'
const helper = createSliceMigrationHelper('cartSlice', reduxStore)
console.log(helper.generateMigrationMap(['CART_ADD_ITEM', 'CART_REMOVE_ITEM', 'CART_CLEAR']))
// { CART_ADD_ITEM: 'add item', CART_REMOVE_ITEM: 'remove item', CART_CLEAR: 'clear' }

DevTools

import { installDevTools } from 'ai-state-store'

const store = createAIStore(config)
if (process.env.NODE_ENV === 'development') {
  installDevTools(store, { name: 'MyApp' })
}

// In browser console:
// window.__AI_STORE_DEVTOOLS__.inspect()     — print audit log
// window.__AI_STORE_DEVTOOLS__.cacheStats()  — cache hit rate, avg latency
// window.__AI_STORE_DEVTOOLS__.exportLog()   — download audit-TIMESTAMP.json
// window.__AI_STORE_DEVTOOLS__.replay(0)     — replay dispatch by index

Works with Redux DevTools Extension automatically if installed.


Audit Log

Every dispatch is automatically logged:

const { auditLog } = useAIStore()

auditLog[0]
// {
//   id: 'dispatch_1716000000000_1',
//   timestamp: '2026-05-24T10:00:00.000Z',
//   action: 'apply promo SAVE20, reduce total by 20%',
//   reasoning: 'Applied 20% discount reducing total from $50 to $40, marked promo as used.',
//   source: 'ai',          // 'ai' | 'cache' | 'optimistic' | 'fallback'
//   latency: 312,          // ms
//   diffs: [
//     { domain: 'cart', before: { total: 50, ... }, after: { total: 40, ... }, changed: ['cart.total', 'cart.promoApplied'] }
//   ]
// }

Export for compliance:

const json = exportAuditLog() // full session JSON

Solving the Hard Problems

| Problem | Solution in ai-store | |---|---| | Latency | Semantic cache → 0ms for known actions. Optimistic updates for instant UI. | | Cost | Cache + domain scoping + action batching = up to 90% fewer AI calls | | Non-determinism | temperature: 0 by default. Zod validates every response. | | Schema drift | Zod strips unknown fields. Schema is the source of truth. | | Debugging | Human-readable audit log. Replay any dispatch. Redux DevTools integration. | | Offline | offlineQueue() middleware. Ollama local model fallback. |


API Reference

AIStoreProvider

Wrap your app. Creates the store engine from config.

useAIStore<TState>()

Returns { state, dispatch, loading, error, auditLog, clearCache, exportAuditLog, reset }.

useDomain<TState, K>(domainKey)

Scoped hook. Returns { state, dispatch, loading, error } for one domain only.

createAIStore(config)

Standalone store (no React context). Returns store object with same API.

dispatch(action, options?)

  • action — natural language string
  • options.domains — limit to specific domains
  • options.skipCache — force AI call
  • options.optimistic — override optimistic patch
  • options.timeout — ms before fallback (default: 8000)

Returns Promise<{ state, reasoning, fromCache, source, latency }>.


License

MIT