Skip to content

API Reference

This is the complete API reference for the z0 SDK. All exports are available from the main package:

import { EntityLedger, LedgerClient, generateId, ... } from '@z0/sdk';

Identity and state container for domain objects.

interface Entity<T = Record<string, unknown>> {
id: string; // Unique platform identifier
type: string; // Domain-level category (e.g., 'account')
tenant_id?: string; // Tenant ownership ID
version: number; // Optimistic concurrency control
metadata: Record<string, unknown>;
data: T; // Main data payload
created_at: number; // Unix timestamp (ms)
updated_at: number; // Unix timestamp (ms)
}

Immutable event record linked to an Entity.

interface Fact<T = Record<string, unknown>> {
id: string; // Unique fact identifier
type: string; // Event category (e.g., 'invocation')
subtype?: string; // Refined action (e.g., 'call_completed')
timestamp: number; // Unix timestamp (ms)
tenant_id: string; // Tenant ID for isolation
source_id?: string; // Source service/tool ID
entity_id?: string; // Parent Entity ID
data: T; // Event payload
}

Versioned configuration primitive.

interface Config<T = Record<string, unknown>> {
id: string;
tenant_id: string;
type: string; // Category (e.g., 'routing', 'policy')
category: string; // Logical grouping
name: string; // Human-readable name
applies_to: string; // Target entity type or ID
scope: string; // 'tenant', 'platform', 'entity'
version: number; // Auto-incrementing version
effective_at: number; // When this version becomes active
superseded_at?: number; // When superseded by newer version
settings: T; // Configuration payload
}

Configuration for declarative invariants.

interface InvariantSettings {
code: string; // Unique code (e.g., 'PAYMENT_POSITIVE')
fact_type: string; // Applies to this fact type ('*' for all)
rule: string; // Expression (e.g., 'data.amount > 0')
engine?: 'expression' | 'jsonschema' | 'sql';
severity: 'error' | 'warning';
message: string; // User-friendly error message
priority?: number; // Override resolution (10=platform, 20=tenant, 30=entity)
}

Reserved tenant ID for platform-level operations.

const SYSTEM_TENANT_ID = 'platform';

Configuration types used internally by the SDK.

const CONFIG_TYPES = {
HOOK: 'hook', // Hook configurations
INVARIANT: 'invariant', // Invariant configurations
} as const;

System fact types for platform operations.

const SYSTEM_FACT_TYPES = {
SYSTEM: 'system',
TENANT_CREATED: 'tenant_created',
ENTITY_CREATED: 'entity_created',
MANIFEST_INIT: 'manifest_init',
HOOK_REGISTERED: 'hook_registered',
} as const;

Hierarchical scope levels for configuration override resolution.

const SCOPE_PRIORITY = {
PLATFORM: 10,
TENANT: 20,
ENTITY: 30,
} as const;

Common ID prefixes for generated identifiers.

const PLATFORM_ID_PREFIXES = {
entity: 'ent_',
fact: 'fact_',
config: 'cfg_',
trace: 'tr_',
} as const;

Abstract base class for domain ledgers. Extend this to create your own ledger types.

abstract class EntityLedger<TEnv extends EntityLedgerEnv = EntityLedgerEnv>
extends DurableObject
constructor(ctx: DurableObjectState, env: TEnv)
MethodDescription
updateCachedState(fact: Fact): Promise<void>Required. Handle new facts to update materialized state
initializeSubclassSchema(): Promise<void>Optional. Add custom SQLite tables
fetchUpstreamConfigs(): Promise<Config[]>Optional. Fetch configs from parent ledgers
MethodReturnsDescription
getEntity()Entity | nullGet the current entity
upsertEntity(entity)EntityCreate or update entity
appendFact(fact)FactAppend immutable fact
getFacts(options?)Fact[]Query facts with filters
getFactById(id)Fact | nullGet single fact
getCurrentConfig(id)Config | nullGet active config
createConfig(config)ConfigCreate new config
updateConfig(id, updates)ConfigUpdate config (creates new version)
getCachedState<T>(key)T | nullRead cached state
setCachedState<T>(key, value)voidWrite cached state
deleteCachedState(key)voidDelete cached state
createSnapshot(options?)LedgerSnapshotCreate point-in-time snapshot
saveSnapshot(snapshot)voidPersist snapshot
getSnapshots(options?)LedgerSnapshot[]List snapshots
reconstructState()Promise<void>Replay all facts to rebuild state
hydrate()Promise<void>Disaster recovery from R2
interface EntityLedgerEnv {
REPLICATION_QUEUE?: Queue;
FACT_EVENTS_QUEUE?: Queue;
SNAPSHOT_BUCKET?: R2Bucket;
z0_STORAGE_CONTEXT?: R2Bucket;
[key: string]: unknown;
}

Root ledger for platform-level operations. Every z0 deployment should have exactly one.

class SystemLedger extends EntityLedger<EntityLedgerEnv>
MethodReturnsDescription
initializeAsRoot()Promise<void>Initialize as platform root
recordTenantCreated(tenantId, metadata?)Promise<Fact>Record tenant creation
recordEntityCreated(tenantId, entityId, entityType)Promise<Fact>Record entity creation
getTenants()Array<{tenant_id, created_at}>List all tenants
getEntities()Array<{tenant_id, entity_id, entity_type}>List all entities
getStats(){tenant_count, entity_count}Get platform statistics

Typed wrapper for interacting with Ledger Durable Objects.

class LedgerClient {
constructor(namespace: DurableObjectNamespace, tenantId?: string)
}
MethodReturnsDescription
stub(name)LedgerStubGet stub using logical name (uses idFromName)
stubFromHexId(hexId)LedgerStubGet stub using DO hex ID
create<T>(type, data, options?)Promise<Entity<T>>Create entity with random ID
get<T>(id)Promise<Entity<T>>Get entity state
emit<T>(id, event, data, options?)Promise<Fact<T>>Append fact to entity

Typed interface for a specific ledger entity instance.

class LedgerStub {
readonly id: string;
}
MethodReturnsDescription
appendFact<T>(fact, options?)Promise<Fact<T>>Append fact
getFact<T>(factId)Promise<Fact<T>>Get fact by ID
getFacts<T>(options?)Promise<Fact<T>[]>Query facts
upsertEntity<T>(entity, options?)Promise<Entity<T>>Create/update entity
getEntity<T>()Promise<Entity<T>>Get current entity state
createConfig<T>(config, options?)Promise<Config<T>>Create configuration
getConfig<T>(configId)Promise<Config<T>>Get configuration
updateConfig<T>(configId, updates, options?)Promise<Config<T>>Update configuration
createSnapshot(options?)Promise<LedgerSnapshot>Create snapshot
getSnapshots(limit?)Promise<LedgerSnapshot[]>List snapshots
interface ClientRequestOptions {
idempotencyKey?: string; // For safe retries
}

Central registry for domain manifests and entity definitions.

class LedgerRegistry {
// Static methods only
}
MethodReturnsDescription
register(manifest)voidRegister domain manifest
getManifest()DomainManifest | nullGet current manifest
getDefinition(type)EntityDefinition | undefinedGet entity definition
getEntityTypes()string[]List registered entity types
isFactAllowed(entityType, factType)booleanCheck if fact type is allowed
getNamespace(env, type)DurableObjectNamespaceGet DO namespace for type
registerHandler(name, handler)voidRegister async event handler
getHandler(name)FactEventHandler | undefinedGet registered handler
getSubscriptions()Subscription[]Get manifest subscriptions
clear()voidReset registry (for tests)
interface DomainManifest {
name: string;
version: string;
entities: Record<string, EntityDefinition>;
subscriptions?: Subscription[];
}
interface EntityDefinition {
ledger: string | LedgerConstructor;
subtype?: string;
description?: string;
fields?: Record<string, FieldDef>;
facts?: string[];
hooks?: HookDef[];
}

function generateId(prefix: string): string

Generates a unique ID with timestamp and random components.

import { generateId, PLATFORM_ID_PREFIXES } from '@z0/sdk';
const factId = generateId(PLATFORM_ID_PREFIXES.fact);
// => "fact_mkp123abc456def"

RFC 7807 Problem Details implementation.

class ApiError extends Error {
constructor(
status: number,
code: string,
message: string,
errors?: FieldError[],
traceId?: string
)
toProblemDetails(instance?: string): ProblemDetails
toResponse(instance?: string): Response
}
const EntityLedgerErrors = {
notFound: (resource, id) => ApiError,
badRequest: (message, errors?) => ApiError,
unauthorized: (message?) => ApiError,
forbidden: (message?) => ApiError,
conflict: (message) => ApiError,
internalError: (message?) => ApiError,
};

function authenticateRequest(request: Request, prefix?: string): AuthResult
function parseApiKey(apiKey: string, prefix?: string): { mode: ApiKeyMode; tenantId: string } | null

Key format: <prefix>_<mode>_<tenant_id>_<random>

type ApiKeyMode = 'live' | 'test';
interface AuthResult =
| { success: true; context: AuthContext }
| { success: false; error: string; status: 401 }
interface AuthContext {
tenantId: string;
mode: ApiKeyMode;
apiKey: string;
}

Zod schemas for input validation.

import { CreateEntitySchema, CreateFactSchema, CreateConfigSchema } from '@z0/sdk';
const result = CreateFactSchema.safeParse(input);

Complete webhook delivery system.

// Signing
async function signPayload(payload: string, timestamp: number, secret: string): Promise<string>
function constantTimeCompare(a: string, b: string): boolean
// Payload Building
function buildWebhookPayload(fact: Fact, pattern: string, deliveryId: string, attempt: number): WebhookPayload
function buildWebhookHeaders(deliveryId: string, signature: string, timestamp: number): Record<string, string>
// ID Generation
function generateDeliveryId(): string
function generateWebhookId(prefix?: string): string
// Matching
function matchWebhookTrigger(pattern: string, factType: string, factSubtype?: string): boolean
function findMatchingWebhooks(webhooks: WebhookConfigSettings[], fact: Fact): WebhookConfigSettings[]
// Retry Logic
function isRetryableError(status: number): boolean
function calculateBackoff(attempt: number, config?: RetryConfig): number
function validateWebhookConfig(config: unknown): boolean
// Constants
const DEFAULT_RETRY_CONFIG: RetryConfig

Runtime assertion system for enforcing platform invariants.

⚠️ Security Note: The expression engine uses new Function() which is equivalent to eval(). Only use with admin-defined rules, never with untrusted user input.

// Simple assertion
function assertInvariant(
condition: boolean,
message: string,
invariant?: string,
context?: Record<string, unknown>
): asserts condition
// Error class
class InvariantViolation extends Error {
readonly invariant: string;
readonly context?: Record<string, unknown>;
}

Static methods for checking various invariants.

MethodDescription
evaluateInvariant(fact, settings)Evaluate declarative invariant against fact
verifyFactUniqueness(fact1, fact2)Check facts with same ID are identical
verifyFactImmutability(original, retrieved)Check fact hasn’t changed
verifyConfigUniqueness(configs)Check at most one active config per type
verifyConfigTemporalOrdering(config)Check effective_at < superseded_at
verifyFactEntityReference(fact, entity)Check entity_id references exist
verifyFactSourceReference(fact, source)Check source_id references exist
verifyConfigEntityReference(config, entity)Check applies_to references exist
verifyFactInvariants(fact, context)Run all fact invariant checks
verifyConfigInvariants(config, context)Run all config invariant checks

Simple request routing utility.

class Router {
get(pattern: string, handler: RouteHandler): this
post(pattern: string, handler: RouteHandler): this
put(pattern: string, handler: RouteHandler): this
delete(pattern: string, handler: RouteHandler): this
handle(request: Request): Promise<Response>
}

interface FactSummary {
total_count: number;
total_amount: number;
by_type: Record<string, { count: number; total_amount: number }>;
}
interface LedgerSnapshot {
id: string;
entity_id: string;
facts_through: string;
timestamp: number;
period_start?: number;
period_end?: number;
entity: Entity;
fact_summary: FactSummary;
cached_states: Record<string, unknown>;
trigger: 'manual' | 'scheduled' | 'period_close' | 'archive' | 'reconstruct_backup';
}
interface HookConfig {
id: string;
version: number;
trigger: { type: string | '*'; subtype?: string | '*' };
mode: 'sync' | 'async';
action: HookAction;
}
interface HookAction {
type: 'queue' | 'webhook' | 'workflow' | 'method';
target: string;
metadata?: Record<string, unknown>;
}

export const VERSION = '0.2.0';