diff --git a/README.md b/README.md index c8d38743..86551113 100644 --- a/README.md +++ b/README.md @@ -59,6 +59,7 @@ The MiniMax Code Agent communicates through the host MCP client. Business reques | --- | --- | --- | | [Postman Lite](plugins/ssugarr/postman-lite/) | A lightweight local API request tool: build requests, send them through a local proxy that sidesteps browser CORS limits, and inspect responses, with collections kept as plain JSON | [ssugarr](https://github.com/ssugarr) | | [Weekly Planner](plugins/alanhean/weekly-planner/) | A local weekly planner: add tasks with a date and a priority, review them day by day, tick them off, and track the week's completion rate | [Alanhean](https://github.com/Alanhean) | +| [天气 · 新闻看板](plugins/lixiangroir-ideal/weather-news-board/) | One dashboard page for live weather, A-share and gold, silver, crude oil and Bitcoin quotes, and six switchable news columns, with precious metals always shown in CNY per gram | [lixiangroir-Ideal](https://github.com/lixiangroir-Ideal) | | [DeepSeek Chat Migration](plugins/danielwalnut/deepseek-chat-migration/) | Preview official DeepSeek web exports locally, restore branches and attachments, and import selected conversations as native MiniMax Code sessions with a bundled importer | [DanielWalnut](https://github.com/DanielWalnut) | | [OpenFilm](plugins/cristinamadureira353-svg/openfilm/) | Run OpenFilm inside MiniMax Code with the desktop interface: Studio editor, chat column and local agents, with a web-Studio fallback | [最爱双皮奶](https://github.com/cristinamadureira353-svg) | | [Dynamic Workflow Console](plugins/stevenjj33/workflow-console/) | Run and supervise MiniMax Code dynamic workflows from one page: live status, a stage-and-dependency flow graph, per-node output, approval and control, templates, and report export | [stevenjj33](https://github.com/stevenjj33) | diff --git a/README.zh-CN.md b/README.zh-CN.md index 3d158767..3178b68a 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -59,6 +59,7 @@ MiniMax Code Agent 通过宿主 MCP 客户端与 MiniApp 协作。业务请求 | --- | --- | --- | | [Postman Lite](plugins/ssugarr/postman-lite/README.zh-CN.md) | 轻量的本地 API 请求工具:构建请求、通过本地代理转发(绕过浏览器 CORS 限制)、查看响应,集合以纯 JSON 保存 | [ssugarr](https://github.com/ssugarr) | | [周计划](plugins/alanhean/weekly-planner/README.zh-CN.md) | 本地周计划:手动录入任务、日期与优先级,按天查看安排,勾选完成并跟踪本周完成率 | [Alanhean](https://github.com/Alanhean) | +| [天气 · 新闻看板](plugins/lixiangroir-ideal/weather-news-board/) | 一个看板页同时看实时天气、A 股与黄金白银原油比特币行情、六个可切换的新闻栏目,贵金属统一按人民币每克显示 | [lixiangroir-Ideal](https://github.com/lixiangroir-Ideal) | | [DeepSeek 会话迁移](plugins/danielwalnut/deepseek-chat-migration/README_ZH.md) | 在本机预览 DeepSeek 网页版官方导出包,恢复分支和附件,并用自带的导入脚本把选中对话导入成 MiniMax Code 原生会话 | [DanielWalnut](https://github.com/DanielWalnut) | | [OpenFilm](plugins/cristinamadureira353-svg/openfilm/) | 把 OpenFilm 装进 MiniMax Code:桌面版界面(Studio 编辑器 + 聊天栏 + 本地 agent),桌面模式不可用时回落网页版 | [最爱双皮奶](https://github.com/cristinamadureira353-svg) | | [动态工作流控制台](plugins/stevenjj33/workflow-console/README.zh-CN.md) | 在一个页面里运行并盯住 MiniMax Code 动态工作流:实时状态、按阶段与依赖画出的流程图、节点输出、审核与控制、模板与报告导出 | [stevenjj33](https://github.com/stevenjj33) | diff --git a/plugins/lixiangroir-ideal/weather-news-board/.minimax-plugin/plugin.json b/plugins/lixiangroir-ideal/weather-news-board/.minimax-plugin/plugin.json new file mode 100644 index 00000000..f7bcba75 --- /dev/null +++ b/plugins/lixiangroir-ideal/weather-news-board/.minimax-plugin/plugin.json @@ -0,0 +1,18 @@ +{ + "schemaVersion": 1, + "name": "weather-news-board", + "displayName": "天气 · 新闻看板", + "version": "1.0.14", + "description": "展示实时天气与国内要闻、今日头条热榜、知乎日报,支持随时手动刷新,并可自选股票与黄金、原油等国际品种行情,自选股支持按名称模糊搜索与拖动排序,新闻支持按关键词筛选。", + "author": "lixiangroir-ideal", + "icon": "icon.png", + "category": "Productivity", + "exampleQueries": [ + "打开天气新闻看板", + "在看板里加一下平安银行", + "把看板里的城市换成杭州" + ], + "apps": [], + "mcpServers": [], + "skills": [] +} diff --git a/plugins/lixiangroir-ideal/weather-news-board/LICENSE b/plugins/lixiangroir-ideal/weather-news-board/LICENSE new file mode 100644 index 00000000..02f85002 --- /dev/null +++ b/plugins/lixiangroir-ideal/weather-news-board/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 lixiangroir-ideal + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/plugins/lixiangroir-ideal/weather-news-board/README.md b/plugins/lixiangroir-ideal/weather-news-board/README.md new file mode 100644 index 00000000..3ef87e9e --- /dev/null +++ b/plugins/lixiangroir-ideal/weather-news-board/README.md @@ -0,0 +1,248 @@ +# 天气 · 新闻看板 + +A standalone Mini App that shows live weather, A-share and international commodity quotes, and six +switchable news columns in one dashboard page. + +- **实时天气** — current temperature, weather condition, apparent temperature, humidity and wind + speed, plus a three-day forecast with precipitation probability. The city can be typed in Chinese + (for example `南京`); **切换** cycles through the places that share that name. +- **自选股** — a personal watchlist of A-share codes, index names (`沪深300`, `科创50`) and + international symbols (gold, silver, crude oil, Bitcoin futures, SGE gold 9999). Prices refresh + on their own interval, separately from the weather and news interval, and the card ends with a + count of the rising, falling and unchanged entries. +- **按名称搜索** — the watchlist input also accepts a name. Typing `银行` lists 招商银行, 平安银行 + and the other matches; typing `沪深` puts 沪深300 first. The candidate list is picked with the + mouse or with the arrow keys and Enter. +- **拖动排序** — every watchlist entry carries a grip handle in its top-left corner. Drag it to move + the entry to another place in the list, in the two-column grid as well as in the narrow one. The + handle is a real button, so with it focused the arrow keys move the entry up and down. The new + order is written to the watchlist file, so it survives a reload and a restart. +- **新闻关键词筛选** — a filter field under the news tabs narrows the current column down to the + entries that mention the words you typed. Words separated by spaces are combined with "or", the + match covers the title, the summary and the source, and it does not care about case. The field is + a view preference, so the filter is still there after a reload. +- **新闻** — six tabs: 要闻, 时政, 科技, 财经, 热榜 (Toutiao hot board) and 知乎日报. The refresh + button in the top bar re-fetches the selected column right away, skipping the 60-second server + cache. + +The whole page reacts to the width of its container rather than to the window size, so it looks the +same whether it is opened in a narrow side panel or on a wide screen. The watchlist is laid out as a +grid that reflows to the available width, so every entry stays on screen instead of pushing the rest +below the fold. + +Each card carries its own resize handle in its bottom-right corner. Drag it to set that one card's +width and height: the weather card can be made narrow and short while the watchlist card stays wide, +and every size is remembered separately. The current size is shown while dragging, the content +scrolls inside a card whose height was set by hand, clicking a handle restores that single card to +the automatic size, and a **reset** button in the top bar puts every card back. When the weather +card and the watchlist card sit side by side and neither was sized by hand, they keep the same +height and the space that frees up is filled row by row with the hourly forecast. The three-column +layout applies the same rule explicitly, and there the two cards end up exactly as tall as the +taller of the two. Sizes restored from the browser storage are clamped to the current container, so +a size saved on a wide screen can never squash a card on a narrow one. The cards that share a row are kept inside the container as well: when their widths no longer fit, the overflow is taken back proportionally, so equally wide cards shrink evenly instead of one of them always giving way first, and while a card is being dragged its neighbour gives way instead of letting the board run past the edge. The size shown while dragging is the size that is actually applied. + +Each card carries a focus button in its header: it hides the other two and gives that card the +whole board, and the same button — or **Exit focus** in the top bar — brings the full board back. + +While a card is being resized, every card that shares its row shows the width range it can still +take, so it is visible when a neighbour has already given everything it can. The size badge shows +the same range next to the current size. + +The resize handle is a real button: with it focused, the arrow keys change the width and the +height of that card — Shift makes the step larger — and Home puts the card back to its automatic +size. + +Precious metals are always shown in **CNY per gram**. The raw USD-per-ounce quote and the FX rate +used for the conversion are kept in the row's tooltip, so the displayed number and the source +figure can be compared. + +The board also keeps working while its own service is still coming up. The Host stops the Mini App +process whenever the page is hidden, so a page that is brought back to the front can find the +service gone. A request that cannot reach the service — no response at all, or a response that is +not JSON — is retried with a growing backoff of 0.4 s, 0.8 s, 1.6 s, 3.2 s, 6.4 s and 10 s, and +the title bar shows how long the next attempt will take. A request that does reach the service but +fails because of an upstream source is not retried, so a broken source never looks like a broken +service. Once the retries are used up the title bar says the service is not ready, and the next +automatic refresh picks the board up again. Adding or removing a watchlist entry is retried the +same way, which is safe because both operations are idempotent on the server. + +The name search runs against the market's public search endpoint, not against a downloaded list. +One request returns the candidates for what was typed, and the names it finds are written to +`security-index.json` in the Host-provided data directory, so a name that was looked up before is +matched locally and offline. Downloading the whole market list was the obvious alternative, but +that takes close to a hundred pages of requests, and the upstream drops the connection after that +much traffic — and once it does, the quote endpoint the dashboard itself uses stops answering as +well. One request per search cannot do that. The upstream address is fixed: one path, a fixed set +of query parameters, and only the code, the name and the kind of each match are kept. The user +input is never forwarded anywhere else. A name is matched as a substring, and the candidates are +ordered by an exact name first, then a name prefix, then a name substring, with everything else +keeping the upstream order. When the upstream is unreachable the search falls back to the locally +known names and the built-in index and ETF names, so the input keeps working. + +The reorder is sent to the server as a new order for the list that is already there, and the server +only accepts a permutation of it: the same entries, none of them twice, and nothing that is not +already in the watchlist. The reorder endpoint therefore cannot be used to add or remove entries +behind the allow list, and `tests/watchlist-order.test.mjs` pins that down. The drag itself is built +on pointer events instead of the HTML5 drag-and-drop API, because the panel the Mini App runs in +does not reliably deliver those; the move, the release and the cancel listeners sit on the window, so +the drag keeps following the pointer when it leaves the card. If the server refuses the new order, +the list is rendered again from the order the server still holds, so the board and the stored +watchlist cannot drift apart. + +The news filter runs entirely in the page. The column is fetched exactly as before and the filter +only decides which of those entries are shown, so it never asks the upstream for less and never +makes it answer more often. The matching rules live in their own ` + + + + + + + diff --git a/plugins/lixiangroir-ideal/weather-news-board/miniapp/miniapp.json b/plugins/lixiangroir-ideal/weather-news-board/miniapp/miniapp.json new file mode 100644 index 00000000..498d880a --- /dev/null +++ b/plugins/lixiangroir-ideal/weather-news-board/miniapp/miniapp.json @@ -0,0 +1,20 @@ +{ + "schemaVersion": 1, + "artifacts": { + "client": [ + "./miniapp/client" + ], + "node": [ + "./miniapp/node" + ] + }, + "runtime": { + "kind": "process", + "entry": "./miniapp/node/server.mjs", + "lifecycle": "on-demand" + }, + "surface": { + "path": "/dashboard" + }, + "mcpEndpoints": [] +} diff --git a/plugins/lixiangroir-ideal/weather-news-board/miniapp/node/miniapp-api.ts b/plugins/lixiangroir-ideal/weather-news-board/miniapp/node/miniapp-api.ts new file mode 100644 index 00000000..5276c6f8 --- /dev/null +++ b/plugins/lixiangroir-ideal/weather-news-board/miniapp/node/miniapp-api.ts @@ -0,0 +1,641 @@ +/** + * Agent-facing Mini App runtime authoring declarations. + * + * Copy this file into a generated plugin for type checking. It contains no Host implementation; + * the Host injects runtime values through start(context). + * Keep the .ts filename: Electron packaging excludes .d.ts files from dependency assets. + */ +export type JsonPrimitive = null | boolean | number | string; +export type JsonValue = JsonPrimitive | JsonObject | readonly JsonValue[]; +export type JsonObject = { readonly [key: string]: JsonValue }; + +declare const HOST_CONNECTOR_TOOL_REF: unique symbol; +export type HostConnectorToolRef = string & { + readonly [HOST_CONNECTOR_TOOL_REF]: 'HostConnectorToolRef'; +}; + +export interface HostConnectorTool { + readonly toolRef: HostConnectorToolRef; + readonly provider: string; + readonly name: string; + readonly description?: string; + readonly inputSchema: JsonValue; + readonly outputSchema?: JsonValue; +} + +export interface HostConnectorListResult { + readonly tools: readonly HostConnectorTool[]; + readonly partial: boolean; +} + +export interface HostConnectorCallOptions { + readonly signal?: AbortSignal; +} + +export interface HostConnectorCallResult { + readonly invocationId: string; + /** + * Raw provider result; it is not normalized by the Host and may be an object, array, or primitive. + * A single text-block array is one provider shape, not a global Host transport contract. + * Decode only a probe-observed envelope; preserve every other value, including direct strings. + */ + readonly value: JsonValue; +} + +export interface HostConnectorClient { + /** Candidate-safe inventory only; available before and after activation. */ + list(options?: HostConnectorCallOptions): Promise; + /** Activation-only business dispatch; call from request handling, never start(context). */ + call( + toolRef: HostConnectorToolRef, + arguments_: JsonObject, + options?: HostConnectorCallOptions, + ): Promise; +} + +export type HostConnectorErrorDisposition = + | 'not_dispatched' + | 'provider_reported' + | 'unknown_after_dispatch'; + +export type HostConnectorErrorCode = + | 'TOOL_REF_STALE' + | 'SERVICE_RESTARTED' + | 'REQUEST_CANCELLED' + | 'CONNECTOR_TIMEOUT' + | 'INVALID_ARGUMENTS' + | 'CONNECTOR_PROVIDER_ERROR' + | 'CONNECTOR_UNAVAILABLE' + /** The user switched this provider off for the Mini App; not dispatched. */ + | 'CONNECTOR_NOT_PERMITTED' + | 'CONNECTOR_OUTCOME_UNKNOWN'; + +export interface HostConnectorError extends Error { + readonly code: HostConnectorErrorCode; + readonly disposition: HostConnectorErrorDisposition; + readonly retryable: boolean; + readonly invocationId?: string; + readonly diagnostic?: { + readonly issues: readonly { + readonly path: string; + readonly constraint: string; + readonly limit?: number; + }[]; + }; +} + +/** What a call would meet now under the user's global permission rules; informational only. */ +export type MiniAppToolPermission = 'allow' | 'ask' | 'deny'; + +/** + * `name` is the runtime name an Agent sees (`mcp____`, `connector____`). + * Take it from `list()`; do not build it. + */ +export type MiniAppTool = + | { + readonly name: string; + readonly kind: 'connector'; + readonly provider: string; + readonly tool: string; + readonly description?: string; + readonly inputSchema: JsonValue; + readonly permission: MiniAppToolPermission; + } + | { + readonly name: string; + readonly kind: 'mcp'; + /** Any installed MCP server: a Plugin's, the user's `mcp.json`, or a Host built-in one. */ + readonly server: string; + readonly tool: string; + readonly description?: string; + readonly inputSchema: JsonValue; + readonly permission: MiniAppToolPermission; + }; + +export interface MiniAppToolListResult { + readonly tools: readonly MiniAppTool[]; + /** A source could not be listed; the listed tools are still callable. */ + readonly partial: boolean; +} + +export type MiniAppToolCallResult = + | { + readonly invocationId: string; + readonly kind: 'connector'; + /** Raw provider result, as in `HostConnectorCallResult.value`. */ + readonly value: JsonValue; + } + | { + readonly invocationId: string; + readonly kind: 'mcp'; + /** The MCP tool reported its own failure; `content` keeps its error text. */ + readonly isError: boolean; + /** MCP content blocks such as `{ type: 'text', text }`, passed through as JSON. */ + readonly content: readonly JsonValue[]; + readonly structuredContent?: JsonObject; + }; + +/** + * Thrown with the `HostConnectorError` shape; Connector tools keep their Connector codes too. The + * code names the cause; `disposition` alone says whether the tool may have run (`TOOL_TIMEOUT` and + * `REQUEST_CANCELLED` can be either `not_dispatched` or `unknown_after_dispatch`). + */ +export type MiniAppToolErrorCode = + | HostConnectorErrorCode + | 'INVALID_ARGUMENTS' + | 'TOOL_NOT_PERMITTED' + | 'TOOL_APPROVAL_REQUIRED' + | 'TOOL_REF_STALE' + | 'TOOL_UNAVAILABLE' + | 'TOOL_TIMEOUT' + | 'TOOL_RESULT_TOO_LARGE' + | 'TOOL_OUTCOME_UNKNOWN' + | 'MCP_SERVER_UNAVAILABLE' + | 'REQUEST_CANCELLED' + | 'SERVICE_RESTARTED'; + +/** + * Present whenever the manifest declares `"toolAccess": ["call"]`, even when the user switched + * `tool:call` off: calls then fail with `TOOL_NOT_PERMITTED`. Every `call` is judged by the user's + * global permission rules: `deny` is `TOOL_NOT_PERMITTED`, `ask` shows a Host prompt, and nobody to + * ask is `TOOL_APPROVAL_REQUIRED`. `list` works before activation; call `call` only from request + * handling after activation. Connector tools time out after 30 s and MCP tools after at most 120 s, + * counted after any prompt. The Host never retries; reconcile an `unknown_after_dispatch` outcome + * before repeating a write. + */ +export interface MiniAppToolClient { + list(options?: HostConnectorCallOptions): Promise; + call( + name: string, + arguments_: JsonObject, + options?: HostConnectorCallOptions, + ): Promise; + /** + * One Host prompt for the named tools (1–10, from `list()`) still at `ask`; the user ticks which + * to always allow. Resolves every name's state afterwards (for your UI only). When nobody can be + * asked it rejects with `TOOL_APPROVAL_REQUIRED` whose error carries `permissions`. With + * `tool:call` switched off it answers `deny` for every name without a prompt. + * Needs `capabilities.has('tool.request')`. + */ + request( + names: readonly string[], + options?: HostConnectorCallOptions, + ): Promise>; +} + +export interface MiniAppLogger { + debug(message: string, fields?: JsonObject): void; + info(message: string, fields?: JsonObject): void; + warn(message: string, fields?: JsonObject): void; + error(message: string, fields?: JsonObject): void; +} + +/** + * How the call's text ended: in its own turn (`finished` / `error` / `aborted`), or, only with + * `whenBusy`, joined into the turn that was already running (`steered`; that turn's own + * call gets the reply). + */ +export type MiniAppAgentRunStatus = 'finished' | 'error' | 'aborted' | 'steered'; + +/** + * The Desktop composer's follow-up behaviours while a session runs a turn. `queue`: the text runs + * as the next turn and the call follows it. `steer`: the running turn reads the text at its next + * input point (the call resolves `steered`), or, if it answered first, the text runs as the next + * turn and the call follows it. + */ +export type MiniAppAgentWhenBusy = 'queue' | 'steer'; + +export type MiniAppAgentQuestionMode = 'questionnaire' | 'feature-enable' | 'plan'; + +export interface MiniAppAgentQuestionOption { + readonly id: string; + readonly label: string; + readonly description?: string; +} + +export interface MiniAppAgentQuestionStep { + readonly id: string; + readonly header?: string; + readonly question: string; + readonly description?: string; + readonly selectionMode: 'single' | 'multiple'; + readonly options: readonly MiniAppAgentQuestionOption[]; + /** Free-text "other" is always accepted; see `MiniAppAgentQuestionAnswer.otherText`. */ + readonly allowOther: true; +} + +/** Same questionnaire the Host chat renders; render every step and answer each one. */ +export interface MiniAppAgentQuestionnaire { + readonly schemaVersion: 2; + readonly id: string; + readonly title?: string; + readonly steps: readonly MiniAppAgentQuestionStep[]; + readonly mode?: MiniAppAgentQuestionMode; + /** Plan review Markdown and other mode-specific data. */ + readonly modePayload?: JsonObject; + /** Unix ms; the request is withdrawn after this. */ + readonly expiresAt?: number; +} + +export interface MiniAppAgentQuestionAnswer { + readonly stepId: string; + readonly selectedOptionIds: readonly string[]; + readonly selectedOther: boolean; + readonly otherText?: string; + readonly skipped?: boolean; +} + +/** A model as the Host's composer selects it; take the values from `models()`. */ +export interface MiniAppAgentModelSelection { + readonly providerId: string; + readonly modelId: string; + /** `''` means thinking is off; it is preserved, distinct from an absent `variant`. */ + readonly variant?: string; + readonly thinking?: { readonly effort: string }; +} + +/** One model this user can use. */ +export interface MiniAppAgentModelOption { + readonly providerId: string; + readonly modelId: string; + readonly displayName: string; + readonly variants?: readonly string[]; + readonly thinking?: { readonly efforts: readonly string[]; readonly default?: string }; +} + +export interface MiniAppAgentModels { + readonly models: readonly MiniAppAgentModelOption[]; + /** What a Node-created session starts with. */ + readonly default: MiniAppAgentModelSelection; +} + +export interface MiniAppAgentAgentOption { + /** Canonical name; what `agent` takes. */ + readonly name: string; + readonly displayName: string; + /** The default agent. */ + readonly primary: boolean; +} + +export interface MiniAppAgentAgents { + readonly agents: readonly MiniAppAgentAgentOption[]; +} + +export interface MiniAppAgentRunResult { + /** Pass back in `run({ sessionId })` to continue the same conversation. */ + readonly sessionId: string; + /** Absent when no turn ran: an `answer` accepted without starting a continuation. */ + readonly turnId?: string; + /** The model the turn was dispatched with; absent when no turn ran or the text was steered. */ + readonly model?: MiniAppAgentModelSelection; + /** `aborted` only when the Host confirmed the abort; an unconfirmed one rejects with `AGENT_OUTCOME_UNKNOWN`. */ + readonly status: MiniAppAgentRunStatus; + /** Final assistant reply; absent when the turn produced none or did not finish. */ + readonly text?: string; + readonly error?: { readonly code: string; readonly message: string }; + /** Set when the turn ended waiting on a questionnaire; render `request` and continue with `agent.answer`. */ + readonly pendingQuestion?: { + readonly requestId: string; + readonly mode: MiniAppAgentQuestionMode; + readonly request: MiniAppAgentQuestionnaire; + }; +} + +/** + * Progress of one run. `turnId` matches the result's, except that a `permission.requested` raised + * by a delegated child session carries that child's own `sessionId` and `turnId`; `reply` with + * those, and do not filter events by the root turn. Ignore unknown `type` values: new event + * types may be added without notice. + * - `run.queued`: the call waits at 1-based `position`, for a run slot or, with + * `whenBusy: 'queue'`, in the session queue (a `whenBusy` call can get both); sent before the + * turn starts, so it has no `turnId` and names a session only when continuing one. + * - `message.pending` / `message.steered`: with `whenBusy: 'steer'`, the text was handed to the + * running turn, then read by it; `message.steered` is the call's last event. + * - `turn.started`: the Agent began the turn; `model` is the model it was dispatched with. + * - `text.delta`: a piece of the reply as it streams. + * - `message.committed`: one complete assistant message (a turn can have several). + * - `tool.started` / `tool.finished`: a tool call by name; `ok` is false when it failed. + * - `turn.finished`: last unless the call ended `steered`; same `status`, `text`, and `error` + * as the run result. + */ +/** + * Every event except `run.queued` names its session, so `reply` can be called from `onEvent` even + * before the `run` that created the session has returned. `answer` cannot: the paused `run` still holds the + * session's single-run slot while `question.requested` is delivered, so call `answer` only after + * that `run` resolves (an earlier call rejects with `BUSY`). Ignore event types you do not know. + */ +export type MiniAppAgentRunEvent = + | { readonly type: 'run.queued'; readonly sessionId?: string; readonly position: number } + | { + readonly type: 'message.pending' | 'message.steered'; + readonly sessionId: string; + readonly turnId: string; + } + | { + readonly type: 'turn.started'; + readonly sessionId: string; + readonly turnId: string; + readonly model: MiniAppAgentModelSelection; + } + | { + readonly type: 'text.delta'; + readonly sessionId: string; + readonly turnId: string; + readonly text: string; + } + | { + readonly type: 'message.committed'; + readonly sessionId: string; + readonly turnId: string; + readonly text: string; + } + | { + readonly type: 'tool.started'; + readonly sessionId: string; + readonly turnId: string; + readonly name: string; + } + | { + readonly type: 'tool.finished'; + readonly sessionId: string; + readonly turnId: string; + readonly name: string; + readonly ok: boolean; + } + /** A tool call is waiting for approval; decide it with `agent.reply`. */ + | { + readonly type: 'permission.requested'; + readonly sessionId: string; + /** Absent when the runtime did not attribute the ask to a turn. */ + readonly turnId?: string; + readonly requestId: string; + readonly toolName: string; + readonly toolInput?: string; + readonly reason: string; + } + /** The turn paused on a questionnaire; continue with `agent.answer`. */ + | { + readonly type: 'question.requested'; + readonly sessionId: string; + readonly turnId?: string; + readonly requestId: string; + readonly mode: MiniAppAgentQuestionMode; + readonly request: MiniAppAgentQuestionnaire; + } + | { + readonly type: 'turn.finished'; + readonly sessionId: string; + readonly turnId: string; + readonly status: Exclude; + readonly text?: string; + readonly error?: { readonly code: string; readonly message: string }; + }; + +/** `observe({ all: true })` only: the conversation's title, when it has one. */ +interface MiniAppAgentObservedTitle { + readonly title?: string; +} + +type MiniAppAgentRunEventOf = Extract< + MiniAppAgentRunEvent, + { readonly type: T } +>; + +/** + * What an observer receives: the run events without `run.queued` and without asks, which reach + * only the run that owns them. `turn.started.model` is present only when the Host could read it. + * Ignore unknown `type` values. + */ +export type MiniAppAgentObservedEvent = + | (Omit, 'model'> & { + readonly model?: MiniAppAgentModelSelection; + } & MiniAppAgentObservedTitle) + | MiniAppAgentRunEventOf<'text.delta' | 'tool.started' | 'tool.finished'> + | (MiniAppAgentRunEventOf<'message.committed'> & MiniAppAgentObservedTitle) + | (MiniAppAgentRunEventOf<'turn.finished'> & MiniAppAgentObservedTitle); + +/** + * `{ all: true }`: `turn.started`, `message.committed` (the final reply) and `turn.finished` of + * every user conversation, with its `title`. `{ sessionId }`: every progress event of that + * session, turn after turn. Exactly one of the two. + */ +export type MiniAppAgentObserveTarget = { readonly sessionId: string } | { readonly all: true }; + +/** One of the user's conversations; `running` while a turn is in flight. */ +export interface MiniAppAgentSessionSummary { + readonly sessionId: string; + readonly title?: string; + /** The Agent the session runs. */ + readonly agent: string; + readonly status: 'idle' | 'running' | 'error' | 'aborted'; + /** The conversation's project directory (absolute) as recorded; it may no longer exist. */ + readonly workspaceDir: string; + /** True when the conversation has no project and runs in the default workspace. */ + readonly isDefaultWorkspace: boolean; + /** Unix ms. */ + readonly createdAtMs: number; + /** Unix ms. */ + readonly updatedAtMs: number; +} + +export interface MiniAppAgentSessionDetail extends MiniAppAgentSessionSummary { + /** The conversation's current model; absent when the Host has none recorded. */ + readonly model?: MiniAppAgentModelSelection; + /** Only while `status` is `error` and the Host recorded a message. */ + readonly error?: { readonly message: string }; + /** Final text of the latest Agent reply, if any. */ + readonly lastAssistantText?: string; +} + +export interface MiniAppAgentSessions { + /** The 50 most recently updated user conversations (no Mini App, scheduled or sub-Agent ones). */ + readonly sessions: readonly MiniAppAgentSessionSummary[]; +} + +export interface MiniAppAgentRunOptions { + readonly signal?: AbortSignal; + readonly onEvent?: (event: MiniAppAgentRunEvent) => void; +} + +export type MiniAppAgentErrorCode = + | 'NOT_PERMITTED' + | 'BUSY' + | 'SESSION_NOT_FOUND' + | 'INVALID_ARGUMENTS' + | 'AGENT_UNAVAILABLE' + | 'REQUEST_CANCELLED' + | 'AGENT_OUTCOME_UNKNOWN' + | 'REQUEST_NOT_FOUND'; + +export interface MiniAppAgentError extends Error { + readonly code: MiniAppAgentErrorCode; + /** + * True when nothing was started and the same call may be retried later. + * `AGENT_OUTCOME_UNKNOWN` is never retryable: the turn may have run. + */ + readonly retryable: boolean; + /** + * Set on every `BUSY`: the session is running a turn, compacting, or has messages queued ahead + * (the text reached no turn), the wait queue is full, the per-minute start cap was hit, or + * `observe` found 4 observers already running. + */ + readonly reason?: 'session_busy' | 'queue_full' | 'rate_limited' | 'observer_limit'; +} + +/** + * Present when the manifest declares `agentAccess` (`"session.run"` and/or `"session.read"`). + * `run` / `reply` / `answer` / `models` / `agents` / `create` need `session.run`; `observe` and + * `sessions` need `session.read` except for this Mini App's own sessions (see + * agent-interaction.md). + * A new Node session uses the primary Agent unless `agent` names one from `agents()`, and works in + * this Mini App's own Agent directory and on the runtime default model; + * continuing a session keeps its Agent, directory and model (unless `model` switches it), including + * one a page created using its host chat's Agent, project directory and model; a session never + * changes its Agent. Runs one turn with that Agent's full capabilities + * (files, shell, Skills, MCP including this Mini App's own), and resolves when the turn ends. + * + * Interaction is yours to render: pass `onEvent` and handle `permission.requested` with + * `reply` and `question.requested` with `answer`. A permission request waits only while + * someone can answer it: this run passed `onEvent`, or a page of this Mini App currently has + * the session open in a chat side panel via `open`. Otherwise it is denied (the model is told + * why), and a questionnaire ends the turn with `result.pendingQuestion`. A run waiting on a + * permission is released by `cancel`/abort, process exit or republish. Up to `agentConcurrency` + * runs (default 4) per Mini App run at once; further `run` / `answer` calls wait in order (up to + * four times that many, see `run.queued`), and aborting a waiting call rejects it with + * `REQUEST_CANCELLED`. A `whenBusy` call on a session that already has a call in flight shares + * that call's slot. Cancelling a queued `whenBusy` text removes it (`REQUEST_CANCELLED`); a steered + * text cannot be withdrawn (`AGENT_OUTCOME_UNKNOWN`, the running turn goes on). + */ +export interface MiniAppAgentClient { + run( + input: { + readonly text: string; + readonly sessionId?: string; + /** + * Switch the session to this model before the turn (validated like the composer validates a + * new session's model: it must be one `models()` lists; unusable is `INVALID_ARGUMENTS`, + * missing BYOK credentials end the turn with `status: 'error'`); the session keeps it. Omit to use the session's current model. + */ + readonly model?: MiniAppAgentModelSelection; + /** + * Only when starting a session (no `sessionId`): an agent `name` from `agents()`. Passing it + * with `sessionId` is `INVALID_ARGUMENTS`. + */ + readonly agent?: string; + /** + * Only with `sessionId`: what to do when that session is already running a turn; on an idle + * session the call starts a turn as usual. Omit to reject with `BUSY` (`session_busy`). + */ + readonly whenBusy?: MiniAppAgentWhenBusy; + }, + options?: MiniAppAgentRunOptions, + ): Promise; + /** + * Decide a pending permission request. Never writes the user's global rules. Node replies + * have 16 separate pending slots; `run` / `answer` / `models` / `agents` / `create` and Connector + * requests share another 16. Filling that ordinary budget still permits replies. A full reply + * budget rejects with retryable `AGENT_UNAVAILABLE`. + */ + reply(input: { + readonly sessionId: string; + readonly requestId: string; + readonly decision: 'allowOnce' | 'deny'; + }): Promise; + /** + * Answer a questionnaire; the continuation turn is observed like `run`. Rejects with + * `AGENT_OUTCOME_UNKNOWN` when the answer was recorded but the continuation turn was not observed. + */ + answer( + input: { + readonly sessionId: string; + readonly requestId: string; + readonly answers: readonly MiniAppAgentQuestionAnswer[]; + /** Same as `run`'s `model`, applied before the continuation turn. */ + readonly model?: MiniAppAgentModelSelection; + }, + options?: MiniAppAgentRunOptions, + ): Promise; + /** + * Returns the model catalog and runtime `default`. Pass `default` directly as `model` to + * `run` / `answer`. For a catalog entry, extract `providerId` / `modelId`, add a selected `variant` + * if needed and preserve `variant: ''`. If thinking is supported, select an effort from + * `thinking.efforts` and pass `thinking: { effort }`. + */ + models(): Promise; + /** The agents the user has configured; `agent` of `create` / a first `run` must be one of them. */ + agents(): Promise; + /** + * Create a session (agent, this Mini App's Agent directory, the runtime default model) without + * running a turn, and return its `sessionId`; continue it with `run({ sessionId })`. A page's + * `create` binds the session to its chat instead, and its `sessionId` can be continued here. + * Takes no Host run slot but uses the ordinary Node request budget. `agent` picks the session's + * agent from `agents()`; a session never changes it. + */ + create(input?: { readonly agent?: string }): Promise<{ readonly sessionId: string }>; + /** + * Watch the user's Agent at work (see `MiniAppAgentObserveTarget`). No request timeout; abort + * `signal` to stop, after which `onEvent` gets nothing more. Resolves when the subscription + * ended: `signal` aborted, the session was deleted, the process is stopping or being replaced, + * or `session.read` was switched off. + * Rejects with a `MiniAppAgentError` when it could not start or failed: `INVALID_ARGUMENTS` (not + * exactly one target), `NOT_PERMITTED`, `SESSION_NOT_FOUND`, retryable `BUSY` past 4 observers + * per Mini App (`reason: 'observer_limit'`) or `AGENT_UNAVAILABLE`. Observers use no run slots + * and no ordinary request budget. Check `context.capabilities?.has('agent.observe')` first. + */ + observe( + target: MiniAppAgentObserveTarget, + options: { + readonly onEvent: (event: MiniAppAgentObservedEvent) => void; + readonly signal?: AbortSignal; + }, + ): Promise; + /** Check `context.capabilities?.has('agent.sessions')` first. */ + sessions(): Promise; + /** + * One conversation with its model and latest reply. `sessionId` is required: Node serves every + * tab, so it has no current chat; a page passes its chat's id (from its own `session()`). + * Check `context.capabilities?.has('agent.session')`. + */ + session(sessionId: string): Promise; +} + +export interface MiniAppLifecycle { + dispose(): void | Promise; +} + +export interface MiniAppContext { + readonly pluginId: string; + readonly pluginRoot: string; + readonly dataDir: string; + readonly listen: Readonly<{ readonly host: '127.0.0.1'; readonly port: number }>; + readonly signal: AbortSignal; + readonly logger: MiniAppLogger; + /** + * Synchronous probe of Host features, fixed per Host version. It says nothing about this + * Mini App's manifest or authorization: `has('agent.run')` is true on a Host that supports the + * Agent API even when `context.agent` is absent because `agentAccess` was not declared. + * Older Hosts do not inject `capabilities`; check `context.capabilities?.has(...)`. + */ + readonly capabilities?: MiniAppHostCapabilities; + /** + * Present when the manifest declares a `hostConnectorAccess` provider; a provider the user + * switched off is missing from `list()` and its calls fail with `CONNECTOR_NOT_PERMITTED`. + */ + readonly hostConnector?: HostConnectorClient; + /** Installed MCP and Connector tools, each call judged by the user's permission rules. */ + readonly tool?: MiniAppToolClient; + /** + * Present when the manifest declares `agentAccess: ["session.run"]`; while the user has it + * switched off, calls fail with `NOT_PERMITTED`. + */ + readonly agent?: MiniAppAgentClient; +} + +export interface MiniAppHostCapabilities { + has(name: string): boolean; +} + +export interface MiniAppModule { + /** Resolve only after the listener accepts connections and every route is installed. */ + start(context: MiniAppContext): Promise; +} diff --git a/plugins/lixiangroir-ideal/weather-news-board/miniapp/node/security-aliases.mjs b/plugins/lixiangroir-ideal/weather-news-board/miniapp/node/security-aliases.mjs new file mode 100644 index 00000000..d3dc04e9 --- /dev/null +++ b/plugins/lixiangroir-ideal/weather-news-board/miniapp/node/security-aliases.mjs @@ -0,0 +1,51 @@ +/** + * 指数与常见 ETF 的名称别名。 + * + * 指数代码不能靠 6 位数字推市场:000001 在深市是平安银行,在沪市才是上证指数; + * 000300、000688 这些同理。所以这里把市场前缀显式写出来,用户直接打名称即可。 + * + * ETF 走 6 位数字就够了(510xxx / 588xxx 在沪市,159xxx / 15xxxx 在深市), + * 这里只收最常被提到的那几只,作为「名称 → 代码」的快捷方式。 + */ + +/** @type {Record} */ +export const SECURITY_ALIASES = { + // 指数 + 上证指数: 'sh000001', + 上证综指: 'sh000001', + 沪指: 'sh000001', + 深证成指: 'sz399001', + 深成指: 'sz399001', + 沪深300: 'sh000300', + 上证50: 'sh000016', + 中证500: 'sh000905', + 中证1000: 'sh000852', + 创业板指: 'sz399006', + 创业板: 'sz399006', + 创业板50: 'sz399673', + 科创50: 'sh000688', + 北证50: 'bj899050', + // ETF + 沪深300ETF: 'sh510300', + 上证50ETF: 'sh510050', + 创业板ETF: 'sz159915', + 科创50ETF: 'sh588000', + 证券ETF: 'sh512880', + 中概互联网ETF: 'sh513050', +}; + +/** @type {Map} */ +const LOOKUP = new Map( + Object.entries(SECURITY_ALIASES).map(([name, code]) => [name.toLowerCase(), code]), +); + +/** + * 名称 → 带市场前缀的代码。大小写不敏感,忽略中间空白。 + * @param {string} text + * @returns {string|null} + */ +export function resolveSecurityAlias(text) { + const value = String(text ?? '').replace(/\s+/g, '').toLowerCase(); + if (!value) return null; + return LOOKUP.get(value) ?? null; +} diff --git a/plugins/lixiangroir-ideal/weather-news-board/miniapp/node/security-index.mjs b/plugins/lixiangroir-ideal/weather-news-board/miniapp/node/security-index.mjs new file mode 100644 index 00000000..fc20867f --- /dev/null +++ b/plugins/lixiangroir-ideal/weather-news-board/miniapp/node/security-index.mjs @@ -0,0 +1,277 @@ +// @ts-check + +/** + * 证券名称搜索。 + * + * 自选股除了 6 位代码和静态别名,也支持按名称模糊搜索(“平安银行”“沪深”“科创”)。 + * 名称检索走东方财富的公开搜索接口,一次请求就能拿到候选; + * 查到的名称会写进本机缓存(context.dataDir),下次直接命中本地,离线也能搜到搜过的名字。 + * + * 为什么不用“拉一份全市场清单再本地匹配”: + * 全市场清单要连续翻将近一百页,而上游对这种密集请求会直接掐连接, + * 被掐之后连看板自己的行情接口也会一起取不到数。名称检索一次只发一个请求, + * 既快又不会拖累行情。 + * + * 安全边界: + * - 只有一个固定地址,用户输入只作为 input 参数,不接受任何其他外部地址; + * - 响应只取代码、名称、品种三项,不转发上游返回的其他字段; + * - 上游不可用时退回本地缓存和内置别名表,功能不中断。 + */ + +import { mkdir, readFile, rename, writeFile } from 'node:fs/promises'; +import { join } from 'node:path'; +import dns from 'node:dns'; + +import { SECURITY_ALIASES } from './security-aliases.mjs'; + +/* 这台机器上行情与搜索主机的 IPv6 链路经常被中途重置,优先走 IPv4。 */ +dns.setDefaultResultOrder('ipv4first'); + +const SUGGEST_ENDPOINT = 'https://searchapi.eastmoney.com/api/suggest/get'; +const SUGGEST_TYPE = '14'; +const SUGGEST_TIMEOUT = 8000; +const CACHE_LIMIT = 2000; + +/** + * @typedef {{code: string, name: string, kind: 'stock' | 'etf' | 'index'}} SecurityEntry + */ + +/** 上游的品种分类 → 本包的种类。板块、美股、港股、开放式基金都不收。 */ +const KIND_BY_CLASSIFY = { + AStock: 'stock', + BStock: 'stock', + Fund: 'etf', + Index: 'index', +}; + +/** + * 归一化查询串:去空白、转小写。 + * @param {string} query + * @returns {string} + */ +export function normalizeQuery(query) { + return String(query ?? '') + .trim() + .replace(/\s+/g, '') + .toLowerCase(); +} + +/** + * 把搜索接口的响应整理成候选条目。 + * + * 只保留个股、ETF 与指数:板块(BK)、美股、港股和开放式基金都跳过; + * 新三板(NEEQ)里只有 920 段是北证 A 股,其余是挂牌公司,取不到行情。 + * + * @param {any} payload + * @returns {SecurityEntry[]} + */ +export function parseSuggestEntries(payload) { + const rows = payload?.QuotationCodeTable?.Data; + if (!Array.isArray(rows)) return []; + const entries = []; + const seenCodes = new Set(); + const seenNames = new Set(); + for (const row of rows) { + const quoteId = String(row?.QuoteID ?? ''); + const dot = quoteId.indexOf('.'); + if (dot < 0) continue; + const market = quoteId.slice(0, dot); + const digits = quoteId.slice(dot + 1); + if (!/^[0-9]{6}$/.test(digits)) continue; + const name = String(row?.Name ?? '').trim(); + if (!name) continue; + const classify = String(row?.Classify ?? ''); + /** @type {string} */ + let prefix; + /** @type {'stock' | 'etf' | 'index'} */ + let kind; + if (classify === 'NEEQ') { + if (!digits.startsWith('92')) continue; + kind = 'stock'; + prefix = 'bj'; + } else { + const mapped = KIND_BY_CLASSIFY[classify]; + if (!mapped) continue; + kind = mapped; + prefix = market === '1' ? 'sh' : 'sz'; + } + const code = `${prefix}${digits}`; + if (seenCodes.has(code) || seenNames.has(name)) continue; + seenCodes.add(code); + seenNames.add(name); + entries.push({ code, name, kind }); + } + return entries; +} + +/** + * 给候选排序:名称完全相同 → 名称前缀 → 名称包含 → 其余(拼音命中等)保持上游顺序。 + * @param {SecurityEntry[]} entries + * @param {string} query + * @param {number} [limit] + * @returns {SecurityEntry[]} + */ +export function rankSuggestEntries(entries, query, limit = 12) { + const q = normalizeQuery(query); + const scored = (entries ?? []).map((entry, index) => { + const name = normalizeQuery(entry.name); + let score = 3; + if (q && name === q) score = 0; + else if (q && name.startsWith(q)) score = 1; + else if (q && name.includes(q)) score = 2; + return { entry, score, index }; + }); + scored.sort((a, b) => (a.score !== b.score ? a.score - b.score : a.index - b.index)); + return scored.slice(0, limit).map((item) => item.entry); +} + +/** + * 在本地缓存里做名称模糊匹配。 + * @param {SecurityEntry[]} entries + * @param {string} query + * @param {number} [limit] + * @returns {SecurityEntry[]} + */ +export function matchCachedEntries(entries, query, limit = 12) { + const q = normalizeQuery(query); + if (!q) return []; + const scored = []; + for (const entry of entries ?? []) { + const name = normalizeQuery(entry.name); + let score = -1; + if (name === q) score = 0; + else if (name.startsWith(q)) score = 1; + else if (name.includes(q)) score = 2; + if (score < 0) continue; + scored.push({ entry, score, length: entry.name.length, code: entry.code }); + } + scored.sort((a, b) => { + if (a.score !== b.score) return a.score - b.score; + if (a.length !== b.length) return a.length - b.length; + return a.code < b.code ? -1 : 1; + }); + return scored.slice(0, limit).map((item) => item.entry); +} + +/** + * 静态别名表的模糊匹配,作为最后一道兜底。 + * @param {string} query + * @param {number} [limit] + * @returns {SecurityEntry[]} + */ +export function searchSecurityAliases(query, limit = 12) { + const q = normalizeQuery(query); + if (!q) return []; + const scored = []; + for (const [name, code] of Object.entries(SECURITY_ALIASES)) { + const lower = normalizeQuery(name); + let score = -1; + if (lower === q) score = 0; + else if (lower.startsWith(q)) score = 1; + else if (lower.includes(q)) score = 2; + if (score < 0) continue; + scored.push({ entry: { code, name, kind: 'stock' }, score, length: name.length, code }); + } + scored.sort((a, b) => { + if (a.score !== b.score) return a.score - b.score; + if (a.length !== b.length) return a.length - b.length; + return a.code < b.code ? -1 : 1; + }); + return scored.slice(0, limit).map((item) => item.entry); +} + +/** + * 名称检索:上游实时检索 + 本地缓存 + 静态别名兜底。 + * + * @param {{dataDir: string, logger?: {warn?: (event: string, data?: any) => void}, httpJson: (url: string, options?: any) => Promise}} options + */ +export function createSecurityIndexStore(options) { + const { dataDir, logger, httpJson } = options; + const file = join(dataDir, 'security-index.json'); + /** @type {SecurityEntry[]} */ + let entries = []; + let diskLoaded = false; + + async function loadFromDisk() { + if (diskLoaded) return; + diskLoaded = true; + try { + const raw = await readFile(file, 'utf8'); + const parsed = JSON.parse(raw); + if (!parsed || !Array.isArray(parsed.entries)) return; + entries = parsed.entries + .map((row) => + Array.isArray(row) && row.length >= 3 + ? { code: String(row[0]), name: String(row[1]), kind: String(row[2]) } + : null, + ) + .filter((row) => row !== null); + } catch { + /* 没有缓存就用空列表 */ + } + } + + /** + * 把新查到的名称并进本地缓存。 + * @param {SecurityEntry[]} fresh + */ + function mergeIntoCache(fresh) { + const map = new Map(); + for (const entry of entries) map.set(entry.code, entry); + for (const entry of fresh) map.set(entry.code, entry); + entries = [...map.values()].slice(-CACHE_LIMIT); + } + + async function saveToDisk() { + try { + await mkdir(dataDir, { recursive: true }); + const temporary = `${file}.tmp`; + const payload = { + updatedAt: new Date().toISOString(), + entries: entries.map((entry) => [entry.code, entry.name, entry.kind]), + }; + await writeFile(temporary, JSON.stringify(payload), 'utf8'); + await rename(temporary, file); + } catch (error) { + logger?.warn?.('miniapp.security_index.save_failed', {}); + } + } + + return { + /** + * 名称搜索。上游通就返回实时候选,不通就退回本地缓存和内置别名。 + * @param {string} query + * @param {number} [limit] + * @returns {Promise} + */ + async search(query, limit = 12) { + await loadFromDisk(); + const q = normalizeQuery(query); + if (!q) return []; + const local = matchCachedEntries(entries, q, limit); + try { + const url = `${SUGGEST_ENDPOINT}?input=${encodeURIComponent(q)}&type=${SUGGEST_TYPE}&count=${Math.min(limit + 6, 20)}`; + const payload = await httpJson(url, { timeout: SUGGEST_TIMEOUT }); + const fresh = parseSuggestEntries(payload); + if (fresh.length) { + mergeIntoCache(fresh); + /* 写盘要等完:否则进程被换掉时缓存可能还没落盘,下次离线就搜不到。 */ + await saveToDisk(); + const live = rankSuggestEntries(fresh, q, limit); + if (live.length) return live; + } + } catch (error) { + logger?.warn?.('miniapp.security_index.suggest_failed', {}); + } + if (local.length) return local; + return searchSecurityAliases(q, limit); + }, + + /** + * 本地缓存规模,供自检使用。 + */ + size() { + return entries.length; + }, + }; +} diff --git a/plugins/lixiangroir-ideal/weather-news-board/miniapp/node/server.mjs b/plugins/lixiangroir-ideal/weather-news-board/miniapp/node/server.mjs new file mode 100644 index 00000000..89a1dab4 --- /dev/null +++ b/plugins/lixiangroir-ideal/weather-news-board/miniapp/node/server.mjs @@ -0,0 +1,1425 @@ +// @ts-check + +/** + * 天气 · 新闻看板 —— Mini App Node 运行时 + * + * 职责: + * - 聚合天气、6 个新闻栏目、自选股行情(A股 + 国际品种) + * - 自选股持久化到 context.dataDir(原子写) + * - 只暴露白名单路由;所有外部取数都在 Node 侧完成 + */ + +import { mkdir, readFile, rename, writeFile } from 'node:fs/promises'; +import { createServer } from 'node:http'; +import { join } from 'node:path'; +import { resolveSecurityAlias } from './security-aliases.mjs'; +import { createSecurityIndexStore } from './security-index.mjs'; +import { resolveReorder } from './watchlist-order.mjs'; + +/** @typedef {import('./miniapp-api.js').MiniAppContext} MiniAppContext */ +/** @typedef {import('./miniapp-api.js').MiniAppLifecycle} MiniAppLifecycle */ + +const USER_AGENT = + 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36'; + +const UPSTREAM_TIMEOUT = 15000; +const QUOTE_TTL = 15_000; +const CONTENT_TTL = 60_000; +const FX_TTL = 30_000; +const MAX_WATCHLIST = 12; +const MAX_BODY_BYTES = 4096; +const GRAMS_PER_OUNCE = 31.1034768; + +/* ------------------------------------------------------------------ * + * 通用取数工具 + * ------------------------------------------------------------------ */ + +/** + * @param {string} url + * @param {{headers?: Record, encoding?: string, timeout?: number}} [options] + * @returns {Promise} + */ +async function httpText(url, options = {}) { + const response = await fetch(url, { + headers: { 'user-agent': USER_AGENT, accept: '*/*', ...(options.headers ?? {}) }, + redirect: 'follow', + signal: AbortSignal.timeout(options.timeout ?? UPSTREAM_TIMEOUT), + }); + if (!response.ok) throw new Error(`upstream_status_${response.status}`); + const buffer = await response.arrayBuffer(); + return new TextDecoder(options.encoding ?? 'utf-8').decode(buffer); +} + +/** + * @param {string} url + * @param {{headers?: Record, timeout?: number}} [options] + * @returns {Promise} + */ +async function httpJson(url, options = {}) { + const text = await httpText(url, options); + try { + return JSON.parse(text); + } catch { + throw new Error('invalid_json'); + } +} + +/* ------------------------------------------------------------------ * + * 文本清洗 + * ------------------------------------------------------------------ */ + +const NAMED_ENTITIES = { + amp: '&', + lt: '<', + gt: '>', + quot: '"', + apos: "'", + nbsp: ' ', + ldquo: '“', + rdquo: '”', + lsquo: '‘', + rsquo: '’', + mdash: '—', + ndash: '–', + hellip: '…', + middot: '·', + times: '×', + copy: '©', +}; + +/** + * @param {string} value + * @returns {string} + */ +function decodeEntities(value) { + return value.replace(/&(#x?[0-9a-fA-F]+|[a-zA-Z][a-zA-Z0-9]*);/g, (match, entity) => { + if (entity.charCodeAt(0) === 35) { + const isHex = entity[1] === 'x' || entity[1] === 'X'; + const code = Number.parseInt(isHex ? entity.slice(2) : entity.slice(1), isHex ? 16 : 10); + if (!Number.isFinite(code) || code < 0 || code > 0x10ffff) return match; + try { + return String.fromCodePoint(code); + } catch { + return match; + } + } + const mapped = NAMED_ENTITIES[entity.toLowerCase()]; + return mapped === undefined ? match : mapped; + }); +} + +/** + * 去标签、解实体、压空白、截断。 + * @param {string} value + * @param {number} [limit] + * @returns {string} + */ +function cleanText(value, limit = 120) { + if (!value) return ''; + const plain = decodeEntities(String(value)) + .replace(//gi, ' ') + .replace(//gi, ' ') + .replace(/<[^>]*>/g, ' ') + .replace(/\s+/g, ' ') + .trim(); + if (plain.length <= limit) return plain; + return `${plain.slice(0, limit).replace(/[\s,.;:!?,。、;:!?]+$/u, '')}…`; +} + +/** + * @param {string} body + * @param {string} tag + * @returns {string} + */ +function pickTag(body, tag) { + const match = body.match(new RegExp(`<${tag}(?:\\s[^>]*)?>([\\s\\S]*?)<\\/${tag}>`, 'i')); + if (!match) return ''; + let value = match[1].trim(); + const cdata = value.match(/^$/); + if (cdata) value = cdata[1]; + return value.trim(); +} + +/** + * 只保留 https 链接。上游返回的地址可能带 http 或其他协议, + * 这里统一过滤,避免把不安全或不可用的链接交给页面。 + * @param {unknown} value + * @returns {string} + */ +function safeHttps(value) { + const text = String(value ?? '').trim(); + return /^https:\/\//i.test(text) ? text : ''; +} + +/** + * @param {string} body + * @returns {string} + */ +function pickLink(body) { + const text = pickTag(body, 'link'); + const link = safeHttps(text); + if (link) return link; + const href = body.match(/]*\bhref=["']([^"']+)["'][^>]*>/i); + if (href) return safeHttps(href[1]); + const guid = pickTag(body, 'guid'); + return safeHttps(guid); +} + +/** + * 解析 RSS 2.0 / Atom 条目。 + * @param {string} xml + * @param {string} sourceName + */ +function parseFeed(xml, sourceName) { + /** @type {Array<{title:string, description:string, url:string, source:string, publishedAt:string|null}>} */ + const items = []; + const pattern = /<(item|entry)\b[^>]*>([\s\S]*?)<\/\1>/gi; + let match; + while ((match = pattern.exec(xml)) !== null) { + const body = match[2]; + const title = cleanText(pickTag(body, 'title'), 90); + if (!title) continue; + const published = + pickTag(body, 'pubDate') || + pickTag(body, 'published') || + pickTag(body, 'updated') || + pickTag(body, 'dc:date'); + items.push({ + title, + description: cleanText( + pickTag(body, 'description') || pickTag(body, 'content:encoded') || pickTag(body, 'summary'), + 110, + ), + url: pickLink(body), + source: sourceName, + publishedAt: published ? toIso(published) : null, + }); + } + return items; +} + +/** + * 把 RSS / 中文相对时间转成 ISO 字符串,无法解析返回 null。 + * @param {string} raw + * @returns {string|null} + */ +function toIso(raw) { + const value = String(raw || '').trim(); + if (!value) return null; + const now = Date.now(); + const minute = /^(\d+)\s*分钟前$/.exec(value); + if (minute) return new Date(now - Number(minute[1]) * 60_000).toISOString(); + const hour = /^(\d+)\s*小时前$/.exec(value); + if (hour) return new Date(now - Number(hour[1]) * 3_600_000).toISOString(); + const yesterday = /^昨天\s*(\d{1,2}):(\d{2})$/.exec(value); + if (yesterday) { + const date = new Date(now); + date.setDate(date.getDate() - 1); + date.setHours(Number(yesterday[1]), Number(yesterday[2]), 0, 0); + return date.toISOString(); + } + const monthDay = /^(\d{2})-(\d{2})\s+(\d{1,2}):(\d{2})$/.exec(value); + if (monthDay) { + const date = new Date(now); + date.setMonth(Number(monthDay[1]) - 1, Number(monthDay[2])); + date.setHours(Number(monthDay[3]), Number(monthDay[4]), 0, 0); + if (date.getTime() > now + 86_400_000) date.setFullYear(date.getFullYear() - 1); + return date.toISOString(); + } + const parsed = Date.parse(value); + if (Number.isFinite(parsed)) return new Date(parsed).toISOString(); + return null; +} + +/* ------------------------------------------------------------------ * + * 天气 + * ------------------------------------------------------------------ */ + +/** WWO 天气码 → 中文描述 + 图标键 */ +const WEATHER_META = { + 113: ['晴', 'sun'], + 116: ['局部多云', 'partly'], + 119: ['多云', 'cloud'], + 122: ['阴', 'overcast'], + 143: ['薄雾', 'fog'], + 149: ['烟霾', 'haze'], + 176: ['局部有雨', 'rain'], + 179: ['吹雪', 'snow'], + 182: ['暴雪', 'snow'], + 185: ['冻雾', 'fog'], + 200: ['雷阵雨', 'thunder'], + 227: ['大风', 'wind'], + 248: ['冻毛毛雨', 'rain'], + 263: ['局部毛毛雨', 'drizzle'], + 266: ['毛毛雨', 'drizzle'], + 281: ['冻雨', 'rain'], + 284: ['强冻毛毛雨', 'rain'], + 293: ['局部小雨', 'rain'], + 296: ['小雨', 'rain'], + 299: ['中雨', 'rain'], + 302: ['中雨', 'rain'], + 305: ['阵雨', 'rain'], + 308: ['大雨', 'rain'], + 311: ['轻冻雨', 'rain'], + 314: ['强冻雨', 'rain'], + 317: ['轻雨夹雪', 'sleet'], + 320: ['强雨夹雪', 'sleet'], + 323: ['局部小雪', 'snow'], + 326: ['小雪', 'snow'], + 329: ['局部中雪', 'snow'], + 332: ['中雪', 'snow'], + 335: ['局部大雪', 'snow'], + 338: ['大雪', 'snow'], + 350: ['冰粒', 'sleet'], + 353: ['小阵雨', 'rain'], + 356: ['强阵雨', 'rain'], + 359: ['暴雨', 'rain'], + 362: ['轻阵性雨夹雪', 'sleet'], + 365: ['强阵性雨夹雪', 'sleet'], + 368: ['小阵雪', 'snow'], + 371: ['强阵雪', 'snow'], + 374: ['阵性冰粒', 'sleet'], + 377: ['强阵性冰粒', 'sleet'], + 386: ['阵雨伴雪', 'sleet'], + 389: ['强阵雨伴雪', 'sleet'], +}; + +/** + * @param {number|string} code + * @returns {{desc:string, icon:string}} + */ +function weatherMeta(code) { + const key = Number(code); + const entry = WEATHER_META[key]; + return entry ? { desc: entry[0], icon: entry[1] } : { desc: '未知', icon: 'cloud' }; +} + +/** + * @param {string} cityName + */ +async function geocodeCity(cityName) { + const url = `https://geocoding-api.open-meteo.com/v1/search?name=${encodeURIComponent( + cityName, + )}&count=8&language=zh&format=json`; + const json = await httpJson(url); + const results = Array.isArray(json?.results) ? json.results : []; + return results.map((item) => ({ + id: String(item.id ?? ''), + name: String(item.name ?? ''), + admin1: String(item.admin1 ?? ''), + country: String(item.country ?? ''), + latitude: Number(item.latitude), + longitude: Number(item.longitude), + })); +} + +/** + * @param {{latitude:number, longitude:number}} candidate + */ +async function fetchWeatherAt(candidate) { + const url = `https://wttr.in/${candidate.latitude},${candidate.longitude}?format=j1`; + const json = await httpJson(url, { timeout: 20_000 }); + const current = json?.current_condition?.[0]; + const area = json?.nearest_area?.[0]; + const days = Array.isArray(json?.weather) ? json.weather : []; + if (!current || days.length === 0) throw new Error('weather_shape'); + + const meta = weatherMeta(current.weatherCode); + const utcHour = new Date().getUTCHours(); + const localHour = (utcHour + Math.round(candidate.longitude / 15) + 24) % 24; + + const forecast = days.slice(0, 3).map((day, index) => { + const hourly = Array.isArray(day.hourly) ? day.hourly : []; + const slots = index === 0 ? hourly.filter((slot) => Number(slot.time) / 100 >= localHour) : hourly; + const pool = slots.length ? slots : hourly; + const probability = pool.reduce((max, slot) => Math.max(max, Number(slot.chanceofrain) || 0), 0); + const mid = hourly[Math.floor(hourly.length / 2)] ?? hourly[0] ?? {}; + const dayMeta = weatherMeta(mid.weatherCode ?? current.weatherCode); + return { + date: String(day.date ?? ''), + label: index === 0 ? '今天' : index === 1 ? '明天' : '后天', + high: Number(day.maxtempC ?? 0), + low: Number(day.mintempC ?? 0), + probability, + desc: dayMeta.desc, + icon: dayMeta.icon, + }; + }); + + // 逐时预报:从当前时段起向后取若干个三小时档位,供空间富余时展开。 + const currentSlot = Math.floor(localHour / 3) * 3; + const hourly = []; + for (let dayIndex = 0; dayIndex < days.length && hourly.length < 6; dayIndex += 1) { + const slots = Array.isArray(days[dayIndex].hourly) ? days[dayIndex].hourly : []; + for (const slot of slots) { + const hour = Number(slot.time) / 100; + if (!Number.isFinite(hour)) continue; + if (dayIndex === 0 && hour < currentSlot) continue; + const slotMeta = weatherMeta(slot.weatherCode); + hourly.push({ + day: dayIndex === 0 ? '今天' : dayIndex === 1 ? '明天' : '后天', + time: `${String(Math.floor(hour)).padStart(2, '0')}:00`, + temp: Number(slot.tempC ?? 0), + probability: Number(slot.chanceofrain) || 0, + humidity: Number(slot.humidity) || 0, + windSpeed: Number(slot.windspeedKmph) || 0, + desc: slotMeta.desc, + icon: slotMeta.icon, + }); + if (hourly.length >= 6) break; + } + } + + const astronomy = Array.isArray(days[0]?.astronomy) ? days[0].astronomy[0] : null; + + return { + // 优先用中文地名(open-meteo geocoding language=zh),再退回 wttr.in 的英文地名。 + city: candidate.name || String(area?.areaName?.[0]?.value ?? ''), + region: candidate.admin1 || String(area?.region?.[0]?.value ?? ''), + country: candidate.country || String(area?.country?.[0]?.value ?? ''), + latitude: candidate.latitude, + longitude: candidate.longitude, + current: { + temp: Number(current.temp_C ?? 0), + feels: Number(current.FeelsLikeC ?? 0), + humidity: Number(current.humidity ?? 0), + windSpeed: Number(current.windspeedKmph ?? 0), + precipitation: Number(current.precipMM ?? 0), + pressure: Number(current.pressure ?? 0), + visibility: Number(current.visibility ?? 0), + cloud: Number(current.cloudcover ?? 0), + sunrise: String(astronomy?.sunrise ?? ''), + sunset: String(astronomy?.sunset ?? ''), + desc: meta.desc, + icon: meta.icon, + observationTime: String(current.observation_time ?? ''), + }, + forecast, + hourly, + }; +} + +/** + * @param {string} cityName + * @param {number} pick + * @param {boolean} refresh + */ +async function loadWeather(cityName, pick, refresh) { + const key = cityName || '南京'; + const cached = contentCache.get(`weather:${key}`); + if (!refresh && cached && Date.now() - cached.at < CONTENT_TTL) { + const candidates = cached.value.candidates ?? []; + const index = Math.min(Math.max(pick, 0), Math.max(candidates.length - 1, 0)); + const selected = candidates[index]; + if (selected) return { ...cached.value.data, candidates, index }; + } + + const candidates = await geocodeCity(key); + if (candidates.length === 0) throw new Error('city_not_found'); + const index = Math.min(Math.max(pick, 0), candidates.length - 1); + const selected = candidates[index]; + const data = await fetchWeatherAt(selected); + contentCache.set(`weather:${key}`, { + at: Date.now(), + value: { query: key, candidates, data }, + }); + lastGoodWeather = { candidates, data }; + return { ...data, candidates, index }; +} + +/* ------------------------------------------------------------------ * + * 新闻栏目 + * ------------------------------------------------------------------ */ + +const NEWS_DEFINITIONS = { + headlines: { label: '要闻', feeds: [{ url: 'https://www.chinanews.com.cn/rss/importnews.xml', name: '中新网' }] }, + politics: { label: '时政', feeds: [{ url: 'https://www.chinanews.com.cn/rss/china.xml', name: '中新网' }] }, + tech: { + label: '科技', + feeds: [ + { url: 'https://www.ithome.com/rss/', name: 'IT之家' }, + { url: 'https://sspai.com/feed', name: '少数派' }, + ], + }, + finance: { label: '财经', yicaiCids: [54, 53] }, + hot: { label: '热榜' }, + stories: { label: '知乎日报' }, +}; + +/** + * @param {string} url + * @param {string} sourceName + */ +async function fetchFeed(url, sourceName) { + const xml = await httpText(url); + return parseFeed(xml, sourceName); +} + +/** + * 科技栏目:两个源合并去重,交替穿插。 + * @returns {Promise} + */ +async function fetchTech() { + const [ithome, sspai] = await Promise.allSettled([ + fetchFeed('https://www.ithome.com/rss/', 'IT之家'), + fetchFeed('https://sspai.com/feed', '少数派'), + ]); + const lists = [ithome.status === 'fulfilled' ? ithome.value : [], sspai.status === 'fulfilled' ? sspai.value : []]; + const seen = new Set(); + const merged = []; + const max = Math.max(lists[0]?.length ?? 0, lists[1]?.length ?? 0); + for (let index = 0; index < max; index += 1) { + for (const list of lists) { + const item = list[index]; + if (!item || seen.has(item.title)) continue; + seen.add(item.title); + merged.push(item); + } + } + if (merged.length === 0) throw new Error('tech_empty'); + return merged; +} + +/** + * @param {number} cid + */ +async function fetchYicai(cid) { + const url = `https://www.yicai.com/api/ajax/getlistbycid?cid=${cid}&page=1&pagesize=12`; + const json = await httpJson(url, { headers: { referer: 'https://www.yicai.com/' } }); + const list = Array.isArray(json) ? json : Array.isArray(json?.data) ? json.data : []; + return list + .map((item) => { + const link = safeHttps(String(item.ShareUrl ?? '')); + const relative = String(item.url ?? ''); + const url = link + || (relative.startsWith('/') ? `https://www.yicai.com${relative}` : safeHttps(relative)); + return { + title: cleanText(String(item.NewsTitle ?? ''), 90), + description: cleanText(String(item.NewsNotes ?? ''), 110), + url, + source: '第一财经', + publishedAt: toIso(String(item.pubDate ?? '')), + publishedLabel: String(item.pubDate ?? ''), + }; + }) + .filter((item) => item.title); +} + +/** + * 热榜:今日头条为主,百度兜底。 + */ +async function fetchHotBoard() { + try { + const json = await httpJson('https://www.toutiao.com/hot-event/hot-board/?origin=toutiao_pc', { + headers: { referer: 'https://www.toutiao.com/' }, + }); + const data = Array.isArray(json?.data) ? json.data : []; + const items = data + .map((item, index) => ({ + rank: index + 1, + title: cleanText(String(item.Title ?? ''), 80), + score: Number(item.HotValue) || 0, + url: item.ClusterIdStr + ? `https://www.toutiao.com/trending/${String(item.ClusterIdStr)}/` + : safeHttps(item.Url), + category: String(item.InterestCategory ?? ''), + })) + .filter((item) => item.title); + if (items.length === 0) throw new Error('toutiao_empty'); + return { sourceName: '今日头条', items }; + } catch (error) { + const json = await httpJson('https://top.baidu.com/api/board?platform=pc&tab=realtime', { + headers: { referer: 'https://top.baidu.com/board?tab=realtime' }, + }); + const content = json?.data?.cards?.[0]?.content; + const list = Array.isArray(content) ? content : []; + const items = list + .map((item, index) => ({ + rank: index + 1, + title: cleanText(String(item.query ?? item.word ?? ''), 80), + score: Number(item.hotScore) || 0, + url: safeHttps(item.rawUrl ?? item.url), + category: String(item.hotTag ?? ''), + })) + .filter((item) => item.title); + if (items.length === 0) throw new Error('hot_empty'); + return { sourceName: '百度', items }; + } +} + +/** + * @returns {Promise} + */ +async function fetchZhihuStories() { + const json = await httpJson('https://news-at.zhihu.com/api/4/news/latest'); + const stories = [ + ...(Array.isArray(json?.stories) ? json.stories : []), + ...(Array.isArray(json?.top_stories) ? json.top_stories : []), + ]; + const seen = new Set(); + const items = []; + for (const story of stories) { + const id = String(story.id ?? story.url ?? ''); + if (!id || seen.has(id)) continue; + seen.add(id); + items.push({ + title: cleanText(String(story.title ?? ''), 90), + description: cleanText(String(story.hint ?? ''), 110), + url: safeHttps(story.url), + source: '知乎日报', + publishedAt: null, + }); + } + if (items.length === 0) throw new Error('zhihu_empty'); + return items; +} + +/** + * @param {string} key + * @param {boolean} refresh + */ +async function loadNews(key, refresh) { + const definition = NEWS_DEFINITIONS[key]; + if (!definition) throw new Error('unknown_source'); + const cached = contentCache.get(`news:${key}`); + if (!refresh && cached && Date.now() - cached.at < CONTENT_TTL) return cached.value; + + /** @type {{sourceName:string, items:any[], status:string, updatedAt?:string}} */ + let result; + if (key === 'hot') { + const hot = await fetchHotBoard(); + result = { sourceName: hot.sourceName, items: hot.items, status: 'ok' }; + } else if (key === 'stories') { + result = { sourceName: '知乎日报', items: await fetchZhihuStories(), status: 'ok' }; + } else if (key === 'tech') { + result = { sourceName: 'IT之家 · 少数派', items: await fetchTech(), status: 'ok' }; + } else if (key === 'finance') { + const groups = await Promise.allSettled(definition.yicaiCids.map((cid) => fetchYicai(cid))); + const items = []; + const seen = new Set(); + for (const group of groups) { + if (group.status !== 'fulfilled') continue; + for (const item of group.value) { + if (seen.has(item.title)) continue; + seen.add(item.title); + items.push(item); + } + } + if (items.length === 0) throw new Error('finance_empty'); + result = { sourceName: '第一财经', items, status: 'ok' }; + } else { + const feeds = definition.feeds ?? []; + const groups = await Promise.allSettled(feeds.map((feed) => fetchFeed(feed.url, feed.name))); + const items = []; + const seen = new Set(); + for (const group of groups) { + if (group.status !== 'fulfilled') continue; + for (const item of group.value) { + if (seen.has(item.title)) continue; + seen.add(item.title); + items.push(item); + } + } + if (items.length === 0) throw new Error('feed_empty'); + result = { sourceName: feeds.map((feed) => feed.name).join(' · '), items, status: 'ok' }; + } + + result.updatedAt = new Date().toISOString(); + contentCache.set(`news:${key}`, { at: Date.now(), value: result }); + return result; +} + +/* ------------------------------------------------------------------ * + * 行情 + * ------------------------------------------------------------------ */ + +const STOCK_FIELDS = 'f43,f44,f45,f46,f47,f48,f57,f58,f59,f60,f86,f169,f170'; + +/** + * 预定义国际品种。aliases 用于中文输入匹配(大小写不敏感)。 + * @type {Record} + */ +const COMMODITY_SPECS = { + XAU: { + code: 'XAU', + name: '伦敦金', + unit: '元/克', + kind: 'metal', + hf: 'hf_XAU', + aliases: ['黄金', '金价', '伦敦金', '现货黄金', '国际金价', 'xau', 'gold'], + }, + XAG: { + code: 'XAG', + name: '伦敦银', + unit: '元/克', + kind: 'metal', + hf: 'hf_XAG', + aliases: ['白银', '银价', '伦敦银', '现货白银', 'xag', 'silver'], + }, + GC: { + code: 'GC', + name: '纽约黄金', + unit: '元/克', + kind: 'metal', + hf: 'hf_GC', + aliases: ['纽约黄金', '纽约金', 'comex黄金', 'gc'], + }, + SI: { + code: 'SI', + name: '纽约白银', + unit: '元/克', + kind: 'metal', + hf: 'hf_SI', + aliases: ['纽约白银', 'comex白银', 'si'], + }, + CL: { + code: 'CL', + name: '纽约原油', + unit: '美元/桶', + kind: 'oil', + hf: 'hf_CL', + aliases: ['原油', '石油', '国际原油', '纽约原油', 'crude', 'cl', 'oil'], + }, + BTC: { + code: 'BTC', + name: '比特币期货', + unit: '美元', + kind: 'crypto', + hf: 'hf_BTC', + aliases: ['比特币', '比特币期货', 'btc', 'bitcoin'], + }, + AU9999: { + code: 'AU9999', + name: '黄金9999', + unit: '元/克', + kind: 'native', + em: '118.Au9999', + decimals: 2, + aliases: ['黄金9999', '沪金', '9999', 'au9999', '黄金9999克'], + }, +}; + +/** + * 6 位数字 → 市场前缀。 + * 按代码段判定:沪市 60/68/90(股票、B 股)与 50/51/56/58(基金), + * 深市 00/30/20(股票、B 股)与 15/16/18(基金),北交所 43/83/87/88。 + * @param {string} digits + * @returns {string} + */ +function marketOf(digits) { + const head = digits.charAt(0); + if (head === '6' || head === '9') return 'sh'; + if (head === '0' || head === '2' || head === '3') return 'sz'; + if (head === '4' || head === '8') return 'bj'; + if (head === '1') return 'sz'; + if (head === '5') return 'sh'; + return 'sh'; +} + +/** + * @param {string} code + * @returns {string} + */ +function secidOf(code) { + const market = code.slice(0, 2); + const digits = code.slice(2); + const prefix = market === 'sh' ? '1.' : '0.'; + return `${prefix}${digits}`; +} + +/** + * 输入白名单解析:6 位数字 / sh|sz|bj 前缀 / 品种别名。 + * @param {string} raw + * @returns {{code:string, kind:'stock'|'commodity'}|null} + */ +function resolveInput(raw) { + const value = String(raw ?? '').trim(); + if (!value || value.length > 32) return null; + const compact = value.replace(/\s+/g, ''); + const lower = compact.toLowerCase(); + + for (const spec of Object.values(COMMODITY_SPECS)) { + if (spec.code.toLowerCase() === lower) return { code: spec.code, kind: 'commodity' }; + if (spec.aliases.some((alias) => alias.toLowerCase() === lower)) { + return { code: spec.code, kind: 'commodity' }; + } + } + + const prefixed = /^(sh|sz|bj)([0-9]{6})$/.exec(lower); + if (prefixed) return { code: `${prefixed[1]}${prefixed[2]}`, kind: 'stock' }; + + /* 指数与常见 ETF 的名称别名(上证指数、沪深300、科创50ETF……)。 + 放在 6 位数字规则之前:指数代码的市场前缀不能靠数字段推。 */ + const alias = resolveSecurityAlias(compact); + if (alias) return { code: alias, kind: 'stock' }; + + if (/^[0-9]{6}$/.test(compact)) { + return { code: `${marketOf(compact)}${compact}`, kind: 'stock' }; + } + return null; +} + +/** + * @param {string} secid + */ +async function fetchEastmoneyQuote(secid) { + const url = `https://push2.eastmoney.com/api/qt/stock/get?ut=fa5fd1943c7b386f172d6893dbfba10b&invt=2&fields=${STOCK_FIELDS}&secid=${secid}`; + const json = await httpJson(url); + const data = json?.data; + if (!data || typeof data.f43 !== 'number' || data.f43 === 0) throw new Error('empty_quote'); + const factor = 10 ** (data.f59 || 2); + return { + name: String(data.f58 ?? ''), + code: String(data.f57 ?? ''), + price: data.f43 / factor, + prevClose: Number(data.f60 ?? 0) / factor, + change: Number(data.f169 ?? 0) / factor, + changePercent: Number(data.f170 ?? 0) / factor, + high: Number(data.f44 ?? 0) / factor, + low: Number(data.f45 ?? 0) / factor, + open: Number(data.f46 ?? 0) / factor, + volume: Number(data.f47 ?? 0), + amount: Number(data.f48 ?? 0), + updatedAt: data.f86 ? new Date(data.f86 * 1000).toISOString() : null, + provider: '东方财富', + }; +} + +/** + * 新浪 A 股备源(GBK + Referer)。 + * @param {string} code + */ +async function fetchSinaStock(code) { + const text = await httpText(`https://hq.sinajs.cn/list=${code}`, { + encoding: 'gbk', + headers: { referer: 'https://finance.sina.com.cn/' }, + }); + const match = text.match(/="([^"]*)"/); + const fields = match ? match[1].split(',') : []; + if (fields.length < 32) throw new Error('empty_quote'); + const price = Number(fields[3]); + const prevClose = Number(fields[2]); + if (!Number.isFinite(price) || price === 0) throw new Error('empty_quote'); + const date = fields[30] ?? ''; + const time = fields[31] ?? ''; + return { + name: String(fields[0] ?? ''), + code: code.slice(2), + price, + prevClose, + change: price - prevClose, + changePercent: prevClose ? ((price - prevClose) / prevClose) * 100 : 0, + high: Number(fields[4] ?? 0), + low: Number(fields[5] ?? 0), + open: Number(fields[1] ?? 0), + volume: Number(fields[8] ?? 0), + amount: Number(fields[9] ?? 0), + updatedAt: date && time ? new Date(`${date}T${time}:00+08:00`).toISOString() : null, + provider: '新浪财经', + }; +} + +/** + * 腾讯 A 股备源(GBK,无需 Referer)。时间字段用 14 位数字锚点定位。 + * @param {string} code + */ +async function fetchTencentStock(code) { + const text = await httpText(`https://qt.gtimg.cn/q=${code}`, { encoding: 'gbk' }); + const match = text.match(/="([^"]*)"/); + const fields = match ? match[1].split('~') : []; + if (fields.length < 32) throw new Error('empty_quote'); + const price = Number(fields[3]); + const prevClose = Number(fields[4]); + if (!Number.isFinite(price) || price === 0) throw new Error('empty_quote'); + const anchor = fields.findIndex((value) => /^\d{14}$/.test(value)); + const change = anchor > 0 ? Number(fields[anchor + 1]) : price - prevClose; + const changePercent = anchor > 0 ? Number(fields[anchor + 2]) : prevClose ? ((price - prevClose) / prevClose) * 100 : 0; + const stamp = anchor > 0 ? fields[anchor] : ''; + const updatedAt = stamp + ? new Date( + `${stamp.slice(0, 4)}-${stamp.slice(4, 6)}-${stamp.slice(6, 8)}T${stamp.slice(8, 10)}:${stamp.slice( + 10, + 12, + )}:${stamp.slice(12, 14)}+08:00`, + ).toISOString() + : null; + return { + name: String(fields[1] ?? ''), + code: String(fields[2] ?? ''), + price, + prevClose, + change: Number.isFinite(change) ? change : 0, + changePercent: Number.isFinite(changePercent) ? changePercent : 0, + high: anchor > 0 ? Number(fields[anchor + 3]) : 0, + low: anchor > 0 ? Number(fields[anchor + 4]) : 0, + open: Number(fields[5] ?? 0), + volume: 0, + amount: 0, + updatedAt, + provider: '腾讯财经', + }; +} + +/** + * 新浪国际品种主源(GBK + Referer)。 + * @param {string} hfCode + */ +async function fetchSinaCommodity(hfCode) { + const text = await httpText(`https://hq.sinajs.cn/list=${hfCode}`, { + encoding: 'gbk', + headers: { referer: 'https://finance.sina.com.cn/' }, + }); + const match = text.match(/="([^"]*)"/); + const fields = match ? match[1].split(',') : []; + if (fields.length < 14) throw new Error('empty_quote'); + const price = Number(fields[0]); + const prevClose = Number(fields[7]); + if (!Number.isFinite(price) || price === 0) throw new Error('empty_quote'); + return { + name: String(fields[13] ?? ''), + price, + prevClose, + change: price - prevClose, + changePercent: prevClose ? ((price - prevClose) / prevClose) * 100 : 0, + high: Number(fields[4] ?? 0), + low: Number(fields[5] ?? 0), + open: Number(fields[8] ?? 0), + updatedAt: fields[12] && fields[6] ? `${fields[12]}T${fields[6]}+08:00` : null, + provider: '新浪财经', + }; +} + +/** + * 腾讯国际品种备源。 + * @param {string} hfCode + */ +async function fetchTencentCommodity(hfCode) { + const text = await httpText(`https://qt.gtimg.cn/q=${hfCode}`, { encoding: 'gbk' }); + const match = text.match(/="([^"]*)"/); + const fields = match ? match[1].split(',') : []; + if (fields.length < 14) throw new Error('empty_quote'); + const price = Number(fields[0]); + const prevClose = Number(fields[7]); + if (!Number.isFinite(price) || price === 0) throw new Error('empty_quote'); + return { + name: String(fields[13] ?? ''), + price, + prevClose, + change: price - prevClose, + changePercent: prevClose ? ((price - prevClose) / prevClose) * 100 : 0, + high: Number(fields[4] ?? 0), + low: Number(fields[5] ?? 0), + open: Number(fields[8] ?? 0), + updatedAt: fields[12] && fields[6] ? `${fields[12]}T${fields[6]}+08:00` : null, + provider: '腾讯财经', + }; +} + +/** + * 美元兑人民币汇率。 + * @param {boolean} refresh + */ +async function loadFxRate(refresh) { + const cached = contentCache.get('fx'); + if (!refresh && cached && Date.now() - cached.at < FX_TTL) return cached.value; + try { + const quote = await fetchEastmoneyQuote('133.USDCNH'); + if (quote.price > 3 && quote.price < 10) { + const value = { rate: quote.price, label: '美元兑离岸人民币', provider: '东方财富' }; + contentCache.set('fx', { at: Date.now(), value }); + return value; + } + throw new Error('fx_range'); + } catch (error) { + const text = await httpText('https://hq.sinajs.cn/list=fx_susdcny', { + encoding: 'gbk', + headers: { referer: 'https://finance.sina.com.cn/' }, + }); + const match = text.match(/="([^"]*)"/); + const fields = match ? match[1].split(',') : []; + const rate = Number(fields[1]); + if (!Number.isFinite(rate) || rate <= 3 || rate >= 10) throw new Error('fx_unavailable'); + const value = { rate, label: '美元兑人民币', provider: '新浪财经' }; + contentCache.set('fx', { at: Date.now(), value }); + return value; + } +} + +/** + * A 股行情:东财主源,新浪 / 腾讯备源。 + * @param {string} code + */ +async function fetchStockQuote(code) { + let quote; + try { + quote = await fetchEastmoneyQuote(secidOf(code)); + } catch (error) { + try { + quote = await fetchSinaStock(code); + } catch (secondError) { + quote = await fetchTencentStock(code); + } + } + // 保留自选股里的规范代码(如 sh600519),供应商原始代码放在 symbol。 + return { ...quote, symbol: quote.code, code }; +} + +/** + * 国际品种行情。贵金属统一折算为人民币/克。 + * @param {string} code + */ +async function fetchCommodityQuote(code) { + const spec = COMMODITY_SPECS[code]; + let raw; + if (spec.em) { + raw = await fetchEastmoneyQuote(spec.em); + } else { + try { + raw = await fetchSinaCommodity(spec.hf); + } catch (error) { + raw = await fetchTencentCommodity(spec.hf); + } + } + + if (spec.kind === 'metal') { + const fx = await loadFxRate(false); + const gramPrice = (raw.price * fx.rate) / GRAMS_PER_OUNCE; + const gramPrev = (raw.prevClose * fx.rate) / GRAMS_PER_OUNCE; + return { + code, + name: spec.name, + price: gramPrice, + prevClose: gramPrev, + change: gramPrice - gramPrev, + changePercent: raw.prevClose ? ((raw.price - raw.prevClose) / raw.prevClose) * 100 : 0, + high: (raw.high * fx.rate) / GRAMS_PER_OUNCE, + low: (raw.low * fx.rate) / GRAMS_PER_OUNCE, + unit: spec.unit, + decimals: 2, + updatedAt: raw.updatedAt, + provider: raw.provider, + title: `原始报价 ${raw.price} 美元/盎司(昨收 ${raw.prevClose})|汇率 ${fx.rate}(${fx.label})|${raw.provider}`, + }; + } + + return { + code, + name: spec.name, + price: raw.price, + prevClose: raw.prevClose, + change: raw.change, + changePercent: raw.changePercent, + high: raw.high, + low: raw.low, + unit: spec.unit, + decimals: spec.decimals ?? 2, + updatedAt: raw.updatedAt, + provider: raw.provider, + title: spec.kind === 'native' ? '上海黄金交易所原生报价(人民币元/克)' : '', + }; +} + +/** + * @param {string} code + * @param {MiniAppContext} context + * @param {boolean} refresh + */ +async function getQuote(code, context, refresh) { + const cached = quoteCache.get(code); + if (!refresh && cached && Date.now() - cached.at < QUOTE_TTL) return cached.value; + try { + const value = COMMODITY_SPECS[code] + ? await fetchCommodityQuote(code) + : await fetchStockQuote(code); + quoteCache.set(code, { at: Date.now(), value }); + return value; + } catch (error) { + context.logger.warn('miniapp.quote.failed', { code }); + if (cached) return { ...cached.value, stale: true }; + return { code, name: code, error: 'quote_unavailable' }; + } +} + +/** + * 股票池与商品池分开取数。 + * @param {string[]} codes + * @param {MiniAppContext} context + * @param {boolean} refresh + */ +async function fetchAllQuotes(codes, context, refresh) { + const stockPool = codes.filter((code) => !COMMODITY_SPECS[code]); + const commodityPool = codes.filter((code) => Boolean(COMMODITY_SPECS[code])); + const [stocks, commodities] = await Promise.all([ + Promise.all(stockPool.map((code) => getQuote(code, context, refresh))), + Promise.all(commodityPool.map((code) => getQuote(code, context, refresh))), + ]); + const map = new Map(); + for (const item of [...stocks, ...commodities]) map.set(item.code, item); + return codes.map((code) => map.get(code) ?? { code, error: 'quote_unavailable' }); +} + +/* ------------------------------------------------------------------ * + * 自选股持久化 + * ------------------------------------------------------------------ */ + +/** + * @param {string} dataDir + * @param {MiniAppContext} context + */ +function createWatchlistStore(dataDir, context) { + const file = join(dataDir, 'watchlist.json'); + /** @type {string[]} */ + let codes = []; + + return { + async load() { + try { + const raw = await readFile(file, 'utf8'); + const parsed = JSON.parse(raw); + const list = Array.isArray(parsed?.codes) ? parsed.codes : []; + codes = list + .map((code) => resolveInput(code)) + .filter((resolved) => Boolean(resolved)) + .map((resolved) => /** @type {{code:string}} */ (resolved).code); + } catch { + codes = []; + } + return codes; + }, + list() { + return [...codes]; + }, + async save(next) { + codes = [...next]; + try { + await mkdir(dataDir, { recursive: true }); + const temporary = `${file}.tmp`; + await writeFile(temporary, JSON.stringify({ codes, updatedAt: new Date().toISOString() }, null, 2), 'utf8'); + await rename(temporary, file); + } catch (error) { + context.logger.warn('miniapp.watchlist.persist_failed', {}); + } + }, + }; +} + +/* ------------------------------------------------------------------ * + * HTTP 层 + * ------------------------------------------------------------------ */ + +/** @type {Map} */ +const contentCache = new Map(); +/** @type {Map} */ +const quoteCache = new Map(); +/** @type {{candidates:any[], data:any}|null} */ +let lastGoodWeather = null; + +/** + * @param {import('node:http').ServerResponse} response + * @param {number} status + * @param {any} payload + */ +function sendJson(response, status, payload) { + const body = JSON.stringify(payload); + response.writeHead(status, { + 'content-type': 'application/json; charset=utf-8', + 'cache-control': 'no-store', + 'content-length': Buffer.byteLength(body), + }); + response.end(body); +} + +/** + * @param {import('node:http').IncomingMessage} request + * @returns {Promise} + */ +async function readBody(request) { + const chunks = []; + let size = 0; + for await (const chunk of request) { + size += chunk.length; + if (size > MAX_BODY_BYTES) throw new Error('body_too_large'); + chunks.push(chunk); + } + return Buffer.concat(chunks).toString('utf8'); +} + +/** + * @param {MiniAppContext} context + * @param {{list: () => string[], save: (next: string[]) => Promise}} watchlist + * @param {ReturnType} securityIndex + * @param {import('node:http').IncomingMessage} request + * @param {import('node:http').ServerResponse} response + */ +async function handleRequest(context, watchlist, securityIndex, request, response) { + const url = new URL(request.url ?? '/', 'http://miniapp.local'); + const path = url.pathname; + const method = request.method ?? 'GET'; + const refresh = url.searchParams.get('refresh') === '1'; + + if (method === 'GET' && path === '/dashboard') { + const html = await readFile(join(context.pluginRoot, 'miniapp/client/index.html')); + response.writeHead(200, { + 'content-type': 'text/html; charset=utf-8', + 'cache-control': 'no-store', + 'content-length': html.length, + }); + response.end(html); + return; + } + + if (method === 'GET' && path === '/api/health') { + sendJson(response, 200, { ok: true }); + return; + } + + if (method === 'GET' && path === '/api/board') { + const source = url.searchParams.get('source') ?? 'weather'; + if (source === 'weather') { + try { + const city = url.searchParams.get('city') ?? '南京'; + const pick = Number(url.searchParams.get('pick') ?? '0') || 0; + const data = await loadWeather(city, pick, refresh); + sendJson(response, 200, { ok: true, source, updatedAt: new Date().toISOString(), data }); + } catch (error) { + context.logger.warn('miniapp.weather.failed', {}); + if (lastGoodWeather) { + sendJson(response, 200, { + ok: true, + source, + updatedAt: new Date().toISOString(), + stale: true, + warning: 'source_error', + message: '天气来源异常,已保留上一次数据', + data: lastGoodWeather.data, + }); + return; + } + sendJson(response, 200, { + ok: true, + source, + updatedAt: new Date().toISOString(), + warning: 'source_error', + message: '天气来源异常,请稍后重试', + data: null, + }); + } + return; + } + + if (NEWS_DEFINITIONS[source]) { + try { + const data = await loadNews(source, refresh); + sendJson(response, 200, { ok: true, source, updatedAt: data.updatedAt, data }); + } catch (error) { + context.logger.warn('miniapp.news.failed', { source }); + const cached = contentCache.get(`news:${source}`); + if (cached) { + sendJson(response, 200, { + ok: true, + source, + updatedAt: cached.value.updatedAt, + stale: true, + warning: 'source_error', + message: '新闻来源异常,已保留上一次数据', + data: cached.value, + }); + return; + } + sendJson(response, 200, { + ok: true, + source, + updatedAt: new Date().toISOString(), + warning: 'source_error', + message: '新闻来源异常,请稍后重试', + data: { label: NEWS_DEFINITIONS[source].label, items: [], status: 'error' }, + }); + } + return; + } + + sendJson(response, 400, { ok: false, error: 'invalid_code', message: '未知的栏目标识' }); + return; + } + + if (method === 'GET' && path === '/api/stocks') { + const codes = watchlist.list(); + const stocks = await fetchAllQuotes(codes, context, refresh); + sendJson(response, 200, { + ok: true, + updatedAt: new Date().toISOString(), + watchlist: codes, + stocks, + }); + return; + } + + if (method === 'GET' && path === '/api/search') { + const query = (url.searchParams.get('q') ?? '').trim(); + if (!query || query.length > 32) { + sendJson(response, 200, { ok: true, items: [] }); + return; + } + const items = await securityIndex.search(query, 12); + sendJson(response, 200, { ok: true, items }); + return; + } + + if (method === 'POST' && path === '/api/watchlist') { + let payload; + try { + const raw = await readBody(request); + payload = JSON.parse(raw); + } catch { + sendJson(response, 400, { ok: false, error: 'invalid_code', message: '请求体无效或超过 4KB' }); + return; + } + + const action = String(payload?.action ?? ''); + const rawCode = String(payload?.code ?? ''); + if (action !== 'add' && action !== 'remove' && action !== 'reorder') { + sendJson(response, 400, { ok: false, error: 'invalid_code', message: '不支持的操作' }); + return; + } + + const codes = watchlist.list(); + + /* 排序:只能对现有清单重新排列,不允许增删或塞入别的代码。 */ + if (action === 'reorder') { + const next = resolveReorder(payload?.codes, codes); + if (!next) { + sendJson(response, 400, { + ok: false, + error: 'invalid_code', + message: '排序参数无效:必须与当前自选股完全一致', + }); + return; + } + await watchlist.save(next); + let stocks = []; + try { + stocks = await fetchAllQuotes(next, context, true); + } catch (error) { + context.logger.warn('miniapp.watchlist.quote_failed', {}); + } + sendJson(response, 200, { ok: true, message: '已调整顺序', watchlist: next, stocks }); + return; + } + + const resolved = resolveInput(rawCode); + if (!resolved) { + sendJson(response, 400, { + ok: false, + error: 'invalid_code', + message: '仅支持 6 位 A 股代码、sh/sz/bj 前缀代码,或在输入框里输入名称后从候选中选择', + }); + return; + } + + if (action === 'add') { + if (codes.includes(resolved.code)) { + const stocks = await fetchAllQuotes(codes, context, true); + sendJson(response, 200, { ok: true, message: '已在自选股中', watchlist: codes, stocks }); + return; + } + if (codes.length >= MAX_WATCHLIST) { + sendJson(response, 400, { + ok: false, + error: 'watchlist_full', + message: `自选股最多 ${MAX_WATCHLIST} 个,请先移除一个`, + }); + return; + } + codes.push(resolved.code); + } else { + const index = codes.indexOf(resolved.code); + if (index >= 0) codes.splice(index, 1); + } + + await watchlist.save(codes); + let stocks = []; + try { + stocks = await fetchAllQuotes(codes, context, true); + } catch (error) { + context.logger.warn('miniapp.watchlist.quote_failed', {}); + } + sendJson(response, 200, { + ok: true, + message: action === 'add' ? '已添加' : '已移除', + watchlist: codes, + stocks, + }); + return; + } + + sendJson(response, 404, { ok: false, error: 'invalid_code', message: '接口不存在' }); +} + +/** + * @param {MiniAppContext} context + */ +export async function start(context) { + const watchlist = createWatchlistStore(context.dataDir, context); + await watchlist.load(); + const securityIndex = createSecurityIndexStore({ + dataDir: context.dataDir, + logger: context.logger, + httpJson, + }); + + const server = createServer((request, response) => { + handleRequest(context, watchlist, securityIndex, request, response).catch((error) => { + context.logger.warn('miniapp.request.failed', {}); + if (!response.headersSent) { + sendJson(response, 500, { ok: false, error: 'invalid_code', message: '服务内部异常,请稍后重试' }); + } else { + response.end(); + } + }); + }); + + await listen(server, context.listen.host, context.listen.port); + context.logger.info('miniapp.runtime.listening', {}); + + let disposed = false; + const dispose = async () => { + if (disposed) return; + disposed = true; + context.signal.removeEventListener('abort', onAbort); + contentCache.clear(); + quoteCache.clear(); + await close(server); + }; + const onAbort = () => { + void dispose(); + }; + context.signal.addEventListener('abort', onAbort, { once: true }); + if (context.signal.aborted) await dispose(); + + return { dispose }; +} + +/** + * @param {import('node:http').Server} server + * @param {string} host + * @param {number} port + */ +function listen(server, host, port) { + return new Promise((resolve, reject) => { + const onError = (error) => reject(error); + server.once('error', onError); + server.listen(port, host, () => { + server.off('error', onError); + resolve(); + }); + }); +} + +/** + * @param {import('node:http').Server} server + */ +function close(server) { + return new Promise((resolve, reject) => { + server.close((error) => (error ? reject(error) : resolve())); + }); +} diff --git a/plugins/lixiangroir-ideal/weather-news-board/miniapp/node/watchlist-order.mjs b/plugins/lixiangroir-ideal/weather-news-board/miniapp/node/watchlist-order.mjs new file mode 100644 index 00000000..3b3df4f3 --- /dev/null +++ b/plugins/lixiangroir-ideal/weather-news-board/miniapp/node/watchlist-order.mjs @@ -0,0 +1,27 @@ +// @ts-check + +/** + * 自选股排序的校验。 + * + * 排序请求只能是对现有清单的一个排列:不能增删条目、不能重复、不能塞进 + * 清单之外的代码。这样这条接口既不能被拿来加内容,也不会把清单外的代码 + * 写进存储。 + */ + +/** + * 校验排序参数,给出新的顺序;不合法时返回 null。 + * @param {unknown} next + * @param {string[]} current + * @returns {string[]|null} + */ +export function resolveReorder(next, current) { + if (!Array.isArray(next)) return null; + const codes = next.map((code) => String(code ?? '')); + if (codes.length !== current.length) return null; + if (new Set(codes).size !== codes.length) return null; + const known = new Set(current); + for (const code of codes) { + if (!known.has(code)) return null; + } + return codes; +} diff --git a/plugins/lixiangroir-ideal/weather-news-board/package.json b/plugins/lixiangroir-ideal/weather-news-board/package.json new file mode 100644 index 00000000..aab6b8dc --- /dev/null +++ b/plugins/lixiangroir-ideal/weather-news-board/package.json @@ -0,0 +1,6 @@ +{ + "mcode": { + "schemaVersion": 2, + "miniApp": "./miniapp/miniapp.json" + } +} diff --git a/plugins/lixiangroir-ideal/weather-news-board/tests/layout.test.mjs b/plugins/lixiangroir-ideal/weather-news-board/tests/layout.test.mjs new file mode 100644 index 00000000..32ea6404 --- /dev/null +++ b/plugins/lixiangroir-ideal/weather-news-board/tests/layout.test.mjs @@ -0,0 +1,193 @@ +/** + * 布局算法的自测。 + * + * 客户端把纯计算部分单独放在