@atcute/jetstream

中文文档
2.2.1发布于 2026/10/270BSDES Module近 30 天下载 1.4万

lightweight and cute Jetstream subscriber for AT Protocol

原始使用文档
文档目录9 节
  1. usage
  2. subscribing to events
  3. filtering
  4. handling event types
  5. validating records
  6. resuming from a cursor
  7. cancelling the subscription
  8. handling errors
  9. connection options

@atcute/jetstream

lightweight Jetstream subscriber for AT Protocol.

npm install @atcute/jetstream

Jetstream is a streaming service that delivers a filtered firehose of AT Protocol events as JSON over WebSocket. this package provides a client to subscribe to those events.

usage

subscribing to events

import { subscribeEvents } from '@atcute/jetstream';

const events = subscribeEvents({
    service: 'wss://jetstream.us-east.bsky.network',
});

for await (const message of events) {
    console.log(message.$type, message.seq, message.did);
}

the connection opens when iteration starts, reconnects automatically, and closes when iteration ends. service accepts one host because v2 sequence cursors are specific to a Jetstream instance.

filtering

filters are combined and match everything when omitted or empty:

const postEvents = subscribeEvents({
    service: 'wss://jetstream.us-east.bsky.network',
    collections: ['app.bsky.feed.post', 'app.bsky.graph.*'],
    dids: ['did:plc:z72i7hdynmk6r22z27h6tvur'],
    kinds: ['commit'],
});

collections only filters commit events. combine it with kinds: ['commit'] to exclude identity, account, and sync events.

handling event types

use $type to narrow an event before accessing its fields:

for await (const message of events) {
    switch (message.$type) {
        case 'network.bsky.jetstream.subscribeEvents#commit': {
            console.log(message.operation, message.collection, message.rkey, message.record);
            break;
        }

        case 'network.bsky.jetstream.subscribeEvents#identity': {
            console.log(message.identity.handle);
            break;
        }

        case 'network.bsky.jetstream.subscribeEvents#account': {
            console.log(message.account.active, message.account.status);
            break;
        }

        case 'network.bsky.jetstream.subscribeEvents#sync': {
            console.log(message.sync.rev);
            break;
        }
    }
}

commit fields are placed directly on the message. identity, account, and sync messages wrap the corresponding upstream relay event. event types unknown to this version of the package are skipped without advancing the cursor.

validating records

event envelopes are validated by default, but commit record values remain unvalidated JSON. narrow them with is() from @atcute/lexicons:

import { AppBskyFeedPost } from '@atcute/bluesky';
import { is } from '@atcute/lexicons';

for await (const message of events) {
    if (message.$type !== 'network.bsky.jetstream.subscribeEvents#commit') {
        continue;
    }

    if (is(AppBskyFeedPost.mainSchema, message.record)) {
        console.log(`@${message.did}: ${message.record.text}`);
    }
}

set validateEvents: false to skip envelope validation. records must still be validated separately.

resuming from a cursor

pass a sequence number to start from, or a CursorStore to load and save the position:

import { readFile, writeFile } from 'node:fs/promises';

const events = subscribeEvents({
    service: 'wss://jetstream.us-east.bsky.network',
    cursor: {
        async load() {
            const saved = await readFile('cursor', 'utf8').catch(() => undefined);
            return saved !== undefined ? Number(saved) : undefined;
        },
        async save(seq) {
            await writeFile('cursor', String(seq));
        },
    },
});

load decides where the subscription starts, and it is consulted again on every reconnection rather than only on the first connection, so a store written elsewhere takes effect on the next connection attempt. returning undefined starts from the live tip. a sequence number is treated as a store that only lasts for the subscription.

the stored cursor advances when the consumer asks for the next event. writes are limited by cursorSaveInterval, which defaults to 5 seconds; a pending write is flushed before reconnecting and when iteration ends. set the interval to 0 to save every event.

a store failure while connecting is reported to onConnectionError and the connection attempt is retried. a save failure during iteration is thrown, except for the final flush, which goes to onError so it does not mask why iteration ended.

delivery is at least once. reconnect duplicates are removed while the same iterator is running, but a new iterator may replay its saved cursor event. event handlers should therefore be idempotent.

cancelling the subscription

an AbortSignal stops the stream. iteration rejects with signal.reason after flushing any pending cursor:

const events = subscribeEvents({
    service: 'wss://jetstream.us-east.bsky.network',
    signal: AbortSignal.timeout(10_000),
});

handling errors

onError receives malformed frames, validation failures, and server error frames. server errors use FirehoseError:

import { FirehoseError, subscribeEvents } from '@atcute/jetstream';

const events = subscribeEvents({
    service: 'wss://jetstream.us-east.bsky.network',
    onError: (err) => {
        if (err instanceof FirehoseError) {
            console.error('jetstream sent', err.error);
        } else {
            console.error('jetstream error:', err);
        }
    },
});

errors returned before the WebSocket upgrade, including CursorTooOld and InvalidRequest, are not visible to WebSocket clients and look like connection failures. they are retried by default; use ws.maxRetries to set a limit. reaching the limit stops reconnection but leaves the iterator open.

connection options

onConnectionOpen, onConnectionClose, and onConnectionError report the socket lifecycle, and ws passes options to the underlying partysocket WebSocket:

const events = subscribeEvents({
    service: 'wss://jetstream.us-east.bsky.network',
    onConnectionClose: (event) => console.log('disconnected', event.code, event.reason),
    ws: {
        minReconnectionDelay: 1_000,
        maxReconnectionDelay: 30_000,
    },
});

版本与发布记录

@atcute/jetstream 共发布 13 个版本,首次发布于 2025/05/14;过去 12 个月发布了 7 个版本。

版本发布日期距今
2.2.1latest2026/10/2711 天前
2.2.02026/09/101 个月前
2.1.02026/08/192 个月前
2.0.22026/07/163 个月前
2.0.12026/06/294 个月前
2.0.02026/05/095 个月前

关于 @atcute/jetstream 的常见问题

@atcute/jetstream 是什么?

lightweight and cute Jetstream subscriber for AT Protocol

如何安装 @atcute/jetstream?

在项目目录运行 npm install @atcute/jetstream,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:@atcute/lexicons(^2.0.0)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@atcute/jetstream 支持 TypeScript 吗?

该包的 package.json 没有声明类型入口。需要类型提示时,可以在 npm 上查找社区维护的 @types/atcute__jetstream 是否存在。

@atcute/jetstream 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@atcute/jetstream 可以商用吗?

@atcute/jetstream 使用 0BSD 许可。几乎没有限制:可自由使用、修改和分发,连保留版权声明也不要求。以上为概括,不构成法律意见,请以许可原文为准。

@atcute/jetstream 的下载量有多少?

根据 npm 官方下载统计,@atcute/jetstream 在 2026/10/07 – 2026/11/05 这 30 天内被下载 14,432 次,日均约 481 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@atcute/jetstream 还在维护吗?

最新版本 2.2.1 发布于 2026/10/27(11 天前);至今共发布 13 个版本,其中过去 12 个月发布了 7 个;首次发布于 2025/05/14。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。