@napuketto/adapter 0.22.0 → 0.23.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.
@@ -6,7 +6,7 @@ import { AsyncLocalStorage } from "node:async_hooks";
6
6
  import { copyFile, lstat, mkdir, mkdtemp, open, readFile, readdir, readlink, realpath, rename, rm, rmdir, stat, unlink, writeFile } from "node:fs/promises";
7
7
  import { tmpdir } from "node:os";
8
8
  import { basename, dirname, extname, isAbsolute, join, resolve, sep } from "node:path";
9
- import { downloadPublicUrl, downloadUrl, encodePcmToSilk, extractVideoFrame, getVideoInfo } from "@napuketto/media";
9
+ import { MAX_AUDIO_INPUT_BYTES, downloadPublicUrl, downloadUrl, encodePcmToSilk, extractVideoFrame, getVideoInfo } from "@napuketto/media";
10
10
  import { pipeline } from "node:stream/promises";
11
11
  import { fileURLToPath } from "node:url";
12
12
  // src/internal/infra/media-cache.ts
@@ -725,7 +725,6 @@ async function exportQqMedia(source, qqRoot, cacheDir) {
725
725
  * 只接收「文件齐全」的 canonical 元素。
726
726
  */
727
727
  const MEDIA_EXTENSION_RE = /^\.[a-zA-Z0-9]+$/;
728
- const MAX_AUDIO_COPY_BYTES = 33554432;
729
728
  /** 协议动作默认走公网下载,兼容模式由受信任的装配方显式启用。 */
730
729
  function mediaDownloader(policy) {
731
730
  return policy === "compat" ? downloadUrl : downloadPublicUrl;
@@ -757,7 +756,7 @@ async function readFileHead(path) {
757
756
  async function ensureSilk(path, logger) {
758
757
  try {
759
758
  const info = await stat(path);
760
- if (!info.isFile() || info.size > MAX_AUDIO_COPY_BYTES) throw kernelError("语音复制输入必须是 32MiB 以内的普通文件", "INVALID_PARAM");
759
+ if (!info.isFile() || info.size > MAX_AUDIO_INPUT_BYTES) throw kernelError("语音复制输入必须是 32MiB 以内的普通文件", "INVALID_PARAM");
761
760
  if ((await readFileHead(path)).startsWith("#!SILK")) return path;
762
761
  const ext = extname(path);
763
762
  return await cacheMediaFile(MEDIA_TEMP_ROOT, MEDIA_EXTENSION_RE.test(ext) ? ext : ".bin", async (copy) => {
package/dist/index.d.mts CHANGED
@@ -8,7 +8,7 @@
8
8
  * 重要(路径契约,勿删):
9
9
  * 1. `package.json` 的 `"."` 子路径需要真实文件存在,`import.meta.resolve()` /
10
10
  * `createRequire().resolve()` 才解析得到本包(外部消费方据此定位 dist);
11
- * 2. cli 把解析结果注入 `NAPUTO_ADAPTER_ENTRY`,loader 再按 `index.mjs` →
11
+ * 2. cli 把解析结果注入 `NAPUKETTO_ADAPTER_ENTRY`,loader 再按 `index.mjs` →
12
12
  * `core|onebot11|satori|kurobot|milky/index.mjs` 字符串替换推出各协议入口
13
13
  * (见 loader `assemble-protocols.ts` / `ipc-ob11.ts` 的 `INDEX_MJS_RE`)。
14
14
  *
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-BrKT5cJA.mjs";
3
- import { r as milkyConfigSchema, t as NapukettoMilkyAdapter } from "./milky-CI0qDQpV.mjs";
4
- import { t as NapukettoOneBot11Adapter, u as ob11ConfigSchema } from "./onebot11-CaSEVtLy.mjs";
5
- import { m as satoriConfigSchema, t as NapukettoSatoriAdapter } from "./satori-B-vWj1fa.mjs";
3
+ import { r as milkyConfigSchema, t as NapukettoMilkyAdapter } from "./milky-6O1JM1A9.mjs";
4
+ import { t as NapukettoOneBot11Adapter, u as ob11ConfigSchema } from "./onebot11-CgylJN92.mjs";
5
+ import { m as satoriConfigSchema, t as NapukettoSatoriAdapter } from "./satori-DdcfE1nh.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-CI0qDQpV.mjs";
1
+ export { a as MilkyApi, t as NapukettoMilkyAdapter, n as assembleMilkyTransports, i as createMilkyActionRegistry, r as milkyConfigSchema, o as milkyErrorCodeMap } from "../milky-6O1JM1A9.mjs";
@@ -1,11 +1,11 @@
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
- import { _ as cacheMediaFile, a as logEventFailure, c as protocolMediaSchema, d as mediaDownloader, g as MediaCache, h as resolveLocalMedia, i as hasGrayTip, n as findRevokeElement, o as sliceRaw, p as bindLocalMediaRoots, r as firstUntranslatedGrayTip, t as collectGrayTipUids, y as withMediaScope } from "./gray-tip-D0SfHr7q.mjs";
2
+ import { _ as cacheMediaFile, a as logEventFailure, c as protocolMediaSchema, d as mediaDownloader, g as MediaCache, h as resolveLocalMedia, i as hasGrayTip, n as findRevokeElement, o as sliceRaw, p as bindLocalMediaRoots, r as firstUntranslatedGrayTip, t as collectGrayTipUids, y as withMediaScope } from "./gray-tip-CiZ6OxlQ.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-B0kwCfKE.mjs";
4
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-ChxJJipr.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";
8
- import { rename, writeFile } from "node:fs/promises";
8
+ import { open, rename } from "node:fs/promises";
9
9
  import { detectFileType, inferExtension } from "@napuketto/media";
10
10
  // src/milky/action/base-action.ts
11
11
  /** KernelErrorCode → Milky retcode 映射表(-400/-403 规范语义,其余取常见 HTTP 语义近似负数)。 */
@@ -328,42 +328,67 @@ function essenceToEntity(item, groupId) {
328
328
  */
329
329
  const HTTP_URL_RE = /^https?:\/\//i;
330
330
  const DETECTED_EXTENSION_RE = /^[a-zA-Z0-9]+$/;
331
+ const BASE64_SCHEME = "base64://";
332
+ const MAX_DATA_BYTES = 31457280;
333
+ const MAX_BASE64_CHARS = Math.ceil(MAX_DATA_BYTES / 3) * 4;
334
+ const BASE64_CHUNK_CHARS = 65536;
335
+ const INVALID_BASE64_CHAR = /[^a-zA-Z0-9+/_-]/;
331
336
  /** 解析远程媒体 URI 为本地绝对路径(base64:// / http(s)://;file:// 走同步面)。 */
332
- async function resolveMediaUri(uri, mediaDir, outboundPolicy) {
337
+ async function resolveMediaUri(uri, mediaDir, outboundPolicy, signal) {
333
338
  if (mediaDir === void 0 || mediaDir === "") throw kernelError("远程媒体发送需要配置 [accounts.milky] cacheDir(下载缓存目录)", "INVALID_PARAM");
334
- if (uri.startsWith("base64://")) return await writeBase64(uri.slice(9), mediaDir);
339
+ if (uri.startsWith(BASE64_SCHEME)) return await writeBase64(uri, mediaDir, signal);
335
340
  return await cacheMediaFile(mediaDir, inferExtension(null, uri), async (dest) => {
336
341
  await mediaDownloader(outboundPolicy)(uri, dest);
337
342
  });
338
343
  }
339
344
  /** 发送段与上传类动作共用相同的 URI 授权与下载规则。 */
340
345
  async function resolveUriToPath(uri, mediaDir, outboundPolicy, localMediaRoots) {
341
- if (HTTP_URL_RE.test(uri) || uri.startsWith("base64://")) return await resolveMediaUri(uri, mediaDir, outboundPolicy);
346
+ if (HTTP_URL_RE.test(uri) || uri.startsWith(BASE64_SCHEME)) return await resolveMediaUri(uri, mediaDir, outboundPolicy);
342
347
  return await resolveLocalMedia(uri, localMediaRoots);
343
348
  }
344
349
  /** base64 载荷 → 落盘(先写 .bin,探测到扩展名再改名)。 */
345
- async function writeBase64(payload, mediaDir) {
346
- let bytes;
347
- try {
348
- bytes = Buffer.from(payload, "base64");
349
- } catch {
350
- throw kernelError("base64:// 载荷解码失败", "INVALID_PARAM");
351
- }
352
- if (bytes.length === 0) throw kernelError("base64:// 载荷为空", "INVALID_PARAM");
350
+ async function writeBase64(uri, mediaDir, signal) {
351
+ signal?.throwIfAborted();
352
+ const start = 9;
353
+ const length = uri.length - start;
354
+ if (length > MAX_BASE64_CHARS) throw kernelError("base64:// 编码载荷超出限制", "INVALID_PARAM");
355
+ const padding = uri.endsWith("==") ? 2 : uri.endsWith("=") ? 1 : 0;
356
+ const chars = length - padding;
357
+ const tail = chars % 4;
358
+ if (chars < 2 || tail === 1 || padding !== 0 && tail + padding !== 4) throw kernelError("base64:// 载荷长度或填充无效", "INVALID_PARAM");
359
+ const expectedBytes = Math.floor(chars * 3 / 4);
360
+ if (expectedBytes > MAX_DATA_BYTES) throw kernelError("base64:// 解码媒体超出限制", "INVALID_PARAM");
353
361
  return await cacheMediaFile(mediaDir, ".bin", async (raw) => {
354
- await writeFile(raw, bytes, { flag: "wx" });
355
- let ext;
356
- try {
357
- ({ext} = await detectFileType(raw));
358
- } catch {
359
- return raw;
360
- }
362
+ await writeBase64Chunks(raw, uri, start + chars, expectedBytes, signal);
363
+ const type = await detectFileType(raw, { signal }).catch(() => void 0);
364
+ signal?.throwIfAborted();
365
+ if (type === void 0) return raw;
366
+ const { ext } = type;
361
367
  if (!DETECTED_EXTENSION_RE.test(ext)) return raw;
362
368
  const final = `${raw.slice(0, -4)}.${ext}`;
363
369
  if (final !== raw) await rename(raw, final);
364
370
  return final;
365
371
  });
366
372
  }
373
+ async function writeBase64Chunks(path, uri, end, expectedBytes, signal) {
374
+ signal?.throwIfAborted();
375
+ const handle = await open(path, "wx", 384);
376
+ try {
377
+ let written = 0;
378
+ for (let offset = 9; offset < end; offset += BASE64_CHUNK_CHARS) {
379
+ signal?.throwIfAborted();
380
+ const chunk = uri.slice(offset, Math.min(offset + BASE64_CHUNK_CHARS, end));
381
+ if (INVALID_BASE64_CHAR.test(chunk)) throw kernelError("base64:// 载荷包含无效字符", "INVALID_PARAM");
382
+ const bytes = Buffer.from(chunk, "base64");
383
+ written += bytes.byteLength;
384
+ if (written > MAX_DATA_BYTES) throw kernelError("base64:// 解码媒体超出限制", "INVALID_PARAM");
385
+ await handle.writeFile(bytes);
386
+ }
387
+ if (written !== expectedBytes) throw kernelError("base64:// 解码长度无效", "INVALID_PARAM");
388
+ } finally {
389
+ await handle.close();
390
+ }
391
+ }
367
392
  // src/milky/action/group-file.ts
368
393
  const fileIdField = { file_id: z.string().min(1) };
369
394
  /** 群文件域动作工厂(列表 / 移动 / 重命名 / 删除 / 转存 / 文件夹 / 闪传上传 / 下载链接)。 */
@@ -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-CaSEVtLy.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-CgylJN92.mjs";
@@ -1,5 +1,5 @@
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 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";
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-CiZ6OxlQ.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-B0kwCfKE.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-ChxJJipr.mjs";
5
5
  import { ChatType, EssenceListSync, GrayTipSubType, GroupApi, GroupNotifyMsgType, NTGroupMemberRole, NTGroupRequestOperateTypes, TicketApi, TipGroupElementType, WebHonorType, errorMessage, findPendingGroupRequest, hasStringProp, isRecord, kernelError, narrowEssenceGroupArg, toCanonicalElements, toPendingGroupRequest } from "@napuketto/kernel";
@@ -2676,7 +2676,7 @@ function createSystemFileActions(api) {
2676
2676
  *
2677
2677
  * - get_login_info:self 由装配方注入(接 kernel selfInfo 取真实昵称)
2678
2678
  * - get_version_info:appVersion 由装配方注入(kernel wrapper 版本或
2679
- * NAPUTO_QQ_VERSION)
2679
+ * NAPUKETTO_QQ_VERSION)
2680
2680
  * - get_status:返回与心跳 status 同构的 OB11Status(online/good)
2681
2681
  * - get_robot_uin_range:NapCat 从配置返回;这里给通用范围(min/max)
2682
2682
  * - translate_en2zh:kernel RichMediaApi.translateWords(词条数组限长)
@@ -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-B-vWj1fa.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-DdcfE1nh.mjs";
@@ -1,5 +1,5 @@
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 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";
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-CiZ6OxlQ.mjs";
3
3
  import { c as MS_TO_SEC, h as toUinString, i as toUnixSeconds, r as subscribeRawMessages } from "./raw-message-B0kwCfKE.mjs";
4
4
  import { ChatType, GrayTipSubType, NTGroupRequestOperateTypes, TipGroupElementType, errorMessage, findPendingGroupRequest, isRecord, kernelError, toCanonicalElements } from "@napuketto/kernel";
5
5
  import { HttpServer, WsServer, isWsOpen, sendWsText } from "@napuketto/network";
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.22.0",
4
+ "version": "0.23.1",
5
5
  "type": "module",
6
6
  "description": "Protocol adapters (OneBot11 / Satori / KuroBot / Milky) for NapukettoQQ",
7
7
  "keywords": [
@@ -83,8 +83,8 @@
83
83
  "dev": "tsdown --watch"
84
84
  },
85
85
  "dependencies": {
86
- "@napuketto/kernel": "^0.18.0",
87
- "@napuketto/media": "^0.3.0",
86
+ "@napuketto/kernel": "^0.19.0",
87
+ "@napuketto/media": "^0.4.0",
88
88
  "@napuketto/network": "^0.5.0",
89
89
  "zod": "^4.6.7"
90
90
  },