From 6470853d1db0f2d8c735370652fd8131d50d0047 Mon Sep 17 00:00:00 2001 From: ppppp2005-p <360128433+ppppp2005-p@users.noreply.github.com> Date: Wed, 25 Nov 2026 15:28:27 -0400 Subject: [PATCH 01/11] feat(ui-plugins): add Help Center Builder (help-center-builder) --- marketplace.json | 50 ++++++++++++++++++++++ pnpm-lock.yaml | 106 ++++++++++++++++++++++++++++++----------------- 2 files changed, 118 insertions(+), 38 deletions(-) diff --git a/marketplace.json b/marketplace.json index 32e8c8ef..9d3172d1 100644 --- a/marketplace.json +++ b/marketplace.json @@ -1673,6 +1673,56 @@ "把上一个 Hi3D 任务生成的模型按角色拆分成部件" ] } + }, + { + "name": "help-center-builder", + "componentTypes": [ + "ui" + ], + "source": "./external_plugins/help-center-builder", + "displayName": "Help Center Builder", + "displayName_i18n": { + "en": "Help Center Builder", + "zh-CN": "帮助中心制作" + }, + "description": "Turn a folder of Markdown / HTML docs into a static help center: home page with category cards, category pages, articles with breadcrumbs, sidebar, table of contents, related articles and previous / next, and instant full-text search that works offline (Chinese too). Incremental builds rewrite only the pages a change affects and list them with the reason. Broken links and anchors are reported. The output folder can be uploaded to any static host.", + "description_i18n": { + "en": "Turn a folder of Markdown / HTML docs into a static help center: home page with category cards, category pages, articles with breadcrumbs, sidebar, table of contents, related articles and previous / next, and instant full-text search that works offline (Chinese too). Incremental builds rewrite only the pages a change affects and list them with the reason. Broken links and anchors are reported. The output folder can be uploaded to any static host.", + "zh-CN": "把一个放 Markdown / HTML 文档的文件夹生成静态帮助中心:带分类卡片的首页、分类页,文章页有面包屑、侧边导航、目录、相关文章和上一篇 / 下一篇,还有离线可用的即时全文搜索(支持中文)。增量构建只重写受改动影响的页面,并列出原因;同时报告坏链和失效锚点。输出文件夹可直接上传到任意静态托管。" + }, + "version": "0.1.0", + "author": { + "name": "Penova", + "url": "https://github.com/ppppp2005-p" + }, + "license": "MIT", + "category": "productivity", + "keywords": [ + "help center", + "knowledge base", + "documentation", + "static site", + "markdown", + "faq", + "search", + "support", + "帮助中心", + "知识库", + "文档站", + "常见问题" + ], + "examplePrompts": [ + "Build a help center from the docs folder", + "I edited a few articles; update the help center", + "Check the help docs for broken links" + ], + "examplePrompts_i18n": { + "zh-CN": [ + "用 docs 文件夹生成帮助中心", + "我改了几篇文章,更新一下帮助中心", + "检查帮助文档里有没有坏链" + ] + } } ] } \ No newline at end of file diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 14b35f76..cbe8f569 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -37,7 +37,7 @@ importers: version: 6.0.2 vitest: specifier: 4.1.4 - version: 4.1.4(@opentelemetry/api@1.9.1)(@types/node@25.5.0)(msw@2.13.3(@types/node@25.5.0)(typescript@6.0.2))(vite@8.3.1(@types/node@25.5.0)(esbuild@0.25.12)(jiti@2.6.1)(tsx@4.21.0)(yaml@2.9.0)) + version: 4.1.4(@opentelemetry/api@1.9.1)(@types/node@25.5.0)(msw@2.13.3(@types/node@25.5.0)(typescript@6.0.2))(vite@8.3.1(@types/node@25.5.0)(esbuild@0.25.12)(jiti@2.6.1)(tsx@4.21.0)(yaml@2.9.1)) zod: specifier: 4.6.5 version: 4.6.5 @@ -89,6 +89,46 @@ importers: ui-plugins/gridcraft: {} + ui-plugins/help-center-builder: + dependencies: + '@modelcontextprotocol/sdk': + specifier: 1.29.0 + version: 1.29.0(zod@4.6.5) + marked: + specifier: 18.3.0 + version: 18.3.0 + minisearch: + specifier: 7.2.0 + version: 7.2.0 + yaml: + specifier: 2.9.1 + version: 2.9.1 + zod: + specifier: ^4.6.5 + version: 4.6.5 + devDependencies: + '@modelcontextprotocol/core': + specifier: 2.0.0 + version: 2.0.0 + '@modelcontextprotocol/ext-apps': + specifier: 2.0.0 + version: 2.0.0(@modelcontextprotocol/client@2.2.0)(@modelcontextprotocol/core@2.0.0)(@modelcontextprotocol/server@2.0.0)(react-dom@19.2.7(react@19.2.7))(react@19.2.7)(zod@4.6.5) + '@types/node': + specifier: 25.5.0 + version: 25.5.0 + esbuild: + specifier: ^0.25.12 + version: 0.25.12 + playwright-core: + specifier: 1.59.1 + version: 1.59.1 + typescript: + specifier: 6.0.2 + version: 6.0.2 + vitest: + specifier: 4.1.4 + version: 4.1.4(@opentelemetry/api@1.9.1)(@types/node@25.5.0)(msw@2.13.3(@types/node@25.5.0)(typescript@6.0.2))(vite@8.3.1(@types/node@25.5.0)(esbuild@0.25.12)(jiti@2.6.1)(tsx@4.21.0)(yaml@2.9.1)) + ui-plugins/jupyter-notebook: dependencies: '@modelcontextprotocol/sdk': @@ -2475,10 +2515,6 @@ packages: resolution: {integrity: sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==} engines: {node: '>= 0.6'} - eventsource-parser@3.1.0: - resolution: {integrity: sha512-kJezFj9YFAMLeORyi7aCLxLbD5/qWMQnoMVlVPyHIll7lgRJCc3JVln9Vgl9nwQi0YkMnhdGTMNn7CkRRAptMg==} - engines: {node: '>=18.0.0'} - eventsource-parser@3.1.1: resolution: {integrity: sha512-EKN1vKAMcZ8MlYMpaNuxN6R9yakzH6uajHcHVTqWJzvu5pWw9DyhbP35HH8MVBQ+dZjAfDxk+A8NiR9KWaXiyQ==} engines: {node: '>=18.0.0'} @@ -2714,9 +2750,6 @@ packages: jose@6.2.12: resolution: {integrity: sha512-9NiFmJEex0sy2Dk58j2UGBSHgUs2ypF9eZSu4L6vjOX3Dp96Sw1F3uL+H+D1sx02jZZdzUT0HgvCy59CuvXcWw==} - jose@6.2.2: - resolution: {integrity: sha512-d7kPDd34KO/YnzaDOlikGpOurfF0ByC2sEV4cANCtdqLlTfBlw2p14O/5d/zv40gJPbIQxfES3nSx1/oYNyuZQ==} - jotai-scope@0.7.2: resolution: {integrity: sha512-Gwed97f3dDObrO43++2lRcgOqw4O2sdr4JCjP/7eHK1oPACDJ7xKHGScpJX9XaflU+KBHXF+VhwECnzcaQiShg==} peerDependencies: @@ -2880,6 +2913,11 @@ packages: engines: {node: '>= 20'} hasBin: true + marked@18.3.0: + resolution: {integrity: sha512-ed8zmPXlBb3UfGXN5iHMQyMhFpdqLgoV5umUXx/Q1R+FW3q8VpqpyoKUwlENL9appo2UMvNLURDVaT3AMOryGA==} + engines: {node: '>= 20'} + hasBin: true + math-intrinsics@1.1.0: resolution: {integrity: sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==} engines: {node: '>= 0.4'} @@ -2906,6 +2944,9 @@ packages: resolution: {integrity: sha512-Lbgzdk0h4juoQ9fCKXW4by0UJqj+nOOrI9MJ1sSj4nI8aI2eo1qmvQEie4VD1glsS250n15LsWsYtCugiStS5A==} engines: {node: '>=18'} + minisearch@7.2.0: + resolution: {integrity: sha512-dqT2XBYUOZOiC5t2HRnwADjhNS2cecp9u+TJRiJ1Qp/f5qjkeT5APcGPjHw+bz89Ms8Jp+cG4AlE+QZ/QnDglg==} + mlly@1.8.2: resolution: {integrity: sha512-d+ObxMQFmbt10sretNDytwt85VrbkhhUA/JBGm1MPaWJ65Cl4wOgLaB1NYvJSZ0Ef03MMEU/0xpPMXUIQ29UfA==} @@ -3068,10 +3109,6 @@ packages: resolution: {integrity: sha512-V7+vQEJ06Z+c5tSye8S+nHUfI51xoXIXjHQ99cQtKUkQqqO1kO/KCJUfZXuB47h/YBlDhah2H3hdUGXn8ie0oA==} engines: {node: '>=8.6'} - picomatch@4.0.4: - resolution: {integrity: sha512-QP88BAKvMam/3NxH6vj2o21R6MjxZUAd6nlwAS/pnGvN9IVLocLHxGYIzFhg6fUQ+5th6P4dv4eW9jX3DSIj7A==} - engines: {node: '>=12'} - picomatch@4.0.7: resolution: {integrity: sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==} engines: {node: '>=12'} @@ -3697,8 +3734,8 @@ packages: resolution: {integrity: sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==} engines: {node: '>=10'} - yaml@2.9.0: - resolution: {integrity: sha512-2AvhNX3mb8zd6Zy7INTtSpl1F15HW6Wnqj0srWlkKLcpYl/gMIMJiyuGq2KeI2YFxUPjdlB+3Lc10seMLtL4cA==} + yaml@2.9.1: + resolution: {integrity: sha512-3NxN8+78OdzbT7C/WjGsyfPAtJaN3FNDsWxv7Y7mcDsT/oOmgW8BpyQQFFBnvZE3j9Y2Sdz1ULFLezL7Eb2yFw==} engines: {node: '>= 14.6'} hasBin: true @@ -4285,11 +4322,11 @@ snapshots: cors: 2.8.6 cross-spawn: 7.0.6 eventsource: 3.0.7 - eventsource-parser: 3.1.0 + eventsource-parser: 3.1.1 express: 5.2.1 express-rate-limit: 8.3.2(express@5.2.1) hono: 4.12.12 - jose: 6.2.2 + jose: 6.2.12 json-schema-typed: 8.0.2 pkce-challenge: 5.0.1 raw-body: 3.0.2 @@ -5151,14 +5188,14 @@ snapshots: chai: 6.2.2 tinyrainbow: 3.1.1 - '@vitest/mocker@4.1.4(msw@2.13.3(@types/node@25.5.0)(typescript@6.0.2))(vite@8.3.1(@types/node@25.5.0)(esbuild@0.25.12)(jiti@2.6.1)(tsx@4.21.0)(yaml@2.9.0))': + '@vitest/mocker@4.1.4(msw@2.13.3(@types/node@25.5.0)(typescript@6.0.2))(vite@8.3.1(@types/node@25.5.0)(esbuild@0.25.12)(jiti@2.6.1)(tsx@4.21.0)(yaml@2.9.1))': dependencies: '@vitest/spy': 4.1.4 estree-walker: 3.0.3 magic-string: 0.30.21 optionalDependencies: msw: 2.13.3(@types/node@25.5.0)(typescript@6.0.2) - vite: 8.3.1(@types/node@25.5.0)(esbuild@0.25.12)(jiti@2.6.1)(tsx@4.21.0)(yaml@2.9.0) + vite: 8.3.1(@types/node@25.5.0)(esbuild@0.25.12)(jiti@2.6.1)(tsx@4.21.0)(yaml@2.9.1) '@vitest/pretty-format@4.1.4': dependencies: @@ -5809,13 +5846,11 @@ snapshots: etag@1.8.1: {} - eventsource-parser@3.1.0: {} - eventsource-parser@3.1.1: {} eventsource@3.0.7: dependencies: - eventsource-parser: 3.1.0 + eventsource-parser: 3.1.1 expect-type@1.4.0: {} @@ -5869,10 +5904,6 @@ snapshots: fast-uri@3.1.0: {} - fdir@6.5.0(picomatch@4.0.4): - optionalDependencies: - picomatch: 4.0.4 - fdir@6.5.0(picomatch@4.0.7): optionalDependencies: picomatch: 4.0.7 @@ -6048,8 +6079,6 @@ snapshots: jose@6.2.12: {} - jose@6.2.2: {} - jotai-scope@0.7.2(jotai@2.11.0(@types/react@19.2.14)(react@19.2.7))(react@19.2.7): dependencies: jotai: 2.11.0(@types/react@19.2.14)(react@19.2.7) @@ -6186,6 +6215,8 @@ snapshots: marked@18.0.14: {} + marked@18.3.0: {} + math-intrinsics@1.1.0: {} mdn-data@2.27.1: {} @@ -6224,6 +6255,8 @@ snapshots: dependencies: mime-db: 1.54.0 + minisearch@7.2.0: {} + mlly@1.8.2: dependencies: acorn: 8.16.0 @@ -6406,8 +6439,6 @@ snapshots: picomatch@2.3.2: {} - picomatch@4.0.4: {} - picomatch@4.0.7: {} pirates@4.0.7: {} @@ -6785,8 +6816,8 @@ snapshots: tinyglobby@0.2.16: dependencies: - fdir: 6.5.0(picomatch@4.0.4) - picomatch: 4.0.4 + fdir: 6.5.0(picomatch@4.0.7) + picomatch: 4.0.7 tinyglobby@0.2.17: dependencies: @@ -6902,7 +6933,7 @@ snapshots: vary@1.1.2: {} - vite@8.3.1(@types/node@25.5.0)(esbuild@0.25.12)(jiti@2.6.1)(tsx@4.21.0)(yaml@2.9.0): + vite@8.3.1(@types/node@25.5.0)(esbuild@0.25.12)(jiti@2.6.1)(tsx@4.21.0)(yaml@2.9.1): dependencies: lightningcss: 1.33.0 picomatch: 4.0.7 @@ -6915,12 +6946,12 @@ snapshots: fsevents: 2.3.3 jiti: 2.6.1 tsx: 4.21.0 - yaml: 2.9.0 + yaml: 2.9.1 - vitest@4.1.4(@opentelemetry/api@1.9.1)(@types/node@25.5.0)(msw@2.13.3(@types/node@25.5.0)(typescript@6.0.2))(vite@8.3.1(@types/node@25.5.0)(esbuild@0.25.12)(jiti@2.6.1)(tsx@4.21.0)(yaml@2.9.0)): + vitest@4.1.4(@opentelemetry/api@1.9.1)(@types/node@25.5.0)(msw@2.13.3(@types/node@25.5.0)(typescript@6.0.2))(vite@8.3.1(@types/node@25.5.0)(esbuild@0.25.12)(jiti@2.6.1)(tsx@4.21.0)(yaml@2.9.1)): dependencies: '@vitest/expect': 4.1.4 - '@vitest/mocker': 4.1.4(msw@2.13.3(@types/node@25.5.0)(typescript@6.0.2))(vite@8.3.1(@types/node@25.5.0)(esbuild@0.25.12)(jiti@2.6.1)(tsx@4.21.0)(yaml@2.9.0)) + '@vitest/mocker': 4.1.4(msw@2.13.3(@types/node@25.5.0)(typescript@6.0.2))(vite@8.3.1(@types/node@25.5.0)(esbuild@0.25.12)(jiti@2.6.1)(tsx@4.21.0)(yaml@2.9.1)) '@vitest/pretty-format': 4.1.4 '@vitest/runner': 4.1.4 '@vitest/snapshot': 4.1.4 @@ -6937,7 +6968,7 @@ snapshots: tinyexec: 1.3.1 tinyglobby: 0.2.17 tinyrainbow: 3.1.1 - vite: 8.3.1(@types/node@25.5.0)(esbuild@0.25.12)(jiti@2.6.1)(tsx@4.21.0)(yaml@2.9.0) + vite: 8.3.1(@types/node@25.5.0)(esbuild@0.25.12)(jiti@2.6.1)(tsx@4.21.0)(yaml@2.9.1) why-is-node-running: 2.3.0 optionalDependencies: '@opentelemetry/api': 1.9.1 @@ -7018,8 +7049,7 @@ snapshots: y18n@5.0.8: optional: true - yaml@2.9.0: - optional: true + yaml@2.9.1: {} yargs-parser@21.1.1: optional: true From aae19ee2313e7bea105c6824a0749e621c0a57f9 Mon Sep 17 00:00:00 2001 From: ppppp2005-p <360128433+ppppp2005-p@users.noreply.github.com> Date: Wed, 25 Nov 2026 15:29:01 -0400 Subject: [PATCH 02/11] feat(ui-plugins): add Help Center Builder (help-center-builder) --- external_plugins/help-center-builder/LICENSE | 21 +++++++ .../help-center-builder/README.md | 59 +++++++++++++++++++ .../help-center-builder/README_CN.md | 59 +++++++++++++++++++ 3 files changed, 139 insertions(+) create mode 100644 external_plugins/help-center-builder/LICENSE create mode 100644 external_plugins/help-center-builder/README.md create mode 100644 external_plugins/help-center-builder/README_CN.md diff --git a/external_plugins/help-center-builder/LICENSE b/external_plugins/help-center-builder/LICENSE new file mode 100644 index 00000000..67e98093 --- /dev/null +++ b/external_plugins/help-center-builder/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 Penova + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/external_plugins/help-center-builder/README.md b/external_plugins/help-center-builder/README.md new file mode 100644 index 00000000..cb14036e --- /dev/null +++ b/external_plugins/help-center-builder/README.md @@ -0,0 +1,59 @@ +# Help Center Builder + +Turn a folder of **Markdown / HTML** docs into a **static help center** with category navigation, breadcrumbs, related articles and instant **full-text search** that works offline. When you edit docs, an **incremental build** rewrites only the pages the change affects and tells you why. + +## What it does + +- **Reads your docs**: + - Sub-folders become categories; files at the top level go to “General”. + - Front matter: `title`, `description`, `order`, `tags`, `related`, `updated`, `category`, `draft`. Without a title, a leading `#` / `##` / setext heading is used. + - An `index.md` in a folder becomes that category's intro; a top-level `index.md` becomes the home page's. + - HTML files (for example CMS exports) are supported: title, meta description and tags are read; navigation, scripts and inline handlers are removed. +- **Optional `help-center.json`** in the docs folder: `title`, `description`, `accent` colour, `logo`, `footer`, `baseUrl`, `lang`, and category names, descriptions and order. +- **Generates** `help-center/`: + - Home page with a search hero and category cards; category pages with article lists. + - Article pages: breadcrumbs, sidebar (the category's articles plus all categories), “On this page” table of contents, related articles (your `related` first, then shared tags and similar titles), and previous / next. + - Search page and 404 page; `sitemap.xml` and canonical links when `baseUrl` is set. + - Responsive, light and dark themes. English or Chinese interface, detected automatically. + - Images and other files are copied, and `.md` links are rewritten to `.html`. +- **Search**: built with [MiniSearch](https://github.com/lucaong/minisearch) at build time and shipped as a script. + - Works on any static host and straight from disk (`file://`), with no server or external service. + - Prefix and fuzzy matching; titles, tags and headings weigh more; Chinese / Japanese / Korean are split into characters and pairs. + - Live dropdown with keyboard navigation (`/` focuses the box), plus a results page. +- **Incremental builds**: + - Each page records what it depends on: its content, its category's article list, the categories, its related articles, previous / next, site settings and the template. + - Only pages whose dependencies changed are rewritten, each listed with the reason (for example “related articles changed”). Deleted articles are removed, and changed images re-copied. + - Use **Full rebuild** to rewrite everything. +- **Checks**: broken links to articles or files, missing `#anchors`, links outside the docs folder, two files producing the same page, missing or duplicate titles, empty articles, unknown `related`, drafts. + +## Usage + +Ask the agent in ZCode Desktop: + +- "Build a help center from the docs folder" +- "I edited a few articles; update the help center" +- "Check the help docs for broken links" + +Or use the panel: choose the docs folder, then **Build help center**; later, **Build changes**. Browse the site map and preview any page, and see which pages were rewritten and why. Open `help-center/index.html` in a browser, or upload the folder to a static host (Cloudflare Pages, Netlify, GitHub Pages, S3…). + +## Tools + +| Tool | Purpose | +|---|---| +| `hc_scan` | Categories, articles and problems in a docs folder (writes nothing) | +| `hc_build` | Build or update the site (incremental; `full` to rewrite everything) | + +## Scope (v0.1) + +- Hosting is up to you: the output is a plain static folder. Deploying it (for example to Cloudflare Pages) is a separate step. +- No feedback buttons, analytics, comments or login-protected articles (they need a backend). +- One language per site. Code blocks aren't syntax-highlighted. MDX, Liquid and other templating aren't run. + +## Privacy, network and files + +- Runs locally with no network access and no API keys. The generated site loads nothing from other servers. +- Reads the docs folder. Writes the output folder and `.help-center/builds.json`, and deletes only pages it wrote earlier. + +## License + +MIT. Uses [marked](https://github.com/markedjs/marked) (MIT), [MiniSearch](https://github.com/lucaong/minisearch) (MIT; also shipped in each generated site) and [yaml](https://github.com/eemeli/yaml) (ISC). diff --git a/external_plugins/help-center-builder/README_CN.md b/external_plugins/help-center-builder/README_CN.md new file mode 100644 index 00000000..3a359f2a --- /dev/null +++ b/external_plugins/help-center-builder/README_CN.md @@ -0,0 +1,59 @@ +# 帮助中心制作 + +把一个放 **Markdown / HTML** 文档的文件夹生成 **静态帮助中心**:分类导航、面包屑、相关文章,以及离线可用的即时 **全文搜索**。改了文档后,**增量构建** 只重写受影响的页面,并告诉你原因。 + +## 功能 + +- **读取文档**: + - 子文件夹就是分类;放在根目录的文件归入“常规”。 + - 支持 front matter:`title`、`description`、`order`、`tags`、`related`、`updated`、`category`、`draft`。没写标题时,用开头的 `#` / `##` / setext 标题。 + - 文件夹里的 `index.md` 作为该分类的介绍;根目录的 `index.md` 作为首页介绍。 + - 支持 HTML 文件(例如从 CMS 导出的):读取标题、meta 描述和标签,去掉导航、脚本和内联事件。 +- **可选的 `help-center.json`**(放在文档目录里):`title`、`description`、主题色 `accent`、`logo`、`footer`、`baseUrl`、`lang`,以及分类名称、说明和顺序。 +- **生成** `help-center/`: + - 首页:搜索大框加分类卡片;分类页:文章列表。 + - 文章页:面包屑、侧边栏(本分类文章加全部分类)、“本页内容”目录、相关文章(先用你写的 `related`,再按共同标签和相近标题补足)、上一篇 / 下一篇。 + - 搜索页和 404 页;设置了 `baseUrl` 时生成 `sitemap.xml` 和 canonical 链接。 + - 响应式布局,支持浅色 / 深色主题;界面中英文自动识别。 + - 图片等文件原样复制,`.md` 链接改写成 `.html`。 +- **搜索**:构建时用 [MiniSearch](https://github.com/lucaong/minisearch) 生成索引,以脚本形式随站点发布。 + - 任何静态托管都能用,直接双击打开(`file://`)也能用,不需要服务器或外部服务。 + - 支持前缀和模糊匹配;标题、标签、小标题权重更高;中日韩文字按单字和双字切分。 + - 输入时实时下拉,可用键盘选择(按 `/` 聚焦搜索框);另有搜索结果页。 +- **增量构建**: + - 每个页面记录它依赖的内容:正文、同分类文章列表、分类列表、相关文章、上一篇 / 下一篇、站点设置、模板。 + - 只重写依赖有变化的页面,并逐页列出原因(例如“相关文章变了”)。删掉的文章会被移除,改过的图片会重新复制。 + - 点“全量重建”可重写全部页面。 +- **检查**:指向文章或文件的坏链、失效的 `#锚点`、指向文档目录外的链接、两个文件生成同一个页面、缺失或重复的标题、空文章、无效的 `related`、草稿。 + +## 使用 + +在 ZCode Desktop 里对 Agent 说: + +- “用 docs 文件夹生成帮助中心” +- “我改了几篇文章,更新一下帮助中心” +- “检查帮助文档里有没有坏链” + +也可以用面板:选择文档目录 → **生成帮助中心**;以后改了文档点 **增量构建**。面板里能浏览站点结构、预览任意页面,并查看哪些页面被重写及原因。用浏览器打开 `help-center/index.html`,或把整个文件夹上传到静态托管(Cloudflare Pages、Netlify、GitHub Pages、S3 等)。 + +## 工具 + +| 工具 | 用途 | +|---|---| +| `hc_scan` | 查看文档目录的分类、文章和问题(不写文件) | +| `hc_build` | 生成或更新站点(默认增量,`full` 为全量重建) | + +## 范围(v0.1) + +- 托管由你决定:输出是普通的静态文件夹,部署(例如到 Cloudflare Pages)是另外一步。 +- 不含“是否有帮助”反馈、统计、评论、需要登录的文章(这些需要后端)。 +- 一个站点一种语言;代码块不做语法高亮;不执行 MDX、Liquid 等模板语法。 + +## 隐私、网络与文件 + +- 在本地运行,不联网,不需要 API Key。生成的站点不从其他服务器加载任何东西。 +- 读取文档目录;写入输出目录和 `.help-center/builds.json`;只删除自己以前生成的页面。 + +## 许可 + +MIT。使用 [marked](https://github.com/markedjs/marked)(MIT)、[MiniSearch](https://github.com/lucaong/minisearch)(MIT,也随每个生成的站点发布)和 [yaml](https://github.com/eemeli/yaml)(ISC)。 From 1132f15fe9e74abe43f925c6caefd880cdc0ee87 Mon Sep 17 00:00:00 2001 From: ppppp2005-p <360128433+ppppp2005-p@users.noreply.github.com> Date: Wed, 25 Nov 2026 15:29:39 -0400 Subject: [PATCH 03/11] feat(ui-plugins): add Help Center Builder (help-center-builder) --- ui-plugins/help-center-builder/package.json | 35 +++++++++++++++++++ ui-plugins/help-center-builder/tsconfig.json | 14 ++++++++ .../help-center-builder/vitest.config.ts | 2 ++ 3 files changed, 51 insertions(+) create mode 100644 ui-plugins/help-center-builder/package.json create mode 100644 ui-plugins/help-center-builder/tsconfig.json create mode 100644 ui-plugins/help-center-builder/vitest.config.ts diff --git a/ui-plugins/help-center-builder/package.json b/ui-plugins/help-center-builder/package.json new file mode 100644 index 00000000..a15da9a6 --- /dev/null +++ b/ui-plugins/help-center-builder/package.json @@ -0,0 +1,35 @@ +{ + "name": "@penova/plugin-help-center-builder", + "version": "0.1.0", + "private": true, + "license": "MIT", + "type": "module", + "scripts": { + "build": "node scripts/build.mjs", + "typecheck": "tsc -p tsconfig.json --noEmit", + "test": "vitest run", + "test:e2e": "node --experimental-strip-types scripts/e2e.mts" + }, + "zcode": { + "title": "Help Center Builder" + }, + "engines": { + "node": ">=22.0.0" + }, + "dependencies": { + "@modelcontextprotocol/sdk": "1.29.0", + "zod": "^4.6.5", + "marked": "18.3.0", + "minisearch": "7.2.0", + "yaml": "2.9.1" + }, + "devDependencies": { + "@modelcontextprotocol/core": "2.0.0", + "@modelcontextprotocol/ext-apps": "2.0.0", + "@types/node": "25.5.0", + "esbuild": "^0.25.12", + "playwright-core": "1.59.1", + "typescript": "6.0.2", + "vitest": "4.1.4" + } +} diff --git a/ui-plugins/help-center-builder/tsconfig.json b/ui-plugins/help-center-builder/tsconfig.json new file mode 100644 index 00000000..39f7ab60 --- /dev/null +++ b/ui-plugins/help-center-builder/tsconfig.json @@ -0,0 +1,14 @@ +{ + "compilerOptions": { + "target": "ES2022", + "module": "NodeNext", + "moduleResolution": "NodeNext", + "lib": ["ES2023", "DOM", "DOM.Iterable"], + "strict": true, + "skipLibCheck": true, + "noEmit": true, + "allowImportingTsExtensions": true, + "types": ["node"] + }, + "include": ["src/**/*.ts", "ui/**/*.ts", "test/**/*.ts"] +} diff --git a/ui-plugins/help-center-builder/vitest.config.ts b/ui-plugins/help-center-builder/vitest.config.ts new file mode 100644 index 00000000..27153a26 --- /dev/null +++ b/ui-plugins/help-center-builder/vitest.config.ts @@ -0,0 +1,2 @@ +import { defineConfig } from "vitest/config"; +export default defineConfig({ test: { include: ["src/**/*.test.ts", "test/**/*.test.ts"], testTimeout: 120000, hookTimeout: 120000 } }); From aa8676d2a273fbf548d38be520058ef814db282e Mon Sep 17 00:00:00 2001 From: ppppp2005-p <360128433+ppppp2005-p@users.noreply.github.com> Date: Wed, 25 Nov 2026 15:30:11 -0400 Subject: [PATCH 04/11] feat(ui-plugins): add Help Center Builder (help-center-builder) --- .../.zcode-plugin/plugin.json | 58 +++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 external_plugins/help-center-builder/.zcode-plugin/plugin.json diff --git a/external_plugins/help-center-builder/.zcode-plugin/plugin.json b/external_plugins/help-center-builder/.zcode-plugin/plugin.json new file mode 100644 index 00000000..26223185 --- /dev/null +++ b/external_plugins/help-center-builder/.zcode-plugin/plugin.json @@ -0,0 +1,58 @@ +{ + "name": "help-center-builder", + "version": "0.1.0", + "description": "Turn a folder of Markdown / HTML docs into a static help center: home page with category cards, category pages, articles with breadcrumbs, sidebar, table of contents, related articles and previous / next, and instant full-text search that works offline (Chinese too). Incremental builds rewrite only the pages a change affects and list them with the reason. Broken links and anchors are reported. The output folder can be uploaded to any static host.", + "description_i18n": { + "en": "Turn a folder of Markdown / HTML docs into a static help center: home page with category cards, category pages, articles with breadcrumbs, sidebar, table of contents, related articles and previous / next, and instant full-text search that works offline (Chinese too). Incremental builds rewrite only the pages a change affects and list them with the reason. Broken links and anchors are reported. The output folder can be uploaded to any static host.", + "zh-CN": "把一个放 Markdown / HTML 文档的文件夹生成静态帮助中心:带分类卡片的首页、分类页,文章页有面包屑、侧边导航、目录、相关文章和上一篇 / 下一篇,还有离线可用的即时全文搜索(支持中文)。增量构建只重写受改动影响的页面,并列出原因;同时报告坏链和失效锚点。输出文件夹可直接上传到任意静态托管。" + }, + "author": { + "name": "Penova", + "url": "https://github.com/ppppp2005-p" + }, + "license": "MIT", + "keywords": [ + "help center", + "knowledge base", + "documentation", + "static site", + "markdown", + "faq", + "search", + "support", + "帮助中心", + "知识库", + "文档站", + "常见问题" + ], + "skills": "skills", + "mcpServers": { + "help-center-builder": { + "type": "stdio", + "command": "node", + "args": [ + "${ZCODE_PLUGIN_ROOT}/dist/server.mjs" + ], + "cwd": "${ZCODE_PROJECT_DIR}", + "timeoutMs": 900000, + "env": { + "ZCODE_WORKSPACE_ROOT": "${ZCODE_PROJECT_DIR}" + } + } + }, + "ui": { + "surfaces": [ + { + "id": "editor", + "title": { + "zh-CN": "帮助中心制作", + "en-US": "Help Center Builder" + }, + "icon": "life-buoy", + "server": "help-center-builder", + "resourceUri": "ui://help-center-builder/panel.html", + "availability": "session" + } + ] + } +} From 2bc9479309c6fb2dffd5b739af2981e7fd812391 Mon Sep 17 00:00:00 2001 From: ppppp2005-p <360128433+ppppp2005-p@users.noreply.github.com> Date: Wed, 25 Nov 2026 15:30:48 -0400 Subject: [PATCH 05/11] feat(ui-plugins): add Help Center Builder (help-center-builder) --- .../help-center-builder/scripts/build.mjs | 81 +++++++++ .../help-center-builder/scripts/e2e.mts | 117 +++++++++++++ .../help-center-builder/scripts/harness.mjs | 162 ++++++++++++++++++ .../help-center-builder/scripts/licenses.mjs | 43 +++++ 4 files changed, 403 insertions(+) create mode 100644 ui-plugins/help-center-builder/scripts/build.mjs create mode 100644 ui-plugins/help-center-builder/scripts/e2e.mts create mode 100644 ui-plugins/help-center-builder/scripts/harness.mjs create mode 100644 ui-plugins/help-center-builder/scripts/licenses.mjs diff --git a/ui-plugins/help-center-builder/scripts/build.mjs b/ui-plugins/help-center-builder/scripts/build.mjs new file mode 100644 index 00000000..5ea87cfb --- /dev/null +++ b/ui-plugins/help-center-builder/scripts/build.mjs @@ -0,0 +1,81 @@ +import { build } from "esbuild"; +import { copyFile, cp, mkdir, readFile, rm, writeFile } from "node:fs/promises"; +import { createRequire } from "node:module"; +import { dirname, join, resolve } from "node:path"; +import { fileURLToPath } from "node:url"; +import { writeNotices } from "./licenses.mjs"; + +const root = resolve(dirname(fileURLToPath(import.meta.url)), ".."); +const dist = join(root, "dist"); +const pkg = JSON.parse(await readFile(join(root, "package.json"), "utf8")); +await rm(dist, { recursive: true, force: true }); +await mkdir(join(dist, "ui"), { recursive: true }); + +// 宿主只提供 HTML 本身,JS 与 CSS 全部内联到一个页面里。 +const ui = await build({ + metafile: true, + entryPoints: [join(root, "ui/main.ts")], + bundle: true, + format: "iife", + platform: "browser", + target: "es2022", + minify: true, + write: false, + outdir: join(dist, "ui"), + legalComments: "none", + loader: { ".css": "text" }, +}); +const js = ui.outputFiles.find((file) => file.path.endsWith(".js")).text; +const escape = (text) => text.replace(/<\/script/gi, "<\\/script"); +const html = `
/gi, (m) => ` ${m} `).replace(/<[^>]+>/g, " ")).replace(/\s+/g, " ").trim();
+
+/** 帮助中心内容不该带脚本:移除 script/iframe/object、内联事件和 javascript: 链接(清理作者内容,不是安全沙箱)。 */
+export function sanitize(html: string): { html: string; stripped: string[] } {
+ const stripped: string[] = [];
+ let out = html.replace(/<(script|iframe|object|embed)\b[\s\S]*?(<\/\1\s*>|$)/gi, (_, t: string) => { stripped.push(`<${t.toLowerCase()}>`); return ""; });
+ out = out.replace(/<(script|iframe|object|embed)\b[^>]*\/?>/gi, (_, t: string) => { stripped.push(`<${t.toLowerCase()}>`); return ""; });
+ out = out.replace(/\s(on[a-z]+)\s*=\s*("[^"]*"|'[^']*'|[^\s>]+)/gi, (_, a: string) => { stripped.push(`${a.toLowerCase()}=`); return ""; });
+ out = out.replace(/\b(href|src)\s*=\s*(["'])\s*javascript:[^"']*\2/gi, (_, a: string) => { stripped.push("javascript:"); return `${a}="#"`; });
+ return { html: out, stripped: [...new Set(stripped)] };
+}
+
+function frontMatter(raw: string): { data: Record; body: string } {
+ const m = raw.match(/^\uFEFF?---\r?\n([\s\S]*?)\r?\n---\r?\n?/);
+ if (!m) return { data: {}, body: raw.replace(/^\uFEFF/, "") };
+ let data: Record = {};
+ try { const y = parseYaml(m[1]); if (y && typeof y === "object") data = y as Record; } catch (e) { data = { __error: (e as Error).message }; }
+ return { data, body: raw.slice(m[0].length) };
+}
+const list = (v: unknown): string[] => (Array.isArray(v) ? v.map(String) : typeof v === "string" ? v.split(/[,,]/) : []).map((s) => s.trim()).filter(Boolean);
+
+function renderMarkdown(md: string) {
+ const used = new Map();
+ const headings: Heading[] = [];
+ const marked = new Marked({ gfm: true });
+ marked.use({
+ renderer: {
+ heading({ tokens, depth }) {
+ const inner = this.parser.parseInline(tokens);
+ const text = plain(inner);
+ let id = slugify(text);
+ const n = used.get(id) ?? 0;
+ used.set(id, n + 1);
+ if (n) id = `${id}-${n}`;
+ headings.push({ level: depth, id, text });
+ return `${inner} \n`;
+ },
+ table(token) { return `${Renderer.prototype.table.call(this, token)}`; },
+ },
+ });
+ return { html: marked.parse(md, { async: false }) as string, headings };
+}
+
+function fromHtml(raw: string) {
+ const title = decode(raw.match(/]*>([\s\S]*?)<\/h1>/i)?.[1]?.replace(/<[^>]+>/g, "").trim() ?? raw.match(/([\s\S]*?)<\/title>/i)?.[1]?.trim() ?? "");
+ const meta = (n: string) => decode(raw.match(new RegExp(`]*>([\s\S]*?)<\/\1>/i)?.[2] ?? raw.match(/ ]*>([\s\S]*?)<\/body>/i)?.[1] ?? raw;
+ body = body.replace(/<(nav|header|footer|style)\b[\s\S]*?<\/\1>/gi, "").replace(/]*>[\s\S]*?<\/h1>/i, "");
+ const used = new Map();
+ const headings: Heading[] = [];
+ body = body.replace(/]*)>([\s\S]*?)<\/h\1>/gi, (_, lv: string, attrs: string, inner: string) => {
+ const text = plain(inner);
+ let id = attrs.match(/\bid=["']([^"']+)["']/)?.[1] ?? slugify(text);
+ const n = used.get(id) ?? 0; used.set(id, n + 1); if (n) id = `${id}-${n}`;
+ headings.push({ level: +lv, id, text });
+ return `${inner} `;
+ });
+ return { title, description: meta("description"), tags: list(meta("tags") || meta("keywords")), html: body.trim(), headings };
+}
+
+/** 解析一篇文档(Markdown 或 HTML)。links 里的 target 是相对文档根目录的路径。 */
+export function parseDoc(src: string, raw: string): Doc {
+ const isHtml = /\.html?$/i.test(src);
+ const base = src.split("/").pop()!.replace(DOC_EXT, "");
+ let title = "", description = "", tags: string[] = [], data: Record = {}, html: string, headings: Heading[];
+ if (isHtml) {
+ const r = fromHtml(raw);
+ ({ title, description, tags, html, headings } = r);
+ } else {
+ const fm = frontMatter(raw);
+ data = fm.data;
+ let body = fm.body;
+ // 没写 title 时,用开头第一个块的一/二级标题(# / ## / setext 都算)作标题,并从正文里去掉。
+ if (!data.title) {
+ const first = new Marked({ gfm: true }).lexer(body).find((t) => t.type !== "space");
+ if (first?.type === "heading" && first.depth <= 2) { title = plain(new Marked().parseInline(first.text, { async: false }) as string); body = body.slice(body.indexOf(first.raw) + first.raw.length); }
+ }
+ ({ html, headings } = renderMarkdown(body));
+ }
+ title = String(data.title ?? title).trim();
+ const titleFromFile = !title;
+ if (!title) title = base.replace(/[-_]+/g, " ").replace(/^\w/, (c) => c.toUpperCase());
+ const s = sanitize(html);
+ html = s.html;
+ const text = plain(html);
+ const ids = [...new Set([...html.matchAll(/\s(?:id|name)\s*=\s*["']([^"']+)["']/gi)].map((m) => m[1]))];
+ const dir = src.includes("/") ? src.slice(0, src.lastIndexOf("/") + 1) : "";
+ const links: Link[] = [];
+ for (const m of html.matchAll(/\s(href|src)\s*=\s*["']([^"']*)["']/gi)) {
+ const href = decode(m[2]);
+ if (!href || /^[a-z][a-z0-9+.-]*:/i.test(href) || href.startsWith("//")) { links.push({ href, target: null, anchor: "", kind: "external" }); continue; }
+ if (href.startsWith("#")) { links.push({ href, target: src, anchor: decodeURIComponent(href.slice(1)), kind: "anchor" }); continue; }
+ const [pathPart, anchor = ""] = href.split("#");
+ const clean = decodeURIComponent(pathPart.split("?")[0]);
+ const target = normalize(clean.startsWith("/") ? clean.slice(1) : dir + clean);
+ links.push({ href, target, anchor: decodeURIComponent(anchor), kind: isDocPath(target ?? "") ? "doc" : "asset" });
+ }
+ const folder = src.includes("/") ? src.split("/")[0] : "";
+ const firstPara = plain(html.match(/]*>([\s\S]*?)<\/p>/i)?.[1] ?? "") || text;
+ description = String(data.description ?? description).trim();
+ return {
+ src, out: outPath(src), hash: sha(raw), title, titleFromFile, description,
+ excerpt: (description || firstPara).slice(0, 180) + ((description || firstPara).length > 180 ? "…" : ""),
+ folder, categoryName: data.category ? String(data.category) : undefined, order: Number.isFinite(Number(data.order)) ? Number(data.order) : 1000,
+ tags: tags.length ? tags : list(data.tags), related: list(data.related), updated: data.updated ? (data.updated instanceof Date ? data.updated.toISOString().slice(0, 10) : String(data.updated)) : undefined,
+ draft: data.draft === true, html, text: text.slice(0, 30_000), headings, ids, links, stripped: s.stripped, isIntro: /(^|\/)index\.(md|markdown|html?)$/i.test(src),
+ };
+}
+
+/** 规范化相对路径(处理 ./ 和 ../);越出根目录返回 null。 */
+export function normalize(p: string): string | null {
+ const out: string[] = [];
+ for (const part of p.split("/")) {
+ if (!part || part === ".") continue;
+ if (part === "..") { if (!out.length) return null; out.pop(); } else out.push(part);
+ }
+ return out.join("/");
+}
diff --git a/ui-plugins/help-center-builder/src/main.ts b/ui-plugins/help-center-builder/src/main.ts
new file mode 100644
index 00000000..50111e63
--- /dev/null
+++ b/ui-plugins/help-center-builder/src/main.ts
@@ -0,0 +1,14 @@
+import "./kit/console.ts";
+import { dirname, resolve } from "node:path";
+import { fileURLToPath } from "node:url";
+import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
+import { createServer } from "./server.ts";
+
+const here = dirname(fileURLToPath(import.meta.url));
+const server = createServer({
+ workspaceRoot: resolve(process.env.ZCODE_WORKSPACE_ROOT || process.cwd()),
+ assetRoot: here,
+ log: (line) => process.stderr.write(`[help-center-builder] ${line}\n`),
+});
+process.stdin.once("end", () => process.exit(0));
+await server.connect(new StdioServerTransport());
diff --git a/ui-plugins/help-center-builder/src/server.ts b/ui-plugins/help-center-builder/src/server.ts
new file mode 100644
index 00000000..9d232064
--- /dev/null
+++ b/ui-plugins/help-center-builder/src/server.ts
@@ -0,0 +1,249 @@
+import { readFile, rm } from "node:fs/promises";
+import { readFileSync } from "node:fs";
+import { join } from "node:path";
+import MiniSearch from "minisearch";
+import { z } from "zod";
+import { createKitServer } from "./kit/server-kit.ts";
+import { KitError, Workspace } from "./kit/workspace.ts";
+import { type Doc, isDocPath, parseDoc, sha } from "./docs.ts";
+import { type Model, REASONS, type SiteConf, TEMPLATE_VERSION, buildModel, detectLang, plan, searchDocs } from "./site.ts";
+
+export const NAME = "help-center-builder";
+export const VERSION = "0.1.0";
+export const PANEL_URI = `ui://${NAME}/panel.html`;
+const STORE = ".help-center/builds.json";
+const CONFIG = "help-center.json";
+const FIELDS = ["title", "headings", "tags", "text"];
+const RUNTIME_ASSETS = ["style.css", "search.js", "tokenize.js", "minisearch.js"];
+
+export interface ServerOptions { workspaceRoot: string; assetRoot: string; log?: (line: string) => void }
+export interface Issue { level: "error" | "warn" | "info"; src: string; message: string }
+interface Manifest { docs: string; out: string; builtAt: string; pages: Record>; files: Record; site: SiteConf; summary: Summary }
+export interface Rebuilt { out: string; kind: string; reasons: string[]; src?: string }
+export interface Summary { pages: number; articles: number; categories: { name: string; out: string; count: number }[]; rebuilt: Rebuilt[]; unchanged: number; removed: string[]; copied: string[]; issues: Issue[]; ms: number; full: boolean; first: boolean; searchRebuilt: boolean; lang: string; bytes: number }
+
+export function createServer(options: ServerOptions) {
+ const ws = new Workspace(options.workspaceRoot);
+ const assets = join(options.assetRoot, "runtime/assets");
+ // 与站点浏览器端完全相同的分词源码(同一个文件),保证索引和查询切词一致。
+ const hcTokenize = new Function(`${readFileSync(join(assets, "tokenize.js"), "utf8")}\nreturn hcTokenize;`)() as (s: string) => string[];
+ const { server, tool } = createKitServer({ name: NAME, version: VERSION, panelUri: PANEL_URI, surface: "editor", panelHtml: () => readFile(join(options.assetRoot, "ui/panel.html"), "utf8"), log: options.log });
+ const load = async (): Promise> => ((await ws.exists(STORE)) ? JSON.parse(await ws.readText(STORE)).builds ?? {} : {});
+ const save = async (all: Record) => ws.write(STORE, JSON.stringify({ version: 1, builds: all }, null, 1) + "\n");
+ const norm = (p: string, what: string) => { const r = p.replace(/\\/g, "/").replace(/\/+$/, "").replace(/^\.\//, "") || "."; ws.resolve(r); if (r.startsWith("..") || r.startsWith("/")) throw new KitError("bad_path", `${what} must be inside the workspace.`); return r; };
+
+ async function read(docsDir: string, overrides: Partial, skip: string[] = []) {
+ if (!(await ws.exists(docsDir))) throw new KitError("not_found", `Folder ${docsDir}/ not found.`);
+ // 输出目录(以及以前建过的站点)可能就在文档目录里面(例如文档在工作区根目录),不能再当成文档扫进来。
+ const files = (await ws.list({ dir: docsDir, limit: 5000 })).filter((f) => !skip.some((o) => f.path === o || f.path.startsWith(`${o}/`)));
+ const relOf = (p: string) => (docsDir === "." ? p : p.slice(docsDir.length + 1));
+ const docs: Doc[] = [];
+ const assetsIn: { path: string; rel: string }[] = [];
+ let conf: Partial & { categories?: SiteConf["categories"] } = {};
+ const issues: Issue[] = [];
+ for (const f of files) {
+ const r = relOf(f.path);
+ if (r === CONFIG) { try { conf = JSON.parse(await ws.readText(f.path)); } catch (e) { issues.push({ level: "error", src: r, message: `Invalid JSON: ${(e as Error).message}` }); } continue; }
+ if (isDocPath(r)) { if (f.size > 5 * 1024 * 1024) { issues.push({ level: "warn", src: r, message: "Skipped: larger than 5 MB." }); continue; } docs.push(parseDoc(r, await ws.readText(f.path))); }
+ else assetsIn.push({ path: f.path, rel: r });
+ }
+ if (!docs.length) throw new KitError("no_docs", `No Markdown or HTML files in ${docsDir}/.`);
+ const site: SiteConf = {
+ title: overrides.title ?? conf.title ?? "Help Center",
+ description: overrides.description ?? conf.description ?? "",
+ accent: overrides.accent ?? conf.accent ?? "#2563eb",
+ baseUrl: overrides.baseUrl ?? conf.baseUrl,
+ footer: conf.footer,
+ logo: conf.logo,
+ lang: (overrides.lang ?? conf.lang ?? detectLang(docs)) === "zh-CN" ? "zh-CN" : "en",
+ categories: Array.isArray(conf.categories) ? conf.categories : [],
+ };
+ if (!/^#[0-9a-f]{6}$/i.test(site.accent)) { issues.push({ level: "warn", src: CONFIG, message: `accent “${site.accent}” isn't #rrggbb; using #2563eb.` }); site.accent = "#2563eb"; }
+ if (site.baseUrl && !/^https?:\/\/[^\s]+$/.test(site.baseUrl)) { issues.push({ level: "warn", src: CONFIG, message: `baseUrl “${site.baseUrl}” isn't an http(s) URL; ignored.` }); site.baseUrl = undefined; }
+ const model = buildModel(docs, site);
+ issues.push(...check(model, docs, new Set(assetsIn.map((a) => a.rel))));
+ return { model, assetsIn, issues, docs };
+ }
+
+ function check(m: Model, all: Doc[], assetSet: Set): Issue[] {
+ const out: Issue[] = [];
+ const docBy = new Map(all.map((d) => [d.src, d]));
+ // 文档间链接按“去掉扩展名的路径”匹配:a.md、a.html 都指向同一篇(输出都是 a.html)。
+ const stem = (p: string) => p.replace(/\.(md|markdown|html?)$/i, "");
+ const byStem = new Map(all.map((d) => [stem(d.src), d]));
+ const findDoc = (p: string) => byStem.get(stem(p));
+ const byOut = new Map();
+ for (const d of all) {
+ if (byOut.has(d.out)) out.push({ level: "error", src: d.src, message: `Same output page as ${byOut.get(d.out)} (${d.out}); rename one.` });
+ byOut.set(d.out, d.src);
+ if (d.draft) { out.push({ level: "info", src: d.src, message: "Draft: not published." }); continue; }
+ if (d.titleFromFile) out.push({ level: "warn", src: d.src, message: `No title; using “${d.title}” from the file name. Add a # heading or title: in front matter.` });
+ if (!d.isIntro && d.text.length < 20) out.push({ level: "warn", src: d.src, message: "Almost empty article." });
+ if (d.stripped.length) out.push({ level: "info", src: d.src, message: `Removed ${d.stripped.join(", ")} (help articles don't run scripts).` });
+ for (const l of d.links) {
+ if (l.kind === "external") continue;
+ if (l.target === null) { out.push({ level: "error", src: d.src, message: `Link ${l.href} points outside the docs folder.` }); continue; }
+ if (l.kind === "asset") { if (!assetSet.has(l.target)) out.push({ level: "error", src: d.src, message: `Broken link: ${l.href} (file not found).` }); continue; }
+ const t = docBy.get(l.target) ?? findDoc(l.target);
+ if (!t) { out.push({ level: "error", src: d.src, message: `Broken link: ${l.href} (no such article).` }); continue; }
+ if (t.draft) out.push({ level: "warn", src: d.src, message: `Links to draft ${t.src}.` });
+ if (l.anchor && !t.ids.includes(l.anchor)) out.push({ level: "warn", src: d.src, message: `Missing anchor: ${l.href} (no #${l.anchor} in ${t.src}).` });
+ }
+ for (const r of d.related) if (!m.docs.some((x) => x.src === r || x.out === r || x.src.replace(/\.\w+$/, "") === r.replace(/\.\w+$/, ""))) out.push({ level: "warn", src: d.src, message: `related: “${r}” isn't a published article.` });
+ }
+ const titles = new Map();
+ for (const d of m.docs) { const k = d.title.toLowerCase(); if (titles.has(k)) out.push({ level: "warn", src: d.src, message: `Same title as ${titles.get(k)}: “${d.title}”.` }); else titles.set(k, d.src); }
+ for (const c of m.site.categories) if (!m.categories.some((x) => x.key === (c.key ?? c.folder) || x.name === c.name)) out.push({ level: "info", src: CONFIG, message: `Category “${c.name ?? c.folder}” has no articles.` });
+ return out;
+ }
+
+ async function build(docsDir: string, outDir: string, overrides: Partial, full: boolean) {
+ const t0 = Date.now();
+ const { model, assetsIn, issues } = await read(docsDir, overrides, [outDir, ...Object.keys(await load())]);
+ if (issues.some((i) => i.level === "error" && /Same output page/.test(i.message))) throw new KitError("conflict", issues.filter((i) => /Same output page/.test(i.message)).map((i) => `${i.src}: ${i.message}`).join("\n"));
+ const all = await load();
+ const prev = all[outDir];
+ const first = !prev;
+ const files: Record = {};
+ const pagesParts: Record> = {};
+ const rebuilt: Rebuilt[] = [];
+ const copied: string[] = [];
+ let unchanged = 0, bytes = 0;
+ const write = async (p: string, data: string | Uint8Array) => { await ws.write(`${outDir}/${p}`, data); bytes += typeof data === "string" ? Buffer.byteLength(data) : data.length; };
+ const exists = (p: string) => ws.exists(`${outDir}/${p}`);
+ for (const p of plan(model)) {
+ pagesParts[p.out] = p.parts;
+ const old = prev?.pages[p.out];
+ let reasons: string[] = [];
+ if (full) reasons = ["full"];
+ else if (!old) reasons = ["new"];
+ else {
+ reasons = Object.keys(p.parts).filter((k) => old[k] !== p.parts[k]);
+ if (!reasons.length && !(await exists(p.out))) reasons = ["missing"];
+ }
+ files[p.out] = sha(JSON.stringify(p.parts));
+ if (!reasons.length) { unchanged++; continue; }
+ await write(p.out, p.render());
+ rebuilt.push({ out: p.out, kind: p.kind, reasons, ...(p.src ? { src: p.src } : {}) });
+ }
+ for (const a of RUNTIME_ASSETS) {
+ const data = await readFile(join(assets, a));
+ const h = sha(data);
+ files[`assets/${a}`] = h;
+ if (full || prev?.files[`assets/${a}`] !== h || !(await exists(`assets/${a}`))) { await write(`assets/${a}`, data); copied.push(`assets/${a}`); }
+ }
+ for (const a of assetsIn) {
+ const data = await ws.read(a.path);
+ const h = sha(data);
+ files[a.rel] = h;
+ if (full || prev?.files[a.rel] !== h || !(await exists(a.rel))) { await write(a.rel, data); copied.push(a.rel); }
+ }
+ const sd = searchDocs(model);
+ const ms = new MiniSearch({ fields: FIELDS, storeFields: [], tokenize: hcTokenize, processTerm: (t: string) => t });
+ ms.addAll(sd.map(({ show: _s, ...d }) => d));
+ const searchH = sha(JSON.stringify(sd) + TEMPLATE_VERSION);
+ files["search-index.js"] = searchH;
+ const searchRebuilt = full || prev?.files["search-index.js"] !== searchH || !(await exists("search-index.js"));
+ if (searchRebuilt) await write("search-index.js", `window.HC_SEARCH=${JSON.stringify({ fields: FIELDS, index: ms.toJSON(), docs: Object.fromEntries(sd.map((d) => [d.id, d.show])) }).replace(/ p.kind !== "404" && p.kind !== "search").map((p) => ` ${base}/${p.out.split("/").map(encodeURIComponent).join("/").replace(/&/g, "&")} ${p.src && model.bySrc.get(p.src)?.updated ? `${model.bySrc.get(p.src)!.updated} ` : ""} `);
+ const xml = `\n\n${urls.join("\n")}\n \n`;
+ const h = sha(xml);
+ files["sitemap.xml"] = h;
+ if (full || prev?.files["sitemap.xml"] !== h || !(await exists("sitemap.xml"))) { await write("sitemap.xml", xml); copied.push("sitemap.xml"); }
+ }
+ const removed: string[] = [];
+ for (const old of Object.keys(prev?.files ?? {})) if (!(old in files)) { await rm(ws.resolve(`${outDir}/${old}`), { force: true }); removed.push(old); }
+ const summary: Summary = { pages: Object.keys(pagesParts).length, articles: model.docs.length, categories: model.categories.map((c) => ({ name: c.name, out: c.out, count: c.docs.length })), rebuilt, unchanged, removed, copied, issues, ms: Date.now() - t0, full, first, searchRebuilt, lang: model.site.lang, bytes };
+ all[outDir] = { docs: docsDir, out: outDir, builtAt: new Date().toISOString(), pages: pagesParts, files, site: model.site, summary };
+ await save(all);
+ return { summary, model };
+ }
+
+ const describe = (docs: string, out: string, s: Summary) => {
+ const errs = s.issues.filter((i) => i.level === "error"), warns = s.issues.filter((i) => i.level === "warn");
+ return [
+ `${s.first ? "Built" : s.full ? "Fully rebuilt" : "Updated"} ${out}/ from ${docs}/: ${s.articles} articles in ${s.categories.length} categories, ${s.pages} pages (${s.ms} ms).`,
+ s.first || s.full ? `Wrote all ${s.rebuilt.length} pages${s.copied.length ? ` and ${s.copied.length} assets` : ""}.` : `Rebuilt ${s.rebuilt.length} page(s), ${s.unchanged} unchanged${s.removed.length ? `, removed ${s.removed.length}` : ""}${s.copied.length ? `, copied ${s.copied.length} asset(s)` : ""}; search index ${s.searchRebuilt ? "rebuilt" : "unchanged"}.`,
+ ...(!s.first && !s.full ? s.rebuilt.slice(0, 40).map((r) => ` ↻ ${r.out} — ${r.reasons.map((k) => REASONS[k]?.en ?? k).join(", ")}`) : []),
+ ...s.removed.map((r) => ` ✕ ${r}`),
+ errs.length || warns.length ? `Problems: ${errs.length} error(s), ${warns.length} warning(s):` : "No broken links or other problems.",
+ ...[...errs, ...warns].slice(0, 30).map((i) => ` ${i.level === "error" ? "✗" : "!"} ${i.src}: ${i.message}`),
+ `Open ${out}/index.html in a browser, or upload the ${out}/ folder to any static host (Cloudflare Pages, Netlify, GitHub Pages, S3).`,
+ ].join("\n");
+ };
+ const siteArgs = {
+ title: z.string().max(80).optional().describe(`Site title (else ${CONFIG} → "Help Center")`),
+ description: z.string().max(200).optional(),
+ accent: z.string().regex(/^#[0-9a-fA-F]{6}$/).optional().describe("Brand colour"),
+ baseUrl: z.string().url().optional().describe("Public URL, for canonical links, sitemap.xml and 404.html"),
+ lang: z.enum(["en", "zh-CN"]).optional().describe("Site UI language (auto-detected)"),
+ };
+
+ tool("hc_scan", {
+ description: `Look at a docs folder (Markdown / HTML, optional ${CONFIG}) without writing anything: categories, articles, language, and problems such as broken links, missing anchors, missing titles and duplicate titles.`,
+ input: { docs: z.string().describe("Docs folder"), ...siteArgs }, readOnly: true,
+ }, async (i) => {
+ const docs = norm(i.docs, "docs");
+ const { model, issues, assetsIn } = await read(docs, i, Object.keys(await load()));
+ const cats = model.categories.map((c) => ({ name: c.name, out: c.out, articles: c.docs.map((d) => ({ src: d.src, title: d.title, tags: d.tags })) }));
+ return {
+ text: [`${docs}/: ${model.docs.length} articles in ${cats.length} categories (${model.site.lang}), ${assetsIn.length} other files.`, ...cats.map((c) => ` ${c.name}: ${c.articles.map((a) => a.title).join(" · ")}`), issues.length ? `Problems:\n${issues.map((x) => ` ${x.level === "error" ? "✗" : x.level === "warn" ? "!" : "·"} ${x.src}: ${x.message}`).join("\n")}` : "No problems found."].join("\n"),
+ structured: { kind: "scan", docs, site: model.site, categories: cats, issues },
+ };
+ });
+
+ tool("hc_build", {
+ description: "Build (or update) a static help center from a docs folder: home page with category cards, category pages, article pages with breadcrumbs, sidebar, table of contents, related articles and previous/next, full-text search (works offline, Chinese too), 404 and sitemap. Incremental: only pages whose content or dependencies changed are rewritten, and they are listed with the reason.",
+ input: { docs: z.string().describe("Docs folder with .md / .html files (sub-folders = categories)"), out: z.string().optional().describe("Output folder (default help-center)"), full: z.boolean().optional().describe("Rewrite every page"), ...siteArgs },
+ openPanel: true, timeoutMs: 180_000,
+ }, async (i) => {
+ const docs = norm(i.docs, "docs");
+ const out = norm(i.out ?? "help-center", "out");
+ if (out === "." || out === docs || docs.startsWith(`${out}/`)) throw new KitError("bad_out", "Choose an output folder that is separate from the docs folder.");
+ const known = await load();
+ if (!known[out] && (await ws.exists(`${out}/index.html`))) throw new KitError("exists", `${out}/ already has a site that this plugin didn't build; choose another out.`);
+ const { summary } = await build(docs, out, { title: i.title, description: i.description, accent: i.accent, baseUrl: i.baseUrl, lang: i.lang }, !!i.full);
+ return { text: describe(docs, out, summary), structured: { kind: "build", docs, out, summary } };
+ });
+
+ tool("hc_preview", {
+ description: "Static preview of a built page for the panel (styles inlined, scripts removed).",
+ input: { out: z.string(), page: z.string().optional() }, readOnly: true, visibility: ["app"],
+ }, async (i) => {
+ const out = norm(i.out, "out");
+ const page = (i.page ?? "index.html").replace(/^\/+/, "");
+ if (!page.endsWith(".html") || page.includes("..")) throw new KitError("bad_page", "Choose an .html page of the site.");
+ let html = await ws.readText(`${out}/${page}`);
+ const css = await ws.readText(`${out}/assets/style.css`).catch(() => "");
+ const dir = page.includes("/") ? page.slice(0, page.lastIndexOf("/") + 1) : "";
+ html = html.replace(/]*>/, ``).replace(/
+
+
+
+
+