AvelonDocs

@avelon

core

@avelon/core

@avelon/core defines the framework-neutral contracts shared by Avelon applications, adapters, and drivers. It gives you a serializable query IR, a portable request dispatcher boundary, capability-narrowed driver facades, normalized errors, and event/listener primitives. Reach for this package when you implement a driver or adapter, or when application code needs a contract without importing an implementation.

Installation

bun add @avelon/core

Basic Usage

Build a query once and pass it to a database facade whose available operations come from literal driver capabilities.

import type { Database, DatabaseDriver, QueryIR } from '@avelon/core'

type AppDatabaseDriver = DatabaseDriver<{
  transactions: true
  rowSecurity: true
  maxRelationDepth: 4
  fullTextSearch: true
  upsert: true
  returning: true
  windowFunctions: true
  jsonOperators: true
}>

export async function latestPublishedPosts(db: Database<AppDatabaseDriver>) {
  const query = {
    table: 'posts',
    mode: 'select',
    select: ['id', 'title', 'published_at'],
    where: [{ kind: 'null', column: 'published_at', negated: true }],
    relations: [],
    order: [{ column: 'published_at', direction: 'desc' }],
    limit: 20,
  } satisfies QueryIR & { mode: 'select'; conflict?: never }

  return db.execute<{ id: string; title: string; published_at: string }>(query)
}

Query IR

QueryIR is serializable and has one meaning across database compilers. Top-level where entries compose with AND, and the ward compiler injects ward as another AND predicate; application code never supplies it. Empty AND is true, empty OR is false, an empty IN list is false unless negated, and a false ward short-circuits without a database round trip. Upserts require an explicit conflict target and update list before execution. Count mode returns the number of rows matching where and ward as QueryResult.count.

import type { QueryIR } from '@avelon/core'

export const updatePost: QueryIR = {
  table: 'posts',
  mode: 'update',
  select: '*',
  where: [{ kind: 'compare', column: 'id', op: '=', value: 'post-7' }],
  relations: [],
  order: [],
  values: { title: 'Frozen contracts' },
  returning: ['id', 'title'],
}

Adapters And Kernel Dispatch

Adapters translate native requests and responses at three seams: mount, request conversion, and response conversion. Every mounted route delegates middleware, binding, validation mapping, controller dispatch, and exception mapping to Kernel. HttpRequest.rawBody() preserves signature-verification bytes, and streaming adapters accept StreamResult. A POST route exists whether the adapter uses a server action or an ordinary HTTP POST, and the adapter alone interprets an opaque view reference.

import type { Adapter, Kernel, RouteManifest } from '@avelon/core'

export async function mountApplication(
  adapter: Adapter<string, string>,
  kernel: Kernel<string, string>,
) {
  const manifest: RouteManifest<string> = {
    version: '2026-08-02',
    routes: [
      {
        name: 'posts.store',
        method: 'POST',
        path: '/posts',
        controller: 'PostController',
        action: 'store',
        middleware: ['auth'],
        bindings: {},
        api: false,
      },
    ],
  }

  return adapter.mount(manifest, { kernel })
}

Capability-Narrowed Drivers

Every driver declares literal capabilities and a named instance. Boolean capabilities add or remove method surfaces; spectra retain exact providers, MFA factors, transforms, channels, algorithms, modes, and relation depth. raw() returns the driver's generic client type without exposing an implementation in core.

import type { Storage, StorageDriver } from '@avelon/core'

type ImageDiskDriver = StorageDriver<{
  signedUrls: true
  transforms: readonly ['resize', 'format']
}>

export async function avatarUrl(storage: Storage<ImageDiskDriver>, path: string) {
  await storage.put(path, new Uint8Array([137, 80, 78, 71]), {
    contentType: 'image/png',
  })

  return storage.transform(path, 'resize', { width: 256, height: 256 })
}

Use supports() only when configuration is resolved dynamically. Static configuration should rely on the narrowed facade so unsupported methods never enter application code.

Normalized Errors

Drivers map failures into the fixed taxonomy. Each error has a stable code, framework-owned metadata, and the original failure on the standard cause property.

import { Conflict } from '@avelon/core'

export function normalizeDuplicateSlug(cause: unknown) {
  return new Conflict('A post already uses this slug.', {
    metadata: { resource: 'Post', key: 'slug' },
    cause,
  })
}

Events And Listeners

Synchronous listeners run by ascending priority and may stop propagation by returning false or calling stopPropagation(). after listeners run post-response without retry. queued listeners declare a queue, attempts, and backoff, and receive no implicit request or actor; authorization-sensitive events must carry an actor explicitly.

import { Event, defineListener } from '@avelon/core'

class PostPublished extends Event {
  constructor(
    readonly postId: string,
    readonly actorId: string,
  ) {
    super()
  }
}

export const IndexPublishedPost = defineListener<PostPublished, void, 'queued'>({
  delivery: 'queued',
  queue: 'search',
  priority: 20,
  tries: 3,
  backoff: [10, 60, 300],
  async handle(event, context) {
    console.info('indexing post', event.postId, context.attempt)
  },
})

Runtime Facades

Wave B implements the frozen contracts as process-local facades. You wire drivers with defineConfig, dispatch events through Events, authorize with Gate, validate with defineRequest, inject wards with injectWard, and run background work through Errands. Named mailers, disks, and connections never fall back to the default when the name is unknown.

import {
  DB,
  Event,
  Events,
  defineConfig,
  defineListener,
  definePolicy,
  defineWard,
  injectWard,
  mailers,
  type DatabaseDriver,
  type MailDriver,
} from '@avelon/core'

class Post {
  static readonly name = 'Post'
  static readonly table = 'posts'
}

class PostPublished extends Event {
  constructor(readonly postId: string) {
    super()
  }
}

export function boot(
  databaseDriver: DatabaseDriver,
  transactionalMail: MailDriver,
  marketingMail: MailDriver,
) {
  defineConfig({
    name: 'app',
    drivers: {
      database: databaseDriver,
      mail: {
        default: 'transactional',
        mailers: { transactional: transactionalMail, marketing: marketingMail },
      },
    },
  })

  Events.listen(
    PostPublished,
    defineListener({
      handle: (event) => {
        console.info('published', event.postId)
      },
    }),
  )

  definePolicy(Post, {
    update: (actor, post) => actor?.id === (post as { user_id: string }).user_id,
  })

  defineWard(Post, {
    read: (actor) =>
      actor ? { or: [{ published: true }, { user_id: actor.id }] } : { published: true },
    insert: (actor) => (actor ? { user_id: actor.id } : false),
    update: (actor) => (actor ? { user_id: actor.id } : false),
    delete: (actor) => (actor ? { user_id: actor.id } : false),
  })
}

export async function publishedPosts() {
  return DB.execute(
    injectWard(
      {
        table: 'posts',
        mode: 'select',
        select: '*',
        where: [],
        relations: [],
        order: [],
      },
      { published: true },
    ),
  )
}

export async function notifyMarketing() {
  return mailers.mailer('marketing').send({
    to: 'reader@example.test',
    subject: 'Published',
    text: 'A post is live.',
  })
}

The Event class stays the frozen primitive. Events is the dispatcher so application code does not add static methods to that class. mailers.mailer, disks.disk, and queues.connection exist because Mail, Storage, and Queue are frozen type aliases.

Method Reference

The table lists every public export. Capability surface interfaces describe methods that appear only when the corresponding literal capability enables them.

ExportSignatureDescription
AItype AI<TDriver>AI facade narrowed to completion, embedding, and streaming capabilities.
ActionResultinterface ActionResult<TData>Transport-neutral controller action state.
Adapterinterface Adapter<TController, TViewRef, TNativeRequest, TNativeResponse>Web framework boundary with capability-aware stream conversion.
AfterListenerContextinterface AfterListenerContextContext for best-effort post-response listeners.
AiCapabilitiesinterface AiCapabilities<TMode>Literal AI mode and streaming declaration.
AiDriverinterface AiDriver<TCapabilities, TRaw>Base AI driver identity extended by mode surfaces.
AiMessageinterface AiMessageRole-tagged completion message.
AiModetype AiModePortable AI operation modes.
Authtype Auth<TDriver>Application-facing alias for Identity<TDriver>.
AuthCapabilitiestype AuthCapabilities<TFactor>Application-facing alias for factor-aware identity capabilities.
AuthDrivertype AuthDriver<TCapabilities, TRaw, TActor, TSession>Application-facing alias for the identity driver contract.
AvelonErrorclass AvelonError<TMetadata>Base normalized error with code, metadata, and cause.
AvelonErrorOptionsinterface AvelonErrorOptions<TMetadata>Typed metadata and cause supplied to framework errors.
BroadcastRealtimeSurfaceinterface BroadcastRealtimeSurfaceBroadcast methods for capable realtime drivers.
Cachetype Cache<TDriver>Cache facade narrowed to tags and locks.
CacheCapabilitiesinterface CacheCapabilitiesLiteral tag and lock declaration.
CacheDriverinterface CacheDriver<TCapabilities, TRaw>Base cache key-value contract.
CacheStoreinterface CacheStoreShared get, put, forget, and flush methods.
CapabilityMemberstype CapabilityMembers<TValues>Members retained by a literal capability spectrum.
CapabilitySurfacetype CapabilitySurface<TCapability, TSurface>Surface present only when a capability is literal true.
CheckoutPaymentSurfaceinterface CheckoutPaymentSurfaceHosted checkout methods for capable payment drivers.
CheckoutSessioninterface CheckoutSessionNormalized hosted checkout session.
CompareOptype CompareOpPortable comparison operator union.
CompletionAiSurfaceinterface CompletionAiSurfaceComplete-response generation method.
CompletionChunkinterface CompletionChunkOne incremental streaming completion chunk.
CompletionRequestinterface CompletionRequestPortable text completion request.
CompletionResultinterface CompletionResultGenerated text and optional token counts.
CookieOptionsinterface CookieOptionsTransport-neutral cookie write options.
Conflictclass ConflictNormalized state conflict error.
ConflictMetadatainterface ConflictMetadataResource and framework-owned conflict key.
Databasetype Database<TDriver>Database facade narrowed to literal capabilities.
DatabaseCapabilitiesinterface DatabaseCapabilitiesExact database capability declaration.
DatabaseDriverinterface DatabaseDriver<TCapabilities, TRaw>Query, routine, migration, and raw client contract.
DatabaseFullTextSurfaceinterface DatabaseFullTextSurfaceNative full-text search method.
DatabaseSurfaceinterface DatabaseSurface<TDriver>Always-available database facade methods.
DatabaseTransactioninterface DatabaseTransactionQuery and routine methods inside a transaction.
DeadLetterQueueSurfaceinterface DeadLetterQueueSurfaceFailed-job inspection, replay, and deletion methods.
DelayedQueueSurfaceinterface DelayedQueueSurfaceScheduled enqueue method.
DeliveryModetype DeliveryModeSync, after-response, or queued listener delivery.
DriverCapabilitiesOftype DriverCapabilitiesOf<TDriver>Extracts a driver's exact capability shape.
DriverContractinterface DriverContract<TCapabilities, TRaw>Shared name, instance, capabilities, and raw client contract.
DriverFaultclass DriverFaultNormalized unmapped driver error.
DriverFaultMetadatainterface DriverFaultMetadataDriver contract and operation identifiers.
EmbeddingAiSurfaceinterface EmbeddingAiSurfaceText embedding method.
EmbeddingResultinterface EmbeddingResultOrdered embedding vectors and token count.
ErrorCodetype ErrorCodeFixed machine-readable error code union.
Eventclass EventEvent primitive with explicit propagation state.
EventConstructorinterface EventConstructor<TEvent>Constructable event class used by registrations.
EventDispatchOptionsinterface EventDispatchOptionsDispatch options including afterCommit.
EventDispatcherinterface EventDispatcherDispatch, post-response, and until event boundary.
EventSerializerinterface EventSerializer<TEvent>Queue serialization and rehydration boundary.
EventSubscriberinterface EventSubscriberMulti-event listener registration contract.
FailedQueueJobinterface FailedQueueJobTerminal queue failure retained for replay.
FlagCapabilitiesinterface FlagCapabilitiesLiteral targeting capability declaration.
FlagContextinterface FlagContextExplicit actor, organization, and targeting attributes.
FlagDriverinterface FlagDriver<TCapabilities, TRaw>Feature flag evaluation contract.
FlagSurfaceinterface FlagSurface<TDriver>Context-restricted feature flag methods.
Flagstype Flags<TDriver>Feature flag facade narrowed to targeting support.
Forbiddenclass ForbiddenNormalized authorization denial.
ForbiddenMetadatainterface ForbiddenMetadataDenied ability and resource identifiers.
HttpMethodtype HttpMethodMethods accepted by route manifests.
HttpRequestinterface HttpRequest<TBody>Framework-neutral decoded request with access to raw bytes.
Identitytype Identity<TDriver>Identity facade narrowed to five auth capabilities.
IdentityCapabilitiesinterface IdentityCapabilities<TFactor>Password, magic-link, OAuth, organization, and MFA factor declaration.
IdentityDriverinterface IdentityDriver<TCapabilities, TRaw, TActor, TSession>Current actor, session, and sign-out contract.
IdentityOrganizationinterface IdentityOrganizationNormalized organization summary.
Invalidclass InvalidNormalized invalid-input error.
InvalidMetadatainterface InvalidMetadataField-keyed validation messages.
IssuedTokeninterface IssuedTokenToken metadata plus one-time plaintext value.
Kernelinterface Kernel<TController, TViewRef>Core request pipeline dispatcher.
KernelResulttype KernelResult<TViewRef>Action, redirect, opaque view, or byte-stream result.
ListenerContexttype ListenerContext<TDelivery>Delivery-specific context with no implicit actor.
ListenerDefinitiontype ListenerDefinition<TEvent, TResult, TDelivery>Listener handler, priority, delivery, retry, and backoff contract.
ListenerRegistrationinterface ListenerRegistration<TEvent>Event class and listener pair.
ListenerResulttype ListenerResult<TResult>Listener value, null, void, or propagation-stopping false.
LockCacheSurfaceinterface LockCacheSurfaceNamed cache lock method.
LogCapabilitiesinterface LogCapabilitiesLiteral tracing capability declaration.
LogDriverinterface LogDriver<TCapabilities, TRaw>Structured log write contract.
LogLeveltype LogLevelPortable structured log severity.
LogRecordinterface LogRecordStructured application log event.
Logstype Logs<TDriver>Logging facade narrowed to tracing support.
MagicLinkIdentitySurfaceinterface MagicLinkIdentitySurfacePasswordless sign-in link method.
Mailtype Mail<TDriver>Mail facade narrowed to hosted templates.
MailAttachmentinterface MailAttachmentPortable attachment filename, bytes, and media type.
MailCapabilitiesinterface MailCapabilitiesLiteral hosted-template capability declaration.
MailDriverinterface MailDriver<TCapabilities, TRaw>Transactional mail send contract.
MailMessageinterface MailMessageTransport-neutral email message with optional reply recipients.
MailReceiptinterface MailReceiptAccepted message identifier and recipients.
MfaChallengeinterface MfaChallenge<TFactor>Normalized challenge retaining its declared factor.
MfaIdentitySurfaceinterface MfaIdentitySurface<TFactor>Factor-restricted challenge and verification methods.
MigrationPlaninterface MigrationPlanDriver-owned pending migration plan.
MigrationStatusinterface MigrationStatusApplied state for one migration.
MountOptionsinterface MountOptions<TController, TViewRef>Kernel, base path, and development mount settings.
MountResultinterface MountResultMounted routes and generated files.
NotFoundclass NotFoundNormalized missing-resource error.
NotFoundMetadatainterface NotFoundMetadataMissing resource and optional identifier.
NotificationCapabilitiesinterface NotificationCapabilities<TChannel>Literal notification channel spectrum.
NotificationChanneltype NotificationChannelPush, SMS, and in-app channels.
NotificationDriverinterface NotificationDriver<TCapabilities, TRaw>Notification delivery contract.
NotificationMessageinterface NotificationMessage<TData>Portable recipient, body, and application data.
NotificationReceiptinterface NotificationReceiptAccepted notification identifier and channel.
NotificationSurfaceinterface NotificationSurface<TDriver>Send method restricted to configured channels.
Notificationstype Notifications<TDriver>Notification facade narrowed to channel literals.
OAuthIdentitySurfaceinterface OAuthIdentitySurfaceSocial identity linking method.
OrderTerminterface OrderTermColumn, direction, and null ordering.
OrganizationIdentitySurfaceinterface OrganizationIdentitySurfaceOrganization listing and selection methods.
PasswordIdentitySurfaceinterface PasswordIdentitySurface<TActor>Registration, sign-in, token reset, and authenticated update methods.
PaymentCapabilitiesinterface PaymentCapabilitiesSubscription, checkout, and webhook declaration.
PaymentCustomerinterface PaymentCustomerNormalized payment customer.
PaymentDriverinterface PaymentDriver<TCapabilities, TRaw>Base payment customer contract.
PaymentSubscriptioninterface PaymentSubscriptionNormalized recurring subscription.
PaymentWebhookinterface PaymentWebhook<TData>Verified normalized payment event.
Paymentstype Payments<TDriver>Payments facade narrowed to optional commerce methods.
Predicatetype PredicateSerializable portable predicate tree.
PresenceRealtimeSurfaceinterface PresenceRealtimeSurfacePresence join, leave, and member methods.
QueryIRinterface QueryIRSerializable select, count, and write query representation.
QueryResultinterface QueryResult<TRow>Returned rows, affected rows, and count-mode total.
Queuetype Queue<TDriver>Queue facade narrowed to delay, retry, and dead letter.
QueueCapabilitiesinterface QueueCapabilitiesLiteral queue capability declaration.
QueueDriverinterface QueueDriver<TCapabilities, TRaw>Base enqueue and drain contract.
QueueJobinterface QueueJob<TPayload>Named serializable queue job.
QueueReceiptinterface QueueReceipt<TPayload>Job delivery identifier and attempt.
QueuedEventEnvelopeinterface QueuedEventEnvelopeDurable event/listener queue boundary without actor context.
QueuedListenerContextinterface QueuedListenerContextQueue, attempt, and maximum tries for a worker.
RateLimittype RateLimit<TDriver>Rate-limit facade narrowed to algorithm literals.
RateLimitAlgorithmtype RateLimitAlgorithmToken-bucket and sliding-window algorithms.
RateLimitCapabilitiesinterface RateLimitCapabilities<TAlgorithm>Literal algorithm spectrum.
RateLimitDecisioninterface RateLimitDecisionAllowance, remaining capacity, and reset time.
RateLimitDriverinterface RateLimitDriver<TCapabilities, TRaw>Rate consumption and reset contract.
RateLimitPolicyinterface RateLimitPolicy<TAlgorithm>Algorithm, limit, and interval settings.
RateLimitSurfaceinterface RateLimitSurface<TDriver>Consume method restricted to configured algorithms.
RateLimitedclass RateLimitedNormalized rate-limit error.
RateLimitedMetadatainterface RateLimitedMetadataKey, retry delay, and applied limit.
Realtimetype Realtime<TDriver>Realtime facade narrowed to presence and broadcast.
RealtimeCapabilitiesinterface RealtimeCapabilitiesLiteral presence and broadcast declaration.
RealtimeDriverinterface RealtimeDriver<TCapabilities, TRaw>Base channel subscription contract.
RealtimeMessageinterface RealtimeMessage<TPayload>Channel event and payload.
RealtimeSubscriptioninterface RealtimeSubscriptionActive subscription with asynchronous unsubscribe.
RedirectResultinterface RedirectResultTransport-neutral redirect result.
RelationLoadinterface RelationLoadFully resolved eager relation plan.
RequestCookiesinterface RequestCookiesRequest-scoped cookie read, write, and delete boundary.
RetryQueueSurfaceinterface RetryQueueSurfaceFailed-attempt retry method.
RouteDefinitioninterface RouteDefinition<TController>Concrete transport-neutral route entry.
RouteManifestinterface RouteManifest<TController>Versioned ordered route collection.
RowSecuritySurfaceinterface RowSecuritySurfaceWard synchronization method.
Searchtype Search<TDriver>Search facade narrowed to facet support.
SearchCapabilitiesinterface SearchCapabilitiesLiteral facet capability declaration.
SearchDocumentinterface SearchDocumentStable document identifier and fields.
SearchDriverinterface SearchDriver<TCapabilities, TRaw>Index, removal, and query contract.
SearchHitinterface SearchHit<TDocument>Matching document and normalized score.
SearchOptionsinterface SearchOptionsPagination, filters, and optional facets.
SearchResultinterface SearchResult<TDocument>Hits, total, and optional facet counts.
SearchSurfaceinterface SearchSurface<TDriver>Query method restricted by facet capability.
SerializedEventinterface SerializedEventQueue-safe event payload and references.
SerializedReferenceinterface SerializedReference<TId>Explicit reference rehydrated in a worker.
SignedUrlStorageSurfaceinterface SignedUrlStorageSurfaceTemporary signed read URL method.
Socialtype Social<TDriver>Social facade narrowed to provider literals.
SocialCapabilitiesinterface SocialCapabilities<TProvider>Literal social provider spectrum.
SocialDriverinterface SocialDriver<TCapabilities, TRaw, TProfile>OAuth redirect and state-verifying callback exchange contract.
SocialIdentityinterface SocialIdentity<TProfile>Normalized social subject and profile.
SocialSurfaceinterface SocialSurface<TDriver>OAuth callback methods restricted to configured providers.
Storagetype Storage<TDriver>Storage facade narrowed to signed URLs and transforms.
StorageCapabilitiesinterface StorageCapabilities<TTransform>Literal signed URL and transform declaration.
StorageDriverinterface StorageDriver<TCapabilities, TRaw>Base put, get, delete, and exists contract.
StorageObjectinterface StorageObjectNormalized stored object metadata.
StorageTransformtype StorageTransformResize, crop, and format operations.
StorageTransformOptionsinterface StorageTransformOptionsPortable dimensions and output format.
StreamResultinterface StreamResultAsync response-byte stream for streaming adapters.
StreamingAiSurfaceinterface StreamingAiSurfaceIncremental completion stream method.
SubscriptionPaymentSurfaceinterface SubscriptionPaymentSurfaceSubscription create, read, and cancel methods.
SyncListenerContextinterface SyncListenerContextContext for inline listeners.
TaggedCacheSurfaceinterface TaggedCacheSurfaceTagged cache namespace method.
TemplateMailSurfaceinterface TemplateMailSurfaceHosted-template mail method.
TokenCapabilitiesinterface TokenCapabilitiesLiteral ability and expiration declaration.
TokenDriverinterface TokenDriver<TCapabilities, TRaw>Token authentication, issuance, listing, and revocation contract.
TokenIssueOptionsinterface TokenIssueOptionsOptional token abilities and expiration.
TokenRecordinterface TokenRecordSubject-owned token metadata without its secret.
TokenSurfaceinterface TokenSurface<TDriver>Verification plus capability-restricted token issuance.
Tokenstype Tokens<TDriver>API-token facade narrowed to issuance features.
TraceLogSurfaceinterface TraceLogSurfaceTrace span creation method.
TraceSpaninterface TraceSpanActive trace span with attributes, errors, and end.
TransactionSurfaceinterface TransactionSurfaceAtomic database callback method.
TransformStorageSurfaceinterface TransformStorageSurface<TTransform>Transform method restricted to literal operations.
Unauthenticatedclass UnauthenticatedNormalized missing-authentication error.
UnauthenticatedMetadatainterface UnauthenticatedMetadataAuthentication guard identifier.
Unavailableclass UnavailableNormalized temporary service outage.
UnavailableMetadatainterface UnavailableMetadataService name and retry delay.
ViewReftype ViewRef<TReference>Opaque adapter-owned view reference.
ViewResultinterface ViewResult<TViewRef, TProps>Opaque view reference and serializable properties.
WebhookPaymentSurfaceinterface WebhookPaymentSurfaceSigned webhook verification and normalization method.
defineListenerdefineListener(definition)Preserves literal delivery, priority, retry, and backoff types.
supportssupports(driver, capability)Runtime capability guard with typed keys.
AvelonConfiginterface AvelonConfigApplication configuration accepted by defineConfig.
AvelonDriversinterface AvelonDriversOptional driver wiring for database, identity, mail, storage, and queue.
CompiledSqlinterface CompiledSqlParameterized SQL boolean expression produced by the ward compiler.
ControllerClasstype ControllerClassConstructable controller accepted by createKernel.
ControllerMethodtype ControllerMethodController action signature.
CreateKernelOptionsinterface CreateKernelOptionsBinding, actor, middleware, and exception-mapping hooks.
DBconst DBDatabase facade with named connection() resolution.
ErrandDefinitioninterface ErrandDefinition<TPayload>Background job contract with three delivery modes.
Errandsconst ErrandsDispatch, drain, failed table, retry, and flush.
Eventsconst EventsProcess-wide EventDispatcher plus after/queued flush helpers.
Events.bindQueue(queue?: QueueDriver) => voidWires a queue driver for queued listeners; omit to use the memory board.
FormRequestinterface FormRequest<TOutput>Request validator with validate().
FormRequestDefinitioninterface FormRequestDefinition<TOutput>Zod schema plus optional authorize hook.
Gateconst GatePolicy can and authorize helpers.
GateActortype GateActorAuthenticated actor or null.
InProcessEventDispatcherclass InProcessEventDispatcherDefault EventDispatcher implementation.
KernelMiddlewaretype KernelMiddlewareNamed middleware callback.
MaybeNamedtype MaybeNamed<TDriver>Single driver or named registry.
MemoryJobBoardclass MemoryJobBoardProcess-local queue and failed table.
NamedDriversinterface NamedDrivers<TDriver>{ default, instances/mailers/disks/connections } registry.
PolicyAbilitiestype PolicyAbilitiesAbility name to handler map.
PolicyHandlertype PolicyHandlerPolicy callback receiving actor and resource.
RequestSchemainterface RequestSchema<TOutput>Zod-compatible parse surface.
WardAbilitiesinterface WardAbilitiesread/insert/update/delete ward factories.
WardActiontype WardActionOne of the four ward abilities.
WardDriftinterface WardDriftFixture evaluation mismatch.
WardFixtureinterface WardFixtureRow plus expected visibility.
WardInputtype WardInputPredicate, boolean, or object shorthand.
WardShorthandinterface WardShorthand{ or, and, not } or column-equals object.
auth(cookies) => IdentityDriverRequest-scoped identity factory.
backoffSeconds(backoff, attempt) => numberDelay for a one-based attempt.
capabilityMatrix(config?) => Record<string, Record<string, unknown>>Literal capabilities for every configured instance.
compilePredicateToSql(predicate) => CompiledSqlParameterized SQL boolean expression.
compileWardPolicy(resource, action, actor, role?) => { statement, params }Postgres RLS CREATE POLICY statement.
compileWardShorthand(input) => PredicateShorthand or boolean to portable predicate.
createEventDispatcher(options?) => InProcessEventDispatcherIsolated event bus.
createKernel(options?) => KernelRequest pipeline with middleware, binding, and exception mapping.
defineAbility(ability, handler) => voidRegisters a global can:* middleware ability.
defineConfig(config, environment?) => configWires drivers; overlay merges on top.
defineErrand(definition) => ErrandDefinitionPreserves errand delivery and retry metadata.
definePolicy(resource, abilities) => voidRegisters policy abilities for a resource.
defineRequest(definition) => FormRequestZod validation with optional authorize hook.
defineWard(resource, abilities) => voidRegisters a ward for IR injection and SQL policy compile.
detectPolicyDrift(currentSql, recordedSql) => booleanTrue when a compiled policy statement changed.
detectWardDrift(predicate, fixtures) => WardDrift[]Client-side evaluation mismatches.
disksconst disksStorage facade with named disk() resolution.
eventDispatcher() => InProcessEventDispatcherProcess-wide dispatcher instance.
evaluatePredicate`(predicate, row) => boolean \null`SQL three-valued client evaluation.
finishResponse() => Promise<void>Flushes after listeners and errands.
flushAfterErrands() => Promise<void>Runs errands scheduled with delivery: 'after'.
getConfig() => AvelonConfigActive configuration, or Unavailable.
holdUntilCommit(task) => voidHolds a task until runInTransaction commits.
injectWard(query, ward) => QueryIRCopies a query and sets ward.
isInTransaction() => booleanWhether an afterCommit boundary is open.
jobBoard() => MemoryJobBoardProcess-local job board used by events and errands.
mailersconst mailersMail facade with named mailer() resolution.
mapKernelException`(error) => KernelResult \undefined`Maps taxonomy errors to HTTP-shaped results.
queuesconst queuesQueue facade with named connection() resolution.
redirect(location, status?) => RedirectResultBuilds a redirect kernel result.
refusedWardShapesreadonly string[]Predicate shapes the ward compiler will not approximate.
registerErrand(definition) => voidRegisters an errand by name.
resetConfig() => voidClears configuration. Test helper.
resetErrands() => voidClears registered errands. Test helper.
resetPolicies() => voidClears registered policies. Test helper.
resetTransaction() => voidClears commit-boundary state. Test helper.
resetWards() => voidClears registered wards. Test helper.
resolveNamedDriver(value, name, kind) => TDriverResolves a named instance or throws Invalid.
resolveWard(resource, action, actor) => PredicateCompiles a registered ward ability.
rowAllowedByWard(predicate, row) => booleanTrue only when evaluation is true.
runInTransaction(callback) => Promise<T>Commit boundary for afterCommit dispatch.
validateRequest(request, schema) => TOutputParses a body or throws Invalid.
view(viewRef, props, status?) => ViewResultBuilds an opaque view kernel result.
withWardtypeof injectWardAlias for injectWard.

Testing

Driver packages provide certified fakes. When you test a package that only consumes the contract, a small structural fake keeps the exact same method surface.

import { expect, test } from 'bun:test'
import type { MailDriver } from '@avelon/core'

const sent: string[] = []
const mail = {
  name: 'memory',
  instance: 'default',
  capabilities: { templates: false } as const,
  async send(message) {
    const recipients = typeof message.to === 'string' ? [message.to] : message.to
    sent.push(...recipients)
    return { id: `message-${sent.length}`, accepted: recipients }
  },
  raw() {
    return null
  },
} satisfies MailDriver<{ templates: false }, null>

test('sends the welcome message', async () => {
  await mail.send({
    to: 'reader@example.com',
    subject: 'Welcome',
    text: 'Your account is ready.',
  })

  expect(sent).toEqual(['reader@example.com'])
})

Run the package's runtime and type-level contract tests together:

bun test
bun run typecheck