@napuketto/adapter 0.14.1 → 0.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,8 +1,9 @@
1
- import { S as ActionRegistry, a as extractSysMsgEnvelope, c as narrowSysMsgBlobs, d as textOf, f as toHex, l as nodeAt, m as varintOf, p as varintAt, r as decodeProtoTree, u as recognizeSysMsg, y as BaseProtocolAdapter } from "../core-CECIwO6s.mjs";
2
- import { a as MS_TO_SEC$2, i as narrowBuddyReqs, n as extractEssenceSetSysMsg, o as resolveUin, r as narrowEssenceGroupArg, t as diffEssenceList } from "../essence-Bdms4trk.mjs";
3
- import { n as firstUntranslatedGrayTip, t as collectGrayTipUids } from "../gray-tip-ByF-MKeV.mjs";
1
+ import { S as runAction, a as extractSysMsgEnvelope, c as narrowSysMsgBlobs, d as textOf, f as toHex, l as nodeAt, m as varintOf, p as varintAt, r as decodeProtoTree, u as recognizeSysMsg, x as ActionRegistry, y as BaseProtocolAdapter } from "../core-Be1hDKmc.mjs";
2
+ import { i as narrowBuddyReqs, n as extractEssenceSetSysMsg, r as narrowEssenceGroupArg, t as EssenceListSync } from "../essence-BP3LE1Bm.mjs";
3
+ import { a as resolveUin, i as MS_TO_SEC$2, n as firstUntranslatedGrayTip, o as toUin, r as hasGrayTip, t as collectGrayTipUids } from "../gray-tip-CitrbUCZ.mjs";
4
4
  import { r as subscribeRawMessages, t as forEachRawMessage } from "../raw-message-D2vA27kj.mjs";
5
- import { ChatType, GrayTipSubType, GroupApi, GroupNotifyMsgStatus, GroupNotifyMsgType, NTGroupRequestOperateTypes, TicketApi, TipGroupElementType, isKernelError, kernelError, toCanonicalElements } from "@napuketto/kernel";
5
+ import { t as findFirstMatch } from "../lookup-Dw0W04Ng.mjs";
6
+ import { ChatType, GrayTipSubType, GroupApi, GroupNotifyMsgStatus, GroupNotifyMsgType, NTGroupRequestOperateTypes, TicketApi, TipGroupElementType, kernelError, toCanonicalElements } from "@napuketto/kernel";
6
7
  import { mkdir, rename, writeFile } from "node:fs/promises";
7
8
  import { join } from "node:path";
8
9
  import { detectFileType, downloadUrl, inferExtension } from "@napuketto/media";
@@ -118,28 +119,23 @@ var MilkyApi = class {
118
119
  /** 通知查找默认搜索数量(单屏全量,OB11 DEFAULT_COUNT 同值)。 */
119
120
  const NOTIFY_SEARCH_COUNT$1 = 100;
120
121
  /**
121
- * 按通知 seq 查找群通知(先非可疑后可疑,OB11 set_group_add_request 同路径)。
122
+ * 按通知 seq 查找群通知(先非可疑后可疑,OB11 set_group_add_request 同路径;
123
+ * 屏序骨架走 core findFirstMatch)。
122
124
  * 未找到抛 NOT_FOUND(应答动作的 seq 无效或已过期)。
123
125
  * 模块级函数(非类成员):应答动作的公共入口,OB11 同路径。
124
126
  */
125
127
  async function findGroupNotify(api, seq) {
126
- const hit = (await api.groupNotifyApi.getSingleScreenNotifies(false, NOTIFY_SEARCH_COUNT$1)).find((item) => item.seq === seq);
127
- if (hit !== void 0) return hit;
128
- const doubtHit = (await api.groupNotifyApi.getSingleScreenNotifies(true, NOTIFY_SEARCH_COUNT$1)).find((item) => item.seq === seq);
129
- if (doubtHit !== void 0) return doubtHit;
130
- throw kernelError(`未找到通知 ${seq}(无效或已过期)`, "NOT_FOUND");
128
+ const hit = await findFirstMatch([() => api.groupNotifyApi.getSingleScreenNotifies(false, NOTIFY_SEARCH_COUNT$1), () => api.groupNotifyApi.getSingleScreenNotifies(true, NOTIFY_SEARCH_COUNT$1)], (item) => item.seq === seq);
129
+ if (hit === void 0) throw kernelError(`未找到通知 ${seq}(无效或已过期)`, "NOT_FOUND");
130
+ return hit;
131
131
  }
132
132
  /** 按发起者 uid 查找好友申请(getBuddyReqList 匹配 friendUid);未找到抛 NOT_FOUND。 */
133
133
  async function findBuddyReq(api, initiatorUid) {
134
- const hit = (await api.friendApi.getBuddyReqList()).find((req) => req.friendUid === initiatorUid);
134
+ const hit = await findFirstMatch([() => api.friendApi.getBuddyReqList()], (req) => req.friendUid === initiatorUid);
135
135
  if (hit === void 0) throw kernelError(`未找到来自 ${initiatorUid} 的好友申请`, "NOT_FOUND");
136
136
  return hit;
137
137
  }
138
138
  // src/milky/helper/event/request.ts
139
- /** uid → uin(core 共享解析;ctx 携带映射)。 */
140
- function toUin$1(uid, ctx) {
141
- return resolveUin(uid, ctx.uidToUin);
142
- }
143
139
  /** BuddyReq → friend_request 事件(comment 取 words 字段,形状待校准,缺省空串)。 */
144
140
  function toFriendRequestEvent(req, ctx) {
145
141
  const words = req["words"];
@@ -148,7 +144,7 @@ function toFriendRequestEvent(req, ctx) {
148
144
  self_id: Number(ctx.selfUin),
149
145
  event_type: "friend_request",
150
146
  data: {
151
- initiator_id: toUin$1(req.friendUid, ctx),
147
+ initiator_id: toUin(req.friendUid, ctx),
152
148
  initiator_uid: req.friendUid,
153
149
  comment: typeof words === "string" ? words : "",
154
150
  via: req.sourceName ?? ""
@@ -171,7 +167,7 @@ function toGroupRequestEvent(notify, doubt, ctx) {
171
167
  group_id: groupId,
172
168
  notification_seq: seq,
173
169
  is_filtered: doubt,
174
- initiator_id: toUin$1(notify.user1?.uid, ctx),
170
+ initiator_id: toUin(notify.user1?.uid, ctx),
175
171
  comment: notify.postscript ?? ""
176
172
  }
177
173
  };
@@ -182,8 +178,8 @@ function toGroupRequestEvent(notify, doubt, ctx) {
182
178
  data: {
183
179
  group_id: groupId,
184
180
  notification_seq: seq,
185
- initiator_id: toUin$1(notify.user1?.uid, ctx),
186
- target_user_id: toUin$1(notify.user2?.uid, ctx)
181
+ initiator_id: toUin(notify.user1?.uid, ctx),
182
+ target_user_id: toUin(notify.user2?.uid, ctx)
187
183
  }
188
184
  };
189
185
  case GroupNotifyMsgType.INVITED_BY_MEMBER: return {
@@ -193,7 +189,7 @@ function toGroupRequestEvent(notify, doubt, ctx) {
193
189
  data: {
194
190
  group_id: groupId,
195
191
  invitation_seq: seq,
196
- initiator_id: toUin$1(notify.user1?.uid, ctx),
192
+ initiator_id: toUin(notify.user1?.uid, ctx),
197
193
  source_group_id: null
198
194
  }
199
195
  };
@@ -337,13 +333,6 @@ const milkyErrorCodeMap = {
337
333
  UNKNOWN: -500
338
334
  };
339
335
  // src/milky/action/base-action.ts
340
- /**
341
- * MilkyAction:Milky 动作基类(zod 校验 + KernelError → 负数 retcode)
342
- *
343
- * 与 OB11 BaseAction 分离的原因:Milky 响应信封无 echo、参数解析失败恒
344
- * retcode=-400(规范),不复用 OB11 的 400/1400 语义。
345
- * 响应信封由 transport 组装(status/retcode/data/message)。
346
- */
347
336
  /** zod 错误摘要(单行,issues 取前 3 条)。 */
348
337
  function zodSummary(error) {
349
338
  const parts = [];
@@ -353,34 +342,24 @@ function zodSummary(error) {
353
342
  var MilkyAction = class {
354
343
  /** 校验并执行(HTTP /api 入口;WS /event 不承载动作)。 */
355
344
  async handle(payload) {
356
- const parsed = this.schema.safeParse(payload);
357
- if (!parsed.success) return {
345
+ const outcome = await runAction({
346
+ schema: this.schema,
347
+ handle: (parsed) => this._handle(parsed),
348
+ errorCodeMap: this.errorCodeMap,
349
+ invalidRetcode: -400,
350
+ invalidMessage: (error) => `参数解析失败: ${zodSummary(error)}`
351
+ }, payload);
352
+ return outcome.ok ? {
353
+ status: "ok",
354
+ retcode: 0,
355
+ data: outcome.data,
356
+ message: ""
357
+ } : {
358
358
  status: "failed",
359
- retcode: -400,
359
+ retcode: outcome.retcode,
360
360
  data: null,
361
- message: `参数解析失败: ${zodSummary(parsed.error)}`
361
+ message: outcome.message
362
362
  };
363
- try {
364
- return {
365
- status: "ok",
366
- retcode: 0,
367
- data: await this._handle(parsed.data),
368
- message: ""
369
- };
370
- } catch (err) {
371
- if (isKernelError(err)) return {
372
- status: "failed",
373
- retcode: this.errorCodeMap[err.code] ?? this.errorCodeMap.UNKNOWN,
374
- data: null,
375
- message: err.message
376
- };
377
- return {
378
- status: "failed",
379
- retcode: this.errorCodeMap.UNKNOWN,
380
- data: null,
381
- message: err instanceof Error ? err.message : "未知错误"
382
- };
383
- }
384
363
  }
385
364
  };
386
365
  /**
@@ -2260,10 +2239,6 @@ function toFriendFileUploadData(msg, selfUin, uidToUin) {
2260
2239
  // src/milky/helper/event/notice.ts
2261
2240
  /** 毫秒 → 秒(Unix 时间戳)。 */
2262
2241
  const MS_TO_SEC = 1e3;
2263
- /** uid → uin(core 共享解析;ctx 携带映射)。 */
2264
- function toUin(uid, ctx) {
2265
- return resolveUin(uid, ctx.uidToUin);
2266
- }
2267
2242
  /** 事件信封公共字段。 */
2268
2243
  function envelope(msg, ctx, eventType, data) {
2269
2244
  return {
@@ -2836,10 +2811,8 @@ var NapukettoMilkyAdapter = class extends BaseProtocolAdapter {
2836
2811
  fileKeys = new RecentKeyCache(6e5);
2837
2812
  /** essence 双路径去重(732:1 快路径 vs 列表 diff,键 群:seq:方向)。 */
2838
2813
  essenceKeys = new RecentKeyCache(3e5);
2839
- /** 精华列表缓存(群号 → seq → 条目{操作者/发送者})。 */
2840
- essenceCaches = /* @__PURE__ */ new Map();
2841
- /** 精华列表拉取串行链(并发回写乱序会把新列表覆盖成旧列表)。 */
2842
- essenceChain = Promise.resolve();
2814
+ /** 精华列表串行同步(core 共享组件:缓存 + 串行链 + diff)。 */
2815
+ essenceSync;
2843
2816
  calibLogger;
2844
2817
  api;
2845
2818
  seqIndex = new MessageSeqIndex();
@@ -2864,6 +2837,17 @@ var NapukettoMilkyAdapter = class extends BaseProtocolAdapter {
2864
2837
  this.loginChannel = opts.loginChannel;
2865
2838
  this.calibLogger = opts.logger;
2866
2839
  this.api = new MilkyApi(opts, this.seqIndex);
2840
+ this.essenceSync = new EssenceListSync({
2841
+ fetchList: (groupCode) => this.api.webApi.getEssenceMsgList(groupCode),
2842
+ onAdded: (groupCode, added) => this.broadcastEssenceAdded(groupCode, added),
2843
+ onRemoved: (groupCode, removed) => this.broadcastEssenceRemoved(groupCode, removed),
2844
+ onFetchError: (groupCode, err) => {
2845
+ this.calibLogger?.warn({
2846
+ group: groupCode,
2847
+ err: String(err)
2848
+ }, "milky: 精华列表拉取失败(diff 跳过)");
2849
+ }
2850
+ });
2867
2851
  this.registry = createMilkyActionRegistry({ api: this.api });
2868
2852
  }
2869
2853
  /** 启动传输 + 订阅(enabled=false 空转:不订阅不起传输)。 */
@@ -3168,31 +3152,12 @@ var NapukettoMilkyAdapter = class extends BaseProtocolAdapter {
3168
3152
  this.calibLogger?.warn({ raw: truncate(JSON.stringify(arg)) }, "milky: onGroupEssenceListChange 未知参数形状");
3169
3153
  return;
3170
3154
  }
3171
- this.essenceChain = this.essenceChain.then(() => this.syncEssenceList(groupCode), () => void 0);
3172
- }
3173
- /** 单群精华列表同步:拉取 → diff → 广播 → 更新缓存(基线未建立只建基线)。 */
3174
- async syncEssenceList(groupCode) {
3175
- let items;
3176
- try {
3177
- items = await this.api.webApi.getEssenceMsgList(groupCode);
3178
- } catch (e) {
3179
- this.calibLogger?.warn({
3180
- group: groupCode,
3181
- err: String(e)
3182
- }, "milky: 精华列表拉取失败(diff 跳过)");
3183
- return;
3184
- }
3185
- const prev = this.essenceCaches.get(groupCode);
3186
- const { cache, added, removed } = diffEssenceList(prev, items);
3187
- this.essenceCaches.set(groupCode, cache);
3188
- if (prev === void 0) return;
3189
- const selfId = Number(this.api.self.uin);
3190
- const now = Math.floor(Date.now() / 1e3);
3191
- this.broadcastEssenceAdded(groupCode, added, now, selfId);
3192
- this.broadcastEssenceRemoved(groupCode, removed, now, selfId);
3155
+ this.essenceSync.enqueue(groupCode);
3193
3156
  }
3194
3157
  /** diff 新增项广播(is_set=true;operator = add_digest_uin;快路径已发则跳过)。 */
3195
- broadcastEssenceAdded(groupCode, added, now, selfId) {
3158
+ broadcastEssenceAdded(groupCode, added) {
3159
+ const now = Math.floor(Date.now() / 1e3);
3160
+ const selfId = Number(this.api.self.uin);
3196
3161
  for (const item of added) {
3197
3162
  if (!this.essenceKeys.claim(`${groupCode}:${item.messageSeq}:1`)) continue;
3198
3163
  const data = essenceAddedData(groupCode, item);
@@ -3205,7 +3170,9 @@ var NapukettoMilkyAdapter = class extends BaseProtocolAdapter {
3205
3170
  }
3206
3171
  }
3207
3172
  /** diff 移除项广播(is_set=false;取消无 sysmsg,operator 不可得省略)。 */
3208
- broadcastEssenceRemoved(groupCode, removed, now, selfId) {
3173
+ broadcastEssenceRemoved(groupCode, removed) {
3174
+ const now = Math.floor(Date.now() / 1e3);
3175
+ const selfId = Number(this.api.self.uin);
3209
3176
  for (const seq of removed) {
3210
3177
  if (!this.essenceKeys.claim(`${groupCode}:${seq}:0`)) continue;
3211
3178
  this.broadcastEvent({
@@ -3267,10 +3234,6 @@ var NapukettoMilkyAdapter = class extends BaseProtocolAdapter {
3267
3234
  return this.api.uidToUin(unique).catch(() => void 0);
3268
3235
  }
3269
3236
  };
3270
- /** 是否含 grayTip 元素(与 OB11 收链路同判据)。 */
3271
- function hasGrayTip(msg) {
3272
- return msg.elements.some((el) => el.grayTipElement != null);
3273
- }
3274
3237
  /** 撤回 grayTip 元素(非撤回消息返回 undefined)。 */
3275
3238
  function findRevokeElement(msg) {
3276
3239
  return msg.elements.find((el) => el.grayTipElement?.revokeElement != null)?.grayTipElement?.revokeElement;