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

@z0-app/sdk

v0.5.0

Published

Build immutable, traceable systems with three primitives: Entity, Fact, Config

Readme

z0 SDK

Build immutable, traceable systems with three primitives: Entity, Fact, Config

z0 is a minimalist SDK for building event-sourced, auditable systems on Cloudflare Workers. Instead of prescribing how your application should work, z0 gives you three powerful primitives and gets out of your way.

Quick Start

npm install @z0-app/sdk
import { EntityLedger, type Fact, type EntityLedgerEnv } from '@z0-app/sdk';

// 1. Define your domain ledger
export class AccountLedger extends EntityLedger<EntityLedgerEnv> {
  protected async updateCachedState(fact: Fact): Promise<void> {
    const balance = this.getCachedState<number>('balance') ?? 0;

    if (fact.type === 'deposit') {
      this.setCachedState('balance', balance + (fact.data.amount as number));
    }
  }
}

// 2. Use it via the Typed Client
import { LedgerClient } from '@z0-app/sdk';

export default {
    async fetch(request: Request, env: EntityLedgerEnv) {
        const client = new LedgerClient(env.ACCOUNT_LEDGER);
        
        // Append a fact
        await client.emit('user_123', 'deposit', { amount: 100 });
        
        // Get the entity state
        const entity = await client.get('user_123');
        return Response.json(entity);
    }
}

The Three Primitives

Entity

Identity and state container. Like a row in a database, but immutable.

interface Entity<T = Record<string, unknown>> {
  id: string;
  type: string;
  tenant_id?: string;
  version: number;
  data: T; // Generic JSON payload
  created_at: number;
  updated_at: number;
}

Fact

Immutable event record. Once written, never changed.

interface Fact<T = Record<string, unknown>> {
  id: string;
  type: string;
  subtype?: string;
  timestamp: number;
  tenant_id: string;
  entity_id?: string;
  data: T; // Generic JSON payload
}

Config

Versioned configuration. Changes create new versions, never overwrite.

interface Config<T = Record<string, unknown>> {
  id: string;
  version: number;
  settings: T; // Generic JSON payload
  // ...
}

Build Your First Domain in 5 Minutes

1. Define Your Domain Manifest

import { LedgerRegistry, type DomainManifest } from '@z0-app/sdk';

const manifest: DomainManifest = {
  name: 'my-app',
  version: '1.0.0',
  entities: {
    account: {
      ledger: 'AccountLedger',
      description: 'User account',
      fields: {
        // No more "slots"! Just define your fields.
        // We automatically generate schema and indexes for you.
        email: { type: 'string', required: true },
        balance: { type: 'number' },
        active: { type: 'boolean' },
      },
      facts: ['deposit', 'withdrawal'],
    },
  },
};

LedgerRegistry.register(manifest);

2. Create Your Ledger Class

import { EntityLedger, type Fact } from '@z0-app/sdk';

export class AccountLedger extends EntityLedger {
  protected async updateCachedState(fact: Fact): Promise<void> {
    const balance = this.getCachedState<number>('balance') ?? 0;

    switch (fact.type) {
      case 'deposit':
        this.setCachedState('balance', balance + (fact.data.amount as number));
        break;
    }
  }
}

3. Use Your Ledger with LedgerClient

import { LedgerClient } from '@z0-app/sdk';

// Create a client for the specific binding
const accounts = new LedgerClient(env.ACCOUNT_LEDGER);

// 1. Initialize (optional, upsert logic handles this)
await accounts.stub('user_123').upsertEntity({
    type: 'account',
    data: { email: '[email protected]', balance: 0 }
});

// 2. Append facts
await accounts.emit('user_123', 'deposit', { amount: 100.00 });

// 3. Query
const entity = await accounts.get<{ balance: number }>('user_123');
console.log(entity.data.balance); // 100.00

Core Features

EntityLedger Base Class

The EntityLedger class provides:

  • SQLite-backed storage with automatic schema initialization
  • Fact append with hooks and replication
  • Config management with versioning
  • Cached state for denormalized views
  • Snapshots for point-in-time recovery
  • Idempotency for safe retries
  • Tenant isolation built-in

LedgerRegistry Pattern

Register your domain manifest once and let z0 handle routing:

import { LedgerRegistry } from '@z0-app/sdk';

LedgerRegistry.register(manifest);

// Get entity definition
const def = LedgerRegistry.getDefinition('account');

// Check fact permissions
const allowed = LedgerRegistry.isFactAllowed('account', 'deposit');

Utilities

ID Generation

import { generateId, PLATFORM_ID_PREFIXES } from '@z0-app/sdk';

const factId = generateId(PLATFORM_ID_PREFIXES.fact);
// => "fact_l3k5j8h9k2j3h4"

Error Handling (RFC 7807)

import { ApiError, EntityLedgerErrors } from '@z0-app/sdk';

throw EntityLedgerErrors.notFound('Account', accountId);
// Returns RFC 7807 Problem Details response

Authentication

import { authenticateRequest } from '@z0-app/sdk';

const auth = authenticateRequest(request);
if (!auth.success) {
  return new Response('Unauthorized', { status: 401 });
}
console.log(auth.context.tenantId);

Webhooks

import { buildWebhookPayload, signPayload } from '@z0-app/sdk';

const payload = buildWebhookPayload(fact, 'deposit.completed', deliveryId, 1);
const signature = await signPayload(JSON.stringify(payload), timestamp, secret);

Runtime Invariants

import { assertInvariant, InvariantChecker } from '@z0-app/sdk';

// Simple assertion
assertInvariant(fact.timestamp > 0, 'Fact timestamp must be positive');

// Declarative invariant evaluation
InvariantChecker.evaluateInvariant(fact, {
  code: 'POSITIVE_AMOUNT',
  fact_type: 'payment',
  rule: 'data.amount > 0',
  severity: 'error',
  message: 'Amount must be positive'
});

// Verify referential integrity
InvariantChecker.verifyFactInvariants(fact, { entity, sourceFact });

Why z0?

Zero Overhead

z0 is primitives, not frameworks. No routing layer, no middleware stack, no magic. Just three types and some utilities.

Zero Lock-in

Built on standard Cloudflare Workers primitives. If you outgrow z0, you own your data and can migrate.

Zero Compromises

Immutability, auditability, and traceability are enforced at the type level. You can't accidentally break them.

Architecture

z0 is built on Cloudflare Durable Objects:

  • One Durable Object per Entity - Perfect isolation, no cross-entity queries
  • SQLite storage - Fast, local, transactional
  • Automatic replication - Facts replicate to D1/R2 for analytics
  • Event-driven hooks - React to facts with sync or async handlers

Examples

See docs.z0.app/examples for:

  • Pay-per-call marketplace
  • Multi-tenant SaaS billing
  • Financial ledger with reconciliation
  • Webhook delivery system
  • Real-time dashboards

Documentation

Requirements

  • Node.js >= 18
  • Cloudflare Workers account
  • Durable Objects enabled

License

MIT

Contributing

We welcome contributions! See CONTRIBUTING.md for guidelines.

Support