@thuum/channels
Installation
Section titled “Installation”npm install @thuum/channels @thuum/transportOverview
Section titled “Overview”@thuum/channels provides schema-validated messaging patterns built on top of @thuum/transport:
createMessageChannel()— One-way messaging with schema validationcreateRequestChannel()— Request/response pattern with automatic correlation and timeout
createMessageChannel(options)
Section titled “createMessageChannel(options)”Creates a channel for one-way messaging with a paired sender and receiver.
import { createMessageChannel } from "@thuum/channels";import { createTransport } from "@thuum/transport";
const channel = createMessageChannel({ schemas: { notification: { message: { parse: (data) => ({ value: data }) }, }, }, transport: createTransport({ type: "window-custom-event", namespace: "app" }),});
// Subscribeconst sub = channel.receiver.on("notification", { ondata: ({ value }) => console.log("Received:", value), onerror: ({ error }) => console.error("Parse error:", error),});
// Sendchannel.sender.send("notification", { text: "Hello!" });
// Cleanupsub.dispose();createRequestChannel(options)
Section titled “createRequestChannel(options)”Creates a channel for request/response communication with automatic correlation and timeout handling.
import { createRequestChannel } from "@thuum/channels";import { createTransport } from "@thuum/transport";
const channel = createRequestChannel({ schemas: { calculate: { request: { parse: (data) => ({ value: data }) }, response: { parse: (data) => ({ value: data }) }, }, }, transport: createTransport({ type: "window-custom-event", namespace: "app" }),});
// Register a handlerchannel.receiver.on("calculate", { ondata: async ({ value }) => value.a + value.b,});
// Send a requestconst result = await channel.sender.send("calculate", { a: 5, b: 3 });
if ("value" in result) { console.log("Result:", result.value); // 8} else { console.error("Error:", result.error);}Result Types
Section titled “Result Types”Channels use a discriminated union for return values:
type Val<T> = { readonly value: T };type Err<T> = { readonly error: T; readonly trace?: readonly [T, ...T[]] };type Result<V, E = unknown> = Val<V> | Err<E>;Schemas
Section titled “Schemas”Schemas define parsers that validate messages at runtime. Each parser must return a Result:
type Parser<T> = { parse(value: T): Result<T>;};
// Message schema: one parser per topicconst messageSchemas = { greeting: { message: { parse: (data) => { if (typeof data === "string") return { value: data }; return { error: new Error("Expected string") }; }, }, },};
// Request schema: request + response parsers per topicconst requestSchemas = { calculate: { request: { parse: (data) => ({ value: data }) }, response: { parse: (data) => ({ value: data }) }, },};