Realtime API
Generated public TypeScript reference for @relkit/realtime.
Common APIs
For configuration and examples, read realtime, access, react.
Frontend usage
Subscribe to a channel shows the client side of this capability.
Public imports
@relkit/realtime— 75 exports@relkit/realtime/operation-id— 9 exports
All exported APIs
Names link to their complete contracts. Re-exports share their original contract; legacy exports keep their separate identity. Examples link to the API’s inline sample, a maintained repository usage, or the shared module walkthrough.
channel-operations.ts
getChannelPresenceEffect
Reads a channel’s presence snapshot in the Effect path.
Example
Effect.runPromise(getChannelPresenceEffect(channel, {}));
Signature
declare const getChannelPresenceEffect: (
channel: ChannelDescriptorData,
params: unknown,
) => Effect.Effect<
PresenceSnapshot,
ChannelValidationError | RealtimeDispatcherError | RealtimeProviderError,
never
>;
runChannelPromise
Converts an Effect result to the legacy Promise rejection shape.
Throws
TypeError, Error, or the original provider rejection on failure.
Example
await runChannelPromise(triggerChannelEffect(channel, {}, "posted", "hello"));
Signature
declare const runChannelPromise: <A, E>(effect: Effect.Effect<A, E>) => Promise<A>;
triggerChannelEffect
Validates and dispatches one channel event in the Effect path.
Example
Effect.runPromise(triggerChannelEffect(channel, {}, "posted", "hello"));
Signature
declare const triggerChannelEffect: (
channel: ChannelDescriptorData,
params: unknown,
event: string,
payload: unknown,
options?: ChannelTriggerOptions | undefined,
) => Effect.Effect<
TriggerReceipt,
ChannelValidationError | RealtimeDispatcherError | RealtimeProviderError,
never
>;
channel-policy.ts
copyChannelClient
Copies a client policy.
Throws
TypeError for a malformed policy.
Example
copyChannelClient({ public: true });
Signature
declare const copyChannelClient: (value: unknown) => ChannelClientPolicy<ChannelGuard> | undefined;
copyChannelClientEffect
Copies an authored client policy into a descriptor value.
Example
Effect.runSync(copyChannelClientEffect({ public: true }));
Signature
declare const copyChannelClientEffect: (
value: unknown,
) => Effect.Effect<
{ public: true; authorize?: never } | { authorize: ChannelGuard; public?: never } | undefined,
ChannelValidationError,
never
>;
copyChannelPresence
Copies a presence policy.
Throws
TypeError for malformed or unprotected member presence.
Example
copyChannelPresence("count", undefined);
Signature
declare const copyChannelPresence: (
value: unknown,
client: ChannelClientPolicy<ChannelGuard> | undefined,
) => ChannelPresence | undefined;
copyChannelPresenceEffect
Copies presence and checks member authorization.
Example
Effect.runSync(copyChannelPresenceEffect("count", undefined));
Signature
declare const copyChannelPresenceEffect: (
value: unknown,
client: ChannelClientPolicy<ChannelGuard> | undefined,
) => Effect.Effect<
| "count"
| {
member: MemberPresenceDescriptor["member"];
resolve: MemberPresenceDescriptor["resolve"];
maxMembers: number;
}
| undefined,
ChannelValidationError,
never
>;
copyChannelReplay
Copies replay limits.
Throws
TypeError for invalid limits.
Example
copyChannelReplay({ retentionMs: 100, maxEvents: 10 });
Signature
declare const copyChannelReplay: (value: unknown) => ChannelReplay | undefined;
copyChannelReplayEffect
Copies replay limits into a descriptor value.
Example
Effect.runSync(copyChannelReplayEffect({ retentionMs: 100, maxEvents: 10 }));
Signature
declare const copyChannelReplayEffect: (
value: unknown,
) => Effect.Effect<
{ retentionMs: number; maxEvents: number } | undefined,
ChannelValidationError,
never
>;
channel-validation.ts
assertChannelSchema
Asserts a Standard Schema v1 validator.
Throws
TypeError for a malformed schema.
Example
assertChannelSchema(schema, "params");
Signature
declare const assertChannelSchema: (
value: unknown,
name: string,
) => asserts value is StandardSchemaV1;
assertChannelSchemaEffect
Validates a schema shape with a tagged error.
Example
Effect.runSync(assertChannelSchemaEffect(schema, "params"));
Signature
declare const assertChannelSchemaEffect: (
value: unknown,
name: string,
) => Effect.Effect<undefined, ChannelValidationError, never>;
copyChannelEvents
Copies an event schema map.
Throws
TypeError for invalid names or schemas.
Example
copyChannelEvents({ changed: schema });
Signature
declare const copyChannelEvents: (value: unknown) => Readonly<Record<string, StandardSchemaV1>>;
copyChannelEventsEffect
Copies and normalizes an authored event schema map.
Example
Effect.runSync(copyChannelEventsEffect({ changed: schema }));
Signature
declare const copyChannelEventsEffect: (
value: unknown,
) => Effect.Effect<
Readonly<Record<string, StandardSchemaV1<unknown, unknown>>>,
ChannelValidationError,
never
>;
isChannelSchema
Checks a Standard Schema v1 validator.
Example
isChannelSchema(schema);
Signature
declare const isChannelSchema: (value: unknown) => value is StandardSchemaV1;
isChannelSchemaEffect
Checks the Standard Schema v1 shape in the Effect path.
Example
Effect.runSync(isChannelSchemaEffect(schema));
Signature
declare const isChannelSchemaEffect: (value: unknown) => Effect.Effect<boolean, never, never>;
isRecord
Checks whether a value is a non-array record.
Example
isRecord({});
Signature
declare const isRecord: (value: unknown) => value is Record<PropertyKey, unknown>;
isRecordEffect
Checks an unknown value for the record shape in the Effect path.
Example
Effect.runSync(isRecordEffect({}));
Signature
declare const isRecordEffect: (value: unknown) => Effect.Effect<boolean, never, never>;
runChannelValidation
Runs a validation effect while retaining the public TypeError contract.
Throws
TypeError for a tagged validation failure.
Example
runChannelValidation(copyChannelEventsEffect({ posted: schema }));
Signature
declare const runChannelValidation: <A>(effect: Effect.Effect<A, ChannelValidationError>) => A;
validateChannelValue
Validates a value through the Promise compatibility API.
Throws
TypeError when validation fails.
Example
await validateChannelValue(schema, value, "params");
Signature
declare const validateChannelValue: (
schema: StandardSchemaV1,
value: unknown,
name: string,
) => Promise<unknown>;
validateChannelValueEffect
Validates a value with a Standard Schema validator.
Example
Effect.runPromise(validateChannelValueEffect(schema, value, "params"));
Signature
declare const validateChannelValueEffect: (
schema: StandardSchemaV1<unknown, unknown>,
value: unknown,
name: string,
) => Effect.Effect<unknown, ChannelValidationError, never>;
channel.ts
defineChannel
Defines a typed channel for validated backend publication and observation.
Throws
TypeError for invalid channel options.
Example
import { defineChannel } from "@relkit/realtime";
import { z } from "@relkit/schema";
const alerts = defineChannel({
id: "alerts",
params: z.object({}),
events: { posted: z.string() },
});
Signature
declare const defineChannel: <
const Id extends string,
const ParamsSchema extends StandardSchemaV1,
const Events extends Readonly<Record<string, StandardSchemaV1>>,
const Client extends ChannelClientPolicy<ChannelGuard<InferOutput<ParamsSchema>>> | undefined,
const Presence extends ChannelPresence<InferOutput<ParamsSchema>> | undefined = undefined,
>(
options: DefineChannelOptions<Id, ParamsSchema, Events, Client, Presence>,
) => ChannelDescriptor<Id, ParamsSchema, Events, Client, Presence>;
Since v0.4.0
Backend and frontend example
Backend — these maintained files define the operation used by the frontend below.
/** Declares public posted-announcement events with five-minute replay retention and a thousand-event limit. */
import { defineChannel } from "@relkit/app/realtime";
import { z } from "@relkit/app/schema";
const announcements = defineChannel({
id: "announcements.feed",
params: z.object({}),
events: { posted: z.object({ message: z.string(), postedAt: z.string() }) },
client: { public: true },
replay: { retentionMs: 300_000, maxEvents: 1_000 },
});
export default announcements;
Frontend
After frontend setup and pulling the commerce contract, render
this component under the provider. It subscribes to this declaration’s announcements.feed channel:
"use client";
/** Combines the commerce announcement query with channel invalidation and reconnect recovery. */
import { useChannel, useRoute } from "@relkit/client/react";
/** Restores authoritative messages on publication, catch-up, and replay gaps.
* @returns The current messages with query failure and channel status feedback. */
export function Announcements() {
const messages = useRoute("GET /announcements", { input: {} });
const channel = useChannel("announcements.feed", {
params: {},
on: {
posted: () => {
void messages.refetch();
},
},
onCaughtUp: async () => {
await messages.refetch();
},
onGap: async () => {
await messages.refetch();
},
});
if (messages.isError) return <p role="alert">{messages.error.message}</p>;
return (
<section>
<p role="status">Channel: {channel.status}</p>
{messages.isPending && <p>Loading messages…</p>}
<ul>
{messages.data?.messages.map((message, index) => (
<li key={index}>{message}</li>
))}
</ul>
</section>
);
}
params: {} selects the channel’s empty partition schema. posted is a declared event, so its
callback is checked against the event map. The route query restores the authoritative messages
after updates, catch-up, or replay gaps. Backend trigger() publishes; the browser subscribes.
Reference: useChannel, useRealtime.
Continue with subscription and recovery.
“./channel.types.js” (namespace export)
Re-exports all named exports from the “./channel.types.js” module.
Signature
export * from "./channel.types.js";
defineChannelEffect
Constructs a typed channel descriptor through validated Effect operations.
Example
Effect.runSync(defineChannelEffect({ id: "news", params: schema, events: { posted: schema } }));
Signature
declare const defineChannelEffect: <
const Id extends string,
const ParamsSchema extends StandardSchemaV1,
const Events extends Readonly<Record<string, StandardSchemaV1>>,
const Client extends ChannelClientPolicy<ChannelGuard<InferOutput<ParamsSchema>>> | undefined,
const Presence extends ChannelPresence<InferOutput<ParamsSchema>> | undefined = undefined,
>(
options: DefineChannelOptions<Id, ParamsSchema, Events, Client, Presence>,
) => Effect.Effect<
ChannelDescriptor<Id, ParamsSchema, Events, Client, Presence>,
ChannelValidationError,
never
>;
getChannelPresenceEffect
Signature
declare const getChannelPresenceEffect: (
channel: ChannelDescriptorData,
params: unknown,
) => Effect.Effect<
PresenceSnapshot,
ChannelValidationError | RealtimeDispatcherError | RealtimeProviderError,
never
>;
isChannelDescriptor
Checks for a channel descriptor.
Example
isChannelDescriptor(channel);
Signature
declare const isChannelDescriptor: (value: unknown) => value is ChannelDescriptorAny;
isChannelDescriptorEffect
Checks for a channel descriptor in the Effect path.
Example
Effect.runSync(isChannelDescriptorEffect(channel));
Signature
declare const isChannelDescriptorEffect: (value: unknown) => Effect.Effect<boolean, never, never>;
triggerChannelEffect
Signature
declare const triggerChannelEffect: (
channel: ChannelDescriptorData,
params: unknown,
event: string,
payload: unknown,
options?: ChannelTriggerOptions | undefined,
) => Effect.Effect<
TriggerReceipt,
ChannelValidationError | RealtimeDispatcherError | RealtimeProviderError,
never
>;
channel.types.ts
ChannelClientPolicy (type alias)
Public access or an authorization guard, exclusively.
Example
const policy: ChannelClientPolicy<ChannelGuard> = { public: true };
Signature
type ChannelClientPolicy<Guard> =
| { readonly public: true; readonly authorize?: never }
| { readonly authorize: Guard; readonly public?: never };
ChannelDescriptor (type alias)
A typed channel descriptor with backend publication methods.
Example
const channel: ChannelDescriptorAny = defineChannel(options);
Signature
type ChannelDescriptor<
Id extends string,
ParamsSchema extends StandardSchemaV1,
Events extends Readonly<Record<string, StandardSchemaV1>>,
Client extends ChannelClientPolicy<ChannelGuard<InferOutput<ParamsSchema>>> | undefined,
Presence extends ChannelPresence<InferOutput<ParamsSchema>> | undefined,
> = DescriptorBase<"channel", Id> & {
readonly params: ParamsSchema;
readonly events: Events;
readonly profile?: string;
readonly client?: Client;
readonly replay?: ChannelReplay;
readonly presence?: Presence;
/** Validates and publishes one event through the bound dispatcher.
* @param params - Schema input for channel parameters.
* @param event - One of the declared event names.
* @param payload - Input for the selected event schema.
* @param options - Optional idempotency key.
* @returns A trigger receipt or validation/provider rejection.
* @example await channel.trigger({ orderId: "o1" }, "changed", { status: "paid" });
*/
readonly trigger: <Name extends Extract<keyof Events, string>>(
params: InferInput<ParamsSchema>,
event: Name,
payload: InferInput<Events[Name]>,
options?: { readonly idempotencyKey?: OperationId },
) => Promise<TriggerReceipt>;
} & ([Presence] extends [undefined]
? {}
: {
/** Reads validated presence through the bound dispatcher.
* @param params - Schema input for channel parameters.
* @returns Count or member presence, or a validation/provider rejection.
* @example await channel.getPresence({ orderId: "o1" });
*/
readonly getPresence: (
params: InferInput<ParamsSchema>,
) => Promise<PresenceResult<Presence>>;
});
ChannelDescriptorAny (type alias)
Erased descriptor type retained for existing public API consumers.
Example
const channel: ChannelDescriptorAny = registry.get("news");
Signature
type ChannelDescriptorAny = ChannelDescriptor<
string,
StandardSchemaV1,
Readonly<Record<string, StandardSchemaV1>>,
ChannelClientPolicy<ChannelGuard> | undefined,
ChannelPresence | undefined
>;
ChannelDescriptorData (type alias)
Descriptor data read by provider and transport boundaries. Typed trigger methods remain on ChannelDescriptor; providers read only this data.
Example
const data: ChannelDescriptorData = defineChannel(options);
Signature
type ChannelDescriptorData = DescriptorBase<"channel", string> & {
readonly params: StandardSchemaV1;
readonly events: Readonly<Record<string, StandardSchemaV1>>;
readonly profile?: string;
readonly client?: ChannelClientPolicy<ChannelGuard>;
readonly replay?: ChannelReplay;
readonly presence?: ChannelPresence;
};
ChannelGuard (type alias)
Authorizes channel parameters against an application context.
Example
const allow: ChannelGuard = async () => true;
Signature
type ChannelGuard<Params = unknown, Context = unknown> = (
params: Params,
context: Context,
) => MaybePromise<boolean>;
ChannelPresence (type alias)
Count-only or protected member presence.
Example
const presence: ChannelPresence = "count";
Signature
type ChannelPresence<Params = unknown, Context = unknown> =
"count" | MemberPresenceDescriptor<StandardSchemaV1, Params, Context>;
ChannelReplay (interface)
Retention settings copied into a channel descriptor.
Example
const replay: ChannelReplay = { retentionMs: 60000, maxEvents: 100 };
Signature
export interface ChannelReplay {
readonly retentionMs: number;
readonly maxEvents: number;
}
DefineChannelOptions (interface)
Authored channel options before validation and normalization.
Example
const options: DefineChannelOptions<
"news",
typeof schema,
{ posted: typeof schema },
undefined,
undefined
> = {
id: "news",
params: schema,
events: { posted: schema },
};
Signature
export interface DefineChannelOptions<
Id extends string,
ParamsSchema extends StandardSchemaV1,
Events extends Readonly<Record<string, StandardSchemaV1>>,
Client extends ChannelClientPolicy<ChannelGuard<InferOutput<ParamsSchema>>> | undefined,
Presence extends ChannelPresence<InferOutput<ParamsSchema>> | undefined,
> extends DescriptorMetadata {
readonly id: Id;
readonly params: ParamsSchema;
readonly events: Events;
readonly profile?: string;
readonly client?: Client;
readonly replay?: ChannelReplay;
readonly presence?: Presence;
}
MemberPresenceDescriptor (interface)
Describes validated member presence for a protected channel.
Example
const presence: MemberPresenceDescriptor<typeof schema> = {
member: schema,
resolve: async () => ({ name: "Ada" }),
maxMembers: 10,
};
Signature
export interface MemberPresenceDescriptor<
MemberSchema extends StandardSchemaV1 = StandardSchemaV1,
Params = unknown,
Context = unknown,
> {
readonly member: MemberSchema;
readonly resolve: (params: Params, context: Context) => MaybePromise<InferInput<MemberSchema>>;
readonly maxMembers: number;
}
dispatch.ts
“./dispatch.types.js” (namespace export)
Re-exports all named exports from the “./dispatch.types.js” module.
Signature
export * from "./dispatch.types.js";
RealtimeDispatcherLive
Resolves the currently bound dispatcher when an Effect requests it.
Example
Effect.provide(currentRealtimeDispatcherEffect(), RealtimeDispatcherLive);
Signature
declare const RealtimeDispatcherLive: Layer.Layer<
RealtimeDispatcherService,
RealtimeDispatcherError,
never
>;
RealtimeDispatcherService (class)
Injectable dispatcher for Effect-native channel operations.
Example
Effect.provide(currentRealtimeDispatcherEffect(), RealtimeDispatcherLive);
Signature
declare class RealtimeDispatcherService
currentRealtimeDispatcher
Returns the dispatcher bound to the current generation.
Throws
Error when no dispatcher is active.
Example
currentRealtimeDispatcher();
Signature
declare const currentRealtimeDispatcher: () => RealtimeDispatcher;
currentRealtimeDispatcherEffect
Resolves the current dispatcher with a typed missing-binding error.
Example
Effect.runPromise(currentRealtimeDispatcherEffect());
Signature
declare const currentRealtimeDispatcherEffect: () => Effect.Effect<
RealtimeDispatcher,
RealtimeDispatcherError,
never
>;
runWithRealtimeDispatcher
Executes an action under a dispatcher scope.
Throws
The action’s synchronous error or an Effect runtime defect.
Example
runWithRealtimeDispatcher(dispatcher, () => channel.trigger({}, "posted", "hello"));
Signature
declare const runWithRealtimeDispatcher: <Value>(
dispatcher: RealtimeDispatcher,
action: () => Value,
) => Value;
runWithRealtimeDispatcherEffect
Runs an action with a dispatcher in async-local generation scope.
Example
Effect.runSync(runWithRealtimeDispatcherEffect(dispatcher, () => 1));
Signature
declare const runWithRealtimeDispatcherEffect: <Value>(
dispatcher: RealtimeDispatcher,
action: (signal: AbortSignal) => Value,
) => Effect.Effect<Awaited<Value>, RealtimeActionError, never>;
setActiveRealtimeDispatcher
Sets the fallback dispatcher for code outside a generation scope.
Example
setActiveRealtimeDispatcher(dispatcher);
Signature
declare const setActiveRealtimeDispatcher: (dispatcher: RealtimeDispatcher | undefined) => void;
setActiveRealtimeDispatcherEffect
Changes the fallback dispatcher in the Effect path.
Example
Effect.runSync(setActiveRealtimeDispatcherEffect(dispatcher));
Signature
declare const setActiveRealtimeDispatcherEffect: (
dispatcher: RealtimeDispatcher | undefined,
) => Effect.Effect<void, never, never>;
dispatch.types.ts
ChannelTriggerOptions (interface)
Options attached to a channel trigger request.
Example
const options: ChannelTriggerOptions = { idempotencyKey: id };
Signature
export interface ChannelTriggerOptions {
readonly idempotencyKey?: OperationId;
}
RealtimeDispatcher (interface)
A generation-bound dispatcher for validated realtime operations.
Example
const dispatcher: RealtimeDispatcher = {
trigger: async () => receipt,
getPresence: async () => presence,
};
Signature
export interface RealtimeDispatcher {
/** Publishes a validated event.
* @param request - Channel, parameters, event, payload, and optional idempotency key.
* @param signal - Optional cancellation signal for in-flight work.
* @returns A trigger receipt or a provider rejection.
* @example await dispatcher.trigger({ channel, params: {}, event: "posted", payload: "hello" });
*/
readonly trigger: (
request: {
readonly channel: ChannelDescriptorData;
readonly params: unknown;
readonly event: string;
readonly payload: unknown;
readonly options?: ChannelTriggerOptions;
},
signal?: AbortSignal,
) => MaybePromise<TriggerReceipt>;
/** Reads the current presence snapshot.
* @param request - Channel and validated parameters.
* @param signal - Optional cancellation signal for in-flight work.
* @returns Presence snapshot or a provider rejection.
* @example await dispatcher.getPresence({ channel, params: {} });
*/
readonly getPresence: (
request: {
readonly channel: ChannelDescriptorData;
readonly params: unknown;
},
signal?: AbortSignal,
) => MaybePromise<PresenceSnapshot>;
}
index.ts
“./channel.js” (namespace export)
Re-exports all named exports from the “./channel.js” module.
Signature
export * from "./channel.js";
“./dispatch.js” (namespace export)
Re-exports all named exports from the “./dispatch.js” module.
Signature
export * from "./dispatch.js";
“./operation-id.js” (namespace export)
Re-exports all named exports from the “./operation-id.js” module.
Signature
export * from "./operation-id.js";
“./provider-dispatcher.js” (namespace export)
Re-exports all named exports from the “./provider-dispatcher.js” module.
Signature
export * from "./provider-dispatcher.js";
“./provider.js” (namespace export)
Re-exports all named exports from the “./provider.js” module.
Signature
export * from "./provider.js";
“./realtime-errors.js” (namespace export)
Re-exports all named exports from the “./realtime-errors.js” module.
Signature
export * from "./realtime-errors.js";
“./realtime-observability.js” (namespace export)
Re-exports all named exports from the “./realtime-observability.js” module.
Signature
export * from "./realtime-observability.js";
“./realtime-observability.types.js” (namespace export)
Re-exports all named exports from the “./realtime-observability.types.js” module.
Signature
export * from "./realtime-observability.types.js";
“./types.js” (namespace export)
Re-exports all named exports from the “./types.js” module.
Signature
export * from "./types.js";
operation-id.ts
OperationIdEntropy (class)
Injectable random-byte service for operation ID generation.
Example
Effect.provide(createOperationIdEffect(0), OperationIdEntropyLive);
Signature
declare class OperationIdEntropy
OperationIdEntropyLive
Cryptographic entropy for live UUIDv7 creation.
Example
Effect.provide(createOperationIdEffect(0), OperationIdEntropyLive);
Signature
declare const OperationIdEntropyLive: Layer.Layer<OperationIdEntropy, never, never>;
OperationIdError (class)
Compatibility error for invalid or expired operation IDs.
Example
new OperationIdError("OPERATION_ID_INVALID", "Operation ID must be a UUIDv7.");
Signature
declare class OperationIdError { constructor(
readonly code: "OPERATION_ID_INVALID" | "IDEMPOTENCY_WINDOW_EXPIRED",
message: string,
) }
createOperationId
Creates a UUIDv7 operation ID.
Throws
RangeError for an invalid timestamp.
Example
createOperationId(Date.now());
Signature
declare const createOperationId: (now?: number) => OperationId;
createOperationIdEffect
Creates a UUIDv7 ID using Effect Clock and injectable entropy.
Example
Effect.runSync(Effect.provide(createOperationIdEffect(0), OperationIdEntropyLive));
Signature
declare const createOperationIdEffect: (
now: number | undefined,
) => Effect.Effect<OperationId, OperationIdFailure, OperationIdEntropy>;
operationIdTimestamp
Extracts a UUIDv7 timestamp without validating the ID.
Example
operationIdTimestamp(id);
Signature
declare const operationIdTimestamp: (value: string) => number;
operationIdTimestampEffect
Extracts the first 48 timestamp bits without validating UUID syntax.
Example
Effect.runSync(operationIdTimestampEffect(id));
Signature
declare const operationIdTimestampEffect: (value: string) => Effect.Effect<number, never, never>;
parseOperationId
Parses a UUIDv7 operation ID through the compatibility API.
Throws
OperationIdError for an invalid or expired ID.
Example
parseOperationId(id, { now: Date.now() });
Signature
declare const parseOperationId: (value: string, options?: ParseOperationIdOptions) => OperationId;
parseOperationIdEffect
Parses a UUIDv7 operation ID and enforces its receipt window.
Example
Effect.runSync(parseOperationIdEffect(id, { now: Date.now() }));
Signature
declare const parseOperationIdEffect: (
value: string,
options?: ParseOperationIdOptions | undefined,
) => Effect.Effect<OperationId, OperationIdFailure, never>;
operation-id.types.ts
OperationIdEntropyService (interface)
Injectable source of UUIDv7 random bytes.
Example
const source: OperationIdEntropyService = { bytes: () => Effect.succeed(new Uint8Array(16)) };
Signature
export interface OperationIdEntropyService {
/** Produces sixteen independent bytes.
* @returns An Effect of random bytes without a typed failure.
* @example Effect.runSync(source.bytes());
*/
readonly bytes: () => Effect.Effect<Uint8Array>;
}
ParseOperationIdOptions (interface)
Optional receipt-window clock controls for ID parsing.
Example
const options: ParseOperationIdOptions = { now: Date.now(), receiptWindowMs: 60000 };
Signature
export interface ParseOperationIdOptions {
readonly now?: number;
readonly receiptWindowMs?: number;
}
provider-dispatcher.ts
“./provider-dispatcher.types.js” (namespace export)
Re-exports all named exports from the “./provider-dispatcher.types.js” module.
Signature
export * from "./provider-dispatcher.types.js";
RealtimeProviderSource (class)
Injectable profile-to-provider lookup.
Example
Effect.provide(triggerProviderEffect(options, request), providerSourceLayer(options));
Signature
declare class RealtimeProviderSource
createProviderRealtimeDispatcher
Creates a provider-backed realtime dispatcher.
Throws
An Effect runtime defect if construction cannot execute synchronously.
Example
const dispatcher = createProviderRealtimeDispatcher(options);
Signature
declare const createProviderRealtimeDispatcher: (
options: ProviderRealtimeDispatcherOptions,
) => RealtimeDispatcher;
createProviderRealtimeDispatcherEffect
Creates the compatibility dispatcher through the Effect path.
Example
Effect.runSync(createProviderRealtimeDispatcherEffect(options));
Signature
declare const createProviderRealtimeDispatcherEffect: (
options: ProviderRealtimeDispatcherOptions,
) => Effect.Effect<RealtimeDispatcher, never, never>;
limitsForEffect
Signature
declare const limitsForEffect: (
options: ProviderRealtimeDispatcherOptions,
) => Effect.Effect<RealtimeLimits, never, never>;
providerSourceLayer
Builds a provider resolver layer from authored dispatcher options.
Example
providerSourceLayer(options);
Signature
declare const providerSourceLayer: (
options: ProviderRealtimeDispatcherOptions,
) => Layer.Layer<RealtimeProviderSource, never, never>;
readProviderPresenceEffect
Reads presence from a resolved provider.
Example
Effect.runPromise(
Effect.provide(readProviderPresenceEffect(options, request), providerSourceLayer(options)),
);
Signature
declare const readProviderPresenceEffect: (
options: ProviderRealtimeDispatcherOptions,
request: { readonly channel: ChannelDescriptorData; readonly params: unknown },
) => Effect.Effect<PresenceSnapshot, RealtimeProviderError, RealtimeProviderSource>;
triggerProviderEffect
Sends a validated trigger to a resolved provider.
Example
Effect.runPromise(
Effect.provide(triggerProviderEffect(options, request), providerSourceLayer(options)),
);
Signature
declare const triggerProviderEffect: (
options: ProviderRealtimeDispatcherOptions,
request: {
readonly channel: ChannelDescriptorData;
readonly params: unknown;
readonly event: string;
readonly payload: unknown;
readonly options?: ChannelTriggerOptions;
},
) => Effect.Effect<
TriggerReceipt,
RealtimeProviderError | OperationIdFailure,
RealtimeProviderSource
>;
provider-dispatcher.types.ts
ProviderRealtimeDispatcherOptions (interface)
Configuration for a provider-backed generation dispatcher.
Example
const options: ProviderRealtimeDispatcherOptions = {
applicationId: "app",
environment: "dev",
generationId: "g1",
publicFingerprint: "p1",
provider: async () => provider,
};
Signature
export interface ProviderRealtimeDispatcherOptions {
readonly applicationId: string;
readonly environment: string;
readonly generationId: string;
readonly publicFingerprint: string;
/** Resolves a provider for one profile.
* @param profile - Validated profile name.
* @param signal - Optional cancellation signal for an in-flight lookup.
* @returns A provider or lookup rejection.
* @example await options.provider("default", controller.signal);
*/
readonly provider: (
profile: string,
signal?: AbortSignal,
) => Promise<RealtimeProvider> | RealtimeProvider;
readonly limits?: Partial<RealtimeLimits>;
}
RealtimeProviderSourceService (interface)
Injectable provider resolver used by Effect-native dispatcher operations.
Example
const source: RealtimeProviderSourceService = { resolve: () => Effect.succeed(provider) };
Signature
export interface RealtimeProviderSourceService {
/** Resolves the provider configured for one profile.
* @param profile - Validated profile name.
* @returns An Effect of the provider or RealtimeProviderError.
* @example Effect.runPromise(source.resolve("default"));
*/
readonly resolve: (profile: string) => Effect.Effect<RealtimeProvider, RealtimeProviderError>;
}
provider-encoding.ts
digestEffect
Hashes canonical JSON for partitions and idempotency.
Example
Effect.runSync(digestEffect({ id: "one" }));
Signature
declare const digestEffect: (value: unknown) => Effect.Effect<string, RealtimeProviderError, never>;
encodedBytesEffect
Measures an encoded event envelope.
Example
Effect.runSync(encodedBytesEffect({ event: "posted" }));
Signature
declare const encodedBytesEffect: (
value: unknown,
) => Effect.Effect<number, RealtimeProviderError, never>;
providerScopeEffect
Computes the immutable portion of a provider scope.
Example
Effect.runSync(providerScopeEffect(options, "news", "default", {}));
Signature
declare const providerScopeEffect: (
options: ProviderRealtimeDispatcherOptions,
channelId: string,
profile: string,
params: unknown,
) => Effect.Effect<
{
applicationId: string;
environment: string;
channelId: string;
partition: string;
profile: string;
policyEpoch: string;
providerEpoch: string;
identityScope: string;
sessionEpoch: string;
},
RealtimeProviderError,
never
>;
provider-limits.ts
limitsForEffect
Computes effective provider limits in the Effect path.
Example
Effect.runSync(limitsForEffect(options));
Signature
declare const limitsForEffect: (
options: ProviderRealtimeDispatcherOptions,
) => Effect.Effect<RealtimeLimits, never, never>;
provider.ts
“./provider.types.js” (namespace export)
Re-exports all named exports from the “./provider.types.js” module.
Signature
export * from "./provider.types.js";
provider.types.ts
AcquirePresenceLease (type alias)
Initial lease request.
Example
const request: AcquirePresenceLease = lease;
Signature
type AcquirePresenceLease = PresenceLeaseRequest;
AppendChannelEvent (interface)
Validated event append request including idempotency and retention settings.
Example
const append: AppendChannelEvent = {
...scope,
event: "posted",
payload: "hi",
encodedBytes: 42,
occurredAt: new Date().toISOString(),
limits,
};
Signature
export interface AppendChannelEvent extends RealtimeScope {
readonly operationId?: OperationId;
readonly semanticDigest?: string;
readonly event: string;
readonly payload: unknown;
readonly encodedBytes: number;
readonly occurredAt: string;
readonly receiptExpiresAt?: string;
readonly retentionMs?: number;
readonly maxEvents?: number;
readonly limits: RealtimeLimits;
}
AppendReceiptLookup (type alias)
Provider receipt lookup result.
Example
const result: AppendReceiptLookup = await provider.lookupAppendReceipt(lookup);
Signature
type AppendReceiptLookup = ReceiptLookup<TriggerReceipt>;
ChannelEventPage (interface)
Ordered provider replay page and its next checkpoint.
Example
const page: ChannelEventPage = await provider.readAfter(read);
Signature
export interface ChannelEventPage {
readonly events: readonly ChannelEventRecord[];
readonly checkpoint: ChannelCheckpoint;
readonly hasMore: boolean;
readonly gap?: "expired" | "foreign" | "future" | "policy" | "session" | "provider-reset";
}
LookupAppendReceipt (interface)
Provider lookup for an existing idempotent append receipt.
Example
const lookup: LookupAppendReceipt = {
...scope,
operationId: id,
semanticDigest: digest,
receiptWindowMs: 60000,
now: new Date().toISOString(),
};
Signature
export interface LookupAppendReceipt extends RealtimeScope {
readonly operationId: OperationId;
readonly semanticDigest: string;
readonly receiptWindowMs: number;
readonly now: string;
}
PresenceLeaseRequest (interface)
Presence lease mutation request; providers own lease persistence.
Example
const lease: PresenceLeaseRequest = {
...scope,
leaseId: "l1",
connectionId: "c1",
expiresAt: new Date().toISOString(),
maxMembers: 10,
maxConnections: 10,
};
Signature
export interface PresenceLeaseRequest extends RealtimeScope {
readonly leaseId: string;
readonly connectionId: string;
readonly opaqueMemberId?: string;
readonly memberInfo?: unknown;
readonly expiresAt: string;
readonly maxMembers: number;
readonly maxConnections: number;
}
ReadChannelEvents (interface)
Bounded replay page request.
Example
const read: ReadChannelEvents = { ...scope, limit: 10, maxEncodedBytes: 4096 };
Signature
export interface ReadChannelEvents extends RealtimeScope {
readonly after?: ChannelCheckpoint;
readonly limit: number;
readonly maxEncodedBytes: number;
}
ReadPresenceRequest (type alias)
Presence read with a bounded member count.
Example
const read: ReadPresenceRequest = { ...scope, maxMembers: 10 };
Signature
type ReadPresenceRequest = RealtimeScope & {
readonly maxMembers: number;
};
RealtimeLimits (interface)
Provider-enforced bounds for event, connection, partition, and presence storage.
Example
const limits: RealtimeLimits = {
maxEventBytes: 1024,
maxRetainedBytes: 4096,
maxPartitions: 10,
maxConnections: 10,
maxPresenceMembers: 10,
};
Signature
export interface RealtimeLimits {
readonly maxEventBytes: number;
readonly maxRetainedBytes: number;
readonly maxPartitions: number;
readonly maxConnections: number;
readonly maxPresenceMembers: number;
}
RealtimeProvider (interface)
Backend contract for ordered events, idempotency, and presence. The caller owns aborting waitAfter; provider implementations own their internal resources.
Example
const epoch = await provider.getEpoch();
Signature
export interface RealtimeProvider {
readonly capabilities: {
readonly replay: "memory" | "retained";
readonly presenceScope: "process" | "shared";
readonly durability: "volatile" | "filesystem" | "redis-configured";
};
/** Reads the provider generation epoch.
* @param signal - Optional cancellation signal for in-flight work.
* @returns The epoch or a provider rejection.
* @example await provider.getEpoch();
*/
getEpoch(signal?: AbortSignal): Promise<string>;
/** Appends a validated event.
* @param request - Event and scope metadata.
* @param signal - Optional cancellation signal; an implementation may already have committed an append when aborted.
* @returns A receipt or a provider rejection.
* @example await provider.append(append);
*/
append(request: AppendChannelEvent, signal?: AbortSignal): Promise<TriggerReceipt>;
/** Looks up an idempotent append receipt.
* @param request - Receipt lookup key and time window.
* @returns Existing receipt state or a provider rejection.
* @example await provider.lookupAppendReceipt(lookup);
*/
lookupAppendReceipt(request: LookupAppendReceipt): Promise<AppendReceiptLookup>;
/** Reads an ordered, bounded event page.
* @param request - Replay cursor and limits.
* @returns A page or a provider rejection.
* @example await provider.readAfter(read);
*/
readAfter(request: ReadChannelEvents): Promise<ChannelEventPage>;
/** Waits for events until a deadline or caller abort.
* @param request - Cursor, deadline, and caller-owned abort signal.
* @returns Completion or a provider rejection.
* @example await provider.waitAfter(wait);
*/
waitAfter(request: WaitForChannelEvents): Promise<void>;
/** Reads current presence.
* @param request - Scope and member limit.
* @param signal - Optional cancellation signal for in-flight work.
* @returns Presence snapshot or a provider rejection.
* @example await provider.readPresence(read);
*/
readPresence(request: ReadPresenceRequest, signal?: AbortSignal): Promise<PresenceSnapshot>;
/** Acquires a presence lease.
* @param request - Lease identity, expiry, and limits.
* @returns Updated presence or a provider rejection.
* @example await provider.acquirePresence(lease);
*/
acquirePresence(request: AcquirePresenceLease): Promise<PresenceSnapshot>;
/** Renews a presence lease.
* @param request - Existing lease and next expiry.
* @returns Updated presence or a provider rejection.
* @example await provider.renewPresence(lease);
*/
renewPresence(request: RenewPresenceLease): Promise<PresenceSnapshot>;
/** Releases a presence lease.
* @param request - Existing lease without expiry.
* @returns Updated presence or a provider rejection.
* @example await provider.releasePresence(release);
*/
releasePresence(request: ReleasePresenceLease): Promise<PresenceSnapshot>;
}
ReleasePresenceLease (type alias)
Lease release request without an expiry.
Example
const request: ReleasePresenceLease = {
...scope,
leaseId: "l1",
connectionId: "c1",
maxMembers: 10,
maxConnections: 10,
};
Signature
type ReleasePresenceLease = Omit<PresenceLeaseRequest, "expiresAt">;
RenewPresenceLease (type alias)
Existing lease renewal request.
Example
const request: RenewPresenceLease = lease;
Signature
type RenewPresenceLease = PresenceLeaseRequest;
WaitForChannelEvents (interface)
Abortable long-poll request owned by its caller.
Example
const wait: WaitForChannelEvents = {
...scope,
after: checkpoint,
deadlineMs: Date.now() + 1000,
signal: controller.signal,
};
Signature
export interface WaitForChannelEvents extends RealtimeScope {
readonly after: ChannelCheckpoint;
readonly deadlineMs: number;
readonly signal: AbortSignal;
}
realtime-errors.ts
ChannelValidationError (class)
Invalid authored channel data or an invalid channel operation.
Example
new ChannelValidationError({ operation: "channel.define", reason: "Missing events" });
Signature
declare class ChannelValidationError
OperationIdFailure (class)
An operation ID is malformed or outside its receipt window.
Example
new OperationIdFailure({ code: "OPERATION_ID_INVALID", reason: "Invalid ID" });
Signature
declare class OperationIdFailure
RealtimeActionError (class)
An action thrown while entering a dispatcher scope.
Example
new RealtimeActionError({ operation: "dispatch.runWith", cause: new Error("failed") });
Signature
declare class RealtimeActionError
RealtimeDispatcherError (class)
A realtime dispatcher was required but none was bound.
Example
new RealtimeDispatcherError({
operation: "dispatch.current",
reason: "No realtime dispatcher is active.",
});
Signature
declare class RealtimeDispatcherError
RealtimeProviderError (class)
A provider operation failed at the external adapter boundary.
Example
new RealtimeProviderError({ operation: "provider.trigger", cause: new Error("offline") });
Signature
declare class RealtimeProviderError
realtime-observability.ts
RealtimeTelemetry (class)
Injectable realtime telemetry boundary.
Example
Effect.provide(Effect.succeed(1), RealtimeTelemetryLive);
Signature
declare class RealtimeTelemetry
RealtimeTelemetryLive
Live span and metric observer for realtime operations.
Example
Effect.provide(Effect.succeed(1), RealtimeTelemetryLive);
Signature
declare const RealtimeTelemetryLive: Layer.Layer<RealtimeTelemetry, never, never>;
observeRealtime
Observes a realtime operation using the supplied test service or live metrics.
Example
observeRealtime("channel.define", Effect.succeed(undefined));
Signature
declare const observeRealtime: <A, E, R>(
operation: RealtimeOperation,
effect: Effect.Effect<A, E, R>,
) => Effect.Effect<A, E, R>;
realtime-observability.types.ts
RealtimeOperation (type alias)
Bounded names used for realtime spans and metrics.
Example
const operation: RealtimeOperation = "channel.define";
Signature
type RealtimeOperation =
| "channel.define"
| "channel.isDescriptor"
| "channel.trigger"
| "channel.getPresence"
| "channel.copyClient"
| "channel.copyPresence"
| "channel.copyEvents"
| "channel.copyReplay"
| "channel.assertSchema"
| "channel.isSchema"
| "channel.validateValue"
| "channel.isRecord"
| "dispatch.setActive"
| "dispatch.runWith"
| "dispatch.current"
| "operationId.parse"
| "operationId.timestamp"
| "operationId.create"
| "provider.createDispatcher"
| "provider.resolve"
| "provider.trigger"
| "provider.getPresence"
| "provider.scope"
| "provider.digest"
| "provider.bytes"
| "provider.limits";
RealtimeTelemetryService (interface)
Substitutable observer for realtime operation tests and application telemetry.
Example
const observer: RealtimeTelemetryService = { observe: (_name, effect) => effect };
Signature
export interface RealtimeTelemetryService {
/** Surrounds an operation without changing its result.
* @param operation - A stable, bounded operation name.
* @param effect - The operation to observe.
* @returns The same success and error channels with telemetry attached.
* @example observer.observe("channel.define", Effect.succeed(undefined));
*/
readonly observe: <A, E, R>(
operation: RealtimeOperation,
effect: Effect.Effect<A, E, R>,
) => Effect.Effect<A, E, R>;
}
types.ts
ChannelCheckpoint (interface)
Replay cursor bound to the provider, policy, and session epochs.
Example
const checkpoint: ChannelCheckpoint = {
...scope,
sequence: "1",
historyStart: "1",
expiresAt: new Date().toISOString(),
};
Signature
export interface ChannelCheckpoint extends RealtimeScope {
readonly sequence: string;
readonly historyStart: string;
readonly expiresAt: string;
}
ChannelEventRecord (interface)
Stored channel event and checkpoint returned by replay.
Example
const record: ChannelEventRecord = {
eventId: "e1",
event: "posted",
payload: "hi",
checkpoint,
encodedBytes: 20,
createdAt: new Date().toISOString(),
};
Signature
export interface ChannelEventRecord {
readonly eventId: string;
readonly event: string;
readonly payload: unknown;
readonly checkpoint: ChannelCheckpoint;
readonly encodedBytes: number;
readonly createdAt: string;
}
ChannelGrant (interface)
Authorized channel grant with a bounded replay window.
Example
const grant: ChannelGrant = {
...scope,
grantId: "g",
principalScope: "user",
historyStart: "1",
expiresAt: new Date().toISOString(),
};
Signature
export interface ChannelGrant extends RealtimeScope {
readonly grantId: string;
readonly principalScope: string;
readonly historyStart: string;
readonly expiresAt: string;
}
CountPresence (interface)
Count-only presence snapshot and freshness state.
Example
const count: CountPresence = { connections: 1, status: "fresh", revision: "1", scope: "shared" };
Signature
export interface CountPresence {
readonly connections: number | undefined;
readonly status: "loading" | "fresh" | "stale" | "error";
readonly revision: string | undefined;
readonly scope: "process" | "shared";
}
MemberPresence (interface)
Presence snapshot with a bounded member list.
Example
const members: MemberPresence<string> = {
connections: 1,
status: "fresh",
revision: "1",
scope: "shared",
memberCount: 1,
members: [{ id: "opaque", info: "Ada" }],
membersTruncated: false,
};
Signature
export interface MemberPresence<Member = unknown> extends CountPresence {
readonly memberCount: number | undefined;
readonly members: readonly PresenceMember<Member>[];
readonly membersTruncated: boolean;
}
PresenceMember (interface)
Member identity and validated application-visible information.
Example
const member: PresenceMember<string> = { id: "opaque", info: "Ada" };
Signature
export interface PresenceMember<Member = unknown> {
readonly id: string;
readonly info: Member;
}
PresenceSnapshot (type alias)
Count-only or member presence returned by a provider.
Example
const snapshot: PresenceSnapshot = await provider.readPresence(read);
Signature
type PresenceSnapshot<Member = unknown> = CountPresence | MemberPresence<Member>;
RealtimeScope (interface)
Identity and partition coordinates shared by all realtime provider requests.
Example
const scope: RealtimeScope = {
applicationId: "app",
environment: "dev",
channelId: "news",
partition: "p",
profile: "default",
policyEpoch: "v1",
providerEpoch: "e1",
identityScope: "public",
sessionEpoch: "s1",
};
Signature
export interface RealtimeScope extends ExpectedClientIdentity {
readonly applicationId: string;
readonly environment: string;
readonly tenantScope?: string;
readonly channelId: string;
readonly partition: string;
readonly profile: string;
readonly policyEpoch: string;
readonly providerEpoch: string;
}
TriggerReceipt (interface)
Provider acknowledgement for an accepted channel event.
Example
const receipt: TriggerReceipt = await channel.trigger({}, "posted", "hi");
Signature
export interface TriggerReceipt {
readonly accepted: true;
readonly operationId?: OperationId;
readonly eventId: string;
readonly checkpoint: ChannelCheckpoint;
readonly profile: string;
readonly providerEpoch: string;
readonly duplicate: boolean;
}