@napuketto/adapter 0.20.0 → 0.21.1

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,12 +1,11 @@
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
- import { _ as withMediaScope, a as logEventFailure, c as protocolMediaSchema, d as fileUriToPath, f as mediaDownloader, g as protectMediaPath, h as cacheMediaFile, i as hasGrayTip, l as downloadProtocolMedia, m as MediaCache, o as sliceRaw, p as prepareVideoElements, r as firstUntranslatedGrayTip, s as truncRaw, t as collectGrayTipUids, u as ensureSilk } from "./gray-tip-BtiJls6z.mjs";
2
+ import { _ as cacheMediaFile, a as logEventFailure, c as protocolMediaSchema, d as mediaDownloader, f as prepareVideoElements, g as MediaCache, h as resolveLocalMedia, i as hasGrayTip, l as downloadProtocolMedia, m as exportQqMedia, o as sliceRaw, p as bindLocalMediaRoots, r as firstUntranslatedGrayTip, s as truncRaw, t as collectGrayTipUids, u as ensureSilk, y as withMediaScope } from "./gray-tip-D0SfHr7q.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, r as subscribeRawMessages, s as startupBaselineSec, u as collectGroupNotifyUids } from "./raw-message-DU8YOhLV.mjs";
4
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-Cn1oRaLw.mjs";
5
5
  import { ChatType, EssenceListSync, GrayTipSubType, GroupApi, GroupNotifyMsgStatus, GroupNotifyMsgType, NTGroupMemberRole, NTGroupRequestOperateTypes, TicketApi, TipGroupElementType, WebHonorType, errorMessage, hasStringProp, isRecord, kernelError, narrowEssenceGroupArg, toCanonicalElements } from "@napuketto/kernel";
6
6
  import { HttpClient, HttpServer, WsClient, WsServer } from "@napuketto/network";
7
7
  import { z } from "zod";
8
- import { existsSync } from "node:fs";
9
- import { join } from "node:path";
8
+ import { basename } from "node:path";
10
9
  import { inferExtension } from "@napuketto/media";
11
10
  // src/onebot11/helper/message-unique.ts
12
11
  /** OB11 message_id 上限(int32 max = 0x7FFF_FFFF)。 */
@@ -2118,17 +2117,8 @@ function createHistoryActions(api) {
2118
2117
  /**
2119
2118
  * 消息媒体域动作
2120
2119
  *
2121
- * - get_image / get_record:获取图片/语音文件(图片接主动下载;语音接原生
2122
- * downloadRichMedia)。message_id 反查 → fetchMsgsByMsgId → 找 PIC/PTT 元素:
2123
- * - 本地文件解析:NT 相对路径(sourcePath/filePath)按 mediaBaseDir(QQ NT
2124
- * global 目录)解析为绝对路径,命中磁盘即返回 file
2125
- * - 图片主动下载:本地未命中且有 picUrl → 按媒体出站策略下载落
2126
- * cacheDir/media/,返回 file(绝对路径)+ url + file_size/file_name
2127
- * - 语音主动下载:本地未命中 → kernel MsgApi.downloadPtt(原生
2128
- * downloadRichMedia + 轮询元素回查)→ filePath 落盘后返回绝对路径;
2129
- * 失败回退原始 filePath(NT 相对/绝对)+ 元数据,不抛错
2130
- * - fetch_ptt_text:message_id → MsgApi.fetchPttText(内部:拉消息 → 找 PTT 元素
2131
- * → translatePtt2Text → 再拉取读 pttElement.text)
2120
+ * - get_image/get_record:经当前账号的消息 API 取资源,并导出到带租约的缓存。
2121
+ * - fetch_ptt_text:经内核拉取语音转文字。
2132
2122
  */
2133
2123
  const getMediaSchema = z.object({
2134
2124
  /** CQ 码 file 字段或 message_id(简化:message_id 反查)。 */
@@ -2136,20 +2126,6 @@ const getMediaSchema = z.object({
2136
2126
  message_id: z.union([z.number(), z.string()]).optional()
2137
2127
  });
2138
2128
  const fetchPttTextSchema = z.object({ message_id: z.union([z.number(), z.string()]) });
2139
- /**
2140
- * NT 相对路径 → 本地绝对路径(存在才返回)。
2141
- * 候选:原样绝对路径 / mediaBaseDir 下相对路径(反斜杠归一化)。
2142
- */
2143
- function resolveLocalMediaFile(relPath, deps) {
2144
- if (relPath === "") return null;
2145
- if (existsSync(relPath)) return relPath;
2146
- const base = deps.mediaBaseDir;
2147
- if (base !== void 0 && base !== "") {
2148
- const joined = join(base, relPath.replaceAll("\\", "/"));
2149
- if (existsSync(joined)) return joined;
2150
- }
2151
- return null;
2152
- }
2153
2129
  /** 图片主动下载(picUrl → cacheDir/media/<uuid>.<ext>;无 cacheDir/url 返回 null)。 */
2154
2130
  async function downloadImageToCache(url, deps) {
2155
2131
  const cacheDir = deps.cacheDir;
@@ -2172,7 +2148,7 @@ async function resolveMedia(id, label, deps, extract) {
2172
2148
  const [first] = await deps.msgApi.fetchMsgsByMsgId(peer, [msgId]);
2173
2149
  if (first === void 0) throw kernelError(`消息 ${id} 不存在或已被撤回`, "NOT_FOUND");
2174
2150
  for (const el of first.elements) {
2175
- const found = extract(el);
2151
+ const found = await extract(el);
2176
2152
  if (found !== void 0) return found;
2177
2153
  }
2178
2154
  throw kernelError(`消息 ${id} 不包含${label}`, "NOT_FOUND");
@@ -2184,17 +2160,17 @@ function takeId(payload, actionName) {
2184
2160
  return id;
2185
2161
  }
2186
2162
  /** 提取 pic 元素 → 媒体信息(url / 本地 file / 元数据;非 pic 元素返回 undefined)。 */
2187
- function extractPicElement(el, deps) {
2163
+ async function extractPicElement(el, deps) {
2188
2164
  const pic = el.picElement;
2189
2165
  if (pic == null) return;
2190
2166
  const out = {};
2191
2167
  if (pic.fileSize != null) out.file_size = pic.fileSize;
2192
2168
  if (pic.fileName != null) out.file_name = pic.fileName;
2193
2169
  if (pic.picUrl != null) out.url = pic.picUrl;
2194
- const rel = pic.sourcePath ?? pic.picPath;
2170
+ const rel = pic.sourcePath || pic.picPath;
2195
2171
  if (rel != null) {
2196
- const local = resolveLocalMediaFile(rel, deps);
2197
- if (local !== null) out.file = local;
2172
+ const local = await exportQqMedia(rel, deps.mediaBaseDir, deps.cacheDir);
2173
+ if (local !== void 0) out.file = local;
2198
2174
  }
2199
2175
  return out;
2200
2176
  }
@@ -2204,8 +2180,8 @@ async function downloadPttFallback(msgId, peer, id, deps) {
2204
2180
  const downloaded = await deps.msgApi.downloadPtt(msgId, peer);
2205
2181
  const rel = downloaded.filePath;
2206
2182
  if (rel != null && rel !== "") {
2207
- const localAfter = resolveLocalMediaFile(rel, deps);
2208
- if (localAfter !== null) return {
2183
+ const localAfter = await exportQqMedia(rel, deps.mediaBaseDir, deps.cacheDir);
2184
+ if (localAfter !== void 0) return {
2209
2185
  ...downloaded.fileSize != null ? { file_size: downloaded.fileSize } : {},
2210
2186
  ...downloaded.fileName != null ? { file_name: downloaded.fileName } : {},
2211
2187
  file: localAfter
@@ -2215,7 +2191,7 @@ async function downloadPttFallback(msgId, peer, id, deps) {
2215
2191
  deps.logger?.warn({
2216
2192
  message_id: id,
2217
2193
  error: errorMessage(err)
2218
- }, "ob11: 语音原生下载失败,get_record 回退原始路径");
2194
+ }, "ob11: 语音原生下载失败,get_record 回退元数据");
2219
2195
  }
2220
2196
  return null;
2221
2197
  }
@@ -2249,15 +2225,12 @@ function createMediaActions(api) {
2249
2225
  ...ptt.fileSize != null ? { file_size: ptt.fileSize } : {},
2250
2226
  ...ptt.fileName != null ? { file_name: ptt.fileName } : {}
2251
2227
  });
2252
- const local = resolveLocalMediaFile(filePath, api);
2253
- if (local !== null) return {
2228
+ const local = await exportQqMedia(filePath, api.mediaBaseDir, api.cacheDir);
2229
+ if (local !== void 0) return {
2254
2230
  ...meta(),
2255
2231
  file: local
2256
2232
  };
2257
- return await downloadPttFallback(msgId, peer, id, api) ?? {
2258
- ...meta(),
2259
- file: filePath
2260
- };
2233
+ return await downloadPttFallback(msgId, peer, id, api) ?? meta();
2261
2234
  }
2262
2235
  }),
2263
2236
  defineOb11Action({
@@ -2418,7 +2391,7 @@ async function sendOb11Message(payload, deps) {
2418
2391
  let canonical;
2419
2392
  if (Array.isArray(payload.message)) canonical = segmentsToCanonical(parseOB11MessageSegments(payload.message));
2420
2393
  else canonical = cqMessageToCanonical(payload.message);
2421
- await protectElements(canonical);
2394
+ canonical = await prepareLocalElements(canonical, deps);
2422
2395
  const atUins = [];
2423
2396
  for (const el of canonical) if (el.type === "at" && el.target !== "all") atUins.push(el.target);
2424
2397
  let uinToUid;
@@ -2450,11 +2423,26 @@ async function sendOb11Message(payload, deps) {
2450
2423
  await prepared.cleanup();
2451
2424
  }
2452
2425
  }
2453
- async function protectElements(elements) {
2426
+ async function prepareLocalElements(elements, deps) {
2427
+ const roots = deps.getLocalMediaRoots?.();
2428
+ const prepared = [];
2454
2429
  for (const el of elements) {
2455
- if ("path" in el) await protectMediaPath(el.path);
2456
- if (el.type === "video" && el.thumbPath) await protectMediaPath(el.thumbPath);
2430
+ if (!("path" in el)) {
2431
+ prepared.push(el);
2432
+ continue;
2433
+ }
2434
+ const path = await resolveLocalMedia(el.path, roots);
2435
+ if (el.type === "video" && el.thumbPath) prepared.push({
2436
+ ...el,
2437
+ path,
2438
+ thumbPath: await resolveLocalMedia(el.thumbPath, roots)
2439
+ });
2440
+ else prepared.push({
2441
+ ...el,
2442
+ path
2443
+ });
2457
2444
  }
2445
+ return prepared;
2458
2446
  }
2459
2447
  /** CQ 特殊字符转义(auto_escape,&、[、]、, 前置 &amp;)。 */
2460
2448
  function escapeText(text) {
@@ -2606,10 +2594,8 @@ function createSystemAccountActions(api) {
2606
2594
  name: "set_qq_avatar",
2607
2595
  schema: setQQAvatarSchema,
2608
2596
  handle: async (payload) => {
2609
- let filePath = payload.file;
2610
- if (URL_PREFIX.test(filePath)) filePath = await downloadAvatarToCache(filePath, api);
2611
- if (!existsSync(filePath)) throw kernelError(`头像文件不存在: ${filePath}`, "NOT_FOUND");
2612
- await api.profileApi.setHeader(await protectMediaPath(filePath));
2597
+ const filePath = URL_PREFIX.test(payload.file) ? await downloadAvatarToCache(payload.file, api) : await resolveLocalMedia(payload.file, api.getLocalMediaRoots?.());
2598
+ await api.profileApi.setHeader(filePath);
2613
2599
  return null;
2614
2600
  }
2615
2601
  })
@@ -2635,8 +2621,6 @@ function createSystemAccountActions(api) {
2635
2621
  * 输入只接受本地路径与 `file://` URI:远程 `http(s)://` / `base64://` 需要下载缓存与媒体
2636
2622
  * 依赖,当前未接(明确报错,不静默失败)。
2637
2623
  */
2638
- /** 路径分隔符(取文件名用)。 */
2639
- const PATH_SEPARATORS = /[\\/]/;
2640
2624
  const downloadFileSchema = z.object({
2641
2625
  url: z.string(),
2642
2626
  thread_count: z.number().optional(),
@@ -2654,18 +2638,6 @@ const uploadPrivateFileSchema = z.object({
2654
2638
  file: z.string().min(1),
2655
2639
  name: z.string().optional()
2656
2640
  });
2657
- /** 本地路径 / file:// 展开;远程 URI 明确拒绝(未接下载缓存)。 */
2658
- function resolveLocalFile(file) {
2659
- if (file.startsWith("http://") || file.startsWith("https://") || file.startsWith("base64://")) throw kernelError("upload_group_file/upload_private_file 目前只支持本地路径与 file:// URI(远程 URI 需要下载缓存,未接入)", "INVALID_PARAM");
2660
- if (file.startsWith("file://")) return fileUriToPath(file);
2661
- return file;
2662
- }
2663
- /** 取路径末段作为缺省文件集名(卡片标题)。 */
2664
- function basename$1(path) {
2665
- const parts = path.split(PATH_SEPARATORS);
2666
- const last = parts[parts.length - 1] ?? "";
2667
- return last === "" ? "文件" : last;
2668
- }
2669
2641
  /** 文件收发域动作工厂(download_file / upload_group_file / upload_private_file)。 */
2670
2642
  function createSystemFileActions(api) {
2671
2643
  return [
@@ -2687,21 +2659,21 @@ function createSystemFileActions(api) {
2687
2659
  name: "upload_group_file",
2688
2660
  schema: uploadGroupFileSchema,
2689
2661
  handle: async (payload) => {
2690
- const path = await protectMediaPath(resolveLocalFile(payload.file));
2662
+ const path = await resolveLocalMedia(payload.file, api.getLocalMediaRoots?.());
2691
2663
  const peer = {
2692
2664
  chatType: ChatType.GROUP,
2693
2665
  peerUid: String(payload.group_id)
2694
2666
  };
2695
- return { file_id: (await api.flashTransferApi.sendFile(peer, [path], { name: payload.name ?? basename$1(path) })).fileSetId };
2667
+ return { file_id: (await api.flashTransferApi.sendFile(peer, [path], { name: payload.name ?? basename(path) })).fileSetId };
2696
2668
  }
2697
2669
  }),
2698
2670
  defineOb11Action({
2699
2671
  name: "upload_private_file",
2700
2672
  schema: uploadPrivateFileSchema,
2701
2673
  handle: async (payload) => {
2702
- const path = await protectMediaPath(resolveLocalFile(payload.file));
2674
+ const path = await resolveLocalMedia(payload.file, api.getLocalMediaRoots?.());
2703
2675
  const peer = await resolveTargetPeer({ user_id: payload.user_id }, api, "upload_private_file 需要 user_id");
2704
- return { file_id: (await api.flashTransferApi.sendFile(peer, [path], { name: payload.name ?? basename$1(path) })).fileSetId };
2676
+ return { file_id: (await api.flashTransferApi.sendFile(peer, [path], { name: payload.name ?? basename(path) })).fileSetId };
2705
2677
  }
2706
2678
  })
2707
2679
  ];
@@ -2994,6 +2966,7 @@ function openOutboundWithRetry(transport, opts) {
2994
2966
  */
2995
2967
  var OneBotApi = class {
2996
2968
  mediaCache;
2969
+ getLocalMediaRoots;
2997
2970
  getMediaOutboundPolicy;
2998
2971
  /** kernel 消息 API(send_msg 等消息类动作用)。 */
2999
2972
  msgApi;
@@ -3037,11 +3010,16 @@ var OneBotApi = class {
3037
3010
  restart;
3038
3011
  /** 降级分支可观测出口(缺省静默)。 */
3039
3012
  logger;
3040
- constructor(opts, getMediaOutboundPolicy) {
3013
+ constructor(opts, getMediaOutboundPolicy, getLocalMediaRoots) {
3041
3014
  this.getMediaOutboundPolicy = getMediaOutboundPolicy;
3015
+ this.getLocalMediaRoots = bindLocalMediaRoots(opts.localMediaBaseDir, getLocalMediaRoots);
3042
3016
  this.mediaCache = new MediaCache({
3043
3017
  root: opts.system?.cacheDir,
3044
- logger: opts.logger
3018
+ logger: opts.logger,
3019
+ owner: {
3020
+ protocol: "onebot11",
3021
+ account: opts.self.uin
3022
+ }
3045
3023
  });
3046
3024
  this.msgApi = opts.msgApi;
3047
3025
  this.groupApi = opts.groupApi;
@@ -3886,7 +3864,7 @@ var NapukettoOneBot11Adapter = class extends BaseProtocolAdapter {
3886
3864
  });
3887
3865
  this.selfUin = opts.self.uin;
3888
3866
  this.logger = opts.logger;
3889
- this.oneBotApi = new OneBotApi(opts, () => config.get?.()?.media?.outboundPolicy);
3867
+ this.oneBotApi = new OneBotApi(opts, () => config.get?.()?.media?.outboundPolicy, () => config.get?.()?.media?.localMediaRoots);
3890
3868
  this.pipeline = new Ob11EventPipeline({
3891
3869
  selfUin: this.selfUin,
3892
3870
  api: this.oneBotApi,
@@ -2,5 +2,5 @@
2
2
  * Satori 协议适配器
3
3
  * 公共面:类型 + 动作注册表 + 配置 schema + 传输装配 + 适配器。
4
4
  */
5
- import { A as Message, B as SatoriActionDeps, C as Emoji, D as GuildRole, E as GuildMember, F as Order, G as SatoriToCanonicalDeps, H as SatoriActionError, I as HTTP_STATUS, J as renderElements, K as SatoriElement, L as satoriHttpStatusMap, M as BidiList, N as Direction, O as Login, P as List, R as SatoriConfig, S as ChannelType, T as Guild, U as SatoriApi, V as createSatoriActionRegistry, W as SatoriApiOptions, _ as MetaBody, a as parseContentToCanonical, b as Signal, c as canonicalToSatoriElements, d as NapukettoSatoriAdapter, f as SatoriAdapterOptions, g as IdentifyBody, h as Event, i as toEventSignal, j as User, k as LoginStatus, l as SatoriEventContent, m as Button, n as SatoriTransportSet, o as satoriToCanonicalElements, p as Argv, q as parseElements, r as assembleSatoriTransports, s as CanonicalToSatoriDeps, t as AssembleSatoriTransportsOptions, u as SatoriEventDeps, v as Opcode, w as Friend, x as Channel, y as ReadyBody, z as satoriConfigSchema } from "../index-CX7UKc6W.mjs";
5
+ import { A as Message, B as SatoriActionDeps, C as Emoji, D as GuildRole, E as GuildMember, F as Order, G as SatoriToCanonicalDeps, H as SatoriActionError, I as HTTP_STATUS, J as renderElements, K as SatoriElement, L as satoriHttpStatusMap, M as BidiList, N as Direction, O as Login, P as List, R as SatoriConfig, S as ChannelType, T as Guild, U as SatoriApi, V as createSatoriActionRegistry, W as SatoriApiOptions, _ as MetaBody, a as parseContentToCanonical, b as Signal, c as canonicalToSatoriElements, d as NapukettoSatoriAdapter, f as SatoriAdapterOptions, g as IdentifyBody, h as Event, i as toEventSignal, j as User, k as LoginStatus, l as SatoriEventContent, m as Button, n as SatoriTransportSet, o as satoriToCanonicalElements, p as Argv, q as parseElements, r as assembleSatoriTransports, s as CanonicalToSatoriDeps, t as AssembleSatoriTransportsOptions, u as SatoriEventDeps, v as Opcode, w as Friend, x as Channel, y as ReadyBody, z as satoriConfigSchema } from "../index-DAoLsewN.mjs";
6
6
  export { type Argv, type AssembleSatoriTransportsOptions, type BidiList, type Button, type CanonicalToSatoriDeps, type Channel, type ChannelType, type Direction, type Emoji, type Event, type Friend, type Guild, type GuildMember, type GuildRole, HTTP_STATUS, type IdentifyBody, type List, type Login, type LoginStatus, type Message, type MetaBody, NapukettoSatoriAdapter, type Opcode, type Order, type ReadyBody, type SatoriActionDeps, SatoriActionError, type SatoriAdapterOptions, SatoriApi, type SatoriApiOptions, type SatoriConfig, type SatoriElement, type SatoriEventContent, type SatoriEventDeps, type SatoriToCanonicalDeps, type SatoriTransportSet, type Signal, type User, assembleSatoriTransports, canonicalToSatoriElements, createSatoriActionRegistry, parseContentToCanonical, parseElements, renderElements, satoriConfigSchema, satoriHttpStatusMap, satoriToCanonicalElements, toEventSignal };
@@ -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-Cetkw86t.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-Cna8fauQ.mjs";
@@ -1,12 +1,12 @@
1
1
  import { a as validateServerTokens, d as tokenEquals, f as ActionRegistry, l as createTokenAuthorize, o as BaseProtocolAdapter, p as runAction, r as createServerSchema, s as resolveProtocolConfig } from "./framework-CA3087JP.mjs";
2
- import { _ as withMediaScope, a as logEventFailure, c as protocolMediaSchema, g as protectMediaPath, h as cacheMediaFile, l as downloadProtocolMedia, m as MediaCache, t as collectGrayTipUids, u as ensureSilk } from "./gray-tip-BtiJls6z.mjs";
2
+ import { _ as cacheMediaFile, a as logEventFailure, c as protocolMediaSchema, g as MediaCache, h as resolveLocalMedia, l as downloadProtocolMedia, m as exportQqMedia, p as bindLocalMediaRoots, t as collectGrayTipUids, u as ensureSilk, v as leaseInternalMedia, y as withMediaScope } from "./gray-tip-D0SfHr7q.mjs";
3
3
  import { c as MS_TO_SEC, h as toUinString, i as toUnixSeconds, r as subscribeRawMessages } from "./raw-message-DU8YOhLV.mjs";
4
- import { ChatType, GrayTipSubType, NTGroupRequestOperateTypes, TipGroupElementType, isRecord, kernelError, toCanonicalElements } from "@napuketto/kernel";
4
+ import { ChatType, GrayTipSubType, NTGroupRequestOperateTypes, TipGroupElementType, errorMessage, isRecord, kernelError, toCanonicalElements } from "@napuketto/kernel";
5
5
  import { HttpServer, WsServer, isWsOpen, sendWsText } from "@napuketto/network";
6
6
  import { z } from "zod";
7
7
  import { rm, rmdir } from "node:fs/promises";
8
8
  import { tmpdir } from "node:os";
9
- import { dirname, join } from "node:path";
9
+ import { basename, dirname, join } from "node:path";
10
10
  import { inferExtension, transcodeVideo } from "@napuketto/media";
11
11
  // src/satori/helper/config.ts
12
12
  /**
@@ -561,11 +561,22 @@ function renderElement(el) {
561
561
  * 收方向 ID 空间:canonical at.target 是 uid,Satori 规范是 uin——经
562
562
  * uidToUin 批量转换(依赖注入,与 OB11 的 ReceiveTranslateContext 同思路)。
563
563
  */
564
- /** RawMessage → Satori Message(资源提升:message 不嵌套 user/member/channel)。 */
565
- async function toSatoriMessage(raw, deps) {
564
+ async function renderMessageContent(raw, deps) {
566
565
  const elementDeps = {};
567
566
  if (deps.uidToUin !== void 0) elementDeps.uidToUin = deps.uidToUin;
568
- const content = renderElements(await canonicalToSatoriElements(toCanonicalElements(raw), elementDeps));
567
+ const elements = await canonicalToSatoriElements(toCanonicalElements(raw), elementDeps);
568
+ if (deps.publishLocalAsset !== void 0) for (const element of elements) {
569
+ const attrs = element.attrs;
570
+ const source = attrs?.["src"];
571
+ if (!attrs || !source) continue;
572
+ const reference = await deps.publishLocalAsset(source);
573
+ if (reference !== void 0) attrs["src"] = reference;
574
+ }
575
+ return renderElements(elements);
576
+ }
577
+ /** RawMessage → Satori Message(资源提升:message 不嵌套 user/member/channel)。 */
578
+ async function toSatoriMessage(raw, deps) {
579
+ const content = await renderMessageContent(raw, deps);
569
580
  const isGroup = raw.chatType === ChatType.GROUP;
570
581
  const peerUin = String(raw.peerUin ?? "");
571
582
  const senderUin = String(raw.senderUin ?? "");
@@ -852,22 +863,6 @@ function createLoginActions(deps) {
852
863
  })];
853
864
  }
854
865
  // src/satori/helper/element/asset.ts
855
- /**
856
- * Satori 发方向资源处理(从 element-convert.ts 拆分,FTA 优化)
857
- *
858
- * - resolveAsset:internal: 路径 / http(s) 下载 / 本地路径原样
859
- * - HTTP(S) 下载遵循当前协议配置的媒体出站策略。
860
- */
861
- /** internal:{platform}/{user.id}/{path} → 本地路径(取 _tmp 之后的路径,回落 cacheDir)。 */
862
- function resolveInternalPath(src) {
863
- const pathPart = src.slice(9);
864
- const slash1 = pathPart.indexOf("/");
865
- const slash2 = slash1 === -1 ? -1 : pathPart.indexOf("/", slash1 + 1);
866
- if (slash2 === -1) return pathPart;
867
- const rest = pathPart.slice(slash2 + 1);
868
- const tmpIdx = rest.indexOf("_tmp/");
869
- return tmpIdx === -1 ? rest : rest.slice(tmpIdx + 5);
870
- }
871
866
  /** http(s) URL 前缀。 */
872
867
  const HTTP_URL_RE = /^https?:\/\//i;
873
868
  const UNSAFE_NAME_RE = /[^a-zA-Z0-9._-]/g;
@@ -877,28 +872,26 @@ function assetFileName(src) {
877
872
  const name = (src.split("/").pop() ?? "").replace(UNSAFE_NAME_RE, "_");
878
873
  return name === "" || name === "." || name === ".." ? void 0 : name;
879
874
  }
880
- /**
881
- * 解析资源 src:
882
- * - internal:{platform}/{user.id}/{path} → 本地路径(第一版仅支持 _tmp 保留路径)
883
- * - http(s):// → 下载到 cacheDir
884
- * - 其他 → 视为本地路径原样返回
885
- */
886
- async function resolveAsset(src, cacheDir, outboundPolicy) {
887
- if (src.startsWith("internal:")) return await protectMediaPath(resolveInternalPath(src));
875
+ async function resolveAsset(src, cacheDir, opts = {}) {
876
+ if (src.startsWith("internal:")) {
877
+ const [platform, account, namespace, entry, file, extra] = src.slice(9).split("/");
878
+ if (platform !== "qq" || account === void 0 || account !== opts.account || namespace !== "_tmp" || entry === void 0 || file === void 0 || extra !== void 0) throw kernelError("内部媒体引用不属于当前平台及账号", "INVALID_PARAM");
879
+ return await leaseInternalMedia(cacheDir, account, entry, file);
880
+ }
888
881
  if (HTTP_URL_RE.test(src)) return await cacheMediaFile(cacheDir, inferExtension(null, src), async (path) => {
889
882
  await downloadProtocolMedia(src, path, {
890
- outboundPolicy,
883
+ outboundPolicy: opts.outboundPolicy,
891
884
  errorLabel: "下载资源失败"
892
885
  });
893
886
  });
894
- return await protectMediaPath(src);
887
+ return await resolveLocalMedia(src, opts.localMediaRoots);
895
888
  }
896
889
  // src/satori/helper/element/media-convert.ts
897
890
  /** 解析元素媒体 src(空 → null 忽略),返回本地路径。 */
898
891
  async function resolveMediaSrc(el, deps) {
899
892
  const src = el.attrs?.["src"] ?? "";
900
893
  if (src === "") return null;
901
- return resolveAsset(src, deps.cacheDir, deps.outboundPolicy);
894
+ return resolveAsset(src, deps.cacheDir, deps);
902
895
  }
903
896
  /** Satori img → canonical image。 */
904
897
  async function imgToCanonical(el, deps) {
@@ -1128,7 +1121,8 @@ function createMessageActions(deps) {
1128
1121
  deps.setChannelType(channelId, peer.chatType === 2);
1129
1122
  return toSatoriMessage(first, {
1130
1123
  selfUin: deps.selfUin,
1131
- uidToUin: (uids) => deps.uidToUin(uids)
1124
+ uidToUin: (uids) => deps.uidToUin(uids),
1125
+ publishLocalAsset: deps.publishLocalAsset
1132
1126
  });
1133
1127
  }
1134
1128
  }),
@@ -1322,6 +1316,7 @@ const notImplementedSchema = z.object({}).passthrough();
1322
1316
  /** Satori 动作统一依赖聚合。 */
1323
1317
  var SatoriApi = class {
1324
1318
  mediaCache;
1319
+ getLocalMediaRoots;
1325
1320
  msgApi;
1326
1321
  groupApi;
1327
1322
  groupNotifyApi;
@@ -1330,6 +1325,7 @@ var SatoriApi = class {
1330
1325
  self;
1331
1326
  selfUin;
1332
1327
  cacheDir;
1328
+ publishLocalAsset;
1333
1329
  groupCache;
1334
1330
  /**
1335
1331
  * 频道类型缓存:channel_id → isGroup(群聊频道 id 与私聊 uin 无法从数字
@@ -1337,8 +1333,9 @@ var SatoriApi = class {
1337
1333
  */
1338
1334
  channelTypeCache = /* @__PURE__ */ new Map();
1339
1335
  getMediaOutboundPolicy;
1340
- constructor(opts, getMediaOutboundPolicy) {
1336
+ constructor(opts, getMediaOutboundPolicy, getLocalMediaRoots) {
1341
1337
  this.getMediaOutboundPolicy = getMediaOutboundPolicy;
1338
+ this.getLocalMediaRoots = bindLocalMediaRoots(opts.localMediaBaseDir, getLocalMediaRoots);
1342
1339
  this.msgApi = opts.msgApi;
1343
1340
  this.groupApi = opts.groupApi;
1344
1341
  this.groupNotifyApi = opts.groupNotifyApi;
@@ -1349,8 +1346,23 @@ var SatoriApi = class {
1349
1346
  this.cacheDir = opts.cacheDir ?? join(tmpdir(), "napuketto-satori-cache");
1350
1347
  this.mediaCache = new MediaCache({
1351
1348
  root: this.cacheDir,
1352
- logger: opts.logger
1349
+ logger: opts.logger,
1350
+ owner: {
1351
+ protocol: "satori",
1352
+ account: opts.self.uin
1353
+ }
1353
1354
  });
1355
+ const mediaBaseDir = opts.mediaBaseDir;
1356
+ if (mediaBaseDir !== void 0) this.publishLocalAsset = async (source) => {
1357
+ try {
1358
+ const file = await exportQqMedia(source, mediaBaseDir, this.cacheDir);
1359
+ if (file === void 0) return void 0;
1360
+ return `internal:qq/${this.selfUin}/_tmp/${basename(dirname(file))}/${basename(file)}`;
1361
+ } catch (err) {
1362
+ opts.logger?.warn({ error: errorMessage(err) }, "satori: 媒体导出失败");
1363
+ return;
1364
+ }
1365
+ };
1354
1366
  this.groupCache = opts.groupCache;
1355
1367
  }
1356
1368
  /** 记录频道类型(消息事件翻译时回填:chatType GROUP → true)。 */
@@ -1398,7 +1410,9 @@ var SatoriApi = class {
1398
1410
  return {
1399
1411
  uinToUid: (uins) => this.groupApi.uinToUid(uins),
1400
1412
  cacheDir: this.cacheDir,
1401
- outboundPolicy: this.getMediaOutboundPolicy?.()
1413
+ outboundPolicy: this.getMediaOutboundPolicy?.(),
1414
+ localMediaRoots: this.getLocalMediaRoots?.(),
1415
+ account: this.selfUin
1402
1416
  };
1403
1417
  }
1404
1418
  };
@@ -1775,18 +1789,19 @@ var NapukettoSatoriAdapter = class extends BaseProtocolAdapter {
1775
1789
  unsubscribe = null;
1776
1790
  eventSn = 0;
1777
1791
  constructor(opts) {
1792
+ const { broadcaster, msgChannel } = opts;
1778
1793
  const config = resolveProtocolConfig(opts.config, satoriConfigSchema, satoriConfigSchema.parse({}));
1779
1794
  super({
1780
1795
  config,
1781
- broadcaster: opts.broadcaster,
1796
+ broadcaster,
1782
1797
  hooks: {
1783
1798
  onStart: (config) => this.startTransports(config),
1784
1799
  onStop: () => this.stopAll(),
1785
1800
  onReload: (config) => this.reloadTransports(config)
1786
1801
  }
1787
1802
  });
1788
- this.msgChannel = opts.msgChannel;
1789
- this.api = new SatoriApi(opts, () => config.get?.()?.media?.outboundPolicy);
1803
+ this.msgChannel = msgChannel;
1804
+ this.api = new SatoriApi(opts, () => config.get?.()?.media?.outboundPolicy, () => config.get?.()?.media?.localMediaRoots);
1790
1805
  this.logger = opts.logger;
1791
1806
  this.registry = createSatoriActionRegistry({ api: this.api });
1792
1807
  }
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.20.0",
4
+ "version": "0.21.1",
5
5
  "type": "module",
6
6
  "description": "Protocol adapters (OneBot11 / Satori / KuroBot / Milky) for NapukettoQQ",
7
7
  "keywords": [
@@ -83,7 +83,7 @@
83
83
  "dev": "tsdown --watch"
84
84
  },
85
85
  "dependencies": {
86
- "@napuketto/kernel": "^0.16.4",
86
+ "@napuketto/kernel": "^0.17.0",
87
87
  "@napuketto/media": "^0.3.0",
88
88
  "@napuketto/network": "^0.5.0",
89
89
  "zod": "^4.6.7"