Skip to content
briefkastencloud

TypeScript library

The briefkasten package: briefkasten(), connect(), .on(), the event type, options and errors.

npm install briefkasten
npm install @briefkasten/adapter-github @briefkasten/adapter-linear   # as needed

briefkasten(options)

Webhook handling inside your app. Returns an App.

import { briefkasten } from "briefkasten";
import { github } from "@briefkasten/adapter-github";

const hooks = briefkasten({
  sources: { github: github({ secret: process.env.GITHUB_WEBHOOK_SECRET }) },
});
OptionType
sourcesRecord<string, Source>The sources, by name. A source comes from an adapter: github({ secret }).
maxBodyBytesnumberLarger deliveries are refused with 413. Default 1 MiB.
retry{ attempts, backoffMs }How often a failing handler runs again. Default 5 attempts, from 1 s.
storeEventStoreWhere events are kept for replay. Default: in memory, the last 1000.
log(line) => voidWhere the app's log lines go. Default: console.warn.

App

Member
on(pattern, handler)Run handler for every event that matches. See patterns.
fetch(request)A fetch handler: (Request) => Promise<Response>. Mount it in Hono, Next.js, a Worker.
nodeA Node handler: (req, res) => void. Mount it in Express or node:http.
replay(id)Run the handlers for a kept event again.
idle()Wait until every event received so far has run its handlers.
close()Stop: running handlers see their signal aborted, and no retry starts.

connect(options)

Receive events from a gateway, hosted or self-hosted, over a WebSocket your app opens. Returns an Inbox.

import { connect } from "briefkasten";

const inbox = connect({
  url: "https://briefkasten.example",
  token: process.env.BRIEFKASTEN_TOKEN,
});
OptionType
urlstringThe gateway, e.g. https://briefkasten.example.
tokenstringA subscriber token (bk_sub_…).
filtersstring[]Only these addresses travel over the wire.
sincestringStart after this event id. Default: where the last connection stopped.
onEvent(event) => voidCalled after every handled event, e.g. to store its id.
signalAbortSignalCloses the connection when aborted.
projectstringOnly this project's events. Default: every project the token reads.
transport"auto" | "websocket" | "sse"Default auto: a WebSocket, SSE when none opens.

The client knows no adapters, so event.body is untyped unless you name the sources' event tables:

import type { GithubEvents } from "@briefkasten/adapter-github";

const inbox = connect<{ github: GithubEvents }>({ url, token });

Inbox

Member
on(pattern, handler)Run handler for every event that matches.
on("error", handler)Connection and handler errors.
close()Close the connection; waits for running handlers.

Patterns

on() takes a glob over source:event, or over the full address project:adapter:source:target:event. * matches one part, ** any number.

hooks.on("github:push", handler);
hooks.on("github:pull_request.*", handler);
hooks.on(["sentry:issue.created", "linear:issue"], handler);

Handlers

hooks.on("github:pull_request.opened", async (event, context) => {
  context.log(`#${event.body.number} opened in ${event.target}`);
});

A handler gets the event and a context with log, an AbortSignal (signal) and the adapter's actions where it has any. A handler that throws runs again with backoff.

BriefkastenEvent

FieldType
idstringStable and time-ordered.
tenantstringWhose event it is.
projectstringThe project of the source.
adapterstringe.g. github.
sourcestringThe source's name.
targetstringWhat it is about: acme/shop, a Linear team.
eventstringe.g. pull_request.opened.
atstringISO 8601, when it was received.
bodytyped per eventThe adapter's parsed payload.
testtrue?Set on test events.

With an adapter's source, event.body is typed by the event name: inside hooks.on("github:pull_request.opened", …) it is GitHub's pull request payload.

send(options)

Posts a webhook to a hook URL, signed with the source's secret the way the provider signs: a real delivery that goes through verification. Each adapter builds its provider's deliveries, typed, from its samples and the fields you give:

import { send } from "briefkasten";
import { github } from "@briefkasten/adapter-github";

await send({
  url: hookUrl,
  secret,
  delivery: github.events.pullRequest.opened({ repo: "acme/shop", number: 42, title: "Fix login" }),
});
OptionType
urlstringThe source's hook URL.
secretstringThe source's secret.
deliveryWebhookDeliveryAn adapter's builder's delivery; withValues(delivery, { "pull_request.draft": true }) sets any value.

It answers { id, status, ok, body }. The builders take repo, number, title and author, where the provider has them; randomFields() makes random ones for simulated traffic.

Errors

Everything throws a BriefkastenError with a code from the error list and the HTTP status: unauthorized for a wrong token, rate_limited, and so on. A client says its errors to its error handlers (to the console when it has none).

import { BriefkastenError } from "briefkasten";

try {
  await inbox.close();
} catch (error) {
  if (error instanceof BriefkastenError && error.code === "unauthorized") rotateToken();
}