Skip to Content
HeronJS v4 is now available.
Knowledge BaseKnowledge Catalog

Knowledge Catalog

HeronJS 4.7.0 applications are assembled from modules, providers, protocol handlers, and managed resources. This catalog explains which package to use, how to register its components, and what to expect when the application runs.

Start with the feature selector below, then read the relevant package section. Each API table links to a guide with configuration and examples. The Knowledge Graph presents the same packages and features interactively. For a complete first application, follow Getting Started.

How the pieces fit together

@heronjs/common supplies declarations such as Module, Provider, Task, and Guard. @heronjs/core creates the application and coordinates startup, resources, and shutdown. Protocol packages connect your handlers to HTTP routes, GraphQL, tRPC, WebSockets, messaging brokers, or agent clients. @heronjs/thread executes work in separate worker threads.

A decorator describes a component. Register that component in a module so it participates in your application:

Module fieldWhat belongs hereExample
importsOther application modulesA shared accounts or jobs module
providersInjectable application classes and task requestsAn order provider or @Task request
controllersREST controllersAn @Rest('/orders') class
servicesStartup, interval, or daemon servicesA recurring cleanup service
databasesManaged datasource classesA SqlDataSource or MongoDataSource subclass
graphqlsGraphQL schema classesAn @GraphQL class
rpcstRPC procedure classesAn @Procedure class
websocketsWebSocket gatewaysAn @WebSocket({namespace: '/chat'}) class
transportersMessaging adapter classesAn @MessagingAdapter broker
mcpsMCP catalog classesAn @MCP({path: '/mcp/tools'}) class
acpsACP agent classesAn @ACP({path: '/acp/review'}) class

Keep reusable application logic in providers. A REST controller, GraphQL resolver, and messaging consumer can use the same provider while retaining their own input validation, authentication, and response contracts. Worker dependencies are separate instances in their own execution context; send cloneable request data to them.

Application lifecycle at a glance

StepWhat you doWhat becomes available
Createawait HeronJS.create({module: AppModule})A configurable application
ConfigureSet listener defaults with app.add(...); register task definition files with app.threads(...)Configuration for startup
Startawait app.start() for background work, or await app.listen({port: 3000}) for HTTPInitialized providers, protocol extensions, resource hooks, and configured workers
UseExecute handlers, dispatch tasks, and acquire resource leasesApplication-owned resources within their scope
Closeawait app.close()Awaited cleanup of owned work and resources

listen() may follow start() without restarting resources. Configure worker sources and protocol defaults before initialization. When using await using app, the application closes when its scope exits.

Choose a feature

I want to…Start here
Create and start an applicationApplication lifecycle
Register providers or enforce permissionsShared APIs
Run isolated tasksWorker tasks
Serve HTTP routes or SSEHTTP
Query GraphQL or tRPCGraphQL · tRPC
Publish or consume broker messagesMessaging
Reply to WebSocket eventsWebSockets
Expose tools or agentsMCP · ACP
Use SQL, MongoDB, Cassandra, ScyllaDB or cacheManaged resources

@heronjs/common

@heronjs/common — Shared contracts and dependency injection.

Use common to define the structure and contracts of an application. Import shared decorators and types from @heronjs/common; import protocol decorators from the package that handles that protocol.

Register providers in @Module({providers: [...]}). Use @Inject with a constructor or typed Token when the dependency needs an explicit identity. A string lookup returns unknown; validate it before use. Instances registered with registerInstance remain caller-owned, while registerOwnedInstance lets the container dispose them.

Security, caching, and resilience work together at the handler boundary. GateKeeper verifies credentials and produces an identity; Guard checks access requirements. For private HTTP response caching, derive a Cacheable identity from the verified principal and include permission changes in the authorization key. Configure a default cache store for cache-backed behavior.

FeaturePublic APIsUsage
ModulesModuleDeclare application components and compose modules with imports.
Dependency injectionProvider, Inject, TokenRegister providers and resolve dependencies using typed tokens.
Task requestsTask, Runnable, RunContextDeclare cloneable worker requests and cancellable handlers.
AuthorizationGuard, GateKeeperVerify identities and enforce controller or handler access rules.
Cache policiesCacheable, EvictPartition private responses by verified identity and invalidate cached routes.
LoggingLoggerWrite readable messages and structured data, with opt-in data redaction and automatic output formatting.
ResilienceRateLimiter, CircuitBreakerLimit request rates and isolate repeated failures.
HTTP contractsHttpRequest, HttpResponse, HttpOptionsType framework request, response and lifecycle configuration.

In 4.7.0, log with logger.info({message, data}) and configure new Logger({target, options}). Register explicit instances with container.registerInstance({token, instance}). Use borrow({value, release, validate}) when adapting a caller-owned resource into a disposable lease.

Startup logs help confirm which components and endpoints were registered. In 4.7.0, names are grouped by component kind; command, event and task handler mappings and protocol resource details remain individual rows. See startup output for an example.

@heronjs/core

@heronjs/core — Application composition and resource ownership.

Use core in your application entrypoint and wherever you declare managed databases or acquire native resource leases. HeronJS.create() prepares the application; start() or listen() performs initialization. Access initialized providers and resource hooks after that startup step.

The root @heronjs/core entrypoint exports SQL, MongoDB, CQL, and cache APIs. Declare datasource classes in databases, then acquire a disposable lease when you need a query builder or native client. The lease exposes .value; releasing it does not shut down the application-owned pool.

For example, after registering and starting a SQL datasource:

import {sql} from '@heronjs/core'; import {PostgresDatabase} from './database.js'; async function listOrderIds() { await using connection = await sql({source: PostgresDatabase}); return await connection.value('orders').select('id'); }

This function runs within the owning application context. The awaited query finishes before the lease is released. Pass a trusted tenant identifier as the second argument to acquire that tenant’s connection. Complete transactions and streams before leaving the lease scope.

With one running application, unscoped resource lookup can use that application. With several, use app.run(callback) to select the owner explicitly. See resource hooks for selection and disposal rules.

FeaturePublic APIsUsage
Application lifecycleHeronJS.create, app.start, app.listen, app.closeConfigure an application, initialize its resources, serve HTTP and await shutdown.
Worker configurationapp.threads, ThreadManagerRegister task definition files before startup and configure generated pools with the core ThreadManager decorator.
SQL connectionsSqlDataSource, SqlSource, sqlAcquire managed SQL query builders with tenant selection and checkout validation.
MongoDB connectionsMongoDataSource, MongoSource, mongoAcquire MongoDB client and database leases for application-owned queries and schema tooling.
Cassandra and ScyllaDBCqlDataSource, CqlSource, cqlAcquire prepared-query clients for a configured keyspace and tenant.
Cache accesscache, useCacheBorrow the application cache through a disposable lease.
Application scopesapp.runSelect the owning application for callbacks in multi-application processes.

Datasource hooks accept {source, tenant?}. For an isolated view, use source.with({tenant}); DataSourceScopeOptions and ScopedDataSource describe scope configuration and the shared contract. Views share their owner’s runtime and do not close it on disposal.

@heronjs/thread

@heronjs/thread — Worker execution and scheduling.

Use worker tasks for CPU-intensive calculations or work that benefits from isolated execution. Ordinary providers and @Service classes execute on the main thread; declaring a service does not move it into a worker.

Declare a request class with @Task({token, handler}), register the request in a module’s providers, and export its definition module. Register the compiled module with app.threads(new URL('./jobs.module.js', import.meta.url)) before startup. Keep that file separate from the executable bootstrap so importing it in a worker cannot start another application.

After startup, dispatch the request through the runtime manager:

import {ThreadManager} from '@heronjs/common'; import {firstValueFrom} from 'rxjs'; import {Square} from './jobs.module.js'; const threads = app.container.resolve(ThreadManager); const result = await firstValueFrom(threads.run({request: new Square(12), options: {timeout: 5000}})); if (typeof result !== 'number') throw new TypeError('Expected a numeric result');

Here, app is your started application and Square is the request from the worker guide. Results cross a worker boundary and must be validated. Request data must support structured cloning; database clients and open connections belong in the worker that uses them.

run({request, options}) is a cold Observable: each subscription submits another job. Use firstValueFrom for a Promise, and unsubscribe to cancel. Explicit task dispatch uses {pool, task, input, options}. Pass signal and timeout in options, and observe context.signal in handlers receiving {input, context}. Tune queue and worker limits with the core @ThreadManager decorator. The runtime class from common/thread and the decorator from core have different roles.

FeaturePublic APIsUsage
Task dispatchThreadManager.runDispatch declared requests, pass cancellation options and validate returned values.
Worker poolsRunOptionsSet per-run timeouts and cancellation; configure pool queue limits with the core ThreadManager decorator.
Worker compilationapp.threads, ESM task definitionsKeep worker definition entries available when bundling an application.

@heronjs/express

@heronjs/express — HTTP routing and request handling.

Use this package for REST endpoints, ordinary HTTP request/response handlers, and Server-Sent Events. The package name is @heronjs/express, while the HTTP engine is Fastify 5. Handler-facing request, response, interceptor, and options types come from @heronjs/common.

Declare a controller with @Rest, add method decorators such as @Get, and register it in controllers. Parameter decorators select request inputs; your application still validates their contents. Apply @Interceptors for shared request/response behavior, or configure typed lifecycle hook arrays in listener options.

Choose an ordinary route for a single result and @SSE for an event stream. A unary Observable handler sends its first emission. SSE consumes events over time, handles backpressure, and cancels on disconnect or shutdown. Observe the request’s executionSignal when your handler performs cancellable work.

Use options.setup and http() for native engine configuration. For CORS, proxy trust, body limits, and default security headers, prefer the documented HTTP options.

FeaturePublic APIsUsage
REST routesRest, Get, Post, Put, Patch, DeleteDeclare controllers and routes on the shared HTTP listener.
Request inputsBody, Params, Queries, Headers, PrincipalSelect request data and authenticated identities; validate payload values in application code.
InterceptorsInterceptors, HttpInterceptorApply request/response behavior at controller, route or application level.
Server-Sent EventsSSE, SseEventStream Observable or async-iterable events with bounded buffering and cancellation.
HTTP setuphttp, useHttpBorrow the managed engine inside options.setup for native customization.

@heronjs/gql

@heronjs/gql — GraphQL schemas and resolvers.

Use GraphQL when clients need to select fields from a shared schema or combine related data in a query. Declare schema classes with @GraphQL, add resolver methods with @Resolver, and register the classes in graphqls.

The extension serves the default /graphql endpoint on the application’s HTTP listener. Resolver decorators provide arguments, parent values, context, and execution information. Keep business logic in injected providers so it can also serve REST routes or broker consumers.

Resolvers accept values, Promises, and Observables. Unary resolver execution uses the first emission, and guards are evaluated before the result is returned. Treat unexpected server failures separately from errors intended for a client; see the GraphQL guide for error and schema configuration.

FeaturePublic APIsUsage
GraphQL schemasGraphQLDeclare schema classes and register them through module graphqls.
ResolversResolverImplement guarded query and mutation handlers using values, Promises or Observables.
Resolver inputsGqlContext, GqlInfo, GqlParams, GqlParentAccess execution context, arguments and parent values.

@heronjs/ebs

@heronjs/ebs — Message publishing and consumption.

Use messaging when an application needs to publish events, consume broker deliveries, or process work independently of an HTTP request. EBS supports Kafka, NATS, and AMQP; broker delivery and acknowledgement behavior remains specific to the selected transport.

Declare a broker with @MessagingAdapter and register its class in transporters. Declare publishers through its publishers() method. Register a @MessagingService class in providers, bind subscriptions with @Subscribe, and inject a MessagingPublisher or MessagingStreamer for outbound work.

Select the adapter class explicitly when two brokers use the same subject. This keeps operations bound to the intended connection. Kafka and AMQP subscription declarations also specify their transport so configuration callbacks receive the appropriate SDK option types.

Kafka and NATS support streaming; AMQP supports bound queue publishing and consumption. Validate decoded message payloads and make handlers idempotent where redelivery is possible. Messaging dependencies activate during startup, so publish after activation rather than from constructors.

FeaturePublic APIsUsage
Broker adaptersMessagingAdapter, TransporterDeclare application-owned Kafka, NATS or AMQP brokers and bind features to adapter classes.
PublishersPublisher, MessagingPublisherPublish envelopes through a selected adapter and subject.
SubscribersMessagingService, Subscribe, PayloadConsume broker payloads with explicit adapter selection and transport options.
StreamingStreamer, MessagingStreamerPublish Kafka or NATS streams with ordering, cancellation and lifecycle handling.

Kafka subscribers can inspect MessagePayload.headers alongside payload data. Header values preserve their original string, Buffer, or repeated-value form and may be absent.

@heronjs/websocket

@heronjs/websocket — Connections and event handlers.

Use WebSockets for ongoing, bidirectional client connections, such as chat, interactive dashboards, or collaborative sessions. Browser WebSocket clients can connect directly. Declare the namespace and its limits or authentication policy on @WebSocket, then register the gateway in websockets.

@OnMessage receives an event and replies to the same connection. By default the response uses the incoming event name; set replyTo to use a different one. A schema can validate the payload before the handler runs. Replies are not automatically broadcast to other clients.

Use @ReceiveFrom alone when a handler should consume an event without returning an automatic reply. @Socket() provides explicit peer operations; @SocketContext() provides identity and cancellation. Handlers execute sequentially per connection. Put allowed origins, authentication, heartbeat, and buffering limits on each gateway.

FeaturePublic APIsUsage
WebSocket gatewaysWebSocketConfigure per-gateway authentication, origins, limits and namespace.
Message repliesOnMessageReceive an event and reply to its originating connection, optionally using a separate reply event.
Connection eventsOnOpen, OnClose, OnErrorHandle connection lifecycle and errors.
Connection contextSocket, SocketContext, PayloadAccess the peer, payload, verified identity and cancellation signal.

@heronjs/trpc

@heronjs/trpc — Procedure endpoints and subscriptions.

Use tRPC to expose procedure-style queries, mutations, and subscriptions to tRPC clients. Declare a @Procedure class, add the relevant method decorators, and register it in rpcs. Input schemas validate values at the request boundary.

The default endpoint is /trpc. Named procedure paths create independent routers, allowing the same method name in different groups. Within a router, procedure names must be unique. Context exposes framework request/response objects, the authenticated identity, and an abort signal.

HeronJS assembles decorated controllers dynamically; they do not automatically provide an inferred application router type. The tRPC guide shows the supported client setup. Queries and mutations consume the first Observable emission; subscriptions support Observable or async-iterable streams over HTTP/SSE.

FeaturePublic APIsUsage
ProceduresProcedure, Query, MutationDeclare independent routers with validated inputs and guarded handlers.
SubscriptionsSubscriptionStream Observable or async-iterable results over HTTP/SSE.
Request contextTRPCContextAccess framework requests and responses, identity and cancellation.
Router accessrpc, useRpcBorrow native router capabilities through a disposable lease.

@heronjs/mcp

@heronjs/mcp — Tools, resources, and prompt catalogs.

Use MCP when a client needs to discover and invoke tools, read fixed resources, or request reusable prompts. Declare an @MCP catalog, register it in mcps, and use @Tool, @Resource, and @Prompt for the operations it exposes.

Each catalog path has its own operation names and endpoint policy. Tool inputs can be validated with a schema, while results follow the MCP SDK contracts. McpContext supplies identity, cancellation, and protocol operations for progress or notifications.

HTTP is the default transport. Configure token verification and Host/Origin policy on the catalog decorator for remote access. For stdio, select transport: 'stdio' on that endpoint and enable runtime: {stdio: true} on the application. Other endpoints remain HTTP, and only one MCP or ACP endpoint can own process stdio.

FeaturePublic APIsUsage
MCP catalogsMCPDeclare independent catalog endpoints with per-endpoint authentication and transport settings.
ToolsToolExpose validated tool inputs and structured results.
Resources and promptsResource, PromptProvide fixed resources and reusable prompts.
Request contextMcpContextUse caller identity, cancellation and SDK protocol context.

@heronjs/acp

@heronjs/acp — Agent endpoints and session execution.

Use ACP for an agent that manages client sessions and responds to prompts with streamed session updates. Declare an @ACP class implementing AcpAgentRuntime, give it a distinct endpoint path, and register it in acps.

Implement session creation and prompt handling, use AcpSessionContext to send updates, and observe its cancellation signal. Authentication and session state are independent for each accepted connection. Configure limits, timeouts, authentication methods, and Host/Origin policy on the agent decorator.

Choose MCP for a catalog of callable tools, resources, and prompts; choose ACP when the integration centers on an agent’s sessions and conversations. ACP defaults to HTTP and can explicitly select stdio using the same application capability described for MCP. See the ACP guide for client transport compatibility and session requirements.

FeaturePublic APIsUsage
ACP agentsACP, AcpAgentRuntimeDeclare agents with independent paths, policies and HTTP or stdio transport.
Agent sessionsAcpSessionContextCreate sessions, send updates, handle prompts and observe cancellation.
Agent authenticationauthMethods, authenticateConfigure agent authentication and connection-specific session limits.

Selecting a response or execution style

RequirementUseExecution behavior
Return one result to an HTTP, GraphQL, or tRPC requestA value, Promise, or unary Observable handlerThe first Observable emission provides the result.
Push server events to an HTTP client@SSEEvery event is streamed until completion or cancellation.
Exchange messages over a persistent client connectionA WebSocket gatewayEvents are processed sequentially per connection.
Stream procedure results to a tRPC client@SubscriptionObservable or async-iterable results use HTTP/SSE.
Consume broker deliveriesAn EBS subscriberCompletion and acknowledgement follow the selected broker’s contract.
Execute a CPU-intensive jobA declared worker taskRequests and results cross an isolated worker boundary.

For long-running work, observe the provided abort signal. A Promise does not stop its underlying work automatically when a client disconnects. See Reactive Execution for completion, empty-result, cancellation, and cleanup behavior.

Using the packages together

Install framework packages at matching versions. Import datasource and cache APIs from the @heronjs/core root. Strict TypeScript builds also need Knex, MongoDB and Cassandra SDK declarations; keep any driver used at runtime in production dependencies. See Getting Started and package entrypoints.

HeronJS.create() returns a configurable application. Register worker definitions and endpoint defaults before awaiting start() or listen(). Acquire resource leases after startup and await close() when finished. See resource hooks.

The ThreadManager export from core is a configuration decorator; the export from common or thread is the injectable runtime manager. See worker tasks.

MongoDB and CQL expose managed native connections. Validation, schemas and migrations belong to your application or chosen database tooling. See MongoDB & CQL.

Practical combinations

An order-processing application can register REST controllers, order providers, a SQL datasource, and a messaging adapter in the same module tree. Controllers validate and authorize incoming requests, providers perform database work through managed leases, and messaging services publish or consume order events after startup. Add worker tasks if a step requires CPU-intensive computation. Transaction boundaries and retry behavior remain application decisions.

An agent application can register MCP tools or ACP agents alongside REST health endpoints. Inject providers into those handlers to reuse domain logic and database access. Keep endpoint authentication explicit, acquire resources in the owning application context, and let application shutdown close managed connections and cancel owned work.

For complete configuration, start with Getting Started, Dependency Injection, and the relevant protocol guide. Use the Migration Guide when moving an existing application to 4.7.0.

Validation and execution in 4.7

@heronjs/express validates Body and Queries; @heronjs/gql validates the complete Params argument object; @heronjs/trpc accepts procedure schema; and @heronjs/websocket accepts top-level message schema. All support asynchronous parsing and transformed values after authorization. Use z.output<typeof Schema> for parameter types. See Input validation for error envelopes and cancellation behavior.

@heronjs/common enforces repeated and inherited guard policies together. Empty policies are invalid, predicates must return true, and application modules share one gatekeeper and resolver instance. See Authorization.

For sustained traffic, configure maxPendingMessages on WebSocket gateways, maxPendingUpdates/maxPendingUpdateBytes on ACP agents, and execution/notification limits on MCP catalogs. Await sends and updates. MCP production limits do not bound the SDK’s internal HTTP SSE buffer. Datasource registration with DataSources accepts current SQL, MongoDB, and CQL classes.

Last updated on