@napuketto/adapter 0.24.4 → 0.24.6

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.
@@ -178,46 +178,32 @@ function decodeTaggedField(data, start, depth) {
178
178
  const [tagValue, afterTag] = tag;
179
179
  const no = Number(tagValue >> 3n);
180
180
  if (no === 0) return null;
181
- return decodeFieldByWire(data, afterTag, no, Number(tagValue & 7n), depth);
182
- }
183
- /** 按 wire type 分派字段解码。 */
184
- function decodeFieldByWire(data, afterTag, no, wireType, depth) {
185
- if (wireType === 0) return decodeVarintFieldAt(data, afterTag, no);
186
- if (wireType === 2) return decodeLengthDelimited(data, afterTag, no, depth);
187
- return decodeFixedField(data, afterTag, wireType);
188
- }
189
- /** wire 0:varint 字段。 */
190
- function decodeVarintFieldAt(data, afterTag, no) {
191
- const v = readVarint(data, afterTag);
192
- if (v === null) return null;
193
- return {
194
- field: {
195
- no,
196
- kind: "varint",
197
- value: v[0]
198
- },
199
- next: v[1]
200
- };
201
- }
202
- /** wire 1/5(fixed64/32):跳过(QQ NT blob 未观测到,防御性兼容);其余判失败。 */
203
- function decodeFixedField(data, afterTag, wireType) {
204
- const width = fixedWireWidth(wireType);
205
- if (width === null) return null;
206
- return skipFixedBytes(data, afterTag, width);
207
- }
208
- /** fixed 类 wire 的字节宽度(非 fixed → null)。 */
209
- function fixedWireWidth(wireType) {
210
- if (wireType === 1) return 8;
211
- return wireType === 5 ? 4 : null;
212
- }
213
- /** 定长跳过(越界判失败)。 */
214
- function skipFixedBytes(data, start, width) {
215
- const next = start + width;
216
- if (next > data.length) return null;
217
- return {
218
- field: void 0,
219
- next
220
- };
181
+ const wireType = Number(tagValue & 7n);
182
+ switch (wireType) {
183
+ case 0: {
184
+ const v = readVarint(data, afterTag);
185
+ if (v === null) return null;
186
+ return {
187
+ field: {
188
+ no,
189
+ kind: "varint",
190
+ value: v[0]
191
+ },
192
+ next: v[1]
193
+ };
194
+ }
195
+ case 2: return decodeLengthDelimited(data, afterTag, no, depth);
196
+ case 1:
197
+ case 5: {
198
+ const next = afterTag + (wireType === 1 ? 8 : 4);
199
+ if (next > data.length) return null;
200
+ return {
201
+ field: void 0,
202
+ next
203
+ };
204
+ }
205
+ default: return null;
206
+ }
221
207
  }
222
208
  /**
223
209
  * 解码 protobuf wire-format 为递归字段树(不维护字段重复/顺序语义以外的信息)。
@@ -301,13 +287,12 @@ function textOf(node, no) {
301
287
  const f = firstField(node, no);
302
288
  return f?.kind === "bytes" ? decodeText(f.value) : null;
303
289
  }
304
- /** 单个候选块 → Uint8Array(number[] -128..255 / TypedArray;其余 null)。 */
290
+ /**
291
+ * 单个候选块 → Uint8Array(Int8Array / Uint8Array / number[] -128..255;其余 null)。
292
+ * 字节值必须是整数:浮点 & 0xff 会静默截断成别的字节。
293
+ */
305
294
  function toBlob(item) {
306
295
  if (item instanceof Int8Array) return Uint8Array.from(item, (b) => b & 255);
307
- return blobFromGeneric(item);
308
- }
309
- /** Uint8Array / 字节数组形态(Int8Array 已在上层处理)。 */
310
- function blobFromGeneric(item) {
311
296
  if (item instanceof Uint8Array) return new Uint8Array(item);
312
297
  if (Array.isArray(item) && item.length > 0) return blobFromArray(item);
313
298
  return null;
@@ -316,17 +301,12 @@ function blobFromGeneric(item) {
316
301
  function blobFromArray(item) {
317
302
  const out = new Uint8Array(item.length);
318
303
  for (let i = 0; i < item.length; i += 1) {
319
- const byte = signedToUnsigned(item[i]);
320
- if (byte === null) return null;
321
- out[i] = byte;
304
+ const b = item[i];
305
+ if (typeof b !== "number" || !Number.isInteger(b) || b < -128 || b > 255) return null;
306
+ out[i] = b & 255;
322
307
  }
323
308
  return out;
324
309
  }
325
- /** 带符号/无符号字节归一(非整数拒绝:浮点 & 0xff 会静默截断成别的字节)。 */
326
- function signedToUnsigned(b) {
327
- if (typeof b !== "number" || !Number.isInteger(b) || b < -128 || b > 255) return null;
328
- return b & 255;
329
- }
330
310
  /**
331
311
  * onRecvSysMsg 参数 → sysmsg 字节块列表(防御性收窄)。
332
312
  * 接受批数组(实测形状)/ 单块裸数组 / TypedArray;零有效块返回 null
package/dist/index.mjs CHANGED
@@ -1,6 +1,6 @@
1
1
  import { f as ActionRegistry, n as ProtocolConfig, o as BaseProtocolAdapter, p as runAction, r as createServerSchema, t as ConfigBase } from "./framework-CA3087JP.mjs";
2
2
  import { N as kurobotConfigSchema, t as NapukettoKurobotAdapter } from "./kurobot-xqbvEUYA.mjs";
3
- import { r as milkyConfigSchema, t as NapukettoMilkyAdapter } from "./milky-CNn-vyvI.mjs";
4
- import { t as NapukettoOneBot11Adapter, u as ob11ConfigSchema } from "./onebot11-DOOBXC3z.mjs";
5
- import { m as satoriConfigSchema, t as NapukettoSatoriAdapter } from "./satori-DewkytUw.mjs";
3
+ import { r as milkyConfigSchema, t as NapukettoMilkyAdapter } from "./milky-DmlPzIeg.mjs";
4
+ import { t as NapukettoOneBot11Adapter, u as ob11ConfigSchema } from "./onebot11-Bq9Qd9ys.mjs";
5
+ import { m as satoriConfigSchema, t as NapukettoSatoriAdapter } from "./satori-Cmu2QGGz.mjs";
6
6
  export { ActionRegistry, BaseProtocolAdapter, ConfigBase, NapukettoKurobotAdapter, NapukettoMilkyAdapter, NapukettoOneBot11Adapter, NapukettoSatoriAdapter, ProtocolConfig, createServerSchema, kurobotConfigSchema, milkyConfigSchema, ob11ConfigSchema, runAction, satoriConfigSchema };
@@ -1 +1 @@
1
- export { a as MilkyApi, t as NapukettoMilkyAdapter, n as assembleMilkyTransports, i as createMilkyActionRegistry, r as milkyConfigSchema, o as milkyErrorCodeMap } from "../milky-CNn-vyvI.mjs";
1
+ export { a as MilkyApi, t as NapukettoMilkyAdapter, n as assembleMilkyTransports, i as createMilkyActionRegistry, r as milkyConfigSchema, o as milkyErrorCodeMap } from "../milky-DmlPzIeg.mjs";
@@ -1,7 +1,7 @@
1
1
  import { c as BEARER_PREFIX, f as ActionRegistry, i as validateListenerToken, l as createTokenAuthorize, o as BaseProtocolAdapter, p as runAction, s as resolveProtocolConfig } from "./framework-CA3087JP.mjs";
2
2
  import { _ as MediaCache, a as logEventFailure, b as withMediaScope, c as protocolMediaSchema, d as resolveLocalMedia, h as prepareImageElements, i as hasGrayTip, l as bindLocalMediaRoots, m as mediaDownloader, n as findRevokeElement, o as sliceRaw, r as firstUntranslatedGrayTip, t as collectGrayTipUids, v as cacheMediaFile } from "./gray-tip-jdpy-Jv3.mjs";
3
3
  import { a as firstNonEmptyString, c as MS_TO_SEC, d as numericUin, f as resolveUidToUinWithFallback, i as toUnixSeconds, l as NUMERIC_RE, m as toUin, o as stringOrUndefined, p as resolveUin, r as subscribeRawMessages, s as startupBaselineSec, t as forEachRawMessage } from "./raw-message-D9-8kPiU.mjs";
4
- import { a as processSysMsgBlob, c as varintAt, d as processInboundBuddyReqs, i as nodeAt, l as varintOf, n as OBSERVED_UNNAMED_SYSMSG_KEYS, o as recognizeSysMsg, r as narrowSysMsgBlobs, s as textOf, t as extractEssenceSetSysMsg, u as BuddyReqDedup } from "./essence-CXj1VAP8.mjs";
4
+ import { a as processSysMsgBlob, c as varintAt, d as processInboundBuddyReqs, i as nodeAt, l as varintOf, n as OBSERVED_UNNAMED_SYSMSG_KEYS, o as recognizeSysMsg, r as narrowSysMsgBlobs, s as textOf, t as extractEssenceSetSysMsg, u as BuddyReqDedup } from "./essence-By64qv90.mjs";
5
5
  import { ChatType, EssenceListSync, GrayTipSubType, GroupApi, GroupNotifyMsgStatus, GroupNotifyMsgType, NTGroupMemberRole, NTGroupRequestOperateTypes, TicketApi, TipGroupElementType, errorMessage, findPendingGroupRequest, hasNumberProp, hasStringProp, isRecord, kernelError, narrowEssenceGroupArg, toCanonicalElements } from "@napuketto/kernel";
6
6
  import { HttpClient, HttpServer, createSseResponse, sendWsText } from "@napuketto/network";
7
7
  import { z } from "zod";
@@ -1172,23 +1172,11 @@ function videoToIncoming(el) {
1172
1172
  /**
1173
1173
  * canonical → IncomingSegment 单元素分发(可辨识联合 switch)。
1174
1174
  * 未映射类型(unknown / forward / 规范无对应)→ null(规范兼容性要求跳过)。
1175
- *
1176
- * 按「简单段 / 媒体与载荷段」拆两级:一级 switch 只分派,二级各管一类,
1177
- * 单函数分支数保持低位(fallow 复杂度门禁)。
1178
1175
  */
1179
1176
  function canonicalToIncomingSegment(el, ctx) {
1180
1177
  switch (el.type) {
1181
1178
  case "at": return atToIncoming(el, ctx);
1182
1179
  case "reply": return replyToIncoming(el, ctx);
1183
- case "text":
1184
- case "face":
1185
- case "file": return simpleIncoming(el);
1186
- default: return mediaOrPayloadIncoming(el);
1187
- }
1188
- }
1189
- /** text / face / file 直映射。 */
1190
- function simpleIncoming(el) {
1191
- switch (el.type) {
1192
1180
  case "text": return {
1193
1181
  type: "text",
1194
1182
  data: { text: el.text }
@@ -1201,11 +1189,6 @@ function simpleIncoming(el) {
1201
1189
  }
1202
1190
  };
1203
1191
  case "file": return fileToIncoming(el);
1204
- }
1205
- }
1206
- /** 媒体段(image / voice / video)与载荷段(json / xml)映射;其余返回 null。 */
1207
- function mediaOrPayloadIncoming(el) {
1208
- switch (el.type) {
1209
1192
  case "image": return imageToIncoming(el);
1210
1193
  case "voice": return voiceToIncoming(el);
1211
1194
  case "video": return videoToIncoming(el);
@@ -1332,53 +1315,10 @@ function outgoingSegmentsToCanonical(segments) {
1332
1315
  replySeqs
1333
1316
  };
1334
1317
  }
1335
- /** 段 data 收窄(非对象按空对象处理,字段守卫会立即拒绝)。 */
1336
- function segmentData(seg) {
1337
- return isRecord(seg.data) ? seg.data : {};
1338
- }
1339
1318
  /** 已知段缺必填字段 / 类型错误 → INVALID_PARAM。 */
1340
1319
  function invalidSegment(type) {
1341
1320
  throw kernelError(`Milky 消息段 ${type} 参数不合法`, "INVALID_PARAM");
1342
1321
  }
1343
- /** text 段(必填 text: string)。 */
1344
- function textSegment(data) {
1345
- if (!hasStringProp(data, "text")) return invalidSegment("text");
1346
- return { element: {
1347
- type: "text",
1348
- text: data["text"]
1349
- } };
1350
- }
1351
- /** mention 段(必填 user_id: number)。 */
1352
- function mentionSegment(data) {
1353
- if (!hasNumberProp(data, "user_id")) return invalidSegment("mention");
1354
- const uin = String(data["user_id"]);
1355
- return {
1356
- element: {
1357
- type: "at",
1358
- target: uin
1359
- },
1360
- atUin: uin
1361
- };
1362
- }
1363
- /** face 段(必填 face_id: string)。 */
1364
- function faceSegment(data) {
1365
- if (!hasStringProp(data, "face_id")) return invalidSegment("face");
1366
- return { element: {
1367
- type: "face",
1368
- id: data["face_id"]
1369
- } };
1370
- }
1371
- /** reply 段(必填 message_seq: number)。 */
1372
- function replySegment(data) {
1373
- if (!hasNumberProp(data, "message_seq")) return invalidSegment("reply");
1374
- return {
1375
- element: {
1376
- type: "reply",
1377
- messageId: String(data["message_seq"])
1378
- },
1379
- replySeq: data["message_seq"]
1380
- };
1381
- }
1382
1322
  /** 媒体段(image/record/video,必填 uri: string)。 */
1383
1323
  function mediaSegment(type, data) {
1384
1324
  if (!hasStringProp(data, "uri")) return invalidSegment(type);
@@ -1392,55 +1332,60 @@ function mediaSegment(type, data) {
1392
1332
  path
1393
1333
  } };
1394
1334
  }
1395
- /** light_app 段(json_payload 缺省按空串,保持容忍)。 */
1396
- function lightAppSegment(data) {
1397
- const payload = data["json_payload"];
1398
- return { element: {
1399
- type: "json",
1400
- raw: typeof payload === "string" ? payload : ""
1401
- } };
1402
- }
1403
- /** 简单段类型判定(字面量联合收窄)。 */
1404
- function isSimpleOutgoingType(type) {
1405
- switch (type) {
1335
+ /** 单段分派(可辨识联合 switch):已知类型逐项守卫,未知段跳过(规范兼容性要求)。 */
1336
+ function outgoingSegmentToCanonical(seg) {
1337
+ const data = isRecord(seg.data) ? seg.data : {};
1338
+ switch (seg.type) {
1406
1339
  case "text":
1407
- case "mention":
1408
- case "mention_all":
1409
- case "face":
1410
- case "reply": return true;
1411
- default: return false;
1412
- }
1413
- }
1414
- /** 简单段分发。 */
1415
- function simpleOutgoingSegment(type, data) {
1416
- switch (type) {
1417
- case "text": return textSegment(data);
1418
- case "mention": return mentionSegment(data);
1340
+ if (!hasStringProp(data, "text")) return invalidSegment("text");
1341
+ return { element: {
1342
+ type: "text",
1343
+ text: data["text"]
1344
+ } };
1345
+ case "mention": {
1346
+ if (!hasNumberProp(data, "user_id")) return invalidSegment("mention");
1347
+ const uin = String(data["user_id"]);
1348
+ return {
1349
+ element: {
1350
+ type: "at",
1351
+ target: uin
1352
+ },
1353
+ atUin: uin
1354
+ };
1355
+ }
1419
1356
  case "mention_all": return { element: {
1420
1357
  type: "at",
1421
1358
  target: "all"
1422
1359
  } };
1423
- case "face": return faceSegment(data);
1424
- case "reply": return replySegment(data);
1425
- }
1426
- }
1427
- /** 复杂段分发(媒体 / light_app / forward / 未知)。 */
1428
- function complexOutgoingSegment(type, data) {
1429
- switch (type) {
1360
+ case "face":
1361
+ if (!hasStringProp(data, "face_id")) return invalidSegment("face");
1362
+ return { element: {
1363
+ type: "face",
1364
+ id: data["face_id"]
1365
+ } };
1366
+ case "reply":
1367
+ if (!hasNumberProp(data, "message_seq")) return invalidSegment("reply");
1368
+ return {
1369
+ element: {
1370
+ type: "reply",
1371
+ messageId: String(data["message_seq"])
1372
+ },
1373
+ replySeq: data["message_seq"]
1374
+ };
1430
1375
  case "image": return mediaSegment("image", data);
1431
1376
  case "record": return mediaSegment("record", data);
1432
1377
  case "video": return mediaSegment("video", data);
1433
- case "light_app": return lightAppSegment(data);
1378
+ case "light_app": {
1379
+ const payload = data["json_payload"];
1380
+ return { element: {
1381
+ type: "json",
1382
+ raw: typeof payload === "string" ? payload : ""
1383
+ } };
1384
+ }
1434
1385
  case "forward": throw kernelError("forward 段不可与其他消息段混发或嵌套(顶层 forward 须单独发送)", "INVALID_PARAM");
1435
1386
  default: return null;
1436
1387
  }
1437
1388
  }
1438
- /** 单段分派入口(简单段 / 复杂段两级,避免单函数分支过多)。 */
1439
- function outgoingSegmentToCanonical(seg) {
1440
- const data = segmentData(seg);
1441
- if (isSimpleOutgoingType(seg.type)) return simpleOutgoingSegment(seg.type, data);
1442
- return complexOutgoingSegment(seg.type, data);
1443
- }
1444
1389
  // src/milky/helper/event/translate.ts
1445
1390
  /**
1446
1391
  * Milky 事件翻译(RawMessage → Milky 事件,纯函数)
@@ -2352,6 +2297,7 @@ var MilkyEventPipeline = class {
2352
2297
  if (this.unsubscribes.length > 0) return;
2353
2298
  this.deps.request.markStartup();
2354
2299
  const { msgChannel, groupChannel, buddyChannel, recentContactChannel, loginChannel } = this.deps;
2300
+ this.deps.essence.start(groupChannel);
2355
2301
  this.unsubscribes.push(subscribeRawMessages(msgChannel, (msg) => this.deps.message.handle(msg).catch((err) => {
2356
2302
  this.logFailure("message_receive", err);
2357
2303
  }), { logger: this.deps.logger }), msgChannel.on("Msg/onRecvSysMsg", (a) => this.deps.sysMsg.handleRawArg(a)), msgChannel.on("Msg/onRecvOfflineFileMsg", (m) => this.deps.fileNotice.fileMessages(m)), msgChannel.on("Msg/onFileMsgCome", (m) => this.deps.fileNotice.fileMessages(m)));
@@ -2375,6 +2321,7 @@ var MilkyEventPipeline = class {
2375
2321
  }
2376
2322
  /** 退订(幂等)。 */
2377
2323
  unsubscribeAll() {
2324
+ this.deps.essence.stop();
2378
2325
  for (const off of this.unsubscribes) off();
2379
2326
  this.unsubscribes = [];
2380
2327
  }
@@ -2479,6 +2426,9 @@ var RecentKeyCache = class {
2479
2426
  this.entries.set(key, now + this.ttlMs);
2480
2427
  return true;
2481
2428
  }
2429
+ deleteMatching(predicate) {
2430
+ for (const key of this.entries.keys()) if (predicate(key)) this.entries.delete(key);
2431
+ }
2482
2432
  /** 惰性清理过期键(每次 claim 顺带执行,量级小无需定时器)。 */
2483
2433
  prune(now) {
2484
2434
  for (const [key, expiry] of this.entries) if (expiry <= now) this.entries.delete(key);
@@ -2493,15 +2443,30 @@ var MilkyInboundEssence = class {
2493
2443
  constructor(deps) {
2494
2444
  this.deps = deps;
2495
2445
  this.essenceSync = new EssenceListSync({
2446
+ allowsGroup: (groupCode) => deps.api.groupCache?.allowsGroupEvents?.(groupCode) !== false,
2496
2447
  fetchList: (groupCode) => deps.api.webApi.getEssenceMsgList(groupCode),
2497
- onAdded: (groupCode, added) => this.broadcastAdded(groupCode, added),
2498
- onRemoved: (groupCode, removed) => this.broadcastRemoved(groupCode, removed),
2448
+ onAdded: (groupCode, added, signal) => this.broadcastAdded(groupCode, added, signal),
2449
+ onRemoved: (groupCode, removed, _prev, signal) => this.broadcastRemoved(groupCode, removed, signal),
2450
+ onMembershipChange: (allows) => {
2451
+ this.essenceKeys.deleteMatching((key) => !allows(key.split(":", 1)[0] ?? ""));
2452
+ },
2453
+ onNotifyError: (groupCode, err) => deps.logger?.warn({
2454
+ group: groupCode,
2455
+ err: String(err)
2456
+ }, "精华事件广播失败"),
2457
+ onQueueFull: (groupCode) => deps.logger?.debug({ group: groupCode }, "精华同步队列已满,下次事件时重试"),
2499
2458
  onFetchError: (g, err) => deps.logger?.warn({
2500
2459
  group: g,
2501
2460
  err: String(err)
2502
2461
  }, "milky: 精华列表拉取失败(diff 跳过)")
2503
2462
  });
2504
2463
  }
2464
+ start(channel) {
2465
+ this.essenceSync.start(channel, this.deps.api.groupApi);
2466
+ }
2467
+ stop() {
2468
+ this.essenceSync.stop();
2469
+ }
2505
2470
  /** sysmsg 732:1 快路径去重守卫:非精华恒 true;精华 claim 失败(diff 已抢发)→ false。 */
2506
2471
  claimFastPath(ruleKind, data) {
2507
2472
  if (ruleKind !== "group_essence_message_change") return true;
@@ -2509,7 +2474,7 @@ var MilkyInboundEssence = class {
2509
2474
  const groupId = data["group_id"];
2510
2475
  const seq = data["message_seq"];
2511
2476
  if (typeof groupId !== "number" || typeof seq !== "number") return true;
2512
- return this.claimChange(groupId, seq, true);
2477
+ return this.essenceSync.accepts(String(groupId)) && this.claimChange(groupId, seq, true);
2513
2478
  }
2514
2479
  /** 精华列表变更:拉全量列表 diff(remove 路径 + operator 回填;串行防乱序)。 */
2515
2480
  change(arg) {
@@ -2521,13 +2486,19 @@ var MilkyInboundEssence = class {
2521
2486
  this.essenceSync.enqueue(groupCode);
2522
2487
  }
2523
2488
  /** diff 广播:add(operator = add_digest_uin,快路径已发则跳过)→ remove(operator 省略)。 */
2524
- broadcastAdded(groupCode, added) {
2489
+ broadcastAdded(groupCode, added, signal) {
2525
2490
  const now = Math.floor(Date.now() / 1e3);
2526
- for (const item of added) if (this.claimChange(groupCode, item.messageSeq, true)) this.broadcastChange(groupCode, item.messageSeq, true, numericUin(item.operatorUin), now);
2491
+ for (const item of added) {
2492
+ if (signal?.aborted === true) return;
2493
+ if (this.claimChange(groupCode, item.messageSeq, true)) this.broadcastChange(groupCode, item.messageSeq, true, numericUin(item.operatorUin), now);
2494
+ }
2527
2495
  }
2528
- broadcastRemoved(groupCode, removed) {
2496
+ broadcastRemoved(groupCode, removed, signal) {
2529
2497
  const now = Math.floor(Date.now() / 1e3);
2530
- for (const seq of removed) if (this.claimChange(groupCode, seq, false)) this.broadcastChange(groupCode, seq, false, null, now);
2498
+ for (const seq of removed) {
2499
+ if (signal?.aborted === true) return;
2500
+ if (this.claimChange(groupCode, seq, false)) this.broadcastChange(groupCode, seq, false, null, now);
2501
+ }
2531
2502
  }
2532
2503
  broadcastChange(groupCode, seq, isSet, operatorId, time) {
2533
2504
  this.deps.broadcast({
@@ -1 +1 @@
1
- export { y as MessageUnique, t as NapukettoOneBot11Adapter, r as OneBotApi, n as assembleOb11Transports, a as canonicalToCqMessage, o as canonicalToSegments, s as cqMessageToCanonical, c as cqMessageToSegments, i as createOb11ActionRegistry, f as encodeCqCode, p as escapeCqParam, m as escapeCqText, u as ob11ConfigSchema, v as ob11ErrorCodeMap, h as parseCqMessage, l as segmentsToCanonical, d as segmentsToCqMessage, g as serializeCqParts, _ as unescapeCqText } from "../onebot11-DOOBXC3z.mjs";
1
+ export { y as MessageUnique, t as NapukettoOneBot11Adapter, r as OneBotApi, n as assembleOb11Transports, a as canonicalToCqMessage, o as canonicalToSegments, s as cqMessageToCanonical, c as cqMessageToSegments, i as createOb11ActionRegistry, f as encodeCqCode, p as escapeCqParam, m as escapeCqText, u as ob11ConfigSchema, v as ob11ErrorCodeMap, h as parseCqMessage, l as segmentsToCanonical, d as segmentsToCqMessage, g as serializeCqParts, _ as unescapeCqText } from "../onebot11-Bq9Qd9ys.mjs";
@@ -1,8 +1,8 @@
1
1
  import { a as validateServerTokens, c as BEARER_PREFIX, f as ActionRegistry, l as createTokenAuthorize, o as BaseProtocolAdapter, p as runAction, r as createServerSchema, s as resolveProtocolConfig } from "./framework-CA3087JP.mjs";
2
2
  import { _ as MediaCache, a as logEventFailure, b as withMediaScope, c as protocolMediaSchema, d as resolveLocalMedia, f as downloadProtocolMedia, g as prepareVideoElements, h as prepareImageElements, i as hasGrayTip, l as bindLocalMediaRoots, m as mediaDownloader, o as sliceRaw, p as ensureSilk, r as firstUntranslatedGrayTip, s as truncRaw, t as collectGrayTipUids, u as exportQqMedia, v as cacheMediaFile } from "./gray-tip-jdpy-Jv3.mjs";
3
3
  import { a as firstNonEmptyString, c as MS_TO_SEC, d as numericUin, f as resolveUidToUinWithFallback, i as toUnixSeconds, l as NUMERIC_RE, m as toUin, n as senderNickname, o as stringOrUndefined, p as resolveUin, r as subscribeRawMessages, s as startupBaselineSec, u as collectGroupNotifyUids } from "./raw-message-D9-8kPiU.mjs";
4
- import { a as processSysMsgBlob, d as processInboundBuddyReqs, n as OBSERVED_UNNAMED_SYSMSG_KEYS, o as recognizeSysMsg, r as narrowSysMsgBlobs, t as extractEssenceSetSysMsg, u as BuddyReqDedup } from "./essence-CXj1VAP8.mjs";
5
- import { ChatType, EssenceListSync, GrayTipSubType, GroupApi, GroupNotifyMsgType, NTGroupMemberRole, NTGroupRequestOperateTypes, TicketApi, TipGroupElementType, WebHonorType, errorMessage, findPendingGroupRequest, hasStringProp, isRecord, kernelError, narrowEssenceGroupArg, toCanonicalElements, toPendingGroupRequest } from "@napuketto/kernel";
4
+ import { a as processSysMsgBlob, d as processInboundBuddyReqs, n as OBSERVED_UNNAMED_SYSMSG_KEYS, o as recognizeSysMsg, r as narrowSysMsgBlobs, t as extractEssenceSetSysMsg, u as BuddyReqDedup } from "./essence-By64qv90.mjs";
5
+ import { ChatType, EssenceListSync, GrayTipSubType, GroupApi, GroupNotifyMsgType, NTGroupMemberRole, NTGroupRequestOperateTypes, TicketApi, TipGroupElementType, WebHonorType, errorMessage, findPendingGroupRequest, hasOptionalStringProp, hasStringProp, isRecord, kernelError, narrowEssenceGroupArg, toCanonicalElements, toPendingGroupRequest } from "@napuketto/kernel";
6
6
  import { HttpClient, HttpServer, WsClient, WsServer } from "@napuketto/network";
7
7
  import { z } from "zod";
8
8
  import { basename } from "node:path";
@@ -1132,33 +1132,23 @@ function rawToString(raw) {
1132
1132
  function isStringOrNumber(val) {
1133
1133
  return typeof val === "string" || typeof val === "number";
1134
1134
  }
1135
- /** 可选字符串字段(缺省合法,出现时必须是 string)。 */
1136
- function isOptionalString(data, key) {
1137
- return data[key] === void 0 || typeof data[key] === "string";
1138
- }
1139
- /** 文本 / at / face 类型的 data 校验。 */
1140
- function isTextLikeSegmentData(type, data) {
1141
- switch (type) {
1135
+ /**
1136
+ * OB11 消息段形状守卫:`type` 为 string,`data` 为对象,且**已知类型的必填字段**
1137
+ * 类型正确。未知 `type` 一律判非法(发送入口显式拒绝,不静默丢段)。
1138
+ */
1139
+ function isOB11MessageSegment(val) {
1140
+ if (!isRecord(val) || !hasStringProp(val, "type")) return false;
1141
+ const data = val["data"];
1142
+ if (!isRecord(data)) return false;
1143
+ switch (val["type"]) {
1142
1144
  case "text":
1143
1145
  case "string": return hasStringProp(data, "text");
1144
- case "at": return isStringOrNumber(data["qq"]) && isOptionalString(data, "name");
1146
+ case "at": return isStringOrNumber(data["qq"]) && hasOptionalStringProp(data, "name");
1145
1147
  case "face": return isStringOrNumber(data["id"]);
1146
- default: return false;
1147
- }
1148
- }
1149
- /** image / record / video / file 类型的 data 校验。 */
1150
- function isMediaSegmentData(type, data) {
1151
- switch (type) {
1152
1148
  case "image":
1153
1149
  case "record":
1154
- case "video": return hasStringProp(data, "file") && isOptionalString(data, "url");
1150
+ case "video": return hasStringProp(data, "file") && hasOptionalStringProp(data, "url");
1155
1151
  case "file": return hasStringProp(data, "file");
1156
- default: return false;
1157
- }
1158
- }
1159
- /** reply / forward / json / xml 类型的 data 校验。 */
1160
- function isPayloadSegmentData(type, data) {
1161
- switch (type) {
1162
1152
  case "reply":
1163
1153
  case "forward": return isStringOrNumber(data["id"]);
1164
1154
  case "json":
@@ -1167,19 +1157,6 @@ function isPayloadSegmentData(type, data) {
1167
1157
  }
1168
1158
  }
1169
1159
  /**
1170
- * OB11 消息段形状守卫:`type` 为 string,`data` 为对象,且**已知类型的必填字段**
1171
- * 类型正确。未知 `type` 一律判非法(发送入口显式拒绝,不静默丢段)。
1172
- *
1173
- * 按 data 校验形态拆成三组小函数(文本类 / 媒体类 / 载荷类),主函数只做短路组合。
1174
- */
1175
- function isOB11MessageSegment(val) {
1176
- if (!isRecord(val) || !hasStringProp(val, "type")) return false;
1177
- const data = val["data"];
1178
- if (!isRecord(data)) return false;
1179
- const type = val["type"];
1180
- return isTextLikeSegmentData(type, data) || isMediaSegmentData(type, data) || isPayloadSegmentData(type, data);
1181
- }
1182
- /**
1183
1160
  * 校验并收窄入站 segment 数组(HTTP 动作载荷 → OB11MessageSegment[])。
1184
1161
  * 任一项不合法即抛 INVALID_PARAM(ADR-009 外部边界统一错误语义)。
1185
1162
  */
@@ -3211,18 +3188,20 @@ var Ob11Enrichment = class {
3211
3188
  * resolveMsgIdBySeq fallback 层)→ MessageUnique.alloc 幂等分配(可被 get_msg
3212
3189
  * 反查的正确空间,对照 recall 的 msgSeq 错位)。未命中返回 null(跳过事件)。
3213
3190
  */
3214
- async resolveEssenceMsgId(groupCode, seq) {
3191
+ async resolveEssenceMsgId(groupCode, seq, signal) {
3215
3192
  const peer = {
3216
3193
  chatType: ChatType.GROUP,
3217
3194
  peerUid: groupCode
3218
3195
  };
3219
- const hit = (await this.api.msgApi.fetchMessages(peer, { count: 60 }).catch((err) => {
3196
+ const msgs = await this.api.msgApi.fetchMessages(peer, { count: 60 }).catch((err) => {
3220
3197
  this.calibLogger?.debug({
3221
3198
  group: groupCode,
3222
3199
  error: errorMessage(err)
3223
3200
  }, "ob11: 精华反查近段历史拉取失败");
3224
3201
  return [];
3225
- })).find((m) => Number(m.msgSeq) === seq);
3202
+ });
3203
+ if (signal?.aborted === true) return null;
3204
+ const hit = msgs.find((m) => Number(m.msgSeq) === seq);
3226
3205
  if (hit === void 0) {
3227
3206
  this.calibLogger?.warn({
3228
3207
  group: groupCode,
@@ -3241,20 +3220,32 @@ var Ob11InboundEssence = class {
3241
3220
  constructor(deps) {
3242
3221
  this.deps = deps;
3243
3222
  this.essenceSync = new EssenceListSync({
3223
+ allowsGroup: (groupCode) => deps.api.groupCache?.allowsGroupEvents?.(groupCode) !== false,
3244
3224
  fetchList: (groupCode) => deps.api.webApi.getEssenceMsgList(groupCode),
3245
- onAdded: (groupCode, added) => this.broadcastDiff(groupCode, added, "add"),
3246
- onRemoved: (groupCode, removed, prev) => this.broadcastDiff(groupCode, removed.map((seq) => ({
3225
+ onAdded: (groupCode, added, signal) => this.broadcastDiff(groupCode, added, "add", signal),
3226
+ onRemoved: (groupCode, removed, prev, signal) => this.broadcastDiff(groupCode, removed.map((seq) => ({
3247
3227
  messageSeq: seq,
3248
3228
  senderUin: prev.get(seq)?.senderUin ?? null,
3249
3229
  operatorUin: null,
3250
3230
  addDigestTime: null
3251
- })), "delete"),
3231
+ })), "delete", signal),
3232
+ onNotifyError: (groupCode, err) => deps.logger?.warn({
3233
+ group: groupCode,
3234
+ err: String(err)
3235
+ }, "精华事件广播失败"),
3236
+ onQueueFull: (groupCode) => deps.logger?.debug({ group: groupCode }, "精华同步队列已满,下次事件时重试"),
3252
3237
  onFetchError: (g, err) => deps.logger?.warn({
3253
3238
  group: g,
3254
3239
  err: String(err)
3255
3240
  }, "ob11: 精华列表拉取失败(diff 跳过)")
3256
3241
  });
3257
3242
  }
3243
+ start(channel) {
3244
+ this.essenceSync.start(channel, this.deps.api.groupApi);
3245
+ }
3246
+ stop() {
3247
+ this.essenceSync.stop();
3248
+ }
3258
3249
  /** sysmsg 732:1 加速触发器:抽取群号踢入串行链(抽取失败 → false 落校准路径)。 */
3259
3250
  triggerFromSysMsg(tree) {
3260
3251
  const hit = extractEssenceSetSysMsg(tree);
@@ -3272,7 +3263,7 @@ var Ob11InboundEssence = class {
3272
3263
  this.essenceSync.enqueue(groupCode);
3273
3264
  }
3274
3265
  /** diff 逐条广播(add/delete 共用):sender 必填 → message_id 反查 → notice 装配。 */
3275
- async broadcastDiff(groupCode, items, subType) {
3266
+ async broadcastDiff(groupCode, items, subType, signal) {
3276
3267
  const { enrich, broadcast, selfUin } = this.deps;
3277
3268
  for (const item of items) {
3278
3269
  const senderId = numericUin(item.senderUin);
@@ -3284,7 +3275,8 @@ var Ob11InboundEssence = class {
3284
3275
  }, `ob11: 精华${detail}(跳过事件)`);
3285
3276
  continue;
3286
3277
  }
3287
- const messageId = await enrich.resolveEssenceMsgId(groupCode, item.messageSeq);
3278
+ const messageId = await enrich.resolveEssenceMsgId(groupCode, item.messageSeq, signal);
3279
+ if (signal?.aborted === true) return;
3288
3280
  if (messageId === null) continue;
3289
3281
  const operatorId = numericUin(item.operatorUin);
3290
3282
  broadcast({
@@ -3721,6 +3713,7 @@ var Ob11EventPipeline = class {
3721
3713
  if (this.unsubscribes.length > 0) return;
3722
3714
  this.request.markStartup();
3723
3715
  const { msgChannel, groupChannel, friendChannel, buddyCacheEvents } = this.deps;
3716
+ this.essence.start(groupChannel);
3724
3717
  this.unsubscribes.push(subscribeRawMessages(msgChannel, (msg) => this.message.handleRawMessage(msg), { logger: this.deps.logger }), msgChannel.on("Msg/onRecvOfflineFileMsg", (a) => this.fileNotice.offlineFile(a)), msgChannel.on("Msg/onRecvSysMsg", (a) => this.sysMsg.handleRawArg(a)), msgChannel.on("Msg/onRecvOnlineFileMsg", (a) => this.fileNotice.onlineFile(a)));
3725
3718
  if (groupChannel !== void 0) this.unsubscribes.push(groupChannel.on("Group/onGroupNotifiesUpdated", (doubt, notifies) => {
3726
3719
  this.request.groupNotifies(doubt, notifies).catch((err) => logEventFailure(this.deps.logger, "ob11: group request 翻译失败(整批丢弃)", err));
@@ -3732,6 +3725,7 @@ var Ob11EventPipeline = class {
3732
3725
  if (buddyCacheEvents !== void 0) this.unsubscribes.push(buddyCacheEvents.on("BuddyCache/onBuddyAdded", (e) => this.fileNotice.friendAdd(e)));
3733
3726
  }
3734
3727
  unsubscribeAll() {
3728
+ this.essence.stop();
3735
3729
  for (const off of this.unsubscribes) off();
3736
3730
  this.unsubscribes = [];
3737
3731
  }
@@ -1 +1 @@
1
- export { f as HTTP_STATUS, t as NapukettoSatoriAdapter, c as SatoriActionError, i as SatoriApi, n as assembleSatoriTransports, d as canonicalToSatoriElements, a as createSatoriActionRegistry, o as parseContentToCanonical, l as parseElements, u as renderElements, m as satoriConfigSchema, p as satoriHttpStatusMap, s as satoriToCanonicalElements, r as toEventSignal } from "../satori-DewkytUw.mjs";
1
+ export { f as HTTP_STATUS, t as NapukettoSatoriAdapter, c as SatoriActionError, i as SatoriApi, n as assembleSatoriTransports, d as canonicalToSatoriElements, a as createSatoriActionRegistry, o as parseContentToCanonical, l as parseElements, u as renderElements, m as satoriConfigSchema, p as satoriHttpStatusMap, s as satoriToCanonicalElements, r as toEventSignal } from "../satori-Cmu2QGGz.mjs";
@@ -384,26 +384,30 @@ function readTag(source, pos) {
384
384
  * - 未配对的标签视为文本内容的一部分
385
385
  * - 文本内容前后包含换行符的连续空白会被忽略
386
386
  */
387
+ /** 文本转义映射(& < >)。 */
388
+ const TEXT_ESCAPES = {
389
+ "&": "&amp;",
390
+ "<": "&lt;",
391
+ ">": "&gt;"
392
+ };
387
393
  /** 文本转义正则(& < >)。 */
388
394
  const TEXT_ESCAPE_RE = /[&<>]/g;
389
395
  /** 文本转义(& < >)。 */
390
396
  function encodeText(input) {
391
- return input.replace(TEXT_ESCAPE_RE, (ch) => {
392
- if (ch === "&") return "&amp;";
393
- if (ch === "<") return "&lt;";
394
- return "&gt;";
395
- });
396
- }
397
+ return input.replace(TEXT_ESCAPE_RE, (ch) => TEXT_ESCAPES[ch] ?? ch);
398
+ }
399
+ /** 属性值转义映射(& " < >)。 */
400
+ const ATTR_ESCAPES = {
401
+ "&": "&amp;",
402
+ "\"": "&quot;",
403
+ "<": "&lt;",
404
+ ">": "&gt;"
405
+ };
397
406
  /** 属性值转义正则(& " < >)。 */
398
407
  const ATTR_ESCAPE_RE = /[&"<>]/g;
399
408
  /** 属性值转义(& " < >)。 */
400
409
  function encodeAttr(input) {
401
- return input.replace(ATTR_ESCAPE_RE, (ch) => {
402
- if (ch === "&") return "&amp;";
403
- if (ch === "\"") return "&quot;";
404
- if (ch === "<") return "&lt;";
405
- return "&gt;";
406
- });
410
+ return input.replace(ATTR_ESCAPE_RE, (ch) => ATTR_ESCAPES[ch] ?? ch);
407
411
  }
408
412
  /** 行首连续空白。 */
409
413
  const LEADING_WS_RE = /^\s+/;
@@ -423,114 +427,91 @@ function normalizeText(raw) {
423
427
  if (trailing !== null && NEWLINE_RE.test(trailing[0])) out = out.slice(0, -trailing[0].length);
424
428
  return out;
425
429
  }
426
- /** Satori 消息解析器状态(挂载点 / 文本缓冲 / 栈管理,拆分主循环复杂度)。 */
427
- var ElementParser = class {
428
- root = [];
429
- stack = [];
430
- text = "";
431
- /** 当前挂载数组(栈顶元素 children 或根数组)。 */
432
- mountPoint() {
433
- const top = this.stack[this.stack.length - 1];
434
- if (top === void 0) return this.root;
435
- top.children ??= [];
436
- return top.children;
437
- }
438
- /** 归一化文本落位到当前挂载点。 */
439
- pushText() {
440
- const normalized = normalizeText(this.text);
441
- this.text = "";
442
- if (normalized !== "") this.mountPoint().push({
443
- type: "text",
444
- text: normalized
445
- });
446
- }
447
- /** 解析完成的元素树。 */
448
- get elements() {
449
- return this.root;
450
- }
451
- /** 追加原始文本(解析间隙累积)。 */
452
- appendRaw(raw) {
453
- this.text += raw;
454
- }
455
- /** 起始/自闭合标签落位(压栈或仅挂载)。 */
456
- openTag(name, attrs, selfClosing) {
457
- const el = {
458
- type: name,
459
- attrs
460
- };
461
- this.mountPoint().push(el);
462
- if (!selfClosing) this.stack.push(el);
463
- }
464
- /** 收尾:剩余文本落位(栈剩余未闭合元素:文本落在栈顶元素内,宽容)。 */
465
- flush() {
466
- this.pushText();
467
- }
468
- /** 注释:返回跳过后的位置;-1 = 未闭合终止解析(注释不渲染)。 */
469
- skipComment(source, pos) {
470
- const end = source.indexOf("-->", pos);
471
- return end === -1 ? -1 : end + 3;
430
+ /** 当前挂载数组(栈顶元素 children 或根数组)。 */
431
+ function mountPoint(state) {
432
+ const top = state.stack[state.stack.length - 1];
433
+ if (top === void 0) return state.root;
434
+ top.children ??= [];
435
+ return top.children;
436
+ }
437
+ /** 归一化文本落位到当前挂载点。 */
438
+ function pushText(state) {
439
+ const normalized = normalizeText(state.text);
440
+ state.text = "";
441
+ if (normalized !== "") mountPoint(state).push({
442
+ type: "text",
443
+ text: normalized
444
+ });
445
+ }
446
+ /**
447
+ * 结束标签:匹配栈顶则闭合,否则按文本保留。
448
+ * @returns 下一个解析位置;-1 = 终止解析。
449
+ */
450
+ function closeTag(state, source, lt, slashPos) {
451
+ const { name, end } = readTagName(source, slashPos + 1);
452
+ if (name === "") {
453
+ state.text += "<";
454
+ return lt + 1;
472
455
  }
473
- /**
474
- * 结束标签:匹配栈顶则闭合,否则按文本保留。
475
- * @returns 下一个解析位置;-1 = 终止解析。
476
- */
477
- closeTag(source, lt, slashPos) {
478
- const { name, end } = readTagName(source, slashPos + 1);
479
- if (name === "") {
480
- this.text += "<";
481
- return lt + 1;
482
- }
483
- const gt = source.indexOf(">", end);
484
- if (gt === -1) {
485
- this.text += source.slice(lt);
486
- return -1;
487
- }
488
- const top = this.stack[this.stack.length - 1];
489
- if (top !== void 0 && top.type === name) {
490
- this.pushText();
491
- this.stack.pop();
492
- } else this.text += source.slice(lt, gt + 1);
493
- return gt + 1;
456
+ const gt = source.indexOf(">", end);
457
+ if (gt === -1) {
458
+ state.text += source.slice(lt);
459
+ return -1;
494
460
  }
495
- };
461
+ const top = state.stack[state.stack.length - 1];
462
+ if (top !== void 0 && top.type === name) {
463
+ pushText(state);
464
+ state.stack.pop();
465
+ } else state.text += source.slice(lt, gt + 1);
466
+ return gt + 1;
467
+ }
496
468
  /**
497
469
  * 解析 Satori 消息字符串 → 元素树。
498
470
  * 容错:未配对标签/非法标签按文本保留;解析不抛错(消息内容宽容)。
499
471
  */
500
472
  function parseElements(source) {
501
- const parser = new ElementParser();
473
+ const state = {
474
+ root: [],
475
+ stack: [],
476
+ text: ""
477
+ };
502
478
  let i = 0;
503
479
  while (i < source.length) {
504
480
  const lt = source.indexOf("<", i);
505
481
  if (lt === -1) {
506
- parser.appendRaw(source.slice(i));
482
+ state.text += source.slice(i);
507
483
  break;
508
484
  }
509
- parser.appendRaw(source.slice(i, lt));
485
+ state.text += source.slice(i, lt);
510
486
  i = lt + 1;
511
487
  if (source.startsWith("!--", i)) {
512
- const next = parser.skipComment(source, i);
513
- if (next === -1) break;
514
- i = next;
488
+ const end = source.indexOf("-->", i);
489
+ if (end === -1) break;
490
+ i = end + 3;
515
491
  continue;
516
492
  }
517
493
  if (source.startsWith("/", i)) {
518
- const next = parser.closeTag(source, lt, i);
494
+ const next = closeTag(state, source, lt, i);
519
495
  if (next === -1) break;
520
496
  i = next;
521
497
  continue;
522
498
  }
523
499
  const tag = readTag(source, i);
524
500
  if (tag.name === "") {
525
- parser.appendRaw("<");
501
+ state.text += "<";
526
502
  continue;
527
503
  }
528
- parser.pushText();
529
- parser.openTag(tag.name, tag.attrs, tag.selfClosing);
504
+ pushText(state);
505
+ const el = {
506
+ type: tag.name,
507
+ attrs: tag.attrs
508
+ };
509
+ mountPoint(state).push(el);
510
+ if (!tag.selfClosing) state.stack.push(el);
530
511
  i = tag.end;
531
512
  }
532
- parser.flush();
533
- return parser.elements;
513
+ pushText(state);
514
+ return state.root;
534
515
  }
535
516
  /** 元素树 → Satori 消息字符串。 */
536
517
  function renderElements(elements) {
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "$schema": "https://json.schemastore.org/package.json",
3
3
  "name": "@napuketto/adapter",
4
- "version": "0.24.4",
4
+ "version": "0.24.6",
5
5
  "type": "module",
6
6
  "description": "Protocol adapters (OneBot11 / Satori / KuroBot / Milky) for Napuketto",
7
7
  "keywords": [
@@ -82,7 +82,7 @@
82
82
  "dev": "tsdown --watch"
83
83
  },
84
84
  "dependencies": {
85
- "@napuketto/kernel": "^0.19.4",
85
+ "@napuketto/kernel": "^0.19.6",
86
86
  "@napuketto/media": "^0.4.1",
87
87
  "@napuketto/network": "^0.5.1",
88
88
  "zod": "^4.6.7"