Core Concepts
From platform endpoints to connections, services, and session-bound resources.
Each Nexus instance connects platform channels to a common model of sessions, services, and remote resources:
Resources include service proxies, remote refs, and callbacks. Either runtime can provide and call services. Endpoints supply the ports that carry messages over the platform channel.
The Nexus Instance
A context is a JavaScript execution environment, such as an extension page, iframe, or process. A Nexus instance manages connections and resources for one communication domain within that context.
Think of it as a virtual network interface with service and resource management above it: local providers, peer sessions, pending calls, and remote references.
import { Nexus } from "@nexus-js/core";
import type { ChromeAdapterModel } from "@nexus-js/chrome";
const app = new Nexus<ChromeAdapterModel>();This creates the runtime. Configure its endpoint before connecting;
ChromeAdapterModel supplies the platform-specific types described below.
A context can host separate instances for extension and iframe communication. Each owns its configuration, providers, and sessions, without automatic routing between instances. A domain here is a communication graph, not a DNS name. Use Nexus Relay and resource scopes when the application must explicitly bridge selected services between adjacent graphs.
Endpoints And Adapters
An Endpoint provides Core with a reliable, bidirectional, point-to-point communication abstraction over the platform transport. It establishes or accepts channels and exposes their local ends as Ports.
An adapter provides the platform’s Endpoint implementation, target types, and setup helpers. Which peers can connect directly depends on that platform.
Port: An Established Channel
A Port (IPort) is the local send/receive handle for one established channel
to one peer. Each end has its own Port; a Port always sends to the same peer
channel. It may wrap a native chrome.runtime.Port or MessagePort, or a channel
constructed by the adapter.
Its responsibilities are small:
port.postMessage(message); // Send to this channel's peer.
port.onMessage(handleMessage); // Receive from that peer.
port.onDisconnect(handleDisconnect); // Observe channel loss.
port.close(); // Close the channel.Endpoint supplies the channel; Port carries its messages. Core then adds the handshake, identity, and service protocol. An open Port is not yet a ready Nexus Connection. Channel reliability does not mean automatic reconnection or RPC retries.
Here, “reliable” means preserving message boundaries and send order in each direction, without introducing duplicates or silently skipping messages in the middle. A successful send only means local acceptance, not remote receipt or execution; when the channel fails, unconfirmed messages may or may not have arrived.
A disconnect notification means this end has observed or declared the channel unusable. Detection is adapter-specific, may be delayed, and need not happen at both ends simultaneously. A terminated Port never resumes or switches to a new channel; reconnecting creates a new Port and requires a new Core handshake.
Endpoint: Providing Ports
The essential implementation looks like this:
// Conceptual implementation: openChannel, onIncomingChannel, and observe
// stand for platform-specific code supplied by the adapter.
const endpoint: IEndpoint<Model> = {
async connect(target) {
const port = await openChannel(target);
return { port, connectionMeta: observe(port) };
},
listen(accept) {
onIncomingChannel((port) => {
accept(port, observe(port));
});
},
};connect(target) returns an outgoing port; listen(accept) delivers incoming
ports through the callback. Each comes with local connectionMeta. An endpoint
may support either direction or both.
This sketch omits setup, target matching, and shutdown. Applications normally use
an adapter helper such as usingBackgroundScript() instead of implementing it.
The Adapter Model
An AdapterModel defines the domain’s address, identity, and connection-fact
types: ConnectionTarget, ContextMeta, and ConnectionMeta. Chrome and Node IPC
use different shapes, but the roles are the same.
The target starts acquisition; the two metadata values describe the peer session. For a background connecting to a content script:
Target: An Address
Target is a topology address, like a URL: “where should I connect?” Use the adapter’s exact constructor:
chromeTarget.contentFrame({ tabId, frameId: 0 });This addresses the content script in a tab’s top frame. The application chooses
tabId and ensures the script is running. The address is not a live session.
ContextMeta: Declared Identity
ContextMeta answers “who does the peer say it is?” It can include a context
role, workspace, or readiness flag. connection.contextMeta holds the peer’s
accepted identity. The peer can update it with updateIdentity; local consumers
observe changes with subscribeIdentity.
ConnectionMeta: Locally Observed Facts
ConnectionMeta answers “what did my adapter observe?” It contains facts such as Chrome sender details or an IPC authentication result. Identity updates do not change these facts. In a Chrome background:
connection.contextMeta.context; // Remote context's declared role.
connection.connectionMeta.observed.tabId; // Adapter-observed tab, when present.Declared identity is not automatically trusted. AdapterModel associates types; authentication depends on the adapter and policy. See Identity and metadata.
Connections
A Connection is a shared handle to one bidirectional session, held by the
runtime rather than leased exclusively to a caller. connect returns a ready
handle, reusing an eligible session. Either side can provide and call services.
Targeting And Filtering
target supplies the address; where constrains the actual peer, using its
declared identity and local connection facts:
const connection = await app.connect({
target: chromeTarget.contentFrame({ tabId, frameId: 0 }),
where: (contextMeta, connectionMeta) =>
contextMeta.context === "content-script" &&
connectionMeta.observed.tabId === tabId,
});Both constraints must pass. A metadata mismatch does not make Nexus search for another destination.
Without a target, connect({ where }) passively waits for exactly one matching
ready session. It does not discover providers or open connections. Multiple
matches are an ambiguity error.
where selects a connection at acquisition time; it is not a per-call permission
check. Use policy.canConnect for session admission and policy.canCall for
operation authorization. See Connections and
Authorization.
Services And Proxies
A connection identifies the peer. A Token identifies a service that peer provides, associating a shared TypeScript contract with a stable runtime ID:
import { Token } from "@nexus-js/core";
export interface Documents {
read(id: string): Promise<string>;
}
export const DocumentsToken = new Token<Documents>("app:documents");A provider registers the actual local implementation. A service proxy is the consumer’s access to it through a particular connection:
// Provider context: register the implementation on its configured runtime.
owner.provide(DocumentsToken, implementation);
// Consumer context: get a proxy on an acquired connection.
const documents = connection.get(DocumentsToken);get checks the session and its current service catalog synchronously, then
creates a lightweight proxy. It neither contacts a new peer nor creates a remote
business instance. A missing service fails acquisition rather than waiting.
Tokens contain no address or implementation. Several peers can provide the same Token, and one connection can provide access to several services. The contract supplies compile-time types, not runtime schema validation. See Services.
Remote References And Callbacks
Services, refs, and callbacks provide different ways to obtain a proxy resource. Their calls behave alike; their origin and reference ownership differ.
Ordinary values travel as serialized data. References keep behavior at its owner:
- A callback is a function passed for the peer to invoke. Its function and closure stay where it was defined.
- A remote ref accesses an object exported through
ref(...). Its methods execute where the object lives.
For a service extending the basic contract with watch, the two work together:
const observation = await documents.watch(documentId, (change) => {
panel.apply(change); // Runs here, with this local panel.
});
await observation.stop(); // Runs on the remote observation object.The provider returns that object through app.ref(observation) and declares a
RefWrapper<Observation> result in the shared contract. An ordinary returned
object does not automatically become a remote ref.
A root service proxy is a lightweight access handle and needs no release.
Received object and callback refs have reference lifetimes and can be released.
See Callbacks and
Remote resources for complete examples.
For independent cleanup of a related group of calls, refs, and callbacks, use an
explicit connection.createScope(Token) as described in
Nexus Relay and resource scopes.
Remote Operations
Service methods, ref methods, property reads, and remote callback invocations declare lazy remote operations. Their result is a thenable, not an already running Promise: first consumption starts execution.
const call = documents.read("intro"); // Declared, not sent.
await call; // Starts execution.
await call; // Observes the same operation, without sending again.Call the method again to create another operation. Remote callbacks also require
consumption: await onChange(change). A closed-session or released-ref error is
delivered when consumed, not when the operation is declared.
Connection acquisition, service acquisition, and execution can fail independently.
safeGet returns an acquisition Result, not a safe proxy. Use
Nexus.safeCall(call) for an individual operation’s Result.
See Remote calls and
Errors and timeouts.
Lifetimes And Ownership
A runtime owns its shared connections. Dropping a local Connection variable does
not close the session. Calling connection.disconnect() ends it for all users
of that session.
Business activity, reference ownership, and session lifetime are distinct:
await observation.stop(); // End the business observation.
Nexus.release(observation); // Give up this remote reference.
connection.disconnect(); // End the shared session, affecting other users too.These lines illustrate different responsibilities, not a mandatory cleanup sequence.
Release does not invoke stop(). Disconnect does not undo remote side effects.
Disconnect fails pending calls, invalidates access through old proxies and refs, and clears session-held references. Handles can be released earlier, but never move to a replacement session. Reconnect and get fresh handles to resume.
A ConnectionCollection is a fixed, ordered snapshot of session handles. It
neither adds newcomers nor removes or replaces disconnected members. Its get
returns one { connection, result } per member; each success is an ordinary
single-connection proxy, not a multicast proxy. See
Multiple connections and
Connection lifecycle.