From db82772f30beff9c5d02b9ac3c20456e557fa337 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=BE=A1=E5=9D=82=E5=A6=B9?= <849063625@qq.com> Date: Sat, 28 Nov 2026 17:47:08 +0800 Subject: [PATCH 1/2] Add postman-lite Mini App --- README.md | 1 + README.zh-CN.md | 1 + .../postman-lite/.minimax-plugin/plugin.json | 17 + plugins/ssugarr/postman-lite/LICENSE | 21 + plugins/ssugarr/postman-lite/README.md | 76 +++ plugins/ssugarr/postman-lite/README.zh-CN.md | 70 ++ plugins/ssugarr/postman-lite/icon.png | Bin 0 -> 1574 bytes .../miniapp/client/assets/index-B2mwHLeF.js | 49 ++ .../miniapp/client/assets/index-CvdCbz-Y.css | 1 + .../postman-lite/miniapp/client/index.html | 27 + .../ssugarr/postman-lite/miniapp/miniapp.json | 27 + .../ssugarr/postman-lite/miniapp/node/api.js | 77 +++ .../postman-lite/miniapp/node/config.js | 38 ++ .../postman-lite/miniapp/node/miniapp-api.ts | 641 ++++++++++++++++++ .../postman-lite/miniapp/node/proxy.js | 167 +++++ .../postman-lite/miniapp/node/server.mjs | 76 +++ .../postman-lite/miniapp/node/shared/body.js | 74 ++ .../miniapp/node/shared/constants.js | 22 + .../postman-lite/miniapp/node/shared/keys.js | 52 ++ .../postman-lite/miniapp/node/shared/url.js | 95 +++ .../postman-lite/miniapp/node/static.js | 81 +++ .../postman-lite/miniapp/node/store.js | 68 ++ plugins/ssugarr/postman-lite/package.json | 10 + 23 files changed, 1691 insertions(+) create mode 100644 plugins/ssugarr/postman-lite/.minimax-plugin/plugin.json create mode 100644 plugins/ssugarr/postman-lite/LICENSE create mode 100644 plugins/ssugarr/postman-lite/README.md create mode 100644 plugins/ssugarr/postman-lite/README.zh-CN.md create mode 100644 plugins/ssugarr/postman-lite/icon.png create mode 100644 plugins/ssugarr/postman-lite/miniapp/client/assets/index-B2mwHLeF.js create mode 100644 plugins/ssugarr/postman-lite/miniapp/client/assets/index-CvdCbz-Y.css create mode 100644 plugins/ssugarr/postman-lite/miniapp/client/index.html create mode 100644 plugins/ssugarr/postman-lite/miniapp/miniapp.json create mode 100644 plugins/ssugarr/postman-lite/miniapp/node/api.js create mode 100644 plugins/ssugarr/postman-lite/miniapp/node/config.js create mode 100644 plugins/ssugarr/postman-lite/miniapp/node/miniapp-api.ts create mode 100644 plugins/ssugarr/postman-lite/miniapp/node/proxy.js create mode 100644 plugins/ssugarr/postman-lite/miniapp/node/server.mjs create mode 100644 plugins/ssugarr/postman-lite/miniapp/node/shared/body.js create mode 100644 plugins/ssugarr/postman-lite/miniapp/node/shared/constants.js create mode 100644 plugins/ssugarr/postman-lite/miniapp/node/shared/keys.js create mode 100644 plugins/ssugarr/postman-lite/miniapp/node/shared/url.js create mode 100644 plugins/ssugarr/postman-lite/miniapp/node/static.js create mode 100644 plugins/ssugarr/postman-lite/miniapp/node/store.js create mode 100644 plugins/ssugarr/postman-lite/package.json diff --git a/README.md b/README.md index 0343acf4..c8d38743 100644 --- a/README.md +++ b/README.md @@ -57,6 +57,7 @@ The MiniMax Code Agent communicates through the host MCP client. Business reques | MiniApp | What it does | Author | | --- | --- | --- | +| [Postman Lite](plugins/ssugarr/postman-lite/) | A lightweight local API request tool: build requests, send them through a local proxy that sidesteps browser CORS limits, and inspect responses, with collections kept as plain JSON | [ssugarr](https://github.com/ssugarr) | | [Weekly Planner](plugins/alanhean/weekly-planner/) | A local weekly planner: add tasks with a date and a priority, review them day by day, tick them off, and track the week's completion rate | [Alanhean](https://github.com/Alanhean) | | [DeepSeek Chat Migration](plugins/danielwalnut/deepseek-chat-migration/) | Preview official DeepSeek web exports locally, restore branches and attachments, and import selected conversations as native MiniMax Code sessions with a bundled importer | [DanielWalnut](https://github.com/DanielWalnut) | | [OpenFilm](plugins/cristinamadureira353-svg/openfilm/) | Run OpenFilm inside MiniMax Code with the desktop interface: Studio editor, chat column and local agents, with a web-Studio fallback | [最爱双皮奶](https://github.com/cristinamadureira353-svg) | diff --git a/README.zh-CN.md b/README.zh-CN.md index c9dbf240..3d158767 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -57,6 +57,7 @@ MiniMax Code Agent 通过宿主 MCP 客户端与 MiniApp 协作。业务请求 | MiniApp | 功能 | 作者 | | --- | --- | --- | +| [Postman Lite](plugins/ssugarr/postman-lite/README.zh-CN.md) | 轻量的本地 API 请求工具:构建请求、通过本地代理转发(绕过浏览器 CORS 限制)、查看响应,集合以纯 JSON 保存 | [ssugarr](https://github.com/ssugarr) | | [周计划](plugins/alanhean/weekly-planner/README.zh-CN.md) | 本地周计划:手动录入任务、日期与优先级,按天查看安排,勾选完成并跟踪本周完成率 | [Alanhean](https://github.com/Alanhean) | | [DeepSeek 会话迁移](plugins/danielwalnut/deepseek-chat-migration/README_ZH.md) | 在本机预览 DeepSeek 网页版官方导出包,恢复分支和附件,并用自带的导入脚本把选中对话导入成 MiniMax Code 原生会话 | [DanielWalnut](https://github.com/DanielWalnut) | | [OpenFilm](plugins/cristinamadureira353-svg/openfilm/) | 把 OpenFilm 装进 MiniMax Code:桌面版界面(Studio 编辑器 + 聊天栏 + 本地 agent),桌面模式不可用时回落网页版 | [最爱双皮奶](https://github.com/cristinamadureira353-svg) | diff --git a/plugins/ssugarr/postman-lite/.minimax-plugin/plugin.json b/plugins/ssugarr/postman-lite/.minimax-plugin/plugin.json new file mode 100644 index 00000000..69ec5f94 --- /dev/null +++ b/plugins/ssugarr/postman-lite/.minimax-plugin/plugin.json @@ -0,0 +1,17 @@ +{ + "schemaVersion": 1, + "name": "postman-lite", + "displayName": "Postman Lite", + "version": "1.0.0", + "description": "本地 API 请求工具:构建请求、查看响应、管理集合。", + "author": "ssugarr", + "icon": "icon.png", + "category": "Code", + "exampleQueries": [ + "打开 API 请求面板", + "用 Postman Lite 调一个接口" + ], + "apps": [], + "mcpServers": [], + "skills": [] +} diff --git a/plugins/ssugarr/postman-lite/LICENSE b/plugins/ssugarr/postman-lite/LICENSE new file mode 100644 index 00000000..d8cee066 --- /dev/null +++ b/plugins/ssugarr/postman-lite/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 ssugarr + +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/ssugarr/postman-lite/README.md b/plugins/ssugarr/postman-lite/README.md new file mode 100644 index 00000000..4992af65 --- /dev/null +++ b/plugins/ssugarr/postman-lite/README.md @@ -0,0 +1,76 @@ +# Postman Lite (`postman-lite`) + +A lightweight, local-first API request tool. Build a request in the page, send it through a Node +proxy that sidesteps browser CORS limits, and read the response — status, timing, size, headers, +body, and an HTML preview — with collections kept as plain JSON on disk. + +The Mini App hosts the Node runtime, so there is nothing to install and no service to start: open +the panel and send requests. + +## Install + +Copy this directory, including the hidden `.minimax-plugin/`, into the MiniMax Code plugins +directory as `postman-lite/` (`~/.minimax/plugins/postman-lite/` by default; the root README's +Install section explains where that directory is). Restart MiniMax Code and ask the Agent to +"Open Postman Lite". + +## What it does + +- **Request builder** — method, URL, query parameters, request headers, and a body in + `none` / `raw` / JSON / `x-www-form-urlencoded` / `form-data` form. Redirect following and + the timeout are switchable per request. +- **Response viewer** — status code, elapsed time, and byte size; body as pretty JSON, raw text, or + an HTML preview in an iframe; binary responses preview inline or download. +- **Collections** — collections, folders, and requests in a tree; create, rename, delete, and + automatic persistence. + +## Tested environment + +- MiniMax Code 3.1.2 or later on Windows 11. The package uses `surface.window`, whose minimum + client version is 3.1.2; the Agent cannot read the exact client build number in this session. +- Client acceptance exercised: initial render and structure, light and dark themes, creating a + collection, sending GET and POST JSON through the proxy, error handling for an unresolvable host, + and collection persistence across a page reload. +- Runtime diagnostics: no console errors and no failed or 4xx/5xx network requests. +- Requests were exercised against a local echo server as the target. + +Not verified: requests against third-party hosts that need credentials or are unreachable from this +network; behaviour on macOS and Linux. + +## Data & access + +- **Files** — reads its own `miniapp/client/` payload and `miniapp/node/` code. Writes + `state.json` in the Host-assigned data directory. +- **Network** — only the host the user explicitly requests through the proxy. No telemetry. +- **Processes** — none. +- **Agent turns** — none. +- **Conversations read** — none. +- **Tools called** — none. +- **Microphone / camera / notifications** — not used. +- **Host navigation read** — not declared. +- **State** — the Host-assigned plugin data directory. `state.json` holds the collection tree and is + replaced atomically, so a forced stop never leaves a half-written file. Clearing that directory + resets every collection. + +## Files + +```text +.minimax-plugin/plugin.json Plugin manifest +package.json Mini App declaration +miniapp/miniapp.json Payload roots, Node entry, page route +miniapp/client/index.html The page served at / +miniapp/client/assets/ Built front-end bundle +miniapp/node/server.mjs Node entry: start(context) -> { dispose } +miniapp/node/miniapp-api.ts Type declarations for the runtime context +miniapp/node/api.js Routes: /api/send, /api/state, /api/health +miniapp/node/proxy.js Request forwarding, timing, binary handling +miniapp/node/store.js Atomic JSON persistence +miniapp/node/static.js Static file serving +miniapp/node/config.js Data directory and limits +miniapp/node/shared/ Shared request-building logic +icon.png Plugin icon +``` + +## License + +[MIT](./LICENSE) diff --git a/plugins/ssugarr/postman-lite/README.zh-CN.md b/plugins/ssugarr/postman-lite/README.zh-CN.md new file mode 100644 index 00000000..87bf55c6 --- /dev/null +++ b/plugins/ssugarr/postman-lite/README.zh-CN.md @@ -0,0 +1,70 @@ +# Postman Lite (`postman-lite`) + +轻量的本地 API 请求工具。在页面里构建请求,由 Node 代理转发(绕过浏览器的 CORS 限制),再读取响应—— +状态码、耗时、字节数、响应头、响应体,以及 HTML 预览;集合以纯 JSON 形式保存在本地磁盘。 + +Mini App 自身托管 Node 运行时,不用安装任何依赖,也不用另外起服务:打开面板就能发请求。 + +[English](./README.md) + +## 安装 + +把这个目录(含隐藏的 `.minimax-plugin/`)复制到 MiniMax Code 的插件目录,命名为 `postman-lite/` +(默认 `~/.minimax/plugins/postman-lite/`;根 README 的 Install 一节说明了该目录的位置)。 +重启 MiniMax Code,然后让 Agent「打开 Postman Lite」。 + +## 功能 + +- **请求构建器** —— 方法、地址、Query 参数、请求头,请求体支持 `无` / `raw` / JSON / + `x-www-form-urlencoded` / `form-data`。是否跟随跳转、超时时长可按请求切换。 +- **响应查看器** —— 状态码、耗时、字节数;响应体可看美化后的 JSON、原文,或用 iframe 预览 HTML; + 二进制响应直接预览或下载。 +- **集合** —— 集合 / 文件夹 / 请求三层树,可新建、重命名、删除,改动自动落盘。 + +## 测试环境 + +- MiniMax Code 3.1.2 及以上,Windows 11。本包用到 `surface.window`,其最低客户端版本为 3.1.2; + 本次会话中 Agent 无法读取客户端的具体构建号。 +- 客户端验收覆盖:首屏渲染与结构、浅色与深色主题、新建集合、通过代理发送 GET 与 POST JSON、 + 无法解析的域名时的错误处理,以及刷新页面后集合仍然存在。 +- 运行时诊断:无 console 错误,无失败或 4xx/5xx 的网络请求。 +- 请求以本地回显服务器为目标验证。 + +未验证:需要凭据或在本网络下不可达的第三方接口;macOS 与 Linux 上的行为。 + +## 数据与访问 + +- **文件** —— 读取自己的 `miniapp/client/` 产物与 `miniapp/node/` 代码;在 Host 分配的数据目录里 + 写入 `state.json`。 +- **网络** —— 只有用户明确请求的目标地址,无任何遥测。 +- **进程** —— 无。 +- **Agent 对话轮次** —— 无。 +- **读取的会话** —— 无。 +- **调用的工具** —— 无。 +- **麦克风 / 摄像头 / 通知** —— 未使用。 +- **Host 导航读取** —— 未声明。 +- **状态位置** —— Host 分配的插件数据目录。`state.json` 保存集合树,采用原子替换写入, + 进程被强制终止也不会留下半截文件;清空该目录即重置所有集合。 + +## 文件 + +```text +.minimax-plugin/plugin.json 插件清单 +package.json Mini App 声明 +miniapp/miniapp.json 产物根目录、Node 入口、页面路由 +miniapp/client/index.html 在 / 上提供的页面 +miniapp/client/assets/ 前端构建产物 +miniapp/node/server.mjs Node 入口:start(context) -> { dispose } +miniapp/node/miniapp-api.ts 运行时上下文的类型声明 +miniapp/node/api.js 路由:/api/send、/api/state、/api/health +miniapp/node/proxy.js 请求转发、计时、二进制处理 +miniapp/node/store.js 原子 JSON 持久化 +miniapp/node/static.js 静态文件服务 +miniapp/node/config.js 数据目录与各项限制 +miniapp/node/shared/ 共享的请求构建逻辑 +icon.png 插件图标 +``` + +## 许可 + +[MIT](./LICENSE) diff --git a/plugins/ssugarr/postman-lite/icon.png b/plugins/ssugarr/postman-lite/icon.png new file mode 100644 index 0000000000000000000000000000000000000000..299a26cbf5c1427dffa9cd575cf721307d570765 GIT binary patch literal 1574 zcmeAS@N?(olHy`uVBq!ia0vp^4Is?H1|$#LC7xzrV7=|>;uumf=gr;N9Fb5F_7BDH zN*t40jx3m@A#jD`h{82~A;W#9hIKB=6V;QM-fp_!Iw3Du_^7z>7spdwD|5UT=(0U- z4vcs42{>&0A!&-l#UFng7Vv9zUfN`Qd~;|s@7+uz9O)JMQ;7Q z+VlNc*1f)P;(=w;neIK@5%Dq?bm#T^{r{9*@ia!gnj^~T2}4Q1*Th_Vu`>}GpIDCO z#4fN@Vt4rd)BClU(Q~fW#@QT3`o97jTK?xMOo;EM)AkEGZ>^la!>4}Tg|#orV!ID- z4G8cmi29Kul*I@Nov(+hUWIHbj*XAkN|#&6e?ev6^ZSxvcK?~yFA_-*H<;a0#(2g^ zzl72KdH~l2CW&?ibaY*)m{GcGsq4HCVQW8`+3MMAA9>%$$6x1gcEXjIh6=|UTHH*2 zPm^w)+0I})`*&FN5&Nu1Y+r6yc*L8(Sa9m$yrfKZ#~fa1&NHPdC8Y+RdyG?WF};29 zt~O0_E62oyX%mAzpJu)CiI9%EV`HT-k0aLM2a{@p^XrK&uP*%0esO=1w)UU=+zCGMvNmy= z|6P>ouW5@p2v)su`cxCfV?$ymt*7pfdX*%ncOdCuPzej4`!;F|NW(R z>9S1?D}6X`#NYh7GVkf}bgjz@`%TThovQS5e3ma}8>P8_foSNz|MS*u5I(ouy{)ZH zDAVlt_qYF?TCQcTsM{ODK6ko9)iJH7$x{Rh??u)A%=k6?)3WE!yQWM!akgaN_W!DX z-#&jmHN3X`^}*WR`-q(SpO3zY`t01fRdCqjHPcc83_B1GbPU2zNIsfpf)(T$7XRi5-O#h75#2n`^6HJMF!qC&lGw+h(&G*h? zk*k_rMVov+YqaeSTOYYZzjSt0F6+COd#ca&eqZ;_rtH&`lb%gyI!#lfHFBb5N}kls z$lZDCNY^>py$dH>z2A9YX;J*2GNpMejVH=I&vYJ{xB2|{X>r$mYq=dibJoiERAfK) zQ9W)K_T5@<--_8kB%7Wkzk0OuD!*pi4Mquhsb5FS-xaZWR zZ|9tq^y-Rf{wEFBD;u8QSW~|%f9dnxxlsofN1ZNZ>HPit!>su-YkBth3z|N4bh|s- zYxS08(KkMRy%ipDKxc+#k7En7+RrklI~Sdmo1bg6`PiN0n#CTy2vIV@izrM+Ju?Ht m|NpbhtN4MXJsYT)XJ&Z(ZtAoneFio_5e83JKbLh*2~7YK=FPVN literal 0 HcmV?d00001 diff --git a/plugins/ssugarr/postman-lite/miniapp/client/assets/index-B2mwHLeF.js b/plugins/ssugarr/postman-lite/miniapp/client/assets/index-B2mwHLeF.js new file mode 100644 index 00000000..1fe81ecb --- /dev/null +++ b/plugins/ssugarr/postman-lite/miniapp/client/assets/index-B2mwHLeF.js @@ -0,0 +1,49 @@ +(function(){const E=document.createElement("link").relList;if(E&&E.supports&&E.supports("modulepreload"))return;for(const z of document.querySelectorAll('link[rel="modulepreload"]'))o(z);new MutationObserver(z=>{for(const A of z)if(A.type==="childList")for(const Q of A.addedNodes)Q.tagName==="LINK"&&Q.rel==="modulepreload"&&o(Q)}).observe(document,{childList:!0,subtree:!0});function r(z){const A={};return z.integrity&&(A.integrity=z.integrity),z.referrerPolicy&&(A.referrerPolicy=z.referrerPolicy),z.crossOrigin==="use-credentials"?A.credentials="include":z.crossOrigin==="anonymous"?A.credentials="omit":A.credentials="same-origin",A}function o(z){if(z.ep)return;z.ep=!0;const A=r(z);fetch(z.href,A)}})();function Uh(f){return f&&f.__esModule&&Object.prototype.hasOwnProperty.call(f,"default")?f.default:f}var Ao={exports:{}},fn={};/** + * @license React + * react-jsx-runtime.production.js + * + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */var fv;function jh(){if(fv)return fn;fv=1;var f=Symbol.for("react.transitional.element"),E=Symbol.for("react.fragment");function r(o,z,A){var Q=null;if(A!==void 0&&(Q=""+A),z.key!==void 0&&(Q=""+z.key),"key"in z){A={};for(var tl in z)tl!=="key"&&(A[tl]=z[tl])}else A=z;return z=A.ref,{$$typeof:f,type:o,key:Q,ref:z!==void 0?z:null,props:A}}return fn.Fragment=E,fn.jsx=r,fn.jsxs=r,fn}var ov;function ph(){return ov||(ov=1,Ao.exports=jh()),Ao.exports}var g=ph(),Mo={exports:{}},K={};/** + * @license React + * react.production.js + * + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */var sv;function xh(){if(sv)return K;sv=1;var f=Symbol.for("react.transitional.element"),E=Symbol.for("react.portal"),r=Symbol.for("react.fragment"),o=Symbol.for("react.strict_mode"),z=Symbol.for("react.profiler"),A=Symbol.for("react.consumer"),Q=Symbol.for("react.context"),tl=Symbol.for("react.forward_ref"),$=Symbol.for("react.suspense"),dl=Symbol.for("react.memo"),x=Symbol.for("react.lazy"),N=Symbol.for("react.activity"),j=Symbol.for("react.view_transition"),vl=Symbol.iterator;function Fl(v){return v===null||typeof v!="object"?null:(v=vl&&v[vl]||v["@@iterator"],typeof v=="function"?v:null)}var Hl={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},ol=Object.assign,Dl={};function kl(v,M,B){this.props=v,this.context=M,this.refs=Dl,this.updater=B||Hl}kl.prototype.isReactComponent={},kl.prototype.setState=function(v,M){if(typeof v!="object"&&typeof v!="function"&&v!=null)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,v,M,"setState")},kl.prototype.forceUpdate=function(v){this.updater.enqueueForceUpdate(this,v,"forceUpdate")};function Ht(){}Ht.prototype=kl.prototype;function rt(v,M,B){this.props=v,this.context=M,this.refs=Dl,this.updater=B||Hl}var Ot=rt.prototype=new Ht;Ot.constructor=rt,ol(Ot,kl.prototype),Ot.isPureReactComponent=!0;var Il=Array.isArray;function F(){}var el={H:null,A:null,T:null,S:null},q=Object.prototype.hasOwnProperty;function at(v,M,B){var Y=B.ref;return{$$typeof:f,type:v,key:M,ref:Y!==void 0?Y:null,props:B}}function Pl(v,M){return at(v.type,M,v.props)}function dt(v){return typeof v=="object"&&v!==null&&v.$$typeof===f}function Te(v){var M={"=":"=0",":":"=2"};return"$"+v.replace(/[=:]/g,function(B){return M[B]})}var Fe=/\/+/g;function ql(v,M){return typeof v=="object"&&v!==null&&v.key!=null?Te(""+v.key):M.toString(36)}function R(v){switch(v.status){case"fulfilled":return v.value;case"rejected":throw v.reason;default:switch(typeof v.status=="string"?v.then(F,F):(v.status="pending",v.then(function(M){v.status==="pending"&&(v.status="fulfilled",v.value=M)},function(M){v.status==="pending"&&(v.status="rejected",v.reason=M)})),v.status){case"fulfilled":return v.value;case"rejected":throw v.reason}}throw v}function X(v,M,B,Y,al){var nl=typeof v;(nl==="undefined"||nl==="boolean")&&(v=null);var il=!1;if(v===null)il=!0;else switch(nl){case"bigint":case"string":case"number":il=!0;break;case"object":switch(v.$$typeof){case f:case E:il=!0;break;case x:return il=v._init,X(il(v._payload),M,B,Y,al)}}if(il)return al=al(v),il=Y===""?"."+ql(v,0):Y,Il(al)?(B="",il!=null&&(B=il.replace(Fe,"$&/")+"/"),X(al,M,B,"",function(ue){return ue})):al!=null&&(dt(al)&&(al=Pl(al,B+(al.key==null||v&&v.key===al.key?"":(""+al.key).replace(Fe,"$&/")+"/")+il)),M.push(al)),1;il=0;var p=Y===""?".":Y+":";if(Il(v))for(var L=0;L>>1,sl=R[Sl];if(0>>1;Slz(We,Z))vz(M,We)?(R[Sl]=M,R[v]=Z,Sl=v):(R[Sl]=We,R[ee]=Z,Sl=ee);else if(vz(M,Z))R[Sl]=M,R[v]=Z,Sl=v;else break l}}return X}function z(R,X){var Z=R.sortIndex-X.sortIndex;return Z!==0?Z:R.id-X.id}if(f.unstable_now=void 0,typeof performance=="object"&&typeof performance.now=="function"){var A=performance;f.unstable_now=function(){return A.now()}}else{var Q=Date,tl=Q.now();f.unstable_now=function(){return Q.now()-tl}}var $=[],dl=[],x=1,N=null,j=3,vl=!1,Fl=!1,Hl=!1,ol=!1,Dl=typeof setTimeout=="function"?setTimeout:null,kl=typeof clearTimeout=="function"?clearTimeout:null,Ht=typeof setImmediate<"u"?setImmediate:null;function rt(R){for(var X=r(dl);X!==null;){if(X.callback===null)o(dl);else if(X.startTime<=R)o(dl),X.sortIndex=X.expirationTime,E($,X);else break;X=r(dl)}}function Ot(R){if(Hl=!1,rt(R),!Fl)if(r($)!==null)Fl=!0,Il||(Il=!0,dt());else{var X=r(dl);X!==null&&ql(Ot,X.startTime-R)}}var Il=!1,F=-1,el=5,q=-1;function at(){return ol?!0:!(f.unstable_now()-qR&&at());){var Sl=N.callback;if(typeof Sl=="function"){N.callback=null,j=N.priorityLevel;var sl=Sl(N.expirationTime<=R);if(R=f.unstable_now(),typeof sl=="function"){N.callback=sl,rt(R),X=!0;break t}N===r($)&&o($),rt(R)}else o($);N=r($)}if(N!==null)X=!0;else{var qt=r(dl);qt!==null&&ql(Ot,qt.startTime-R),X=!1}}break l}finally{N=null,j=Z,vl=!1}X=void 0}}finally{X?dt():Il=!1}}}var dt;if(typeof Ht=="function")dt=function(){Ht(Pl)};else if(typeof MessageChannel<"u"){var Te=new MessageChannel,Fe=Te.port2;Te.port1.onmessage=Pl,dt=function(){Fe.postMessage(null)}}else dt=function(){Dl(Pl,0)};function ql(R,X){F=Dl(function(){R(f.unstable_now())},X)}f.unstable_IdlePriority=5,f.unstable_ImmediatePriority=1,f.unstable_LowPriority=4,f.unstable_NormalPriority=3,f.unstable_Profiling=null,f.unstable_UserBlockingPriority=2,f.unstable_cancelCallback=function(R){R.callback=null},f.unstable_forceFrameRate=function(R){0>R||125Sl?(R.sortIndex=Z,E(dl,R),r($)===null&&R===r(dl)&&(Hl?(kl(F),F=-1):Hl=!0,ql(Ot,Z-Sl))):(R.sortIndex=sl,E($,R),Fl||vl||(Fl=!0,Il||(Il=!0,dt()))),R},f.unstable_shouldYield=at,f.unstable_wrapCallback=function(R){var X=j;return function(){var Z=j;j=X;try{return R.apply(this,arguments)}finally{j=Z}}}})(Uo)),Uo}var vv;function qh(){return vv||(vv=1,Co.exports=Hh()),Co.exports}var jo={exports:{}},$l={};/** + * @license React + * react-dom.production.js + * + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */var mv;function Bh(){if(mv)return $l;mv=1;var f=Ho();function E(x){var N="https://react.dev/errors/"+x;if(1"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(f)}catch(E){console.error(E)}}return f(),jo.exports=Bh(),jo.exports}/** + * @license React + * react-dom-client.production.js + * + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */var hv;function Gh(){if(hv)return on;hv=1;var f=qh(),E=Ho(),r=Yh();function o(l){var t="https://react.dev/errors/"+l;if(1Eu||(l.current=Zc[Eu],Zc[Eu]=null,Eu--)}function bl(l,t){Eu++,Zc[Eu]=l.current,l.current=t}var Lt=Zt(null),va=Zt(null),be=Zt(null),sn=Zt(null);function rn(l,t){switch(bl(be,t),bl(va,l),bl(Lt,null),t.nodeType){case 9:case 11:l=(l=t.documentElement)&&(l=l.namespaceURI)?g0(l):0;break;default:if(l=t.tagName,t=t.namespaceURI)t=g0(t),l=S0(t,l);else switch(l){case"svg":l=1;break;case"math":l=2;break;default:l=0}}Xl(Lt),bl(Lt,l)}function zu(){Xl(Lt),Xl(va),Xl(be)}function Lc(l){var t=l.memoizedState;t!==null&&(oa._currentValue=t.memoizedState,bl(sn,l)),t=Lt.current;var e=S0(t,l.type);t!==e&&(bl(va,l),bl(Lt,e))}function dn(l){va.current===l&&(Xl(Lt),Xl(va)),sn.current===l&&(Xl(sn),oa._currentValue=ue)}var Kc,Yo;function Ee(l){if(Kc===void 0)try{throw Error()}catch(e){var t=e.stack.trim().match(/\n( *(at )?)/);Kc=t&&t[1]||"",Yo=-1)":-1a||s[u]!==h[a]){var b=` +`+s[u].replace(" at new "," at ");return l.displayName&&b.includes("")&&(b=b.replace("",l.displayName)),b}while(1<=u&&0<=a);break}}}finally{Jc=!1,Error.prepareStackTrace=e}return(e=l?l.displayName||l.name:"")?Ee(e):""}function Hv(l,t){switch(l.tag){case 26:case 27:case 5:return Ee(l.type);case 16:return Ee("Lazy");case 13:return l.child!==t&&t!==null?Ee("Suspense Fallback"):Ee("Suspense");case 19:return Ee("SuspenseList");case 0:case 15:return wc(l.type,!1);case 11:return wc(l.type.render,!1);case 1:return wc(l.type,!0);case 31:return Ee("Activity");case 30:return Ee("ViewTransition");default:return""}}function Go(l){try{var t="",e=null;do t+=Hv(l,e),e=l,l=l.return;while(l);return t}catch(u){return` +Error generating stack: `+u.message+` +`+u.stack}}var $c=Object.prototype.hasOwnProperty,Fc=f.unstable_scheduleCallback,Wc=f.unstable_cancelCallback,qv=f.unstable_shouldYield,Bv=f.unstable_requestPaint,vt=f.unstable_now,Yv=f.unstable_getCurrentPriorityLevel,Qo=f.unstable_ImmediatePriority,Xo=f.unstable_UserBlockingPriority,vn=f.unstable_NormalPriority,Gv=f.unstable_LowPriority,Vo=f.unstable_IdlePriority,Qv=f.log,Xv=f.unstable_setDisableYieldValue,ma=null,mt=null;function ze(l){if(typeof Qv=="function"&&Xv(l),mt&&typeof mt.setStrictMode=="function")try{mt.setStrictMode(ma,l)}catch{}}var yt=Math.clz32?Math.clz32:Lv,Vv=Math.log,Zv=Math.LN2;function Lv(l){return l>>>=0,l===0?32:31-(Vv(l)/Zv|0)|0}var mn=256,yn=262144,hn=4194304;function ke(l){var t=l&42;if(t!==0)return t;switch(l&-l){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:return 64;case 128:return 128;case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:return l&-l;case 262144:case 524288:case 1048576:case 2097152:return l&3932160;case 4194304:case 8388608:case 16777216:case 33554432:return l&62914560;case 67108864:return 67108864;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 0;default:return l}}function gn(l,t,e){var u=l.pendingLanes;if(u===0)return 0;var a=0,n=l.suspendedLanes,c=l.pingedLanes;l=l.warmLanes;var i=u&134217727;return i!==0?(u=i&~n,u!==0?a=ke(u):(c&=i,c!==0?a=ke(c):e||(e=i&~l,e!==0&&(a=ke(e))))):(i=u&~n,i!==0?a=ke(i):c!==0?a=ke(c):e||(e=u&~l,e!==0&&(a=ke(e)))),a===0?0:t!==0&&t!==a&&(t&n)===0&&(n=a&-a,e=t&-t,n>=e||n===32&&(e&4194048)!==0)?t:a}function ya(l,t){return(l.pendingLanes&~(l.suspendedLanes&~l.pingedLanes)&t)===0}function Zo(l,t){(t&8)!==0&&(t|=t&32);var e=l.entangledLanes;if(e!==0)for(l=l.entanglements,e&=t;0e;e++)t.push(l);return t}function ha(l,t){l.pendingLanes|=t,t!==268435456&&(l.suspendedLanes=0,l.pingedLanes=0,l.warmLanes=0)}function Jv(l,t,e,u,a,n){var c=l.pendingLanes;l.pendingLanes=e,l.suspendedLanes=0,l.pingedLanes=0,l.warmLanes=0,l.expiredLanes&=e,l.entangledLanes&=e,l.errorRecoveryDisabledLanes&=e,l.shellSuspendCounter=0;var i=l.entanglements,s=l.expirationTimes,h=l.hiddenUpdates;for(e=c&~e;0"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),ii=!1;if(ce)try{var ba={};Object.defineProperty(ba,"passive",{get:function(){ii=!0}}),window.addEventListener("test",ba,ba),window.removeEventListener("test",ba,ba)}catch{ii=!1}var Ne=null,fi=null,Nn=null;function vs(){if(Nn)return Nn;var l,t=fi,e=t.length,u,a="value"in Ne?Ne.value:Ne.textContent,n=a.length;for(l=0;l=Na),Ts=" ",bs=!1;function Es(l,t){switch(l){case"keyup":return Dm.indexOf(t.keyCode)!==-1;case"keydown":return t.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function zs(l){return l=l.detail,typeof l=="object"&&"data"in l?l.data:null}var Uu=!1;function Cm(l,t){switch(l){case"compositionend":return zs(t);case"keypress":return t.which!==32?null:(bs=!0,Ts);case"textInput":return l=t.data,l===Ts&&bs?null:l;default:return null}}function Um(l,t){if(Uu)return l==="compositionend"||!vi&&Es(l,t)?(l=vs(),Nn=fi=Ne=null,Uu=!1,l):null;switch(l){case"paste":return null;case"keypress":if(!(t.ctrlKey||t.altKey||t.metaKey)||t.ctrlKey&&t.altKey){if(t.char&&1"u")return null;try{return l.activeElement||l.body}catch{return l.body}}function Cs(l){for(;l&&l.firstChild;)l=l.firstChild;return l}function Us(l,t){var e=Cs(l);l=0;for(var u;e;){if(e.nodeType===3){if(u=l+e.textContent.length,l<=t&&u>=t)return{node:e,offset:t-l};l=u}l:{for(;e;){if(e.nextSibling){e=e.nextSibling;break l}e=e.parentNode}e=void 0}e=Cs(e)}}function js(l,t){return l&&t?l===t?!0:l&&l.nodeType===3?!1:t&&t.nodeType===3?js(l,t.parentNode):"contains"in l?l.contains(t):l.compareDocumentPosition?!!(l.compareDocumentPosition(t)&16):!1:!1}function ps(l){l=l!=null&&l.ownerDocument!=null&&l.ownerDocument.defaultView!=null?l.ownerDocument.defaultView:window;for(var t=hi(l.document);t instanceof l.HTMLIFrameElement;){try{var e=typeof t.contentWindow.location.href=="string"}catch{e=!1}if(e)l=t.contentWindow;else break;t=hi(l.document)}return t}function gi(l){var t=l&&l.nodeName&&l.nodeName.toLowerCase();return t&&(t==="input"&&(l.type==="text"||l.type==="search"||l.type==="tel"||l.type==="url"||l.type==="password")||t==="textarea"||l.contentEditable==="true")}var Gm=ce&&"documentMode"in document&&11>=document.documentMode,ju=null,Si=null,Ma=null,Ti=!1;function xs(l,t,e){var u=e.window===e?e.document:e.nodeType===9?e:e.ownerDocument;Ti||ju==null||ju!==hi(u)||(u=ju,"selectionStart"in u&&gi(u)?u={start:u.selectionStart,end:u.selectionEnd}:(u=(u.ownerDocument&&u.ownerDocument.defaultView||window).getSelection(),u={anchorNode:u.anchorNode,anchorOffset:u.anchorOffset,focusNode:u.focusNode,focusOffset:u.focusOffset}),Ma&&Aa(Ma,u)||(Ma=u,u=Dc(Si,"onSelect"),0>=c,a-=c,Jt=1<<32-yt(t)+a|e<G?(pl=H,H=null):pl=H.sibling;var ul=m(y,H,S[G],O);if(ul===null){H===null&&(H=pl);break}l&&H&&ul.alternate===null&&t(y,H),d=n(ul,d,G),ll===null?C=ul:ll.sibling=ul,ll=ul,H=pl}if(G===S.length)return e(y,H),W&&se(y,G),C;if(H===null){for(;GG?(pl=H,H=null):pl=H.sibling;var $e=m(y,H,ul.value,O);if($e===null){H===null&&(H=pl);break}l&&H&&$e.alternate===null&&t(y,H),d=n($e,d,G),ll===null?C=$e:ll.sibling=$e,ll=$e,H=pl}if(ul.done)return e(y,H),W&&se(y,G),C;if(H===null){for(;!ul.done;G++,ul=S.next())ul=_(y,ul.value,O),ul!==null&&(d=n(ul,d,G),ll===null?C=ul:ll.sibling=ul,ll=ul);return W&&se(y,G),C}for(H=u(H);!ul.done;G++,ul=S.next())ul=T(H,y,G,ul.value,O),ul!==null&&(l&&(pl=ul.alternate,pl!==null&&H.delete(pl.key===null?G:pl.key)),d=n(ul,d,G),ll===null?C=ul:ll.sibling=ul,ll=ul);return l&&H.forEach(function(Ch){return t(y,Ch)}),W&&se(y,G),C}function w(y,d,S,O){if(typeof S=="object"&&S!==null&&S.type===Pl&&S.key===null&&S.props.ref===void 0&&(S=S.props.children),typeof S=="object"&&S!==null){switch(S.$$typeof){case q:l:{for(var C=S.key;d!==null;){if(d.key===C){if(C=S.type,C===Pl){if(d.tag===7){e(y,d.sibling),O=a(d,S.props.children),Re(O,S),O.return=y,y=O;break l}}else if(d.elementType===C||typeof C=="object"&&C!==null&&C.$$typeof===sl&&su(C)===d.type){e(y,d.sibling),O=a(d,S.props),Re(O,S),O.return=y,y=O;break l}e(y,d);break}else t(y,d);d=d.sibling}S.type===Pl?(O=uu(S.props.children,y.mode,O,S.key),Re(O,S),O.return=y,y=O):(O=pn(S.type,S.key,S.props,null,y.mode,O),Re(O,S),O.return=y,y=O)}return c(y);case at:l:{for(C=S.key;d!==null;){if(d.key===C)if(d.tag===4&&d.stateNode.containerInfo===S.containerInfo&&d.stateNode.implementation===S.implementation){e(y,d.sibling),O=a(d,S.children||[]),O.return=y,y=O;break l}else{e(y,d);break}else t(y,d);d=d.sibling}O=Ai(S,y.mode,O),O.return=y,y=O}return c(y);case sl:return S=su(S),w(y,d,S,O)}if(il(S))return D(y,d,S,O);if(Y(S)){if(C=Y(S),typeof C!="function")throw Error(o(150));return S=C.call(S),U(y,d,S,O)}if(typeof S.then=="function")return w(y,d,Zn(S),O);if(S.$$typeof===ql)return w(y,d,Gn(y,S),O);Ln(y,S)}return typeof S=="string"&&S!==""||typeof S=="number"||typeof S=="bigint"?(S=""+S,d!==null&&d.tag===6?(e(y,d.sibling),O=a(d,S),O.return=y,y=O):(e(y,d),O=_i(S,y.mode,O),O.return=y,y=O),c(y)):e(y,d)}return function(y,d,S,O){try{pa=0;var C=w(y,d,S,O);return Xu=null,C}catch(H){if(H===Qu||H===Xn)throw H;var ll=ct(29,H,null,y.mode);return ll.lanes=O,ll.return=y,ll}finally{}}}var du=ar(!0),nr=ar(!1),Ce=!1;function qi(l){l.updateQueue={baseState:l.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,lanes:0,hiddenCallbacks:null},callbacks:null}}function Bi(l,t){l=l.updateQueue,t.updateQueue===l&&(t.updateQueue={baseState:l.baseState,firstBaseUpdate:l.firstBaseUpdate,lastBaseUpdate:l.lastBaseUpdate,shared:l.shared,callbacks:null})}function Ue(l){return{lane:l,tag:0,payload:null,callback:null,next:null}}function je(l,t,e){var u=l.updateQueue;if(u===null)return null;if(u=u.shared,(fl&2)!==0){var a=u.pending;return a===null?t.next=t:(t.next=a.next,a.next=t),u.pending=t,t=jn(l),Vs(l,null,e),t}return Un(l,u,t,e),jn(l)}function xa(l,t,e){if(t=t.updateQueue,t!==null&&(t=t.shared,(e&4194048)!==0)){var u=t.lanes;u&=l.pendingLanes,e|=u,t.lanes=e,Jo(l,e)}}function Yi(l,t){var e=l.updateQueue,u=l.alternate;if(u!==null&&(u=u.updateQueue,e===u)){var a=null,n=null;if(e=e.firstBaseUpdate,e!==null){do{var c={lane:e.lane,tag:e.tag,payload:e.payload,callback:null,next:null};n===null?a=n=c:n=n.next=c,e=e.next}while(e!==null);n===null?a=n=t:n=n.next=t}else a=n=t;e={baseState:u.baseState,firstBaseUpdate:a,lastBaseUpdate:n,shared:u.shared,callbacks:u.callbacks},l.updateQueue=e;return}l=e.lastBaseUpdate,l===null?e.firstBaseUpdate=t:l.next=t,e.lastBaseUpdate=t}var Gi=!1;function Ha(){if(Gi){var l=Gu;if(l!==null)throw l}}function qa(l,t,e,u){Gi=!1;var a=l.updateQueue;Ce=!1;var n=a.firstBaseUpdate,c=a.lastBaseUpdate,i=a.shared.pending;if(i!==null){a.shared.pending=null;var s=i,h=s.next;s.next=null,c===null?n=h:c.next=h,c=s;var b=l.alternate;b!==null&&(b=b.updateQueue,i=b.lastBaseUpdate,i!==c&&(i===null?b.firstBaseUpdate=h:i.next=h,b.lastBaseUpdate=s))}if(n!==null){var _=a.baseState;c=0,b=h=s=null,i=n;do{var m=i.lane&-536870913,T=m!==i.lane;if(T?(P&m)===m:(u&m)===m){m!==0&&m===fu&&(Gi=!0),b!==null&&(b=b.next={lane:0,tag:i.tag,payload:i.payload,callback:null,next:null});l:{var D=l,U=i;m=t;var w=e;switch(U.tag){case 1:if(D=U.payload,typeof D=="function"){_=D.call(w,_,m);break l}_=D;break l;case 3:D.flags=D.flags&-65537|128;case 0:if(D=U.payload,m=typeof D=="function"?D.call(w,_,m):D,m==null)break l;_=F({},_,m);break l;case 2:Ce=!0}}m=i.callback,m!==null&&(l.flags|=64,T&&(l.flags|=8192),T=a.callbacks,T===null?a.callbacks=[m]:T.push(m))}else T={lane:m,tag:i.tag,payload:i.payload,callback:i.callback,next:null},b===null?(h=b=T,s=_):b=b.next=T,c|=m;if(i=i.next,i===null){if(i=a.shared.pending,i===null)break;T=i,i=T.next,T.next=null,a.lastBaseUpdate=T,a.shared.pending=null}}while(!0);b===null&&(s=_),a.baseState=s,a.firstBaseUpdate=h,a.lastBaseUpdate=b,n===null&&(a.shared.lanes=0),Ge|=c,l.lanes=c,l.memoizedState=_}}function cr(l,t){if(typeof l!="function")throw Error(o(191,l));l.call(t)}function ir(l,t){var e=l.callbacks;if(e!==null)for(l.callbacks=null,l=0;ln?n:8;var c=p.T,i={};i.types=c!==null?c.types:null,p.T=i,nf(l,!1,t,e);try{var s=a(),h=p.S;if(h!==null&&h(i,s),s!==null&&typeof s=="object"&&typeof s.then=="function"){var b=Wm(s,u);Qa(l,t,b,zt(l))}else Qa(l,t,u,zt(l))}catch(_){Qa(l,t,{then:function(){},status:"rejected",reason:_},zt())}finally{L.p=n,c!==null&&i.types!==null&&(c.types=i.types),p.T=c}}function ey(){}function uf(l,t,e,u){if(l.tag!==5)throw Error(o(476));var a=Gr(l).queue;Yr(l,a,t,ue,e===null?ey:function(){return Qr(l),e(u)})}function Gr(l){var t=l.memoizedState;if(t!==null)return t;t={memoizedState:ue,baseState:ue,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:me,lastRenderedState:ue},next:null};var e={};return t.next={memoizedState:e,baseState:e,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:me,lastRenderedState:e},next:null},l.memoizedState=t,l=l.alternate,l!==null&&(l.memoizedState=t),t}function Qr(l){var t=Gr(l);t.next===null&&(t=l.alternate.memoizedState),Qa(l,t.next.queue,{},zt())}function af(){return Zl(oa)}function Xr(){return Rl().memoizedState}function Vr(){return Rl().memoizedState}function uy(l){for(var t=l.return;t!==null;){switch(t.tag){case 24:case 3:var e=zt();l=Ue(e);var u=je(t,l,e);u!==null&&(st(u,t,e),xa(u,t,e)),t={cache:ji()},l.payload=t;return}t=t.return}}function ay(l,t,e){var u=zt();e={lane:u,revertLane:0,gesture:null,action:e,hasEagerState:!1,eagerState:null,next:null},lc(l)?Lr(t,e):(e=Ni(l,t,e,u),e!==null&&(st(e,l,u),Kr(e,t,u)))}function Zr(l,t,e){var u=zt();Qa(l,t,e,u)}function Qa(l,t,e,u){var a={lane:u,revertLane:0,gesture:null,action:e,hasEagerState:!1,eagerState:null,next:null};if(lc(l))Lr(t,a);else{var n=l.alternate;if(l.lanes===0&&(n===null||n.lanes===0)&&(n=t.lastRenderedReducer,n!==null))try{var c=t.lastRenderedState,i=n(c,e);if(a.hasEagerState=!0,a.eagerState=i,gt(i,c))return Un(l,t,a,0),Tl===null&&Cn(),!1}catch{}finally{}if(e=Ni(l,t,a,u),e!==null)return st(e,l,u),Kr(e,t,u),!0}return!1}function nf(l,t,e,u){if(u={lane:2,revertLane:Wf(),gesture:null,action:u,hasEagerState:!1,eagerState:null,next:null},lc(l)){if(t)throw Error(o(479))}else t=Ni(l,e,u,2),t!==null&&st(t,l,2)}function lc(l){var t=l.alternate;return l===J||t!==null&&t===J}function Lr(l,t){Vu=wn=!0;var e=l.pending;e===null?t.next=t:(t.next=e.next,e.next=t),l.pending=t}function Kr(l,t,e){if((e&4194048)!==0){var u=t.lanes;u&=l.pendingLanes,e|=u,t.lanes=e,Jo(l,e)}}var tc={readContext:Zl,use:Wn,useCallback:Al,useContext:Al,useEffect:Al,useImperativeHandle:Al,useLayoutEffect:Al,useInsertionEffect:Al,useMemo:Al,useReducer:Al,useRef:Al,useState:Al,useDebugValue:Al,useDeferredValue:Al,useTransition:Al,useSyncExternalStore:Al,useId:Al,useHostTransitionStatus:Al,useFormState:Al,useActionState:Al,useOptimistic:Al,useMemoCache:Al,useCacheRefresh:Al,useEffectEvent:Al},Jr={readContext:Zl,use:Wn,useCallback:function(l,t){return tt().memoizedState=[l,t===void 0?null:t],l},useContext:Zl,useEffect:Rr,useImperativeHandle:function(l,t,e){e=e!=null?e.concat([l]):null,In(4194308,4,pr.bind(null,t,l),e)},useLayoutEffect:function(l,t){return In(4194308,4,l,t)},useInsertionEffect:function(l,t){In(4,2,l,t)},useMemo:function(l,t){var e=tt();t=t===void 0?null:t;var u=l();if(vu){ze(!0);try{l()}finally{ze(!1)}}return e.memoizedState=[u,t],u},useReducer:function(l,t,e){var u=tt();if(e!==void 0){var a=e(t);if(vu){ze(!0);try{e(t)}finally{ze(!1)}}}else a=t;return u.memoizedState=u.baseState=a,l={pending:null,lanes:0,dispatch:null,lastRenderedReducer:l,lastRenderedState:a},u.queue=l,l=l.dispatch=ay.bind(null,J,l),[u.memoizedState,l]},useRef:function(l){var t=tt();return l={current:l},t.memoizedState=l},useState:function(l){l=Ii(l);var t=l.queue,e=Zr.bind(null,J,t);return t.dispatch=e,[l.memoizedState,e]},useDebugValue:tf,useDeferredValue:function(l,t){var e=tt();return ef(e,l,t)},useTransition:function(){var l=Ii(!1);return l=Yr.bind(null,J,l.queue,!0,!1),tt().memoizedState=l,[!1,l]},useSyncExternalStore:function(l,t,e){var u=J,a=tt();if(W){if(e===void 0)throw Error(o(407));e=e()}else{if(e=t(),Tl===null)throw Error(o(349));(P&127)!==0||vr(u,t,e)}a.memoizedState=e;var n={value:e,getSnapshot:t};return a.queue=n,Rr(yr.bind(null,u,n,l),[l]),u.flags|=2048,Lu(9,{destroy:void 0},mr.bind(null,u,n,e,t),null),e},useId:function(){var l=tt(),t=Tl.identifierPrefix;if(W){var e=wt,u=Jt;e=(u&~(1<<32-yt(u)-1)).toString(32)+e,t="_"+t+"R_"+e,e=$n++,0<\/script>",n=n.removeChild(n.firstChild);break;case"select":n=typeof u.is=="string"?c.createElement("select",{is:u.is}):c.createElement("select"),u.multiple?n.multiple=!0:u.size&&(n.size=u.size);break;default:n=typeof u.is=="string"?c.createElement(a,{is:u.is}):c.createElement(a)}}n[Vl]=t,n[nt]=u;l:for(c=t.child;c!==null;){if(c.tag===5||c.tag===6)n.appendChild(c.stateNode);else if(c.tag!==4&&c.tag!==27&&c.child!==null){c.child.return=c,c=c.child;continue}if(c===t)break l;for(;c.sibling===null;){if(c.return===null||c.return===t)break l;c=c.return}c.sibling.return=c.return,c=c.sibling}t.stateNode=n;l:switch(wl(n,a,u),a){case"button":case"input":case"select":case"textarea":u=!!u.autoFocus;break l;case"img":u=!0;break l;default:u=!1}u&&he(t)}}return zl(t),t.subtreeFlags&=-33554433,Tf(t,t.type,l===null?null:l.memoizedProps,t.pendingProps,e),null;case 6:if(l&&t.stateNode!=null)l.memoizedProps!==u&&he(t);else{if(typeof u!="string"&&t.stateNode===null)throw Error(o(166));if(l=be.current,Yu(t)){if(l=t.stateNode,e=t.memoizedProps,u=null,a=Yl,a!==null)switch(a.tag){case 27:case 5:u=a.memoizedProps}l[Vl]=t,l=!!(l.nodeValue===e||u!==null&&u.suppressHydrationWarning===!0||y0(l.nodeValue,e)),l||Me(t,!0)}else l=Pa(l).createTextNode(u),l[Vl]=t,t.stateNode=l}return zl(t),null;case 31:if(e=t.memoizedState,l===null||l.memoizedState!==null){if(u=Yu(t),e!==null){if(l===null){if(!u)throw Error(o(318));if(l=t.memoizedState,l=l!==null?l.dehydrated:null,!l)throw Error(o(557));l[Vl]=t}else au(),(t.flags&128)===0&&(t.memoizedState=null),t.flags|=4;zl(t),l=!1}else e=Ri(),l!==null&&l.memoizedState!==null&&(l.memoizedState.hydrationErrors=e),l=!0;if(!l)return t.flags&256?(St(t),t):(St(t),null);if((t.flags&128)!==0)throw Error(o(558))}return zl(t),null;case 13:if(u=t.memoizedState,l===null||l.memoizedState!==null&&l.memoizedState.dehydrated!==null){if(a=Yu(t),u!==null&&u.dehydrated!==null){if(l===null){if(!a)throw Error(o(318));if(a=t.memoizedState,a=a!==null?a.dehydrated:null,!a)throw Error(o(317));a[Vl]=t}else au(),(t.flags&128)===0&&(t.memoizedState=null),t.flags|=4;zl(t),a=!1}else a=Ri(),l!==null&&l.memoizedState!==null&&(l.memoizedState.hydrationErrors=a),a=!0;if(!a)return t.flags&256?(St(t),t):(St(t),null)}return St(t),(t.flags&128)!==0?(t.lanes=e,t):(e=u!==null,l=l!==null&&l.memoizedState!==null,e&&(u=t.child,a=null,u.alternate!==null&&u.alternate.memoizedState!==null&&u.alternate.memoizedState.cachePool!==null&&(a=u.alternate.memoizedState.cachePool.pool),n=null,u.memoizedState!==null&&u.memoizedState.cachePool!==null&&(n=u.memoizedState.cachePool.pool),n!==a&&(u.flags|=2048)),e!==l&&e&&(t.child.flags|=8192),ic(t,t.updateQueue),zl(t),null);case 4:return zu(),l===null&&lo(t.stateNode.containerInfo),t.flags|=67108864,zl(t),null;case 10:return de(t.type),zl(t),null;case 19:if(Zi(t),u=t.memoizedState,u===null)return zl(t),null;if(a=(t.flags&128)!==0,n=u.rendering,n===null)if(a)Va(u,!1);else{if(Ml!==0||l!==null&&(l.flags&128)!==0)for(l=t.child;l!==null;){if(n=Jn(l),n!==null){for(t.flags|=128,Va(u,!1),l=n.updateQueue,t.updateQueue=l,ic(t,l),t.subtreeFlags=0,l=e,e=t.child;e!==null;)Zs(e,l),e=e.sibling;return Ba(t,Kl.current&1|2),W&&se(t,u.treeForkCount),t.child}l=l.sibling}u.tail!==null&&vt()>Tc&&(t.flags|=128,a=!0,Va(u,!1),t.lanes=4194304)}else{if(!a)if(l=Jn(n),l!==null){if(t.flags|=128,a=!0,l=l.updateQueue,t.updateQueue=l,ic(t,l),Va(u,!0),u.tail===null&&u.tailMode!=="collapsed"&&u.tailMode!=="visible"&&!n.alternate&&!W)return zl(t),null}else 2*vt()-u.renderingStartTime>Tc&&e!==536870912&&(t.flags|=128,a=!0,Va(u,!1),t.lanes=4194304);u.isBackwards?(n.sibling=t.child,t.child=n):(l=u.last,l!==null?l.sibling=n:t.child=n,u.last=n)}if(u.tail!==null){l=u.tail;l:{for(e=l;e!==null;){if(e.alternate!==null){e=!1;break l}e=e.sibling}e=!0}return u.rendering=l,u.tail=l.sibling,u.renderingStartTime=vt(),l.sibling=null,n=Kl.current,n=a?n&1|2:n&1,u.tailMode==="visible"||u.tailMode==="collapsed"||!e||W?Ba(t,n):(e=n,bl(Ll,t),bl(Kl,e),Wl===null&&(Wl=t)),W&&se(t,u.treeForkCount),l}return zl(t),null;case 22:case 23:return St(t),Xi(),u=t.memoizedState!==null,l!==null?l.memoizedState!==null!==u&&(t.flags|=8192):u&&(t.flags|=8192),u?(e&536870912)!==0&&(t.flags&128)===0&&(zl(t),t.subtreeFlags&6&&(t.flags|=8192)):zl(t),e=t.updateQueue,e!==null&&ic(t,e.retryQueue),e=null,l!==null&&l.memoizedState!==null&&l.memoizedState.cachePool!==null&&(e=l.memoizedState.cachePool.pool),u=null,t.memoizedState!==null&&t.memoizedState.cachePool!==null&&(u=t.memoizedState.cachePool.pool),u!==e&&(t.flags|=2048),l!==null&&Xl(ou),null;case 24:return e=null,l!==null&&(e=l.memoizedState.cache),t.memoizedState.cache!==e&&(t.flags|=2048),de(Cl),zl(t),null;case 25:return null;case 30:return t.flags|=33554432,zl(t),null}throw Error(o(156,t.tag))}function ry(l,t){switch(Mi(t),t.tag){case 1:return l=t.flags,l&65536?(t.flags=l&-65537|128,t):null;case 3:return de(Cl),zu(),l=t.flags,(l&65536)!==0&&(l&128)===0?(t.flags=l&-65537|128,t):null;case 26:case 27:case 5:return dn(t),null;case 31:if(t.memoizedState!==null){if(St(t),t.alternate===null)throw Error(o(340));au()}return l=t.flags,l&65536?(t.flags=l&-65537|128,t):null;case 13:if(St(t),l=t.memoizedState,l!==null&&l.dehydrated!==null){if(t.alternate===null)throw Error(o(340));au()}return l=t.flags,l&65536?(t.flags=l&-65537|128,t):null;case 19:return Zi(t),l=t.flags,l&65536?(t.flags=l&-65537|128,l=t.memoizedState,l!==null&&(l.rendering=null,l.tail=null),t.flags|=4,t):null;case 4:return zu(),null;case 10:return de(t.type),null;case 22:case 23:return St(t),Xi(),l!==null&&Xl(ou),l=t.flags,l&65536?(t.flags=l&-65537|128,t):null;case 24:return de(Cl),null;case 25:return null;default:return null}}function gd(l,t){switch(Mi(t),t.tag){case 3:de(Cl),zu();break;case 26:case 27:case 5:dn(t);break;case 4:zu();break;case 31:t.memoizedState!==null&&St(t);break;case 13:St(t);break;case 19:Zi(t);break;case 10:de(t.type);break;case 22:case 23:St(t),Xi(),l!==null&&Xl(ou);break;case 24:de(Cl)}}function Za(l,t){try{var e=t.updateQueue,u=e!==null?e.lastEffect:null;if(u!==null){var a=u.next;e=a;do{if((e.tag&l)===l){u=void 0;var n=e.create,c=e.inst;u=n(),c.destroy=u}e=e.next}while(e!==a)}}catch(i){yl(t,t.return,i)}}function qe(l,t,e){try{var u=t.updateQueue,a=u!==null?u.lastEffect:null;if(a!==null){var n=a.next;u=n;do{if((u.tag&l)===l){var c=u.inst,i=c.destroy;if(i!==void 0){c.destroy=void 0,a=t;var s=e,h=i;try{h()}catch(b){yl(a,s,b)}}}u=u.next}while(u!==n)}}catch(b){yl(t,t.return,b)}}function Sd(l){var t=l.updateQueue;if(t!==null){var e=l.stateNode;try{ir(t,e)}catch(u){yl(l,l.return,u)}}}function Td(l,t,e){e.props=mu(l.type,l.memoizedProps),e.state=l.memoizedState;try{e.componentWillUnmount()}catch(u){yl(l,t,u)}}function $t(l,t){try{var e=l.ref;if(e!==null){switch(l.tag){case 26:case 27:case 5:var u=l.stateNode;break;case 30:var a=l.stateNode,n=ie(l.memoizedProps,a);(a.ref===null||a.ref.name!==n)&&(a.ref=A0(n)),u=a.ref;break;case 7:if(l.stateNode===null){var c=new Nt(l);N(l.child,!1,th,c,void 0,void 0),l.stateNode=c}u=l.stateNode;break;default:u=l.stateNode}typeof e=="function"?l.refCleanup=e(u):e.current=u}}catch(i){yl(l,t,i)}}function Jl(l,t){var e=l.ref,u=l.refCleanup;if(e!==null)if(typeof u=="function")try{u()}catch(a){yl(l,t,a)}finally{l.refCleanup=null,l=l.alternate,l!=null&&(l.refCleanup=null)}else if(typeof e=="function")try{e(null)}catch(a){yl(l,t,a)}else e.current=null}function fc(l,t){if((l.tag===5||l.tag===27||l.tag===6)&&l.alternate===null&&t!==null)for(var e=0;e title"))),wl(u,t,e),u[Vl]=l,Bl(u),t=u;break l;case"link":if(n=Z0("link","href",a).get(t+(e.href||""))){for(c=0;cw&&(c=w,w=U,U=c);var y=Us(i,U),d=Us(i,w);if(y&&d&&(T.rangeCount!==1||T.anchorNode!==y.node||T.anchorOffset!==y.offset||T.focusNode!==d.node||T.focusOffset!==d.offset)){var S=_.createRange();S.setStart(y.node,y.offset),T.removeAllRanges(),U>w?(T.addRange(S),T.extend(d.node,d.offset)):(S.setEnd(d.node,d.offset),T.addRange(S))}}}}for(_=[],T=i;T=T.parentNode;)T.nodeType===1&&_.push({element:T,left:T.scrollLeft,top:T.scrollTop});for(typeof i.focus=="function"&&i.focus(),i=0;i<_.length;i++){var O=_[i];O.element.scrollLeft=O.left,O.element.scrollTop=O.top}}sa=!!uo,ao=uo=null}finally{fl=n,L.p=a,p.T=u}}l.current=t,_l=2}}function Lf(){if(_l===2){_l=0;var l=Xt,t=Su,e=(t.flags&8772)!==0;if((t.subtreeFlags&8772)!==0||e){e=p.T,p.T=null;var u=L.p;L.p=2;var a=fl;fl|=4;try{Cd(l,t.alternate,t)}finally{fl=a,L.p=u,p.T=e}}_l=3}}function Kf(){if(_l===4||_l===3){_l=0;var l=ku;ku=null,Bv();var t=Xt,e=Su,u=le,a=Kd,n=(u&335544064)===u?10262:10256;if((e.subtreeFlags&n)!==0||(e.flags&n)!==0?_l=5:(_l=0,Su=Xt=null,u0(t,t.pendingLanes)),n=t.pendingLanes,n===0&&(Qe=null),Pc(u),e=e.stateNode,mt&&typeof mt.onCommitFiberRoot=="function")try{mt.onCommitFiberRoot(ma,e,void 0,(e.current.flags&128)===128)}catch{}if(a!==null){e=p.T,n=L.p,L.p=2,p.T=null;try{for(var c=t.onRecoverableError,i=0;ie?32:e,p.T=null,e=Qf,Qf=null;var n=Xt,c=le;if(_l=0,Su=Xt=null,le=0,(fl&6)!==0)throw Error(o(331));var i=fl;if(fl|=4,Vd(n.current),Gd(n,n.current,c,e),fl=i,Wa(0,!1),mt&&typeof mt.onPostCommitFiberRoot=="function")try{mt.onPostCommitFiberRoot(ma,n)}catch{}return!0}finally{L.p=a,p.T=u,u0(l,t)}}function a0(l,t,e){t=Mt(e,t),t=of(l.stateNode,t,2),l=je(l,t,2),l!==null&&(ha(l,2),te(l))}function yl(l,t,e){if(l.tag===3)a0(l,l,e);else for(;t!==null;){if(t.tag===3){a0(t,l,e);break}else if(t.tag===1){var u=t.stateNode;if(typeof t.type.getDerivedStateFromError=="function"||typeof u.componentDidCatch=="function"&&(Qe===null||!Qe.has(u))){l=Mt(e,l),e=ld(2),u=je(t,e,2),u!==null&&(td(e,u,t,l),ha(u,2),te(u));break}}t=t.return}}function wf(l,t,e){var u=l.pingCache;if(u===null){u=l.pingCache=new yy;var a=new Set;u.set(t,a)}else a=u.get(t),a===void 0&&(a=new Set,u.set(t,a));a.has(e)||(Bf=!0,a.add(e),l=Ny.bind(null,l,t,e),t.then(l,l))}function Ny(l,t,e){var u=l.pingCache;u!==null&&u.delete(t),l.pingedLanes|=l.suspendedLanes&e,l.warmLanes&=~e,Tl===l&&(P&e)===e&&((Ml===4||Ml===3&&(P&62914560)===P&&300>vt()-Sc)&&(fl&2)===0?ta(l,0):gc|=e,Wu===P&&(Wu=0)),te(l)}function n0(l,t){t===0&&(t=Lo()),l=eu(l,t),l!==null&&(ha(l,t),te(l))}function Oy(l){var t=l.memoizedState,e=0;t!==null&&(e=t.retryLane),n0(l,e)}function _y(l,t){var e=0;switch(l.tag){case 31:case 13:var u=l.stateNode,a=l.memoizedState;a!==null&&(e=a.retryLane);break;case 19:u=l.stateNode;break;case 22:u=l.stateNode._retryCache;break;default:throw Error(o(314))}u!==null&&u.delete(t),n0(l,e)}function Ay(l,t){return Fc(l,t)}var ua=null,aa=null,$f=!1,Ac=!1,Ff=!1,Ve=0;function te(l){l!==aa&&l.next===null&&(aa===null?ua=aa=l:aa=aa.next=l),Ac=!0,$f||($f=!0,Dy())}function Wa(l,t){if(!Ff&&Ac){Ff=!0;do for(var e=!1,u=ua;u!==null;){if(l!==0){var a=u.pendingLanes;if(a===0)var n=0;else{var c=u.suspendedLanes,i=u.pingedLanes;n=(1<<31-yt(42|l)+1)-1,n&=a&~(c&~i),n=n&201326741?n&201326741|1:n?n|2:0}n!==0&&(e=!0,o0(u,n))}else n=P,n=gn(u,u===Tl?n:0,u.cancelPendingCommit!==null||u.timeoutHandle!==-1),(n&3)===0||ya(u,n)||(e=!0,o0(u,n));u=u.next}while(e);Ff=!1}}function My(){c0()}function c0(){Ac=$f=!1;var l=0;Ve!==0&&Gy()&&(l=Ve);for(var t=vt(),e=null,u=ua;u!==null;){var a=u.next,n=i0(u,t);n===0?(u.next=null,e===null?ua=a:e.next=a,a===null&&(aa=e)):(e=u,(l!==0||(n&3)!==0)&&(Ac=!0)),u=a}_l!==0&&_l!==5||Wa(l),Ve!==0&&(Ve=0)}function i0(l,t){for(var e=l.suspendedLanes,u=l.pingedLanes,a=l.expirationTimes,n=l.pendingLanes&-62914561;0i)break;var b=s.transferSize,_=s.initiatorType;b&&h0(_)&&(s=s.responseEnd,c+=b*(sUc){U.length=D;break}S=new Promise(Ky.bind(S)),U.push(S)}}}if(0"u"?null:document;function G0(l,t,e){var u=ca;if(u&&typeof t=="string"&&t){var a=_t(t);a='link[rel="'+l+'"][href="'+a+'"]',typeof e=="string"&&(a+='[crossorigin="'+e+'"]'),Y0.has(a)||(Y0.add(a),l={rel:l,crossOrigin:e,href:t},u.querySelector(a)===null&&(t=u.createElement("link"),wl(t,"link",l),Bl(t),u.head.appendChild(t)))}}function sh(l){Se.D(l),G0("dns-prefetch",l,null)}function rh(l,t){Se.C(l,t),G0("preconnect",l,t)}function dh(l,t,e){Se.L(l,t,e);var u=ca;if(u&&l&&t){var a='link[rel="preload"][as="'+_t(t)+'"]';t==="image"&&e&&e.imageSrcSet?(a+='[imagesrcset="'+_t(e.imageSrcSet)+'"]',typeof e.imageSizes=="string"&&(a+='[imagesizes="'+_t(e.imageSizes)+'"]')):a+='[href="'+_t(l)+'"]';var n=a;switch(t){case"style":n=ia(l);break;case"script":n=fa(l)}if(!(pt.has(n)||(l=F({rel:"preload",href:t==="image"&&e&&e.imageSrcSet?void 0:l,as:t},e),pt.set(n,l),u.querySelector(a)!==null||t==="style"&&u.querySelector(tn(n))||t==="script"&&u.querySelector(en(n))))){var c=u.createElement("link");wl(c,"link",l),t==="style"&&(c[Sn]=!0,c.onload=c.onerror=function(){Io(c)}),Bl(c),u.head.appendChild(c)}}}function vh(l,t){Se.m(l,t);var e=ca;if(e&&l){var u=t&&typeof t.as=="string"?t.as:"script",a='link[rel="modulepreload"][as="'+_t(u)+'"][href="'+_t(l)+'"]',n=a;switch(u){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":n=fa(l)}if(!pt.has(n)&&(l=F({rel:"modulepreload",href:l},t),pt.set(n,l),e.querySelector(a)===null)){switch(u){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":if(e.querySelector(en(n)))return}u=e.createElement("link"),wl(u,"link",l),Bl(u),e.head.appendChild(u)}}}function mh(l,t,e){Se.S(l,t,e);var u=ca;if(u&&l){var a=_u(u).hoistableStyles,n=ia(l);t=t||"default";var c=a.get(n);if(!c){var i={loading:0,preload:null};if(c=u.querySelector(tn(n)))i.loading=5;else{l=F({rel:"stylesheet",href:l,"data-precedence":t},e),(e=pt.get(n))&&go(l,e);var s=c=u.createElement("link");Bl(s),wl(s,"link",l),s._p=new Promise(function(h,b){s.onload=h,s.onerror=b}),s.addEventListener("load",function(){i.loading|=1}),s.addEventListener("error",function(){i.loading|=2}),i.loading|=4,Rc(c,t,u)}c={type:"stylesheet",instance:c,count:1,state:i},a.set(n,c)}}}function yh(l,t){Se.X(l,t);var e=ca;if(e&&l){var u=_u(e).hoistableScripts,a=fa(l),n=u.get(a);n||(n=e.querySelector(en(a)),n||(l=F({src:l,async:!0},t),(t=pt.get(a))&&So(l,t),n=e.createElement("script"),Bl(n),wl(n,"link",l),e.head.appendChild(n)),n={type:"script",instance:n,count:1,state:null},u.set(a,n))}}function hh(l,t){Se.M(l,t);var e=ca;if(e&&l){var u=_u(e).hoistableScripts,a=fa(l),n=u.get(a);n||(n=e.querySelector(en(a)),n||(l=F({src:l,async:!0,type:"module"},t),(t=pt.get(a))&&So(l,t),n=e.createElement("script"),Bl(n),wl(n,"link",l),e.head.appendChild(n)),n={type:"script",instance:n,count:1,state:null},u.set(a,n))}}function Q0(l,t,e,u){var a=(a=be.current)?ln(a):null;if(!a)throw Error(o(446));switch(l){case"meta":case"title":return null;case"style":return typeof e.precedence=="string"&&typeof e.href=="string"?(e=ia(e.href),t=_u(a).hoistableStyles,u=t.get(e),u||(u={type:"style",instance:null,count:0,state:null},t.set(e,u)),u):{type:"void",instance:null,count:0,state:null};case"link":if(e.rel==="stylesheet"&&typeof e.href=="string"&&typeof e.precedence=="string"){l=ia(e.href);var n=_u(a).hoistableStyles,c=n.get(l);if(c||(a=a.ownerDocument||a,c={type:"stylesheet",instance:null,count:0,state:{loading:0,preload:null}},n.set(l,c),(n=a.querySelector(tn(l)))?n._p||(c.instance=n,c.state.loading=5):(n=pt.get(l),n||(n={rel:"preload",as:"style",href:e.href,crossOrigin:e.crossOrigin,integrity:e.integrity,media:e.media,hrefLang:e.hrefLang,referrerPolicy:e.referrerPolicy},pt.set(l,n)),gh(a,l,n,c.state))),t&&u===null)throw Error(o(528,""));return c}if(t&&u!==null)throw Error(o(529,""));return null;case"script":return t=e.async,e=e.src,typeof e=="string"&&t&&typeof t!="function"&&typeof t!="symbol"?(e=fa(e),t=_u(a).hoistableScripts,u=t.get(e),u||(u={type:"script",instance:null,count:0,state:null},t.set(e,u)),u):{type:"void",instance:null,count:0,state:null};default:throw Error(o(444,l))}}function ia(l){return'href="'+_t(l)+'"'}function tn(l){return'link[rel="stylesheet"]['+l+"]"}function X0(l){return F({},l,{"data-precedence":l.precedence,precedence:null})}function gh(l,t,e,u){if(t=l.querySelector('link[rel="preload"][as="style"]['+t+"]")){if(t[Sn]!==!0){u.loading=1;return}}else t=l.createElement("link"),t[Sn]=!0,t.onload=t.onerror=Io.bind(null,t),wl(t,"link",e),Bl(t),l.head.appendChild(t);u.preload=t,t.addEventListener("load",function(){return u.loading|=1}),t.addEventListener("error",function(){return u.loading|=2})}function fa(l){return'[src="'+_t(l)+'"]'}function en(l){return"script[async]"+l}function V0(l,t,e){if(t.count++,t.instance===null)switch(t.type){case"style":var u=l.querySelector('style[data-href~="'+_t(e.href)+'"]');if(u)return t.instance=u,Bl(u),u;var a=F({},e,{"data-href":e.href,"data-precedence":e.precedence,href:null,precedence:null});return u=(l.ownerDocument||l).createElement("style"),Bl(u),wl(u,"style",a),Rc(u,e.precedence,l),t.instance=u;case"stylesheet":a=ia(e.href);var n=l.querySelector(tn(a));if(n)return t.state.loading|=4,t.instance=n,Bl(n),n;u=X0(e),(a=pt.get(a))&&go(u,a),n=(l.ownerDocument||l).createElement("link"),Bl(n);var c=n;return c._p=new Promise(function(i,s){c.onload=i,c.onerror=s}),wl(n,"link",u),t.state.loading|=4,Rc(n,e.precedence,l),t.instance=n;case"script":return n=fa(e.src),(a=l.querySelector(en(n)))?(t.instance=a,Bl(a),a):(u=e,(a=pt.get(n))&&(u=F({},e),So(u,a)),l=l.ownerDocument||l,a=l.createElement("script"),Bl(a),wl(a,"link",u),l.head.appendChild(a),t.instance=a);case"void":return null;default:throw Error(o(443,t.type))}else t.type==="stylesheet"&&(t.state.loading&4)===0&&(u=t.instance,t.state.loading|=4,Rc(u,e.precedence,l));return t.instance}function Rc(l,t,e){for(var u=e.querySelectorAll('link[rel="stylesheet"][data-precedence],style[data-precedence]'),a=u.length?u[u.length-1]:null,n=a,c=0;c title"):null)}function Sh(l,t,e){if(e===1||t.itemProp!=null)return!1;switch(l){case"meta":case"title":return!0;case"style":if(typeof t.precedence!="string"||typeof t.href!="string"||t.href==="")break;return!0;case"link":if(typeof t.rel!="string"||typeof t.href!="string"||t.href===""||t.onLoad||t.onError)break;switch(t.rel){case"stylesheet":return l=t.disabled,typeof t.precedence=="string"&&l==null;default:return!0}case"script":if(t.async&&typeof t.async!="function"&&typeof t.async!="symbol"&&!t.onLoad&&!t.onError&&t.src&&typeof t.src=="string")return!0}return!1}function L0(l,t){return l==="img"&&t.src!=null&&t.src!==""&&t.onLoad==null&&t.loading!=="lazy"}function K0(l){return!(l.type==="stylesheet"&&(l.state.loading&3)===0)}function J0(l){return(l.width||100)*(l.height||100)*(typeof devicePixelRatio=="number"?devicePixelRatio:1)*.25}function w0(l,t){typeof t.decode=="function"&&(l.imgCount++,t.complete||(l.imgBytes+=J0(t),l.suspenseyImages.push(t)),l=Eh.bind(l),t.decode().then(l,l))}function Th(l,t,e,u){if(e.type==="stylesheet"&&(typeof u.media!="string"||matchMedia(u.media).matches!==!1)&&(e.state.loading&4)===0){if(e.instance===null){var a=ia(u.href),n=t.querySelector(tn(a));if(n){t=n._p,t!==null&&typeof t=="object"&&typeof t.then=="function"&&(l.count++,l=un.bind(l),t.then(l,l)),e.state.loading|=4,e.instance=n,Bl(n);return}n=t.ownerDocument||t,u=X0(u),(a=pt.get(a))&&go(u,a),n=n.createElement("link"),Bl(n);var c=n;c._p=new Promise(function(i,s){c.onload=i,c.onerror=s}),wl(n,"link",u),e.instance=n}l.stylesheets===null&&(l.stylesheets=new Map),l.stylesheets.set(e,t),(t=e.state.preload)&&(e.state.loading&3)===0&&(l.count++,e=un.bind(l),t.addEventListener("load",e),t.addEventListener("error",e))}}var Uc=0;function bh(l,t){return l.stylesheets&&l.count===0&&pc(l,l.stylesheets),0Uc?50:800)+t);return l.unsuspend=e,function(){l.unsuspend=null,clearTimeout(u),clearTimeout(a)}}:null}function $0(l){if(l.count===0&&(l.imgCount===0||!l.waitingForImages)){if(l.stylesheets)pc(l,l.stylesheets);else if(l.unsuspend){var t=l.unsuspend;l.unsuspend=null,t()}}}function un(){this.count--,$0(this)}function Eh(){this.imgCount--,$0(this)}var jc=null;function pc(l,t){l.stylesheets=null,l.unsuspend!==null&&(l.count++,jc=new Map,t.forEach(zh,l),jc=null,un.call(l))}function zh(l,t){if(!(t.state.loading&4)){var e=jc.get(l);if(e)var u=e.get(null);else{e=new Map,jc.set(l,e);for(var a=l.querySelectorAll("link[data-precedence],style[data-precedence]"),n=0;n"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(f)}catch(E){console.error(E)}}return f(),Ro.exports=Gh(),Ro.exports}var Xh=Qh();const Vh=["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"],Zh=["none","raw","json","urlencoded","form"],Lh={none:"无",raw:"raw",json:"JSON",urlencoded:"x-www-form-urlencoded",form:"form-data"};function Kh(f){try{return JSON.parse(String(f??"")),{ok:!0,message:""}}catch(E){return{ok:!1,message:(E==null?void 0:E.message)??"JSON 解析失败"}}}function Nv(f){try{return JSON.stringify(JSON.parse(String(f??"")),null,2)}catch{return String(f??"")}}const Sv=f=>{let E;const r=new Set,o=(dl,x)=>{const N=typeof dl=="function"?dl(E):dl;if(!Object.is(N,E)){const j=E;E=x??(typeof N!="object"||N===null)?N:Object.assign({},E,N),r.forEach(vl=>vl(E,j))}},z=()=>E,tl={setState:o,getState:z,getInitialState:()=>$,subscribe:dl=>(r.add(dl),()=>r.delete(dl))},$=E=f(o,z,tl);return tl},Jh=(f=>f?Sv(f):Sv),wh=f=>f;function $h(f,E=wh){const r=Do.useSyncExternalStore(f.subscribe,Do.useCallback(()=>E(f.getState()),[f,E]),()=>E(f.getInitialState()));return Do.useDebugValue(r),r}const Tv=f=>{const E=Jh(f),r=o=>$h(E,o);return Object.assign(r,E),r},Fh=(f=>f?Tv(f):Tv);async function qo(f,E){var A;const r=await fetch(f,E),o=await r.text();let z=null;try{z=o?JSON.parse(o):null}catch{throw new Error(`本地服务返回了非 JSON 内容(HTTP ${r.status})`)}if(!r.ok){const Q=((A=z==null?void 0:z.error)==null?void 0:A.message)??`请求失败(HTTP ${r.status})`;throw new Error(Q)}return z}function Ov(){return qo("/api/state")}function Wh(f,E=!1){return qo("/api/state",{method:"PUT",headers:{"content-type":"application/json"},body:JSON.stringify(f),keepalive:E})}function kh(f){return qo("/api/send",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(f)})}function Ih(f){const E=f.indexOf("#");return E===-1?[f,""]:[f.slice(0,E),f.slice(E)]}function Ph(f){const E=String(f??"").trim();if(!E)return!1;let r;try{r=new URL(E)}catch{return!1}return r.protocol==="http:"||r.protocol==="https:"}function l1(f){const E=String(f??"").trim(),r=E.indexOf("#"),o=r===-1?E:E.slice(0,r),z=o.indexOf("?");if(z===-1)return[];const A=o.slice(z+1);if(!A)return[];const Q=[];for(const[tl,$]of new URLSearchParams(A))Q.push({key:tl,value:$,enabled:!0});return Q}function t1(f){const E=String(f??"").trim();if(!E)return"";const[r,o]=Ih(E),z=r.indexOf("?");return z===-1?E:r.slice(0,z)+o}function da(){return{method:"GET",url:"",params:[],headers:[],body:{mode:"none"}}}function po(){return"n_"+Math.random().toString(16).slice(2,10).padEnd(8,"0")}function xo(f,E){if(!E)return null;for(const r of f){if(r.id===E)return r;if(r.children){const o=xo(r.children,E);if(o)return o}}return null}function Xc(f,E,r){return f.map(o=>o.id===E?r(o):o.children?{...o,children:Xc(o.children,E,r)}:o)}function _v(f,E){return f.filter(r=>r.id!==E).map(r=>r.children?{...r,children:_v(r.children,E)}:r)}function Av(f,E,r){return E?f.map(o=>o.id===E?{...o,children:[...o.children??[],r]}:o.children?{...o,children:Av(o.children,E,r)}:o):[...f,r]}function Qc(f,E){if(!f.currentRequestId)return{draft:E};const r=Xc(f.doc.nodes,f.currentRequestId,o=>({...o,request:E}));return{draft:E,doc:{...f.doc,nodes:r}}}const V=Fh((f,E)=>({doc:{version:1,rev:0,nodes:[]},currentRequestId:null,draft:da(),response:null,error:null,sending:!1,requestTab:"params",responseTab:"body",saveStatus:"idle",saveNotice:null,followRedirects:!0,timeoutMs:3e4,renamingId:null,init:async()=>{try{const r=await Ov();f({doc:r})}catch(r){f({error:r.message})}},selectRequest:r=>f(o=>{if(!r)return{currentRequestId:null,draft:da(),response:null,error:null};const z=xo(o.doc.nodes,r);if(!z||z.type!=="request")return{};const A=z.request?structuredClone(z.request):da();return{currentRequestId:r,draft:A,response:null,error:null}}),patchDraft:r=>f(o=>Qc(o,{...o.draft,...r})),setParams:r=>f(o=>Qc(o,{...o.draft,params:r})),setHeaders:r=>f(o=>Qc(o,{...o.draft,headers:r})),setBody:r=>f(o=>{const z={...o.draft.body,...r};return r.mode&&r.mode!==o.draft.body.mode&&(r.mode==="json"&&z.json===void 0&&(z.json=""),r.mode==="raw"&&z.raw===void 0&&(z.raw=""),r.mode==="urlencoded"&&z.urlencoded===void 0&&(z.urlencoded=[]),r.mode==="form"&&z.form===void 0&&(z.form=[])),Qc(o,{...o.draft,body:z})}),addCollection:()=>f(r=>{const o={id:po(),type:"collection",name:"新建集合",collapsed:!1,children:[]};return{doc:{...r.doc,nodes:[...r.doc.nodes,o]},renamingId:o.id}}),addChild:(r,o)=>f(z=>{const A=o==="folder"?{id:po(),type:"folder",name:"新建文件夹",collapsed:!1,children:[]}:{id:po(),type:"request",name:"新建请求",request:da()},Q=Av(z.doc.nodes,r,A);return{doc:{...z.doc,nodes:Q},renamingId:A.id,currentRequestId:o==="request"?A.id:z.currentRequestId,draft:o==="request"?da():z.draft}}),renameNode:(r,o)=>f(z=>({doc:{...z.doc,nodes:Xc(z.doc.nodes,r,A=>({...A,name:o}))},renamingId:null})),deleteNode:r=>f(o=>{const z=_v(o.doc.nodes,r),A=xo(z,o.currentRequestId);return o.currentRequestId&&!A?{doc:{...o.doc,nodes:z},currentRequestId:null,draft:da()}:{doc:{...o.doc,nodes:z}}}),toggleCollapse:r=>f(o=>({doc:{...o.doc,nodes:Xc(o.doc.nodes,r,z=>({...z,collapsed:!z.collapsed}))}})),setRequestTab:r=>f({requestTab:r}),setResponseTab:r=>f({responseTab:r}),setSaveStatus:r=>f({saveStatus:r}),setSaveNotice:r=>f({saveNotice:r}),setRenamingId:r=>f({renamingId:r}),send:async()=>{const r=E();if(r.sending)return;const o=r.draft.url.trim();if(!o){f({error:"请填写 URL",response:null});return}if(!Ph(o)){f({error:"请填写以 http:// 或 https:// 开头的完整 URL",response:null});return}f({sending:!0,error:null,responseTab:"body"});try{const z=await kh({method:r.draft.method,url:t1(r.draft.url),params:r.draft.params,headers:r.draft.headers,body:r.draft.body,options:{followRedirects:r.followRedirects,timeoutMs:r.timeoutMs}});z.ok?f({response:z.response,error:null}):f({response:null,error:z.error.message})}catch(z){f({response:null,error:z.message})}finally{f({sending:!1})}}}));function xt({size:f=16,className:E,children:r}){return g.jsx("svg",{width:f,height:f,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:1.5,strokeLinecap:"round",strokeLinejoin:"round",className:E,"aria-hidden":"true",focusable:"false",children:r})}function e1(f){return g.jsx(xt,{...f,children:g.jsx("path",{d:"M6 9l6 6 6-6"})})}function u1(f){return g.jsx(xt,{...f,children:g.jsx("path",{d:"M3 7a2 2 0 0 1 2-2h3.6a2 2 0 0 1 1.6.8L12 7.5h7a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V7z"})})}function a1(f){return g.jsxs(xt,{...f,children:[g.jsx("path",{d:"M3 7a2 2 0 0 1 2-2h3.6a2 2 0 0 1 1.6.8L12 7.5h7a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V7z"}),g.jsx("path",{d:"M12 11v5M9.5 13.5h5"})]})}function n1(f){return g.jsxs(xt,{...f,children:[g.jsx("path",{d:"M14 3H7a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V8l-5-5z"}),g.jsx("path",{d:"M14 3v5h5"}),g.jsx("path",{d:"M12 12v5M9.5 14.5h5"})]})}function c1(f){return g.jsxs(xt,{...f,children:[g.jsx("path",{d:"M12 20h9"}),g.jsx("path",{d:"M16.5 3.5a2.12 2.12 0 0 1 3 3L7 19l-4 1 1-4 12.5-12.5z"})]})}function Mv(f){return g.jsxs(xt,{...f,children:[g.jsx("path",{d:"M3 6h18M8 6V4a1 1 0 0 1 1-1h6a1 1 0 0 1 1 1v2M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"}),g.jsx("path",{d:"M10 11v6M14 11v6"})]})}function i1(f){return g.jsx(xt,{...f,children:g.jsx("path",{d:"M12 5v14M5 12h14"})})}function f1(f){return g.jsx(xt,{...f,children:g.jsx("path",{d:"M22 2L11 13M22 2l-7 20-4-9-9-4 20-7z"})})}function o1(f){return g.jsxs(xt,{...f,children:[g.jsx("circle",{cx:"12",cy:"12",r:"4"}),g.jsx("path",{d:"M12 2v2M12 20v2M4.9 4.9l1.4 1.4M17.7 17.7l1.4 1.4M2 12h2M20 12h2M4.9 19.1l1.4-1.4M17.7 6.3l1.4-1.4"})]})}function s1(f){return g.jsx(xt,{...f,children:g.jsx("path",{d:"M21 12.8A9 9 0 1 1 11.2 3a7 7 0 0 0 9.8 9.8z"})})}function r1(f){return g.jsxs(xt,{...f,children:[g.jsx("rect",{x:"9",y:"9",width:"12",height:"12",rx:"2"}),g.jsx("path",{d:"M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"})]})}function Bo(f){return g.jsxs(xt,{...f,children:[g.jsx("path",{d:"M22 12h-6l-2 3h-4l-2-3H2"}),g.jsx("path",{d:"M5.5 5.1L2 12v6a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-6l-3.5-6.9A2 2 0 0 0 16.8 4H7.2a2 2 0 0 0-1.7 1.1z"})]})}function Vc({rows:f,onChange:E,keyPlaceholder:r="键",valuePlaceholder:o="值"}){const z=(A,Q)=>{E(f.map((tl,$)=>$===A?{...tl,...Q}:tl))};return g.jsxs("div",{className:"kv-table",children:[g.jsxs("table",{children:[g.jsx("thead",{children:g.jsxs("tr",{children:[g.jsx("th",{className:"kv-check"}),g.jsx("th",{children:r}),g.jsx("th",{children:o}),g.jsx("th",{className:"kv-action"})]})}),g.jsx("tbody",{children:f.map((A,Q)=>g.jsxs("tr",{className:A.enabled?"":"kv-disabled",children:[g.jsx("td",{className:"kv-check",children:g.jsx("input",{type:"checkbox",checked:A.enabled,onChange:tl=>z(Q,{enabled:tl.target.checked})})}),g.jsx("td",{children:g.jsx("input",{type:"text",value:A.key,placeholder:r,onChange:tl=>z(Q,{key:tl.target.value})})}),g.jsx("td",{children:g.jsx("input",{type:"text",value:A.value,placeholder:o,onChange:tl=>z(Q,{value:tl.target.value})})}),g.jsx("td",{className:"kv-action",children:g.jsx("button",{type:"button",title:"删除",onClick:()=>E(f.filter((tl,$)=>$!==Q)),children:g.jsx(Mv,{size:13})})})]},Q))})]}),g.jsx("button",{type:"button",className:"kv-add",onClick:()=>E([...f,{key:"",value:"",enabled:!0}]),children:"+ 添加"})]})}function d1(){const f=V(r=>r.draft.body.mode),E=V(r=>r.setBody);return g.jsxs("div",{className:"body-editor",children:[g.jsx("div",{className:"body-modes",children:Zh.map(r=>g.jsx("button",{type:"button",className:f===r?"active":"",onClick:()=>E({mode:r}),children:Lh[r]},r))}),f==="none"&&g.jsx("div",{className:"empty-hint",children:"该请求不携带请求体"}),f==="raw"&&g.jsx(v1,{}),f==="json"&&g.jsx(m1,{}),f==="urlencoded"&&g.jsx(y1,{}),f==="form"&&g.jsx(h1,{})]})}function v1(){const f=V(r=>r.draft.body.raw??""),E=V(r=>r.setBody);return g.jsx("textarea",{className:"body-textarea",value:f,placeholder:"输入原始请求体;Content-Type 需要在 Headers 里自行指定",onChange:r=>E({raw:r.target.value})})}function m1(){const f=V(o=>o.draft.body.json??""),E=V(o=>o.setBody),r=Kh(f);return g.jsxs("div",{className:"json-editor",children:[g.jsxs("div",{className:"json-toolbar",children:[g.jsx("button",{type:"button",onClick:()=>E({json:Nv(f)}),children:"格式化"}),!r.ok&&g.jsxs("span",{className:"json-error",children:["JSON 解析失败:",r.message]})]}),g.jsx("textarea",{className:"body-textarea",value:f,placeholder:'{"key": "value"}',onChange:o=>E({json:o.target.value})})]})}function y1(){const f=V(r=>r.draft.body.urlencoded??[]),E=V(r=>r.setBody);return g.jsx(Vc,{rows:f,onChange:r=>E({urlencoded:r}),keyPlaceholder:"字段名",valuePlaceholder:"字段值"})}function h1(){const f=V(r=>r.draft.body.form??[]),E=V(r=>r.setBody);return g.jsx(Vc,{rows:f,onChange:r=>E({form:r}),keyPlaceholder:"字段名",valuePlaceholder:"字段值"})}function g1(f){return/^image\//i.test(f??"")}function S1(f,E){const r=atob(f),o=new Uint8Array(r.length);for(let z=0;z=500?"status-5xx":f>=400?"status-4xx":f>=300?"status-3xx":f>=200?"status-2xx":"status-1xx"}function z1({tab:f}){const E=V(r=>r.response);return E?f==="headers"?g.jsx(N1,{response:E}):f==="preview"?g.jsx(O1,{response:E}):g.jsx(_1,{response:E}):g.jsxs("div",{className:"empty-state",children:[g.jsx("div",{className:"empty-state-icon",children:g.jsx(Bo,{size:20})}),g.jsx("div",{className:"empty-state-title",children:"还没有响应"}),g.jsx("div",{className:"empty-state-hint",children:"填好地址后点右上角「发送」,或按 Enter"})]})}function N1({response:f}){const E=Object.entries(f.headers);return E.length===0?g.jsx("div",{className:"empty-hint",children:"响应没有头信息"}):g.jsx("table",{className:"header-table",children:g.jsx("tbody",{children:E.map(([r,o])=>g.jsxs("tr",{children:[g.jsx("td",{className:"header-key",children:r}),g.jsx("td",{children:o})]},r))})})}function O1({response:f}){return(f.contentType||f.headers["content-type"]||"").includes("html")?g.jsx("iframe",{className:"preview-frame",title:"响应预览",sandbox:"allow-scripts",srcDoc:f.body??""}):g.jsx("div",{className:"empty-hint",children:"该响应不是 HTML,无法预览"})}function _1({response:f}){const E=Ol.useMemo(()=>!f.bodyBase64||!g1(f.contentType)?null:URL.createObjectURL(S1(f.bodyBase64,f.contentType)),[f]);if(Ol.useEffect(()=>()=>{E&&URL.revokeObjectURL(E)},[E]),f.bodyBase64){if(E)return g.jsx("img",{className:"response-image",src:E,alt:"响应图片"});const z=f.contentType||f.headers["content-type"]||"未知类型",A=T1(f.bodyBase64,f.contentType);return g.jsxs("div",{className:"binary-box",children:[g.jsxs("div",{children:["二进制响应(",z,",",Dv(f.size),")"]}),g.jsxs("a",{className:"btn",href:A,download:"response.bin",children:[g.jsx(r1,{size:13}),"下载"]})]})}const o=(f.contentType||f.headers["content-type"]||"").includes("json")?Nv(f.body??""):f.body??"";return g.jsx("pre",{className:"response-text",children:o})}const A1=[{id:"body",label:"Body"},{id:"headers",label:"Headers"},{id:"preview",label:"Preview"}];function M1(){const f=V(A=>A.response),E=V(A=>A.error),r=V(A=>A.sending),o=V(A=>A.responseTab),z=V(A=>A.setResponseTab);return g.jsxs("section",{className:"response-panel",children:[g.jsxs("div",{className:"response-summary",children:[r&&g.jsxs("span",{className:"response-status is-loading",children:[g.jsx("span",{className:"spinner"}),"发送中…"]}),f&&g.jsxs(g.Fragment,{children:[g.jsxs("span",{className:`response-status ${E1(f.status)}`,children:[f.status," ",f.statusText]}),g.jsx("span",{className:"response-meta",children:b1(f.timeMs)}),g.jsx("span",{className:"response-meta",children:Dv(f.size)}),f.truncated&&g.jsx("span",{className:"response-meta warn",children:"响应过大已截断"})]})]}),E?g.jsxs("div",{className:"response-error",children:[g.jsxs("div",{className:"response-error-title",children:[g.jsx(Bo,{size:14}),"请求失败"]}),g.jsx("div",{className:"response-error-message",children:E})]}):g.jsxs(g.Fragment,{children:[g.jsx("div",{className:"tabs",children:A1.map(A=>g.jsx("button",{type:"button",className:o===A.id?"active":"",onClick:()=>z(A.id),children:A.label},A.id))}),g.jsx("div",{className:"response-body",children:g.jsx(z1,{tab:o})})]})]})}function Rv({nodes:f,depth:E}){return g.jsx("ul",{className:"tree",children:f.map(r=>g.jsx(D1,{node:r,depth:E},r.id))})}function D1({node:f,depth:E}){var F,el;const r=V(q=>q.currentRequestId),o=V(q=>q.renamingId),z=V(q=>q.setRenamingId),A=V(q=>q.renameNode),Q=V(q=>q.deleteNode),tl=V(q=>q.toggleCollapse),$=V(q=>q.addChild),dl=V(q=>q.selectRequest),[x,N]=Ol.useState(f.name),j=Ol.useRef(null),vl=o===f.id,Fl=Ol.useRef(!1),Hl=Ol.useRef(0),ol=Ol.useCallback(()=>{A(f.id,x.trim()||f.name)},[f.id,x,A]);Ol.useEffect(()=>{var q;Fl.current=vl,Hl.current=0,vl&&((q=j.current)==null||q.focus())},[vl]),Ol.useEffect(()=>{if(!vl)return;const q=at=>{const Pl=j.current;Pl&&!Pl.contains(at.target)&&ol()};return document.addEventListener("mousedown",q),()=>document.removeEventListener("mousedown",q)},[vl,ol]);const Dl=f.type==="request",kl=Dl&&f.id===r,Ht=f.collapsed===!0,rt=()=>{N(f.name),z(f.id)},Ot=()=>{var q;Fl.current&&(Hl.current>=3||(Hl.current+=1,(q=j.current)==null||q.focus()))},Il=()=>{z(null)};return g.jsxs("li",{className:`tree-node tree-${f.type}`,children:[g.jsxs("div",{className:`tree-row ${kl?"active":""}`,style:{paddingLeft:8+E*14},onClick:()=>{Dl&&dl(f.id)},children:[!Dl&&g.jsx("button",{type:"button",className:`tree-caret ${Ht?"is-collapsed":""}`,title:Ht?"展开":"折叠",onMouseDown:q=>q.preventDefault(),onClick:q=>{q.stopPropagation(),tl(f.id)},children:g.jsx(e1,{size:14})}),!Dl&&g.jsx(u1,{size:15,className:"icon tree-folder"}),Dl&&g.jsx("span",{className:`method-badge method-${((F=f.request)==null?void 0:F.method)??"GET"}`,children:((el=f.request)==null?void 0:el.method)??"GET"}),vl?g.jsx("input",{ref:j,className:"tree-rename",value:x,onMouseDown:q=>q.stopPropagation(),onChange:q=>N(q.target.value),onBlur:Ot,onKeyDown:q=>{q.key==="Enter"&&ol(),q.key==="Escape"&&Il()}}):g.jsx("span",{className:"tree-name",onDoubleClick:rt,children:f.name}),g.jsxs("span",{className:"tree-actions",onClick:q=>q.stopPropagation(),children:[!Dl&&g.jsx("button",{type:"button",title:"新建文件夹",onMouseDown:q=>q.preventDefault(),onClick:()=>$(f.id,"folder"),children:g.jsx(a1,{size:14})}),!Dl&&g.jsx("button",{type:"button",title:"新建请求",onMouseDown:q=>q.preventDefault(),onClick:()=>$(f.id,"request"),children:g.jsx(n1,{size:14})}),g.jsx("button",{type:"button",title:"重命名",onMouseDown:q=>q.preventDefault(),onClick:rt,children:g.jsx(c1,{size:13})}),g.jsx("button",{type:"button",className:"danger",title:"删除",onMouseDown:q=>q.preventDefault(),onClick:()=>{window.confirm(`删除「${f.name}」?`)&&Q(f.id)},children:g.jsx(Mv,{size:13})})]})]}),!Dl&&!Ht&&f.children&&f.children.length>0&&g.jsx(Rv,{nodes:f.children,depth:E+1})]})}const Cv="pm-lite:theme";function R1(f){return f==="auto"||f==="light"||f==="dark"}function bv(){try{const f=window.localStorage.getItem(Cv);return R1(f)?f:"auto"}catch{return"auto"}}function C1(){return window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}function Uv(f){return f==="auto"?C1():f}let Ev=0;function U1(f){const E=Uv(f),r=document.documentElement;r.classList.add("theme-switching"),r.dataset.theme=E,r.offsetHeight;const o=++Ev,z=()=>{o===Ev&&r.classList.remove("theme-switching")};return requestAnimationFrame(z),window.setTimeout(z,120),E}function j1(){const[f,E]=Ol.useState(()=>bv()),[r,o]=Ol.useState(()=>Uv(bv()));Ol.useEffect(()=>{const Q=window.matchMedia("(prefers-color-scheme: dark)"),tl=()=>o(U1(f));if(tl(),f==="auto")return Q.addEventListener("change",tl),()=>Q.removeEventListener("change",tl)},[f]);const z=Ol.useCallback(Q=>{try{window.localStorage.setItem(Cv,Q)}catch{}E(Q)},[]),A=Ol.useCallback(()=>{z(r==="dark"?"light":"dark")},[r,z]);return{choice:f,resolved:r,setChoice:z,toggle:A}}function p1(){const f=V(z=>z.doc.nodes),E=V(z=>z.addCollection),{resolved:r,toggle:o}=j1();return g.jsxs("aside",{className:"sidebar",children:[g.jsxs("div",{className:"sidebar-head",children:[g.jsx("span",{className:"brand",children:"Postman Lite"}),g.jsx("button",{type:"button",className:"theme-toggle",title:r==="dark"?"切换到浅色主题":"切换到深色主题",onClick:o,children:r==="dark"?g.jsx(o1,{size:15}):g.jsx(s1,{size:15})})]}),g.jsx("div",{className:"sidebar-actions",children:g.jsxs("button",{type:"button",onMouseDown:z=>z.preventDefault(),onClick:E,children:[g.jsx(i1,{size:14}),"新建集合"]})}),g.jsx("div",{className:"tree-scroll",children:f.length===0?g.jsxs("div",{className:"empty-state",children:[g.jsx("div",{className:"empty-state-icon",children:g.jsx(Bo,{size:20})}),g.jsx("div",{className:"empty-state-title",children:"还没有集合"}),g.jsx("div",{className:"empty-state-hint",children:"点上面的「新建集合」开始"})]}):g.jsx(Rv,{nodes:f,depth:0})})]})}const zv="pm-lite:split-ratio";function x1({top:f,bottom:E,initialRatio:r=.45}){const o=Ol.useRef(null),z=Ol.useRef(!1),A=Ol.useRef(r),[Q,tl]=Ol.useState(()=>{const $=Number(window.localStorage.getItem(zv));return Number.isFinite($)&&$>.1&&$<.9?$:r});return Ol.useEffect(()=>{A.current=Q},[Q]),Ol.useEffect(()=>{const $=x=>{if(!z.current)return;const N=o.current;if(!N)return;const j=N.getBoundingClientRect();if(j.height===0)return;const vl=(x.clientY-j.top)/j.height;tl(Math.min(.85,Math.max(.15,vl)))},dl=()=>{z.current&&(z.current=!1,window.localStorage.setItem(zv,String(A.current)))};return window.addEventListener("mousemove",$),window.addEventListener("mouseup",dl),()=>{window.removeEventListener("mousemove",$),window.removeEventListener("mouseup",dl)}},[]),g.jsxs("div",{className:"split",ref:o,children:[g.jsx("div",{className:"split-top",style:{height:`${Q*100}%`},children:f}),g.jsx("div",{className:"split-handle",title:"拖动调整上下比例",onMouseDown:$=>{$.preventDefault(),z.current=!0}}),g.jsx("div",{className:"split-bottom",children:E})]})}const H1=[{value:1e4,label:"10 秒"},{value:3e4,label:"30 秒"},{value:6e4,label:"60 秒"},{value:12e4,label:"120 秒"}],q1={idle:"",saving:"保存中…",saved:"已保存",error:"保存失败"};function B1(){const f=V(A=>A.followRedirects),E=V(A=>A.timeoutMs),r=V(A=>A.saveStatus),o=V(A=>A.saveNotice),z=V.setState;return g.jsxs("div",{className:"toolbar",children:[g.jsxs("label",{className:"option",children:[g.jsx("input",{type:"checkbox",checked:f,onChange:A=>z({followRedirects:A.target.checked})}),"跟随跳转"]}),g.jsxs("label",{className:"option",children:["超时",g.jsx("select",{value:E,onChange:A=>z({timeoutMs:Number(A.target.value)}),children:H1.map(A=>g.jsx("option",{value:A.value,children:A.label},A.value))})]}),g.jsx("span",{className:`save-status save-${r}`,children:o||q1[r]})]})}function Y1(){const f=V(A=>A.draft),E=V(A=>A.sending),r=V(A=>A.patchDraft),o=V(A=>A.send),z=A=>{const Q=l1(A);if(Q.length>0){r({url:A,params:Q});return}r({url:A})};return g.jsxs("div",{className:"urlbar",children:[g.jsx("select",{className:"method-select",value:f.method,onChange:A=>r({method:A.target.value}),children:Vh.map(A=>g.jsx("option",{value:A,children:A},A))}),g.jsx("input",{className:"url-input",value:f.url,placeholder:"输入请求地址,例如 https://httpbin.org/get",onChange:A=>z(A.target.value),onKeyDown:A=>{A.key==="Enter"&&o()}}),g.jsxs("button",{type:"button",className:"send-btn",disabled:E,onClick:()=>void o(),children:[g.jsx(f1,{size:14}),E?"发送中…":"发送"]})]})}const G1=600;let jv=!1,bu=null;function Q1(){jv=!0}async function pv(f={}){const E=V.getState();if(!(E.saveStatus==="saving"&&!f.force)){V.setState({saveStatus:"saving"});try{const r=await Wh(E.doc,f.keepalive===!0);if(r!=null&&r.stale){const o=await Ov();V.setState({doc:o,saveStatus:"error",saveNotice:"检测到另一个页面也在修改集合,已重新载入最新数据"});return}r!=null&&r.ok?V.setState(o=>({doc:{...o.doc,rev:r.rev},saveStatus:"saved",saveNotice:null})):V.setState({saveStatus:"error",saveNotice:"保存失败"})}catch{V.setState({saveStatus:"error",saveNotice:"保存失败"})}}}function X1(){V.subscribe((f,E)=>{jv&&f.doc.nodes!==E.doc.nodes&&(bu&&clearTimeout(bu),bu=setTimeout(()=>{bu=null,pv()},G1))})}function V1(){const f=()=>{bu&&(clearTimeout(bu),bu=null),pv({keepalive:!0,force:!0})};window.addEventListener("beforeunload",f),document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&f()})}const Z1=[{id:"params",label:"Params"},{id:"headers",label:"Headers"},{id:"body",label:"Body"}];function L1(){const f=Ol.useRef(!1),E=V(z=>z.requestTab),r=V(z=>z.setRequestTab),o=V(z=>z.draft);return Ol.useEffect(()=>{f.current||(f.current=!0,X1(),V1(),V.getState().init().then(()=>Q1()))},[]),g.jsxs("div",{className:"app",children:[g.jsx(p1,{}),g.jsxs("main",{className:"main",children:[g.jsx(Y1,{}),g.jsx(B1,{}),g.jsx(x1,{top:g.jsxs("div",{className:"pane-request",children:[g.jsx("div",{className:"tabs",children:Z1.map(z=>g.jsx("button",{type:"button",className:E===z.id?"active":"",onClick:()=>r(z.id),children:z.label},z.id))}),g.jsxs("div",{className:"request-content",children:[E==="params"&&g.jsx(Vc,{rows:o.params,onChange:z=>V.getState().setParams(z),keyPlaceholder:"参数名",valuePlaceholder:"参数值"}),E==="headers"&&g.jsx(Vc,{rows:o.headers,onChange:z=>V.getState().setHeaders(z),keyPlaceholder:"请求头",valuePlaceholder:"值"}),E==="body"&&g.jsx(d1,{})]})]}),bottom:g.jsx(M1,{})})]})]})}const xv=document.getElementById("root");if(!xv)throw new Error("找不到 #root 挂载点");Xh.createRoot(xv).render(g.jsx(Ol.StrictMode,{children:g.jsx(L1,{})})); diff --git a/plugins/ssugarr/postman-lite/miniapp/client/assets/index-CvdCbz-Y.css b/plugins/ssugarr/postman-lite/miniapp/client/assets/index-CvdCbz-Y.css new file mode 100644 index 00000000..3f2a1a60 --- /dev/null +++ b/plugins/ssugarr/postman-lite/miniapp/client/assets/index-CvdCbz-Y.css @@ -0,0 +1 @@ +:root{color-scheme:light;--bg: #ffffff;--bg-sub: #f7f8fa;--bg-elevated: #ffffff;--bg-inset: #fafbfc;--bg-hover: #eef0f3;--bg-active: #e5e9ef;--border: #e6e8ec;--border-strong: #d4d9df;--text: #1c2430;--text-secondary: #4c5764;--text-muted: #8a94a2;--text-inverse: #ffffff;--brand: #ff6c37;--brand-soft: #fff2ec;--send: #49cc90;--send-hover: #3cb87e;--send-text: #ffffff;--primary: #2f6fed;--primary-soft: #eaf1fe;--danger: #d64545;--danger-soft: #fdeeee;--danger-text: #8f2727;--warn: #bd7a12;--status-1xx: #8a94a2;--status-2xx: #2f9e6b;--status-3xx: #2f6fed;--status-4xx: #bd7a12;--status-5xx: #d64545;--method-get: #3b82f6;--method-post: #2f9e6b;--method-put: #d98324;--method-patch: #7c6cf0;--method-delete: #d64545;--method-head: #6b7785;--method-options: #2f9e8f;--shadow-xs: 0 1px 2px rgba(16, 24, 40, .05);--shadow-sm: 0 1px 3px rgba(16, 24, 40, .07), 0 1px 2px rgba(16, 24, 40, .04);--shadow-md: 0 8px 20px rgba(16, 24, 40, .1), 0 2px 6px rgba(16, 24, 40, .04);--shadow-focus: 0 0 0 3px rgba(47, 111, 237, .15);--radius-sm: 4px;--radius: 6px;--radius-lg: 10px;--sidebar-w: 264px;--ease: cubic-bezier(.32, .72, 0, 1);--dur-fast: .11s;--dur: .16s;--dur-slow: .26s;--font: -apple-system, BlinkMacSystemFont, "Segoe UI", "Microsoft YaHei UI", "Microsoft YaHei", Roboto, Helvetica, Arial, sans-serif;--mono: "SFMono-Regular", Consolas, "Liberation Mono", Menlo, "Cascadia Mono", monospace}:root[data-theme=dark]{color-scheme:dark;--bg: #15171c;--bg-sub: #1a1d23;--bg-elevated: #1e222a;--bg-inset: #191c21;--bg-hover: #242932;--bg-active: #2b313a;--border: #262b33;--border-strong: #363d47;--text: #e4e8ee;--text-secondary: #b0bac7;--text-muted: #7b8593;--text-inverse: #15171c;--brand: #ff8251;--brand-soft: #2a1a13;--send: #3fbb85;--send-hover: #35a274;--send-text: #0c1a14;--primary: #5b8def;--primary-soft: #1a2334;--danger: #e56a6a;--danger-soft: #2a1a1c;--danger-text: #f0a3a3;--warn: #dda049;--status-1xx: #7b8593;--status-2xx: #4ec98d;--status-3xx: #6aa2f5;--status-4xx: #dda049;--status-5xx: #e56a6a;--method-get: #4d8dfd;--method-post: #3fbb85;--method-put: #d98324;--method-patch: #8b7cf5;--method-delete: #e56a6a;--method-head: #6b7785;--method-options: #3fbb9b;--shadow-xs: 0 1px 2px rgba(0, 0, 0, .4);--shadow-sm: 0 1px 3px rgba(0, 0, 0, .5);--shadow-md: 0 10px 26px rgba(0, 0, 0, .55);--shadow-focus: 0 0 0 3px rgba(91, 141, 239, .28)}*{box-sizing:border-box}*{scrollbar-width:thin;scrollbar-color:var(--border-strong) transparent}::-webkit-scrollbar{width:10px;height:10px}::-webkit-scrollbar-track{background:transparent}::-webkit-scrollbar-thumb{border:3px solid transparent;border-radius:5px;background:var(--border-strong);background-clip:content-box}::-webkit-scrollbar-thumb:hover{background:var(--text-muted);background-clip:content-box}html,body,#root{height:100%;margin:0}body{font-family:var(--font);font-size:14px;line-height:1.5;color:var(--text);background:var(--bg);-webkit-font-smoothing:antialiased;text-rendering:optimizeLegibility}button{font-family:inherit;font-size:inherit;color:inherit;cursor:pointer}input,select,textarea{font-family:inherit;font-size:inherit;color:var(--text)}.icon{display:block;flex:0 0 auto}.app{display:flex;height:100%;overflow:hidden}.main{flex:1;display:flex;flex-direction:column;min-width:0;background:var(--bg)}.sidebar{width:var(--sidebar-w);flex:0 0 var(--sidebar-w);display:flex;flex-direction:column;border-right:1px solid var(--border);background:var(--bg-sub)}.sidebar-head{height:52px;display:flex;align-items:center;justify-content:space-between;gap:8px;padding:0 10px 0 16px;border-bottom:1px solid var(--border)}.brand{font-weight:700;font-size:14px;color:var(--brand);letter-spacing:.2px}.theme-toggle{width:30px;height:30px;display:grid;place-items:center;border:1px solid transparent;border-radius:var(--radius-sm);background:transparent;color:var(--text-muted);transition:background var(--dur-fast) var(--ease),color var(--dur-fast) var(--ease),border-color var(--dur-fast) var(--ease)}.theme-toggle:hover{background:var(--bg-hover);border-color:var(--border);color:var(--text)}.sidebar-actions{padding:12px;border-bottom:1px solid var(--border)}.sidebar-actions button{width:100%;height:32px;display:inline-flex;align-items:center;justify-content:center;gap:6px;border:1px dashed var(--border-strong);border-radius:var(--radius);background:transparent;color:var(--text-secondary);font-size:13px;transition:background var(--dur-fast) var(--ease),border-color var(--dur-fast) var(--ease),color var(--dur-fast) var(--ease)}.sidebar-actions button:hover{background:var(--brand-soft);border-color:var(--brand);color:var(--brand)}.tree-scroll{flex:1;overflow:auto;padding:8px 8px 20px}.tree{list-style:none;margin:0;padding:0}.tree-row{display:flex;align-items:center;gap:6px;height:30px;padding-right:6px;border-radius:var(--radius-sm);cursor:pointer;-webkit-user-select:none;user-select:none;transition:background var(--dur-fast) var(--ease),color var(--dur-fast) var(--ease)}.tree-row:hover{background:var(--bg-hover)}.tree-row.active{background:var(--primary-soft);color:var(--primary)}.tree-caret{width:18px;height:18px;padding:0;display:grid;place-items:center;border:none;background:transparent;color:var(--text-muted);transition:color var(--dur-fast) var(--ease)}.tree-caret:hover{color:var(--text)}.tree-caret svg{transition:transform var(--dur) var(--ease)}.tree-caret.is-collapsed svg{transform:rotate(-90deg)}.tree-folder{color:var(--text-muted);transition:color var(--dur-fast) var(--ease)}.tree-row:hover .tree-folder{color:var(--text-secondary)}.tree-name{flex:1;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-size:13px}.tree-rename{flex:1;min-width:0;height:22px;padding:0 6px;border:1px solid var(--primary);border-radius:var(--radius-sm);background:var(--bg);box-shadow:var(--shadow-focus);outline:none}.tree-actions{display:none;gap:2px}.tree-row:hover .tree-actions,.tree-row:focus-within .tree-actions{display:flex}.tree-actions button{width:22px;height:22px;padding:0;display:grid;place-items:center;border:none;background:transparent;color:var(--text-muted);border-radius:var(--radius-sm);transition:background var(--dur-fast) var(--ease),color var(--dur-fast) var(--ease)}.tree-actions button:hover{background:var(--bg-active);color:var(--text)}.tree-actions button.danger:hover{background:var(--danger-soft);color:var(--danger)}.method-badge{min-width:42px;padding:2px 5px;border-radius:var(--radius-sm);font-family:var(--mono);font-size:10px;font-weight:700;letter-spacing:.03em;text-align:center;color:#fff;background:#8a94a2}.method-GET{background:var(--method-get)}.method-POST{background:var(--method-post)}.method-PUT{background:var(--method-put)}.method-PATCH{background:var(--method-patch)}.method-DELETE{background:var(--method-delete)}.method-HEAD{background:var(--method-head)}.method-OPTIONS{background:var(--method-options)}.urlbar{display:flex;align-items:center;gap:8px;padding:14px 16px 10px}.method-select{height:34px;padding:0 10px;border:1px solid var(--border-strong);border-radius:var(--radius);background:var(--bg);font-weight:600;font-size:13px;cursor:pointer;transition:border-color var(--dur-fast) var(--ease),box-shadow var(--dur-fast) var(--ease)}.method-select:hover{border-color:var(--text-muted)}.method-select:focus{outline:none;border-color:var(--primary);box-shadow:var(--shadow-focus)}.url-input{flex:1;min-width:0;height:34px;padding:0 12px;border:1px solid var(--border-strong);border-radius:var(--radius);background:var(--bg);transition:border-color var(--dur-fast) var(--ease),box-shadow var(--dur-fast) var(--ease)}.url-input::placeholder{color:var(--text-muted)}.url-input:hover{border-color:var(--text-muted)}.url-input:focus{outline:none;border-color:var(--primary);box-shadow:var(--shadow-focus)}.send-btn{height:34px;padding:0 18px;display:inline-flex;align-items:center;gap:7px;border:none;border-radius:var(--radius);background:var(--send);color:var(--send-text);font-weight:600;box-shadow:var(--shadow-xs);transition:background var(--dur-fast) var(--ease),box-shadow var(--dur-fast) var(--ease),transform var(--dur-fast) var(--ease)}.send-btn:hover:not(:disabled){background:var(--send-hover);box-shadow:var(--shadow-sm)}.send-btn:active:not(:disabled){transform:translateY(1px);box-shadow:none}.send-btn:disabled{opacity:.55;cursor:not-allowed}.toolbar{display:flex;align-items:center;gap:18px;padding:0 16px 12px;font-size:12px;color:var(--text-muted)}.option{display:inline-flex;align-items:center;gap:6px;cursor:pointer;transition:color var(--dur-fast) var(--ease)}.option:hover{color:var(--text-secondary)}.option select{height:26px;padding:0 6px;border:1px solid var(--border-strong);border-radius:var(--radius-sm);background:var(--bg);color:var(--text-secondary);cursor:pointer;transition:border-color var(--dur-fast) var(--ease)}.option select:hover{border-color:var(--text-muted)}.save-status{margin-left:auto;transition:color var(--dur-fast) var(--ease)}.save-saved{color:var(--status-2xx)}.save-saving{color:var(--text-muted)}.save-error{color:var(--danger)}.tabs{display:flex;gap:2px;padding:0 16px;border-bottom:1px solid var(--border)}.tabs button{position:relative;padding:9px 12px;border:none;background:transparent;color:var(--text-muted);font-size:13px;transition:color var(--dur-fast) var(--ease)}.tabs button:after{content:"";position:absolute;left:10px;right:10px;bottom:-1px;height:2px;border-radius:2px 2px 0 0;background:var(--primary);transform:scaleX(0);transition:transform var(--dur) var(--ease)}.tabs button:hover{color:var(--text)}.tabs button.active{color:var(--primary);font-weight:600}.tabs button.active:after{transform:scaleX(1)}.split{flex:1;display:flex;flex-direction:column;min-height:0}.split-top{overflow:auto}.split-bottom{flex:1;overflow:auto;min-height:0}.split-handle{height:10px;flex:0 0 auto;display:grid;place-items:center;cursor:row-resize;background:var(--bg-sub);border-top:1px solid var(--border);border-bottom:1px solid var(--border);transition:background var(--dur-fast) var(--ease)}.split-handle:before{content:"";width:36px;height:3px;border-radius:2px;background:var(--border-strong);opacity:.55;transition:opacity var(--dur-fast) var(--ease),background var(--dur-fast) var(--ease)}.split-handle:hover{background:var(--bg-hover)}.split-handle:hover:before{opacity:1;background:var(--text-muted)}.pane-request{display:flex;flex-direction:column;height:100%}.request-content{flex:1;overflow:auto;min-height:0}.kv-table{padding:4px 16px 16px}.kv-table table{width:100%;border-collapse:separate;border-spacing:0}.kv-table thead th{position:sticky;top:0;z-index:1;padding:7px 8px;text-align:left;font-size:11px;font-weight:500;letter-spacing:.04em;color:var(--text-muted);background:var(--bg);border-bottom:1px solid var(--border)}.kv-table tbody tr{transition:background var(--dur-fast) var(--ease)}.kv-table tbody tr:hover{background:var(--bg-hover)}.kv-table td{padding:0;border-bottom:1px solid var(--border)}.kv-table td input{width:100%;height:30px;padding:0 8px;border:1px solid transparent;border-radius:0;background:transparent;transition:background var(--dur-fast) var(--ease),border-color var(--dur-fast) var(--ease),box-shadow var(--dur-fast) var(--ease)}.kv-table td input::placeholder{color:var(--text-muted)}.kv-table td input:hover{background:var(--bg-inset)}.kv-table td input:focus{outline:none;background:var(--bg);border-color:var(--primary);box-shadow:var(--shadow-focus)}.kv-check{width:32px;text-align:center}.kv-action{width:34px;text-align:right}.kv-action button{width:22px;height:22px;display:grid;place-items:center;border:none;background:transparent;color:var(--text-muted);border-radius:var(--radius-sm);opacity:0;transition:opacity var(--dur-fast) var(--ease),background var(--dur-fast) var(--ease),color var(--dur-fast) var(--ease)}.kv-table tbody tr:hover .kv-action button{opacity:1}.kv-action button:hover{background:var(--danger-soft);color:var(--danger)}.kv-disabled{opacity:.45}.kv-add{margin-top:10px;padding:5px 12px;border:1px dashed var(--border-strong);border-radius:var(--radius);background:transparent;color:var(--text-muted);font-size:12px;transition:border-color var(--dur-fast) var(--ease),color var(--dur-fast) var(--ease),background var(--dur-fast) var(--ease)}.kv-add:hover{border-color:var(--primary);color:var(--primary);background:var(--primary-soft)}.body-editor{padding:12px 16px 16px}.body-modes{display:flex;gap:6px;margin-bottom:12px;flex-wrap:wrap}.body-modes button{padding:4px 12px;border:1px solid var(--border-strong);border-radius:999px;background:var(--bg);color:var(--text-muted);font-size:12px;transition:border-color var(--dur-fast) var(--ease),color var(--dur-fast) var(--ease),background var(--dur-fast) var(--ease)}.body-modes button:hover{border-color:var(--text-muted);color:var(--text-secondary)}.body-modes button.active{border-color:var(--primary);background:var(--primary-soft);color:var(--primary);font-weight:600}.body-textarea{width:100%;min-height:200px;padding:10px 12px;resize:vertical;border:1px solid var(--border-strong);border-radius:var(--radius);background:var(--bg-inset);font-family:var(--mono);font-size:12.5px;line-height:1.65;transition:border-color var(--dur-fast) var(--ease),box-shadow var(--dur-fast) var(--ease),background var(--dur-fast) var(--ease)}.body-textarea:hover{border-color:var(--text-muted)}.body-textarea:focus{outline:none;background:var(--bg);border-color:var(--primary);box-shadow:var(--shadow-focus)}.json-toolbar{display:flex;align-items:center;gap:12px;margin-bottom:8px}.json-toolbar button{padding:4px 12px;border:1px solid var(--border-strong);border-radius:var(--radius-sm);background:var(--bg);color:var(--text-secondary);font-size:12px;transition:border-color var(--dur-fast) var(--ease),color var(--dur-fast) var(--ease)}.json-toolbar button:hover{border-color:var(--primary);color:var(--primary)}.json-error{color:var(--danger);font-size:12px}.response-panel{display:flex;flex-direction:column;height:100%;min-height:0}:root.theme-switching *{transition:none!important}.response-summary{position:relative;z-index:1;display:flex;align-items:center;gap:14px;min-height:40px;padding:8px 16px;border-bottom:1px solid var(--border);background:var(--bg);box-shadow:var(--shadow-xs);font-size:12px}.response-status{font-family:var(--mono);font-weight:700;font-variant-numeric:tabular-nums}.status-1xx{color:var(--status-1xx)}.status-2xx{color:var(--status-2xx)}.status-3xx{color:var(--status-3xx)}.status-4xx{color:var(--status-4xx)}.status-5xx{color:var(--status-5xx)}.response-meta{color:var(--text-muted);font-family:var(--mono);font-variant-numeric:tabular-nums}.response-meta.warn{color:var(--warn)}.response-body{flex:1;overflow:auto;min-height:0}.response-text{margin:0;padding:14px 16px;font-family:var(--mono);font-size:12.5px;line-height:1.65;white-space:pre-wrap;word-break:break-word;color:var(--text-secondary)}.header-table{width:100%;border-collapse:separate;border-spacing:0}.header-table tr{transition:background var(--dur-fast) var(--ease)}.header-table tr:hover{background:var(--bg-hover)}.header-table td{padding:6px 16px;border-bottom:1px solid var(--border);vertical-align:top;font-family:var(--mono);font-size:12px}.header-key{width:240px;color:var(--text-muted);word-break:break-all}.preview-frame{width:100%;height:100%;min-height:280px;border:0;background:#fff}.response-image{display:block;max-width:100%;margin:16px auto;border-radius:var(--radius);box-shadow:var(--shadow-md)}.binary-box{padding:28px;text-align:center;color:var(--text-muted)}.binary-box .btn{display:inline-flex;align-items:center;gap:6px;margin-top:12px;padding:6px 16px;border:1px solid var(--border-strong);border-radius:var(--radius);background:var(--bg);color:var(--text-secondary);font-size:12px;text-decoration:none;transition:border-color var(--dur-fast) var(--ease),color var(--dur-fast) var(--ease)}.binary-box .btn:hover{border-color:var(--primary);color:var(--primary)}.response-error{padding:20px 16px}.response-error-title{display:flex;align-items:center;gap:6px;color:var(--danger);font-weight:600;margin-bottom:8px}.spinner{display:inline-block;width:12px;height:12px;border-radius:50%;border:1.5px solid var(--border-strong);border-top-color:var(--primary);animation:pm-spin .7s linear infinite}@keyframes pm-spin{to{transform:rotate(360deg)}}.response-status.is-loading{display:inline-flex;align-items:center;gap:7px;color:var(--text-muted);font-family:var(--font);font-weight:500}.response-error-message{padding:12px 14px;border-radius:var(--radius);background:var(--danger-soft);border:1px solid var(--danger);color:var(--danger-text);font-size:13px}.empty-state{display:flex;flex-direction:column;align-items:center;justify-content:center;gap:10px;padding:64px 24px;text-align:center;color:var(--text-muted)}.empty-state-icon{width:46px;height:46px;display:grid;place-items:center;border-radius:var(--radius-lg);background:var(--bg-hover);color:var(--text-muted);margin-bottom:2px}.empty-state-title{color:var(--text-secondary);font-size:13px}.empty-state-hint{font-size:12px;opacity:.75}.empty-hint{padding:20px 16px;color:var(--text-muted);font-size:13px} diff --git a/plugins/ssugarr/postman-lite/miniapp/client/index.html b/plugins/ssugarr/postman-lite/miniapp/client/index.html new file mode 100644 index 00000000..f0fc665c --- /dev/null +++ b/plugins/ssugarr/postman-lite/miniapp/client/index.html @@ -0,0 +1,27 @@ + + + + + + Postman Lite + + + + + +
+ + diff --git a/plugins/ssugarr/postman-lite/miniapp/miniapp.json b/plugins/ssugarr/postman-lite/miniapp/miniapp.json new file mode 100644 index 00000000..8068e0dd --- /dev/null +++ b/plugins/ssugarr/postman-lite/miniapp/miniapp.json @@ -0,0 +1,27 @@ +{ + "schemaVersion": 1, + "artifacts": { + "client": [ + "./miniapp/client" + ], + "node": [ + "./miniapp/node" + ] + }, + "runtime": { + "kind": "process", + "entry": "./miniapp/node/server.mjs", + "lifecycle": "on-demand" + }, + "surface": { + "path": "/", + "window": { + "width": 1280, + "height": 820, + "minWidth": 640, + "minHeight": 480, + "resizable": true + } + }, + "mcpEndpoints": [] +} diff --git a/plugins/ssugarr/postman-lite/miniapp/node/api.js b/plugins/ssugarr/postman-lite/miniapp/node/api.js new file mode 100644 index 00000000..7292041a --- /dev/null +++ b/plugins/ssugarr/postman-lite/miniapp/node/api.js @@ -0,0 +1,77 @@ +import { readState, writeState } from './store.js'; +import { sendRequest } from './proxy.js'; + +/** 单次请求体最大字节数 */ +const MAX_BODY_BYTES = 8 * 1024 * 1024; + +function sendJson(res, status, data) { + const text = JSON.stringify(data); + res.writeHead(status, { + 'content-type': 'application/json; charset=utf-8', + 'content-length': Buffer.byteLength(text), + 'cache-control': 'no-store', + }); + res.end(text); +} + +async function readJsonBody(req) { + const chunks = []; + let size = 0; + for await (const chunk of req) { + size += chunk.length; + if (size > MAX_BODY_BYTES) throw new Error('请求体过大'); + chunks.push(chunk); + } + if (chunks.length === 0) return {}; + const text = Buffer.concat(chunks).toString('utf8'); + return JSON.parse(text); +} + +/** + * API 处理器。 + * 以 (req, res, next) 形式实现,既能挂进 Vite 中间件栈,也能作为独立 http server 的入口。 + */ +export function createApiHandler() { + return async function apiHandler(req, res, next) { + let pathname; + try { + pathname = new URL(req.url ?? '/', 'http://localhost').pathname; + } catch { + return next(); + } + if (!pathname.startsWith('/api/')) return next(); + + try { + if (req.method === 'GET' && pathname === '/api/health') { + return sendJson(res, 200, { ok: true, name: 'postman-lite', time: Date.now() }); + } + + if (req.method === 'GET' && pathname === '/api/state') { + return sendJson(res, 200, readState()); + } + + if (req.method === 'PUT' && pathname === '/api/state') { + const doc = await readJsonBody(req); + const written = writeState(doc); + const stale = written.stale === true; + return sendJson(res, 200, { ok: !stale, rev: written.rev, stale }); + } + + if (req.method === 'POST' && pathname === '/api/send') { + const payload = await readJsonBody(req); + const result = await sendRequest(payload); + return sendJson(res, 200, result); + } + + return sendJson(res, 404, { + ok: false, + error: { kind: 'not_found', message: `接口不存在:${req.method} ${pathname}` }, + }); + } catch (err) { + return sendJson(res, 500, { + ok: false, + error: { kind: 'server', message: err?.message ?? '本地服务异常' }, + }); + } + }; +} diff --git a/plugins/ssugarr/postman-lite/miniapp/node/config.js b/plugins/ssugarr/postman-lite/miniapp/node/config.js new file mode 100644 index 00000000..c1eda20d --- /dev/null +++ b/plugins/ssugarr/postman-lite/miniapp/node/config.js @@ -0,0 +1,38 @@ +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; + +const here = path.dirname(fileURLToPath(import.meta.url)); + +/** 仓库根目录 */ +export const ROOT_DIR = path.resolve(here, '..'); + +/** + * 运行时数据目录。 + * 默认取仓库下的 data/,也可以用 PM_DATA_DIR 覆盖; + * Mini App 场景下由 Node 入口用 setDataDir() 注入 Host 分配的数据目录, + * 这样同一套存储代码能同时服务「独立运行」和「Mini App」两种宿主。 + */ +let dataDir = process.env.PM_DATA_DIR + ? path.resolve(process.env.PM_DATA_DIR) + : path.join(ROOT_DIR, 'data'); + +export function getDataDir() { + return dataDir; +} + +export function setDataDir(dir) { + dataDir = path.resolve(dir); +} + +/** 集合数据文件名 */ +export const STATE_FILE = 'state.json'; + +/** 前端构建产物目录 */ +export const DIST_DIR = path.join(ROOT_DIR, 'dist'); + +/** 生产模式监听端口 */ +export const PORT = Number(process.env.PORT || 8787); + +/** 生产模式监听地址,默认只绑定本机 */ +export const HOST = process.env.HOST || '127.0.0.1'; + diff --git a/plugins/ssugarr/postman-lite/miniapp/node/miniapp-api.ts b/plugins/ssugarr/postman-lite/miniapp/node/miniapp-api.ts new file mode 100644 index 00000000..5276c6f8 --- /dev/null +++ b/plugins/ssugarr/postman-lite/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/ssugarr/postman-lite/miniapp/node/proxy.js b/plugins/ssugarr/postman-lite/miniapp/node/proxy.js new file mode 100644 index 00000000..0a0b37ee --- /dev/null +++ b/plugins/ssugarr/postman-lite/miniapp/node/proxy.js @@ -0,0 +1,167 @@ +import { buildUrl, isValidHttpUrl } from './shared/url.js'; +import { encodeBody } from './shared/body.js'; +import { DEFAULT_TIMEOUT_MS, MAX_RESPONSE_BYTES } from './shared/constants.js'; + +/** 这些头由传输层管理,用户设置会与 undici 冲突 */ +const STRIPPED_HEADERS = new Set([ + 'host', + 'content-length', + 'connection', + 'transfer-encoding', + 'keep-alive', + 'upgrade', + 'expect', +]); + +const BINARY_CONTENT_TYPES = [ + /^image\//i, + /^audio\//i, + /^video\//i, + /^application\/octet-stream$/i, + /^application\/pdf$/i, +]; + +/** 没有 content-type 时,用 NUL 字节粗判是否为二进制 */ +function looksBinary(contentType, buffer) { + if (BINARY_CONTENT_TYPES.some((pattern) => pattern.test(contentType))) return true; + if (contentType) return false; + return buffer.includes(0); +} + +/** 把底层网络错误翻译成人话 */ +function describeNetworkError(err) { + const code = err?.cause?.code ?? err?.code ?? ''; + const messages = { + ENOTFOUND: '域名解析失败,请检查地址是否正确', + EAI_AGAIN: '域名解析临时失败,请稍后重试', + ECONNREFUSED: '连接被拒绝,目标端口没有开放', + ECONNRESET: '连接被对方重置', + ETIMEDOUT: '连接超时', + CERT_HAS_EXPIRED: '目标站点的 HTTPS 证书已过期', + DEPTH_ZERO_SELF_SIGNED_CERT: '目标站点使用自签名证书,校验失败', + UNABLE_TO_VERIFY_LEAF_SIGNATURE: '无法验证目标站点的 HTTPS 证书', + }; + if (messages[code]) return messages[code]; + return err?.cause?.message || err?.message || '网络请求失败'; +} + +/** + * 组装最终请求头。 + * 自动 Content-Type 打底,用户显式写的同名头优先;form 模式一律丢弃 Content-Type。 + */ +export function buildHeaders({ userHeaders = [], contentType = null, bodyMode = 'none' } = {}) { + const headers = {}; + + // 同名头按大小写不敏感地覆盖,避免出现 + // "application/json, application/vnd.api+json" 这种被 fetch 拼接的结果 + const setHeader = (name, value) => { + const lower = name.toLowerCase(); + for (const key of Object.keys(headers)) { + if (key.toLowerCase() === lower) delete headers[key]; + } + headers[name] = value; + }; + + const removeHeader = (name) => { + const lower = name.toLowerCase(); + for (const key of Object.keys(headers)) { + if (key.toLowerCase() === lower) delete headers[key]; + } + }; + + if (contentType) setHeader('content-type', contentType); + + for (const item of userHeaders) { + if (!item || item.enabled === false) continue; + const key = String(item.key ?? '').trim(); + if (!key) continue; + if (STRIPPED_HEADERS.has(key.toLowerCase())) continue; + setHeader(key, String(item.value ?? '')); + } + + if (bodyMode === 'form') { + // multipart 的 boundary 必须由 fetch 生成,手写 Content-Type 会导致服务端无法解析表单 + removeHeader('content-type'); + } + return headers; +} + +/** + * 转发一次请求。 + * @returns {Promise<{ok: true, response: object} | {ok: false, error: object}>} + */ +export async function sendRequest(payload) { + const body = payload?.body ?? { mode: 'none' }; + const method = String(payload?.method ?? 'GET').toUpperCase(); + const rawUrl = String(payload?.url ?? '').trim(); + + if (!isValidHttpUrl(rawUrl)) { + return { + ok: false, + error: { kind: 'invalid_url', message: 'URL 不合法,需要以 http:// 或 https:// 开头的完整地址' }, + }; + } + + const target = buildUrl(rawUrl, payload?.params ?? []); + const encoded = encodeBody(body, { method }); + const headers = buildHeaders({ + userHeaders: payload?.headers ?? [], + contentType: encoded.contentType, + bodyMode: body.mode, + }); + + const timeoutMs = Number(payload?.options?.timeoutMs) > 0 ? Number(payload.options.timeoutMs) : DEFAULT_TIMEOUT_MS; + const followRedirects = payload?.options?.followRedirects !== false; + + const controller = new AbortController(); + let timedOut = false; + const timer = setTimeout(() => { + timedOut = true; + controller.abort(); + }, timeoutMs); + + const started = performance.now(); + + try { + const res = await fetch(target, { + method, + headers, + body: encoded.payload, + redirect: followRedirects ? 'follow' : 'manual', + signal: controller.signal, + }); + + const buffer = Buffer.from(await res.arrayBuffer()); + const size = buffer.length; + const truncated = size > MAX_RESPONSE_BYTES; + const payloadBuffer = truncated ? buffer.subarray(0, MAX_RESPONSE_BYTES) : buffer; + const contentType = res.headers.get('content-type') ?? ''; + const isBinary = looksBinary(contentType, payloadBuffer); + const timeMs = Math.round(performance.now() - started); + + return { + ok: true, + response: { + status: res.status, + statusText: res.statusText, + headers: Object.fromEntries(res.headers.entries()), + body: isBinary ? null : payloadBuffer.toString('utf8'), + bodyBase64: isBinary ? payloadBuffer.toString('base64') : null, + size, + timeMs, + finalUrl: res.url, + redirected: res.redirected, + truncated, + contentType, + }, + }; + } catch (err) { + const timeMs = Math.round(performance.now() - started); + if (timedOut || err?.name === 'AbortError' || err?.name === 'TimeoutError') { + return { ok: false, error: { kind: 'timeout', message: `请求超时(${timeoutMs}ms)`, timeMs } }; + } + return { ok: false, error: { kind: 'network', message: describeNetworkError(err), timeMs } }; + } finally { + clearTimeout(timer); + } +} diff --git a/plugins/ssugarr/postman-lite/miniapp/node/server.mjs b/plugins/ssugarr/postman-lite/miniapp/node/server.mjs new file mode 100644 index 00000000..84658460 --- /dev/null +++ b/plugins/ssugarr/postman-lite/miniapp/node/server.mjs @@ -0,0 +1,76 @@ +// @ts-check + +import { createServer } from 'node:http'; +import { join } from 'node:path'; + +import { createApiHandler } from './api.js'; +import { createStaticHandler } from './static.js'; +import { setDataDir } from './config.js'; + +/** @typedef {import('./miniapp-api.js').MiniAppContext} MiniAppContext */ +/** @typedef {import('./miniapp-api.js').MiniAppLifecycle} MiniAppLifecycle */ + +/** + * Mini App 的 Node 运行时入口。 + * + * 复用独立版 Postman Lite 的同一套后端逻辑(api / proxy / static / store), + * 差别只有两点: + * 1. 集合数据写进 Host 分配的数据目录,而不是仓库里的 data/ + * 2. 静态资源来自 Mini App 自己的 client/ 产物 + * + * @param {MiniAppContext} context + * @returns {Promise} + */ +export async function start(context) { + // 集合数据落在 Host 分配的数据目录 + setDataDir(context.dataDir); + + const clientDir = join(context.pluginRoot, 'miniapp/client'); + const apiHandler = createApiHandler(); + const staticHandler = createStaticHandler(clientDir); + + const server = createServer((request, response) => { + // /api/* 交给业务接口,其余路径交给静态资源 + apiHandler(request, response, () => { + staticHandler(request, response, () => { + response.writeHead(404, { 'content-type': 'text/plain; charset=utf-8' }); + response.end('404 Not Found'); + }); + }); + }); + + await listen(server, context.listen.host, context.listen.port); + context.logger.info('miniapp.runtime.listening', { port: context.listen.port }); + + let disposed = false; + const dispose = async () => { + if (disposed) return; + disposed = true; + context.signal.removeEventListener('abort', onAbort); + await close(server); + }; + const onAbort = () => { + void dispose(); + }; + context.signal.addEventListener('abort', onAbort, { once: true }); + if (context.signal.aborted) await dispose(); + + return { dispose }; +} + +function listen(server, host, port) { + return new Promise((resolve, reject) => { + const onError = (error) => reject(error); + server.once('error', onError); + server.listen(port, host, () => { + server.off('error', onError); + resolve(); + }); + }); +} + +function close(server) { + return new Promise((resolve, reject) => { + server.close((error) => (error ? reject(error) : resolve())); + }); +} diff --git a/plugins/ssugarr/postman-lite/miniapp/node/shared/body.js b/plugins/ssugarr/postman-lite/miniapp/node/shared/body.js new file mode 100644 index 00000000..44ed3264 --- /dev/null +++ b/plugins/ssugarr/postman-lite/miniapp/node/shared/body.js @@ -0,0 +1,74 @@ +/** + * 请求体编码:前后端共用。 + * 纯函数(FormData 为环境全局对象),无 IO。 + */ + +/** 这些方法不允许携带请求体 */ +const BODYLESS_METHODS = ['GET', 'HEAD']; + +function enabledRows(rows) { + return (Array.isArray(rows) ? rows : []).filter( + (row) => row && row.enabled !== false && String(row.key ?? '').trim() !== '', + ); +} + +/** + * 按 mode 编码请求体。 + * @param {{mode?: string, raw?: string, json?: string, urlencoded?: Array, form?: Array}} body + * @param {{method?: string}} options + * @returns {{payload: string|FormData|undefined, contentType: string|null, mode: string}} + */ +export function encodeBody(body, options = {}) { + const mode = body?.mode ?? 'none'; + const method = String(options.method ?? 'GET').toUpperCase(); + + if (BODYLESS_METHODS.includes(method)) { + return { payload: undefined, contentType: null, mode }; + } + + switch (mode) { + case 'json': { + return { payload: String(body?.json ?? ''), contentType: 'application/json', mode }; + } + case 'raw': { + return { payload: String(body?.raw ?? ''), contentType: null, mode }; + } + case 'urlencoded': { + const search = new URLSearchParams(); + for (const row of enabledRows(body?.urlencoded)) { + search.append(String(row.key).trim(), String(row.value ?? '')); + } + return { payload: search.toString(), contentType: 'application/x-www-form-urlencoded', mode }; + } + case 'form': { + const form = new FormData(); + for (const row of enabledRows(body?.form)) { + form.append(String(row.key).trim(), String(row.value ?? '')); + } + // Content-Type 交给 fetch 生成(含 boundary) + return { payload: form, contentType: null, mode }; + } + case 'none': + default: + return { payload: undefined, contentType: null, mode: 'none' }; + } +} + +/** JSON 语法预检 */ +export function validateJsonBody(text) { + try { + JSON.parse(String(text ?? '')); + return { ok: true, message: '' }; + } catch (err) { + return { ok: false, message: err?.message ?? 'JSON 解析失败' }; + } +} + +/** 美化 JSON 文本;解析失败时原样返回 */ +export function prettyJson(text) { + try { + return JSON.stringify(JSON.parse(String(text ?? '')), null, 2); + } catch { + return String(text ?? ''); + } +} diff --git a/plugins/ssugarr/postman-lite/miniapp/node/shared/constants.js b/plugins/ssugarr/postman-lite/miniapp/node/shared/constants.js new file mode 100644 index 00000000..d92efbdd --- /dev/null +++ b/plugins/ssugarr/postman-lite/miniapp/node/shared/constants.js @@ -0,0 +1,22 @@ +/** 全局常量:前后端共用 */ + +/** @type {string[]} */ +export const HTTP_METHODS = ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS']; + +/** @type {Array<'none'|'raw'|'json'|'urlencoded'|'form'>} */ +export const BODY_MODES = ['none', 'raw', 'json', 'urlencoded', 'form']; + +/** @type {Record} */ +export const BODY_MODE_LABELS = { + none: '无', + raw: 'raw', + json: 'JSON', + urlencoded: 'x-www-form-urlencoded', + form: 'form-data', +}; + +/** 响应体最大字节数,超过则截断 */ +export const MAX_RESPONSE_BYTES = 20 * 1024 * 1024; + +/** 默认请求超时(毫秒) */ +export const DEFAULT_TIMEOUT_MS = 30000; diff --git a/plugins/ssugarr/postman-lite/miniapp/node/shared/keys.js b/plugins/ssugarr/postman-lite/miniapp/node/shared/keys.js new file mode 100644 index 00000000..438031a3 --- /dev/null +++ b/plugins/ssugarr/postman-lite/miniapp/node/shared/keys.js @@ -0,0 +1,52 @@ +/** 键值表操作:前后端共用(params / headers / 表单字段) */ + +export function createRow(key = '', value = '', enabled = true) { + return { key, value, enabled }; +} + +export function enabledRows(rows) { + return (Array.isArray(rows) ? rows : []).filter( + (row) => row && row.enabled !== false && String(row.key ?? '').trim() !== '', + ); +} + +export function rowsToObject(rows) { + const out = {}; + for (const row of enabledRows(rows)) { + out[String(row.key).trim()] = String(row.value ?? ''); + } + return out; +} + +export function rowsToSearchParams(rows) { + const search = new URLSearchParams(); + for (const row of enabledRows(rows)) { + search.append(String(row.key).trim(), String(row.value ?? '')); + } + return search; +} + +export function updateRow(rows, index, patch) { + const next = [...(rows ?? [])]; + if (index < 0 || index >= next.length) return next; + next[index] = { ...next[index], ...patch }; + return next; +} + +export function removeRow(rows, index) { + const next = [...(rows ?? [])]; + if (index < 0 || index >= next.length) return next; + next.splice(index, 1); + return next; +} + +export function appendRow(rows, row = createRow()) { + return [...(rows ?? []), row]; +} + +export function toggleRow(rows, index) { + const next = [...(rows ?? [])]; + if (index < 0 || index >= next.length) return next; + next[index] = { ...next[index], enabled: next[index].enabled === false }; + return next; +} diff --git a/plugins/ssugarr/postman-lite/miniapp/node/shared/url.js b/plugins/ssugarr/postman-lite/miniapp/node/shared/url.js new file mode 100644 index 00000000..8d2c5585 --- /dev/null +++ b/plugins/ssugarr/postman-lite/miniapp/node/shared/url.js @@ -0,0 +1,95 @@ +/** + * URL 工具:前后端共用。 + * 纯函数、无 IO,可直接用 node --test 覆盖。 + */ + +/** 拆出 #fragment 部分 */ +function splitHash(url) { + const index = url.indexOf('#'); + return index === -1 ? [url, ''] : [url.slice(0, index), url.slice(index)]; +} + +/** 校验是否为合法的 http/https 绝对地址 */ +export function isValidHttpUrl(raw) { + const url = String(raw ?? '').trim(); + if (!url) return false; + let parsed; + try { + parsed = new URL(url); + } catch { + return false; + } + return parsed.protocol === 'http:' || parsed.protocol === 'https:'; +} + +/** 从 URL 的 query string 解析出参数行 */ +export function parseQuery(rawUrl) { + const url = String(rawUrl ?? '').trim(); + const hashIndex = url.indexOf('#'); + const withoutHash = hashIndex === -1 ? url : url.slice(0, hashIndex); + const queryIndex = withoutHash.indexOf('?'); + if (queryIndex === -1) return []; + const query = withoutHash.slice(queryIndex + 1); + if (!query) return []; + const rows = []; + for (const [key, value] of new URLSearchParams(query)) { + rows.push({ key, value, enabled: true }); + } + return rows; +} + +/** + * 去掉 URL 里的 query string,保留 fragment。 + * + * 请求发送时用它把 query 从「地址栏」剥离出来, + * 统一交给参数表承载——否则地址栏里的 ?x=1 和参数表里的 x=1 + * 会在最终 URL 里各出现一次,同一个参数被发两遍。 + */ +export function stripQuery(rawUrl) { + const url = String(rawUrl ?? '').trim(); + if (!url) return ''; + const [withoutHash, hash] = splitHash(url); + const queryIndex = withoutHash.indexOf('?'); + if (queryIndex === -1) return url; + return withoutHash.slice(0, queryIndex) + hash; +} + +/** + * 把启用的 query 参数合并进 URL。 + * - URL 原有的 query 保留 + * - 关闭的行、空 key 的行忽略 + * - 同名 key 追加而非覆盖 + */ +export function buildUrl(rawUrl, params) { + const url = String(rawUrl ?? '').trim(); + if (!url) return ''; + const rows = (Array.isArray(params) ? params : []).filter( + (row) => row && row.enabled !== false && String(row.key ?? '').trim() !== '', + ); + if (rows.length === 0) return url; + + const [withoutHash, hash] = splitHash(url); + const queryIndex = withoutHash.indexOf('?'); + const path = queryIndex === -1 ? withoutHash : withoutHash.slice(0, queryIndex); + const existing = queryIndex === -1 ? '' : withoutHash.slice(queryIndex + 1); + + const search = new URLSearchParams(existing); + for (const row of rows) { + search.append(String(row.key).trim(), String(row.value ?? '')); + } + const query = search.toString(); + return query ? `${path}?${query}${hash}` : `${path}${hash}`; +} + +/** + * 变量插值钩子(v2 预留)。 + * 目前对未提供的变量原样返回,接入环境变量后在此替换 {{var}}。 + */ +export function resolveVariables(value, variables = {}) { + const text = String(value ?? ''); + if (!text.includes('{{')) return text; + return text.replace(/\{\{\s*([\w.-]+)\s*\}\}/g, (match, name) => { + return Object.prototype.hasOwnProperty.call(variables, name) ? String(variables[name]) : match; + }); +} + diff --git a/plugins/ssugarr/postman-lite/miniapp/node/static.js b/plugins/ssugarr/postman-lite/miniapp/node/static.js new file mode 100644 index 00000000..4c39ab1d --- /dev/null +++ b/plugins/ssugarr/postman-lite/miniapp/node/static.js @@ -0,0 +1,81 @@ +import fs from 'node:fs'; +import path from 'node:path'; + +const MIME_TYPES = { + '.html': 'text/html; charset=utf-8', + '.js': 'text/javascript; charset=utf-8', + '.mjs': 'text/javascript; charset=utf-8', + '.css': 'text/css; charset=utf-8', + '.json': 'application/json; charset=utf-8', + '.svg': 'image/svg+xml', + '.png': 'image/png', + '.jpg': 'image/jpeg', + '.jpeg': 'image/jpeg', + '.gif': 'image/gif', + '.webp': 'image/webp', + '.ico': 'image/x-icon', + '.woff': 'font/woff', + '.woff2': 'font/woff2', + '.ttf': 'font/ttf', + '.txt': 'text/plain; charset=utf-8', + '.map': 'application/json; charset=utf-8', +}; + +function contentTypeFor(filePath) { + return MIME_TYPES[path.extname(filePath).toLowerCase()] ?? 'application/octet-stream'; +} + +/** + * 静态文件处理器:托管 dist/,找不到的路径回退到 index.html(SPA 路由)。 + * 带扩展名的路径不回退,避免把缺失的 JS 资源返回成 HTML。 + */ +export function createStaticHandler(rootDir) { + const root = path.resolve(rootDir); + + return function staticHandler(req, res, next) { + if (req.method !== 'GET' && req.method !== 'HEAD') return next(); + + let pathname; + try { + pathname = decodeURIComponent(new URL(req.url ?? '/', 'http://localhost').pathname); + } catch { + return next(); + } + if (pathname.endsWith('/')) pathname += 'index.html'; + + const target = path.resolve(path.join(root, pathname)); + // 防目录穿越 + if (target !== root && !target.startsWith(root + path.sep)) return next(); + + const send = (filePath, stat) => { + res.writeHead(200, { + 'content-type': contentTypeFor(filePath), + 'content-length': stat.size, + }); + if (req.method === 'HEAD') { + res.end(); + return; + } + fs.createReadStream(filePath).pipe(res); + }; + + fs.stat(target, (err, stat) => { + if (!err && stat.isFile()) { + send(target, stat); + return; + } + if (path.extname(pathname)) { + next(); + return; + } + const indexPath = path.join(root, 'index.html'); + fs.stat(indexPath, (indexErr, indexStat) => { + if (indexErr || !indexStat.isFile()) { + next(); + return; + } + send(indexPath, indexStat); + }); + }); + }; +} diff --git a/plugins/ssugarr/postman-lite/miniapp/node/store.js b/plugins/ssugarr/postman-lite/miniapp/node/store.js new file mode 100644 index 00000000..f4129fe3 --- /dev/null +++ b/plugins/ssugarr/postman-lite/miniapp/node/store.js @@ -0,0 +1,68 @@ +import fs from 'node:fs'; +import path from 'node:path'; + +import { getDataDir, STATE_FILE } from './config.js'; + +function statePath() { + return path.join(getDataDir(), STATE_FILE); +} + +/** 空文档 */ +export function emptyState() { + return { version: 1, rev: 0, nodes: [] }; +} + +/** 规整外部传入的文档,剔除非法字段 */ +export function normalizeState(raw) { + const doc = raw && typeof raw === 'object' ? raw : {}; + return { + version: 1, + rev: Number.isFinite(doc.rev) ? doc.rev : 0, + nodes: Array.isArray(doc.nodes) ? doc.nodes : [], + }; +} + +/** + * 读取集合文档。 + * 文件不存在时返回空文档;文件损坏时先备份为 .bak 再返回空文档,绝不静默丢弃用户数据。 + */ +export function readState() { + const file = statePath(); + if (!fs.existsSync(file)) return emptyState(); + try { + const raw = fs.readFileSync(file, 'utf8'); + return normalizeState(JSON.parse(raw)); + } catch { + try { + fs.copyFileSync(file, `${file}.bak`); + } catch { + // 备份失败也不能阻止启动 + } + return emptyState(); + } +} + +/** + * 原子写入集合文档。 + * 先写 .tmp 再 rename,保证任何时刻磁盘上的 state.json 都是完整 JSON。 + * rev 由服务端自增并回传,客户端传来的 rev 不作为权威值。 + */ +export function writeState(doc) { + fs.mkdirSync(getDataDir(), { recursive: true }); + const file = statePath(); + const onDisk = readState(); + const incomingRev = Number.isFinite(doc?.rev) ? doc.rev : 0; + + if (incomingRev < onDisk.rev) { + // 客户端基于更旧的版本提交(说明另一个页面/标签已经改过集合), + // 丢弃这次写入,避免陈旧页面把新数据覆盖回旧值。 + return { ...onDisk, stale: true }; + } + + const next = { ...normalizeState(doc), rev: onDisk.rev + 1 }; + const tmp = `${file}.tmp`; + fs.writeFileSync(tmp, JSON.stringify(next, null, 2), 'utf8'); + fs.renameSync(tmp, file); + return next; +} + diff --git a/plugins/ssugarr/postman-lite/package.json b/plugins/ssugarr/postman-lite/package.json new file mode 100644 index 00000000..01651921 --- /dev/null +++ b/plugins/ssugarr/postman-lite/package.json @@ -0,0 +1,10 @@ +{ + "name": "postman-lite-mini-app", + "private": true, + "version": "1.0.0", + "type": "module", + "mcode": { + "schemaVersion": 2, + "miniApp": "./miniapp/miniapp.json" + } +} From 863b3cd59c3cbcab4c76237d771a98970b334d14 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=BE=A1=E5=9D=82=E5=A6=B9?= <849063625@qq.com> Date: Sun, 29 Nov 2026 00:16:08 +0800 Subject: [PATCH 2/2] Address review notes: harden static handler, document proxy behavior --- plugins/ssugarr/postman-lite/README.md | 11 +++- plugins/ssugarr/postman-lite/README.zh-CN.md | 7 ++- .../postman-lite/miniapp/node/static.js | 44 ++++++++++++-- .../ssugarr/postman-lite/test/static.test.js | 60 +++++++++++++++++++ 4 files changed, 113 insertions(+), 9 deletions(-) create mode 100644 plugins/ssugarr/postman-lite/test/static.test.js diff --git a/plugins/ssugarr/postman-lite/README.md b/plugins/ssugarr/postman-lite/README.md index 4992af65..47f84d09 100644 --- a/plugins/ssugarr/postman-lite/README.md +++ b/plugins/ssugarr/postman-lite/README.md @@ -41,7 +41,10 @@ network; behaviour on macOS and Linux. - **Files** — reads its own `miniapp/client/` payload and `miniapp/node/` code. Writes `state.json` in the Host-assigned data directory. -- **Network** — only the host the user explicitly requests through the proxy. No telemetry. +- **Network** — the host the user explicitly requests through the proxy, plus whatever + host a redirect points to: redirect following is on by default, so a response can send the request + on to a different host than the one in the address bar. Turning off "Follow redirects" keeps the + request on the original host. No telemetry. - **Processes** — none. - **Agent turns** — none. - **Conversations read** — none. @@ -49,8 +52,10 @@ network; behaviour on macOS and Linux. - **Microphone / camera / notifications** — not used. - **Host navigation read** — not declared. - **State** — the Host-assigned plugin data directory. `state.json` holds the collection tree and is - replaced atomically, so a forced stop never leaves a half-written file. Clearing that directory - resets every collection. + replaced atomically, so a forced stop never leaves a half-written file. Request headers are stored + as written, so credentials such as `Authorization`, `Cookie`, or `X-Api-Key` are kept in + plaintext in `state.json` and are returned by `GET /api/state`. Clearing that directory resets + every collection. ## Files diff --git a/plugins/ssugarr/postman-lite/README.zh-CN.md b/plugins/ssugarr/postman-lite/README.zh-CN.md index 87bf55c6..c1296423 100644 --- a/plugins/ssugarr/postman-lite/README.zh-CN.md +++ b/plugins/ssugarr/postman-lite/README.zh-CN.md @@ -36,7 +36,8 @@ Mini App 自身托管 Node 运行时,不用安装任何依赖,也不用另 - **文件** —— 读取自己的 `miniapp/client/` 产物与 `miniapp/node/` 代码;在 Host 分配的数据目录里 写入 `state.json`。 -- **网络** —— 只有用户明确请求的目标地址,无任何遥测。 +- **网络** —— 用户明确请求的目标地址,以及重定向所指向的主机:默认跟随跳转,因此响应 + 可能把请求转发到地址栏之外的主机。关掉「跟随跳转」可让请求始终留在原始主机上。无任何遥测。 - **进程** —— 无。 - **Agent 对话轮次** —— 无。 - **读取的会话** —— 无。 @@ -44,7 +45,9 @@ Mini App 自身托管 Node 运行时,不用安装任何依赖,也不用另 - **麦克风 / 摄像头 / 通知** —— 未使用。 - **Host 导航读取** —— 未声明。 - **状态位置** —— Host 分配的插件数据目录。`state.json` 保存集合树,采用原子替换写入, - 进程被强制终止也不会留下半截文件;清空该目录即重置所有集合。 + 进程被强制终止也不会留下半截文件。请求头按原样保存,因此 `Authorization`、`Cookie`、 + `X-Api-Key` 等凭据会以明文存在 `state.json` 里,并由 `GET /api/state` 返回; + 清空该目录即重置所有集合。 ## 文件 diff --git a/plugins/ssugarr/postman-lite/miniapp/node/static.js b/plugins/ssugarr/postman-lite/miniapp/node/static.js index 4c39ab1d..0a8e8487 100644 --- a/plugins/ssugarr/postman-lite/miniapp/node/static.js +++ b/plugins/ssugarr/postman-lite/miniapp/node/static.js @@ -21,6 +21,19 @@ const MIME_TYPES = { '.map': 'application/json; charset=utf-8', }; +/** + * fs.stat 在路径非法(比如含 null byte)时会同步抛错, + * 那样异常会穿过请求处理冒到事件循环里,把进程带崩。 + * 这里统一收成回调错误,让调用方按普通 IO 失败处理。 + */ +function safeStat(target, callback) { + try { + fs.stat(target, callback); + } catch (err) { + callback(err); + } +} + function contentTypeFor(filePath) { return MIME_TYPES[path.extname(filePath).toLowerCase()] ?? 'application/octet-stream'; } @@ -37,10 +50,18 @@ export function createStaticHandler(rootDir) { let pathname; try { - pathname = decodeURIComponent(new URL(req.url ?? '/', 'http://localhost').pathname); + pathname = decodeURIComponent(new URL(req.url ?? '/', 'http://miniapp.local').pathname); } catch { return next(); } + + // 路径里带 null byte 会让 fs 同步抛错,这里直接挡成 400 + if (pathname.includes('\0')) { + res.writeHead(400, { 'content-type': 'text/plain; charset=utf-8' }); + res.end('400 Bad Request'); + return; + } + if (pathname.endsWith('/')) pathname += 'index.html'; const target = path.resolve(path.join(root, pathname)); @@ -56,10 +77,24 @@ export function createStaticHandler(rootDir) { res.end(); return; } - fs.createReadStream(filePath).pipe(res); + let stream; + try { + stream = fs.createReadStream(filePath); + } catch { + res.writeHead(500, { 'content-type': 'text/plain; charset=utf-8' }); + res.end('500 Internal Server Error'); + return; + } + stream.on('error', () => { + if (!res.headersSent) { + res.writeHead(500, { 'content-type': 'text/plain; charset=utf-8' }); + } + res.end('500 Internal Server Error'); + }); + stream.pipe(res); }; - fs.stat(target, (err, stat) => { + safeStat(target, (err, stat) => { if (!err && stat.isFile()) { send(target, stat); return; @@ -69,7 +104,7 @@ export function createStaticHandler(rootDir) { return; } const indexPath = path.join(root, 'index.html'); - fs.stat(indexPath, (indexErr, indexStat) => { + safeStat(indexPath, (indexErr, indexStat) => { if (indexErr || !indexStat.isFile()) { next(); return; @@ -79,3 +114,4 @@ export function createStaticHandler(rootDir) { }); }; } + diff --git a/plugins/ssugarr/postman-lite/test/static.test.js b/plugins/ssugarr/postman-lite/test/static.test.js new file mode 100644 index 00000000..3edba150 --- /dev/null +++ b/plugins/ssugarr/postman-lite/test/static.test.js @@ -0,0 +1,60 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import http from 'node:http'; +import os from 'node:os'; +import path from 'node:path'; + +import { createStaticHandler } from '../server/static.js'; + +function startStatic(rootDir) { + const handler = createStaticHandler(rootDir); + const server = http.createServer((req, res) => { + handler(req, res, () => { + res.writeHead(404, { 'content-type': 'text/plain; charset=utf-8' }); + res.end('not found'); + }); + }); + return new Promise((resolve) => { + server.listen(0, '127.0.0.1', () => resolve({ server, port: server.address().port })); + }); +} + +test('static:路径含 null byte 返回 400,服务器不受影响', async () => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'pm-static-')); + fs.writeFileSync(path.join(dir, 'index.html'), 'ok'); + const { server, port } = await startStatic(dir); + try { + // fs.stat 在这种路径上会同步抛错;handler 必须自己挡成 400,而不是让进程崩掉 + const res = await fetch(`http://127.0.0.1:${port}/%00`); + assert.equal(res.status, 400); + + // 服务器仍然活着 + const alive = await fetch(`http://127.0.0.1:${port}/`); + assert.equal(alive.status, 200); + } finally { + server.close(); + fs.rmSync(dir, { recursive: true, force: true }); + } +}); + +test('static:目录穿越被挡在 root 之外', async () => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'pm-static-')); + fs.writeFileSync(path.join(dir, 'index.html'), 'ok'); + const { server, port } = await startStatic(dir); + try { + // URL 会把 %2e%2e 当成 .. 规范化掉,但 %2f 不是分隔符、不会被规范化; + // handler 里的 decodeURIComponent 会把它还原成 /,这才是真正能触发越界的路径 + const res = await fetch(`http://127.0.0.1:${port}/%2e%2e%2f%2e%2e%2fetc/passwd`); + assert.notEqual(res.status, 200); + // 服务器仍然活着 + const alive = await fetch(`http://127.0.0.1:${port}/`); + assert.equal(alive.status, 200); + } finally { + server.close(); + fs.rmSync(dir, { recursive: true, force: true }); + } +}); + + +