@xiaozhu2007/koishi-plugin-litematic-renderer 0.6.0 → 0.7.20

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.
Files changed (62) hide show
  1. package/README.md +94 -6
  2. package/assets/standalone-renderer/litematic-standalone-renderer-0.2.8-patch.1.jar +0 -0
  3. package/dist/index.css +1 -0
  4. package/dist/index.js +13 -1
  5. package/lib/cache.d.ts +94 -0
  6. package/lib/cache.js +1 -0
  7. package/lib/concurrency.d.ts +13 -0
  8. package/lib/concurrency.js +1 -0
  9. package/lib/config.d.ts +205 -0
  10. package/lib/config.js +1 -0
  11. package/lib/diagnostics.d.ts +86 -0
  12. package/lib/diagnostics.js +1 -0
  13. package/lib/gpuAgentProtocol.d.ts +196 -0
  14. package/lib/gpuAgentProtocol.js +1 -0
  15. package/lib/index.d.ts +74 -435
  16. package/lib/index.js +1 -1
  17. package/lib/jsonFile.d.ts +8 -0
  18. package/lib/jsonFile.js +1 -0
  19. package/lib/litematic.d.ts +103 -0
  20. package/lib/litematic.js +1 -0
  21. package/lib/messageDelivery.d.ts +82 -0
  22. package/lib/messageDelivery.js +1 -0
  23. package/lib/messageFiles.d.ts +93 -0
  24. package/lib/messageFiles.js +1 -0
  25. package/lib/officialProxy.d.ts +12 -0
  26. package/lib/officialProxy.js +1 -0
  27. package/lib/onebotCompat.d.ts +29 -0
  28. package/lib/onebotCompat.js +1 -0
  29. package/lib/projectionCache.d.ts +83 -0
  30. package/lib/projectionCache.js +1 -0
  31. package/lib/projectionSearch.d.ts +3 -0
  32. package/lib/projectionSearch.js +1 -0
  33. package/lib/rateLimit.d.ts +18 -0
  34. package/lib/rateLimit.js +1 -0
  35. package/lib/render/cpu.d.ts +23 -0
  36. package/lib/render/cpu.js +1 -0
  37. package/lib/render/externalGpu.d.ts +12 -0
  38. package/lib/render/externalGpu.js +1 -0
  39. package/lib/render/gpuAgent.d.ts +7 -0
  40. package/lib/render/gpuAgent.js +1 -0
  41. package/lib/render/imageValidation.d.ts +18 -0
  42. package/lib/render/imageValidation.js +1 -0
  43. package/lib/render/javaBridge.d.ts +11 -0
  44. package/lib/render/javaBridge.js +1 -0
  45. package/lib/render/standalone.d.ts +76 -0
  46. package/lib/render/standalone.js +1 -0
  47. package/lib/render/types.d.ts +5 -0
  48. package/lib/render/types.js +1 -0
  49. package/lib/render/webgl.d.ts +21 -0
  50. package/lib/render/webgl.js +1 -0
  51. package/lib/resourcePacks.d.ts +15 -0
  52. package/lib/resourcePacks.js +1 -0
  53. package/lib/runtimePaths.d.ts +8 -0
  54. package/lib/runtimePaths.js +1 -0
  55. package/lib/schematicFormats.d.ts +8 -0
  56. package/lib/schematicFormats.js +1 -0
  57. package/package.json +18 -14
  58. package/client/index.ts +0 -136
  59. package/client/style.css +0 -18
  60. package/dist/style.css +0 -1
  61. package/lib/gpu-agent-protocol.d.ts +0 -102
  62. package/lib/gpu-agent-protocol.js +0 -257
@@ -0,0 +1,12 @@
1
+ import type { Context } from "koishi";
2
+ import type { Config } from "./config";
3
+ /** 官方 QQ 固定出口逻辑所需的配置子集。 */
4
+ type OfficialProxyConfig = Pick<Config, "officialProxyMode" | "officialProxyUrl" | "sshProxyExecutable" | "sshProxyHost" | "sshProxyPort" | "sshProxyUser" | "sshProxyPrivateKey" | "sshProxyPassword" | "sshProxyLocalPort">;
5
+ /** 解析官方 QQ 应使用的出站代理地址。 */
6
+ export declare function resolveOfficialProxyUrl(config: OfficialProxyConfig): string | undefined;
7
+ /** 构造不包含密码的系统 SSH 动态转发参数。 */
8
+ export declare function buildSshProxyArguments(config: OfficialProxyConfig): string[];
9
+ export declare function startSshProxyTunnel(config: OfficialProxyConfig, logger: ReturnType<Context["logger"]>): () => void;
10
+ /** 热重载官方 QQ 适配器;只由显式启用的实验性看门狗调用。 */
11
+ export declare function reloadOfficialQqAdapter(ctx: Context, logger: ReturnType<Context["logger"]>): Promise<boolean>;
12
+ export {};
@@ -0,0 +1 @@
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.resolveOfficialProxyUrl=resolveOfficialProxyUrl,exports.buildSshProxyArguments=buildSshProxyArguments,exports.startSshProxyTunnel=startSshProxyTunnel,exports.reloadOfficialQqAdapter=reloadOfficialQqAdapter;const node_child_process_1=require("node:child_process"),node_fs_1=require("node:fs"),node_net_1=require("node:net"),node_path_1=require("node:path"),ssh2_1=require("ssh2"),SUPPORTED_PROXY_PROTOCOLS=new Set(["http:","https:","socks:","socks5:","socks5h:"]);function resolveOfficialProxyUrl(e){if("disabled"===e.officialProxyMode)return;const r="ssh"===e.officialProxyMode?`socks5h://127.0.0.1:${e.sshProxyLocalPort}`:e.officialProxyUrl.trim();if(!r)throw new Error("已开启官方 QQ 中转,但代理地址为空");let o;try{o=new URL(r)}catch{throw new Error(`代理地址格式无效:${r}`)}if(!SUPPORTED_PROXY_PROTOCOLS.has(o.protocol))throw new Error(`不支持的代理协议:${o.protocol}`);return o.href}function buildSshProxyArguments(e){const r=e.sshProxyHost.trim(),o=e.sshProxyUser.trim(),t=e.sshProxyPrivateKey.trim();if(!r)throw new Error("SSH 中转服务器 IP 不能为空");if(!o)throw new Error("SSH 登录用户名不能为空");if(!t&&!e.sshProxyPassword)throw new Error("SSH 私钥和密码至少填写一项");const s=["-NT","-D",`127.0.0.1:${e.sshProxyLocalPort}`,"-p",String(e.sshProxyPort),"-o","BatchMode=yes","-o","ExitOnForwardFailure=yes","-o","ServerAliveInterval=30","-o","ServerAliveCountMax=3","-o","StrictHostKeyChecking=accept-new"];return t&&s.push("-i",(0,node_path_1.resolve)(t)),s.push(`${o}@${r}`),s}function isTcpPortOpen(e,r,o=1e3){return new Promise(t=>{const s=new node_net_1.Socket;let n=!1;const i=e=>{n||(n=!0,s.destroy(),t(e))};s.setTimeout(o),s.once("connect",()=>i(!0)),s.once("timeout",()=>i(!1)),s.once("error",()=>i(!1)),s.connect(r,e)})}function startPasswordSshProxyTunnel(e,r){let o,t,s,n=!1;const i=new Set,a=()=>{n||(o=new ssh2_1.Client,o.once("ready",()=>{!n&&o&&(t=(0,node_net_1.createServer)(e=>{i.add(e),e.once("close",()=>i.delete(e)),handleSocks5Connection(e,o)}),t.once("error",e=>{r.warn(`本地 SOCKS5 监听失败:${e.message}`),o?.end()}),t.listen(e.sshProxyLocalPort,"127.0.0.1",()=>{r.info(`官方 QQ 中转已就绪:socks5h://127.0.0.1:${e.sshProxyLocalPort}`)}))}),o.once("error",e=>r.warn(`SSH 密码登录失败:${e.message}`)),o.once("close",()=>{o=void 0,t?.close(),t=void 0;for(const e of i)e.destroy();n||n||s||(s=setTimeout(()=>{s=void 0,a()},5e3))}),r.info(`正在使用密码建立官方 QQ SSH 中转:${e.sshProxyUser}@${e.sshProxyHost}`),o.connect({host:e.sshProxyHost.trim(),port:e.sshProxyPort,username:e.sshProxyUser.trim(),password:e.sshProxyPassword,keepaliveInterval:3e4,keepaliveCountMax:3,readyTimeout:15e3}))};return a(),()=>{n=!0,s&&clearTimeout(s),t?.close(),o?.end();for(const e of i)e.destroy()}}function handleSocks5Connection(e,r){let o=Buffer.alloc(0),t="greeting";const s=(r=1)=>{"request"===t&&e.write(Buffer.from([5,r,0,1,0,0,0,0,0,0])),e.destroy()};e.on("data",n=>{if(o=Buffer.concat([o,n]),"greeting"===t){if(o.length<2)return;const r=2+o[1];if(o.length<r)return;if(5!==o[0]||!o.subarray(2,r).includes(0))return s();o=o.subarray(r),t="request",e.write(Buffer.from([5,0]))}if("request"!==t||o.length<4)return;if(5!==o[0]||1!==o[1])return s(7);const i=o[3];let a,c;if(1===i){if(o.length<10)return;a=[...o.subarray(4,8)].join("."),c=8}else if(3===i){const e=o[4];if(o.length<7+e)return;a=o.subarray(5,5+e).toString("utf8"),c=5+e}else{if(4!==i)return s(8);{if(o.length<22)return;const e=[];for(let r=4;r<20;r+=2)e.push(o.readUInt16BE(r).toString(16));a=e.join(":"),c=20}}const l=o.readUInt16BE(c);e.pause(),e.removeAllListeners("data"),r.forwardOut("127.0.0.1",0,a,l,(r,o)=>{if(r)return s(5);e.write(Buffer.from([5,0,0,1,0,0,0,0,0,0])),e.pipe(o).pipe(e),e.resume()})}),e.once("error",()=>e.destroy())}function startSshProxyTunnel(e,r){if(buildSshProxyArguments(e),!e.sshProxyPrivateKey.trim())return startPasswordSshProxyTunnel(e,r);const o=e.sshProxyExecutable.trim()||"ssh",t=buildSshProxyArguments(e);let s,n,i=!1;const a=()=>{i||n||(n=setTimeout(()=>{n=void 0,c()},5e3))},c=async()=>{if(i)return;if(await isTcpPortOpen("127.0.0.1",e.sshProxyLocalPort))return void r.info(`官方 QQ 中转已就绪:socks5h://127.0.0.1:${e.sshProxyLocalPort}`);try{await node_fs_1.promises.access((0,node_path_1.resolve)(e.sshProxyPrivateKey),node_fs_1.constants.R_OK)}catch{return r.warn(`SSH 私钥不可读:${(0,node_path_1.resolve)(e.sshProxyPrivateKey)}`),void a()}s=(0,node_child_process_1.spawn)(o,t,{stdio:["ignore","ignore","pipe"],windowsHide:!0});let n="";s.stderr?.on("data",e=>{n=`${n}${e.toString()}`.slice(-2e3)}),s.once("spawn",()=>r.info(`正在建立官方 QQ SSH 中转:${e.sshProxyUser}@${e.sshProxyHost}`)),s.once("error",e=>{r.warn(`SSH 中转启动失败:${e.message}`),a()}),s.once("close",e=>{if(s=void 0,i)return;const o=n.trim().split(/\r?\n/).at(-1);r.warn(`SSH 中转已断开(退出码 ${e??"unknown"})${o?`:${o}`:""}`),a()});for(let o=0;o<20&&s&&!i;o++){if(await isTcpPortOpen("127.0.0.1",e.sshProxyLocalPort,300)){r.info(`官方 QQ 中转已就绪:socks5h://127.0.0.1:${e.sshProxyLocalPort}`);break}await new Promise(e=>setTimeout(e,250))}};return c(),()=>{i=!0,n&&clearTimeout(n),s?.kill()}}async function reloadOfficialQqAdapter(e,r){try{const o=e.loader;if(!o?.entries)return!1;for(const e of o.entries.values())if(e?.config&&"secret"in e.config&&"intents"in e.config&&String(e.name??"").includes("adapter-qq"))return r.warn("官方 QQ 网关看门狗:8 分钟无消息,正在热重载适配器"),await o.reload(e),!0}catch(e){r.warn(`官方 QQ 网关看门狗热重载失败:${e instanceof Error?e.message:String(e)}`)}return!1}
@@ -0,0 +1,29 @@
1
+ import type { Context } from "koishi";
2
+ /** OneBot 适配器源码兼容补丁的处理结果 */
3
+ interface SourcePatchResult {
4
+ /** 处理后的适配器源码 */
5
+ source: string;
6
+ /** 本次处理是否修改了源码 */
7
+ changed: boolean;
8
+ /** 原始源码是否已经支持群文件上传事件 */
9
+ alreadyCompatible: boolean;
10
+ }
11
+ /**
12
+ * 恢复特定 OneBot 适配器版本中被注释的群文件上传事件映射
13
+ *
14
+ * @remarks
15
+ * 如果源码已经兼容或无法识别预期代码块,函数会原样返回源码
16
+ *
17
+ * @param source - OneBot 适配器编译后的 JavaScript 源码
18
+ * @returns 补丁后的源码以及是否修改、是否已兼容的状态
19
+ */
20
+ export declare function patchOneBotAdapterSource(source: string): SourcePatchResult;
21
+ /**
22
+ * 检查已安装的 OneBot 适配器,并在启用时应用群文件事件兼容补丁
23
+ *
24
+ * @param logger - 用于记录补丁状态的 Koishi 日志器
25
+ * @param enabled - 是否允许修改适配器源码
26
+ * @returns 补丁检查和文件操作完成后解决的 Promise
27
+ */
28
+ export declare function ensureOneBotGroupUploadCompatibility(logger: ReturnType<Context["logger"]>, enabled: boolean): Promise<void>;
29
+ export {};
@@ -0,0 +1 @@
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.patchOneBotAdapterSource=patchOneBotAdapterSource,exports.ensureOneBotGroupUploadCompatibility=ensureOneBotGroupUploadCompatibility;const node_fs_1=require("node:fs"),node_path_1=require("node:path"),runtimePaths_1=require("./runtimePaths");function patchOneBotAdapterSource(e){if(/^\s*case ["']group_upload["']:/m.test(e))return{source:e,changed:!1,alreadyCompatible:!0};const s=e.match(/\(0,\s*(import_[\w$]+)\.hyphenate\)\(data\.sub_type\)/)?.[1]??"import_koishi2",i=/ \/\/ https:\/\/github\.com\/koishijs\/koishi-plugin-adapter-onebot\/issues\/33\r?\n \/\/ case 'offline_file':\r?\n \/\/ session\.elements = \[h\('file', data\.file\)\]\r?\n \/\/ session\.type = 'message'\r?\n \/\/ session\.subtype = 'private'\r?\n \/\/ session\.isDirect = true\r?\n \/\/ session\.subsubtype = 'offline-file-added'\r?\n \/\/ break\r?\n \/\/ case 'group_upload':\r?\n \/\/ session\.elements = \[h\('file', data\.file\)\]\r?\n \/\/ session\.type = 'message'\r?\n \/\/ session\.subtype = 'group'\r?\n \/\/ session\.subsubtype = 'guild-file-added'\r?\n \/\/ break/;if(!i.test(e))return{source:e,changed:!1,alreadyCompatible:!1};const o=[" // Restored by koishi-plugin-litematic-renderer so NapCat group file uploads reach middleware",' case "offline_file":',` session.elements = [(0, ${s}.h)("file", data.file)];`,' session.type = "message";',' session.subtype = "private";'," session.isDirect = true;",' session.subsubtype = "offline-file-added";'," break;",' case "group_upload":',` session.elements = [(0, ${s}.h)("file", data.file)];`,' session.type = "message";',' session.subtype = "group";',' session.subsubtype = "guild-file-added";'," break;"].join("\n");return{source:e.replace(i,o),changed:!0,alreadyCompatible:!1}}async function ensureOneBotGroupUploadCompatibility(e,s){if(!s)return;let i;try{i=require.resolve("koishi-plugin-adapter-onebot/package.json",{paths:[process.cwd(),runtimePaths_1.LIB_DIRECTORY]})}catch{return void e.debug("未安装 koishi-plugin-adapter-onebot,跳过群文件上传事件兼容修复")}try{const s=(0,node_path_1.dirname)(i),o=JSON.parse(await node_fs_1.promises.readFile(i,"utf8")),t=(0,node_path_1.join)(s,"lib","index.js"),n=await node_fs_1.promises.readFile(t,"utf8"),r=patchOneBotAdapterSource(n);if(r.alreadyCompatible)return void e.debug(`koishi-plugin-adapter-onebot@${o.version??"unknown"} 已支持 group_upload`);if(!r.changed)return void e.warn(`koishi-plugin-adapter-onebot@${o.version??"unknown"} 未识别到可自动修复的 group_upload 代码段`);const a=`${t}.litematic-renderer.bak`;await exists(a)||await node_fs_1.promises.writeFile(a,n),await node_fs_1.promises.writeFile(t,r.source),e.warn(`已修复 koishi-plugin-adapter-onebot@${o.version??"unknown"} 的群文件上传事件映射;请重启 Koishi 让已加载的 OneBot 适配器生效`)}catch(s){e.warn(`修复 OneBot 群文件上传事件失败:${s instanceof Error?s.message:String(s)}`)}}async function exists(e){return node_fs_1.promises.access(e).then(()=>!0).catch(()=>!1)}
@@ -0,0 +1,83 @@
1
+ import type { GpuRenderResult } from "./gpuAgentProtocol";
2
+ import type { ImageResult } from "./messageDelivery";
3
+ /** 持久源文件资料目录,独立于可清理的版本及配置渲染目录 */
4
+ export declare const PROJECTION_LIBRARY = ".projection-library";
5
+ /** 一份投影在特定插件版本和渲染配置下的结果位置 */
6
+ export interface ProjectionVariant {
7
+ /** 相对于缓存根目录的渲染结果目录,禁止跳出根目录 */
8
+ directory: string;
9
+ /** 创建该结果的插件版本 */
10
+ pluginVersion: string;
11
+ /** 包含资源、参数和节点能力的本地配置摘要 */
12
+ renderConfigSha256: string;
13
+ }
14
+ /** 投影身份与多个渲染配置之间的持久映射 */
15
+ export interface ProjectionRecord {
16
+ /** 原始文件哈希,保持本地多格式输入的缓存身份 */
17
+ contentSha256: string;
18
+ /** 转换后的 Litematic 哈希,供协议及资料导出核对 */
19
+ normalizedContentSha256: string;
20
+ /** 首次收到的投影文件名,用于展示名称 */
21
+ sourceFilename: string;
22
+ /** 可发送源文件的名称,旧缓存缺少原文件时使用 Litematic 后缀 */
23
+ downloadFilename: string;
24
+ /** 资料目录中的源文件名,不包含路径 */
25
+ storedFilename: string;
26
+ /** 是否保留上传原始字节,旧缓存迁移可能只有规范化后的 Litematic */
27
+ originalAvailable: boolean;
28
+ /** 按配置区分的渲染结果位置,图片淘汰不删除投影资料 */
29
+ variants: ProjectionVariant[];
30
+ /** 搜索和渲染调用次数,沿用上游 Koishi 的搜索排序 */
31
+ cacheCalls: number;
32
+ }
33
+ /** 磁盘图片清单,缓存命中时仍保留 Agent 的拆图要求 */
34
+ export interface RenderManifest {
35
+ /** 图片文件名及展示标题,按发送顺序保存 */
36
+ images: Array<{
37
+ filename: string;
38
+ title: string;
39
+ }>;
40
+ /** 合成图超过平台限制时必须逐张发送 */
41
+ forceSeparateImages: boolean;
42
+ /** 实际 Agent 工具版本,旧节点可以不提供 */
43
+ rendererVersion?: string;
44
+ /** 实际完成任务的节点能力摘要 */
45
+ rendererFingerprint?: string;
46
+ }
47
+ /** 一页搜索中的候选项,同一原始投影只出现一次 */
48
+ export interface ProjectionSearchEntry {
49
+ /** 投影的持久身份与配置索引 */
50
+ record: ProjectionRecord;
51
+ /** 当前配置有效的图片清单 */
52
+ images: ImageResult[];
53
+ /** 选中的渲染配置目录 */
54
+ directory: string;
55
+ /** 可发送的持久源文件路径 */
56
+ projectionPath: string;
57
+ /** 当前结果必须逐张发送时为 true */
58
+ forceSeparateImages: boolean;
59
+ }
60
+ /** 搜索关键词及有序结果,序号只在该页中有效,与上游 Koishi 一致 */
61
+ export interface ProjectionSearchPage {
62
+ /** 已去除首尾空白的搜索关键词 */
63
+ keyword: string;
64
+ /** 按调用次数、名称和内容哈希排序的结果 */
65
+ entries: ProjectionSearchEntry[];
66
+ }
67
+ /** 同目录原子替换,读者不会看到半份图片清单或资料索引 */
68
+ export declare function writeCacheJson(path: string, value: unknown): Promise<void>;
69
+ /** 持久保存全部 Agent 视角,文件名由本地分配,避免重复 ID 或路径覆盖 */
70
+ export declare function saveGpuRenderManifest(directory: string, result: GpuRenderResult): Promise<void>;
71
+ /** 清单完整且文件都存在时才算命中,任一视角被淘汰后需要重新渲染 */
72
+ export declare function readRenderManifest(directory: string): Promise<RenderManifest | undefined>;
73
+ /** 登记源投影和渲染配置;原始字节缺省只用于升级前缓存的资料重建 */
74
+ export declare function rememberProjection(root: string, identity: {
75
+ contentSha256: string;
76
+ sourceFilename: string;
77
+ }, normalizedBytes: Buffer, variant: ProjectionVariant, originalBytes?: Buffer): Promise<void>;
78
+ /** 从保留的版本及配置目录重建资料,兼容多格式转换前后的不同哈希 */
79
+ export declare function rebuildProjectionLibrary(root: string): Promise<void>;
80
+ /** 按上游 Koishi 规则搜索,仅展示当前渲染配置仍有完整图片的投影 */
81
+ export declare function searchCachedProjections(root: string, keyword: string, limit: number, accepts: (record: ProjectionRecord, variant: ProjectionVariant) => Promise<boolean>): Promise<ProjectionSearchPage>;
82
+ /** 累计资料调用次数,不依赖某份图片是否仍在磁盘上 */
83
+ export declare function recordProjectionUse(root: string, fileHash: string): Promise<void>;
@@ -0,0 +1 @@
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.PROJECTION_LIBRARY=void 0,exports.writeCacheJson=writeCacheJson,exports.saveGpuRenderManifest=saveGpuRenderManifest,exports.readRenderManifest=readRenderManifest,exports.rememberProjection=rememberProjection,exports.rebuildProjectionLibrary=rebuildProjectionLibrary,exports.searchCachedProjections=searchCachedProjections,exports.recordProjectionUse=recordProjectionUse;const node_crypto_1=require("node:crypto"),node_fs_1=require("node:fs"),node_path_1=require("node:path"),cache_1=require("./cache");exports.PROJECTION_LIBRARY=".projection-library";const libraryWrites=new Map;async function withLibraryLock(e,a){const t=(0,node_path_1.resolve)(e),n=(libraryWrites.get(t)??Promise.resolve()).catch(()=>{}).then(a);libraryWrites.set(t,n);try{return await n}finally{libraryWrites.get(t)===n&&libraryWrites.delete(t)}}async function readJson(e){try{return JSON.parse(await node_fs_1.promises.readFile(e,"utf8"))}catch(e){if("ENOENT"===e?.code||e instanceof SyntaxError)return;throw e}}async function writeCacheJson(e,a){const t=`${e}.${(0,node_crypto_1.randomUUID)()}.tmp`;try{await node_fs_1.promises.writeFile(t,JSON.stringify(a,null,2)+"\n"),await node_fs_1.promises.rename(t,e)}finally{await node_fs_1.promises.rm(t,{force:!0})}}function containedPath(e,a){const t=(0,node_path_1.resolve)(e,a),n=(0,node_path_1.relative)((0,node_path_1.resolve)(e),t);return!n||n.startsWith("..")||n.startsWith("/")?void 0:t}async function saveGpuRenderManifest(e,a){if(!a.images.length)throw new Error("GPU Agent 没有返回渲染图片");const t=[],n=new Set;for(const[o,r]of a.images.entries()){let a="merged"===r.id||"isometric"===r.id?"isometric.png":"isometric-reverse"===r.id?"isometric-reverse.png":"six-face"===r.id||"six-faces"===r.id?"six-faces.png":`agent-view-${o}.png`;n.has(a)&&(a=`agent-view-${o}.png`),n.add(a),await node_fs_1.promises.writeFile((0,node_path_1.join)(e,a),r.png),t.push({filename:a,title:r.name||r.id})}await writeCacheJson((0,node_path_1.join)(e,"images.json"),{images:t,forceSeparateImages:!0===a.forceSeparateImages,rendererVersion:a.rendererVersion,rendererFingerprint:a.rendererFingerprint})}async function readRenderManifest(e){const a=await readJson((0,node_path_1.join)(e,"images.json"));if(a&&Array.isArray(a.images)&&a.images.length){for(const t of a.images){if(!t||"string"!=typeof t.filename||(0,node_path_1.basename)(t.filename)!==t.filename)return;if(!t.filename.endsWith(".png")||"string"!=typeof t.title)return;if(!(await node_fs_1.promises.stat((0,node_path_1.join)(e,t.filename)).catch(()=>{}))?.isFile())return}return a}}async function rememberProjection(e,a,t,n,o){if(!/^[a-f0-9]{64}$/.test(a.contentSha256))throw new Error("无效的投影内容哈希");if(!containedPath(e,n.directory))throw new Error("无效的渲染配置目录");await withLibraryLock(e,async()=>{const r=(0,node_path_1.join)(e,exports.PROJECTION_LIBRARY,a.contentSha256);await node_fs_1.promises.mkdir(r,{recursive:!0});const i=await readJson((0,node_path_1.join)(r,"about.json5")),s=(0,node_path_1.extname)(a.sourceFilename).toLowerCase(),c=o&&[".schem",".nbt"].includes(s)?s:".litematic",d=o&&!i?.originalAvailable?`source${c}`:i?.storedFilename??`source${c}`;if((0,node_path_1.basename)(d)!==d)throw new Error("无效的投影源文件名");const l=(0,node_path_1.join)(r,d);(await node_fs_1.promises.stat(l).catch(()=>{}))?.isFile()||await node_fs_1.promises.writeFile(l,o??t);const h=(0,node_path_1.join)(r,"projection.litematic");(await node_fs_1.promises.stat(h).catch(()=>{}))?.isFile()||await node_fs_1.promises.writeFile(h,t);const m={...a,normalizedContentSha256:(0,node_crypto_1.createHash)("sha256").update(t).digest("hex"),sourceFilename:i?.sourceFilename??(0,node_path_1.basename)(a.sourceFilename),downloadFilename:o&&!i?.originalAvailable?(0,node_path_1.basename)(a.sourceFilename):i?.downloadFilename??(o?(0,node_path_1.basename)(a.sourceFilename):`${(0,cache_1.projectionNameFromFilename)(a.sourceFilename)}.litematic`),storedFilename:d,originalAvailable:Boolean(o||i?.originalAvailable),variants:[...(i?.variants??[]).filter(e=>e.directory!==n.directory),n],cacheCalls:Math.max(0,i?.cacheCalls??0)};await writeCacheJson((0,node_path_1.join)(r,"about.json5"),m);const p=(0,node_path_1.join)(e,"index.json5"),_=await readJson(p),f=(Array.isArray(_)?_:[]).filter(e=>e&&e.哈希值!==m.contentSha256);f.push({"投影文件名称":m.sourceFilename,"哈希值":m.contentSha256,"规范化哈希值":m.normalizedContentSha256,"相对路径":(0,node_path_1.relative)(e,r),"渲染配置":m.variants}),await writeCacheJson(p,f)})}async function rebuildProjectionLibrary(e){const a=await node_fs_1.promises.readdir(e,{withFileTypes:!0}).catch(()=>[]);for(const t of a){if(!t.isDirectory()||!t.name.startsWith("v"))continue;const a=(0,node_path_1.join)(e,t.name);for(const t of await node_fs_1.promises.readdir(a,{withFileTypes:!0})){if(!t.isDirectory())continue;const n=(0,node_path_1.join)(a,t.name),o=await readJson((0,node_path_1.join)(n,"cache.json"));if(!o||"string"!=typeof o.contentSha256||!/^[a-f0-9]{64}$/.test(o.contentSha256)||"string"!=typeof o.sourceFilename||"string"!=typeof o.renderConfigSha256||"string"!=typeof o.pluginVersion)continue;const r=await node_fs_1.promises.readFile((0,node_path_1.join)(n,"projection.litematic")).catch(()=>{});r&&await rememberProjection(e,{contentSha256:o.contentSha256,sourceFilename:o.sourceFilename},r,{directory:(0,node_path_1.relative)(e,n),pluginVersion:o.pluginVersion,renderConfigSha256:o.renderConfigSha256})}}}async function searchCachedProjections(e,a,t,n){const o=a.trim().toLocaleLowerCase();if(!o)throw new Error("搜索关键词不能为空");await rebuildProjectionLibrary(e);const r=await node_fs_1.promises.readdir((0,node_path_1.join)(e,exports.PROJECTION_LIBRARY),{withFileTypes:!0}).catch(()=>[]),i=[];for(const a of r){if(!a.isDirectory()||!/^[a-f0-9]{64}$/.test(a.name))continue;const t=(0,node_path_1.join)(e,exports.PROJECTION_LIBRARY,a.name),r=await readJson((0,node_path_1.join)(t,"about.json5"));if(!r||r.contentSha256!==a.name||"string"!=typeof r.sourceFilename||"string"!=typeof r.storedFilename||!Array.isArray(r.variants))continue;if(!(0,cache_1.projectionNameFromFilename)(r.sourceFilename).toLocaleLowerCase().includes(o))continue;const s=containedPath(t,r.storedFilename);if(s&&(await node_fs_1.promises.stat(s).catch(()=>{}))?.isFile())for(const a of[...r.variants].reverse()){const t="string"==typeof a.directory&&containedPath(e,a.directory);if(!t||!await n(r,a))continue;const o=await readRenderManifest(t);if(o){i.push({record:r,directory:t,projectionPath:s,images:o.images.map(e=>({title:e.title,path:(0,node_path_1.join)(t,e.filename)})),forceSeparateImages:!0===o.forceSeparateImages});break}}}return i.sort((e,a)=>a.record.cacheCalls-e.record.cacheCalls||(0,cache_1.projectionNameFromFilename)(e.record.sourceFilename).localeCompare((0,cache_1.projectionNameFromFilename)(a.record.sourceFilename),"zh-Hans-CN")||e.record.contentSha256.localeCompare(a.record.contentSha256)),{keyword:a.trim(),entries:i.slice(0,Math.max(1,Math.min(100,Math.floor(t||15))))}}async function recordProjectionUse(e,a){/^[a-f0-9]{64}$/.test(a)&&await withLibraryLock(e,async()=>{const t=(0,node_path_1.join)(e,exports.PROJECTION_LIBRARY,a,"about.json5"),n=await readJson(t);n&&(n.cacheCalls=Math.max(0,n.cacheCalls||0)+1,await writeCacheJson(t,n))})}
@@ -0,0 +1,3 @@
1
+ import type { ProjectionSearchPage } from "./projectionCache";
2
+ /** 复用上游 Koishi 的编号缩略图布局,编号对应当前搜索页 */
3
+ export declare function createProjectionSearchSheet(page: ProjectionSearchPage, cacheDirectory: string): Promise<string>;
@@ -0,0 +1 @@
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.createProjectionSearchSheet=createProjectionSearchSheet;const node_fs_1=require("node:fs"),node_path_1=require("node:path"),node_crypto_1=require("node:crypto"),pngjs_1=require("pngjs"),messageDelivery_1=require("./messageDelivery");async function createProjectionSearchSheet(e,t){if(!e.entries.length)throw new Error("没有可显示的投影搜索结果");const n=Math.min(3,e.entries.length),a=Math.ceil(e.entries.length/n),r=360,o=224,i=new pngjs_1.PNG({width:32+n*r+12*(n-1),height:46+266*a+12*(a-1)+16});fillPng(i,255,255,255,255);for(let t=0;t<e.entries.length;t++){const a=e.entries[t],h=pngjs_1.PNG.sync.read(await node_fs_1.promises.readFile(a.images[0].path)),s=16+372*(t%n),l=46+278*Math.floor(t/n);fillRect(i,s,l,r,266,245,247,250,255),fillRect(i,s+14,l+10,332,204,0,0,0,255);const c=Math.min(332/h.width,o/h.height),d=Math.max(1,Math.round(h.width*c)),g=Math.max(1,Math.round(h.height*c));(0,messageDelivery_1.drawScaledPng)(i,{image:h,x:s+Math.floor((r-d)/2),y:l+Math.floor((o-g)/2),width:d,height:g}),drawSearchBadge(i,s+20,l+18,t+1)}const h=(0,node_path_1.join)(t,`.projection-search-${(0,node_crypto_1.randomUUID)()}.png`);return await node_fs_1.promises.writeFile(h,pngjs_1.PNG.sync.write(i)),h}function fillPng(e,t,n,a,r){for(let o=0;o<e.data.length;o+=4)e.data[o]=t,e.data[o+1]=n,e.data[o+2]=a,e.data[o+3]=r}function fillRect(e,t,n,a,r,o,i,h,s){for(let l=Math.max(0,n);l<Math.min(e.height,n+r);l++)for(let n=Math.max(0,t);n<Math.min(e.width,t+a);n++){const t=4*(l*e.width+n);e.data[t]=o,e.data[t+1]=i,e.data[t+2]=h,e.data[t+3]=s}}const SEARCH_DIGITS=[["11110","10001","10011","10101","11001","10001","11110"],["00100","01100","00100","00100","00100","00100","01110"],["11110","00001","00001","01110","10000","10000","11111"],["11110","00001","00001","01110","00001","00001","11110"],["10010","10010","10010","11111","00010","00010","00010"],["11111","10000","10000","11110","00001","00001","11110"],["01110","10000","10000","11110","10001","10001","01110"],["11111","00001","00010","00100","01000","01000","01000"],["01110","10001","10001","01110","10001","10001","01110"],["01110","10001","10001","01111","00001","00001","01110"]];function drawSearchBadge(e,t,n,a){fillRect(e,t,n,44,34,27,111,208,255);const r=String(a),o=5*r.length*3+3*(r.length-1);let i=t+Math.floor((44-o)/2);for(const t of r){const a=SEARCH_DIGITS[Number(t)];for(let t=0;t<a.length;t++)for(let r=0;r<a[t].length;r++)"1"===a[t][r]&&fillRect(e,i+3*r,n+4+3*t,3,3,255,255,255,255);i+=18}}
@@ -0,0 +1,18 @@
1
+ export interface RateLimitDecision {
2
+ allowed: boolean;
3
+ retryAfterSeconds: number;
4
+ }
5
+ /** 以滚动时间窗口限制单个来源的渲染请求数量。 */
6
+ export declare class RenderRateLimiter {
7
+ private readonly limitPerMinute;
8
+ private readonly now;
9
+ private readonly windows;
10
+ constructor(limitPerMinute: number, now?: () => number);
11
+ check(key: string): RateLimitDecision;
12
+ clear(key?: string): void;
13
+ }
14
+ /** 为会话生成稳定的限流键,优先区分用户,其次区分群组。 */
15
+ export declare function renderRateLimitKey(session: {
16
+ userId?: string;
17
+ guildId?: string;
18
+ }): string;
@@ -0,0 +1 @@
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.RenderRateLimiter=void 0,exports.renderRateLimitKey=renderRateLimitKey;class RenderRateLimiter{limitPerMinute;now;windows=new Map;constructor(e,t=()=>Date.now()){this.limitPerMinute=e,this.now=t}check(e){if(!this.limitPerMinute||this.limitPerMinute<1)return{allowed:!0,retryAfterSeconds:0};const t=this.now()-6e4,i=(this.windows.get(e)??[]).filter(e=>e>t);return i.length>=this.limitPerMinute?(this.windows.set(e,i),{allowed:!1,retryAfterSeconds:Math.max(1,Math.ceil((i[0]+6e4-this.now())/1e3))}):(i.push(this.now()),this.windows.set(e,i),{allowed:!0,retryAfterSeconds:0})}clear(e){e?this.windows.delete(e):this.windows.clear()}}function renderRateLimitKey(e){return e.userId?`user:${e.userId}`:e.guildId?`group:${e.guildId}`:"anonymous"}exports.RenderRateLimiter=RenderRateLimiter;
@@ -0,0 +1,23 @@
1
+ import type { Config, SixFaceLayout } from "../config";
2
+ import type { Block } from "../litematic";
3
+ /**
4
+ * 使用内置 CPU 栅格器生成正向和反向轴测 PNG
5
+ *
6
+ * @param blocks - 要渲染的非空气方块
7
+ * @param config - 控制尺寸、背景和方块比例的插件配置
8
+ * @returns 两张带固定文件名的内存 PNG
9
+ */
10
+ export declare function renderSchematic(blocks: Block[], config: Config): {
11
+ title: string;
12
+ png: Buffer<ArrayBuffer>;
13
+ }[];
14
+ /**
15
+ * 将投影的上下东西南北视图合成为一张正交总览 PNG
16
+ *
17
+ * @param blocks - 要投影的非空气方块
18
+ * @param config - 控制输出尺寸和背景的插件配置
19
+ * @param layout - 六张视图采用横向 3×2 或纵向 2×3 排列
20
+ * @returns 包含六个方向标签的 PNG 数据
21
+ * @throws 方块列表为空时抛出错误
22
+ */
23
+ export declare function renderSixFaceOverview(blocks: Block[], config: Config, layout?: SixFaceLayout): Buffer<ArrayBuffer>;
@@ -0,0 +1 @@
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.renderSchematic=renderSchematic,exports.renderSixFaceOverview=renderSixFaceOverview;const node_crypto_1=require("node:crypto"),node_zlib_1=require("node:zlib");function renderSchematic(t,e){const a=getBounds(t);return[{title:"isometric.png",png:renderIsometric(t,a,e,!1)},{title:"isometric-reverse.png",png:renderIsometric(t,a,e,!0)}]}function getBounds(t){return t.reduce((t,e)=>({minX:Math.min(t.minX,e.x),minY:Math.min(t.minY,e.y),minZ:Math.min(t.minZ,e.z),maxX:Math.max(t.maxX,e.x),maxY:Math.max(t.maxY,e.y),maxZ:Math.max(t.maxZ,e.z)}),{minX:1/0,minY:1/0,minZ:1/0,maxX:-1/0,maxY:-1/0,maxZ:-1/0})}const SIX_FACE_ORDER=["up","down","east","south","west","north"],SIX_FACE_LABELS={up:["00000100000","00000100000","00000100000","00000100000","00000111110","00000100000","00000100000","00000100000","00000100000","00000100000","11111111111"],down:["00000000000","11111111111","00000100000","00000100000","00000110000","00000101000","00000100100","00000100100","00000100000","00000100000","00000100000"],east:["00000100000","00000100000","01111111111","00001010000","00010010000","00111111110","00000010000","00010010100","00100010010","01000010001","00001110000"],south:["00000100000","11111111111","00000100000","01111111110","01010001010","01001010010","01111111110","01000100010","01111111110","01000100010","01000100110"],west:["00000000000","11111111111","00001010000","01111111110","01001010010","01001010010","01010010010","01100001110","01000000010","01111111110","01000000010"],north:["00010010000","00010010000","00010010000","11110010011","00010011100","00010010000","00010010000","00110010000","01010010001","10010010001","00010001111"]};function renderSixFaceOverview(t,e,a=e.sixFaceLayout??"horizontal"){if(!t.length)throw new Error("投影中没有可生成六面图的方块");const r=Math.max(128,Math.floor(e.outputSize)),o=Math.max(4,Math.round(.01*r)),n="vertical"===a?2:3,i="vertical"===a?3:2,c=Math.floor((r-o*("vertical"===a?i+1:n+1))/("vertical"===a?i:n)),h=new Raster("vertical"===a?n*c+o*(n+1):r,"vertical"===a?r:i*c+o*(i+1),e),s=getBounds(t);for(const[e,a]of SIX_FACE_ORDER.entries()){const r=o+e%n*(c+o),i=o+Math.floor(e/n)*(c+o);drawOrthographicFace(h,t,s,a,r,i,c,o),drawFaceLabel(h,a,r,i,c,o)}return h.png()}function drawOrthographicFace(t,e,a,r,o,n,i,c){const h="east"===r||"west"===r?a.maxZ-a.minZ+1:a.maxX-a.minX+1,s="up"===r||"down"===r?a.maxZ-a.minZ+1:a.maxY-a.minY+1,l=new Map;for(const t of e){const e=orthographicCoordinates(t,a,r),o=`${e.a},${e.b}`,n=l.get(o);(!n||e.depth>n.depth)&&l.set(o,{block:t,...e})}const d=Math.max(2,Math.floor(c/2)),m=Math.max(1,i-2*d),f=Math.min(m/h,m/s),u=o+d+(m-h*f)/2,x=n+d+(m-s*f)/2;for(const{block:e,a:a,b:r}of[...l.values()].sort((t,e)=>t.b-e.b||t.a-e.a)){const o=Math.floor(u+a*f),n=Math.floor(x+r*f),i=Math.max(o+1,Math.ceil(u+(a+1)*f)),c=Math.max(n+1,Math.ceil(x+(r+1)*f));t.rect(o,n,i-o,c-n,colorFor(e.name))}}function orthographicCoordinates(t,e,a){switch(a){case"up":return{a:t.x-e.minX,b:t.z-e.minZ,depth:t.y};case"down":return{a:e.maxX-t.x,b:t.z-e.minZ,depth:-t.y};case"east":return{a:e.maxZ-t.z,b:e.maxY-t.y,depth:t.x};case"south":return{a:t.x-e.minX,b:e.maxY-t.y,depth:t.z};case"west":return{a:t.z-e.minZ,b:e.maxY-t.y,depth:-t.x};case"north":return{a:e.maxX-t.x,b:e.maxY-t.y,depth:-t.z}}}function drawFaceLabel(t,e,a,r,o,n){const i=SIX_FACE_LABELS[e],c=Math.max(1,Math.min(6,Math.floor(o/80))),h=Math.max(1,Math.floor(c/2)),s=a+Math.max(2,Math.floor(n/2)),l=r+Math.max(2,Math.floor(n/2));t.rect(s,l,i[0].length*c+2*h,i.length*c+2*h,"#000000");for(let e=0;e<i.length;e++)for(let a=0;a<i[e].length;a++)"1"===i[e][a]&&t.rect(s+h+a*c,l+h+e*c,c,c,"#ffffff")}function renderIsometric(t,e,a,r){const o=a.isometricCellSize,n=Math.ceil(o/2),i=(e.maxX-e.minX+e.maxZ-e.minZ+2)*o+4,c=(e.maxX-e.minX+e.maxZ-e.minZ+2)*n+(e.maxY-e.minY+2)*o+4,h=Math.max(1,Math.min(1,a.outputSize/Math.max(i,c))),s=new Raster(Math.ceil(i*h),Math.ceil(c*h),a),l=t=>({x:r?e.maxX-t.x:t.x-e.minX,z:r?e.maxZ-t.z:t.z-e.minZ}),d=[...t].sort((t,e)=>{const a=l(t),r=l(e);return a.x+a.z+t.y-(r.x+r.z+e.y)});for(const t of d){const a=l(t),r=(a.x-a.z)*o+i/2,c=(a.x+a.z)*n+(e.maxY-t.y+1)*o;s.voxel(Math.round(r*h),Math.round(c*h),Math.max(2,Math.round(o*h)),colorFor(t.name))}return s.png()}const COLORS={stone:"#777777",cobblestone:"#707070",deepslate:"#4b4b50",dirt:"#855b37",grass_block:"#63913d",sand:"#dbca85",glass:"#a7d9df",water:"#3f76e4",lava:"#e05b22",oak_planks:"#b9915a",spruce_planks:"#765033",birch_planks:"#d9c485",iron_block:"#d7d7d7",gold_block:"#f6c543",diamond_block:"#5ed6c7",redstone_block:"#b21d1d",netherrack:"#823332",quartz_block:"#e9e4dc",obsidian:"#211d2d",white_wool:"#e9e9e9",black_wool:"#1d1d1d",red_wool:"#a12722",blue_wool:"#3549a7",green_wool:"#4c702c",yellow_wool:"#e5c440"};function colorFor(t){const e=t.replace(/^minecraft:/,"");if(COLORS[e])return COLORS[e];for(const[t,a]of Object.entries(COLORS))if(e.includes(t))return a;const a=(0,node_crypto_1.createHash)("md5").update(e).digest();return`#${(90+a[0]%120).toString(16).padStart(2,"0")}${(90+a[1]%120).toString(16).padStart(2,"0")}${(90+a[2]%120).toString(16).padStart(2,"0")}`}class Raster{width;height;data;background;constructor(t,e,a){this.width=t,this.height=e,this.background=parseColor(a.background,a.transparentBackground?0:255),this.data=Buffer.alloc(t*e*4);for(let t=0;t<this.data.length;t+=4)this.data.set(this.background,t)}rect(t,e,a,r,o){for(let n=Math.max(0,e);n<Math.min(this.height,e+r);n++)for(let e=Math.max(0,t);e<Math.min(this.width,t+a);e++)this.pixel(e,n,o)}pixel(t,e,a){t<0||e<0||t>=this.width||e>=this.height||this.data.set(parseColor(a),4*(e*this.width+t))}voxel(t,e,a,r){const o=adjust(r,1.15),n=adjust(r,.78),i=adjust(r,.6),c=Math.ceil(a/2);for(let r=0;r<c;r++)for(let n=-a+r;n<=a-r;n++)this.pixel(t+n,e-c+r,o);for(let r=0;r<a;r++)for(let o=-a+Math.floor(r/2);o<=0;o++)this.pixel(t+o,e+r,n);for(let r=0;r<a;r++)for(let o=0;o<=a-Math.floor(r/2);o++)this.pixel(t+o,e+r,i)}png(){const t=Buffer.alloc((4*this.width+1)*this.height);for(let e=0;e<this.height;e++)t[e*(4*this.width+1)]=0,this.data.copy(t,e*(4*this.width+1)+1,e*this.width*4,(e+1)*this.width*4);const e=Buffer.alloc(13);return e.writeUInt32BE(this.width,0),e.writeUInt32BE(this.height,4),e.set([8,6,0,0,0],8),Buffer.concat([Buffer.from("‰PNG\r\n\n","binary"),chunk("IHDR",e),chunk("IDAT",(0,node_zlib_1.deflateSync)(t)),chunk("IEND",Buffer.alloc(0))])}}function parseColor(t,e=255){const a=/^#?([0-9a-f]{6})$/i.exec(t)?.[1]??"182026";return[parseInt(a.slice(0,2),16),parseInt(a.slice(2,4),16),parseInt(a.slice(4,6),16),e]}function adjust(t,e){const[a,r,o]=parseColor(t);return`#${[a,r,o].map(t=>Math.round(Math.min(255,t*e)).toString(16).padStart(2,"0")).join("")}`}function chunk(t,e){const a=Buffer.from(t),r=Buffer.alloc(4);r.writeUInt32BE(e.length);const o=Buffer.alloc(4);return o.writeUInt32BE(crc32(Buffer.concat([a,e]))>>>0),Buffer.concat([r,a,e,o])}const CRC_TABLE=Array.from({length:256},(t,e)=>{let a=e;for(let t=0;t<8;t++)a=1&a?3988292384^a>>>1:a>>>1;return a>>>0});function crc32(t){let e=4294967295;for(const a of t)e=CRC_TABLE[255&(e^a)]^e>>>8;return(4294967295^e)>>>0}
@@ -0,0 +1,12 @@
1
+ import type { Context } from "koishi";
2
+ /**
3
+ * 尝试调用外部 GPU 渲染器
4
+ *
5
+ * @param command - 外部 GPU 渲染器命令
6
+ * @param input - Litematic 输入文件路径
7
+ * @param output - 渲染输出目录
8
+ * @param timeout - 进程超时时间,单位为毫秒
9
+ * @param logger - 用于报告回退原因的 Koishi 日志器
10
+ * @returns 渲染器正常退出时返回 `true`,失败并记录日志后返回 `false`
11
+ */
12
+ export declare function renderWithGpu(command: string, input: string, output: string, timeout: number, logger: ReturnType<Context["logger"]>, maxOutputBytes?: number): Promise<boolean>;
@@ -0,0 +1 @@
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.renderWithGpu=renderWithGpu;const node_child_process_1=require("node:child_process"),imageValidation_1=require("./imageValidation");async function renderWithGpu(e,r,i,t,o,n=67108864){try{return await new Promise((o,n)=>{const s=(0,node_child_process_1.spawn)(e,["--input",r,"--output",i,"--views","isometric,isometric-reverse"],{shell:!1,windowsHide:!0}),a=setTimeout(()=>{s.kill(),n(new Error("GPU 渲染超时"))},t);s.once("error",n),s.once("exit",e=>0===e?o():n(new Error(`GPU 渲染器退出码:${e}`))),s.once("close",()=>clearTimeout(a))}),await(0,imageValidation_1.validatePngFiles)(i,["isometric.png","isometric-reverse.png"],{maxBytes:n}),!0}catch(e){return o.warn(`GPU 渲染器不可用,回退 CPU:${e instanceof Error?e.message:String(e)}`),!1}}
@@ -0,0 +1,7 @@
1
+ import { type Config } from "../config";
2
+ import type { GpuRenderRequest } from "../gpuAgentProtocol";
3
+ /** 创建与 GPU Agent v2 协议兼容的双视图任务。 */
4
+ export declare function createGpuRenderRequest(filename: string, config: Pick<Config, "outputSize" | "background" | "transparentBackground" | "javaSupersampling" | "isometricRotation" | "isometricSlant" | "isometricFill"> & Partial<Pick<Config, "imageSendLayout">>, source?: {
5
+ group?: string;
6
+ user?: string;
7
+ }, resourcePackProfile?: string, renderConfigSha256?: string): GpuRenderRequest;
@@ -0,0 +1 @@
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.createGpuRenderRequest=createGpuRenderRequest;const node_crypto_1=require("node:crypto"),node_path_1=require("node:path"),config_1=require("../config");function createGpuRenderRequest(e,r,o,t,a){const n=Math.max(128,Math.min(4096,Math.floor(r.outputSize))),i=(e,o,t)=>({id:e,name:o,yaw:t,pitch:r.isometricSlant,zoom:Math.max(.05,r.isometricFill/.95),autoFill:!0,width:n,height:n,background:r.background,transparentBackground:r.transparentBackground,supersampling:Math.max(1,Math.min(4,Math.floor(r.javaSupersampling)))});return{version:2,id:(0,node_crypto_1.randomUUID)(),filename:(0,node_path_1.basename)(e),views:[i("isometric","正二轴测",r.isometricRotation),i("isometric-reverse","反向正二轴测(旋转 180°)",r.isometricRotation+180)],resourcePackProfile:t,imageSendLayout:(0,config_1.normalizeImageSendLayout)(r.imageSendLayout),sourceGroup:o?.group,sourceUser:o?.user,pluginVersion:require("../../package.json").version,renderConfigSha256:a}}
@@ -0,0 +1,18 @@
1
+ export interface PngValidationOptions {
2
+ maxBytes?: number;
3
+ maxWidth?: number;
4
+ maxHeight?: number;
5
+ }
6
+ /** 校验 PNG 签名、IHDR 尺寸和大小,防止外部渲染器返回伪造或超大文件。 */
7
+ export declare function validatePngBuffer(data: Buffer, options?: PngValidationOptions): {
8
+ width: number;
9
+ height: number;
10
+ bytes: number;
11
+ };
12
+ /** 校验输出目录中已经生成的 PNG;不存在的视图交由上层回退逻辑处理。 */
13
+ export declare function validatePngFiles(output: string, names: string[], options?: PngValidationOptions): Promise<{
14
+ width: number;
15
+ height: number;
16
+ bytes: number;
17
+ name: string;
18
+ }[]>;
@@ -0,0 +1 @@
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.validatePngBuffer=validatePngBuffer,exports.validatePngFiles=validatePngFiles;const node_fs_1=require("node:fs"),node_path_1=require("node:path"),PNG_SIGNATURE=Buffer.from([137,80,78,71,13,10,26,10]);function validatePngBuffer(e,t={}){const r=t.maxBytes??67108864,n=t.maxWidth??8192,o=t.maxHeight??8192;if(e.length<24||!e.subarray(0,8).equals(PNG_SIGNATURE))throw new Error("渲染器返回的不是有效 PNG");const a=e.readUInt32BE(16),i=e.readUInt32BE(20);if(!a||!i||a>n||i>o)throw new Error(`渲染器返回了超出尺寸限制的 PNG:${a} × ${i}`);if(e.length>r)throw new Error(`渲染器返回的 PNG 超过 ${r} 字节限制`);return{width:a,height:i,bytes:e.length}}async function validatePngFiles(e,t,r){const n=[];for(const o of t)try{const t=await node_fs_1.promises.readFile((0,node_path_1.join)(e,o));n.push({name:o,...validatePngBuffer(t,r)})}catch(e){if("ENOENT"===e?.code)continue;throw e}return n}
@@ -0,0 +1,11 @@
1
+ import type { Config } from "../config";
2
+ /**
3
+ * 通过文件任务队列请求 Fabric 客户端渲染投影
4
+ *
5
+ * @param input - Litematic 输入文件路径
6
+ * @param output - 渲染输出目录
7
+ * @param config - Java 渲染桥相关配置
8
+ * @returns 渲染桥返回成功结果后解决的 Promise
9
+ * @throws 渲染桥未就绪、材质包不匹配、渲染失败或超时时抛出错误
10
+ */
11
+ export declare function renderWithJavaBridge(input: string, output: string, config: Config): Promise<void>;
@@ -0,0 +1 @@
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.renderWithJavaBridge=renderWithJavaBridge;const node_crypto_1=require("node:crypto"),node_fs_1=require("node:fs"),node_path_1=require("node:path"),jsonFile_1=require("../jsonFile");async function renderWithJavaBridge(e,r,o){if(!o.javaBridgeDirectory.trim())throw new Error("Fabric Java 渲染桥任务目录未配置;使用 java 后端时请填写 javaBridgeDirectory");const a=(0,node_path_1.resolve)(o.javaBridgeDirectory),t=await(0,jsonFile_1.readJson)((0,node_path_1.join)(a,"status.json"));if(!t?.timestamp||Date.now()-t.timestamp>5e3)throw new Error("Minecraft Java 渲染桥未运行;请启动 1.21.1-Fabric 客户端并进入一个世界");if(!t.inWorld)throw new Error("Minecraft Java 渲染桥已启动,但客户端尚未进入世界");const i=t.resourcePacks??[];if(![["XeKr","3.6forMC1.20.2~1.21.5.zip"],["XKRDA","1.19.4~1.21snapshot.zip"]].every(e=>i.some(r=>e.every(e=>r.includes(e)))))throw new Error("Minecraft 客户端没有同时启用 XeKr 红显基础包和 XKRDA 附加包");const n=(0,node_crypto_1.randomUUID)(),s=(0,node_path_1.join)(a,"jobs"),d=(0,node_path_1.join)(a,"results",`${n}.result.json`),c=(0,node_path_1.join)(s,`${n}.job.json`),_=`${c}.tmp`;await node_fs_1.promises.mkdir(s,{recursive:!0}),await node_fs_1.promises.rm(d,{force:!0}),await node_fs_1.promises.writeFile(_,JSON.stringify({id:n,input:(0,node_path_1.resolve)(e),outputDirectory:(0,node_path_1.resolve)(r),resolution:o.javaResolution,supersampling:o.javaSupersampling,rotation:o.isometricRotation,slant:o.isometricSlant,fill:o.isometricFill,background:o.background,transparentBackground:o.transparentBackground})),await node_fs_1.promises.rename(_,c);const p=Date.now()+o.javaRenderTimeout;for(;Date.now()<p;){const e=await(0,jsonFile_1.readJson)(d);if(e){if(await node_fs_1.promises.rm(d,{force:!0}),!e.success)throw new Error(`Minecraft Java 渲染失败:${e.error??"未知错误"}`);return}await new Promise(e=>setTimeout(e,200))}throw new Error(`Minecraft Java 渲染超过 ${Math.round(o.javaRenderTimeout/1e3)} 秒`)}
@@ -0,0 +1,76 @@
1
+ import type { Context } from "koishi";
2
+ import type { Config } from "../config";
3
+ /**
4
+ * 从未知配置值中筛选非空材质包路径
5
+ *
6
+ * @param value - 待解析的配置值
7
+ * @returns 仅包含非空字符串的材质包路径数组
8
+ */
9
+ export declare function resourcePackPaths(value: unknown): string[];
10
+ /**
11
+ * 收集文件绝对路径、大小和修改时间,用于缓存失效判断
12
+ *
13
+ * @param paths - 可能包含无效值的文件路径列表
14
+ * @returns 每个有效路径的文件指纹或缺失标记
15
+ */
16
+ export declare function fingerprintFiles(paths: unknown[]): Promise<({
17
+ path: string;
18
+ size: number;
19
+ modified: number;
20
+ missing?: undefined;
21
+ } | {
22
+ path: string;
23
+ missing: boolean;
24
+ size?: undefined;
25
+ modified?: undefined;
26
+ })[]>;
27
+ /**
28
+ * 判断 Java 主版本是否满足独立渲染器的最低要求
29
+ *
30
+ * @param version - Java 主版本号;检测失败时为 `undefined`
31
+ * @returns 版本为 21 或更高时返回 `true`
32
+ */
33
+ export declare function supportsStandaloneJavaVersion(version: number | undefined): boolean;
34
+ /**
35
+ * 生成独立 Java 渲染进程使用的 JVM 内存和垃圾回收参数
36
+ *
37
+ * @param maxHeapMb - 请求的最大堆内存,单位为 MiB
38
+ * @returns 最大堆被限制在 128 到 32768 MiB 范围内的 JVM 参数
39
+ */
40
+ export declare function standaloneJvmOptions(maxHeapMb: number): string[];
41
+ /**
42
+ * 根据退出码和标准错误判断 Java 进程是否因内存不足而失败
43
+ *
44
+ * @param output - Java 进程的标准错误输出
45
+ * @param exitCode - Java 进程退出码
46
+ * @returns 输出包含常见内存错误或退出码为 137 时返回 `true`
47
+ */
48
+ export declare function isJavaMemoryFailure(output: string, exitCode?: number | null): boolean;
49
+ /**
50
+ * 解析配置或插件内置的 Minecraft 基础资源包路径
51
+ *
52
+ * @param config - 包含资源路径的插件配置
53
+ * @returns 可读取的资源包绝对路径
54
+ * @throws 配置路径和内置资源均不可用时抛出错误
55
+ */
56
+ export declare function resolveMinecraftResources(config: Config): Promise<string>;
57
+ /**
58
+ * 使用独立 Java 进程生成轴测图或六面正交图
59
+ *
60
+ * @param input - Litematic 输入文件路径
61
+ * @param output - 渲染输出目录
62
+ * @param minecraftJarPath - Minecraft JAR 或基础资源包路径
63
+ * @param config - 独立渲染相关配置
64
+ * @param logger - 用于报告内存重试的 Koishi 日志器
65
+ * @param mode - 要生成的视图模式
66
+ * @returns 渲染成功后解决的 Promise
67
+ * @throws 资源缺失、Java 不可用、超时或渲染进程失败时抛出错误
68
+ */
69
+ export declare function renderWithStandalone(input: string, output: string, minecraftJarPath: string, config: Config, logger: ReturnType<Context["logger"]>, mode?: "isometric" | "six-face"): Promise<void>;
70
+ /**
71
+ * 终止插件仍在跟踪的所有独立 Java 渲染进程
72
+ *
73
+ * @param logger - 用于报告回收数量的 Koishi 日志器
74
+ * @returns 全部进程终止后解决的 Promise
75
+ */
76
+ export declare function terminateActiveStandaloneJavaProcesses(logger: ReturnType<Context["logger"]>): Promise<void>;
@@ -0,0 +1 @@
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.resourcePackPaths=resourcePackPaths,exports.fingerprintFiles=fingerprintFiles,exports.supportsStandaloneJavaVersion=supportsStandaloneJavaVersion,exports.standaloneJvmOptions=standaloneJvmOptions,exports.isJavaMemoryFailure=isJavaMemoryFailure,exports.resolveMinecraftResources=resolveMinecraftResources,exports.renderWithStandalone=renderWithStandalone,exports.terminateActiveStandaloneJavaProcesses=terminateActiveStandaloneJavaProcesses;const node_child_process_1=require("node:child_process"),node_fs_1=require("node:fs"),node_path_1=require("node:path"),runtimePaths_1=require("../runtimePaths"),activeStandaloneJavaProcesses=new Set;let standaloneRenderQueue=Promise.resolve();async function acquireStandaloneRenderSlot(){const e=standaloneRenderQueue;let a;return standaloneRenderQueue=new Promise(e=>{a=e}),await e.catch(()=>{}),a}function resourcePackPaths(e){return Array.isArray(e)?e.filter(e=>"string"==typeof e&&Boolean(e.trim())):[]}async function fingerprintFiles(e){return Promise.all(e.filter(e=>"string"==typeof e&&Boolean(e.trim())).map(async e=>{const a=(0,node_path_1.resolve)(e);try{const e=await node_fs_1.promises.stat(a);return{path:a,size:e.size,modified:e.mtimeMs}}catch{return{path:a,missing:!0}}}))}async function resolveStandaloneJavaCommand(e){const a=e.trim();if(a)return a;const n="win32"===process.platform?"java.exe":"java",t=new Set;if(process.env.JAVA_HOME&&t.add((0,node_path_1.join)(process.env.JAVA_HOME,"bin",n)),"win32"===process.platform){const e=new Set([(0,node_path_1.join)(process.env.ProgramFiles??"C:/Program Files","Java"),(0,node_path_1.join)(process.env.ProgramFiles??"C:/Program Files","Eclipse Adoptium"),(0,node_path_1.join)(process.env.ProgramFiles??"C:/Program Files","Microsoft","jdk")]);for(const a of e)try{const e=await node_fs_1.promises.readdir(a,{withFileTypes:!0});for(const o of e)o.isDirectory()&&/(?:^|[-_])21(?:[._-]|$)/.test(o.name)&&t.add((0,node_path_1.join)(a,o.name,"bin",n))}catch{}}t.add("java");for(const e of t)if(supportsStandaloneJavaVersion(await javaMajorVersion(e)))return e;throw new Error("未找到 Java 21+;请安装 Java 21 或更高版本,设置 JAVA_HOME,或填写 standaloneJavaCommand")}async function javaMajorVersion(e){return new Promise(a=>{let n="",t=!1;const o=e=>{t||(t=!0,clearTimeout(i),a(e))},r=(0,node_child_process_1.spawn)(e,["-version"],{shell:!1,windowsHide:!0}),s=e=>{n=(n+String(e)).slice(-2e3)};r.stdout?.on("data",s),r.stderr?.on("data",s),r.once("error",()=>o()),r.once("close",()=>{const e=n.match(/(?:java|openjdk) version "(\d+)/i);o(e?Number(e[1]):void 0)});const i=setTimeout(()=>{r.kill(),o()},5e3)})}function supportsStandaloneJavaVersion(e){return void 0!==e&&e>=21}function standaloneJvmOptions(e){return["-Xms128m",`-Xmx${Math.max(128,Math.min(32768,Math.floor(e)))}m`,"-XX:+UseG1GC","-XX:+UseStringDeduplication","-XX:+ExitOnOutOfMemoryError"]}function isJavaMemoryFailure(e,a){return 137===a||/outofmemoryerror|java heap space|gc overhead limit|cannot reserve enough space|native memory allocation|insufficient memory|malloc failed|os::commit_memory/i.test(e)}async function resolveMinecraftResources(e){const a="string"==typeof e.minecraftJarPath?e.minecraftJarPath.trim():"";if(a&&await exists((0,node_path_1.resolve)(a)))return(0,node_path_1.resolve)(a);const n=(0,node_path_1.resolve)((0,runtimePaths_1.assetPath)("vanilla-resources","Minecraft-26.2-Vanilla-Resources.zip"));if(!await exists(n))throw new Error(`插件内置的 Minecraft 26.2 原版资源包不存在:${n}`);return n}async function renderWithStandalone(e,a,n,t,o,r="isometric"){const s=await acquireStandaloneRenderSlot();try{const s=(0,node_path_1.resolve)(t.standaloneRendererJar||(0,node_path_1.join)(runtimePaths_1.LIB_DIRECTORY,"../assets/standalone-renderer/litematic-standalone-renderer-0.2.8-patch.1.jar"));if(!await exists(s))throw new Error(`独立 Java 渲染器不存在:${s}`);if(!await exists(n))throw new Error(`Minecraft 资源 JAR 不存在:${n}`);for(const e of resourcePackPaths(t.resourcePackPaths))if(!await exists((0,node_path_1.resolve)(e)))throw new Error(`材质包不存在:${e}`);const i=["-Djava.awt.headless=true","-jar",s,"--input",(0,node_path_1.resolve)(e),"--output",(0,node_path_1.resolve)(a),"--minecraft-jar",n,"--resolution",String(t.javaResolution),"--supersampling",String(t.javaSupersampling),"--rotation",String(t.isometricRotation),"--slant",String(t.isometricSlant),"--fill",String(t.isometricFill),"--background",t.background];"six-face"===r&&i.push("--six-face-only","--six-face-resolution",String(t.outputSize),"--six-face-layout",t.sixFaceLayout),t.transparentBackground&&i.push("--transparent-background");for(const e of resourcePackPaths(t.resourcePackPaths))i.push("--resource-pack",(0,node_path_1.resolve)(e));const c=await resolveStandaloneJavaCommand(t.standaloneJavaCommand);for(let e=0;e<=t.standaloneJavaMemoryRestartLimit;e++){const n=0===e?t.standaloneJavaMaxHeapMb:t.standaloneJavaRetryMaxHeapMb,s=await runStandaloneJava(c,[...standaloneJvmOptions(n),...i],t.standaloneRenderTimeout);if(0===s.code)return;const l=isJavaMemoryFailure(s.stderr,s.code);if(l&&e<t.standaloneJavaMemoryRestartLimit){o.warn(`独立 Java 渲染超出 ${t.standaloneJavaMaxHeapMb} MiB 堆内存限制;正在启动全新进程重试(${e+1}/${t.standaloneJavaMemoryRestartLimit})`);const n="six-face"===r?["six-faces.png"]:["isometric.png","isometric-reverse.png"];await Promise.all(n.map(e=>node_fs_1.promises.rm((0,node_path_1.join)(a,e),{force:!0})));continue}const d=l?`;Java 内存不足(最大堆 ${t.standaloneJavaMaxHeapMb} MiB,已重启 ${e} 次)`:"";throw new Error(`独立 Java 渲染器退出码 ${s.code}${d}${s.stderr?`:${s.stderr.trim()}`:""}`)}}finally{s()}}async function runStandaloneJava(e,a,n){return new Promise((t,o)=>{const r=(0,node_child_process_1.spawn)(e,a,{shell:!1,windowsHide:!0});activeStandaloneJavaProcesses.add(r);let s="",i=!1;const c=()=>activeStandaloneJavaProcesses.delete(r);r.stderr?.on("data",e=>{s=(s+String(e)).slice(-6e3)});const l=setTimeout(()=>{i||(i=!0,(async()=>{await terminateStandaloneJavaProcess(r),c(),o(new Error("Standalone Java render timed out; process terminated and memory reclaimed"))})())},n);r.once("error",e=>{i||(i=!0,clearTimeout(l),terminateStandaloneJavaProcess(r),c(),o(e))}),r.once("close",e=>{i||(i=!0,clearTimeout(l),c(),t({code:e,stderr:s}))})})}async function terminateStandaloneJavaProcess(e){const a=e.pid;a&&("win32"===process.platform&&await new Promise(e=>{const n=(0,node_child_process_1.spawn)("taskkill.exe",["/PID",String(a),"/T","/F"],{windowsHide:!0});n.once("close",()=>e()),n.once("error",()=>e())}),null!=e.exitCode||e.killed||e.kill())}async function terminateActiveStandaloneJavaProcesses(e){const a=[...activeStandaloneJavaProcesses];a.length&&(await Promise.all(a.map(e=>terminateStandaloneJavaProcess(e))),e.info(`已终止 ${a.length} 个独立渲染 Java 进程并回收其子进程`))}async function exists(e){try{return await node_fs_1.promises.access(e,node_fs_1.constants.R_OK),!0}catch{return!1}}
@@ -0,0 +1,5 @@
1
+ export interface RenderedImage {
2
+ title: string;
3
+ png: Buffer;
4
+ }
5
+ /** 单次投影渲染产生的图片和展示信息 */
@@ -0,0 +1 @@
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});
@@ -0,0 +1,21 @@
1
+ import type { Context } from "koishi";
2
+ import type { Config } from "../config";
3
+ import type { RenderedImage } from "./types";
4
+ /**
5
+ * 使用 Puppeteer 中的 Three.js 查看器生成两张轴测 PNG
6
+ *
7
+ * @param ctx - 注入 Puppeteer 服务的 Koishi 上下文
8
+ * @param data - 原始 Litematic 文件数据
9
+ * @param config - WebGL 画布和轴测视图配置
10
+ * @returns 正向及反向轴测 PNG
11
+ * @throws 页面加载、投影解析或截图数据解码失败时抛出错误
12
+ */
13
+ export declare function renderWithWebgl(ctx: Context, data: Buffer, config: Config): Promise<RenderedImage[]>;
14
+ /**
15
+ * 解码 WebGL 查看器返回的图像 Data URL
16
+ *
17
+ * @param value - 查看器返回的未知值
18
+ * @returns Base64 解码后的图像数据
19
+ * @throws 返回值不是有效图像 Data URL 时抛出错误
20
+ */
21
+ export declare function decodeDataUrl(value: unknown, maxBytes?: number, maxWidth?: number, maxHeight?: number): Buffer<ArrayBuffer>;
@@ -0,0 +1 @@
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.renderWithWebgl=renderWithWebgl,exports.decodeDataUrl=decodeDataUrl;const node_url_1=require("node:url"),runtimePaths_1=require("../runtimePaths"),imageValidation_1=require("./imageValidation");async function renderWithWebgl(e,t,i){const r=await e.puppeteer.page();try{const e=(0,node_url_1.pathToFileURL)((0,runtimePaths_1.assetPath)("threeviews","index.html")).href;await r.goto(e,{waitUntil:"networkidle0",timeout:i.renderTimeout}),await r.waitForFunction(()=>Boolean(window.litematicViewerAPI&&window.deepslateResources),{timeout:i.renderTimeout});const a=await r.evaluate(async({base64:e,width:t,height:i,quality:r,isometricSquare:a,isometricFill:o,isometricRotation:n,isometricSlant:l})=>{const s=atob(e),c=new Uint8Array(s.length);for(let e=0;e<s.length;e++)c[e]=s.charCodeAt(e);const m=new File([c],"schematic.litematic",{type:"application/octet-stream"});return await window.litematicViewerAPI.loadFromFile(m),window.litematicViewerAPI.renderIsometricViews({width:t,height:i,quality:r,isometricSquare:a,isometricFill:o,isometricRotation:n,isometricSlant:l})},{base64:t.toString("base64"),width:i.webglWidth,height:i.webglHeight,quality:i.webglQuality,isometricSquare:i.isometricSquare,isometricFill:i.isometricFill,isometricRotation:i.isometricRotation,isometricSlant:i.isometricSlant});return[{title:"isometric.png",png:decodeDataUrl(a.isometricView,i.maxRenderedImageBytes,i.webglWidth,i.webglHeight)},{title:"isometric-reverse.png",png:decodeDataUrl(a.reverseIsometricView,i.maxRenderedImageBytes,i.webglWidth,i.webglHeight)}]}finally{await r.close().catch(()=>{})}}function decodeDataUrl(e,t,i,r){if("string"!=typeof e||!e.startsWith("data:image/"))throw new Error("WebGL 渲染器没有返回 PNG 数据");const a=e.indexOf(",");if(a<0)throw new Error("WebGL 渲染器返回了无效图像数据");const o=Buffer.from(e.slice(a+1),"base64");return(0,imageValidation_1.validatePngBuffer)(o,{maxBytes:t,maxWidth:i,maxHeight:r}),o}
@@ -0,0 +1,15 @@
1
+ import type { Config } from "./config";
2
+ export interface ResolvedResourcePackProfile {
3
+ name: string;
4
+ minecraftJarPath: string;
5
+ resourcePackPaths: string[];
6
+ }
7
+ /** 检查 ZIP 中央目录,拒绝路径穿越和明显的解压炸弹。 */
8
+ export declare function validateResourcePackArchive(bytes: Buffer): {
9
+ entries: number;
10
+ uncompressedBytes: number;
11
+ };
12
+ /** 按显式选项、群映射和全局默认值依次选择材质包配置档。 */
13
+ export declare function resolveResourcePackProfile(config: Pick<Config, "minecraftJarPath" | "resourcePackPaths" | "resourcePackProfiles" | "defaultResourcePackProfile" | "groupResourcePackProfiles">, groupId?: string, requestedProfile?: string): ResolvedResourcePackProfile;
14
+ /** 校验并按内容哈希保存 Koishi 控制台上传的 ZIP 材质包。 */
15
+ export declare function saveUploadedResourcePack(filename: unknown, base64: unknown, directory: string): Promise<string>;
@@ -0,0 +1 @@
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.validateResourcePackArchive=validateResourcePackArchive,exports.resolveResourcePackProfile=resolveResourcePackProfile,exports.saveUploadedResourcePack=saveUploadedResourcePack;const node_crypto_1=require("node:crypto"),node_fs_1=require("node:fs"),node_path_1=require("node:path"),RESOURCE_PACK_UPLOAD_LIMIT=268435456,RESOURCE_PACK_MAX_ENTRIES=1e5,RESOURCE_PACK_MAX_UNCOMPRESSED_BYTES=2147483648;function validateResourcePackArchive(e){const r=Math.max(0,e.length-65557);let t=-1;for(let o=e.length-22;o>=r;o--)if(o>=0&&101010256===e.readUInt32LE(o)){t=o;break}if(t<0)return{entries:0,uncompressedBytes:0};const o=e.readUInt16LE(t+10),a=e.readUInt32LE(t+12),n=e.readUInt32LE(t+16);if(o>RESOURCE_PACK_MAX_ENTRIES)throw new Error(`材质包文件数量超过 ${RESOURCE_PACK_MAX_ENTRIES} 项限制`);if(n+a>e.length)throw new Error("材质包 ZIP 中央目录损坏");let s=n,i=0;for(let r=0;r<o;r++){if(s+46>e.length||33639248!==e.readUInt32LE(s))throw new Error("材质包 ZIP 中央目录损坏");const r=e.readUInt32LE(s+20),t=e.readUInt32LE(s+24),o=e.readUInt16LE(s+28),a=e.readUInt16LE(s+30),n=e.readUInt16LE(s+32);if(4294967295===r||4294967295===t)throw new Error("暂不支持 ZIP64 材质包");const c=s+46,f=c+o,E=f+a+n;if(E>e.length)throw new Error("材质包 ZIP 文件名或扩展字段损坏");const P=e.subarray(c,f).toString("utf8");if(P.startsWith("/")||P.startsWith("\\")||P.split(/[\\/]/).some(e=>".."===e)||P.includes("\0"))throw new Error(`材质包包含不安全路径:${P}`);if(i+=t,i>RESOURCE_PACK_MAX_UNCOMPRESSED_BYTES)throw new Error("材质包解压后超过 2 GiB 安全上限");s=E}return{entries:o,uncompressedBytes:i}}function resolveResourcePackProfile(e,r,t){const o=r?[...e.groupResourcePackProfiles??[]].reverse().find(e=>e.groupId?.trim()===r.trim())?.profile?.trim():void 0,a=t?.trim()||o||e.defaultResourcePackProfile?.trim()||"default";if("default"===a)return{name:a,minecraftJarPath:e.minecraftJarPath??"",resourcePackPaths:[...e.resourcePackPaths??[]]};const n=[...e.resourcePackProfiles??[]].reverse().find(e=>e.name?.trim()===a);if(!n)throw new Error(`材质包配置档不存在:${a}`);return{name:a,minecraftJarPath:n.minecraftJarPath?.trim()||e.minecraftJarPath||"",resourcePackPaths:[...n.resourcePackPaths??[]]}}async function saveUploadedResourcePack(e,r,t){if("string"!=typeof e||!/\.zip$/i.test(e))throw new Error("只允许上传 ZIP 材质包");if("string"!=typeof r||!r.length)throw new Error("材质包内容为空");const o=Buffer.from(r,"base64");if(!o.length)throw new Error("材质包内容为空");if(o.length>RESOURCE_PACK_UPLOAD_LIMIT)throw new Error("材质包超过 256 MB 上传上限");if(o.length<4)throw new Error("文件不是有效的 ZIP 材质包");const a=o.readUInt32LE(0);if(![67324752,101010256,134695760].includes(a))throw new Error("文件不是有效的 ZIP 材质包");validateResourcePackArchive(o);const n=(0,node_path_1.basename)(e).replace(/\.zip$/i,"").replace(/[<>:"/\\|?*\x00-\x1f]/g,"_").replace(/[. ]+$/g,"").trim()||"resource-pack",s=(0,node_crypto_1.createHash)("sha256").update(o).digest("hex").slice(0,12),i=(0,node_path_1.join)(t,`${n}-${s}.zip`);return await node_fs_1.promises.mkdir(t,{recursive:!0}),await node_fs_1.promises.writeFile(i,o),i.replace(/\\/g,"/")}
@@ -0,0 +1,8 @@
1
+ /** Compiled library directory, independent of the importing module's nesting. */
2
+ export declare const LIB_DIRECTORY: string;
3
+ /** Package root containing package.json, assets, client, and dist. */
4
+ export declare const PACKAGE_ROOT: string;
5
+ /** Resolve a path below the package's bundled assets directory. */
6
+ export declare function assetPath(...segments: string[]): string;
7
+ /** Plugin version used in cache partitions and diagnostic snapshots. */
8
+ export declare const PLUGIN_VERSION: string;
@@ -0,0 +1 @@
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.PLUGIN_VERSION=exports.PACKAGE_ROOT=exports.LIB_DIRECTORY=void 0,exports.assetPath=assetPath;const node_path_1=require("node:path");function assetPath(...e){return(0,node_path_1.join)(exports.PACKAGE_ROOT,"assets",...e)}exports.LIB_DIRECTORY=__dirname,exports.PACKAGE_ROOT=(0,node_path_1.resolve)(exports.LIB_DIRECTORY,"..");const packageVersion=require("../package.json").version;exports.PLUGIN_VERSION="string"==typeof packageVersion?packageVersion:"unknown";
@@ -0,0 +1,8 @@
1
+ export type SchematicFormat = "litematic" | "sponge" | "structure";
2
+ export interface NormalizedSchematic {
3
+ bytes: Buffer;
4
+ sourceFormat: SchematicFormat;
5
+ filename: string;
6
+ }
7
+ export declare function litematicFilename(filename: string): string;
8
+ export declare function normalizeSchematic(data: Buffer, filename?: string, maxBlocks?: number): NormalizedSchematic;
@@ -0,0 +1 @@
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.litematicFilename=litematicFilename,exports.normalizeSchematic=normalizeSchematic;const node_path_1=require("node:path"),node_zlib_1=require("node:zlib"),litematic_1=require("./litematic"),AIR="minecraft:air",AIR_NAMES=new Set([AIR,"minecraft:cave_air","minecraft:void_air"]),DEFAULT_BLOCK_LIMIT=5e6;function forceTag(e,t){return{forcedNbtTag:!0,type:e,value:t}}function isForcedTag(e){return!0===(0,litematic_1.compoundValue)(e)?.forcedNbtTag}function intPayload(e){const t=Buffer.allocUnsafe(4);return t.writeInt32BE(e),t}function longPayload(e){const t=Buffer.allocUnsafe(8);return t.writeBigInt64BE(BigInt.asIntN(64,BigInt(e))),t}function doublePayload(e){const t=Buffer.allocUnsafe(8);return t.writeDoubleBE(e),t}function stringPayload(e){const t=Buffer.from(e,"utf8");if(t.length>65535)throw new Error("NBT 字符串超过 65535 字节限制");const n=Buffer.allocUnsafe(2);return n.writeUInt16BE(t.length),Buffer.concat([n,t])}function namedTag(e,t,n){return Buffer.concat([Buffer.from([e]),stringPayload(t),n])}function compoundPayload(e){return Buffer.concat([...e,Buffer.from([0])])}function listPayload(e,t){return Buffer.concat([Buffer.from([e]),intPayload(t.length),...t])}function encodeCompound(e){const t=[];for(const[n,a]of Object.entries(e)){const e=encodeValue(a);e&&t.push(namedTag(e.type,n,e.payload))}return compoundPayload(t)}function encodeList(e){if(!e.length)return{type:9,payload:listPayload(0,[])};const t=e.map(encodeValue);if(t.some(e=>!e))throw new Error("NBT 列表包含无法编码的值");const n=t[0].type;if(t.some(e=>e.type!==n))throw new Error("NBT 列表元素类型不一致");return{type:9,payload:listPayload(n,t.map(e=>e.payload))}}function encodeForced(e){if(6===e.type&&"number"==typeof e.value)return{type:6,payload:doublePayload(e.value)};if(9===e.type&&Array.isArray(e.value)){return{type:9,payload:listPayload(6,e.value.map(e=>doublePayload(Number(e))))}}}function encodeValue(e){if(isForcedTag(e))return encodeForced(e);if("string"==typeof e)return{type:8,payload:stringPayload(e)};if("bigint"==typeof e)return{type:4,payload:longPayload(e)};if("number"==typeof e&&Number.isFinite(e))return Number.isInteger(e)&&e>=-2147483648&&e<=2147483647?{type:3,payload:intPayload(e)}:{type:6,payload:doublePayload(e)};if(Buffer.isBuffer(e))return{type:7,payload:Buffer.concat([intPayload(e.length),e])};if(Array.isArray(e))return encodeList(e);const t=(0,litematic_1.compoundValue)(e);return t?{type:10,payload:encodeCompound(t)}:void 0}function integer(e,t){const n=(0,litematic_1.numericValue)(e);if(!Number.isSafeInteger(n))throw new Error(`${t} 必须是整数`);return n}function dimensions(e,t,n){if(e.length<3)throw new Error(`${t} 缺少三轴尺寸`);const a=e.slice(0,3).map((e,n)=>integer(e,`${t}[${n}]`));if(a.some(e=>e<=0))throw new Error(`${t} 必须大于 0`);const o=a.reduce((e,t)=>e*t,1),r=Number.isSafeInteger(n)&&n>0?n:5e6;if(!Number.isSafeInteger(o)||o>r)throw new Error(`投影方块数或区域体积超过 ${r.toLocaleString("en-US")} 限制`);return a}function vector(e,t,n){if(!Array.isArray(e))return n;if(e.length<3)throw new Error(`${t} 缺少三轴坐标`);return e.slice(0,3).map((e,n)=>integer(e,`${t}[${n}]`))}function parseStateString(e){const t=e.trim(),n=t.indexOf("["),a=(n<0?t:t.slice(0,n)).trim();if(!a)throw new Error("Sponge 调色板包含空方块名称");if(n<0)return{Name:a};if(!t.endsWith("]"))throw new Error(`无法解析方块状态:${t}`);const o={},r=t.slice(n+1,-1);for(const e of r?r.split(","):[]){const t=e.indexOf("=");if(t<=0||t===e.length-1)throw new Error(`无法解析方块状态属性:${e}`);o[e.slice(0,t).trim()]=e.slice(t+1).trim()}return Object.keys(o).length?{Name:a,Properties:o}:{Name:a}}function paletteFromSponge(e){const t=(0,litematic_1.compoundValue)(e);if(!t||!Object.keys(t).length)throw new Error("Sponge Schematic 缺少 Palette");const n=new Set;let a=-1;const o=[];for(const[e,r]of Object.entries(t)){const t=integer(r,`Palette.${e}`);if(t<0||t>5e6)throw new Error(`无效的调色板索引:${t}`);if(n.has(t))throw new Error(`Sponge 调色板索引重复:${t}`);n.add(t),a=Math.max(a,t),o.push([e,t])}const r=Array.from({length:a+1},()=>({Name:AIR}));for(const[e,t]of o)r[t]=parseStateString(e);return{palette:r,used:n}}function decodeVarInts(e,t,n){const a=new Array(t);let o=0;for(let r=0;r<t;r++){let t=0,i=0;for(;;){if(o>=e.length)throw new Error("Sponge BlockData 在体积填满前结束");const n=e[o++];if(t+=(127&n)*2**i,!(128&n))break;if(i+=7,i>28)throw new Error("Sponge BlockData 包含过长 VarInt")}if(!Number.isSafeInteger(t)||!n.has(t))throw new Error(`Sponge BlockData 引用了不存在的调色板索引:${t}`);a[r]=t}if(o!==e.length)throw new Error("Sponge BlockData 包含多余数据");return a}function stringValue(e,t=""){return"string"==typeof e&&e.trim()?e.trim():t}function sourceMetadata(e){const t=(0,litematic_1.compoundValue)(e.Metadata)??{};return{author:stringValue(t.Author??e.Author,"未知"),createdAt:(0,litematic_1.numericValue)(t.Date??t.TimeCreated)??0,dataVersion:integerOrDefault(e.DataVersion??e.MinecraftDataVersion,3465)}}function integerOrDefault(e,t){const n=(0,litematic_1.numericValue)(e);return Number.isInteger(n)&&n>=-2147483648&&n<=2147483647?n:t}function normalizeBlockEntity(e,t){const n=(0,litematic_1.compoundValue)(e);if(!n)return;const a=(0,litematic_1.compoundValue)(n.Data)??(0,litematic_1.compoundValue)(n.nbt)??n,o=vector(n.Pos??n.pos,"方块实体坐标",t??[0,0,0]),r=stringValue(a.id??n.Id??n.id);return{...a,...r?{id:r}:{},x:o[0],y:o[1],z:o[2]}}function normalizeEntity(e){const t=(0,litematic_1.compoundValue)(e);if(!t)return;const n=(0,litematic_1.compoundValue)(t.Data)??(0,litematic_1.compoundValue)(t.nbt)??t,a=t.Pos??t.pos;if(!Array.isArray(a)||a.length<3)return;const o=a.slice(0,3).map(e=>Number((0,litematic_1.numericValue)(e)));if(o.some(e=>!Number.isFinite(e)))return;const r=stringValue(n.id??t.Id??t.id);return{...n,...r?{id:r}:{},Pos:forceTag(9,o)}}function convertSponge(e,t){const n=(0,litematic_1.compoundValue)(e.Schematic)??e,a=(0,litematic_1.compoundValue)(n.Blocks),o=dimensions([n.Width,n.Height,n.Length],"Sponge Schematic 尺寸",t),r=o[0]*o[1]*o[2],{palette:i,used:c}=paletteFromSponge(a?.Palette??n.Palette),l=a?.Data??n.BlockData;if(!Buffer.isBuffer(l))throw new Error("Sponge Schematic 缺少 BlockData");const s=a?.BlockEntities??n.BlockEntities??n.TileEntities,u=n.Entities;return{size:o,offset:vector(n.Offset,"Sponge Schematic Offset",[0,0,0]),palette:i,states:decodeVarInts(l,r,c),blockEntities:Array.isArray(s)?s.map(e=>normalizeBlockEntity(e)).filter(e=>Boolean(e)):[],entities:Array.isArray(u)?u.map(normalizeEntity).filter(e=>Boolean(e)):[],...sourceMetadata(n)}}function stateFromVanilla(e){const t=(0,litematic_1.compoundValue)(e),n=stringValue(t?.Name);if(!t||!n)throw new Error("原版结构调色板包含无效方块状态");const a=(0,litematic_1.compoundValue)(t.Properties),o=a?Object.fromEntries(Object.entries(a).filter(e=>"string"==typeof e[1])):void 0;return o&&Object.keys(o).length?{Name:n,Properties:o}:{Name:n}}function convertStructure(e,t){const n=dimensions(Array.isArray(e.size)?e.size:[],"原版结构尺寸",t),a=Array.isArray(e.palette)?e.palette:Array.isArray(e.palettes)&&Array.isArray(e.palettes[0])?e.palettes[0]:void 0;if(!a?.length)throw new Error("原版结构缺少 palette");const o=a.map(stateFromVanilla);let r=o.findIndex(e=>AIR_NAMES.has(e.Name));const i=r<0?1:0;r<0&&(o.unshift({Name:AIR}),r=0);const c=new Array(n[0]*n[1]*n[2]).fill(r),l=[];if(!Array.isArray(e.blocks))throw new Error("原版结构缺少 blocks");for(const t of e.blocks){const e=(0,litematic_1.compoundValue)(t);if(!e)throw new Error("原版结构包含无效 blocks 条目");const o=vector(e.pos,"原版结构方块坐标",[0,0,0]);if(o.some((e,t)=>e<0||e>=n[t]))throw new Error(`原版结构方块坐标越界:${o.join(",")}`);const r=integer(e.state,"原版结构方块状态");if(r<0||r>=a.length)throw new Error(`原版结构引用了不存在的调色板索引:${r}`);if(c[o[0]+o[2]*n[0]+o[1]*n[0]*n[2]]=r+i,(0,litematic_1.compoundValue)(e.nbt)){const t=normalizeBlockEntity(e,o);t&&l.push(t)}}return{size:n,offset:[0,0,0],palette:o,states:c,blockEntities:l,entities:Array.isArray(e.entities)?e.entities.map(normalizeEntity).filter(e=>Boolean(e)):[],...sourceMetadata(e)}}function packBlockStates(e,t){const n=Math.max(2,Math.ceil(Math.log2(Math.max(1,t)))),a=Array.from({length:Math.ceil(e.length*n/64)},()=>0n),o=(1n<<BigInt(n))-1n;for(let t=0;t<e.length;t++){const r=BigInt(e[t])&o,i=t*n,c=Math.floor(i/64),l=i%64;a[c]=BigInt.asUintN(64,a[c]|r<<BigInt(l)),l+n>64&&(a[c+1]=BigInt.asUintN(64,a[c+1]|r>>BigInt(64-l)))}return Buffer.concat([intPayload(a.length),...a.map(e=>longPayload(e))])}function palettePayload(e){return listPayload(10,e.map(e=>encodeCompound({Name:e.Name,...e.Properties?{Properties:e.Properties}:{}})))}function listOfCompounds(e){return listPayload(10,e.map(encodeCompound))}function coordinateCompound(e){return encodeCompound({x:e[0],y:e[1],z:e[2]})}function createLitematic(e,t){const n=e.states.reduce((t,n)=>t+(AIR_NAMES.has(e.palette[n]?.Name??AIR)?0:1),0),a=compoundPayload([namedTag(8,"Name",stringPayload((0,node_path_1.basename)(t,(0,node_path_1.extname)(t)).slice(0,200)||"schematic")),namedTag(8,"Author",stringPayload(e.author)),namedTag(8,"Description",stringPayload("Converted by koishi-plugin-litematic-renderer")),namedTag(3,"RegionCount",intPayload(1)),namedTag(4,"TimeCreated",longPayload(e.createdAt)),namedTag(4,"TimeModified",longPayload(e.createdAt)),namedTag(3,"TotalBlocks",intPayload(n)),namedTag(3,"TotalVolume",intPayload(e.states.length)),namedTag(10,"EnclosingSize",coordinateCompound(e.size))]),o=compoundPayload([namedTag(10,"Position",coordinateCompound(e.offset)),namedTag(10,"Size",coordinateCompound(e.size)),namedTag(9,"BlockStatePalette",palettePayload(e.palette)),namedTag(12,"BlockStates",packBlockStates(e.states,e.palette.length)),namedTag(9,"TileEntities",listOfCompounds(e.blockEntities)),namedTag(9,"Entities",listOfCompounds(e.entities)),namedTag(9,"PendingBlockTicks",listPayload(0,[])),namedTag(9,"PendingFluidTicks",listPayload(0,[]))]),r=compoundPayload([namedTag(3,"Version",intPayload(6)),namedTag(3,"SubVersion",intPayload(1)),namedTag(3,"MinecraftDataVersion",intPayload(e.dataVersion)),namedTag(10,"Metadata",a),namedTag(10,"Regions",compoundPayload([namedTag(10,"Converted",o)]))]);return(0,node_zlib_1.gzipSync)(Buffer.concat([Buffer.from([10]),stringPayload(""),r]),{level:9})}function litematicFilename(e){const t=(0,node_path_1.basename)(e||"schematic"),n=(0,node_path_1.extname)(t);return`${n?t.slice(0,-n.length):t}.litematic`}function normalizeSchematic(e,t="schematic.litematic",n){const a=(0,litematic_1.readNbtRoot)(e);if((0,litematic_1.compoundValue)(a.Regions))return{bytes:e,sourceFormat:"litematic",filename:litematicFilename(t)};const o=(0,litematic_1.compoundValue)(a.Schematic)??a;if(null!=(0,litematic_1.numericValue)(o.Width)&&null!=(0,litematic_1.numericValue)(o.Height)&&null!=(0,litematic_1.numericValue)(o.Length))return{bytes:createLitematic(convertSponge(a,n),t),sourceFormat:"sponge",filename:litematicFilename(t)};if(Array.isArray(a.size)&&(Array.isArray(a.palette)||Array.isArray(a.palettes)))return{bytes:createLitematic(convertStructure(a,n),t),sourceFormat:"structure",filename:litematicFilename(t)};throw new Error("文件不是受支持的 Litematic、Sponge Schematic 或原版结构 NBT")}