Compare commits

..
27 Commits
Author SHA1 Message Date
snowluma-bot[bot] 54c4641a0e Merge pull request #66 from SnowLuma/dev
chore: promote dev → main (5924346)
2026-05-24 10:02:15 +00:00
snowluma-bot[bot] 08b7ab7f15 Merge pull request #63 from SnowLuma/dev
chore: promote dev → main (ee0f159)
2026-05-21 09:50:31 +00:00
snowluma-bot[bot] 4a92dd71ad Merge pull request #62 from SnowLuma/dev
chore: promote dev → main (607a7b3)
2026-05-21 09:34:03 +00:00
snowluma-bot[bot] 1bd0cbc359 Merge pull request #57 from SnowLuma/dev
chore: promote dev → main (2de1ff4)
2026-05-20 06:21:32 +00:00
snowluma-bot[bot] fe567caeec Merge pull request #50 from SnowLuma/dev
chore: promote dev → main (941e60d)
2026-05-18 07:04:16 +00:00
snowluma-bot[bot] 231d60411b Merge pull request #48 from SnowLuma/dev
chore: promote dev → main (b94775c)
2026-05-18 05:31:37 +00:00
snowluma-bot[bot] bee1e67c60 Merge pull request #46 from SnowLuma/dev
chore: promote dev → main (c6f4d5c)
2026-05-17 16:11:03 +00:00
snowluma-bot[bot] 71b0bda8f4 Merge pull request #44 from SnowLuma/dev
chore: promote dev → main (90884df)
2026-05-17 11:29:18 +00:00
墨梓柒 133cfc0c0e Merge pull request #40 from SnowLuma/revert/pr-38-c2c-video-sceneType
Revert "fix(send): keep c2c video compatQMsgSceneType at 2 (#38)"
2026-05-16 16:44:38 +08:00
DrSmoothl b959783ded Revert "fix(send): keep c2c video compatQMsgSceneType at 2 (#38)"
This reverts commit 463e0ffb5d.
2026-05-16 14:54:56 +08:00
时瑾 463e0ffb5d fix(send): keep c2c video compatQMsgSceneType at 2 (#38)
Commit 29f28d6 changed c2c video `compatQmsgSceneType` from 2 to 1
as a "symmetric asymmetry" cleanup, matching the image/ptt convention
where the field tracks the upload's sceneType (c2c=1, group=2). For
video this is wrong.

Image and ptt have *different* legacy compat elements per scene
(notOnlineImage vs customFace; ptt c2c vs group), so the server needs
to know which scene shape to emit. The legacy `videoFile` element
(packet element type 19) has no scene split — fromChatType /
toChatType live inside the element itself — so the QQ NT server
emits a single group-shaped compat payload regardless. NapCat
hardcodes `compatQMsgSceneType: 2` for *both* UploadGroupVideo and
UploadPrivateVideo for exactly this reason.

Setting it to 1 on c2c made the server emit a c2c-scene shaped
compat blob that older QQ clients failed to resolve, showing the
message as "视频已过期" on those receivers. Newer clients only read
the commonElem(48, 11) and displayed fine — which is why only "some
devices" saw the breakage.

Keep `commonElem.businessType = isGroup ? 21 : 11` untouched — that
piece of 29f28d6 is still correct and is what fixed PbSendMsg
result=79.
2026-05-16 14:22:49 +08:00
snowluma-bot[bot] 9d55e86b1c Merge pull request #37 from SnowLuma/dev
chore: promote dev → main (7da52bc)
2026-05-15 23:18:33 +08:00
snowluma-bot[bot] 07449788c6 Merge pull request #36 from SnowLuma/dev
chore: promote dev → main (85b59bc)
2026-05-15 01:48:08 +08:00
snowluma-bot[bot] fe4af70562 Merge pull request #34 from SnowLuma/dev
chore: promote dev → main (564eec2)
2026-05-14 20:50:46 +08:00
snowluma-bot[bot] 545a732385 Merge pull request #30 from SnowLuma/dev
chore: promote dev → main (ada591b)
2026-05-13 16:55:55 +08:00
snowluma-bot[bot] c2f22d8daf Merge pull request #29 from SnowLuma/dev
chore: promote dev → main (6abde40)
2026-05-13 16:23:42 +08:00
snowluma-bot[bot] 9216b54427 Merge pull request #28 from SnowLuma/dev
chore: promote dev → main (1b2dd83)
2026-05-12 22:06:52 +08:00
snowluma-bot[bot] fd9a239241 Merge pull request #27 from SnowLuma/dev
chore: promote dev → main (8636222)
2026-05-11 15:32:46 +00:00
snowluma-bot[bot] 5a4028d5dc Merge pull request #25 from SnowLuma/dev
chore: promote dev → main (6f6ce11)
2026-05-10 10:17:23 +08:00
snowluma-bot[bot] d02e7cc3ab Merge pull request #23 from SnowLuma/dev
chore: promote dev → main (bec23c4)
2026-05-10 01:32:20 +08:00
snowluma-bot[bot] 9938545788 Merge pull request #21 from SnowLuma/dev
chore: promote dev → main (a7b3809)
2026-05-09 19:40:04 +08:00
snowluma-bot[bot] 7149bc8689 Merge pull request #20 from SnowLuma/dev
chore: promote dev → main (c39b3f5)
2026-05-09 19:33:40 +08:00
snowluma-bot[bot] 9802128421 Merge pull request #19 from SnowLuma/dev
chore: promote dev → main (2af273b)
2026-05-09 16:40:37 +08:00
墨梓柒 a572d05c25 Merge pull request #18 from SnowLuma/dependabot/npm_and_yarn/hono-4.12.18
build(deps-dev): bump hono from 4.12.14 to 4.12.18
2026-05-09 16:03:21 +08:00
dependabot[bot] cb06624d12 build(deps-dev): bump hono from 4.12.14 to 4.12.18
Bumps [hono](https://github.com/honojs/hono) from 4.12.14 to 4.12.18.
- [Release notes](https://github.com/honojs/hono/releases)
- [Commits](https://github.com/honojs/hono/compare/v4.12.14...v4.12.18)

---
updated-dependencies:
- dependency-name: hono
  dependency-version: 4.12.18
  dependency-type: direct:development
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-05-09 08:01:11 +00:00
snowluma-bot[bot] 7b93839186 Merge pull request #17 from SnowLuma/dev
chore: promote dev → main (1565749)
2026-05-09 15:37:22 +08:00
snowluma-bot[bot] d0085ec052 Merge pull request #15 from SnowLuma/dev
chore: promote dev → main (c3b328f)
2026-05-09 15:04:19 +08:00
136 changed files with 2316 additions and 3903 deletions

No files matched your search

+9 -491
View File
@@ -1,491 +1,9 @@
# SnowLuma v3 — 目标架构
> v2 已完成:UID/UIN Service(SQLite 持久化)、tsx+map Debug、包拆分、proto-defs 剥离、消息 hot-path 优化(17.5μs → 4.7μs)、NapCat 风格 Api 层、Bridge/Account 分层(v2 发布在 `@snowluma/bridge`,v3 重命名为 `@snowluma/channel`)。
---
## 0. 数据流总览(一图概览所有权)
```
┌─ @snowluma/channel-hook ─────────┐ ┌─ @snowluma/channel-socket ──────┐
│ HookManager + HookChannel │ │ SocketChannel (future) │
│ — 仅 send/recv + pid/hook state — │ │ — 仅 send/recv + socket state — │
└────────────┬─────────────────────┘ └─────────────┬───────────────────┘
│ Channel 实例 │
└───────────┬──────────────────────────┘
│ 通过 ChannelAdapter 注册
▼
┌─ @snowluma/core ──── Hub(主入口 / 持有一切)──────────────┐
│ │
│ 内部:Map<uin, Core> │
│ │
│ channel available ──► ctx = capability(channel) │
│ ──► core = new Core(ctx) │
│ ──► emit 'core-online' { uin, apis, events, ... } │
│ │
│ channel gone ──► core.dispose() + emit 'core-offline' { uin } │
└─────────────────────────────────────┬─────────────────────────────────┘
│ 顶层 lifecycle 事件(仅 2 个)
▼
┌─ @snowluma/onebot ──────────────────────────────────────────────────────┐
│ hub.events.on('core-online', ctx => { │
│ this.byUin.set(ctx.uin, ctx); │
│ ctx.events.on('group_message', e => …); // 每账号 bus │
│ }); │
│ // 处理 OneBot action: │
│ this.byUin.get(uin)?.apis.message.sendGroup(...) │
└─────────────────────────────────────────────────────────────────────────┘
```
**核心约定**:
- `Channel` / adapter 包 **只**做 send/recv + 自己的内部状态(pid set / hook session / socket fd)。完全无业务。
- `Hub` 是**主入口**,独占持有 Channels + Cores。`Core` 实例由它构造,外部拿不到 Core 类本身。
- `Core` 通过 **ctx**(capability,一个 POJO)拿到 send/recv,从不直接持有 Channel。
- 外部消费者(OneBot / WebUI)只拿 `CoreCtx`(Core 的对外投影:`{ uin, apis, events, identity }`),不知道 Core 类的存在。
- 每个账号一个 `events`(在 Core 上),不做全局 bus;Hub 只 emit 两个顶层生命周期事件。
---
## 1. 目标包结构
```
SnowLuma/
├── packages/
│ │
│ │ ── Infrastructure(无业务) ──
│ ├── common/ logger / packet-sender / protocol-types / async-context
│ ├── proto-defs/ protobuf TS 接口定义
│ ├── proton/ protobuf codec 编译时生成器
│ ├── runtime/ native .node 产物清单
│ ├── ui/ Tailwind v4 + shadcn 组件(前端)
│ │
│ │ ── Protocol(解析层,纯函数) ──
│ ├── protocol/ events / identity-service / msg-push / oidb / highway /
│ │ element-builder / packet-pipeline / event-bus
│ │
│ │ ── Channel & adapters(transport 端口与实现) ──
│ ├── channel/ ⭐ Channel 接口 + 抽象类 + ChannelAdapter 端口
│ │ —— 只定义接口和最小抽象,**不**含 Hub
│ ├── channel-hook/ ⭐ HookManager + HookChannel + HookAdapter
│ │ —— 现 @snowluma/channel 大部分内容搬来
│ ├── channel-socket/ ⭐ 未来:SocketChannel + SocketAdapter
│ │
│ │ ── Core(主入口 + 业务封装) ──
│ ├── core/ ⭐ Core + Hub + CoreCtx + ApiHub + 协议封装
│ │ —— Hub 在这里(避免 channel↔core 循环)
│ │
│ │ ── Inbound(外部协议消费 CoreCtx) ──
│ ├── onebot/ OneBot v11 (HTTP + WS)
│ ├── websocket/ 底层 WS server(被 onebot / webui-backend 共用)
│ ├── webui-backend/ ⭐ Hono server + REST/WS(拆自 webui)
│ ├── webui-frontend/ ⭐ Vite SPA(拆自 webui)
│ └── sdk/ TS SDK
│
├── package.json
└── pnpm-workspace.yaml
```
⭐ 标记的是 v3 改动。
### 1.1 关键变动
| 当前 | 目标 | 备注 |
|---|---|---|
| `@snowluma/bridge`(hook + transport + adapter + manager) | `@snowluma/channel`(仅接口 + abstract Channel)+ `@snowluma/channel-hook`(hook 实现) | 包名 v2 叫 bridge,v3 重命名;hook 全套迁出独立包 |
| `@snowluma/core`(含 Account + AccountManager) | `core`:Core + Hub | Account → Core;AccountManager 折进 Hub |
| —— | `channel-socket` | 新建 stub |
| `@snowluma/webui` | `webui-backend` + `webui-frontend` | 前后端拆分 |
### 1.2 依赖 DAG(无环)
```
common ◄── proton, proto-defs, protocol, runtime, ui, channel
proto-defs ◄── protocol
proton ◄── protocol
protocol ◄── core
channel ◄── channel-hook, channel-socket, core
channel-hook ◄── core
channel-socket ◄── core
core ◄── onebot, webui-backend
websocket ◄── onebot, webui-backend
ui ◄── webui-frontend
```
**核心要点**:`core` 是唯一一处同时知道 `channel` 端口 + 业务实现的地方。Channel 包不反向依赖 core,因此 Hub **住在 core**,而不是 channel —— 名字保留 `Hub` 是因为它语义上仍是「channel 集群的指挥官」。
---
## 2. 三个关键类型 / 接口(设计核心)
整个系统由 **3 个类型** 串起来。每个职责单一、边界清晰。
### 2.1 `Channel`(在 `@snowluma/channel`)—— 纯 transport
```ts
// packages/channel/src/channel.ts
export type ChannelKind = 'inject' | 'socket';
export interface Channel {
readonly kind: ChannelKind;
readonly uin: string;
readonly id: string; // adapter:uin 形式
sendRawPacket(cmd: string, body: Uint8Array): Promise<SendPacketResult>;
setPacketHandler(h: ((pkt: PacketInfo) => void) | null): void;
deliverPacket(pkt: PacketInfo): void; // adapter 内部用
dispose(): void;
}
```
Adapter 包(`channel-hook` / `channel-socket`)的具体类(`HookChannel` / `SocketChannel`)实现 `Channel`。它们的内部状态(PID set、hook session、socket fd)对外不可见。
### 2.2 `ChannelCtx`(在 `@snowluma/channel`)—— channel → core 的能力 POJO
```ts
// packages/channel/src/channel-ctx.ts
export interface ChannelCtx {
readonly uin: string;
readonly kind: ChannelKind;
readonly sendRawPacket: (cmd: string, body: Uint8Array) => Promise<SendPacketResult>;
readonly onPacket: (h: (pkt: PacketInfo) => void) => void;
readonly dispose: () => void;
}
// Hub 用 makeCtx(channel) 把 Channel 投影成 ChannelCtx:
export function makeChannelCtx(b: Channel): ChannelCtx {
return {
uin: b.uin, kind: b.kind,
sendRawPacket: (c, x) => b.sendRawPacket(c, x),
onPacket: (h) => b.setPacketHandler(h),
dispose: () => b.dispose(),
};
}
```
**关键设计**:`Core` 只接收 `ChannelCtx`(capability POJO),**不**持有 `Channel` 类引用。这样 `core` 包不依赖任何 adapter 实现细节,连 Channel 抽象类都不用 import。
### 2.3 `CoreCtx`(在 `@snowluma/core`)—— core → onebot 的能力 POJO
```ts
// packages/core/src/core-ctx.ts
export interface CoreCtx {
readonly uin: string;
readonly kind: ChannelKind;
readonly apis: ApiHub; // 所有 typed api(message/contacts/...)
readonly events: EventBus; // 该账号的事件(per-uin)
readonly identity: IdentityService; // UID/UIN/group roster
}
```
**关键设计**:OneBot 拿到的就是这个 POJO 投影,**不**持有 `Core` 类引用。Hub 在 `core-online` 事件里把 `CoreCtx` 透出去;OneBot 按 uin 存起来用。
---
## 3. `Hub` —— 主入口完整实现
所有所有权、生命周期、装配都在这里。**外部 main.ts 只跟它打交道。**
```ts
// packages/core/src/hub.ts
import { Channel, ChannelAdapter, ChannelAdapterHost, makeChannelCtx } from '@snowluma/channel';
import { Core } from './core';
import type { CoreCtx } from './core-ctx';
import { TypedEmitter } from '@snowluma/common/typed-emitter';
type Lifecycle = {
'core-online': CoreCtx;
'core-offline': { uin: string };
};
export class Hub {
private readonly cores = new Map<string, Core>();
private readonly adapters: ChannelAdapter[] = [];
readonly events = new TypedEmitter<Lifecycle>();
registerAdapter(a: ChannelAdapter): void {
this.adapters.push(a);
}
async start(): Promise<void> {
const host: ChannelAdapterHost = {
onChannelReady: (b) => this.onChannelReady(b),
onChannelGone: (uin) => this.onChannelGone(uin),
};
await Promise.all(this.adapters.map((a) => a.start(host)));
}
async stop(): Promise<void> {
await Promise.all(this.adapters.map((a) => a.stop()));
for (const c of this.cores.values()) c.dispose();
this.cores.clear();
}
// ─── private ───────────────────────────────
private onChannelReady(channel: Channel): void {
const stale = this.cores.get(channel.uin);
if (stale) {
stale.dispose();
this.events.emit('core-offline', { uin: channel.uin });
}
const core = new Core(makeChannelCtx(channel));
this.cores.set(channel.uin, core);
this.events.emit('core-online', core.publicCtx);
}
private onChannelGone(uin: string): void {
const core = this.cores.get(uin);
if (!core) return;
core.dispose();
this.cores.delete(uin);
this.events.emit('core-offline', { uin });
}
}
```
## 4. `Core` 实现要点
```ts
// packages/core/src/core.ts
import type { ChannelCtx } from '@snowluma/channel';
import { EventBus } from '@snowluma/protocol/event-bus';
import { IdentityService } from '@snowluma/protocol/identity-service';
import { IncomingPacketPipeline } from '@snowluma/protocol/packet-pipeline';
import { buildApiHub, type ApiHub } from './apis';
import type { CoreCtx } from './core-ctx';
export class Core {
readonly events = new EventBus(); // ← 每账号一个 bus
readonly identity: IdentityService;
readonly apis: ApiHub;
private readonly pipeline: IncomingPacketPipeline;
constructor(private readonly channelCtx: ChannelCtx) {
this.identity = IdentityService.openForUin(channelCtx.uin);
this.pipeline = new IncomingPacketPipeline(this.events, this.identity);
this.apis = buildApiHub(this); // apis 内部持 Core 引用,调 sendRawPacket
channelCtx.onPacket((pkt) => this.pipeline.process(pkt));
}
// 给外部消费者的投影(只读 POJO,不暴露 Core 实例)
get publicCtx(): CoreCtx {
return {
uin: this.channelCtx.uin,
kind: this.channelCtx.kind,
apis: this.apis,
events: this.events,
identity: this.identity,
};
}
// apis 内部通过 core 调发包
sendRawPacket(cmd: string, body: Uint8Array) {
return this.channelCtx.sendRawPacket(cmd, body);
}
dispose(): void {
this.channelCtx.dispose();
this.identity.close();
}
}
```
## 5. OneBot 消费 `CoreCtx`
```ts
// packages/onebot/src/manager.ts
import type { Hub, CoreCtx } from '@snowluma/core';
export class OneBotManager {
private readonly byUin = new Map<string, CoreCtx>();
bind(hub: Hub): void {
hub.events.on('core-online', (ctx) => this.attach(ctx));
hub.events.on('core-offline', ({ uin }) => this.detach(uin));
}
private attach(ctx: CoreCtx): void {
this.byUin.set(ctx.uin, ctx);
ctx.events.on('group_message', (e) => this.dispatchGroupMessage(ctx, e));
ctx.events.on('private_message',(e) => this.dispatchPrivateMessage(ctx, e));
// ... 其它 kind
}
private detach(uin: string): void {
this.byUin.delete(uin);
// ctx.events 随 Core dispose 一起释放
}
// 处理 OneBot HTTP/WS action:用 uin 查到 ctx,直接调 apis
async handleSendGroupMsg(uin: string, groupId: number, msg: OneBotMsg) {
const ctx = this.byUin.get(uin);
if (!ctx) throw new Error(`unknown uin: ${uin}`);
return ctx.apis.message.sendGroup(groupId, msg); // ← 直接调封装好的 api
}
}
```
## 6. 主入口(`packages/core/src/index.ts`)
```ts
import { HookAdapter } from '@snowluma/channel-hook';
import { OneBotManager } from '@snowluma/onebot';
import { Hub } from './hub';
const hub = new Hub();
hub.registerAdapter(new HookAdapter({ autoLoadOnDiscovery: true }));
// hub.registerAdapter(new SocketAdapter()); // 未来
const onebot = new OneBotManager();
onebot.bind(hub);
await hub.start();
await initWebUI(port, onebot, /* hookManager from adapter */);
```
9 行装配,每行都是有意义的所有权声明。
---
## 7. 为什么这样设计优雅
### 7.1 单向数据流
```
adapter → Channel → ChannelCtx → Core → CoreCtx → OneBot
transport capability capability
```
**没有反向引用**:Core 不知道 Channel 类,OneBot 不知道 Core 类。每层只看到「下一层的能力 POJO」。
### 7.2 单一所有者
`Hub.cores: Map<uin, Core>` 是 **唯一** 持有 Core 的地方。OneBot 只持 `CoreCtx`(投影,不算所有权)。Core 销毁 = 从这个 Map 里删 = 所有 ctx 同时失效。无需引用计数、无需 GC 协调。
### 7.3 每账号独立 EventBus
Core 自带 `events: EventBus`,互不干扰。OneBot 通过 `core-online` 拿到 ctx 后立即 subscribe,`core-offline` 时 Core 已 dispose,bus 自然失效,不会泄漏。**没有全局 bus**,没有「哪个账号的事件」问题。
### 7.4 完全可测
- 测 Channel:mock `setPacketHandler` 回调(已在 `account-private-routing.test.ts` 用 `FakeChannel` 验证)
- 测 Core:传 `ChannelCtx` POJO 即可,无需真 Channel
- 测 OneBot:emit 一个 `core-online` + 假 `CoreCtx`
- 测 Hub:用 fake `ChannelAdapter`
每层都能独立测试。
### 7.5 内部还要避免 ctx 漫天的两个小招
**(a) Api 类捕获 deps(已做)**
```ts
class MessageApi {
constructor(private readonly core: Core) {}
// 方法签名只有业务参数:
async sendGroup(groupId: number, msg: Msg) { this.core.sendRawPacket(...) }
}
```
**(b) AsyncLocalStorage 处理日志 / trace(建议引入)**
```ts
// packages/common/src/async-context.ts
import { AsyncLocalStorage } from 'node:async_hooks';
const als = new AsyncLocalStorage<{ uin?: string; trace?: string }>();
export const runInContext = <T>(c: { uin?: string; trace?: string }, fn: () => T) =>
als.run(c, fn);
export const ctx = () => als.getStore() ?? {};
// logger 自动 prefix [uin],业务代码不用接 log 参数
```
在 `Core.constructor` 给 `onPacket` 包一层:
```ts
channelCtx.onPacket((pkt) => {
runInContext({ uin: channelCtx.uin, trace: `pkt:${pkt.seqId}` }, () => {
this.pipeline.process(pkt);
});
});
```
所有下游 `log.info()` 自动带 `[10001]` 前缀,不污染业务签名。开销 ~50ns/call。
---
## 8. 不要的设计(保持简单)
| 方案 | 不做的原因 |
|---|---|
| **`CoreFactory` 抽象** | Core 只一种,多此一举。直接 `new Core(ctx)` |
| **全局 EventBus** | 每账号自己的 bus 更清晰,OneBot 按 uin 订阅,不混杂 |
| **`AccountManager` 独立层** | 多余的中间层,折进 `Hub` |
| **`InboundAdapter` 抽象** | OneBot / WebUI 数量有限且固定,直接 `bm.events.on(...)` 即可,不抽插件层 |
| **DI 容器(tsyringe 等)** | 9 行手动装配已经清晰,DI 引入反射/装饰器元数据反而难调 |
| **Effect monad / Reader monad** | TS 缺 do-notation,类型噪音 > 收益 |
| **CQRS / Event-sourced state** | 当前状态量级(10 账号 × 100 群)远未到 |
---
## 9. 迁移路线(每步独立可 ship)
> typecheck + 全测试通过才进下一步。
**Step 1** —— ⭐ 重命名 + 拆现有的 `@snowluma/bridge`
- `packages/bridge/` 重命名为 `packages/channel/`;package.json name 改为 `@snowluma/channel`
- 新建 `packages/channel-hook/`,从 `@snowluma/channel` 搬:`hook-manager.ts` / `hook-session.ts` / `hook-packet-client.ts` / `injector.ts` / `pipe-watcher.ts` / `qq-hook-client.ts` / `qq-port-probe.ts` / `hook-channel.ts`(原 inject-bridge.ts)/ `hook-adapter.ts`(原 inject-adapter.ts)
- `@snowluma/channel` 留:`channel.ts`(abstract,原 bridge.ts)/ `channel-interface.ts` / `channel-ctx.ts`(新)/ `adapter.ts`(端口)+ `makeChannelCtx` 工具
- 删除:`manager.ts`(原 BridgeManager)(搬到 core/hub.ts)/ `socket-channel.ts` + `socket-adapter.ts`(搬到 `channel-socket` stub)
**Step 2** —— ⭐ 重塑 `@snowluma/core`
- 删除:`account/account.ts` / `account-interface.ts` / `account-context.ts` / `account-manager.ts`
- 新建:`core.ts`(吸收 Account 业务,构造接 `ChannelCtx`)/ `core-ctx.ts` / `hub.ts`
- `apis/` 内部 `AccountContext` → `Core`(直接拿 Core 类型)
- `index.ts` 9 行装配(见 §6)
**Step 3** —— OneBot 适配 CoreCtx
- 全局 `AccountInterface` → `CoreCtx`
- `OneBotManager.bind(hub)` 订阅 `'core-online'` / `'core-offline'`
- 内部 `byUin.get(uin).apis.<area>.method()` 调 api
**Step 4** —— 引入 `AsyncLocalStorage`
- `packages/common/src/async-context.ts`
- `logger.ts` 自动读 ALS,加 `[uin]` 前缀
- `Core.constructor` 在 `onPacket` 回调外包 `runInContext`
**Step 5** —— `channel-socket` stub 包(占位)
- 把 `socket-channel.ts` / `socket-adapter.ts` 搬过来
- 实现 placeholder,让 `ChannelAdapter` 端口齐
**Step 6** —— ⭐ 拆 `webui` 为 `webui-backend` + `webui-frontend`
- Hono server + REST/WS → `webui-backend`,依赖 `@snowluma/core`(消费 `CoreCtx`)
- Vite SPA + UI → `webui-frontend`,依赖 `@snowluma/ui`
---
## 10. 设计原则速查
- **单向数据流**:`adapter → Channel → ChannelCtx → Core → CoreCtx → OneBot`,无反向引用
- **能力 POJO 跨层传递**:层间用 `{ uin, sendRawPacket, ... }` / `{ uin, apis, events, ... }` 这种纯数据,不传类实例
- **单一所有者**:`Hub.cores` 是 Core 唯一容器,消费者只持投影
- **每账号自带 EventBus**:避免全局 bus 混杂,订阅生命周期与 Core 绑定
- **Class 封装 deps**:构造时捕获,方法签名只剩业务参数
- **AsyncLocalStorage 跨切面**:日志 / trace 不进显式参数
- **不引入过度抽象**:no factory / no DI / no Effect monad / no global bus
- **可测**:每层接 POJO,fake 一下就能测
---
## 11. v2.0.0 已完成
- ✅ UID/UIN Service + SQLite 持久化
- ✅ tsx 免打包 Debug
- ✅ Common / OneBot / Core / Bridge / Protocol / proto-defs 拆包
- ✅ 消息 hot-path 优化(17.5μs → 4.7μs,better-sqlite3 + prepared-statement cache)
- ✅ NapCat 风格 Api 层(13 Api 类)
- ✅ Bridge / Account 严格分层(v2 中间形态;v3 重命名为 Channel + Core,并用 ctx 替代直接引用)
- ✅ `@snowluma/bridge` 完整 transport 包(v3 重命名为 `@snowluma/channel`)
# V2.0.0 前计划
- [x] 统一Uid/Uin提供一个Service,并实现Sqlite持久化,群/好友/入群和好友申请 获取新Uid。
- [x] 优化Debug体验,实现免打包Debug,同时数据目录正确。(Proton兜底思路改成ts+map提取类型,用于tsx和nodejs,vite正常打包的时候剥离)
- [x] 拆分core,架构为Common(公共能力) OneBot(外层封装 协议转换),Core(Api raw能力,基础能力等功能),Bridge(封装和关键解析能力和Event message/sent group/member_add ...)
- [x] 剥离ProtocolBuffer定义到单独package。
- [x] 整理发送和解析消息链路,提高性能。`packages/{bridge,onebot}/bench/*.bench.ts` 拿到了基线数字。最大瓶颈不在 protobuf 解析(已经 sub-μs),而在两处 SQLite 反复 `db.prepare(sql)` 重 parse —— 把 `node:sqlite`(实验性)换成 `better-sqlite3`(稳定)+ 缓存 prepared statements 后:`group_member_join` 全链路 17.5μs → 4.7μs(**3.7x**),`storeMeta` 17μs → 11μs,`storeEvent` 23μs → 18μs,`findMeta` 5.4μs → 1.3μs(**4x**)。送侧组合 hot path(storeMeta + storeEvent)单条消息 40μs → 29μs。另外干掉 `Buffer.from(pkt.body)` 的冗余 alloc(pkt.body 本来就是 Uint8Array)。`elementsToJson` 同步快路径 / WAL checkpoint 调参 / JSON 序列化替换 等次要优化点保留,待真有 throughput 压力再做。
- [x] 对齐NapCat设计采用Api层,挂到ctx,Core与Onebot都这么设计。
- [x] Core 侧:13 个 Api 类(message/contacts/groupAdmin/groupFile/groupAlbum/interaction/friend/profile/forward/misc/extras/web)已挂到 `bridge.apis.<area>.method()`,`BridgeInterface` + `actions/*` 全部删除。
- [x] OneBot 侧:`ApiActionContext` 砍掉 ~40 个纯转发字段(groupAdmin / groupFile / groupAlbum / friend / interaction / message / profile / web 八区),actions 直接 `ctx.bridge.apis.<area>.method(...)` 调用 Core 的 Api 层。保留的 ~30 个字段全是真组合 helper(module-level send/forward、message store reads、meta-lookup composers)。完全 NapCat 化(class-per-action / TypeBox schema / actionName 枚举 / auto-register decorator)暂未做——profile 文档/工具链需求出现后再做。
@@ -1,9 +1,9 @@
{
"name": "@snowluma/channel-hook",
"name": "@snowluma/bridge",
"version": "1.9.2",
"private": true,
"type": "module",
"description": "SnowLuma `inject` channel implementation — in-process NTQQ hook runtime. Bundles HookManager / HookSession / pipe-watcher / injector / qq-hook-client plus the `HookChannel` and `HookAdapter` that `Hub` (in @snowluma/core) registers as the primary transport on Windows. Depends on `@snowluma/channel` for the abstract `Channel` + `ChannelAdapter` contracts.",
"description": "SnowLuma bridge — QQ NT desktop client lifecycle: hook injection (via native addon), per-PID HookSession orchestration, pipe-watcher for process discovery, and the BridgeManagerSink interface that lets the hook layer call back into a UIN-keyed session router without depending on @snowluma/core. Consumed by the top-level app entry (which constructs the BridgeManager from @snowluma/core and injects it as the sink) and by the WebUI server (read-only HookProcessInfo views).",
"main": "./src/index.ts",
"types": "./src/index.ts",
"exports": {
@@ -11,14 +11,6 @@
"types": "./src/index.ts",
"default": "./src/index.ts"
},
"./hook-channel": {
"types": "./src/hook-channel.ts",
"default": "./src/hook-channel.ts"
},
"./hook-adapter": {
"types": "./src/hook-adapter.ts",
"default": "./src/hook-adapter.ts"
},
"./hook-manager": {
"types": "./src/hook-manager.ts",
"default": "./src/hook-manager.ts"
@@ -57,7 +49,6 @@
"typecheck": "tsc --noEmit"
},
"dependencies": {
"@snowluma/channel": "workspace:*",
"@snowluma/common": "workspace:*"
},
"devDependencies": {
@@ -18,23 +18,22 @@ import type { HookProcessInfo } from './types';
/**
* Sink that the hook layer calls back into when it observes a new login,
* a parsed packet, or a PID disconnect. The concrete implementation is
* `HookAdapter`, which sits between this hook runtime and the `Hub` in
* `@snowluma/core`. Declaring it here keeps `@snowluma/channel` (and
* future `@snowluma/channel-hook`) free of any dependency on
* `@snowluma/core` — the hook package is self-contained.
* a parsed packet, or a PID disconnect. The concrete implementation lives
* in @snowluma/core (`BridgeManager`), which is wired in by the top-level
* app entry. Declaring it here keeps @snowluma/bridge free of any
* dependency on @snowluma/core — the hook package is self-contained.
*/
export interface HookSink {
export interface BridgeManagerSink {
onHookLogin(pid: number, uin: string, packetClient: PacketSender): void;
onPacket(pkt: PacketInfo): void;
onPidDisconnected(pid: number): void;
}
export type HookManagerDeps = {
sink: HookSink;
bridgeManager: BridgeManagerSink;
/** Sink for parsed packets from any live HookSession. Defaults to
* `sink.onPacket` — every packet flows straight into the per-UIN
* channel dispatcher with no intermediate event emitter. */
* `bridgeManager.onPacket` — every packet flows straight into the
* per-UIN bridge dispatcher with no intermediate event emitter. */
onPacket?: PacketSink;
/** Native injector entrypoints. Defaults to the real native addon. */
injector?: HookSessionDeps['injector'];
@@ -60,7 +59,7 @@ export type HookManagerDeps = {
* Responsibilities:
* - Route user commands (load/unload/refresh) to the matching session.
* - Route watcher diff events to the matching session.
* - Forward session events ('login' / 'disconnected') to the `HookSink`.
* - Forward session events ('login' / 'disconnected') to BridgeManager.
* - Retry stuck-in-connecting sessions on every watcher tick (so a
* failed connect eventually recovers without a manual refresh).
*
@@ -69,7 +68,7 @@ export type HookManagerDeps = {
* real QQ.exe or a native addon.
*/
export class HookManager {
private readonly sink: HookSink;
private readonly bridgeManager: BridgeManagerSink;
private readonly onPacket: PacketSink;
private readonly injector: HookSessionDeps['injector'];
private readonly makeClient: HookSessionDeps['makeClient'];
@@ -84,8 +83,8 @@ export class HookManager {
private disposed = false;
constructor(deps: HookManagerDeps) {
this.sink = deps.sink;
this.onPacket = deps.onPacket ?? ((pkt) => deps.sink.onPacket(pkt));
this.bridgeManager = deps.bridgeManager;
this.onPacket = deps.onPacket ?? ((pkt) => deps.bridgeManager.onPacket(pkt));
this.log = deps.log ?? createLogger('Hook');
this.injector = deps.injector ?? {
@@ -249,10 +248,10 @@ export class HookManager {
session.attachProcessInfo({ name: defaultProcessName() });
session.on('login', (uin: string, sender) => {
this.sink.onHookLogin(pid, uin, sender);
this.bridgeManager.onHookLogin(pid, uin, sender);
});
session.on('disconnected', (wasLoggedIn: boolean) => {
if (wasLoggedIn) this.sink.onPidDisconnected(pid);
if (wasLoggedIn) this.bridgeManager.onPidDisconnected(pid);
});
session.on('disposed', () => {
this.sessions.delete(pid);
@@ -313,4 +312,3 @@ export function shouldAutoLoadPid(pid: number, log: Logger): boolean {
export type { HookProcessBaseInfo } from './injector';
export type { QqPortLoginInfo } from './qq-port-probe';
export type { HookProcessInfo, HookProcessStatus } from './types';
@@ -20,8 +20,8 @@ export type HookSessionDeps = {
isPipeLive: (pid: number) => boolean;
tickNow?: () => Promise<void>;
};
/** Sink for parsed packets. Called with the canonical PacketInfo
* shape for every packet received while logged in. If omitted,
/** Sink for parsed packets. Called with the BridgeManager-shaped
* PacketInfo for every packet received while logged in. If omitted,
* packets are dropped (useful in unit tests that don't care). */
onPacket?: PacketSink;
log?: Logger;
@@ -35,7 +35,7 @@ export type HookSessionDeps = {
* promise chain so user clicks (load/unload/refresh) and watcher-driven
* events (onPipeUp/onPipeDown) never interleave.
*
* Communication: emits high-level events instead of calling the sink
* Communication: emits high-level events instead of calling BridgeManager
* directly, so HookManager forwards them and tests can attach spies.
*
* Emitted events:
@@ -406,7 +406,7 @@ export class HookSession extends EventEmitter {
const uin = packet.uin || this._uin;
if (!isRealUin(uin)) return;
if (!this.onPacket) return;
// Re-shape the hook-client wire packet into the canonical PacketInfo
// Re-shape the hook-client wire packet into BridgeManager's PacketInfo
// shape. Used to live in the deleted NtqqHandler.onHookPacket; field
// renaming was that module's entire purpose, so it lives at the source
// now (no need for a single-listener event-emitter in between).
+5
View File
@@ -0,0 +1,5 @@
export {
HookManager, type BridgeManagerSink, type HookManagerDeps, type HookProcessBaseInfo, type HookProcessInfo,
type HookProcessStatus, type QqPortLoginInfo
} from './hook-manager';
@@ -55,9 +55,9 @@ function defaultProcessName(): string {
function nativeSearchDirs(): string[] {
// Several layouts must be supported:
// 1. Released zip (flattened dist/): __dirname=<extracted>/, native at <extracted>/native
// 2. Dev via tsx (packages/channel/src/injector.ts): __dirname=<root>/packages/channel/src
// 2. Dev via tsx (packages/bridge/src/injector.ts): __dirname=<root>/packages/bridge/src
// → walk up to <root>/packages and append runtime/native
// Same offset works for `packages/channel/dist/index.mjs` after build.
// Same offset works for `packages/bridge/dist/index.mjs` after build.
// 3. cwd-based fallback when neither __dirname-relative path resolves.
return [
path.resolve(__dirname, 'native'),
File renamed without changes.
@@ -6,7 +6,7 @@ import path from 'path';
import { HookManager, shouldAutoLoadPid } from '../src/hook-manager';
import { PipeWatcher } from '../src/pipe-watcher';
import type { ManualMapHandle } from '../src/injector';
import type { HookSink } from '../src/hook-manager';
import type { BridgeManagerSink } from '../src/hook-manager';
import type { QqHookClient } from '../src/qq-hook-client';
import { createLogger } from '@snowluma/common/logger';
@@ -37,13 +37,13 @@ function makeManager(opts: {
(c as any).close = () => { (c as any).isClosed = true; };
return c as unknown as QqHookClient;
});
const sink = {
const bridgeManager = {
onPacket: vi.fn(),
onHookLogin: vi.fn(),
onPidDisconnected: vi.fn(),
} as unknown as HookSink;
} as unknown as BridgeManagerSink;
const manager = new HookManager({
sink,
bridgeManager,
pipeWatcher,
injector: { inject, unload },
makeClient,
@@ -9,7 +9,7 @@ import { EventEmitter } from 'events';
import { HookManager } from '../src/hook-manager';
import { PipeWatcher } from '../src/pipe-watcher';
import type { ManualMapHandle } from '../src/injector';
import type { HookSink } from '../src/hook-manager';
import type { BridgeManagerSink } from '../src/hook-manager';
import type { QqHookClient } from '../src/qq-hook-client';
const DUMMY_HANDLE: ManualMapHandle = { base: 0n, entry: 0n, exceptionTable: 0n, size: 0 };
@@ -41,14 +41,14 @@ describe('HookManager — Docker reconnect-without-login leak guard', () => {
intervalMs: 60_000, // manual ticks only
});
const sink = {
const bridgeManager = {
onPacket: vi.fn(),
onHookLogin: vi.fn(),
onPidDisconnected: vi.fn(),
} as unknown as HookSink;
} as unknown as BridgeManagerSink;
const manager = new HookManager({
sink,
bridgeManager,
pipeWatcher,
injector: {
inject: vi.fn(() => ({ method: 'loadModuleManual' as const, handle: DUMMY_HANDLE })),
@@ -82,9 +82,9 @@ describe('HookManager — Docker reconnect-without-login leak guard', () => {
// The "QQ never logs in" hypothesis: BridgeManager should never have
// been told about a login or a disconnect.
expect(sink.onHookLogin).not.toHaveBeenCalled();
expect(sink.onPidDisconnected).not.toHaveBeenCalled();
expect(sink.onPacket).not.toHaveBeenCalled();
expect(bridgeManager.onHookLogin).not.toHaveBeenCalled();
expect(bridgeManager.onPidDisconnected).not.toHaveBeenCalled();
expect(bridgeManager.onPacket).not.toHaveBeenCalled();
// Hook layer should hold at most one live client.
const alive = clients.filter(c => !c.isClosed);
@@ -1,9 +1,7 @@
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"types": [
"node"
],
"types": ["node"],
"noEmit": true
},
"include": [
File renamed without changes.
-174
View File
@@ -1,174 +0,0 @@
import type { ChannelAdapter, ChannelAdapterHost } from '@snowluma/channel';
import type { PacketSender } from '@snowluma/common/packet-sender';
import type { PacketInfo } from '@snowluma/common/protocol-types';
import { HookChannel } from './hook-channel';
import { HookManager, type HookManagerDeps, type HookSink } from './hook-manager';
/** Subset of `HookManagerDeps` the operator is allowed to forward
* through the adapter. The `sink` is owned by the adapter itself and
* intentionally not exposed. */
export type HookAdapterOptions = Omit<HookManagerDeps, 'sink'>;
/**
* `HookAdapter` — the `ChannelAdapter` for the NTQQ hook runtime. It
* owns the `HookManager` and translates its three sink callbacks
* (`onHookLogin` / `onPacket` / `onPidDisconnected`) into lifecycle
* events on a per-UIN `HookChannel`.
*
* Why an adapter rather than letting the `Hub` keep the hook sink:
* this is the only place in the codebase that legitimately needs to
* know about PIDs. Quarantining that knowledge here keeps the `Hub`
* (and everything above it) free of `pid`, leaving the door open for
* a future `SocketAdapter` that doesn't have the concept at all.
*
* Internal bookkeeping:
*
* - `pidToUin` — quick "which UIN does this PID feed?" lookup,
* populated on login (and lazily during defensive
* packet routing for PIDs that arrived ahead of
* their login notification).
* - `pidToSender` — the live `PacketSender` per PID, so a re-login
* from the same PID rotates the outbound sender
* without dropping the channel.
* - `uinToPids` — reverse index for fast "did this UIN lose its
* last PID?" checks on disconnect.
* - `channelsByUin` — one `HookChannel` per UIN; the hub only sees
* `Channel` instances, never the PID set living
* inside them.
*/
export class HookAdapter implements ChannelAdapter, HookSink {
readonly kind = 'inject' as const;
private readonly hookManager_: HookManager;
private readonly pidToUin = new Map<number, string>();
private readonly pidToSender = new Map<number, PacketSender>();
private readonly uinToPids = new Map<string, Set<number>>();
private readonly channelsByUin = new Map<string, HookChannel>();
private host_: ChannelAdapterHost | null = null;
private disposed_ = false;
constructor(opts: HookAdapterOptions = {}) {
// `sink: this` wires HookManager → adapter sink. The HookManager
// doesn't know about the broader ChannelAdapter contract; it only
// sees the three sink methods we implement below.
this.hookManager_ = new HookManager({ ...opts, sink: this });
}
/** The underlying `HookManager`, exposed so WebUI can keep its
* `/api/processes/*` endpoints pointing at the hook process table.
* Higher-level code (OneBot, channel consumers) MUST NOT reach into
* this — that's the whole point of the adapter layer. */
get hookManager(): HookManager { return this.hookManager_; }
// ─── ChannelAdapter contract ─────────────────────────────────────
start(host: ChannelAdapterHost): void {
this.host_ = host;
host.log.debug('hook adapter started');
}
dispose(): void {
if (this.disposed_) return;
this.disposed_ = true;
// Tear down hook sessions first so no more sink callbacks fire.
this.hookManager_.dispose();
// Then proactively remove every channel we published; the hub
// will call `channel.dispose()` on its way out.
for (const id of [...this.channelsByUin.values()].map(c => c.id)) {
this.host_?.removeChannel(id);
}
this.pidToUin.clear();
this.pidToSender.clear();
this.uinToPids.clear();
this.channelsByUin.clear();
this.host_ = null;
}
// ─── HookSink contract (called by HookManager) ──────────────────
onHookLogin(pid: number, uin: string, packetClient: PacketSender): void {
if (this.disposed_ || !isRealUin(uin)) return;
this.recordPidMapping(pid, uin, packetClient);
const channel = this.ensureChannel(uin);
channel.attachPid(pid, packetClient);
}
onPacket(pkt: PacketInfo): void {
if (this.disposed_ || !pkt.uin || !isRealUin(pkt.uin)) return;
const uin = pkt.uin;
const channel = this.ensureChannel(uin);
// Defensive: a packet may arrive before its login notification
// when the channel is being re-adopted (SnowLuma restarted while
// the hook stayed resident in QQ.exe). If we have a sender for
// this PID, weave it in so subsequent sends through this channel
// succeed.
if (pkt.pid) {
const sender = this.pidToSender.get(pkt.pid);
if (sender && !this.pidToUin.has(pkt.pid)) {
this.recordPidMapping(pkt.pid, uin, sender);
channel.attachPid(pkt.pid, sender);
}
}
channel.deliverPacket(pkt);
}
onPidDisconnected(pid: number): void {
if (this.disposed_) return;
this.pidToSender.delete(pid);
const uin = this.pidToUin.get(pid);
if (!uin) return;
this.pidToUin.delete(pid);
const pids = this.uinToPids.get(uin);
if (pids) {
pids.delete(pid);
if (pids.size === 0) this.uinToPids.delete(uin);
}
const channel = this.channelsByUin.get(uin);
if (!channel) return;
channel.detachPid(pid);
if (channel.isEmpty) {
this.channelsByUin.delete(uin);
this.host_?.removeChannel(channel.id);
}
}
// ─── internal ────────────────────────────────────────────────────
private recordPidMapping(pid: number, uin: string, sender: PacketSender): void {
this.pidToUin.set(pid, uin);
this.pidToSender.set(pid, sender);
let pids = this.uinToPids.get(uin);
if (!pids) {
pids = new Set();
this.uinToPids.set(uin, pids);
}
pids.add(pid);
}
private ensureChannel(uin: string): HookChannel {
let channel = this.channelsByUin.get(uin);
if (channel) return channel;
channel = new HookChannel(uin);
this.channelsByUin.set(uin, channel);
this.host_?.addChannel(channel);
return channel;
}
}
// QQ uins are 5-12 decimal digits; "0" is the hook's "no login yet"
// sentinel. Anything else (empty, alpha, too short) is a sign the hook
// callback fired before login info was probed — we ignore those.
function isRealUin(uin: string): boolean {
if (!uin || uin === '0') return false;
return /^\d+$/.test(uin) && uin.length >= 5;
}
-82
View File
@@ -1,82 +0,0 @@
import { Channel } from '@snowluma/channel';
import type { PacketSender, SendPacketResult } from '@snowluma/common/packet-sender';
/**
* `HookChannel` — concrete transport backed by the in-process NTQQ
* hook. One UIN may be served simultaneously by several injected
* processes; the channel therefore tracks an unordered set of PIDs and
* keeps a single live `PacketSender` (the most recently logged-in
* pipe) for outbound traffic.
*
* PID bookkeeping is scoped to this transport because the socket-only
* runtime never has the concept; quarantining it here keeps the
* abstract `Channel` and the `Hub` free of pid awareness.
*
* The owning `HookAdapter` is responsible for calling
* `attachPid(pid, sender)` on every successful hook login,
* `detachPid(pid)` when the watcher reports a pipe drop, and tearing
* the channel down once `isEmpty` returns true.
*/
export class HookChannel extends Channel {
readonly kind = 'inject' as const;
readonly uin: string;
private readonly pids_ = new Set<number>();
private packetClient_: PacketSender | null = null;
constructor(uin: string) {
super();
this.uin = uin;
}
get id(): string { return `inject:${this.uin}`; }
/** PIDs currently routing packets into this channel. Read-only view
* for diagnostics — mutate only via `attachPid` / `detachPid`. */
get pids(): ReadonlySet<number> { return this.pids_; }
/** True iff no PID is currently bound; the adapter uses this to
* decide when to remove the channel from the `Hub`. */
get isEmpty(): boolean { return this.pids_.size === 0; }
/** Bind a freshly-logged-in PID (and its outbound `PacketSender`)
* to this channel. Idempotent — re-binding the same PID just rotates
* the active sender. */
attachPid(pid: number, sender: PacketSender): void {
this.pids_.add(pid);
this.packetClient_ = sender;
}
/** Forget a PID. If it owned the active sender we drop it; the next
* `attachPid` (or pipe-up) will install a fresh one. */
detachPid(pid: number): void {
this.pids_.delete(pid);
if (this.pids_.size === 0) {
this.packetClient_ = null;
}
}
override async sendRawPacket(
serviceCmd: string,
body: Uint8Array,
timeoutMs = 15000,
): Promise<SendPacketResult> {
const client = this.packetClient_;
if (!client) {
return {
success: false,
gotResponse: false,
errorCode: -1,
errorMessage: 'hook channel has no live packet sender',
responseData: null,
};
}
return client.sendPacket(serviceCmd, Buffer.from(body), timeoutMs);
}
override dispose(): void {
super.dispose();
this.packetClient_ = null;
this.pids_.clear();
}
}
-15
View File
@@ -1,15 +0,0 @@
// `@snowluma/channel-hook` — the `inject` channel implementation
// (NTQQ in-process hook). Registered with `Hub` from `@snowluma/core`
// as a `ChannelAdapter` of kind `'inject'`. Everything pid-related is
// scoped to this package — neither `@snowluma/channel` nor anything
// downstream knows about it.
// ─── Hook runtime ──────────────────────────────────────────────────
export {
HookManager, type HookSink, type HookManagerDeps, type HookProcessBaseInfo, type HookProcessInfo,
type HookProcessStatus, type QqPortLoginInfo
} from './hook-manager';
// ─── Concrete Channel + Adapter ────────────────────────────────────
export { HookChannel } from './hook-channel';
export { HookAdapter, type HookAdapterOptions } from './hook-adapter';
-34
View File
@@ -1,34 +0,0 @@
{
"name": "@snowluma/channel-socket",
"version": "1.9.2",
"private": true,
"type": "module",
"description": "SnowLuma `socket` channel implementation — placeholder for the future pure-socket runtime (no QQ.exe, no hook). Today registers as a no-op `ChannelAdapter` so the Hub-adapter architecture is exercised end-to-end. Will gain a `SocketClient` long-lived TCP login session when the protocol runtime lands.",
"main": "./src/index.ts",
"types": "./src/index.ts",
"exports": {
".": {
"types": "./src/index.ts",
"default": "./src/index.ts"
},
"./socket-channel": {
"types": "./src/socket-channel.ts",
"default": "./src/socket-channel.ts"
},
"./socket-adapter": {
"types": "./src/socket-adapter.ts",
"default": "./src/socket-adapter.ts"
}
},
"scripts": {
"typecheck": "tsc --noEmit"
},
"dependencies": {
"@snowluma/channel": "workspace:*",
"@snowluma/common": "workspace:*"
},
"devDependencies": {
"@types/node": "^24.12.2",
"typescript": "catalog:"
}
}
-8
View File
@@ -1,8 +0,0 @@
// `@snowluma/channel-socket` — future pure-socket transport (no
// QQ.exe, no hook). Today an empty stub so `Hub` can register it as a
// `ChannelAdapter` of kind `'socket'` and exercise the adapter pool
// end-to-end. Will materialise a real `SocketChannel` once the
// pure-socket login client lands.
export { SocketChannel } from './socket-channel';
export { SocketAdapter } from './socket-adapter';
@@ -1,30 +0,0 @@
import type { ChannelAdapter, ChannelAdapterHost } from '@snowluma/channel';
/**
* `SocketAdapter` — placeholder for the future pure-socket runtime.
* Once a `SocketClient` (long-lived TCP login session, heartbeat,
* reconnect loop, …) lands, this adapter will:
*
* 1. Read its account list from runtime config.
* 2. Spin up one `SocketClient` per configured account.
* 3. On successful login, materialise a `SocketChannel` and call
* `host.addChannel(channel)`.
* 4. On logout / fatal error, call `host.removeChannel(channel.id)`.
*
* Until that lands the adapter is registered as a no-op so the wider
* architecture (Hub → ChannelAdapter[] → Channel → Core) is already in
* place and exercised in production. Registering it is harmless:
* `start()` does nothing, `dispose()` does nothing, no channels are
* ever produced.
*/
export class SocketAdapter implements ChannelAdapter {
readonly kind = 'socket' as const;
start(host: ChannelAdapterHost): void {
host.log.debug('socket adapter is a stub; no socket clients will be opened');
}
dispose(): void {
// Nothing to tear down yet.
}
}
@@ -1,41 +0,0 @@
import { Channel } from '@snowluma/channel';
import type { SendPacketResult } from '@snowluma/common/packet-sender';
/**
* `SocketChannel` — placeholder transport for the future pure-socket
* runtime (no QQ.exe, no hook). It already participates in the `Hub`
* (in `@snowluma/core`) so the wider architecture (ChannelAdapter pool
* → Hub → Core → OneBot) is exercised end-to-end today; once a real
* `SocketClient` lands the transport will gain a constructor argument
* and `sendRawPacket` will route through it.
*
* Until then `sendRawPacket` returns a structured "not implemented"
* failure rather than throwing, so the surrounding code treats it as
* a regular transport-down result.
*/
export class SocketChannel extends Channel {
readonly kind = 'socket' as const;
readonly uin: string;
constructor(uin: string) {
super();
this.uin = uin;
}
get id(): string { return `socket:${this.uin}`; }
override async sendRawPacket(
serviceCmd: string,
body: Uint8Array,
timeoutMs?: number,
): Promise<SendPacketResult> {
void serviceCmd; void body; void timeoutMs;
return {
success: false,
gotResponse: false,
errorCode: -1,
errorMessage: 'socket channel transport is not yet implemented',
responseData: null,
};
}
}
-44
View File
@@ -1,44 +0,0 @@
{
"name": "@snowluma/channel",
"version": "1.9.2",
"private": true,
"type": "module",
"description": "SnowLuma transport abstract layer. Defines the `Channel` abstract base + `ChannelCtx` capability POJO + `ChannelAdapter` port that `Hub` (in @snowluma/core) consumes. Concrete transports live in `@snowluma/channel-hook` (in-process NTQQ hook) and `@snowluma/channel-socket` (future pure-socket).",
"main": "./src/index.ts",
"types": "./src/index.ts",
"exports": {
".": {
"types": "./src/index.ts",
"default": "./src/index.ts"
},
"./channel": {
"types": "./src/channel.ts",
"default": "./src/channel.ts"
},
"./channel-interface": {
"types": "./src/channel-interface.ts",
"default": "./src/channel-interface.ts"
},
"./channel-ctx": {
"types": "./src/channel-ctx.ts",
"default": "./src/channel-ctx.ts"
},
"./adapter": {
"types": "./src/adapter.ts",
"default": "./src/adapter.ts"
}
},
"scripts": {
"test": "vitest run --passWithNoTests",
"typecheck": "tsc --noEmit"
},
"dependencies": {
"@snowluma/common": "workspace:*"
},
"devDependencies": {
"@types/node": "^24.12.2",
"typescript": "catalog:",
"vite": "catalog:",
"vitest": "^4.1.4"
}
}
-15
View File
@@ -1,15 +0,0 @@
import type { Logger } from '@snowluma/common/logger';
import type { Channel } from './channel';
import type { ChannelKind } from './channel-interface';
export interface ChannelAdapterHost {
addChannel(channel: Channel): void;
removeChannel(channelId: string): void;
readonly log: Logger;
}
export interface ChannelAdapter {
readonly kind: ChannelKind;
start(host: ChannelAdapterHost): Promise<void> | void;
dispose(): Promise<void> | void;
}
-26
View File
@@ -1,26 +0,0 @@
import type { SendPacketResult } from '@snowluma/common/packet-sender';
import type { PacketInfo } from '@snowluma/common/protocol-types';
import type { Channel } from './channel';
import type { ChannelKind } from './channel-interface';
export interface ChannelCtx {
readonly uin: string;
readonly kind: ChannelKind;
readonly sendRawPacket: (
serviceCmd: string,
body: Uint8Array,
timeoutMs?: number,
) => Promise<SendPacketResult>;
readonly onPacket: (handler: ((pkt: PacketInfo) => void) | null) => void;
readonly dispose: () => void;
}
export function makeChannelCtx(channel: Channel): ChannelCtx {
return {
uin: channel.uin,
kind: channel.kind,
sendRawPacket: (cmd, body, timeoutMs) => channel.sendRawPacket(cmd, body, timeoutMs),
onPacket: (handler) => channel.setPacketHandler(handler),
dispose: () => channel.dispose(),
};
}
-73
View File
@@ -1,73 +0,0 @@
import type { SendPacketResult } from '@snowluma/common/packet-sender';
import type { PacketInfo } from '@snowluma/common/protocol-types';
/**
* Discriminator for the two channel transport implementations:
*
* - `'inject'` — backed by an in-process NTQQ hook (one or more
* QQ.exe processes injected with the SnowLuma DLL,
* talking over named pipes). Implemented by
* `HookChannel` in `@snowluma/channel-hook`.
* - `'socket'` — backed by a direct protocol client (no QQ.exe, no
* hook). Reserved for the future pure-protocol
* runtime; `SocketChannel` is a stub until then.
*
* Mirrored on `CoreCtx.kind` so account-level consumers can branch on
* transport without `instanceof` checks against a concrete subclass
* (diagnostics, kind-specific WebUI panels, …).
*/
export type ChannelKind = 'inject' | 'socket';
/**
* `ChannelInterface` — **strictly transport**. A channel owns one
* wire-level connection to QQ for a given UIN: it sends opaque packets
* out and surfaces received packets to whoever subscribed via
* `setPacketHandler`.
*
* It deliberately knows nothing about identity caches, the event bus,
* the api hub, or the cmd-dispatch pipeline — that machinery lives on
* the `Core` layer (`@snowluma/core`) which wraps a `Channel` (via a
* `ChannelCtx` capability POJO) to expose a business-level API to
* OneBot and friends.
*
* Direct consumers are limited to:
* - `ChannelAdapter` implementations (they create / dispose channels
* and pump received packets through `deliverPacket`),
* - `Hub` in `@snowluma/core` (the only place that turns a `Channel`
* into a `ChannelCtx` and hands the ctx to `Core`),
* - `Core` (only via the `ChannelCtx` projection; never holds a
* Channel reference directly).
*
* OneBot and api modules NEVER import `ChannelInterface`; they consume
* `CoreCtx` from `@snowluma/core`.
*/
export interface ChannelInterface {
/** Transport family backing this channel. */
readonly kind: ChannelKind;
/** Stable, unique-per-live-channel id inside the `Hub`
* (e.g. `'inject:3161592748'`). */
readonly id: string;
/** QQ number this transport carries. */
readonly uin: string;
/** Wire-level send. The only escape hatch the apis layer eventually
* routes through (via `Core.sendRawPacket` → `ChannelCtx.sendRawPacket`). */
sendRawPacket(
serviceCmd: string,
body: Uint8Array,
timeoutMs?: number,
): Promise<SendPacketResult>;
/** Subscribe to inbound packets. Called once by `Hub` (via
* `ChannelCtx.onPacket`) when a `Core` is constructed on top of this
* channel. Passing `null` detaches. */
setPacketHandler(handler: ((pkt: PacketInfo) => void) | null): void;
/** Adapter-side hook: feed a freshly-received packet into the
* current subscriber (if any). Called by `ChannelAdapter`s when
* their underlying runtime delivers a frame. */
deliverPacket(pkt: PacketInfo): void;
/** Release transport-side resources. Idempotent. */
dispose(): void;
}
-34
View File
@@ -1,34 +0,0 @@
import type { SendPacketResult } from '@snowluma/common/packet-sender';
import type { PacketInfo } from '@snowluma/common/protocol-types';
import type { ChannelInterface, ChannelKind } from './channel-interface';
export abstract class Channel implements ChannelInterface {
abstract readonly kind: ChannelKind;
abstract readonly id: string;
abstract readonly uin: string;
abstract sendRawPacket(
serviceCmd: string,
body: Uint8Array,
timeoutMs?: number,
): Promise<SendPacketResult>;
private packetHandler_: ((pkt: PacketInfo) => void) | null = null;
private disposed_ = false;
setPacketHandler(handler: ((pkt: PacketInfo) => void) | null): void {
this.packetHandler_ = handler;
}
deliverPacket(pkt: PacketInfo): void {
this.packetHandler_?.(pkt);
}
get isDisposed(): boolean { return this.disposed_; }
dispose(): void {
if (this.disposed_) return;
this.disposed_ = true;
this.packetHandler_ = null;
}
}
View File
Whitespace-only changes.
-5
View File
@@ -1,5 +0,0 @@
export { type ChannelAdapter, type ChannelAdapterHost } from './adapter';
export { Channel } from './channel';
export { makeChannelCtx, type ChannelCtx } from './channel-ctx';
export { type ChannelInterface, type ChannelKind } from './channel-interface';
-16
View File
@@ -1,16 +0,0 @@
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"types": [
"node"
],
"noEmit": true
},
"include": [
"src/**/*",
"tests"
],
"exclude": [
"node_modules"
]
}
-8
View File
@@ -1,8 +0,0 @@
import { defineConfig } from 'vitest/config';
export default defineConfig({
test: {
include: ['tests/**/*.test.ts'],
environment: 'node',
},
});
+16 -17
View File
@@ -10,25 +10,25 @@
"types": "./src/index.ts",
"default": "../../dist/index.mjs"
},
"./core": {
"types": "./src/core.ts",
"default": "./src/core.ts"
"./bridge": {
"types": "./src/bridge/bridge.ts",
"default": "./src/bridge/bridge.ts"
},
"./core-context": {
"types": "./src/core-context.ts",
"default": "./src/core-context.ts"
"./bridge-interface": {
"types": "./src/bridge/bridge-interface.ts",
"default": "./src/bridge/bridge-interface.ts"
},
"./core-ctx": {
"types": "./src/core-ctx.ts",
"default": "./src/core-ctx.ts"
"./bridge-context": {
"types": "./src/bridge/bridge-context.ts",
"default": "./src/bridge/bridge-context.ts"
},
"./hub": {
"types": "./src/hub.ts",
"default": "./src/hub.ts"
"./manager": {
"types": "./src/bridge/manager.ts",
"default": "./src/bridge/manager.ts"
},
"./apis": {
"types": "./src/apis/index.ts",
"default": "./src/apis/index.ts"
"types": "./src/bridge/apis/index.ts",
"default": "./src/bridge/apis/index.ts"
}
},
"scripts": {
@@ -40,14 +40,13 @@
"typecheck": "tsc --noEmit"
},
"dependencies": {
"@snowluma/channel": "workspace:*",
"@snowluma/channel-hook": "workspace:*",
"@snowluma/channel-socket": "workspace:*",
"@snowluma/bridge": "workspace:*",
"@snowluma/common": "workspace:*",
"@snowluma/onebot": "workspace:*",
"@snowluma/protocol": "workspace:*",
"@snowluma/proto-defs": "workspace:*",
"@snowluma/proton": "workspace:*",
"@snowluma/sqlite": "workspace:*",
"@snowluma/websocket": "workspace:*"
},
"devDependencies": {
@@ -12,22 +12,8 @@ import type {
QQGroupInfo,
UserProfileInfo,
} from '@snowluma/protocol/qq-info';
import type { CoreContext } from '../core-context';
/**
* One row of an `OidbSvcTrpcTcp.0x9067_202` (download rkey) response.
* Cached for the duration of `ttlSeconds` and consumed by the OneBot
* media-URL resolver / message converter when a download URL must be
* minted on the fly. Lives at the apis layer (not on `Bridge`) because
* only `apis.contacts.fetchDownloadRKeys` materialises these rows.
*/
export interface DownloadRKeyInfo {
rkey: string;
ttlSeconds: number;
storeId: number;
createTime: number;
type: number;
}
import type { DownloadRKeyInfo } from '../bridge';
import type { BridgeContext } from '../bridge-context';
// ─── Helpers (previously in bridge-contacts.ts) ───────────────────
@@ -77,7 +63,7 @@ export class ContactsApi {
private memberListInflight = new Map<number, Promise<GroupMemberInfo[]>>();
private memberListLastFetch = new Map<number, { at: number; data: GroupMemberInfo[] }>();
constructor(private readonly ctx: CoreContext) { }
constructor(private readonly ctx: BridgeContext) { }
async fetchFriendList(): Promise<FriendInfo[]> {
const friends: FriendInfo[] = [];
@@ -5,7 +5,7 @@ import {
} from '@snowluma/protocol/oidb-services/extras/fetch-ai-voice-list';
import { GetStrangerStatus, type StrangerStatus as NamespaceStrangerStatus } from '@snowluma/protocol/oidb-services/extras/get-stranger-status';
import { GroupTodo } from '@snowluma/protocol/oidb-services/extras/group-todo';
import type { CoreContext } from '../core-context';
import type { BridgeContext } from '../bridge-context';
import type { MediaIndexNode } from './shared';
// ─────────────── public types (re-exported from bridge.ts as before) ───
@@ -27,7 +27,7 @@ export interface AiVoiceItem {
}
export class ExtrasApi {
constructor(private readonly ctx: CoreContext) { }
constructor(private readonly ctx: BridgeContext) { }
// ─────────────── Group todo (0xF90) ───────────────
@@ -7,16 +7,18 @@ import type {
SendLongMsgResp,
} from '@snowluma/proto-defs/longmsg';
import type { FileExtra, PushMsg, PushMsgBody } from '@snowluma/proto-defs/message';
import type { BridgeContext } from '@snowluma/protocol/bridge-context';
import { buildSendElems } from '@snowluma/protocol/element-builder';
import type { ForwardNodePayload, MessageElement } from '@snowluma/protocol/events';
import { parseMsgPush } from '@snowluma/protocol/msg-push';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import { randomUUID } from 'crypto';
import { gunzipSync, gzipSync } from 'zlib';
import type { CoreContext } from '../core-context';
import type { Bridge } from '../bridge';
import type { BridgeContext } from '../bridge-context';
import { resolveSelfUid, toInt } from './shared';
function asBridge(ctx: BridgeContext): Bridge { return ctx as unknown as Bridge; }
// Module-scoped cache, keyed by res_id. Survives only for the lifetime
// of the process — that's enough because OneBot clients typically
// resolve a forward immediately after receiving the parent message.
@@ -60,7 +62,7 @@ function hexToBytesLocal(hex: string): Uint8Array {
}
async function buildForwardPushBody(
bridge: BridgeContext,
bridge: Bridge,
node: ForwardNodePayload,
groupId?: number,
userUid?: string,
@@ -201,7 +203,7 @@ function previewFromElements(elements: MessageElement[]): string {
}
export class ForwardApi {
constructor(private readonly ctx: CoreContext) { }
constructor(private readonly ctx: BridgeContext) { }
async upload(nodes: ForwardNodePayload[], groupId?: number, userId?: number): Promise<string> {
const { resId } = await this.uploadRecursive(nodes, groupId, userId);
@@ -231,7 +233,7 @@ export class ForwardApi {
throw new Error('forward nodes are required');
}
const bridge = this.ctx;
const bridge = asBridge(this.ctx);
// For a private forward to `userId`, any image/record/video inside a node
// needs the recipient's uid as upload scene. Resolve it once up-front,
@@ -376,7 +378,7 @@ export class ForwardApi {
}
async fetch(resId: string): Promise<ForwardNodePayload[]> {
const bridge = this.ctx;
const bridge = asBridge(this.ctx);
const cached = forwardResCache.get(resId);
if (cached) {
return cached.map(node => ({
@@ -1,10 +1,10 @@
import { DeleteFriend } from '@snowluma/protocol/oidb-services/friend/delete-friend';
import { HandleFriendRequest } from '@snowluma/protocol/oidb-services/friend/handle-friend-request';
import { SetFriendRemark } from '@snowluma/protocol/oidb-services/friend/set-friend-remark';
import type { CoreContext } from '../core-context';
import type { BridgeContext } from '../bridge-context';
export class FriendApi {
constructor(private readonly ctx: CoreContext) { }
constructor(private readonly ctx: BridgeContext) { }
/**
* Accept or reject an inbound friend request. `uidOrFlag` is either a
@@ -12,10 +12,10 @@ import { SetGroupRemark } from '@snowluma/protocol/oidb-services/group-admin/set
import { SetMemberCard } from '@snowluma/protocol/oidb-services/group-admin/set-member-card';
import { SetSearch } from '@snowluma/protocol/oidb-services/group-admin/set-search';
import { SetSpecialTitle } from '@snowluma/protocol/oidb-services/group-admin/set-special-title';
import type { CoreContext } from '../core-context';
import type { BridgeContext } from '../bridge-context';
export class GroupAdminApi {
constructor(private readonly ctx: CoreContext) { }
constructor(private readonly ctx: BridgeContext) { }
muteMember(groupId: number, userId: number, duration: number): Promise<void> {
return MuteMember.invoke(this.ctx, { groupId, userId, duration });
@@ -12,7 +12,7 @@ import type {
} from '@snowluma/proto-defs/oidb-actions/group-album';
import { getGroupAlbumList, uploadImageToGroupAlbum } from '@snowluma/protocol/web/group-album';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { CoreContext } from '../core-context';
import type { BridgeContext } from '../bridge-context';
function convertBigIntToString(obj: unknown): JsonValue {
@@ -31,7 +31,7 @@ function convertBigIntToString(obj: unknown): JsonValue {
}
export class GroupAlbumApi {
constructor(private readonly ctx: CoreContext) { }
constructor(private readonly ctx: BridgeContext) { }
// 列出群相册(基于 qzone.qq.com 的 HTTP Cookie)。
async list(groupId: number): Promise<GroupAlbumList> {
@@ -4,7 +4,8 @@ import type { FileUploadExt } from '@snowluma/proto-defs/highway';
import { fetchHighwaySession, uploadHighwayHttp } from '@snowluma/protocol/highway';
import { computeHashes, computeMd5, FILE_UPLOAD_MAX_BYTES, loadBinarySource } from '@snowluma/protocol/highway/utils';
import { protobuf_encode } from '@snowluma/proton';
import type { CoreContext } from '../core-context';
import type { Bridge } from '../bridge';
import type { BridgeContext } from '../bridge-context';
import { resolveSelfUid, toInt, type MediaIndexNode } from './shared';
import { CreateGroupFolder } from '@snowluma/protocol/oidb-services/group-file/create-group-folder';
@@ -27,6 +28,8 @@ import { ensureRetCodeZero } from '@snowluma/protocol/oidb-services/shared';
const log = createLogger('GroupFile');
function asBridge(ctx: BridgeContext): Bridge { return ctx as unknown as Bridge; }
// ─────────────── public result types ───────────────
export interface GroupFileInfo {
@@ -214,7 +217,7 @@ function buildPrivateFileUploadExt(
}
export class GroupFileApi {
constructor(private readonly ctx: CoreContext) { }
constructor(private readonly ctx: BridgeContext) { }
// ─────────────── publish (group file → chat) ───────────────
@@ -238,7 +241,7 @@ export class GroupFileApi {
folderId = '/',
uploadFile = true,
): Promise<UploadFileResult> {
const bridge = this.ctx;
const bridge = asBridge(this.ctx);
// Group/private files may legitimately be up to 4 GiB on QQ's wire,
// so override the default 1 GiB cap with the protocol ceiling.
const loaded = await loadBinarySource(source, 'file', FILE_UPLOAD_MAX_BYTES);
@@ -338,7 +341,7 @@ export class GroupFileApi {
name = '',
uploadFile = true,
): Promise<UploadFileResult> {
const bridge = this.ctx;
const bridge = asBridge(this.ctx);
const loaded = await loadBinarySource(source, 'file', FILE_UPLOAD_MAX_BYTES);
if (!loaded.bytes.length) throw new Error('private file is empty');
@@ -577,7 +580,7 @@ export class GroupFileApi {
}
async getPrivateUrl(userId: number, fileId: string, fileHash: string): Promise<string> {
const bridge = this.ctx;
const bridge = asBridge(this.ctx);
const selfUid = await resolveSelfUid(bridge);
void userId;
const result = await GetPrivateFileUrl.invoke(this.ctx, { selfUid, fileId, fileHash });
@@ -624,7 +627,7 @@ export class GroupFileApi {
}
async getPrivatePttUrl(node: MediaIndexNode): Promise<string> {
const bridge = this.ctx;
const bridge = asBridge(this.ctx);
const selfUid = await resolveSelfUid(bridge);
return GetPrivatePttUrl.invoke(this.ctx, { selfUid, node });
}
@@ -634,7 +637,7 @@ export class GroupFileApi {
}
async getPrivateVideoUrl(node: MediaIndexNode): Promise<string> {
const bridge = this.ctx;
const bridge = asBridge(this.ctx);
const selfUid = await resolveSelfUid(bridge);
return GetPrivateVideoUrl.invoke(this.ctx, { selfUid, node });
}
@@ -1,4 +1,4 @@
import type { CoreContext } from '../core-context';
import type { BridgeContext } from '../bridge-context';
import { ContactsApi } from './contacts';
import { ExtrasApi } from './extras';
import { ForwardApi } from './forward';
@@ -47,7 +47,7 @@ export interface ApiHub {
* runtime-mutated `apis.xxx` slots, neither of which is worth the
* complexity for ~13 small classes.
*/
export function buildApiHub(ctx: CoreContext): ApiHub {
export function buildApiHub(ctx: BridgeContext): ApiHub {
return {
message: new MessageApi(ctx),
contacts: new ContactsApi(ctx),
@@ -67,21 +67,16 @@ export function buildApiHub(ctx: CoreContext): ApiHub {
// Re-export the Api classes themselves so callers can write
// `import type { MessageApi } from '@snowluma/core/.../apis'` for
// signature use. Concrete instances always come from `bridge.apis.*`.
export { ContactsApi, type DownloadRKeyInfo } from './contacts';
export {
AiVoiceChatType, ExtrasApi, type AiVoiceCategory,
type AiVoiceItem,
type StrangerStatus
} from './extras';
export { ContactsApi } from './contacts';
export { ExtrasApi } from './extras';
export { ForwardApi } from './forward';
export { FriendApi } from './friend';
export { GroupAdminApi } from './group-admin';
export { GroupAlbumApi } from './group-album';
export { GroupFileApi } from './group-file';
export { InteractionApi } from './interaction';
export { MessageApi, type SendMessageReceipt } from './message';
export { MessageApi } from './message';
export { MiscApi } from './misc';
export { ProfileApi } from './profile';
export { type MediaIndexNode } from './shared';
export { WebApi, type ClientKeyInfo, type WebHonorInfo, type WebNoticeInfo } from './web';
export { WebApi } from './web';
@@ -12,10 +12,10 @@ import { SetEssence } from '@snowluma/protocol/oidb-services/interaction/set-ess
import { FetchReactionSummary } from '@snowluma/protocol/oidb-services/reaction/fetch-reaction-summary';
import { GetEmojiLikes } from '@snowluma/protocol/oidb-services/reaction/get-emoji-likes';
import { SetReaction } from '@snowluma/protocol/oidb-services/reaction/set-reaction';
import type { CoreContext } from '../core-context';
import type { BridgeContext } from '../bridge-context';
export class InteractionApi {
constructor(private readonly ctx: CoreContext) { }
constructor(private readonly ctx: BridgeContext) { }
sendPoke(isGroup: boolean, peerUin: number, targetUin?: number): Promise<void> {
return SendPoke.invoke(this.ctx, { isGroup, peerUin, targetUin });
@@ -11,26 +11,21 @@ import type {
import { buildSendElems } from '@snowluma/protocol/element-builder';
import type { MessageElement } from '@snowluma/protocol/events';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { CoreContext } from '../core-context';
/**
* Receipt returned by every typed `send*Message` call. The OneBot
* adapter feeds these into its `MessageStore` so later `recall_msg`
* actions can resolve the wire-level coordinates (sequence + random)
* from the `message_id` it previously emitted.
*/
export interface SendMessageReceipt {
messageId: number;
sequence: number;
clientSequence: number;
random: number;
timestamp: number;
}
import type { BridgeContext } from '../bridge-context';
// `Bridge` is imported as a type only so we can narrow `ctx` back to
// the concrete Bridge instance when passing it to `buildSendElems`
// (which still takes `Bridge` because the highway upload helpers it
// transitively calls each take `Bridge` — refactoring those is a
// separate concern that doesn't need to land alongside the Api split).
//
// At runtime `ctx` IS the Bridge instance that constructed this
// MessageApi — `buildApiHub(ctx)` passes the Bridge itself.
import type { Bridge, SendMessageReceipt } from '../bridge';
const SEND_MSG_CMD = 'MessageSvc.PbSendMsg';
export class MessageApi {
constructor(private readonly ctx: CoreContext) { }
constructor(private readonly ctx: BridgeContext) { }
/**
* Send a message to a QQ group.
@@ -46,7 +41,7 @@ export class MessageApi {
async sendGroup(groupId: number, elements: MessageElement[]): Promise<SendMessageReceipt> {
if (elements.length === 0) throw new Error('message is empty');
const protoElems = await buildSendElems(elements, { bridge: this.ctx, groupId });
const protoElems = await buildSendElems(elements, { bridge: this.ctx as unknown as Bridge, groupId });
const random = this.ctx.nextMessageRandom();
const request = protobuf_encode<SendMessageRequest>({
@@ -102,7 +97,7 @@ export class MessageApi {
userUid = await this.ctx.resolveUserUid(userUin);
}
const protoElems = await buildSendElems(elements, { bridge: this.ctx, userUid });
const protoElems = await buildSendElems(elements, { bridge: this.ctx as unknown as Bridge, userUid });
const random = this.ctx.nextMessageRandom();
const clientSeq = this.ctx.nextClientSequence();
@@ -4,14 +4,14 @@ import type {
MiniAppShareResp,
} from '@snowluma/proto-defs/oidb-actions/base';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { BridgeContext } from '../bridge-context';
// Migrated OIDB cmds — facade methods are one-line forwarders.
import { ClickInlineKeyboardButton } from '@snowluma/protocol/oidb-services/misc/click-inline-keyboard-button';
import { SendGroupSign } from '@snowluma/protocol/oidb-services/misc/send-group-sign';
import { TranslateEnToZh } from '@snowluma/protocol/oidb-services/misc/translate-en-to-zh';
import type { CoreContext } from '../core-context';
export class MiscApi {
constructor(private readonly ctx: CoreContext) { }
constructor(private readonly ctx: BridgeContext) { }
translateEn2Zh(words: string[]): Promise<string[]> {
return TranslateEnToZh.invoke(this.ctx, { words });
@@ -13,10 +13,13 @@ import { SetInputStatus } from '@snowluma/protocol/oidb-services/profile/set-inp
import { SetProfile } from '@snowluma/protocol/oidb-services/profile/set-profile';
import { SetSelfLongNick } from '@snowluma/protocol/oidb-services/profile/set-self-long-nick';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { CoreContext } from '../core-context';
import type { Bridge } from '../bridge';
import type { BridgeContext } from '../bridge-context';
function asBridge(ctx: BridgeContext): Bridge { return ctx as unknown as Bridge; }
export class ProfileApi {
constructor(private readonly ctx: CoreContext) { }
constructor(private readonly ctx: BridgeContext) { }
// ─────────────── status / profile setters ───────────────
@@ -79,7 +82,7 @@ export class ProfileApi {
}
async setAvatar(source: string): Promise<void> {
const bridge = this.ctx;
const bridge = asBridge(this.ctx);
const loaded = await loadBinarySource(source, 'avatar');
if (!loaded.bytes.length) throw new Error('avatar file is empty');
@@ -99,7 +102,7 @@ export class ProfileApi {
* Source ref: Lagrange.Core/Internal/Context/Logic/Implementation/OperationLogic.cs#GroupSetAvatar.
*/
async setGroupAvatar(groupId: number, source: string): Promise<void> {
const bridge = this.ctx;
const bridge = asBridge(this.ctx);
const loaded = await loadBinarySource(source, 'group-avatar');
if (!loaded.bytes.length) throw new Error('group avatar file is empty');
@@ -1,5 +1,4 @@
import type { BridgeContext } from '@snowluma/protocol/bridge-context';
import type { Bridge } from '../bridge';
export function toInt(value: unknown): number {
if (typeof value === 'number' && Number.isFinite(value)) return Math.trunc(value);
@@ -32,7 +31,7 @@ export function ensureRetCodeZero(operation: string, code: unknown, msg: unknown
* `selfProfile`; forward/profile actions need this fast path before
* warmup completes.
*/
export async function resolveSelfUid(bridge: BridgeContext): Promise<string> {
export async function resolveSelfUid(bridge: Bridge): Promise<string> {
let selfUid = bridge.identity.selfUid;
if (selfUid) return selfUid;
@@ -1,4 +1,3 @@
import type { BridgeContext } from '@snowluma/protocol/bridge-context';
import { ForceFetchClientKey, type ClientKeyInfo as NamespaceClientKeyInfo } from '@snowluma/protocol/oidb-services/web/force-fetch-client-key';
import { GetPskey } from '@snowluma/protocol/oidb-services/web/get-pskey';
import { getGroupEssenceMsg, getGroupEssenceMsgAll, type GroupEssenceMsgRet } from '@snowluma/protocol/web/group-essence';
@@ -11,7 +10,10 @@ import {
type SetNoticeRetSuccess,
} from '@snowluma/protocol/web/group-notice';
import { RequestUtil } from '@snowluma/protocol/web/request-util';
import type { CoreContext } from '../core-context';
import type { Bridge } from '../bridge';
import type { BridgeContext } from '../bridge-context';
function asBridge(ctx: BridgeContext): Bridge { return ctx as unknown as Bridge; }
export type ClientKeyInfo = NamespaceClientKeyInfo;
@@ -42,15 +44,15 @@ export interface WebNoticeInfo {
// ─────────────── private helpers (cookie acquisition) ───────────────
function forceFetchClientKeyInner(bridge: BridgeContext): Promise<ClientKeyInfo> {
function forceFetchClientKeyInner(bridge: Bridge): Promise<ClientKeyInfo> {
return ForceFetchClientKey.invoke(bridge);
}
function getPSkey(bridge: BridgeContext, domainList: string[]): Promise<{ domainPskeyMap: Map<string, string> }> {
function getPSkey(bridge: Bridge, domainList: string[]): Promise<{ domainPskeyMap: Map<string, string> }> {
return GetPskey.invoke(bridge, { domainList });
}
async function getCookies(bridge: BridgeContext, domain: string): Promise<Record<string, string>> {
async function getCookies(bridge: Bridge, domain: string): Promise<Record<string, string>> {
const ClientKeyData = await forceFetchClientKeyInner(bridge);
// Build the ptlogin2 jump URL: this is the canonical way for the
@@ -80,7 +82,7 @@ async function getCookies(bridge: BridgeContext, domain: string): Promise<Record
return data;
}
async function getSKey(bridge: BridgeContext): Promise<string> {
async function getSKey(bridge: Bridge): Promise<string> {
const ClientKeyData = await forceFetchClientKeyInner(bridge);
if (!ClientKeyData.clientKey) {
@@ -117,23 +119,23 @@ function getBknFromSKey(skey: string): number {
}
export class WebApi {
constructor(private readonly ctx: CoreContext) { }
constructor(private readonly ctx: BridgeContext) { }
// ─────────────── cookie / token primitives ───────────────
async forceFetchClientKey(): Promise<ClientKeyInfo> {
return forceFetchClientKeyInner(this.ctx);
return forceFetchClientKeyInner(asBridge(this.ctx));
}
/** Fetch the cookie jar for a `qq.com` subdomain. Used by GroupAlbumApi
* (qzone.qq.com) and by every other web helper here. */
async getCookies(domain: string): Promise<Record<string, string>> {
return getCookies(this.ctx, domain);
return getCookies(asBridge(this.ctx), domain);
}
/** Cookies for `domain` joined into the canonical "k=v; k=v" header form. */
async getCookiesStr(domain: string): Promise<string> {
const cookieObject = await getCookies(this.ctx, domain);
const cookieObject = await getCookies(asBridge(this.ctx), domain);
return Object.entries(cookieObject)
.map(([key, value]) => `${key}=${value}`)
.join('; ');
@@ -141,7 +143,7 @@ export class WebApi {
/** CSRF token == bkn(skey) — used by qzone / qun web APIs. */
async getCsrfToken(): Promise<number> {
const skey = await getSKey(this.ctx);
const skey = await getSKey(asBridge(this.ctx));
if (!skey) {
throw new Error('SKey is Empty');
}
@@ -150,7 +152,7 @@ export class WebApi {
/** Returns the OneBot `get_credentials` payload (cookie string + bkn). */
async getCredentials(domain: string): Promise<{ cookies: string; token: number; csrf_token: number }> {
const cookieObject = await getCookies(this.ctx, domain);
const cookieObject = await getCookies(asBridge(this.ctx), domain);
const cookiesStr = Object.entries(cookieObject)
.map(([key, value]) => `${key}=${value}`)
.join('; ');
@@ -169,7 +171,7 @@ export class WebApi {
/** Paginated fetch — `pageStart` is 0-indexed, `pageLimit` is server-capped at 50. */
async getEssence(groupId: number, pageStart = 0, pageLimit = 50): Promise<GroupEssenceMsgRet> {
const bridge = this.ctx;
const bridge = asBridge(this.ctx);
const groupCode = groupId.toString();
const cookieObject = await getCookies(bridge, 'qun.qq.com');
const essenceData = await getGroupEssenceMsg(cookieObject, groupCode, pageStart, pageLimit);
@@ -178,7 +180,7 @@ export class WebApi {
/** Walks every page and returns the concatenated result. */
async getEssenceAll(groupId: number): Promise<GroupEssenceMsgRet[]> {
const bridge = this.ctx;
const bridge = asBridge(this.ctx);
const groupCode = groupId.toString();
const cookieObject = await getCookies(bridge, 'qun.qq.com');
return await getGroupEssenceMsgAll(cookieObject, groupCode);
@@ -187,7 +189,7 @@ export class WebApi {
// ─────────────── group honor ───────────────
async getHonorInfo(groupId: number, type: WebHonorType | string): Promise<WebHonorInfo> {
const bridge = this.ctx;
const bridge = asBridge(this.ctx);
const groupCode = groupId.toString();
const cookieObject = await getCookies(bridge, 'qun.qq.com');
@@ -236,7 +238,7 @@ export class WebApi {
confirm_required?: number;
},
): Promise<SetNoticeRetSuccess> {
const bridge = this.ctx;
const bridge = asBridge(this.ctx);
const groupCode = groupId.toString();
const cookieObject = await getCookies(bridge, 'qun.qq.com');
@@ -286,7 +288,7 @@ export class WebApi {
}
async getNotice(groupId: number): Promise<WebNoticeInfo[]> {
const bridge = this.ctx;
const bridge = asBridge(this.ctx);
const groupCode = groupId.toString();
const cookieObject = await getCookies(bridge, 'qun.qq.com');
@@ -327,7 +329,7 @@ export class WebApi {
}
async deleteNotice(groupId: number, fid: string): Promise<boolean> {
const bridge = this.ctx;
const bridge = asBridge(this.ctx);
const groupCode = groupId.toString();
const cookieObject = await getCookies(bridge, 'qun.qq.com');
return await deleteGroupNoticeHttp(cookieObject, groupCode, fid);
@@ -0,0 +1,8 @@
import type { BridgeContext as BaseBridgeContext } from '@snowluma/protocol/bridge-context';
import type { ApiHub } from './apis';
export interface BridgeContext extends BaseBridgeContext {
readonly apis: ApiHub;
}
export type { UploadedFileMeta } from '@snowluma/protocol/bridge-context';
@@ -0,0 +1,5 @@
import type { BridgeContext } from './bridge-context';
export interface BridgeInterface extends BridgeContext {
readonly activePid: number | null;
}
+183
View File
@@ -0,0 +1,183 @@
import type { PacketSender, SendPacketResult } from '@snowluma/common/packet-sender';
import type { PacketInfo } from '@snowluma/common/protocol-types';
import { BridgeEventBus } from '@snowluma/protocol/event-bus';
import { IdentityService } from '@snowluma/protocol/identity-service';
import { MSG_PUSH_CMD, parseMsgPush } from '@snowluma/protocol/msg-push';
import { IncomingPacketPipeline, type CmdParser } from '@snowluma/protocol/packet-pipeline';
import { buildApiHub, type ApiHub } from './apis';
import {
AiVoiceChatType,
type AiVoiceCategory,
type StrangerStatus,
} from './apis/extras';
import type { BridgeInterface } from './bridge-interface';
export class Bridge implements BridgeInterface {
readonly identity: IdentityService;
private pids_ = new Set<number>();
readonly events = new BridgeEventBus();
readonly apis: ApiHub;
private readonly pipeline: IncomingPacketPipeline;
private packetClient_: PacketSender | null = null;
private static readonly UPLOADED_FILE_CACHE_MAX = 1024;
private uploadedFileMeta_ = new Map<string, UploadedFileMeta>();
private clientSeq_ = 100000000 + (Date.now() % 1000000000);
private msgRandom_ = (Date.now() & 0xFFFFFFFF) >>> 0;
constructor(identity: IdentityService) {
this.identity = identity;
this.apis = buildApiHub(this);
this.identity.setFetcher({
fetchProfile: (uin) => this.apis.contacts.fetchUserProfile(uin),
fetchGroupMemberList: (gid) => this.apis.contacts.fetchGroupMemberList(gid),
});
this.pipeline = new IncomingPacketPipeline({
identity: this.identity,
events: this.events,
refreshMemberCache: (groupId, refreshGroupList, forceMemberList) =>
this.refreshMemberCache(groupId, refreshGroupList, forceMemberList),
resolveStrangerProfile: async (uid) => {
try {
const p = await this.apis.contacts.fetchUserProfileByUid(uid);
if (p.uin <= 0) return null;
return { uin: p.uin, nickname: p.nickname };
} catch {
return null;
}
},
resolveGroupJoinRequest: async (groupId, uid, subType) => {
try {
const requests = await this.apis.contacts.fetchGroupRequests();
const match = requests.find(r => {
if (r.groupId !== groupId) return false;
return subType === 'invite' ? r.invitorUid === uid : r.targetUid === uid;
});
if (!match) return null;
return { comment: match.comment, sequence: match.sequence };
} catch {
return null;
}
},
});
this.pipeline.registerCmd(MSG_PUSH_CMD, parseMsgPush);
}
dispose(): void {
this.identity.close();
this.events.clear();
}
setPacketClient(client: PacketSender): void {
this.packetClient_ = client;
}
registerCmd(cmd: string, parser: CmdParser): void {
this.pipeline.registerCmd(cmd, parser);
}
handlesCmd(cmd: string): boolean {
return this.pipeline.handlesCmd(cmd);
}
attachPid(pid: number): void {
this.pids_.add(pid);
}
detachPid(pid: number): void {
this.pids_.delete(pid);
}
hasPid(pid: number): boolean { return this.pids_.has(pid); }
get empty(): boolean { return this.pids_.size === 0; }
get activePid(): number | null {
for (const pid of this.pids_) return pid;
return null;
}
onPacket(pkt: PacketInfo): void {
this.pipeline.process(pkt);
}
private async refreshMemberCache(groupId: number, refreshGroupList: boolean, forceMemberList: boolean): Promise<boolean> {
if (refreshGroupList) {
try { await this.apis.contacts.fetchGroupList(); } catch { /* ignore */ }
}
if (!this.identity.findGroup(groupId)) return false;
await this.apis.contacts.fetchGroupMemberList(groupId, { force: forceMemberList });
return true;
}
rememberUploadedFile(meta: UploadedFileMeta): void {
if (!meta.fileId) return;
if (this.uploadedFileMeta_.size >= Bridge.UPLOADED_FILE_CACHE_MAX) {
// Map iteration order is insertion order — drop the oldest.
const oldest = this.uploadedFileMeta_.keys().next().value;
if (oldest !== undefined) this.uploadedFileMeta_.delete(oldest);
}
this.uploadedFileMeta_.set(meta.fileId, meta);
}
recallUploadedFile(fileId: string): UploadedFileMeta | undefined {
if (!fileId) return undefined;
return this.uploadedFileMeta_.get(fileId);
}
nextClientSequence(): number {
return ++this.clientSeq_;
}
nextMessageRandom(): number {
this.msgRandom_ = (this.msgRandom_ + 0x9E3779B9) >>> 0;
return this.msgRandom_ & 0x7FFFFFFF;
}
async sendRawPacket(serviceCmd: string, body: Uint8Array, timeoutMs = 15000): Promise<SendPacketResult> {
if (!this.packetClient_) {
return {
success: false, gotResponse: false, errorCode: -1,
errorMessage: 'no packet sender attached', responseData: null,
};
}
return this.packetClient_.sendPacket(serviceCmd, Buffer.from(body), timeoutMs);
}
async resolveUserUid(uin: number, groupId?: number): Promise<string> {
return this.identity.resolveUid(uin, groupId);
}
}
export interface SendMessageReceipt {
messageId: number;
sequence: number;
clientSequence: number;
random: number;
timestamp: number;
}
export interface UploadedFileMeta {
fileId: string;
scope: 'group' | 'private';
/** Group id if scope='group', else `undefined`. */
groupId?: number;
/** Friend uin if scope='private', else `undefined`. */
userId?: number;
fileName: string;
fileSize: number;
fileMd5: Uint8Array;
fileSha1: Uint8Array;
/** Server-issued hash returned alongside the upload (private only). */
fileHash?: string;
/** Insert time — used to evict the oldest entry when the cache fills. */
rememberedAt: number;
}
export interface DownloadRKeyInfo {
rkey: string;
ttlSeconds: number;
storeId: number;
createTime: number;
type: number;
}
export interface ClientKeyInfo {
clientKey: string;
expireTime: string;
keyIndex: string
}
export { AiVoiceChatType };
export type { AiVoiceCategory, StrangerStatus };
+117
View File
@@ -0,0 +1,117 @@
import { createLogger } from '@snowluma/common/logger';
import type { PacketSender } from '@snowluma/common/packet-sender';
import type { PacketInfo } from '@snowluma/common/protocol-types';
import { IdentityService } from '@snowluma/protocol/identity-service';
import { Bridge } from './bridge';
export type SessionStartedCallback = (uin: string, bridge: Bridge) => void;
export type SessionClosedCallback = (uin: string) => void;
interface QQSession {
bridge: Bridge;
}
const log = createLogger('Bridge');
export class BridgeManager {
private sessions_ = new Map<string, QQSession>();
private pidToUin_ = new Map<number, string>();
private pidPacketClients_ = new Map<number, PacketSender>();
private onSessionStarted_: SessionStartedCallback | null = null;
private onSessionClosed_: SessionClosedCallback | null = null;
setSessionStartedCallback(cb: SessionStartedCallback): void { this.onSessionStarted_ = cb; }
setSessionClosedCallback(cb: SessionClosedCallback): void { this.onSessionClosed_ = cb; }
onPidDisconnected(pid: number): void {
this.pidPacketClients_.delete(pid);
const uin = this.pidToUin_.get(pid);
if (!uin) return;
this.pidToUin_.delete(pid);
const session = this.sessions_.get(uin);
if (!session) return;
session.bridge.detachPid(pid);
if (session.bridge.empty) {
this.sessions_.delete(uin);
log.debug('session closed: UIN=%s', uin);
if (this.onSessionClosed_) this.onSessionClosed_(uin);
session.bridge.dispose();
}
}
private static isRealUin(uin: string): boolean {
if (!uin || uin === '0') return false;
return /^\d+$/.test(uin) && uin.length >= 5;
}
onHookLogin(pid: number, uin: string, packetClient: PacketSender): void {
if (!BridgeManager.isRealUin(uin)) return;
this.pidPacketClients_.set(pid, packetClient);
const { session, created } = this.ensureSession(uin);
session.bridge.attachPid(pid);
session.bridge.setPacketClient(packetClient);
this.pidToUin_.set(pid, uin);
if (created) {
log.debug('session started: UIN=%s', uin);
if (this.onSessionStarted_) {
this.onSessionStarted_(uin, session.bridge);
}
}
}
onPacket(pkt: PacketInfo): void {
if (!pkt.uin || !BridgeManager.isRealUin(pkt.uin)) return;
const uin = pkt.uin;
// Ensure session exists
const { session, created } = this.ensureSession(uin);
// Attach PID if known
if (pkt.pid && this.pidPacketClients_.has(pkt.pid)) {
session.bridge.attachPid(pkt.pid);
this.pidToUin_.set(pkt.pid, uin);
const client = this.pidPacketClients_.get(pkt.pid);
if (client) session.bridge.setPacketClient(client);
}
// Notify session started on first real packet
if (created) {
log.debug('session started: UIN=%s', uin);
if (this.onSessionStarted_) {
this.onSessionStarted_(uin, session.bridge);
}
}
// Dispatch packet to bridge
session.bridge.onPacket(pkt);
}
private ensureSession(uin: string): { session: QQSession; created: boolean } {
let session = this.sessions_.get(uin);
if (session) return { session, created: false };
const bridge = new Bridge(IdentityService.openForUin(uin));
session = { bridge };
this.sessions_.set(uin, session);
// Each downstream consumer (e.g. OneBotInstance) subscribes to
// `bridge.events` directly via the per-kind bus — there is no longer a
// generic firehose to wire here.
return { session, created: true };
}
getSession(uin: string): QQSession | null {
return this.sessions_.get(uin) ?? null;
}
get sessions(): Map<string, { bridge: Bridge }> {
return this.sessions_;
}
}
-26
View File
@@ -1,26 +0,0 @@
import type { BridgeContext as ProtocolBridgeContext } from '@snowluma/protocol/bridge-context';
import type { ApiHub } from './apis';
/**
* `CoreContext` — the internal context that Api wrappers (`apis/*`)
* consume. Only used inside `@snowluma/core`; OneBot and other inbound
* adapters consume the narrower `CoreCtx` projection instead.
*
* It extends the protocol-layer `BridgeContext` with one extra slot:
* `apis: ApiHub`. The protocol layer can't mention `ApiHub` because
* the apis live in @snowluma/core, so the shared surface is layered:
*
* - `@snowluma/protocol/bridge-context.BridgeContext` — identity,
* events, raw packet I/O, sequences, file cache. Consumed by
* `element-builder`, highway uploaders, msg-push decoders.
* - `@snowluma/core/core-context.CoreContext` — adds `apis`.
* Consumed by everything inside `apis/*` and by tests that
* stub the surface for OneBot-side unit tests.
*
* The concrete `Core` class implements this extended interface.
*/
export interface CoreContext extends ProtocolBridgeContext {
readonly apis: ApiHub;
}
export type { UploadedFileMeta } from '@snowluma/protocol/bridge-context';
-34
View File
@@ -1,34 +0,0 @@
import type { ChannelKind } from '@snowluma/channel';
import type { CoreContext } from './core-context';
/**
* `CoreCtx` — the public surface every QQ account exposes to the rest
* of the system (OneBot, future MCP clients, WebUI status panels). It
* is the structural projection of a `Core` instance that consumers
* receive via `Hub.events.on('core-online', ...)`.
*
* Reading this type is the right starting point when wiring a new
* consumer:
*
* - `identity` / `events` / `apis` / sequence helpers / file cache
* are inherited from `CoreContext`.
* - `kind` / `id` / `uin` mirror the underlying channel's identity
* so consumers can branch on transport kind when they really need
* to (e.g. WebUI diagnostics) without `instanceof` checks.
* - `dispose()` is the lifecycle hook; `Hub` calls it when the
* underlying channel disappears.
*
* Day-to-day consumers should stay kind-agnostic — that's the entire
* point of the abstraction.
*/
export interface CoreCtx extends CoreContext {
/** Transport family backing this account. */
readonly kind: ChannelKind;
/** Stable, unique-per-account id (mirrors the channel's id). */
readonly id: string;
/** QQ number this account represents. Mirrors `identity.uin`. */
readonly uin: string;
/** Release identity DB handles, event subscribers, and any
* account-level resources. Idempotent. */
dispose(): void;
}
-181
View File
@@ -1,181 +0,0 @@
import type { ChannelCtx, ChannelKind } from '@snowluma/channel';
import type { SendPacketResult } from '@snowluma/common/packet-sender';
import type { PacketInfo } from '@snowluma/common/protocol-types';
import type { UploadedFileMeta } from '@snowluma/protocol/bridge-context';
import { BridgeEventBus } from '@snowluma/protocol/event-bus';
import { IdentityService } from '@snowluma/protocol/identity-service';
import { MSG_PUSH_CMD, parseMsgPush } from '@snowluma/protocol/msg-push';
import { IncomingPacketPipeline, type CmdParser } from '@snowluma/protocol/packet-pipeline';
import { buildApiHub, type ApiHub } from './apis';
import type { CoreCtx } from './core-ctx';
/**
* `Core` — the QQ-account-level business object that sits on top of a
* `Channel` transport (consumed indirectly via a `ChannelCtx`
* capability POJO). Owns everything OneBot, the apis, and the msg-push
* pipeline care about:
*
* - `identity` (per-uin SQLite-backed roster + uid↔uin index),
* - the typed `BridgeEventBus` (subscribe to per-account events by kind),
* - the `ApiHub` (typed wrappers around `sendRawPacket`),
* - the `IncomingPacketPipeline` (cmd → decoder → emit on bus),
* - the uploaded-file cache (shared between `upload_*_file` and
* `send_msg`),
* - the monotonic `clientSequence` / `messageRandom` counters.
*
* The transport is opaque: `Core` only calls `channelCtx.sendRawPacket`
* and subscribes via `channelCtx.onPacket` so all incoming packets flow
* into its pipeline. Swap the transport (hook → socket) and everything
* above keeps working unchanged because `Core` never holds the `Channel`
* itself — only the capability POJO.
*
* Lifecycle is managed by `Hub`: the hub registers `ChannelAdapter`s,
* builds a `ChannelCtx` from each freshly-available channel, materialises
* a `Core` on the way up, and calls `dispose()` on the way down. OneBot
* consumers see `CoreCtx` (the structural projection); never `Core`
* itself.
*/
export class Core implements CoreCtx {
readonly kind: ChannelKind;
readonly id: string;
readonly uin: string;
readonly identity: IdentityService;
readonly events = new BridgeEventBus();
readonly apis: ApiHub;
private readonly channelCtx_: ChannelCtx;
private readonly pipeline_: IncomingPacketPipeline;
private static readonly UPLOADED_FILE_CACHE_MAX = 1024;
private readonly uploadedFileMeta_ = new Map<string, UploadedFileMeta>();
private clientSeq_ = 100000000 + (Date.now() % 1000000000);
private msgRandom_ = (Date.now() & 0xFFFFFFFF) >>> 0;
private disposed_ = false;
constructor(channelCtx: ChannelCtx, identity: IdentityService = IdentityService.openForUin(channelCtx.uin)) {
this.channelCtx_ = channelCtx;
this.kind = channelCtx.kind;
this.id = `${channelCtx.kind}:${channelCtx.uin}`;
this.uin = channelCtx.uin;
this.identity = identity;
this.apis = buildApiHub(this);
this.identity.setFetcher({
fetchProfile: (uin) => this.apis.contacts.fetchUserProfile(uin),
fetchGroupMemberList: (gid) => this.apis.contacts.fetchGroupMemberList(gid),
});
this.pipeline_ = new IncomingPacketPipeline({
identity: this.identity,
events: this.events,
refreshMemberCache: (groupId, refreshGroupList, forceMemberList) =>
this.refreshMemberCache(groupId, refreshGroupList, forceMemberList),
resolveStrangerProfile: async (uid) => {
try {
const p = await this.apis.contacts.fetchUserProfileByUid(uid);
if (p.uin <= 0) return null;
return { uin: p.uin, nickname: p.nickname };
} catch {
return null;
}
},
resolveGroupJoinRequest: async (groupId, uid, subType) => {
try {
const requests = await this.apis.contacts.fetchGroupRequests();
const match = requests.find(r => {
if (r.groupId !== groupId) return false;
return subType === 'invite' ? r.invitorUid === uid : r.targetUid === uid;
});
if (!match) return null;
return { comment: match.comment, sequence: match.sequence };
} catch {
return null;
}
},
});
this.pipeline_.registerCmd(MSG_PUSH_CMD, parseMsgPush);
// Subscribe to inbound packets from the channel. The underlying
// `Channel` only supports a single subscriber (us); the
// `ChannelAdapter` pumps packets through `channel.deliverPacket`,
// which `Hub` wires into us via `channelCtx.onPacket`.
channelCtx.onPacket((pkt: PacketInfo) => this.pipeline_.process(pkt));
}
// ─── CoreCtx plumbing ────────────────────────────────────────────
dispose(): void {
if (this.disposed_) return;
this.disposed_ = true;
this.channelCtx_.onPacket(null);
this.identity.close();
this.events.clear();
}
get isDisposed(): boolean { return this.disposed_; }
// ─── Transport (proxied to the underlying Bridge) ──────────────
async sendRawPacket(
serviceCmd: string,
body: Uint8Array,
timeoutMs?: number,
): Promise<SendPacketResult> {
return this.channelCtx_.sendRawPacket(serviceCmd, body, timeoutMs);
}
// ─── Pipeline registration (used by tests + extra cmd modules) ─
registerCmd(cmd: string, parser: CmdParser): void {
this.pipeline_.registerCmd(cmd, parser);
}
handlesCmd(cmd: string): boolean {
return this.pipeline_.handlesCmd(cmd);
}
// ─── Send-side protocol helpers (shared sequence generators) ───
nextClientSequence(): number {
return ++this.clientSeq_;
}
nextMessageRandom(): number {
this.msgRandom_ = (this.msgRandom_ + 0x9E3779B9) >>> 0;
return this.msgRandom_ & 0x7FFFFFFF;
}
// ─── Uploaded-file cache ───────────────────────────────────────
rememberUploadedFile(meta: UploadedFileMeta): void {
if (!meta.fileId) return;
if (this.uploadedFileMeta_.size >= Core.UPLOADED_FILE_CACHE_MAX) {
// Map iteration order is insertion order — drop the oldest.
const oldest = this.uploadedFileMeta_.keys().next().value;
if (oldest !== undefined) this.uploadedFileMeta_.delete(oldest);
}
this.uploadedFileMeta_.set(meta.fileId, meta);
}
recallUploadedFile(fileId: string): UploadedFileMeta | undefined {
if (!fileId) return undefined;
return this.uploadedFileMeta_.get(fileId);
}
// ─── Identity convenience ──────────────────────────────────────
async resolveUserUid(uin: number, groupId?: number): Promise<string> {
return this.identity.resolveUid(uin, groupId);
}
// ─── Internal helpers ──────────────────────────────────────────
private async refreshMemberCache(
groupId: number,
refreshGroupList: boolean,
forceMemberList: boolean,
): Promise<boolean> {
if (refreshGroupList) {
try { await this.apis.contacts.fetchGroupList(); } catch { /* ignore */ }
}
if (!this.identity.findGroup(groupId)) return false;
await this.apis.contacts.fetchGroupMemberList(groupId, { force: forceMemberList });
return true;
}
}
-238
View File
@@ -1,238 +0,0 @@
import {
makeChannelCtx,
type Channel,
type ChannelAdapter,
type ChannelAdapterHost,
type ChannelKind,
} from '@snowluma/channel';
import { createLogger, type Logger } from '@snowluma/common/logger';
import { Core } from './core';
import type { CoreCtx } from './core-ctx';
const log = createLogger('Hub');
export type HubEventMap = {
'core-online': CoreCtx;
'core-offline': { uin: string };
};
export type HubEventHandler<K extends keyof HubEventMap> = (payload: HubEventMap[K]) => void;
export type HubEventDisposer = () => void;
class HubEvents {
private readonly listeners_ = new Map<keyof HubEventMap, Set<(p: unknown) => void>>();
on<K extends keyof HubEventMap>(event: K, handler: HubEventHandler<K>): HubEventDisposer {
let set = this.listeners_.get(event);
if (!set) {
set = new Set();
this.listeners_.set(event, set);
}
const wrapped = handler as (p: unknown) => void;
set.add(wrapped);
return () => set!.delete(wrapped);
}
emit<K extends keyof HubEventMap>(event: K, payload: HubEventMap[K]): void {
const set = this.listeners_.get(event);
if (!set || set.size === 0) return;
for (const handler of [...set]) {
try {
(handler as HubEventHandler<K>)(payload);
} catch (err) {
log.warn('hub listener (%s) threw: %s', event, err instanceof Error ? err.message : String(err));
}
}
}
clear(): void {
this.listeners_.clear();
}
}
export class Hub {
private readonly adapters_ = new Map<ChannelKind, ChannelAdapter>();
private readonly channelsById_ = new Map<string, Channel>();
private readonly channelsByUin_ = new Map<string, Channel>();
// ─── core pool (was AccountManager) ──────────────────────────────
private readonly cores_ = new Map<string, Core>();
// ─── lifecycle event bus ──────────────────────────────────────────
readonly events = new HubEvents();
private started_ = false;
private disposed_ = false;
// ─── adapter registration ────────────────────────────────────────
/**
* Register a channel adapter. Must be called BEFORE `start()`; the
* hub enforces at most one adapter per `kind`.
*/
registerAdapter(adapter: ChannelAdapter): void {
if (this.started_) {
throw new Error('Hub: cannot register adapters after start()');
}
if (this.adapters_.has(adapter.kind)) {
throw new Error(`Hub: adapter of kind '${adapter.kind}' is already registered`);
}
this.adapters_.set(adapter.kind, adapter);
}
getAdapter(kind: ChannelKind): ChannelAdapter | null {
return this.adapters_.get(kind) ?? null;
}
// ─── lifecycle ───────────────────────────────────────────────────
/** Start every registered adapter. Idempotent. */
async start(): Promise<void> {
if (this.started_) return;
this.started_ = true;
for (const [kind, adapter] of this.adapters_) {
const host = this.makeHost(kind);
try {
await adapter.start(host);
} catch (err) {
log.warn('adapter [%s] failed to start: %s', kind,
err instanceof Error ? (err.stack ?? err.message) : String(err));
}
}
}
/** Dispose every adapter (which removes their channels via the
* host), then dispose any cores/channels that somehow remain.
* Idempotent. */
async dispose(): Promise<void> {
if (this.disposed_) return;
this.disposed_ = true;
for (const [kind, adapter] of this.adapters_) {
try {
await adapter.dispose();
} catch (err) {
log.warn('adapter [%s] failed to dispose: %s', kind,
err instanceof Error ? err.message : String(err));
}
}
for (const core of this.cores_.values()) {
try { core.dispose(); } catch { /* ignore */ }
}
for (const channel of this.channelsById_.values()) {
try { channel.dispose(); } catch { /* ignore */ }
}
this.cores_.clear();
this.channelsById_.clear();
this.channelsByUin_.clear();
this.events.clear();
}
// ─── queries ─────────────────────────────────────────────────────
/** The `Core` (full business object) for a UIN, or `null` if no
* account is online. Internal-ish — callers typically work with
* `CoreCtx` received from the `'core-online'` event instead. */
getCore(uin: string): Core | null {
return this.cores_.get(uin) ?? null;
}
getCores(): readonly Core[] {
return [...this.cores_.values()];
}
/** Channel for a UIN, or `null` if the UIN is offline. */
getChannel(uin: string): Channel | null {
return this.channelsByUin_.get(uin) ?? null;
}
getOnlineUins(): readonly string[] {
return [...this.channelsByUin_.keys()];
}
// ─── ChannelAdapterHost implementation (per-adapter) ─────────────
private makeHost(kind: ChannelKind): ChannelAdapterHost {
const adapterLog = log.child({ adapter: kind });
return {
log: adapterLog,
addChannel: (channel) => this.addChannel(channel, adapterLog),
removeChannel: (id) => this.removeChannel(id, adapterLog),
};
}
private addChannel(channel: Channel, adapterLog: Logger): void {
if (this.disposed_) return;
if (this.channelsById_.has(channel.id)) {
adapterLog.warn('addChannel: id=%s already registered, ignoring', channel.id);
return;
}
const existing = this.channelsByUin_.get(channel.uin);
if (existing) {
adapterLog.warn('addChannel: UIN=%s already has channel=%s, replacing with %s',
channel.uin, existing.id, channel.id);
this.channelsById_.delete(existing.id);
this.channelsById_.set(channel.id, channel);
this.channelsByUin_.set(channel.uin, channel);
this.bringCoreOffline(channel.uin);
this.bringCoreOnline(channel.uin, channel);
try { existing.dispose(); } catch (err) {
adapterLog.debug('channel.dispose() threw: %s',
err instanceof Error ? err.message : String(err));
}
return;
}
this.channelsById_.set(channel.id, channel);
this.channelsByUin_.set(channel.uin, channel);
log.debug('account online: UIN=%s via %s', channel.uin, channel.id);
this.bringCoreOnline(channel.uin, channel);
}
private removeChannel(id: string, adapterLog: Logger): void {
const channel = this.channelsById_.get(id);
if (!channel) return;
this.channelsById_.delete(id);
const current = this.channelsByUin_.get(channel.uin);
const wasCurrent = current?.id === id;
if (wasCurrent) {
this.channelsByUin_.delete(channel.uin);
log.debug('account offline: UIN=%s', channel.uin);
this.bringCoreOffline(channel.uin);
}
try { channel.dispose(); } catch (err) {
adapterLog.debug('channel.dispose() threw: %s',
err instanceof Error ? err.message : String(err));
}
}
private bringCoreOnline(uin: string, channel: Channel): void {
// Defensive: stale core on the same UIN means we missed the
// offline event. Tear it down first so identity DB handles don't
// leak.
const stale = this.cores_.get(uin);
if (stale) {
log.warn('replacing stale core: UIN=%s id=%s', uin, stale.id);
try { stale.dispose(); } catch { /* ignore */ }
this.cores_.delete(uin);
}
const core = new Core(makeChannelCtx(channel));
this.cores_.set(uin, core);
this.events.emit('core-online', core);
}
private bringCoreOffline(uin: string): void {
const core = this.cores_.get(uin);
if (!core) return;
this.cores_.delete(uin);
this.events.emit('core-offline', { uin });
try { core.dispose(); } catch (err) {
log.debug('core.dispose() threw: %s', err instanceof Error ? err.message : String(err));
}
}
}
+7 -25
View File
@@ -1,9 +1,8 @@
import { HookAdapter } from '@snowluma/channel-hook';
import { SocketAdapter } from '@snowluma/channel-socket';
import { HookManager } from '@snowluma/bridge';
import { closeLogger, createLogger } from '@snowluma/common/logger';
import { loadRuntimeConfig } from '@snowluma/common/runtime';
import { OneBotManager } from '@snowluma/onebot/manager';
import { Hub } from './hub';
import { BridgeManager } from './bridge/manager';
const runtimeConfig = loadRuntimeConfig();
const log = createLogger('App');
@@ -11,28 +10,15 @@ const log = createLogger('App');
async function main() {
log.info('SnowLuma starting');
// `Hub` is the single multi-account entry point — it owns channel
// adapters (hook, socket), the per-uin `Core` map, and the
// `core-online` / `core-offline` lifecycle event bus. Adapters
// must be registered BEFORE hub.start().
const hub = new Hub();
const bridgeManager = new BridgeManager();
const oneBotManager = new OneBotManager();
const autoLoadOnDiscovery = resolveAutoLoad(runtimeConfig.hookAutoLoad);
const hookManager = new HookManager({ bridgeManager, autoLoadOnDiscovery });
if (autoLoadOnDiscovery) {
log.info('hook auto-load enabled: every discovered QQ process will be injected');
}
const hookAdapter = new HookAdapter({ autoLoadOnDiscovery });
hub.registerAdapter(hookAdapter);
hub.registerAdapter(new SocketAdapter());
// OneBot subscribes to Hub's two lifecycle events (`core-online` /
// `core-offline`) to materialise / tear down its per-account
// instances. Bind before start() so the very first login is
// delivered to OneBot.
oneBotManager.bind(hub);
await hub.start();
oneBotManager.bind(bridgeManager);
if (
(typeof __BUILD_WEBUI__ !== 'undefined' && __BUILD_WEBUI__) ||
@@ -40,11 +26,7 @@ async function main() {
) {
try {
const { initWebUI } = await import('./webui/server');
// The WebUI's process management surface is hook-specific (it
// exposes load/unload/refresh by PID); we hand it the
// adapter-owned HookManager directly. Future socket-only
// panels would receive their adapter through the same channel.
await initWebUI(runtimeConfig.webuiPort || 5099, oneBotManager, hookAdapter.hookManager);
await initWebUI(runtimeConfig.webuiPort || 5099, oneBotManager, hookManager);
} catch (err) {
log.error('Failed to start WebUI: ', err);
}
@@ -55,7 +37,7 @@ async function main() {
const shutdown = (signal: string) => async () => {
log.warn(`Shutting down (${signal})...`);
oneBotManager.dispose();
await hub.dispose();
hookManager.dispose();
await closeLogger();
process.exit(0);
};
+1 -1
View File
@@ -1,6 +1,6 @@
import { serve } from '@hono/node-server';
import { serveStatic } from '@hono/node-server/serve-static';
import type { HookManager, HookProcessInfo } from '@snowluma/channel-hook';
import type { HookManager, HookProcessInfo } from '@snowluma/bridge';
import { createLogger, getLogLevel, getRecentLogs, LOG_LEVELS, setLogLevel, subscribeLogs } from '@snowluma/common/logger';
import { loadOneBotConfig, saveOneBotConfig } from '@snowluma/onebot/config';
import type { OneBotManager } from '@snowluma/onebot/manager';
+3 -3
View File
@@ -1,3 +1,5 @@
import { describe, it, expect } from 'vitest';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type {
OidbGroupTodo,
@@ -10,13 +12,11 @@ import type {
OidbAiVoiceReq,
OidbAiVoiceResp,
} from '@snowluma/proto-defs/oidb-actions/media';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import { describe, expect, it } from 'vitest';
// Post-namespace migration: ExtrasApi forwards 6 OIDB cmds through
// namespaces under @snowluma/protocol/oidb-services/extras. Tests assert
// against bridge.sendRawPacket directly.
import { AiVoiceChatType, ExtrasApi } from '../../src/apis/extras';
import { ExtrasApi, AiVoiceChatType } from '../../src/bridge/apis/extras';
import { mockBridge } from './_helpers';
function packResponse(body: Uint8Array) {
@@ -23,7 +23,7 @@
// Mirrors NapCat's `PacketMsgFileElement.{buildElement,buildContent}`
// split.
import { describe, expect, it, vi } from 'vitest';
import { describe, it, expect, vi } from 'vitest';
vi.mock('@snowluma/protocol/bridge-oidb', () => ({
runOidb: vi.fn(async () => new Uint8Array()),
@@ -44,9 +44,9 @@ vi.mock('@snowluma/protocol/element-builder', () => ({
buildSendElems: buildSendElemsMock,
}));
import type { SendLongMsgResp } from '@snowluma/proto-defs/longmsg';
import { protobuf_encode } from '@snowluma/proton';
import { ForwardApi } from '../../src/apis/forward';
import type { SendLongMsgResp } from '@snowluma/proto-defs/longmsg';
import { ForwardApi } from '../../src/bridge/apis/forward';
import { mockBridge } from './_helpers';
function uploadResponseWithResId(resId: string) {
@@ -16,12 +16,12 @@
// dev/Lagrange.Core/.../Message/Entity/MultiMsgEntity.cs:43-115
// dev/NapCatQQ/.../helper/forward-msg-builder.ts:52-122
import type { Elem } from '@snowluma/proto-defs/element';
import type { LongMsgResult, SendLongMsgReq, SendLongMsgResp } from '@snowluma/proto-defs/longmsg';
import type { PushMsgBody } from '@snowluma/proto-defs/message';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import { describe, expect, it, vi } from 'vitest';
import { describe, it, expect, vi } from 'vitest';
import { gunzipSync, inflateSync } from 'zlib';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { SendLongMsgReq, SendLongMsgResp, LongMsgResult } from '@snowluma/proto-defs/longmsg';
import type { PushMsgBody } from '@snowluma/proto-defs/message';
import type { Elem } from '@snowluma/proto-defs/element';
// Don't mock element-builder — we WANT the real forward preview
// element to land in the encoded wire bytes so we can verify the
@@ -39,7 +39,7 @@ vi.mock('@snowluma/protocol/highway/video-upload', () => ({
uploadVideoMsgInfo: vi.fn(async () => new Uint8Array()),
}));
import { ForwardApi } from '../../src/apis/forward';
import { ForwardApi } from '../../src/bridge/apis/forward';
import { mockBridge } from './_helpers';
function uploadResponseWithResId(resId: string) {
+3 -3
View File
@@ -1,4 +1,4 @@
import { describe, expect, it, vi } from 'vitest';
import { describe, it, expect, vi } from 'vitest';
vi.mock('@snowluma/protocol/bridge-oidb', () => ({
runOidb: vi.fn(async () => new Uint8Array()),
@@ -14,9 +14,9 @@ vi.mock('@snowluma/protocol/element-builder', () => ({
buildSendElems: vi.fn(async () => []),
}));
import type { SendLongMsgResp } from '@snowluma/proto-defs/longmsg';
import { protobuf_encode } from '@snowluma/proton';
import { ForwardApi } from '../../src/apis/forward';
import type { SendLongMsgResp } from '@snowluma/proto-defs/longmsg';
import { ForwardApi } from '../../src/bridge/apis/forward';
import { mockBridge } from './_helpers';
function uploadResponseWithResId(resId: string) {
+3 -3
View File
@@ -1,17 +1,17 @@
import { describe, it, expect, vi } from 'vitest';
import { protobuf_decode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type {
OidbDeleteFriend,
OidbFriendRequestAction,
OidbSetFriendRemark,
} from '@snowluma/proto-defs/oidb-actions/base';
import { protobuf_decode } from '@snowluma/proton';
import { describe, expect, it, vi } from 'vitest';
// Post-namespace migration: FriendApi is a thin facade over the
// namespaces under @snowluma/protocol/oidb-services/friend. Tests assert
// against the bridge mock's sendRawPacket directly — no need for
// module-level bridge-oidb mocks anymore.
import { FriendApi } from '../../src/apis/friend';
import { FriendApi } from '../../src/bridge/apis/friend';
import { mockBridge } from './_helpers';
describe('apis/friend', () => {
@@ -1,9 +1,11 @@
import { describe, it, expect, vi } from 'vitest';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type {
Oidb0x89a_0AddOption,
Oidb0x89a_0Search,
Oidb0x8a0Req,
Oidb0x8a7Resp,
Oidb0x89a_0AddOption,
Oidb0x89a_0Search,
Oidb0xf16Req,
OidbGroupRequestAction,
OidbKickMember,
@@ -15,13 +17,11 @@ import type {
OidbSetAdmin,
OidbSpecialTitle,
} from '@snowluma/proto-defs/oidb-actions/base';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import { describe, expect, it, vi } from 'vitest';
// Post-namespace migration: GroupAdminApi forwards through namespaces
// under @snowluma/protocol/oidb-services/group-admin. Tests assert
// against bridge.sendRawPacket directly — no module-level mocks.
import { GroupAdminApi } from '../../src/apis/group-admin';
import { GroupAdminApi } from '../../src/bridge/apis/group-admin';
import { mockBridge } from './_helpers';
function packResponse(body: Uint8Array) {
@@ -1,18 +1,18 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type {
OidbGroupFileCountViewResp,
OidbGroupFileFolderResp,
OidbGroupFileReq,
OidbGroupFileResp,
OidbGroupFileViewResp,
OidbGroupFileFolderResp,
OidbGroupSendFileReq,
} from '@snowluma/proto-defs/oidb-actions/group-file';
import type {
NTV2RichMediaResp,
OidbPrivateFileUploadResp,
NTV2RichMediaResp,
} from '@snowluma/proto-defs/oidb-actions/media';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import { beforeEach, describe, expect, it, vi } from 'vitest';
// Post-namespace migration: GroupFileApi forwards single-OIDB methods
// through namespaces under @snowluma/protocol/oidb-services/group-file.
@@ -38,7 +38,7 @@ vi.mock('@snowluma/protocol/highway/utils', () => ({
}));
import * as highwayClient from '@snowluma/protocol/highway';
import { GroupFileApi } from '../../src/apis/group-file';
import { GroupFileApi } from '../../src/bridge/apis/group-file';
import { mockBridge } from './_helpers';
function packResponse(body: Uint8Array) {
@@ -4,7 +4,7 @@
// after #6 commit 1 moved the recall + markRead helpers onto MessageApi
// and #6 commit 6 absorbed setEssence into InteractionApi.
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { describe, it, expect, vi, beforeEach } from 'vitest';
vi.mock('@snowluma/protocol/bridge-oidb', () => ({
runOidb: vi.fn(async () => new Uint8Array()),
@@ -13,7 +13,7 @@ vi.mock('@snowluma/protocol/bridge-oidb', () => ({
decodeOidbEnv: vi.fn(() => ({ body: {} })),
}));
import { MessageApi } from '../../src/apis/message';
import { MessageApi } from '../../src/bridge/apis/message';
import { mockBridge } from './_helpers';
describe('apis/message — recall + markRead', () => {
@@ -1,14 +1,14 @@
import { describe, it, expect } from 'vitest';
import { protobuf_encode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type { Oidb0x9083Resp } from '@snowluma/proto-defs/oidb-actions/base';
import { protobuf_encode } from '@snowluma/proton';
import { describe, expect, it } from 'vitest';
// Post-namespace-migration: InteractionApi is a thin facade and
// production code routes through the namespace path (sender →
// sendRawPacket). Tests now assert against the bridge mock's
// sendRawPacket directly — no need for module-level mocks on the
// bridge-oidb internals.
import { InteractionApi } from '../../src/apis/interaction';
import { InteractionApi } from '../../src/bridge/apis/interaction';
import { mockBridge } from './_helpers';
describe('apis/interaction', () => {
+4 -4
View File
@@ -1,16 +1,16 @@
import { describe, it, expect, vi } from 'vitest';
import { protobuf_encode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type {
Oidb0x112eResp,
Oidb0x990Resp,
Oidb0x112eResp,
} from '@snowluma/proto-defs/oidb-actions/base';
import { protobuf_encode } from '@snowluma/proton';
import { describe, expect, it, vi } from 'vitest';
// Post-namespace migration: MiscApi forwards 3 OIDB cmds through
// @snowluma/protocol/oidb-services/misc namespaces. The non-OIDB
// `getMiniAppArk` (LightAppSvc) stays inline on the facade. Tests
// hit bridge.sendRawPacket directly.
import { MiscApi } from '../../src/apis/misc';
import { MiscApi } from '../../src/bridge/apis/misc';
import { mockBridge } from './_helpers';
function packResponse(body: Uint8Array) {
+13 -13
View File
@@ -1,3 +1,5 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type {
GroupAvatarExtra,
@@ -6,8 +8,6 @@ import type {
SetStatusReq,
SetStatusResp,
} from '@snowluma/proto-defs/oidb-actions/base';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import { beforeEach, describe, expect, it, vi } from 'vitest';
// `encodeOidbEnv` / `decodeOidbEnv` are proton-bound pass-through wrappers
// (substituted at the call site with the inlined codec). Mocking them on
@@ -38,7 +38,7 @@ vi.mock('@snowluma/protocol/highway/utils', () => ({
import * as oidb from '@snowluma/protocol/bridge-oidb';
import * as highwayClient from '@snowluma/protocol/highway';
import { ProfileApi } from '../../src/apis/profile';
import { ProfileApi } from '../../src/bridge/apis/profile';
import { mockBridge } from './_helpers';
describe('apis/profile', () => {
@@ -52,14 +52,14 @@ describe('apis/profile', () => {
it('setOnlineStatus sends to status_svc.SetStatus and accepts an empty response', async () => {
const bridge = mockBridge();
await new ProfileApi(bridge as any).setOnlineStatus(11, 0, 100);
await new ProfileApi(bridge as any).setOnlineStatus( 11, 0, 100);
const [serviceCmd] = bridge.sendRawPacket.mock.calls[0]!;
expect(serviceCmd).toBe('trpc.qq_new_tech.status_svc.StatusService.SetStatus');
});
it('setOnlineStatus does NOT include the customExt field 4 (varint 0x22 absent in body)', async () => {
const bridge = mockBridge();
await new ProfileApi(bridge as any).setOnlineStatus(11, 0, 100);
await new ProfileApi(bridge as any).setOnlineStatus( 11, 0, 100);
const [, body] = bridge.sendRawPacket.mock.calls[0]!;
// proto field 4 length-delimited tag = (4 << 3) | 2 = 0x22. The
// body should not contain that byte; if encoder ever leaks an
@@ -69,7 +69,7 @@ describe('apis/profile', () => {
it('setDiyOnlineStatus hardcodes status=10 / extStatus=2000 and packs faceId+wording+faceType into customExt', async () => {
const bridge = mockBridge();
await new ProfileApi(bridge as any).setDiyOnlineStatus(1234, '摸鱼中', 2);
await new ProfileApi(bridge as any).setDiyOnlineStatus( 1234, '摸鱼中', 2);
const [serviceCmd, body] = bridge.sendRawPacket.mock.calls[0]!;
expect(serviceCmd).toBe('trpc.qq_new_tech.status_svc.StatusService.SetStatus');
// Decode the wire bytes back through the same schema to assert
@@ -90,7 +90,7 @@ describe('apis/profile', () => {
bridge.sendRawPacket.mockResolvedValueOnce({
success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData: respBuf,
} as any);
await expect(new ProfileApi(bridge as any).setDiyOnlineStatus(1, 't', 1)).rejects.toThrow(/denied/);
await expect(new ProfileApi(bridge as any).setDiyOnlineStatus( 1, 't', 1)).rejects.toThrow(/denied/);
});
it('setDiyOnlineStatus rejects when the transport itself fails', async () => {
@@ -98,7 +98,7 @@ describe('apis/profile', () => {
bridge.sendRawPacket.mockResolvedValueOnce({
success: false, gotResponse: false, errorCode: -1, errorMessage: 'pipe closed', responseData: null,
} as any);
await expect(new ProfileApi(bridge as any).setDiyOnlineStatus(1, 't', 1)).rejects.toThrow(/pipe closed/);
await expect(new ProfileApi(bridge as any).setDiyOnlineStatus( 1, 't', 1)).rejects.toThrow(/pipe closed/);
});
it('setProfile is a no-op when both arguments are undefined', async () => {
@@ -117,20 +117,20 @@ describe('apis/profile', () => {
it('setSelfLongNick targets 0x112a_2 wire cmd', async () => {
const bridge = mockBridge();
await new ProfileApi(bridge as any).setSelfLongNick('hello world');
await new ProfileApi(bridge as any).setSelfLongNick( 'hello world');
expect(bridge.sendRawPacket.mock.calls[0]![0]).toBe('OidbSvcTrpcTcp.0x112a_2');
});
it('setInputStatus resolves UID first and sends 0xcd4_1', async () => {
const bridge = mockBridge();
await new ProfileApi(bridge as any).setInputStatus(10001, 1);
await new ProfileApi(bridge as any).setInputStatus( 10001, 1);
expect(bridge.resolveUserUid).toHaveBeenCalledWith(10001);
expect(bridge.sendRawPacket.mock.calls[0]![0]).toBe('OidbSvcTrpcTcp.0xcd4_1');
});
it('setAvatar loads bytes and pushes through the highway upload path (cmd 90)', async () => {
const bridge = mockBridge();
await new ProfileApi(bridge as any).setAvatar('/some/avatar.png');
await new ProfileApi(bridge as any).setAvatar( '/some/avatar.png');
expect(highwayClient.fetchHighwaySession).toHaveBeenCalledOnce();
expect(highwayClient.uploadHighwayHttp).toHaveBeenCalledOnce();
const [, , cmdId, , , extend] = vi.mocked(highwayClient.uploadHighwayHttp).mock.calls[0]!;
@@ -140,7 +140,7 @@ describe('apis/profile', () => {
it('setGroupAvatar uses cmdId 3000 and packs the Lagrange GroupAvatarExtra constants', async () => {
const bridge = mockBridge();
await new ProfileApi(bridge as any).setGroupAvatar(12345, '/some/group-avatar.png');
await new ProfileApi(bridge as any).setGroupAvatar( 12345, '/some/group-avatar.png');
expect(highwayClient.fetchHighwaySession).toHaveBeenCalledOnce();
expect(highwayClient.uploadHighwayHttp).toHaveBeenCalledOnce();
const [, , cmdId, , , extend] = vi.mocked(highwayClient.uploadHighwayHttp).mock.calls[0]!;
@@ -163,7 +163,7 @@ describe('apis/profile', () => {
vi.mocked(loadBinarySource).mockResolvedValueOnce({
bytes: new Uint8Array(0), fileName: 'empty.png',
} as any);
await expect(new ProfileApi(bridge as any).setGroupAvatar(1, 'empty.png')).rejects.toThrow(/empty/);
await expect(new ProfileApi(bridge as any).setGroupAvatar( 1, 'empty.png')).rejects.toThrow(/empty/);
expect(highwayClient.fetchHighwaySession).not.toHaveBeenCalled();
});
@@ -1,11 +1,9 @@
import { makeChannelCtx } from '@snowluma/channel';
import { HookChannel } from '@snowluma/channel-hook';
import type { PacketInfo } from '@snowluma/common/protocol-types';
import type { GroupMemberJoin, QQEventVariant } from '@snowluma/protocol/events';
import { describe, expect, it } from 'vitest';
import { Bridge } from '../src/bridge/bridge';
import { IdentityService } from '@snowluma/protocol/identity-service';
import type { GroupMemberInfo, QQGroupInfo } from '@snowluma/protocol/qq-info';
import { describe, expect, it } from 'vitest';
import { Core } from '../src/core';
import type { GroupMemberJoin, QQEventVariant } from '@snowluma/protocol/events';
import type { PacketInfo } from '@snowluma/common/protocol-types';
const SELF_UIN = '10001';
const GROUP_ID = 123456789;
@@ -36,21 +34,28 @@ function makeGroup(members: GroupMemberInfo[] = []): QQGroupInfo {
};
}
function buildCore(identity: IdentityService, refreshedMembers: GroupMemberInfo[]) {
const channel = new HookChannel(identity.uin);
const core = new Core(makeChannelCtx(channel), identity);
const memberFetches: Array<{ groupId: number; force: boolean }> = [];
core.apis.contacts.fetchGroupMemberList = async (
groupId: number,
options: { force?: boolean } = {},
): Promise<GroupMemberInfo[]> => {
memberFetches.push({ groupId, force: Boolean(options.force) });
for (const member of refreshedMembers) {
core.identity.updateGroupMember(groupId, member);
}
return refreshedMembers;
};
return { core, channel, memberFetches };
class RefreshingBridge extends Bridge {
readonly memberFetches: Array<{ groupId: number; force: boolean }> = [];
constructor(identity: IdentityService, private readonly refreshedMembers: GroupMemberInfo[]) {
super(identity);
// `fetchGroupMemberList` moved from Bridge onto `apis.contacts`
// under the #6 refactor — patch the method on the constructed
// ContactsApi instance to intercept calls + record them for
// assertions. (Direct property assignment works because the
// method is just an own property on the Api instance, not on
// its prototype.)
this.apis.contacts.fetchGroupMemberList = async (
groupId: number,
options: { force?: boolean } = {},
): Promise<GroupMemberInfo[]> => {
this.memberFetches.push({ groupId, force: Boolean(options.force) });
for (const member of this.refreshedMembers) {
this.identity.updateGroupMember(groupId, member);
}
return this.refreshedMembers;
};
}
}
function makePacket(): PacketInfo {
@@ -80,15 +85,15 @@ async function waitForEvent(events: GroupMemberJoin[]): Promise<GroupMemberJoin>
throw new Error('timed out waiting for group_member_join');
}
describe('Core group member identity refresh', () => {
describe('Bridge group member identity refresh', () => {
it('forces a fresh member list before dispatching an unresolved join event', async () => {
const member = makeGroupMember(22222, 'u_new_member');
const identity = IdentityService.memory(SELF_UIN);
identity.rememberGroups([makeGroup()]);
const { core, channel, memberFetches } = buildCore(identity, [member]);
const bridge = new RefreshingBridge(identity, [member]);
const seen: GroupMemberJoin[] = [];
core.registerCmd('test.member_join', () => [{
bridge.registerCmd('test.member_join', () => [{
kind: 'group_member_join',
time: 1710000000,
selfUin: Number(SELF_UIN),
@@ -98,21 +103,20 @@ describe('Core group member identity refresh', () => {
userUid: member.uid,
operatorUid: member.uid,
}]);
core.events.on('group_member_join', (event: GroupMemberJoin) => {
bridge.events.on('group_member_join', (event) => {
seen.push(event);
});
channel.deliverPacket(makePacket());
bridge.onPacket(makePacket());
const event = await waitForEvent(seen);
expect(memberFetches).toEqual([{ groupId: GROUP_ID, force: true }]);
expect(bridge.memberFetches).toEqual([{ groupId: GROUP_ID, force: true }]);
expect(event.userUin).toBe(member.uin);
expect(event.operatorUin).toBe(member.uin);
});
it('remembers UID mappings from realtime request events', () => {
const channel = new HookChannel(SELF_UIN);
const core = new Core(makeChannelCtx(channel), IdentityService.memory(SELF_UIN));
const bridge = new Bridge(IdentityService.memory(SELF_UIN));
const events: QQEventVariant[] = [
{
kind: 'friend_request',
@@ -136,12 +140,12 @@ describe('Core group member identity refresh', () => {
},
];
core.registerCmd('test.request_identity', () => events);
channel.deliverPacket(makeRequestPacket());
bridge.registerCmd('test.request_identity', () => events);
bridge.onPacket(makeRequestPacket());
expect(core.identity.findUidByUin(55555)).toBe('u_friend_request');
expect(core.identity.findUidByUin(66666)).toBe('u_group_request');
expect(core.identity.findUinByUid('u_friend_request')).toBe(55555);
expect(core.identity.findUinByUid('u_group_request')).toBe(66666);
expect(bridge.identity.findUidByUin(55555)).toBe('u_friend_request');
expect(bridge.identity.findUidByUin(66666)).toBe('u_group_request');
expect(bridge.identity.findUinByUid('u_friend_request')).toBe(55555);
expect(bridge.identity.findUinByUid('u_group_request')).toBe(66666);
});
});
@@ -1,73 +1,49 @@
import type { ChannelCtx } from '@snowluma/channel';
import { describe, expect, it, vi } from 'vitest';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { SendPacketResult } from '@snowluma/common/packet-sender';
import type { SendMessageRequest, SendMessageResponse } from '@snowluma/proto-defs/action';
import type { FileExtra } from '@snowluma/proto-defs/message';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import { describe, expect, it, vi } from 'vitest';
import { Core } from '../src/core';
vi.mock('@snowluma/protocol/element-builder', () => ({
buildSendElems: vi.fn(async () => [{ text: { str: 'stub media elem' } }]),
}));
/**
* Build a fake `ChannelCtx` POJO that captures the outbound packet
* body for assertions. The `Core` under test consumes this ctx exactly
* the way `Hub` would in production — via `sendRawPacket` and
* `onPacket` only.
*/
function makeFakeCtx(uin: string): {
ctx: ChannelCtx;
getCapturedBody: () => Uint8Array | null;
setResponse: (resp: SendPacketResult) => void;
} {
let capturedBody: Uint8Array | null = null;
let response: SendPacketResult = {
success: true,
gotResponse: true,
errorCode: 0,
errorMessage: '',
responseData: Buffer.from(protobuf_encode<SendMessageResponse>({
result: 0,
errMsg: '',
privateSequence: 88,
timestamp1: 1710000000,
})),
};
const ctx: ChannelCtx = {
uin,
kind: 'inject',
sendRawPacket: async (_cmd, body) => {
capturedBody = body;
return response;
},
onPacket: () => { /* unused */ },
dispose: () => { /* unused */ },
};
return {
ctx,
getCapturedBody: () => capturedBody,
setResponse: (resp) => { response = resp; },
};
}
describe('Core private media routing', () => {
describe('Bridge private media routing', () => {
it('includes resolved uid in the final c2c send request for media messages', async () => {
const { Bridge } = await import('../src/bridge/bridge');
const { IdentityService } = await import('@snowluma/protocol/identity-service');
const fake = makeFakeCtx('10000');
const core = new Core(fake.ctx, IdentityService.memory('10000'));
// resolveUserUid lookup needs an explicit override since the
// identity store has no mapping for the test peer.
core.resolveUserUid = vi.fn(async (uin: number) => {
expect(uin).toBe(12345);
return 'u_peer_12345';
});
class TestBridge extends Bridge {
capturedBody: Uint8Array | null = null;
await core.apis.message.sendPrivate(12345, [{ type: 'video', url: 'file:///tmp/clip.mp4' } as any]);
override async resolveUserUid(uin: number): Promise<string> {
expect(uin).toBe(12345);
return 'u_peer_12345';
}
expect(fake.getCapturedBody()).toBeInstanceOf(Uint8Array);
const request = protobuf_decode<SendMessageRequest>(fake.getCapturedBody() as Uint8Array);
override async sendRawPacket(serviceCmd: string, body: Uint8Array): Promise<SendPacketResult> {
expect(serviceCmd).toBe('MessageSvc.PbSendMsg');
this.capturedBody = body;
return {
success: true,
gotResponse: true,
errorCode: 0,
errorMessage: '',
responseData: Buffer.from(protobuf_encode<SendMessageResponse>({
result: 0,
errMsg: '',
privateSequence: 88,
timestamp1: 1710000000,
})),
};
}
}
const bridge = new TestBridge(IdentityService.memory('10000'));
await bridge.apis.message.sendPrivate(12345, [{ type: 'video', url: 'file:///tmp/clip.mp4' } as any]);
expect(bridge.capturedBody).toBeInstanceOf(Uint8Array);
const request = protobuf_decode<SendMessageRequest>(bridge.capturedBody as Uint8Array);
expect(request?.routingHead?.c2c).toMatchObject({
uin: 12345,
uid: 'u_peer_12345',
@@ -83,13 +59,25 @@ describe('Core private media routing', () => {
// BuildPacketBase` + `FileEntity.PackMessageContent`. Previous
// implementation wrote c2c routing + richText.notOnlineFile +
// c2cCmd=11 — the QQ-NT server rejected every c2c file send.
const { Bridge } = await import('../src/bridge/bridge');
const { IdentityService } = await import('@snowluma/protocol/identity-service');
const fake = makeFakeCtx('10000');
const core = new Core(fake.ctx, IdentityService.memory('10000'));
class TestBridge extends Bridge {
capturedBody: Uint8Array | null = null;
override async sendRawPacket(_cmd: string, body: Uint8Array): Promise<SendPacketResult> {
this.capturedBody = body;
return {
success: true, gotResponse: true, errorCode: 0, errorMessage: '',
responseData: Buffer.from(protobuf_encode<SendMessageResponse>({
result: 0, errMsg: '', privateSequence: 88, timestamp1: 1710000000,
})),
};
}
}
const bridge = new TestBridge(IdentityService.memory('10000'));
const fileMd5 = new Uint8Array([0xde, 0xad, 0xbe, 0xef]);
await core.apis.message.sendC2cFile(67890, 'u_peer_xyz', {
await bridge.apis.message.sendC2cFile(67890, 'u_peer_xyz', {
fileId: 'uuid-abc-123',
fileName: 'doc.txt',
fileSize: 1024,
@@ -97,7 +85,7 @@ describe('Core private media routing', () => {
fileHash: 'hash-xyz',
});
const request = protobuf_decode<SendMessageRequest>(fake.getCapturedBody() as Uint8Array);
const request = protobuf_decode<SendMessageRequest>(bridge.capturedBody as Uint8Array);
// Routing: must be trans0x211 with ccCmd=4 + uid, no c2c slot.
expect(request?.routingHead?.trans0x211).toMatchObject({
@@ -121,6 +109,10 @@ describe('Core private media routing', () => {
fileSize: 1024n,
fileHash: 'hash-xyz',
subcmd: 1, // server-required intake validator field
// dangerEvel and fileType are 0 — proto3 omits zero values on
// the wire, so they're not asserted here (matches Lagrange's
// behaviour: it sets `DangerEvel = 0` but protobuf-net also
// skips serialising default ints).
});
expect(fileExtra?.file?.fileMd5).toEqual(fileMd5);
// expireTime is now+7d; just sanity-check it landed (non-zero, plausible)
+22 -8
View File
@@ -1,10 +1,10 @@
import protobufVitePlugin from '@snowluma/proton/vite';
import fs from 'fs';
import { builtinModules } from 'module';
import path from 'path';
import { fileURLToPath } from 'url';
import { defineConfig, PluginOption, UserConfig } from 'vite';
import { fileURLToPath } from 'url';
import fs from 'fs';
import path from 'path';
import { builtinModules } from 'module';
import cp from 'vite-plugin-cp';
import protobufVitePlugin from '@snowluma/proton/vite';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const repoRoot = path.resolve(__dirname, '..', '..');
@@ -20,9 +20,11 @@ const rootPkg = JSON.parse(
// vite-plugin-cp consumes globs through globby; on Windows we must use POSIX-style separators.
const toPosix = (p: string) => p.replace(/\\/g, '/');
// `@snowluma/websocket` is bundled — it's an
// in-tree TS workspace wrapper that routes its native `.node`
// addon through `dist/native/`. Only Node builtins stay external.
// `@snowluma/websocket` and `@snowluma/sqlite` are bundled — they're
// in-tree TS workspace wrappers that route their native `.node`
// addons through `dist/native/`. Only Node builtins stay external;
// the actual `better-sqlite3` JS wrapper is pulled in via the
// `@snowluma/sqlite` re-export and bundled into `index.mjs`.
const external: string[] = [];
const nodeModules = [...builtinModules, ...builtinModules.map((m) => `node:${m}`)].flat();
@@ -44,8 +46,20 @@ const runtimeDistFiles = ['package.json',
// Native binaries shipped for the selected target:
// * `snowluma-*.{dll,node,so}` – NTQQ hook (Windows + Linux).
// * `websocket-*.node` – RFC 6455 framing/mask addon (all platforms).
// * `better-sqlite3-v<abi>-*.node` – SQLite native binding consumed
// by @snowluma/sqlite. Two ABIs
// vendored side-by-side
// (v127 = Node 22 LTS, v137 =
// Node 24) so the runtime can
// pick whichever matches the
// host's `process.versions.modules`.
// Vendored via
// `tools/fetch-sqlite-prebuilts.mjs`
// from WiseLibs's prebuild releases.
const SQLITE_ABIS = ['v127', 'v137'];
const nativeFiles = [
`websocket-${targetTriple}.node`,
...SQLITE_ABIS.map((abi) => `better-sqlite3-${abi}-${targetTriple}.node`),
...(targetPlatform === 'win32'
? [`snowluma-${targetTriple}.dll`, `snowluma-${targetTriple}.node`]
: []),
+3 -3
View File
@@ -1,12 +1,12 @@
import protobufVitePlugin from '@snowluma/proton/vite';
import { defineConfig } from 'vitest/config';
import path from 'path';
import { fileURLToPath } from 'url';
import { defineConfig } from 'vitest/config';
import protobufVitePlugin from '@snowluma/proton/vite';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
export default defineConfig({
plugins: [protobufVitePlugin({ root: path.resolve(__dirname, '../..') })],
plugins: [protobufVitePlugin()],
resolve: {
alias: {
'@': path.resolve(__dirname, 'src')
+1 -1
View File
@@ -86,12 +86,12 @@
"typecheck": "tsc --noEmit"
},
"dependencies": {
"@snowluma/channel": "workspace:*",
"@snowluma/common": "workspace:*",
"@snowluma/core": "workspace:*",
"@snowluma/proto-defs": "workspace:*",
"@snowluma/proton": "workspace:*",
"@snowluma/protocol": "workspace:*",
"@snowluma/sqlite": "workspace:*",
"@snowluma/websocket": "workspace:*"
},
"devDependencies": {
+2 -2
View File
@@ -1,6 +1,6 @@
import { summarizeParams } from '@snowluma/common/log-summary';
import { createLogger, type Logger } from '@snowluma/common/logger';
import type { CoreCtx } from '@snowluma/core/core-ctx';
import type { BridgeInterface } from '@snowluma/core/bridge-interface';
import { register as registerExtended } from './actions/extended';
import { register as registerFriend } from './actions/friend';
import { register as registerGroupAdmin } from './actions/group-admin';
@@ -33,7 +33,7 @@ export interface GroupEssenceMsgRet {
}
export interface ApiActionContext {
bridge: CoreCtx;
bridge: BridgeInterface;
getLoginInfo: () => { userId: number; nickname: string };
isOnline: () => boolean;
getMessage: (messageId: number) => JsonObject | null;
+4 -3
View File
@@ -1,4 +1,5 @@
import type { CoreCtx } from '@snowluma/core/core-ctx';
import type { Bridge } from '@snowluma/core/bridge';
import type { BridgeInterface } from '@snowluma/core/bridge-interface';
import type { WebHonorType } from '@snowluma/protocol/web/group-honor';
import type { ApiActionContext } from './api-handler';
import type { ConverterContext } from './event-converter';
@@ -40,7 +41,7 @@ import type { JsonObject, MessageMeta, OneBotConfig } from './types';
export interface OneBotInstanceContext {
uin: string;
selfId: number;
bridge: CoreCtx;
bridge: BridgeInterface;
messageStore: MessageStore;
mediaStore: MediaStore;
reactionStore: ReactionStore;
@@ -118,5 +119,5 @@ export function buildApiContext(ref: OneBotInstanceContext): ApiActionContext {
};
}
export type { WebHonorType };
export type { Bridge, WebHonorType };
+7 -7
View File
@@ -1,6 +1,6 @@
import { createLogger } from '@snowluma/common/logger';
import type { CoreCtx } from '@snowluma/core/core-ctx';
import type { DownloadRKeyInfo } from '@snowluma/core/apis';
import type { DownloadRKeyInfo } from '@snowluma/core/bridge';
import type { BridgeInterface } from '@snowluma/core/bridge-interface';
import type { MessageElement } from '@snowluma/protocol/events';
const log = createLogger('OneBot');
@@ -27,7 +27,7 @@ export class RKeyCache {
private cache = new Map<number, CachedRKey>();
private lastRefreshAttempt = 0;
warmUp(bridge: CoreCtx, uin: string): void {
warmUp(bridge: BridgeInterface, uin: string): void {
bridge.apis.contacts.fetchDownloadRKeys().then(
(rkeys) => {
this.updateCache(rkeys);
@@ -39,7 +39,7 @@ export class RKeyCache {
);
}
resolveImageUrl(bridge: CoreCtx, element: MessageElement, isGroup: boolean): string {
resolveImageUrl(bridge: BridgeInterface, element: MessageElement, isGroup: boolean): string {
const url = element.imageUrl ?? '';
if (!urlNeedsRKey(url)) return url;
@@ -50,7 +50,7 @@ export class RKeyCache {
const separator = url.includes('?') ? '&rkey=' : '?rkey=';
return url + separator + encodeURIComponent(cleanRKey);
}
resolveMediaUrl(bridge: CoreCtx, element: MessageElement, isGroup: boolean): string {
resolveMediaUrl(bridge: BridgeInterface, element: MessageElement, isGroup: boolean): string {
const url = element.url ?? '';
if (!url || !urlNeedsRKey(url)) return url;
@@ -89,12 +89,12 @@ export class RKeyCache {
}
}
private findRKey(bridge: CoreCtx, isGroup: boolean): string | null {
private findRKey(bridge: BridgeInterface, isGroup: boolean): string | null {
const primaryType = isGroup ? GROUP_IMAGE_RKEY_TYPE : PRIVATE_IMAGE_RKEY_TYPE;
return this.findRKeyForType(bridge, primaryType);
}
private findRKeyForType(bridge: CoreCtx, primaryType: number): string | null {
private findRKeyForType(bridge: BridgeInterface, primaryType: number): string | null {
const now = Math.floor(Date.now() / 1000);
const tryFind = (type: number): string | null => {
+24 -3
View File
@@ -1,5 +1,5 @@
import { createLogger, type Logger } from '@snowluma/common/logger';
import type { CoreCtx } from '@snowluma/core/core-ctx';
import type { BridgeInterface } from '@snowluma/core/bridge-interface';
import { formatGroup, formatMessageSegments, formatReply, formatUser } from '@snowluma/protocol/format';
import path from 'path';
import { ApiHandler } from './api-handler';
@@ -28,7 +28,7 @@ const moduleLog = createLogger('Event');
export class OneBotInstance {
readonly uin: string;
private readonly bridge: CoreCtx;
private readonly bridge: BridgeInterface;
private readonly apiHandler: ApiHandler;
private readonly converterCtx: ConverterContext;
private readonly messageStore: MessageStore;
@@ -38,6 +38,7 @@ export class OneBotInstance {
private readonly rkeyCache: RKeyCache;
private disposeEventPipeline: (() => void) | null = null;
private readonly pids = new Set<number>();
private online = true;
private heartbeatTimer: NodeJS.Timeout | null = null;
private static readonly HEARTBEAT_INTERVAL = 30000;
@@ -45,7 +46,7 @@ export class OneBotInstance {
get nickname(): string { return this.bridge.identity.nickname; }
constructor(uin: string, bridge: CoreCtx, config: OneBotConfig) {
constructor(uin: string, bridge: BridgeInterface, config: OneBotConfig) {
this.uin = uin;
this.bridge = bridge;
const uinNum = Number.parseInt(uin, 10);
@@ -115,6 +116,26 @@ export class OneBotInstance {
this.reactionStore.close();
}
addPid(pid: number): void {
this.pids.add(pid);
}
removePid(pid: number): void {
this.pids.delete(pid);
}
hasPid(pid: number): boolean {
return this.pids.has(pid);
}
getPids(): number[] {
return [...this.pids];
}
get empty(): boolean {
return this.pids.size === 0;
}
private dispatchEvent(event: JsonObject): void {
this.cacheMessageEvent(event);
this.logReceivedMessage(event);
+12 -8
View File
@@ -1,6 +1,6 @@
import { createLogger } from '@snowluma/common/logger';
import type { CoreCtx } from '@snowluma/core/core-ctx';
import type { Hub } from '@snowluma/core/hub';
import type { BridgeInterface } from '@snowluma/core/bridge-interface';
import type { BridgeManager } from '@snowluma/core/manager';
import { loadOneBotConfig } from './config';
import { OneBotInstance } from './instance';
@@ -10,12 +10,12 @@ const VERBOSE_WARMUP = process.env.SNOWLUMA_VERBOSE_WARMUP === '1';
export class OneBotManager {
private readonly instances = new Map<string, OneBotInstance>();
bind(hub: Hub): void {
hub.events.on('core-online', (ctx) => {
this.onSessionStarted(ctx.uin, ctx);
bind(bridgeManager: BridgeManager): void {
bridgeManager.setSessionStartedCallback((uin, bridge) => {
this.onSessionStarted(uin, bridge);
});
hub.events.on('core-offline', ({ uin }) => {
bridgeManager.setSessionClosedCallback((uin) => {
this.onSessionClosed(uin);
});
}
@@ -45,12 +45,16 @@ export class OneBotManager {
this.instances.clear();
}
private onSessionStarted(uin: string, bridge: CoreCtx): void {
private onSessionStarted(uin: string, bridge: BridgeInterface): void {
if (this.instances.has(uin)) return;
const config = loadOneBotConfig(uin, { persistDefaults: true });
const instance = new OneBotInstance(uin, bridge, config);
const activePid = bridge.activePid;
if (activePid !== null) {
instance.addPid(activePid);
}
if (!bridge.identity.nickname) bridge.identity.nickname = uin;
this.instances.set(uin, instance);
@@ -71,7 +75,7 @@ export class OneBotManager {
}
async function warmUpBridgeState(uin: string, bridge: CoreCtx): Promise<void> {
async function warmUpBridgeState(uin: string, bridge: BridgeInterface): Promise<void> {
const selfUin = parseInt(uin, 10) || 0;
let selfResolved = false;
+12 -12
View File
@@ -1,6 +1,6 @@
import type { MessageElement } from '@snowluma/protocol/events';
import Database, { type Database as DatabaseType, type Statement } from '@snowluma/sqlite';
import fs from 'fs';
import { DatabaseSync, type StatementSync } from 'node:sqlite';
import path from 'path';
export interface CachedImage {
@@ -62,17 +62,17 @@ const TYPE_VIDEO = 'video';
const DEFAULT_KEEP_ENTRIES = 4096;
export class MediaStore {
private readonly db: DatabaseSync;
private readonly db: DatabaseType;
private readonly maxEntriesPerType: number;
// Prepared statements (pay the parsing cost once at startup).
private readonly upsertEntry: StatementSync;
private readonly upsertKey: StatementSync;
private readonly findEntryByKey: StatementSync;
private readonly findEntryByPrimary: StatementSync;
private readonly evictByType: StatementSync;
private readonly purgeOrphanKeys: StatementSync;
private readonly countByType: StatementSync;
private readonly upsertEntry: Statement;
private readonly upsertKey: Statement;
private readonly findEntryByKey: Statement;
private readonly findEntryByPrimary: Statement;
private readonly evictByType: Statement;
private readonly purgeOrphanKeys: Statement;
private readonly countByType: Statement;
constructor(dbPath: string, maxEntriesPerType = DEFAULT_KEEP_ENTRIES) {
this.maxEntriesPerType = Math.max(64, maxEntriesPerType);
@@ -80,9 +80,9 @@ export class MediaStore {
const dir = path.dirname(dbPath);
fs.mkdirSync(dir, { recursive: true });
this.db = new DatabaseSync(dbPath);
this.db.exec('PRAGMA journal_mode = WAL');
this.db.exec('PRAGMA synchronous = NORMAL');
this.db = new Database(dbPath);
this.db.pragma('journal_mode = WAL');
this.db.pragma('synchronous = NORMAL');
this.initSchema();
this.upsertEntry = this.db.prepare(
+2 -2
View File
@@ -1,10 +1,10 @@
import type { CoreCtx } from '@snowluma/core/core-ctx';
import type { BridgeInterface } from '@snowluma/core/bridge-interface';
import type { MessageElement } from '@snowluma/protocol/events';
import type { RKeyCache } from './instance-rkey';
export class MediaUrlResolver {
constructor(
private readonly bridge: CoreCtx,
private readonly bridge: BridgeInterface,
private readonly rkeyCache: RKeyCache,
) { }
+13 -13
View File
@@ -1,18 +1,18 @@
import Database, { type Database as DatabaseType, type Statement } from '@snowluma/sqlite';
import fs from 'fs';
import { DatabaseSync, type StatementSync } from 'node:sqlite';
import path from 'path';
import type { JsonObject, MessageMeta } from './types';
export class MessageStore {
private readonly db: DatabaseSync;
private readonly stmtStoreEvent: StatementSync;
private readonly stmtStoreMeta: StatementSync;
private readonly stmtFindEvent: StatementSync;
private readonly stmtFindMeta: StatementSync;
private readonly stmtResolveReplyGroup: StatementSync;
private readonly stmtResolveReplyPrivate: StatementSync;
private readonly stmtListEventsAnchored: StatementSync;
private readonly stmtListEventsLatest: StatementSync;
private readonly db: DatabaseType;
private readonly stmtStoreEvent: Statement;
private readonly stmtStoreMeta: Statement;
private readonly stmtFindEvent: Statement;
private readonly stmtFindMeta: Statement;
private readonly stmtResolveReplyGroup: Statement;
private readonly stmtResolveReplyPrivate: Statement;
private readonly stmtListEventsAnchored: Statement;
private readonly stmtListEventsLatest: Statement;
constructor(dbPath: string) {
const dir = path.dirname(dbPath);
@@ -20,9 +20,9 @@ export class MessageStore {
// Replace .json extension with .db if present
const finalPath = dbPath.replace(/\.json$/, '.db');
this.db = new DatabaseSync(finalPath);
this.db.exec('PRAGMA journal_mode = WAL');
this.db.exec('PRAGMA synchronous = NORMAL');
this.db = new Database(finalPath);
this.db.pragma('journal_mode = WAL');
this.db.pragma('synchronous = NORMAL');
this.initSchema();
// Prepare once. Statements survive for the lifetime of the
+11 -11
View File
@@ -1,4 +1,4 @@
import type { CoreCtx } from '@snowluma/core/core-ctx';
import type { BridgeInterface } from '@snowluma/core/bridge-interface';
import type { IdentityService } from '@snowluma/protocol/identity-service';
import type { OneBotInstanceContext } from '../instance-context';
import type { JsonObject } from '../types';
@@ -9,7 +9,7 @@ export function getLoginInfo(ref: OneBotInstanceContext): { userId: number; nick
return { userId, nickname };
}
async function refreshSingleGroupMembers(bridge: CoreCtx, groupId: number): Promise<void> {
async function refreshSingleGroupMembers(bridge: BridgeInterface, groupId: number): Promise<void> {
try {
await bridge.apis.contacts.fetchGroupMemberList(groupId);
} catch {
@@ -17,7 +17,7 @@ async function refreshSingleGroupMembers(bridge: CoreCtx, groupId: number): Prom
}
}
export async function getFriendList(bridge: CoreCtx): Promise<JsonObject[]> {
export async function getFriendList(bridge: BridgeInterface): Promise<JsonObject[]> {
try {
const friends = await bridge.apis.contacts.fetchFriendList();
return friends.map(f => ({
@@ -35,7 +35,7 @@ export async function getFriendList(bridge: CoreCtx): Promise<JsonObject[]> {
}
export async function getGroupList(
bridge: CoreCtx,
bridge: BridgeInterface,
noCache?: boolean,
): Promise<JsonObject[]> {
try {
@@ -54,7 +54,7 @@ export async function getGroupList(
}
export async function getGroupInfo(
bridge: CoreCtx,
bridge: BridgeInterface,
groupId: number,
noCache?: boolean,
): Promise<JsonObject | null> {
@@ -76,7 +76,7 @@ export async function getGroupInfo(
}
export async function getGroupMemberList(
bridge: CoreCtx,
bridge: BridgeInterface,
groupId: number,
noCache?: boolean,
): Promise<JsonObject[]> {
@@ -94,7 +94,7 @@ export async function getGroupMemberList(
}
export async function getGroupMemberInfo(
bridge: CoreCtx,
bridge: BridgeInterface,
groupId: number,
userId: number,
noCache?: boolean,
@@ -108,7 +108,7 @@ export async function getGroupMemberInfo(
}
export async function getGroupFiles(
bridge: CoreCtx,
bridge: BridgeInterface,
groupId: number,
folderId?: string,
): Promise<JsonObject> {
@@ -140,7 +140,7 @@ export async function getGroupFiles(
}
export async function getStrangerInfo(
bridge: CoreCtx,
bridge: BridgeInterface,
userId: number,
): Promise<JsonObject | null> {
try {
@@ -167,7 +167,7 @@ export async function getStrangerInfo(
}
}
export async function getGroupSystemMessages(bridge: CoreCtx): Promise<JsonObject[]> {
export async function getGroupSystemMessages(bridge: BridgeInterface): Promise<JsonObject[]> {
try {
const reqs = await bridge.apis.contacts.fetchGroupRequests();
return reqs.map(r => ({
@@ -184,7 +184,7 @@ export async function getGroupSystemMessages(bridge: CoreCtx): Promise<JsonObjec
}
}
export async function getDownloadRKeys(bridge: CoreCtx): Promise<JsonObject[]> {
export async function getDownloadRKeys(bridge: BridgeInterface): Promise<JsonObject[]> {
try {
const rkeys = await bridge.apis.contacts.fetchDownloadRKeys();
return rkeys.map(r => ({
+2 -2
View File
@@ -1,5 +1,5 @@
import { createLogger } from '@snowluma/common/logger';
import type { CoreCtx } from '@snowluma/core/core-ctx';
import type { BridgeInterface } from '@snowluma/core/bridge-interface';
import type { MediaStore } from '../media-store';
import type { JsonObject } from '../types';
@@ -21,7 +21,7 @@ export async function getImageInfo(
}
export async function getRecordInfo(
bridge: CoreCtx,
bridge: BridgeInterface,
mediaStore: MediaStore,
file: string,
): Promise<JsonObject | null> {
@@ -1,5 +1,5 @@
import { createLogger } from '@snowluma/common/logger';
import type { CoreCtx } from '@snowluma/core/core-ctx';
import type { BridgeInterface } from '@snowluma/core/bridge-interface';
import type { ForwardNodePayload, MessageElement } from '@snowluma/protocol/events';
import type { MessageSendResult } from '../api-handler';
import { elementsToOneBotSegments } from '../event-converter';
@@ -64,7 +64,7 @@ export async function getFriendMsgHistory(
.map(sanitizeMessageEventForApi);
}
export async function deleteMessage(bridge: CoreCtx, meta: MessageMeta): Promise<void> {
export async function deleteMessage(bridge: BridgeInterface, meta: MessageMeta): Promise<void> {
if (meta.isGroup) {
await bridge.apis.message.recallGroup(meta.targetId, meta.sequence);
} else {
@@ -79,7 +79,7 @@ export async function deleteMessage(bridge: CoreCtx, meta: MessageMeta): Promise
}
export async function setEssenceMessage(
bridge: CoreCtx,
bridge: BridgeInterface,
messageStore: MessageStore,
messageId: number,
enable: boolean,
@@ -1,7 +1,7 @@
import type { CoreCtx } from '@snowluma/core/core-ctx';
import type { BridgeInterface } from '@snowluma/core/bridge-interface';
export async function handleGroupAddRequest(
bridge: CoreCtx,
bridge: BridgeInterface,
flag: string,
approve: boolean,
reason: string,
+10 -10
View File
@@ -1,21 +1,21 @@
import Database, { type Database as DatabaseType, type Statement } from '@snowluma/sqlite';
import fs from 'fs';
import { DatabaseSync, type StatementSync } from 'node:sqlite';
import path from 'path';
export class ReactionStore {
private readonly db: DatabaseSync;
private readonly stmtUpsert: StatementSync;
private readonly stmtRemove: StatementSync;
private readonly stmtList: StatementSync;
private readonly stmtCount: StatementSync;
private readonly stmtCountByEmoji: StatementSync;
private readonly db: DatabaseType;
private readonly stmtUpsert: Statement;
private readonly stmtRemove: Statement;
private readonly stmtList: Statement;
private readonly stmtCount: Statement;
private readonly stmtCountByEmoji: Statement;
constructor(dbPath: string) {
const dir = path.dirname(dbPath);
fs.mkdirSync(dir, { recursive: true });
this.db = new DatabaseSync(dbPath);
this.db.exec('PRAGMA journal_mode = WAL');
this.db.exec('PRAGMA synchronous = NORMAL');
this.db = new Database(dbPath);
this.db.pragma('journal_mode = WAL');
this.db.pragma('synchronous = NORMAL');
this.initSchema();
this.stmtUpsert = this.db.prepare(
+4 -11
View File
@@ -3,22 +3,15 @@
// inside `packages/core/tests/` and ran via `@snowluma/core`'s vitest
// invocation; they moved over wholesale in the Phase 3 split.
import protobufVitePlugin from '@snowluma/proton/vite';
import path from 'path';
import { fileURLToPath } from 'url';
import { defineConfig } from 'vitest/config';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
export default defineConfig({
// `@snowluma/proton` provides the bare-specifier resolver that turns
// `import type { OidbBase } from '@snowluma/proto-defs/oidb'` into
// a zero-runtime encoder/decoder at the call site. Set `root` to the
// monorepo root so the plugin transforms protobuf_encode/decode call
// sites inside transitively-imported workspace packages (notably
// `@snowluma/protocol`'s element-builder + msg-push decoders) —
// otherwise OneBot tests that exercise those code paths blow up with
// "was not transformed". Mirrors `@snowluma/core`'s setup.
plugins: [protobufVitePlugin({ root: path.resolve(__dirname, '../..') })],
// a zero-runtime encoder/decoder at the call site. The same plugin
// is loaded by `@snowluma/core`'s vite config — keep it here so the
// OneBot tests resolve identically.
plugins: [protobufVitePlugin()],
test: {
include: ['tests/**/*.test.ts'],
// Per-RoadMap-#5 bench files live in `bench/*.bench.ts`. Use the
+2 -1
View File
@@ -368,7 +368,8 @@
"dependencies": {
"@snowluma/common": "workspace:*",
"@snowluma/proto-defs": "workspace:*",
"@snowluma/proton": "workspace:*"
"@snowluma/proton": "workspace:*",
"@snowluma/sqlite": "workspace:*"
},
"devDependencies": {
"@types/node": "^24.12.2",
+10 -12
View File
@@ -1,14 +1,12 @@
import fs from 'fs';
import { DatabaseSync, type StatementSync } from 'node:sqlite';
import path from 'path';
import Database, { type Database as DatabaseType, type Statement } from '@snowluma/sqlite';
import { createLogger, type Logger } from '@snowluma/common/logger';
import type {
FriendInfo, GroupMemberInfo,
GroupRequestInfo,
QQGroupInfo,
UserProfileInfo,
FriendInfo, GroupMemberInfo, QQGroupInfo,
UserProfileInfo, GroupRequestInfo,
} from './qq-info';
import { createLogger, type Logger } from '@snowluma/common/logger';
const moduleLogger = createLogger('Identity');
@@ -111,14 +109,14 @@ export class IdentityService {
private readonly uidByUin = new Map<number, string>();
// ─── Persistence + fetcher ───
private readonly db: DatabaseSync | null;
private readonly db: DatabaseType | null;
// Prepared-statement cache. Every `.prepare(sql)` call in this
// service re-parses the SQL — that's the SQLite anti-pattern
// RoadMap #5 is fixing. We memoize by the SQL string itself so the
// call sites stay readable (no need to enumerate 20+ named fields
// upfront); the Map lookup is O(1) hash + string-eq, which is
// negligible next to the SQL parse it replaces.
private readonly stmtCache_ = new Map<string, StatementSync>();
private readonly stmtCache_ = new Map<string, Statement>();
private inTransaction = false;
private fetcher: IdentityFetcher | null = null;
private readonly log: Logger;
@@ -136,16 +134,16 @@ export class IdentityService {
}
fs.mkdirSync(path.dirname(dbPath), { recursive: true });
this.db = new DatabaseSync(dbPath);
this.db.exec('PRAGMA journal_mode = WAL');
this.db.exec('PRAGMA synchronous = NORMAL');
this.db = new Database(dbPath);
this.db.pragma('journal_mode = WAL');
this.db.pragma('synchronous = NORMAL');
this.initSchema();
this.loadSnapshot();
}
/** Cached `prepare(sql)`. First call per unique SQL parses; later
* calls reuse the same `Statement` object. See `stmtCache_`. */
private pstmt(sql: string): StatementSync {
private pstmt(sql: string): Statement {
let cached = this.stmtCache_.get(sql);
if (cached !== undefined) return cached;
cached = this.db!.prepare(sql);
+144 -188
View File
@@ -1,13 +1,19 @@
# @snowluma/proton
用于 SnowLuma 的编译时 protobuf 编码器/解码器生成器。输入 TypeScript 接口,输出完全内联、零运行时的编解码函数。
Compile-time protobuf encoder/decoder generator for SnowLuma. TypeScript
interfaces in, fully-inlined zero-runtime codec functions out.
> 该项目衍生自(Vendored自)[SnowLuma/protobuf-dsl](https://github.com/SnowLuma/protobuf-dsl)
> 并修复了若干边缘情况。未做修改的上游源码保留在 `dev/protobuf-dsl/` 下作为参考副本。
> Vendored from [SnowLuma/protobuf-dsl](https://github.com/SnowLuma/protobuf-dsl)
> with edge-case fixes applied. The unmodified upstream is kept under
> `dev/protobuf-dsl/` as a reference copy.
## 功能特性
## What it does
你只需使用 `pb<N, T>` 标记的普通 TypeScript 接口来声明你的传输 Schema。在构建时,一个 Vite 插件会扫描 `protobuf_encode<T>` / `protobuf_decode<T>` 的调用位置,并将它们替换为特定于类型的、完全内联的编解码函数。无需运行时 Schema 查找,无需反射,无需 `.proto` 文件,也无需 `protoc`。
You declare your wire schema as plain TypeScript interfaces marked up with
`pb<N, T>`. At build time a Vite plugin walks the call sites of
`protobuf_encode<T>` / `protobuf_decode<T>` and replaces them with
type-specific, fully-inlined codec functions. No runtime schema lookup,
no reflection, no `.proto` files, no `protoc`.
```ts
import type { pb, pb_repeated, uint_32, bool } from '@snowluma/proton';
@@ -24,85 +30,71 @@ const bytes = protobuf_encode<UserProfile>({
id: 42, username: 'alice', active: true, tags: ['admin'],
});
const user = protobuf_decode<UserProfile>(bytes);
```
经过插件转换后,上述代码会变成:
After the plugin transform, this becomes:
```js
// 预计算的 Tag 字面量、内联的 varint 循环、无函数调用开销
// pre-computed tag literals, inlined varint loops, no function-call overhead
const bytes = protobuf_encode_UserProfile({ id: 42, ... });
const user = protobuf_decode_UserProfile(bytes);
```
如果**未安装**该插件,调用 `protobuf_encode` / `protobuf_decode` 将直接抛出明显的错误,而不是静默生成错误的字节数据。
If the plugin **isn't** installed, calling `protobuf_encode` / `protobuf_decode`
throws a loud error rather than silently producing wrong bytes.
## 在 SnowLuma 中配置
## Setup in SnowLuma
该包已经内置到 `@snowluma/core` 的 `vitest.config.ts` 中。若要在 Monorepo 的其他地方使用:
The package is already wired into `@snowluma/core`'s `vitest.config.ts`. To use
it elsewhere in the monorepo:
```ts
// vite.config.ts (或 vitest.config.ts)
// vite.config.ts (or vitest.config.ts)
import { defineConfig } from 'vite';
import protobufVitePlugin from '@snowluma/proton/vite';
export default defineConfig({
plugins: [
protobufVitePlugin({
root: 'src', // 可选:限制插件只处理该目录下的 .ts 文件
cache: true, // 可选:默认启用,缓存写入 Vite cacheDir/proton
}),
],
plugins: [protobufVitePlugin()],
});
```
插件在 Vite `configResolved` 阶段解析作用目录。所有类型分析都基于 AST(不依赖 `tsconfig.json` 或 TypeChecker),跨文件 `extends` 链通过 `import-resolver` 的文件缓存遍历。如果启用缓存(默认),Proton 会在 Vite 的 `cacheDir` 下维护:
```text
node_modules/.vite/proton/
transform/ 按源码 hash + 配置 hash + 依赖 mtime 命中的 transform 结果
```
这样普通文件的 transform 可以先走作用域过滤与 hash cache;未命中时才执行 AST 分析、跨文件导入解析和子类包装器解析。
添加工作区依赖:
Add the workspace dep:
```json
{
"dependencies": { "@snowluma/proton": "workspace:*" }
}
```
## 原生类型
## Primitive types
标记格式为 `pb<FieldNumber, Type>`(数组则使用 `pb_repeated<FieldNumber, Type>`)。可用的原生类型包括:
The marker is `pb<FieldNumber, Type>` (or `pb_repeated<FieldNumber, Type>` for
arrays). Available primitives:
| 标记 | TS 类型 | 传输格式(Wire) |
| --- | --- | --- |
| `bool` | `boolean` | varint |
| `uint_32` | `number` | varint |
| `int_32` | `number` | varint |
| `sint_32` | `number` | varint (zigzag) |
| `uint_64` | `bigint` | varint |
| `int_64` | `bigint` | varint |
| `sint_64` | `bigint` | varint (zigzag) |
| `fixed_32` | `number` | 32-bit |
| `fixed_64` | `bigint` | 64-bit |
| `sfixed_32` | `number` | 32-bit |
| `sfixed_64` | `bigint` | 64-bit |
| `float` | `number` | 32-bit |
| `double` | `number` | 64-bit |
| `string` | `string` | length-delimited |
| `bytes` | `Uint8Array` | length-delimited |
| Marker | TS type | Wire |
| ----------- | ------------ | ---------------- |
| `bool` | `boolean` | varint |
| `uint_32` | `number` | varint |
| `int_32` | `number` | varint |
| `sint_32` | `number` | varint (zigzag) |
| `uint_64` | `bigint` | varint |
| `int_64` | `bigint` | varint |
| `sint_64` | `bigint` | varint (zigzag) |
| `fixed_32` | `number` | 32-bit |
| `fixed_64` | `bigint` | 64-bit |
| `sfixed_32` | `number` | 32-bit |
| `sfixed_64` | `bigint` | 64-bit |
| `float` | `number` | 32-bit |
| `double` | `number` | 64-bit |
| `string` | `string` | length-delimited |
| `bytes` | `Uint8Array` | length-delimited |
此外,还支持消息类型(任何其他带有 `pb<>` 标记字段的接口),作为 `pb<>` / `pb_repeated<>` 的第二个类型参数。
Plus message types (any other interface marked with `pb<>` fields) used as
the second type-arg to `pb<>` / `pb_repeated<>`.
## 泛型模板
## Generic templates
你可以将可复用的包装器声明为泛型接口:
You can declare reusable wrappers as generic interfaces:
```ts
interface Wrapper<T> {
@@ -110,36 +102,35 @@ interface Wrapper<T> {
}
const bytes = protobuf_encode<Wrapper<uint_32>>({ value: 42 });
// ^ 在调用处实例化
// ^ instantiated at the call site
```
嵌套实例化同样有效 —— `Wrapper<Wrapper<string>>` 会被单态化(mono-morphizes)为 `Wrapper__string` + `Wrapper__Wrapper__string`,并且在构建时两者都会进入注册表。
Nested instantiations work too — `Wrapper<Wrapper<string>>` mono-morphizes to
`Wrapper__string` + `Wrapper__Wrapper__string` and both end up in the registry
at build time.
你可以在具体接口中组合它们:
Compose them in concrete interfaces:
```ts
interface Container {
wrapped?: pb<5, Wrapper<uint_32>>;
}
```
……或者在其他泛型模板中组合:
…or in other generic templates:
```ts
interface Outer<U> {
wrapped?: pb<5, Wrapper<U>>;
}
const bytes = protobuf_encode<Outer<uint_32>>({ wrapped: { value: 42 } });
```
这两种形式均已通过回归测试。
Both forms are covered by regression tests.
## 跨文件与包装器绑定
## Cross-file & wrapper-binding
Schema 和调用位置可以位于不同的文件中:
Schemas can live in one file and call sites in another:
```ts
// schema/user.ts
@@ -149,10 +140,10 @@ export interface UserProfile { id?: pb<1, uint_32>; }
import type { UserProfile } from './schema/user';
import { protobuf_encode } from '@snowluma/proton';
const bytes = protobuf_encode<UserProfile>({ id: 42 });
```
你也可以围绕 `protobuf_encode` / `_decode` 构建轻量级的泛型包装函数,插件会对其进行追踪,即使跨越文件边界也适用:
You can also build thin generic wrappers around `protobuf_encode` / `_decode`
and the plugin will trace through them, including across file boundaries:
```ts
// schema/wrap.ts
@@ -163,83 +154,33 @@ export function encodeWrapped<T>(v: Wrapper<T>): Uint8Array {
// usage.ts
import { encodeWrapped } from './schema/wrap';
const bytes = encodeWrapped<string>({ value: 'hi' });
// ^ 插件会将其重写为 protobuf_encode_Wrapper__string(...)
// ^ plugin rewrites to protobuf_encode_Wrapper__string(...)
```
链式转发同样有效(例如:`A` 转发给 `B`,而 `B` 是从另一个模块导入的,依此类推)。
Chained forwarders also work (`A` forwards to `B` which is imported from
another module, etc.).
## 静态方法包装器(每个子类的重写)
## proto3 default-value semantics
有时,你可能希望抽象基类只保留一次编码/解码管道,而让每个子类仅提供对应请求/响应结构的辅助方法:
**Important behavioural detail.** Proton follows the proto3 wire format spec:
fields whose value equals the type's default (`0` / `false` / `""` /
empty bytes) are **not emitted** on the wire. This is byte-different from
SnowLuma's legacy `protoEncode` runtime, which always emits every field.
```ts
import { protobuf_encode, protobuf_decode } from '@snowluma/proton';
Both forms are wire-compatible with any conforming proto3 reader (missing
fields decode as the default value). When migrating legacy schemas to proton,
do **not** treat byte-level inequality on default values as a regression — see
[`packages/core/tests/proton-parity.test.ts`](../../packages/core/tests/proton-parity.test.ts)
for the test that pins this divergence.
abstract class PacketTransformer {
static encode<R, T extends { serialize: (ctx: unknown, p: never) => R }>(
this: T,
ctx: unknown,
params: T['serialize'] extends (ctx: unknown, p: infer P) => R ? P : never,
): Uint8Array {
return protobuf_encode<R>((this as any).serialize(ctx, params));
}
If you have a wire consumer that depends on byte-level identity (e.g. for
hashing or signing), prefer to set non-default values explicitly rather than
relying on the encoder.
static decode<B, Res, T extends { deserialize: (ctx: unknown, body: B) => Res }>(
this: T,
ctx: unknown,
bytes: Uint8Array,
): Res {
return (this as any).deserialize(ctx, protobuf_decode<B>(bytes));
}
}
## Diagnostics
class DemoTransformer extends PacketTransformer {
static serialize(_ctx: unknown, p: DemoReq): DemoReqPb { /* … */ }
static deserialize(_ctx: unknown, b: DemoResPb): DemoRes { /* … */ }
}
// 自然地调用继承的方法:
const bytes = DemoTransformer.encode(undefined, { /* … */ });
const result = DemoTransformer.decode(undefined, bytes);
```
抽象体内部的 `protobuf_encode<R>` / `protobuf_decode<B>` 无法进行静态替换 —— 因为 `R` 和 `B` 在运行时会被擦除。Proton 通过以下方式处理此问题:
1. **检测**满足以下条件的类:其静态方法 (a) 接收类型参数,(b) 调用 `protobuf_encode<R>` / `protobuf_decode<R>` 且其中 `R` 是这些参数之一,以及 (c) 使用 `this: T extends { … }` 进行约束,且该参数出现在约束内部。
2. **AST-only 解析**:通过文件级导入解析(与 protobuf 接口共用同一套 `import-resolver` 机制)遍历每个子类的 `extends` 链(含跨文件边和包/路径别名),并把包装器的类型参数和子类的同级方法签名进行匹配(本例中 `R` 对应 `serialize` 的返回值类型,`B` 对应 `deserialize` 的参数类型)。
3. 在类声明后**追加**一个针对每个子类的重写(Override):
```js
DemoTransformer.encode = function (ctx, params) {
return protobuf_encode_DemoReqPb(this.serialize(ctx, params));
};
```
原始的调用位置保持不变 —— 运行时调度会自然地找到重写方法,因为静态属性存在于构造函数上。抽象基类的主体也会保持原样,且永远不会被调用。
这种命名方式是结构化的,而非配置出来的:
* 包装器方法可以命名为任何名称(`encode`、`enc`、`request` 等)—— Proton 只关注主体和约束的形状。
* 同级方法的名称是从 `this: T extends { … }` 约束中读取的,因此 `serialize`/`deserialize`、`build`/`parse` 或任何其他组合都可以正常工作。
* 多层继承(`Leaf → MidBase → AbstractBase`)通过逐级 `extends` 解析支持。
同级方法**必须**显式声明返回值/参数类型注解:AST-only 路径不进行类型推导,缺少注解的方法会被跳过。只有当包装器主体中的每个编解码器调用都成功解析时,才会输出重写代码 —— 部分解析会在运行时产生死标识符引用,因此“全有或全无(all-or-nothing)”的规则是故意为之的。
## proto3 默认值语义
**重要的行为细节。** Proton 遵循 proto3 传输格式规范:如果字段的值等于该类型的默认值(`0` / `false` / `""` / 空字节),则**不会**在网络传输中输出。这在字节层面上与 SnowLuma 旧版始终输出每个字段的 `protoEncode` 运行时不同。
这两种形式与任何符合规范的 proto3 读取器都是网络兼容的(缺失的字段会解码为默认值)。在将旧版 Schema 迁移到 Proton 时,**请勿**将默认值上的字节级不一致视为回归故障 —— 参见 [`packages/core/tests/proton-parity.test.ts`](https://www.google.com/search?q=../../packages/core/tests/proton-parity.test.ts) 中固定此差异的测试。
如果你的网络数据消费者依赖于字节级的完全一致(例如用于哈希或签名),建议显式设置非默认值,而不是依赖编码器。
## 诊断机制
任何无法解析为原生类型或已注册消息的内容都会**在构建时抛出错误**,而不是静默泄露错误的传输类型:
Anything that doesn't resolve to a primitive or a registered message **throws
at build time** rather than silently leaking a wrong wire type:
```
Cannot resolve protobuf field type "Partial__UserProfile" on message "Foo"
@@ -247,71 +188,86 @@ Cannot resolve protobuf field type "Partial__UserProfile" on message "Foo"
registered message for this type. Common causes: union / intersection /
mapped / conditional types, TypeScript utility types (Partial<T>, Pick<T>, …),
qualified names (ns.Type), or a missing import.
```
这是针对分析器无法建模的 TypeScript 结构的的安全网。目前不支持的特性包括:
This is the safety net for TypeScript constructs the analyzer doesn't model.
Currently unsupported:
* 联合/交叉类型(`A | B`,`A & B`)
* 条件/映射类型(`T extends X ? A : B`,`{ [K in keyof T]: ... }`)
* TS 工具类型(`Partial<T>`,`Pick<T>`,`Readonly<T>` 等)
* 限定类型名称(`ns.Type`)
* 通过命名空间导入访问的包装函数(`import * as ns from`)
- Union / intersection types (`A | B`, `A & B`)
- Conditional / mapped types (`T extends X ? A : B`, `{ [K in keyof T]: ... }`)
- TS utility types (`Partial<T>`, `Pick<T>`, `Readonly<T>`, …)
- Qualified type names (`ns.Type`)
- Wrapper functions reached via namespace import (`import * as ns from`)
……所有这些情况都将抛出清晰的错误提示,而不会产生错误的字节。
…all of these will throw with a clear message instead of producing bad bytes.
## 边缘情况修复(对比上游)
## Optional: runtime-map fallback
每个修复在 `test/__tests__/analyzer.test.ts` 中都有对应的回归测试:
If a call site can't be statically resolved (e.g. dynamic loading after build),
the plugin can emit a JSON map that the runtime can consume to generate codecs
on the fly. Off by default.
| # | 以前会损坏的情况 |
| --- | --- |
| 1 | `import { pb as P }` —— 别名标记曾被忽略;字段被静默丢弃 |
| 2 | `interface Foo { x: pb<1, Wrapper<uint_32>> }` —— typeName 曾卡在 `"Wrapper"`,未对内部实例化进行单态化 |
| 3 | `interface Outer<U> { x: pb<1, Wrapper<U>> }` —— 外部单态化曾未重新实例化内部泛型 |
| 4 | 包装器绑定生成的虚拟 SourceFile 文本曾为空 → `getText()` 返回垃圾数据 |
| 5 | 跨文件转发的包装器(链式 → 导入的基类)曾无法被检测 |
| 6 | `matchForwardedKnownWrapper` 曾未传播 `typePattern` —— 链式调用曾将 `<X>` 视为编码类型,而不是 `Wrapper<X>` |
| 7 | 虚拟 SF 的 WeakMap 曾对 `analyzer.ts` 私有 → 替换器使用了错误的 SF |
此外,前述的构建时防线可确保未来的分析器漏洞会直接触发硬错误,而不是产生静默的编码错误。
## 脚本命令
```bash
pnpm --filter @snowluma/proton build # 打包 src/index.ts → dist/index.js
pnpm --filter @snowluma/proton test # 运行 vitest (109 个测试)
pnpm --filter @snowluma/proton typecheck # 运行 tsc --noEmit
```ts
import protobufVitePlugin from '@snowluma/proton/vite';
export default defineConfig({
plugins: [protobufVitePlugin({
runtimeMap: { enabled: true, fileName: 'snowluma-proton.runtime-map.json' },
})],
});
```
## 目录结构
```ts
import runtimeMap from './snowluma-proton.runtime-map.json';
import { protobuf_enableRuntimeMapFallback } from '@snowluma/proton';
```text
protobuf_enableRuntimeMapFallback(runtimeMap);
```
## Edge cases fixed on top of upstream
Each has a regression test in `test/__tests__/analyzer.test.ts`:
| # | What used to break |
| - | --------------------- |
| 1 | `import { pb as P }` — aliased markers were ignored; fields dropped silently |
| 2 | `interface Foo { x: pb<1, Wrapper<uint_32>> }` — typeName stuck at `"Wrapper"`, no mono of the inner instantiation |
| 3 | `interface Outer<U> { x: pb<1, Wrapper<U>> }` — outer mono didn't re-instantiate the inner generic |
| 4 | Wrapper-binding synthetic SourceFile had empty text → `getText()` returned garbage |
| 5 | Cross-file forwarded wrappers (chain → imported base) not detected |
| 6 | `matchForwardedKnownWrapper` didn't propagate `typePattern` — chain treated `<X>` as the encoded type instead of `Wrapper<X>` |
| 7 | Synthetic-SF WeakMap was private to analyzer.ts → replacer used the wrong SF |
Plus the build-time guard (above) that turns future analyzer gaps into hard
errors instead of silent miscodes.
## Scripts
```
pnpm --filter @snowluma/proton build # bundle src/index.ts → dist/index.js
pnpm --filter @snowluma/proton test # vitest run (95 tests)
pnpm --filter @snowluma/proton typecheck # tsc --noEmit
```
## Layout
```
src/
ast/ 分析器 + 类型追踪管道
analyzer.ts 单次遍历的消息 + 调用位置收集
collector.ts interface → ProtobufField/GenericFieldTemplate
monomorphizer.ts 泛型实例化 → 具体 ProtobufMessage
import-resolver.ts 跨文件定义 + 包装器解析
callsite.ts 匹配 protobuf_encode/decode 调用
ast-helpers.ts 共享 AST 小工具 + 快速预检
wrapper-binding.ts 包装器绑定类型 + 类型模板实例化
static-wrapper.ts 静态方法包装器检测 (AST)
subclass-wrapper.ts AST-only extends 链遍历 + 类型参数解析
file-pipeline.ts 插件 transform() 使用的单文件胶水层
utils.ts 名称解析 + 虚拟 SF 追踪
dependency-graph.ts 拓扑排序 + 可达性
types.ts 共享的 Schema 类型
codegen/ 内联传输格式发射器
subclass-override.ts 每个子类重写的代码生成
transform/ Vite 插件字符串编辑
replacer.ts protobuf 调用替换编辑收集
text-edits.ts 通用倒序文本编辑应用
index.ts 插件入口 (./vite)
runtime.ts 运行时桩代码 (.)
protobuf.d.ts 公共类型 (pb<>, pb_repeated<>, 原生别名)
test/ vitest 测试套件 (包含分析器 + 跨文件 + 插件 + 子类包装器)
ast/ analyzer + type-tracking pipeline
analyzer.ts single-walk message + call-site collection
collector.ts interface → ProtobufField/GenericFieldTemplate
monomorphizer.ts generic instantiation → concrete ProtobufMessage
import-resolver.ts cross-file definition + wrapper resolution
callsite.ts matches protobuf_encode/decode invocations
utils.ts name resolution + synthetic-SF tracking
dependency-graph.ts topo sort + reachability
types.ts shared schema types
codegen/ inlined wire-format emitters
transform/ Vite plugin string edits
index.ts plugin entry (./vite)
runtime.ts runtime stubs + map fallback (.)
runtime-map.ts serialized map format
protobuf.d.ts public types (pb<>, pb_repeated<>, primitive aliases)
test/ vitest suite (analyzer + cross-file + plugin)
```
+36
View File
@@ -23,3 +23,39 @@ export type bytes = Uint8Array;
// ── Encode / decode (replaced at compile-time by the vite plugin) ────
export function protobuf_encode<T>(params: T): Uint8Array;
export function protobuf_decode<T>(data: Uint8Array): T;
// ── Optional runtime map fallback (disabled by default) ───────────────
export interface ProtobufRuntimeField {
name: string;
fieldNumber: number;
typeName: string;
wireType: 0 | 1 | 2 | 5;
isMessage: boolean;
isOptional: boolean;
isRepeated: boolean;
}
export interface ProtobufRuntimeMessage {
name: string;
fields: ProtobufRuntimeField[];
}
export interface ProtobufRuntimeCallSite {
file: string;
line: number;
column: number;
fnName: 'protobuf_encode' | 'protobuf_decode';
typeName: string;
}
export interface ProtobufRuntimeMap {
version: 1;
messages: ProtobufRuntimeMessage[];
callSites: ProtobufRuntimeCallSite[];
}
/** Enables map-based runtime dynamic code generation fallback. */
export function protobuf_enableRuntimeMapFallback(map: ProtobufRuntimeMap): void;
/** Disables map-based runtime fallback and clears generated function cache. */
export function protobuf_disableRuntimeMapFallback(): void;
+50 -26
View File
@@ -1,32 +1,68 @@
import ts from 'typescript';
import { getCallableName } from './ast-helpers.js';
import { WireType, PRIMITIVE_TYPE_MAP, type ProtobufMessage, type MessageRegistry, type GenericProtobufTemplate } from './types.js';
import { collectInterface, collectGenericInterface, collectConcreteFieldGenericTypeArgs } from './collector.js';
import { monomorphizeTypeNode } from './monomorphizer.js';
import {
createImportedTypeNameResolver,
typeNodeToMangledName,
registerSyntheticTypeSourceFile,
resolveSourceFileForTypeNode,
} from './utils.js';
import type { ImportedDefinitions, WrapperBinding } from './import-resolver.js';
import {
collectProtobufImportBindings,
matchProtobufCallSite,
type CanonicalProtobufFn,
} from './callsite.js';
import { collectConcreteFieldGenericTypeArgs, collectGenericInterface, collectInterface } from './collector.js';
import { buildDependencyRegistry } from './dependency-graph.js';
import type { ImportedDefinitions } from './import-resolver.js';
import { monomorphizeTypeNode } from './monomorphizer.js';
import { PRIMITIVE_TYPE_MAP, WireType, type GenericProtobufTemplate, type MessageRegistry, type ProtobufMessage } from './types.js';
import {
createImportedTypeNameResolver,
resolveSourceFileForTypeNode,
typeNodeToMangledName,
} from './utils.js';
import { instantiateWrapperTypePattern, type WrapperBinding } from './wrapper-binding.js';
export { typeNodeToMangledName } from './utils.js';
function getCallableName(expr: ts.Expression): string | null {
if (ts.isIdentifier(expr)) return expr.text;
if (ts.isPropertyAccessExpression(expr)) return expr.name.text;
return null;
}
function instantiateWrapperTypePattern(
binding: WrapperBinding,
callerTypeArgs: ts.NodeArray<ts.TypeNode>,
sf: ts.SourceFile,
): ts.TypeNode | null {
if (!binding.typePattern || !binding.typeParamNames?.length) return callerTypeArgs[binding.typeArgIndex] ?? null;
let text = binding.typePattern;
for (let i = 0; i < binding.typeParamNames.length; i++) {
const arg = callerTypeArgs[i];
if (!arg) return null;
text = text.replace(new RegExp(`\\b${binding.typeParamNames[i]}\\b`, 'g'), arg.getText(sf));
}
// Parse the substituted type pattern into a fresh source file whose
// `fileName` is the binding's origin (so subsequent import resolution can
// find the right module) AND whose `text` contains the substituted source
// (so `getText()` on the resulting TypeNode returns the actual type, not
// garbage from an empty-text companion file).
const parsed = ts.createSourceFile(
binding.sourceFilePath ?? sf.fileName,
`type __T = ${text};`,
ts.ScriptTarget.Latest,
true,
);
const stmt = parsed.statements[0];
if (!ts.isTypeAliasDeclaration(stmt)) return null;
registerSyntheticTypeSourceFile(stmt.type, parsed);
return stmt.type;
}
/** A recorded call-site for later replacement. */
export interface CallSiteRecord {
fnName: CanonicalProtobufFn;
exprStart: number; // position of identifier start
typeArgsEnd: number; // position after closing '>'
firstTypeArg: ts.TypeNode; // the type argument node
line: number; // 1-based source position for diagnostics
column: number; // 1-based source position for diagnostics
line: number; // 1-based line for runtime map lookup
column: number; // 1-based column for runtime map lookup
}
export interface ResolvedCallSiteRecord extends CallSiteRecord {
@@ -55,7 +91,7 @@ export interface UsedRegistryResult {
* Then post-processes: monomorphize → resolve wire types → topo sort.
*/
export function analyze(code: string, filePath: string, imported?: ImportedDefinitions): AnalysisResult {
const sf = imported?.sourceFile ?? ts.createSourceFile(filePath, code, ts.ScriptTarget.Latest, true);
const sf = ts.createSourceFile(filePath, code, ts.ScriptTarget.Latest, true);
const concrete: ProtobufMessage[] = [];
const templates = new Map<string, GenericProtobufTemplate>();
const mono = new Map<string, ProtobufMessage>();
@@ -224,17 +260,11 @@ export function analyzeSource(code: string, filePath: string, imported?: Importe
/**
* Build a minimal message registry by collecting only call-site root types and
* their transitive message dependencies.
*
* `extraRootNames` lets callers seed the root set with type names that
* weren't discovered through `protobuf_encode/decode` call sites — used by
* the subclass-wrapper pipeline to drag in codecs whose only consumer is a
* per-subclass override generated outside this analyzer.
*/
export function selectUsedRegistry(
registry: MessageRegistry,
callSites: CallSiteRecord[],
sourceFile: ts.SourceFile,
extraRootNames?: Iterable<string>,
): UsedRegistryResult {
const roots = new Set<string>();
const resolved: ResolvedCallSiteRecord[] = [];
@@ -246,12 +276,6 @@ export function selectUsedRegistry(
resolved.push({ ...cs, typeName });
}
if (extraRootNames) {
for (const name of extraRootNames) {
if (registry.has(name)) roots.add(name);
}
}
if (roots.size === 0) {
return { registry: new Map(), roots, callSites: resolved };
}
-64
View File
@@ -1,64 +0,0 @@
import ts from 'typescript';
/**
* Tiny AST predicates shared across the analyzer, callsite matcher,
* wrapper detector, and subclass resolver.
*
* All of these are pure structural checks on individual nodes — they
* don't walk children, don't read file content, and don't touch the
* TypeChecker. Collecting them in one module avoids the four+ private
* re-definitions that accreted while the feature stack grew.
*/
/** Identifier text behind a call's callee, normalising `foo(...)` and
* `obj.foo(...)` to just `foo`. Returns null for any other shape
* (element access, parenthesised expression, etc.) so callers don't
* accidentally treat dynamic dispatch as a known identifier. */
export function getCallableName(expr: ts.Expression): string | null {
if (ts.isIdentifier(expr)) return expr.text;
if (ts.isPropertyAccessExpression(expr)) return expr.name.text;
return null;
}
export function isStaticMethod(m: ts.MethodDeclaration): boolean {
const mods = ts.getModifiers(m);
return mods?.some(mod => mod.kind === ts.SyntaxKind.StaticKeyword) ?? false;
}
export function getMethodName(m: ts.MethodDeclaration): string | null {
if (ts.isIdentifier(m.name)) return m.name.text;
if (ts.isStringLiteral(m.name)) return m.name.text;
return null;
}
export function getPropertyNameText(name: ts.PropertyName): string | null {
if (ts.isIdentifier(name)) return name.text;
if (ts.isStringLiteral(name)) return name.text;
return null;
}
/** Match a `TypeNode` that's just a bare reference to `name` with no
* type-args (`Foo`, NOT `Foo<X>` and NOT `ns.Foo`). Used by the
* subclass resolver when looking for a method's type parameter inside
* a `this: T extends {…}` constraint. */
export function isBareTypeRef(node: ts.TypeNode, name: string): boolean {
if (!ts.isTypeReferenceNode(node)) return false;
if (!ts.isIdentifier(node.typeName)) return false;
return node.typeName.text === name;
}
/** True if the file has at least one top-level class declaration whose
* heritage clause includes `extends X`. Cheap O(top-level) scan used
* as a precondition guard before doing TypeChecker-heavy work — most
* files in a typical project have no extending classes and this lets
* us short-circuit the whole subclass-wrapper pipeline. */
export function fileHasExtendingClass(sf: ts.SourceFile): boolean {
for (const stmt of sf.statements) {
if (!ts.isClassDeclaration(stmt)) continue;
if (!stmt.heritageClauses?.length) continue;
for (const h of stmt.heritageClauses) {
if (h.token === ts.SyntaxKind.ExtendsKeyword && h.types.length > 0) return true;
}
}
return false;
}
+1 -11
View File
@@ -23,15 +23,7 @@ export interface ProtobufCallSite {
column: number;
}
// Same shape as utils.ts' `resolverCache`: bindings are deterministic per
// SourceFile and queried from analyzer + replacer + wrapper detector +
// import resolver, so memoise by node identity.
const bindingsCache = new WeakMap<ts.SourceFile, ProtobufImportBindings>();
export function collectProtobufImportBindings(sf: ts.SourceFile): ProtobufImportBindings {
const cached = bindingsCache.get(sf);
if (cached) return cached;
const identifierToCanonical = new Map<string, CanonicalProtobufFn>();
const namespaceAliases = new Set<string>();
const blockedLegacyCanonical = new Set<CanonicalProtobufFn>();
@@ -73,9 +65,7 @@ export function collectProtobufImportBindings(sf: ts.SourceFile): ProtobufImport
}
}
const result: ProtobufImportBindings = { identifierToCanonical, namespaceAliases, blockedLegacyCanonical, hasRuntimeImport };
bindingsCache.set(sf, result);
return result;
return { identifierToCanonical, namespaceAliases, blockedLegacyCanonical, hasRuntimeImport };
}
interface MatchOptions {
+13 -10
View File
@@ -1,12 +1,15 @@
import ts from 'typescript';
import {
PB_MARKER, PB_REPEATED_MARKER,
WireType,
type GenericFieldTemplate,
type GenericProtobufTemplate,
PB_MARKER, PB_REPEATED_MARKER,
type ProtobufField, type ProtobufMessage,
type GenericProtobufTemplate, type GenericFieldTemplate,
} from './types.js';
import { identityImportedTypeName, isKeywordTypeNode, typeNodeToMangledName, type ImportedTypeNameResolver } from './utils.js';
import { isKeywordTypeNode, typeNodeToMangledName, type ImportedTypeNameResolver } from './utils.js';
function identityImportedTypeName(name: string): string {
return name;
}
/**
* Yield generic-instantiated type-arg nodes appearing as field types on a
@@ -147,12 +150,12 @@ function extractGenericField(
isOptional: member.questionToken != null,
isRepeated: parsed.marker === PB_REPEATED_MARKER,
};
// If the field's type-arg is itself a generic instantiation (`Wrapper<U>`,
// where U is a type param of the enclosing template), capture the original
// source text so monomorphization can substitute U and re-instantiate the
// inner generic. Without this the field's `rawTypeName` would stay at the
// unsubstituted `'Wrapper__U'` form and the substituted instantiation
// would never reach the registry.
// If the field's type-arg is itself a generic instantiation (`Wrapper<U>`,
// where U is a type param of the enclosing template), capture the original
// source text so monomorphization can substitute U and re-instantiate the
// inner generic. Without this the field's `rawTypeName` would stay at the
// unsubstituted `'Wrapper__U'` form and the substituted instantiation
// would never reach the registry.
const ta = parsed.typeArgNode;
if (ts.isTypeReferenceNode(ta) && ta.typeArguments && ta.typeArguments.length > 0) {
result.genericTypeArgText = ta.getText(sf);
-101
View File
@@ -1,101 +0,0 @@
import { readFileSync } from 'fs';
import ts from 'typescript';
import { renderSubclassOverride } from '../codegen/subclass-override.js';
import { fileHasExtendingClass } from './ast-helpers.js';
import { resolveImports, type ParsedFileEntry } from './import-resolver.js';
import {
resolveSubclassWrappers,
sharedWrapperCache,
type ResolvedSubclassWrapper,
} from './subclass-wrapper.js';
/** One contiguous insertion to splice into the user file, addressing the
* spot immediately after a subclass's closing `}`. Grouped per subclass so
* multiple inherited overrides (encode + decode + …) land together. */
export interface SubclassOverrideInsertion {
/** Source-file offset of the insertion point. Always == subclass.end so
* any user code after the class declaration runs against the override. */
position: number;
/** Pre-rendered TS-flavoured snippet, ready to splice. */
code: string;
}
/** Result returned by `runSubclassWrapperPipeline`. */
export interface SubclassWrapperPipelineResult {
/** All resolved subclass overrides reachable from this file. Empty when
* no class in the file extends a wrapper-bearing base, or when resolution
* fails for every candidate. */
resolvedWrappers: ResolvedSubclassWrapper[];
/** Mangled type names that must be present in the codec registry for the
* generated overrides to compile against. Handed to `selectUsedRegistry`
* as extra roots. */
extraRootTypeNames: string[];
/** Pre-rendered insertions ready to feed into the text-edit applier. */
insertions: SubclassOverrideInsertion[];
}
const EMPTY: SubclassWrapperPipelineResult = {
resolvedWrappers: [],
extraRootTypeNames: [],
insertions: [],
};
/** Resolve inherited wrapper overrides for every class in `sourceFile` using
* the AST-only resolver. `fileCache` is the same map populated by
* `resolveImports`; cross-file extends edges are walked through it. */
export function runSubclassWrapperPipeline(
sourceFile: ts.SourceFile,
fileCache: Map<string, ParsedFileEntry>,
): SubclassWrapperPipelineResult {
const allResolved: ResolvedSubclassWrapper[] = [];
const extraRoots = new Set<string>();
// Group per subclass so encode + decode + ... land in one contiguous block.
const perSubclass = new Map<ts.ClassDeclaration, string[]>();
for (const stmt of sourceFile.statements) {
if (!ts.isClassDeclaration(stmt) || !stmt.name) continue;
const resolved = resolveSubclassWrappers(stmt, sourceFile, fileCache, sharedWrapperCache);
for (const r of resolved) {
allResolved.push(r);
for (const c of r.resolvedCodecCalls) extraRoots.add(c.resolvedTypeName);
const rendered = renderSubclassOverride(r);
if (!rendered) continue;
const bucket = perSubclass.get(r.subclass);
if (bucket) bucket.push(rendered.code);
else perSubclass.set(r.subclass, [rendered.code]);
}
}
if (allResolved.length === 0) return EMPTY;
const insertions: SubclassOverrideInsertion[] = [];
for (const [subclass, codes] of perSubclass) {
insertions.push({ position: subclass.end, code: '\n' + codes.join('\n') });
}
return {
resolvedWrappers: allResolved,
extraRootTypeNames: Array.from(extraRoots),
insertions,
};
}
/** Convenience entry that reads `filePath` from disk, builds a fresh file
* cache, and delegates to `runSubclassWrapperPipeline`. Used by tests and
* callers that don't already have a parsed source file + cache on hand. */
export function runSubclassWrapperPipelineFromPath(filePath: string): SubclassWrapperPipelineResult {
let code: string;
try {
code = readFileSync(filePath, 'utf-8');
} catch {
return EMPTY;
}
// Cheap AST scan first — most files have no extending classes and we can
// skip the expensive `resolveImports` recursive descent entirely.
const probeSf = ts.createSourceFile(filePath, code, ts.ScriptTarget.Latest, true);
if (!fileHasExtendingClass(probeSf)) return EMPTY;
const fileCache = new Map<string, ParsedFileEntry>();
const imported = resolveImports(code, filePath, fileCache);
return runSubclassWrapperPipeline(imported.sourceFile, fileCache);
}
+192 -117
View File
@@ -1,61 +1,59 @@
import { existsSync, readFileSync } from 'fs';
import { dirname, resolve } from 'path';
import ts from 'typescript';
import { getCallableName } from './ast-helpers.js';
import { collectProtobufImportBindings, matchProtobufCallSite } from './callsite.js';
import { collectGenericInterface, collectInterface } from './collector.js';
import { PRIMITIVE_TYPE_MAP, type GenericProtobufTemplate, type ProtobufMessage } from './types.js';
import { readFileSync, existsSync } from 'fs';
import { dirname, resolve } from 'path';
import { collectInterface, collectGenericInterface } from './collector.js';
import { PRIMITIVE_TYPE_MAP, type ProtobufMessage, type GenericProtobufTemplate } from './types.js';
import { createImportedTypeNameResolver, isKeywordTypeNode, type ImportedTypeNameResolver } from './utils.js';
import { instantiateWrapperTypePattern, type WrapperBinding } from './wrapper-binding.js';
export type { WrapperBinding } from './wrapper-binding.js';
import { collectProtobufImportBindings, matchProtobufCallSite, type CanonicalProtobufFn } from './callsite.js';
export interface WrapperBinding {
fnName: CanonicalProtobufFn;
typeArgIndex: number;
typePattern?: string;
typeParamNames?: string[];
sourceFilePath?: string;
}
export interface ParsedFileEntry {
filePath: string;
sourceFile: ts.SourceFile;
dependencyFiles: string[];
concrete: ProtobufMessage[];
templates: Map<string, GenericProtobufTemplate>;
importedTypeSources: Map<string, string>;
exportAllTypeSources: Map<string, string>;
resolveImportedTypeName: ImportedTypeNameResolver;
exportedWrappers: Map<string, WrapperBinding>;
filePath: string;
concrete: ProtobufMessage[];
templates: Map<string, GenericProtobufTemplate>;
importedTypeSources: Map<string, string>;
exportAllTypeSources: Map<string, string>;
resolveImportedTypeName: ImportedTypeNameResolver;
exportedWrappers: Map<string, WrapperBinding>;
}
export interface ImportedDefinitions {
sourceFile: ts.SourceFile;
dependencyFiles: string[];
concrete: ProtobufMessage[];
templates: Map<string, GenericProtobufTemplate>;
wrapperBindings: Map<string, WrapperBinding>;
concrete: ProtobufMessage[];
templates: Map<string, GenericProtobufTemplate>;
wrapperBindings: Map<string, WrapperBinding>;
}
interface ImportClause {
importedName: string;
localName: string;
specifier: string;
importedName: string;
localName: string;
specifier: string;
}
const importClausesCache = new WeakMap<ts.SourceFile, ImportClause[]>();
const valueImportClausesCache = new WeakMap<ts.SourceFile, ImportClause[]>();
const exportAllSpecifiersCache = new WeakMap<ts.SourceFile, string[]>();
function collectImportClauses(sf: ts.SourceFile, valueOnly: boolean): ImportClause[] {
const cache = valueOnly ? valueImportClausesCache : importClausesCache;
const cached = cache.get(sf);
if (cached) return cached;
function getCallableName(expr: ts.Expression): string | null {
if (ts.isIdentifier(expr)) return expr.text;
if (ts.isPropertyAccessExpression(expr)) return expr.name.text;
return null;
}
/** Extract all named imports from the source file (both type and value imports). */
function extractImports(sf: ts.SourceFile): ImportClause[] {
const result: ImportClause[] = [];
for (const stmt of sf.statements) {
if (!ts.isImportDeclaration(stmt) || !stmt.importClause) continue;
if (valueOnly && stmt.importClause.isTypeOnly) continue;
const spec = stmt.moduleSpecifier;
if (!ts.isStringLiteral(spec)) continue;
const specifier = spec.text;
const named = stmt.importClause.namedBindings;
if (named && ts.isNamedImports(named)) {
for (const el of named.elements) {
if (valueOnly && el.isTypeOnly) continue;
const clause = stmt.importClause;
if (clause.namedBindings && ts.isNamedImports(clause.namedBindings)) {
for (const el of clause.namedBindings.elements) {
result.push({
importedName: (el.propertyName ?? el.name).text,
localName: el.name.text,
@@ -64,33 +62,52 @@ function collectImportClauses(sf: ts.SourceFile, valueOnly: boolean): ImportClau
}
}
}
cache.set(sf, result);
return result;
}
/** All named imports (type + value). */
const extractImports = (sf: ts.SourceFile): ImportClause[] => collectImportClauses(sf, false);
/** Like `extractImports`, but skips `import type { ... }` and `import { type X }`
* entries. Wrapper functions are values, so type-only imports can't introduce
* one and we shouldn't eagerly parse their source files just to look for wrappers. */
function extractValueImports(sf: ts.SourceFile): ImportClause[] {
const result: ImportClause[] = [];
for (const stmt of sf.statements) {
if (!ts.isImportDeclaration(stmt) || !stmt.importClause) continue;
if (stmt.importClause.isTypeOnly) continue;
const spec = stmt.moduleSpecifier;
if (!ts.isStringLiteral(spec)) continue;
const specifier = spec.text;
/** Value-only named imports. Type-only imports can't introduce a wrapper function
* and shouldn't trigger eager source-file parsing. */
const extractValueImports = (sf: ts.SourceFile): ImportClause[] => collectImportClauses(sf, true);
const clause = stmt.importClause;
if (clause.namedBindings && ts.isNamedImports(clause.namedBindings)) {
for (const el of clause.namedBindings.elements) {
if (el.isTypeOnly) continue;
result.push({
importedName: (el.propertyName ?? el.name).text,
localName: el.name.text,
specifier,
});
}
}
}
return result;
}
function extractExportAllSpecifiers(sf: ts.SourceFile): string[] {
const cached = exportAllSpecifiersCache.get(sf);
if (cached) return cached;
const result: string[] = [];
for (const stmt of sf.statements) {
if (!ts.isExportDeclaration(stmt) || stmt.exportClause) continue;
const spec = stmt.moduleSpecifier;
if (spec && ts.isStringLiteral(spec)) result.push(spec.text);
}
exportAllSpecifiersCache.set(sf, result);
return result;
}
// Bundler resolution for bare specifiers: supports package.json exports,
// workspace symlinks, and path aliases without requiring extensions.
// Compiler options used for bare-specifier module resolution. `Bundler`
// matches modern monorepo + vite tooling: it understands `package.json`
// `exports`, `main`, and workspace symlinks without forcing the caller
// to spell out file extensions. We pass these once per process — the
// only consumer here is `ts.resolveModuleName` and it doesn't mutate
// them.
const BARE_SPECIFIER_COMPILER_OPTIONS: ts.CompilerOptions = {
moduleResolution: ts.ModuleResolutionKind.Bundler,
module: ts.ModuleKind.ESNext,
@@ -114,14 +131,44 @@ function getBareModuleResolutionCache(): ts.ModuleResolutionCache {
return bareModuleResolutionCache;
}
/** Resolve a specifier (relative or bare) to an absolute `.ts` source path.
* Returns `null` for non-.ts files (`.d.ts`, `.js`) or unresolved paths.
* Relative specifiers use direct file probing; bare specifiers use TS bundler
* resolution so workspaces, path aliases, and `package.json` exports work.
* Only `.ts` source is accepted — `.d.ts` strips the `pb<>` type arguments. */
/**
* Resolve a module specifier (relative OR bare) to an absolute `.ts`
* source-file path. Returns `null` if the resolution lands on something
* proton can't consume (a `.d.ts` declaration, a `.js` build artifact,
* or just not-found).
*
* Two code paths:
*
* - **Relative** (`./foo`, `../bar`): direct file-existence probe.
* Same behavior as before — fast, no TS dependency. Preserved
* verbatim so that the common case (cross-file imports inside a
* single package) is unaffected by the new bare-specifier logic.
*
* - **Bare** (`@scope/pkg`, `pkg-name`, `~alias`): delegate to
* TypeScript's module resolution so monorepo workspaces / npm
* packages / tsconfig paths / package.json `exports` all just work.
* Required to support proto definitions that live in a separate
* workspace package — e.g. moving `bridge/proto/proton/*.ts` into a
* dedicated `@snowluma/proto-defs` package while keeping the call
* sites in `@snowluma/core`.
*
* We deliberately require the resolved file to be `.ts` (not
* `.d.ts`): proton collects `pb<…>` field tags by walking interface
* AST nodes, and a hand-written `.d.ts` *would* work too — but the
* typical `dist/index.d.ts` strips away the `pb<>` type arguments
* proton needs. Asking proto-definition packages to ship source
* `.ts` (the same model `@snowluma/proton` itself uses) avoids that
* footgun entirely.
*/
function resolveModulePath(specifier: string, importerPath: string): string | null {
if (specifier.startsWith('.')) {
// ── Relative path branch (preserved verbatim from the pre-bare-
// specifier implementation; existing callers depend on its
// exact behavior, including the .ts-only filter). ──
const base = resolve(dirname(importerPath), specifier);
// Try exact path (e.g., './types.ts')
if (existsSync(base) && !base.endsWith('.ts') === false) return base;
if (base.endsWith('.ts') && existsSync(base)) return base;
// Try appending .ts
@@ -135,6 +182,7 @@ function resolveModulePath(specifier: string, importerPath: string): string | nu
return null;
}
// ── Bare specifier branch ──
const result = ts.resolveModuleName(
specifier,
importerPath,
@@ -149,19 +197,6 @@ function resolveModulePath(specifier: string, importerPath: string): string | nu
return resolved.resolvedFileName;
}
/** Resolve `name` (imported into `sf`) to the absolute path of the `.ts`
* module that declares it. Returns null for local symbols, type-only imports,
* or unresolved specifiers. Used by the AST-only subclass-wrapper resolver to
* walk extends edges across file boundaries. */
export function findImportSourcePath(sf: ts.SourceFile, name: string, fromPath: string): string | null {
for (const imp of collectImportClauses(sf, false)) {
if (imp.importedName === name || imp.localName === name) {
return resolveModulePath(imp.specifier, fromPath);
}
}
return null;
}
function hasExportModifier(node: ts.Node): boolean {
return ts.canHaveModifiers(node) && !!ts.getModifiers(node)?.some(m => m.kind === ts.SyntaxKind.ExportKeyword);
}
@@ -185,9 +220,9 @@ function matchForwardedProtobufFn(
});
if (
cs &&
ts.isTypeReferenceNode(cs.firstTypeArg) &&
ts.isIdentifier(cs.firstTypeArg.typeName) &&
typeParamIndexes.has(cs.firstTypeArg.typeName.text)
ts.isTypeReferenceNode(cs.firstTypeArg) &&
ts.isIdentifier(cs.firstTypeArg.typeName) &&
typeParamIndexes.has(cs.firstTypeArg.typeName.text)
) {
found = {
fnName: cs.fnName,
@@ -197,10 +232,10 @@ function matchForwardedProtobufFn(
return;
}
if (cs && findTypeParameterIndex(cs.firstTypeArg, typeParamIndexes) !== null) {
if (cs && containsTypeParameter(cs.firstTypeArg, typeParamIndexes)) {
found = {
fnName: cs.fnName,
typeArgIndex: findTypeParameterIndex(cs.firstTypeArg, typeParamIndexes) ?? 0,
typeArgIndex: firstTypeParameterIndex(cs.firstTypeArg, typeParamIndexes) ?? 0,
typePattern: cs.firstTypeArg.getText(sf),
typeParamNames,
sourceFilePath: sf.fileName,
@@ -215,7 +250,21 @@ function matchForwardedProtobufFn(
return found;
}
function findTypeParameterIndex(typeNode: ts.TypeNode, typeParamIndexes: Map<string, number>): number | null {
function containsTypeParameter(typeNode: ts.TypeNode, typeParamIndexes: Map<string, number>): boolean {
let found = false;
function visit(node: ts.Node): void {
if (found) return;
if (ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName) && typeParamIndexes.has(node.typeName.text)) {
found = true;
return;
}
ts.forEachChild(node, visit);
}
visit(typeNode);
return found;
}
function firstTypeParameterIndex(typeNode: ts.TypeNode, typeParamIndexes: Map<string, number>): number | null {
let index: number | null = null;
function visit(node: ts.Node): void {
if (index !== null) return;
@@ -229,6 +278,26 @@ function findTypeParameterIndex(typeNode: ts.TypeNode, typeParamIndexes: Map<str
return index;
}
function instantiateWrapperTypePattern(
binding: WrapperBinding,
callerTypeArgs: ts.NodeArray<ts.TypeNode>,
sf: ts.SourceFile,
): ts.TypeNode | null {
if (!binding.typePattern || !binding.typeParamNames?.length) return callerTypeArgs[binding.typeArgIndex] ?? null;
let text = binding.typePattern;
for (let i = 0; i < binding.typeParamNames.length; i++) {
const arg = callerTypeArgs[i];
if (!arg) return null;
text = text.replace(new RegExp(`\\b${binding.typeParamNames[i]}\\b`, 'g'), arg.getText(sf));
}
const parsed = ts.createSourceFile('wrapper-type.ts', `type __T = ${text};`, ts.ScriptTarget.Latest, true);
const stmt = parsed.statements[0];
if (!ts.isTypeAliasDeclaration(stmt)) return null;
return stmt.type;
}
function matchForwardedKnownWrapper(
body: ts.ConciseBody | ts.Block | undefined,
typeParams: readonly ts.TypeParameterDeclaration[] | undefined,
@@ -247,11 +316,11 @@ function matchForwardedKnownWrapper(
const forwardedTypeArg = wrapper ? node.typeArguments[wrapper.typeArgIndex] : undefined;
if (
wrapper &&
forwardedTypeArg &&
ts.isTypeReferenceNode(forwardedTypeArg) &&
ts.isIdentifier(forwardedTypeArg.typeName) &&
!forwardedTypeArg.typeArguments?.length &&
typeParamIndexes.has(forwardedTypeArg.typeName.text)
forwardedTypeArg &&
ts.isTypeReferenceNode(forwardedTypeArg) &&
ts.isIdentifier(forwardedTypeArg.typeName) &&
!forwardedTypeArg.typeArguments?.length &&
typeParamIndexes.has(forwardedTypeArg.typeName.text)
) {
const chainTypeArgIndex = typeParamIndexes.get(forwardedTypeArg.typeName.text)!;
const binding: WrapperBinding = {
@@ -390,6 +459,13 @@ function collectWrappers(
return wrappers;
}
function collectExportedWrappers(
sf: ts.SourceFile,
externalKnownWrappers: Map<string, WrapperBinding> = new Map(),
): Map<string, WrapperBinding> {
return collectWrappers(sf, true, externalKnownWrappers);
}
/**
* Parse a file and extract its protobuf interfaces and generic templates.
*
@@ -411,10 +487,14 @@ function parseFileForDefinitions(
const resolveImportedTypeName = createImportedTypeNameResolver(sf);
const importedTypeSources = new Map<string, string>();
const exportAllTypeSources = new Map<string, string>();
const dependencyFiles = new Set<string>([absolutePath]);
// Collect imported wrapper bindings (value imports only, not type-only)
// so this file's forwarders can match against them.
// Collect imported wrapper bindings under their LOCAL names so this file's
// forwarders can match against them. Skip work entirely if there's no cache
// (legacy callers that don't care about cross-file forwarding).
//
// Only descends into value imports (not `import type { ... }`), since
// type-only imports can never introduce a wrapper function. This avoids
// pulling unrelated type-only modules into the cache.
const importedKnownWrappers = new Map<string, WrapperBinding>();
if (cache) {
const inProgress = parsing ?? new Set<string>();
@@ -428,15 +508,13 @@ function parseFileForDefinitions(
entry = parseFileForDefinitions(resolved, undefined, cache, inProgress);
cache.set(resolved, entry);
}
dependencyFiles.add(resolved);
for (const dep of entry.dependencyFiles) dependencyFiles.add(dep);
const wrapperFn = entry.exportedWrappers.get(imp.importedName);
if (wrapperFn) importedKnownWrappers.set(imp.localName, wrapperFn);
}
inProgress.delete(absolutePath);
}
const exportedWrappers = collectWrappers(sf, true, importedKnownWrappers);
const exportedWrappers = collectExportedWrappers(sf, importedKnownWrappers);
for (const imp of extractImports(sf)) {
const resolved = resolveModulePath(imp.specifier, absolutePath);
@@ -456,8 +534,6 @@ function parseFileForDefinitions(
entry = parseFileForDefinitions(resolved, undefined, cache, inProgress);
cache.set(resolved, entry);
}
dependencyFiles.add(resolved);
for (const dep of entry.dependencyFiles) dependencyFiles.add(dep);
for (const msg of entry.concrete) exportAllTypeSources.set(msg.name, resolved);
for (const name of entry.templates.keys()) exportAllTypeSources.set(name, resolved);
for (const [name, source] of entry.exportAllTypeSources) exportAllTypeSources.set(name, source);
@@ -478,8 +554,6 @@ function parseFileForDefinitions(
return {
filePath: absolutePath,
sourceFile: sf,
dependencyFiles: [...dependencyFiles],
concrete,
templates,
importedTypeSources,
@@ -508,8 +582,8 @@ function collectCallRootTypeNodes(sf: ts.SourceFile): ts.TypeNode[] {
}
interface RootTypeNode {
typeNode: ts.TypeNode;
from: ParsedFileEntry;
typeNode: ts.TypeNode;
from: ParsedFileEntry;
}
/**
@@ -642,29 +716,39 @@ export function resolveImports(
}
}
const entrySourceFile = entry.sourceFile;
const rootTypeNodes: RootTypeNode[] = collectCallRootTypeNodes(entrySourceFile)
const rootTypeNodes: RootTypeNode[] = collectCallRootTypeNodes(ts.createSourceFile(entryPath, code, ts.ScriptTarget.Latest, true))
.map(typeNode => ({ typeNode, from: entry }));
const entrySourceFile = ts.createSourceFile(entryPath, code, ts.ScriptTarget.Latest, true);
const wrapperBindings = collectWrapperBindings(entry, entrySourceFile);
ts.forEachChild(entrySourceFile, function visit(node) {
if (ts.isCallExpression(node) && node.typeArguments?.length) {
const callableName = getCallableName(node.expression);
const binding = callableName ? wrapperBindings.get(callableName) ?? (
if (
ts.isCallExpression(node) &&
node.typeArguments?.length &&
getCallableName(node.expression) &&
(
wrapperBindings.has(getCallableName(node.expression)!) ||
(
ts.isPropertyAccessExpression(node.expression) &&
ts.isIdentifier(node.expression.expression) &&
importedObjectWrapperMembers.get(node.expression.expression.text)?.has(node.expression.name.text)
)
)
) {
const binding = wrapperBindings.get(getCallableName(node.expression)!) ?? (
ts.isPropertyAccessExpression(node.expression) && ts.isIdentifier(node.expression.expression)
? importedObjectWrapperMembers.get(node.expression.expression.text)?.get(node.expression.name.text)
: undefined
) : undefined;
if (binding) {
const typeArg = instantiateWrapperTypePattern(binding, node.typeArguments, entrySourceFile);
if (typeArg) rootTypeNodes.push({
typeNode: typeArg,
from: binding.typePattern && binding.sourceFilePath ? getEntry(binding.sourceFilePath) : entry,
});
if (binding.typePattern) {
for (const callerTypeArg of node.typeArguments) {
rootTypeNodes.push({ typeNode: callerTypeArg, from: entry });
}
);
if (!binding) return;
const typeArg = instantiateWrapperTypePattern(binding, node.typeArguments, entrySourceFile);
if (typeArg) rootTypeNodes.push({
typeNode: typeArg,
from: binding.typePattern && binding.sourceFilePath ? getEntry(binding.sourceFilePath) : entry,
});
if (binding.typePattern) {
for (const callerTypeArg of node.typeArguments) {
rootTypeNodes.push({ typeNode: callerTypeArg, from: entry });
}
}
}
@@ -676,14 +760,5 @@ export function resolveImports(
resolveTypeNode(root.typeNode, root.from);
}
const dependencyFiles = new Set<string>(entry.dependencyFiles);
for (const filePath of fileEntries.keys()) dependencyFiles.add(filePath);
return {
sourceFile: entrySourceFile,
dependencyFiles: [...dependencyFiles],
concrete: [...concrete.values()],
templates,
wrapperBindings,
};
return { concrete: [...concrete.values()], templates, wrapperBindings };
}
Loaded 100 of 136 files, more files were not shown because too many files have changed in this diff. Show more