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 field | What belongs here | Example |
|---|---|---|
imports | Other application modules | A shared accounts or jobs module |
providers | Injectable application classes and task requests | An order provider or @Task request |
controllers | REST controllers | An @Rest('/orders') class |
services | Startup, interval, or daemon services | A recurring cleanup service |
databases | Managed datasource classes | A SqlDataSource or MongoDataSource subclass |
graphqls | GraphQL schema classes | An @GraphQL class |
rpcs | tRPC procedure classes | An @Procedure class |
websockets | WebSocket gateways | An @WebSocket({namespace: '/chat'}) class |
transporters | Messaging adapter classes | An @MessagingAdapter broker |
mcps | MCP catalog classes | An @MCP({path: '/mcp/tools'}) class |
acps | ACP agent classes | An @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
| Step | What you do | What becomes available |
|---|---|---|
| Create | await HeronJS.create({module: AppModule}) | A configurable application |
| Configure | Set listener defaults with app.add(...); register task definition files with app.threads(...) | Configuration for startup |
| Start | await app.start() for background work, or await app.listen({port: 3000}) for HTTP | Initialized providers, protocol extensions, resource hooks, and configured workers |
| Use | Execute handlers, dispatch tasks, and acquire resource leases | Application-owned resources within their scope |
| Close | await 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 application | Application lifecycle |
| Register providers or enforce permissions | Shared APIs |
| Run isolated tasks | Worker tasks |
| Serve HTTP routes or SSE | HTTP |
| Query GraphQL or tRPC | GraphQL · tRPC |
| Publish or consume broker messages | Messaging |
| Reply to WebSocket events | WebSockets |
| Expose tools or agents | MCP · ACP |
| Use SQL, MongoDB, Cassandra, ScyllaDB or cache | Managed 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.
| Feature | Public APIs | Usage |
|---|---|---|
| Modules | Module | Declare application components and compose modules with imports. |
| Dependency injection | Provider, Inject, Token | Register providers and resolve dependencies using typed tokens. |
| Task requests | Task, Runnable, RunContext | Declare cloneable worker requests and cancellable handlers. |
| Authorization | Guard, GateKeeper | Verify identities and enforce controller or handler access rules. |
| Cache policies | Cacheable, Evict | Partition private responses by verified identity and invalidate cached routes. |
| Logging | Logger | Write readable messages and structured data, with opt-in data redaction and automatic output formatting. |
| Resilience | RateLimiter, CircuitBreaker | Limit request rates and isolate repeated failures. |
| HTTP contracts | HttpRequest, HttpResponse, HttpOptions | Type 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.
| Feature | Public APIs | Usage |
|---|---|---|
| Application lifecycle | HeronJS.create, app.start, app.listen, app.close | Configure an application, initialize its resources, serve HTTP and await shutdown. |
| Worker configuration | app.threads, ThreadManager | Register task definition files before startup and configure generated pools with the core ThreadManager decorator. |
| SQL connections | SqlDataSource, SqlSource, sql | Acquire managed SQL query builders with tenant selection and checkout validation. |
| MongoDB connections | MongoDataSource, MongoSource, mongo | Acquire MongoDB client and database leases for application-owned queries and schema tooling. |
| Cassandra and ScyllaDB | CqlDataSource, CqlSource, cql | Acquire prepared-query clients for a configured keyspace and tenant. |
| Cache access | cache, useCache | Borrow the application cache through a disposable lease. |
| Application scopes | app.run | Select 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.
| Feature | Public APIs | Usage |
|---|---|---|
| Task dispatch | ThreadManager.run | Dispatch declared requests, pass cancellation options and validate returned values. |
| Worker pools | RunOptions | Set per-run timeouts and cancellation; configure pool queue limits with the core ThreadManager decorator. |
| Worker compilation | app.threads, ESM task definitions | Keep 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.
| Feature | Public APIs | Usage |
|---|---|---|
| REST routes | Rest, Get, Post, Put, Patch, Delete | Declare controllers and routes on the shared HTTP listener. |
| Request inputs | Body, Params, Queries, Headers, Principal | Select request data and authenticated identities; validate payload values in application code. |
| Interceptors | Interceptors, HttpInterceptor | Apply request/response behavior at controller, route or application level. |
| Server-Sent Events | SSE, SseEvent | Stream Observable or async-iterable events with bounded buffering and cancellation. |
| HTTP setup | http, useHttp | Borrow 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.
| Feature | Public APIs | Usage |
|---|---|---|
| GraphQL schemas | GraphQL | Declare schema classes and register them through module graphqls. |
| Resolvers | Resolver | Implement guarded query and mutation handlers using values, Promises or Observables. |
| Resolver inputs | GqlContext, GqlInfo, GqlParams, GqlParent | Access 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.
| Feature | Public APIs | Usage |
|---|---|---|
| Broker adapters | MessagingAdapter, Transporter | Declare application-owned Kafka, NATS or AMQP brokers and bind features to adapter classes. |
| Publishers | Publisher, MessagingPublisher | Publish envelopes through a selected adapter and subject. |
| Subscribers | MessagingService, Subscribe, Payload | Consume broker payloads with explicit adapter selection and transport options. |
| Streaming | Streamer, MessagingStreamer | Publish 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.
| Feature | Public APIs | Usage |
|---|---|---|
| WebSocket gateways | WebSocket | Configure per-gateway authentication, origins, limits and namespace. |
| Message replies | OnMessage | Receive an event and reply to its originating connection, optionally using a separate reply event. |
| Connection events | OnOpen, OnClose, OnError | Handle connection lifecycle and errors. |
| Connection context | Socket, SocketContext, Payload | Access 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.
| Feature | Public APIs | Usage |
|---|---|---|
| Procedures | Procedure, Query, Mutation | Declare independent routers with validated inputs and guarded handlers. |
| Subscriptions | Subscription | Stream Observable or async-iterable results over HTTP/SSE. |
| Request context | TRPCContext | Access framework requests and responses, identity and cancellation. |
| Router access | rpc, useRpc | Borrow 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.
| Feature | Public APIs | Usage |
|---|---|---|
| MCP catalogs | MCP | Declare independent catalog endpoints with per-endpoint authentication and transport settings. |
| Tools | Tool | Expose validated tool inputs and structured results. |
| Resources and prompts | Resource, Prompt | Provide fixed resources and reusable prompts. |
| Request context | McpContext | Use 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.
| Feature | Public APIs | Usage |
|---|---|---|
| ACP agents | ACP, AcpAgentRuntime | Declare agents with independent paths, policies and HTTP or stdio transport. |
| Agent sessions | AcpSessionContext | Create sessions, send updates, handle prompts and observe cancellation. |
| Agent authentication | authMethods, authenticate | Configure agent authentication and connection-specific session limits. |
Selecting a response or execution style
| Requirement | Use | Execution behavior |
|---|---|---|
| Return one result to an HTTP, GraphQL, or tRPC request | A value, Promise, or unary Observable handler | The first Observable emission provides the result. |
| Push server events to an HTTP client | @SSE | Every event is streamed until completion or cancellation. |
| Exchange messages over a persistent client connection | A WebSocket gateway | Events are processed sequentially per connection. |
| Stream procedure results to a tRPC client | @Subscription | Observable or async-iterable results use HTTP/SSE. |
| Consume broker deliveries | An EBS subscriber | Completion and acknowledgement follow the selected broker’s contract. |
| Execute a CPU-intensive job | A declared worker task | Requests 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.