From 6df7f42918f681f398ec9f79c236a8a0016c1d92 Mon Sep 17 00:00:00 2001 From: qianmoQ Date: Thu, 3 Dec 2026 01:21:33 -0500 Subject: [PATCH 01/15] feat(release): reuse CI results and leave online plugins out of checks scripts/release.sh ran the full cargo xtask check before tagging. Most of that time went to the online plugins in market/, which the app neither depends on nor bundles: they are built and published by plugins.yml and checked by PR CI. The commit being released has usually passed CI on every platform already when it was merged. - skip local checks when ci.yml passed on HEAD in the remote's repository (shown in the plan, so a dry run tells which path will be taken) - otherwise run the new cargo xtask check app: rules, rustfmt, clippy and tests for every crate outside market/, and the frontend checks without the online plugin UIs - keep the old behaviour behind --full-checks --- crates/xtask/src/check.rs | 146 +++++++++++++++++++++++++++++++-- crates/xtask/src/check_test.rs | 51 ++++++++++++ crates/xtask/src/main.rs | 4 +- scripts/release.sh | 79 ++++++++++++++++-- 4 files changed, 268 insertions(+), 12 deletions(-) create mode 100644 crates/xtask/src/check_test.rs diff --git a/crates/xtask/src/check.rs b/crates/xtask/src/check.rs index 079dd906..af8f2752 100644 --- a/crates/xtask/src/check.rs +++ b/crates/xtask/src/check.rs @@ -2,6 +2,8 @@ use std::path::{Path, PathBuf}; use std::process::Command; use std::time::Instant; +use serde_json::Value; + use crate::rules; pub fn workspace_root() -> PathBuf { @@ -74,33 +76,42 @@ pub enum Part { Rules, Rust, Web, + /// 应用发布用:除在线插件(market/)外的全部检查。在线插件独立编译、由 PR CI 与 + /// plugins.yml 检查和发布,不进入应用安装包 + App, } +/// 在线插件所在目录:不属于应用本体 +const MARKET: &str = "market/"; + /// 逐步执行检查;子进程继承终端输出,耗时步骤的日志实时可见。 pub fn run(part: Part, fast: bool) -> Result<(), String> { let root = workspace_root(); let started = Instant::now(); - if matches!(part, Part::All | Part::Rules) { + if matches!(part, Part::All | Part::Rules | Part::App) { stage("convention rules"); rules::run(&root)?; } - let mut steps: Vec<&Step> = Vec::new(); + let mut steps: Vec = Vec::new(); if matches!(part, Part::All | Part::Rust) { - steps.extend(RUST_STEPS); + steps.extend(RUST_STEPS.iter().map(OwnedStep::from)); } if matches!(part, Part::All | Part::Web) { - steps.extend(WEB_STEPS); + steps.extend(WEB_STEPS.iter().map(OwnedStep::from)); if !fast { - steps.extend(BUILD_STEPS); + steps.extend(BUILD_STEPS.iter().map(OwnedStep::from)); } } + if part == Part::App { + steps.extend(app_steps(&app_packages(&root)?, fast)); + } for step in steps { stage(step.name); let begin = Instant::now(); let status = Command::new(program(step.program)) - .args(step.args) + .args(&step.args) .current_dir(&root) .status() .map_err(|e| format!("failed to spawn `{}`: {e}", step.program))?; @@ -121,6 +132,125 @@ pub fn run(part: Part, fast: bool) -> Result<(), String> { Ok(()) } +/// 参数在运行时确定的检查步骤 +pub struct OwnedStep { + pub name: &'static str, + pub program: &'static str, + pub args: Vec, +} + +impl From<&Step> for OwnedStep { + fn from(step: &Step) -> Self { + Self { + name: step.name, + program: step.program, + args: step.args.iter().map(|a| (*a).to_owned()).collect(), + } + } +} + +/// 应用本体的检查:Rust 只检查给定的包,前端排除在线插件的界面包 +pub fn app_steps(packages: &[String], fast: bool) -> Vec { + let owned = |args: &[&str]| args.iter().map(|a| (*a).to_owned()).collect::>(); + let selected: Vec = packages + .iter() + .flat_map(|p| ["-p".to_owned(), p.clone()]) + .collect(); + let mut clippy = owned(&["clippy"]); + clippy.extend(selected.iter().cloned()); + clippy.extend(owned(&[ + "--all-targets", + "--all-features", + "--", + "-D", + "warnings", + ])); + let mut test = owned(&["test"]); + test.extend(selected); + test.extend(owned(&["--all-features"])); + let without_market = format!("!./{MARKET}**"); + let mut steps = vec![ + OwnedStep::from(&RUST_STEPS[0]), + OwnedStep { + name: "clippy (app)", + program: "cargo", + args: clippy, + }, + OwnedStep { + name: "rust tests (app)", + program: "cargo", + args: test, + }, + OwnedStep { + name: "typecheck (app)", + program: "pnpm", + args: owned(&[ + "-r", + "--workspace-concurrency=4", + "--filter", + &without_market, + "typecheck", + ]), + }, + OwnedStep { + name: "eslint (app)", + program: "pnpm", + args: owned(&[ + "exec", + "eslint", + "apps", + "packages", + "plugins", + "--max-warnings", + "0", + ]), + }, + OwnedStep { + name: "web tests (app)", + program: "pnpm", + args: owned(&["-r", "--if-present", "--filter", &without_market, "test"]), + }, + ]; + if !fast { + steps.extend(BUILD_STEPS.iter().map(OwnedStep::from)); + } + steps +} + +/// 工作区中除在线插件外的全部包 +fn app_packages(root: &Path) -> Result, String> { + let output = Command::new("cargo") + .args(["metadata", "--no-deps", "--format-version", "1"]) + .current_dir(root) + .output() + .map_err(|e| format!("failed to run cargo metadata: {e}"))?; + if !output.status.success() { + return Err(String::from_utf8_lossy(&output.stderr).trim().to_owned()); + } + let metadata: Value = serde_json::from_slice(&output.stdout).map_err(|e| e.to_string())?; + Ok(select_app_packages(root, &metadata)) +} + +/// 从 cargo metadata 中选出 manifest 不在 market/ 下的包 +pub fn select_app_packages(root: &Path, metadata: &Value) -> Vec { + let mut packages: Vec = metadata["packages"] + .as_array() + .into_iter() + .flatten() + .filter(|package| { + let manifest = Path::new(package["manifest_path"].as_str().unwrap_or_default()); + let relative = manifest.strip_prefix(root).unwrap_or(manifest); + !relative + .to_string_lossy() + .replace('\\', "/") + .starts_with(MARKET) + }) + .filter_map(|package| package["name"].as_str().map(str::to_owned)) + .collect(); + packages.sort(); + packages +} + fn stage(name: &str) { println!("\n\x1b[1;36m==> {name}\x1b[0m"); } @@ -133,3 +263,7 @@ fn program(name: &str) -> String { name.into() } } + +#[cfg(test)] +#[path = "check_test.rs"] +mod tests; diff --git a/crates/xtask/src/check_test.rs b/crates/xtask/src/check_test.rs new file mode 100644 index 00000000..f42d741e --- /dev/null +++ b/crates/xtask/src/check_test.rs @@ -0,0 +1,51 @@ +use std::path::Path; + +use serde_json::json; + +use super::*; + +#[test] +fn app_packages_leave_out_online_plugins() { + let root = Path::new("/repo"); + let metadata = json!({ + "packages": [ + { "name": "toolforge", "manifest_path": "/repo/apps/desktop/src-tauri/Cargo.toml" }, + { "name": "tfp-hash", "manifest_path": "/repo/plugins/hash/backend/Cargo.toml" }, + { "name": "tf-wasm", "manifest_path": "/repo/crates/tf-wasm/Cargo.toml" }, + { "name": "tfm-base-converter", "manifest_path": "/repo/market/base-converter/backend/Cargo.toml" }, + { "name": "marketing", "manifest_path": "/repo/crates/marketing/Cargo.toml" } + ] + }); + assert_eq!( + select_app_packages(root, &metadata), + vec!["marketing", "tf-wasm", "tfp-hash", "toolforge"] + ); +} + +#[test] +fn app_steps_select_packages_and_skip_market_ui() { + let steps = app_steps(&["toolforge".to_owned(), "tf-core".to_owned()], true); + let names: Vec<&str> = steps.iter().map(|s| s.name).collect(); + assert_eq!( + names, + vec![ + "rustfmt", + "clippy (app)", + "rust tests (app)", + "typecheck (app)", + "eslint (app)", + "web tests (app)" + ] + ); + let clippy = steps[1].args.join(" "); + assert!(clippy.contains("-p toolforge -p tf-core")); + assert!(!clippy.contains("--workspace")); + assert!(steps[3].args.contains(&"!./market/**".to_owned())); + assert!(!steps[4].args.iter().any(|a| a == "market" || a == ".")); +} + +#[test] +fn app_steps_build_the_desktop_frontend_unless_fast() { + let steps = app_steps(&[], false); + assert_eq!(steps.last().map(|s| s.name), Some("web build")); +} diff --git a/crates/xtask/src/main.rs b/crates/xtask/src/main.rs index af2ac9a6..fb0b664e 100644 --- a/crates/xtask/src/main.rs +++ b/crates/xtask/src/main.rs @@ -19,7 +19,8 @@ const HELP: &str = "\ Usage: cargo xtask Commands: - check [part] [--fast] Run the checks CI runs; part = rules | rust | web (default: all) + check [part] [--fast] Run the checks CI runs; part = rules | rust | web | app (default: all) + app checks everything except online plugins (market/), for app releases --fast skips the web build rules Scan the repository for convention violations only version Print the current app version @@ -59,6 +60,7 @@ fn main() -> ExitCode { Some("rules") => check::run(check::Part::Rules, fast), Some("rust") => check::run(check::Part::Rust, fast), Some("web") => check::run(check::Part::Web, fast), + Some("app") => check::run(check::Part::App, fast), Some(other) => Err(format!("unknown check part `{other}`\n\n{HELP}")), } } diff --git a/scripts/release.sh b/scripts/release.sh index 1931284d..e2bbbc4a 100755 --- a/scripts/release.sh +++ b/scripts/release.sh @@ -2,7 +2,7 @@ # # ToolForge 发布脚本 # -# 流程:预检 → 运行检查 → (需要时)更新版本号并提交 → 创建附注标签(内容为该版本的提交历史) +# 流程:预检 → 检查(复用发布目标仓库上已通过的 CI,否则在本地检查应用部分) → (需要时)更新版本号并提交 → 创建附注标签(内容为该版本的提交历史) # → 推送标签触发 GitHub Actions release 工作流 → 立即把版本号更新为下一个开发版本并提交 # → 推送分支 → (可选)等待工作流完成。 # @@ -20,6 +20,7 @@ REMOTE="origin" DRY_RUN=0 ASSUME_YES=0 SKIP_CHECKS=0 +FULL_CHECKS=0 WAIT=0 PUSH_BRANCH=1 NOTES_ONLY=0 @@ -68,13 +69,20 @@ Version: 0.1.10 → 0.2.0, 0.10.10 → 1.0.0) Options: +Checks: + The commit is released without local checks when CI (ci.yml) already passed + on it in the remote's repository: CI covers every platform. Otherwise the app + is checked locally (cargo xtask check app): online plugins in market/ are + built and published separately, so they are left to PR CI and plugins.yml. + -n, --dry-run Show the plan and release notes, change nothing -y, --yes Do not ask for confirmation --next Next development version: patch (default), minor, major, an exact version, or "none" to keep the released version --wait Wait for the GitHub release workflow afterwards (needs gh) --no-push Do not push the branch (release and bump commits stay local) - --skip-checks Skip cargo xtask check (not recommended) + --full-checks Always run the full cargo xtask check locally, online plugins included + --skip-checks Skip all checks, including the CI status (not recommended) --remote Git remote to push to (default: origin) --notes Only print the release notes for the target version -h, --help Show this help @@ -98,6 +106,7 @@ while [ $# -gt 0 ]; do --push) PUSH_BRANCH=1 ;; --no-push) PUSH_BRANCH=0 ;; --skip-checks) SKIP_CHECKS=1 ;; + --full-checks) FULL_CHECKS=1 ;; --notes) NOTES_ONLY=1 ;; --next) [ $# -ge 2 ] || die "--next requires a value" @@ -200,6 +209,38 @@ start_next() { ok "committed chore(release): start $next development" } +# 发布目标仓库(owner/repo),由 remote 地址解析;不是 GitHub 地址时为空 +GITHUB_REMOTE_RE='github\.com[:/]([^/]+/[^/]+)$' +remote_repo() { + local url + url="$(git remote get-url "$REMOTE")" + if [[ "$url" =~ $GITHUB_REMOTE_RE ]]; then + echo "${BASH_REMATCH[1]%.git}" + fi +} + +# 提交在仓库中推送触发的 CI(ci.yml)结论:success / running / failure / none / unknown +ci_status() { + local repo="$1" sha="$2" result + command -v gh >/dev/null 2>&1 || { + echo unknown + return + } + for _ in 1 2 3; do + if result="$(gh api "repos/$repo/actions/runs?head_sha=$sha&event=push&per_page=100" --jq ' + [.workflow_runs[] | select(.path == ".github/workflows/ci.yml")] + | if length == 0 then "none" + elif any(.[]; .conclusion == "success") then "success" + elif any(.[]; .status != "completed") then "running" + else "failure" end' 2>/dev/null)"; then + echo "$result" + return + fi + sleep 2 + done + echo unknown +} + push_branch() { local branch="$1" step "Pushing $branch to $REMOTE" @@ -279,6 +320,25 @@ else fi ok "$TAG is available and $BRANCH is up to date" +# 合入时 CI 已在全部平台上检查过这个提交(含在线插件),通过就不必在本机重复 +CI_STATUS="" +if [ "$SKIP_CHECKS" -eq 1 ]; then + CHECKS_PLAN="skipped" +elif [ "$FULL_CHECKS" -eq 1 ]; then + CHECKS_PLAN="cargo xtask check (full, online plugins included)" +else + HEAD_SHA="$(git rev-parse HEAD)" + CI_REPO="$(remote_repo)" + CI_STATUS="unknown" + [ -z "$CI_REPO" ] || CI_STATUS="$(ci_status "$CI_REPO" "$HEAD_SHA")" + CI_WHERE="${CI_REPO:-$REMOTE}@$(git rev-parse --short HEAD)" + if [ "$CI_STATUS" = "success" ]; then + CHECKS_PLAN="CI passed on $CI_WHERE; no local checks" + else + CHECKS_PLAN="cargo xtask check app (CI on $CI_WHERE: $CI_STATUS)" + fi +fi + # ---------------------------------------------------------------- 计划 step "Release plan" @@ -290,7 +350,7 @@ else info "version $CURRENT → ${C_BOLD}$VERSION${C_RESET} (commit: chore(release): $TAG)" fi info "tag ${C_BOLD}$TAG${C_RESET} → push to $REMOTE (triggers $WORKFLOW)" -info "checks $([ "$SKIP_CHECKS" -eq 1 ] && echo skipped || echo 'cargo xtask check')" +info "checks $CHECKS_PLAN" if [ -n "$NEXT_VERSION" ]; then info "next version ${C_BOLD}$NEXT_VERSION${C_RESET} right after the tag is pushed (commit: chore(release): start $NEXT_VERSION development)" else @@ -335,8 +395,17 @@ on_error() { trap on_error ERR if [ "$SKIP_CHECKS" -eq 0 ]; then - step "Running checks" - cargo xtask check + if [ "$FULL_CHECKS" -eq 1 ]; then + step "Running checks" + cargo xtask check + elif [ "$CI_STATUS" = "success" ]; then + step "Checks" + ok "CI passed on $CI_WHERE; skipping local checks" + else + step "Running app checks" + info "CI on $CI_WHERE: $CI_STATUS; online plugins are checked by PR CI and plugins.yml" + cargo xtask check app + fi fi if [ "$VERSION" != "$CURRENT" ]; then From 5b46fd7a07e3d7817eeba95415aa8f6c7d17f08e Mon Sep 17 00:00:00 2001 From: qianmoQ Date: Thu, 3 Dec 2026 02:10:28 -0500 Subject: [PATCH 02/15] fix(market): declare file access for plugins that read user files device-mockup, festival-avatar, id-photo-maker, avro-inspector and native-deps-inspector read the picked file through the host but did not declare fs:user-selected, so the host refused every read and the tools only ever reported that the file could not be read. Saving was broken as well: the mockup, avatar and ID photo tools used an link, which the desktop WebView ignores. They now ask for a path with the save dialog; the ID photo PNG is written by a new UI-only save function because the host only writes text from the UI. --- market/avro-inspector/manifest.json | 4 +- market/device-mockup/manifest.json | 4 +- market/device-mockup/ui/src/index.tsx | 21 +++---- market/festival-avatar/manifest.json | 4 +- market/festival-avatar/ui/src/index.tsx | 21 +++---- market/id-photo-maker/backend/src/lib.rs | 57 +++++++++++++++++++ market/id-photo-maker/backend/src/lib_test.rs | 39 +++++++++++++ market/id-photo-maker/locales/en-US.json | 7 ++- market/id-photo-maker/locales/zh-CN.json | 7 ++- market/id-photo-maker/manifest.json | 7 ++- market/id-photo-maker/ui/src/index.tsx | 25 ++++---- market/native-deps-inspector/manifest.json | 4 +- 12 files changed, 156 insertions(+), 44 deletions(-) diff --git a/market/avro-inspector/manifest.json b/market/avro-inspector/manifest.json index 2a7399a1..e345cedf 100644 --- a/market/avro-inspector/manifest.json +++ b/market/avro-inspector/manifest.json @@ -1,6 +1,6 @@ { "id": "org.devlive.toolforge.avro-inspector", - "version": "0.1.0", + "version": "0.1.1", "name": "i18n:name", "description": "i18n:description", "category": "dev", @@ -17,7 +17,7 @@ "en-US" ], "minAppVersion": "0.2.0", - "permissions": [], + "permissions": ["fs:user-selected"], "functions": { "inspect": { "history": true, diff --git a/market/device-mockup/manifest.json b/market/device-mockup/manifest.json index c3001657..c4cbc31f 100644 --- a/market/device-mockup/manifest.json +++ b/market/device-mockup/manifest.json @@ -1,6 +1,6 @@ { "id": "org.devlive.toolforge.device-mockup", - "version": "0.1.0", + "version": "0.1.1", "name": "i18n:name", "description": "i18n:description", "category": "image", @@ -17,7 +17,7 @@ "en-US" ], "minAppVersion": "0.2.0", - "permissions": [], + "permissions": ["fs:user-selected"], "functions": { "templates": { "history": false, diff --git a/market/device-mockup/ui/src/index.tsx b/market/device-mockup/ui/src/index.tsx index d67f4011..88215c6c 100644 --- a/market/device-mockup/ui/src/index.tsx +++ b/market/device-mockup/ui/src/index.tsx @@ -67,16 +67,17 @@ export default function DeviceMockup() { } } - const download = () => { + // WebView 不支持 :通过系统保存对话框选择路径后写入 + const download = async () => { if (!out) return - const blob = new Blob([out.svg], { type: 'image/svg+xml' }) - const url = URL.createObjectURL(blob) - const anchor = document.createElement('a') - anchor.href = url - anchor.download = `mockup-${out.template}.svg` - anchor.click() - URL.revokeObjectURL(url) - toast.success(t('ui.saved')) + try { + const target = await host.dialog.saveFile(`mockup-${out.template}.svg`, [{ name: 'SVG', extensions: ['svg'] }]) + if (!target) return + await host.fs.writeText(target, out.svg) + toast.success(t('ui.saved')) + } catch (caught) { + toast.error(errorMessage(caught)) + } } const active = templates?.find((item) => item.id === template) @@ -148,7 +149,7 @@ export default function DeviceMockup() { <>
-
diff --git a/market/festival-avatar/manifest.json b/market/festival-avatar/manifest.json index 9fd9e778..fbf2dc27 100644 --- a/market/festival-avatar/manifest.json +++ b/market/festival-avatar/manifest.json @@ -1,6 +1,6 @@ { "id": "org.devlive.toolforge.festival-avatar", - "version": "0.1.0", + "version": "0.1.1", "name": "i18n:name", "description": "i18n:description", "category": "image", @@ -17,7 +17,7 @@ "en-US" ], "minAppVersion": "0.2.0", - "permissions": [], + "permissions": ["fs:user-selected"], "functions": { "templates": { "history": false, diff --git a/market/festival-avatar/ui/src/index.tsx b/market/festival-avatar/ui/src/index.tsx index aaa8f39a..34ea5fbb 100644 --- a/market/festival-avatar/ui/src/index.tsx +++ b/market/festival-avatar/ui/src/index.tsx @@ -58,16 +58,17 @@ export default function FestivalAvatar() { } } - const download = () => { + // WebView 不支持
:通过系统保存对话框选择路径后写入 + const download = async () => { if (!out) return - const blob = new Blob([out.svg], { type: 'image/svg+xml' }) - const url = URL.createObjectURL(blob) - const anchor = document.createElement('a') - anchor.href = url - anchor.download = `avatar-${out.template}.svg` - anchor.click() - URL.revokeObjectURL(url) - toast.success(t('ui.saved')) + try { + const target = await host.dialog.saveFile(`avatar-${out.template}.svg`, [{ name: 'SVG', extensions: ['svg'] }]) + if (!target) return + await host.fs.writeText(target, out.svg) + toast.success(t('ui.saved')) + } catch (caught) { + toast.error(errorMessage(caught)) + } } return ( @@ -121,7 +122,7 @@ export default function FestivalAvatar() { <>
-
diff --git a/market/id-photo-maker/backend/src/lib.rs b/market/id-photo-maker/backend/src/lib.rs index a4d14696..69177df4 100644 --- a/market/id-photo-maker/backend/src/lib.rs +++ b/market/id-photo-maker/backend/src/lib.rs @@ -33,6 +33,7 @@ impl ToolPlugin for IdPhotoMaker { match function { "specs" => to_value(specs()), "compose" => to_value(compose(parse_args(args)?)?), + "save" => to_value(save(parse_args(args)?)?), other => Err(unknown_function(other)), } } @@ -83,6 +84,62 @@ pub fn specs() -> Vec { .collect() } +/// 解码 `data:image/png;base64,...`;只接受标准 base64 字母表 +pub fn decode_png_data_uri(uri: &str) -> PluginResult> { + let encoded = uri + .strip_prefix("data:image/png;base64,") + .ok_or_else(|| PluginError::new("photo.bad_data"))?; + let value = |c: u8| -> Option { + match c { + b'A'..=b'Z' => Some((c - b'A') as u32), + b'a'..=b'z' => Some((c - b'a' + 26) as u32), + b'0'..=b'9' => Some((c - b'0' + 52) as u32), + b'+' => Some(62), + b'/' => Some(63), + _ => None, + } + }; + let bytes = encoded.as_bytes(); + if bytes.len() % 4 != 0 { + return Err(PluginError::new("photo.bad_data")); + } + let mut out = Vec::with_capacity(bytes.len() / 4 * 3); + for chunk in bytes.chunks(4) { + let pad = chunk.iter().rev().take_while(|&&c| c == b'=').count(); + if pad > 2 { + return Err(PluginError::new("photo.bad_data")); + } + let mut triple = 0u32; + for (index, &c) in chunk.iter().enumerate() { + let digit = if index >= 4 - pad { + 0 + } else { + value(c).ok_or_else(|| PluginError::new("photo.bad_data"))? + }; + triple = (triple << 6) | digit; + } + let decoded = [(triple >> 16) as u8, (triple >> 8) as u8, triple as u8]; + out.extend_from_slice(&decoded[..3 - pad]); + } + Ok(out) +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct SaveArgs { + /// compose 返回的 png / layoutPng + pub data_uri: String, + /// 用户在保存对话框中选择的路径 + pub path: String, +} + +/// 保存 compose 生成的 PNG:界面无法直接写二进制文件,由后端解码后写入 +pub fn save(args: SaveArgs) -> PluginResult<()> { + let bytes = decode_png_data_uri(&args.data_uri)?; + net::write_file(&args.path, &bytes) + .map_err(|e| PluginError::new("photo.write_failed").with("detail", e.code)) +} + /// 标准 base64(无依赖实现,输出不换行) fn base64_encode(data: &[u8]) -> String { const TABLE: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; diff --git a/market/id-photo-maker/backend/src/lib_test.rs b/market/id-photo-maker/backend/src/lib_test.rs index c27699d0..7d20d8d0 100644 --- a/market/id-photo-maker/backend/src/lib_test.rs +++ b/market/id-photo-maker/backend/src/lib_test.rs @@ -144,3 +144,42 @@ fn declared_interfaces_match_backend_args() { tf_plugin_api::interface::check_declared_interfaces(&IdPhotoMaker::default()).unwrap(); assert_eq!(checked, 2); } + +#[test] +fn png_data_uri_round_trips() { + for data in [&b""[..], b"a", b"ab", b"abc", b"\x89PNG\r\n\x1a\n\x00\xff"] { + let uri = format!("data:image/png;base64,{}", base64_encode(data)); + assert_eq!(decode_png_data_uri(&uri).unwrap(), data); + } +} + +#[test] +fn bad_data_uris_are_rejected() { + for uri in [ + "data:image/jpeg;base64,AAAA", + "data:image/png;base64,AAA", + "data:image/png;base64,A$AA", + "data:image/png;base64,A===", + ] { + assert_eq!(decode_png_data_uri(uri).unwrap_err().code, "photo.bad_data"); + } +} + +#[test] +fn save_writes_the_decoded_png() { + let path = tmp_png("save-src"); + let out = compose( + serde_json::from_value(json!({ "spec": "one_inch", "imagePath": path.to_string_lossy() })) + .unwrap(), + ) + .unwrap(); + let target = + std::env::temp_dir().join(format!("tf-photo-test/saved-{}.png", std::process::id())); + save(SaveArgs { + data_uri: out.png.clone(), + path: target.to_string_lossy().into_owned(), + }) + .unwrap(); + let written = image::open(&target).unwrap(); + assert_eq!((written.width(), written.height()), (out.width, out.height)); +} diff --git a/market/id-photo-maker/locales/en-US.json b/market/id-photo-maker/locales/en-US.json index 5e4913ac..7dc2ce6b 100644 --- a/market/id-photo-maker/locales/en-US.json +++ b/market/id-photo-maker/locales/en-US.json @@ -30,7 +30,9 @@ "photo.too_large": "Photo exceeds 16MB", "photo.too_small": "Photo too small (at least 50px)", "photo.bad_color": "Background must be #rrggbb", - "photo.encode_failed": "PNG encoding failed" + "photo.encode_failed": "PNG encoding failed", + "photo.bad_data": "Invalid image data", + "photo.write_failed": "Could not save the file" }, "ui": { "spec": "Spec", @@ -44,6 +46,7 @@ "download": "Download PNG", "downloadLayout": "Download layout", "corpusNote": "Center cropping without subject detection; no hair-edge feathering", - "empty": "Pick a photo and press Generate" + "empty": "Pick a photo and press Generate", + "saved": "Saved" } } diff --git a/market/id-photo-maker/locales/zh-CN.json b/market/id-photo-maker/locales/zh-CN.json index 59e1df0b..68066901 100644 --- a/market/id-photo-maker/locales/zh-CN.json +++ b/market/id-photo-maker/locales/zh-CN.json @@ -30,7 +30,9 @@ "photo.too_large": "照片超过 16MB", "photo.too_small": "照片太小(至少 50px)", "photo.bad_color": "背景色必须是 #rrggbb", - "photo.encode_failed": "PNG 编码失败" + "photo.encode_failed": "PNG 编码失败", + "photo.bad_data": "图片数据无效", + "photo.write_failed": "保存失败" }, "ui": { "spec": "规格", @@ -44,6 +46,7 @@ "download": "下载 PNG", "downloadLayout": "下载排版", "corpusNote": "整图居中裁切,未做人像主体检测;发丝边缘未做羽化", - "empty": "选择照片后点「生成」" + "empty": "选择照片后点「生成」", + "saved": "已保存" } } diff --git a/market/id-photo-maker/manifest.json b/market/id-photo-maker/manifest.json index f1914cd5..4388d4fb 100644 --- a/market/id-photo-maker/manifest.json +++ b/market/id-photo-maker/manifest.json @@ -1,6 +1,6 @@ { "id": "org.devlive.toolforge.id-photo-maker", - "version": "0.1.0", + "version": "0.1.1", "name": "i18n:name", "description": "i18n:description", "category": "image", @@ -17,7 +17,7 @@ "en-US" ], "minAppVersion": "0.2.0", - "permissions": [], + "permissions": ["fs:user-selected"], "functions": { "specs": { "history": false, @@ -35,6 +35,9 @@ } } }, + "save": { + "interface": false + }, "compose": { "history": true, "interface": { diff --git a/market/id-photo-maker/ui/src/index.tsx b/market/id-photo-maker/ui/src/index.tsx index 4fd01db6..97f0d77e 100644 --- a/market/id-photo-maker/ui/src/index.tsx +++ b/market/id-photo-maker/ui/src/index.tsx @@ -1,5 +1,5 @@ import { useEffect, useState } from 'react' -import { Button, Input, Panel, Spinner } from '@toolforge/ui' +import { Button, Input, Panel, Spinner, toast } from '@toolforge/ui' import { host, usePlugin } from '@toolforge/plugin-ui-sdk' import { IdCard, ImagePlus, Download } from 'lucide-react' @@ -21,13 +21,6 @@ interface ComposeOut { replacedPercent: number } -const download = (dataUri: string, name: string) => { - const anchor = document.createElement('a') - anchor.href = dataUri - anchor.download = name - anchor.click() -} - export default function IdPhotoMaker() { const { call, t, errorMessage } = usePlugin() const [specs, setSpecs] = useState(null) @@ -38,6 +31,18 @@ export default function IdPhotoMaker() { const [layout, setLayout] = useState(false) const [out, setOut] = useState(null) const [pending, setPending] = useState(false) + + // WebView 不支持
:选择保存路径后由后端把 PNG 写成文件 + const download = async (dataUri: string, name: string) => { + try { + const path = await host.dialog.saveFile(name, [{ name: 'PNG', extensions: ['png'] }]) + if (!path) return + await call('save', { dataUri, path }) + toast.success(t('ui.saved')) + } catch (caught) { + toast.error(errorMessage(caught)) + } + } const [error, setError] = useState(null) useEffect(() => { @@ -136,12 +141,12 @@ export default function IdPhotoMaker() { {out ? ( <>
- {out.layoutPng && ( - diff --git a/market/native-deps-inspector/manifest.json b/market/native-deps-inspector/manifest.json index dd77548f..ca622d82 100644 --- a/market/native-deps-inspector/manifest.json +++ b/market/native-deps-inspector/manifest.json @@ -1,6 +1,6 @@ { "id": "org.devlive.toolforge.native-deps-inspector", - "version": "0.1.0", + "version": "0.1.1", "name": "i18n:name", "description": "i18n:description", "category": "dev", @@ -18,7 +18,7 @@ "en-US" ], "minAppVersion": "0.2.0", - "permissions": [], + "permissions": ["fs:user-selected"], "functions": { "inspect": { "history": true, From 83ebaa351f30b2a56a9ec4b0d2400afd6cf38c79 Mon Sep 17 00:00:00 2001 From: qianmoQ Date: Thu, 3 Dec 2026 02:11:34 -0500 Subject: [PATCH 03/15] feat(xtask): require permissions for host capabilities in online plugins The host grants file and network access only from the manifest, so a backend that reads files or sends requests without declaring fs:user-selected or network fails on every call. Five plugins shipped that way unnoticed. cargo xtask check rules now scans each online plugin's backend sources (tests excluded) for the guest file and network APIs and reports the missing permission against its manifest. --- crates/xtask/src/manifests.rs | 72 ++++++++++++++++++++++++++++++ crates/xtask/src/manifests_test.rs | 28 ++++++++++++ 2 files changed, 100 insertions(+) diff --git a/crates/xtask/src/manifests.rs b/crates/xtask/src/manifests.rs index 0e96d12e..a6d96b71 100644 --- a/crates/xtask/src/manifests.rs +++ b/crates/xtask/src/manifests.rs @@ -5,6 +5,7 @@ use std::path::Path; +use regex::Regex; use serde_json::Value; use crate::interfaces::{self, Plugin}; @@ -77,6 +78,73 @@ pub fn require_interfaces(slug_path: &str, manifest: &Value, baseline: Baseline< .any(|(path, allowed)| *path == slug_path && version == Some(*allowed)) } +/// 在线插件后端调用宿主能力所需的权限:(权限, 匹配调用的正则)。 +/// 宿主只按 manifest 声明放行,漏写时每次调用都会被拒绝 +const CAPABILITIES: &[(&str, &str)] = &[ + ( + "fs:user-selected", + r"net::(read_to_end|read_file|write_file|file_size)\b|tf_plugin_guest::net::\{[^}]*\b(read_to_end|read_file|write_file|file_size)\b", + ), + ( + "network", + r"net::(send|Stream|Callback)\b|tf_plugin_guest::net::\{[^}]*\b(send|Stream|Callback)\b", + ), +]; + +/// 一段后端源码用到、需要在 manifest 中声明的权限 +pub fn required_permissions(source: &str) -> Vec<&'static str> { + CAPABILITIES + .iter() + .filter(|(_, pattern)| Regex::new(pattern).expect("valid pattern").is_match(source)) + .map(|(permission, _)| *permission) + .collect() +} + +/// 在线插件后端(不含测试文件)用到了宿主能力却没有声明对应权限 +fn permission_violations(root: &Path, slug_path: &str, manifest: &Value) -> Vec { + let declared: Vec<&str> = manifest + .get("permissions") + .and_then(Value::as_array) + .into_iter() + .flatten() + .filter_map(Value::as_str) + .collect(); + let mut needed: Vec<(&'static str, String)> = Vec::new(); + let sources = walkdir::WalkDir::new(root.join(slug_path).join("backend/src")) + .into_iter() + .flatten() + .filter(|entry| { + let name = entry.file_name().to_string_lossy(); + name.ends_with(".rs") && !name.ends_with("_test.rs") + }); + for entry in sources { + let Ok(source) = std::fs::read_to_string(entry.path()) else { + continue; + }; + for permission in required_permissions(&source) { + if !declared.contains(&permission) && !needed.iter().any(|(p, _)| *p == permission) { + let file = entry + .path() + .strip_prefix(root) + .unwrap_or(entry.path()) + .to_string_lossy() + .replace('\\', "/"); + needed.push((permission, file)); + } + } + } + needed + .into_iter() + .map(|(permission, file)| Violation { + rule: "plugin-permission", + message: format!( + "{file} uses a host capability that needs the `{permission}` permission" + ), + location: format!("{slug_path}/manifest.json:1"), + }) + .collect() +} + /// 读取插件声明的各语言包(locales/<语言>.json) fn locales(dir: &Path, manifest: &Value) -> Vec<(String, Value)> { manifest @@ -141,6 +209,10 @@ pub fn scan(root: &Path) -> Vec { }; violations.extend(check(&relative, &manifest, baseline)); let slug_path = format!("{base}/{slug}"); + // 内置插件是原生代码、不经过 WASM 权限检查,只有在线插件需要声明 + if *base == "market" { + violations.extend(permission_violations(root, &slug_path, &manifest)); + } let locales = locales(&root.join(&slug_path), &manifest); let plugin = Plugin { relative: &relative, diff --git a/crates/xtask/src/manifests_test.rs b/crates/xtask/src/manifests_test.rs index 6f052bf1..b65c922a 100644 --- a/crates/xtask/src/manifests_test.rs +++ b/crates/xtask/src/manifests_test.rs @@ -73,3 +73,31 @@ fn interfaces_are_required_for_changed_plugins_except_grandfathered_versions() { Baseline::Missing )); } + +#[test] +fn file_and_network_calls_need_permissions() { + assert_eq!( + required_permissions("let bytes = net::read_to_end(&path, MAX)?;"), + vec!["fs:user-selected"] + ); + assert_eq!( + required_permissions( + "use tf_plugin_guest::net::{self, HttpRequest};\nnet::send(&req, None)" + ), + vec!["network"] + ); + assert_eq!( + required_permissions("use tf_plugin_guest::net::{Stream, StreamRequest};"), + vec!["network"] + ); + assert_eq!( + required_permissions("net::file_size(p)?; net::send(&r, None)?;"), + vec!["fs:user-selected", "network"] + ); +} + +#[test] +fn unrelated_code_needs_no_permission() { + assert!(required_permissions("fn read_file_name(x: &str) {} std::fs::read(path)").is_empty()); + assert!(required_permissions("use tf_plugin_guest::net::StreamEvent;").is_empty()); +} From a5ff41bbd5b5f820131d59be6e66d085d44af98e Mon Sep 17 00:00:00 2001 From: qianmoQ Date: Thu, 3 Dec 2026 02:12:35 -0500 Subject: [PATCH 04/15] feat(app): let the sidebar be hidden and shown again A button next to the logo in the title bar, or Cmd/Ctrl+\, collapses the left sidebar to give tools the full window width and brings it back. The choice is saved with the other preferences. Cmd/Ctrl+B is left alone because editor plugins use it for bold. The sidebar narrows with a width transition while its content keeps a fixed width, so nothing reflows during the animation, and the hidden sidebar is inert so it cannot take keyboard focus. --- apps/desktop/src/layout/Sidebar.tsx | 13 +++++++++++- apps/desktop/src/layout/TitleBar.tsx | 30 +++++++++++++++++++++++++++- apps/desktop/src/lib/boot.ts | 2 ++ apps/desktop/src/locales/en-US.json | 4 +++- apps/desktop/src/locales/zh-CN.json | 4 +++- apps/desktop/src/stores/prefs.ts | 7 +++++++ 6 files changed, 56 insertions(+), 4 deletions(-) diff --git a/apps/desktop/src/layout/Sidebar.tsx b/apps/desktop/src/layout/Sidebar.tsx index 3b99ab55..0539dc7d 100644 --- a/apps/desktop/src/layout/Sidebar.tsx +++ b/apps/desktop/src/layout/Sidebar.tsx @@ -62,12 +62,22 @@ export function Sidebar() { const openTool = useApp((s) => s.openTool) const collapsed = usePrefs((s) => s.collapsed) const toggleCategory = usePrefs((s) => s.toggleCategory) + const sidebarHidden = usePrefs((s) => s.sidebarHidden) const is = (view: Route['view']) => route.view === view const activeTool = route.view === 'tool' ? route.pluginId : null return ( -
) } diff --git a/apps/desktop/src/layout/TitleBar.tsx b/apps/desktop/src/layout/TitleBar.tsx index 848a6960..5990ff99 100644 --- a/apps/desktop/src/layout/TitleBar.tsx +++ b/apps/desktop/src/layout/TitleBar.tsx @@ -1,5 +1,6 @@ import { Badge, Button, Kbd, Tooltip } from '@toolforge/ui' -import { ArrowUpCircle, History, ListChecks, Moon, Search, Settings, Star, Sun } from 'lucide-react' +import { ArrowUpCircle, History, ListChecks, Moon, PanelLeftClose, PanelLeftOpen, Search, Settings, Star, Sun } from 'lucide-react' +import { useEffect } from 'react' import { useTranslation } from 'react-i18next' import { isMac } from '../lib/boot' import { useApp } from '../stores/app' @@ -20,6 +21,21 @@ export function TitleBar() { const openUpdate = useUpdate((s) => s.setDialogOpen) const running = useRunningCount() const openTasks = useTasks((s) => s.setOpen) + const sidebarHidden = usePrefs((s) => s.sidebarHidden) + const toggleSidebar = usePrefs((s) => s.toggleSidebar) + const sidebarLabel = t(sidebarHidden ? 'titlebar.showSidebar' : 'titlebar.hideSidebar') + + // ⌘\ / Ctrl+\ 切换侧边栏;不用 ⌘B,避免与编辑器类插件的加粗冲突 + useEffect(() => { + const onKey = (event: KeyboardEvent) => { + if ((event.metaKey || event.ctrlKey) && !event.altKey && !event.shiftKey && event.key === '\\') { + event.preventDefault() + usePrefs.getState().toggleSidebar() + } + } + window.addEventListener('keydown', onKey) + return () => window.removeEventListener('keydown', onKey) + }, []) return (
{version && v{version}} + + + )} + {checkedCount > 0 && ( +
+ {t('market.online.selectedCount', { count: checkedCount })} + + + +
+ )} {list.length === 0 ? ( } title={t('market.empty')} /> ) : ( @@ -132,9 +177,27 @@ export function Market() { {list.map((manifest) => { const status = toolStatus(manifest, seen) const isHidden = hidden.includes(manifest.id) + const canRemove = installedIds.includes(manifest.id) return ( -
- +
{t('market.version', { version: manifest.version })} · @@ -218,6 +282,30 @@ export function Market() { } onClose={() => setSelected(null)} /> + !open && setBulkUninstall(null)} + title={t('market.online.bulkUninstallTitle', { count: bulkUninstall?.length ?? 0 })} + closeLabel={t('common:close')} + footer={ + <> + + + + } + > +
    + {(bulkUninstall ?? []).map((manifest) => ( +
  • + {text(manifest, manifest.name)} + {manifest.id} +
  • + ))} +
+
{config.dialog} ) From a2b3a8b7e68562bdf6dd9e775df41d56cf60b1be Mon Sep 17 00:00:00 2001 From: qianmoQ Date: Thu, 3 Dec 2026 02:16:04 -0500 Subject: [PATCH 06/15] feat(ui): give every plugin accent its own tile color Plugins use 18 accent values, but only six had a tile color, so 47 tools such as amber, red or teal ones all fell back to the same green tile. Add tile colors for every accent, and deepen orange, cyan and the new yellow so a white glyph keeps at least 3:1 contrast at the gradient midpoint. cargo xtask check rules now rejects an accent without a tile color, a test keeps the xtask list, accentTiles and tokens.css in step, and the plugin guide lists the allowed values. --- apps/desktop/src/plugins/ToolIcon.tsx | 17 ++++- crates/xtask/src/manifests.rs | 21 ++++++ crates/xtask/src/manifests_test.rs | 25 +++++++ docs/src/content/dev/plugin-development.en.md | 1 + docs/src/content/dev/plugin-development.zh.md | 1 + packages/ui/src/styles/tokens.css | 75 +++++++++++++++++-- 6 files changed, 131 insertions(+), 9 deletions(-) diff --git a/apps/desktop/src/plugins/ToolIcon.tsx b/apps/desktop/src/plugins/ToolIcon.tsx index 3aac0a9f..9eaaedae 100644 --- a/apps/desktop/src/plugins/ToolIcon.tsx +++ b/apps/desktop/src/plugins/ToolIcon.tsx @@ -3,14 +3,27 @@ import { Wrench } from 'lucide-react' import type { Manifest } from '@toolforge/plugin-ui-sdk' import { pluginIcon } from './modules' -/** manifest.accent → 图标底色工具类;与索引条目(MarketOnline)共用同一套颜色规则 */ +/** manifest.accent → 图标底色工具类;与索引条目(MarketOnline)共用同一套颜色规则。 + * 取值须与 xtask 的 ACCENTS、ui tokens.css 的 tile-* 保持一致 */ export const accentTiles: Record = { violet: 'tile-violet', + purple: 'tile-purple', + indigo: 'tile-indigo', blue: 'tile-blue', + sky: 'tile-sky', + cyan: 'tile-cyan', + teal: 'tile-teal', + emerald: 'tile-emerald', green: 'tile-green', + lime: 'tile-lime', + yellow: 'tile-yellow', + amber: 'tile-amber', orange: 'tile-orange', + red: 'tile-red', + rose: 'tile-rose', pink: 'tile-pink', - cyan: 'tile-cyan', + brown: 'tile-brown', + gray: 'tile-gray', } as const /** 插件图标:内置插件图标为随包分发的 SVG(使用 currentColor) */ diff --git a/crates/xtask/src/manifests.rs b/crates/xtask/src/manifests.rs index a6d96b71..dcd9c4a8 100644 --- a/crates/xtask/src/manifests.rs +++ b/crates/xtask/src/manifests.rs @@ -78,6 +78,26 @@ pub fn require_interfaces(slug_path: &str, manifest: &Value, baseline: Baseline< .any(|(path, allowed)| *path == slug_path && version == Some(*allowed)) } +/// manifest.accent 可用的图标底色;与 ui tokens.css 的 tile-*、桌面端 accentTiles 一一对应, +/// 未知取值在界面上会回退成绿色 +pub const ACCENTS: &[&str] = &[ + "violet", "purple", "indigo", "blue", "sky", "cyan", "teal", "emerald", "green", "lime", + "yellow", "amber", "orange", "red", "rose", "pink", "brown", "gray", +]; + +/// accent 不在可用颜色中 +pub fn check_accent(relative: &str, manifest: &Value) -> Option { + let accent = manifest.get("accent")?.as_str().unwrap_or_default(); + (!ACCENTS.contains(&accent)).then(|| Violation { + rule: "plugin-accent", + message: format!( + "accent `{accent}` has no tile color; use one of: {}", + ACCENTS.join(", ") + ), + location: format!("{relative}:1"), + }) +} + /// 在线插件后端调用宿主能力所需的权限:(权限, 匹配调用的正则)。 /// 宿主只按 manifest 声明放行,漏写时每次调用都会被拒绝 const CAPABILITIES: &[(&str, &str)] = &[ @@ -208,6 +228,7 @@ pub fn scan(root: &Path) -> Vec { (Some(_), None) => Baseline::Missing, }; violations.extend(check(&relative, &manifest, baseline)); + violations.extend(check_accent(&relative, &manifest)); let slug_path = format!("{base}/{slug}"); // 内置插件是原生代码、不经过 WASM 权限检查,只有在线插件需要声明 if *base == "market" { diff --git a/crates/xtask/src/manifests_test.rs b/crates/xtask/src/manifests_test.rs index b65c922a..1b6a7067 100644 --- a/crates/xtask/src/manifests_test.rs +++ b/crates/xtask/src/manifests_test.rs @@ -101,3 +101,28 @@ fn unrelated_code_needs_no_permission() { assert!(required_permissions("fn read_file_name(x: &str) {} std::fs::read(path)").is_empty()); assert!(required_permissions("use tf_plugin_guest::net::StreamEvent;").is_empty()); } + +#[test] +fn accents_must_have_a_tile_color() { + assert!(check_accent(PATH, &json!({ "accent": "teal" })).is_none()); + assert!(check_accent(PATH, &json!({})).is_none()); + assert!(check_accent(PATH, &json!({ "accent": "magenta" })).is_some()); +} + +#[test] +fn desktop_and_ui_know_every_accent() { + let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../.."); + let tiles = + std::fs::read_to_string(root.join("apps/desktop/src/plugins/ToolIcon.tsx")).unwrap(); + let tokens = std::fs::read_to_string(root.join("packages/ui/src/styles/tokens.css")).unwrap(); + for accent in ACCENTS { + assert!( + tiles.contains(&format!("{accent}: 'tile-{accent}'")), + "accentTiles lacks {accent}" + ); + assert!( + tokens.contains(&format!("@utility tile-{accent} ")), + "tokens.css lacks tile-{accent}" + ); + } +} diff --git a/docs/src/content/dev/plugin-development.en.md b/docs/src/content/dev/plugin-development.en.md index ce046896..488a701c 100644 --- a/docs/src/content/dev/plugin-development.en.md +++ b/docs/src/content/dev/plugin-development.en.md @@ -56,6 +56,7 @@ market/my-tool/ | `version` | Bump once per release; several changes in one release cycle share one bump | | `name` / `description` | Written as `i18n:key`; the real text lives in the locales | | `category` | One of `dev`, `text`, `encode`, `convert`, `image`, `network`, `system`, `calc`, `life`, `other` | +| `accent` | Icon tile color, one of `violet`, `purple`, `indigo`, `blue`, `sky`, `cyan`, `teal`, `emerald`, `green`, `lime`, `yellow`, `amber`, `orange`, `red`, `rose`, `pink`, `brown`, `gray`; defaults to `green` and is checked by `cargo xtask check rules` | | `minAppVersion` | The lowest app version the plugin needs; required for new and changed plugins | | `permissions` | Capabilities the plugin code needs, enforced by the host (see below) | | `functions` | Functions the backend provides; `task: true` marks long-running tasks, `history: true` records successful calls in history | diff --git a/docs/src/content/dev/plugin-development.zh.md b/docs/src/content/dev/plugin-development.zh.md index e5be67d1..d165acee 100644 --- a/docs/src/content/dev/plugin-development.zh.md +++ b/docs/src/content/dev/plugin-development.zh.md @@ -56,6 +56,7 @@ market/my-tool/ | `version` | 每次发布递增一次;同一个发布周期内多次修改共用一次递增 | | `name` / `description` | 写成 `i18n:键名`,真实文案在 locales 中 | | `category` | `dev`、`text`、`encode`、`convert`、`image`、`network`、`system`、`calc`、`life`、`other` 之一 | +| `accent` | 图标底色,`violet`、`purple`、`indigo`、`blue`、`sky`、`cyan`、`teal`、`emerald`、`green`、`lime`、`yellow`、`amber`、`orange`、`red`、`rose`、`pink`、`brown`、`gray` 之一,不写时为 `green`;`cargo xtask check rules` 会检查 | | `minAppVersion` | 插件需要的最低应用版本,新插件和修改过的插件必须填写 | | `permissions` | 插件代码需要的能力,由宿主强制检查,见下文 | | `functions` | 后端提供的函数;`task: true` 表示耗时任务,`history: true` 表示调用成功后记入历史 | diff --git a/packages/ui/src/styles/tokens.css b/packages/ui/src/styles/tokens.css index 8fefc854..0bd0019d 100644 --- a/packages/ui/src/styles/tokens.css +++ b/packages/ui/src/styles/tokens.css @@ -63,18 +63,43 @@ /* 工具图标底色(渐变两端)及其上的图标色 */ --tf-on-tile: #ffffff; + /* 白色图标叠加在渐变中点上的对比度均 ≥ 3:1(图形元素的 WCAG 要求) */ --tf-tile-violet-from: #8b5cf6; --tf-tile-violet-to: #6d28d9; + --tf-tile-purple-from: #a855f7; + --tf-tile-purple-to: #7e22ce; + --tf-tile-indigo-from: #6366f1; + --tf-tile-indigo-to: #4338ca; --tf-tile-blue-from: #3b82f6; --tf-tile-blue-to: #1d4ed8; + --tf-tile-sky-from: #0ea5e9; + --tf-tile-sky-to: #0369a1; + --tf-tile-cyan-from: #06b6d4; + --tf-tile-cyan-to: #0e7490; + --tf-tile-teal-from: #14b8a6; + --tf-tile-teal-to: #0f766e; + --tf-tile-emerald-from: #10b981; + --tf-tile-emerald-to: #047857; --tf-tile-green-from: #22c55e; --tf-tile-green-to: #15803d; - --tf-tile-orange-from: #fb923c; - --tf-tile-orange-to: #ea580c; + --tf-tile-lime-from: #65a30d; + --tf-tile-lime-to: #3f6212; + --tf-tile-yellow-from: #ca8a04; + --tf-tile-yellow-to: #854d0e; + --tf-tile-amber-from: #f59e0b; + --tf-tile-amber-to: #b45309; + --tf-tile-orange-from: #f97316; + --tf-tile-orange-to: #c2410c; + --tf-tile-red-from: #ef4444; + --tf-tile-red-to: #b91c1c; + --tf-tile-rose-from: #f43f5e; + --tf-tile-rose-to: #be123c; --tf-tile-pink-from: #f472b6; --tf-tile-pink-to: #db2777; - --tf-tile-cyan-from: #22d3ee; - --tf-tile-cyan-to: #0891b2; + --tf-tile-brown-from: #a8714a; + --tf-tile-brown-to: #6b4226; + --tf-tile-gray-from: #64748b; + --tf-tile-gray-to: #334155; /* 支付测试卡:固定深色卡面,明暗主题下保持读数与测试标记的对比度 */ --tf-payment-card-from: #244c43; @@ -277,24 +302,60 @@ z-index: 70; } -/* 工具图标底色:tile-violet / tile-blue … */ +/* 工具图标底色:tile-violet / tile-blue …,与 manifest.accent 的取值一一对应 */ @utility tile-violet { background-image: linear-gradient(135deg, var(--tf-tile-violet-from), var(--tf-tile-violet-to)); } +@utility tile-purple { + background-image: linear-gradient(135deg, var(--tf-tile-purple-from), var(--tf-tile-purple-to)); +} +@utility tile-indigo { + background-image: linear-gradient(135deg, var(--tf-tile-indigo-from), var(--tf-tile-indigo-to)); +} @utility tile-blue { background-image: linear-gradient(135deg, var(--tf-tile-blue-from), var(--tf-tile-blue-to)); } +@utility tile-sky { + background-image: linear-gradient(135deg, var(--tf-tile-sky-from), var(--tf-tile-sky-to)); +} +@utility tile-cyan { + background-image: linear-gradient(135deg, var(--tf-tile-cyan-from), var(--tf-tile-cyan-to)); +} +@utility tile-teal { + background-image: linear-gradient(135deg, var(--tf-tile-teal-from), var(--tf-tile-teal-to)); +} +@utility tile-emerald { + background-image: linear-gradient(135deg, var(--tf-tile-emerald-from), var(--tf-tile-emerald-to)); +} @utility tile-green { background-image: linear-gradient(135deg, var(--tf-tile-green-from), var(--tf-tile-green-to)); } +@utility tile-lime { + background-image: linear-gradient(135deg, var(--tf-tile-lime-from), var(--tf-tile-lime-to)); +} +@utility tile-yellow { + background-image: linear-gradient(135deg, var(--tf-tile-yellow-from), var(--tf-tile-yellow-to)); +} +@utility tile-amber { + background-image: linear-gradient(135deg, var(--tf-tile-amber-from), var(--tf-tile-amber-to)); +} @utility tile-orange { background-image: linear-gradient(135deg, var(--tf-tile-orange-from), var(--tf-tile-orange-to)); } +@utility tile-red { + background-image: linear-gradient(135deg, var(--tf-tile-red-from), var(--tf-tile-red-to)); +} +@utility tile-rose { + background-image: linear-gradient(135deg, var(--tf-tile-rose-from), var(--tf-tile-rose-to)); +} @utility tile-pink { background-image: linear-gradient(135deg, var(--tf-tile-pink-from), var(--tf-tile-pink-to)); } -@utility tile-cyan { - background-image: linear-gradient(135deg, var(--tf-tile-cyan-from), var(--tf-tile-cyan-to)); +@utility tile-brown { + background-image: linear-gradient(135deg, var(--tf-tile-brown-from), var(--tf-tile-brown-to)); +} +@utility tile-gray { + background-image: linear-gradient(135deg, var(--tf-tile-gray-from), var(--tf-tile-gray-to)); } @layer base { From 63b482e51da82d7745f70796e14c4b81a55dc216 Mon Sep 17 00:00:00 2001 From: qianmoQ Date: Thu, 3 Dec 2026 02:23:58 -0500 Subject: [PATCH 07/15] feat(market): redraw plugin icons as tile-colored line icons 74 plugin icons were 64x64 drawings with their own colored square, most of them the same placeholder circle. In the app they sat as a second tile inside the accent tile, and on the website, which uses icons as a mask, they rendered as a solid block. Redraw each one as a 24x24 currentColor line icon that depicts its tool, matching the rest of the catalog, and bump the published plugins whose icon changed. cargo xtask check rules now rejects icons that are not 24x24, do not stroke with currentColor or hard-code colors, and the plugin guide states the requirement. --- crates/xtask/src/manifests.rs | 23 +++++++++++++++++++ crates/xtask/src/manifests_test.rs | 12 ++++++++++ docs/src/content/dev/plugin-development.en.md | 1 + docs/src/content/dev/plugin-development.zh.md | 1 + market/address-parser/icon.svg | 6 +---- market/address-parser/manifest.json | 2 +- market/ambient-effects/icon.svg | 6 +---- market/ambient-effects/manifest.json | 2 +- market/avro-inspector/icon.svg | 6 +---- market/bead-pattern/icon.svg | 5 +--- market/bead-pattern/manifest.json | 2 +- market/bingo-cards/icon.svg | 6 +---- market/bingo-cards/manifest.json | 2 +- market/chat-mockup/icon.svg | 6 +---- market/chat-mockup/manifest.json | 2 +- market/css-generator/icon.svg | 6 +---- market/css-generator/manifest.json | 2 +- market/css-selector-inspector/icon.svg | 6 +---- market/css-selector-inspector/manifest.json | 2 +- market/dep-graph/icon.svg | 6 +---- market/dep-graph/manifest.json | 2 +- market/dev-directory/icon.svg | 6 +---- market/dev-directory/manifest.json | 2 +- market/device-mockup/icon.svg | 6 +---- market/dockerfile-lint/icon.svg | 6 +---- market/dockerfile-lint/manifest.json | 2 +- market/domain-toolbox/icon.svg | 6 +---- market/domain-toolbox/manifest.json | 2 +- market/dynasty-timeline/icon.svg | 6 +---- market/dynasty-timeline/manifest.json | 2 +- market/festival-avatar/icon.svg | 6 +---- market/file-extension/icon.svg | 6 +---- market/file-extension/manifest.json | 2 +- market/file-permission-inspector/icon.svg | 6 +---- .../file-permission-inspector/manifest.json | 2 +- market/fortune-tarot/icon.svg | 6 +---- market/fortune-tarot/manifest.json | 2 +- market/geometry-calculator/icon.svg | 6 +---- market/geometry-calculator/manifest.json | 2 +- market/git-hooks-manager/icon.svg | 6 +---- market/git-hooks-manager/manifest.json | 2 +- market/hanzi-copybook/icon.svg | 6 +---- market/hanzi-copybook/manifest.json | 2 +- market/hanzi-pinyin/icon.svg | 6 +---- market/hanzi-pinyin/manifest.json | 2 +- market/health-calculator/icon.svg | 6 +---- market/health-calculator/manifest.json | 2 +- market/icu-lint/icon.svg | 6 +---- market/icu-lint/manifest.json | 2 +- market/id-photo-maker/icon.svg | 6 +---- market/idiom-reference/icon.svg | 6 +---- market/idiom-reference/manifest.json | 2 +- market/invoice-assistant/icon.svg | 6 +---- market/invoice-assistant/manifest.json | 2 +- market/js-minify-beautify/icon.svg | 6 +---- market/js-minify-beautify/manifest.json | 2 +- market/keyword-density/icon.svg | 6 +---- market/keyword-density/manifest.json | 2 +- market/kinship-calculator/icon.svg | 6 +---- market/kinship-calculator/manifest.json | 2 +- market/license-plate/icon.svg | 6 +---- market/license-plate/manifest.json | 2 +- market/meme-composer/icon.svg | 5 +--- market/meme-composer/manifest.json | 2 +- market/meta-tags/icon.svg | 6 +---- market/meta-tags/manifest.json | 2 +- market/metronome/icon.svg | 6 +---- market/metronome/manifest.json | 2 +- market/mini-instrument/icon.svg | 6 +---- market/mini-instrument/manifest.json | 2 +- market/name-generator/icon.svg | 6 +---- market/name-generator/manifest.json | 2 +- market/native-deps-inspector/icon.svg | 6 +---- market/nginx-config-generator/icon.svg | 6 +---- market/nginx-config-generator/manifest.json | 2 +- market/nginx-log-analyzer/icon.svg | 6 +---- market/nginx-log-analyzer/manifest.json | 2 +- market/package-entry-resolver/icon.svg | 6 +---- market/package-entry-resolver/manifest.json | 2 +- market/paper-box-templates/icon.svg | 6 +---- market/paper-box-templates/manifest.json | 2 +- market/paper-size/icon.svg | 6 +---- market/paper-size/manifest.json | 2 +- market/parquet-inspector/icon.svg | 6 +---- market/parquet-inspector/manifest.json | 2 +- market/pcap-viewer/icon.svg | 5 +--- market/pcap-viewer/manifest.json | 2 +- market/periodic-table/icon.svg | 6 +---- market/periodic-table/manifest.json | 2 +- market/phone-region-lookup/icon.svg | 6 +---- market/phone-region-lookup/manifest.json | 2 +- market/physics-calculator/icon.svg | 6 +---- market/physics-calculator/manifest.json | 2 +- market/postal-lookup/icon.svg | 6 +---- market/postal-lookup/manifest.json | 2 +- market/pour-over-coffee/icon.svg | 6 +---- market/pour-over-coffee/manifest.json | 2 +- market/reaction-challenge/icon.svg | 6 +---- market/reaction-challenge/manifest.json | 2 +- market/redirect-map/icon.svg | 6 +---- market/redirect-map/manifest.json | 2 +- market/rewrite-converter/icon.svg | 6 +---- market/rewrite-converter/manifest.json | 2 +- market/robots-sitemap/icon.svg | 6 +---- market/robots-sitemap/manifest.json | 2 +- market/saml-inspector/icon.svg | 6 +---- market/saml-inspector/manifest.json | 2 +- market/scratch-calculator/icon.svg | 13 +---------- market/scratch-calculator/manifest.json | 2 +- market/seal-designer/icon.svg | 5 +--- market/seal-designer/manifest.json | 2 +- market/seo-auditor/icon.svg | 6 +---- market/seo-auditor/manifest.json | 2 +- market/shortcut-cheatsheet/icon.svg | 6 +---- market/shortcut-cheatsheet/manifest.json | 2 +- market/stargazing-guide/icon.svg | 6 +---- market/stargazing-guide/manifest.json | 2 +- market/sudoku/icon.svg | 6 +---- market/sudoku/manifest.json | 2 +- market/symmetry-drawing/icon.svg | 6 +---- market/symmetry-drawing/manifest.json | 2 +- market/tangram-studio/icon.svg | 5 +--- market/tangram-studio/manifest.json | 2 +- market/token-counter/icon.svg | 6 +---- market/token-counter/manifest.json | 2 +- market/torrent-analyzer/icon.svg | 6 +---- market/torrent-analyzer/manifest.json | 2 +- market/trace-viewer/icon.svg | 5 +--- market/trace-viewer/manifest.json | 2 +- market/undercover-host/icon.svg | 6 +---- market/undercover-host/manifest.json | 2 +- market/url-rewrite-generator/icon.svg | 6 +---- market/url-rewrite-generator/manifest.json | 2 +- market/verse-checker/icon.svg | 6 +---- market/verse-checker/manifest.json | 2 +- market/vertical-stationery/icon.svg | 5 +--- market/vertical-stationery/manifest.json | 2 +- market/wardrobe-journal/icon.svg | 5 +--- market/wardrobe-journal/manifest.json | 2 +- market/weekly-menu/icon.svg | 5 +--- market/weekly-menu/manifest.json | 2 +- market/workflow-dag/icon.svg | 6 +---- market/workflow-dag/manifest.json | 2 +- market/world-geography/icon.svg | 6 +---- market/world-geography/manifest.json | 2 +- plugins/proxy-inspector/icon.svg | 9 +------- 146 files changed, 179 insertions(+), 439 deletions(-) diff --git a/crates/xtask/src/manifests.rs b/crates/xtask/src/manifests.rs index dcd9c4a8..26d4ccf9 100644 --- a/crates/xtask/src/manifests.rs +++ b/crates/xtask/src/manifests.rs @@ -98,6 +98,25 @@ pub fn check_accent(relative: &str, manifest: &Value) -> Option { }) } +/// 插件图标必须是 24×24、currentColor 描边的线性图标:界面把它画在 accent 底色上, +/// 官网用作蒙版;自带底色或固定颜色的图标会在两处都显示错误 +pub fn check_icon(relative: &str, svg: &str) -> Option { + let problem = if !svg.contains(r#"viewBox="0 0 24 24""#) { + "icon must use viewBox=\"0 0 24 24\"" + } else if !svg.contains(r#"stroke="currentColor""#) { + "icon must draw with stroke=\"currentColor\"" + } else if svg.contains("fill=\"#") || svg.contains("stroke=\"#") || svg.contains("rgb(") { + "icon must not hard-code colors; the tile supplies the background" + } else { + return None; + }; + Some(Violation { + rule: "plugin-icon", + message: problem.to_owned(), + location: format!("{relative}:1"), + }) +} + /// 在线插件后端调用宿主能力所需的权限:(权限, 匹配调用的正则)。 /// 宿主只按 manifest 声明放行,漏写时每次调用都会被拒绝 const CAPABILITIES: &[(&str, &str)] = &[ @@ -229,6 +248,10 @@ pub fn scan(root: &Path) -> Vec { }; violations.extend(check(&relative, &manifest, baseline)); violations.extend(check_accent(&relative, &manifest)); + let icon = format!("{base}/{slug}/icon.svg"); + if let Ok(svg) = std::fs::read_to_string(root.join(&icon)) { + violations.extend(check_icon(&icon, &svg)); + } let slug_path = format!("{base}/{slug}"); // 内置插件是原生代码、不经过 WASM 权限检查,只有在线插件需要声明 if *base == "market" { diff --git a/crates/xtask/src/manifests_test.rs b/crates/xtask/src/manifests_test.rs index 1b6a7067..55e3d171 100644 --- a/crates/xtask/src/manifests_test.rs +++ b/crates/xtask/src/manifests_test.rs @@ -126,3 +126,15 @@ fn desktop_and_ui_know_every_accent() { ); } } + +#[test] +fn icons_are_24px_current_color_line_icons() { + let icon = "market/demo/icon.svg"; + let good = + r#""#; + assert!(check_icon(icon, good).is_none()); + let tile = r##""##; + assert!(check_icon(icon, tile).is_some()); + let colored = r##""##; + assert!(check_icon(icon, colored).is_some()); +} diff --git a/docs/src/content/dev/plugin-development.en.md b/docs/src/content/dev/plugin-development.en.md index 488a701c..eb7d737b 100644 --- a/docs/src/content/dev/plugin-development.en.md +++ b/docs/src/content/dev/plugin-development.en.md @@ -9,6 +9,7 @@ A plugin has four parts and ships as an ed25519-signed `.tfp` file: - **manifest.json**: identity, permissions, functions and interface declarations. - **Rust backend**: compiled to a `wasm32-wasip2` component and run in the wasmtime sandbox. **All data processing happens here.** - **React user interface**: input and display only, no data processing. +- **icon.svg**: a 24×24 line icon drawn with `stroke="currentColor"`, without its own background or fixed colors; the tile color comes from `accent`, and `cargo xtask check rules` checks it. - **locales**: Chinese and English text for the interface, error messages and interface docs. ```text diff --git a/docs/src/content/dev/plugin-development.zh.md b/docs/src/content/dev/plugin-development.zh.md index d165acee..9dff8dc0 100644 --- a/docs/src/content/dev/plugin-development.zh.md +++ b/docs/src/content/dev/plugin-development.zh.md @@ -9,6 +9,7 @@ ToolForge 里的每个工具都是插件,包括随应用内置的工具。本 - **manifest.json**:插件的身份、权限、函数和接口声明。 - **Rust 后端**:编译为 `wasm32-wasip2` 组件,在 wasmtime 沙箱中运行。**所有数据处理都在这里完成**。 - **React 界面**:只负责输入和展示,不做数据处理。 +- **icon.svg**:24×24 的线性图标,使用 `stroke="currentColor"`、不带底色和固定颜色;底色由 `accent` 决定,`cargo xtask check rules` 会检查。 - **locales**:中英文文案。界面、错误信息和接口说明都从这里取。 ```text diff --git a/market/address-parser/icon.svg b/market/address-parser/icon.svg index 258be13f..3194a926 100644 --- a/market/address-parser/icon.svg +++ b/market/address-parser/icon.svg @@ -1,5 +1 @@ - - - - - + diff --git a/market/address-parser/manifest.json b/market/address-parser/manifest.json index 480f383d..c70e7ebd 100644 --- a/market/address-parser/manifest.json +++ b/market/address-parser/manifest.json @@ -1,6 +1,6 @@ { "id": "org.devlive.toolforge.address-parser", - "version": "0.1.0", + "version": "0.1.1", "name": "i18n:name", "description": "i18n:description", "category": "life", diff --git a/market/ambient-effects/icon.svg b/market/ambient-effects/icon.svg index 3031b30d..fba602ec 100644 --- a/market/ambient-effects/icon.svg +++ b/market/ambient-effects/icon.svg @@ -1,5 +1 @@ - - - - - + diff --git a/market/ambient-effects/manifest.json b/market/ambient-effects/manifest.json index f396ad9d..8ba1ff0f 100644 --- a/market/ambient-effects/manifest.json +++ b/market/ambient-effects/manifest.json @@ -1,6 +1,6 @@ { "id": "org.devlive.toolforge.ambient-effects", - "version": "0.1.0", + "version": "0.1.1", "name": "i18n:name", "description": "i18n:description", "category": "life", diff --git a/market/avro-inspector/icon.svg b/market/avro-inspector/icon.svg index 6168eb74..0dddbc0c 100644 --- a/market/avro-inspector/icon.svg +++ b/market/avro-inspector/icon.svg @@ -1,5 +1 @@ - - - - - + diff --git a/market/bead-pattern/icon.svg b/market/bead-pattern/icon.svg index 43e757dd..9ce23dbb 100644 --- a/market/bead-pattern/icon.svg +++ b/market/bead-pattern/icon.svg @@ -1,4 +1 @@ - - - - + diff --git a/market/bead-pattern/manifest.json b/market/bead-pattern/manifest.json index 08171937..87e8f847 100644 --- a/market/bead-pattern/manifest.json +++ b/market/bead-pattern/manifest.json @@ -1,6 +1,6 @@ { "id": "org.devlive.toolforge.bead-pattern", - "version": "0.1.0", + "version": "0.1.1", "name": "i18n:name", "description": "i18n:description", "category": "image", diff --git a/market/bingo-cards/icon.svg b/market/bingo-cards/icon.svg index 9863c6ea..54a3e45f 100644 --- a/market/bingo-cards/icon.svg +++ b/market/bingo-cards/icon.svg @@ -1,5 +1 @@ - - - - - + diff --git a/market/bingo-cards/manifest.json b/market/bingo-cards/manifest.json index 3ebc978d..b5fcac64 100644 --- a/market/bingo-cards/manifest.json +++ b/market/bingo-cards/manifest.json @@ -1,6 +1,6 @@ { "id": "org.devlive.toolforge.bingo-cards", - "version": "0.1.1", + "version": "0.1.2", "name": "i18n:name", "description": "i18n:description", "category": "life", diff --git a/market/chat-mockup/icon.svg b/market/chat-mockup/icon.svg index 258be13f..a284919f 100644 --- a/market/chat-mockup/icon.svg +++ b/market/chat-mockup/icon.svg @@ -1,5 +1 @@ - - - - - + diff --git a/market/chat-mockup/manifest.json b/market/chat-mockup/manifest.json index fb7a5f53..774fbc42 100644 --- a/market/chat-mockup/manifest.json +++ b/market/chat-mockup/manifest.json @@ -1,6 +1,6 @@ { "id": "org.devlive.toolforge.chat-mockup", - "version": "0.1.0", + "version": "0.1.1", "name": "i18n:name", "description": "i18n:description", "category": "image", diff --git a/market/css-generator/icon.svg b/market/css-generator/icon.svg index 258be13f..32079ac2 100644 --- a/market/css-generator/icon.svg +++ b/market/css-generator/icon.svg @@ -1,5 +1 @@ - - - - - + diff --git a/market/css-generator/manifest.json b/market/css-generator/manifest.json index 0080f842..278c4759 100644 --- a/market/css-generator/manifest.json +++ b/market/css-generator/manifest.json @@ -1,6 +1,6 @@ { "id": "org.devlive.toolforge.css-generator", - "version": "0.1.0", + "version": "0.1.1", "name": "i18n:name", "description": "i18n:description", "category": "dev", diff --git a/market/css-selector-inspector/icon.svg b/market/css-selector-inspector/icon.svg index 258be13f..03859833 100644 --- a/market/css-selector-inspector/icon.svg +++ b/market/css-selector-inspector/icon.svg @@ -1,5 +1 @@ - - - - - + diff --git a/market/css-selector-inspector/manifest.json b/market/css-selector-inspector/manifest.json index dd8788fc..1bed34a4 100644 --- a/market/css-selector-inspector/manifest.json +++ b/market/css-selector-inspector/manifest.json @@ -1,6 +1,6 @@ { "id": "org.devlive.toolforge.css-selector-inspector", - "version": "0.1.0", + "version": "0.1.1", "name": "i18n:name", "description": "i18n:description", "category": "dev", diff --git a/market/dep-graph/icon.svg b/market/dep-graph/icon.svg index b40cdf13..89c6eadc 100644 --- a/market/dep-graph/icon.svg +++ b/market/dep-graph/icon.svg @@ -1,5 +1 @@ - - - - - + diff --git a/market/dep-graph/manifest.json b/market/dep-graph/manifest.json index de42a3b9..c9eed822 100644 --- a/market/dep-graph/manifest.json +++ b/market/dep-graph/manifest.json @@ -1,6 +1,6 @@ { "id": "org.devlive.toolforge.dep-graph", - "version": "0.1.0", + "version": "0.1.1", "name": "i18n:name", "description": "i18n:description", "category": "dev", diff --git a/market/dev-directory/icon.svg b/market/dev-directory/icon.svg index e15c45d4..605bdffe 100644 --- a/market/dev-directory/icon.svg +++ b/market/dev-directory/icon.svg @@ -1,5 +1 @@ - - - - - + diff --git a/market/dev-directory/manifest.json b/market/dev-directory/manifest.json index cc7245ac..5a3a982c 100644 --- a/market/dev-directory/manifest.json +++ b/market/dev-directory/manifest.json @@ -1,6 +1,6 @@ { "id": "org.devlive.toolforge.dev-directory", - "version": "0.1.0", + "version": "0.1.1", "name": "i18n:name", "description": "i18n:description", "category": "dev", diff --git a/market/device-mockup/icon.svg b/market/device-mockup/icon.svg index 258be13f..f278ea1c 100644 --- a/market/device-mockup/icon.svg +++ b/market/device-mockup/icon.svg @@ -1,5 +1 @@ - - - - - + diff --git a/market/dockerfile-lint/icon.svg b/market/dockerfile-lint/icon.svg index 6168eb74..5e34c15e 100644 --- a/market/dockerfile-lint/icon.svg +++ b/market/dockerfile-lint/icon.svg @@ -1,5 +1 @@ - - - - - + diff --git a/market/dockerfile-lint/manifest.json b/market/dockerfile-lint/manifest.json index 2ad7e0da..7b0a4ed4 100644 --- a/market/dockerfile-lint/manifest.json +++ b/market/dockerfile-lint/manifest.json @@ -1,6 +1,6 @@ { "id": "org.devlive.toolforge.dockerfile-lint", - "version": "0.1.0", + "version": "0.1.1", "name": "i18n:name", "description": "i18n:description", "category": "dev", diff --git a/market/domain-toolbox/icon.svg b/market/domain-toolbox/icon.svg index 83719481..bdbd0f40 100644 --- a/market/domain-toolbox/icon.svg +++ b/market/domain-toolbox/icon.svg @@ -1,5 +1 @@ - - - - - + diff --git a/market/domain-toolbox/manifest.json b/market/domain-toolbox/manifest.json index c8e92d01..2bfa1d97 100644 --- a/market/domain-toolbox/manifest.json +++ b/market/domain-toolbox/manifest.json @@ -1,6 +1,6 @@ { "id": "org.devlive.toolforge.domain-toolbox", - "version": "0.1.0", + "version": "0.1.1", "name": "i18n:name", "description": "i18n:description", "category": "network", diff --git a/market/dynasty-timeline/icon.svg b/market/dynasty-timeline/icon.svg index cb2899d9..30c6399a 100644 --- a/market/dynasty-timeline/icon.svg +++ b/market/dynasty-timeline/icon.svg @@ -1,5 +1 @@ - - - - - + diff --git a/market/dynasty-timeline/manifest.json b/market/dynasty-timeline/manifest.json index bce578cc..24973be9 100644 --- a/market/dynasty-timeline/manifest.json +++ b/market/dynasty-timeline/manifest.json @@ -1,6 +1,6 @@ { "id": "org.devlive.toolforge.dynasty-timeline", - "version": "0.1.0", + "version": "0.1.1", "name": "i18n:name", "description": "i18n:description", "category": "other", diff --git a/market/festival-avatar/icon.svg b/market/festival-avatar/icon.svg index 258be13f..586c3d40 100644 --- a/market/festival-avatar/icon.svg +++ b/market/festival-avatar/icon.svg @@ -1,5 +1 @@ - - - - - + diff --git a/market/file-extension/icon.svg b/market/file-extension/icon.svg index 0384dcaf..add8db50 100644 --- a/market/file-extension/icon.svg +++ b/market/file-extension/icon.svg @@ -1,5 +1 @@ - - - - - + diff --git a/market/file-extension/manifest.json b/market/file-extension/manifest.json index 68fc9888..e0157d1c 100644 --- a/market/file-extension/manifest.json +++ b/market/file-extension/manifest.json @@ -1,6 +1,6 @@ { "id": "org.devlive.toolforge.file-extension", - "version": "0.1.0", + "version": "0.1.1", "name": "i18n:name", "description": "i18n:description", "category": "other", diff --git a/market/file-permission-inspector/icon.svg b/market/file-permission-inspector/icon.svg index 258be13f..419c53c5 100644 --- a/market/file-permission-inspector/icon.svg +++ b/market/file-permission-inspector/icon.svg @@ -1,5 +1 @@ - - - - - + diff --git a/market/file-permission-inspector/manifest.json b/market/file-permission-inspector/manifest.json index 2e5ce700..b26276f5 100644 --- a/market/file-permission-inspector/manifest.json +++ b/market/file-permission-inspector/manifest.json @@ -1,6 +1,6 @@ { "id": "org.devlive.toolforge.file-permission-inspector", - "version": "0.1.0", + "version": "0.1.1", "name": "i18n:name", "description": "i18n:description", "category": "dev", diff --git a/market/fortune-tarot/icon.svg b/market/fortune-tarot/icon.svg index a4ce8938..38b6a8d4 100644 --- a/market/fortune-tarot/icon.svg +++ b/market/fortune-tarot/icon.svg @@ -1,5 +1 @@ - - - - - + diff --git a/market/fortune-tarot/manifest.json b/market/fortune-tarot/manifest.json index 42bff892..74eeb531 100644 --- a/market/fortune-tarot/manifest.json +++ b/market/fortune-tarot/manifest.json @@ -1,6 +1,6 @@ { "id": "org.devlive.toolforge.fortune-tarot", - "version": "0.1.0", + "version": "0.1.1", "name": "i18n:name", "description": "i18n:description", "category": "life", diff --git a/market/geometry-calculator/icon.svg b/market/geometry-calculator/icon.svg index 04142d7d..2188f964 100644 --- a/market/geometry-calculator/icon.svg +++ b/market/geometry-calculator/icon.svg @@ -1,5 +1 @@ - - - - - + diff --git a/market/geometry-calculator/manifest.json b/market/geometry-calculator/manifest.json index 8892550f..dc1ab924 100644 --- a/market/geometry-calculator/manifest.json +++ b/market/geometry-calculator/manifest.json @@ -1,6 +1,6 @@ { "id": "org.devlive.toolforge.geometry-calculator", - "version": "0.1.0", + "version": "0.1.1", "name": "i18n:name", "description": "i18n:description", "category": "calc", diff --git a/market/git-hooks-manager/icon.svg b/market/git-hooks-manager/icon.svg index 258be13f..dde67aeb 100644 --- a/market/git-hooks-manager/icon.svg +++ b/market/git-hooks-manager/icon.svg @@ -1,5 +1 @@ - - - - - + diff --git a/market/git-hooks-manager/manifest.json b/market/git-hooks-manager/manifest.json index ac91f452..415ef2e4 100644 --- a/market/git-hooks-manager/manifest.json +++ b/market/git-hooks-manager/manifest.json @@ -1,6 +1,6 @@ { "id": "org.devlive.toolforge.git-hooks-manager", - "version": "0.1.0", + "version": "0.1.1", "name": "i18n:name", "description": "i18n:description", "category": "dev", diff --git a/market/hanzi-copybook/icon.svg b/market/hanzi-copybook/icon.svg index 0ffa485e..fc2a1115 100644 --- a/market/hanzi-copybook/icon.svg +++ b/market/hanzi-copybook/icon.svg @@ -1,5 +1 @@ - - - - - + diff --git a/market/hanzi-copybook/manifest.json b/market/hanzi-copybook/manifest.json index dd4cf540..8295bafe 100644 --- a/market/hanzi-copybook/manifest.json +++ b/market/hanzi-copybook/manifest.json @@ -1,6 +1,6 @@ { "id": "org.devlive.toolforge.hanzi-copybook", - "version": "0.1.0", + "version": "0.1.1", "name": "i18n:name", "description": "i18n:description", "category": "other", diff --git a/market/hanzi-pinyin/icon.svg b/market/hanzi-pinyin/icon.svg index 258be13f..61781d50 100644 --- a/market/hanzi-pinyin/icon.svg +++ b/market/hanzi-pinyin/icon.svg @@ -1,5 +1 @@ - - - - - + diff --git a/market/hanzi-pinyin/manifest.json b/market/hanzi-pinyin/manifest.json index ed130726..9be225ac 100644 --- a/market/hanzi-pinyin/manifest.json +++ b/market/hanzi-pinyin/manifest.json @@ -1,6 +1,6 @@ { "id": "org.devlive.toolforge.hanzi-pinyin", - "version": "0.1.0", + "version": "0.1.1", "name": "i18n:name", "description": "i18n:description", "category": "text", diff --git a/market/health-calculator/icon.svg b/market/health-calculator/icon.svg index 387c3799..c3b13ab1 100644 --- a/market/health-calculator/icon.svg +++ b/market/health-calculator/icon.svg @@ -1,5 +1 @@ - - - - - + diff --git a/market/health-calculator/manifest.json b/market/health-calculator/manifest.json index bcd1a646..4dda4318 100644 --- a/market/health-calculator/manifest.json +++ b/market/health-calculator/manifest.json @@ -1,6 +1,6 @@ { "id": "org.devlive.toolforge.health-calculator", - "version": "0.1.0", + "version": "0.1.1", "name": "i18n:name", "description": "i18n:description", "category": "calc", diff --git a/market/icu-lint/icon.svg b/market/icu-lint/icon.svg index d965bd2e..f8ec9685 100644 --- a/market/icu-lint/icon.svg +++ b/market/icu-lint/icon.svg @@ -1,5 +1 @@ - - - - - + diff --git a/market/icu-lint/manifest.json b/market/icu-lint/manifest.json index dcf49ef0..9122ea49 100644 --- a/market/icu-lint/manifest.json +++ b/market/icu-lint/manifest.json @@ -1,6 +1,6 @@ { "id": "org.devlive.toolforge.icu-lint", - "version": "0.1.1", + "version": "0.1.2", "name": "i18n:name", "description": "i18n:description", "category": "dev", diff --git a/market/id-photo-maker/icon.svg b/market/id-photo-maker/icon.svg index 258be13f..b161de10 100644 --- a/market/id-photo-maker/icon.svg +++ b/market/id-photo-maker/icon.svg @@ -1,5 +1 @@ - - - - - + diff --git a/market/idiom-reference/icon.svg b/market/idiom-reference/icon.svg index 258be13f..49938273 100644 --- a/market/idiom-reference/icon.svg +++ b/market/idiom-reference/icon.svg @@ -1,5 +1 @@ - - - - - + diff --git a/market/idiom-reference/manifest.json b/market/idiom-reference/manifest.json index 4109f72f..6b3ac5e1 100644 --- a/market/idiom-reference/manifest.json +++ b/market/idiom-reference/manifest.json @@ -1,6 +1,6 @@ { "id": "org.devlive.toolforge.idiom-reference", - "version": "0.1.0", + "version": "0.1.1", "name": "i18n:name", "description": "i18n:description", "category": "text", diff --git a/market/invoice-assistant/icon.svg b/market/invoice-assistant/icon.svg index 0b6497a1..d787b892 100644 --- a/market/invoice-assistant/icon.svg +++ b/market/invoice-assistant/icon.svg @@ -1,5 +1 @@ - - - - - + diff --git a/market/invoice-assistant/manifest.json b/market/invoice-assistant/manifest.json index 58edd2ad..0dc1ff6e 100644 --- a/market/invoice-assistant/manifest.json +++ b/market/invoice-assistant/manifest.json @@ -1,6 +1,6 @@ { "id": "org.devlive.toolforge.invoice-assistant", - "version": "0.1.1", + "version": "0.1.2", "name": "i18n:name", "description": "i18n:description", "category": "calc", diff --git a/market/js-minify-beautify/icon.svg b/market/js-minify-beautify/icon.svg index 258be13f..4c6a9ac1 100644 --- a/market/js-minify-beautify/icon.svg +++ b/market/js-minify-beautify/icon.svg @@ -1,5 +1 @@ - - - - - + diff --git a/market/js-minify-beautify/manifest.json b/market/js-minify-beautify/manifest.json index ce87a7bf..19e36f80 100644 --- a/market/js-minify-beautify/manifest.json +++ b/market/js-minify-beautify/manifest.json @@ -1,6 +1,6 @@ { "id": "org.devlive.toolforge.js-minify-beautify", - "version": "0.1.0", + "version": "0.1.1", "name": "i18n:name", "description": "i18n:description", "category": "dev", diff --git a/market/keyword-density/icon.svg b/market/keyword-density/icon.svg index 856eb6b1..1634d2a8 100644 --- a/market/keyword-density/icon.svg +++ b/market/keyword-density/icon.svg @@ -1,5 +1 @@ - - - - - + diff --git a/market/keyword-density/manifest.json b/market/keyword-density/manifest.json index b7633a0b..e0cbb420 100644 --- a/market/keyword-density/manifest.json +++ b/market/keyword-density/manifest.json @@ -1,6 +1,6 @@ { "id": "org.devlive.toolforge.keyword-density", - "version": "0.1.0", + "version": "0.1.1", "name": "i18n:name", "description": "i18n:description", "category": "dev", diff --git a/market/kinship-calculator/icon.svg b/market/kinship-calculator/icon.svg index bffdd055..6904d92c 100644 --- a/market/kinship-calculator/icon.svg +++ b/market/kinship-calculator/icon.svg @@ -1,5 +1 @@ - - - - - + diff --git a/market/kinship-calculator/manifest.json b/market/kinship-calculator/manifest.json index 997b1530..b8caa896 100644 --- a/market/kinship-calculator/manifest.json +++ b/market/kinship-calculator/manifest.json @@ -1,6 +1,6 @@ { "id": "org.devlive.toolforge.kinship-calculator", - "version": "0.1.0", + "version": "0.1.1", "name": "i18n:name", "description": "i18n:description", "category": "dev", diff --git a/market/license-plate/icon.svg b/market/license-plate/icon.svg index 258be13f..d8b82227 100644 --- a/market/license-plate/icon.svg +++ b/market/license-plate/icon.svg @@ -1,5 +1 @@ - - - - - + diff --git a/market/license-plate/manifest.json b/market/license-plate/manifest.json index ee19abf4..defbbfbd 100644 --- a/market/license-plate/manifest.json +++ b/market/license-plate/manifest.json @@ -1,6 +1,6 @@ { "id": "org.devlive.toolforge.license-plate", - "version": "0.1.0", + "version": "0.1.1", "name": "i18n:name", "description": "i18n:description", "category": "dev", diff --git a/market/meme-composer/icon.svg b/market/meme-composer/icon.svg index c8f822e1..c62f2474 100644 --- a/market/meme-composer/icon.svg +++ b/market/meme-composer/icon.svg @@ -1,4 +1 @@ - - - - + diff --git a/market/meme-composer/manifest.json b/market/meme-composer/manifest.json index efbfee89..9257dd9a 100644 --- a/market/meme-composer/manifest.json +++ b/market/meme-composer/manifest.json @@ -1,6 +1,6 @@ { "id": "org.devlive.toolforge.meme-composer", - "version": "0.1.0", + "version": "0.1.1", "name": "i18n:name", "description": "i18n:description", "category": "image", diff --git a/market/meta-tags/icon.svg b/market/meta-tags/icon.svg index a5e53de3..0f4d8245 100644 --- a/market/meta-tags/icon.svg +++ b/market/meta-tags/icon.svg @@ -1,5 +1 @@ - - - - - + diff --git a/market/meta-tags/manifest.json b/market/meta-tags/manifest.json index 048daeb8..11939136 100644 --- a/market/meta-tags/manifest.json +++ b/market/meta-tags/manifest.json @@ -1,6 +1,6 @@ { "id": "org.devlive.toolforge.meta-tags", - "version": "0.1.0", + "version": "0.1.1", "name": "i18n:name", "description": "i18n:description", "category": "dev", diff --git a/market/metronome/icon.svg b/market/metronome/icon.svg index 258be13f..b0c64933 100644 --- a/market/metronome/icon.svg +++ b/market/metronome/icon.svg @@ -1,5 +1 @@ - - - - - + diff --git a/market/metronome/manifest.json b/market/metronome/manifest.json index 322ab139..09a8e130 100644 --- a/market/metronome/manifest.json +++ b/market/metronome/manifest.json @@ -1,6 +1,6 @@ { "id": "org.devlive.toolforge.metronome", - "version": "0.1.0", + "version": "0.1.1", "name": "i18n:name", "description": "i18n:description", "category": "life", diff --git a/market/mini-instrument/icon.svg b/market/mini-instrument/icon.svg index 6f3eba46..2d63f597 100644 --- a/market/mini-instrument/icon.svg +++ b/market/mini-instrument/icon.svg @@ -1,5 +1 @@ - - - - - + diff --git a/market/mini-instrument/manifest.json b/market/mini-instrument/manifest.json index 6ce10542..94bfe755 100644 --- a/market/mini-instrument/manifest.json +++ b/market/mini-instrument/manifest.json @@ -1,6 +1,6 @@ { "id": "org.devlive.toolforge.mini-instrument", - "version": "0.1.0", + "version": "0.1.1", "name": "i18n:name", "description": "i18n:description", "category": "life", diff --git a/market/name-generator/icon.svg b/market/name-generator/icon.svg index 258be13f..90b1a024 100644 --- a/market/name-generator/icon.svg +++ b/market/name-generator/icon.svg @@ -1,5 +1 @@ - - - - - + diff --git a/market/name-generator/manifest.json b/market/name-generator/manifest.json index 2d2b79cf..a4a88ac7 100644 --- a/market/name-generator/manifest.json +++ b/market/name-generator/manifest.json @@ -1,6 +1,6 @@ { "id": "org.devlive.toolforge.name-generator", - "version": "0.1.0", + "version": "0.1.1", "name": "i18n:name", "description": "i18n:description", "category": "life", diff --git a/market/native-deps-inspector/icon.svg b/market/native-deps-inspector/icon.svg index 258be13f..e55f28e7 100644 --- a/market/native-deps-inspector/icon.svg +++ b/market/native-deps-inspector/icon.svg @@ -1,5 +1 @@ - - - - - + diff --git a/market/nginx-config-generator/icon.svg b/market/nginx-config-generator/icon.svg index af9a19c1..236b1750 100644 --- a/market/nginx-config-generator/icon.svg +++ b/market/nginx-config-generator/icon.svg @@ -1,5 +1 @@ - - - - - + diff --git a/market/nginx-config-generator/manifest.json b/market/nginx-config-generator/manifest.json index e4139227..7c8ca3f7 100644 --- a/market/nginx-config-generator/manifest.json +++ b/market/nginx-config-generator/manifest.json @@ -1,6 +1,6 @@ { "id": "org.devlive.toolforge.nginx-config-generator", - "version": "0.1.0", + "version": "0.1.1", "name": "i18n:name", "description": "i18n:description", "category": "dev", diff --git a/market/nginx-log-analyzer/icon.svg b/market/nginx-log-analyzer/icon.svg index 6f3eba46..08f440f1 100644 --- a/market/nginx-log-analyzer/icon.svg +++ b/market/nginx-log-analyzer/icon.svg @@ -1,5 +1 @@ - - - - - + diff --git a/market/nginx-log-analyzer/manifest.json b/market/nginx-log-analyzer/manifest.json index bf36f151..f9e1e329 100644 --- a/market/nginx-log-analyzer/manifest.json +++ b/market/nginx-log-analyzer/manifest.json @@ -1,6 +1,6 @@ { "id": "org.devlive.toolforge.nginx-log-analyzer", - "version": "0.1.0", + "version": "0.1.1", "name": "i18n:name", "description": "i18n:description", "category": "dev", diff --git a/market/package-entry-resolver/icon.svg b/market/package-entry-resolver/icon.svg index 6eea6281..c9a513b8 100644 --- a/market/package-entry-resolver/icon.svg +++ b/market/package-entry-resolver/icon.svg @@ -1,5 +1 @@ - - - - - + diff --git a/market/package-entry-resolver/manifest.json b/market/package-entry-resolver/manifest.json index 255c137b..2b779c13 100644 --- a/market/package-entry-resolver/manifest.json +++ b/market/package-entry-resolver/manifest.json @@ -1,6 +1,6 @@ { "id": "org.devlive.toolforge.package-entry-resolver", - "version": "0.1.0", + "version": "0.1.1", "name": "i18n:name", "description": "i18n:description", "category": "dev", diff --git a/market/paper-box-templates/icon.svg b/market/paper-box-templates/icon.svg index 183e50b0..3f643e34 100644 --- a/market/paper-box-templates/icon.svg +++ b/market/paper-box-templates/icon.svg @@ -1,5 +1 @@ - - - - - + diff --git a/market/paper-box-templates/manifest.json b/market/paper-box-templates/manifest.json index ac866049..dd92afa1 100644 --- a/market/paper-box-templates/manifest.json +++ b/market/paper-box-templates/manifest.json @@ -1,6 +1,6 @@ { "id": "org.devlive.toolforge.paper-box-templates", - "version": "0.1.1", + "version": "0.1.2", "name": "i18n:name", "description": "i18n:description", "category": "other", diff --git a/market/paper-size/icon.svg b/market/paper-size/icon.svg index 574218f3..450aa381 100644 --- a/market/paper-size/icon.svg +++ b/market/paper-size/icon.svg @@ -1,5 +1 @@ - - - - - + diff --git a/market/paper-size/manifest.json b/market/paper-size/manifest.json index 3e627c61..71f610cb 100644 --- a/market/paper-size/manifest.json +++ b/market/paper-size/manifest.json @@ -1,6 +1,6 @@ { "id": "org.devlive.toolforge.paper-size", - "version": "0.1.0", + "version": "0.1.1", "name": "i18n:name", "description": "i18n:description", "category": "other", diff --git a/market/parquet-inspector/icon.svg b/market/parquet-inspector/icon.svg index 258be13f..af0e2e4c 100644 --- a/market/parquet-inspector/icon.svg +++ b/market/parquet-inspector/icon.svg @@ -1,5 +1 @@ - - - - - + diff --git a/market/parquet-inspector/manifest.json b/market/parquet-inspector/manifest.json index 4f5e2c67..414fb3e2 100644 --- a/market/parquet-inspector/manifest.json +++ b/market/parquet-inspector/manifest.json @@ -1,6 +1,6 @@ { "id": "org.devlive.toolforge.parquet-inspector", - "version": "0.1.0", + "version": "0.1.1", "name": "i18n:name", "description": "i18n:description", "category": "dev", diff --git a/market/pcap-viewer/icon.svg b/market/pcap-viewer/icon.svg index 1f0170ba..d06d31f8 100644 --- a/market/pcap-viewer/icon.svg +++ b/market/pcap-viewer/icon.svg @@ -1,4 +1 @@ - - - - + diff --git a/market/pcap-viewer/manifest.json b/market/pcap-viewer/manifest.json index 01308725..3e88f184 100644 --- a/market/pcap-viewer/manifest.json +++ b/market/pcap-viewer/manifest.json @@ -1,6 +1,6 @@ { "id": "org.devlive.toolforge.pcap-viewer", - "version": "0.1.0", + "version": "0.1.1", "name": "i18n:name", "description": "i18n:description", "category": "network", diff --git a/market/periodic-table/icon.svg b/market/periodic-table/icon.svg index 258be13f..c0bf0ec4 100644 --- a/market/periodic-table/icon.svg +++ b/market/periodic-table/icon.svg @@ -1,5 +1 @@ - - - - - + diff --git a/market/periodic-table/manifest.json b/market/periodic-table/manifest.json index 94a63d7f..b44e3629 100644 --- a/market/periodic-table/manifest.json +++ b/market/periodic-table/manifest.json @@ -1,6 +1,6 @@ { "id": "org.devlive.toolforge.periodic-table", - "version": "0.1.0", + "version": "0.1.1", "name": "i18n:name", "description": "i18n:description", "category": "dev", diff --git a/market/phone-region-lookup/icon.svg b/market/phone-region-lookup/icon.svg index 258be13f..659f192b 100644 --- a/market/phone-region-lookup/icon.svg +++ b/market/phone-region-lookup/icon.svg @@ -1,5 +1 @@ - - - - - + diff --git a/market/phone-region-lookup/manifest.json b/market/phone-region-lookup/manifest.json index 2e238b5a..84de0702 100644 --- a/market/phone-region-lookup/manifest.json +++ b/market/phone-region-lookup/manifest.json @@ -1,6 +1,6 @@ { "id": "org.devlive.toolforge.phone-region-lookup", - "version": "0.1.0", + "version": "0.1.1", "name": "i18n:name", "description": "i18n:description", "category": "life", diff --git a/market/physics-calculator/icon.svg b/market/physics-calculator/icon.svg index 9a215811..17ddf89a 100644 --- a/market/physics-calculator/icon.svg +++ b/market/physics-calculator/icon.svg @@ -1,5 +1 @@ - - - - - + diff --git a/market/physics-calculator/manifest.json b/market/physics-calculator/manifest.json index c5cd214c..c803e5c8 100644 --- a/market/physics-calculator/manifest.json +++ b/market/physics-calculator/manifest.json @@ -1,6 +1,6 @@ { "id": "org.devlive.toolforge.physics-calculator", - "version": "0.1.1", + "version": "0.1.2", "name": "i18n:name", "description": "i18n:description", "category": "calc", diff --git a/market/postal-lookup/icon.svg b/market/postal-lookup/icon.svg index 6f3eba46..9b1b24cd 100644 --- a/market/postal-lookup/icon.svg +++ b/market/postal-lookup/icon.svg @@ -1,5 +1 @@ - - - - - + diff --git a/market/postal-lookup/manifest.json b/market/postal-lookup/manifest.json index 45d45512..c097d007 100644 --- a/market/postal-lookup/manifest.json +++ b/market/postal-lookup/manifest.json @@ -1,6 +1,6 @@ { "id": "org.devlive.toolforge.postal-lookup", - "version": "0.1.0", + "version": "0.1.1", "name": "i18n:name", "description": "i18n:description", "category": "dev", diff --git a/market/pour-over-coffee/icon.svg b/market/pour-over-coffee/icon.svg index 8e672c0b..844bbfa7 100644 --- a/market/pour-over-coffee/icon.svg +++ b/market/pour-over-coffee/icon.svg @@ -1,5 +1 @@ - - - - - + diff --git a/market/pour-over-coffee/manifest.json b/market/pour-over-coffee/manifest.json index 28282de3..373de1d7 100644 --- a/market/pour-over-coffee/manifest.json +++ b/market/pour-over-coffee/manifest.json @@ -1,6 +1,6 @@ { "id": "org.devlive.toolforge.pour-over-coffee", - "version": "0.1.1", + "version": "0.1.2", "name": "i18n:name", "description": "i18n:description", "category": "life", diff --git a/market/reaction-challenge/icon.svg b/market/reaction-challenge/icon.svg index 856eb6b1..ddfb9190 100644 --- a/market/reaction-challenge/icon.svg +++ b/market/reaction-challenge/icon.svg @@ -1,5 +1 @@ - - - - - + diff --git a/market/reaction-challenge/manifest.json b/market/reaction-challenge/manifest.json index d87eb111..62f8226f 100644 --- a/market/reaction-challenge/manifest.json +++ b/market/reaction-challenge/manifest.json @@ -1,6 +1,6 @@ { "id": "org.devlive.toolforge.reaction-challenge", - "version": "0.1.0", + "version": "0.1.1", "name": "i18n:name", "description": "i18n:description", "category": "life", diff --git a/market/redirect-map/icon.svg b/market/redirect-map/icon.svg index 3031b30d..bd0e492c 100644 --- a/market/redirect-map/icon.svg +++ b/market/redirect-map/icon.svg @@ -1,5 +1 @@ - - - - - + diff --git a/market/redirect-map/manifest.json b/market/redirect-map/manifest.json index ba44c0a1..33966677 100644 --- a/market/redirect-map/manifest.json +++ b/market/redirect-map/manifest.json @@ -1,6 +1,6 @@ { "id": "org.devlive.toolforge.redirect-map", - "version": "0.1.1", + "version": "0.1.2", "name": "i18n:name", "description": "i18n:description", "category": "dev", diff --git a/market/rewrite-converter/icon.svg b/market/rewrite-converter/icon.svg index 9863c6ea..096b4480 100644 --- a/market/rewrite-converter/icon.svg +++ b/market/rewrite-converter/icon.svg @@ -1,5 +1 @@ - - - - - + diff --git a/market/rewrite-converter/manifest.json b/market/rewrite-converter/manifest.json index eb730794..f342996b 100644 --- a/market/rewrite-converter/manifest.json +++ b/market/rewrite-converter/manifest.json @@ -1,6 +1,6 @@ { "id": "org.devlive.toolforge.rewrite-converter", - "version": "0.1.0", + "version": "0.1.1", "name": "i18n:name", "description": "i18n:description", "category": "dev", diff --git a/market/robots-sitemap/icon.svg b/market/robots-sitemap/icon.svg index af9a19c1..56940a9b 100644 --- a/market/robots-sitemap/icon.svg +++ b/market/robots-sitemap/icon.svg @@ -1,5 +1 @@ - - - - - + diff --git a/market/robots-sitemap/manifest.json b/market/robots-sitemap/manifest.json index 55f6874a..f2b6ed6d 100644 --- a/market/robots-sitemap/manifest.json +++ b/market/robots-sitemap/manifest.json @@ -1,6 +1,6 @@ { "id": "org.devlive.toolforge.robots-sitemap", - "version": "0.1.1", + "version": "0.1.2", "name": "i18n:name", "description": "i18n:description", "category": "dev", diff --git a/market/saml-inspector/icon.svg b/market/saml-inspector/icon.svg index 258be13f..09f0adc7 100644 --- a/market/saml-inspector/icon.svg +++ b/market/saml-inspector/icon.svg @@ -1,5 +1 @@ - - - - - + diff --git a/market/saml-inspector/manifest.json b/market/saml-inspector/manifest.json index c8e218bf..486bead4 100644 --- a/market/saml-inspector/manifest.json +++ b/market/saml-inspector/manifest.json @@ -1,6 +1,6 @@ { "id": "org.devlive.toolforge.saml-inspector", - "version": "0.1.0", + "version": "0.1.1", "name": "i18n:name", "description": "i18n:description", "category": "dev", diff --git a/market/scratch-calculator/icon.svg b/market/scratch-calculator/icon.svg index 58f58d29..fbf01941 100644 --- a/market/scratch-calculator/icon.svg +++ b/market/scratch-calculator/icon.svg @@ -1,12 +1 @@ - - - - - - - - - - - - + diff --git a/market/scratch-calculator/manifest.json b/market/scratch-calculator/manifest.json index c34cf20a..63050725 100644 --- a/market/scratch-calculator/manifest.json +++ b/market/scratch-calculator/manifest.json @@ -1,6 +1,6 @@ { "id": "org.devlive.toolforge.scratch-calculator", - "version": "0.1.2", + "version": "0.1.3", "name": "i18n:name", "description": "i18n:description", "category": "calc", diff --git a/market/seal-designer/icon.svg b/market/seal-designer/icon.svg index faefd1ae..f523c907 100644 --- a/market/seal-designer/icon.svg +++ b/market/seal-designer/icon.svg @@ -1,4 +1 @@ - - - - + diff --git a/market/seal-designer/manifest.json b/market/seal-designer/manifest.json index 5802dfc4..2f421eeb 100644 --- a/market/seal-designer/manifest.json +++ b/market/seal-designer/manifest.json @@ -1,6 +1,6 @@ { "id": "org.devlive.toolforge.seal-designer", - "version": "0.1.0", + "version": "0.1.1", "name": "i18n:name", "description": "i18n:description", "category": "image", diff --git a/market/seo-auditor/icon.svg b/market/seo-auditor/icon.svg index a5e53de3..a78434b2 100644 --- a/market/seo-auditor/icon.svg +++ b/market/seo-auditor/icon.svg @@ -1,5 +1 @@ - - - - - + diff --git a/market/seo-auditor/manifest.json b/market/seo-auditor/manifest.json index 767a185e..47338929 100644 --- a/market/seo-auditor/manifest.json +++ b/market/seo-auditor/manifest.json @@ -1,6 +1,6 @@ { "id": "org.devlive.toolforge.seo-auditor", - "version": "0.1.0", + "version": "0.1.1", "name": "i18n:name", "description": "i18n:description", "category": "dev", diff --git a/market/shortcut-cheatsheet/icon.svg b/market/shortcut-cheatsheet/icon.svg index 69310b8f..701426c1 100644 --- a/market/shortcut-cheatsheet/icon.svg +++ b/market/shortcut-cheatsheet/icon.svg @@ -1,5 +1 @@ - - - - - + diff --git a/market/shortcut-cheatsheet/manifest.json b/market/shortcut-cheatsheet/manifest.json index 1409e75f..f437e439 100644 --- a/market/shortcut-cheatsheet/manifest.json +++ b/market/shortcut-cheatsheet/manifest.json @@ -1,6 +1,6 @@ { "id": "org.devlive.toolforge.shortcut-cheatsheet", - "version": "0.1.0", + "version": "0.1.1", "name": "i18n:name", "description": "i18n:description", "category": "dev", diff --git a/market/stargazing-guide/icon.svg b/market/stargazing-guide/icon.svg index 9fb05e3e..91eab52c 100644 --- a/market/stargazing-guide/icon.svg +++ b/market/stargazing-guide/icon.svg @@ -1,5 +1 @@ - - - - - + diff --git a/market/stargazing-guide/manifest.json b/market/stargazing-guide/manifest.json index 2695aee3..10f626a2 100644 --- a/market/stargazing-guide/manifest.json +++ b/market/stargazing-guide/manifest.json @@ -1,6 +1,6 @@ { "id": "org.devlive.toolforge.stargazing-guide", - "version": "0.1.0", + "version": "0.1.1", "name": "i18n:name", "description": "i18n:description", "category": "life", diff --git a/market/sudoku/icon.svg b/market/sudoku/icon.svg index 617d7989..e9c41cb7 100644 --- a/market/sudoku/icon.svg +++ b/market/sudoku/icon.svg @@ -1,5 +1 @@ - - - - - + diff --git a/market/sudoku/manifest.json b/market/sudoku/manifest.json index 9e9e0fb5..7c174b60 100644 --- a/market/sudoku/manifest.json +++ b/market/sudoku/manifest.json @@ -1,6 +1,6 @@ { "id": "org.devlive.toolforge.sudoku", - "version": "0.1.0", + "version": "0.1.1", "name": "i18n:name", "description": "i18n:description", "category": "life", diff --git a/market/symmetry-drawing/icon.svg b/market/symmetry-drawing/icon.svg index a5e53de3..e3bf588e 100644 --- a/market/symmetry-drawing/icon.svg +++ b/market/symmetry-drawing/icon.svg @@ -1,5 +1 @@ - - - - - + diff --git a/market/symmetry-drawing/manifest.json b/market/symmetry-drawing/manifest.json index 36328b07..d731266c 100644 --- a/market/symmetry-drawing/manifest.json +++ b/market/symmetry-drawing/manifest.json @@ -1,6 +1,6 @@ { "id": "org.devlive.toolforge.symmetry-drawing", - "version": "0.1.1", + "version": "0.1.2", "name": "i18n:name", "description": "i18n:description", "category": "image", diff --git a/market/tangram-studio/icon.svg b/market/tangram-studio/icon.svg index 73aa198d..f71c6732 100644 --- a/market/tangram-studio/icon.svg +++ b/market/tangram-studio/icon.svg @@ -1,4 +1 @@ - - - - + diff --git a/market/tangram-studio/manifest.json b/market/tangram-studio/manifest.json index 89d8ebd0..52df6706 100644 --- a/market/tangram-studio/manifest.json +++ b/market/tangram-studio/manifest.json @@ -1,6 +1,6 @@ { "id": "org.devlive.toolforge.tangram-studio", - "version": "0.1.1", + "version": "0.1.2", "name": "i18n:name", "description": "i18n:description", "category": "life", diff --git a/market/token-counter/icon.svg b/market/token-counter/icon.svg index 5398dffd..11577b07 100644 --- a/market/token-counter/icon.svg +++ b/market/token-counter/icon.svg @@ -1,5 +1 @@ - - - - - + diff --git a/market/token-counter/manifest.json b/market/token-counter/manifest.json index d2096a10..522f8a9d 100644 --- a/market/token-counter/manifest.json +++ b/market/token-counter/manifest.json @@ -1,6 +1,6 @@ { "id": "org.devlive.toolforge.token-counter", - "version": "0.1.0", + "version": "0.1.1", "name": "i18n:name", "description": "i18n:description", "category": "calc", diff --git a/market/torrent-analyzer/icon.svg b/market/torrent-analyzer/icon.svg index b40cdf13..d07f1c0f 100644 --- a/market/torrent-analyzer/icon.svg +++ b/market/torrent-analyzer/icon.svg @@ -1,5 +1 @@ - - - - - + diff --git a/market/torrent-analyzer/manifest.json b/market/torrent-analyzer/manifest.json index cddb7969..9d525f45 100644 --- a/market/torrent-analyzer/manifest.json +++ b/market/torrent-analyzer/manifest.json @@ -1,6 +1,6 @@ { "id": "org.devlive.toolforge.torrent-analyzer", - "version": "0.1.0", + "version": "0.1.1", "name": "i18n:name", "description": "i18n:description", "category": "dev", diff --git a/market/trace-viewer/icon.svg b/market/trace-viewer/icon.svg index 3c1dae4b..ba9b2c51 100644 --- a/market/trace-viewer/icon.svg +++ b/market/trace-viewer/icon.svg @@ -1,4 +1 @@ - - - - + diff --git a/market/trace-viewer/manifest.json b/market/trace-viewer/manifest.json index 6e00401e..a1d7ea01 100644 --- a/market/trace-viewer/manifest.json +++ b/market/trace-viewer/manifest.json @@ -1,6 +1,6 @@ { "id": "org.devlive.toolforge.trace-viewer", - "version": "0.1.0", + "version": "0.1.1", "name": "i18n:name", "description": "i18n:description", "category": "dev", diff --git a/market/undercover-host/icon.svg b/market/undercover-host/icon.svg index bffdd055..bf70c331 100644 --- a/market/undercover-host/icon.svg +++ b/market/undercover-host/icon.svg @@ -1,5 +1 @@ - - - - - + diff --git a/market/undercover-host/manifest.json b/market/undercover-host/manifest.json index 1ff8744e..61818ae9 100644 --- a/market/undercover-host/manifest.json +++ b/market/undercover-host/manifest.json @@ -1,6 +1,6 @@ { "id": "org.devlive.toolforge.undercover-host", - "version": "0.1.1", + "version": "0.1.2", "name": "i18n:name", "description": "i18n:description", "category": "life", diff --git a/market/url-rewrite-generator/icon.svg b/market/url-rewrite-generator/icon.svg index 258be13f..8203c464 100644 --- a/market/url-rewrite-generator/icon.svg +++ b/market/url-rewrite-generator/icon.svg @@ -1,5 +1 @@ - - - - - + diff --git a/market/url-rewrite-generator/manifest.json b/market/url-rewrite-generator/manifest.json index 991f8063..41801fb1 100644 --- a/market/url-rewrite-generator/manifest.json +++ b/market/url-rewrite-generator/manifest.json @@ -1,6 +1,6 @@ { "id": "org.devlive.toolforge.url-rewrite-generator", - "version": "0.1.0", + "version": "0.1.1", "name": "i18n:name", "description": "i18n:description", "category": "dev", diff --git a/market/verse-checker/icon.svg b/market/verse-checker/icon.svg index 258be13f..2ad5d5d9 100644 --- a/market/verse-checker/icon.svg +++ b/market/verse-checker/icon.svg @@ -1,5 +1 @@ - - - - - + diff --git a/market/verse-checker/manifest.json b/market/verse-checker/manifest.json index 78ea814f..838637bb 100644 --- a/market/verse-checker/manifest.json +++ b/market/verse-checker/manifest.json @@ -1,6 +1,6 @@ { "id": "org.devlive.toolforge.verse-checker", - "version": "0.1.0", + "version": "0.1.1", "name": "i18n:name", "description": "i18n:description", "category": "text", diff --git a/market/vertical-stationery/icon.svg b/market/vertical-stationery/icon.svg index 9d82adee..2afbad24 100644 --- a/market/vertical-stationery/icon.svg +++ b/market/vertical-stationery/icon.svg @@ -1,4 +1 @@ - - - - + diff --git a/market/vertical-stationery/manifest.json b/market/vertical-stationery/manifest.json index 28987112..744301f2 100644 --- a/market/vertical-stationery/manifest.json +++ b/market/vertical-stationery/manifest.json @@ -1,6 +1,6 @@ { "id": "org.devlive.toolforge.vertical-stationery", - "version": "0.1.0", + "version": "0.1.1", "name": "i18n:name", "description": "i18n:description", "category": "image", diff --git a/market/wardrobe-journal/icon.svg b/market/wardrobe-journal/icon.svg index c13ba4d0..7b6c16ea 100644 --- a/market/wardrobe-journal/icon.svg +++ b/market/wardrobe-journal/icon.svg @@ -1,4 +1 @@ - - - - + diff --git a/market/wardrobe-journal/manifest.json b/market/wardrobe-journal/manifest.json index dc19269a..cfb73bd9 100644 --- a/market/wardrobe-journal/manifest.json +++ b/market/wardrobe-journal/manifest.json @@ -1,6 +1,6 @@ { "id": "org.devlive.toolforge.wardrobe-journal", - "version": "0.1.1", + "version": "0.1.2", "name": "i18n:name", "description": "i18n:description", "category": "life", diff --git a/market/weekly-menu/icon.svg b/market/weekly-menu/icon.svg index ec8bedbf..cebb6eb6 100644 --- a/market/weekly-menu/icon.svg +++ b/market/weekly-menu/icon.svg @@ -1,4 +1 @@ - - - - + diff --git a/market/weekly-menu/manifest.json b/market/weekly-menu/manifest.json index 905de9b7..e6ce3ec5 100644 --- a/market/weekly-menu/manifest.json +++ b/market/weekly-menu/manifest.json @@ -1,6 +1,6 @@ { "id": "org.devlive.toolforge.weekly-menu", - "version": "0.1.1", + "version": "0.1.2", "name": "i18n:name", "description": "i18n:description", "category": "life", diff --git a/market/workflow-dag/icon.svg b/market/workflow-dag/icon.svg index d965bd2e..ef82c7c9 100644 --- a/market/workflow-dag/icon.svg +++ b/market/workflow-dag/icon.svg @@ -1,5 +1 @@ - - - - - + diff --git a/market/workflow-dag/manifest.json b/market/workflow-dag/manifest.json index 762daf8a..d96c027e 100644 --- a/market/workflow-dag/manifest.json +++ b/market/workflow-dag/manifest.json @@ -1,6 +1,6 @@ { "id": "org.devlive.toolforge.workflow-dag", - "version": "0.1.0", + "version": "0.1.1", "name": "i18n:name", "description": "i18n:description", "category": "dev", diff --git a/market/world-geography/icon.svg b/market/world-geography/icon.svg index b7bc23f7..f0f654b8 100644 --- a/market/world-geography/icon.svg +++ b/market/world-geography/icon.svg @@ -1,5 +1 @@ - - - - - + diff --git a/market/world-geography/manifest.json b/market/world-geography/manifest.json index 3c4afa3a..782159d2 100644 --- a/market/world-geography/manifest.json +++ b/market/world-geography/manifest.json @@ -1,6 +1,6 @@ { "id": "org.devlive.toolforge.world-geography", - "version": "0.1.0", + "version": "0.1.1", "name": "i18n:name", "description": "i18n:description", "category": "other", diff --git a/plugins/proxy-inspector/icon.svg b/plugins/proxy-inspector/icon.svg index 397df8a5..1142462a 100644 --- a/plugins/proxy-inspector/icon.svg +++ b/plugins/proxy-inspector/icon.svg @@ -1,8 +1 @@ - - - - - - - - + From 8cd4e29f58a2e06151910a6e7b04eee5bbbeb1ad Mon Sep 17 00:00:00 2001 From: qianmoQ Date: Thu, 3 Dec 2026 02:32:19 -0500 Subject: [PATCH 08/15] feat(markdown-editor): render LaTeX math as MathML $...$ and $$...$$ formulas showed up as plain text. The backend now enables math parsing and converts each formula to MathML with pulldown-latex, so the preview and exported HTML typeset it natively without scripts, fonts or a network connection. Invalid LaTeX is marked in red inside the formula instead of failing the render, and the status bar counts formulas. pulldown-latex writes formula text, error context and the source annotation unescaped, so <, > and " are swapped for private-use placeholders before conversion and written back as entities afterwards; output with any element outside the MathML set falls back to escaped code. Tests cover the injection cases found while probing the library. Refs #132 --- Cargo.lock | 10 ++ market/markdown-editor/backend/Cargo.toml | 1 + market/markdown-editor/backend/src/export.css | 2 + market/markdown-editor/backend/src/lib.rs | 1 + market/markdown-editor/backend/src/math.rs | 126 ++++++++++++++++++ .../markdown-editor/backend/src/math_test.rs | 68 ++++++++++ market/markdown-editor/backend/src/render.rs | 25 +++- .../backend/src/render_test.rs | 34 +++++ market/markdown-editor/locales/en-US.json | 4 +- market/markdown-editor/locales/zh-CN.json | 4 +- market/markdown-editor/manifest.json | 2 +- .../markdown-editor/ui/src/MarkdownEditor.tsx | 3 + market/markdown-editor/ui/src/types.ts | 1 + 13 files changed, 274 insertions(+), 7 deletions(-) create mode 100644 market/markdown-editor/backend/src/math.rs create mode 100644 market/markdown-editor/backend/src/math_test.rs diff --git a/Cargo.lock b/Cargo.lock index 5ead1dbc..0af2a9b1 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6502,6 +6502,15 @@ version = "0.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "007d8adb5ddab6f8e3f491ac63566a7d5002cc7ed73901f72057943fa71ae1ae" +[[package]] +name = "pulldown-latex" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1cf850381ae0dbb131f36e31d6090f55363d079ab3e518ad0323b9cb6a96d115" +dependencies = [ + "bumpalo", +] + [[package]] name = "pulley-interpreter" version = "49.0.3" @@ -9852,6 +9861,7 @@ name = "tfm-markdown-editor" version = "0.1.0" dependencies = [ "pulldown-cmark", + "pulldown-latex", "serde", "serde_json", "tf-plugin-api", diff --git a/market/markdown-editor/backend/Cargo.toml b/market/markdown-editor/backend/Cargo.toml index df9735ca..5c662326 100644 --- a/market/markdown-editor/backend/Cargo.toml +++ b/market/markdown-editor/backend/Cargo.toml @@ -16,3 +16,4 @@ serde_json.workspace = true tf-plugin-api.workspace = true tf-plugin-guest = { path = "../../../crates/tf-plugin-guest" } pulldown-cmark = { version = "0.13", default-features = false, features = ["html"] } +pulldown-latex = "0.8" diff --git a/market/markdown-editor/backend/src/export.css b/market/markdown-editor/backend/src/export.css index 6c43125e..c1acfdac 100644 --- a/market/markdown-editor/backend/src/export.css +++ b/market/markdown-editor/backend/src/export.css @@ -69,3 +69,5 @@ img { max-width: 100%; } .markdown-alert-important { border-color: var(--important); } .markdown-alert-warning { border-color: var(--warning); } .markdown-alert-caution { border-color: var(--caution); } +.math { font-size: 1.05em; } +.math-display { display: block; margin: 0 0 1em; padding: 0.25em 0; overflow-x: auto; } diff --git a/market/markdown-editor/backend/src/lib.rs b/market/markdown-editor/backend/src/lib.rs index 818a7880..2931028b 100644 --- a/market/markdown-editor/backend/src/lib.rs +++ b/market/markdown-editor/backend/src/lib.rs @@ -1,6 +1,7 @@ //! Markdown 编辑器插件后端:GFM 渲染、安全过滤、目录与统计,以及导出独立 HTML。 mod export; +mod math; mod render; mod styled; mod toc; diff --git a/market/markdown-editor/backend/src/math.rs b/market/markdown-editor/backend/src/math.rs new file mode 100644 index 00000000..4c8024a5 --- /dev/null +++ b/market/markdown-editor/backend/src/math.rs @@ -0,0 +1,126 @@ +//! LaTeX 公式:`$…$` 行内、`$$…$$` 块级。在 Rust 中转换为 MathML,WebView 与浏览器 +//! 原生排版,预览和导出的 HTML 都不需要脚本或额外字体。 +//! +//! pulldown-latex 不转义输出:`\text`、`\operatorname`、错误提示与 annotation 都会原样 +//! 写出公式里的字符。因此转换前把 `<` `>` `"` 换成私用区占位符,转换后再写成实体, +//! 用户文字永远不会成为标签或属性;最后再按白名单检查一遍标签名。 + +use pulldown_latex::config::DisplayMode; +use pulldown_latex::{Parser, RenderConfig, Storage, push_mathml}; + +/// 错误与无法识别的命令用红色标出,公式其余部分照常显示 +const ERROR_COLOR: (u8, u8, u8) = (0xdc, 0x26, 0x26); + +/// 占位符与它最终写出的实体 +const PLACEHOLDERS: [(char, char, &str); 3] = [ + ('<', '\u{E000}', "<"), + ('>', '\u{E001}', ">"), + ('"', '\u{E002}', """), +]; + +/// pulldown-latex 会生成的元素 +const ELEMENTS: &[&str] = &[ + "math", + "semantics", + "annotation", + "mrow", + "mi", + "mo", + "mn", + "ms", + "mtext", + "mspace", + "msup", + "msub", + "msubsup", + "mfrac", + "msqrt", + "mroot", + "mover", + "munder", + "munderover", + "mtable", + "mtr", + "mtd", + "mstyle", + "mpadded", + "mphantom", + "merror", + "menclose", + "mmultiscripts", + "mprescripts", + "none", +]; + +/// 把一段 LaTeX 转为包裹好的 MathML;原文作为 annotation 保留,复制公式时可取回 +pub fn to_html(latex: &str, display: bool) -> String { + let class = if display { + "math math-display" + } else { + "math math-inline" + }; + mathml(latex, display) + .map(|mathml| format!("{mathml}")) + // 写入失败或出现意外标签时按代码显示原文 + .unwrap_or_else(|| format!("{}", escape(latex))) +} + +fn mathml(latex: &str, display: bool) -> Option { + let guarded: String = latex + .chars() + .map(|c| match PLACEHOLDERS.iter().find(|(raw, ..)| *raw == c) { + Some((_, placeholder, _)) => *placeholder, + // 输入里本来就有的占位符字符不能被还原成标记 + None if PLACEHOLDERS.iter().any(|(_, p, _)| *p == c) => '\u{FFFD}', + None => c, + }) + .collect(); + let storage = Storage::new(); + let config = RenderConfig { + display_mode: if display { + DisplayMode::Block + } else { + DisplayMode::Inline + }, + annotation: Some(&guarded), + error_color: ERROR_COLOR, + ..RenderConfig::default() + }; + let mut out = String::new(); + push_mathml(&mut out, Parser::new(&guarded, &storage), config).ok()?; + // \lt、\gt 生成的运算符本身也是未转义的尖括号 + let mut out = out + .replace("<", "<") + .replace(">", ">"); + for (_, placeholder, entity) in PLACEHOLDERS { + out = out.replace(placeholder, entity); + } + // 直接输入的 < > 被当成了标识符,改回运算符才有比较号两侧的间距 + let out = out + .replace("<", "<") + .replace(">", ">"); + only_known_elements(&out).then_some(out) +} + +/// 每个 `<` 都必须开始一个白名单内的元素(或其结束标签) +fn only_known_elements(html: &str) -> bool { + html.match_indices('<').all(|(i, _)| { + let rest = html[i + 1..].strip_prefix('/').unwrap_or(&html[i + 1..]); + let name: String = rest + .chars() + .take_while(char::is_ascii_alphanumeric) + .collect(); + let after = rest[name.len()..].chars().next(); + ELEMENTS.contains(&name.as_str()) && matches!(after, Some(' ' | '>' | '/')) + }) +} + +fn escape(text: &str) -> String { + text.replace('&', "&") + .replace('<', "<") + .replace('>', ">") +} + +#[cfg(test)] +#[path = "math_test.rs"] +mod tests; diff --git a/market/markdown-editor/backend/src/math_test.rs b/market/markdown-editor/backend/src/math_test.rs new file mode 100644 index 00000000..89814541 --- /dev/null +++ b/market/markdown-editor/backend/src/math_test.rs @@ -0,0 +1,68 @@ +use super::*; + +#[test] +fn inline_and_display_math_become_mathml() { + let inline = to_html("x^2", false); + assert!(inline.starts_with("")); + let display = to_html(r"\frac{a}{b}", true); + assert!(display.contains("display=\"block\"")); + assert!(display.contains("")); +} + +#[test] +fn user_text_never_becomes_markup() { + for latex in [ + r"\text{}", + r"\operatorname{}", + r"\frac{}", + r#"\text{" onclick="1}"#, + "ac", + "\u{E000}img\u{E001}", + ] { + let html = to_html(latex, false); + assert!( + only_known_elements( + &html + .replace("", "") + .replace("", "") + ), + "{latex}: {html}" + ); + assert!( + !html.contains("onclick=1>") && !html.contains(" d", false); + assert!(!html.contains("<")); + assert!(html.contains("<")); + assert!(html.contains(">")); + assert!(!html.contains("<")); +} + +#[test] +fn errors_render_inline_instead_of_failing() { + let html = to_html(r"\frac{a", false); + assert!(html.contains("x")); + assert!(!only_known_elements("")); + assert!(!only_known_elements(" Options { | Options::ENABLE_HEADING_ATTRIBUTES | Options::ENABLE_YAML_STYLE_METADATA_BLOCKS | Options::ENABLE_GFM + | Options::ENABLE_MATH } /// 链接是否可以保留:允许 http(s)、mailto、页内锚点与相对路径;图片额外允许位图 data URI @@ -144,10 +149,22 @@ pub fn render(args: Args) -> PluginResult { let mut plain = String::new(); let mut in_metadata = false; - // 原始 HTML 不执行,按文本显示(先转换,标题文字才完整) + // 原始 HTML 不执行,按文本显示(先转换,标题文字才完整); + // 公式在这之后才转成 MathML,它是唯一由插件自己生成、原样输出的标记 for (event, _) in events.iter_mut() { - if let Event::Html(raw) | Event::InlineHtml(raw) = event { - *event = Event::Text(std::mem::replace(raw, CowStr::Borrowed(""))); + match event { + Event::Html(raw) | Event::InlineHtml(raw) => { + *event = Event::Text(std::mem::replace(raw, CowStr::Borrowed(""))); + } + Event::InlineMath(latex) => { + stats.formulas += 1; + *event = Event::InlineHtml(math::to_html(latex, false).into()); + } + Event::DisplayMath(latex) => { + stats.formulas += 1; + *event = Event::InlineHtml(math::to_html(latex, true).into()); + } + _ => {} } } diff --git a/market/markdown-editor/backend/src/render_test.rs b/market/markdown-editor/backend/src/render_test.rs index 1dca8b93..7f45d835 100644 --- a/market/markdown-editor/backend/src/render_test.rs +++ b/market/markdown-editor/backend/src/render_test.rs @@ -119,3 +119,37 @@ fn rejects_huge_documents() { "md.too_large" ); } + +#[test] +fn math_renders_as_mathml() { + let out = render(Args { + source: "Euler: $e^{i\\pi}+1=0$\n\n$$\n\\int_0^1 x\\,dx\n$$\n".to_owned(), + }) + .unwrap(); + assert!(out.html.contains(" and $a<")); +} diff --git a/market/markdown-editor/locales/en-US.json b/market/markdown-editor/locales/en-US.json index 95f16805..c33b5783 100644 --- a/market/markdown-editor/locales/en-US.json +++ b/market/markdown-editor/locales/en-US.json @@ -3,6 +3,7 @@ "description": "Write Markdown with live preview, outline and word count, and export to HTML", "help": [ "Supports GitHub Flavored Markdown: tables, task lists, footnotes, strikethrough and alerts such as > [!NOTE].", + "LaTeX math: write $E=mc^2$ for inline math and $$ … $$ in its own paragraph for display math. It is converted to MathML locally, so exported HTML shows it offline.", "The preview is rendered in Rust. Raw HTML is shown as text and unsafe links are removed, so documents from anywhere are safe to open.", "Edit multiple files at once with tabs; changes can be auto-saved to disk on a configurable interval.", "Shortcuts: ⌘/Ctrl+S save, ⌘/Ctrl+B bold, ⌘/Ctrl+I italic, ⌘/Ctrl+K link. Drop a .md file onto the window to open it." @@ -11,7 +12,7 @@ "render": "Render Markdown", "export_html": "Export HTML" }, - "sample": "# Welcome to the Markdown Editor\n\nType on the left and the preview updates as you write. Your draft is **saved automatically**.\n\n## Features\n\n- [x] GitHub Flavored Markdown\n- [x] Outline, word count and reading time\n- [ ] Export to a standalone HTML file\n\n| Shortcut | Action |\n| --- | --- |\n| ⌘/Ctrl + S | Save |\n| ⌘/Ctrl + B | Bold |\n\n> [!TIP]\n> Click a heading in the outline to jump to it.\n\n```rust\nfn main() {\n println!(\"Hello, ToolForge!\");\n}\n```\n", + "sample": "# Welcome to the Markdown Editor\n\nType on the left and the preview updates as you write. Your draft is **saved automatically**.\n\n## Features\n\n- [x] GitHub Flavored Markdown\n- [x] Outline, word count and reading time\n- [ ] Export to a standalone HTML file\n\n| Shortcut | Action |\n| --- | --- |\n| ⌘/Ctrl + S | Save |\n| ⌘/Ctrl + B | Bold |\n\n> [!TIP]\n> Click a heading in the outline to jump to it.\n\n```rust\nfn main() {\n println!(\"Hello, ToolForge!\");\n}\n```\n\n## Math\n\nInline $E = mc^2$, and on its own line:\n\n$$\n\\int_0^1 x^2\\,dx = \\frac{1}{3}\n$$\n", "file": { "new": "New", "open": "Open", @@ -81,6 +82,7 @@ "chars": "{{count}} characters", "lines": "{{count}} lines", "reading": "{{count}} min read", + "formulas": "{{count}} formulas", "tasks": "{{done}}/{{total}} tasks", "cursor": "Ln {{line}}, Col {{column}}" }, diff --git a/market/markdown-editor/locales/zh-CN.json b/market/markdown-editor/locales/zh-CN.json index d814c693..7554fd63 100644 --- a/market/markdown-editor/locales/zh-CN.json +++ b/market/markdown-editor/locales/zh-CN.json @@ -3,6 +3,7 @@ "description": "实时预览、目录与字数统计的 Markdown 编辑器,可导出 HTML", "help": [ "支持 GitHub 风格 Markdown:表格、任务列表、脚注、删除线,以及 > [!NOTE] 等提示块。", + "支持 LaTeX 公式:$E=mc^2$ 写行内公式,$$ … $$ 单独成段写块级公式;在本地转换为 MathML,导出的 HTML 无需联网即可显示。", "预览由 Rust 渲染:原始 HTML 按文本显示,不安全的链接会被移除,打开任何来源的文档都是安全的。", "支持多标签页同时编辑多个文件;可配置间隔把修改自动保存到本地文件。", "快捷键:⌘/Ctrl+S 保存,⌘/Ctrl+B 加粗,⌘/Ctrl+I 斜体,⌘/Ctrl+K 链接。把 .md 文件拖入窗口即可打开。" @@ -11,7 +12,7 @@ "render": "渲染 Markdown", "export_html": "导出 HTML" }, - "sample": "# 欢迎使用 Markdown 编辑器\n\n在左侧输入,右侧会实时预览。草稿会**自动保存**。\n\n## 功能\n\n- [x] GitHub 风格 Markdown\n- [x] 目录、字数与阅读时长\n- [ ] 导出为独立的 HTML 文件\n\n| 快捷键 | 作用 |\n| --- | --- |\n| ⌘/Ctrl + S | 保存 |\n| ⌘/Ctrl + B | 加粗 |\n\n> [!TIP]\n> 点击目录中的标题即可跳转。\n\n```rust\nfn main() {\n println!(\"Hello, ToolForge!\");\n}\n```\n", + "sample": "# 欢迎使用 Markdown 编辑器\n\n在左侧输入,右侧会实时预览。草稿会**自动保存**。\n\n## 功能\n\n- [x] GitHub 风格 Markdown\n- [x] 目录、字数与阅读时长\n- [ ] 导出为独立的 HTML 文件\n\n| 快捷键 | 作用 |\n| --- | --- |\n| ⌘/Ctrl + S | 保存 |\n| ⌘/Ctrl + B | 加粗 |\n\n> [!TIP]\n> 点击目录中的标题即可跳转。\n\n```rust\nfn main() {\n println!(\"Hello, ToolForge!\");\n}\n```\n\n## 公式\n\n行内公式 $E = mc^2$,块级公式:\n\n$$\n\\int_0^1 x^2\\,dx = \\frac{1}{3}\n$$\n", "file": { "new": "新建", "open": "打开", @@ -81,6 +82,7 @@ "chars": "{{count}} 字符", "lines": "{{count}} 行", "reading": "约 {{count}} 分钟", + "formulas": "{{count}} 个公式", "tasks": "任务 {{done}}/{{total}}", "cursor": "第 {{line}} 行,第 {{column}} 列" }, diff --git a/market/markdown-editor/manifest.json b/market/markdown-editor/manifest.json index 6d2937a7..1f9dbbfd 100644 --- a/market/markdown-editor/manifest.json +++ b/market/markdown-editor/manifest.json @@ -1,6 +1,6 @@ { "id": "org.devlive.toolforge.markdown-editor", - "version": "0.2.4", + "version": "0.2.5", "name": "i18n:name", "description": "i18n:description", "category": "text", diff --git a/market/markdown-editor/ui/src/MarkdownEditor.tsx b/market/markdown-editor/ui/src/MarkdownEditor.tsx index 2dfc8c73..090d4211 100644 --- a/market/markdown-editor/ui/src/MarkdownEditor.tsx +++ b/market/markdown-editor/ui/src/MarkdownEditor.tsx @@ -68,6 +68,8 @@ const PROSE = cn( '[&_hr]:my-6 [&_hr]:border-border [&_img]:max-w-full [&_img]:rounded-control', '[&_.footnote-definition]:flex [&_.footnote-definition]:gap-2 [&_.footnote-definition]:text-xs [&_.footnote-definition]:text-fg-muted', '[&_.footnote-definition_p]:my-0 [&_sup]:text-[0.75em]', + // 块级公式居中,过长时横向滚动而不是撑破预览区 + '[&_.math-display]:my-3 [&_.math-display]:block [&_.math-display]:overflow-x-auto [&_.math-display]:py-1 [&_.math]:text-[1.05em]', ) export function MarkdownEditor() { @@ -542,6 +544,7 @@ export function MarkdownEditor() { {t('stats.lines', { count: stats.lines })} {stats.readingMinutes > 0 && {t('stats.reading', { count: stats.readingMinutes })}} {stats.tasks > 0 && {t('stats.tasks', { done: stats.tasksDone, total: stats.tasks })}} + {stats.formulas > 0 && {t('stats.formulas', { count: stats.formulas })}} )} {view !== 'preview' && {t('stats.cursor', cursor)}} diff --git a/market/markdown-editor/ui/src/types.ts b/market/markdown-editor/ui/src/types.ts index 099c11f0..73c7c5c6 100644 --- a/market/markdown-editor/ui/src/types.ts +++ b/market/markdown-editor/ui/src/types.ts @@ -15,6 +15,7 @@ export interface Stats { codeBlocks: number tasks: number tasksDone: number + formulas: number } export interface Rendered { From 22a550dc785077fc4581450a6da3ec596872edb7 Mon Sep 17 00:00:00 2001 From: qianmoQ Date: Thu, 3 Dec 2026 02:41:18 -0500 Subject: [PATCH 09/15] feat(markdown-editor): render mermaid code blocks as diagrams Mermaid blocks were shown as code. The backend now renders them to SVG with mermaid-rs-renderer in Rust, so flowcharts, sequence, class, state, ER, pie and Gantt diagrams appear in the preview and in exported HTML without mermaid.js or a network connection. A diagram that fails to parse shows the error above its source instead of breaking the page. The SVG is embedded as a data URI image: an SVG image cannot run scripts or load external resources, so labels and style directives stay inert whether or not the renderer escapes them. Text is measured with character widths because the sandbox has no system fonts, diagrams over 64 KB are refused, and diagrams sit on a white card in dark mode. Refs #158 --- Cargo.lock | 18 +++ market/markdown-editor/backend/Cargo.toml | 1 + market/markdown-editor/backend/src/export.css | 5 + market/markdown-editor/backend/src/lib.rs | 1 + market/markdown-editor/backend/src/mermaid.rs | 69 ++++++++++++ .../backend/src/mermaid_test.rs | 106 ++++++++++++++++++ market/markdown-editor/backend/src/render.rs | 54 ++++++++- .../backend/src/render_test.rs | 28 +++++ market/markdown-editor/locales/en-US.json | 4 +- market/markdown-editor/locales/zh-CN.json | 4 +- .../markdown-editor/ui/src/MarkdownEditor.tsx | 6 + market/markdown-editor/ui/src/types.ts | 1 + 12 files changed, 292 insertions(+), 5 deletions(-) create mode 100644 market/markdown-editor/backend/src/mermaid.rs create mode 100644 market/markdown-editor/backend/src/mermaid_test.rs diff --git a/Cargo.lock b/Cargo.lock index 0af2a9b1..93bf73f3 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4925,6 +4925,23 @@ dependencies = [ "autocfg", ] +[[package]] +name = "mermaid-rs-renderer" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6cb5b469222ce6b9896edf0a969cf68464f5a028ef394fd6643f00bd943df117" +dependencies = [ + "anyhow", + "fontdb", + "json5", + "once_cell", + "regex", + "serde", + "serde_json", + "thiserror 2.0.20", + "ttf-parser", +] + [[package]] name = "micromap" version = "0.3.0" @@ -9860,6 +9877,7 @@ dependencies = [ name = "tfm-markdown-editor" version = "0.1.0" dependencies = [ + "mermaid-rs-renderer", "pulldown-cmark", "pulldown-latex", "serde", diff --git a/market/markdown-editor/backend/Cargo.toml b/market/markdown-editor/backend/Cargo.toml index 5c662326..83d33c32 100644 --- a/market/markdown-editor/backend/Cargo.toml +++ b/market/markdown-editor/backend/Cargo.toml @@ -17,3 +17,4 @@ tf-plugin-api.workspace = true tf-plugin-guest = { path = "../../../crates/tf-plugin-guest" } pulldown-cmark = { version = "0.13", default-features = false, features = ["html"] } pulldown-latex = "0.8" +mermaid-rs-renderer = { version = "0.3", default-features = false } diff --git a/market/markdown-editor/backend/src/export.css b/market/markdown-editor/backend/src/export.css index c1acfdac..be66dcb5 100644 --- a/market/markdown-editor/backend/src/export.css +++ b/market/markdown-editor/backend/src/export.css @@ -71,3 +71,8 @@ img { max-width: 100%; } .markdown-alert-caution { border-color: var(--caution); } .math { font-size: 1.05em; } .math-display { display: block; margin: 0 0 1em; padding: 0.25em 0; overflow-x: auto; } +.mermaid { display: flex; justify-content: center; margin: 0 0 1em; padding: 12px; border: 1px solid var(--border); border-radius: 6px; background: #ffffff; } +.mermaid img { max-width: 100%; } +.mermaid-error { margin: 0 0 1em; padding: 12px; border: 1px solid var(--caution); border-radius: 6px; } +.mermaid-error > p { margin: 0 0 0.5em; font-size: 0.875em; color: var(--caution); } +.mermaid-error pre { margin: 0; } diff --git a/market/markdown-editor/backend/src/lib.rs b/market/markdown-editor/backend/src/lib.rs index 2931028b..d4ca3735 100644 --- a/market/markdown-editor/backend/src/lib.rs +++ b/market/markdown-editor/backend/src/lib.rs @@ -2,6 +2,7 @@ mod export; mod math; +mod mermaid; mod render; mod styled; mod toc; diff --git a/market/markdown-editor/backend/src/mermaid.rs b/market/markdown-editor/backend/src/mermaid.rs new file mode 100644 index 00000000..767acd4a --- /dev/null +++ b/market/markdown-editor/backend/src/mermaid.rs @@ -0,0 +1,69 @@ +//! ```mermaid 代码块:在 Rust 中把图表渲染成 SVG(mermaid-rs-renderer),预览与导出的 +//! HTML 都不依赖 mermaid.js 和网络。 +//! +//! SVG 以 `` 嵌入:作为图片的 SVG 不会执行脚本, +//! 也不会加载外部资源,图表里的文字和样式指令即使没有被渲染器转义也无法注入页面。 + +use mermaid_rs_renderer::{RenderOptions, render_with_options}; + +/// 单个图表源码上限:超出时不渲染,避免大图拖慢每次预览 +pub const MAX_DIAGRAM: usize = 64 * 1024; + +/// 渲染结果:图片或带原文的错误提示 +pub fn to_html(source: &str, label: &str) -> String { + match render(source) { + Ok(svg) => format!( + "
\"{}\"
\n", + escape(label), + base64(svg.as_bytes()) + ), + Err(message) => format!( + "

{}

{}
\n", + escape(&message), + escape(source) + ), + } +} + +fn render(source: &str) -> Result { + if source.len() > MAX_DIAGRAM { + return Err(format!( + "Mermaid: diagram larger than {} KB", + MAX_DIAGRAM / 1024 + )); + } + let mut options = RenderOptions::modern(); + // 插件沙箱读不到系统字体;直接用字符宽度估算,本机测试与 WASM 中排版一致 + options.layout.fast_text_metrics = true; + render_with_options(source, options).map_err(|error| format!("Mermaid: {error}")) +} + +fn escape(text: &str) -> String { + text.replace('&', "&") + .replace('<', "<") + .replace('>', ">") + .replace('"', """) +} + +fn base64(bytes: &[u8]) -> String { + const ALPHABET: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + let mut out = String::with_capacity(bytes.len().div_ceil(3) * 4); + for chunk in bytes.chunks(3) { + let n = chunk + .iter() + .enumerate() + .fold(0u32, |n, (i, b)| n | u32::from(*b) << (16 - 8 * i)); + for i in 0..4 { + out.push(if i <= chunk.len() { + ALPHABET[(n >> (18 - 6 * i) & 63) as usize] as char + } else { + '=' + }); + } + } + out +} + +#[cfg(test)] +#[path = "mermaid_test.rs"] +mod tests; diff --git a/market/markdown-editor/backend/src/mermaid_test.rs b/market/markdown-editor/backend/src/mermaid_test.rs new file mode 100644 index 00000000..e89b7b27 --- /dev/null +++ b/market/markdown-editor/backend/src/mermaid_test.rs @@ -0,0 +1,106 @@ +use super::*; + +fn decode(html: &str) -> String { + let start = html.find("base64,").unwrap() + 7; + let data = &html[start..html[start..].find('"').unwrap() + start]; + let mut bytes = Vec::new(); + let value = |c: u8| -> u32 { + match c { + b'A'..=b'Z' => u32::from(c - b'A'), + b'a'..=b'z' => u32::from(c - b'a') + 26, + b'0'..=b'9' => u32::from(c - b'0') + 52, + b'+' => 62, + _ => 63, + } + }; + for chunk in data.as_bytes().chunks(4) { + let n = chunk + .iter() + .filter(|c| **c != b'=') + .enumerate() + .fold(0u32, |n, (i, c)| n | value(*c) << (18 - 6 * i)); + let len = chunk.iter().filter(|c| **c != b'=').count() - 1; + bytes.extend((0..len).map(|i| (n >> (16 - 8 * i)) as u8)); + } + String::from_utf8(bytes).unwrap() +} + +#[test] +fn base64_matches_known_vectors() { + assert_eq!(base64(b""), ""); + assert_eq!(base64(b"f"), "Zg=="); + assert_eq!(base64(b"fo"), "Zm8="); + assert_eq!(base64(b"foo"), "Zm9v"); + assert_eq!(base64(b"foobar"), "Zm9vYmFy"); +} + +#[test] +fn flowchart_becomes_an_svg_image() { + let html = to_html( + "flowchart LR\n A[开始] --> B{判断}\n B -->|是| C[结束]", + "diagram", + ); + assert!(html.starts_with( + "
\"diagram\">Bob: Hi\n Bob-->>Alice: Hello", + "classDiagram\n Animal <|-- Duck", + "stateDiagram-v2\n [*] --> Still\n Still --> [*]", + "erDiagram\n CUSTOMER ||--o{ ORDER : places", + "pie title Pets\n \"Dogs\" : 386\n \"Cats\" : 85", + "gantt\n title Plan\n dateFormat YYYY-MM-DD\n section A\n Task :a1, 2024-01-01, 3d", + ] { + let html = to_html(source, "diagram"); + assert!(html.contains(" [", "diagram"); + if html.contains("mermaid-error") { + assert!(!html.contains("")); + } + let garbage = to_html("not a diagram at all", "diagram"); + assert!(garbage.contains("mermaid-error"), "{garbage}"); +} + +#[test] +fn oversized_diagrams_are_refused() { + let html = to_html( + &format!("flowchart LR\n{}", "A-->B\n".repeat(20_000)), + "diagram", + ); + assert!(html.contains("mermaid-error")); +} + +#[test] +fn malformed_inputs_do_not_panic() { + for source in [ + "", + "flowchart", + "flowchart LR\n A -->", + "sequenceDiagram\n ->>", + "pie\n \"x\" : -1", + "graph TD\n A((((", + "gantt\n dateFormat\n x :", + "classDiagram\n class {", + "stateDiagram-v2\n state {\n", + "erDiagram\n A ||--", + "flowchart LR\n subgraph\n end\n end", + ] { + let _ = to_html(source, "diagram"); + } +} diff --git a/market/markdown-editor/backend/src/render.rs b/market/markdown-editor/backend/src/render.rs index 06245190..2ae90835 100644 --- a/market/markdown-editor/backend/src/render.rs +++ b/market/markdown-editor/backend/src/render.rs @@ -1,13 +1,13 @@ -//! Markdown 渲染:GFM 扩展(表格、任务列表、脚注、删除线、提示块)与 LaTeX 公式, +//! Markdown 渲染:GFM 扩展(表格、任务列表、脚注、删除线、提示块)、LaTeX 公式与 Mermaid 图表, //! 原始 HTML 按文本显示,不安全的链接协议被移除;同时生成目录与统计信息。 use std::collections::HashMap; -use pulldown_cmark::{CowStr, Event, Options, Parser, Tag, TagEnd, html}; +use pulldown_cmark::{CodeBlockKind, CowStr, Event, Options, Parser, Tag, TagEnd, html}; use serde::{Deserialize, Serialize}; use tf_plugin_api::{PluginError, PluginResult}; -use crate::math; +use crate::{math, mermaid}; pub const MAX_SOURCE: usize = 5 * 1024 * 1024; @@ -42,6 +42,8 @@ pub struct Stats { pub tasks_done: usize, /// `$…$` 与 `$$…$$` 公式数 pub formulas: usize, + /// ```mermaid 图表数 + pub diagrams: usize, } #[derive(Debug, Serialize)] @@ -130,6 +132,50 @@ fn reading_minutes(words: usize, cjk: usize) -> u32 { ((words as f64 / 230.0 + cjk as f64 / 400.0).ceil() as u32).max(1) } +/// 代码块语言是否为 mermaid(允许后面跟其他信息,如 ```mermaid title) +fn is_mermaid(kind: &CodeBlockKind) -> bool { + matches!(kind, CodeBlockKind::Fenced(info) if info.split_whitespace().next() == Some("mermaid")) +} + +/// 把 ```mermaid 代码块整体替换为渲染好的图表 +fn render_diagrams(events: &mut Vec<(Event, std::ops::Range)>, stats: &mut Stats) { + let mut index = 0; + while index < events.len() { + let Event::Start(Tag::CodeBlock(kind)) = &events[index].0 else { + index += 1; + continue; + }; + if !is_mermaid(kind) { + index += 1; + continue; + } + let Some(end) = events[index..] + .iter() + .position(|(event, _)| matches!(event, Event::End(TagEnd::CodeBlock))) + .map(|offset| index + offset) + else { + break; + }; + let source: String = events[index + 1..end] + .iter() + .filter_map(|(event, _)| match event { + Event::Text(text) => Some(text.as_ref()), + _ => None, + }) + .collect(); + // 图片替代文字用图表类型(源码第一行),不需要翻译 + let label = format!( + "mermaid: {}", + source.lines().next().unwrap_or_default().trim() + ); + let range = events[index].1.clone(); + let html = mermaid::to_html(&source, &label); + events.splice(index..=end, [(Event::Html(html.into()), range)]); + stats.diagrams += 1; + index += 1; + } +} + pub fn render(args: Args) -> PluginResult { let source = args.source.as_str(); if source.len() > MAX_SOURCE { @@ -168,6 +214,8 @@ pub fn render(args: Args) -> PluginResult { } } + render_diagrams(&mut events, &mut stats); + for index in 0..events.len() { match &mut events[index].0 { Event::Start(Tag::Heading { .. }) => { diff --git a/market/markdown-editor/backend/src/render_test.rs b/market/markdown-editor/backend/src/render_test.rs index 7f45d835..db05d41f 100644 --- a/market/markdown-editor/backend/src/render_test.rs +++ b/market/markdown-editor/backend/src/render_test.rs @@ -153,3 +153,31 @@ fn raw_html_stays_text_next_to_math() { assert!(!out.html.contains("<")); } + +#[test] +fn mermaid_blocks_become_diagrams() { + let out = render(Args { + source: + "# Flow\n\n```mermaid\nflowchart LR\n A --> B\n```\n\n```rust\nfn main() {}\n```\n" + .to_owned(), + }) + .unwrap(); + assert!( + out.html + .contains("
\"mermaid:")); + assert!(!out.html.contains("language-mermaid")); + assert_eq!(out.stats.diagrams, 1); + assert_eq!(out.stats.code_blocks, 1); +} + +#[test] +fn broken_mermaid_keeps_its_source() { + let out = render(Args { + source: "```mermaid\nnot a diagram \n```\n".to_owned(), + }) + .unwrap(); + assert!(out.html.contains("mermaid-error")); + assert!(out.html.contains("not a diagram <b>")); +} diff --git a/market/markdown-editor/locales/en-US.json b/market/markdown-editor/locales/en-US.json index c33b5783..dcea5ed2 100644 --- a/market/markdown-editor/locales/en-US.json +++ b/market/markdown-editor/locales/en-US.json @@ -4,6 +4,7 @@ "help": [ "Supports GitHub Flavored Markdown: tables, task lists, footnotes, strikethrough and alerts such as > [!NOTE].", "LaTeX math: write $E=mc^2$ for inline math and $$ … $$ in its own paragraph for display math. It is converted to MathML locally, so exported HTML shows it offline.", + "Code blocks tagged mermaid render as diagrams: flowcharts, sequence, class, state, ER, pie and Gantt charts and more. They are drawn locally, so exported HTML works offline too.", "The preview is rendered in Rust. Raw HTML is shown as text and unsafe links are removed, so documents from anywhere are safe to open.", "Edit multiple files at once with tabs; changes can be auto-saved to disk on a configurable interval.", "Shortcuts: ⌘/Ctrl+S save, ⌘/Ctrl+B bold, ⌘/Ctrl+I italic, ⌘/Ctrl+K link. Drop a .md file onto the window to open it." @@ -12,7 +13,7 @@ "render": "Render Markdown", "export_html": "Export HTML" }, - "sample": "# Welcome to the Markdown Editor\n\nType on the left and the preview updates as you write. Your draft is **saved automatically**.\n\n## Features\n\n- [x] GitHub Flavored Markdown\n- [x] Outline, word count and reading time\n- [ ] Export to a standalone HTML file\n\n| Shortcut | Action |\n| --- | --- |\n| ⌘/Ctrl + S | Save |\n| ⌘/Ctrl + B | Bold |\n\n> [!TIP]\n> Click a heading in the outline to jump to it.\n\n```rust\nfn main() {\n println!(\"Hello, ToolForge!\");\n}\n```\n\n## Math\n\nInline $E = mc^2$, and on its own line:\n\n$$\n\\int_0^1 x^2\\,dx = \\frac{1}{3}\n$$\n", + "sample": "# Welcome to the Markdown Editor\n\nType on the left and the preview updates as you write. Your draft is **saved automatically**.\n\n## Features\n\n- [x] GitHub Flavored Markdown\n- [x] Outline, word count and reading time\n- [ ] Export to a standalone HTML file\n\n| Shortcut | Action |\n| --- | --- |\n| ⌘/Ctrl + S | Save |\n| ⌘/Ctrl + B | Bold |\n\n> [!TIP]\n> Click a heading in the outline to jump to it.\n\n```rust\nfn main() {\n println!(\"Hello, ToolForge!\");\n}\n```\n\n## Math\n\nInline $E = mc^2$, and on its own line:\n\n$$\n\\int_0^1 x^2\\,dx = \\frac{1}{3}\n$$\n\n## Diagrams\n\n```mermaid\nflowchart LR\n A[Write] --> B{Preview}\n B -->|Happy| C[Export]\n B -->|Edit| A\n```\n", "file": { "new": "New", "open": "Open", @@ -83,6 +84,7 @@ "lines": "{{count}} lines", "reading": "{{count}} min read", "formulas": "{{count}} formulas", + "diagrams": "{{count}} diagrams", "tasks": "{{done}}/{{total}} tasks", "cursor": "Ln {{line}}, Col {{column}}" }, diff --git a/market/markdown-editor/locales/zh-CN.json b/market/markdown-editor/locales/zh-CN.json index 7554fd63..dbf5e73b 100644 --- a/market/markdown-editor/locales/zh-CN.json +++ b/market/markdown-editor/locales/zh-CN.json @@ -4,6 +4,7 @@ "help": [ "支持 GitHub 风格 Markdown:表格、任务列表、脚注、删除线,以及 > [!NOTE] 等提示块。", "支持 LaTeX 公式:$E=mc^2$ 写行内公式,$$ … $$ 单独成段写块级公式;在本地转换为 MathML,导出的 HTML 无需联网即可显示。", + "语言标记为 mermaid 的代码块会渲染成图表:流程图、时序图、类图、状态图、ER 图、饼图、甘特图等;在本地渲染,导出的 HTML 同样离线可看。", "预览由 Rust 渲染:原始 HTML 按文本显示,不安全的链接会被移除,打开任何来源的文档都是安全的。", "支持多标签页同时编辑多个文件;可配置间隔把修改自动保存到本地文件。", "快捷键:⌘/Ctrl+S 保存,⌘/Ctrl+B 加粗,⌘/Ctrl+I 斜体,⌘/Ctrl+K 链接。把 .md 文件拖入窗口即可打开。" @@ -12,7 +13,7 @@ "render": "渲染 Markdown", "export_html": "导出 HTML" }, - "sample": "# 欢迎使用 Markdown 编辑器\n\n在左侧输入,右侧会实时预览。草稿会**自动保存**。\n\n## 功能\n\n- [x] GitHub 风格 Markdown\n- [x] 目录、字数与阅读时长\n- [ ] 导出为独立的 HTML 文件\n\n| 快捷键 | 作用 |\n| --- | --- |\n| ⌘/Ctrl + S | 保存 |\n| ⌘/Ctrl + B | 加粗 |\n\n> [!TIP]\n> 点击目录中的标题即可跳转。\n\n```rust\nfn main() {\n println!(\"Hello, ToolForge!\");\n}\n```\n\n## 公式\n\n行内公式 $E = mc^2$,块级公式:\n\n$$\n\\int_0^1 x^2\\,dx = \\frac{1}{3}\n$$\n", + "sample": "# 欢迎使用 Markdown 编辑器\n\n在左侧输入,右侧会实时预览。草稿会**自动保存**。\n\n## 功能\n\n- [x] GitHub 风格 Markdown\n- [x] 目录、字数与阅读时长\n- [ ] 导出为独立的 HTML 文件\n\n| 快捷键 | 作用 |\n| --- | --- |\n| ⌘/Ctrl + S | 保存 |\n| ⌘/Ctrl + B | 加粗 |\n\n> [!TIP]\n> 点击目录中的标题即可跳转。\n\n```rust\nfn main() {\n println!(\"Hello, ToolForge!\");\n}\n```\n\n## 公式\n\n行内公式 $E = mc^2$,块级公式:\n\n$$\n\\int_0^1 x^2\\,dx = \\frac{1}{3}\n$$\n\n## 图表\n\n```mermaid\nflowchart LR\n A[编写] --> B{预览}\n B -->|满意| C[导出]\n B -->|修改| A\n```\n", "file": { "new": "新建", "open": "打开", @@ -83,6 +84,7 @@ "lines": "{{count}} 行", "reading": "约 {{count}} 分钟", "formulas": "{{count}} 个公式", + "diagrams": "{{count}} 张图表", "tasks": "任务 {{done}}/{{total}}", "cursor": "第 {{line}} 行,第 {{column}} 列" }, diff --git a/market/markdown-editor/ui/src/MarkdownEditor.tsx b/market/markdown-editor/ui/src/MarkdownEditor.tsx index 090d4211..5b37b298 100644 --- a/market/markdown-editor/ui/src/MarkdownEditor.tsx +++ b/market/markdown-editor/ui/src/MarkdownEditor.tsx @@ -70,6 +70,11 @@ const PROSE = cn( '[&_.footnote-definition_p]:my-0 [&_sup]:text-[0.75em]', // 块级公式居中,过长时横向滚动而不是撑破预览区 '[&_.math-display]:my-3 [&_.math-display]:block [&_.math-display]:overflow-x-auto [&_.math-display]:py-1 [&_.math]:text-[1.05em]', + // 图表是浅色主题的 SVG 图片,深色模式下也放在白底卡片上保证可读 + '[&_.mermaid]:my-3 [&_.mermaid]:flex [&_.mermaid]:justify-center [&_.mermaid]:rounded-control [&_.mermaid]:border [&_.mermaid]:border-border [&_.mermaid]:bg-white [&_.mermaid]:p-3', + '[&_.mermaid_img]:max-w-full [&_.mermaid_img]:rounded-none', + '[&_.mermaid-error]:my-3 [&_.mermaid-error]:rounded-control [&_.mermaid-error]:border [&_.mermaid-error]:border-danger [&_.mermaid-error]:p-3', + '[&_.mermaid-error>p]:mt-0 [&_.mermaid-error>p]:text-xs [&_.mermaid-error>p]:text-danger [&_.mermaid-error_pre]:mb-0', ) export function MarkdownEditor() { @@ -545,6 +550,7 @@ export function MarkdownEditor() { {stats.readingMinutes > 0 && {t('stats.reading', { count: stats.readingMinutes })}} {stats.tasks > 0 && {t('stats.tasks', { done: stats.tasksDone, total: stats.tasks })}} {stats.formulas > 0 && {t('stats.formulas', { count: stats.formulas })}} + {stats.diagrams > 0 && {t('stats.diagrams', { count: stats.diagrams })}} )} {view !== 'preview' && {t('stats.cursor', cursor)}} diff --git a/market/markdown-editor/ui/src/types.ts b/market/markdown-editor/ui/src/types.ts index 73c7c5c6..0fb52fa0 100644 --- a/market/markdown-editor/ui/src/types.ts +++ b/market/markdown-editor/ui/src/types.ts @@ -16,6 +16,7 @@ export interface Stats { tasks: number tasksDone: number formulas: number + diagrams: number } export interface Rendered { From 6b92ab9c80b28d1795aa6d28c264c88816d82f42 Mon Sep 17 00:00:00 2001 From: qianmoQ Date: Thu, 3 Dec 2026 02:51:50 -0500 Subject: [PATCH 10/15] feat(sdk): let plugin pages copy PNG images to the clipboard Plugins could only put text on the clipboard. host.clipboard.writeImage takes PNG bytes and sends them to a new clipboard_write_png command as the raw request body, since a multi-megabyte image passed as a JSON number array spends seconds in serialization. The host decodes the PNG and writes it with the clipboard plugin; broken data reports a translatable error. The SDK is shared by the host at runtime, so on older apps the method is undefined and plugins check for it before offering image copy. --- apps/desktop/src-tauri/src/commands.rs | 33 +++++++++++++++++++ apps/desktop/src-tauri/src/commands_test.rs | 23 +++++++++++++ apps/desktop/src-tauri/src/lib.rs | 1 + apps/desktop/src/locales/en-US.json | 2 ++ apps/desktop/src/locales/zh-CN.json | 2 ++ docs/src/content/dev/plugin-development.en.md | 2 +- docs/src/content/dev/plugin-development.zh.md | 2 +- packages/plugin-ui-sdk/src/host.ts | 5 +++ 8 files changed, 68 insertions(+), 2 deletions(-) create mode 100644 apps/desktop/src-tauri/src/commands_test.rs diff --git a/apps/desktop/src-tauri/src/commands.rs b/apps/desktop/src-tauri/src/commands.rs index 8f3eca0b..dd22963e 100644 --- a/apps/desktop/src-tauri/src/commands.rs +++ b/apps/desktop/src-tauri/src/commands.rs @@ -237,6 +237,35 @@ pub async fn fs_read_text(path: String) -> AppResult { .map_err(|e| AppError::new("fs.io").with("detail", e.to_string()))? } +/// 解码要写入剪贴板的 PNG;损坏或不是 PNG 时返回可翻译的错误码 +pub fn png_image(bytes: &[u8]) -> AppResult> { + tauri::image::Image::from_bytes(bytes) + .map(|image| image.to_owned()) + .map_err(|e| AppError::new("clipboard.bad_image").with("detail", e.to_string())) +} + +/// 把 PNG 图片写入剪贴板(插件导出长图等)。请求体直接是 PNG 字节: +/// 几 MB 的图片若作为 JSON 数组参数传递,序列化本身就要数秒 +#[tauri::command] +pub async fn clipboard_write_png( + app: tauri::AppHandle, + request: tauri::ipc::Request<'_>, +) -> AppResult<()> { + use tauri_plugin_clipboard_manager::ClipboardExt; + let tauri::ipc::InvokeBody::Raw(bytes) = request.body() else { + return Err(AppError::new("clipboard.bad_image").with("detail", "expected raw PNG bytes")); + }; + let bytes = bytes.clone(); + tauri::async_runtime::spawn_blocking(move || { + let image = png_image(&bytes)?; + app.clipboard() + .write_image(&image) + .map_err(|e| AppError::new("clipboard.write_failed").with("detail", e.to_string())) + }) + .await + .map_err(|e| AppError::new("clipboard.write_failed").with("detail", e.to_string()))? +} + /// 写入用户通过保存对话框选择的文件 #[tauri::command] pub async fn fs_write_text(path: String, text: String) -> AppResult<()> { @@ -244,3 +273,7 @@ pub async fn fs_write_text(path: String, text: String) -> AppResult<()> { .await .map_err(|e| AppError::new("fs.io").with("detail", e.to_string()))? } + +#[cfg(test)] +#[path = "commands_test.rs"] +mod tests; diff --git a/apps/desktop/src-tauri/src/commands_test.rs b/apps/desktop/src-tauri/src/commands_test.rs new file mode 100644 index 00000000..621e288c --- /dev/null +++ b/apps/desktop/src-tauri/src/commands_test.rs @@ -0,0 +1,23 @@ +use super::*; + +/// 1×1 的红色 PNG +const PIXEL: &[u8] = &[ + 137, 80, 78, 71, 13, 10, 26, 10, 0, 0, 0, 13, 73, 72, 68, 82, 0, 0, 0, 1, 0, 0, 0, 1, 8, 6, 0, + 0, 0, 31, 21, 196, 137, 0, 0, 0, 13, 73, 68, 65, 84, 120, 218, 99, 252, 207, 192, 240, 31, 0, + 5, 5, 2, 0, 95, 200, 241, 210, 0, 0, 0, 0, 73, 69, 78, 68, 174, 66, 96, 130, +]; + +#[test] +fn png_bytes_decode_to_an_image() { + let image = png_image(PIXEL).unwrap(); + assert_eq!((image.width(), image.height()), (1, 1)); + assert_eq!(image.rgba().len(), 4); +} + +#[test] +fn broken_images_report_a_translatable_code() { + let error = png_image(b"not a png").unwrap_err(); + assert_eq!(error.code, "clipboard.bad_image"); + let truncated = png_image(&PIXEL[..PIXEL.len() / 2]).unwrap_err(); + assert_eq!(truncated.code, "clipboard.bad_image"); +} diff --git a/apps/desktop/src-tauri/src/lib.rs b/apps/desktop/src-tauri/src/lib.rs index aed8cb66..d01f2ef9 100644 --- a/apps/desktop/src-tauri/src/lib.rs +++ b/apps/desktop/src-tauri/src/lib.rs @@ -175,6 +175,7 @@ pub fn run() { commands::plugin_state_set, commands::fs_read_text, commands::fs_write_text, + commands::clipboard_write_png, tasks::task_start, tasks::task_cancel, tasks::task_list, diff --git a/apps/desktop/src/locales/en-US.json b/apps/desktop/src/locales/en-US.json index 23075c5f..95f2bf2c 100644 --- a/apps/desktop/src/locales/en-US.json +++ b/apps/desktop/src/locales/en-US.json @@ -467,6 +467,8 @@ "plugin.crashed": "The plugin crashed", "state.invalid_key": "Invalid storage key: {{key}}", "state.too_large": "The data is too large to save (over {{limit}})", + "clipboard.bad_image": "Cannot read the image: {{detail}}", + "clipboard.write_failed": "Failed to write to the clipboard: {{detail}}", "fs.not_utf8": "The file is not UTF-8 encoded text", "update.check_failed": "Failed to check for updates; check your network and try again", "update.install_failed": "Failed to install the update", diff --git a/apps/desktop/src/locales/zh-CN.json b/apps/desktop/src/locales/zh-CN.json index 8d0bfb49..0f2a5aff 100644 --- a/apps/desktop/src/locales/zh-CN.json +++ b/apps/desktop/src/locales/zh-CN.json @@ -465,6 +465,8 @@ "plugin.crashed": "插件执行异常", "state.invalid_key": "无效的存储键:{{key}}", "state.too_large": "数据过大,无法保存(超过 {{limit}})", + "clipboard.bad_image": "无法读取图片:{{detail}}", + "clipboard.write_failed": "写入剪贴板失败:{{detail}}", "fs.not_utf8": "文件不是 UTF-8 编码的文本", "update.check_failed": "检查更新失败,请检查网络后重试", "update.install_failed": "更新安装失败", diff --git a/docs/src/content/dev/plugin-development.en.md b/docs/src/content/dev/plugin-development.en.md index eb7d737b..ca4d8660 100644 --- a/docs/src/content/dev/plugin-development.en.md +++ b/docs/src/content/dev/plugin-development.en.md @@ -69,7 +69,7 @@ Common permissions: | --- | --- | | `fs:user-selected` | Reading and writing files the user chose (host functions `read-file` / `write-file`) | | `network` | HTTP requests sent by the host and one-off local callbacks | -| `clipboard:read` / `clipboard:write` | Reading or writing the clipboard from the interface | +| `clipboard:read` / `clipboard:write` | Reading or writing the clipboard from the interface; `host.clipboard.writeImage(png)` copies a PNG image (app 0.2.6 and later, so check that it exists before calling) | ## Step 2: Implement the Rust backend diff --git a/docs/src/content/dev/plugin-development.zh.md b/docs/src/content/dev/plugin-development.zh.md index 9dff8dc0..176755e5 100644 --- a/docs/src/content/dev/plugin-development.zh.md +++ b/docs/src/content/dev/plugin-development.zh.md @@ -69,7 +69,7 @@ market/my-tool/ | --- | --- | | `fs:user-selected` | 读写用户选择的文件(宿主函数 `read-file` / `write-file`) | | `network` | 由宿主发送 HTTP 请求、监听一次性本地回调 | -| `clipboard:read` / `clipboard:write` | 界面读取或写入剪贴板 | +| `clipboard:read` / `clipboard:write` | 界面读取或写入剪贴板;`host.clipboard.writeImage(png)` 写入 PNG 图片(应用 0.2.6 起,调用前先判断是否存在) | ## 第二步:实现 Rust 后端 diff --git a/packages/plugin-ui-sdk/src/host.ts b/packages/plugin-ui-sdk/src/host.ts index 444a6c38..bb08a8cf 100644 --- a/packages/plugin-ui-sdk/src/host.ts +++ b/packages/plugin-ui-sdk/src/host.ts @@ -29,6 +29,11 @@ export const host = { clipboard: { readText: () => wrap(readText()), writeText: (text: string) => wrap(writeText(text)), + /** + * 把 PNG 图片写入剪贴板。应用 0.2.6 起提供:插件界面由宿主共享 SDK, + * 在更早的应用中运行时这里是 undefined,调用前先判断是否存在 + */ + writeImage: (png: Uint8Array | ArrayBuffer) => wrap(invoke('clipboard_write_png', png)), }, dialog: { /** 选择单个文件,取消时返回 null */ From 7e340be2b5c5c78a198326bda80052c7f15a56c2 Mon Sep 17 00:00:00 2001 From: qianmoQ Date: Thu, 3 Dec 2026 02:53:04 -0500 Subject: [PATCH 11/15] ci(plugins): treat the image clipboard SDK method as a host-only change --- .github/plugin-sdk-host-only.txt | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/plugin-sdk-host-only.txt b/.github/plugin-sdk-host-only.txt index 5fb59049..c8b7cf8d 100644 --- a/.github/plugin-sdk-host-only.txt +++ b/.github/plugin-sdk-host-only.txt @@ -13,3 +13,4 @@ a8c6206be3e56e692e709c36f92c4245e5b632a8 function interface declarations are par 1ecbfc9bbb489b5d7b289a39ea85e1e6c56d3cd1 check_declared_interfaces is a test helper for plugin tests 2c172d8a6871ca3ca3d56847a97652ed1f618501 read_to_end is an additive helper that no published plugin calls, so their builds behave the same 7d76e1b7e1c085de28892e6fda25faeb8efa18af the native file_size error code only affects unit tests, not WASM builds +6b92ab9c80b28d1795aa6d28c264c88816d82f42 clipboard.writeImage is provided by the host at runtime; plugin packages do not bundle the UI SDK From be2e1764168ea01bb0e4e8b8f212411f7ace82ac Mon Sep 17 00:00:00 2001 From: qianmoQ Date: Thu, 3 Dec 2026 03:01:26 -0500 Subject: [PATCH 12/15] feat(markdown-editor): export the document as a long image Sharing notes in chat apps meant stitching screenshots. Export long image in the More menu turns the document into one PNG whose height follows the content, with adjustable width, margin, 1x to 3x resolution and a light, dark or app-matching theme. It can be saved, or copied to the clipboard on apps that provide image copy. The standalone export is laid out off screen at the chosen width; once images and fonts are ready its height is measured and the same DOM is drawn through an SVG foreignObject. The SVG is loaded from a data URL because WebKit taints the canvas for foreignObject images from blob URLs, which was confirmed in WKWebView. The scale drops automatically when the canvas would exceed browser limits, and a document too tall even at 1x gets a clear message. The backend checks the PNG signature before writing the file. Refs #102 --- market/markdown-editor/backend/src/image.rs | 71 +++++++++ .../markdown-editor/backend/src/image_test.rs | 38 +++++ market/markdown-editor/backend/src/lib.rs | 4 +- market/markdown-editor/locales/en-US.json | 28 +++- market/markdown-editor/locales/zh-CN.json | 28 +++- market/markdown-editor/manifest.json | 3 + market/markdown-editor/ui/package.json | 3 +- .../ui/src/LongImageDialog.tsx | 136 ++++++++++++++++++ .../markdown-editor/ui/src/MarkdownEditor.tsx | 11 ++ market/markdown-editor/ui/src/longImage.ts | 94 ++++++++++++ .../markdown-editor/ui/src/longImagePlan.ts | 88 ++++++++++++ .../ui/tests/longImagePlan.test.mjs | 45 ++++++ 12 files changed, 545 insertions(+), 4 deletions(-) create mode 100644 market/markdown-editor/backend/src/image.rs create mode 100644 market/markdown-editor/backend/src/image_test.rs create mode 100644 market/markdown-editor/ui/src/LongImageDialog.tsx create mode 100644 market/markdown-editor/ui/src/longImage.ts create mode 100644 market/markdown-editor/ui/src/longImagePlan.ts create mode 100644 market/markdown-editor/ui/tests/longImagePlan.test.mjs diff --git a/market/markdown-editor/backend/src/image.rs b/market/markdown-editor/backend/src/image.rs new file mode 100644 index 00000000..c9c7ed0c --- /dev/null +++ b/market/markdown-editor/backend/src/image.rs @@ -0,0 +1,71 @@ +//! 保存界面生成的长图:界面不能直接写二进制文件,PNG 以 base64 传给后端解码后写入 +//! 用户在保存对话框中选择的路径。 + +use serde::Deserialize; +use tf_plugin_api::{PluginError, PluginResult}; +use tf_plugin_guest::net; + +const PNG_SIGNATURE: &[u8] = b"\x89PNG\r\n\x1a\n"; + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct SaveArgs { + /// `data:image/png;base64,…` + pub data_uri: String, + pub path: String, +} + +pub fn save_image(args: SaveArgs) -> PluginResult<()> { + let bytes = decode_png(&args.data_uri)?; + net::write_file(&args.path, &bytes) + .map_err(|e| PluginError::new("md.write_failed").with("detail", e.code)) +} + +/// 解码 PNG data URI,并确认内容确实是 PNG +pub fn decode_png(uri: &str) -> PluginResult> { + let bad = || PluginError::new("md.bad_image"); + let encoded = uri.strip_prefix("data:image/png;base64,").ok_or_else(bad)?; + let bytes = encoded.as_bytes(); + if bytes.is_empty() || bytes.len() % 4 != 0 { + return Err(bad()); + } + let value = |c: u8| -> Option { + Some(match c { + b'A'..=b'Z' => c - b'A', + b'a'..=b'z' => c - b'a' + 26, + b'0'..=b'9' => c - b'0' + 52, + b'+' => 62, + b'/' => 63, + _ => return None, + } as u32) + }; + let mut out = Vec::with_capacity(bytes.len() / 4 * 3); + let last = bytes.len() / 4 - 1; + for (index, chunk) in bytes.chunks(4).enumerate() { + let pad = chunk.iter().rev().take_while(|&&c| c == b'=').count(); + // 只有最后一组可以带 1–2 个填充 + if pad > 2 || (pad > 0 && index != last) { + return Err(bad()); + } + let mut triple = 0u32; + for (position, &c) in chunk.iter().enumerate() { + let digit = if position >= 4 - pad { + 0 + } else { + value(c).ok_or_else(bad)? + }; + triple = (triple << 6) | digit; + } + out.extend_from_slice( + &[(triple >> 16) as u8, (triple >> 8) as u8, triple as u8][..3 - pad], + ); + } + if !out.starts_with(PNG_SIGNATURE) { + return Err(bad()); + } + Ok(out) +} + +#[cfg(test)] +#[path = "image_test.rs"] +mod tests; diff --git a/market/markdown-editor/backend/src/image_test.rs b/market/markdown-editor/backend/src/image_test.rs new file mode 100644 index 00000000..4f7eaad3 --- /dev/null +++ b/market/markdown-editor/backend/src/image_test.rs @@ -0,0 +1,38 @@ +use super::*; + +/// 1×1 的红色 PNG +const PIXEL: &str = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8DwHwAFBQIAX8jx0gAAAABJRU5ErkJggg=="; + +#[test] +fn png_data_uris_decode() { + let bytes = decode_png(PIXEL).unwrap(); + assert!(bytes.starts_with(PNG_SIGNATURE)); + assert_eq!(bytes.len(), 70); +} + +#[test] +fn other_data_is_rejected() { + for uri in [ + "", + "data:image/jpeg;base64,/9j/", + "data:image/png;base64,", + "data:image/png;base64,abc", + "data:image/png;base64,aGVsbG8=", + "data:image/png;base64,iV=BORw0", + "data:image/png;base64,iVBO!w0K", + ] { + assert_eq!(decode_png(uri).unwrap_err().code, "md.bad_image", "{uri}"); + } +} + +#[test] +fn save_writes_the_decoded_png() { + let path = std::env::temp_dir().join(format!("tf-md-long-{}.png", std::process::id())); + save_image(SaveArgs { + data_uri: PIXEL.to_owned(), + path: path.to_string_lossy().into_owned(), + }) + .unwrap(); + assert!(std::fs::read(&path).unwrap().starts_with(PNG_SIGNATURE)); + let _ = std::fs::remove_file(path); +} diff --git a/market/markdown-editor/backend/src/lib.rs b/market/markdown-editor/backend/src/lib.rs index d4ca3735..3ebe3426 100644 --- a/market/markdown-editor/backend/src/lib.rs +++ b/market/markdown-editor/backend/src/lib.rs @@ -1,6 +1,7 @@ -//! Markdown 编辑器插件后端:GFM 渲染、安全过滤、目录与统计,以及导出独立 HTML。 +//! Markdown 编辑器插件后端:GFM 渲染、安全过滤、目录与统计,导出独立 HTML 与保存长图。 mod export; +mod image; mod math; mod mermaid; mod render; @@ -35,6 +36,7 @@ impl ToolPlugin for MarkdownEditor { "export_html" => to_value(export::export_html(parse_args(args)?)?), "export_styled" => to_value(styled::styled_html(parse_args(args)?)?), "toc" => to_value(toc::toc(parse_args(args)?)?), + "save_image" => to_value(image::save_image(parse_args(args)?)?), other => Err(unknown_function(other)), } } diff --git a/market/markdown-editor/locales/en-US.json b/market/markdown-editor/locales/en-US.json index dcea5ed2..9179c5e7 100644 --- a/market/markdown-editor/locales/en-US.json +++ b/market/markdown-editor/locales/en-US.json @@ -5,6 +5,7 @@ "Supports GitHub Flavored Markdown: tables, task lists, footnotes, strikethrough and alerts such as > [!NOTE].", "LaTeX math: write $E=mc^2$ for inline math and $$ … $$ in its own paragraph for display math. It is converted to MathML locally, so exported HTML shows it offline.", "Code blocks tagged mermaid render as diagrams: flowcharts, sequence, class, state, ER, pie and Gantt charts and more. They are drawn locally, so exported HTML works offline too.", + "Export long image in the More menu turns the document into one PNG with adjustable width, margin, 1x–3x resolution and theme; diagrams and math are captured after they finish rendering.", "The preview is rendered in Rust. Raw HTML is shown as text and unsafe links are removed, so documents from anywhere are safe to open.", "Edit multiple files at once with tabs; changes can be auto-saved to disk on a configurable interval.", "Shortcuts: ⌘/Ctrl+S save, ⌘/Ctrl+B bold, ⌘/Ctrl+I italic, ⌘/Ctrl+K link. Drop a .md file onto the window to open it." @@ -92,7 +93,9 @@ "empty": "Nothing to preview yet" }, "errors": { - "md.too_large": "The document is larger than {{limit}}" + "md.too_large": "The document is larger than {{limit}}", + "md.bad_image": "The image data is invalid", + "md.write_failed": "Failed to write the file: {{detail}}" }, "api": { "render": { @@ -130,5 +133,28 @@ "anchorsOk": "All anchors valid", "anchorsBad": "{{count}} broken anchors", "empty": "No headings" + }, + "longImage": { + "menu": "Export long image…", + "title": "Export long image", + "hint": "Turns the preview into one PNG whose height follows the content, ready to share in chats and social apps.", + "width": "Width", + "margin": "Margin", + "scale": "Resolution", + "theme": "Theme", + "themeApp": "Follow app", + "themeLight": "Light", + "themeDark": "Dark", + "save": "Save PNG", + "copy": "Copy image", + "close": "Close", + "saving": "Creating the image…", + "copying": "Creating and copying…", + "saved": "Saved {{name}}", + "copied": "Image copied to the clipboard", + "scaled": "The document is long, so it was exported at {{scale}}x to stay within the image size limit", + "tooTall": "The document is {{height}} px tall, more than one image can hold. Use a wider width or export it in parts", + "failed": "Could not create the image: {{detail}}", + "px": "px" } } diff --git a/market/markdown-editor/locales/zh-CN.json b/market/markdown-editor/locales/zh-CN.json index dbf5e73b..e21ff45d 100644 --- a/market/markdown-editor/locales/zh-CN.json +++ b/market/markdown-editor/locales/zh-CN.json @@ -5,6 +5,7 @@ "支持 GitHub 风格 Markdown:表格、任务列表、脚注、删除线,以及 > [!NOTE] 等提示块。", "支持 LaTeX 公式:$E=mc^2$ 写行内公式,$$ … $$ 单独成段写块级公式;在本地转换为 MathML,导出的 HTML 无需联网即可显示。", "语言标记为 mermaid 的代码块会渲染成图表:流程图、时序图、类图、状态图、ER 图、饼图、甘特图等;在本地渲染,导出的 HTML 同样离线可看。", + "更多菜单中的「导出长图」可把文档生成一张 PNG:可设宽度、边距、1x–3x 清晰度和主题,图表与公式渲染完成后才截取。", "预览由 Rust 渲染:原始 HTML 按文本显示,不安全的链接会被移除,打开任何来源的文档都是安全的。", "支持多标签页同时编辑多个文件;可配置间隔把修改自动保存到本地文件。", "快捷键:⌘/Ctrl+S 保存,⌘/Ctrl+B 加粗,⌘/Ctrl+I 斜体,⌘/Ctrl+K 链接。把 .md 文件拖入窗口即可打开。" @@ -92,7 +93,9 @@ "empty": "暂无可预览的内容" }, "errors": { - "md.too_large": "文档超过 {{limit}}" + "md.too_large": "文档超过 {{limit}}", + "md.bad_image": "图片数据无效", + "md.write_failed": "写入文件失败:{{detail}}" }, "api": { "render": { @@ -130,5 +133,28 @@ "anchorsOk": "全部锚点有效", "anchorsBad": "{{count}} 个失效锚点", "empty": "没有标题" + }, + "longImage": { + "menu": "导出长图…", + "title": "导出长图", + "hint": "把预览内容生成一张 PNG 长图,高度随内容自动撑开,适合分享到聊天和社交平台。", + "width": "宽度", + "margin": "边距", + "scale": "清晰度", + "theme": "主题", + "themeApp": "跟随应用", + "themeLight": "浅色", + "themeDark": "深色", + "save": "保存 PNG", + "copy": "复制图片", + "close": "关闭", + "saving": "正在生成长图…", + "copying": "正在生成并复制…", + "saved": "已保存 {{name}}", + "copied": "长图已复制到剪贴板", + "scaled": "文档较长,已降为 {{scale}}x 以免超出图片尺寸上限", + "tooTall": "文档排版后高 {{height}} 像素,超出单张图片的尺寸上限,请调大宽度或分段导出", + "failed": "生成长图失败:{{detail}}", + "px": "px" } } diff --git a/market/markdown-editor/manifest.json b/market/markdown-editor/manifest.json index 1f9dbbfd..e6183843 100644 --- a/market/markdown-editor/manifest.json +++ b/market/markdown-editor/manifest.json @@ -128,6 +128,9 @@ ] } }, + "save_image": { + "interface": false + }, "toc": { "history": true, "interface": { diff --git a/market/markdown-editor/ui/package.json b/market/markdown-editor/ui/package.json index 99ede8d1..7c14de6f 100644 --- a/market/markdown-editor/ui/package.json +++ b/market/markdown-editor/ui/package.json @@ -7,7 +7,8 @@ ".": "./src/index.tsx" }, "scripts": { - "typecheck": "tsc -p tsconfig.json" + "typecheck": "tsc -p tsconfig.json", + "test": "node --experimental-strip-types --test tests/longImagePlan.test.mjs" }, "peerDependencies": { "react": "^19" diff --git a/market/markdown-editor/ui/src/LongImageDialog.tsx b/market/markdown-editor/ui/src/LongImageDialog.tsx new file mode 100644 index 00000000..f747ed47 --- /dev/null +++ b/market/markdown-editor/ui/src/LongImageDialog.tsx @@ -0,0 +1,136 @@ +import { useState } from 'react' +import { Button, Modal, NumberInput, SegmentedControl, Spinner, toast } from '@toolforge/ui' +import { host, usePlugin, usePluginState } from '@toolforge/plugin-ui-sdk' +import { Copy, ImageDown } from 'lucide-react' +import { LongImageTooTall, renderLongImage, toDataUri, type LongImage } from './longImage' +import { DEFAULT_OPTIONS, MARGIN_RANGE, WIDTH_RANGE, normalizeOptions, type ImageScale, type ImageTheme, type LongImageOptions } from './longImagePlan' + +export interface LongImageDialogProps { + open: boolean + onOpenChange: (open: boolean) => void + source: string + /** 文件名与导出文档标题 */ + title: string | undefined + fileName: string +} + +type Busy = 'save' | 'copy' | null + +/** 应用 0.2.6 起提供图片剪贴板;更早的应用里 SDK 没有这个方法,不显示复制按钮 */ +const canCopyImage = () => typeof (host.clipboard as { writeImage?: unknown }).writeImage === 'function' + +/** 导出长图:设置项固定高度一次显示完整,生成期间用遮罩提示,避免弹窗内容跳动 */ +export function LongImageDialog({ open, onOpenChange, source, title, fileName }: LongImageDialogProps) { + const { t, call, errorMessage } = usePlugin() + const [stored, setStored] = usePluginState('longImage', DEFAULT_OPTIONS) + const options = normalizeOptions(stored) + const [busy, setBusy] = useState(null) + const update = (patch: Partial) => setStored(normalizeOptions({ ...options, ...patch })) + + const generate = async (): Promise => { + const { html } = await call<{ html: string }>('export_html', { source, title }) + try { + const image = await renderLongImage(html, options, document.documentElement.classList.contains('dark')) + if (image.scale < options.scale) toast.info(t('longImage.scaled', { scale: image.scale })) + return image + } catch (error) { + if (error instanceof LongImageTooTall) { + toast.error(t('longImage.tooTall', { height: error.height })) + return null + } + throw error + } + } + + const act = async (kind: Exclude, action: () => Promise) => { + setBusy(kind) + try { + if (await action()) onOpenChange(false) + } catch (error) { + toast.error(error instanceof Error && !('code' in error) ? t('longImage.failed', { detail: error.message }) : errorMessage(error)) + } finally { + setBusy(null) + } + } + + const save = () => + act('save', async () => { + const path = await host.dialog.saveFile(`${fileName}.png`, [{ name: 'PNG', extensions: ['png'] }]) + if (!path) return false + const image = await generate() + if (!image) return false + await call('save_image', { dataUri: await toDataUri(image.png), path }) + toast.success(t('longImage.saved', { name: path.split(/[\\/]/).pop() ?? path })) + return true + }) + + const copy = () => + act('copy', async () => { + const image = await generate() + if (!image) return false + await host.clipboard.writeImage(new Uint8Array(await image.png.arrayBuffer())) + toast.success(t('longImage.copied')) + return true + }) + + const themes: { value: ImageTheme; label: string }[] = [ + { value: 'app', label: t('longImage.themeApp') }, + { value: 'light', label: t('longImage.themeLight') }, + { value: 'dark', label: t('longImage.themeDark') }, + ] + const scales: { value: `${ImageScale}`; label: string }[] = [ + { value: '1', label: '1x' }, + { value: '2', label: '2x' }, + { value: '3', label: '3x' }, + ] + + return ( + busy === null && onOpenChange(next)} + title={t('longImage.title')} + description={t('longImage.hint')} + closeLabel={t('longImage.close')} + size="sm" + footer={ + <> + {canCopyImage() && ( + + )} + + + } + > +
+
+ {t('longImage.width')} +
+ update({ width })} aria-label={t('longImage.width')} /> + {t('longImage.px')} +
+ {t('longImage.margin')} +
+ update({ margin })} aria-label={t('longImage.margin')} /> + {t('longImage.px')} +
+ {t('longImage.scale')} + update({ scale: Number(value) as ImageScale })} aria-label={t('longImage.scale')} /> + {t('longImage.theme')} + update({ theme })} aria-label={t('longImage.theme')} /> +
+ {busy && ( +
+ + {t(busy === 'save' ? 'longImage.saving' : 'longImage.copying')} +
+ )} +
+
+ ) +} diff --git a/market/markdown-editor/ui/src/MarkdownEditor.tsx b/market/markdown-editor/ui/src/MarkdownEditor.tsx index 5b37b298..d96c53cb 100644 --- a/market/markdown-editor/ui/src/MarkdownEditor.tsx +++ b/market/markdown-editor/ui/src/MarkdownEditor.tsx @@ -6,6 +6,7 @@ import { Code, Ellipsis, FileDown, + ImageDown, FilePlus, FileText, FolderOpen, @@ -26,6 +27,7 @@ import { TextQuote, X, } from 'lucide-react' +import { LongImageDialog } from './LongImageDialog' import type { AutoSaveMode, Draft, EditorStore, Heading as OutlineHeading, Rendered, ViewMode } from './types' import { AUTO_SAVE_MS } from './types' @@ -92,6 +94,7 @@ export function MarkdownEditor() { const [cursor, setCursor] = useState({ line: 1, column: 1 }) const [pendingClose, setPendingClose] = useState(null) const [busy, setBusy] = useState(false) + const [longImageOpen, setLongImageOpen] = useState(false) /** 最近一次生成的目录(含锚点校验结果),随下次生成刷新 */ const [tocOut, setTocOut] = useState(null) @@ -338,6 +341,7 @@ export function MarkdownEditor() { items={[ { key: 'saveAs', label: t('file.saveAs'), icon: , onSelect: saveAs }, { key: 'export', label: t('file.export'), icon: , onSelect: exportHtml }, + { key: 'longImage', label: t('longImage.menu'), icon: , disabled: !draft.text.trim(), onSelect: () => setLongImageOpen(true) }, { key: 'styled', label: t('styled.copy'), icon: , onSelect: copyStyled }, { key: 'copy', label: t('file.copyHtml'), icon: , disabled: !result, onSelect: () => result && copy(result.html) }, ...(draft.path @@ -587,6 +591,13 @@ export function MarkdownEditor() { } /> +
) } diff --git a/market/markdown-editor/ui/src/longImage.ts b/market/markdown-editor/ui/src/longImage.ts new file mode 100644 index 00000000..d2c15af6 --- /dev/null +++ b/market/markdown-editor/ui/src/longImage.ts @@ -0,0 +1,94 @@ +import { type ImageScale, type LongImageOptions, imageCss, planScale, splitExport, themeVariables } from './longImagePlan' + +export class LongImageTooTall extends Error { + constructor(readonly height: number) { + super(`document is ${height}px tall`) + } +} + +export interface LongImage { + png: Blob + width: number + height: number + /** 实际使用的倍数:画布放不下请求的倍数时会降低 */ + scale: ImageScale +} + +const nextFrame = () => new Promise((resolve) => requestAnimationFrame(() => resolve())) + +/** + * 把 export_html 的独立文档画成一张 PNG 长图。 + * + * 先在屏幕外的 Shadow DOM 里按目标宽度排版、等图片和字体加载完再量出高度, + * 再把同一份 DOM 序列化为 SVG foreignObject 画到画布上。SVG 必须用 data URL + * 加载:WebKit(macOS、Linux)对 blob URL 中含 foreignObject 的图片会污染画布, + * 之后 toBlob 抛出 SecurityError。 + */ +export async function renderLongImage(exported: string, options: LongImageOptions, appDark: boolean): Promise { + const { css, body } = splitExport(exported) + const dark = options.theme === 'dark' || (options.theme === 'app' && appDark) + + const host = document.createElement('div') + host.setAttribute('aria-hidden', 'true') + host.style.cssText = 'position:fixed;left:-100000px;top:0;pointer-events:none;' + const page = document.createElement('div') + page.className = 'page' + page.setAttribute('style', `${themeVariables(css, dark)}; width: ${options.width}px`) + const style = document.createElement('style') + style.textContent = imageCss(css, options.margin) + const article = document.createElement('article') + article.className = 'markdown-body' + // 正文来自插件后端:原始 HTML 已转成文本、链接已过滤,与预览插入的是同一份内容 + article.innerHTML = body + page.append(style, article) + host.attachShadow({ mode: 'open' }).append(page) + document.body.append(host) + + try { + // 图表等图片解码完成、字体就绪后再量高度,避免长图被截断 + await Promise.all([...article.querySelectorAll('img')].map((img) => img.decode().catch(() => undefined))) + await document.fonts.ready + await nextFrame() + const height = Math.ceil(page.getBoundingClientRect().height) + const scale = planScale(options.width, height, options.scale) + if (scale === null) throw new LongImageTooTall(height) + + const svg = + `` + + `${new XMLSerializer().serializeToString(page)}` + const image = new Image() + image.decoding = 'sync' + await new Promise((resolve, reject) => { + image.onload = () => resolve() + image.onerror = () => reject(new Error('long image failed to load')) + image.src = `data:image/svg+xml;charset=utf-8,${encodeURIComponent(svg)}` + }) + // 图片内嵌的图表在 onload 之后才完成绘制 + await nextFrame() + await nextFrame() + + const canvas = document.createElement('canvas') + canvas.width = options.width * scale + canvas.height = height * scale + const context = canvas.getContext('2d') + if (!context) throw new Error('canvas unavailable') + context.scale(scale, scale) + context.drawImage(image, 0, 0, options.width, height) + const png = await new Promise((resolve, reject) => + canvas.toBlob((blob) => (blob ? resolve(blob) : reject(new Error('png encoding failed'))), 'image/png'), + ) + return { png, width: options.width, height, scale } + } finally { + host.remove() + } +} + +/** Blob → data URI,交给后端解码写文件 */ +export function toDataUri(blob: Blob): Promise { + return new Promise((resolve, reject) => { + const reader = new FileReader() + reader.onload = () => resolve(String(reader.result)) + reader.onerror = () => reject(reader.error ?? new Error('read failed')) + reader.readAsDataURL(blob) + }) +} diff --git a/market/markdown-editor/ui/src/longImagePlan.ts b/market/markdown-editor/ui/src/longImagePlan.ts new file mode 100644 index 00000000..f85d2876 --- /dev/null +++ b/market/markdown-editor/ui/src/longImagePlan.ts @@ -0,0 +1,88 @@ +/** + * 长图导出中不依赖 DOM 的部分:从 export_html 的完整文档里取出样式与正文、 + * 生成指定主题的样式,以及在画布尺寸上限内选择缩放倍数。 + */ + +export type ImageTheme = 'app' | 'light' | 'dark' +export type ImageScale = 1 | 2 | 3 + +export interface LongImageOptions { + /** 图片内容宽度(CSS 像素,不含缩放) */ + width: number + /** 四周留白 */ + margin: number + scale: ImageScale + theme: ImageTheme +} + +export const DEFAULT_OPTIONS: LongImageOptions = { width: 720, margin: 40, scale: 2, theme: 'app' } +export const WIDTH_RANGE = { min: 320, max: 1600 } as const +export const MARGIN_RANGE = { min: 0, max: 120 } as const + +/** + * 画布上限:WebKit 与 Chromium 单边都不超过 32767 像素、总面积不超过 16384²; + * 超出时 toBlob 直接失败,因此先按上限降低缩放倍数 + */ +export const MAX_SIDE = 32767 +export const MAX_AREA = 16384 * 16384 + +/** 从 export_html 生成的独立文档中取出样式表和正文 */ +export function splitExport(html: string): { css: string; body: string } { + const css = between(html, '') + const body = between(html, '
', '
') + if (css === null || body === null) throw new Error('unexpected export_html output') + return { css, body } +} + +function between(text: string, open: string, close: string): string | null { + const start = text.indexOf(open) + const end = text.lastIndexOf(close) + return start < 0 || end < start ? null : text.slice(start + open.length, end) +} + +/** + * 导出样式里的两套颜色变量:第一个 :root 块是浅色, + * prefers-color-scheme: dark 媒体查询里的 :root 块是深色 + */ +export function themeVariables(css: string, dark: boolean): string { + const blocks = [...css.matchAll(/:root\s*\{([^}]*)\}/g)].map((match) => match[1]) + const declarations = (block: string | undefined) => + (block ?? '') + .split(';') + .map((part) => part.trim()) + .filter((part) => part.startsWith('--')) + const light = declarations(blocks[0]) + // 深色只覆盖颜色,缺少的变量沿用浅色 + const chosen = dark ? [...light, ...declarations(blocks[1])] : light + return [...chosen, `color-scheme: ${dark ? 'dark' : 'light'}`].join('; ') +} + +/** 长图用的样式:页面根节点替代 body,正文宽度占满、留白按设置 */ +export function imageCss(css: string, margin: number): string { + return ( + css.replace(/(^|\n)body\s*\{/, '$1.page {') + + `\n.page .markdown-body { max-width: none; margin: 0; padding: ${margin}px; }\n` + ) +} + +/** 不超过请求倍数、且画布在上限内的最大缩放倍数;连 1 倍都放不下时返回 null */ +export function planScale(width: number, height: number, scale: ImageScale): ImageScale | null { + for (let s = scale; s >= 1; s--) { + const w = width * s + const h = height * s + if (w <= MAX_SIDE && h <= MAX_SIDE && w * h <= MAX_AREA) return s as ImageScale + } + return null +} + +/** 界面传入的设置可能来自旧版本存储,逐项校正到合法范围 */ +export function normalizeOptions(value: Partial | null | undefined): LongImageOptions { + const clamp = (n: unknown, min: number, max: number, fallback: number) => + typeof n === 'number' && Number.isFinite(n) ? Math.min(max, Math.max(min, Math.round(n))) : fallback + return { + width: clamp(value?.width, WIDTH_RANGE.min, WIDTH_RANGE.max, DEFAULT_OPTIONS.width), + margin: clamp(value?.margin, MARGIN_RANGE.min, MARGIN_RANGE.max, DEFAULT_OPTIONS.margin), + scale: value?.scale === 1 || value?.scale === 2 || value?.scale === 3 ? value.scale : DEFAULT_OPTIONS.scale, + theme: value?.theme === 'light' || value?.theme === 'dark' || value?.theme === 'app' ? value.theme : DEFAULT_OPTIONS.theme, + } +} diff --git a/market/markdown-editor/ui/tests/longImagePlan.test.mjs b/market/markdown-editor/ui/tests/longImagePlan.test.mjs new file mode 100644 index 00000000..1c2ed589 --- /dev/null +++ b/market/markdown-editor/ui/tests/longImagePlan.test.mjs @@ -0,0 +1,45 @@ +import assert from 'node:assert/strict' +import { readFileSync } from 'node:fs' +import { join } from 'node:path' +import test from 'node:test' +import { DEFAULT_OPTIONS, MAX_SIDE, imageCss, normalizeOptions, planScale, splitExport, themeVariables } from '../src/longImagePlan.ts' + +const css = readFileSync(join(import.meta.dirname, '../../backend/src/export.css'), 'utf8') +const exported = `\n\n\n\n\n\n
\n

Hi

\n
\n\n\n` + +test('splitExport takes the stylesheet and article body', () => { + const { css: style, body } = splitExport(exported) + assert.equal(style.trim(), css.trim()) + assert.equal(body.trim(), '

Hi

') + assert.throws(() => splitExport('')) +}) + +test('themeVariables picks the light or dark palette from export.css', () => { + const light = themeVariables(css, false) + const dark = themeVariables(css, true) + assert.match(light, /--bg: #ffffff/) + assert.match(light, /color-scheme: light$/) + // 深色变量写在浅色之后,覆盖同名变量 + assert.ok(dark.lastIndexOf('--bg: #0d1117') > dark.indexOf('--bg: #ffffff')) + assert.match(dark, /color-scheme: dark$/) +}) + +test('imageCss swaps body for the page root and applies the margin', () => { + const out = imageCss(css, 24) + assert.match(out, /\.page \{\n\s*margin: 0;/) + assert.doesNotMatch(out, /(^|\n)body\s*\{/) + assert.match(out, /padding: 24px; \}/) +}) + +test('planScale lowers the scale to fit the canvas and gives up when 1x is too tall', () => { + assert.equal(planScale(720, 2000, 3), 3) + assert.equal(planScale(720, 12000, 3), 2) + assert.equal(planScale(720, 20000, 3), 1) + assert.equal(planScale(720, MAX_SIDE + 1, 2), null) +}) + +test('normalizeOptions repairs stored settings', () => { + assert.deepEqual(normalizeOptions(null), DEFAULT_OPTIONS) + assert.deepEqual(normalizeOptions({ width: 99999, margin: -5, scale: 4, theme: 'pink' }), { width: 1600, margin: 0, scale: 2, theme: 'app' }) + assert.deepEqual(normalizeOptions({ width: 400.4, margin: 10, scale: 3, theme: 'dark' }), { width: 400, margin: 10, scale: 3, theme: 'dark' }) +}) From 39b729a5b9f3d1dd3796145dd5c33c8caa6a4ef7 Mon Sep 17 00:00:00 2001 From: qianmoQ Date: Thu, 3 Dec 2026 03:31:05 -0500 Subject: [PATCH 13/15] fix(net): accept close-delimited bodies ending without TLS close_notify An HTTP/1 response with neither Content-Length nor Transfer-Encoding ends when the server closes the connection. Some servers, such as Verisign's RDAP service for its 404 answers, close TLS without sending close_notify, so rustls reported UnexpectedEof and plugins saw a network error instead of the status. curl and browsers treat this as the end of the body; responses with a length or chunked encoding still fail when cut short. --- crates/tf-net/src/lib.rs | 32 ++++++++++++++++++++++++---- crates/tf-net/src/lib_test.rs | 39 +++++++++++++++++++++++++++++++++++ 2 files changed, 67 insertions(+), 4 deletions(-) diff --git a/crates/tf-net/src/lib.rs b/crates/tf-net/src/lib.rs index 9354293d..4988d2ef 100644 --- a/crates/tf-net/src/lib.rs +++ b/crates/tf-net/src/lib.rs @@ -15,7 +15,7 @@ use std::sync::{Arc, Mutex, Once}; use std::thread::JoinHandle; use std::time::{Duration, Instant}; -use reqwest::header::{HeaderMap, HeaderName, HeaderValue, USER_AGENT}; +use reqwest::header::{HeaderMap, HeaderName, HeaderValue, TRANSFER_ENCODING, USER_AGENT}; use reqwest::redirect::Policy; use tf_plugin_api::net::{HttpRequest, HttpResponse}; use tf_plugin_api::{PluginError, PluginResult, cancelled}; @@ -78,6 +78,25 @@ fn too_large(limit: u64) -> PluginError { PluginError::new("net.too_large").with("limit", limit) } +/// 没有长度、也不分块的 HTTP/1 响应体以关闭连接结束。部分服务器(如 Verisign RDAP 的 404) +/// 关闭 TLS 连接时不发 close_notify,rustls 报 UnexpectedEof;这种响应本身无法区分截断, +/// curl 与浏览器都按正常结束处理,这里也一样。有长度或分块的响应仍然报错。 +fn is_unexpected_eof(error: &std::io::Error) -> bool { + let mut current: Option<&(dyn std::error::Error + 'static)> = Some(error); + while let Some(inner) = current { + current = match inner.downcast_ref::() { + Some(io) if io.kind() == std::io::ErrorKind::UnexpectedEof => return true, + // io::Error 的 source() 跳过它包着的错误本身,要用 get_ref 取出来继续找 + Some(io) => match io.get_ref() { + Some(wrapped) => Some(wrapped as &(dyn std::error::Error + 'static)), + None => inner.source(), + }, + None => inner.source(), + }; + } + false +} + /// 发送请求并读取完整响应;`cancelled` 在读取响应体时检查,`progress` 报告已读字节 pub fn send( request: &HttpRequest, @@ -138,15 +157,20 @@ pub fn send( if expected.is_some_and(|len| len > max_body) { return Err(too_large(max_body)); } + let close_delimited = expected.is_none() + && response.version() <= reqwest::Version::HTTP_11 + && !response.headers().contains_key(TRANSFER_ENCODING); let mut body = Vec::with_capacity(expected.unwrap_or(0).min(max_body) as usize); let mut buffer = vec![0u8; CHUNK]; loop { if cancel() { return Err(cancelled()); } - let read = response - .read(&mut buffer) - .map_err(|e| PluginError::new("net.failed").with("detail", e.to_string()))?; + let read = match response.read(&mut buffer) { + Ok(read) => read, + Err(e) if close_delimited && is_unexpected_eof(&e) => 0, + Err(e) => return Err(PluginError::new("net.failed").with("detail", e.to_string())), + }; if read == 0 { break; } diff --git a/crates/tf-net/src/lib_test.rs b/crates/tf-net/src/lib_test.rs index 231ac319..6dc9ebc4 100644 --- a/crates/tf-net/src/lib_test.rs +++ b/crates/tf-net/src/lib_test.rs @@ -227,3 +227,42 @@ fn writes_files() { "fs.io" ); } + +#[test] +fn unexpected_eof_is_found_anywhere_in_the_error_chain() { + use std::io::{Error, ErrorKind}; + let tls = Error::new( + ErrorKind::UnexpectedEof, + "peer closed connection without sending TLS close_notify", + ); + assert!(is_unexpected_eof(&tls)); + let wrapped = Error::other(Error::other(tls)); + assert!(is_unexpected_eof(&wrapped)); + assert!(!is_unexpected_eof(&Error::new( + ErrorKind::ConnectionReset, + "reset" + ))); +} + +#[test] +fn close_delimited_bodies_end_when_the_connection_closes() { + use std::io::{BufRead, BufReader, Write}; + let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).unwrap(); + let port = listener.local_addr().unwrap().port(); + std::thread::spawn(move || { + let (stream, _) = listener.accept().unwrap(); + let mut reader = BufReader::new(stream.try_clone().unwrap()); + let mut line = String::new(); + while reader.read_line(&mut line).unwrap() > 2 { + line.clear(); + } + let mut stream = stream; + // 没有 Content-Length 也没有 Transfer-Encoding:响应体读到连接关闭为止 + stream + .write_all(b"HTTP/1.1 404 Not Found\r\nContent-Type: application/rdap+json\r\n\r\n{}") + .unwrap(); + }); + let response = run(&get(&format!("http://127.0.0.1:{port}/domain/x.com"))).unwrap(); + assert_eq!(response.status, 404); + assert_eq!(text(&response), "{}"); +} From 8b8b75d0b6496d8195ed66ac55be9cd5df2f5ba4 Mon Sep 17 00:00:00 2001 From: qianmoQ Date: Thu, 3 Dec 2026 03:33:56 -0500 Subject: [PATCH 14/15] feat(domain-lookup): add RDAP domain lookup with batch queries Find the registry from the IANA bootstrap file, cached by ETag, and follow the registrar's RDAP link for contacts. Show the registrar, key dates, EPP statuses, name servers and DNSSEC, and mark redacted data from RFC 9537 declarations and placeholder text, saying whether the registry or the registrar redacted it. - a 404 means the registry has no such domain; expiry shows unknown or expired, never a negative countdown - TLDs without RDAP, such as .de and .cn, show the IANA record instead, since plugins cannot use WHOIS on port 43 - batches queue per RDAP host with one request in flight, wait for Retry-After or back off with jitter, stop on 403, cache results for six hours and export CSV - lookup is open to the CLI and agents; needs app 0.2.6 for Verisign's not-found answers Refs #183 --- Cargo.lock | 12 + market/domain-lookup/backend/Cargo.toml | 21 + market/domain-lookup/backend/src/bootstrap.rs | 132 ++++++ .../backend/src/bootstrap_test.rs | 88 ++++ market/domain-lookup/backend/src/domain.rs | 155 +++++++ .../domain-lookup/backend/src/domain_test.rs | 99 ++++ market/domain-lookup/backend/src/lib.rs | 46 ++ market/domain-lookup/backend/src/lib_test.rs | 39 ++ market/domain-lookup/backend/src/parse.rs | 428 ++++++++++++++++++ .../domain-lookup/backend/src/parse_test.rs | 211 +++++++++ market/domain-lookup/backend/src/rdap.rs | 188 ++++++++ market/domain-lookup/backend/src/rdap_test.rs | 149 ++++++ market/domain-lookup/icon.svg | 1 + market/domain-lookup/locales/en-US.json | 197 ++++++++ market/domain-lookup/locales/zh-CN.json | 196 ++++++++ market/domain-lookup/manifest.json | 41 ++ market/domain-lookup/ui/package.json | 25 + market/domain-lookup/ui/src/Card.tsx | 262 +++++++++++ market/domain-lookup/ui/src/data.ts | 50 ++ market/domain-lookup/ui/src/index.tsx | 316 +++++++++++++ market/domain-lookup/ui/src/logic.ts | 83 ++++ market/domain-lookup/ui/src/queue.ts | 98 ++++ market/domain-lookup/ui/src/types.ts | 98 ++++ market/domain-lookup/ui/tests/logic.test.mjs | 54 +++ market/domain-lookup/ui/tests/queue.test.mjs | 95 ++++ market/domain-lookup/ui/tsconfig.json | 4 + pnpm-lock.yaml | 31 ++ 27 files changed, 3119 insertions(+) create mode 100644 market/domain-lookup/backend/Cargo.toml create mode 100644 market/domain-lookup/backend/src/bootstrap.rs create mode 100644 market/domain-lookup/backend/src/bootstrap_test.rs create mode 100644 market/domain-lookup/backend/src/domain.rs create mode 100644 market/domain-lookup/backend/src/domain_test.rs create mode 100644 market/domain-lookup/backend/src/lib.rs create mode 100644 market/domain-lookup/backend/src/lib_test.rs create mode 100644 market/domain-lookup/backend/src/parse.rs create mode 100644 market/domain-lookup/backend/src/parse_test.rs create mode 100644 market/domain-lookup/backend/src/rdap.rs create mode 100644 market/domain-lookup/backend/src/rdap_test.rs create mode 100644 market/domain-lookup/icon.svg create mode 100644 market/domain-lookup/locales/en-US.json create mode 100644 market/domain-lookup/locales/zh-CN.json create mode 100644 market/domain-lookup/manifest.json create mode 100644 market/domain-lookup/ui/package.json create mode 100644 market/domain-lookup/ui/src/Card.tsx create mode 100644 market/domain-lookup/ui/src/data.ts create mode 100644 market/domain-lookup/ui/src/index.tsx create mode 100644 market/domain-lookup/ui/src/logic.ts create mode 100644 market/domain-lookup/ui/src/queue.ts create mode 100644 market/domain-lookup/ui/src/types.ts create mode 100644 market/domain-lookup/ui/tests/logic.test.mjs create mode 100644 market/domain-lookup/ui/tests/queue.test.mjs create mode 100644 market/domain-lookup/ui/tsconfig.json diff --git a/Cargo.lock b/Cargo.lock index 93bf73f3..bdc980a2 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -9268,6 +9268,18 @@ dependencies = [ "tf-plugin-guest", ] +[[package]] +name = "tfm-domain-lookup" +version = "0.1.0" +dependencies = [ + "idna", + "serde", + "serde_json", + "tf-plugin-api", + "tf-plugin-guest", + "tiny_http", +] + [[package]] name = "tfm-domain-toolbox" version = "0.1.0" diff --git a/market/domain-lookup/backend/Cargo.toml b/market/domain-lookup/backend/Cargo.toml new file mode 100644 index 00000000..1dfde8be --- /dev/null +++ b/market/domain-lookup/backend/Cargo.toml @@ -0,0 +1,21 @@ +[package] +name = "tfm-domain-lookup" +description = "ToolForge market plugin: domain registration lookup over RDAP" +version = "0.1.0" +edition.workspace = true +license.workspace = true +authors.workspace = true + +[lib] +# cdylib 编译为 WASM 组件,rlib 供本机单元测试 +crate-type = ["cdylib", "rlib"] + +[dependencies] +serde.workspace = true +serde_json.workspace = true +tf-plugin-api.workspace = true +tf-plugin-guest = { path = "../../../crates/tf-plugin-guest" } +idna = "1" + +[dev-dependencies] +tiny_http = "0.12" diff --git a/market/domain-lookup/backend/src/bootstrap.rs b/market/domain-lookup/backend/src/bootstrap.rs new file mode 100644 index 00000000..78b262b7 --- /dev/null +++ b/market/domain-lookup/backend/src/bootstrap.rs @@ -0,0 +1,132 @@ +//! IANA 的 RDAP 引导文件(dns.json):顶级域 → RDAP 服务地址。 +//! 用条件请求(ETag / If-Modified-Since)刷新,未变化时服务器返回 304,不重复下载。 + +use serde::{Deserialize, Serialize}; +use serde_json::Value; +use tf_plugin_api::{PluginError, PluginResult}; + +use crate::rdap::{get, header}; + +pub const BOOTSTRAP_URL: &str = "https://data.iana.org/rdap/dns.json"; +const MAX_BOOTSTRAP: u64 = 4 * 1024 * 1024; + +/// 一组共享 RDAP 服务的顶级域;`urls` 按引导文件中的顺序依次尝试 +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct Service { + pub tlds: Vec, + pub urls: Vec, +} + +#[derive(Debug, Default, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct BootstrapArgs { + /// 上次响应的 ETag 与 Last-Modified,用于条件请求 + #[serde(default)] + pub etag: Option, + #[serde(default)] + pub last_modified: Option, +} + +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct Bootstrap { + /// 服务器确认缓存仍然有效(304);此时 services 为空,继续用缓存 + pub not_modified: bool, + pub services: Vec, + pub etag: Option, + pub last_modified: Option, + /// 引导文件自身的发布时间 + pub publication: Option, +} + +pub fn fetch(args: BootstrapArgs) -> PluginResult { + fetch_from(BOOTSTRAP_URL, args) +} + +pub fn fetch_from(url: &str, args: BootstrapArgs) -> PluginResult { + let mut headers = vec![("Accept".to_owned(), "application/json".to_owned())]; + if let Some(etag) = args.etag.filter(|v| !v.is_empty()) { + headers.push(("If-None-Match".to_owned(), etag)); + } + if let Some(date) = args.last_modified.filter(|v| !v.is_empty()) { + headers.push(("If-Modified-Since".to_owned(), date)); + } + let host = crate::domain::host_of(url); + let response = get(url, headers, MAX_BOOTSTRAP) + .map_err(|e| PluginError::new("bootstrap.failed").with("detail", e.code))?; + let etag = header(&response.headers, "etag"); + let last_modified = header(&response.headers, "last-modified"); + match response.status { + 304 => Ok(Bootstrap { + not_modified: true, + services: Vec::new(), + etag, + last_modified, + publication: None, + }), + 200 => { + let (services, publication) = parse(&response.body)?; + Ok(Bootstrap { + not_modified: false, + services, + etag, + last_modified, + publication, + }) + } + status => { + Err(PluginError::new("bootstrap.failed") + .with("detail", format!("HTTP {status} ({host})"))) + } + } +} + +/// 解析 dns.json;只保留 http(s) 地址,地址统一以 `/` 结尾,顶级域转小写 +pub fn parse(body: &[u8]) -> PluginResult<(Vec, Option)> { + let bad = || PluginError::new("bootstrap.bad_file"); + let value: Value = serde_json::from_slice(body).map_err(|_| bad())?; + let entries = value + .get("services") + .and_then(Value::as_array) + .ok_or_else(bad)?; + let strings = |v: &Value| -> Vec { + v.as_array() + .map(|items| { + items + .iter() + .filter_map(Value::as_str) + .map(str::to_owned) + .collect() + }) + .unwrap_or_default() + }; + let services = entries + .iter() + .filter_map(|entry| { + let pair = entry.as_array()?; + let tlds: Vec = strings(pair.first()?) + .into_iter() + .map(|t| t.trim().trim_matches('.').to_ascii_lowercase()) + .filter(|t| !t.is_empty()) + .collect(); + let urls: Vec = strings(pair.get(1)?) + .into_iter() + .filter(|u| u.starts_with("https://") || u.starts_with("http://")) + .map(|u| if u.ends_with('/') { u } else { format!("{u}/") }) + .collect(); + (!tlds.is_empty() && !urls.is_empty()).then_some(Service { tlds, urls }) + }) + .collect::>(); + if services.is_empty() { + return Err(bad()); + } + let publication = value + .get("publication") + .and_then(Value::as_str) + .map(str::to_owned); + Ok((services, publication)) +} + +#[cfg(test)] +#[path = "bootstrap_test.rs"] +mod tests; diff --git a/market/domain-lookup/backend/src/bootstrap_test.rs b/market/domain-lookup/backend/src/bootstrap_test.rs new file mode 100644 index 00000000..528b423f --- /dev/null +++ b/market/domain-lookup/backend/src/bootstrap_test.rs @@ -0,0 +1,88 @@ +use super::*; + +#[test] +fn parses_services_and_normalizes_urls() { + let body = br#"{ + "publication": "2026-12-02T20:00:03Z", + "services": [ + [["COM", "net"], ["https://rdap.verisign.com/com/v1"]], + [["kg"], ["http://rdap.cctld.kg/", "ftp://nope/"]], + [["bad"], ["ftp://only/"]], + [[], ["https://empty/"]] + ] + }"#; + let (services, publication) = parse(body).unwrap(); + assert_eq!(publication.as_deref(), Some("2026-12-02T20:00:03Z")); + assert_eq!( + services, + vec![ + Service { + tlds: vec!["com".into(), "net".into()], + urls: vec!["https://rdap.verisign.com/com/v1/".into()] + }, + Service { + tlds: vec!["kg".into()], + urls: vec!["http://rdap.cctld.kg/".into()] + }, + ] + ); +} + +#[test] +fn rejects_files_without_services() { + assert_eq!(parse(b"{}").unwrap_err().code, "bootstrap.bad_file"); + assert_eq!(parse(b"not json").unwrap_err().code, "bootstrap.bad_file"); + assert_eq!( + parse(br#"{"services": []}"#).unwrap_err().code, + "bootstrap.bad_file" + ); +} + +#[test] +fn conditional_requests_send_validators_and_accept_304() { + let server = tiny_http::Server::http("127.0.0.1:0").unwrap(); + let url = format!( + "http://127.0.0.1:{}/dns.json", + server.server_addr().to_ip().unwrap().port() + ); + std::thread::spawn(move || { + for request in server.incoming_requests() { + let header = |name: &'static str| { + request + .headers() + .iter() + .find(|h| h.field.equiv(name)) + .map(|h| h.value.to_string()) + }; + let response = if header("If-None-Match").as_deref() == Some("\"v1\"") + && header("If-Modified-Since").is_some() + { + tiny_http::Response::from_string("").with_status_code(304) + } else { + tiny_http::Response::from_string( + r#"{"services":[[["com"],["https://r.example/"]]]}"#, + ) + .with_header(tiny_http::Header::from_bytes("ETag", "\"v1\"").unwrap()) + .with_header( + tiny_http::Header::from_bytes("Last-Modified", "Wed, 02 Dec 2026 20:00:03 GMT") + .unwrap(), + ) + }; + let _ = request.respond(response); + } + }); + let fresh = fetch_from(&url, BootstrapArgs::default()).unwrap(); + assert!(!fresh.not_modified); + assert_eq!(fresh.services.len(), 1); + assert_eq!(fresh.etag.as_deref(), Some("\"v1\"")); + let cached = fetch_from( + &url, + BootstrapArgs { + etag: fresh.etag, + last_modified: fresh.last_modified, + }, + ) + .unwrap(); + assert!(cached.not_modified); + assert!(cached.services.is_empty()); +} diff --git a/market/domain-lookup/backend/src/domain.rs b/market/domain-lookup/backend/src/domain.rs new file mode 100644 index 00000000..6e8338cf --- /dev/null +++ b/market/domain-lookup/backend/src/domain.rs @@ -0,0 +1,155 @@ +//! 输入整理:从网址或带空格的列表中取出域名,转为 ASCII(国际化域名转 Punycode), +//! 按最长后缀匹配找到负责的 RDAP 服务,并生成批量查询计划。 + +use serde::{Deserialize, Serialize}; +use tf_plugin_api::{PluginError, PluginResult}; + +use crate::bootstrap::Service; + +/// 没有 RDAP 服务的顶级域改查 IANA 的顶级域记录 +pub const IANA_HOST: &str = "rdap.iana.org"; +/// 一次批量查询的上限,避免对注册局造成压力 +pub const MAX_BATCH: usize = 500; + +/// 整理单个输入:去掉协议、路径、端口、账号和末尾的点,小写并转 ASCII +pub fn normalize(raw: &str) -> Result { + let mut text = raw.trim(); + if let Some((_, rest)) = text.split_once("://") { + text = rest; + } + text = text.split(['/', '?', '#']).next().unwrap_or_default(); + if let Some((_, host)) = text.rsplit_once('@') { + text = host; + } + // 端口:IPv6 地址不是域名,冒号后面全部去掉即可 + text = text.split(':').next().unwrap_or_default(); + let text = text.trim_end_matches('.'); + if text.is_empty() { + return Err("domain.empty"); + } + let ascii = idna::domain_to_ascii(text).map_err(|_| "domain.invalid")?; + let labels: Vec<&str> = ascii.split('.').collect(); + let label_ok = |label: &&str| { + !label.is_empty() + && label.len() <= 63 + && !label.starts_with('-') + && !label.ends_with('-') + && label + .bytes() + .all(|b| b.is_ascii_alphanumeric() || b == b'-') + }; + if labels.len() < 2 || ascii.len() > 253 || !labels.iter().all(label_ok) { + return Err("domain.invalid"); + } + // 顶级域不会是纯数字:排除 IPv4 地址 + if labels + .last() + .is_some_and(|tld| tld.bytes().all(|b| b.is_ascii_digit())) + { + return Err("domain.invalid"); + } + Ok(ascii) +} + +/// 国际化域名的 Unicode 形式;与 ASCII 相同时返回 None +pub fn unicode_of(ascii: &str) -> Option { + let (unicode, result) = idna::domain_to_unicode(ascii); + (result.is_ok() && unicode != ascii).then_some(unicode) +} + +pub fn tld_of(ascii: &str) -> &str { + ascii.rsplit('.').next().unwrap_or(ascii) +} + +/// 按最长后缀匹配负责该域名的服务 +pub fn route<'a>(ascii: &str, services: &'a [Service]) -> Option<&'a Service> { + services + .iter() + .flat_map(|service| service.tlds.iter().map(move |tld| (tld, service))) + .filter(|(tld, _)| ascii == tld.as_str() || ascii.ends_with(&format!(".{tld}"))) + .max_by_key(|(tld, _)| tld.len()) + .map(|(_, service)| service) +} + +pub fn host_of(url: &str) -> String { + let rest = url.split_once("://").map_or(url, |(_, rest)| rest); + rest.split(['/', '?', '#']) + .next() + .unwrap_or_default() + .to_ascii_lowercase() +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct PlanArgs { + pub input: String, + #[serde(default)] + pub services: Vec, +} + +#[derive(Debug, Serialize, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct PlanItem { + pub input: String, + pub domain: Option, + pub unicode: Option, + /// 负责查询的 RDAP 服务器主机名:批量查询按它排队,同一主机一次只发一个请求 + pub host: Option, + /// 无法查询时的错误码 + pub error: Option, +} + +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct Plan { + pub items: Vec, + /// 去掉的重复项数 + pub duplicates: usize, +} + +/// 拆分批量输入(空白、逗号、分号分隔),去重并为每个域名找到查询主机 +pub fn plan(args: PlanArgs) -> PluginResult { + let mut seen = std::collections::HashSet::new(); + let mut items = Vec::new(); + let mut duplicates = 0; + for input in args + .input + .split([' ', '\t', '\n', '\r', ',', ';', ',', ';']) + .filter(|s| !s.trim().is_empty()) + { + let item = match normalize(input) { + Ok(domain) => { + if !seen.insert(domain.clone()) { + duplicates += 1; + continue; + } + let host = route(&domain, &args.services) + .and_then(|service| service.urls.first()) + .map_or_else(|| IANA_HOST.to_owned(), |url| host_of(url)); + PlanItem { + input: input.to_owned(), + unicode: unicode_of(&domain), + domain: Some(domain), + host: Some(host), + error: None, + } + } + Err(code) => PlanItem { + input: input.to_owned(), + domain: None, + unicode: None, + host: None, + error: Some(code.to_owned()), + }, + }; + items.push(item); + if items.len() > MAX_BATCH { + return Err(PluginError::new("domain.too_many").with("limit", MAX_BATCH)); + } + } + Ok(Plan { items, duplicates }) +} + +#[cfg(test)] +#[path = "domain_test.rs"] +mod tests; diff --git a/market/domain-lookup/backend/src/domain_test.rs b/market/domain-lookup/backend/src/domain_test.rs new file mode 100644 index 00000000..c671889a --- /dev/null +++ b/market/domain-lookup/backend/src/domain_test.rs @@ -0,0 +1,99 @@ +use super::*; + +fn services() -> Vec { + vec![ + Service { + tlds: vec!["com".into(), "net".into()], + urls: vec!["https://rdap.verisign.com/com/v1/".into()], + }, + Service { + tlds: vec!["uk".into()], + urls: vec!["https://rdap.nominet.uk/uk/".into()], + }, + Service { + tlds: vec!["co.uk".into()], + urls: vec!["https://rdap.example/couk/".into()], + }, + ] +} + +#[test] +fn normalizes_urls_and_case() { + assert_eq!( + normalize(" HTTPS://User@WWW.Example.COM:8443/path?q#x ").unwrap(), + "www.example.com" + ); + assert_eq!(normalize("example.com.").unwrap(), "example.com"); + assert_eq!(normalize("例子.中国").unwrap(), "xn--fsqu00a.xn--fiqs8s"); + assert_eq!( + unicode_of("xn--fsqu00a.xn--fiqs8s").as_deref(), + Some("例子.中国") + ); + assert_eq!(unicode_of("example.com"), None); +} + +#[test] +fn rejects_what_is_not_a_domain() { + for bad in [ + "", + "com", + "a..b", + "-a.com", + "a-.com", + "1.2.3.4", + "exa mple.com", + &format!("{}.com", "a".repeat(64)), + ] { + assert!(normalize(bad).is_err(), "{bad}"); + } +} + +#[test] +fn routes_by_longest_suffix_and_falls_back_to_iana() { + let services = services(); + assert_eq!(route("github.com", &services).unwrap().tlds[0], "com"); + assert_eq!(route("bbc.co.uk", &services).unwrap().tlds[0], "co.uk"); + assert_eq!(route("nominet.uk", &services).unwrap().tlds[0], "uk"); + assert!(route("denic.de", &services).is_none()); + // 后缀必须按标签匹配:notcom 不属于 com + assert!(route("example.notcom", &services).is_none()); +} + +#[test] +fn plans_batches_by_host_and_skips_duplicates() { + let plan = plan(PlanArgs { + input: "github.com\nexample.net, GitHub.com;denic.de;;bad..x".into(), + services: services(), + }) + .unwrap(); + assert_eq!(plan.duplicates, 1); + let hosts: Vec<_> = plan.items.iter().map(|i| i.host.as_deref()).collect(); + // .com 与 .net 共用 Verisign 的主机:批量队列按主机而不是按顶级域排队 + assert_eq!( + hosts, + vec![ + Some("rdap.verisign.com"), + Some("rdap.verisign.com"), + Some(IANA_HOST), + None + ] + ); + assert_eq!(plan.items[3].error.as_deref(), Some("domain.invalid")); +} + +#[test] +fn batches_are_capped() { + let input = (0..=MAX_BATCH) + .map(|i| format!("d{i}.com")) + .collect::>() + .join(" "); + assert_eq!( + plan(PlanArgs { + input, + services: services() + }) + .unwrap_err() + .code, + "domain.too_many" + ); +} diff --git a/market/domain-lookup/backend/src/lib.rs b/market/domain-lookup/backend/src/lib.rs new file mode 100644 index 00000000..cca30bf7 --- /dev/null +++ b/market/domain-lookup/backend/src/lib.rs @@ -0,0 +1,46 @@ +//! 域名信息查询(在线安装插件):经 RDAP 查询注册商、注册与到期日期、状态、DNS 服务器 +//! 与 DNSSEC,并如实标注注册局或注册商隐去的隐私信息。顶级域没有 RDAP 时给出 IANA 的 +//! 顶级域信息。插件运行在沙箱中只能发 HTTP 请求,不支持 43 端口的 WHOIS。 + +mod bootstrap; +mod domain; +mod parse; +mod rdap; + +use serde_json::Value; +use tf_plugin_api::{Manifest, PluginResult, ToolPlugin, parse_args, to_value, unknown_function}; + +const MANIFEST: &str = include_str!("../../manifest.json"); + +pub struct DomainLookup { + manifest: Manifest, +} + +impl Default for DomainLookup { + fn default() -> Self { + Self { + manifest: Manifest::from_static(MANIFEST), + } + } +} + +impl ToolPlugin for DomainLookup { + fn manifest(&self) -> &Manifest { + &self.manifest + } + + fn call(&self, function: &str, args: Value) -> PluginResult { + match function { + "bootstrap" => to_value(bootstrap::fetch(parse_args(args)?)?), + "plan" => to_value(domain::plan(parse_args(args)?)?), + "lookup" => to_value(rdap::lookup(parse_args(args)?)?), + other => Err(unknown_function(other)), + } + } +} + +tf_plugin_guest::export_plugin!(DomainLookup); + +#[cfg(test)] +#[path = "lib_test.rs"] +mod tests; diff --git a/market/domain-lookup/backend/src/lib_test.rs b/market/domain-lookup/backend/src/lib_test.rs new file mode 100644 index 00000000..b11c2453 --- /dev/null +++ b/market/domain-lookup/backend/src/lib_test.rs @@ -0,0 +1,39 @@ +use super::*; +use serde_json::json; + +#[test] +fn dispatches_offline_functions() { + let tool = DomainLookup::default(); + let services = json!([{ "tlds": ["com"], "urls": ["https://rdap.example/"] }]); + let plan = tool + .call( + "plan", + json!({ "input": "Example.com, bad..name", "services": services }), + ) + .unwrap(); + assert_eq!(plan["items"][0]["domain"], "example.com"); + assert_eq!(plan["items"][0]["host"], "rdap.example"); + assert_eq!(plan["items"][1]["error"], "domain.invalid"); + assert_eq!( + tool.call("nope", json!({})).unwrap_err().code, + "plugin.function_not_found" + ); + for function in ["bootstrap", "plan", "lookup"] { + assert!(tool.manifest().functions.contains_key(function)); + } +} + +#[test] +fn lookup_rejects_invalid_input_before_any_request() { + let error = DomainLookup::default() + .call("lookup", json!({ "domain": "not a domain" })) + .unwrap_err(); + assert_eq!(error.code, "domain.invalid"); +} + +#[test] +fn declared_interfaces_match_backend_args() { + let checked = + tf_plugin_api::interface::check_declared_interfaces(&DomainLookup::default()).unwrap(); + assert_eq!(checked, 1); +} diff --git a/market/domain-lookup/backend/src/parse.rs b/market/domain-lookup/backend/src/parse.rs new file mode 100644 index 00000000..0a0f22df --- /dev/null +++ b/market/domain-lookup/backend/src/parse.rs @@ -0,0 +1,428 @@ +//! 把 RDAP 响应(RFC 9083)整理成信息卡:注册商、联系人、关键日期、状态、DNS 与 DNSSEC。 +//! +//! 隐私信息如实标注:首先依据 RFC 9537 顶层的 `redacted` 数组(字段、方式、原因), +//! 其次参考实体备注里的隐私说明,以及姓名、单位、邮箱中的占位文本; +//! 并区分是注册局还是注册商的响应隐去的。不从字段为空去推断。 + +use serde::Serialize; +use serde_json::Value; + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +#[serde(rename_all = "lowercase")] +pub enum Party { + Registry, + Registrar, +} + +#[derive(Debug, Default, Serialize, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct Registrar { + pub name: Option, + pub iana_id: Option, + pub abuse_email: Option, + pub abuse_phone: Option, +} + +#[derive(Debug, Serialize, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct Contact { + /// registrant / administrative / technical / billing + pub role: String, + pub by: Party, + pub name: Option, + pub organization: Option, + pub email: Option, + pub phone: Option, + pub country: Option, + /// 值是隐私占位文本(如 REDACTED FOR PRIVACY)的字段 + pub placeholders: Vec, + /// 实体备注说明信息已隐去 + pub remarks_redacted: bool, +} + +#[derive(Debug, Default, Serialize, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct Events { + pub registration: Option, + pub expiration: Option, + pub last_changed: Option, + pub last_rdap_update: Option, +} + +/// RFC 9537 声明的隐去字段 +#[derive(Debug, Serialize, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct Redaction { + pub field: String, + pub by: Party, + /// removal / emptyValue / partialValue / replacementValue + pub method: Option, + pub reason: Option, +} + +#[derive(Debug, Serialize, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct Source { + pub by: Party, + pub url: String, + /// 这次请求失败时的错误码(注册商查询失败不影响注册局结果) + pub error: Option, +} + +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct RawResponse { + pub by: Party, + pub url: String, + pub json: Value, +} + +#[derive(Debug, Default, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct DomainInfo { + pub ldh_name: String, + pub handle: Option, + pub statuses: Vec, + pub registrar: Option, + pub contacts: Vec, + pub events: Events, + pub nameservers: Vec, + pub dnssec: Option, + pub redactions: Vec, + pub sources: Vec, + pub raw: Vec, +} + +impl DomainInfo { + pub fn note_source(&mut self, by: Party, url: &str, error: Option<&str>) { + self.sources.push(Source { + by, + url: url.to_owned(), + error: error.map(str::to_owned), + }); + } +} + +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct TldInfo { + pub tld: String, + /// 顶级域管理机构 + pub manager: Option, + /// 管理机构公布的注册信息网址 + pub registration_url: Option, + pub nameservers: Vec, + pub dnssec: Option, + pub registered: Option, + pub last_changed: Option, + pub raw: Value, +} + +const CONTACT_ROLES: [&str; 4] = ["registrant", "administrative", "technical", "billing"]; + +/// 注册商常用的隐私占位文本 +const PLACEHOLDERS: [&str; 9] = [ + "redacted", + "data protected", + "not disclosed", + "withheld for privacy", + "privacy protect", + "gdpr masked", + "statutory masking", + "non-public data", + "contact privacy", +]; + +pub fn is_placeholder(value: &str) -> bool { + let lower = value.to_lowercase(); + PLACEHOLDERS.iter().any(|p| lower.contains(p)) +} + +fn text(value: &Value, key: &str) -> Option { + value + .get(key) + .and_then(Value::as_str) + .map(str::trim) + .filter(|s| !s.is_empty()) + .map(str::to_owned) +} + +fn array<'a>(value: &'a Value, key: &str) -> &'a [Value] { + value + .get(key) + .and_then(Value::as_array) + .map_or(&[], Vec::as_slice) +} + +fn roles(entity: &Value) -> Vec<&str> { + array(entity, "roles") + .iter() + .filter_map(Value::as_str) + .collect() +} + +/// vCard 属性:`[名称, 参数, 类型, 值…]`;值是数组时(org、adr)拼成一行 +fn vcard<'a>(entity: &'a Value, name: &str) -> Option<&'a Value> { + entity + .get("vcardArray")? + .as_array()? + .get(1)? + .as_array()? + .iter() + .find(|prop| { + prop.get(0) + .and_then(Value::as_str) + .is_some_and(|n| n.eq_ignore_ascii_case(name)) + }) +} + +fn vcard_text(entity: &Value, name: &str) -> Option { + let value = vcard(entity, name)?.get(3)?; + let joined = match value { + Value::String(s) => s.trim().to_owned(), + Value::Array(parts) => parts + .iter() + .filter_map(Value::as_str) + .map(str::trim) + .filter(|s| !s.is_empty()) + .collect::>() + .join(" "), + _ => String::new(), + }; + (!joined.is_empty()).then_some(joined) +} + +fn country(entity: &Value) -> Option { + let adr = vcard(entity, "adr")?; + let code = adr.get(1).and_then(|params| text(params, "cc")); + let name = adr + .get(3) + .and_then(Value::as_array) + .and_then(|parts| parts.get(6)) + .and_then(Value::as_str) + .map(str::trim) + .filter(|s| !s.is_empty()) + .map(str::to_owned); + code.or(name) +} + +fn remarks_mention_redaction(entity: &Value) -> bool { + array(entity, "remarks").iter().any(|remark| { + let title = text(remark, "title").unwrap_or_default(); + let description: Vec<&str> = array(remark, "description") + .iter() + .filter_map(Value::as_str) + .collect(); + is_placeholder(&title) || description.iter().any(|d| is_placeholder(d)) + }) +} + +fn contact(entity: &Value, role: &str, by: Party) -> Contact { + let mut placeholders = Vec::new(); + // 姓名、单位、邮箱常被替换成占位文本:记下字段,值不当作真实信息展示 + let mut field = |name: &str, value: Option| match value { + Some(v) if is_placeholder(&v) => { + placeholders.push(name.to_owned()); + None + } + other => other, + }; + let name = field("name", vcard_text(entity, "fn")); + let organization = field("organization", vcard_text(entity, "org")); + let email = field("email", vcard_text(entity, "email")); + let phone = vcard_text(entity, "tel").map(|t| t.trim_start_matches("tel:").to_owned()); + Contact { + role: role.to_owned(), + by, + name, + organization, + email, + phone, + country: country(entity), + placeholders, + remarks_redacted: remarks_mention_redaction(entity), + } +} + +fn registrar(entity: &Value) -> Registrar { + let iana_id = array(entity, "publicIds") + .iter() + .find(|id| text(id, "type").is_some_and(|t| t.eq_ignore_ascii_case("IANA Registrar ID"))) + .and_then(|id| text(id, "identifier")); + let abuse = array(entity, "entities") + .iter() + .find(|e| roles(e).contains(&"abuse")); + Registrar { + name: vcard_text(entity, "fn").or_else(|| vcard_text(entity, "org")), + iana_id, + abuse_email: abuse.and_then(|a| vcard_text(a, "email")), + abuse_phone: abuse + .and_then(|a| vcard_text(a, "tel")) + .map(|t| t.trim_start_matches("tel:").to_owned()), + } +} + +fn events(value: &Value) -> Events { + let mut out = Events::default(); + for event in array(value, "events") { + let (Some(action), Some(date)) = (text(event, "eventAction"), text(event, "eventDate")) + else { + continue; + }; + let slot = match action.to_ascii_lowercase().as_str() { + "registration" => &mut out.registration, + "expiration" => &mut out.expiration, + "last changed" => &mut out.last_changed, + "last update of rdap database" => &mut out.last_rdap_update, + _ => continue, + }; + slot.get_or_insert(date); + } + out +} + +fn nameservers(value: &Value) -> Vec { + array(value, "nameservers") + .iter() + .filter_map(|ns| text(ns, "ldhName")) + .map(|n| n.trim_end_matches('.').to_ascii_lowercase()) + .collect() +} + +fn dnssec(value: &Value) -> Option { + value.get("secureDNS")?.get("delegationSigned")?.as_bool() +} + +fn redactions(value: &Value, by: Party) -> Vec { + array(value, "redacted") + .iter() + .filter_map(|item| { + let name = item.get("name")?; + let field = text(name, "type").or_else(|| text(name, "description"))?; + let reason = item + .get("reason") + .and_then(|r| text(r, "type").or_else(|| text(r, "description"))); + Some(Redaction { + field, + by, + method: text(item, "method"), + reason, + }) + }) + .collect() +} + +fn contacts(value: &Value, by: Party) -> Vec { + let mut out = Vec::new(); + for entity in array(value, "entities") { + for role in roles(entity) { + if CONTACT_ROLES.contains(&role) { + out.push(contact(entity, role, by)); + } + } + } + out +} + +pub fn domain(value: &Value, by: Party, url: &str) -> DomainInfo { + let entities = array(value, "entities"); + DomainInfo { + ldh_name: text(value, "ldhName") + .unwrap_or_default() + .to_ascii_lowercase(), + handle: text(value, "handle"), + statuses: array(value, "status") + .iter() + .filter_map(Value::as_str) + .map(str::to_owned) + .collect(), + registrar: entities + .iter() + .find(|e| roles(e).contains(&"registrar")) + .map(registrar), + contacts: contacts(value, by), + events: events(value), + nameservers: nameservers(value), + dnssec: dnssec(value), + redactions: redactions(value, by), + sources: vec![Source { + by, + url: url.to_owned(), + error: None, + }], + raw: vec![RawResponse { + by, + url: url.to_owned(), + json: value.clone(), + }], + } +} + +/// 注册局响应里指向注册商 RDAP 的链接(rel=related,类型为 RDAP) +pub fn registrar_link(value: &Value, self_url: &str) -> Option { + array(value, "links") + .iter() + .filter(|link| text(link, "rel").as_deref() == Some("related")) + .filter_map(|link| { + let href = text(link, "href")?; + let rdap_type = text(link, "type").is_some_and(|t| t.contains("rdap+json")); + let looks_rdap = href.contains("/domain/"); + (rdap_type || looks_rdap).then_some(href) + }) + .find(|href| { + (href.starts_with("https://") || href.starts_with("http://")) && href != self_url + }) +} + +/// 并入注册商的响应:联系人与隐去声明标为注册商来源,注册局缺少的日期和注册商信息用它补齐 +pub fn merge_registrar(info: &mut DomainInfo, value: &Value, url: &str) { + let other = domain(value, Party::Registrar, url); + info.contacts.extend(other.contacts); + info.redactions.extend(other.redactions); + let fill = |mine: &mut Option, theirs: Option| { + if mine.is_none() { + *mine = theirs; + } + }; + fill(&mut info.events.registration, other.events.registration); + fill(&mut info.events.expiration, other.events.expiration); + fill(&mut info.events.last_changed, other.events.last_changed); + if let Some(theirs) = other.registrar { + let mine = info.registrar.get_or_insert_with(Registrar::default); + fill(&mut mine.name, theirs.name); + fill(&mut mine.iana_id, theirs.iana_id); + fill(&mut mine.abuse_email, theirs.abuse_email); + fill(&mut mine.abuse_phone, theirs.abuse_phone); + } + info.sources.extend(other.sources); + info.raw.extend(other.raw); +} + +pub fn tld(tld: &str, value: &Value) -> TldInfo { + let manager = array(value, "entities") + .iter() + .find(|e| roles(e).contains(&"registrant")) + .and_then(|e| vcard_text(e, "org").or_else(|| vcard_text(e, "fn"))); + let registration_url = array(value, "links") + .iter() + .find(|link| { + text(link, "rel").as_deref() == Some("related") + && text(link, "type").is_some_and(|t| t.contains("html")) + }) + .and_then(|link| text(link, "href")); + let events = events(value); + TldInfo { + tld: tld.to_owned(), + manager, + registration_url, + nameservers: nameservers(value), + dnssec: dnssec(value), + registered: events.registration, + last_changed: events.last_changed, + raw: value.clone(), + } +} + +#[cfg(test)] +#[path = "parse_test.rs"] +pub(crate) mod tests; diff --git a/market/domain-lookup/backend/src/parse_test.rs b/market/domain-lookup/backend/src/parse_test.rs new file mode 100644 index 00000000..ff44409c --- /dev/null +++ b/market/domain-lookup/backend/src/parse_test.rs @@ -0,0 +1,211 @@ +use serde_json::json; + +use super::*; + +/// .com 注册局风格的响应(RFC 9083),带注册商链接与 RFC 9537 隐去声明 +pub fn registry_json() -> Value { + json!({ + "objectClassName": "domain", + "handle": "1_DOMAIN_COM-VRSN", + "ldhName": "EXAMPLE.COM", + "status": ["client delete prohibited", "client transfer prohibited"], + "links": [ + { "rel": "self", "href": "https://rdap.verisign.com/com/v1/domain/EXAMPLE.COM", "type": "application/rdap+json" }, + { "rel": "related", "href": "https://rdap.registrar.example/domain/EXAMPLE.COM", "type": "application/rdap+json" } + ], + "entities": [{ + "objectClassName": "entity", + "roles": ["registrar"], + "publicIds": [{ "type": "IANA Registrar ID", "identifier": "292" }], + "vcardArray": ["vcard", [["version", {}, "text", "4.0"], ["fn", {}, "text", "Example Registrar, Inc."]]], + "entities": [{ + "roles": ["abuse"], + "vcardArray": ["vcard", [["fn", {}, "text", ""], ["tel", { "type": "voice" }, "uri", "tel:+1.5555551234"], ["email", {}, "text", "abuse@registrar.example"]]] + }] + }], + "events": [ + { "eventAction": "registration", "eventDate": "1995-08-14T04:00:00Z" }, + { "eventAction": "expiration", "eventDate": "2027-08-13T04:00:00Z" }, + { "eventAction": "last changed", "eventDate": "2026-08-14T07:01:44Z" }, + { "eventAction": "last update of RDAP database", "eventDate": "2026-12-03T01:00:00Z" } + ], + "secureDNS": { "delegationSigned": true }, + "nameservers": [{ "ldhName": "A.IANA-SERVERS.NET" }, { "ldhName": "B.IANA-SERVERS.NET." }] + }) +} + +/// 注册商响应:联系人用占位文本,并按 RFC 9537 声明隐去的字段 +pub fn registrar_json() -> Value { + json!({ + "ldhName": "example.com", + "entities": [ + { + "roles": ["registrant"], + "vcardArray": ["vcard", [ + ["fn", {}, "text", "REDACTED FOR PRIVACY"], + ["org", {}, "text", "Example Org"], + ["email", {}, "text", "Please query the RDDS service of the Registrar of Record"], + ["adr", { "cc": "US" }, "text", ["", "", "", "", "CA", "", "United States"]] + ]], + "remarks": [{ "title": "REDACTED FOR PRIVACY", "description": ["Some of the data in this object has been removed."] }] + }, + { + "roles": ["technical", "administrative"], + "vcardArray": ["vcard", [["fn", {}, "text", "Data Protected"]]] + } + ], + "redacted": [ + { "name": { "type": "Registrant Name" }, "prePath": "$.entities[?(@.roles[0]=='registrant')].vcardArray[1][?(@[0]=='fn')]", "method": "removal", "reason": { "type": "Server policy" } }, + { "name": { "description": "Registrant Phone" }, "method": "emptyValue" } + ] + }) +} + +#[test] +fn registry_response_becomes_an_info_card() { + let url = "https://rdap.verisign.com/com/v1/domain/example.com"; + let info = domain(®istry_json(), Party::Registry, url); + assert_eq!(info.ldh_name, "example.com"); + assert_eq!( + info.statuses, + vec!["client delete prohibited", "client transfer prohibited"] + ); + assert_eq!( + info.registrar, + Some(Registrar { + name: Some("Example Registrar, Inc.".into()), + iana_id: Some("292".into()), + abuse_email: Some("abuse@registrar.example".into()), + abuse_phone: Some("+1.5555551234".into()), + }) + ); + assert_eq!( + info.events.expiration.as_deref(), + Some("2027-08-13T04:00:00Z") + ); + assert_eq!( + info.events.last_rdap_update.as_deref(), + Some("2026-12-03T01:00:00Z") + ); + assert_eq!( + info.nameservers, + vec!["a.iana-servers.net", "b.iana-servers.net"] + ); + assert_eq!(info.dnssec, Some(true)); + assert!(info.contacts.is_empty()); + assert_eq!( + registrar_link(®istry_json(), url).as_deref(), + Some("https://rdap.registrar.example/domain/EXAMPLE.COM") + ); +} + +#[test] +fn registrar_data_is_merged_and_redactions_are_attributed() { + let mut info = domain(®istry_json(), Party::Registry, "https://registry/"); + merge_registrar(&mut info, ®istrar_json(), "https://registrar/"); + assert_eq!( + info.redactions, + vec![ + Redaction { + field: "Registrant Name".into(), + by: Party::Registrar, + method: Some("removal".into()), + reason: Some("Server policy".into()) + }, + Redaction { + field: "Registrant Phone".into(), + by: Party::Registrar, + method: Some("emptyValue".into()), + reason: None + }, + ] + ); + let registrant = &info.contacts[0]; + assert_eq!(registrant.role, "registrant"); + assert_eq!(registrant.by, Party::Registrar); + // 占位文本不当作姓名展示,只记下字段被隐去 + assert_eq!(registrant.name, None); + assert_eq!(registrant.organization.as_deref(), Some("Example Org")); + assert_eq!(registrant.placeholders, vec!["name"]); + assert!(registrant.remarks_redacted); + assert_eq!(registrant.country.as_deref(), Some("US")); + // 一个实体可以同时承担多个角色 + assert_eq!( + info.contacts + .iter() + .filter(|c| c.placeholders == ["name"]) + .count(), + 3 + ); + assert_eq!(info.sources.len(), 2); + assert_eq!(info.raw.len(), 2); +} + +#[test] +fn registrar_fills_what_the_registry_lacks() { + let mut info = domain( + &json!({ "ldhName": "example.de" }), + Party::Registry, + "https://registry/", + ); + let registrar = json!({ + "events": [{ "eventAction": "expiration", "eventDate": "2030-01-01T00:00:00Z" }], + "entities": [{ "roles": ["registrar"], "vcardArray": ["vcard", [["fn", {}, "text", "R"]]] }] + }); + merge_registrar(&mut info, ®istrar, "https://registrar/"); + assert_eq!( + info.events.expiration.as_deref(), + Some("2030-01-01T00:00:00Z") + ); + assert_eq!(info.registrar.unwrap().name.as_deref(), Some("R")); +} + +#[test] +fn missing_fields_are_not_mistaken_for_redaction() { + let info = domain( + &json!({ "ldhName": "a.de", "entities": [{ "roles": ["registrant"], "vcardArray": ["vcard", [["fn", {}, "text", ""]]] }] }), + Party::Registry, + "u", + ); + assert!(info.redactions.is_empty()); + assert!(info.contacts[0].placeholders.is_empty()); + assert!(!info.contacts[0].remarks_redacted); + assert_eq!(info.events, Events::default()); +} + +#[test] +fn placeholders_cover_common_registrar_wording() { + for text in [ + "REDACTED FOR PRIVACY", + "Data Protected", + "Not Disclosed", + "Withheld for Privacy ehf", + "Statutory Masking Enabled", + ] { + assert!(is_placeholder(text), "{text}"); + } + assert!(!is_placeholder("Example Org")); +} + +#[test] +fn iana_tld_record_lists_manager_and_registration_url() { + let value = json!({ + "ldhName": "de", + "entities": [{ "roles": ["registrant"], "vcardArray": ["vcard", [["fn", {}, "text", "DENIC eG"]]] }], + "links": [{ "rel": "related", "href": "http://www.denic.de/", "type": "text/html", "title": "Registration URL" }], + "nameservers": [{ "ldhName": "a.nic.de" }], + "secureDNS": { "delegationSigned": true }, + "events": [{ "eventAction": "registration", "eventDate": "1986-11-05T00:00:00+00:00" }] + }); + let info = tld("de", &value); + assert_eq!(info.manager.as_deref(), Some("DENIC eG")); + assert_eq!( + info.registration_url.as_deref(), + Some("http://www.denic.de/") + ); + assert_eq!(info.nameservers, vec!["a.nic.de"]); + assert_eq!( + info.registered.as_deref(), + Some("1986-11-05T00:00:00+00:00") + ); +} diff --git a/market/domain-lookup/backend/src/rdap.rs b/market/domain-lookup/backend/src/rdap.rs new file mode 100644 index 00000000..d0f9fc52 --- /dev/null +++ b/market/domain-lookup/backend/src/rdap.rs @@ -0,0 +1,188 @@ +//! RDAP 请求:按引导文件中的地址依次尝试;404 表示注册局没有这个域名; +//! 429 带上 Retry-After 交给界面的队列退避重试,403 视为不可重试。 +//! 注册局响应里有注册商 RDAP 链接时再查一次注册商,补充联系人与隐私信息。 + +use serde::{Deserialize, Serialize}; +use serde_json::Value; +use tf_plugin_api::{PluginError, PluginResult}; +use tf_plugin_guest::net::{self, HttpRequest, HttpResponse}; + +use crate::bootstrap::{self, Service}; +use crate::domain::{IANA_HOST, host_of, normalize, route, tld_of, unicode_of}; +use crate::parse::{self, DomainInfo, Party, TldInfo}; + +const MAX_RDAP: u64 = 2 * 1024 * 1024; +const TIMEOUT_MS: u32 = 15_000; + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct LookupArgs { + pub domain: String, + /// 界面缓存的引导文件;为空时现取一份(命令行与 AI 调用) + #[serde(default)] + pub services: Option>, + /// 是否再查注册商的 RDAP(批量查询时关闭以减少请求) + #[serde(default)] + pub follow_registrar: Option, +} + +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase", tag = "kind")] +pub enum Outcome { + /// 注册局返回了域名记录 + Found { info: Box }, + /// 注册局没有这个域名:通常表示尚未注册 + NotFound { server: String }, + /// 该顶级域没有 RDAP 服务,只能给出 IANA 的顶级域信息 + NoRdap { tld: Box }, +} + +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct Lookup { + pub domain: String, + pub unicode: Option, + pub result: Outcome, +} + +pub fn get(url: &str, headers: Vec<(String, String)>, max_body: u64) -> PluginResult { + let request = HttpRequest { + method: "GET".to_owned(), + url: url.to_owned(), + headers, + body: None, + timeout_ms: TIMEOUT_MS, + follow_redirects: true, + max_redirects: 5, + use_proxy: true, + max_body, + }; + net::send(&request, None) +} + +pub fn header(headers: &[(String, String)], name: &str) -> Option { + headers + .iter() + .find(|(key, _)| key.eq_ignore_ascii_case(name)) + .map(|(_, value)| value.trim().to_owned()) +} + +/// Retry-After 的秒数形式;HTTP 日期形式交给界面按默认退避处理 +pub fn retry_after(headers: &[(String, String)]) -> Option { + header(headers, "retry-after")?.parse().ok() +} + +/// 取一个 RDAP 对象;404 返回 None +pub fn fetch_json(url: &str) -> PluginResult> { + let host = host_of(url); + let accept = ( + "Accept".to_owned(), + "application/rdap+json, application/json;q=0.9".to_owned(), + ); + let response = get(url, vec![accept], MAX_RDAP).map_err(|e| { + PluginError::new("rdap.network") + .with("host", host.as_str()) + .with("detail", e.code) + })?; + match response.status { + 200..=299 => serde_json::from_slice(&response.body) + .map(Some) + .map_err(|_| PluginError::new("rdap.bad_response").with("host", host.as_str())), + 404 => Ok(None), + 429 => { + let mut error = PluginError::new("rdap.rate_limited").with("host", host.as_str()); + if let Some(seconds) = retry_after(&response.headers) { + error = error.with("retryAfter", seconds); + } + Err(error) + } + 403 => Err(PluginError::new("rdap.forbidden").with("host", host.as_str())), + status => Err(PluginError::new("rdap.failed") + .with("host", host.as_str()) + .with("status", status)), + } +} + +/// 换一个地址可能成功的错误:网络故障、服务器错误与无法解析的响应 +fn worth_next_url(error: &PluginError) -> bool { + match error.code.as_str() { + "rdap.network" | "rdap.bad_response" => true, + "rdap.failed" => error + .params + .get("status") + .and_then(Value::as_u64) + .is_some_and(|s| s >= 500), + _ => false, + } +} + +pub fn lookup(args: LookupArgs) -> PluginResult { + let domain = normalize(&args.domain) + .map_err(|code| PluginError::new(code).with("input", args.domain.as_str()))?; + let services = match args.services { + Some(services) if !services.is_empty() => services, + _ => bootstrap::fetch(bootstrap::BootstrapArgs::default())?.services, + }; + let result = match route(&domain, &services) { + Some(service) => registry( + &domain, + &service.urls, + args.follow_registrar.unwrap_or(true), + )?, + None => tld(&domain, &format!("https://{IANA_HOST}/"))?, + }; + Ok(Lookup { + unicode: unicode_of(&domain), + domain, + result, + }) +} + +/// 查注册局:地址按顺序尝试,网络或服务器错误时换下一个 +pub fn registry(domain: &str, urls: &[String], follow_registrar: bool) -> PluginResult { + let mut last = None; + for base in urls { + let url = format!("{base}domain/{domain}"); + match fetch_json(&url) { + Ok(Some(value)) => { + let mut info = parse::domain(&value, Party::Registry, &url); + if follow_registrar && let Some(link) = parse::registrar_link(&value, &url) { + match fetch_json(&link) { + Ok(Some(registrar)) => parse::merge_registrar(&mut info, ®istrar, &link), + Ok(None) => { + info.note_source(Party::Registrar, &link, Some("rdap.not_found")) + } + Err(error) => info.note_source(Party::Registrar, &link, Some(&error.code)), + } + } + return Ok(Outcome::Found { + info: Box::new(info), + }); + } + Ok(None) => { + return Ok(Outcome::NotFound { + server: host_of(&url), + }); + } + Err(error) if worth_next_url(&error) => last = Some(error), + Err(error) => return Err(error), + } + } + Err(last.unwrap_or_else(|| PluginError::new("rdap.no_server"))) +} + +/// 没有 RDAP 服务的顶级域:查 IANA 的顶级域记录(管理机构、注册信息网址、DNS 服务器) +pub fn tld(domain: &str, iana_base: &str) -> PluginResult { + let tld = tld_of(domain); + let url = format!("{iana_base}domain/{tld}"); + match fetch_json(&url)? { + Some(value) => Ok(Outcome::NoRdap { + tld: Box::new(parse::tld(tld, &value)), + }), + None => Err(PluginError::new("domain.unknown_tld").with("tld", tld)), + } +} + +#[cfg(test)] +#[path = "rdap_test.rs"] +mod tests; diff --git a/market/domain-lookup/backend/src/rdap_test.rs b/market/domain-lookup/backend/src/rdap_test.rs new file mode 100644 index 00000000..d6262c9c --- /dev/null +++ b/market/domain-lookup/backend/src/rdap_test.rs @@ -0,0 +1,149 @@ +use std::sync::{Arc, Mutex}; + +use serde_json::json; + +use super::*; +use crate::parse::tests::{registrar_json, registry_json}; + +/// 路径前缀、状态码、响应体与响应头 +type Route = (&'static str, u16, String, Vec<(&'static str, &'static str)>); + +/// 本地 RDAP 服务器:按路径返回固定的状态码与内容,并记录收到的请求 +fn serve(routes: Vec) -> (String, Arc>>) { + let server = tiny_http::Server::http("127.0.0.1:0").unwrap(); + let base = format!( + "http://127.0.0.1:{}/", + server.server_addr().to_ip().unwrap().port() + ); + let seen = Arc::new(Mutex::new(Vec::new())); + let log = seen.clone(); + std::thread::spawn(move || { + for request in server.incoming_requests() { + let path = request.url().to_owned(); + log.lock().unwrap().push(path.clone()); + let (status, body, headers) = routes + .iter() + .find(|(prefix, ..)| path.starts_with(prefix)) + .map_or( + (404, String::new(), Vec::new()), + |(_, status, body, headers)| (*status, body.clone(), headers.clone()), + ); + let mut response = tiny_http::Response::from_string(body).with_status_code(status); + for (name, value) in headers { + response = + response.with_header(tiny_http::Header::from_bytes(name, value).unwrap()); + } + let _ = request.respond(response); + } + }); + (base, seen) +} + +#[test] +fn found_domains_follow_the_registrar_link() { + let (registrar_base, _) = serve(vec![( + "/domain/", + 200, + registrar_json().to_string(), + vec![], + )]); + let mut registry = registry_json(); + registry["links"][1]["href"] = json!(format!("{registrar_base}domain/example.com")); + let (base, seen) = serve(vec![( + "/domain/example.com", + 200, + registry.to_string(), + vec![], + )]); + let Outcome::Found { info } = registry_lookup(&base) else { + panic!("expected a record") + }; + assert_eq!(info.sources.len(), 2); + assert!(info.sources.iter().all(|s| s.error.is_none())); + assert_eq!(info.redactions.len(), 2); + assert_eq!(seen.lock().unwrap().as_slice(), ["/domain/example.com"]); +} + +fn registry_lookup(base: &str) -> Outcome { + registry("example.com", &[base.to_owned()], true).unwrap() +} + +#[test] +fn registrar_failures_do_not_hide_the_registry_record() { + let mut registry = registry_json(); + registry["links"][1]["href"] = json!("http://127.0.0.1:9/domain/example.com"); + let (base, _) = serve(vec![("/domain/", 200, registry.to_string(), vec![])]); + let Outcome::Found { info } = registry_lookup(&base) else { + panic!("expected a record") + }; + assert_eq!(info.sources[1].error.as_deref(), Some("rdap.network")); + assert_eq!(info.registrar.unwrap().iana_id.as_deref(), Some("292")); +} + +#[test] +fn not_found_means_unregistered() { + let (base, _) = serve(vec![]); + let Outcome::NotFound { server } = registry_lookup(&base) else { + panic!("expected not found") + }; + assert_eq!(server, host_of(&base)); +} + +#[test] +fn rate_limits_carry_retry_after_and_forbidden_is_terminal() { + let (limited, _) = serve(vec![( + "/domain/", + 429, + String::new(), + vec![("Retry-After", "7")], + )]); + let error = registry("example.com", &[limited], false).unwrap_err(); + assert_eq!(error.code, "rdap.rate_limited"); + assert_eq!(error.params["retryAfter"], 7); + + let (forbidden, _) = serve(vec![("/domain/", 403, String::new(), vec![])]); + let (backup, seen) = serve(vec![("/domain/", 200, registry_json().to_string(), vec![])]); + // 403 不换地址重试 + assert_eq!( + registry("example.com", &[forbidden, backup], false) + .unwrap_err() + .code, + "rdap.forbidden" + ); + assert!(seen.lock().unwrap().is_empty()); +} + +#[test] +fn server_errors_try_the_next_url_in_order() { + let (broken, _) = serve(vec![("/domain/", 503, String::new(), vec![])]); + let (garbled, _) = serve(vec![("/domain/", 200, "".into(), vec![])]); + let (working, _) = serve(vec![("/domain/", 200, registry_json().to_string(), vec![])]); + let outcome = registry("example.com", &[broken.clone(), garbled, working], false).unwrap(); + assert!(matches!(outcome, Outcome::Found { .. })); + let error = registry("example.com", &[broken], false).unwrap_err(); + assert_eq!(error.code, "rdap.failed"); + assert_eq!(error.params["status"], 503); +} + +#[test] +fn tlds_without_rdap_use_the_iana_record() { + let (iana, seen) = serve(vec![( + "/domain/de", + 200, + json!({ "ldhName": "de", "entities": [] }).to_string(), + vec![], + )]); + let Outcome::NoRdap { tld: info } = tld("denic.de", &iana).unwrap() else { + panic!("expected tld info") + }; + assert_eq!(info.tld, "de"); + assert_eq!(seen.lock().unwrap().as_slice(), ["/domain/de"]); + assert_eq!(tld("x.zz", &iana).unwrap_err().code, "domain.unknown_tld"); +} + +#[test] +fn retry_after_accepts_seconds_only() { + let headers = |v: &str| vec![("retry-after".to_owned(), v.to_owned())]; + assert_eq!(retry_after(&headers("12")), Some(12)); + assert_eq!(retry_after(&headers("Wed, 21 Oct 2026 07:28:00 GMT")), None); +} diff --git a/market/domain-lookup/icon.svg b/market/domain-lookup/icon.svg new file mode 100644 index 00000000..841fbc1e --- /dev/null +++ b/market/domain-lookup/icon.svg @@ -0,0 +1 @@ + diff --git a/market/domain-lookup/locales/en-US.json b/market/domain-lookup/locales/en-US.json new file mode 100644 index 00000000..0111676c --- /dev/null +++ b/market/domain-lookup/locales/en-US.json @@ -0,0 +1,197 @@ +{ + "name": "Domain Lookup", + "description": "Look up a domain's registrar, registration and expiry dates, status, DNS and DNSSEC over RDAP, with redacted privacy data marked, one at a time or in batches", + "help": [ + "Uses RDAP, the successor to WHOIS: the IANA bootstrap file points to the registry server for the TLD, then the registrar's RDAP fills in contacts. The bootstrap file is cached by ETag and only downloaded again when it changes.", + "A 404 from the registry means it has no such domain, which usually means it is not registered; whether you can register it is up to the registrar.", + "Some TLDs (such as .de and .cn) have no RDAP service, and plugins run in a sandbox that cannot use WHOIS on port 43, so only the IANA record for the TLD is shown (manager, registration URL, name servers).", + "Privacy data is marked from RFC 9537 redaction declarations and placeholder text such as \"REDACTED FOR PRIVACY\", along with whether the registry or the registrar redacted it. A missing field does not mean it was redacted.", + "Batches queue per RDAP server with one request in flight per server. Rate limits wait for Retry-After and retry; 403 is not retried. Results are cached locally for 6 hours." + ], + "tabs": { + "single": "Single", + "batch": "Batch" + }, + "bootstrap": { + "published": "Bootstrap file {{date}}" + }, + "single": { + "title": "Domain", + "placeholder": "example.com, https://例子.中国/path …", + "lookup": "Look up", + "refresh": "Look up again", + "empty": "Enter a domain to start", + "hint": "You can paste a URL too; the host name is taken from it and internationalized names are converted to Punycode", + "cached": "From the local cache; choose Look up again for fresh data", + "footer": "Data comes from the registry's and registrar's RDAP services" + }, + "batch": { + "input": "Domains", + "placeholder": "One per line, or separated by commas or spaces", + "start": "Start", + "stop": "Stop", + "hint": "Up to 500; batches query the registry only", + "result": "Results", + "progress": "{{done}} / {{total}}", + "duplicates_one": "{{count}} duplicate skipped", + "duplicates_other": "{{count}} duplicates skipped", + "pending": "Queued", + "running": "Looking up", + "waiting": "Attempt {{attempt}} failed, retrying in {{seconds}} s", + "export": "Export", + "copyCsv": "Copy as CSV", + "saveCsv": "Save as CSV…", + "copied": "Copied", + "saved": "Saved", + "empty": "No results yet", + "emptyHint": "Enter domains on the left and choose Start" + }, + "table": { + "domain": "Domain", + "result": "Result", + "registrar": "Registrar", + "expiration": "Expires", + "daysLeft": "Days left", + "status": "Status", + "error": "Error" + }, + "outcome": { + "found": "Registered", + "notFound": "Not found", + "noRdap": "No RDAP", + "notFoundHint": "The registry ({{server}}) has no record of this domain, which usually means it is not registered. Check with a registrar whether it can be registered." + }, + "expiry": { + "unknown": "Expiry unknown", + "notPublished": "Not published", + "expired_one": "Expired {{count}} day ago", + "expired_other": "Expired {{count}} days ago", + "left_one": "{{count}} day left", + "left_other": "{{count}} days left" + }, + "section": { + "dates": "Key dates", + "registrar": "Registrar", + "status": "Status", + "dns": "Name servers", + "contacts": "Contacts", + "privacy": "Privacy", + "sources": "Sources" + }, + "date": { + "registration": "Registered", + "expiration": "Expires", + "lastChanged": "Last changed", + "lastRdapUpdate": "RDAP updated" + }, + "registrar": { + "name": "Name", + "ianaId": "IANA ID", + "abuseEmail": "Abuse email", + "abusePhone": "Abuse phone", + "none": "The response has no registrar" + }, + "dnssec": { + "signed": "DNSSEC: signed", + "unsigned": "DNSSEC: unsigned", + "unknown": "DNSSEC: unknown" + }, + "party": { + "registry": "Registry", + "registrar": "Registrar" + }, + "role": { + "registrant": "Registrant", + "administrative": "Admin contact", + "technical": "Tech contact", + "billing": "Billing contact" + }, + "contact": { + "name": "Name", + "organization": "Organization", + "email": "Email", + "phone": "Phone", + "country": "Country", + "none": "Nothing published", + "noneListed": "The response lists no contacts" + }, + "privacy": { + "placeholder": "Redacted by the {{party}}", + "remarks": "Remarks say data is redacted", + "redactedBy": "{{field}}: redacted by the {{party}}", + "noneDeclared": "The response declares no redacted fields", + "hint": "Based on RFC 9537 declarations and placeholder text; a missing field does not mean it was redacted." + }, + "method": { + "removal": "Removed", + "emptyValue": "Emptied", + "partialValue": "Partly redacted", + "replacementValue": "Replaced" + }, + "raw": { + "title": "Raw responses", + "copy": "Copy JSON" + }, + "noRdap": { + "notice": ".{{tld}} has no RDAP service. Below is the IANA record for the TLD; look up registration data on the manager's website.", + "registry": "TLD manager", + "manager": "Manager", + "registrationUrl": "Registration URL", + "registered": "Created", + "dns": "TLD name servers" + }, + "status": { + "active": "Active", + "ok": "OK", + "inactive": "Inactive", + "clientTransferProhibited": "Registrar transfer lock", + "clientDeleteProhibited": "Registrar delete lock", + "clientUpdateProhibited": "Registrar update lock", + "clientRenewProhibited": "Registrar renew lock", + "clientHold": "Registrar hold", + "serverTransferProhibited": "Registry transfer lock", + "serverDeleteProhibited": "Registry delete lock", + "serverUpdateProhibited": "Registry update lock", + "serverRenewProhibited": "Registry renew lock", + "serverHold": "Registry hold", + "transferProhibited": "Transfer prohibited", + "deleteProhibited": "Delete prohibited", + "updateProhibited": "Update prohibited", + "renewProhibited": "Renew prohibited", + "redemptionPeriod": "Redemption period", + "pendingDelete": "Pending delete", + "pendingRestore": "Pending restore", + "pendingTransfer": "Pending transfer", + "pendingCreate": "Pending create", + "pendingRenew": "Pending renew", + "pendingUpdate": "Pending update", + "addPeriod": "Add grace period", + "autoRenewPeriod": "Auto-renew grace period", + "renewPeriod": "Renew grace period", + "transferPeriod": "Transfer grace period", + "associated": "Associated", + "locked": "Locked" + }, + "errors": { + "domain.empty": "Enter a domain", + "domain.invalid": "Not a valid domain: {{input}}", + "domain.too_many": "Up to {{limit}} domains at a time", + "domain.unknown_tld": "The TLD .{{tld}} does not exist", + "bootstrap.failed": "Could not fetch the RDAP bootstrap file ({{detail}})", + "bootstrap.bad_file": "The RDAP bootstrap file is malformed", + "rdap.network": "Could not connect to {{host}}", + "rdap.bad_response": "{{host}} did not return RDAP data", + "rdap.rate_limited": "{{host}} is rate limiting requests; try again later", + "rdap.forbidden": "{{host}} refused the request (403)", + "rdap.failed": "{{host}} returned HTTP {{status}}", + "rdap.no_server": "No RDAP server is available", + "rdap.not_found": "The registrar has no record of this domain" + }, + "api": { + "lookup": { + "summary": "Look up a domain's registrar, registration and expiry dates, status, name servers and redacted privacy data over RDAP", + "domain": "Domain to look up; a URL works too", + "followRegistrar": "Also query the registrar's RDAP for contacts; defaults to true" + } + } +} diff --git a/market/domain-lookup/locales/zh-CN.json b/market/domain-lookup/locales/zh-CN.json new file mode 100644 index 00000000..f610c13a --- /dev/null +++ b/market/domain-lookup/locales/zh-CN.json @@ -0,0 +1,196 @@ +{ + "name": "域名信息查询", + "description": "通过 RDAP 查询域名的注册商、注册与到期日期、状态、DNS 与 DNSSEC,并标注被隐去的隐私信息,支持批量查询", + "help": [ + "使用 RDAP(WHOIS 的继任协议)查询:先按 IANA 引导文件找到顶级域的注册局服务器,再查注册商的 RDAP 补充联系人信息。引导文件按 ETag 缓存,没有变化时不会重复下载。", + "注册局返回 404 表示没有这个域名,通常意味着尚未注册;但域名是否可以注册仍以注册商为准。", + "部分顶级域(如 .de、.cn)没有 RDAP 服务,插件在沙箱中也不能使用 43 端口的 WHOIS,这时只显示 IANA 的顶级域信息(管理机构、注册信息网址、DNS 服务器)。", + "隐私信息依据响应中的 RFC 9537 隐去声明,以及「REDACTED FOR PRIVACY」等占位文本标注,并注明是注册局还是注册商隐去的;字段缺失不代表被隐去。", + "批量查询按 RDAP 服务器排队,同一服务器一次只发一个请求;遇到限流时按 Retry-After 等待后重试,403 不重试。结果在本地缓存 6 小时。" + ], + "tabs": { + "single": "单个查询", + "batch": "批量查询" + }, + "bootstrap": { + "published": "引导文件 {{date}}" + }, + "single": { + "title": "域名", + "placeholder": "example.com、https://例子.中国/path …", + "lookup": "查询", + "refresh": "重新查询", + "empty": "输入域名开始查询", + "hint": "也可以粘贴网址,会自动取出主机名;国际化域名会转换为 Punycode", + "cached": "来自本地缓存,点「重新查询」获取最新数据", + "footer": "数据来自注册局与注册商的 RDAP 服务" + }, + "batch": { + "input": "域名列表", + "placeholder": "每行一个,也可以用逗号、空格分隔", + "start": "开始", + "stop": "停止", + "hint": "最多 500 个;批量查询只查注册局", + "result": "查询结果", + "progress": "{{done}} / {{total}}", + "duplicates": "已跳过 {{count}} 个重复", + "pending": "排队中", + "running": "查询中", + "waiting": "第 {{attempt}} 次失败,{{seconds}} 秒后重试", + "export": "导出", + "copyCsv": "复制为 CSV", + "saveCsv": "保存为 CSV…", + "copied": "已复制", + "saved": "已保存", + "empty": "还没有结果", + "emptyHint": "在左侧输入域名后点击「开始」" + }, + "table": { + "domain": "域名", + "result": "结果", + "registrar": "注册商", + "expiration": "到期", + "daysLeft": "剩余天数", + "status": "状态", + "error": "错误" + }, + "outcome": { + "found": "已注册", + "notFound": "未找到", + "noRdap": "无 RDAP", + "notFoundHint": "注册局({{server}})没有这个域名的记录,通常表示尚未注册。是否可以注册请以注册商为准。" + }, + "expiry": { + "unknown": "到期未知", + "notPublished": "未公布", + "expired_one": "已过期 {{count}} 天", + "expired_other": "已过期 {{count}} 天", + "left_one": "剩余 {{count}} 天", + "left_other": "剩余 {{count}} 天" + }, + "section": { + "dates": "关键日期", + "registrar": "注册商", + "status": "状态", + "dns": "DNS 服务器", + "contacts": "联系人", + "privacy": "隐私信息", + "sources": "数据来源" + }, + "date": { + "registration": "注册", + "expiration": "到期", + "lastChanged": "最后修改", + "lastRdapUpdate": "RDAP 更新" + }, + "registrar": { + "name": "名称", + "ianaId": "IANA 编号", + "abuseEmail": "投诉邮箱", + "abusePhone": "投诉电话", + "none": "响应中没有注册商信息" + }, + "dnssec": { + "signed": "DNSSEC:已签名", + "unsigned": "DNSSEC:未签名", + "unknown": "DNSSEC:未知" + }, + "party": { + "registry": "注册局", + "registrar": "注册商" + }, + "role": { + "registrant": "注册人", + "administrative": "管理联系人", + "technical": "技术联系人", + "billing": "付费联系人" + }, + "contact": { + "name": "姓名", + "organization": "单位", + "email": "邮箱", + "phone": "电话", + "country": "国家/地区", + "none": "没有公开的信息", + "noneListed": "响应中没有联系人" + }, + "privacy": { + "placeholder": "已被{{party}}隐去", + "remarks": "备注说明已隐去", + "redactedBy": "{{field}}:已被{{party}}隐去", + "noneDeclared": "响应没有声明隐去的字段", + "hint": "依据 RFC 9537 隐去声明与占位文本判断;字段缺失不代表被隐去。" + }, + "method": { + "removal": "移除", + "emptyValue": "置空", + "partialValue": "部分隐去", + "replacementValue": "替换" + }, + "raw": { + "title": "原始响应", + "copy": "复制 JSON" + }, + "noRdap": { + "notice": ".{{tld}} 没有 RDAP 服务,以下是 IANA 的顶级域信息。注册信息请到管理机构的网站查询。", + "registry": "顶级域管理机构", + "manager": "管理机构", + "registrationUrl": "注册信息网址", + "registered": "设立日期", + "dns": "顶级域 DNS 服务器" + }, + "status": { + "active": "正常", + "ok": "正常", + "inactive": "未激活", + "clientTransferProhibited": "注册商禁止转移", + "clientDeleteProhibited": "注册商禁止删除", + "clientUpdateProhibited": "注册商禁止修改", + "clientRenewProhibited": "注册商禁止续费", + "clientHold": "注册商暂停解析", + "serverTransferProhibited": "注册局禁止转移", + "serverDeleteProhibited": "注册局禁止删除", + "serverUpdateProhibited": "注册局禁止修改", + "serverRenewProhibited": "注册局禁止续费", + "serverHold": "注册局暂停解析", + "transferProhibited": "禁止转移", + "deleteProhibited": "禁止删除", + "updateProhibited": "禁止修改", + "renewProhibited": "禁止续费", + "redemptionPeriod": "赎回期", + "pendingDelete": "待删除", + "pendingRestore": "待恢复", + "pendingTransfer": "转移中", + "pendingCreate": "创建中", + "pendingRenew": "续费中", + "pendingUpdate": "修改中", + "addPeriod": "新注册宽限期", + "autoRenewPeriod": "自动续费宽限期", + "renewPeriod": "续费宽限期", + "transferPeriod": "转移宽限期", + "associated": "已关联", + "locked": "已锁定" + }, + "errors": { + "domain.empty": "请输入域名", + "domain.invalid": "不是有效的域名:{{input}}", + "domain.too_many": "一次最多查询 {{limit}} 个域名", + "domain.unknown_tld": "顶级域 .{{tld}} 不存在", + "bootstrap.failed": "无法获取 RDAP 引导文件({{detail}})", + "bootstrap.bad_file": "RDAP 引导文件格式不正确", + "rdap.network": "连接 {{host}} 失败", + "rdap.bad_response": "{{host}} 返回的不是 RDAP 数据", + "rdap.rate_limited": "{{host}} 请求过于频繁,请稍后再试", + "rdap.forbidden": "{{host}} 拒绝了请求(403)", + "rdap.failed": "{{host}} 返回 HTTP {{status}}", + "rdap.no_server": "没有可用的 RDAP 服务器", + "rdap.not_found": "注册商没有这个域名的记录" + }, + "api": { + "lookup": { + "summary": "经 RDAP 查询域名的注册商、注册与到期日期、状态、DNS 服务器与隐去的隐私信息", + "domain": "要查询的域名,也可以是网址", + "followRegistrar": "是否再查注册商的 RDAP 补充联系人信息,默认是" + } + } +} diff --git a/market/domain-lookup/manifest.json b/market/domain-lookup/manifest.json new file mode 100644 index 00000000..d6473ac2 --- /dev/null +++ b/market/domain-lookup/manifest.json @@ -0,0 +1,41 @@ +{ + "id": "org.devlive.toolforge.domain-lookup", + "version": "0.1.0", + "name": "i18n:name", + "description": "i18n:description", + "category": "network", + "keywords": ["rdap", "whois", "domain", "registrar", "expiry", "expiration", "dns", "域名", "域名查询", "注册商", "到期", "过期", "注册信息"], + "accent": "sky", + "locales": ["zh-CN", "en-US"], + "minAppVersion": "0.2.6", + "permissions": ["network", "clipboard:write"], + "functions": { + "bootstrap": { "interface": false }, + "plan": { "interface": false }, + "lookup": { + "history": true, + "interface": { + "expose": ["cli", "agent"], + "summary": "i18n:api.lookup.summary", + "effect": "external", + "params": { + "type": "object", + "required": ["domain"], + "properties": { + "domain": { + "type": "string", + "description": "i18n:api.lookup.domain", + "x-positional": 0 + }, + "followRegistrar": { + "type": "boolean", + "description": "i18n:api.lookup.followRegistrar" + } + } + }, + "examples": ["tfp-domain-lookup lookup example.com --json"] + } + } + }, + "sensitive": false +} diff --git a/market/domain-lookup/ui/package.json b/market/domain-lookup/ui/package.json new file mode 100644 index 00000000..b8bcb468 --- /dev/null +++ b/market/domain-lookup/ui/package.json @@ -0,0 +1,25 @@ +{ + "name": "@toolforge-market/domain-lookup", + "private": true, + "version": "0.1.0", + "type": "module", + "exports": { ".": "./src/index.tsx" }, + "scripts": { + "typecheck": "tsc -p tsconfig.json", + "test": "node --experimental-strip-types --test tests/logic.test.mjs tests/queue.test.mjs" + }, + "peerDependencies": { "react": "^19" }, + "dependencies": { + "@toolforge/plugin-ui-sdk": "workspace:*", + "@toolforge/ui": "workspace:*", + "lucide-react": "1.47.0", + "react-i18next": "17.0.15" + }, + "devDependencies": { + "@types/react": "19.3.0", + "react": "19.3.0", + "tailwindcss": "4.3.3", + "typescript": "5.9.3", + "vite": "8.3.0" + } +} diff --git a/market/domain-lookup/ui/src/Card.tsx b/market/domain-lookup/ui/src/Card.tsx new file mode 100644 index 00000000..734e5956 --- /dev/null +++ b/market/domain-lookup/ui/src/Card.tsx @@ -0,0 +1,262 @@ +import type { ReactNode } from 'react' +import { Badge, Button, cn } from '@toolforge/ui' +import { useCopy, usePlugin } from '@toolforge/plugin-ui-sdk' +import { useTranslation } from 'react-i18next' +import { Braces, CalendarClock, Copy, EyeOff, Globe, Server, ShieldCheck, Store, UserRound } from 'lucide-react' +import { SOON_DAYS, expiry, statusKey, statusTone } from './logic.ts' +import type { Contact, DomainInfo, Lookup, Party, TldInfo } from './types.ts' + +export function useDate() { + const { i18n } = useTranslation() + return (value: string | null | undefined) => { + if (!value) return null + const at = new Date(value) + return Number.isNaN(at.getTime()) ? value : at.toLocaleDateString(i18n.language, { year: 'numeric', month: 'short', day: 'numeric' }) + } +} + +export function ExpiryBadge({ expiration, now }: { expiration: string | null; now: number }) { + const { t } = usePlugin() + const state = expiry(expiration, now) + if (state.kind === 'unknown') return {t('expiry.unknown')} + if (state.kind === 'expired') return {t('expiry.expired', { count: state.days })} + return {t('expiry.left', { count: state.days })} +} + +export function StatusBadge({ status }: { status: string }) { + const { t } = usePlugin() + const tone = statusTone(status) + return ( + + {t(`status.${statusKey(status)}`, { defaultValue: status })} + + ) +} + +function Section({ icon, title, children, className }: { icon: ReactNode; title: string; children: ReactNode; className?: string }) { + return ( +
+

+ {icon} + {title} +

+ {children} +
+ ) +} + +function Row({ label, value }: { label: string; value: ReactNode }) { + return ( +
+ {label} + + {value} + +
+ ) +} + +function PartyBadge({ by }: { by: Party }) { + const { t } = usePlugin() + return {t(`party.${by}`)} +} + +function ContactView({ contact }: { contact: Contact }) { + const { t } = usePlugin() + const placeholder = (field: string) => contact.placeholders.includes(field) + const value = (field: 'name' | 'organization' | 'email', text: string | null) => + placeholder(field) ? ( + + + {t('privacy.placeholder', { party: t(`party.${contact.by}`) })} + + ) : ( + text + ) + const rows = [ + ['name', value('name', contact.name)], + ['organization', value('organization', contact.organization)], + ['email', value('email', contact.email)], + ['phone', contact.phone], + ['country', contact.country], + ].filter(([, v]) => v) as [string, ReactNode][] + return ( +
+
+ {t(`role.${contact.role}`, { defaultValue: contact.role })} + + {contact.remarksRedacted && {t('privacy.remarks')}} +
+ {rows.length > 0 ? rows.map(([field, v]) => ) :

{t('contact.none')}

} +
+ ) +} + +function RawJson({ items }: { items: { label: string; json: unknown }[] }) { + const { t } = usePlugin() + const { copy } = useCopy() + return ( +
} title={t('raw.title')}> + {items.map((item) => ( +
+ + {item.label} + + +
+            {JSON.stringify(item.json, null, 2)}
+          
+
+ ))} +
+ ) +} + +function Found({ info, now }: { info: DomainInfo; now: number }) { + const { t, errorMessage } = usePlugin() + const date = useDate() + const registrar = info.registrar + return ( +
+
} title={t('section.dates')}> + + + {date(info.events.expiration) ?? t('expiry.notPublished')} + + + } + /> + + +
+
} title={t('section.registrar')}> + {registrar ? ( + <> + + {registrar.ianaId && } + {registrar.abuseEmail && } + {registrar.abusePhone && } + + ) : ( +

{t('registrar.none')}

+ )} +
+
} title={t('section.status')}> +
{info.statuses.length > 0 ? info.statuses.map((s) => ) : {'—'}}
+
+
} title={t('section.dns')}> + {info.nameservers.map((ns) => ( +

+ {ns} +

+ ))} + {info.nameservers.length === 0 &&

{'—'}

} +

{info.dnssec === null ? t('dnssec.unknown') : info.dnssec ? t('dnssec.signed') : t('dnssec.unsigned')}

+
+
} title={t('section.contacts')} className="col-span-full"> + {info.contacts.length > 0 ? ( +
+ {info.contacts.map((contact, index) => ( + + ))} +
+ ) : ( +

{t('contact.noneListed')}

+ )} +
+
} title={t('section.privacy')} className="col-span-full"> + {info.redactions.length > 0 ? ( +
    + {info.redactions.map((r, index) => ( +
  • + + {t('privacy.redactedBy', { field: r.field, party: t(`party.${r.by}`) })} + {r.method && {t(`method.${r.method}`, { defaultValue: r.method })}} + {r.reason && {r.reason}} +
  • + ))} +
+ ) : ( +

{t('privacy.noneDeclared')}

+ )} +

{t('privacy.hint')}

+
+
} title={t('section.sources')} className="col-span-full"> + {info.sources.map((source) => ( +

+ + + {source.url} + + {source.error && {errorMessage({ code: source.error, params: {} })}} +

+ ))} +
+
+ ({ label: `${t(`party.${r.by}`)} · ${r.url}`, json: r.json }))} /> +
+
+ ) +} + +function NoRdap({ tld }: { tld: TldInfo }) { + const { t } = usePlugin() + const date = useDate() + return ( +
+

{t('noRdap.notice', { tld: tld.tld })}

+
+
} title={t('noRdap.registry')}> + + + + +
+
} title={t('noRdap.dns')}> + {tld.nameservers.map((ns) => ( +

+ {ns} +

+ ))} +

{tld.dnssec === null ? t('dnssec.unknown') : tld.dnssec ? t('dnssec.signed') : t('dnssec.unsigned')}

+
+
+ +
+ ) +} + +export function ResultCard({ lookup, now }: { lookup: Lookup; now: number }) { + const { t } = usePlugin() + const { result } = lookup + return ( +
+
+

+ {lookup.unicode ?? lookup.domain} +

+ {lookup.unicode && {lookup.domain}} + {result.kind === 'found' && {t('outcome.found')}} + {result.kind === 'found' && } + {result.kind === 'notFound' && {t('outcome.notFound')}} + {result.kind === 'noRdap' && {t('outcome.noRdap')}} +
+ {result.kind === 'found' && } + {result.kind === 'notFound' &&

{t('outcome.notFoundHint', { server: result.server })}

} + {result.kind === 'noRdap' && } +
+ ) +} diff --git a/market/domain-lookup/ui/src/data.ts b/market/domain-lookup/ui/src/data.ts new file mode 100644 index 00000000..c472d8b5 --- /dev/null +++ b/market/domain-lookup/ui/src/data.ts @@ -0,0 +1,50 @@ +import { useRef } from 'react' +import { usePlugin, usePluginState } from '@toolforge/plugin-ui-sdk' +import { cached, remember } from './logic.ts' +import type { Bootstrap, BootstrapCache, Lookup, LookupCache, Plan } from './types.ts' + +/** + * 引导文件与查询结果的本地缓存。引导文件每次打开工具后首次查询时用条件请求确认一次: + * 没有变化时服务器回 304,不重复下载;请求失败但有旧缓存时继续用旧的。 + */ +export function useRdap() { + const { call } = usePlugin() + const [bootstrap, setBootstrap] = usePluginState('bootstrap', null) + const [cache, setCache] = usePluginState('cache', {}) + const checked = useRef | null>(null) + + const services = () => { + checked.current ??= (async () => { + const current = bootstrap + try { + const fresh = await call('bootstrap', { etag: current?.etag ?? null, lastModified: current?.lastModified ?? null }) + const next: BootstrapCache = + fresh.notModified && current + ? { ...current, checkedAt: Date.now() } + : { services: fresh.services, etag: fresh.etag, lastModified: fresh.lastModified, publication: fresh.publication, checkedAt: Date.now() } + setBootstrap(next) + return next + } catch (error) { + checked.current = null + if (current && current.services.length > 0) return current + throw error + } + })() + return checked.current.then((b) => b.services) + } + + const plan = async (input: string) => call('plan', { input, services: await services() }) + + /** 查询一个已整理好的域名;refresh 为真时跳过缓存 */ + const lookup = async (domain: string, options: { refresh?: boolean; followRegistrar: boolean }) => { + if (!options.refresh) { + const hit = cached(cache, domain, Date.now()) + if (hit) return { lookup: hit, fromCache: true } + } + const result = await call('lookup', { domain, services: await services(), followRegistrar: options.followRegistrar }) + setCache((prev) => remember(prev, result, Date.now())) + return { lookup: result, fromCache: false } + } + + return { bootstrap, plan, lookup, cache } +} diff --git a/market/domain-lookup/ui/src/index.tsx b/market/domain-lookup/ui/src/index.tsx new file mode 100644 index 00000000..d4aca132 --- /dev/null +++ b/market/domain-lookup/ui/src/index.tsx @@ -0,0 +1,316 @@ +import { useRef, useState, type FormEvent } from 'react' +import { Badge, Button, CodeEditor, DropdownMenu, Empty, Input, Panel, Spinner, Tabs, toast } from '@toolforge/ui' +import { host, useLaunchInput, usePlugin } from '@toolforge/plugin-ui-sdk' +import { ChevronDown, Download, Globe, ListChecks, Play, RefreshCw, Search, Square } from 'lucide-react' +import { ExpiryBadge, ResultCard, useDate } from './Card.tsx' +import { useRdap } from './data.ts' +import { expiry, toCsv } from './logic.ts' +import { DEFAULT_QUEUE, runQueue, type JobState } from './queue.ts' +import type { Lookup, PlanItem } from './types.ts' + +type Tab = 'single' | 'batch' + +function Single({ rdap }: { rdap: ReturnType }) { + const { t, errorMessage } = usePlugin() + const [input, setInput] = useState('') + const [busy, setBusy] = useState(false) + const [current, setCurrent] = useState<{ lookup: Lookup; fromCache: boolean; at: number } | null>(null) + const [error, setError] = useState(null) + + const run = async (text: string, refresh = false) => { + if (!text.trim() || busy) return + setBusy(true) + setError(null) + try { + const plan = await rdap.plan(text) + const item = plan.items[0] + if (!item?.domain) { + setError(errorMessage({ code: item?.error ?? 'domain.empty', params: { input: text } })) + return + } + const result = await rdap.lookup(item.domain, { refresh, followRegistrar: true }) + setCurrent({ ...result, at: Date.now() }) + } catch (reason) { + setError(errorMessage(reason)) + } finally { + setBusy(false) + } + } + + useLaunchInput((text) => { + setInput(text.trim()) + void run(text) + }) + + const submit = (event: FormEvent) => { + event.preventDefault() + void run(input) + } + + return ( + } + title={t('single.title')} + extra={busy && } + actions={ + current && ( + + ) + } + footer={current?.fromCache ? {t('single.cached')} : {t('single.footer')}} + className="h-full" + bodyClassName="space-y-3 overflow-auto p-3" + > +
+ setInput(event.target.value)} + placeholder={t('single.placeholder')} + aria-label={t('single.title')} + leading={} + wrapperClassName="flex-1" + className="font-mono" + autoFocus + /> + + + {error ? ( +

{error}

+ ) : current ? ( + + ) : ( + } title={t('single.empty')} description={t('single.hint')} /> + )} +
+ ) +} + +interface Row extends PlanItem { + state: JobState | null +} + +function outcomeLabel(t: ReturnType['t'], lookup: Lookup) { + return t(`outcome.${lookup.result.kind}`) +} + +function Batch({ rdap }: { rdap: ReturnType }) { + const { t, errorMessage } = usePlugin() + const date = useDate() + const [input, setInput] = useState('') + const [rows, setRows] = useState([]) + const [running, setRunning] = useState(false) + const [duplicates, setDuplicates] = useState(0) + const [now, setNow] = useState(() => Date.now()) + const controller = useRef(null) + + const update = (domain: string, state: JobState) => setRows((prev) => prev.map((row) => (row.domain === domain ? { ...row, state } : row))) + + const start = async () => { + if (running || !input.trim()) return + setRunning(true) + const abort = new AbortController() + controller.current = abort + try { + const plan = await rdap.plan(input) + setDuplicates(plan.duplicates) + setRows(plan.items.map((item) => ({ ...item, state: null }))) + const queued = plan.items.filter((item): item is PlanItem & { domain: string; host: string } => item.domain !== null && item.host !== null) + await runQueue( + queued.map(({ domain, host: lane }) => ({ domain, host: lane })), + { + ...DEFAULT_QUEUE, + signal: abort.signal, + // 批量查询只查注册局,减少对注册商服务器的请求 + lookup: async (domain) => (await rdap.lookup(domain, { followRegistrar: false })).lookup, + onChange: update, + }, + ) + } catch (reason) { + toast.error(errorMessage(reason)) + } finally { + setNow(Date.now()) + setRunning(false) + controller.current = null + } + } + + const stop = () => controller.current?.abort() + + const done = rows.filter((row) => row.state?.status === 'done' || row.state?.status === 'failed' || row.error).length + const exportRows = () => [ + [t('table.domain'), t('table.result'), t('table.registrar'), t('table.expiration'), t('table.daysLeft'), t('table.status'), t('table.error')], + ...rows.map((row) => { + const lookup = row.state?.status === 'done' ? row.state.lookup : null + const info = lookup?.result.kind === 'found' ? lookup.result.info : null + const state = info ? expiry(info.events.expiration, now) : null + const error = row.error ? errorMessage({ code: row.error, params: { input: row.input } }) : row.state?.status === 'failed' ? errorMessage(row.state.error) : '' + return [ + row.unicode ?? row.domain ?? row.input, + lookup ? outcomeLabel(t, lookup) : '', + info?.registrar?.name ?? '', + info?.events.expiration ?? '', + state?.kind === 'active' ? state.days : state?.kind === 'expired' ? -state.days : '', + info?.statuses.join('; ') ?? '', + error, + ] + }), + ] + + const exportCsv = async (target: 'copy' | 'save') => { + try { + const text = toCsv(exportRows()) + if (target === 'copy') { + await host.clipboard.writeText(text) + toast.success(t('batch.copied')) + return + } + const path = await host.dialog.saveFile('domains.csv', [{ name: 'CSV', extensions: ['csv'] }]) + if (!path) return + await host.fs.writeText(path, `\uFEFF${text}`) + toast.success(t('batch.saved')) + } catch (reason) { + toast.error(errorMessage(reason)) + } + } + + const stateCell = (row: Row) => { + if (row.error) return {errorMessage({ code: row.error, params: { input: row.input } })} + const state = row.state + if (!state || state.status === 'pending') return {t('batch.pending')} + if (state.status === 'running') return {t('batch.running')} + if (state.status === 'waiting') return {t('batch.waiting', { seconds: Math.max(1, Math.ceil(state.delay / 1000)), attempt: state.attempt })} + if (state.status === 'failed') return {errorMessage(state.error)} + const result = state.lookup.result + return {outcomeLabel(t, state.lookup)} + } + + return ( +
+ } + title={t('batch.input')} + actions={ + running ? ( + + ) : ( + + ) + } + footer={{t('batch.hint')}} + > + + + } + title={t('batch.result')} + extra={ + rows.length > 0 && ( + + {t('batch.progress', { done, total: rows.length })} + {duplicates > 0 && {t('batch.duplicates', { count: duplicates })}} + + ) + } + actions={ + + + {t('batch.export')} + + + } + items={[ + { key: 'copy', label: t('batch.copyCsv'), onSelect: () => void exportCsv('copy') }, + { key: 'save', label: t('batch.saveCsv'), onSelect: () => void exportCsv('save') }, + ]} + /> + } + bodyClassName="overflow-auto" + > + {rows.length === 0 ? ( + } title={t('batch.empty')} description={t('batch.emptyHint')} /> + ) : ( + + + + + + + + + + + {rows.map((row, index) => { + const lookup = row.state?.status === 'done' ? row.state.lookup : null + const info = lookup?.result.kind === 'found' ? lookup.result.info : null + return ( + + + + + + + ) + })} + +
{t('table.domain')}{t('table.result')}{t('table.registrar')}{t('table.expiration')}
+ {row.unicode ?? row.domain ?? row.input} + {stateCell(row)}{info?.registrar?.name ?? ''} + {info && ( + + {date(info.events.expiration)} + + + )} +
+ )} +
+
+ ) +} + +function DomainLookupTool() { + const { t } = usePlugin() + const date = useDate() + const rdap = useRdap() + const [tab, setTab] = useState('single') + return ( +
+
+ + value={tab} + onValueChange={setTab} + aria-label={t('name')} + items={[ + { value: 'single', label: t('tabs.single'), icon: }, + { value: 'batch', label: t('tabs.batch'), icon: }, + ]} + /> + {rdap.bootstrap?.publication && {t('bootstrap.published', { date: date(rdap.bootstrap.publication) })}} +
+
+ + +
+
+ ) +} + +export default DomainLookupTool diff --git a/market/domain-lookup/ui/src/logic.ts b/market/domain-lookup/ui/src/logic.ts new file mode 100644 index 00000000..c780050b --- /dev/null +++ b/market/domain-lookup/ui/src/logic.ts @@ -0,0 +1,83 @@ +import type { Lookup, LookupCache } from './types.ts' + +const DAY = 24 * 60 * 60 * 1000 + +/** 单个域名的结果缓存多久;之后重新查询,手动刷新总是重新查询 */ +export const CACHE_TTL = 6 * 60 * 60 * 1000 +/** 缓存最多保留的域名数,超出时丢弃最早的 */ +export const CACHE_LIMIT = 300 + +export type Expiry = { kind: 'unknown' } | { kind: 'expired'; days: number } | { kind: 'active'; days: number } + +/** + * 到期状态:没有到期日期时是「未知」(如 .de 不公布),不是 0 天; + * 已过期的显示过期天数,不显示负数倒计时 + */ +export function expiry(expiration: string | null | undefined, now: number): Expiry { + if (!expiration) return { kind: 'unknown' } + const at = Date.parse(expiration) + if (Number.isNaN(at)) return { kind: 'unknown' } + if (at <= now) return { kind: 'expired', days: Math.floor((now - at) / DAY) } + return { kind: 'active', days: Math.ceil((at - now) / DAY) } +} + +/** 快到期(30 天内)时提醒 */ +export const SOON_DAYS = 30 + +export type Tone = 'success' | 'warning' | 'danger' | 'neutral' + +/** 「client transfer prohibited」→「clientTransferProhibited」,作为翻译键 */ +export function statusKey(status: string): string { + return status + .trim() + .toLowerCase() + .split(/[\s_-]+/) + .filter(Boolean) + .map((part, index) => (index === 0 ? part : part[0].toUpperCase() + part.slice(1))) + .join('') +} + +/** 状态的提示色:赎回期、待删除为危险,暂停解析为警告,锁定类为中性 */ +export function statusTone(status: string): Tone { + const key = statusKey(status).toLowerCase() + if (key.includes('redemption') || key.includes('pendingdelete') || key.includes('pendingrestore')) return 'danger' + if (key.includes('hold') || key.includes('inactive') || key.includes('expired')) return 'warning' + if (key === 'active' || key === 'ok') return 'success' + return 'neutral' +} + +/** + * 退避时间:服务器给了 Retry-After 就照它等;否则指数退避(2s、4s、8s… 上限 60s), + * 再乘以 0.7–1.3 的随机系数,避免同一主机的请求同时重来 + */ +export function backoff(attempt: number, retryAfterSeconds: number | null | undefined, random: () => number = Math.random): number { + if (retryAfterSeconds !== null && retryAfterSeconds !== undefined && retryAfterSeconds >= 0) return Math.min(retryAfterSeconds, 300) * 1000 + const base = Math.min(2000 * 2 ** attempt, 60_000) + return Math.round(base * (0.7 + random() * 0.6)) +} + +export function cached(cache: LookupCache, domain: string, now: number): Lookup | null { + const entry = cache[domain] + return entry && now - entry.at < CACHE_TTL ? entry.lookup : null +} + +/** 写入缓存并按时间淘汰最早的条目 */ +export function remember(cache: LookupCache, lookup: Lookup, now: number): LookupCache { + const next: LookupCache = { ...cache, [lookup.domain]: { at: now, lookup } } + const keys = Object.keys(next) + if (keys.length <= CACHE_LIMIT) return next + keys.sort((a, b) => next[a].at - next[b].at) + for (const key of keys.slice(0, keys.length - CACHE_LIMIT)) delete next[key] + return next +} + +export function csvField(value: string | number | null | undefined): string { + const text = value === null || value === undefined ? '' : String(value) + // 以 = + - @ 开头的值在表格软件里会被当成公式执行 + const safe = /^[=+\-@\t\r]/.test(text) ? `'${text}` : text + return /[",\n\r]/.test(safe) ? `"${safe.replace(/"/g, '""')}"` : safe +} + +export function toCsv(rows: (string | number | null | undefined)[][]): string { + return rows.map((row) => row.map(csvField).join(',')).join('\r\n') + '\r\n' +} diff --git a/market/domain-lookup/ui/src/queue.ts b/market/domain-lookup/ui/src/queue.ts new file mode 100644 index 00000000..0fb80325 --- /dev/null +++ b/market/domain-lookup/ui/src/queue.ts @@ -0,0 +1,98 @@ +import { backoff } from './logic.ts' +import type { Lookup } from './types.ts' + +export interface QueueError { + code: string + params?: Record +} + +export type JobState = + | { status: 'pending' } + | { status: 'running'; attempt: number } + | { status: 'waiting'; attempt: number; delay: number } + | { status: 'done'; lookup: Lookup } + | { status: 'failed'; error: QueueError } + +export interface QueueOptions { + /** 不同 RDAP 主机同时进行的数量;同一主机始终只有一个请求 */ + parallelHosts: number + maxAttempts: number + lookup: (domain: string) => Promise + onChange: (domain: string, state: JobState) => void + signal: AbortSignal + sleep?: (ms: number, signal: AbortSignal) => Promise + random?: () => number +} + +export const DEFAULT_QUEUE = { parallelHosts: 3, maxAttempts: 5 } as const + +/** 值得退避重试的错误:限流、网络故障与服务器错误;403 等其他错误不重试 */ +export function retryable(error: QueueError): boolean { + if (error.code === 'rdap.rate_limited' || error.code === 'rdap.network') return true + if (error.code === 'rdap.failed') return Number(error.params?.status) >= 500 + return false +} + +export function abortableSleep(ms: number, signal: AbortSignal): Promise { + return new Promise((resolve, reject) => { + if (signal.aborted) return reject(signal.reason) + const timer = setTimeout(() => { + signal.removeEventListener('abort', onAbort) + resolve() + }, ms) + const onAbort = () => { + clearTimeout(timer) + reject(signal.reason) + } + signal.addEventListener('abort', onAbort, { once: true }) + }) +} + +const asError = (reason: unknown): QueueError => + reason && typeof reason === 'object' && 'code' in reason ? (reason as QueueError) : { code: 'app.unknown', params: { detail: String(reason) } } + +/** + * 批量查询:按 RDAP 主机分道(.com 与 .net 同在 Verisign,共用一道), + * 每道依次查询,多道并行;被限流的那一道按 Retry-After 或退避时间等待后重试。 + * 停止后不再发出新请求,已发出的请求结果照常记录。 + */ +export async function runQueue(items: { domain: string; host: string }[], options: QueueOptions): Promise { + const sleep = options.sleep ?? abortableSleep + const lanes = new Map() + for (const { domain, host } of items) { + lanes.set(host, [...(lanes.get(host) ?? []), domain]) + } + const pending = [...lanes.values()] + + const runLane = async (domains: string[]) => { + for (const domain of domains) { + for (let attempt = 1; ; attempt++) { + if (options.signal.aborted) return + options.onChange(domain, { status: 'running', attempt }) + try { + options.onChange(domain, { status: 'done', lookup: await options.lookup(domain) }) + break + } catch (reason) { + const error = asError(reason) + if (!retryable(error) || attempt >= options.maxAttempts) { + options.onChange(domain, { status: 'failed', error }) + break + } + const retryAfter = typeof error.params?.retryAfter === 'number' ? error.params.retryAfter : null + const delay = backoff(attempt - 1, retryAfter, options.random) + options.onChange(domain, { status: 'waiting', attempt, delay }) + try { + await sleep(delay, options.signal) + } catch { + return + } + } + } + } + } + + const worker = async () => { + for (let lane = pending.shift(); lane; lane = pending.shift()) await runLane(lane) + } + await Promise.all(Array.from({ length: Math.max(1, Math.min(options.parallelHosts, pending.length)) }, worker)) +} diff --git a/market/domain-lookup/ui/src/types.ts b/market/domain-lookup/ui/src/types.ts new file mode 100644 index 00000000..4664b32b --- /dev/null +++ b/market/domain-lookup/ui/src/types.ts @@ -0,0 +1,98 @@ +export type Party = 'registry' | 'registrar' + +export interface Service { + tlds: string[] + urls: string[] +} + +export interface Bootstrap { + notModified: boolean + services: Service[] + etag: string | null + lastModified: string | null + publication: string | null +} + +/** 插件存储中的引导文件缓存 */ +export interface BootstrapCache { + services: Service[] + etag: string | null + lastModified: string | null + publication: string | null + checkedAt: number +} + +export interface Registrar { + name: string | null + ianaId: string | null + abuseEmail: string | null + abusePhone: string | null +} + +export interface Contact { + role: string + by: Party + name: string | null + organization: string | null + email: string | null + phone: string | null + country: string | null + placeholders: string[] + remarksRedacted: boolean +} + +export interface Redaction { + field: string + by: Party + method: string | null + reason: string | null +} + +export interface DomainInfo { + ldhName: string + handle: string | null + statuses: string[] + registrar: Registrar | null + contacts: Contact[] + events: { registration: string | null; expiration: string | null; lastChanged: string | null; lastRdapUpdate: string | null } + nameservers: string[] + dnssec: boolean | null + redactions: Redaction[] + sources: { by: Party; url: string; error: string | null }[] + raw: { by: Party; url: string; json: unknown }[] +} + +export interface TldInfo { + tld: string + manager: string | null + registrationUrl: string | null + nameservers: string[] + dnssec: boolean | null + registered: string | null + lastChanged: string | null + raw: unknown +} + +export type Outcome = { kind: 'found'; info: DomainInfo } | { kind: 'notFound'; server: string } | { kind: 'noRdap'; tld: TldInfo } + +export interface Lookup { + domain: string + unicode: string | null + result: Outcome +} + +export interface PlanItem { + input: string + domain: string | null + unicode: string | null + host: string | null + error: string | null +} + +export interface Plan { + items: PlanItem[] + duplicates: number +} + +/** 按域名缓存的查询结果 */ +export type LookupCache = Record diff --git a/market/domain-lookup/ui/tests/logic.test.mjs b/market/domain-lookup/ui/tests/logic.test.mjs new file mode 100644 index 00000000..7336c31b --- /dev/null +++ b/market/domain-lookup/ui/tests/logic.test.mjs @@ -0,0 +1,54 @@ +import assert from 'node:assert/strict' +import test from 'node:test' +import { CACHE_LIMIT, CACHE_TTL, backoff, cached, csvField, expiry, remember, statusKey, statusTone, toCsv } from '../src/logic.ts' + +const now = Date.parse('2026-12-03T00:00:00Z') + +test('expiry has unknown, expired and active states, never a negative countdown', () => { + assert.deepEqual(expiry(null, now), { kind: 'unknown' }) + assert.deepEqual(expiry('garbage', now), { kind: 'unknown' }) + assert.deepEqual(expiry('2026-12-13T00:00:00Z', now), { kind: 'active', days: 10 }) + assert.deepEqual(expiry('2026-12-03T00:00:01Z', now), { kind: 'active', days: 1 }) + assert.deepEqual(expiry('2026-11-23T00:00:00Z', now), { kind: 'expired', days: 10 }) + assert.deepEqual(expiry('2026-12-03T00:00:00Z', now), { kind: 'expired', days: 0 }) +}) + +test('status keys and tones', () => { + assert.equal(statusKey('client transfer prohibited'), 'clientTransferProhibited') + assert.equal(statusKey('redemption period'), 'redemptionPeriod') + assert.equal(statusTone('pending delete'), 'danger') + assert.equal(statusTone('redemption period'), 'danger') + assert.equal(statusTone('server hold'), 'warning') + assert.equal(statusTone('active'), 'success') + assert.equal(statusTone('client transfer prohibited'), 'neutral') +}) + +test('backoff honors Retry-After and otherwise grows with jitter up to a cap', () => { + assert.equal(backoff(0, 7), 7000) + assert.equal(backoff(3, 0), 0) + assert.equal(backoff(0, 9999), 300_000) + assert.equal(backoff(0, null, () => 0.5), 2000) + assert.equal(backoff(2, null, () => 0.5), 8000) + assert.equal(backoff(10, null, () => 0.5), 60_000) + assert.equal(backoff(0, null, () => 0), 1400) + assert.equal(backoff(0, null, () => 1), 2600) +}) + +test('cache expires and evicts the oldest entries', () => { + const lookup = (domain) => ({ domain, unicode: null, result: { kind: 'notFound', server: 'x' } }) + let cache = remember({}, lookup('a.com'), now) + assert.equal(cached(cache, 'a.com', now + 1)?.domain, 'a.com') + assert.equal(cached(cache, 'a.com', now + CACHE_TTL), null) + for (let i = 0; i < CACHE_LIMIT + 5; i++) cache = remember(cache, lookup(`d${i}.com`), now + i + 1) + assert.equal(Object.keys(cache).length, CACHE_LIMIT) + assert.equal(cache['a.com'], undefined) +}) + +test('csv escapes quotes, separators and formula prefixes', () => { + assert.equal(csvField('plain'), 'plain') + assert.equal(csvField('a,b'), '"a,b"') + assert.equal(csvField('say "hi"'), '"say ""hi"""') + assert.equal(csvField('=HYPERLINK("x")'), `"'=HYPERLINK(""x"")"`) + assert.equal(csvField(null), '') + assert.equal(toCsv([['a', 1], ['b', null]]), 'a,1\r\nb,\r\n') +}) diff --git a/market/domain-lookup/ui/tests/queue.test.mjs b/market/domain-lookup/ui/tests/queue.test.mjs new file mode 100644 index 00000000..efe21c37 --- /dev/null +++ b/market/domain-lookup/ui/tests/queue.test.mjs @@ -0,0 +1,95 @@ +/* global AbortController, setTimeout */ +import assert from 'node:assert/strict' +import test from 'node:test' +import { retryable, runQueue } from '../src/queue.ts' + +const found = (domain) => ({ domain, unicode: null, result: { kind: 'notFound', server: 'h' } }) + +function harness(behaviour) { + const calls = [] + const sleeps = [] + const states = new Map() + let inFlight = new Map() + let maxPerHost = 0 + const hostOf = (domain) => domain.split('@')[1] + return { + calls, + sleeps, + states, + get maxPerHost() { + return maxPerHost + }, + options: (signal = new AbortController().signal) => ({ + parallelHosts: 3, + maxAttempts: 3, + signal, + random: () => 0.5, + sleep: async (ms) => { + sleeps.push(ms) + }, + onChange: (domain, state) => states.set(domain, state), + lookup: async (domain) => { + const host = hostOf(domain) + inFlight.set(host, (inFlight.get(host) ?? 0) + 1) + maxPerHost = Math.max(maxPerHost, inFlight.get(host)) + calls.push(domain) + await new Promise((r) => setTimeout(r, 1)) + inFlight.set(host, inFlight.get(host) - 1) + return behaviour(domain, calls.filter((c) => c === domain).length) + }, + }), + } +} + +const items = (...domains) => domains.map((domain) => ({ domain, host: domain.split('@')[1] })) + +test('one request at a time per host, several hosts in parallel', async () => { + const h = harness((domain) => found(domain)) + await runQueue(items('a@x', 'b@x', 'c@x', 'd@y', 'e@z'), h.options()) + assert.equal(h.maxPerHost, 1) + assert.equal(h.calls.length, 5) + assert.ok([...h.states.values()].every((s) => s.status === 'done')) +}) + +test('rate limits wait for Retry-After, then succeed', async () => { + const h = harness((domain, n) => { + if (n === 1) throw { code: 'rdap.rate_limited', params: { retryAfter: 4 } } + return found(domain) + }) + await runQueue(items('a@x'), h.options()) + assert.deepEqual(h.sleeps, [4000]) + assert.equal(h.states.get('a@x').status, 'done') +}) + +test('server errors back off exponentially and give up after max attempts', async () => { + const h = harness(() => { + throw { code: 'rdap.failed', params: { status: 503 } } + }) + await runQueue(items('a@x'), h.options()) + assert.deepEqual(h.sleeps, [2000, 4000]) + assert.equal(h.calls.length, 3) + assert.equal(h.states.get('a@x').status, 'failed') +}) + +test('forbidden and other errors are not retried', async () => { + const h = harness(() => { + throw { code: 'rdap.forbidden', params: { host: 'x' } } + }) + await runQueue(items('a@x', 'b@x'), h.options()) + assert.equal(h.calls.length, 2) + assert.deepEqual(h.sleeps, []) + assert.equal(retryable({ code: 'rdap.failed', params: { status: 404 } }), false) + assert.equal(retryable({ code: 'rdap.network' }), true) +}) + +test('stopping sends no new requests', async () => { + const controller = new AbortController() + const h = harness((domain) => { + controller.abort() + return found(domain) + }) + await runQueue(items('a@x', 'b@x', 'c@x'), h.options(controller.signal)) + assert.deepEqual(h.calls, ['a@x']) + assert.equal(h.states.get('a@x').status, 'done') + assert.equal(h.states.has('b@x'), false) +}) diff --git a/market/domain-lookup/ui/tsconfig.json b/market/domain-lookup/ui/tsconfig.json new file mode 100644 index 00000000..625277c6 --- /dev/null +++ b/market/domain-lookup/ui/tsconfig.json @@ -0,0 +1,4 @@ +{ + "extends": "../../../tsconfig.base.json", + "include": ["src"] +} diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index c5af0181..e1493601 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -928,6 +928,37 @@ importers: specifier: 8.3.0 version: 8.3.0(@types/node@24.13.6)(jiti@2.7.0) + market/domain-lookup/ui: + dependencies: + '@toolforge/plugin-ui-sdk': + specifier: workspace:* + version: link:../../../packages/plugin-ui-sdk + '@toolforge/ui': + specifier: workspace:* + version: link:../../../packages/ui + lucide-react: + specifier: 1.47.0 + version: 1.47.0(react@19.3.0) + react-i18next: + specifier: 17.0.15 + version: 17.0.15(i18next@26.4.2(typescript@5.9.3))(react-dom@19.3.0(react@19.3.0))(react@19.3.0)(typescript@5.9.3) + devDependencies: + '@types/react': + specifier: 19.3.0 + version: 19.3.0 + react: + specifier: 19.3.0 + version: 19.3.0 + tailwindcss: + specifier: 4.3.3 + version: 4.3.3 + typescript: + specifier: 5.9.3 + version: 5.9.3 + vite: + specifier: 8.3.0 + version: 8.3.0(@types/node@24.13.6)(jiti@2.7.0) + market/domain-toolbox/ui: dependencies: '@toolforge/plugin-ui-sdk': From bb3c402ded5602d51bd3dea1538095fb4993042e Mon Sep 17 00:00:00 2001 From: qianmoQ Date: Thu, 3 Dec 2026 04:20:11 -0500 Subject: [PATCH 15/15] feat(ai-writer): add offline writing assistant with local models Run Qwen2.5 Instruct (0.5B or 1.5B, Q4_K_M GGUF) with candle on the CPU to polish, proofread, rewrite, shorten, expand, summarize, translate or follow a custom instruction. The models are plugin resources, so their cards are the model manager: download with resume and SHA-256 checks from Hugging Face or its mirrors, switch, and delete. - a byte-level BPE tokenizer built from the GGUF vocabulary and merges, so no tokenizer file or C regex library is needed; markers typed by users stay plain text - generate runs as a cancellable task: chunked prefill, low-temperature sampling, streamed partial text through throttled logs; the model unloads after five idle minutes - other tools can start the generate task; it picks the best downloaded model and answers ai.no_model when there is none Refs #205 --- Cargo.lock | 555 +++++++++++++++++- Cargo.toml | 31 + README.md | 1 + README.zh-CN.md | 1 + apps/desktop/src-tauri/Cargo.toml | 1 + apps/desktop/src-tauri/src/plugins.rs | 1 + plugins/ai-writer/backend/Cargo.toml | 15 + plugins/ai-writer/backend/src/engine.rs | 273 +++++++++ plugins/ai-writer/backend/src/lib.rs | 175 ++++++ plugins/ai-writer/backend/src/lib_test.rs | 159 +++++ plugins/ai-writer/backend/src/prompt.rs | 137 +++++ plugins/ai-writer/backend/src/prompt_test.rs | 71 +++ plugins/ai-writer/backend/src/tokenizer.rs | 190 ++++++ .../ai-writer/backend/src/tokenizer_test.rs | 83 +++ plugins/ai-writer/icon.svg | 1 + plugins/ai-writer/locales/en-US.json | 106 ++++ plugins/ai-writer/locales/zh-CN.json | 105 ++++ plugins/ai-writer/manifest.json | 40 ++ plugins/ai-writer/ui/package.json | 27 + plugins/ai-writer/ui/src/AiWriter.tsx | 150 +++++ plugins/ai-writer/ui/src/index.tsx | 3 + plugins/ai-writer/ui/src/useGeneration.ts | 101 ++++ plugins/ai-writer/ui/tsconfig.json | 4 + pnpm-lock.yaml | 28 + 24 files changed, 2251 insertions(+), 7 deletions(-) create mode 100644 plugins/ai-writer/backend/Cargo.toml create mode 100644 plugins/ai-writer/backend/src/engine.rs create mode 100644 plugins/ai-writer/backend/src/lib.rs create mode 100644 plugins/ai-writer/backend/src/lib_test.rs create mode 100644 plugins/ai-writer/backend/src/prompt.rs create mode 100644 plugins/ai-writer/backend/src/prompt_test.rs create mode 100644 plugins/ai-writer/backend/src/tokenizer.rs create mode 100644 plugins/ai-writer/backend/src/tokenizer_test.rs create mode 100644 plugins/ai-writer/icon.svg create mode 100644 plugins/ai-writer/locales/en-US.json create mode 100644 plugins/ai-writer/locales/zh-CN.json create mode 100644 plugins/ai-writer/manifest.json create mode 100644 plugins/ai-writer/ui/package.json create mode 100644 plugins/ai-writer/ui/src/AiWriter.tsx create mode 100644 plugins/ai-writer/ui/src/index.tsx create mode 100644 plugins/ai-writer/ui/src/useGeneration.ts create mode 100644 plugins/ai-writer/ui/tsconfig.json diff --git a/Cargo.lock b/Cargo.lock index bdc980a2..f414d6fd 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -561,6 +561,12 @@ version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4c7f02d4ea65f2c1853089ffd8d2787bdbc63de2f0d29dedbcf8ccdfa0ccd4cf" +[[package]] +name = "base64" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e1b586273c5702936fe7b7d6896644d8be71e6314cfe09d3167c95f712589e8" + [[package]] name = "base64" version = "0.21.7" @@ -689,7 +695,7 @@ dependencies = [ "arrayvec", "cc", "cfg-if", - "constant_time_eq", + "constant_time_eq 0.4.2", "cpufeatures 0.3.1", ] @@ -970,6 +976,68 @@ dependencies = [ "serde_core", ] +[[package]] +name = "candle-core" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d11c8be87cfbaef9ebb62fb3f850d1fc8e00cc1d11d393fdbe55a4d5c2cdb325" +dependencies = [ + "byteorder", + "float8", + "gemm", + "half", + "libc", + "libm", + "memmap2", + "num-traits", + "num_cpus", + "parking_lot", + "rand 0.9.5", + "rand_distr 0.5.1", + "rayon", + "safetensors", + "thiserror 2.0.20", + "tokenizers", + "yoke", + "zerocopy", + "zip 9.9.0", +] + +[[package]] +name = "candle-nn" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "437fabe77547c2447c7bdf3cc946e19db29a2832440176b419f77c80b0a9a05e" +dependencies = [ + "candle-core", + "half", + "libc", + "num-traits", + "rayon", + "safetensors", + "serde", + "thiserror 2.0.20", +] + +[[package]] +name = "candle-transformers" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b1e1abeac23d7df4f94e8a3852b3dbb661d332e37c3bef479507bac867187b2" +dependencies = [ + "byteorder", + "candle-core", + "candle-nn", + "fancy-regex 0.19.2", + "num-traits", + "rand 0.9.5", + "rayon", + "serde", + "serde_json", + "serde_plain", + "tracing", +] + [[package]] name = "cap-primitives" version = "4.0.3" @@ -1021,6 +1089,15 @@ dependencies = [ "toml 0.9.12+spec-1.1.0", ] +[[package]] +name = "castaway" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dec551ab6e7578819132c713a93c022a05d60159dc86e7a7050223577484c55a" +dependencies = [ + "rustversion", +] + [[package]] name = "cbc" version = "0.1.2" @@ -1262,6 +1339,21 @@ dependencies = [ "memchr", ] +[[package]] +name = "compact_str" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9dfdd1c2274d9aa354115b09dc9a901d6c5576818cdf70d14cae2bdb47df00ab" +dependencies = [ + "castaway", + "cfg-if", + "itoa", + "rustversion", + "ryu", + "serde", + "static_assertions", +] + [[package]] name = "concurrent-queue" version = "2.5.0" @@ -1309,6 +1401,15 @@ version = "0.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3d52eff69cd5e647efe296129160853a42795992097e8af39800e1060caeea9b" +[[package]] +name = "constant_time_eq" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "144e7f1de087984240b7816d47f698b414979faa6f40839c5b86d6bd47db57b7" +dependencies = [ + "rustversion", +] + [[package]] name = "cookie" version = "0.18.2" @@ -1789,6 +1890,12 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "daachorse" +version = "3.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5614204febbc33cc07a2806aa6440b904ac012b68eecc37f4493ea4a76455a3d" + [[package]] name = "darling" version = "0.20.11" @@ -1858,6 +1965,15 @@ dependencies = [ "syn 3.0.6", ] +[[package]] +name = "dary_heap" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b1e3a325bc115f096c8b77bbf027a7c2592230e70be2d985be950d3d5e60ebe" +dependencies = [ + "serde", +] + [[package]] name = "data-encoding" version = "2.11.1" @@ -2234,6 +2350,22 @@ version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5fdab65db9274e0168143841eb8f864a0a21f8b1b8d2ba6812bbe6024346e99e" +[[package]] +name = "dyn-stack" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c4713e43e2886ba72b8271aa66c93d722116acf7a75555cce11dcde84388fe8" +dependencies = [ + "bytemuck", + "dyn-stack-macros", +] + +[[package]] +name = "dyn-stack-macros" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e1d926b4d407d372f141f93bb444696142c29d32962ccbd3531117cf3aa0bfa9" + [[package]] name = "ecb" version = "0.1.2" @@ -2379,6 +2511,18 @@ version = "1.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "66b7e2430c6dff6a955451e2cfc438f09cea1965a9d6f87f7e3b90decc014099" +[[package]] +name = "enum-as-inner" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a1e6a265c649f3f5979b601d26f1d05ada116434c87741c9493cb56218f76cbc" +dependencies = [ + "heck 0.5.0", + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "enumflags2" version = "0.7.12" @@ -2433,6 +2577,12 @@ version = "3.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0b5343afd4a8365a643ac588dab4cf234a190c7f6c88c9f6dd6ffe00837661b7" +[[package]] +name = "esaxx-rs" +version = "0.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d817e038c30374a4bcb22f94d0a8a0e216958d4c3dcde369b1439fec4bdda6e6" + [[package]] name = "euclid" version = "0.22.14" @@ -2480,6 +2630,17 @@ version = "0.1.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7360491ce676a36bf9bb3c56c1aa791658183a54d2744120f27285738d90465a" +[[package]] +name = "fancy-regex" +version = "0.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72cf461f865c862bb7dc573f643dd6a2b6842f7c30b07882b56bd148cc2761b8" +dependencies = [ + "bit-set 0.8.0", + "regex-automata", + "regex-syntax", +] + [[package]] name = "fancy-regex" version = "0.19.2" @@ -2605,6 +2766,18 @@ version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8ce81f49ae8a0482e4c55ea62ebbd7e5a686af544c00b9d090bba3ff9be97b3d" +[[package]] +name = "float8" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2d1f04709a8ac06e8e8042875a3c466cc4832d3c1a18dbcb9dba3c6e83046bc" +dependencies = [ + "half", + "num-traits", + "rand 0.9.5", + "rand_distr 0.5.1", +] + [[package]] name = "fluent-uri" version = "0.4.1" @@ -2950,6 +3123,125 @@ dependencies = [ "x11", ] +[[package]] +name = "gemm" +version = "0.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aa0673db364b12263d103b68337a68fbecc541d6f6b61ba72fe438654709eacb" +dependencies = [ + "dyn-stack", + "gemm-c32", + "gemm-c64", + "gemm-common", + "gemm-f16", + "gemm-f32", + "gemm-f64", + "num-complex", + "num-traits", + "paste", + "raw-cpuid", + "seq-macro", +] + +[[package]] +name = "gemm-c32" +version = "0.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "086936dbdcb99e37aad81d320f98f670e53c1e55a98bee70573e83f95beb128c" +dependencies = [ + "dyn-stack", + "gemm-common", + "num-complex", + "num-traits", + "paste", + "raw-cpuid", + "seq-macro", +] + +[[package]] +name = "gemm-c64" +version = "0.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20c8aeeeec425959bda4d9827664029ba1501a90a0d1e6228e48bef741db3a3f" +dependencies = [ + "dyn-stack", + "gemm-common", + "num-complex", + "num-traits", + "paste", + "raw-cpuid", + "seq-macro", +] + +[[package]] +name = "gemm-common" +version = "0.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "88027625910cc9b1085aaaa1c4bc46bb3a36aad323452b33c25b5e4e7c8e2a3e" +dependencies = [ + "bytemuck", + "dyn-stack", + "half", + "libm", + "num-complex", + "num-traits", + "once_cell", + "paste", + "pulp", + "raw-cpuid", + "rayon", + "seq-macro", + "sysctl", +] + +[[package]] +name = "gemm-f16" +version = "0.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3df7a55202e6cd6739d82ae3399c8e0c7e1402859b30e4cb780e61525d9486e" +dependencies = [ + "dyn-stack", + "gemm-common", + "gemm-f32", + "half", + "num-complex", + "num-traits", + "paste", + "raw-cpuid", + "rayon", + "seq-macro", +] + +[[package]] +name = "gemm-f32" +version = "0.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "02e0b8c9da1fbec6e3e3ab2ce6bc259ef18eb5f6f0d3e4edf54b75f9fd41a81c" +dependencies = [ + "dyn-stack", + "gemm-common", + "num-complex", + "num-traits", + "paste", + "raw-cpuid", + "seq-macro", +] + +[[package]] +name = "gemm-f64" +version = "0.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "056131e8f2a521bfab322f804ccd652520c79700d81209e9d9275bbdecaadc6a" +dependencies = [ + "dyn-stack", + "gemm-common", + "num-complex", + "num-traits", + "paste", + "raw-cpuid", + "seq-macro", +] + [[package]] name = "generic-array" version = "0.14.7" @@ -3280,9 +3572,12 @@ version = "2.7.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6ea2d84b969582b4b1864a92dc5d27cd2b77b622a8d79306834f1be5ba20d84b" dependencies = [ + "bytemuck", "cfg-if", "crunchy", "num-traits", + "rand 0.9.5", + "rand_distr 0.5.1", "zerocopy", ] @@ -3313,7 +3608,11 @@ version = "0.16.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100" dependencies = [ + "allocator-api2", + "equivalent", "foldhash 0.2.0", + "serde", + "serde_core", ] [[package]] @@ -4302,7 +4601,7 @@ dependencies = [ "bytecount", "data-encoding", "email_address", - "fancy-regex", + "fancy-regex 0.19.2", "fraction", "getrandom 0.3.4", "idna", @@ -4339,7 +4638,7 @@ version = "0.58.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bf3ebe067f2c25a981a7d1b2f696fc213e10dbf80ba5fe997f7dc2e4fe261f26" dependencies = [ - "fancy-regex", + "fancy-regex 0.19.2", "indexmap 2.14.2", "jsonschema-regex", "percent-encoding", @@ -4833,6 +5132,22 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "macro_rules_attribute" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b3ae8f6d608c795738406608304d30a2dfbdc8e58e44f7ba43236da5208ded3c" +dependencies = [ + "macro_rules_attribute-proc_macro", + "pastey", +] + +[[package]] +name = "macro_rules_attribute-proc_macro" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc04a4c58212d57930a24bf47d3fa87485264a3a054e9c10e042eb373573ad3c" + [[package]] name = "maplit" version = "1.0.2" @@ -4908,6 +5223,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d1219ed1b7f229ee7104d281dd01d6802fe28bb6e95d292942c4daacdeb798c0" dependencies = [ "libc", + "stable_deref_trait", ] [[package]] @@ -5056,6 +5372,28 @@ dependencies = [ "uuid", ] +[[package]] +name = "monostate" +version = "0.1.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3341a273f6c9d5bef1908f17b7267bbab0e95c9bf69a0d4dcf8e9e1b2c76ef67" +dependencies = [ + "monostate-impl", + "serde", + "serde_core", +] + +[[package]] +name = "monostate-impl" +version = "0.1.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e4db6d5580af57bf992f59068d4ea26fd518574ff48d7639b255a36f9de6e7e9" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "moxcms" version = "0.8.1" @@ -5361,6 +5699,7 @@ version = "0.4.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "73f88a1307638156682bada9d7604135552957b7818057dcef22705b4d509495" dependencies = [ + "bytemuck", "num-traits", ] @@ -5421,6 +5760,16 @@ dependencies = [ "libm", ] +[[package]] +name = "num_cpus" +version = "1.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "91df4bbde75afed763b708b7eee1e8e7651e02d97f6d5dd763e89367e957b23b" +dependencies = [ + "hermit-abi", + "libc", +] + [[package]] name = "num_enum" version = "0.7.6" @@ -6551,6 +6900,29 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "pulp" +version = "0.22.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "046aa45b989642ec2e4717c8e72d677b13edd831a4d3b6cf37d9a3e54912496a" +dependencies = [ + "bytemuck", + "cfg-if", + "libm", + "num-complex", + "paste", + "pulp-wasm-simd-flag", + "raw-cpuid", + "reborrow", + "version_check", +] + +[[package]] +name = "pulp-wasm-simd-flag" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d8f70e07b9c3962945a74e59ca1c511bba65b6419468acc217c457d93f3c740" + [[package]] name = "pxfm" version = "0.1.30" @@ -6691,6 +7063,16 @@ version = "0.10.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69" +[[package]] +name = "rand_distr" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6a8615d50dcf34fa31f7ab52692afec947c4dd0ab803cc87cb3b0b4570ff7463" +dependencies = [ + "num-traits", + "rand 0.9.5", +] + [[package]] name = "rand_distr" version = "0.6.0" @@ -6707,6 +7089,15 @@ version = "1.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a611d15b50743feb4c76b7d03edcb0e64f399c26961e4efe6975bc398be6aa3d" +[[package]] +name = "raw-cpuid" +version = "11.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "498cd0dc59d73224351ee52a95fee0f1a617a2eae0e7d9d720cc622c73a54186" +dependencies = [ + "bitflags 2.13.2", +] + [[package]] name = "raw-window-handle" version = "0.6.2" @@ -6729,6 +7120,17 @@ dependencies = [ "rayon-core", ] +[[package]] +name = "rayon-cond" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2964d0cf57a3e7a06e8183d14a8b527195c706b7983549cd5462d5aa3747438f" +dependencies = [ + "either", + "itertools 0.14.0", + "rayon", +] + [[package]] name = "rayon-core" version = "1.13.0" @@ -6763,6 +7165,12 @@ dependencies = [ "font-types", ] +[[package]] +name = "reborrow" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "03251193000f4bd3b042892be858ee50e8b3719f2b08e5833ac4353724632430" + [[package]] name = "redox_syscall" version = "0.5.18" @@ -7277,6 +7685,19 @@ version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" +[[package]] +name = "safetensors" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "79b079b829cb27a1c3c374341345ed2e8b2c0c839034522cee576c140bd7f846" +dependencies = [ + "hashbrown 0.16.1", + "libc", + "serde", + "serde_json", + "tempfile", +] + [[package]] name = "same-file" version = "1.0.6" @@ -7557,6 +7978,15 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "serde_plain" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ce1fc6db65a611022b23a0dec6975d63fb80a302cb3388835ff02c097258d50" +dependencies = [ + "serde", +] + [[package]] name = "serde_repr" version = "0.1.21" @@ -7999,6 +8429,18 @@ dependencies = [ "der", ] +[[package]] +name = "spm_precompiled" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5851699c4033c63636f7ea4cf7b7c1f1bf06d0cc03cfb42e711de5a5c46cf326" +dependencies = [ + "base64 0.13.1", + "nom 7.1.3", + "serde", + "unicode-segmentation", +] + [[package]] name = "sponge-cursor" version = "0.1.0" @@ -8084,6 +8526,12 @@ version = "1.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" +[[package]] +name = "static_assertions" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" + [[package]] name = "strength_reduce" version = "0.2.4" @@ -8302,6 +8750,20 @@ dependencies = [ "syn 3.0.6", ] +[[package]] +name = "sysctl" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "01198a2debb237c62b6826ec7081082d951f46dbb64b0e8c7649a452230d1dfc" +dependencies = [ + "bitflags 2.13.2", + "byteorder", + "enum-as-inner", + "libc", + "thiserror 1.0.69", + "walkdir", +] + [[package]] name = "sysinfo" version = "0.39.6" @@ -10272,7 +10734,7 @@ dependencies = [ name = "tfm-regex" version = "0.1.0" dependencies = [ - "fancy-regex", + "fancy-regex 0.19.2", "serde", "serde_json", "tf-plugin-api", @@ -10767,6 +11229,18 @@ dependencies = [ "tf-plugin-guest", ] +[[package]] +name = "tfp-ai-writer" +version = "0.1.0" +dependencies = [ + "candle-core", + "candle-transformers", + "fancy-regex 0.19.2", + "serde", + "serde_json", + "tf-plugin-api", +] + [[package]] name = "tfp-archive" version = "0.1.0" @@ -11252,6 +11726,39 @@ version = "1.13.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee" +[[package]] +name = "tokenizers" +version = "0.23.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7afbf6e88718afcc138bad01d6ccc3051dbbc3b2ce9793d8b8a3aeb610969cfc" +dependencies = [ + "ahash", + "compact_str", + "daachorse", + "dary_heap", + "derive_builder", + "esaxx-rs", + "fancy-regex 0.17.0", + "getrandom 0.3.4", + "itertools 0.14.0", + "log", + "macro_rules_attribute", + "monostate", + "paste", + "rand 0.9.5", + "rayon", + "rayon-cond", + "regex", + "regex-syntax", + "serde", + "serde_json", + "spm_precompiled", + "thiserror 2.0.20", + "unicode-normalization-alignments", + "unicode-segmentation", + "unicode_categories", +] + [[package]] name = "tokio" version = "1.53.1" @@ -11448,6 +11955,7 @@ dependencies = [ "tf-package", "tf-plugin-api", "tf-wasm", + "tfp-ai-writer", "tfp-archive", "tfp-background-remover", "tfp-barcode", @@ -11720,7 +12228,7 @@ dependencies = [ "getrandom 0.4.3", "log", "rand 0.10.3", - "rand_distr", + "rand_distr 0.6.0", "rustfft", "tract-extra", "tract-nnef", @@ -11861,6 +12369,12 @@ checksum = "6af6ae20167a9ece4bcb41af5b80f8a1f1df981f6391189ce00fd257af04126a" name = "typed-path" version = "0.12.3" +[[package]] +name = "typed-path" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ce898823d8cd0f028662d2f349694b1af0a5cc9be83f1d213a00d3147445e1e" + [[package]] name = "typeid" version = "1.0.3" @@ -11995,6 +12509,15 @@ dependencies = [ "tinyvec", ] +[[package]] +name = "unicode-normalization-alignments" +version = "0.1.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "43f613e4fa046e69818dd287fdc4bc78175ff20331479dab6e1b0f98d57062de" +dependencies = [ + "smallvec", +] + [[package]] name = "unicode-properties" version = "0.1.4" @@ -14040,7 +14563,7 @@ checksum = "2d04a6b5381502aa6087c94c669499eb1602eb9c5e8198e534de571f7154809b" dependencies = [ "aes 0.9.3", "bzip2", - "constant_time_eq", + "constant_time_eq 0.4.2", "crc32fast", "deflate64", "flate2", @@ -14051,11 +14574,29 @@ dependencies = [ "memchr", "pbkdf2 0.13.0", "sha1 0.11.0", - "typed-path", + "typed-path 0.12.3", "zeroize", "zopfli", ] +[[package]] +name = "zip" +version = "9.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "07db37dec4a7c468df4723fba4cadb4822d1d0f10dbea367100b6a6881b2a9c9" +dependencies = [ + "constant_time_eq 0.6.2", + "crc32fast", + "getrandom 0.4.3", + "indexmap 2.14.2", + "libc", + "memchr", + "nix", + "typed-path 0.13.0", + "windows-sys 0.61.2", + "zeroize", +] + [[package]] name = "zlib-rs" version = "0.6.8" diff --git a/Cargo.toml b/Cargo.toml index cdfabd88..588fc1d7 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -36,6 +36,7 @@ tf-plugin-api = { path = "crates/tf-plugin-api" } tf-net = { path = "crates/tf-net" } tf-package = { path = "crates/tf-package" } tf-wasm = { path = "crates/tf-wasm" } +tfp-ai-writer = { path = "plugins/ai-writer/backend" } tfp-archive = { path = "plugins/archive/backend" } tfp-background-remover = { path = "plugins/background-remover/backend" } tfp-barcode = { path = "plugins/barcode/backend" } @@ -88,6 +89,21 @@ opt-level = 3 opt-level = 3 [profile.dev.package.tract-onnx-opl] opt-level = 3 +# 本地语言模型推理(candle 与 gemm) +[profile.dev.package.candle-core] +opt-level = 3 +[profile.dev.package.candle-nn] +opt-level = 3 +[profile.dev.package.candle-transformers] +opt-level = 3 +[profile.dev.package.gemm] +opt-level = 3 +[profile.dev.package.gemm-common] +opt-level = 3 +[profile.dev.package.gemm-f32] +opt-level = 3 +[profile.dev.package.gemm-f16] +opt-level = 3 [profile.dev.package.image] opt-level = 3 [profile.dev.package.png] @@ -117,6 +133,21 @@ opt-level = 3 opt-level = 3 [profile.release.package.tract-onnx-opl] opt-level = 3 +# 本地语言模型推理(candle 与 gemm) +[profile.release.package.candle-core] +opt-level = 3 +[profile.release.package.candle-nn] +opt-level = 3 +[profile.release.package.candle-transformers] +opt-level = 3 +[profile.release.package.gemm] +opt-level = 3 +[profile.release.package.gemm-common] +opt-level = 3 +[profile.release.package.gemm-f32] +opt-level = 3 +[profile.release.package.gemm-f16] +opt-level = 3 [profile.release.package.image] opt-level = 3 [profile.release.package.png] diff --git a/README.md b/README.md index 65265d8d..6b92d4db 100644 --- a/README.md +++ b/README.md @@ -50,6 +50,7 @@ and the modern interface supports light / dark themes, Chinese and English, and | **Barcode** | Generate EAN-13, EAN-8, UPC-A, ITF-14, Code 128, Code 39, Code 93, Codabar, Data Matrix, PDF417 and Aztec codes; retail check digits are added or verified automatically, EAN/UPC are drawn with guard bars and grouped digits; save as SVG or PNG, and read every barcode in an image or a clipboard screenshot | | **Background Remover** | Remove image backgrounds with a local AI model (U²-Net lite or IS-Net) running in Rust; models download on first use with resume and SHA-256 verification; transparent PNG or a solid color | | **OCR** | Extract Chinese and English text from images, screenshots and PDFs with PaddleOCR PP-OCRv4 models running in Rust (about 15 MB, downloaded on first use); paste screenshots with ⌘V, see recognized boxes and copy lines; PDFs are rendered and recognized page by page (up to 200 pages) | +| **AI Writing Assistant** | Polish, proofread, rewrite, shorten, expand, summarize, translate or apply your own instruction with Qwen2.5 Instruct (0.5B or 1.5B, GGUF) running locally in Rust; models download on first use with resume and SHA-256 verification, output streams as it is written, and text never leaves your computer | | **WebSocket Client** | Connect to ws:// and wss:// servers with custom headers and subprotocols, watch every received and sent frame live, format JSON, and send text, hex / base64 binary or pings with saved snippets | | **DNS Lookup** | A / AAAA / CNAME / MX / TXT / NS / SOA / SRV / CAA / PTR records from the system resolver or public DNS, compared side by side with timings; flags proxy fake IPs | | **Port Manager** | See which process listens on each TCP / UDP port (with user, memory and command line), search, stop the process, and check remote ports in parallel with latency and failure reasons | diff --git a/README.zh-CN.md b/README.zh-CN.md index 89ca5ffb..d33e2ccb 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -50,6 +50,7 @@ | **条形码** | 生成 EAN-13、EAN-8、UPC-A、ITF-14、Code 128、Code 39、Code 93、Codabar 以及 Data Matrix、PDF417、Aztec,商品码自动补全或核对校验位,EAN/UPC 按标准绘制护线与分组数字;保存为 SVG 或 PNG,可识别图片或剪贴板截图中的所有条码 | | **去除背景** | 使用本地 AI 模型(U²-Net 轻量版或 IS-Net)在 Rust 中抠图;模型首次使用时下载,支持续传与 SHA-256 校验;输出透明 PNG 或纯色背景 | | **文字识别** | 使用 PaddleOCR PP-OCRv4 模型在 Rust 中离线识别图片、截图与 PDF 中的中英文文字(首次使用下载约 15 MB 模型);支持 ⌘V 粘贴截图,显示文字框并可点击复制单行;PDF 逐页渲染识别(最多 200 页) | +| **AI 写作助手** | 在 Rust 中本地运行 Qwen2.5 Instruct(0.5B 或 1.5B,GGUF 量化)润色、纠错、改写、精简、扩写、摘要、翻译或按自定义指令处理文本;模型首次使用时下载,支持续传与 SHA-256 校验,结果边生成边显示,文本不离开本机 | | **WebSocket 客户端** | 连接 ws:// 与 wss:// 服务,可设置请求头与子协议,实时查看收发的每一帧并格式化 JSON,发送文本、十六进制 / Base64 二进制或 Ping,支持保存常用片段 | | **DNS 查询** | 通过系统解析器或公共 DNS 查询 A / AAAA / CNAME / MX / TXT / NS / SOA / SRV / CAA / PTR 记录,并排对比结果与耗时;识别代理的 fake-ip | | **端口管理** | 查看每个 TCP / UDP 端口被哪个进程占用(含用户、内存与命令行),支持搜索与结束进程;并行检查远程端口是否可达并显示延迟与失败原因 | diff --git a/apps/desktop/src-tauri/Cargo.toml b/apps/desktop/src-tauri/Cargo.toml index fd9c37dd..9e22b8e3 100644 --- a/apps/desktop/src-tauri/Cargo.toml +++ b/apps/desktop/src-tauri/Cargo.toml @@ -37,6 +37,7 @@ httpdate = "1" tf-wasm.workspace = true tf-plugin-api.workspace = true tfp-archive.workspace = true +tfp-ai-writer.workspace = true tfp-background-remover.workspace = true tfp-barcode.workspace = true tfp-batch-rename.workspace = true diff --git a/apps/desktop/src-tauri/src/plugins.rs b/apps/desktop/src-tauri/src/plugins.rs index 16b4c0b3..8737545c 100644 --- a/apps/desktop/src-tauri/src/plugins.rs +++ b/apps/desktop/src-tauri/src/plugins.rs @@ -47,6 +47,7 @@ pub fn builtin_for(os: &str) -> PluginRegistry { registry.register_for(Arc::new(tfp_doc_converter::DocConverter::default()), os); registry.register_for(Arc::new(tfp_context_menu::ContextMenu::default()), os); registry.register_for(Arc::new(tfp_input_stats::InputStats::default()), os); + registry.register_for(Arc::new(tfp_ai_writer::AiWriter::default()), os); registry } diff --git a/plugins/ai-writer/backend/Cargo.toml b/plugins/ai-writer/backend/Cargo.toml new file mode 100644 index 00000000..de2aff90 --- /dev/null +++ b/plugins/ai-writer/backend/Cargo.toml @@ -0,0 +1,15 @@ +[package] +name = "tfp-ai-writer" +description = "ToolForge plugin: offline writing assistant running small language models locally" +version = "0.1.0" +edition.workspace = true +license.workspace = true +authors.workspace = true + +[dependencies] +serde.workspace = true +serde_json.workspace = true +tf-plugin-api.workspace = true +candle-core = "0.11" +candle-transformers = "0.11" +fancy-regex = "0.19" diff --git a/plugins/ai-writer/backend/src/engine.rs b/plugins/ai-writer/backend/src/engine.rs new file mode 100644 index 00000000..4bb9f16d --- /dev/null +++ b/plugins/ai-writer/backend/src/engine.rs @@ -0,0 +1,273 @@ +//! 本地推理:candle 在 CPU 上运行量化的 Qwen2.5 Instruct(GGUF)。模型加载一次后常驻, +//! 闲置一段时间后自动释放内存;同一时间只运行一个生成任务,其余排队等待。 + +use std::fs::File; +use std::io::BufReader; +use std::path::Path; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::{Arc, Mutex, OnceLock}; +use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; + +use candle_core::quantized::gguf_file; +use candle_core::{Device, Tensor}; +use candle_transformers::generation::{LogitsProcessor, Sampling}; +use candle_transformers::models::quantized_qwen2::ModelWeights; +use candle_transformers::utils::apply_repeat_penalty; +use tf_plugin_api::{PluginError, PluginResult, cancelled}; + +use crate::prompt::Prompt; +use crate::tokenizer::{StreamDecoder, Tokenizer}; + +/// 提示词的最大长度(编号数);超出时提示分段处理 +pub const MAX_PROMPT_TOKENS: usize = 6144; +/// 预填充分块:每块之间检查取消 +const PREFILL_CHUNK: usize = 256; +/// 闲置多久后释放模型 +const IDLE_UNLOAD: Duration = Duration::from_secs(5 * 60); +const REPEAT_PENALTY: f32 = 1.1; +const REPEAT_WINDOW: usize = 64; + +fn failed(err: impl std::fmt::Display) -> PluginError { + PluginError::new("ai.inference_failed").with("detail", err.to_string()) +} + +fn invalid(err: impl std::fmt::Display) -> PluginError { + PluginError::new("ai.model_invalid").with("detail", err.to_string()) +} + +struct Loaded { + id: String, + model: ModelWeights, + tokenizer: Tokenizer, + im_start: u32, + im_end: u32, + end_of_text: u32, +} + +fn strings(content: &gguf_file::Content, key: &str) -> PluginResult> { + let value = content + .metadata + .get(key) + .ok_or_else(|| invalid(format!("missing {key}")))?; + value + .to_vec() + .map_err(invalid)? + .iter() + .map(|v| v.to_string().map(|s| s.to_owned()).map_err(invalid)) + .collect() +} + +fn load(id: &str, path: &Path) -> PluginResult { + let mut reader = BufReader::new( + File::open(path) + .map_err(|e| PluginError::new("ai.model_invalid").with("detail", e.to_string()))?, + ); + let content = gguf_file::Content::read(&mut reader).map_err(invalid)?; + let tokens = strings(&content, "tokenizer.ggml.tokens")?; + let merges = strings(&content, "tokenizer.ggml.merges")?; + // token_type 3 为控制符 + let control = match content.metadata.get("tokenizer.ggml.token_type") { + Some(types) => types + .to_vec() + .map_err(invalid)? + .iter() + .map(|t| t.to_i32().is_ok_and(|t| t == 3)) + .collect(), + None => Vec::new(), + }; + let tokenizer = Tokenizer::new(tokens, control, &merges)?; + let model = ModelWeights::from_gguf(content, &mut reader, &Device::Cpu).map_err(invalid)?; + Ok(Loaded { + id: id.to_owned(), + im_start: tokenizer.special("<|im_start|>")?, + im_end: tokenizer.special("<|im_end|>")?, + end_of_text: tokenizer.special("<|endoftext|>")?, + tokenizer, + model, + }) +} + +/// Qwen 的对话模板:system、user 两段,之后由模型续写 assistant +fn chat(loaded: &Loaded, prompt: &Prompt) -> Vec { + let t = &loaded.tokenizer; + let mut ids = Vec::new(); + let mut turn = |role: &str, text: Option<&str>| { + ids.push(loaded.im_start); + ids.extend(t.encode(&format!("{role}\n"))); + if let Some(text) = text { + ids.extend(t.encode(text)); + ids.push(loaded.im_end); + ids.extend(t.encode("\n")); + } + }; + turn("system", Some(&prompt.system)); + turn("user", Some(&prompt.user)); + turn("assistant", None); + ids +} + +/// 生成过程中的回调 +pub trait Observer { + fn cancelled(&self) -> bool; + /// 模型加载完成(是否新加载、用时) + fn loaded(&self, fresh: bool, elapsed: Duration); + /// 预填充进度 + fn reading(&self, done: usize, total: usize); + /// 已生成的文本 + fn partial(&self, generated: usize, max: usize, text: &str); +} + +pub struct Generation { + pub text: String, + pub prompt_tokens: usize, + pub tokens: usize, + pub elapsed_ms: u64, + /// 是否因达到长度上限而截断 + pub truncated: bool, +} + +fn now_secs() -> u64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .map_or(0, |d| d.as_secs()) +} + +#[derive(Default)] +pub struct Engine { + slot: Arc>>, + last_used: Arc, + janitor: OnceLock<()>, +} + +impl Engine { + /// 后台线程定期检查:闲置超过 IDLE_UNLOAD 且没有任务在用时释放模型 + fn start_janitor(&self) { + let slot = Arc::downgrade(&self.slot); + let last_used = self.last_used.clone(); + self.janitor.get_or_init(|| { + std::thread::Builder::new() + .name("ai-writer-idle".into()) + .spawn(move || { + while let Some(slot) = slot.upgrade() { + std::thread::sleep(Duration::from_secs(30)); + let idle = now_secs().saturating_sub(last_used.load(Ordering::Relaxed)); + if idle >= IDLE_UNLOAD.as_secs() + && let Ok(mut guard) = slot.try_lock() + { + *guard = None; + } + } + }) + .ok(); + }); + } + + pub fn generate( + &self, + model_id: &str, + model_path: &Path, + prompt: &Prompt, + max_new: impl Fn(usize) -> usize, + observer: &dyn Observer, + ) -> PluginResult { + self.start_janitor(); + let mut guard = self.slot.lock().unwrap_or_else(|e| e.into_inner()); + if observer.cancelled() { + return Err(cancelled()); + } + let started = Instant::now(); + let fresh = guard.as_ref().is_none_or(|l| l.id != model_id); + if fresh { + *guard = None; + *guard = Some(load(model_id, model_path)?); + } + observer.loaded(fresh, started.elapsed()); + let result = run( + guard.as_mut().expect("model loaded"), + prompt, + &max_new, + observer, + ); + self.last_used.store(now_secs(), Ordering::Relaxed); + if let Some(loaded) = guard.as_mut() { + loaded.model.clear_kv_cache(); + } + result.map(|mut g| { + g.elapsed_ms = started.elapsed().as_millis() as u64; + g + }) + } +} + +fn run( + loaded: &mut Loaded, + prompt: &Prompt, + max_new: &dyn Fn(usize) -> usize, + observer: &dyn Observer, +) -> PluginResult { + let input = chat(loaded, prompt); + if input.len() > MAX_PROMPT_TOKENS { + return Err(PluginError::new("ai.too_long_tokens").with("max", MAX_PROMPT_TOKENS)); + } + // 输入文本的编号数(去掉模板开销)决定生成上限 + let user_tokens = loaded.tokenizer.encode(&prompt.user).len(); + let max_new = max_new(user_tokens); + loaded.model.clear_kv_cache(); + + let mut logits = None; + for (index, chunk) in input.chunks(PREFILL_CHUNK).enumerate() { + if observer.cancelled() { + return Err(cancelled()); + } + let position = index * PREFILL_CHUNK; + let tensor = Tensor::new(chunk, &Device::Cpu) + .and_then(|t| t.unsqueeze(0)) + .map_err(failed)?; + logits = Some(loaded.model.forward(&tensor, position).map_err(failed)?); + observer.reading((position + chunk.len()).min(input.len()), input.len()); + } + let mut logits = logits.ok_or_else(|| failed("empty prompt"))?; + + // 低温采样:结果稳定,又不至于原样复读 + let mut sampler = LogitsProcessor::from_sampling( + 42, + Sampling::TopP { + p: 0.9, + temperature: 0.3, + }, + ); + let mut generated: Vec = Vec::new(); + let mut decoder = StreamDecoder::default(); + let mut truncated = true; + for step in 0..max_new { + if observer.cancelled() { + return Err(cancelled()); + } + let squeezed = logits.squeeze(0).map_err(failed)?; + let start = generated.len().saturating_sub(REPEAT_WINDOW); + let penalized = + apply_repeat_penalty(&squeezed, REPEAT_PENALTY, &generated[start..]).map_err(failed)?; + let next = sampler.sample(&penalized).map_err(failed)?; + if next == loaded.im_end || next == loaded.end_of_text { + truncated = false; + break; + } + generated.push(next); + decoder.push(&loaded.tokenizer.bytes(next)); + observer.partial(step + 1, max_new, &decoder.text); + let tensor = Tensor::new(&[next], &Device::Cpu) + .and_then(|t| t.unsqueeze(0)) + .map_err(failed)?; + logits = loaded + .model + .forward(&tensor, input.len() + step) + .map_err(failed)?; + } + Ok(Generation { + text: decoder.finish(), + prompt_tokens: input.len(), + tokens: generated.len(), + elapsed_ms: 0, + truncated, + }) +} diff --git a/plugins/ai-writer/backend/src/lib.rs b/plugins/ai-writer/backend/src/lib.rs new file mode 100644 index 00000000..5dfcbf8c --- /dev/null +++ b/plugins/ai-writer/backend/src/lib.rs @@ -0,0 +1,175 @@ +//! AI 写作助手:在本机运行小型语言模型(Qwen2.5 Instruct,GGUF 量化),提供润色、纠错、改写、 +//! 精简、扩写、摘要、翻译与自定义指令。模型作为资源按需下载,资源列表就是模型管理器; +//! 文本不离开本机。其他工具(如 Markdown 编辑器)以任务方式调用 `generate`。 + +mod engine; +mod prompt; +mod tokenizer; + +use std::cell::Cell; +use std::time::{Duration, Instant}; + +use serde::Serialize; +use serde_json::{Value, json}; +use tf_plugin_api::{ + LogLevel, Manifest, PluginError, PluginResult, TaskContext, ToolPlugin, parse_args, to_value, + unknown_function, +}; + +const MANIFEST: &str = include_str!("../../manifest.json"); + +/// 模型资源 id,按质量从高到低:没有指定模型时用已下载的第一个 +pub const MODELS: [&str; 2] = ["qwen2.5-1.5b-instruct", "qwen2.5-0.5b-instruct"]; + +/// 生成中的文本最多每隔这么久推送一次 +const PARTIAL_INTERVAL: Duration = Duration::from_millis(250); + +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct Output { + pub text: String, + pub model: String, + pub prompt_tokens: usize, + pub tokens: usize, + pub elapsed_ms: u64, + pub truncated: bool, +} + +pub struct AiWriter { + manifest: Manifest, + engine: engine::Engine, +} + +impl Default for AiWriter { + fn default() -> Self { + Self { + manifest: Manifest::from_static(MANIFEST), + engine: engine::Engine::default(), + } + } +} + +/// 选择模型:指定了就必须已下载;否则用已下载的最好的一个 +fn pick_model( + requested: Option<&str>, + ctx: &dyn TaskContext, +) -> PluginResult<(String, std::path::PathBuf)> { + if let Some(id) = requested.filter(|id| !id.is_empty()) { + if !MODELS.contains(&id) { + return Err(PluginError::new("ai.unknown_model").with("id", id)); + } + let path = ctx + .resource_path(id) + .map_err(|_| PluginError::new("ai.no_model"))?; + return Ok((id.to_owned(), path)); + } + MODELS + .iter() + .find_map(|id| { + ctx.resource_path(id) + .ok() + .map(|path| ((*id).to_owned(), path)) + }) + .ok_or_else(|| PluginError::new("ai.no_model")) +} + +struct TaskObserver<'a> { + ctx: &'a dyn TaskContext, + last_partial: Cell>, + writing: Cell, +} + +impl engine::Observer for TaskObserver<'_> { + fn cancelled(&self) -> bool { + self.ctx.is_cancelled() + } + + fn loaded(&self, fresh: bool, elapsed: Duration) { + if fresh { + self.ctx.log( + LogLevel::Info, + "ai.model_loaded", + json!({ "ms": elapsed.as_millis() as u64 }), + ); + } + self.ctx.stage("ai.read"); + } + + fn reading(&self, done: usize, total: usize) { + self.ctx.progress(done as u64, total as u64); + } + + fn partial(&self, generated: usize, max: usize, text: &str) { + if !self.writing.replace(true) { + self.ctx.stage("ai.write"); + } + self.ctx.progress(generated as u64, max as u64); + let due = self + .last_partial + .get() + .is_none_or(|at| at.elapsed() >= PARTIAL_INTERVAL); + if due { + self.last_partial.set(Some(Instant::now())); + self.ctx + .log(LogLevel::Debug, "ai.partial", json!({ "text": text })); + } + } +} + +fn generate(engine: &engine::Engine, args: Value, ctx: &dyn TaskContext) -> PluginResult { + let request: prompt::Request = parse_args(args)?; + let built = prompt::build(&request)?; + let (model, path) = pick_model(request.model.as_deref(), ctx)?; + ctx.stage("ai.load"); + let observer = TaskObserver { + ctx, + last_partial: Cell::new(None), + writing: Cell::new(false), + }; + let action = request.action; + let generation = engine.generate( + &model, + &path, + &built, + |input| prompt::max_new_tokens(action, input), + &observer, + )?; + let text = prompt::clean(&generation.text, &request.text); + ctx.log( + LogLevel::Info, + "ai.done", + json!({ "tokens": generation.tokens, "ms": generation.elapsed_ms, "model": model }), + ); + if text.is_empty() { + return Err(PluginError::new("ai.empty_output")); + } + Ok(Output { + text, + model, + prompt_tokens: generation.prompt_tokens, + tokens: generation.tokens, + elapsed_ms: generation.elapsed_ms, + truncated: generation.truncated, + }) +} + +impl ToolPlugin for AiWriter { + fn manifest(&self) -> &Manifest { + &self.manifest + } + + fn call(&self, function: &str, _args: Value) -> PluginResult { + Err(unknown_function(function)) + } + + fn run_task(&self, function: &str, args: Value, ctx: &dyn TaskContext) -> PluginResult { + match function { + "generate" => to_value(generate(&self.engine, args, ctx)?), + _ => self.call(function, args), + } + } +} + +#[cfg(test)] +#[path = "lib_test.rs"] +mod tests; diff --git a/plugins/ai-writer/backend/src/lib_test.rs b/plugins/ai-writer/backend/src/lib_test.rs new file mode 100644 index 00000000..a51ca9ee --- /dev/null +++ b/plugins/ai-writer/backend/src/lib_test.rs @@ -0,0 +1,159 @@ +use std::collections::HashMap; +use std::path::PathBuf; +use std::sync::Mutex; + +use super::*; +use serde_json::json; + +#[derive(Default)] +struct Ctx { + resources: HashMap, + logs: Mutex>, + stages: Mutex>, +} + +impl TaskContext for Ctx { + fn log(&self, _level: LogLevel, code: &str, params: Value) { + self.logs.lock().unwrap().push((code.to_owned(), params)); + } + fn progress(&self, _done: u64, _total: u64) {} + fn stage(&self, code: &str) { + self.stages.lock().unwrap().push(code.to_owned()); + } + fn is_cancelled(&self) -> bool { + false + } + fn open_file(&self, _path: &str) -> PluginResult> { + unreachable!() + } + fn file_size(&self, _path: &str) -> PluginResult { + unreachable!() + } + fn resource_path(&self, id: &str) -> PluginResult { + self.resources + .get(id) + .cloned() + .ok_or_else(|| PluginError::new("resource.missing").with("id", id)) + } +} + +fn with(ids: &[&str]) -> Ctx { + Ctx { + resources: ids + .iter() + .map(|id| (id.to_string(), PathBuf::from(format!("/models/{id}")))) + .collect(), + ..Ctx::default() + } +} + +#[test] +fn manifest_declares_the_models_in_quality_order() { + let tool = AiWriter::default(); + assert!(tool.manifest().functions["generate"].task); + let ids: Vec<&str> = tool + .manifest() + .resources + .iter() + .map(|r| r.id.as_str()) + .collect(); + for model in MODELS { + assert!(ids.contains(&model), "{model}"); + } + assert_eq!( + tool.call("generate", json!({})).unwrap_err().code, + "plugin.function_not_found" + ); +} + +#[test] +fn picks_the_best_downloaded_model_unless_one_is_requested() { + assert_eq!( + pick_model(None, &with(&[])).unwrap_err().code, + "ai.no_model" + ); + assert_eq!( + pick_model(None, &with(&["qwen2.5-0.5b-instruct"])) + .unwrap() + .0, + "qwen2.5-0.5b-instruct" + ); + let both = with(&MODELS); + assert_eq!(pick_model(None, &both).unwrap().0, "qwen2.5-1.5b-instruct"); + assert_eq!( + pick_model(Some("qwen2.5-0.5b-instruct"), &both).unwrap().0, + "qwen2.5-0.5b-instruct" + ); + assert_eq!( + pick_model( + Some("qwen2.5-1.5b-instruct"), + &with(&["qwen2.5-0.5b-instruct"]) + ) + .unwrap_err() + .code, + "ai.no_model" + ); + assert_eq!( + pick_model(Some("gpt"), &both).unwrap_err().code, + "ai.unknown_model" + ); +} + +#[test] +fn validates_requests_before_loading_a_model() { + let tool = AiWriter::default(); + let ctx = with(&[]); + let error = tool + .run_task("generate", json!({ "action": "polish", "text": "" }), &ctx) + .unwrap_err(); + assert_eq!(error.code, "ai.empty"); + let error = tool + .run_task( + "generate", + json!({ "action": "polish", "text": "hi" }), + &ctx, + ) + .unwrap_err(); + assert_eq!(error.code, "ai.no_model"); + assert!( + tool.run_task("generate", json!({ "action": "dance", "text": "hi" }), &ctx) + .is_err() + ); +} + +/// 用真实模型跑一遍:`TF_AI_MODEL=/path/to/qwen2.5-0.5b-instruct-q4_k_m.gguf cargo test -p tfp-ai-writer -- --ignored` +#[test] +#[ignore = "needs a downloaded model"] +fn generates_with_a_real_model() { + let path = PathBuf::from(std::env::var("TF_AI_MODEL").expect("TF_AI_MODEL")); + let ctx = Ctx { + resources: HashMap::from([("qwen2.5-0.5b-instruct".to_owned(), path)]), + ..Ctx::default() + }; + let tool = AiWriter::default(); + for (args, check) in [ + ( + json!({ "action": "translate", "text": "今天天气很好,我们去公园散步吧。", "language": "English" }), + "park", + ), + ( + json!({ "action": "proofread", "text": "I has a apple and she have two.", "markdown": true }), + "have", + ), + ] { + let output: Value = tool.run_task("generate", args, &ctx).unwrap(); + let text = output["text"].as_str().unwrap(); + eprintln!("{output}"); + assert!(text.to_lowercase().contains(check), "{text}"); + } + let stages = ctx.stages.lock().unwrap(); + assert_eq!(stages.first().map(String::as_str), Some("ai.load")); + assert!(stages.contains(&"ai.write".to_owned())); + assert!( + ctx.logs + .lock() + .unwrap() + .iter() + .any(|(code, _)| code == "ai.partial") + ); +} diff --git a/plugins/ai-writer/backend/src/prompt.rs b/plugins/ai-writer/backend/src/prompt.rs new file mode 100644 index 00000000..c0c2149d --- /dev/null +++ b/plugins/ai-writer/backend/src/prompt.rs @@ -0,0 +1,137 @@ +//! 写作动作 → 对话提示词。模型只输出结果文本;Markdown 文本保留格式、链接、代码与公式。 + +use serde::Deserialize; +use tf_plugin_api::{PluginError, PluginResult}; + +/// 单次输入的最大字符数;更长的文本请分段处理 +pub const MAX_INPUT_CHARS: usize = 12_000; +/// 自定义指令的最大字符数 +pub const MAX_INSTRUCTION_CHARS: usize = 500; + +#[derive(Debug, Clone, Copy, Deserialize, PartialEq, Eq)] +#[serde(rename_all = "camelCase")] +pub enum Action { + /// 润色:更通顺、更自然,意思不变 + Polish, + /// 纠错:只改错别字、语法与标点 + Proofread, + /// 改写:换一种说法 + Rewrite, + /// 精简 + Shorten, + /// 扩写 + Expand, + /// 摘要 + Summarize, + /// 翻译到目标语言 + Translate, + /// 按自定义指令处理 + Custom, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Request { + pub action: Action, + pub text: String, + /// 翻译的目标语言,如「English」「简体中文」 + #[serde(default)] + pub language: Option, + /// 自定义动作的指令 + #[serde(default)] + pub instruction: Option, + /// 文本是 Markdown,要保留格式 + #[serde(default)] + pub markdown: bool, + /// 使用的模型(资源 id);不填时用已下载的最大模型 + #[serde(default)] + pub model: Option, +} + +#[derive(Debug)] +pub struct Prompt { + pub system: String, + pub user: String, +} + +fn task(request: &Request) -> PluginResult { + Ok(match request.action { + Action::Polish => "Polish the text below: make it clearer, smoother and more natural while keeping its meaning, tone and language.".to_owned(), + Action::Proofread => "Proofread the text below: fix only typos, grammar and punctuation. Do not rephrase sentences that are already correct.".to_owned(), + Action::Rewrite => "Rewrite the text below in different words, keeping its meaning and language.".to_owned(), + Action::Shorten => "Make the text below shorter and more concise, keeping the key points and its language.".to_owned(), + Action::Expand => "Expand the text below with more detail and explanation, keeping its meaning, tone and language.".to_owned(), + Action::Summarize => "Summarize the text below in a few sentences, in the same language as the text.".to_owned(), + Action::Translate => { + let language = request.language.as_deref().map(str::trim).filter(|s| !s.is_empty()).ok_or_else(|| PluginError::new("ai.no_language"))?; + format!("Translate the text below into {language}. Translate faithfully and naturally.") + } + Action::Custom => { + let instruction = request.instruction.as_deref().map(str::trim).filter(|s| !s.is_empty()).ok_or_else(|| PluginError::new("ai.no_instruction"))?; + if instruction.chars().count() > MAX_INSTRUCTION_CHARS { + return Err(PluginError::new("ai.instruction_too_long").with("max", MAX_INSTRUCTION_CHARS)); + } + format!("Apply this instruction to the text below: {instruction}") + } + }) +} + +pub fn build(request: &Request) -> PluginResult { + let text = request.text.trim(); + if text.is_empty() { + return Err(PluginError::new("ai.empty")); + } + if text.chars().count() > MAX_INPUT_CHARS { + return Err(PluginError::new("ai.too_long").with("max", MAX_INPUT_CHARS)); + } + let mut system = String::from( + "You are a careful writing assistant. Reply with the resulting text only: no explanations, no preamble, no notes, no surrounding quotes.", + ); + if request.markdown { + system.push_str(" The text is Markdown: keep its structure, headings, lists, links, images, code and math unchanged unless the task requires otherwise."); + } + Ok(Prompt { + system, + user: format!("{}\n\n{text}", task(request)?), + }) +} + +/// 生成长度上限:摘要较短,扩写较长,其余与原文相当 +pub fn max_new_tokens(action: Action, input_tokens: usize) -> usize { + match action { + Action::Summarize => 512, + Action::Expand => (input_tokens * 3 + 128).clamp(128, 3072), + Action::Shorten => (input_tokens + 64).clamp(64, 2048), + _ => (input_tokens * 2 + 64).clamp(64, 3072), + } +} + +/// 去掉模型偶尔加上的整体代码块围栏与成对引号 +pub fn clean(output: &str, input: &str) -> String { + let mut text = output.trim(); + if !input.trim_start().starts_with("```") + && let Some(rest) = text.strip_prefix("```") + && let Some(inner) = rest.strip_suffix("```") + { + // 围栏后第一行是语言标记(可能为空) + text = inner + .split_once('\n') + .map_or(inner, |(_, body)| body) + .trim(); + } + for (open, close) in [('"', '"'), ('“', '”'), ('「', '」')] { + let input = input.trim(); + if text.starts_with(open) + && text.ends_with(close) + && text.chars().count() > 1 + && !(input.starts_with(open) && input.ends_with(close)) + { + text = text[open.len_utf8()..text.len() - close.len_utf8()].trim(); + } + } + text.to_owned() +} + +#[cfg(test)] +#[path = "prompt_test.rs"] +mod tests; diff --git a/plugins/ai-writer/backend/src/prompt_test.rs b/plugins/ai-writer/backend/src/prompt_test.rs new file mode 100644 index 00000000..d30c6175 --- /dev/null +++ b/plugins/ai-writer/backend/src/prompt_test.rs @@ -0,0 +1,71 @@ +use super::*; + +fn request(action: Action, text: &str) -> Request { + Request { + action, + text: text.into(), + language: None, + instruction: None, + markdown: false, + model: None, + } +} + +#[test] +fn builds_prompts_for_each_action() { + let prompt = build(&request(Action::Polish, " hello ")).unwrap(); + assert!(prompt.user.starts_with("Polish")); + assert!(prompt.user.ends_with("\n\nhello")); + assert!(!prompt.system.contains("Markdown")); + + let mut translate = request(Action::Translate, "你好"); + assert_eq!(build(&translate).unwrap_err().code, "ai.no_language"); + translate.language = Some("English".into()); + assert!(build(&translate).unwrap().user.contains("into English")); + + let mut custom = request(Action::Custom, "text"); + assert_eq!(build(&custom).unwrap_err().code, "ai.no_instruction"); + custom.instruction = Some("x".repeat(MAX_INSTRUCTION_CHARS + 1)); + assert_eq!(build(&custom).unwrap_err().code, "ai.instruction_too_long"); + custom.instruction = Some("make it formal".into()); + assert!(build(&custom).unwrap().user.contains("make it formal")); + + let mut markdown = request(Action::Proofread, "# Title"); + markdown.markdown = true; + assert!(build(&markdown).unwrap().system.contains("Markdown")); +} + +#[test] +fn rejects_empty_and_oversized_input() { + assert_eq!( + build(&request(Action::Polish, " \n ")).unwrap_err().code, + "ai.empty" + ); + let long = "字".repeat(MAX_INPUT_CHARS + 1); + let error = build(&request(Action::Polish, &long)).unwrap_err(); + assert_eq!(error.code, "ai.too_long"); + assert_eq!(error.params["max"], MAX_INPUT_CHARS); +} + +#[test] +fn output_budgets_follow_the_action() { + assert_eq!(max_new_tokens(Action::Summarize, 5000), 512); + assert_eq!(max_new_tokens(Action::Polish, 10), 84); + assert_eq!(max_new_tokens(Action::Polish, 5000), 3072); + assert_eq!(max_new_tokens(Action::Expand, 10), 158); + assert_eq!(max_new_tokens(Action::Shorten, 1), 65); +} + +#[test] +fn cleans_wrapping_fences_and_quotes_the_input_did_not_have() { + assert_eq!(clean("```markdown\n# Hi\n```", "# Hi"), "# Hi"); + assert_eq!(clean("```\nplain\n```", "plain"), "plain"); + assert_eq!( + clean("```rust\nfn x() {}\n```", "```rust\nfn x() {}\n```"), + "```rust\nfn x() {}\n```" + ); + assert_eq!(clean("\"Hello\"", "hello"), "Hello"); + assert_eq!(clean("“你好”", "你好"), "你好"); + assert_eq!(clean("\"quoted\"", "\"quoted\""), "\"quoted\""); + assert_eq!(clean(" spaced ", "x"), "spaced"); +} diff --git a/plugins/ai-writer/backend/src/tokenizer.rs b/plugins/ai-writer/backend/src/tokenizer.rs new file mode 100644 index 00000000..6ccaa4db --- /dev/null +++ b/plugins/ai-writer/backend/src/tokenizer.rs @@ -0,0 +1,190 @@ +//! 字节级 BPE 分词器(与 Qwen2 的 tokenizer 一致),词表与合并规则直接取自 GGUF 文件的元数据, +//! 不需要另外下载 tokenizer.json,也不依赖 C 实现的正则库。 +//! +//! 用户文本只按普通文本编码:其中的 `<|im_start|>` 等特殊标记不会被当成控制符, +//! 控制符只能由 [`Tokenizer::special`] 按名称取得后插入。 + +use std::collections::HashMap; + +use fancy_regex::Regex; +use tf_plugin_api::{PluginError, PluginResult}; + +/// Qwen2 的预分词规则:英文缩写、字母串、单个数字、标点串、换行与空白 +const PRE_TOKENIZE: &str = r"(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\r\n\p{L}\p{N}]?\p{L}+|\p{N}| ?[^\s\p{L}\p{N}]+[\r\n]*|\s*[\r\n]+|\s+(?!\S)|\s+"; + +/// GPT-2 的字节到可见字符映射:可打印字节保持原样,其余映射到 256 起的码位 +fn byte_chars() -> [char; 256] { + let mut table = ['\0'; 256]; + let mut next = 256u32; + for byte in 0..=255u8 { + let printable = matches!(byte, b'!'..=b'~' | 0xA1..=0xAC | 0xAE..=0xFF); + table[byte as usize] = if printable { + byte as char + } else { + let c = char::from_u32(next).unwrap_or('\0'); + next += 1; + c + }; + } + table +} + +pub struct Tokenizer { + vocab: HashMap, + tokens: Vec, + /// 控制符(如 `<|im_end|>`):解码时跳过 + control: Vec, + ranks: HashMap<(String, String), usize>, + to_char: [char; 256], + to_byte: HashMap, + pre: Regex, +} + +fn invalid(detail: impl ToString) -> PluginError { + PluginError::new("ai.model_invalid").with("detail", detail.to_string()) +} + +impl Tokenizer { + /// `tokens` 按编号排列;`control` 标出控制符;`merges` 形如 `"a b"`,按优先级排列 + pub fn new(tokens: Vec, control: Vec, merges: &[String]) -> PluginResult { + let vocab = tokens + .iter() + .enumerate() + .map(|(i, t)| (t.clone(), i as u32)) + .collect(); + let ranks = merges + .iter() + .enumerate() + .filter_map(|(rank, merge)| { + let (a, b) = merge.split_once(' ')?; + Some(((a.to_owned(), b.to_owned()), rank)) + }) + .collect(); + let to_char = byte_chars(); + let to_byte = to_char + .iter() + .enumerate() + .map(|(b, c)| (*c, b as u8)) + .collect(); + let mut control = control; + control.resize(tokens.len(), false); + Ok(Self { + vocab, + tokens, + control, + ranks, + to_char, + to_byte, + pre: Regex::new(PRE_TOKENIZE).map_err(invalid)?, + }) + } + + /// 按名称取控制符的编号 + pub fn special(&self, name: &str) -> PluginResult { + self.vocab + .get(name) + .copied() + .ok_or_else(|| invalid(format!("missing token {name}"))) + } + + fn bpe(&self, word: &str, out: &mut Vec) { + if let Some(id) = self.vocab.get(word) { + out.push(*id); + return; + } + let mut parts: Vec = word.chars().map(String::from).collect(); + while parts.len() > 1 { + let best = parts + .windows(2) + .enumerate() + .filter_map(|(i, pair)| { + self.ranks + .get(&(pair[0].clone(), pair[1].clone())) + .map(|rank| (*rank, i)) + }) + .min(); + let Some((_, i)) = best else { break }; + let merged = format!("{}{}", parts[i], parts[i + 1]); + parts.splice(i..=i + 1, [merged]); + } + for part in parts { + match self.vocab.get(&part) { + Some(id) => out.push(*id), + // 字节级词表覆盖全部 256 个字节,正常不会走到这里 + None => out.extend( + part.chars() + .filter_map(|c| self.vocab.get(&c.to_string()).copied()), + ), + } + } + } + + pub fn encode(&self, text: &str) -> Vec { + let mut out = Vec::new(); + for piece in self.pre.find_iter(text) { + let Ok(piece) = piece else { continue }; + let mapped: String = piece + .as_str() + .bytes() + .map(|b| self.to_char[b as usize]) + .collect(); + self.bpe(&mapped, &mut out); + } + out + } + + /// 编号对应的原始字节;控制符与越界编号返回空 + pub fn bytes(&self, id: u32) -> Vec { + let index = id as usize; + if index >= self.tokens.len() || self.control[index] { + return Vec::new(); + } + self.tokens[index] + .chars() + .filter_map(|c| self.to_byte.get(&c).copied()) + .collect() + } + + #[cfg(test)] + pub fn decode(&self, ids: &[u32]) -> String { + let bytes: Vec = ids.iter().flat_map(|id| self.bytes(*id)).collect(); + String::from_utf8_lossy(&bytes).into_owned() + } +} + +/// 逐个编号解码:一个汉字可能跨多个编号,凑齐完整的 UTF-8 字符后才输出 +#[derive(Default)] +pub struct StreamDecoder { + pending: Vec, + pub text: String, +} + +impl StreamDecoder { + pub fn push(&mut self, bytes: &[u8]) { + self.pending.extend_from_slice(bytes); + let valid = match std::str::from_utf8(&self.pending) { + Ok(s) => s.len(), + Err(e) if e.error_len().is_none() => e.valid_up_to(), + // 真正非法的字节:按替换字符输出,不再等待 + Err(_) => { + self.text.push_str(&String::from_utf8_lossy(&self.pending)); + self.pending.clear(); + return; + } + }; + self.text + .push_str(std::str::from_utf8(&self.pending[..valid]).unwrap_or_default()); + self.pending.drain(..valid); + } + + pub fn finish(mut self) -> String { + if !self.pending.is_empty() { + self.text.push_str(&String::from_utf8_lossy(&self.pending)); + } + self.text + } +} + +#[cfg(test)] +#[path = "tokenizer_test.rs"] +mod tests; diff --git a/plugins/ai-writer/backend/src/tokenizer_test.rs b/plugins/ai-writer/backend/src/tokenizer_test.rs new file mode 100644 index 00000000..17664ca7 --- /dev/null +++ b/plugins/ai-writer/backend/src/tokenizer_test.rs @@ -0,0 +1,83 @@ +use super::*; + +/// 合成词表:256 个字节字符 + 几个合并结果 + 控制符 +fn tokenizer() -> Tokenizer { + let chars = byte_chars(); + let mut tokens: Vec = chars.iter().map(|c| c.to_string()).collect(); + let merges: Vec = ["h e", "l l", "he ll", "hell o", "Ġ w", "Ġw o"] + .iter() + .map(|s| s.to_string()) + .collect(); + tokens.extend( + ["he", "ll", "hell", "hello", "Ġw", "Ġwo"] + .iter() + .map(|s| s.to_string()), + ); + tokens.extend(["<|im_start|>", "<|im_end|>"].iter().map(|s| s.to_string())); + let mut control = vec![false; tokens.len()]; + let n = control.len(); + control[n - 1] = true; + control[n - 2] = true; + Tokenizer::new(tokens, control, &merges).unwrap() +} + +#[test] +fn byte_map_is_a_bijection_with_printable_bytes_unchanged() { + let table = byte_chars(); + let unique: std::collections::HashSet<_> = table.iter().collect(); + assert_eq!(unique.len(), 256); + assert_eq!(table[b'a' as usize], 'a'); + assert_eq!(table[b' ' as usize], 'Ġ'); + assert_eq!(table[b'\n' as usize], 'Ċ'); +} + +#[test] +fn merges_apply_in_rank_order() { + let t = tokenizer(); + let hello = t.special("hello").unwrap(); + let wo = t.special("Ġwo").unwrap(); + let ids = t.encode("hello world"); + assert_eq!(ids[0], hello); + assert_eq!(ids[1], wo); + // 剩下的 r l d 没有合并规则,按单字节编号 + assert_eq!(&ids[2..], &[b'r' as u32, b'l' as u32, b'd' as u32]); + assert_eq!(t.decode(&ids), "hello world"); +} + +#[test] +fn round_trips_any_text_byte_by_byte() { + let t = tokenizer(); + for text in [ + "中文,标点!", + "emoji 🦀 and\ttabs\n\nlines", + "数字 2026 年 12 月", + " leading spaces", + ] { + assert_eq!(t.decode(&t.encode(text)), text); + } +} + +#[test] +fn special_markers_in_user_text_stay_plain_text() { + let t = tokenizer(); + let start = t.special("<|im_start|>").unwrap(); + let ids = t.encode("<|im_start|>system"); + assert!(!ids.contains(&start)); + assert_eq!(t.decode(&ids), "<|im_start|>system"); + // 控制符解码为空 + assert_eq!(t.decode(&[start]), ""); +} + +#[test] +fn stream_decoder_waits_for_complete_characters() { + let mut decoder = StreamDecoder::default(); + let bytes = "汉字".as_bytes(); + decoder.push(&bytes[..2]); + assert_eq!(decoder.text, ""); + decoder.push(&bytes[2..4]); + assert_eq!(decoder.text, "汉"); + decoder.push(&bytes[4..]); + assert_eq!(decoder.text, "汉字"); + decoder.push(&[0xE6]); + assert_eq!(decoder.finish(), "汉字\u{FFFD}"); +} diff --git a/plugins/ai-writer/icon.svg b/plugins/ai-writer/icon.svg new file mode 100644 index 00000000..084e3a5e --- /dev/null +++ b/plugins/ai-writer/icon.svg @@ -0,0 +1 @@ + diff --git a/plugins/ai-writer/locales/en-US.json b/plugins/ai-writer/locales/en-US.json new file mode 100644 index 00000000..80012749 --- /dev/null +++ b/plugins/ai-writer/locales/en-US.json @@ -0,0 +1,106 @@ +{ + "name": "AI Writing Assistant", + "description": "Polish, proofread, rewrite, shorten, expand, summarize and translate text with a small language model that runs on this computer; your text never leaves it", + "help": [ + "The model runs locally (Qwen2.5 Instruct, Apache-2.0). Download one on the left before first use; text is never sent to any server.", + "The 1.5B model gives better results, the 0.5B model is faster and lighter. With both downloaded, 1.5B is used by default; click a model card to switch.", + "The model is released from memory after 5 idle minutes and loaded again when needed.", + "Small models sometimes make mistakes or miss things, so check the result before using it. Tools such as the Markdown editor also use the models downloaded here." + ], + "model": { + "title": "Models", + "hint": "Models are stored on this computer and can be deleted at any time; click a downloaded model to use it.", + "needed": "Download a model on the left first" + }, + "resources": { + "qwen2.5-0.5b-instruct": { + "name": "Qwen2.5 0.5B", + "description": "Fast and light; good for proofreading and simple rewrites" + }, + "qwen2.5-1.5b-instruct": { + "name": "Qwen2.5 1.5B (recommended)", + "description": "Better results; good for polishing, summaries and translation" + } + }, + "action": { + "title": "Action", + "instruction": "For example: make it a formal business tone", + "markdown": "Keep Markdown formatting" + }, + "actions": { + "polish": "Polish", + "proofread": "Proofread", + "rewrite": "Rewrite", + "shorten": "Shorten", + "expand": "Expand", + "summarize": "Summarize", + "translate": "Translate", + "custom": "Custom" + }, + "actionHints": { + "polish": "Smoother, more natural wording with the same meaning and tone", + "proofread": "Fix only typos, grammar and punctuation", + "rewrite": "Say the same thing in different words", + "shorten": "Keep the key points in fewer words", + "expand": "Add detail and explanation", + "summarize": "The key points in a few sentences", + "translate": "Translate into the chosen language", + "custom": "Process the text with your own instruction" + }, + "languages": { + "Simplified Chinese": "Simplified Chinese", + "Traditional Chinese": "Traditional Chinese", + "English": "English", + "Japanese": "Japanese", + "Korean": "Korean", + "French": "French", + "German": "German", + "Spanish": "Spanish", + "Russian": "Russian" + }, + "input": { + "title": "Original", + "count_one": "{{count}} character", + "count_other": "{{count}} characters", + "placeholder": "Paste or type the text to process…", + "footer": "Up to 12,000 characters at a time" + }, + "run": { + "start": "Start", + "stop": "Stop" + }, + "output": { + "title": "Result", + "stats": "{{tokens}} tokens in {{seconds}} s", + "truncated": "length limit reached", + "useAsInput": "Use as original", + "placeholder": "The result appears here" + }, + "stages": { + "ai": { + "load": "Loading the model…", + "read": "Reading the text…", + "write": "Writing…" + } + }, + "logs": { + "ai": { + "model_loaded": "Model loaded in {{ms}} ms", + "partial": "So far: {{text}}", + "done": "{{tokens}} tokens in {{ms}} ms ({{model}})" + } + }, + "errors": { + "ai.empty": "Enter some text to process", + "ai.too_long": "The text is longer than {{max}} characters; process it in parts", + "ai.too_long_tokens": "The text is too long (over {{max}} tokens); process it in parts", + "ai.no_language": "Choose a target language", + "ai.no_instruction": "Enter an instruction", + "ai.instruction_too_long": "The instruction can be at most {{max}} characters", + "ai.no_model": "No model is downloaded yet; download one in the AI Writing Assistant first", + "ai.unknown_model": "Unknown model: {{id}}", + "ai.model_invalid": "The model file could not be read: {{detail}}", + "ai.inference_failed": "Generation failed: {{detail}}", + "ai.empty_output": "The model produced no text; try again" + } +} diff --git a/plugins/ai-writer/locales/zh-CN.json b/plugins/ai-writer/locales/zh-CN.json new file mode 100644 index 00000000..7ae90918 --- /dev/null +++ b/plugins/ai-writer/locales/zh-CN.json @@ -0,0 +1,105 @@ +{ + "name": "AI 写作助手", + "description": "在本机运行小型语言模型润色、纠错、改写、精简、扩写、摘要与翻译文本,文本不离开本机", + "help": [ + "模型在本机运行(Qwen2.5 Instruct,Apache-2.0 许可),首次使用前在左侧下载;文本不会发送到任何服务器。", + "1.5B 模型效果更好,0.5B 模型更快、占用更少;都下载时默认使用 1.5B,可点击模型卡片切换。", + "模型闲置 5 分钟后自动释放内存,下次使用时重新加载。", + "小模型偶尔会出错或漏改,请核对结果后再使用。Markdown 编辑器等工具也会调用这里下载的模型。" + ], + "model": { + "title": "模型", + "hint": "模型保存在本机,可随时删除;点击已下载的模型切换使用。", + "needed": "请先在左侧下载一个模型" + }, + "resources": { + "qwen2.5-0.5b-instruct": { + "name": "Qwen2.5 0.5B", + "description": "速度快、占用少,适合纠错与简单改写" + }, + "qwen2.5-1.5b-instruct": { + "name": "Qwen2.5 1.5B(推荐)", + "description": "效果更好,适合润色、摘要与翻译" + } + }, + "action": { + "title": "动作", + "instruction": "例如:改成正式的商务语气", + "markdown": "保留 Markdown 格式" + }, + "actions": { + "polish": "润色", + "proofread": "纠错", + "rewrite": "改写", + "shorten": "精简", + "expand": "扩写", + "summarize": "摘要", + "translate": "翻译", + "custom": "自定义" + }, + "actionHints": { + "polish": "让文字更通顺自然,意思与语气不变", + "proofread": "只修正错别字、语法与标点", + "rewrite": "换一种说法表达同样的意思", + "shorten": "保留要点,压缩篇幅", + "expand": "补充细节与解释", + "summarize": "用几句话概括要点", + "translate": "翻译为选定的语言", + "custom": "按你写的指令处理文本" + }, + "languages": { + "Simplified Chinese": "简体中文", + "Traditional Chinese": "繁體中文", + "English": "英语", + "Japanese": "日语", + "Korean": "韩语", + "French": "法语", + "German": "德语", + "Spanish": "西班牙语", + "Russian": "俄语" + }, + "input": { + "title": "原文", + "count": "{{count}} 字", + "placeholder": "粘贴或输入要处理的文本…", + "footer": "单次最多 12000 字" + }, + "run": { + "start": "开始", + "stop": "停止" + }, + "output": { + "title": "结果", + "stats": "生成 {{tokens}} 个词元,用时 {{seconds}} 秒", + "truncated": "已达长度上限", + "useAsInput": "作为原文", + "placeholder": "结果会显示在这里" + }, + "stages": { + "ai": { + "load": "正在加载模型…", + "read": "正在阅读原文…", + "write": "正在生成…" + } + }, + "logs": { + "ai": { + "model_loaded": "模型加载用时 {{ms}} 毫秒", + "partial": "已生成:{{text}}", + "done": "生成 {{tokens}} 个词元,用时 {{ms}} 毫秒({{model}})" + } + }, + "errors": { + "ai.empty": "请输入要处理的文本", + "ai.too_long": "文本超过 {{max}} 字,请分段处理", + "ai.too_long_tokens": "文本过长(超过 {{max}} 个词元),请分段处理", + "ai.no_language": "请选择目标语言", + "ai.no_instruction": "请输入指令", + "ai.instruction_too_long": "指令不能超过 {{max}} 字", + "ai.no_model": "还没有下载模型,请先在 AI 写作助手中下载", + "ai.unknown_model": "未知的模型:{{id}}", + "ai.model_invalid": "模型文件无法读取:{{detail}}", + "ai.inference_failed": "生成失败:{{detail}}", + "ai.empty_output": "模型没有生成内容,请重试" + } +} diff --git a/plugins/ai-writer/manifest.json b/plugins/ai-writer/manifest.json new file mode 100644 index 00000000..0081f9b3 --- /dev/null +++ b/plugins/ai-writer/manifest.json @@ -0,0 +1,40 @@ +{ + "id": "org.devlive.toolforge.ai-writer", + "version": "0.1.0", + "name": "i18n:name", + "description": "i18n:description", + "category": "text", + "keywords": ["ai", "llm", "writing", "polish", "proofread", "rewrite", "summarize", "translate", "qwen", "offline", "写作", "润色", "纠错", "改写", "摘要", "翻译", "扩写", "精简", "本地模型", "模型管理"], + "accent": "purple", + "locales": ["zh-CN", "en-US"], + "minAppVersion": "0.2.6", + "permissions": ["clipboard:write", "network:resources"], + "functions": { + "generate": { "task": true, "interface": false } + }, + "sensitive": false, + "resources": [ + { + "id": "qwen2.5-0.5b-instruct", + "urls": [ + "https://huggingface.co/Qwen/Qwen2.5-0.5B-Instruct-GGUF/resolve/main/qwen2.5-0.5b-instruct-q4_k_m.gguf", + "https://hf-mirror.com/Qwen/Qwen2.5-0.5B-Instruct-GGUF/resolve/main/qwen2.5-0.5b-instruct-q4_k_m.gguf", + "https://www.modelscope.cn/models/Qwen/Qwen2.5-0.5B-Instruct-GGUF/resolve/master/qwen2.5-0.5b-instruct-q4_k_m.gguf" + ], + "sha256": "74a4da8c9fdbcd15bd1f6d01d621410d31c6fc00986f5eb687824e7b93d7a9db", + "size": 491400032, + "license": "Apache-2.0" + }, + { + "id": "qwen2.5-1.5b-instruct", + "urls": [ + "https://huggingface.co/Qwen/Qwen2.5-1.5B-Instruct-GGUF/resolve/main/qwen2.5-1.5b-instruct-q4_k_m.gguf", + "https://hf-mirror.com/Qwen/Qwen2.5-1.5B-Instruct-GGUF/resolve/main/qwen2.5-1.5b-instruct-q4_k_m.gguf", + "https://www.modelscope.cn/models/Qwen/Qwen2.5-1.5B-Instruct-GGUF/resolve/master/qwen2.5-1.5b-instruct-q4_k_m.gguf" + ], + "sha256": "6a1a2eb6d15622bf3c96857206351ba97e1af16c30d7a74ee38970e434e9407e", + "size": 1117320736, + "license": "Apache-2.0" + } + ] +} diff --git a/plugins/ai-writer/ui/package.json b/plugins/ai-writer/ui/package.json new file mode 100644 index 00000000..e4204ecf --- /dev/null +++ b/plugins/ai-writer/ui/package.json @@ -0,0 +1,27 @@ +{ + "name": "@toolforge-plugin/ai-writer", + "private": true, + "version": "0.1.0", + "type": "module", + "exports": { + ".": "./src/index.tsx" + }, + "scripts": { + "typecheck": "tsc -p tsconfig.json" + }, + "peerDependencies": { + "react": "^19" + }, + "dependencies": { + "@toolforge/plugin-ui-sdk": "workspace:*", + "@toolforge/ui": "workspace:*", + "lucide-react": "1.47.0", + "react-i18next": "17.0.15" + }, + "devDependencies": { + "@types/react": "19.3.0", + "react": "19.3.0", + "typescript": "5.9.3", + "vite": "8.3.0" + } +} diff --git a/plugins/ai-writer/ui/src/AiWriter.tsx b/plugins/ai-writer/ui/src/AiWriter.tsx new file mode 100644 index 00000000..8d3a68dd --- /dev/null +++ b/plugins/ai-writer/ui/src/AiWriter.tsx @@ -0,0 +1,150 @@ +import { useEffect, useState } from 'react' +import { Button, CodeEditor, Input, Panel, Progress, Select, Spinner, Switch, toast } from '@toolforge/ui' +import { CopyButton, ResourceItem, useLaunchInput, usePlugin, usePluginState, useResources } from '@toolforge/plugin-ui-sdk' +import { ArrowLeftRight, Brain, PenLine, Sparkles, Square, Wand2 } from 'lucide-react' +import { ACTIONS, LANGUAGES, useGeneration, type Action } from './useGeneration' + +const MODELS = ['qwen2.5-1.5b-instruct', 'qwen2.5-0.5b-instruct'] as const + +interface Settings { + action: Action + language: string + instruction: string + markdown: boolean + model: string | null +} + +const DEFAULTS: Settings = { action: 'polish', language: 'English', instruction: '', markdown: false, model: null } + +export function AiWriter() { + const { t, errorMessage } = usePlugin() + const resources = useResources() + const generation = useGeneration() + const [settings, setSettings] = usePluginState('settings', DEFAULTS) + const [input, setInput] = useState('') + const update = (patch: Partial) => setSettings((prev) => ({ ...prev, ...patch })) + + useLaunchInput((text) => setInput(text)) + + const installed = MODELS.filter((id) => resources.get(id)?.installed) + // 选中的模型被删除后回到「自动」:用已下载的最好的模型 + const model = settings.model && installed.includes(settings.model as (typeof MODELS)[number]) ? settings.model : null + const ready = installed.length > 0 + + useEffect(() => { + if (generation.status === 'failed' && generation.error && generation.error.code !== 'task.cancelled') toast.error(errorMessage(generation.error)) + }, [generation.status, generation.error, errorMessage]) + + const run = () => { + if (!input.trim() || generation.running) return + void generation.start({ + action: settings.action, + text: input, + language: settings.language, + instruction: settings.instruction, + markdown: settings.markdown, + model: model ?? undefined, + }) + } + + const output = generation.result?.text ?? generation.partial + const progress = generation.progress && generation.progress.total > 0 ? (generation.progress.done / generation.progress.total) * 100 : null + const canRun = ready && input.trim().length > 0 && !generation.running && (settings.action !== 'custom' || settings.instruction.trim().length > 0) + + return ( +
+
+ } title={t('model.title')} className="shrink-0" bodyClassName="space-y-2 p-3"> + {MODELS.map((id) => ( + update({ model: id }) : undefined} + /> + ))} +

{t('model.hint')}

+
+ } title={t('action.title')} className="shrink-0" bodyClassName="space-y-3 p-3"> +
+ {ACTIONS.map((action) => ( + + ))} +
+

{t(`actionHints.${settings.action}`)}

+ {settings.action === 'translate' && ( + update({ instruction: e.target.value })} placeholder={t('action.instruction')} aria-label={t('action.instruction')} maxLength={500} /> + )} + +
+
+
+ } + title={t('input.title')} + extra={{t('input.count', { count: input.length })}} + actions={ + generation.running ? ( + + ) : ( + + ) + } + footer={!ready ? {t('model.needed')} : {t('input.footer')}} + > + + + } + title={t('output.title')} + extra={ + generation.running ? ( + + + {t(`stages.${generation.stage ?? 'ai.load'}`)} + + ) : generation.result ? ( + + {t('output.stats', { tokens: generation.result.tokens, seconds: (generation.result.elapsedMs / 1000).toFixed(1) })} + {generation.result.truncated && ` · ${t('output.truncated')}`} + + ) : null + } + actions={ + generation.result && ( + <> + + + + ) + } + footer={generation.running && } + > + + +
+
+ ) +} diff --git a/plugins/ai-writer/ui/src/index.tsx b/plugins/ai-writer/ui/src/index.tsx new file mode 100644 index 00000000..148d5f39 --- /dev/null +++ b/plugins/ai-writer/ui/src/index.tsx @@ -0,0 +1,3 @@ +import { AiWriter } from './AiWriter' + +export default AiWriter diff --git a/plugins/ai-writer/ui/src/useGeneration.ts b/plugins/ai-writer/ui/src/useGeneration.ts new file mode 100644 index 00000000..62c384f9 --- /dev/null +++ b/plugins/ai-writer/ui/src/useGeneration.ts @@ -0,0 +1,101 @@ +import { useCallback, useEffect, useRef, useState } from 'react' +import { cancelTask, startTask, toAppError, type AppError, type TaskEvent } from '@toolforge/plugin-ui-sdk' + +export const AI_WRITER_ID = 'org.devlive.toolforge.ai-writer' + +export type Action = 'polish' | 'proofread' | 'rewrite' | 'shorten' | 'expand' | 'summarize' | 'translate' | 'custom' + +export const ACTIONS: Action[] = ['polish', 'proofread', 'rewrite', 'shorten', 'expand', 'summarize', 'translate', 'custom'] + +/** 翻译目标语言:值直接交给模型,显示名走翻译 */ +export const LANGUAGES = ['Simplified Chinese', 'Traditional Chinese', 'English', 'Japanese', 'Korean', 'French', 'German', 'Spanish', 'Russian'] as const + +export interface GenerateRequest { + action: Action + text: string + language?: string + instruction?: string + markdown?: boolean + model?: string +} + +export interface GenerateOutput { + text: string + model: string + promptTokens: number + tokens: number + elapsedMs: number + truncated: boolean +} + +export interface GenerationState { + status: 'idle' | 'running' | 'succeeded' | 'failed' | 'cancelled' + stage: string | null + progress: { done: number; total: number } | null + /** 生成中的文本(每隔一小段时间更新) */ + partial: string + result: GenerateOutput | null + error: AppError | null +} + +const IDLE: GenerationState = { status: 'idle', stage: null, progress: null, partial: '', result: null, error: null } + +/** 以任务方式运行 AI 写作助手的 generate,并读取流式输出 */ +export function useGeneration() { + const [state, setState] = useState(IDLE) + const taskId = useRef(null) + const run = useRef(0) + + useEffect( + () => () => { + run.current++ + }, + [], + ) + + const start = useCallback(async (request: GenerateRequest) => { + const mine = ++run.current + setState({ ...IDLE, status: 'running' }) + const onEvent = (event: TaskEvent) => { + if (mine !== run.current) return + setState((prev) => { + switch (event.type) { + case 'stage': + return { ...prev, stage: event.code } + case 'progress': + return { ...prev, progress: { done: event.done, total: event.total } } + case 'logs': { + const partial = event.lines.filter((line) => line.code === 'ai.partial').at(-1)?.params?.text + return typeof partial === 'string' ? { ...prev, partial } : prev + } + case 'finished': + taskId.current = null + return { + ...prev, + status: event.status, + result: event.status === 'succeeded' ? (event.result as GenerateOutput) : null, + error: event.error, + } + default: + return prev + } + }) + } + try { + taskId.current = await startTask(AI_WRITER_ID, 'generate', request, onEvent) + } catch (error) { + if (mine === run.current) setState({ ...IDLE, status: 'failed', error: toAppError(error) }) + } + }, []) + + const cancel = useCallback(() => { + if (taskId.current) void cancelTask(taskId.current) + }, []) + + const reset = useCallback(() => { + run.current++ + setState(IDLE) + }, []) + + return { ...state, running: state.status === 'running', start, cancel, reset } +} diff --git a/plugins/ai-writer/ui/tsconfig.json b/plugins/ai-writer/ui/tsconfig.json new file mode 100644 index 00000000..625277c6 --- /dev/null +++ b/plugins/ai-writer/ui/tsconfig.json @@ -0,0 +1,4 @@ +{ + "extends": "../../../tsconfig.base.json", + "include": ["src"] +} diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index e1493601..d2a4033f 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -5207,6 +5207,34 @@ importers: specifier: 8.3.0 version: 8.3.0(@types/node@24.13.6)(jiti@2.7.0) + plugins/ai-writer/ui: + dependencies: + '@toolforge/plugin-ui-sdk': + specifier: workspace:* + version: link:../../../packages/plugin-ui-sdk + '@toolforge/ui': + specifier: workspace:* + version: link:../../../packages/ui + lucide-react: + specifier: 1.47.0 + version: 1.47.0(react@19.3.0) + react-i18next: + specifier: 17.0.15 + version: 17.0.15(i18next@26.4.2(typescript@5.9.3))(react-dom@19.3.0(react@19.3.0))(react@19.3.0)(typescript@5.9.3) + devDependencies: + '@types/react': + specifier: 19.3.0 + version: 19.3.0 + react: + specifier: 19.3.0 + version: 19.3.0 + typescript: + specifier: 5.9.3 + version: 5.9.3 + vite: + specifier: 8.3.0 + version: 8.3.0(@types/node@24.13.6)(jiti@2.7.0) + plugins/archive/ui: dependencies: '@tanstack/react-virtual':