diff --git a/README.md b/README.md index dcda9d15..88387f99 100644 --- a/README.md +++ b/README.md @@ -91,6 +91,7 @@ The MiniMax Code Agent communicates through the host MCP client. Business reques | [Quota Bottle](plugins/7723qqq/quota-bottle/) | An octopus-shaped glass bottle that floats on your desktop and shows the remaining Token Plan quota from a login you configure yourself, with the liquid level and opacity following the remaining share, and a device-code login plus an opt-in local token-usage estimate as fallbacks | [7723qqq](https://github.com/7723qqq) | | [Site QA](plugins/lonelyguy-se1/site-qa/) | Check local HTML/robots/sitemap for SEO and accessibility gaps, then ask the agent to fix them (Mini App + skill/CLI). Requires MiniMax Code 3.1.6 or later | [LonelyGuySE1](https://github.com/LonelyGuy-SE1) | | [H3-Image-Executor](plugins/liddalidd/h3-image-executor/) | Turn one sentence into verified 4K images: it plans the shot list, searches for reference images, generates, reviews each image by looking at it, corrects colour cast, runs a bounded fix loop and delivers the result with an acceptance report; multi-image runs generate a character sheet first so the same subject stays the same subject. Needs an H3-Image endpoint and key you configure yourself. Requires MiniMax Code 3.1.6 or later | [liddalidd](https://github.com/liddalidd) | +| [GML Practice Log · Project Manager](plugins/basetier-gml/miniapp-44928b90-e36d-46c5-9f7e-4d3d5ac5cda0/) | Manage many GameMaker (GML) practice notebooks inside MiniMax Code: each project is its own save file with an API library, ordered code carriers, a recycle bin and backups; a hosted MCP server lets the Agent list, read and search your notes | [basetier-gml](https://github.com/basetier-gml) |
Preview: Cutline diff --git a/README.zh-CN.md b/README.zh-CN.md index 223aae0b..83636bf5 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -91,6 +91,7 @@ MiniMax Code Agent 通过宿主 MCP 客户端与 MiniApp 协作。业务请求 | [额度瓶](plugins/7723qqq/quota-bottle/README.zh-CN.md) | 一只悬浮在桌面上的章鱼形玻璃瓶,用你自己配置的登录读取 Token Plan 剩余额度;液面与透明度按剩余占比走,拿不到实时额度时回退到设备码登录或手填总额与可选的本机本月用量 | [7723qqq](https://github.com/7723qqq) | | [Site QA](plugins/lonelyguy-se1/site-qa/) | 检查本地 HTML/robots/sitemap 的 SEO / 无障碍问题,再让 Agent 修复(Mini App + skill/CLI)。需要 MiniMax Code 3.1.6 或更高版本(说明文档为英文) | [LonelyGuySE1](https://github.com/LonelyGuy-SE1) | | [H3-Image-Executor](plugins/liddalidd/h3-image-executor/README.zh-CN.md) | 把一句话需求跑成经过校验的 4K 图片:规划分镜、检索参考图、生成、看图评审、色偏校正、有限次修正,最后交付图片和验收报告;多图任务会先生成角色设定图锁定主体外观。需要自备 H3-Image 接口地址和 Key。需要 MiniMax Code 3.1.6 或更高版本 | [liddalidd](https://github.com/liddalidd) | +| [GML 练习记录 · 项目存档管理器](plugins/basetier-gml/miniapp-44928b90-e36d-46c5-9f7e-4d3d5ac5cda0/) | 在 MiniMax Code 里管理多本 GameMaker(GML)练习笔记:每个项目一份独立存档,带 API 库、按顺序排列的代码载体、回收站与备份;随包附带的托管 MCP 让 Agent 直接列出、读取和检索你的笔记 | [basetier-gml](https://github.com/basetier-gml) |
预览:Cutline diff --git a/plugins/basetier-gml/miniapp-44928b90-e36d-46c5-9f7e-4d3d5ac5cda0/.minimax-plugin/plugin.json b/plugins/basetier-gml/miniapp-44928b90-e36d-46c5-9f7e-4d3d5ac5cda0/.minimax-plugin/plugin.json new file mode 100644 index 00000000..b01f75e8 --- /dev/null +++ b/plugins/basetier-gml/miniapp-44928b90-e36d-46c5-9f7e-4d3d5ac5cda0/.minimax-plugin/plugin.json @@ -0,0 +1,22 @@ +{ + "schemaVersion": 1, + "name": "miniapp-44928b90-e36d-46c5-9f7e-4d3d5ac5cda0", + "displayName": "GML 练习记录", + "version": "1.1.0", + "description": "GameMaker(GML)代码学习笔记:多本互不干扰的练习存档,打卡记录、API 库与代码载体随写随存,并能全文搜索回溯。", + "author": "basetier-gml", + "icon": "icon.png", + "category": "Education", + "exampleQueries": [ + "打开我的 GML 练习记录。", + "新建一本 GML 学习笔记。", + "搜索我的 GML 练习里关于云层特效的代码。" + ], + "apps": [], + "mcpServers": [ + "servers.mcp.json" + ], + "skills": [ + "skills/gml-practice-notes/SKILL.md" + ] +} diff --git a/plugins/basetier-gml/miniapp-44928b90-e36d-46c5-9f7e-4d3d5ac5cda0/LICENSE b/plugins/basetier-gml/miniapp-44928b90-e36d-46c5-9f7e-4d3d5ac5cda0/LICENSE new file mode 100644 index 00000000..6a6f1e89 --- /dev/null +++ b/plugins/basetier-gml/miniapp-44928b90-e36d-46c5-9f7e-4d3d5ac5cda0/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 basetier-gml + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/plugins/basetier-gml/miniapp-44928b90-e36d-46c5-9f7e-4d3d5ac5cda0/README.md b/plugins/basetier-gml/miniapp-44928b90-e36d-46c5-9f7e-4d3d5ac5cda0/README.md new file mode 100644 index 00000000..a49b7581 --- /dev/null +++ b/plugins/basetier-gml/miniapp-44928b90-e36d-46c5-9f7e-4d3d5ac5cda0/README.md @@ -0,0 +1,140 @@ +# GML 练习记录 · 项目存档管理器 + +GameMaker(GML)代码学习笔记的 Mini App:**多本互不干扰的练习存档**,每本都能独立打卡、登记 API 库、按顺序记录代码载体,随写随存。 + +把「Gml代码练习记录」打卡网页版搬进 MiniMax Code:数据从浏览器的 localStorage 换成了 Mini App 的数据目录(本机的 `.json` 文件),项目之间彻底隔离,回收站和备份也都在。 + +--- + +## 功能 + +**项目管理器** + +- 多本练习笔记并存,互不干扰;每一本是一个独立的 `.json` 存档文件 +- 项目列表每次从磁盘重读,删文件/改文件都能被识别 +- 回收站:删除的项目进回收站,`trash-index.json` 记着清单,随时恢复 +- 导出全部 / 导出单个项目 / 导入存档 +- 界面语言中英双语,跟随 MiniMax Code 的界面语言 + +**练习记录(打卡网页版)** + +- 打卡记录:题目要求 + 提示 + 按顺序排列的代码载体(操作描述 / 脚本 / 对象) +- API 库:代码名 + 一句话介绍 + 参数列表,记录按引用关联 +- 打卡日历、每日目标、连续打卡天数 +- 一键分享打卡记录长图 + +**版本管理** + +- 内置一份网页版副本,离线可用 +- 「抓取最新版本」从来源地址重新下载网页版并缓存到数据目录 +- 「恢复内置版」删掉缓存,回到内置副本 +- 抓取版与内置版都可用,存档数据始终写在数据目录里 + +--- + +## 安装 + +### 从 Git 仓库导入(推荐) + +MiniMax Code v3.1.11 起支持从公开 Git 仓库导入 Mini App: + +1. 插件市场点「创建」→ 选「Mini App」分类下的「从 Git 仓库导入」 +2. 填仓库地址(单个包就填插件子目录的链接): + + ``` + https://github.com/MiniMax-AI/MiniMax-Code-MiniApps/tree/main/plugins/basetier-gml/miniapp-44928b90-e36d-46c5-9f7e-4d3d5ac5cda0 + ``` + +3. 点「预览」核对包名、版本、来源目录和声明的权限 → 「导入」 +4. 在插件管理里确认已启用,再正常打开 + +> 不要把整个社区仓库当作一个 Mini App 导入。 + +### 手动安装 + +把整个插件目录(**包括隐藏的 `.minimax-plugin/`**)复制到: + +``` +/plugins/miniapp-44928b90-e36d-46c5-9f7e-4d3d5ac5cda0/ +``` + +默认是 `~/.minimax/plugins/`。重启 MiniMax Code,确认插件已识别并启用。 + +### 从 ZIP 安装 + +把目录或 ZIP 直接交给 Agent,让它按成品包流程发布即可。 + +--- + +## Data & access + +数据与服务访问范围: + +**本机数据(只写不读,除用户自己的存档外不碰任何其他文件)** + +| 位置 | 内容 | +| --- | --- | +| `/GML-Saves/` | 练习存档 `<名称>..json` + `save-index.json` | +| `/GML-Trash/` | 回收站 `.<删除时间>.json` + `trash-index.json` | +| `/GML-App/` | 抓取下来的网页版 `app.html` + `app-meta.json` | +| `/exports/` | 用户导出的备份文件 | + +`` 由宿主注入,随 Mini App 数据目录走。**所有写入都是原子写**(同目录临时文件 → rename),宿主强制结束进程也不会留下半个文件。 + +**网络访问** + +只有一处:用户在页面上主动点「抓取最新版本」时,Node 服务会去下载网页版。 + +- 默认来源:`https://basetier-gml.github.io/gml-practice-log/` +- 来源地址可在页面上改 +- 下载有大小上限和超时;失败时保留原来的版本,应用照常可用 + +**不上传任何数据。** 练习内容、API 库、存档文件全部留在本机,不发往任何服务器。 + +**不申请** Connector、Agent 运行、设备、导航等任何额外权限。 + +--- + +## Agent 能做什么 + +包里带了一个托管 MCP server `gml-notes` 和一个 Skill,Agent 可以直接查你的笔记: + +| 工具 | 用途 | +| --- | --- | +| `list_projects` | 列出所有练习笔记(记录数、API 数、打卡天数) | +| `get_project` | 读一本笔记的完整内容 | +| `search_notes` | 跨所有笔记搜索题目、提示、代码、API 介绍 | +| `list_api_library` | 汇总 API 库(代码名、介绍、参数) | +| `create_project` | 新建一本空白笔记 | +| `export_backup` | 导出全部存档为 JSON 备份 | + +边界说明:练习记录的**正文**(题目、提示、代码载体)只能在页面里编辑——那是浏览器侧的写入通道,托管 MCP 不暴露写接口。所以 Agent 负责读、搜、汇总、整理,以及新建笔记和导出备份;要落进某条记录的具体内容,Agent 会把整理好的版本给你,由你粘到页面里。 + +--- + +## Tested environment + +测试环境: + +- MiniMax Code **v3.1.16**(Windows x64)—— 完整功能验证 +- Mini App 运行时(Node 进程):`node:http` + 内置模块,无第三方依赖,无构建步骤 +- 网页版:`bzhm-1cb4mgb`(来源 `basetier-gml/gml-practice-log`,MIT) + +已验证:内置版与抓取版都能正常打开项目、读写存档;API 介绍随存档落盘并在重新载入后保留;退出前的「要不要导出存档」提醒在 Mini App 里被屏蔽(存档由宿主自动落盘,不需要用户手动导出);存档文件在完全刷新、重启服务后逐字节一致。 + +--- + +## 已知限制 + +- 练习记录正文只能在本机页面上编辑,Agent 不能直接写入(见上文边界说明) +- 「抓取最新版本」依赖网络;离线时请用内置版 +- 网页版页面被嵌在 Mini App 的 iframe 里,因此网页菜单里的「存档 / 读档 / 清空缓存 / 新手教程 / 切换语言」入口被隐藏,由项目管理器统一接管 +- 打卡分享长图依赖浏览器的截图能力,在部分嵌入环境下可能不可用 + +--- + +## 许可与致谢 + +本插件代码以 MIT 许可发布,见 [LICENSE](LICENSE)。 + +内置的练习应用网页版(`miniapp/client/core/app.html`)来自 [basetier-gml/gml-practice-log](https://github.com/basetier-gml/gml-practice-log),同为 MIT 许可,版权归原作者所有。 diff --git a/plugins/basetier-gml/miniapp-44928b90-e36d-46c5-9f7e-4d3d5ac5cda0/icon.png b/plugins/basetier-gml/miniapp-44928b90-e36d-46c5-9f7e-4d3d5ac5cda0/icon.png new file mode 100644 index 00000000..c9fc5c53 Binary files /dev/null and b/plugins/basetier-gml/miniapp-44928b90-e36d-46c5-9f7e-4d3d5ac5cda0/icon.png differ diff --git a/plugins/basetier-gml/miniapp-44928b90-e36d-46c5-9f7e-4d3d5ac5cda0/miniapp/client/core/app.html b/plugins/basetier-gml/miniapp-44928b90-e36d-46c5-9f7e-4d3d5ac5cda0/miniapp/client/core/app.html new file mode 100644 index 00000000..d1250557 --- /dev/null +++ b/plugins/basetier-gml/miniapp-44928b90-e36d-46c5-9f7e-4d3d5ac5cda0/miniapp/client/core/app.html @@ -0,0 +1,12009 @@ + + + + + +Gml代码练习记录 + + + + + + + + + + + + +
+
+
+ + + +
+
+
+ 编程新手 + +
+

Gml代码练习记录

+ +
+ +
+
+ +
+ + +
+
+ +

练习记录

+ 点一次 = 一次打卡 + +
+ + +
+ +
+
+
今日合计
+
0次
+
+
+
已挑战次数
+
0次
+
+
+
每日目标
+
+ + 次 +
+
+
+ +
+
今日进度 0 / 5
+ + + +
今日打卡明细点一下打开练习过程
+
+
今天还没有记录。
点上面的按钮完成第一次打卡。
+
+ + + +
+ + +
+
+ +

API 库

+ 共 0 个 + +
+ +
+
+
API 库还是空的。
点右上角「新建 API」把常用 API 存进来,
练习时就能直接引用,不用重复写。
+

练习题要求的 API 和代码载体里的 api,都从库里引用。

+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + + + + + + + + + + + + + + diff --git a/plugins/basetier-gml/miniapp-44928b90-e36d-46c5-9f7e-4d3d5ac5cda0/miniapp/client/core/boot.js b/plugins/basetier-gml/miniapp-44928b90-e36d-46c5-9f7e-4d3d5ac5cda0/miniapp/client/core/boot.js new file mode 100644 index 00000000..9ed84c5c --- /dev/null +++ b/plugins/basetier-gml/miniapp-44928b90-e36d-46c5-9f7e-4d3d5ac5cda0/miniapp/client/core/boot.js @@ -0,0 +1,414 @@ +/* ============================================================ + GML 项目存档管理器 —— 网页内注入层(运行在 iframe 里) + 1. 用「当前存档槽」的数据虚拟出 window.localStorage / sessionStorage + 2. 网页每次自动存档(setItem / removeItem / clear)都回传宿主,由管理器落盘 + 3. 提供命令通道,让宿主调用网页自带的 export / import 存档接口 + ============================================================ */ +(function(){ + 'use strict'; + var B = window.__GML_PM_BOOT__ || { saveId:'', data:{} }; + var TAG = '__gml_pm'; + var LANG = (B.lang === 'en') ? 'en' : 'zh'; + var ls = Object.create(null); /* 当前存档槽的 localStorage 镜像 */ + var ss = Object.create(null); /* sessionStorage 不持久化 */ + Object.keys(B.data || {}).forEach(function(k){ ls[k] = String(B.data[k]); }); + + /* 界面语言由管理器统一决定:在网页任何脚本启动之前,把 lang 写进虚拟 settings。 + 网页的 detectLang() 优先级最高就读这里,所以打开项目时不会先闪一下中文/英文。 */ + (function(){ + var KEY = 'gml-practice-log-v2:settings'; + try{ + var o = ls[KEY] ? JSON.parse(ls[KEY]) : {}; + if(!o || typeof o !== 'object') o = {}; + o.lang = LANG; + ls[KEY] = JSON.stringify(o); + }catch(e){ + ls[KEY] = JSON.stringify({ dailyGoal:5, lang:LANG, carrierColors:{}, customTypes:[] }); + } + })(); + + var timer = null, dirty = false, seq = 0; + function has(m, k){ return Object.prototype.hasOwnProperty.call(m, k); } + + /* 注:早期版本这里有一层「API 介绍(desc)持久化补丁」,用来兜住网页版 + partApi() 落盘时丢掉 desc 的老 bug。现在内置版与抓取版都已自行修复 + (out[id] = { code, desc, params }),补丁纯属冗余,且每 2 秒拉一次 + export 存档,开销不值当,故已撤掉。 */ + + function snap(){ + var o = {}, ks = Object.keys(ls); + for(var i=0;i= 0 && i < ks.length) ? ks[i] : null; }; + if(p === 'getItem') return function(k){ k = String(k); return h(k) ? m[k] : null; }; + if(p === 'setItem') return function(k, v){ m[String(k)] = String(v); onChange(); }; + if(p === 'removeItem') return function(k){ delete m[String(k)]; onChange(); }; + if(p === 'clear') return function(){ Object.keys(m).forEach(function(k){ delete m[k]; }); onChange(); }; + if(typeof p === 'string' && h(p)) return m[p]; + return undefined; + }, + set: function(t, p, v){ if(typeof p === 'string'){ m[p] = String(v); onChange(); } return true; }, + has: function(t, p){ return typeof p === 'string' && h(p); }, + deleteProperty: function(t, p){ if(typeof p === 'string') delete m[p]; onChange(); return true; }, + ownKeys: function(){ return Object.keys(m); }, + getOwnPropertyDescriptor: function(t, p){ + if(typeof p === 'string' && h(p)) + return { value:m[p], writable:true, enumerable:true, configurable:true }; + return undefined; + } + }); + } + var LS = makeStore(ls, mark); + var SS = makeStore(ss, function(){}); + function def(name, val){ + try{ Object.defineProperty(window, name, { value:val, configurable:true, writable:true }); } + catch(e){ try{ window[name] = val; }catch(e2){} } + } + def('localStorage', LS); + def('sessionStorage', SS); + + /* ---- 宿主 ⇄ 网页的命令通道 ---- */ + function runCmd(d){ + var tries = 0; + (function attempt(){ + if(window.gml && typeof window.gml.cmd === 'function'){ + var r; + try{ r = window.gml.cmd(d.name, d.args || {}); } + catch(e){ post('cmd-result', { id:d.id, ok:false, error:String((e && e.message) || e) }); return; } + Promise.resolve(r).then(function(v){ post('cmd-result', { id:d.id, ok:true, result:v }); }) + .catch(function(e){ post('cmd-result', { id:d.id, ok:false, error:String((e && e.message) || e) }); }); + return; + } + if(tries++ < 240) setTimeout(attempt, 50); + else post('cmd-result', { id:d.id, ok:false, error:'网页接口未就绪' }); + })(); + } + window.addEventListener('message', function(e){ + var d = e.data; + if(!d || d[TAG] !== true || d.dir !== 'to-app') return; + if(d.type === 'flush'){ flush(); post('cmd-result', { id:d.id, ok:true, result:{ flushed:true } }); return; } + if(d.type === 'cmd'){ runCmd(d); return; } + if(d.type === 'ping'){ post('pong', { id:d.id }); return; } + }); + window.addEventListener('pagehide', flush); + window.addEventListener('beforeunload', flush); + + /* ---- 屏蔽网页版的「退出前要不要导出存档」提醒 ---- + 网页在 beforeunload 里做两件事: + ① e.preventDefault() + e.returnValue → 浏览器原生「离开此网站?」提示 + ② showExitModal() → 网页自己的 #exitModal 弹层 + 在 Chrome 里 iframe 挂了 beforeunload 还会连带拦住整个页面的关闭/刷新, + 管理器里关掉项目就会卡住用户。 + + 存档本来已经由宿主自动落盘,不需要这个提醒 ⇒ 这里屏蔽掉。 + 做法(不改网页本体,内置版和抓取回来的网页版都生效): + · beforeunload 用捕获阶段抢先跑,把 preventDefault / returnValue 摆平, + 浏览器就不会弹原生提示(网页自己的处理器仍会跑,flushPendingSave 不受影响); + · 再用 MutationObserver 盯着 #exitModal 的 open 类,一加上就撤掉。 */ + window.addEventListener('beforeunload', function(e){ + /* Blink 的 legacy setter:event.returnValue = 任何非 "false" 的值都等价于调用 + preventDefault(),会直接拉起浏览器原生「离开此网站?」框。 + ⇒ 先用 defineProperty 把 returnValue 换成普通数据属性,绕开 setter; + 网页后面写 e.returnValue = '' 只落到这个数据属性上,不再有任何副作用。 + ⇒ 绝不能先写 e.returnValue = xxx,那一行自己就会把 canceled 置位。 */ + try{ + Object.defineProperty(e, 'returnValue', { value: '', writable: true, configurable: true }); + }catch(err){} + try{ + Object.defineProperty(e, 'preventDefault', { value: function(){}, writable: true, configurable: true }); + }catch(err){} + }, true); + function ready(){ post('ready'); } + if(document.readyState === 'loading') document.addEventListener('DOMContentLoaded', ready); + else ready(); + setTimeout(flush, 400); +})(); + +/* ============================================================ + 界面接管:屏蔽网页菜单里会和「项目存档管理器」冲突的入口 + 存档 / 读档 / 清空缓存 / 新手教程 / 切换到 English + 只隐藏 + 拦截点击,不删除 DOM —— 网页脚本会直接给这些元素绑事件, + 删掉会让它在初始化时抛 null 错误,整页功能就废了。 + ============================================================ */ +(function(){ + 'use strict'; + var B = window.__GML_PM_BOOT__ || {}; + var NOTE = { + zh: '存档由项目管理器写进 Mini App 的数据目录(.json 文件);换设备前请在管理页点「导出全部」备份。', + en: 'Saves are written by the project manager into the Mini App data folder (.json files). Use "Export all" on the manager page before switching devices.' + }; + var curLang = (B.lang === 'en') ? 'en' : 'zh'; + var IDS = ['miExport','miImport','miClear','miTutorial','miLang']; + var SEL = '#' + IDS.join(',#'); + var css = SEL + '{display:none !important;}' + + '#userMenu .um-note:not(.gml-pm-note){display:none !important;}' + + '#userMenu .gml-pm-note{display:block !important;}'; + var st = document.createElement('style'); + st.setAttribute('data-gml-pm','menu-guard'); + st.textContent = css; + try{ (document.head || document.documentElement).appendChild(st); }catch(e){} + + /* ---- 退出前的「要不要导出存档」弹层:屏蔽 ---- + 存档在 Mini App 里由宿主自动落盘,这个提醒只会挡住用户。 + 网页的 showExitModal() 是给 #exitModal 加 open 类 ⇒ 盯着这个类, + 一加上就撤掉,等于弹层从未出现过。 + 不删 DOM(网页脚本还握着它的引用)。 */ + function killExitModal(){ + var m = document.getElementById('exitModal'); + if(!m) return; + if(m.classList.contains('open')){ + m.classList.remove('open'); + try{ document.body.style.overflow = ''; }catch(e){} + } + } + function watchExitModal(){ + killExitModal(); + try{ + var mo = new MutationObserver(killExitModal); + mo.observe(document.documentElement, { attributes:true, subtree:true, attributeFilter:['class'] }); + }catch(e){} + setInterval(killExitModal, 400); + } + if(document.readyState === 'loading') document.addEventListener('DOMContentLoaded', watchExitModal); + else watchExitModal(); + + /* 即使样式被绕过,也在捕获阶段拦下这 5 个按钮的点击 */ + document.addEventListener('click', function(e){ + var t = e.target; + if(!t || typeof t.closest !== 'function') return; + if(t.closest(SEL)){ e.preventDefault(); e.stopImmediatePropagation(); } + }, true); + + /* 原菜单底部那句「存档只存在浏览器里」在管理器里是错的,换成准确说明。 + 新节点带 data-i18n-skip,网页自己的中英翻译不会改写它,由管理器按下发的语言更新。 */ + function applyNote(){ + var n = document.querySelector('#userMenu .gml-pm-note'); + if(n) n.textContent = NOTE[curLang]; + } + function patchNote(){ + var menu = document.getElementById('userMenu'); + if(!menu || menu.querySelector('.gml-pm-note')) return; + var p = document.createElement('p'); + p.className = 'um-note gml-pm-note'; + p.setAttribute('data-i18n-skip',''); + p.textContent = NOTE[curLang]; + menu.appendChild(p); + } + if(document.readyState === 'loading') document.addEventListener('DOMContentLoaded', patchNote); + else patchNote(); + setTimeout(patchNote, 1200); /* 兜底:菜单若被网页重建,再补一次 */ + + /* 管理器切换语言时下发:菜单提示跟着变英文/中文; + 网页本身的界面切换由宿主调用 gml.cmd('lang') 完成。 */ + window.addEventListener('message', function(e){ + var d = e.data; + if(!d || d.__gml_pm !== true || d.dir !== 'to-app' || d.type !== 'ui-lang') return; + curLang = (d.lang === 'en') ? 'en' : 'zh'; + applyNote(); patchNote(); + setTimeout(function(){ applyNote(); patchNote(); }, 400); + }); +})(); + +/* ============================================================ + 文案校正层:原网页的文案假设「数据存在浏览器的 localStorage 里」, + 这在 Mini App 里不成立——数据由项目管理器写进数据目录。 + 网页的字典对象不是全局的(拿不到),所以这里直接改渲染出来的文本: + · RULES —— 整句固定的文案 + · PATTERNS —— 带数量的文案(「当前设备上有 1 条记录、0 个 API。」) + 对内置版和「抓取最新版本」下载回来的网页都有效。 + ============================================================ */ +(function(){ + 'use strict'; + var B = window.__GML_PM_BOOT__ || {}; + var lang = (B.lang === 'en') ? 'en' : 'zh'; + + /* 整句文案:olds 里是中英文旧说法,zh/en 是 Mini App 里该显示的说法 */ + var RULES = [ + { olds: ['存档只存在这台设备的浏览器里。换设备或清缓存前,先导出备份。', + 'Your data lives only in this browser on this device. Export a backup before switching devices or clearing the cache.'], + zh: '存档由项目管理器写进 Mini App 的数据目录(.json 文件);换设备前请在管理页点「导出全部」备份。', + en: 'Saves are written by the project manager into the Mini App data folder (.json files). Use "Export all" on the manager page before switching devices.' }, + { olds: ['存档只存在这台设备的浏览器里,刷新、换浏览器、清缓存都会丢。要现在导出一份完整存档文件吗?', + 'Your data only lives in this browser on this device - refreshing, switching browsers or clearing cache will lose it. Export a full backup file now?'], + zh: '存档写在 Mini App 的数据目录里(.json 文件),刷新不会丢;换设备前请在管理页点「导出全部」备份。要现在导出一份完整存档文件吗?', + en: 'Saves are stored in the Mini App data folder (.json files); a refresh will not lose them, but export a full backup before switching devices. Export a full backup file now?' }, + { olds: ['昵称与记录只保存在这台设备的浏览器里,刷新后依然在。
别人首次打开时看到的是默认昵称和空白记录。', + 'Your nickname and records are stored only in this browser on this device and survive a refresh.
Anyone else opening it sees the default nickname and no records.'], + zh: '昵称与记录保存在当前项目文件里,刷新后依然在。
别人首次打开时看到的是默认昵称和空白记录。', + en: 'Your nickname and records are stored in the current project file and survive a refresh.
Anyone else opening it sees the default nickname and no records.' }, + { olds: ['昵称与记录只保存在这台设备的浏览器里,刷新后依然在。', + 'Your nickname and records are stored only in this browser on this device and survive a refresh.'], + zh: '昵称与记录保存在当前项目文件里,刷新后依然在。', + en: 'Your nickname and records are stored in the current project file and survive a refresh.' }, + { olds: ['图片会自动缩到 1024px 以内保存,只存在这台设备上。', + 'Images are scaled to fit within 1024px before saving, and stay on this device only.'], + zh: '图片会自动缩到 1024px 以内保存,只存在当前项目里。', + en: 'Images are scaled to fit within 1024px before saving, and stay in the current project only.' }, + /* 内置的新手教程说明(Mini App 里入口已隐藏,但数据仍要改对) */ + { olds: ['数据只存在这台设备的浏览器里。\n换设备或清缓存前,\n先导出备份。\n\n页面里没有上报代码,\n断网也能用。', + 'The data only lives in this browser\non this device.\nExport a backup before switching\ndevices or clearing the cache.\n\nNothing is uploaded:\nthe site works offline.'], + zh: '数据写在 Mini App 的数据目录里。\n换设备前,\n先在管理页导出备份。\n\n页面里没有上报代码,\n断网也能用。', + en: 'The data is written into the Mini App\ndata folder.\nExport a backup from the manager page\nbefore switching devices.\n\nNothing is uploaded:\nthe site works offline.' }, + { olds: ['清空会删掉这台设备上的全部数据,\n包括这几条说明。\n删之前想留一份,就先「存档」。', + 'Clearing deletes everything stored on\nthis device, including this guide.\nExport an archive first if you want to keep it.'], + zh: '清空会删掉当前项目的全部数据,\n包括这几条说明。\n删之前想留一份,就先「存档」。', + en: 'Clearing deletes everything stored in\nthe current project, including this guide.\nExport an archive first if you want to keep it.' } + ]; + + /* 带数量的文案:记录条数会变,只能按模式匹配。 + 新旧两种写法都列出来,这样中英互切时不会卡在对方那一边。 */ + var PATTERNS = [ + { re: /当前设备上有\s*(\d+)\s*条记录、\s*(\d+)\s*个 API。/g, + zh: '当前项目里有 $1 条记录、$2 个 API。', + en: 'This project has $1 records and $2 APIs.' }, + { re: /这台设备上有\s*(\d+)\s*条记录、\s*(\d+)\s*个 API。/g, + zh: '当前项目里有 $1 条记录、$2 个 API。', + en: 'This project has $1 records and $2 APIs.' }, + { re: /当前项目里有\s*(\d+)\s*条记录、\s*(\d+)\s*个 API。/g, + zh: '当前项目里有 $1 条记录、$2 个 API。', + en: 'This project has $1 records and $2 APIs.' }, + { re: /On this device - records: (\d+), APIs: (\d+)/g, + zh: '当前项目里有 $1 条记录、$2 个 API。', + en: 'In this project - records: $1, APIs: $2' }, + { re: /This device currently has (\d+) records and (\d+) APIs\./g, + zh: '当前项目里有 $1 条记录、$2 个 API。', + en: 'This project has $1 records and $2 APIs.' }, + { re: /In this project - records: (\d+), APIs: (\d+)/g, + zh: '当前项目里有 $1 条记录、$2 个 API。', + en: 'In this project - records: $1, APIs: $2' }, + { re: /This project has (\d+) records and (\d+) APIs\./g, + zh: '当前项目里有 $1 条记录、$2 个 API。', + en: 'This project has $1 records and $2 APIs.' } + ]; + + function fixText(raw, outLang){ + var L = outLang || lang; + var trimmed = raw.trim(); + if(!trimmed) return null; + var i, j, out = null; + for(i=0;i自动保存:练习应用每次自动存档都会写回当前项目文件,数据存在 Mini App 的数据目录里。', + intro_2: '默认是空的:没有存档文件就是 0 个项目,不自动创建。', + intro_3: '回收站:删除的项目移入回收站,并登记在「trash-index.json」清单里,可随时恢复。', + foot_note: '删除不会立刻抹掉数据:项目文件会被移进「回收站」,并登记在「trash-index.json」清单里。', + foot_site: '练习应用来源:basetier-gml.github.io/gml-practice-log', + fsloc_mc: '项目存档 {proj} / <名称>.<ID>.json
回收站  {trash} / <ID>.<删除时间>.json
导出备份 {export}(每次导出都会在这里留一份)
应用缓存 {app}(抓取到的练习应用版本)', + app_title: '练习应用版本', + app_intro: '练习应用内置在 Mini App 里,可以单独更新版本。默认用内置版;点「抓取最新版本」会从来源重新下载网页并缓存到 Mini App 数据目录,之后所有项目都用这份缓存。存档数据始终写在数据目录里。', + app_dialog_title: '练习应用来源', + app_dialog_desc: '填写一个可公开访问的练习应用网页地址。抓取后缓存到 Mini App 数据目录,删除缓存即可回到内置版。', + app_need_folder: '缓存需要写进 Mini App 数据目录', + app_reset_ok: '已恢复内置版本,缓存已从数据目录删除', + app_cannot_fetch_locked: '数据目录暂不可用,恢复访问后再抓取', + sb_scanned: '
📂 已读取存档目录 {dir}:识别 {ok} 个存档 · 读取于 {time}{bad}
', + sb_skipped: '
未识别 {n} 个:{list}
', + chip_data_dir: '📁 Mini App 数据目录', + copied_path: '保存位置已复制到剪贴板', + rescan_done: '已重新读取存档列表', + store_info_mc: '· {n} 个存档文件 · 数据保存在 Mini App 数据目录', + created_project: '已创建空白项目「{name}」', + copy_done: '已复制为新项目', + export_one_ok: '已导出:{name}(同时备份到 {path})', + export_all_ok: '已导出 {n} 个项目 + {t} 个回收站项目(备份在 {path})', + export_site_ok: '已导出网站原生存档格式(备份在 {path})', + import_done: '已导入 {n} 个项目', + import_opening: '已导入,正在打开新项目…', + create_fail: '创建失败:{err}', + save_fail: '保存失败:{err}', + export_fail: '导出失败:{err}', + import_fail: '导入失败:{err}', + rename_fail: '重命名失败:{err}', + copy_fail: '复制失败:{err}', + delete_fail: '删除失败:{err}', + restore_fail: '恢复失败:{err}', + clear_fail: '清空失败:{err}', + load_fail: '载入失败:{err}', + no_saves: '还没有存档文件', + no_saves_hint: '默认就是空项目:新建一个空白项目,或导入一个存档 .json 文件。', + store_unavailable: '保存位置不可用', + trash_head_mc: '文件位于 {dir},清单写在「{idx}」。', + file_generic: '存档文件', +}); + +Object.assign(EN, { + intro_1: 'Auto-save: every auto-save from the practice app is written back to the current project file in the Mini App data folder.', + intro_2: 'Empty by default: no save files means 0 projects — nothing is created automatically.', + intro_3: 'Trash: deleted projects move into the trash and are recorded in "trash-index.json", so they can be restored.', + foot_note: 'Deleting does not erase anything right away: the project file is moved into the trash and recorded in "trash-index.json".', + foot_site: 'Practice app source: basetier-gml.github.io/gml-practice-log', + fsloc_mc: 'Projects {proj} / <name>.<ID>.json
Trash {trash} / <ID>.<deleted-at>.json
Export backups {export} (every export is also saved here)
App cache {app} (the fetched practice-app version)', + app_title: 'Practice app version', + app_intro: 'The practice app is bundled inside this Mini App and can be updated on its own. The built-in version is used by default; "Fetch latest" downloads the page again into the Mini App data folder, and every project then uses that cache. Save data always stays in the data folder.', + app_dialog_title: 'Practice app source', + app_dialog_desc: 'Enter a publicly reachable URL for the practice app. It is cached in the Mini App data folder; delete the cache to go back to the built-in version.', + app_need_folder: 'The cache has to be written into the Mini App data folder', + app_reset_ok: 'Built-in version restored; the cache was removed from the data folder', + app_cannot_fetch_locked: 'The data folder is not available right now — try fetching again later', + sb_scanned: '
📂 Read save folder {dir}: {ok} saves recognised · read at {time}{bad}
', + sb_skipped: '
{n} file(s) not recognised: {list}
', + chip_data_dir: '📁 Mini App data folder', + copied_path: 'Save location copied to the clipboard', + rescan_done: 'Reloaded the save list', + store_info_mc: '· {n} save files · stored in the Mini App data folder', + created_project: 'Created a blank project "{name}"', + copy_done: 'Copied to a new project', + export_one_ok: 'Exported: {name} (also backed up to {path})', + export_all_ok: 'Exported {n} projects + {t} trash items (backup in {path})', + export_site_ok: 'Exported in the site backup format (backup in {path})', + import_done: 'Imported {n} project(s)', + import_opening: 'Imported, opening the new project…', + create_fail: 'Could not create: {err}', + save_fail: 'Save failed: {err}', + export_fail: 'Export failed: {err}', + import_fail: 'Import failed: {err}', + rename_fail: 'Rename failed: {err}', + copy_fail: 'Copy failed: {err}', + delete_fail: 'Delete failed: {err}', + restore_fail: 'Restore failed: {err}', + clear_fail: 'Could not empty the trash: {err}', + load_fail: 'Could not load: {err}', + no_saves: 'No save files yet', + no_saves_hint: 'It starts empty: create a blank project, or import a .json save file.', + '多本互不干扰的练习笔记;每次自动保存都会写回当前项目文件': 'Separate practice notebooks; every auto-save is written back to the current project file', + '查看保存位置': 'Show save location', + '读取保存位置…': 'Reading save location…', + '正在载入网页与项目…': 'Loading the app and project…', + '导入存档': 'Import save', + '导出全部': 'Export all', + '+ 新建项目': '+ New project', + '项目列表': 'Project list', + '它怎么工作': 'How it works', + '回收站': 'Trash', + '🗑 回收站': '🗑 Trash', + '清空回收站': 'Empty trash', + '完成': 'Done', + '← 项目管理': '← Projects', + '立即保存': 'Save now', + '另存为新项目': 'Save as new project', + '重命名': 'Rename', + '导出': 'Export', + '网站存档格式': 'Site backup format', + '导入备份': 'Import backup', + '取消': 'Cancel', + '确定': 'OK', + '名称': 'Name', + '网页地址': 'Page URL', + '还没有存档文件': 'No save files yet', + '默认就是空项目:新建一个空白项目,或导入一个存档 .json 文件。': 'It starts empty: create a blank project, or import a .json save file.', + store_unavailable: 'Save location unavailable', + trash_head_mc: 'Files live in {dir}; the index is written to "{idx}".', + file_generic: 'save file', + '· 自动存档': '· auto-saves', + ' 次': ' times', + '「{name}」会被移动到回收站,并登记到清单里。可以随时恢复,数据不会立刻消失。': '"{name}" moves into the trash and is recorded in the index. You can restore it at any time — the data is not erased right away.', + '已恢复项目': 'Project restored', + '该项目将无法恢复,回收站里的文件也会被删除。': 'This project can no longer be restored and its file in the trash will be deleted.', + '另存失败:{err}': 'Could not save as a new project: {err}', +}); diff --git a/plugins/basetier-gml/miniapp-44928b90-e36d-46c5-9f7e-4d3d5ac5cda0/miniapp/client/i18n.js b/plugins/basetier-gml/miniapp-44928b90-e36d-46c5-9f7e-4d3d5ac5cda0/miniapp/client/i18n.js new file mode 100644 index 00000000..e27ef2e5 --- /dev/null +++ b/plugins/basetier-gml/miniapp-44928b90-e36d-46c5-9f7e-4d3d5ac5cda0/miniapp/client/i18n.js @@ -0,0 +1,3 @@ +/* 管理器文案(与原工具一致) */ +var ZH = {"setup_lead": "选一个文件夹存放项目文件。之后打开会自动恢复这个位置,不再弹出选择菜单;浏览器只记位置,不存项目数据。", "setup_li1": "① 自动恢复打开时自动找到这个文件夹,扫描里面的 .json 存档。", "setup_li2": "② 回收站删除的项目移入回收站并登记在「垃圾回收文件」,可随时恢复。", "setup_li3": "③ 不会丢记住的是文件夹本身;改名、移动、文件被删都不影响删除与恢复。", "intro_1": "自动恢复:打开时自动找到上次的文件夹并扫描 .json 存档,不再弹选择菜单。", "intro_2": "默认是空的:没有存档文件就是 0 个项目,不自动创建。", "intro_3": "自动存档被接管:网页只写回当前打开的文件;外部改动后点「重新扫描」即可同步。", "foot_note": "删除不会立刻抹掉数据:项目文件会被移进「回收站」,并登记在「垃圾回收文件」里。", "foot_site": "核心页面:basetier-gml.github.io/gml-practice-log", "fsloc_saved": "保存位置 {name} / {proj} / <name>.<ID>.json(打开时自动查找并扫描)
回收站  {name} / {trash} / <ID>.<deleted-at>.json
垃圾回收文件 {name} / {trash} / {idx}
浏览器只存 上次选择的文件夹位置(不存任何项目数据);目录名固定用英文,不含中文", "fsloc_unsaved": "保存位置 尚未选择文件夹,仅第一次需要选择;之后打开会自动恢复
浏览器只存 上次选择的文件夹位置(不存任何项目数据)", "sb_locked": "
📂 已自动找到上次的文件夹 {name} / {dir}:浏览器需要一次确认才能读取。点页面任意处即可自动恢复并扫描,不会重新弹出选择文件夹菜单。
{change}
", "sb_change_btn": "", "sb_scanned": "
📂 已扫描文件夹 {dir}:找到 {total} 个 .json 文件,识别 {ok} 个存档 · 扫描于 {time}{bad}
", "sb_skipped": "
未识别 {n} 个:{list}
", "sb_empty": "
📁 首次使用需要选一次保存位置;之后打开会自动查找并恢复这个文件夹,不再弹出选择菜单。列表完全由文件夹里的 .json 存档决定。{unsupported}
{action}", "sb_pick_btn": "
", "trash_empty": "
回收站是空的。
", "trash_item": "

{name} {tag}

删除于 {deleted} · {size}{file}
", "app_title": "打卡网页版本", "app_intro": "管理页是独立的程序,打卡网页可单独更新版本。默认用内置版;点「抓取最新版本」会从来源重新下载网页并存到你的文件夹,之后所有项目都用这份缓存。存档数据仍只写在文件夹里。", "app_src_label": "来源地址", "app_ver_label": "版本", "app_fetched_label": "抓取于", "app_size_label": "大小", "app_builtin": "内置版本(出厂自带)", "app_custom": "自定义版本", "app_never_fetched": "尚未抓取", "app_btn_source": "更换来源", "app_btn_fetch": "⇩ 抓取最新版本", "app_btn_builtin": "恢复内置版", "app_dialog_title": "打卡网页来源", "app_dialog_desc": "填写一个可公开访问的打卡网页地址。抓取后缓存到文件夹,删除缓存即可回到内置版。", "app_url_hint": "网页地址(以 http:// 或 https:// 开头)", "app_fetching": "正在抓取最新版本…", "app_fetched_ok": "已抓取最新版本:{v}", "app_fetched_fail": "抓取失败:{err}", "app_url_invalid": "请输入以 http:// 或 https:// 开头的地址", "app_need_folder": "请先选择保存文件夹,缓存需要写进文件夹", "app_not_html": "抓取到的内容不是网页(缺少 html 标签)", "app_reset_ok": "已恢复内置版本,缓存已从文件夹删除", "app_reset_fail": "删除缓存失败:{err}", "app_cannot_fetch_locked": "文件夹暂未连接,恢复访问后再抓取"} +EN = {"垃圾回收文件:记录所有被移入回收站的项目文件,可据此恢复。": "Garbage collection file: lists every project moved to the Trash so it can be restored.", " · 副本": " (copy)", "打卡次数": "Check-ins", "练习天数": "Practice days", "练习记录": "Records", " · 目标 ": " · Goal ", " 次 · 累计自动存档 ": " · Auto-saves ", " 次
": "
", "· 文件修改": " · File modified", "· 最后保存": " · Last save", "": "", "": "", "": "", "": "", "": "", "
大小": "
Size", "
格式": "
Format", "
📄 存档文件": "
📄 Save file", "
昵称 ": "
Nickname ", "最近打开": "Last opened", "网站原生存档": "Site backup", "GML 代码练习记录": "GML Code Practice Log", "GML 练习记录 · 项目存档管理器": "GML Practice Log · Project Manager", "IndexedDB 打开失败": "Failed to open IndexedDB", "foot_note": "Deleting does not erase data right away: the project file is moved to the Trash and listed in the garbage-collection file.", "foot_site": "Core page: basetier-gml.github.io/gml-practice-log", "fsloc_saved": "Save location  {name} / {proj} / <name>.<ID>.json (auto-found and scanned on open)
Trash  {name} / {trash} / <ID>.<deleted-at>.json
Garbage collection file  {name} / {trash} / {idx}
Browser stores only  the last folder location (no project data). Folder names are fixed in English, with no Chinese in paths.", "fsloc_unsaved": "Save location  No folder chosen yet — you only need to pick one the first time; it is restored automatically afterwards.
Browser stores only  the last folder location (no project data)", "gml-pm-save": "Manager save", "gml存档库-": "gml-vault-", "gml项目-": "gml-project-", "intro_1": "Auto-restore: on open it finds the last folder and scans .json saves — no picker pops up.", "intro_2": "Empty by default: no save files means 0 projects; nothing is created automatically.", "intro_3": "Auto-save is taken over: the page only writes back to the currently open file; click \"Rescan folder\" after external changes.", "sb_change_btn": "", "sb_empty": "
📁 Pick a save location the first time; afterwards it is found and restored automatically, with no folder picker. The list comes entirely from the .json saves in the folder.{unsupported}
{action}", "sb_locked": "
📂 Found your last folder {name} / {dir}: the browser needs one confirmation before reading it. Click anywhere on the page to restore and scan — no folder picker will pop up.
{change}
", "sb_pick_btn": "
", "sb_scanned": "
📂 Scanned folder {dir}: found {total} .json file(s), recognized {ok} save(s) · scanned at {time}{bad}
", "sb_skipped": "
Skipped {n}: {list}
", "setup_lead": "Pick a folder to hold your project files. It is restored automatically every time you open this page — the folder picker will not pop up again. The browser only remembers the location, never your project data.", "setup_li1": "① Auto-restoreOn open it finds this folder and scans the .json saves inside.", "setup_li2": "② TrashDeleted projects move to the Trash and are listed in the garbage-collection file, ready to restore.", "setup_li3": "③ Nothing gets lostWhat is remembered is the folder itself; renaming, moving, or deleting files never breaks delete and restore.", "trash_empty": "
Trash is empty.
", "trash_item": "

{name} {tag}

Deleted {deleted} · {size}{file}
", "{n} 个项目": "{n} project{s}", "· {n} 个存档文件 · 数据只存在文件夹里": "· {n} save file{s} · data lives only in your folder", "· 已找到上次的文件夹,等待恢复": "· Last folder found, waiting to reconnect", "· 未连接文件夹": "· No folder connected", "← 项目管理": "← Projects", "⚠ 请选择存档文件夹": "⚠ Choose a save folder", "「{name}」会被移动到回收站文件夹,并登记到「{idx}」。 可以在回收站里随时恢复,数据不会立刻消失。": "\"{name}\" will be moved to the Trash folder and listed in \"{idx}\". You can restore it any time; the data is not deleted right away.", "「{name}」将无法恢复,回收站里的文件也会被删除。": "\"{name}\" cannot be recovered, and its file will be removed from the Trash.", "一个网页,多个互不干扰的项目文件;网页的每次自动保存都由这里接管": "One page, multiple isolated project files; every auto-save of the app is managed here", "上次的位置:{name}。": "Last location: {name}. ", "上次的文件夹": "the last folder", "上次的文件夹暂时无法访问:点「更换文件夹」可另选一个,项目数据仍在原文件夹里": "The last folder is temporarily unavailable: click \"Change folder\" to pick another one. Your project data is still in the original folder.", "上次选择的文件夹": "the last selected folder", "不是存档格式 · ": "Not a save file · ", "不是有效 JSON · ": "Invalid JSON · ", "不是有效的 JSON 存档文件": "Not a valid JSON save file", "仅第一次需要选择文件夹,之后打开会自动查找并恢复。项目数据只保存在文件夹里。": "You only need to choose a folder the first time; afterwards it is found and restored automatically. Project data lives only in the folder.", "仅第一次需要选择;之后打开会自动查找并恢复,不再弹出选择菜单。浏览器只记位置,不存任何项目数据。": "Only needed the first time; afterwards it is found and restored automatically with no folder picker. The browser only remembers the location, never any project data.", "保存": "Save", "保存失败:{err}": "Save failed: {err}", "保存失败:请先重新选择存档文件夹": "Save failed: please choose a save folder again", "保存目录不可用": "Save folder unavailable", "先选一个保存位置(仅第一次)": "Choose a save location (first time only)", "全部清空": "Empty all", "共 {n} 个项目。": "{n} item{s}. ", "写入回收站失败,项目未删除(数据仍在原文件里):{err}": "Could not write to Trash; project was not deleted (data is still in the original file): {err}", "写入文件夹失败:{err}(原文件未受影响,点顶部圆点恢复上次的文件夹)": "Could not write to the folder: {err} (original files are untouched; click the top dot to reconnect the last folder)", "分片存档": "Storage shards", "创建": "Create", "创建 ": "Created ", "取消": "Cancel", "另存为新项目": "Save as new project", "名称": "Name", "命令执行失败": "Command failed", "回收站已清空": "Trash emptied", "回收站已经是空的": "Trash is already empty", "回收站文件": "Trash file", "备份已导入当前项目,并自动存档": "Backup imported into the current project and auto-saved", "存档文件夹不可访问,请点顶部圆点恢复上次的文件夹": "Save folder is unavailable — click the top dot to reconnect the last folder", "它怎么工作": "How it works", "完成": "Done", "导入备份": "Import backup", "导入失败:": "Import failed: ", "导入失败:{err}": "Import failed: {err}", "导入存档": "Import save", "导入项目": "Imported project", "导出": "Export", "导出全部": "Export all", "导出失败": "Export failed", "导出失败:{err}": "Export failed: {err}", "将永久删除回收站里的 {n} 个项目,无法恢复。建议先「导出全部」备份。": "This permanently deletes {n} item{s} from the Trash and they cannot be recovered. Consider using \"Export all\" first.", "尚未选择存档文件夹": "No save folder selected yet", "已写入当前项目文件": "Written to the current project file", "已创建空白项目「{name}」,并写入存档文件": "Created empty project \"{name}\" and wrote its save file", "已删除项目": "Deleted project", "已另存为「{name}」(当前仍在编辑原项目)": "Saved a copy as \"{name}\" (you are still editing the original)", "已复制为「{name}」": "Duplicated as \"{name}\"", "已导入 {n} 个项目、{t} 个回收站项目": "Imported {n} projects and {t} trash items", "已导入项目:{name}": "Imported project: {name}", "已导出 {n} 个项目 + {t} 个回收站项目": "Exported {n} projects + {t} trash items", "已导出当前项目": "Current project exported", "已导出网站原生存档格式": "Exported in the site's native backup format", "已导出(管理器格式,可再导入)": "Exported (manager format, can be re-imported)", "已彻底删除": "Permanently deleted", "已恢复项目:{name}": "Restored project: {name}", "已手动保存 · {t}": "Manually saved · {t}", "已扫描「{name}」:{n} 个存档文件": "Scanned \"{name}\": {n} save file{s}", "已找到上次的文件夹": "Last folder found", "已把网站存档导入当前项目": "Site backup imported into the current project", "已移入回收站:{name}": "Moved to Trash: {name}", "已自动保存 · {t}": "Auto-saved · {t}", "已自动恢复上次的文件夹「{name}」:{n} 个存档": "Restored last folder \"{name}\": {n} save{s}", "已自动打开上次的文件夹「{name}」:{n} 个存档": "Opened last folder \"{name}\": {n} save{s}", "已自动找到上次的文件夹,点击恢复访问(不会弹出选择菜单)": "Last folder found automatically; click to restore access (no folder picker will pop up)", "已选择的文件夹": "Selected folder", "已重命名": "Renamed", "已重命名(文件已同步改名)": "Renamed (file name synced)", "当前保存位置;点击可更换文件夹": "Current save location; click to change folder", "当前浏览器不支持选择文件夹,请用 Chrome / Edge 桌面浏览器。": "This browser cannot pick folders — please use desktop Chrome or Edge.", "当前浏览器不支持选择文件夹,请用 Chrome / Edge 桌面浏览器打开": "This browser cannot pick folders — please open this tool in desktop Chrome or Edge", "当前浏览器不支持选择文件夹,请用 Chrome / Edge 桌面浏览器打开本工具。": "This browser cannot pick folders — please open this tool in desktop Chrome or Edge.", "彻底删除": "Delete permanently", "恢复": "Restore", "扫描失败:{err}": "Scan failed: {err}", "文件位于 {name} / {dir},清单写在「{idx}」。": "Files are in {name} / {dir}, listed in \"{idx}\". ", "文件夹": "folder", "文件夹里还没有存档文件": "No save files in the folder yet", "新名称": "New name", "新建或导入项目后即可打开": "Create or import a project to open it", "新建项目": "New project", "无法读取": "Unreadable", "查看 / 更换保存位置": "View / change save location", "正在把网站存档导入新项目…": "Importing the site backup into a new project…", "正在载入网页…": "Loading page…", "正在载入网页与项目…": "Loading page and project…", "永久删除": "Delete permanently", "浏览器不支持选择文件夹": "Browser does not support folder selection", "清空回收站": "Empty Trash", "点「打开项目」开始练习": "Click \"Open project\" to start practicing", "点一下页面任意处或顶部圆点即可自动恢复并扫描,不会重新弹出选择文件夹的菜单。": "Click anywhere on the page or the top dot to restore and scan automatically; the folder picker will not pop up again.", "点击选择保存文件夹": "Click to choose a save folder", "确定": "OK", "移入回收站": "Move to Trash", "立即保存": "Save now", "练习项目 ": "Project ", "编程新手": "Newbie", "网站原生存档": "Site native backup", "网站存档-": "site-backup-", "网站存档格式": "Site backup format", "网页加载较慢,请稍候…(若一直空白可返回重试)": "The page is slow to load, please wait… (if it stays blank, go back and retry)", "网页尚未打开": "Page not open yet", "网页拒绝了这份存档": "The page rejected this backup", "网页无响应(超时)": "Page did not respond (timeout)", "自动存档已接管": "Auto-save managed by the manager", "请先打开一个项目": "Open a project first", "请先点一下页面,恢复上次的文件夹。": "Click anywhere on the page to reconnect the last folder. ", "请先选择存档文件夹。": "Please choose a save folder. ", "请点一下页面或顶部圆点,恢复上次的文件夹": "Click the page or the top dot to reconnect the last folder", "读取失败": "Read failed", "读取文件失败": "Could not read the file", "还没有可用的存档文件夹,请先点右上角圆点选择": "No save folder available yet — click the top-right dot to choose one", "这个文件夹无法写入,请重新选择一个可写的文件夹": "This folder is not writable — please choose a writable folder", "选择失败:{err}": "Selection failed: {err}", "重命名": "Rename", "重命名当前项目": "Rename current project", "重命名项目": "Rename project", "项目列表": "Projects", "项目名称": "Project name", "默认就是空项目:新建一个空白项目,或把存档 .json 放进文件夹后点「重新扫描」。": "Empty by default: create a blank project, or drop a save .json into the folder and click \"Rescan\".", "+ 新建项目": "+ New project", "📁 {name} · 已记住": "📁 {name} · remembered", "📁 上次:{name} · 点击恢复": "📁 Last: {name} · click to reconnect", "📁 选择文件夹": "📁 Choose folder", "🗑 回收站": "🗑 Trash", "app_title": "Check-in page version", "app_intro": "The manager is a standalone program; the check-in page can be updated on its own. It starts with the built-in version. Click \"Fetch latest\" to download the page from its source into your folder; all projects then use that cached copy. Save data still lives only in the folder.", "app_src_label": "Source URL", "app_ver_label": "Version", "app_fetched_label": "Fetched", "app_size_label": "Size", "app_builtin": "Built-in (bundled)", "app_custom": "Custom version", "app_never_fetched": "Not fetched yet", "app_btn_source": "Change source", "app_btn_fetch": "⇩ Fetch latest", "app_btn_builtin": "Restore built-in", "app_dialog_title": "Check-in page source", "app_dialog_desc": "Enter a publicly reachable check-in page URL. It is cached in your folder; delete the cache to return to the built-in version.", "app_url_hint": "Page URL (starts with http:// or https://)", "app_fetching": "Fetching latest version…", "app_fetched_ok": "Fetched latest version: {v}", "app_fetched_fail": "Fetch failed: {err}", "app_url_invalid": "Enter a URL starting with http:// or https://", "app_need_folder": "Choose a save folder first; the cache is stored in the folder", "app_not_html": "Fetched content is not a web page (no html tag)", "app_reset_ok": "Restored built-in version; cache removed from folder", "app_reset_fail": "Could not remove cache: {err}", "app_cannot_fetch_locked": "Folder not connected; reconnect it before fetching"} diff --git a/plugins/basetier-gml/miniapp-44928b90-e36d-46c5-9f7e-4d3d5ac5cda0/miniapp/client/index.html b/plugins/basetier-gml/miniapp-44928b90-e36d-46c5-9f7e-4d3d5ac5cda0/miniapp/client/index.html new file mode 100644 index 00000000..b77ccfb2 --- /dev/null +++ b/plugins/basetier-gml/miniapp-44928b90-e36d-46c5-9f7e-4d3d5ac5cda0/miniapp/client/index.html @@ -0,0 +1,148 @@ + + + + + +GML 练习记录 · 项目存档管理器 + + + + + + + + + +
+
+
+ +
+

GML 练习记录 · 项目存档管理器

+

多本互不干扰的练习笔记;每次自动保存都会写回当前项目文件

+
+
+
+ + + + + +
+
+
+ +
+
+

它怎么工作

+
    +
  • 自动保存:练习应用每次自动存档都会写回当前项目文件,数据存在 Mini App 的数据目录里。
  • +
  • 默认是空的:没有存档文件就是 0 个项目,不自动创建。
  • +
  • 回收站:删除的项目移入回收站,并登记在「trash-index.json」清单里,可随时恢复。
  • +
+
+
+ +
+

📦练习应用版本—

+

练习应用内置在 Mini App 里,可以单独更新版本。

+
+
来源地址—
+
版本—
+
抓取于—
+
大小—
+
+
+ + + +
+
+ +
+

项目列表

0 个项目 + + 点「打开项目」开始练习 +
+ +
+ +
+ 删除不会立刻抹掉数据:项目文件会被移进「回收站」,并登记在「trash-index.json」清单里。 + 练习应用来源:basetier-gml.github.io/gml-practice-log +
+
+
+ + + + + + +
+ + + + + + + + + + diff --git a/plugins/basetier-gml/miniapp-44928b90-e36d-46c5-9f7e-4d3d5ac5cda0/miniapp/client/manager.css b/plugins/basetier-gml/miniapp-44928b90-e36d-46c5-9f7e-4d3d5ac5cda0/miniapp/client/manager.css new file mode 100644 index 00000000..d5073c92 --- /dev/null +++ b/plugins/basetier-gml/miniapp-44928b90-e36d-46c5-9f7e-4d3d5ac5cda0/miniapp/client/manager.css @@ -0,0 +1,193 @@ + +:root{ + --bg:#191b1e; --panel:#222428; --card:#282b30; --card2:#2e3137; + --line:#3a3e46; --line-soft:#31353c; + --ink:#f0f2f5; --ink2:#b9c0ca; --ink3:#808895; + --accent:#4a90e2; --accent2:#7ab4f0; + --ok:#4fbd8b; --danger:#e2605f; --warn:#d9a441; + --radius:14px; --radius-sm:9px; + --sans:"Outfit","PingFang SC","Hiragino Sans GB","Microsoft YaHei","Noto Sans CJK SC",sans-serif; + --mono:"JetBrains Mono","SF Mono",Menlo,Consolas,monospace; +} +*{box-sizing:border-box} +html,body{margin:0;padding:0;height:100%} +body{background:var(--bg);color:var(--ink);font-family:var(--sans);font-size:14px;line-height:1.6;-webkit-font-smoothing:antialiased} +[hidden]{display:none !important} +button{font-family:inherit;font-size:inherit;cursor:pointer} +a{color:var(--accent2);text-decoration:none} +a:hover{text-decoration:underline} +code{font-family:var(--mono);font-size:12px;background:rgba(255,255,255,.07);padding:1px 5px;border-radius:4px} +::-webkit-scrollbar{width:9px;height:9px} +::-webkit-scrollbar-thumb{background:#454a53;border-radius:6px} +::-webkit-scrollbar-track{background:transparent} + +.topbar{border-bottom:1px solid var(--line-soft);background:linear-gradient(180deg,#23262b,#1e2024)} +.topbar-in{max-width:1180px;margin:0 auto;padding:18px 22px;display:flex;align-items:center;gap:14px;flex-wrap:wrap} +.logo{width:40px;height:40px;border-radius:11px;background:var(--accent);color:#fff;font-weight:700;font-size:23px;display:flex;align-items:center;justify-content:center;flex:0 0 auto;box-shadow:0 5px 16px -6px var(--accent)} +.brand-txt h1{margin:0;font-size:17px;font-weight:700;letter-spacing:.2px} +.brand-txt p{margin:1px 0 0;font-size:12px;color:var(--ink3)} +.top-actions{margin-left:auto;display:flex;gap:8px;flex-wrap:wrap;align-items:center} + +.btn{border:1px solid var(--line);background:var(--card2);color:var(--ink2);padding:8px 13px;border-radius:var(--radius-sm);transition:.16s;white-space:nowrap;display:inline-flex;align-items:center;gap:6px;font-size:13px} +.btn:hover{border-color:#5a606b;color:var(--ink);background:#353940} +.btn.primary{background:var(--accent);border-color:var(--accent);color:#fff;font-weight:600} +.btn.primary:hover{background:#5b9de8;border-color:#5b9de8} +.btn.danger{background:transparent;border-color:rgba(226,96,95,.5);color:#ef8d8c} +.btn.danger:hover{background:rgba(226,96,95,.14);color:#ffb3b2} +.btn.mini{padding:6px 10px;font-size:12px;background:transparent} +.btn.ghost{background:transparent} +.btn:disabled{opacity:.45;cursor:not-allowed} +.chip{display:inline-flex;align-items:center;gap:7px;border:1px solid var(--line);background:var(--card2);color:var(--ink2);padding:7px 11px;border-radius:20px;font-size:12px;max-width:260px} +.chip i{width:7px;height:7px;border-radius:50%;background:var(--ok);flex:0 0 auto} +.chip.bad i{background:var(--warn)} +.chip.wait i{background:#7aa2f7} +.chip span{overflow:hidden;text-overflow:ellipsis;white-space:nowrap} +.chip:hover{border-color:#5a606b;color:var(--ink)} + +.wrap{max-width:1180px;margin:0 auto;padding:22px} +.intro{background:linear-gradient(120deg,rgba(74,144,226,.13),rgba(74,144,226,.02));border:1px solid rgba(74,144,226,.3);border-radius:var(--radius);padding:16px 18px;margin-bottom:18px} +.intro h2{margin:0 0 6px;font-size:15px;color:var(--accent2)} +.intro p{margin:0;color:var(--ink2);font-size:13px} +.intro ul.intro-list{list-style:none;margin:0;padding:0;display:grid;gap:3px} +.intro ul.intro-list li{color:var(--ink2);font-size:13px;line-height:1.65} +.intro ul.intro-list li::before{content:'·';color:var(--accent2);font-weight:700;margin-right:7px} +.intro ul.intro-list b{color:var(--ink)} +.intro ul.intro-list code{font-family:var(--mono);font-size:12px} +.fsloc{margin-top:12px;background:rgba(0,0,0,.22);border:1px solid var(--line-soft);border-radius:var(--radius-sm);padding:10px 12px;font-family:var(--mono);font-size:12px;color:var(--ink2);line-height:1.9;word-break:break-all} +.fsloc b{color:var(--accent2);font-family:var(--sans)} +.section-head{display:flex;align-items:baseline;gap:10px;margin:0 0 14px;flex-wrap:wrap} +.section-head h2{margin:0;font-size:16px} +.section-head span{color:var(--ink3);font-size:12px} +.section-head .right{margin-left:auto} + +.grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(330px,1fr));gap:16px} +.card{background:var(--card);border:1px solid var(--line-soft);border-radius:var(--radius);padding:16px 17px 14px;display:flex;flex-direction:column;transition:.18s;position:relative;overflow:hidden} +.card:hover{border-color:#4c586b;transform:translateY(-2px);box-shadow:0 12px 30px -14px #000} +.card::before{content:"";position:absolute;left:0;top:0;bottom:0;width:3px;background:var(--accent);opacity:.65} +.card.is-last::before{background:var(--ok)} +.card-top{display:flex;align-items:flex-start;gap:10px} +.card-title h3{margin:0;font-size:16px;font-weight:650;word-break:break-all} +.badge{font-size:11px;padding:2px 8px;border-radius:20px;border:1px solid var(--line);color:var(--ink3);white-space:nowrap} +.badge.on{color:var(--ok);border-color:rgba(79,189,139,.45);background:rgba(79,189,139,.08)} +.stats{display:grid;grid-template-columns:repeat(4,1fr);gap:8px;margin:15px 0 12px} +.stat{background:var(--card2);border-radius:var(--radius-sm);padding:8px 6px;text-align:center} +.stat b{display:block;font-size:17px;font-variant-numeric:tabular-nums;line-height:1.25} +.stat span{font-size:11px;color:var(--ink3)} +.meta{font-size:12px;color:var(--ink3);line-height:1.85;min-height:44px} +.meta em{font-style:normal;color:var(--ink2)} +.card-actions{margin-top:13px;padding-top:12px;border-top:1px solid var(--line-soft);display:flex;gap:6px;flex-wrap:wrap;align-items:center} +.card-actions .btn.primary{margin-right:auto} +.empty{text-align:center;padding:56px 20px;color:var(--ink3);border:1px dashed var(--line);border-radius:var(--radius)} +.empty .big{font-size:40px;margin-bottom:8px;opacity:.5} +.empty h3{color:var(--ink2);margin:0 0 6px} +.foot{margin-top:26px;padding-top:14px;border-top:1px solid var(--line-soft);color:var(--ink3);font-size:12px;display:flex;gap:12px;flex-wrap:wrap} +/* 存档文件信息区:这些内容全部来自文件夹里读到的真实文件 */ +.fileinfo{margin:2px 0 10px;background:rgba(74,144,226,.07);border:1px solid rgba(74,144,226,.20);border-radius:9px;padding:9px 10px;display:grid;gap:4px} +.fi-row{display:flex;align-items:baseline;gap:6px;font-size:12px;color:var(--ink3);flex-wrap:wrap;line-height:1.5} +.fi-row em{font-style:normal;color:var(--ink2);font-family:var(--mono);font-size:11.5px;word-break:break-all} +.scan-banner{display:flex;align-items:flex-start;gap:10px;flex-wrap:wrap;background:linear-gradient(100deg,rgba(79,189,139,.10),rgba(74,144,226,.05));border:1px solid rgba(79,189,139,.28);border-radius:var(--radius-sm);padding:10px 14px;margin-bottom:16px;font-size:12.5px;color:var(--ink2);line-height:1.7} +.scan-banner b{color:var(--ink);font-weight:600} +.scan-banner .sb-main{flex:1;min-width:220px} +.scan-banner .sb-bad{color:var(--warn);font-size:12px} +.scan-banner .sb-actions{margin-left:auto;display:flex;gap:6px;align-items:flex-start} + +#view-project{height:100vh;display:flex;flex-direction:column} +.project-bar{height:56px;flex:0 0 56px;display:flex;align-items:center;gap:10px;padding:0 14px;background:var(--panel);border-bottom:1px solid var(--line);z-index:5} +.project-bar .pname{font-weight:650;font-size:15px;max-width:200px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap} +.pstatus{display:flex;align-items:center;gap:7px;font-size:12px;color:var(--ink3);white-space:nowrap} +.pstatus i{width:7px;height:7px;border-radius:50%;background:var(--warn);display:inline-block;box-shadow:0 0 0 3px rgba(217,164,65,.14)} +.pstatus.ok i{background:var(--ok);box-shadow:0 0 0 3px rgba(79,189,139,.15)} +.pstatus.flash i{animation:pulse .7s ease} +@keyframes pulse{0%{transform:scale(1)}45%{transform:scale(1.9)}100%{transform:scale(1)}} +.project-bar .spacer{flex:1} +.project-bar .btn{padding:6px 11px;font-size:12px} +#stage{position:relative;flex:1;min-height:0;background:#222} +.app-frame{display:block;width:100%;height:100%;border:0;background:#222} +.loading{position:absolute;inset:0;display:flex;align-items:center;justify-content:center;flex-direction:column;gap:12px;background:#1b1d20;color:var(--ink3);z-index:2} +.spinner{width:26px;height:26px;border:3px solid #3a3f48;border-top-color:var(--accent);border-radius:50%;animation:spin .8s linear infinite} +@keyframes spin{to{transform:rotate(360deg)}} + +.overlay{position:fixed;inset:0;background:rgba(0,0,0,.72);display:flex;align-items:center;justify-content:center;z-index:50;padding:20px} +.modal{width:min(460px,100%);background:var(--panel);border:1px solid var(--line);border-radius:var(--radius);padding:20px;box-shadow:0 24px 60px -20px #000} +.modal h3{margin:0 0 8px;font-size:16px} +.modal label{display:block;font-size:12px;color:var(--ink3);margin:12px 0 6px} +.modal input{width:100%;background:var(--bg);border:1px solid var(--line);color:var(--ink);border-radius:var(--radius-sm);padding:9px 11px;outline:none;font-family:inherit} +.modal input:focus{border-color:var(--accent)} +.modal p{margin:0;color:var(--ink2);font-size:13px;white-space:pre-line} +.modal-actions{display:flex;justify-content:flex-end;gap:8px;margin-top:20px;flex-wrap:wrap} +.setup-card{width:min(560px,100%);background:var(--panel);border:1px solid rgba(74,144,226,.4);border-radius:18px;padding:26px;box-shadow:0 30px 80px -24px #000} +.setup-card h2{margin:0 0 8px;font-size:20px} +.setup-card .lead{color:var(--ink2);font-size:13px;margin:0 0 16px} +.setup-list{margin:0 0 18px;padding:0;list-style:none;display:grid;gap:9px} +.setup-list li{display:flex;gap:10px;color:var(--ink2);font-size:13px;background:var(--card);border:1px solid var(--line-soft);border-radius:10px;padding:9px 11px} +.setup-list b{color:var(--accent2);flex:0 0 auto} +.setup-actions{display:flex;gap:9px;flex-wrap:wrap} +.setup-note{margin-top:14px;color:var(--ink3);font-size:12px} +.sheet{width:min(720px,100%);max-height:86vh;display:flex;flex-direction:column;background:var(--panel);border:1px solid var(--line);border-radius:18px;overflow:hidden;box-shadow:0 30px 80px -24px #000} +.sheet-head{padding:18px 20px;border-bottom:1px solid var(--line-soft);display:flex;align-items:center;gap:12px;flex-wrap:wrap} +.sheet-head h2{margin:0;font-size:17px} +.sheet-head p{margin:2px 0 0;color:var(--ink3);font-size:12px;width:100%} +.sheet-body{overflow:auto;padding:14px 20px;flex:1;min-height:120px} +.sheet-foot{padding:12px 20px;border-top:1px solid var(--line-soft);display:flex;gap:8px;justify-content:flex-end;flex-wrap:wrap} +.titem{display:flex;gap:12px;align-items:center;background:var(--card);border:1px solid var(--line-soft);border-radius:12px;padding:12px 14px;margin-bottom:10px;flex-wrap:wrap} +.titem .ti-main{flex:1;min-width:180px} +.titem h4{margin:0;font-size:14px;word-break:break-all} +.titem small{color:var(--ink3);font-size:12px} +.tag{font-size:11px;border:1px solid var(--line);border-radius:20px;padding:2px 8px;color:var(--ink3);white-space:nowrap} +.tag.file{color:var(--ok);border-color:rgba(79,189,139,.45)} +.titem .btn{padding:6px 10px;font-size:12px} +.trash-empty{text-align:center;color:var(--ink3);padding:44px 10px} +#toast{position:fixed;left:50%;bottom:26px;transform:translate(-50%,14px);background:#343942;color:var(--ink);border:1px solid var(--line);padding:10px 18px;border-radius:24px;font-size:13px;opacity:0;pointer-events:none;transition:.24s;z-index:80;box-shadow:0 10px 30px -10px #000;max-width:88vw;text-align:center} +#toast.show{opacity:1;transform:translate(-50%,0)} +#toast.err{border-color:rgba(226,96,95,.7);background:#4a2c2c} +#toast.ok{border-color:rgba(79,189,139,.6);background:#254236} +.warn-banner{position:fixed;top:0;left:0;right:0;z-index:90;background:#4a3a1c;border-bottom:1px solid #8a6a25;color:#ffdd9c;padding:8px 16px;text-align:center;font-size:12px} +@media(max-width:720px){ + .topbar-in{padding:14px 16px}.wrap{padding:16px} + .grid{grid-template-columns:1fr} + .top-actions{width:100%;margin-left:0} + .project-bar .pname{max-width:100px} + .project-bar .hide-sm{display:none} + .chip{max-width:180px} +} + +/* 界面语言切换 */ +.lang-sw{display:inline-flex;border:1px solid var(--line);border-radius:20px;overflow:hidden;background:var(--card2);flex:0 0 auto} +.lang-sw button{border:0;background:transparent;color:var(--ink3);padding:6px 12px;font-size:12px;line-height:1.5;font-weight:600;letter-spacing:.3px} +.lang-sw button + button{border-left:1px solid var(--line)} +.lang-sw button.on{background:var(--accent);color:#fff} +.lang-sw button:hover:not(.on){color:var(--ink);background:#353940} +.setup-card{position:relative} +.setup-lang{position:absolute;right:22px;top:22px} +@media(max-width:720px){.setup-lang{position:static;float:right;margin-bottom:8px}} +/* 打卡网页版本卡片 */ +.appcard{background:linear-gradient(120deg,rgba(122,180,240,.10),rgba(74,144,226,.02));border:1px solid rgba(122,180,240,.28);border-radius:var(--radius);padding:14px 17px;margin-bottom:18px} +.appcard h2{margin:0 0 6px;font-size:15px;color:var(--accent2);display:flex;align-items:center;gap:9px;flex-wrap:wrap} +.appcard h2 .avert{font-size:11px;font-weight:600;padding:2px 9px;border-radius:20px;border:1px solid var(--line);color:var(--ink2);background:rgba(0,0,0,.2)} +.appcard h2 .avert.custom{color:var(--ok);border-color:rgba(79,189,139,.45);background:rgba(79,189,139,.09)} +.appcard p.aintro{margin:0 0 11px;color:var(--ink2);font-size:12.5px;line-height:1.7} +.avgrid{display:grid;grid-template-columns:repeat(auto-fit,minmax(200px,1fr));gap:8px;margin-bottom:12px} +.avcell{background:rgba(0,0,0,.22);border:1px solid var(--line-soft);border-radius:var(--radius-sm);padding:8px 11px;font-size:12px;min-width:0} +.avcell span{color:var(--ink3);display:block;font-size:11px;margin-bottom:2px} +.avcell em{font-style:normal;color:var(--ink2);font-family:var(--mono);font-size:11.5px;word-break:break-all;display:block} +.avacts{display:flex;gap:8px;flex-wrap:wrap} +.avacts .btn.mini{padding:7px 12px} + +/* ---------------- 键盘可达性 ---------------- + 深色底上浏览器默认的焦点框几乎看不见,这里统一画一个高对比的焦点环。 + 用 :focus-visible,只在键盘操作时出现,鼠标点击不打扰。 */ +button:focus-visible, +a:focus-visible, +input:focus-visible, +select:focus-visible, +textarea:focus-visible, +[tabindex]:focus-visible{ + outline:2px solid var(--accent2); + outline-offset:2px; + border-radius:6px; +} +/* 输入框原本用 outline:none + 换边框色表示聚焦,边框太弱,这里补上焦点环 */ +.modal input:focus-visible{outline:2px solid var(--accent2);outline-offset:1px} +/* 焦点态下按钮稍微提亮,避免只在深色里“消失” */ +.btn:focus-visible,.chip:focus-visible,.lang-sw button:focus-visible{background:var(--card2)} +.lang-sw button:focus-visible{outline-offset:-2px} diff --git a/plugins/basetier-gml/miniapp-44928b90-e36d-46c5-9f7e-4d3d5ac5cda0/miniapp/client/manager.js b/plugins/basetier-gml/miniapp-44928b90-e36d-46c5-9f7e-4d3d5ac5cda0/miniapp/client/manager.js new file mode 100644 index 00000000..5854bc7b --- /dev/null +++ b/plugins/basetier-gml/miniapp-44928b90-e36d-46c5-9f7e-4d3d5ac5cda0/miniapp/client/manager.js @@ -0,0 +1,944 @@ +/* ============================================================ + GML 练习记录 · 项目存档管理器(Mini App 版) + - 数据不再落在用户自选的文件夹,而是由 Mini App 的 Node 服务 + 写进宿主分配的数据目录(GML-Saves / GML-Trash / GML-App)。 + - 打卡网页仍然以 iframe + srcdoc 载入,注入层(core/boot.js) + 把 localStorage 虚拟成「当前存档槽」,每次自动存档回传这里, + 由本文件转成业务请求交给 Node 服务落盘。 + ============================================================ */ +(function () { + 'use strict'; + + var $ = function (s) { return document.querySelector(s); }; + var API = '/app/api/'; + var PREFIX = 'gml-practice-log-v2:'; + var APP_DEFAULT_URL = 'https://basetier-gml.github.io/gml-practice-log/'; + + function has(o, k) { return Object.prototype.hasOwnProperty.call(o, k); } + function clone(o) { return o === undefined ? o : JSON.parse(JSON.stringify(o)); } + function pad(n) { return n < 10 ? '0' + n : '' + n; } + function hhmmss(t) { + var d = t instanceof Date ? t : new Date(t); + return pad(d.getHours()) + ':' + pad(d.getMinutes()) + ':' + pad(d.getSeconds()); + } + function fmtTime(t) { + if (!t) return '—'; + var d = new Date(t); + return (d.getMonth() + 1) + '/' + d.getDate() + ' ' + hhmmss(d); + } + function fmtSize(n) { + n = Number(n) || 0; + if (n < 1024) return n + ' B'; + if (n < 1048576) return (n / 1024).toFixed(1) + ' KB'; + return (n / 1048576).toFixed(2) + ' MB'; + } + function esc(s) { + return String(s == null ? '' : s).replace(/[&<>"']/g, function (c) { + return { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]; + }); + } + function safeFile(s) { return String(s || '存档').replace(/[\\/:*?"<>|]/g, '_').slice(0, 48); } + + /* ---------------- 弹层焦点管理(键盘可达性) ---------------- + 统一接管三个弹层(回收站 / 通用对话框 / 应用来源)的开关: + 打开时记录来源元素并把焦点移进弹层,关闭时把焦点还给来源元素, + Tab / Shift+Tab 在弹层内循环,Esc 关闭最上层弹层。 */ + var FOCUSABLE = 'a[href],button:not([disabled]),input:not([disabled]):not([type="hidden"]),select:not([disabled]),textarea:not([disabled]),[tabindex]:not([tabindex="-1"])'; + var overlayStack = []; + var overlayCloser = Object.create(null); /* 元素 id -> 额外的关闭清理逻辑 */ + + function isVisible(el) { + if (!el || el.hidden) return false; + if (!el.getClientRects) return false; + return el.getClientRects().length > 0; + } + + function focusablesIn(root) { + var list = root.querySelectorAll(FOCUSABLE), out = []; + for (var i = 0; i < list.length; i++) if (isVisible(list[i])) out.push(list[i]); + return out; + } + + function topOverlay() { + return overlayStack.length ? overlayStack[overlayStack.length - 1] : null; + } + + function openOverlay(el, opts) { + if (!el) return; + opts = opts || {}; + if (overlayStack.indexOf(el) === -1) { + var active = document.activeElement; + el._returnFocus = (active && active !== document.body) ? active : null; + overlayStack.push(el); + } + el.hidden = false; + var target = opts.focus ? $(opts.focus) : null; + if (!target || !isVisible(target)) { + var list = focusablesIn(el); + target = list[0] || null; + } + if (target) setTimeout(function () { + try { target.focus(); if (typeof target.select === 'function' && target.value != null) target.select(); } catch (e) { } + }, 30); + } + + function closeOverlay(el) { + if (!el) return; + var i = overlayStack.indexOf(el); + if (i !== -1) overlayStack.splice(i, 1); + el.hidden = true; + var back = el._returnFocus; + el._returnFocus = null; + if (back && back.focus && isVisible(back)) { + setTimeout(function () { try { back.focus(); } catch (e) { } }, 0); + } + } + + document.addEventListener('keydown', function (e) { + var top = topOverlay(); + if (!top) return; + if (e.key === 'Escape') { + var closer = overlayCloser[top.id]; + if (closer) { e.preventDefault(); closer(); } + else closeOverlay(top); + return; + } + if (e.key !== 'Tab') return; + var list = focusablesIn(top); + if (!list.length) { e.preventDefault(); return; } + var first = list[0], last = list[list.length - 1]; + var cur = document.activeElement; + if (!top.contains(cur)) { e.preventDefault(); (e.shiftKey ? last : first).focus(); return; } + if (e.shiftKey && cur === first) { e.preventDefault(); last.focus(); } + else if (!e.shiftKey && cur === last) { e.preventDefault(); first.focus(); } + }); + + /* ---------------- 界面语言 ---------------- */ + var UI = { lang: 'zh' }; + function T(s, vars) { + if (s == null) return ''; + var k = String(s), t; + if (UI.lang === 'en' && has(EN, k)) t = EN[k]; + else if (has(ZH, k)) t = ZH[k]; + else t = k; + if (vars) { + t = t.replace(/\{s\}/g, function () { return String(vars.n) === '1' ? '' : 's'; }); + t = t.replace(/\{(\w+)\}/g, function (m, x) { return (vars[x] != null) ? vars[x] : m; }); + } + return t; + } + + /* ---------------- 业务请求 ---------------- */ + function api(path, options) { + options = options || {}; + var init = { method: options.method || 'GET', headers: {} }; + if (options.body !== undefined) { + init.headers['content-type'] = 'application/json; charset=utf-8'; + init.body = JSON.stringify(options.body); + } + return fetch(API + path, init).then(function (resp) { + return resp.text().then(function (text) { + var data = null; + try { data = text ? JSON.parse(text) : null; } catch (e) { data = null; } + if (!resp.ok) { + var msg = (data && (data.error || data.message)) || ('HTTP ' + resp.status); + throw new Error(String(msg)); + } + return data; + }); + }); + } + + /* ---------------- 全局状态 ---------------- */ + var vault = { saves: [], trash: [], skipped: [], lastOpenedId: null }; + var APP_INFO = { url: APP_DEFAULT_URL, version: '', fetchedAt: 0, size: 0, custom: false, builtinSize: 0 }; + var STORE = { projDir: '', trashDir: '', appDir: '', exportDir: '' }; + var SCAN = { at: 0, total: 0, ok: 0 }; + var activeId = null; + var frame = null; + var APP_HTML = null; + var BOOT_SRC = null; + var curStatus = null; + var loadingKey = null; + var LK_LOADING = '正在载入网页与项目…', LK_SLOW = '网页加载较慢,请稍候…(若一直空白可返回重试)'; + var pendingImport = null; + var importMode = 'vault'; + var loadTimer = null; + var rpcSeq = 0; + var rpcPending = Object.create(null); + var saveTimer = null; + var saveChain = Promise.resolve(); + var dirtyIds = {}; + + function toast(msg, kind) { + var t = $('#toast'); + t.textContent = msg; + t.className = 'show' + (kind ? ' ' + kind : ''); + clearTimeout(t._timer); + t._timer = setTimeout(function () { t.className = ''; }, 3000); + } + + function dialog(opts) { + return new Promise(function (resolve) { + var m = $('#modal'), ok = $('#modalOk'), cancel = $('#modalCancel'), input = $('#modalInput'); + $('#modalTitle').textContent = opts.title || ''; + $('#modalDesc').textContent = opts.desc || ''; + $('#modalDesc').hidden = !opts.desc; + $('#modalLabel').textContent = opts.label || T('名称'); + $('#modalLabel').hidden = !!opts.noInput; + input.hidden = !!opts.noInput; + input.value = opts.value || ''; + ok.textContent = opts.confirmText || T('确定'); + ok.className = 'btn ' + (opts.danger ? 'danger' : 'primary'); + overlayCloser.modal = function () { finish(null); }; + openOverlay(m, { focus: opts.noInput ? '#modalOk' : '#modalInput' }); + function finish(v) { + delete overlayCloser.modal; + closeOverlay(m); + ok.onclick = null; cancel.onclick = null; m.onclick = null; input.onkeydown = null; + resolve(v); + } + ok.onclick = function () { finish(opts.noInput ? true : input.value.trim()); }; + cancel.onclick = function () { finish(null); }; + m.onclick = function (e) { if (e.target === m) finish(null); }; + input.onkeydown = function (e) { + if (e.key === 'Enter') { e.preventDefault(); ok.click(); } + }; + }); + } + + /* ---------------- 读写数据 ---------------- */ + function loadState() { + return api('state').then(function (state) { + UI.lang = state.uiLang === 'en' ? 'en' : 'zh'; + vault.saves = state.saves || []; + vault.trash = state.trash || []; + vault.skipped = state.skipped || []; + APP_INFO = state.app || APP_INFO; + STORE = state.store || STORE; + SCAN = state.scan || SCAN; + var last = null; + try { last = localStorage.getItem('gml-miniapp:last-project'); } catch (e) { last = null; } + vault.lastOpenedId = vault.saves.some(function (s) { return s.id === last; }) + ? last + : (vault.saves.length ? vault.saves[0].id : null); + applyUiLang(); + renderManager(); + renderTrash(); + updateFsChip(); + return state; + }); + } + + function slotStats(s) { + function part(k, def) { + try { + var v = JSON.parse((s.data && s.data[PREFIX + k]) || 'null'); + return (v && typeof v === 'object') ? v : def; + } catch (e) { return def; } + } + var records = part('records', {}), days = part('days', {}), apiPart = part('api', {}), + user = part('user', {}), settings = part('settings', {}); + if (s.siteBackup) { + var sd = s.siteBackup.data || s.siteBackup; + var srecs = Array.isArray(sd.records) ? sd.records.length : (sd.records ? Object.keys(sd.records).length : 0); + var sapis = Array.isArray(sd.apiLib) ? sd.apiLib.length : (sd.apiLib ? Object.keys(sd.apiLib).length : 0); + return { + recs: srecs, apis: sapis, days: 0, checkins: 0, + nick: (sd.user && sd.user.name) || sd.nickname || T('编程新手'), + goal: sd.dailyGoal || 5, size: JSON.stringify(s.data || {}).length, saves: s.saveCount || 0, + }; + } + var checkins = 0; + for (var d in days) { + var arr = days[d] && days[d].records; + if (Array.isArray(arr)) checkins += arr.length; + } + return { + recs: Object.keys(records).length, + apis: Object.keys(apiPart).length, + days: Object.keys(days).length, + checkins: checkins, + nick: user.name || T('编程新手'), + goal: settings.dailyGoal || 5, + size: JSON.stringify(s.data || {}).length, + saves: s.saveCount || 0, + }; + } + + function findSlot(id) { + for (var i = 0; i < vault.saves.length; i++) if (vault.saves[i].id === id) return vault.saves[i]; + return null; + } + + function ensureFileMeta(s) { + if (!s.file) s.file = T('file_generic'); + if (s.fileSize == null) s.fileSize = JSON.stringify(s.data || {}).length; + if (s.fileModified == null) s.fileModified = s.updatedAt || Date.now(); + if (!s.fileFormat) s.fileFormat = 'gml-pm-save'; + return s; + } + + /* ---------------- 渲染 ---------------- */ + function cardHtml(s) { + ensureFileMeta(s); + var st = slotStats(s); + var last = (s.id === vault.lastOpenedId); + var site = !!s.siteBackup; + return '
' + + '

' + esc(s.name) + '

' + + (last ? T('最近打开') : '') + + (site ? T('网站原生存档') : '') + '
' + + '
' + + '
' + st.recs + T('练习记录
') + + '
' + st.apis + 'API
' + + '
' + st.checkins + T('打卡次数
') + + '
' + st.days + T('练习天数
') + + '
' + + T('
📄 存档文件') + esc(s.file) + '
' + + T('
大小') + fmtSize(s.fileSize) + T('· 最后保存') + fmtTime(s.updatedAt) + '
' + + T('
格式') + esc(s.fileFormat) + T('· 自动存档') + st.saves + T(' 次
') + + '
' + + '
昵称 ' + esc(st.nick) + T(' · 目标 ') + esc(st.goal) + T(' 次
') + + T('创建 ') + fmtTime(s.createdAt) + '
' + + '
' + + T('') + + T('') + + T('') + + T('') + + T('') + + '
'; + } + + function renderManager() { + var list = vault.saves.slice().sort(function (a, b) { return (b.updatedAt || 0) - (a.updatedAt || 0); }); + list.forEach(ensureFileMeta); + $('#saveCount').textContent = T('{n} 个项目', { n: list.length }); + $('#emptyState').hidden = list.length > 0; + $('#saveGrid').hidden = list.length === 0; + if (!list.length) { + $('#emptyState h3').textContent = T('no_saves'); + $('#emptyState p').innerHTML = T('no_saves_hint'); + $('#listHint').textContent = T('新建或导入项目后即可打开'); + } else { + $('#listHint').textContent = T('点「打开项目」开始练习'); + } + $('#saveGrid').innerHTML = list.map(cardHtml).join(''); + $('#trashCount').textContent = String(vault.trash.length); + updateStoreInfo(); + renderScanBanner(); + } + + function updateStoreInfo() { + var el = $('#storeInfo'); + if (!el) return; + el.textContent = T('store_info_mc', { n: vault.saves.length }); + } + + function renderScanBanner() { + var b = $('#scanBanner'); + if (!b) return; + b.hidden = false; + var bad = vault.skipped && vault.skipped.length; + b.innerHTML = T('sb_scanned', { + dir: esc(STORE.projDir || 'GML-Saves'), + total: SCAN.total, ok: SCAN.ok, time: hhmmss(SCAN.at), + bad: (bad ? T('sb_skipped', { n: bad, list: esc(vault.skipped.map(function (x) { return x.name; }).join('、')) }) : ''), + }); + } + + function renderTrash() { + var box = $('#trashList'); + $('#trashCount').textContent = String(vault.trash.length); + $('#trashHeadInfo').textContent = T('共 {n} 个项目。', { n: vault.trash.length }) + + T('trash_head_mc', { dir: esc(STORE.trashDir || 'GML-Trash'), idx: 'trash-index.json' }); + if (!vault.trash.length) { box.innerHTML = T('trash_empty'); return; } + box.innerHTML = vault.trash.slice().sort(function (a, b) { return (b.deletedAt || 0) - (a.deletedAt || 0); }).map(function (t) { + return T('trash_item', { + id: esc(t.id), name: esc(t.name), tag: T('回收站文件'), + deleted: fmtTime(t.deletedAt), size: fmtSize(JSON.stringify(t.data || {}).length), + file: (t.file ? ' · ' + esc(t.file) : ''), restore: T('恢复'), purge: T('彻底删除'), + }); + }).join(''); + } + + function updateFsChip() { + var chip = $('#fsChip'), txt = $('#fsChipText'); + chip.className = 'chip'; + txt.textContent = T('chip_data_dir'); + chip.title = STORE.projDir || ''; + var loc = $('#fsloc'); + loc.innerHTML = T('fsloc_mc', { + proj: esc(STORE.projDir || 'GML-Saves'), + trash: esc(STORE.trashDir || 'GML-Trash'), + export: esc(STORE.exportDir || 'exports'), + app: esc(STORE.appDir || 'GML-App'), + }); + } + + function renderAppCard() { + var tag = $('#appVerTag'), src = $('#appSrcText'), ver = $('#appVerText'), + ft = $('#appFetchedText'), sz = $('#appSizeText'); + if (!tag) return; + var custom = APP_INFO.custom; + tag.textContent = custom ? T('app_custom') : T('app_builtin'); + tag.className = 'avert' + (custom ? ' custom' : ''); + src.textContent = APP_INFO.url || APP_DEFAULT_URL; + src.title = APP_INFO.url || APP_DEFAULT_URL; + if (custom) { + ver.textContent = APP_INFO.version || '—'; + ft.textContent = APP_INFO.fetchedAt ? new Date(APP_INFO.fetchedAt).toLocaleString() : T('app_never_fetched'); + sz.textContent = APP_INFO.size ? fmtSize(APP_INFO.size) : '—'; + } else { + ver.textContent = T('app_builtin'); + ft.textContent = '—'; + sz.textContent = fmtSize(APP_INFO.builtinSize || 0); + } + } + + function applyUiLang() { + document.documentElement.setAttribute('lang', UI.lang === 'en' ? 'en' : 'zh-CN'); + document.title = T('GML 练习记录 · 项目存档管理器'); + var i, els; + els = document.querySelectorAll('[data-i18n]'); + for (i = 0; i < els.length; i++) els[i].textContent = T(els[i].getAttribute('data-i18n')); + els = document.querySelectorAll('[data-i18n-html]'); + for (i = 0; i < els.length; i++) els[i].innerHTML = T(els[i].getAttribute('data-i18n-html')); + els = document.querySelectorAll('[data-i18n-title]'); + for (i = 0; i < els.length; i++) els[i].title = T(els[i].getAttribute('data-i18n-title')); + els = document.querySelectorAll('[data-lang-set]'); + for (i = 0; i < els.length; i++) { + var on = els[i].getAttribute('data-lang-set') === UI.lang; + els[i].classList.toggle('on', on); + els[i].setAttribute('aria-pressed', on ? 'true' : 'false'); + } + renderManager(); renderTrash(); updateFsChip(); renderAppCard(); + if (curStatus) setStatus(curStatus.key, curStatus.ok, false, curStatus.vars); + if (loadingKey) { var lt = $('#loadingText'); if (lt) lt.textContent = T(loadingKey); } + var fr = $('#appFrame'); if (fr) fr.title = T('GML 代码练习记录'); + } + + function setUiLang(lang) { + if (lang !== 'zh' && lang !== 'en') return; + UI.lang = lang; + applyUiLang(); + api('config', { method: 'PUT', body: { uiLang: lang } }).catch(function () { }); + if (frame && frame.contentWindow) { + try { frame.contentWindow.postMessage({ __gml_pm: true, dir: 'to-app', type: 'ui-lang', lang: lang }, '*'); } catch (e) { } + rpc('cmd', { name: 'lang', args: { lang: lang } }, 8000).catch(function () { }); + } + } + + function setStatus(key, ok, flash, vars) { + curStatus = { key: key, ok: ok, vars: vars }; + var p = $('#pstatus'); + $('#statusText').textContent = T(key, vars); + p.className = 'pstatus' + (ok ? ' ok' : '') + (flash ? ' flash' : ''); + if (flash) setTimeout(function () { p.className = 'pstatus' + (ok ? ' ok' : ''); }, 750); + } + + function showView(name) { + $('#view-manager').hidden = (name !== 'manager'); + $('#view-project').hidden = (name !== 'project'); + } + + /* ---------------- 落盘 ---------------- */ + function persistSlot(id) { + var slot = findSlot(id); + if (!slot) return Promise.resolve(); + return api('projects/' + encodeURIComponent(id), { method: 'PUT', body: { data: slot.data || {} } }) + .then(function (res) { + if (res) { + slot.updatedAt = res.updatedAt || slot.updatedAt; + slot.saveCount = res.saveCount || slot.saveCount; + } + }); + } + + function persist(ids) { + var list = ids ? (Array.isArray(ids) ? ids : [ids]) : vault.saves.map(function (s) { return s.id; }); + list.forEach(function (x) { dirtyIds[x] = 1; }); + if (saveTimer) clearTimeout(saveTimer); + saveTimer = setTimeout(function () { + saveTimer = null; + var ids2 = Object.keys(dirtyIds); + dirtyIds = {}; + saveChain = saveChain.then(function () { + return ids2.reduce(function (p, id) { + return p.then(function () { return persistSlot(id); }); + }, Promise.resolve()); + }).catch(function (e) { + toast(T('save_fail', { err: String((e && e.message) || e) }), 'err'); + }); + }, 150); + } + + function persistNow() { + if (saveTimer) { clearTimeout(saveTimer); saveTimer = null; } + var ids = Object.keys(dirtyIds); + dirtyIds = {}; + saveChain = saveChain.then(function () { + return ids.reduce(function (p, id) { + return p.then(function () { return persistSlot(id); }); + }, Promise.resolve()); + }); + return saveChain.catch(function (e) { + toast(T('save_fail', { err: String((e && e.message) || e) }), 'err'); + throw e; + }); + } + + /* ---------------- 内嵌打卡网页 ---------------- */ + function stripRemoteFonts(html) { + return String(html) + .replace(/]*fonts\.googleapis\.com[^>]*>\s*/gi, '') + .replace(/]*fonts\.gstatic\.com[^>]*>\s*/gi, ''); + } + + function loadAppHtml() { + if (APP_HTML) return Promise.resolve(APP_HTML); + /* 这个接口返回的是网页源码(text/html),不能走 JSON 解析 */ + return fetch(API + 'app/html').then(function (r) { return r.text(); }).then(function (text) { + APP_HTML = stripRemoteFonts(text); + return APP_HTML; + }); + } + + function loadBootSrc() { + if (BOOT_SRC) return Promise.resolve(BOOT_SRC); + return fetch('/app/core/boot.js').then(function (r) { return r.text(); }).then(function (text) { + BOOT_SRC = text; + return BOOT_SRC; + }); + } + + function safeJson(o) { + return JSON.stringify(o).replace(/' + setup + BOOT_SRC + '<' + '/script>'; + return APP_HTML.replace('', '\n' + inject); + } + + function openSlot(id) { + var slot = findSlot(id); + if (!slot) return Promise.resolve(); + activeId = id; + vault.lastOpenedId = id; + try { localStorage.setItem('gml-miniapp:last-project', id); } catch (e) { } + pendingImport = slot.siteBackup ? slot.siteBackup : null; + $('#projName').textContent = slot.name; + showView('project'); + setStatus(T('正在载入网页…'), false); + var stage = $('#stage'); + stage.innerHTML = '
' + T(LK_LOADING) + '
'; + loadingKey = LK_LOADING; + + return Promise.all([loadAppHtml(), loadBootSrc()]).then(function () { + var f = document.createElement('iframe'); + f.id = 'appFrame'; + f.className = 'app-frame'; + f.title = T('GML 代码练习记录'); + f.setAttribute('allowfullscreen', ''); + frame = f; + stage.insertBefore(f, stage.firstChild); + f.srcdoc = buildSrcdoc(slot); + clearTimeout(loadTimer); + loadTimer = setTimeout(function () { + var lt = $('#loadingText'); + if (lt && !$('#loading').hidden) { lt.textContent = T(LK_SLOW); loadingKey = LK_SLOW; } + }, 9000); + }).catch(function (e) { + toast(T('load_fail', { err: String((e && e.message) || e) }), 'err'); + showView('manager'); + }); + } + + function closeProject() { + /* 先等网页把待写数据 flush 回来,再拆 iframe;否则最后一次自动存档会丢 */ + var flushed = frame ? rpc('flush', {}, 2500).catch(function () { }) : Promise.resolve(); + return flushed.then(function () { + if (frame) { try { frame.remove(); } catch (e) { } } + frame = null; activeId = null; clearTimeout(loadTimer); + return persistNow().catch(function () { }); + }).then(function () { + return loadState(); + }).then(function () { + showView('manager'); + }); + } + + /* ---------------- 宿主 ⇄ 网页消息 ---------------- */ + function rpc(type, extra, timeout) { + return new Promise(function (resolve, reject) { + if (!frame || !frame.contentWindow) { reject(new Error(T('网页尚未打开'))); return; } + var id = 'r' + (++rpcSeq); + var timer = setTimeout(function () { delete rpcPending[id]; reject(new Error(T('网页无响应(超时)'))); }, timeout || 12000); + rpcPending[id] = { resolve: resolve, reject: reject, timer: timer }; + var msg = { __gml_pm: true, dir: 'to-app', id: id, type: type }; + if (extra) for (var k in extra) if (has(extra, k)) msg[k] = extra[k]; + try { frame.contentWindow.postMessage(msg, '*'); } + catch (e) { clearTimeout(timer); delete rpcPending[id]; reject(e); } + }); + } + + function handleCommit(d) { + if (!activeId || d.saveId !== activeId) return; + var slot = findSlot(activeId); + if (!slot) return; + slot.data = d.data || {}; + slot.updatedAt = d.ts || Date.now(); + slot.saveCount = (slot.saveCount || 0) + 1; + persist(slot.id); + setStatus(T('已自动保存 · {t}'), true, true, { t: hhmmss(slot.updatedAt) }); + } + + function onFrameReady() { + var l = $('#loading'); if (l) l.hidden = true; + clearTimeout(loadTimer); + setStatus(T('自动存档已接管'), true); + if (pendingImport) { + var o = pendingImport; pendingImport = null; + rpc('cmd', { name: 'import', args: { json: o } }).then(function (r) { + if (r && r.ok === false) throw new Error(r.error || T('网页拒绝了这份存档')); + toast(T('已把网站存档导入当前项目'), 'ok'); + return rpc('flush', {}, 4000); + }).catch(function (e) { toast(T('import_fail', { err: e.message }), 'err'); }); + } + } + + window.addEventListener('message', function (e) { + var d = e.data; + if (!d || d.__gml_pm !== true || d.dir !== 'to-host') return; + if (frame && e.source !== frame.contentWindow) return; + if (d.type === 'commit') { handleCommit(d); return; } + if (d.type === 'ready') { onFrameReady(); return; } + var p = rpcPending[d.id]; + if (!p) return; + delete rpcPending[d.id]; clearTimeout(p.timer); + if (d.type === 'cmd-result') { if (d.ok) p.resolve(d.result); else p.reject(new Error(d.error || T('命令执行失败'))); } + else p.resolve(true); + }); + + /* ---------------- 导入 / 导出 ---------------- */ + function download(name, text) { + try { + var blob = new Blob([text], { type: 'application/json;charset=utf-8' }); + var url = URL.createObjectURL(blob), a = document.createElement('a'); + a.href = url; a.download = name; document.body.appendChild(a); a.click(); + setTimeout(function () { try { document.body.removeChild(a); } catch (e) { } URL.revokeObjectURL(url); }, 1500); + return true; + } catch (e) { return false; } + } + + function exportProject(id) { + return api('export/project/' + encodeURIComponent(id)).then(function (res) { + download(res.filename, res.text); + toast(T('export_one_ok', { name: res.filename, path: res.path }), 'ok'); + }).catch(function (e) { toast(T('export_fail', { err: e.message }), 'err'); }); + } + + function exportAll() { + return api('export/all').then(function (res) { + download(res.filename, res.text); + toast(T('export_all_ok', { + n: vault.saves.length, t: vault.trash.length, path: res.path, + }), 'ok'); + }).catch(function (e) { toast(T('export_fail', { err: e.message }), 'err'); }); + } + + function handleImportText(text, filename) { + var base = filename.replace(/\.json$/i, '').slice(0, 40) || T('导入项目'); + if (importMode === 'backup') { + if (!activeId) { toast(T('请先打开一个项目'), 'err'); return; } + var obj; + try { obj = JSON.parse(text); } catch (e) { toast(T('不是有效的 JSON 存档文件'), 'err'); return; } + rpc('cmd', { name: 'import', args: { json: obj } }).then(function (r) { + if (r && r.ok === false) throw new Error(r.error || T('网页拒绝了这份存档')); + toast(T('备份已导入当前项目,并自动存档'), 'ok'); + return rpc('flush', {}, 4000); + }).catch(function (e) { toast(T('import_fail', { err: e.message }), 'err'); }); + return; + } + api('import', { method: 'POST', body: { text: text, filename: filename } }).then(function (res) { + return loadState().then(function () { + if (res && res.project && res.project.siteBackup) { + toast(T('import_opening'), 'ok'); + return openSlot(res.project.id); + } + toast(T('import_done', { n: (res && res.imported) || 1 }), 'ok'); + }); + }).catch(function (e) { toast(T('import_fail', { err: e.message }), 'err'); }); + } + + /* ---------------- 打卡网页版本 ---------------- */ + function openAppSource() { + $('#appSrcInput').value = APP_INFO.url || APP_DEFAULT_URL; + openOverlay($('#appSrcOverlay'), { focus: '#appSrcInput' }); + } + + function fetchLatestApp() { + var url = (APP_INFO.url || '').trim(); + if (!/^https?:\/\//i.test(url)) { openAppSource(); toast(T('app_url_invalid'), 'err'); return Promise.resolve(); } + var btn = $('#btnAppFetch'); + if (btn) { btn.disabled = true; btn.textContent = T('app_fetching'); } + return api('app/fetch', { method: 'POST', body: { url: url } }).then(function (info) { + APP_INFO = info; + APP_HTML = null; + renderAppCard(); + toast(T('app_fetched_ok', { v: info.version }), 'ok'); + }).catch(function (e) { + toast(T('app_fetched_fail', { err: String((e && e.message) || e) }), 'err'); + }).finally(function () { + if (btn) { btn.disabled = false; btn.textContent = T('app_btn_fetch'); } + }); + } + + function restoreBuiltinApp() { + return api('app/builtin', { method: 'POST' }).then(function (info) { + APP_INFO = info; + APP_HTML = null; + renderAppCard(); + toast(T('app_reset_ok'), 'ok'); + }).catch(function (e) { toast(T('app_reset_fail', { err: String((e && e.message) || e) }), 'err'); }); + } + + /* ---------------- 事件绑定 ---------------- */ + $('#saveGrid').addEventListener('click', function (e) { + var btn = e.target.closest('[data-act]'); + if (!btn) return; + var card = btn.closest('[data-id]'); + if (!card) return; + var id = card.getAttribute('data-id'); + var act = btn.getAttribute('data-act'); + var slot = findSlot(id); + if (!slot) return; + if (act === 'open') { openSlot(id); return; } + if (act === 'rename') { + dialog({ title: T('重命名项目'), label: T('新名称'), value: slot.name, confirmText: T('保存') }).then(function (v) { + if (!v) return; + api('projects/' + encodeURIComponent(id), { method: 'PATCH', body: { name: v } }) + .then(function () { return loadState(); }) + .then(function () { toast(T('已重命名'), 'ok'); }) + .catch(function (err) { toast(T('rename_fail', { err: err.message }), 'err'); }); + }); + return; + } + if (act === 'dup') { + api('projects/' + encodeURIComponent(id) + '/copy', { method: 'POST' }) + .then(function () { return loadState(); }) + .then(function () { toast(T('copy_done'), 'ok'); }) + .catch(function (err) { toast(T('copy_fail', { err: err.message }), 'err'); }); + return; + } + if (act === 'export') { exportProject(id); return; } + if (act === 'del') { + dialog({ + title: T('移入回收站'), noInput: true, danger: true, confirmText: T('移入回收站'), + desc: T('「{name}」会被移动到回收站,并登记到清单里。可以随时恢复,数据不会立刻消失。', { name: slot.name }), + }).then(function (ok) { + if (!ok) return; + api('projects/' + encodeURIComponent(id), { method: 'DELETE' }) + .then(function () { return loadState(); }) + .then(function () { toast(T('已移入回收站:{name}', { name: slot.name }), 'ok'); }) + .catch(function (err) { toast(T('delete_fail', { err: err.message }), 'err'); }); + }); + } + }); + + $('#trashList').addEventListener('click', function (e) { + var btn = e.target.closest('[data-tact]'); + if (!btn) return; + var row = btn.closest('[data-id]'); + if (!row) return; + var id = row.getAttribute('data-id'); + if (btn.getAttribute('data-tact') === 'restore') { + api('trash/' + encodeURIComponent(id) + '/restore', { method: 'POST' }) + .then(function () { return loadState(); }) + .then(function () { toast(T('已恢复项目'), 'ok'); }) + .catch(function (err) { toast(T('restore_fail', { err: err.message }), 'err'); }); + return; + } + dialog({ + title: T('彻底删除'), noInput: true, danger: true, confirmText: T('永久删除'), + desc: T('该项目将无法恢复,回收站里的文件也会被删除。'), + }).then(function (ok) { + if (!ok) return; + api('trash/' + encodeURIComponent(id), { method: 'DELETE' }) + .then(function () { return loadState(); }) + .then(function () { toast(T('已彻底删除'), 'ok'); }) + .catch(function (err) { toast(T('delete_fail', { err: err.message }), 'err'); }); + }); + }); + + $('#btnClearTrash').addEventListener('click', function () { + if (!vault.trash.length) { toast(T('回收站已经是空的')); return; } + dialog({ + title: T('清空回收站'), noInput: true, danger: true, confirmText: T('全部清空'), + desc: T('将永久删除回收站里的 {n} 个项目,无法恢复。建议先「导出全部」备份。', { n: vault.trash.length }), + }).then(function (ok) { + if (!ok) return; + api('trash/clear', { method: 'POST' }) + .then(function () { return loadState(); }) + .then(function () { toast(T('回收站已清空'), 'ok'); }) + .catch(function (err) { toast(T('clear_fail', { err: err.message }), 'err'); }); + }); + }); + + $('#btnTrash').addEventListener('click', function () { renderTrash(); openOverlay($('#trashOverlay'), { focus: '#btnCloseTrash' }); }); + $('#btnCloseTrash').addEventListener('click', function () { closeOverlay($('#trashOverlay')); }); + $('#trashOverlay').addEventListener('click', function (e) { if (e.target === this) closeOverlay(this); }); + + $('#fsChip').addEventListener('click', function () { + var text = STORE.projDir || ''; + if (text && navigator.clipboard && navigator.clipboard.writeText) { + navigator.clipboard.writeText(text).then(function () { + toast(T('copied_path'), 'ok'); + }).catch(function () { + toast(text); + }); + } else { + toast(text || T('store_unavailable')); + } + }); + + $('#scanBanner').addEventListener('click', function (e) { + if (e.target.closest('#btnRescan')) { + loadState().then(function () { toast(T('rescan_done'), 'ok'); }); + } + }); + + function newSlot() { + dialog({ + title: T('新建项目'), label: T('项目名称'), + value: T('练习项目 ') + (vault.saves.length + 1), confirmText: T('创建'), + }).then(function (name) { + if (!name) return; + api('projects', { method: 'POST', body: { name: name } }) + .then(function () { return loadState(); }) + .then(function () { toast(T('created_project', { name: name }), 'ok'); }) + .catch(function (err) { toast(T('create_fail', { err: err.message }), 'err'); }); + }); + } + $('#btnNew').addEventListener('click', newSlot); + $('#btnNew2').addEventListener('click', newSlot); + $('#btnExportAll').addEventListener('click', exportAll); + $('#btnImport').addEventListener('click', function () { importMode = 'vault'; $('#fileInput').click(); }); + $('#fileInput').addEventListener('change', function (e) { + var file = e.target.files && e.target.files[0]; + if (!file) return; + var reader = new FileReader(); + reader.onload = function () { handleImportText(String(reader.result), file.name); }; + reader.onerror = function () { toast(T('读取文件失败'), 'err'); }; + reader.readAsText(file, 'utf-8'); + e.target.value = ''; + }); + + $('#btnBack').addEventListener('click', function () { closeProject(); }); + $('#btnSaveNow').addEventListener('click', function () { + var run = function () { return persistNow(); }; + if (frame) { + rpc('flush', {}, 4000).then(run).catch(function () { + return run(); + }).then(function () { + toast(T('已写入当前项目文件'), 'ok'); + setStatus(T('已手动保存 · {t}'), true, true, { t: hhmmss(Date.now()) }); + }).catch(function (e) { toast(T('save_fail', { err: e.message }), 'err'); }); + } else { + run().then(function () { toast(T('已写入当前项目文件'), 'ok'); }) + .catch(function (e) { toast(T('save_fail', { err: e.message }), 'err'); }); + } + }); + + $('#btnFork').addEventListener('click', function () { + if (!activeId) return; + var id = activeId; + var run = function () { return api('projects/' + encodeURIComponent(id) + '/copy', { method: 'POST' }); }; + var flush = frame ? rpc('flush', {}, 4000).catch(function () { }) : Promise.resolve(); + flush.then(run).then(function (res) { + return loadState().then(function () { + toast(T('已另存为「{name}」(当前仍在编辑原项目)', { name: res.name }), 'ok'); + }); + }).catch(function (err) { toast(T('另存失败:{err}', { err: err.message }), 'err'); }); + }); + + $('#btnRename').addEventListener('click', function () { + if (!activeId) return; + var id = activeId; + var slot = findSlot(id); + if (!slot) return; + dialog({ title: T('重命名当前项目'), label: T('新名称'), value: slot.name, confirmText: T('保存') }).then(function (v) { + if (!v) return; + api('projects/' + encodeURIComponent(id), { method: 'PATCH', body: { name: v } }) + .then(function () { $('#projName').textContent = v; return loadState(); }) + .then(function () { toast(T('已重命名'), 'ok'); }) + .catch(function (err) { toast(T('rename_fail', { err: err.message }), 'err'); }); + }); + }); + + $('#btnExportPm').addEventListener('click', function () { + if (!activeId) return; + var id = activeId; + var flush = frame ? rpc('flush', {}, 4000).catch(function () { }) : Promise.resolve(); + flush.then(function () { return persistNow(); }) + .then(function () { return exportProject(id); }) + .catch(function (e) { toast(T('export_fail', { err: e.message }), 'err'); }); + }); + + $('#btnExportSite').addEventListener('click', function () { + rpc('cmd', { name: 'export', args: {} }).then(function (r) { + if (!r || r.ok === false) throw new Error((r && r.error) || T('导出失败')); + var slot = activeId ? findSlot(activeId) : null; + var filename = T('网站存档-') + safeFile(slot ? slot.name : 'gml') + '.json'; + var text = JSON.stringify(r.payload); + return api('export/file', { method: 'POST', body: { filename: filename, text: text } }).then(function (res) { + download(filename, text); + toast(T('export_site_ok', { path: res.path }), 'ok'); + }); + }).catch(function (e) { toast(T('export_fail', { err: e.message }), 'err'); }); + }); + + $('#btnImportBackup').addEventListener('click', function () { importMode = 'backup'; $('#fileInput').click(); }); + + document.addEventListener('click', function (e) { + var t = e.target; + var b = (t && t.closest) ? t.closest('[data-lang-set]') : null; + if (!b) return; + setUiLang(b.getAttribute('data-lang-set')); + }); + + $('#btnAppSource').addEventListener('click', openAppSource); + $('#btnAppFetch').addEventListener('click', function () { fetchLatestApp(); }); + $('#btnAppBuiltin').addEventListener('click', function () { restoreBuiltinApp(); }); + $('#appSrcCancel').addEventListener('click', function () { closeOverlay($('#appSrcOverlay')); }); + $('#appSrcOverlay').addEventListener('click', function (e) { if (e.target === this) closeOverlay(this); }); + $('#appSrcOk').addEventListener('click', function () { + var url = ($('#appSrcInput').value || '').trim(); + if (!/^https?:\/\//i.test(url)) { toast(T('app_url_invalid'), 'err'); return; } + APP_INFO.url = url; + closeOverlay($('#appSrcOverlay')); + renderAppCard(); + fetchLatestApp(); + }); + + /* 页面被隐藏时把待写数据立刻落盘,避免宿主回收后台进程时丢数据 */ + document.addEventListener('visibilitychange', function () { + if (document.visibilityState === 'hidden') { + if (frame) { try { rpc('flush', {}, 1500).catch(function () { }); } catch (e) { } } + persistNow().catch(function () { }); + } + }); + + /* ---------------- 启动 ---------------- */ + function boot() { + renderAppCard(); + loadState().then(function () { + return Promise.all([loadAppHtml(), loadBootSrc()]); + }).catch(function (e) { + toast(T('load_fail', { err: String((e && e.message) || e) }), 'err'); + }); + } + boot(); +})(); diff --git a/plugins/basetier-gml/miniapp-44928b90-e36d-46c5-9f7e-4d3d5ac5cda0/miniapp/miniapp.json b/plugins/basetier-gml/miniapp-44928b90-e36d-46c5-9f7e-4d3d5ac5cda0/miniapp/miniapp.json new file mode 100644 index 00000000..6ab2132e --- /dev/null +++ b/plugins/basetier-gml/miniapp-44928b90-e36d-46c5-9f7e-4d3d5ac5cda0/miniapp/miniapp.json @@ -0,0 +1,35 @@ +{ + "schemaVersion": 1, + "artifacts": { + "client": [ + "./miniapp/client" + ], + "node": [ + "./miniapp/node" + ] + }, + "runtime": { + "kind": "process", + "entry": "./miniapp/node/server.mjs", + "lifecycle": "on-demand" + }, + "surface": { + "path": "/app", + "window": { + "width": 1180, + "height": 820, + "minWidth": 480, + "minHeight": 360, + "resizable": true + } + }, + "mcpEndpoints": [ + { + "server": "gml-notes", + "path": "/mcp/gml-notes" + } + ], + "engines": { + "mcode": ">=3.1.11" + } +} diff --git a/plugins/basetier-gml/miniapp-44928b90-e36d-46c5-9f7e-4d3d5ac5cda0/miniapp/node/mcp.mjs b/plugins/basetier-gml/miniapp-44928b90-e36d-46c5-9f7e-4d3d5ac5cda0/miniapp/node/mcp.mjs new file mode 100644 index 00000000..0b695403 --- /dev/null +++ b/plugins/basetier-gml/miniapp-44928b90-e36d-46c5-9f7e-4d3d5ac5cda0/miniapp/node/mcp.mjs @@ -0,0 +1,420 @@ +/** + * 托管 MCP(Streamable HTTP):把练习存档的业务能力交给 Agent。 + * + * 挂在 Mini App 自己的 Node 服务上,路径见 miniapp/miniapp.json 的 mcpEndpoints。 + * 全部读写都走 store(数据目录里的存档文件),浏览器页面与 Agent 共用同一份数据。 + */ +import { randomUUID } from 'node:crypto'; + +const PREFIX = 'gml-practice-log-v2:'; +const SERVER_INFO = { name: 'gml-practice-notes', version: '1.1.0' }; + +/* ------------------------------ 工具定义 ------------------------------ */ +const TOOLS = [ + { + name: 'list_projects', + description: + '列出这台机器上的所有 GML 练习存档项目(每本互不干扰的学习笔记)。返回项目名、记录数、API 数、打卡天数、存档文件名与更新时间。', + inputSchema: { type: 'object', properties: {}, additionalProperties: false }, + }, + { + name: 'get_project', + description: + '读取一本练习存档的完整内容:练习记录(名称、题目要求、提示、代码载体)、API 库、打卡日历与设置。project 可填项目 ID 或项目名。', + inputSchema: { + type: 'object', + properties: { project: { type: 'string', description: '项目 ID 或项目名' } }, + required: ['project'], + additionalProperties: false, + }, + }, + { + name: 'search_notes', + description: + '跨所有练习存档搜索:匹配练习记录名称、题目要求、提示、代码文本,以及 API 名称与介绍。返回命中片段与出处。', + inputSchema: { + type: 'object', + properties: { + query: { type: 'string', description: '要搜索的关键词' }, + limit: { type: 'number', description: '最多返回多少条(默认 20)' }, + }, + required: ['query'], + additionalProperties: false, + }, + }, + { + name: 'list_api_library', + description: + '汇总 API 库:每个 GML 函数/内置变量的代码名、介绍与参数列表。可按项目过滤。不指定项目时汇总所有项目。', + inputSchema: { + type: 'object', + properties: { project: { type: 'string', description: '可选:只查某个项目' } }, + additionalProperties: false, + }, + }, + { + name: 'create_project', + description: '新建一本空白练习存档(学习笔记),用于换一个主题单独记录。', + inputSchema: { + type: 'object', + properties: { name: { type: 'string', description: '项目名称' } }, + required: ['name'], + additionalProperties: false, + }, + }, + { + name: 'export_backup', + description: + '把全部练习存档(含回收站)导出成一个 JSON 备份文件,落在 Mini App 数据目录的 exports 文件夹里。换设备或清缓存前用得上。', + inputSchema: { type: 'object', properties: {}, additionalProperties: false }, + }, +]; + +/* ------------------------------ 数据读取 ------------------------------ */ +/** 存档里的每一段都是 localStorage key → JSON 字符串 */ +function part(data, key) { + const raw = data && data[PREFIX + key]; + if (raw == null) return null; + try { + return JSON.parse(raw); + } catch { + return null; + } +} + +function apiListOf(data) { + const apis = part(data, 'api'); + if (!apis || typeof apis !== 'object') return []; + return Object.keys(apis).map((id) => { + const a = apis[id] || {}; + return { id, code: a.code || '', desc: a.desc || '', params: a.params || [] }; + }); +} + +function recordListOf(data) { + const records = part(data, 'records'); + if (!records || typeof records !== 'object') return []; + return Object.keys(records).map((id) => { + const r = records[id] || {}; + const modules = Array.isArray(r.modules) ? r.modules : []; + return { + id, + ts: r.ts || 0, + name: r.name || '', + requirement: r.requirement || '', + hint: r.hint || '', + modules: modules.map((m) => ({ + type: m && m.type ? m.type : '', + value: m && typeof m.value === 'string' ? m.value : '', + fields: m && Array.isArray(m.fields) ? m.fields : undefined, + events: m && Array.isArray(m.events) ? m.events : undefined, + })), + apiIds: Array.isArray(r.apis) ? r.apis : [], + }; + }); +} + +function daysOf(data) { + const days = part(data, 'days'); + return days && typeof days === 'object' ? days : {}; +} + +function findSlot(slots, key) { + const q = String(key || '').trim(); + if (!q) return null; + return ( + slots.find((s) => s.id === q) || + slots.find((s) => s.name === q) || + slots.find((s) => s.name.toLowerCase() === q.toLowerCase()) || + slots.find((s) => s.name.includes(q)) || + null + ); +} + +function clip(text, n) { + const s = String(text == null ? '' : text); + return s.length > n ? s.slice(0, n) + '…' : s; +} + +/* ------------------------------ 工具实现 ------------------------------ */ +function makeHandlers(store) { + return { + async list_projects() { + const scan = await store.scanProjects(); + const projects = scan.slots.map((s) => { + const records = part(s.data, 'records') || {}; + const apis = part(s.data, 'api') || {}; + const days = daysOf(s.data); + return { + id: s.id, + name: s.name, + file: s.file, + recordCount: Object.keys(records).length, + apiCount: Object.keys(apis).length, + checkinDays: Object.keys(days).length, + saveCount: s.saveCount || 0, + sizeBytes: s.fileSize || 0, + createdAt: s.createdAt, + updatedAt: s.updatedAt, + lastModified: s.fileModified, + }; + }); + return { total: projects.length, projects, skippedFiles: scan.skipped }; + }, + + async get_project(args) { + const scan = await store.scanProjects(); + const slot = findSlot(scan.slots, args && args.project); + if (!slot) { + const names = scan.slots.map((s) => s.name).join('、') || '无'; + throw new Error(`找不到项目:${args && args.project}(可用项目:${names})`); + } + const apis = apiListOf(slot.data); + const byId = new Map(apis.map((a) => [a.id, a])); + const records = recordListOf(slot.data).map((r) => ({ + ...r, + apis: r.apiIds.map((id) => byId.get(id)).filter(Boolean).map((a) => ({ code: a.code, desc: a.desc })), + })); + return { + id: slot.id, + name: slot.name, + note: slot.note || '', + file: slot.file, + createdAt: slot.createdAt, + updatedAt: slot.updatedAt, + saveCount: slot.saveCount || 0, + user: part(slot.data, 'user') || null, + settings: part(slot.data, 'settings') || null, + days: daysOf(slot.data), + records, + apiLibrary: apis.map((a) => ({ code: a.code, desc: a.desc, params: a.params })), + }; + }, + + async search_notes(args) { + const q = String((args && args.query) || '').trim().toLowerCase(); + if (!q) throw new Error('请给出搜索关键词'); + const limit = Math.max(1, Math.min(100, Number((args && args.limit) || 20))); + const scan = await store.scanProjects(); + const hits = []; + for (const slot of scan.slots) { + for (const r of recordListOf(slot.data)) { + const fields = [ + ['名称', r.name], + ['题目要求', r.requirement], + ['提示', r.hint], + ]; + for (const m of r.modules) fields.push([`载体·${m.type}`, m.value]); + for (const [label, text] of fields) { + const hay = String(text || '').toLowerCase(); + const at = hay.indexOf(q); + if (at >= 0) { + hits.push({ + project: slot.name, + projectId: slot.id, + recordId: r.id, + recordName: r.name, + field: label, + snippet: clip(String(text), 240), + matchedAt: at, + }); + } + } + } + for (const a of apiListOf(slot.data)) { + const hay = `${a.code}\n${a.desc}`.toLowerCase(); + if (hay.includes(q)) { + hits.push({ + project: slot.name, + projectId: slot.id, + apiCode: a.code, + field: 'API', + snippet: clip(`${a.code} — ${a.desc}`, 240), + }); + } + } + } + return { query: args && args.query, total: hits.length, hits: hits.slice(0, limit) }; + }, + + async list_api_library(args) { + const scan = await store.scanProjects(); + const slots = args && args.project ? [findSlot(scan.slots, args.project)].filter(Boolean) : scan.slots; + if (!slots.length) throw new Error(`找不到项目:${args && args.project}`); + const merged = new Map(); + for (const slot of slots) { + for (const a of apiListOf(slot.data)) { + const key = a.code || a.id; + if (!merged.has(key)) merged.set(key, { code: a.code, desc: a.desc, params: a.params, projects: [] }); + merged.get(key).projects.push(slot.name); + } + } + return { + total: merged.size, + apis: Array.from(merged.values()).map((a) => ({ + code: a.code, + desc: a.desc, + params: a.params, + usedIn: a.projects, + })), + }; + }, + + async create_project(args) { + const name = String((args && args.name) || '').trim(); + if (!name) throw new Error('项目名称不能为空'); + const scan = await store.scanProjects(); + const slot = { + id: 's' + Date.now().toString(36) + Math.random().toString(36).slice(2, 7), + name: await store.uniqueName(name, scan.slots), + note: '', + createdAt: Date.now(), + updatedAt: Date.now(), + saveCount: 0, + data: {}, + }; + await store.writeSlot(slot); + await store.writeIndex([...scan.slots, slot], (await store.readIndex())?.uiLang); + return { ok: true, id: slot.id, name: slot.name }; + }, + + async export_backup() { + const scan = await store.scanProjects(); + const trash = await store.readTrash(); + const payload = { + format: 'gml-pm-vault', + version: 2, + exportedAt: new Date().toISOString(), + saves: scan.slots, + trash, + }; + const filename = `gml存档库-${new Date().toISOString().slice(0, 10)}.json`; + const path = await store.saveExport(filename, JSON.stringify(payload)); + return { ok: true, filename, path, projects: scan.slots.length }; + }, + }; +} + +/* ------------------------------ MCP 协议 ------------------------------ */ +function jsonRpcError(id, code, message) { + return { jsonrpc: '2.0', id: id === undefined ? null : id, error: { code, message } }; +} + +function jsonRpcResult(id, result) { + return { jsonrpc: '2.0', id: id === undefined ? null : id, result }; +} + +async function readBody(req) { + const chunks = []; + for await (const chunk of req) chunks.push(chunk); + if (!chunks.length) return null; + const text = Buffer.concat(chunks).toString('utf8'); + try { + return JSON.parse(text); + } catch { + return null; + } +} + +function sendJson(res, status, body, headers) { + const text = JSON.stringify(body); + res.writeHead(status, { + 'content-type': 'application/json; charset=utf-8', + 'content-length': Buffer.byteLength(text), + ...(headers || {}), + }); + res.end(text); +} + +/** + * @param {object} store createStore() 返回的数据服务 + * @returns {(req: import('node:http').IncomingMessage, res: import('node:http').ServerResponse) => Promise} + */ +export function createMcpHandler(store) { + const handlers = makeHandlers(store); + const sessionId = randomUUID(); + + async function callTool(name, args) { + const fn = handlers[name]; + if (!fn) throw new Error(`未知工具:${name}`); + const data = await fn(args || {}); + return { content: [{ type: 'text', text: JSON.stringify(data, null, 2) }] }; + } + + async function handleOne(msg) { + const { id, method, params } = msg || {}; + if (!method) return jsonRpcError(id, -32600, '缺少 method'); + + if (method === 'initialize') { + return { + __headers: { 'mcp-session-id': sessionId }, + body: jsonRpcResult(id, { + protocolVersion: (params && params.protocolVersion) || '2025-06-18', + capabilities: { tools: { listChanged: false } }, + serverInfo: SERVER_INFO, + }), + }; + } + if (method === 'notifications/initialized' || method === 'notifications/cancelled') return null; + if (method === 'ping') return jsonRpcResult(id, {}); + if (method === 'tools/list') return jsonRpcResult(id, { tools: TOOLS }); + if (method === 'tools/call') { + const name = params && params.name; + try { + return jsonRpcResult(id, await callTool(name, params && params.arguments)); + } catch (error) { + const message = String((error && error.message) || error); + return jsonRpcResult(id, { content: [{ type: 'text', text: `执行失败:${message}` }], isError: true }); + } + } + return jsonRpcError(id, -32601, `不支持的方法:${method}`); + } + + return async function handleMcp(req, res) { + const method = (req.method || 'GET').toUpperCase(); + + if (method === 'GET') { + /* 本服务不主动推送事件,客户端不需要 SSE 通道 */ + res.writeHead(405, { + 'content-type': 'application/json; charset=utf-8', + allow: 'POST, DELETE', + }); + res.end(JSON.stringify(jsonRpcError(null, -32000, '该服务不提供服务器端事件流'))); + return; + } + if (method === 'DELETE') { + res.writeHead(204); + res.end(); + return; + } + if (method !== 'POST') { + sendJson(res, 405, jsonRpcError(null, -32000, '仅支持 POST')); + return; + } + + const body = await readBody(req); + if (body === null) { + sendJson(res, 400, jsonRpcError(null, -32700, 'JSON 解析失败')); + return; + } + + const list = Array.isArray(body) ? body : [body]; + const out = []; + let headers = null; + for (const msg of list) { + const r = await handleOne(msg); + if (!r) continue; + if (r.__headers) { + headers = { ...(headers || {}), ...r.__headers }; + delete r.__headers; + } + out.push(r); + } + if (!out.length) { + res.writeHead(202, headers || {}); + res.end(); + return; + } + sendJson(res, 200, Array.isArray(body) ? out : out[0], headers); + }; +} diff --git a/plugins/basetier-gml/miniapp-44928b90-e36d-46c5-9f7e-4d3d5ac5cda0/miniapp/node/miniapp-api.ts b/plugins/basetier-gml/miniapp-44928b90-e36d-46c5-9f7e-4d3d5ac5cda0/miniapp/node/miniapp-api.ts new file mode 100644 index 00000000..5276c6f8 --- /dev/null +++ b/plugins/basetier-gml/miniapp-44928b90-e36d-46c5-9f7e-4d3d5ac5cda0/miniapp/node/miniapp-api.ts @@ -0,0 +1,641 @@ +/** + * Agent-facing Mini App runtime authoring declarations. + * + * Copy this file into a generated plugin for type checking. It contains no Host implementation; + * the Host injects runtime values through start(context). + * Keep the .ts filename: Electron packaging excludes .d.ts files from dependency assets. + */ +export type JsonPrimitive = null | boolean | number | string; +export type JsonValue = JsonPrimitive | JsonObject | readonly JsonValue[]; +export type JsonObject = { readonly [key: string]: JsonValue }; + +declare const HOST_CONNECTOR_TOOL_REF: unique symbol; +export type HostConnectorToolRef = string & { + readonly [HOST_CONNECTOR_TOOL_REF]: 'HostConnectorToolRef'; +}; + +export interface HostConnectorTool { + readonly toolRef: HostConnectorToolRef; + readonly provider: string; + readonly name: string; + readonly description?: string; + readonly inputSchema: JsonValue; + readonly outputSchema?: JsonValue; +} + +export interface HostConnectorListResult { + readonly tools: readonly HostConnectorTool[]; + readonly partial: boolean; +} + +export interface HostConnectorCallOptions { + readonly signal?: AbortSignal; +} + +export interface HostConnectorCallResult { + readonly invocationId: string; + /** + * Raw provider result; it is not normalized by the Host and may be an object, array, or primitive. + * A single text-block array is one provider shape, not a global Host transport contract. + * Decode only a probe-observed envelope; preserve every other value, including direct strings. + */ + readonly value: JsonValue; +} + +export interface HostConnectorClient { + /** Candidate-safe inventory only; available before and after activation. */ + list(options?: HostConnectorCallOptions): Promise; + /** Activation-only business dispatch; call from request handling, never start(context). */ + call( + toolRef: HostConnectorToolRef, + arguments_: JsonObject, + options?: HostConnectorCallOptions, + ): Promise; +} + +export type HostConnectorErrorDisposition = + | 'not_dispatched' + | 'provider_reported' + | 'unknown_after_dispatch'; + +export type HostConnectorErrorCode = + | 'TOOL_REF_STALE' + | 'SERVICE_RESTARTED' + | 'REQUEST_CANCELLED' + | 'CONNECTOR_TIMEOUT' + | 'INVALID_ARGUMENTS' + | 'CONNECTOR_PROVIDER_ERROR' + | 'CONNECTOR_UNAVAILABLE' + /** The user switched this provider off for the Mini App; not dispatched. */ + | 'CONNECTOR_NOT_PERMITTED' + | 'CONNECTOR_OUTCOME_UNKNOWN'; + +export interface HostConnectorError extends Error { + readonly code: HostConnectorErrorCode; + readonly disposition: HostConnectorErrorDisposition; + readonly retryable: boolean; + readonly invocationId?: string; + readonly diagnostic?: { + readonly issues: readonly { + readonly path: string; + readonly constraint: string; + readonly limit?: number; + }[]; + }; +} + +/** What a call would meet now under the user's global permission rules; informational only. */ +export type MiniAppToolPermission = 'allow' | 'ask' | 'deny'; + +/** + * `name` is the runtime name an Agent sees (`mcp____`, `connector____`). + * Take it from `list()`; do not build it. + */ +export type MiniAppTool = + | { + readonly name: string; + readonly kind: 'connector'; + readonly provider: string; + readonly tool: string; + readonly description?: string; + readonly inputSchema: JsonValue; + readonly permission: MiniAppToolPermission; + } + | { + readonly name: string; + readonly kind: 'mcp'; + /** Any installed MCP server: a Plugin's, the user's `mcp.json`, or a Host built-in one. */ + readonly server: string; + readonly tool: string; + readonly description?: string; + readonly inputSchema: JsonValue; + readonly permission: MiniAppToolPermission; + }; + +export interface MiniAppToolListResult { + readonly tools: readonly MiniAppTool[]; + /** A source could not be listed; the listed tools are still callable. */ + readonly partial: boolean; +} + +export type MiniAppToolCallResult = + | { + readonly invocationId: string; + readonly kind: 'connector'; + /** Raw provider result, as in `HostConnectorCallResult.value`. */ + readonly value: JsonValue; + } + | { + readonly invocationId: string; + readonly kind: 'mcp'; + /** The MCP tool reported its own failure; `content` keeps its error text. */ + readonly isError: boolean; + /** MCP content blocks such as `{ type: 'text', text }`, passed through as JSON. */ + readonly content: readonly JsonValue[]; + readonly structuredContent?: JsonObject; + }; + +/** + * Thrown with the `HostConnectorError` shape; Connector tools keep their Connector codes too. The + * code names the cause; `disposition` alone says whether the tool may have run (`TOOL_TIMEOUT` and + * `REQUEST_CANCELLED` can be either `not_dispatched` or `unknown_after_dispatch`). + */ +export type MiniAppToolErrorCode = + | HostConnectorErrorCode + | 'INVALID_ARGUMENTS' + | 'TOOL_NOT_PERMITTED' + | 'TOOL_APPROVAL_REQUIRED' + | 'TOOL_REF_STALE' + | 'TOOL_UNAVAILABLE' + | 'TOOL_TIMEOUT' + | 'TOOL_RESULT_TOO_LARGE' + | 'TOOL_OUTCOME_UNKNOWN' + | 'MCP_SERVER_UNAVAILABLE' + | 'REQUEST_CANCELLED' + | 'SERVICE_RESTARTED'; + +/** + * Present whenever the manifest declares `"toolAccess": ["call"]`, even when the user switched + * `tool:call` off: calls then fail with `TOOL_NOT_PERMITTED`. Every `call` is judged by the user's + * global permission rules: `deny` is `TOOL_NOT_PERMITTED`, `ask` shows a Host prompt, and nobody to + * ask is `TOOL_APPROVAL_REQUIRED`. `list` works before activation; call `call` only from request + * handling after activation. Connector tools time out after 30 s and MCP tools after at most 120 s, + * counted after any prompt. The Host never retries; reconcile an `unknown_after_dispatch` outcome + * before repeating a write. + */ +export interface MiniAppToolClient { + list(options?: HostConnectorCallOptions): Promise; + call( + name: string, + arguments_: JsonObject, + options?: HostConnectorCallOptions, + ): Promise; + /** + * One Host prompt for the named tools (1–10, from `list()`) still at `ask`; the user ticks which + * to always allow. Resolves every name's state afterwards (for your UI only). When nobody can be + * asked it rejects with `TOOL_APPROVAL_REQUIRED` whose error carries `permissions`. With + * `tool:call` switched off it answers `deny` for every name without a prompt. + * Needs `capabilities.has('tool.request')`. + */ + request( + names: readonly string[], + options?: HostConnectorCallOptions, + ): Promise>; +} + +export interface MiniAppLogger { + debug(message: string, fields?: JsonObject): void; + info(message: string, fields?: JsonObject): void; + warn(message: string, fields?: JsonObject): void; + error(message: string, fields?: JsonObject): void; +} + +/** + * How the call's text ended: in its own turn (`finished` / `error` / `aborted`), or, only with + * `whenBusy`, joined into the turn that was already running (`steered`; that turn's own + * call gets the reply). + */ +export type MiniAppAgentRunStatus = 'finished' | 'error' | 'aborted' | 'steered'; + +/** + * The Desktop composer's follow-up behaviours while a session runs a turn. `queue`: the text runs + * as the next turn and the call follows it. `steer`: the running turn reads the text at its next + * input point (the call resolves `steered`), or, if it answered first, the text runs as the next + * turn and the call follows it. + */ +export type MiniAppAgentWhenBusy = 'queue' | 'steer'; + +export type MiniAppAgentQuestionMode = 'questionnaire' | 'feature-enable' | 'plan'; + +export interface MiniAppAgentQuestionOption { + readonly id: string; + readonly label: string; + readonly description?: string; +} + +export interface MiniAppAgentQuestionStep { + readonly id: string; + readonly header?: string; + readonly question: string; + readonly description?: string; + readonly selectionMode: 'single' | 'multiple'; + readonly options: readonly MiniAppAgentQuestionOption[]; + /** Free-text "other" is always accepted; see `MiniAppAgentQuestionAnswer.otherText`. */ + readonly allowOther: true; +} + +/** Same questionnaire the Host chat renders; render every step and answer each one. */ +export interface MiniAppAgentQuestionnaire { + readonly schemaVersion: 2; + readonly id: string; + readonly title?: string; + readonly steps: readonly MiniAppAgentQuestionStep[]; + readonly mode?: MiniAppAgentQuestionMode; + /** Plan review Markdown and other mode-specific data. */ + readonly modePayload?: JsonObject; + /** Unix ms; the request is withdrawn after this. */ + readonly expiresAt?: number; +} + +export interface MiniAppAgentQuestionAnswer { + readonly stepId: string; + readonly selectedOptionIds: readonly string[]; + readonly selectedOther: boolean; + readonly otherText?: string; + readonly skipped?: boolean; +} + +/** A model as the Host's composer selects it; take the values from `models()`. */ +export interface MiniAppAgentModelSelection { + readonly providerId: string; + readonly modelId: string; + /** `''` means thinking is off; it is preserved, distinct from an absent `variant`. */ + readonly variant?: string; + readonly thinking?: { readonly effort: string }; +} + +/** One model this user can use. */ +export interface MiniAppAgentModelOption { + readonly providerId: string; + readonly modelId: string; + readonly displayName: string; + readonly variants?: readonly string[]; + readonly thinking?: { readonly efforts: readonly string[]; readonly default?: string }; +} + +export interface MiniAppAgentModels { + readonly models: readonly MiniAppAgentModelOption[]; + /** What a Node-created session starts with. */ + readonly default: MiniAppAgentModelSelection; +} + +export interface MiniAppAgentAgentOption { + /** Canonical name; what `agent` takes. */ + readonly name: string; + readonly displayName: string; + /** The default agent. */ + readonly primary: boolean; +} + +export interface MiniAppAgentAgents { + readonly agents: readonly MiniAppAgentAgentOption[]; +} + +export interface MiniAppAgentRunResult { + /** Pass back in `run({ sessionId })` to continue the same conversation. */ + readonly sessionId: string; + /** Absent when no turn ran: an `answer` accepted without starting a continuation. */ + readonly turnId?: string; + /** The model the turn was dispatched with; absent when no turn ran or the text was steered. */ + readonly model?: MiniAppAgentModelSelection; + /** `aborted` only when the Host confirmed the abort; an unconfirmed one rejects with `AGENT_OUTCOME_UNKNOWN`. */ + readonly status: MiniAppAgentRunStatus; + /** Final assistant reply; absent when the turn produced none or did not finish. */ + readonly text?: string; + readonly error?: { readonly code: string; readonly message: string }; + /** Set when the turn ended waiting on a questionnaire; render `request` and continue with `agent.answer`. */ + readonly pendingQuestion?: { + readonly requestId: string; + readonly mode: MiniAppAgentQuestionMode; + readonly request: MiniAppAgentQuestionnaire; + }; +} + +/** + * Progress of one run. `turnId` matches the result's, except that a `permission.requested` raised + * by a delegated child session carries that child's own `sessionId` and `turnId`; `reply` with + * those, and do not filter events by the root turn. Ignore unknown `type` values: new event + * types may be added without notice. + * - `run.queued`: the call waits at 1-based `position`, for a run slot or, with + * `whenBusy: 'queue'`, in the session queue (a `whenBusy` call can get both); sent before the + * turn starts, so it has no `turnId` and names a session only when continuing one. + * - `message.pending` / `message.steered`: with `whenBusy: 'steer'`, the text was handed to the + * running turn, then read by it; `message.steered` is the call's last event. + * - `turn.started`: the Agent began the turn; `model` is the model it was dispatched with. + * - `text.delta`: a piece of the reply as it streams. + * - `message.committed`: one complete assistant message (a turn can have several). + * - `tool.started` / `tool.finished`: a tool call by name; `ok` is false when it failed. + * - `turn.finished`: last unless the call ended `steered`; same `status`, `text`, and `error` + * as the run result. + */ +/** + * Every event except `run.queued` names its session, so `reply` can be called from `onEvent` even + * before the `run` that created the session has returned. `answer` cannot: the paused `run` still holds the + * session's single-run slot while `question.requested` is delivered, so call `answer` only after + * that `run` resolves (an earlier call rejects with `BUSY`). Ignore event types you do not know. + */ +export type MiniAppAgentRunEvent = + | { readonly type: 'run.queued'; readonly sessionId?: string; readonly position: number } + | { + readonly type: 'message.pending' | 'message.steered'; + readonly sessionId: string; + readonly turnId: string; + } + | { + readonly type: 'turn.started'; + readonly sessionId: string; + readonly turnId: string; + readonly model: MiniAppAgentModelSelection; + } + | { + readonly type: 'text.delta'; + readonly sessionId: string; + readonly turnId: string; + readonly text: string; + } + | { + readonly type: 'message.committed'; + readonly sessionId: string; + readonly turnId: string; + readonly text: string; + } + | { + readonly type: 'tool.started'; + readonly sessionId: string; + readonly turnId: string; + readonly name: string; + } + | { + readonly type: 'tool.finished'; + readonly sessionId: string; + readonly turnId: string; + readonly name: string; + readonly ok: boolean; + } + /** A tool call is waiting for approval; decide it with `agent.reply`. */ + | { + readonly type: 'permission.requested'; + readonly sessionId: string; + /** Absent when the runtime did not attribute the ask to a turn. */ + readonly turnId?: string; + readonly requestId: string; + readonly toolName: string; + readonly toolInput?: string; + readonly reason: string; + } + /** The turn paused on a questionnaire; continue with `agent.answer`. */ + | { + readonly type: 'question.requested'; + readonly sessionId: string; + readonly turnId?: string; + readonly requestId: string; + readonly mode: MiniAppAgentQuestionMode; + readonly request: MiniAppAgentQuestionnaire; + } + | { + readonly type: 'turn.finished'; + readonly sessionId: string; + readonly turnId: string; + readonly status: Exclude; + readonly text?: string; + readonly error?: { readonly code: string; readonly message: string }; + }; + +/** `observe({ all: true })` only: the conversation's title, when it has one. */ +interface MiniAppAgentObservedTitle { + readonly title?: string; +} + +type MiniAppAgentRunEventOf = Extract< + MiniAppAgentRunEvent, + { readonly type: T } +>; + +/** + * What an observer receives: the run events without `run.queued` and without asks, which reach + * only the run that owns them. `turn.started.model` is present only when the Host could read it. + * Ignore unknown `type` values. + */ +export type MiniAppAgentObservedEvent = + | (Omit, 'model'> & { + readonly model?: MiniAppAgentModelSelection; + } & MiniAppAgentObservedTitle) + | MiniAppAgentRunEventOf<'text.delta' | 'tool.started' | 'tool.finished'> + | (MiniAppAgentRunEventOf<'message.committed'> & MiniAppAgentObservedTitle) + | (MiniAppAgentRunEventOf<'turn.finished'> & MiniAppAgentObservedTitle); + +/** + * `{ all: true }`: `turn.started`, `message.committed` (the final reply) and `turn.finished` of + * every user conversation, with its `title`. `{ sessionId }`: every progress event of that + * session, turn after turn. Exactly one of the two. + */ +export type MiniAppAgentObserveTarget = { readonly sessionId: string } | { readonly all: true }; + +/** One of the user's conversations; `running` while a turn is in flight. */ +export interface MiniAppAgentSessionSummary { + readonly sessionId: string; + readonly title?: string; + /** The Agent the session runs. */ + readonly agent: string; + readonly status: 'idle' | 'running' | 'error' | 'aborted'; + /** The conversation's project directory (absolute) as recorded; it may no longer exist. */ + readonly workspaceDir: string; + /** True when the conversation has no project and runs in the default workspace. */ + readonly isDefaultWorkspace: boolean; + /** Unix ms. */ + readonly createdAtMs: number; + /** Unix ms. */ + readonly updatedAtMs: number; +} + +export interface MiniAppAgentSessionDetail extends MiniAppAgentSessionSummary { + /** The conversation's current model; absent when the Host has none recorded. */ + readonly model?: MiniAppAgentModelSelection; + /** Only while `status` is `error` and the Host recorded a message. */ + readonly error?: { readonly message: string }; + /** Final text of the latest Agent reply, if any. */ + readonly lastAssistantText?: string; +} + +export interface MiniAppAgentSessions { + /** The 50 most recently updated user conversations (no Mini App, scheduled or sub-Agent ones). */ + readonly sessions: readonly MiniAppAgentSessionSummary[]; +} + +export interface MiniAppAgentRunOptions { + readonly signal?: AbortSignal; + readonly onEvent?: (event: MiniAppAgentRunEvent) => void; +} + +export type MiniAppAgentErrorCode = + | 'NOT_PERMITTED' + | 'BUSY' + | 'SESSION_NOT_FOUND' + | 'INVALID_ARGUMENTS' + | 'AGENT_UNAVAILABLE' + | 'REQUEST_CANCELLED' + | 'AGENT_OUTCOME_UNKNOWN' + | 'REQUEST_NOT_FOUND'; + +export interface MiniAppAgentError extends Error { + readonly code: MiniAppAgentErrorCode; + /** + * True when nothing was started and the same call may be retried later. + * `AGENT_OUTCOME_UNKNOWN` is never retryable: the turn may have run. + */ + readonly retryable: boolean; + /** + * Set on every `BUSY`: the session is running a turn, compacting, or has messages queued ahead + * (the text reached no turn), the wait queue is full, the per-minute start cap was hit, or + * `observe` found 4 observers already running. + */ + readonly reason?: 'session_busy' | 'queue_full' | 'rate_limited' | 'observer_limit'; +} + +/** + * Present when the manifest declares `agentAccess` (`"session.run"` and/or `"session.read"`). + * `run` / `reply` / `answer` / `models` / `agents` / `create` need `session.run`; `observe` and + * `sessions` need `session.read` except for this Mini App's own sessions (see + * agent-interaction.md). + * A new Node session uses the primary Agent unless `agent` names one from `agents()`, and works in + * this Mini App's own Agent directory and on the runtime default model; + * continuing a session keeps its Agent, directory and model (unless `model` switches it), including + * one a page created using its host chat's Agent, project directory and model; a session never + * changes its Agent. Runs one turn with that Agent's full capabilities + * (files, shell, Skills, MCP including this Mini App's own), and resolves when the turn ends. + * + * Interaction is yours to render: pass `onEvent` and handle `permission.requested` with + * `reply` and `question.requested` with `answer`. A permission request waits only while + * someone can answer it: this run passed `onEvent`, or a page of this Mini App currently has + * the session open in a chat side panel via `open`. Otherwise it is denied (the model is told + * why), and a questionnaire ends the turn with `result.pendingQuestion`. A run waiting on a + * permission is released by `cancel`/abort, process exit or republish. Up to `agentConcurrency` + * runs (default 4) per Mini App run at once; further `run` / `answer` calls wait in order (up to + * four times that many, see `run.queued`), and aborting a waiting call rejects it with + * `REQUEST_CANCELLED`. A `whenBusy` call on a session that already has a call in flight shares + * that call's slot. Cancelling a queued `whenBusy` text removes it (`REQUEST_CANCELLED`); a steered + * text cannot be withdrawn (`AGENT_OUTCOME_UNKNOWN`, the running turn goes on). + */ +export interface MiniAppAgentClient { + run( + input: { + readonly text: string; + readonly sessionId?: string; + /** + * Switch the session to this model before the turn (validated like the composer validates a + * new session's model: it must be one `models()` lists; unusable is `INVALID_ARGUMENTS`, + * missing BYOK credentials end the turn with `status: 'error'`); the session keeps it. Omit to use the session's current model. + */ + readonly model?: MiniAppAgentModelSelection; + /** + * Only when starting a session (no `sessionId`): an agent `name` from `agents()`. Passing it + * with `sessionId` is `INVALID_ARGUMENTS`. + */ + readonly agent?: string; + /** + * Only with `sessionId`: what to do when that session is already running a turn; on an idle + * session the call starts a turn as usual. Omit to reject with `BUSY` (`session_busy`). + */ + readonly whenBusy?: MiniAppAgentWhenBusy; + }, + options?: MiniAppAgentRunOptions, + ): Promise; + /** + * Decide a pending permission request. Never writes the user's global rules. Node replies + * have 16 separate pending slots; `run` / `answer` / `models` / `agents` / `create` and Connector + * requests share another 16. Filling that ordinary budget still permits replies. A full reply + * budget rejects with retryable `AGENT_UNAVAILABLE`. + */ + reply(input: { + readonly sessionId: string; + readonly requestId: string; + readonly decision: 'allowOnce' | 'deny'; + }): Promise; + /** + * Answer a questionnaire; the continuation turn is observed like `run`. Rejects with + * `AGENT_OUTCOME_UNKNOWN` when the answer was recorded but the continuation turn was not observed. + */ + answer( + input: { + readonly sessionId: string; + readonly requestId: string; + readonly answers: readonly MiniAppAgentQuestionAnswer[]; + /** Same as `run`'s `model`, applied before the continuation turn. */ + readonly model?: MiniAppAgentModelSelection; + }, + options?: MiniAppAgentRunOptions, + ): Promise; + /** + * Returns the model catalog and runtime `default`. Pass `default` directly as `model` to + * `run` / `answer`. For a catalog entry, extract `providerId` / `modelId`, add a selected `variant` + * if needed and preserve `variant: ''`. If thinking is supported, select an effort from + * `thinking.efforts` and pass `thinking: { effort }`. + */ + models(): Promise; + /** The agents the user has configured; `agent` of `create` / a first `run` must be one of them. */ + agents(): Promise; + /** + * Create a session (agent, this Mini App's Agent directory, the runtime default model) without + * running a turn, and return its `sessionId`; continue it with `run({ sessionId })`. A page's + * `create` binds the session to its chat instead, and its `sessionId` can be continued here. + * Takes no Host run slot but uses the ordinary Node request budget. `agent` picks the session's + * agent from `agents()`; a session never changes it. + */ + create(input?: { readonly agent?: string }): Promise<{ readonly sessionId: string }>; + /** + * Watch the user's Agent at work (see `MiniAppAgentObserveTarget`). No request timeout; abort + * `signal` to stop, after which `onEvent` gets nothing more. Resolves when the subscription + * ended: `signal` aborted, the session was deleted, the process is stopping or being replaced, + * or `session.read` was switched off. + * Rejects with a `MiniAppAgentError` when it could not start or failed: `INVALID_ARGUMENTS` (not + * exactly one target), `NOT_PERMITTED`, `SESSION_NOT_FOUND`, retryable `BUSY` past 4 observers + * per Mini App (`reason: 'observer_limit'`) or `AGENT_UNAVAILABLE`. Observers use no run slots + * and no ordinary request budget. Check `context.capabilities?.has('agent.observe')` first. + */ + observe( + target: MiniAppAgentObserveTarget, + options: { + readonly onEvent: (event: MiniAppAgentObservedEvent) => void; + readonly signal?: AbortSignal; + }, + ): Promise; + /** Check `context.capabilities?.has('agent.sessions')` first. */ + sessions(): Promise; + /** + * One conversation with its model and latest reply. `sessionId` is required: Node serves every + * tab, so it has no current chat; a page passes its chat's id (from its own `session()`). + * Check `context.capabilities?.has('agent.session')`. + */ + session(sessionId: string): Promise; +} + +export interface MiniAppLifecycle { + dispose(): void | Promise; +} + +export interface MiniAppContext { + readonly pluginId: string; + readonly pluginRoot: string; + readonly dataDir: string; + readonly listen: Readonly<{ readonly host: '127.0.0.1'; readonly port: number }>; + readonly signal: AbortSignal; + readonly logger: MiniAppLogger; + /** + * Synchronous probe of Host features, fixed per Host version. It says nothing about this + * Mini App's manifest or authorization: `has('agent.run')` is true on a Host that supports the + * Agent API even when `context.agent` is absent because `agentAccess` was not declared. + * Older Hosts do not inject `capabilities`; check `context.capabilities?.has(...)`. + */ + readonly capabilities?: MiniAppHostCapabilities; + /** + * Present when the manifest declares a `hostConnectorAccess` provider; a provider the user + * switched off is missing from `list()` and its calls fail with `CONNECTOR_NOT_PERMITTED`. + */ + readonly hostConnector?: HostConnectorClient; + /** Installed MCP and Connector tools, each call judged by the user's permission rules. */ + readonly tool?: MiniAppToolClient; + /** + * Present when the manifest declares `agentAccess: ["session.run"]`; while the user has it + * switched off, calls fail with `NOT_PERMITTED`. + */ + readonly agent?: MiniAppAgentClient; +} + +export interface MiniAppHostCapabilities { + has(name: string): boolean; +} + +export interface MiniAppModule { + /** Resolve only after the listener accepts connections and every route is installed. */ + start(context: MiniAppContext): Promise; +} diff --git a/plugins/basetier-gml/miniapp-44928b90-e36d-46c5-9f7e-4d3d5ac5cda0/miniapp/node/server.mjs b/plugins/basetier-gml/miniapp-44928b90-e36d-46c5-9f7e-4d3d5ac5cda0/miniapp/node/server.mjs new file mode 100644 index 00000000..100841ec --- /dev/null +++ b/plugins/basetier-gml/miniapp-44928b90-e36d-46c5-9f7e-4d3d5ac5cda0/miniapp/node/server.mjs @@ -0,0 +1,892 @@ +/** + * GML 练习记录 · Mini App 运行时 + * + * 数据目录(Host 注入的 dataDir): + * GML-Saves/ 项目存档文件:<名称>..json + save-index.json + * GML-Trash/ 回收站:.<删除时间>.json + trash-index.json + * GML-App/ 打卡网页版本:app.html + app-meta.json + * exports/ 用户导出的备份文件 + * + * 所有写入都走这一层(校验 → 落盘 → 再广播),浏览器端只负责界面。 + */ +import { createServer } from 'node:http'; +import { mkdir, readFile, writeFile, rename, readdir, rm, stat } from 'node:fs/promises'; +import { join } from 'node:path'; +import { createMcpHandler } from './mcp.mjs'; + +const PREFIX = 'gml-practice-log-v2:'; +const PATHS = { + proj: 'GML-Saves', + trash: 'GML-Trash', + index: 'save-index.json', + trashIndex: 'trash-index.json', + appDir: 'GML-App', + appFile: 'app.html', + appMeta: 'app-meta.json', + exports: 'exports', +}; +const APP_DEFAULT_URL = 'https://basetier-gml.github.io/gml-practice-log/'; +const APP_MAX_BYTES = 8 * 1024 * 1024; + +/* ------------------------------ 小工具 ------------------------------ */ +function uid() { + return 's' + Date.now().toString(36) + Math.random().toString(36).slice(2, 7); +} +function safeFile(s) { + return String(s || '存档').replace(/[\\/:*?"<>|]/g, '_').slice(0, 48); +} +function stableId(name) { + let h = 2166136261; + for (let i = 0; i < name.length; i += 1) { + h ^= name.charCodeAt(i); + h = Math.imul(h, 16777619); + } + return 'f' + (h >>> 0).toString(36); +} +function clone(o) { + return o === undefined ? o : JSON.parse(JSON.stringify(o)); +} +function appVersionOf(html) { + let h = 5381; + const lim = Math.min(html.length, 200000); + for (let i = 0; i < lim; i += 1) h = ((h << 5) + h + html.charCodeAt(i)) | 0; + return html.length.toString(36) + '-' + (h >>> 0).toString(36); +} +function hasStorageKeys(o) { + if (!o || typeof o !== 'object') return false; + return Object.keys(o).some((k) => k.indexOf(PREFIX) === 0); +} + +/* ------------------------------ 存储层 ------------------------------ */ +function createStore(dataDir) { + const projDir = join(dataDir, PATHS.proj); + const trashDir = join(dataDir, PATHS.trash); + const appDir = join(dataDir, PATHS.appDir); + const exportDir = join(dataDir, PATHS.exports); + const builtinAppPath = join(dataDir, '..', 'unused'); + + async function ensureDirs() { + await mkdir(projDir, { recursive: true }); + await mkdir(trashDir, { recursive: true }); + await mkdir(appDir, { recursive: true }); + await mkdir(exportDir, { recursive: true }); + } + + async function readJson(dir, name) { + try { + return JSON.parse(await readFile(join(dir, name), 'utf8')); + } catch { + return null; + } + } + + /** 原子写:同目录临时文件 → rename,避免宿主强制结束进程时留下半个文件。 */ + async function writeJson(dir, name, obj) { + const target = join(dir, name); + const tmp = join(dir, `.${name}.tmp`); + await writeFile(tmp, JSON.stringify(obj), 'utf8'); + await rename(tmp, target); + return name; + } + + async function writeText(dir, name, text) { + const target = join(dir, name); + const tmp = join(dir, `.${name}.tmp`); + await writeFile(tmp, text, 'utf8'); + await rename(tmp, target); + return name; + } + + async function listFiles(dir) { + try { + const entries = await readdir(dir, { withFileTypes: true }); + return entries.filter((e) => e.isFile()).map((e) => e.name); + } catch { + return []; + } + } + + async function fileMeta(dir, name) { + try { + const st = await stat(join(dir, name)); + return { size: st.size, lastModified: st.mtimeMs }; + } catch { + return null; + } + } + + /* 把任意一个 json 文件解析成一条存档记录;返回 null 表示不是存档 */ + function parseSaveFile(obj, name, lastModified) { + if (!obj || typeof obj !== 'object' || Array.isArray(obj)) return null; + const out = { format: '', name: '', id: '', note: '', createdAt: 0, updatedAt: 0, saveCount: 0, data: {}, siteBackup: null }; + + const sv = obj.format === 'gml-pm-save' && obj.save && typeof obj.save === 'object' + ? obj.save + : (obj.save && obj.save.data && typeof obj.save.data === 'object' ? obj.save : null); + if (sv) { + out.format = obj.format || 'gml-pm-save'; + out.data = sv.data && typeof sv.data === 'object' ? sv.data : {}; + out.name = String(sv.name || name.replace(/\.json$/i, '')); + out.id = String(sv.id || '') || stableId(name); + out.note = String(sv.note || ''); + out.createdAt = Number(sv.createdAt) || lastModified || Date.now(); + out.updatedAt = Number(sv.updatedAt) || lastModified || Date.now(); + out.saveCount = Number(sv.saveCount) || 0; + out.siteBackup = sv.siteBackup || null; + return out; + } + + let site = null; + if (obj.app && obj.data && typeof obj.data === 'object') site = obj; + else if (obj.records || obj.apiLib || obj.apiById || obj.dailyGoal || obj.nickname) site = obj; + if (site) { + out.format = 'site-native'; + out.name = name.replace(/\.json$/i, ''); + out.id = stableId(name); + out.createdAt = lastModified || Date.now(); + out.updatedAt = lastModified || Date.now(); + out.data = {}; + out.siteBackup = site; + return out; + } + + if (hasStorageKeys(obj)) { + out.format = 'fragmented'; + out.name = name.replace(/\.json$/i, ''); + out.id = stableId(name); + out.createdAt = lastModified || Date.now(); + out.updatedAt = lastModified || Date.now(); + out.data = obj; + return out; + } + return null; + } + + /** 扫描项目目录:项目列表的唯一数据源 */ + async function scanProjects() { + const names = (await listFiles(projDir)).filter((n) => /\.json$/i.test(n) && n !== PATHS.index).sort(); + const slots = []; + const skipped = []; + for (const name of names) { + const meta = await fileMeta(projDir, name); + let obj = null; + try { + obj = JSON.parse(await readFile(join(projDir, name), 'utf8')); + } catch (e) { + skipped.push({ name, reason: String((e && e.message) || e) }); + continue; + } + const parsed = parseSaveFile(obj, name, meta ? meta.lastModified : Date.now()); + if (!parsed) { + skipped.push({ name, reason: '不是存档格式' }); + continue; + } + slots.push({ + id: parsed.id, + name: parsed.name, + note: parsed.note, + createdAt: parsed.createdAt, + updatedAt: parsed.updatedAt, + saveCount: parsed.saveCount, + data: parsed.data, + siteBackup: parsed.siteBackup, + file: name, + fileSize: meta ? meta.size : 0, + fileModified: meta ? meta.lastModified : parsed.updatedAt, + fileFormat: parsed.format, + }); + } + return { slots, skipped, total: names.length, at: Date.now() }; + } + + async function readIndex() { + const idx = await readJson(projDir, PATHS.index); + return idx && typeof idx === 'object' ? idx : null; + } + + async function writeIndex(saves, uiLang) { + const prev = (await readIndex()) || {}; + await writeJson(projDir, PATHS.index, { + format: 'gml-pm-index', + version: 1, + updatedAt: new Date().toISOString(), + root: PATHS.proj, + uiLang: uiLang || prev.uiLang || 'zh', + saves: saves.map((s) => ({ + id: s.id, + name: s.name, + file: slotFileName(s), + createdAt: s.createdAt, + updatedAt: s.updatedAt, + size: JSON.stringify(s.data || {}).length, + })), + }); + } + + async function readTrashIndex() { + const idx = await readJson(trashDir, PATHS.trashIndex); + return idx && Array.isArray(idx.items) ? idx : null; + } + + async function writeTrashIndex(items) { + await writeJson(trashDir, PATHS.trashIndex, { + format: 'gml-trash-index', + version: 1, + updatedAt: new Date().toISOString(), + note: '垃圾回收文件:记录所有被移入回收站的项目文件,可据此恢复。', + items: items.map((t) => ({ + id: t.id, + name: t.name, + originalName: t.originalName || t.name, + file: t.file, + deletedAt: t.deletedAt, + size: JSON.stringify(t.data || {}).length, + where: 'file', + })), + }); + } + + async function readTrash() { + const idx = await readTrashIndex(); + const items = []; + if (idx) { + for (const it of idx.items) { + if (!it || !it.id) continue; + const tf = it.file ? await readJson(trashDir, it.file) : null; + items.push({ + id: it.id, + name: it.name, + originalName: it.originalName || it.name, + createdAt: it.createdAt, + deletedAt: it.deletedAt || Date.now(), + data: (tf && tf.data) || {}, + siteBackup: (tf && tf.siteBackup) || null, + file: it.file || null, + where: 'file', + }); + } + } + return items; + } + + function slotFileName(slot) { + return `${safeFile(slot.name).slice(0, 40)}.${slot.id}.json`; + } + + /** 写项目文件;改名后同步删掉旧文件,绝不留下重复存档 */ + async function writeSlot(slot, previousFile) { + const name = slotFileName(slot); + const save = { + id: slot.id, + name: slot.name, + note: slot.note || '', + createdAt: slot.createdAt, + updatedAt: slot.updatedAt, + saveCount: slot.saveCount || 0, + data: slot.data || {}, + }; + if (slot.siteBackup) save.siteBackup = slot.siteBackup; + await writeJson(projDir, name, { format: 'gml-pm-save', version: 1, exportedAt: new Date().toISOString(), save }); + if (previousFile && previousFile !== name) { + await rm(join(projDir, previousFile), { force: true }); + } + slot.file = name; + return name; + } + + async function removeSlotFile(slot) { + const names = await listFiles(projDir); + for (const n of names) { + if (!/\.json$/i.test(n) || n === PATHS.index) continue; + if (n === slot.file || n === slotFileName(slot) || n.indexOf(`.${slot.id}.json`) >= 0) { + await rm(join(projDir, n), { force: true }); + } + } + } + + async function writeTrashFile(item) { + const name = `${item.id}.${item.deletedAt}.json`; + await writeJson(trashDir, name, { + format: 'gml-pm-trash', + version: 1, + deletedAt: item.deletedAt, + id: item.id, + name: item.name, + originalName: item.originalName, + createdAt: item.createdAt, + data: item.data, + siteBackup: item.siteBackup || null, + }); + item.file = name; + item.where = 'file'; + return name; + } + + async function removeTrashFile(item) { + const names = await listFiles(trashDir); + for (const n of names) { + if (n === PATHS.trashIndex) continue; + if (n === item.file || n.indexOf(item.id) === 0) await rm(join(trashDir, n), { force: true }); + } + } + + async function uniqueName(base, slots) { + const names = new Set(slots.map((s) => s.name)); + if (!names.has(base)) return base; + let i = 2; + while (names.has(`${base} (${i})`)) i += 1; + return `${base} (${i})`; + } + + /* --------------------- 打卡网页版本 --------------------- */ + async function readAppInfo() { + const meta = await readJson(appDir, PATHS.appMeta); + if (meta && meta.url) { + return { + url: String(meta.url), + version: String(meta.version || ''), + fetchedAt: Number(meta.fetchedAt || 0), + size: Number(meta.size || 0), + custom: true, + }; + } + return { url: APP_DEFAULT_URL, version: '', fetchedAt: 0, size: 0, custom: false }; + } + + async function appHtmlPath() { + const custom = join(appDir, PATHS.appFile); + try { + const st = await stat(custom); + if (st.size > 0) return custom; + } catch { + /* 没有缓存版本 */ + } + return null; + } + + async function fetchApp(url) { + const target = String(url || '').trim(); + if (!/^https?:\/\//i.test(target)) throw new Error('网址无效'); + const controller = new AbortController(); + const timer = setTimeout(() => controller.abort(), 30000); + let html; + try { + const resp = await fetch(target, { signal: controller.signal, redirect: 'follow' }); + if (!resp.ok) throw new Error(`HTTP ${resp.status}`); + const buf = Buffer.from(await resp.arrayBuffer()); + if (buf.length > APP_MAX_BYTES) throw new Error('网页文件过大'); + html = buf.toString('utf8'); + } finally { + clearTimeout(timer); + } + if (!/]/i.test(html)) throw new Error('抓到的不是 HTML 网页'); + if (!/gml-practice-log-v2/.test(html) || !/cmd/.test(html)) throw new Error('这不是同一个打卡网页'); + await writeText(appDir, PATHS.appFile, html); + const info = { url: target, version: appVersionOf(html), fetchedAt: Date.now(), size: html.length, custom: true }; + await writeJson(appDir, PATHS.appMeta, info); + return info; + } + + async function restoreBuiltinApp() { + await rm(join(appDir, PATHS.appFile), { force: true }); + await rm(join(appDir, PATHS.appMeta), { force: true }); + return { url: APP_DEFAULT_URL, version: '', fetchedAt: 0, size: 0, custom: false }; + } + + async function saveExport(name, text) { + const file = safeFile(name).replace(/\.json$/i, '') + '.json'; + await writeText(exportDir, file, text); + return join(exportDir, file); + } + + return { + dirs: { projDir, trashDir, appDir, exportDir }, + ensureDirs, + readJson, + writeJson, + listFiles, + fileMeta, + scanProjects, + readIndex, + writeIndex, + readTrash, + writeTrashIndex, + writeSlot, + removeSlotFile, + writeTrashFile, + removeTrashFile, + slotFileName, + uniqueName, + readAppInfo, + appHtmlPath, + fetchApp, + restoreBuiltinApp, + saveExport, + builtinAppPath, + }; +} + +/* ------------------------------ HTTP ------------------------------ */ +function sendJson(res, status, obj) { + const body = JSON.stringify(obj); + res.writeHead(status, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' }); + res.end(body); +} +function sendText(res, status, text, type) { + res.writeHead(status, { 'content-type': `${type || 'text/plain'}; charset=utf-8`, 'cache-control': 'no-store' }); + res.end(text); +} +/** 打卡网页自带的 Google Fonts 远程链接在 Mini App 里去掉,改用系统字体栈。 */ +function stripRemoteFonts(html) { + return String(html) + .replace(/]*fonts\.googleapis\.com[^>]*>\s*/gi, '') + .replace(/]*fonts\.gstatic\.com[^>]*>\s*/gi, ''); +} + +function mimeOf(name) { + if (name.endsWith('.html')) return 'text/html'; + if (name.endsWith('.css')) return 'text/css'; + if (name.endsWith('.js') || name.endsWith('.mjs')) return 'text/javascript'; + if (name.endsWith('.json')) return 'application/json'; + if (name.endsWith('.png')) return 'image/png'; + if (name.endsWith('.svg')) return 'image/svg+xml'; + if (name.endsWith('.woff2')) return 'font/woff2'; + return 'application/octet-stream'; +} + +async function readBody(req, limit = 16 * 1024 * 1024) { + const chunks = []; + let size = 0; + for await (const chunk of req) { + size += chunk.length; + if (size > limit) throw new Error('请求体过大'); + chunks.push(chunk); + } + if (!chunks.length) return null; + try { + return JSON.parse(Buffer.concat(chunks).toString('utf8')); + } catch { + throw new Error('请求体不是合法 JSON'); + } +} + +export async function start(context) { + const store = createStore(context.dataDir); + await store.ensureDirs(); + + const clientRoot = join(context.pluginRoot, 'miniapp/client'); + const builtinApp = join(clientRoot, 'core/app.html'); + const clientIndex = join(clientRoot, 'index.html'); + + const readFileSafe = async (p) => { + try { + return await readFile(p, 'utf8'); + } catch { + return null; + } + }; + + const server = createServer((req, res) => { + handle(req, res).catch((error) => { + const message = String((error && error.message) || error); + if (!res.headersSent) sendJson(res, 400, { error: message }); + else res.end(); + }); + }); + + /* 托管 MCP:把练习存档的业务能力交给 Agent(路径见 miniapp.json 的 mcpEndpoints) */ + const mcpHandler = createMcpHandler(store); + + async function handle(req, res) { + const url = new URL(req.url ?? '/', 'http://miniapp.local'); + const path = url.pathname; + const method = (req.method ?? 'GET').toUpperCase(); + + /* ---- 页面与静态资源 ---- */ + if (method === 'GET' && (path === '/app' || path === '/app/' || path === '/app/index.html')) { + const html = await readFileSafe(clientIndex); + if (!html) return sendText(res, 404, 'client missing'); + return sendText(res, 200, html, 'text/html'); + } + + if (method === 'GET' && path.startsWith('/app/') && !path.startsWith('/app/api/')) { + const rel = path.slice('/app/'.length); + if (!rel || rel.includes('..') || rel.includes('\\')) return sendJson(res, 404, { error: 'not_found' }); + const filePath = join(clientRoot, rel); + if (!filePath.startsWith(clientRoot)) return sendJson(res, 404, { error: 'not_found' }); + const body = await readFileSafe(filePath); + if (body === null) return sendJson(res, 404, { error: 'not_found' }); + return sendText(res, 200, body, mimeOf(rel)); + } + + /* ---- 托管 MCP(Agent 调用) ---- */ + if (path === '/mcp/gml-notes') return mcpHandler(req, res); + + if (!path.startsWith('/app/api/')) return sendJson(res, 404, { error: 'not_found' }); + + const api = path.slice('/app/api/'.length); + const seg = api.split('/').map((s) => decodeURIComponent(s)); + + /* ---- 总状态:列表 / 回收站 / 版本信息 ---- */ + if (method === 'GET' && api === 'state') { + const scan = await store.scanProjects(); + const trash = await store.readTrash(); + const index = await store.readIndex(); + const app = await store.readAppInfo(); + const builtinSize = (await store.fileMeta(join(context.pluginRoot, 'miniapp/client/core'), 'app.html'))?.size || 0; + return sendJson(res, 200, { + uiLang: (index && index.uiLang) || 'zh', + saves: scan.slots, + trash, + skipped: scan.skipped, + scan: { at: scan.at, total: scan.total, ok: scan.slots.length }, + app: { ...app, builtinSize }, + store: { + projDir: store.dirs.projDir, + trashDir: store.dirs.trashDir, + appDir: store.dirs.appDir, + exportDir: store.dirs.exportDir, + }, + }); + } + + /* ---- 打卡网页 HTML(内置版或已抓取的缓存版) ---- */ + if (method === 'GET' && api === 'app/html') { + const cached = await store.appHtmlPath(); + const html = cached ? await readFileSafe(cached) : await readFileSafe(builtinApp); + if (!html) return sendText(res, 404, 'app missing'); + return sendText(res, 200, stripRemoteFonts(html), 'text/html'); + } + + /* ---- 打卡网页版本管理 ---- */ + if (method === 'POST' && api === 'app/fetch') { + const body = await readBody(req); + const info = await store.fetchApp(body && body.url); + return sendJson(res, 200, info); + } + if (method === 'POST' && api === 'app/builtin') { + return sendJson(res, 200, await store.restoreBuiltinApp()); + } + + /* ---- 配置(界面语言 / 来源网址) ---- */ + if (method === 'PUT' && api === 'config') { + const body = await readBody(req); + const scan = await store.scanProjects(); + if (body && typeof body.uiLang === 'string' && body.uiLang !== 'en' && body.uiLang !== 'zh') { + throw new Error('语言取值无效'); + } + await store.writeIndex(scan.slots, body && body.uiLang); + if (body && typeof body.appUrl === 'string' && body.appUrl.trim()) { + const meta = await store.readJson(store.dirs.appDir, 'app-meta.json'); + if (meta && meta.custom) await store.writeJson(store.dirs.appDir, 'app-meta.json', { ...meta, url: body.appUrl.trim() }); + } + return sendJson(res, 200, { ok: true }); + } + + /* ---- 项目 ---- */ + if (seg[0] === 'projects') { + if (method === 'POST' && seg.length === 1) { + const body = await readBody(req); + const name = String((body && body.name) || '').trim(); + if (!name) throw new Error('项目名称不能为空'); + const scan = await store.scanProjects(); + const slot = { + id: uid(), + name: await store.uniqueName(name, scan.slots), + note: '', + createdAt: Date.now(), + updatedAt: Date.now(), + saveCount: 0, + data: {}, + }; + await store.writeSlot(slot); + await store.writeIndex([...scan.slots, slot], (await store.readIndex())?.uiLang); + return sendJson(res, 200, slot); + } + + const id = seg[1]; + if (!id) throw new Error('缺少项目 ID'); + + if (method === 'GET' && seg.length === 2) { + const scan = await store.scanProjects(); + const slot = scan.slots.find((s) => s.id === id); + if (!slot) return sendJson(res, 404, { error: '项目不存在' }); + return sendJson(res, 200, slot); + } + + if (method === 'PUT' && seg.length === 2) { + const body = await readBody(req); + if (!body || typeof body.data !== 'object' || body.data === null) throw new Error('存档数据无效'); + const scan = await store.scanProjects(); + const slot = scan.slots.find((s) => s.id === id); + if (!slot) return sendJson(res, 404, { error: '项目不存在' }); + const previousFile = slot.file; + slot.data = body.data; + slot.updatedAt = Date.now(); + slot.saveCount = (slot.saveCount || 0) + 1; + await store.writeSlot(slot, previousFile); + await store.writeIndex(scan.slots, (await store.readIndex())?.uiLang); + return sendJson(res, 200, { id: slot.id, updatedAt: slot.updatedAt, saveCount: slot.saveCount }); + } + + if (method === 'PATCH' && seg.length === 2) { + const body = await readBody(req); + const scan = await store.scanProjects(); + const slot = scan.slots.find((s) => s.id === id); + if (!slot) return sendJson(res, 404, { error: '项目不存在' }); + const previousFile = slot.file; + if (body && typeof body.name === 'string' && body.name.trim()) slot.name = body.name.trim(); + slot.updatedAt = Date.now(); + await store.writeSlot(slot, previousFile); + await store.writeIndex(scan.slots, (await store.readIndex())?.uiLang); + return sendJson(res, 200, slot); + } + + if (method === 'POST' && seg[2] === 'copy') { + const scan = await store.scanProjects(); + const slot = scan.slots.find((s) => s.id === id); + if (!slot) return sendJson(res, 404, { error: '项目不存在' }); + const copy = { + id: uid(), + name: await store.uniqueName(`${slot.name} · 副本`, scan.slots), + note: slot.note || '', + createdAt: Date.now(), + updatedAt: Date.now(), + saveCount: 0, + data: clone(slot.data || {}), + siteBackup: slot.siteBackup || null, + }; + await store.writeSlot(copy); + await store.writeIndex([...scan.slots, copy], (await store.readIndex())?.uiLang); + return sendJson(res, 200, copy); + } + + if (method === 'DELETE' && seg.length === 2) { + const scan = await store.scanProjects(); + const slot = scan.slots.find((s) => s.id === id); + if (!slot) return sendJson(res, 404, { error: '项目不存在' }); + const item = { + id: slot.id, + name: slot.name, + originalName: slot.name, + createdAt: slot.createdAt, + deletedAt: Date.now(), + data: clone(slot.data || {}), + siteBackup: slot.siteBackup || null, + }; + /* 必须先成功写进回收站,才允许删原件 */ + await store.writeTrashFile(item); + await store.removeSlotFile(slot); + const trash = await store.readTrash(); + trash.push(item); + await store.writeTrashIndex(trash); + await store.writeIndex(scan.slots.filter((s) => s.id !== id), (await store.readIndex())?.uiLang); + return sendJson(res, 200, { ok: true, trash: item }); + } + } + + /* ---- 回收站 ---- */ + if (seg[0] === 'trash') { + if (method === 'POST' && seg[2] === 'restore') { + const trash = await store.readTrash(); + const item = trash.find((t) => t.id === seg[1]); + if (!item) return sendJson(res, 404, { error: '回收站里没有这个项目' }); + const scan = await store.scanProjects(); + const slot = { + id: item.id, + name: await store.uniqueName(item.originalName || item.name, scan.slots), + note: '', + createdAt: item.createdAt || Date.now(), + updatedAt: Date.now(), + saveCount: 0, + data: item.data || {}, + siteBackup: item.siteBackup || null, + }; + await store.writeSlot(slot); + await store.removeTrashFile(item); + await store.writeTrashIndex(trash.filter((t) => t.id !== item.id)); + await store.writeIndex([...scan.slots, slot], (await store.readIndex())?.uiLang); + return sendJson(res, 200, slot); + } + + if (method === 'DELETE' && seg.length === 2) { + const trash = await store.readTrash(); + const item = trash.find((t) => t.id === seg[1]); + if (!item) return sendJson(res, 404, { error: '回收站里没有这个项目' }); + await store.removeTrashFile(item); + await store.writeTrashIndex(trash.filter((t) => t.id !== item.id)); + return sendJson(res, 200, { ok: true }); + } + + if (method === 'POST' && seg[1] === 'clear') { + const trash = await store.readTrash(); + for (const item of trash) await store.removeTrashFile(item); + await store.writeTrashIndex([]); + return sendJson(res, 200, { ok: true }); + } + } + + /* ---- 导入 ---- */ + if (method === 'POST' && api === 'import') { + const body = await readBody(req); + if (!body || typeof body.text !== 'string') throw new Error('导入内容无效'); + let obj; + try { + obj = JSON.parse(body.text); + } catch { + throw new Error('不是有效的 JSON 存档文件'); + } + const base = String(body.filename || '').replace(/\.json$/i, '').slice(0, 40) || '导入项目'; + const scan = await store.scanProjects(); + const uiLang = (await store.readIndex())?.uiLang; + const created = []; + + if (obj && obj.format === 'gml-pm-vault') { + const saves = Array.isArray(obj.saves) ? obj.saves : []; + for (const s of saves) { + if (!s || typeof s !== 'object' || !s.data) continue; + const slot = { + id: uid(), + name: await store.uniqueName(s.name || base, [...scan.slots, ...created]), + note: s.note || '', + createdAt: s.createdAt || Date.now(), + updatedAt: s.updatedAt || Date.now(), + saveCount: 0, + data: clone(s.data), + siteBackup: s.siteBackup || null, + }; + await store.writeSlot(slot); + created.push(slot); + } + const trash = await store.readTrash(); + const importedTrash = Array.isArray(obj.trash) ? obj.trash : []; + for (const t of importedTrash) { + if (!t || !t.id || trash.some((x) => x.id === t.id)) continue; + const item = { + id: t.id, + name: t.name || '已删除项目', + originalName: t.originalName || t.name, + createdAt: t.createdAt, + deletedAt: t.deletedAt || Date.now(), + data: t.data || {}, + siteBackup: t.siteBackup || null, + }; + await store.writeTrashFile(item); + trash.push(item); + } + await store.writeTrashIndex(trash); + await store.writeIndex([...scan.slots, ...created], uiLang); + return sendJson(res, 200, { ok: true, imported: created.length, trash: importedTrash.length }); + } + + if (obj && obj.format === 'gml-pm-save' && obj.save && obj.save.data) { + const s = obj.save; + const slot = { + id: uid(), + name: await store.uniqueName(s.name || base, scan.slots), + note: s.note || '', + createdAt: s.createdAt || Date.now(), + updatedAt: s.updatedAt || Date.now(), + saveCount: 0, + data: clone(s.data), + siteBackup: s.siteBackup || null, + }; + await store.writeSlot(slot); + await store.writeIndex([...scan.slots, slot], uiLang); + return sendJson(res, 200, { ok: true, imported: 1, project: slot }); + } + + /* 网站原生存档 / 分片存档:先建项目,打开时交给打卡网页自己的 import 接口转换 */ + const site = obj && typeof obj === 'object' ? obj : {}; + const slot = { + id: uid(), + name: await store.uniqueName(base, scan.slots), + note: '', + createdAt: Date.now(), + updatedAt: Date.now(), + saveCount: 0, + data: hasStorageKeys(site) ? clone(site) : {}, + siteBackup: hasStorageKeys(site) ? null : clone(site), + }; + await store.writeSlot(slot); + await store.writeIndex([...scan.slots, slot], uiLang); + return sendJson(res, 200, { ok: true, imported: 1, project: slot }); + } + + /* ---- 导出 ---- */ + if (method === 'GET' && seg[0] === 'export') { + if (seg[1] === 'all') { + const scan = await store.scanProjects(); + const trash = await store.readTrash(); + const payload = { + format: 'gml-pm-vault', + version: 2, + exportedAt: new Date().toISOString(), + saves: scan.slots, + trash, + }; + const text = JSON.stringify(payload); + const path = await store.saveExport(`gml存档库-${new Date().toISOString().slice(0, 10)}.json`, text); + return sendJson(res, 200, { filename: `gml存档库-${new Date().toISOString().slice(0, 10)}.json`, text, path }); + } + if (seg[1] === 'project' && seg[2]) { + const scan = await store.scanProjects(); + const slot = scan.slots.find((s) => s.id === seg[2]); + if (!slot) return sendJson(res, 404, { error: '项目不存在' }); + const payload = { + format: 'gml-pm-save', + version: 1, + exportedAt: new Date().toISOString(), + save: { + name: slot.name, + note: slot.note || '', + createdAt: slot.createdAt, + updatedAt: slot.updatedAt, + data: slot.data || {}, + }, + }; + const text = JSON.stringify(payload); + const filename = `gml项目-${safeFile(slot.name)}.json`; + const path = await store.saveExport(filename, text); + return sendJson(res, 200, { filename, text, path }); + } + } + + /* ---- 导出落盘(网站存档格式等由网页生成的内容) ---- */ + if (method === 'POST' && api === 'export/file') { + const body = await readBody(req); + if (!body || typeof body.text !== 'string') throw new Error('导出内容无效'); + const filename = String(body.filename || 'gml-export.json'); + const path = await store.saveExport(filename, body.text); + return sendJson(res, 200, { filename, path }); + } + + return sendJson(res, 404, { error: 'not_found' }); + } + + await new Promise((resolve, reject) => { + const onError = (error) => reject(error); + server.once('error', onError); + server.listen(context.listen.port, context.listen.host, () => { + server.off('error', onError); + resolve(); + }); + }); + + let disposal; + const dispose = () => { + if (disposal) return disposal; + context.signal.removeEventListener('abort', onAbort); + disposal = new Promise((resolve, reject) => { + server.close((error) => (error ? reject(error) : resolve())); + }); + return disposal; + }; + const onAbort = () => { + void dispose().catch(() => undefined); + }; + context.signal.addEventListener('abort', onAbort, { once: true }); + if (context.signal.aborted) await dispose(); + + return { dispose }; +} diff --git a/plugins/basetier-gml/miniapp-44928b90-e36d-46c5-9f7e-4d3d5ac5cda0/package.json b/plugins/basetier-gml/miniapp-44928b90-e36d-46c5-9f7e-4d3d5ac5cda0/package.json new file mode 100644 index 00000000..aab6b8dc --- /dev/null +++ b/plugins/basetier-gml/miniapp-44928b90-e36d-46c5-9f7e-4d3d5ac5cda0/package.json @@ -0,0 +1,6 @@ +{ + "mcode": { + "schemaVersion": 2, + "miniApp": "./miniapp/miniapp.json" + } +} diff --git a/plugins/basetier-gml/miniapp-44928b90-e36d-46c5-9f7e-4d3d5ac5cda0/servers.mcp.json b/plugins/basetier-gml/miniapp-44928b90-e36d-46c5-9f7e-4d3d5ac5cda0/servers.mcp.json new file mode 100644 index 00000000..8d4c00b9 --- /dev/null +++ b/plugins/basetier-gml/miniapp-44928b90-e36d-46c5-9f7e-4d3d5ac5cda0/servers.mcp.json @@ -0,0 +1,12 @@ +{ + "schemaVersion": 1, + "mcpServers": { + "gml-notes": { + "type": "streamable-http", + "url": "http://127.0.0.1:9/mcp/gml-notes", + "headers": {}, + "description": "读取与整理 GML 练习存档:项目列表、记录内容、API 库、跨项目搜索。", + "timeout": 30000 + } + } +} diff --git a/plugins/basetier-gml/miniapp-44928b90-e36d-46c5-9f7e-4d3d5ac5cda0/skills/gml-practice-notes/SKILL.md b/plugins/basetier-gml/miniapp-44928b90-e36d-46c5-9f7e-4d3d5ac5cda0/skills/gml-practice-notes/SKILL.md new file mode 100644 index 00000000..bbba1267 --- /dev/null +++ b/plugins/basetier-gml/miniapp-44928b90-e36d-46c5-9f7e-4d3d5ac5cda0/skills/gml-practice-notes/SKILL.md @@ -0,0 +1,64 @@ +--- +name: gml-practice-notes +description: 管理 GML(GameMaker Language)代码学习笔记。当用户要查看、搜索、整理或新建 GML 练习打卡记录,要回顾某次练习的代码或题目,或要复用已登记的 GML 函数与内置变量时使用。 +--- + +# GML 练习记录 · 项目存档管理器 + +这是 MiniMax Code 的一个 Mini App:多本互不干扰的 GML 学习笔记,每本都能独立打卡、登记 API 库、记录代码载体。数据存在 Mini App 的数据目录里(`GML-Saves/`,另有 `GML-Trash/` 回收站与 `exports/` 导出目录)。 + +Agent 通过托管 MCP server `gml-notes` 访问这些数据。 + +## 什么时候用 + +- 用户问「我的 GML 练习记录有哪些」「上次那道云层特效怎么写的」 +- 用户要在这台机器上搜索某段 GML 代码、某个 API 名字 +- 用户要复用已经登记过的 GML 函数或内置变量 +- 用户要新建一本练习笔记,或把存档导出备份 + +## 可用工具 + +| 工具 | 用途 | 关键参数 | +| --- | --- | --- | +| `list_projects` | 列出全部练习笔记,含记录数、API 数、打卡天数、存档文件名 | 无 | +| `get_project` | 读一本笔记的完整内容:练习记录、API 库、打卡日历、设置 | `project`(项目 ID 或名称) | +| `search_notes` | 跨所有笔记搜索记录名称、题目要求、提示、代码文本、API 介绍 | `query`、`limit`(默认 20) | +| `list_api_library` | 汇总 API 库(代码名、介绍、参数、被哪些笔记引用) | `project`(可选,不过滤时汇总全部) | +| `create_project` | 新建一本空白练习笔记 | `name` | +| `export_backup` | 把全部笔记(含回收站)导出成 JSON 备份,落在 `exports/` | 无 | + +推荐顺序:先用 `list_projects` 拿到项目 ID 与名称,再用 `get_project` 或 `search_notes` 取内容。 + +## 记录里有什么 + +一条练习记录包含: + +- `name` — 记录标题(用户一般写成「082.云层特效」这样的序号 + 主题) +- `requirement` — 题目要求 +- `hint` — 提示 +- `modules` — 代码载体,按顺序排列,常见三类: + - **操作描述**:这一步在编辑器里做了什么(纯文字) + - **脚本**:GML 代码,第一行写 `// 文件名` 标明来源文件 + - **对象**:带预定义变量表和事件代码框(Create / Step / Draw 等) +- `apis` — 这条记录引用了哪些 API(引用式:API 库只存一份,记录只存引用) + +API 库条目:`code`(函数名或内置变量名,只写名字)、`desc`(一句话说明)、`params`(参数列表)。 + +## 边界:Agent 能读,不能直接改记录内容 + +记录正文(题目、提示、代码载体)只能在 Mini App 页面里编辑——那是浏览器侧的写入通道,托管 MCP 不暴露。所以: + +- **不要**试图用 MCP 工具写入或覆盖已有记录内容,会失败。 +- 用户说「把这段代码记进我的笔记」时,正确做法是:把整理好的内容(标题、题目要求、提示、按顺序排好的脚本/对象载体)直接给用户,告诉他粘到页面里对应位置。 +- 用户说「建一本新的」时,用 `create_project`,这个是支持的。 + +## 写作约定(整理给用户的内容时遵守) + +- 代码逐字贴,不改一个字;需要改的地方写在提示里,不要动代码本身。 +- 脚本载体的第一行写 `// 文件名`。 +- 对象载体用「预定义变量表 + 事件代码框」两部分表达。 +- API 只登记代码名;一条记录里引用 API 时,说明它引用的 API 名字列表。 + +## 数据与隐私 + +所有练习数据只写在本机 Mini App 数据目录,不上传任何服务器。唯一的网络访问是用户在页面里主动点「抓取最新版本」时去下载打卡网页版(默认来源 `https://basetier-gml.github.io/gml-practice-log/`)。