From b96eca4dd3d24d4e122e71ba2930ec48d5caa652 Mon Sep 17 00:00:00 2001 From: ppppp2005-p <360128433+ppppp2005-p@users.noreply.github.com> Date: Wed, 25 Nov 2026 15:04:56 -0400 Subject: [PATCH 01/11] feat(ui-plugins): add API To SDK (api-to-sdk) --- marketplace.json | 50 +++++++++++++++++++++++ pnpm-lock.yaml | 103 +++++++++++++++++++++++------------------------ 2 files changed, 100 insertions(+), 53 deletions(-) diff --git a/marketplace.json b/marketplace.json index 32e8c8ef..40da090e 100644 --- a/marketplace.json +++ b/marketplace.json @@ -1673,6 +1673,56 @@ "把上一个 Hi3D 任务生成的模型按角色拆分成部件" ] } + }, + { + "name": "api-to-sdk", + "componentTypes": [ + "ui" + ], + "source": "./external_plugins/api-to-sdk", + "displayName": "API To SDK", + "displayName_i18n": { + "en": "API To SDK", + "zh-CN": "接口转 SDK" + }, + "description": "Turn an OpenAPI 3.0 / 3.1 spec (YAML or JSON) into a typed TypeScript SDK package: types for every schema, a dependency-free fetch client with one method per operation (path, query and header parameters, JSON / multipart / form bodies, bearer / API key / basic auth, timeouts, ApiError with the parsed error body), a README and an example that calls every operation, plus a mock server built from the spec's examples. Verified automatically: strict TypeScript compile, then every operation is called against the mock and checked against the spec.", + "description_i18n": { + "en": "Turn an OpenAPI 3.0 / 3.1 spec (YAML or JSON) into a typed TypeScript SDK package: types for every schema, a dependency-free fetch client with one method per operation (path, query and header parameters, JSON / multipart / form bodies, bearer / API key / basic auth, timeouts, ApiError with the parsed error body), a README and an example that calls every operation, plus a mock server built from the spec's examples. Verified automatically: strict TypeScript compile, then every operation is called against the mock and checked against the spec.", + "zh-CN": "把 OpenAPI 3.0 / 3.1 规范(YAML 或 JSON)生成带完整类型的 TypeScript SDK 包:每个数据结构都有类型;基于 fetch、没有依赖的客户端,每个接口一个方法(路径/查询/请求头参数,JSON / multipart / 表单请求体,Bearer / API Key / Basic 认证,超时,带解析后错误内容的 ApiError);附 README、调用全部接口的示例,以及用规范示例搭建的模拟服务器。自动验证:TypeScript 严格模式编译,再逐个调用每个接口并按规范检查。" + }, + "version": "0.1.0", + "author": { + "name": "Penova", + "url": "https://github.com/ppppp2005-p" + }, + "license": "MIT", + "category": "developer-tools", + "keywords": [ + "openapi", + "swagger", + "sdk", + "typescript", + "api client", + "codegen", + "mock server", + "fetch", + "接口", + "SDK", + "代码生成", + "模拟服务器" + ], + "examplePrompts": [ + "Generate a TypeScript SDK from openapi.yaml", + "Make a client for this API spec and test it", + "Re-verify the SDK after I changed the spec" + ], + "examplePrompts_i18n": { + "zh-CN": [ + "根据 openapi.yaml 生成 TypeScript SDK", + "给这个接口文档生成客户端并测试", + "规范改了,重新验证 SDK" + ] + } } ] } \ No newline at end of file diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 14b35f76..8da84dc1 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -37,11 +37,45 @@ importers: version: 6.0.2 vitest: specifier: 4.1.4 - version: 4.1.4(@opentelemetry/api@1.9.1)(@types/node@25.5.0)(msw@2.13.3(@types/node@25.5.0)(typescript@6.0.2))(vite@8.3.1(@types/node@25.5.0)(esbuild@0.25.12)(jiti@2.6.1)(tsx@4.21.0)(yaml@2.9.0)) + version: 4.1.4(@opentelemetry/api@1.9.1)(@types/node@25.5.0)(msw@2.13.3(@types/node@25.5.0)(typescript@6.0.2))(vite@8.3.1(@types/node@25.5.0)(esbuild@0.25.12)(jiti@2.6.1)(tsx@4.21.0)(yaml@2.9.1)) zod: specifier: 4.6.5 version: 4.6.5 + ui-plugins/api-to-sdk: + dependencies: + '@modelcontextprotocol/sdk': + specifier: 1.29.0 + version: 1.29.0(zod@4.6.5) + typescript: + specifier: 6.0.2 + version: 6.0.2 + yaml: + specifier: 2.9.1 + version: 2.9.1 + zod: + specifier: ^4.6.5 + version: 4.6.5 + devDependencies: + '@modelcontextprotocol/core': + specifier: 2.0.0 + version: 2.0.0 + '@modelcontextprotocol/ext-apps': + specifier: 2.0.0 + version: 2.0.0(@modelcontextprotocol/client@2.2.0)(@modelcontextprotocol/core@2.0.0)(@modelcontextprotocol/server@2.0.0)(react-dom@19.2.7(react@19.2.7))(react@19.2.7)(zod@4.6.5) + '@types/node': + specifier: 25.5.0 + version: 25.5.0 + esbuild: + specifier: ^0.25.12 + version: 0.25.12 + playwright-core: + specifier: 1.59.1 + version: 1.59.1 + vitest: + specifier: 4.1.4 + version: 4.1.4(@opentelemetry/api@1.9.1)(@types/node@25.5.0)(msw@2.13.3(@types/node@25.5.0)(typescript@6.0.2))(vite@8.3.1(@types/node@25.5.0)(esbuild@0.25.12)(jiti@2.6.1)(tsx@4.21.0)(yaml@2.9.1)) + ui-plugins/cadcraft: {} ui-plugins/craft-runtime: {} @@ -2475,10 +2509,6 @@ packages: resolution: {integrity: sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==} engines: {node: '>= 0.6'} - eventsource-parser@3.1.0: - resolution: {integrity: sha512-kJezFj9YFAMLeORyi7aCLxLbD5/qWMQnoMVlVPyHIll7lgRJCc3JVln9Vgl9nwQi0YkMnhdGTMNn7CkRRAptMg==} - engines: {node: '>=18.0.0'} - eventsource-parser@3.1.1: resolution: {integrity: sha512-EKN1vKAMcZ8MlYMpaNuxN6R9yakzH6uajHcHVTqWJzvu5pWw9DyhbP35HH8MVBQ+dZjAfDxk+A8NiR9KWaXiyQ==} engines: {node: '>=18.0.0'} @@ -2714,9 +2744,6 @@ packages: jose@6.2.12: resolution: {integrity: sha512-9NiFmJEex0sy2Dk58j2UGBSHgUs2ypF9eZSu4L6vjOX3Dp96Sw1F3uL+H+D1sx02jZZdzUT0HgvCy59CuvXcWw==} - jose@6.2.2: - resolution: {integrity: sha512-d7kPDd34KO/YnzaDOlikGpOurfF0ByC2sEV4cANCtdqLlTfBlw2p14O/5d/zv40gJPbIQxfES3nSx1/oYNyuZQ==} - jotai-scope@0.7.2: resolution: {integrity: sha512-Gwed97f3dDObrO43++2lRcgOqw4O2sdr4JCjP/7eHK1oPACDJ7xKHGScpJX9XaflU+KBHXF+VhwECnzcaQiShg==} peerDependencies: @@ -3068,10 +3095,6 @@ packages: resolution: {integrity: sha512-V7+vQEJ06Z+c5tSye8S+nHUfI51xoXIXjHQ99cQtKUkQqqO1kO/KCJUfZXuB47h/YBlDhah2H3hdUGXn8ie0oA==} engines: {node: '>=8.6'} - picomatch@4.0.4: - resolution: {integrity: sha512-QP88BAKvMam/3NxH6vj2o21R6MjxZUAd6nlwAS/pnGvN9IVLocLHxGYIzFhg6fUQ+5th6P4dv4eW9jX3DSIj7A==} - engines: {node: '>=12'} - picomatch@4.0.7: resolution: {integrity: sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==} engines: {node: '>=12'} @@ -3383,18 +3406,10 @@ packages: tinybench@2.9.0: resolution: {integrity: sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg==} - tinyexec@1.1.1: - resolution: {integrity: sha512-VKS/ZaQhhkKFMANmAOhhXVoIfBXblQxGX1myCQ2faQrfmobMftXeJPcZGp0gS07ocvGJWDLZGyOZDadDBqYIJg==} - engines: {node: '>=18'} - tinyexec@1.3.1: resolution: {integrity: sha512-GCvB3aoys96IuDFBMcTB46JOR6mdMtAToqwiW8JlWhsoh1mhHi/xn9ss/Dg7N555GiJyEt2qzoG/NHCwM6h1EA==} engines: {node: '>=18'} - tinyglobby@0.2.16: - resolution: {integrity: sha512-pn99VhoACYR8nFHhxqix+uvsbXineAasWm5ojXoN8xEwK5Kd3/TrhNn1wByuD52UxWRLy8pu+kRMniEi6Eq9Zg==} - engines: {node: '>=12.0.0'} - tinyglobby@0.2.17: resolution: {integrity: sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==} engines: {node: '>=12.0.0'} @@ -3697,8 +3712,8 @@ packages: resolution: {integrity: sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==} engines: {node: '>=10'} - yaml@2.9.0: - resolution: {integrity: sha512-2AvhNX3mb8zd6Zy7INTtSpl1F15HW6Wnqj0srWlkKLcpYl/gMIMJiyuGq2KeI2YFxUPjdlB+3Lc10seMLtL4cA==} + yaml@2.9.1: + resolution: {integrity: sha512-3NxN8+78OdzbT7C/WjGsyfPAtJaN3FNDsWxv7Y7mcDsT/oOmgW8BpyQQFFBnvZE3j9Y2Sdz1ULFLezL7Eb2yFw==} engines: {node: '>= 14.6'} hasBin: true @@ -3742,7 +3757,7 @@ snapshots: '@antfu/install-pkg@1.1.0': dependencies: package-manager-detector: 1.6.0 - tinyexec: 1.1.1 + tinyexec: 1.3.1 '@atlaskit/pragmatic-drag-and-drop-hitbox@1.2.0': dependencies: @@ -4285,11 +4300,11 @@ snapshots: cors: 2.8.6 cross-spawn: 7.0.6 eventsource: 3.0.7 - eventsource-parser: 3.1.0 + eventsource-parser: 3.1.1 express: 5.2.1 express-rate-limit: 8.3.2(express@5.2.1) hono: 4.12.12 - jose: 6.2.2 + jose: 6.2.12 json-schema-typed: 8.0.2 pkce-challenge: 5.0.1 raw-body: 3.0.2 @@ -5151,14 +5166,14 @@ snapshots: chai: 6.2.2 tinyrainbow: 3.1.1 - '@vitest/mocker@4.1.4(msw@2.13.3(@types/node@25.5.0)(typescript@6.0.2))(vite@8.3.1(@types/node@25.5.0)(esbuild@0.25.12)(jiti@2.6.1)(tsx@4.21.0)(yaml@2.9.0))': + '@vitest/mocker@4.1.4(msw@2.13.3(@types/node@25.5.0)(typescript@6.0.2))(vite@8.3.1(@types/node@25.5.0)(esbuild@0.25.12)(jiti@2.6.1)(tsx@4.21.0)(yaml@2.9.1))': dependencies: '@vitest/spy': 4.1.4 estree-walker: 3.0.3 magic-string: 0.30.21 optionalDependencies: msw: 2.13.3(@types/node@25.5.0)(typescript@6.0.2) - vite: 8.3.1(@types/node@25.5.0)(esbuild@0.25.12)(jiti@2.6.1)(tsx@4.21.0)(yaml@2.9.0) + vite: 8.3.1(@types/node@25.5.0)(esbuild@0.25.12)(jiti@2.6.1)(tsx@4.21.0)(yaml@2.9.1) '@vitest/pretty-format@4.1.4': dependencies: @@ -5809,13 +5824,11 @@ snapshots: etag@1.8.1: {} - eventsource-parser@3.1.0: {} - eventsource-parser@3.1.1: {} eventsource@3.0.7: dependencies: - eventsource-parser: 3.1.0 + eventsource-parser: 3.1.1 expect-type@1.4.0: {} @@ -5869,10 +5882,6 @@ snapshots: fast-uri@3.1.0: {} - fdir@6.5.0(picomatch@4.0.4): - optionalDependencies: - picomatch: 4.0.4 - fdir@6.5.0(picomatch@4.0.7): optionalDependencies: picomatch: 4.0.7 @@ -6048,8 +6057,6 @@ snapshots: jose@6.2.12: {} - jose@6.2.2: {} - jotai-scope@0.7.2(jotai@2.11.0(@types/react@19.2.14)(react@19.2.7))(react@19.2.7): dependencies: jotai: 2.11.0(@types/react@19.2.14)(react@19.2.7) @@ -6406,8 +6413,6 @@ snapshots: picomatch@2.3.2: {} - picomatch@4.0.4: {} - picomatch@4.0.7: {} pirates@4.0.7: {} @@ -6745,7 +6750,7 @@ snapshots: lines-and-columns: 1.2.4 mz: 2.7.0 pirates: 4.0.7 - tinyglobby: 0.2.16 + tinyglobby: 0.2.17 ts-interface-checker: 0.1.13 svg-pathdata@6.0.3: @@ -6779,15 +6784,8 @@ snapshots: tinybench@2.9.0: {} - tinyexec@1.1.1: {} - tinyexec@1.3.1: {} - tinyglobby@0.2.16: - dependencies: - fdir: 6.5.0(picomatch@4.0.4) - picomatch: 4.0.4 - tinyglobby@0.2.17: dependencies: fdir: 6.5.0(picomatch@4.0.7) @@ -6902,7 +6900,7 @@ snapshots: vary@1.1.2: {} - vite@8.3.1(@types/node@25.5.0)(esbuild@0.25.12)(jiti@2.6.1)(tsx@4.21.0)(yaml@2.9.0): + vite@8.3.1(@types/node@25.5.0)(esbuild@0.25.12)(jiti@2.6.1)(tsx@4.21.0)(yaml@2.9.1): dependencies: lightningcss: 1.33.0 picomatch: 4.0.7 @@ -6915,12 +6913,12 @@ snapshots: fsevents: 2.3.3 jiti: 2.6.1 tsx: 4.21.0 - yaml: 2.9.0 + yaml: 2.9.1 - vitest@4.1.4(@opentelemetry/api@1.9.1)(@types/node@25.5.0)(msw@2.13.3(@types/node@25.5.0)(typescript@6.0.2))(vite@8.3.1(@types/node@25.5.0)(esbuild@0.25.12)(jiti@2.6.1)(tsx@4.21.0)(yaml@2.9.0)): + vitest@4.1.4(@opentelemetry/api@1.9.1)(@types/node@25.5.0)(msw@2.13.3(@types/node@25.5.0)(typescript@6.0.2))(vite@8.3.1(@types/node@25.5.0)(esbuild@0.25.12)(jiti@2.6.1)(tsx@4.21.0)(yaml@2.9.1)): dependencies: '@vitest/expect': 4.1.4 - '@vitest/mocker': 4.1.4(msw@2.13.3(@types/node@25.5.0)(typescript@6.0.2))(vite@8.3.1(@types/node@25.5.0)(esbuild@0.25.12)(jiti@2.6.1)(tsx@4.21.0)(yaml@2.9.0)) + '@vitest/mocker': 4.1.4(msw@2.13.3(@types/node@25.5.0)(typescript@6.0.2))(vite@8.3.1(@types/node@25.5.0)(esbuild@0.25.12)(jiti@2.6.1)(tsx@4.21.0)(yaml@2.9.1)) '@vitest/pretty-format': 4.1.4 '@vitest/runner': 4.1.4 '@vitest/snapshot': 4.1.4 @@ -6937,7 +6935,7 @@ snapshots: tinyexec: 1.3.1 tinyglobby: 0.2.17 tinyrainbow: 3.1.1 - vite: 8.3.1(@types/node@25.5.0)(esbuild@0.25.12)(jiti@2.6.1)(tsx@4.21.0)(yaml@2.9.0) + vite: 8.3.1(@types/node@25.5.0)(esbuild@0.25.12)(jiti@2.6.1)(tsx@4.21.0)(yaml@2.9.1) why-is-node-running: 2.3.0 optionalDependencies: '@opentelemetry/api': 1.9.1 @@ -7018,8 +7016,7 @@ snapshots: y18n@5.0.8: optional: true - yaml@2.9.0: - optional: true + yaml@2.9.1: {} yargs-parser@21.1.1: optional: true From 78bcd4212a66442fd020efe4489bbd5e7e21db60 Mon Sep 17 00:00:00 2001 From: ppppp2005-p <360128433+ppppp2005-p@users.noreply.github.com> Date: Wed, 25 Nov 2026 15:05:37 -0400 Subject: [PATCH 02/11] feat(ui-plugins): add API To SDK (api-to-sdk) --- external_plugins/api-to-sdk/LICENSE | 21 +++++++++ external_plugins/api-to-sdk/README.md | 54 ++++++++++++++++++++++++ external_plugins/api-to-sdk/README_CN.md | 54 ++++++++++++++++++++++++ 3 files changed, 129 insertions(+) create mode 100644 external_plugins/api-to-sdk/LICENSE create mode 100644 external_plugins/api-to-sdk/README.md create mode 100644 external_plugins/api-to-sdk/README_CN.md diff --git a/external_plugins/api-to-sdk/LICENSE b/external_plugins/api-to-sdk/LICENSE new file mode 100644 index 00000000..67e98093 --- /dev/null +++ b/external_plugins/api-to-sdk/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 Penova + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/external_plugins/api-to-sdk/README.md b/external_plugins/api-to-sdk/README.md new file mode 100644 index 00000000..a2587a9a --- /dev/null +++ b/external_plugins/api-to-sdk/README.md @@ -0,0 +1,54 @@ +# API To SDK + +Turn an **OpenAPI 3.0 / 3.1** spec (YAML or JSON) into a **typed TypeScript SDK package**, then prove it works: it is compiled with TypeScript in strict mode, and every operation is called against a mock server built from the spec. + +## What it does + +- **Reads the spec**: local `$ref`s (schemas, parameters, request bodies, responses), path-level parameters, `allOf` / `oneOf` / `anyOf`, `const`, enums, 3.0 `nullable` and 3.1 type arrays, `additionalProperties`, security schemes. It warns about external or broken `$ref`s, undeclared path parameters, missing or duplicate operationIds and OAuth flows. +- **Generates** `sdk//`: + - `src/types.ts`: one type per schema, with descriptions as JSDoc. + - `src/client.ts`: a client class with one method per operation (`api.getBike({ bikeId: 7 })`). It has typed arguments and responses, and also provides: + - Path, query (arrays repeated) and header parameters; JSON, multipart (`FormData`, `Blob`), form and raw bodies. + - Bearer token (string or function), API key (header, query or cookie) and basic auth, chosen per operation from `security`. + - `timeoutMs`, `AbortSignal`, custom `fetch` and per-request headers. + - `ApiError` with status and parsed body; typed error bodies are exported as `ErrorBody`. + - No runtime dependencies (works in Node 20+, Deno, Bun and browsers). Pre-built `dist/` (JS + `.d.ts`), `package.json` and `tsconfig.json`. + - `README.md` with an operation table, and `examples/all-operations.ts`, which calls every operation with the spec's example values (spec examples that don't match their schema are reported). + - `mock/server.mjs`: a dependency-free mock answering from the spec's examples (or values synthesised from schemas). It checks requests against the spec (400 with reasons), supports `Prefer: code=404` to return documented errors, and allows CORS. +- **Verifies**: + - Strict TypeScript compile. + - Calling every operation against the mock. Each call checks method, path parameters, query, headers, credentials and JSON body against what was passed; that the response was parsed; and that a documented error status throws `ApiError` with the parsed body. + +## Usage + +Ask the agent in ZCode Desktop: + +- "Generate a TypeScript SDK from openapi.yaml" +- "Make a client for this API spec and test it" +- "Re-verify the SDK after I changed the spec" + +Or use the panel: choose the spec, **Read spec**, optionally set the folder, package name and class name, then **Generate & verify**. + +## Tools + +| Tool | Purpose | +|---|---| +| `sdk_inspect` | List operations, schemas, auth and spec problems (writes nothing) | +| `sdk_generate` | Write the SDK package, compile it and call every operation against the mock | +| `sdk_test` | Re-run the compile and mock calls (for example after editing generated code) | + +## Scope (v0.1) + +- TypeScript only; publishing to npm is up to you (`npm publish` in the folder). +- OpenAPI 2 (Swagger) must be converted to 3 first. External `$ref` files are not followed. +- OAuth2 / OpenID flows are not generated; pass an access token with `token`. Cookie parameters, `deepObject` query style, XML bodies and callbacks/webhooks are not supported. +- The mock is for development and tests, not a full contract tester. Its checks cover types, required fields, enums, `const`, formats, ranges and `oneOf` / `anyOf` / `allOf`. + +## Privacy, network and files + +- Runs locally with no network access and no API keys. Verification talks only to a mock on 127.0.0.1; the real API is never called. +- Reads the spec. Writes the SDK folder and `.api-to-sdk/sdks.json`. + +## License + +MIT. Bundles [yaml](https://github.com/eemeli/yaml) (ISC) and [TypeScript](https://github.com/microsoft/TypeScript) (Apache-2.0) for compiling. diff --git a/external_plugins/api-to-sdk/README_CN.md b/external_plugins/api-to-sdk/README_CN.md new file mode 100644 index 00000000..31349d57 --- /dev/null +++ b/external_plugins/api-to-sdk/README_CN.md @@ -0,0 +1,54 @@ +# 接口转 SDK + +把 **OpenAPI 3.0 / 3.1** 规范(YAML 或 JSON)生成**带完整类型的 TypeScript SDK 包**,并证明它能用:用 TypeScript 严格模式编译,再对照用规范搭建的模拟服务器,逐个调用每个接口。 + +## 功能 + +- **读取规范**:本地 `$ref`(数据结构、参数、请求体、响应)、路径级参数、`allOf` / `oneOf` / `anyOf`、`const`、枚举、3.0 的 `nullable` 和 3.1 的类型数组、`additionalProperties`、认证方案。会提示外部或失效的 `$ref`、未声明的路径参数、缺失或重复的 operationId,以及 OAuth 流程。 +- **生成** `sdk//`: + - `src/types.ts`:每个数据结构一个类型,说明文字转成 JSDoc。 + - `src/client.ts`:客户端类,每个接口一个方法(如 `api.getBike({ bikeId: 7 })`),参数和返回值都有类型。还支持: + - 路径、查询(数组会重复参数)和请求头参数;JSON、multipart(`FormData`、`Blob`)、表单和原始请求体。 + - Bearer 令牌(字符串或函数)、API Key(请求头、查询参数或 Cookie)和 Basic 认证,按每个接口的 `security` 自动选择。 + - `timeoutMs`、`AbortSignal`、自定义 `fetch`、单次请求的请求头。 + - 失败时抛出 `ApiError`,带状态码和解析后的错误内容;错误内容的类型导出为 `<接口>ErrorBody`。 + - 没有运行时依赖,可用于 Node 20+、Deno、Bun 和浏览器。已预先构建好 `dist/`(JS + `.d.ts`),附 `package.json` 和 `tsconfig.json`。 + - `README.md`(含接口表)和 `examples/all-operations.ts`(用规范里的示例值调用每个接口;示例与数据结构不符时会提示)。 + - `mock/server.mjs`:没有依赖的模拟服务器。按规范里的示例(或根据数据结构生成的值)返回响应;对照规范检查请求,不符时返回 400 并说明原因;支持用 `Prefer: code=404` 返回文档里写的错误;允许跨域。 +- **验证**: + - TypeScript 严格模式编译。 + - 对模拟服务器逐个调用接口。检查方法、路径参数、查询参数、请求头、认证信息和 JSON 请求体是否和传入的一致,响应是否正确解析,文档里写的错误状态码是否抛出带解析内容的 `ApiError`。 + +## 使用 + +在 ZCode Desktop 里对助手说: + +- “根据 openapi.yaml 生成 TypeScript SDK” +- “给这个接口文档生成客户端并测试” +- “规范改了,重新验证 SDK” + +也可以用面板:选择规范文件,点 **读取接口**,按需填写输出目录、包名和类名,再点 **生成 SDK 并验证**。 + +## 工具 + +| 工具 | 作用 | +|---|---| +| `sdk_inspect` | 列出接口、数据结构、认证和规范问题(不写文件) | +| `sdk_generate` | 生成 SDK 包、编译,并对模拟服务器调用每个接口 | +| `sdk_test` | 重新编译并调用(例如手动改过生成的代码之后) | + +## 范围(v0.1) + +- 只生成 TypeScript;发布到 npm 由你自己完成(在目录里运行 `npm publish`)。 +- OpenAPI 2(Swagger)需要先转换成 3。不跟随外部 `$ref` 文件。 +- 不生成 OAuth2 / OpenID 登录流程,请用 `token` 传入访问令牌。不支持 Cookie 参数、`deepObject` 查询参数、XML 请求体和回调/Webhook。 +- 模拟服务器用于开发和测试,不是完整的契约测试工具。它检查类型、必填、枚举、`const`、格式、范围和 `oneOf` / `anyOf` / `allOf`。 + +## 隐私、网络与文件 + +- 全部在本地运行,不联网,不需要 API Key。验证时只访问 127.0.0.1 上的模拟服务器,不会调用真实接口。 +- 读取规范文件,写入 SDK 目录和 `.api-to-sdk/sdks.json`。 + +## 许可证 + +MIT。内置 [yaml](https://github.com/eemeli/yaml)(ISC)和用于编译的 [TypeScript](https://github.com/microsoft/TypeScript)(Apache-2.0)。 From 531cc21197b5c9d7918bfa870bc23f813ca7e6c6 Mon Sep 17 00:00:00 2001 From: ppppp2005-p <360128433+ppppp2005-p@users.noreply.github.com> Date: Wed, 25 Nov 2026 15:06:28 -0400 Subject: [PATCH 03/11] feat(ui-plugins): add API To SDK (api-to-sdk) --- ui-plugins/api-to-sdk/package.json | 34 ++++++++++++++++++++++++++ ui-plugins/api-to-sdk/tsconfig.json | 14 +++++++++++ ui-plugins/api-to-sdk/vitest.config.ts | 2 ++ 3 files changed, 50 insertions(+) create mode 100644 ui-plugins/api-to-sdk/package.json create mode 100644 ui-plugins/api-to-sdk/tsconfig.json create mode 100644 ui-plugins/api-to-sdk/vitest.config.ts diff --git a/ui-plugins/api-to-sdk/package.json b/ui-plugins/api-to-sdk/package.json new file mode 100644 index 00000000..b079281d --- /dev/null +++ b/ui-plugins/api-to-sdk/package.json @@ -0,0 +1,34 @@ +{ + "name": "@penova/plugin-api-to-sdk", + "version": "0.1.0", + "private": true, + "license": "MIT", + "type": "module", + "scripts": { + "build": "node scripts/build.mjs", + "typecheck": "tsc -p tsconfig.json --noEmit", + "test": "vitest run", + "test:e2e": "node --experimental-strip-types scripts/e2e.mts" + }, + "zcode": { + "title": "API To SDK" + }, + "engines": { + "node": ">=22.0.0" + }, + "dependencies": { + "@modelcontextprotocol/sdk": "1.29.0", + "zod": "^4.6.5", + "yaml": "2.9.1", + "typescript": "6.0.2" + }, + "devDependencies": { + "@modelcontextprotocol/core": "2.0.0", + "@modelcontextprotocol/ext-apps": "2.0.0", + "@types/node": "25.5.0", + "esbuild": "^0.25.12", + "playwright-core": "1.59.1", + "typescript": "6.0.2", + "vitest": "4.1.4" + } +} diff --git a/ui-plugins/api-to-sdk/tsconfig.json b/ui-plugins/api-to-sdk/tsconfig.json new file mode 100644 index 00000000..39f7ab60 --- /dev/null +++ b/ui-plugins/api-to-sdk/tsconfig.json @@ -0,0 +1,14 @@ +{ + "compilerOptions": { + "target": "ES2022", + "module": "NodeNext", + "moduleResolution": "NodeNext", + "lib": ["ES2023", "DOM", "DOM.Iterable"], + "strict": true, + "skipLibCheck": true, + "noEmit": true, + "allowImportingTsExtensions": true, + "types": ["node"] + }, + "include": ["src/**/*.ts", "ui/**/*.ts", "test/**/*.ts"] +} diff --git a/ui-plugins/api-to-sdk/vitest.config.ts b/ui-plugins/api-to-sdk/vitest.config.ts new file mode 100644 index 00000000..27153a26 --- /dev/null +++ b/ui-plugins/api-to-sdk/vitest.config.ts @@ -0,0 +1,2 @@ +import { defineConfig } from "vitest/config"; +export default defineConfig({ test: { include: ["src/**/*.test.ts", "test/**/*.test.ts"], testTimeout: 120000, hookTimeout: 120000 } }); From 57106aac5c9bb00b11fcd8b8d8008d63787eb221 Mon Sep 17 00:00:00 2001 From: ppppp2005-p <360128433+ppppp2005-p@users.noreply.github.com> Date: Wed, 25 Nov 2026 15:07:09 -0400 Subject: [PATCH 04/11] feat(ui-plugins): add API To SDK (api-to-sdk) --- .../api-to-sdk/.zcode-plugin/plugin.json | 58 +++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 external_plugins/api-to-sdk/.zcode-plugin/plugin.json diff --git a/external_plugins/api-to-sdk/.zcode-plugin/plugin.json b/external_plugins/api-to-sdk/.zcode-plugin/plugin.json new file mode 100644 index 00000000..64ef8b32 --- /dev/null +++ b/external_plugins/api-to-sdk/.zcode-plugin/plugin.json @@ -0,0 +1,58 @@ +{ + "name": "api-to-sdk", + "version": "0.1.0", + "description": "Turn an OpenAPI 3.0 / 3.1 spec (YAML or JSON) into a typed TypeScript SDK package: types for every schema, a dependency-free fetch client with one method per operation (path, query and header parameters, JSON / multipart / form bodies, bearer / API key / basic auth, timeouts, ApiError with the parsed error body), a README and an example that calls every operation, plus a mock server built from the spec's examples. Verified automatically: strict TypeScript compile, then every operation is called against the mock and checked against the spec.", + "description_i18n": { + "en": "Turn an OpenAPI 3.0 / 3.1 spec (YAML or JSON) into a typed TypeScript SDK package: types for every schema, a dependency-free fetch client with one method per operation (path, query and header parameters, JSON / multipart / form bodies, bearer / API key / basic auth, timeouts, ApiError with the parsed error body), a README and an example that calls every operation, plus a mock server built from the spec's examples. Verified automatically: strict TypeScript compile, then every operation is called against the mock and checked against the spec.", + "zh-CN": "把 OpenAPI 3.0 / 3.1 规范(YAML 或 JSON)生成带完整类型的 TypeScript SDK 包:每个数据结构都有类型;基于 fetch、没有依赖的客户端,每个接口一个方法(路径/查询/请求头参数,JSON / multipart / 表单请求体,Bearer / API Key / Basic 认证,超时,带解析后错误内容的 ApiError);附 README、调用全部接口的示例,以及用规范示例搭建的模拟服务器。自动验证:TypeScript 严格模式编译,再逐个调用每个接口并按规范检查。" + }, + "author": { + "name": "Penova", + "url": "https://github.com/ppppp2005-p" + }, + "license": "MIT", + "keywords": [ + "openapi", + "swagger", + "sdk", + "typescript", + "api client", + "codegen", + "mock server", + "fetch", + "接口", + "SDK", + "代码生成", + "模拟服务器" + ], + "skills": "skills", + "mcpServers": { + "api-to-sdk": { + "type": "stdio", + "command": "node", + "args": [ + "${ZCODE_PLUGIN_ROOT}/dist/server.mjs" + ], + "cwd": "${ZCODE_PROJECT_DIR}", + "timeoutMs": 900000, + "env": { + "ZCODE_WORKSPACE_ROOT": "${ZCODE_PROJECT_DIR}" + } + } + }, + "ui": { + "surfaces": [ + { + "id": "editor", + "title": { + "zh-CN": "接口转 SDK", + "en-US": "API To SDK" + }, + "icon": "code", + "server": "api-to-sdk", + "resourceUri": "ui://api-to-sdk/panel.html", + "availability": "session" + } + ] + } +} From 4f2ca05dda20809acc93b721844427f3901ab463 Mon Sep 17 00:00:00 2001 From: ppppp2005-p <360128433+ppppp2005-p@users.noreply.github.com> Date: Wed, 25 Nov 2026 15:07:52 -0400 Subject: [PATCH 05/11] feat(ui-plugins): add API To SDK (api-to-sdk) --- ui-plugins/api-to-sdk/scripts/build.mjs | 79 ++++++++++ ui-plugins/api-to-sdk/scripts/e2e.mts | 88 +++++++++++ ui-plugins/api-to-sdk/scripts/harness.mjs | 162 +++++++++++++++++++++ ui-plugins/api-to-sdk/scripts/licenses.mjs | 43 ++++++ 4 files changed, 372 insertions(+) create mode 100644 ui-plugins/api-to-sdk/scripts/build.mjs create mode 100644 ui-plugins/api-to-sdk/scripts/e2e.mts create mode 100644 ui-plugins/api-to-sdk/scripts/harness.mjs create mode 100644 ui-plugins/api-to-sdk/scripts/licenses.mjs diff --git a/ui-plugins/api-to-sdk/scripts/build.mjs b/ui-plugins/api-to-sdk/scripts/build.mjs new file mode 100644 index 00000000..d49c8d66 --- /dev/null +++ b/ui-plugins/api-to-sdk/scripts/build.mjs @@ -0,0 +1,79 @@ +import { build } from "esbuild"; +import { copyFile, cp, mkdir, readFile, rm, writeFile } from "node:fs/promises"; +import { createRequire } from "node:module"; +import { dirname, join, resolve } from "node:path"; +import { fileURLToPath } from "node:url"; +import { writeNotices } from "./licenses.mjs"; + +const root = resolve(dirname(fileURLToPath(import.meta.url)), ".."); +const dist = join(root, "dist"); +const pkg = JSON.parse(await readFile(join(root, "package.json"), "utf8")); +await rm(dist, { recursive: true, force: true }); +await mkdir(join(dist, "ui"), { recursive: true }); + +// 宿主只提供 HTML 本身,JS 与 CSS 全部内联到一个页面里。 +const ui = await build({ + metafile: true, + entryPoints: [join(root, "ui/main.ts")], + bundle: true, + format: "iife", + platform: "browser", + target: "es2022", + minify: true, + write: false, + outdir: join(dist, "ui"), + legalComments: "none", + loader: { ".css": "text" }, +}); +const js = ui.outputFiles.find((file) => file.path.endsWith(".js")).text; +const escape = (text) => text.replace(/<\/script/gi, "<\\/script"); +const html = `${pkg.zcode?.title ?? pkg.name}
`; +const htmlBytes = Buffer.byteLength(html); +if (htmlBytes > 4 * 1024 * 1024 - 64 * 1024) throw new Error(`panel.html is ${Math.round(htmlBytes / 1024)} KiB; keep it below 4 MiB`); +await writeFile(join(dist, "ui/panel.html"), html); + +// 用不到、且许可证不明的可选依赖(package.json 的 zcode.stub)替换为空模块。 +const stubs = pkg.zcode?.stub ?? []; +const stubPlugin = { + name: "stub", + setup(b) { + if (!stubs.length) return; + const filter = new RegExp(`^(${stubs.map((s) => s.replace(/[.*+?^${}()|[\]\\/]/g, "\\$&")).join("|")})$`); + b.onResolve({ filter }, (args) => ({ path: args.path, namespace: "stub" })); + b.onLoad({ filter: /.*/, namespace: "stub" }, () => ({ contents: "module.exports = {};", loader: "js" })); + }, +}; + +const server = await build({ + plugins: [stubPlugin], + metafile: true, + entryPoints: [join(root, "src/main.ts")], + outfile: join(dist, "server.mjs"), + bundle: true, + platform: "node", + format: "esm", + target: "node22", + legalComments: "none", + banner: { + js: 'import { createRequire as __createRequire } from "node:module"; const require=__createRequire(import.meta.url); import { fileURLToPath as __fu } from "node:url"; import { dirname as __dn } from "node:path"; const __filename=__fu(import.meta.url); const __dirname=__dn(__filename);', + }, +}); + +// 运行时需要的 wasm 等文件(package.json 的 zcode.assets:{ 包内路径: 输出文件名 })。 +const require = createRequire(join(root, "package.json")); +for (const [from, to] of Object.entries(pkg.zcode?.assets ?? {})) await copyFile(require.resolve(from), join(dist, to)); + +// 整个目录(package.json 的 zcode.dirs:{ "包名:子目录": 输出目录 }),例如 pdf.js 的 CMap。 +for (const [spec, to] of Object.entries(pkg.zcode?.dirs ?? {})) { + const [name, sub] = spec.split(":"); + const base = dirname(require.resolve(`${name}/package.json`)); + await cp(join(base, sub), join(dist, to), { recursive: true, filter: (path) => !/(_nowasm_fallback\.js|quickjs-eval\.(js|wasm))$/.test(path) }); +} + +// TypeScript 的 lib.*.d.ts(内存编译用)和生成 SDK 附带的 mock 运行时。 +await mkdir(join(dist, "types/ts-lib"), { recursive: true }); +for (const f of (await import("node:fs")).readdirSync(dirname(require.resolve("typescript/lib/lib.d.ts")))) if (/^lib\..*\.d\.ts$/.test(f)) await copyFile(join(dirname(require.resolve("typescript/lib/lib.d.ts")), f), join(dist, "types/ts-lib", f)); +await cp(join(root, "src/runtime"), join(dist, "runtime"), { recursive: true }); + +await writeNotices([ui.metafile, server.metafile], join(dist, "THIRD_PARTY_NOTICES.txt"), Object.keys(pkg.zcode?.assets ?? {})); +process.stdout.write(`${pkg.name}: panel ${Math.round(htmlBytes / 1024)} KiB, server ${Math.round((await readFile(join(dist, "server.mjs"))).length / 1024)} KiB\n`); diff --git a/ui-plugins/api-to-sdk/scripts/e2e.mts b/ui-plugins/api-to-sdk/scripts/e2e.mts new file mode 100644 index 00000000..a50d240e --- /dev/null +++ b/ui-plugins/api-to-sdk/scripts/e2e.mts @@ -0,0 +1,88 @@ +// 浏览器端到端测试:真实打包的 server + 官方 AppBridge 宿主 + 隔离 iframe 中的面板(读取规范 → 生成 SDK → 验证结果); +// 然后在 Chrome 页面里直接 import 生成的 SDK(ESM),对随包附带的模拟服务器发请求,验证浏览器环境可用(含错误处理)。需要 Chrome。 +import assert from "node:assert/strict"; +import { spawn } from "node:child_process"; +import { copyFileSync, mkdirSync, readFileSync } from "node:fs"; +import { mkdtemp } from "node:fs/promises"; +import { createServer } from "node:http"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { startHarness } from "./harness.mjs"; + +const shots = process.env.E2E_SHOTS ?? join(tmpdir(), "api-to-sdk-shots"); +mkdirSync(shots, { recursive: true }); +const workspace = await mkdtemp(join(tmpdir(), "a2s-e2e-")); +const S = process.env.API_SAMPLES ?? "/workspace/zcode-new-plugins/samples/api"; +mkdirSync(join(workspace, "specs")); +copyFileSync(join(S, "harbor-bikes-api.yaml"), join(workspace, "specs/harbor-bikes-api.yaml")); +copyFileSync(join(S, "petstore3.json"), join(workspace, "specs/petstore3.json")); +const harness = await startHarness({ workspace }); +const step = (t: string) => process.stdout.write(`• ${t}\n`); +let mock: ReturnType | undefined; +let web: ReturnType | undefined; +try { + const { outer, frame, context } = await harness.open("?locale=zh-CN", { width: 1440, height: 1000 }); + step("panel: read the spec"); + await frame.locator("select.spec").selectOption("specs/harbor-bikes-api.yaml"); + await frame.locator("button.inspect").click(); + await frame.locator("tr[data-op='getReportsMonthlyCsv']", { hasText: "自动命名" }).waitFor({ timeout: 20_000 }); + step("panel: generate + verify"); + await frame.locator("input.cls").fill("HarborBikes"); + await frame.locator("button.gen").click(); + await frame.locator(".done", { hasText: "12/12" }).waitFor({ timeout: 120_000 }); + assert.equal(await frame.locator("td.res .ok").count(), 12); + await frame.locator("pre.code", { hasText: "export class HarborBikes" }).waitFor(); + await outer.screenshot({ path: join(shots, "01-generated.png") }); + step("panel: second spec (real Petstore)"); + await frame.locator("select.spec").selectOption("specs/petstore3.json"); + await frame.locator("button.inspect").click(); + await frame.locator("tr[data-op='findPetsByStatus']").waitFor(); + await frame.locator("input.out").fill("sdk/petstore"); + await frame.locator("input.cls").fill(""); + await frame.locator("input.pkg").fill(""); + await frame.locator("button.gen").click(); + await frame.locator(".done", { hasText: "19/19" }).waitFor({ timeout: 120_000 }); + await outer.screenshot({ path: join(shots, "02-petstore.png") }); + + step("browser: import the generated SDK and call the bundled mock"); + const sdk = join(workspace, "sdk/harbor-bikes-rental"); + mock = spawn(process.execPath, [join(sdk, "mock/server.mjs"), "0"], { stdio: ["ignore", "pipe", "pipe"] }); + const mockPort = await new Promise((ok, fail) => { let o = ""; mock!.stdout!.on("data", (d) => { o += d; const m = /127\.0\.0\.1:(\d+)/.exec(o); if (m) ok(Number(m[1])); }); setTimeout(() => fail(new Error(o)), 10_000); }); + const page = `SDK demo

Harbor Bikes SDK in the browser

    +`; + web = createServer((req, res) => { + if (req.url === "/") { res.writeHead(200, { "Content-Type": "text/html" }); return res.end(page); } + try { const body = readFileSync(join(sdk, req.url!.split("?")[0])); res.writeHead(200, { "Content-Type": "text/javascript" }); res.end(body); } catch { res.writeHead(404); res.end(); } + }); + const webPort = await new Promise((ok) => web!.listen(0, "127.0.0.1", () => ok((web!.address() as { port: number }).port))); + const p = await context.newPage(); + const errs: string[] = []; + p.on("pageerror", (e) => errs.push(String(e))); + p.on("console", (m) => { if (m.type() === "error" && !/status of 404/.test(m.text())) errs.push(m.text()); }); + await p.setViewportSize({ width: 900, height: 420 }); + await p.goto(`http://127.0.0.1:${webPort}/`); + await p.waitForFunction(() => document.title === "done", undefined, { timeout: 15_000 }); + await p.locator("li", { hasText: "HB-0007 · Volt Cargo" }).waitFor(); + await p.locator("li.err", { hasText: "ApiError 404: bike 999 not found" }).waitFor(); + await p.locator("li", { hasText: "report: category,rentals,revenue" }).waitFor(); + await p.screenshot({ path: join(shots, "03-sdk-in-browser.png") }); + assert.deepEqual(errs, []); + assert.deepEqual(harness.errors, []); + step(`ok — screenshots in ${shots}`); +} finally { + mock?.kill(); + web?.close(); + await harness.close(); +} diff --git a/ui-plugins/api-to-sdk/scripts/harness.mjs b/ui-plugins/api-to-sdk/scripts/harness.mjs new file mode 100644 index 00000000..a45e6e41 --- /dev/null +++ b/ui-plugins/api-to-sdk/scripts/harness.mjs @@ -0,0 +1,162 @@ +import assert from "node:assert/strict"; +import { createServer } from "node:http"; +import { readFile } from "node:fs/promises"; +import { dirname, join, resolve } from "node:path"; +import { fileURLToPath } from "node:url"; +import { build } from "esbuild"; +import { chromium } from "playwright-core"; +import { Client } from "@modelcontextprotocol/sdk/client/index.js"; +import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js"; +import { ResourceUpdatedNotificationSchema } from "@modelcontextprotocol/sdk/types.js"; + +/** + * 浏览器测试宿主:真实打包的 server(stdio)+ 官方 AppBridge 宿主页 + 隔离 iframe 中的面板。 + * 宿主页用与 ZCode 相同的 CSP 约束面板。测试脚本同时扮演 Agent:经同一个 MCP 连接调用工具, + * 并像宿主一样把结果推给页面。 + */ +const root = resolve(dirname(fileURLToPath(import.meta.url)), ".."); + +// 与 ZCode 给 MCP App 页面的限制一致:没有网络,允许 wasm(声明了 zcode/csp.wasmUnsafeEval)。 +export const PANEL_CSP = + "default-src 'none'; script-src 'self' 'unsafe-inline' blob: data: 'wasm-unsafe-eval'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; font-src 'self' data:; media-src 'self' data: blob:; worker-src 'self' blob:; connect-src 'none'; frame-src 'none'; base-uri 'self'; form-action 'none'"; + +/** server:要运行的 server 入口(默认真实打包的 dist/server.mjs)。 */ +export async function startHarness({ env = {}, workspace, server = join(root, "dist/server.mjs") }) { + const client = new Client({ name: "kit-harness", version: "1" }); + const sseClients = new Set(); + client.setNotificationHandler(ResourceUpdatedNotificationSchema, (notification) => { + for (const response of sseClients) response.write(`data: ${JSON.stringify(notification.params)}\n\n`); + }); + const stderr = []; + const transport = new StdioClientTransport({ + command: process.execPath, + args: [server], + cwd: workspace, + env: { ...process.env, ZCODE_WORKSPACE_ROOT: workspace, ...env }, + stderr: "pipe", + }); + transport.stderr?.on("data", (chunk) => stderr.push(String(chunk))); + await client.connect(transport); + const html = await readFile(join(root, "dist/ui/panel.html"), "utf8"); + const hostJs = await build({ + stdin: { + contents: ` +import { AppBridge, PostMessageTransport } from "@modelcontextprotocol/ext-apps/app-bridge"; +import { z } from "zod"; +const WidgetState = z.object({ method: z.literal('ui/set-widget-state'), params: z.object({ widgetState: z.unknown() }) }); +const rpc = async (method, args) => { + const response = await fetch('/rpc', {method:'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify({method,args})}); + const result = await response.json(); if (!response.ok) throw Error(result.error); return result; +}; +const params = new URLSearchParams(location.search); +const context = { theme: params.get('theme') || 'light', locale: params.get('locale') || 'en-US', displayMode: params.get('mode') || 'fullscreen' }; +const bridge = new AppBridge(null, {name:"kit-harness",version:"1"}, { + serverTools:{}, serverResources:{ listChanged: true }, message:{text:{}}, updateModelContext:{text:{}, structuredContent:{}}, openLinks:{}, + experimental: params.get('nosub') ? { "zcode/widgetState": {} } : { "zcode/resourceSubscribe": {}, "zcode/widgetState": {} }, +}, {hostContext:{...context, "zcode/widgetState": JSON.parse(sessionStorage.getItem('widgetState') || 'null')}}); +window.__messages = []; +window.__context = []; +window.__links = []; +window.__calls = []; +window.__initializations = 0; +bridge.oncalltool = (args) => { window.__calls.push(args.name); return rpc('callTool', args); }; +bridge.onreadresource = (args) => rpc('readResource', args); +bridge.onmessage = async (params) => { window.__messages.push(params.content[0].text); return {}; }; +bridge.onupdatemodelcontext = async (params) => { window.__context.push(params); return {}; }; +bridge.onopenlink = async (params) => { window.__links.push(params.url); return {}; }; +bridge.setRequestHandler('resources/subscribe', async (request) => { await rpc('subscribe', { uri: request.params.uri }); return {}; }); +bridge.setRequestHandler('resources/unsubscribe', async (request) => { await rpc('unsubscribe', { uri: request.params.uri }); return {}; }); +bridge.setRequestHandler(WidgetState, async (request) => { sessionStorage.setItem('widgetState', JSON.stringify(request.params.widgetState)); return {}; }); +bridge.oninitialized = () => { window.__initializations++; }; +window.__sendToolResult = (result) => bridge.sendToolResult(result); +window.__setContext = (patch) => bridge.setHostContext({ ...context, ...patch }); +new EventSource('/events').onmessage = (event) => { + bridge.notification({ method: 'notifications/resources/updated', params: JSON.parse(event.data) }); +}; +const frame = document.querySelector('iframe'); +await bridge.connect(new PostMessageTransport(frame.contentWindow, frame.contentWindow)); +frame.src = '/panel'; +`, + resolveDir: root, + sourcefile: "browser-host.mjs", + }, + bundle: true, + format: "esm", + platform: "browser", + write: false, + }); + const http = createServer(async (request, response) => { + try { + const url = new URL(request.url, "http://localhost"); + if (url.pathname === "/") { + response.setHeader("Content-Type", "text/html; charset=utf-8"); + response.end( + '', + ); + } else if (url.pathname === "/host.js") { + response.setHeader("Content-Type", "text/javascript"); + response.end(hostJs.outputFiles[0].text); + } else if (url.pathname === "/panel") { + response.setHeader("Content-Type", "text/html; charset=utf-8"); + response.setHeader("Content-Security-Policy", PANEL_CSP); + response.end(html); + } else if (url.pathname === "/events") { + response.writeHead(200, { "Content-Type": "text/event-stream", "Cache-Control": "no-cache" }); + response.write(": connected\n\n"); + sseClients.add(response); + request.on("close", () => sseClients.delete(response)); + } else if (request.method === "POST" && url.pathname === "/rpc") { + let body = ""; + for await (const chunk of request) body += chunk; + const { method, args } = JSON.parse(body); + const result = + method === "readResource" + ? await client.readResource(args) + : method === "subscribe" + ? await client.subscribeResource(args) + : method === "unsubscribe" + ? await client.unsubscribeResource(args) + : await client.callTool(args, undefined, { timeout: 300_000 }); + response.setHeader("Content-Type", "application/json"); + response.end(JSON.stringify(result ?? {})); + } else if (url.pathname === "/favicon.ico") response.writeHead(204).end(); + else response.writeHead(404).end(); + } catch (error) { + response.writeHead(500, { "Content-Type": "application/json" }).end(JSON.stringify({ error: String(error) })); + } + }); + await new Promise((done) => http.listen(0, "127.0.0.1", done)); + const base = `http://127.0.0.1:${http.address().port}`; + const browser = await chromium.launch(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : { channel: "chrome" }); + const errors = []; + const contexts = []; + + const open = async (query = "", viewport = { width: 720, height: 900 }) => { + const context = await browser.newContext({ viewport, deviceScaleFactor: 2 }); + contexts.push(context); + const outer = await context.newPage(); + outer.on("pageerror", (error) => errors.push(String(error))); + outer.on("console", (message) => { + if (message.type() === "error" && !/favicon/.test(message.text())) errors.push(message.text()); + }); + await outer.goto(`${base}/${query}`); + await outer.waitForFunction(() => window.__initializations === 1); + const frame = outer.frames().find((item) => item !== outer.mainFrame()); + assert.ok(frame, "official App iframe exists"); + return { outer, frame, context }; + }; + /** 扮演 Agent:调用工具,再像宿主一样把结果推给页面。 */ + const agent = async (outer, name, args, { expectError = false } = {}) => { + const result = await client.callTool({ name, arguments: args }, undefined, { timeout: 300_000 }); + if (expectError) assert.ok(result.isError, `${name} should fail`); + else assert.ok(!result.isError, `${name}: ${JSON.stringify(result.content)}`); + if (outer) await outer.evaluate((value) => window.__sendToolResult(value), result); + return result; + }; + const close = async () => { + await browser.close().catch(() => undefined); + await client.close().catch(() => undefined); + http.close(); + }; + return { client, open, agent, close, errors, stderr, base, contexts: () => contexts.filter((context) => context.pages().length) }; +} diff --git a/ui-plugins/api-to-sdk/scripts/licenses.mjs b/ui-plugins/api-to-sdk/scripts/licenses.mjs new file mode 100644 index 00000000..5107fe7c --- /dev/null +++ b/ui-plugins/api-to-sdk/scripts/licenses.mjs @@ -0,0 +1,43 @@ +import { readFile, readdir, writeFile } from "node:fs/promises"; +import { dirname, join, resolve } from "node:path"; + +// 从实际参与打包的模块收集许可证,避免只列直接依赖而漏掉 Canvas/SDK 的传递依赖。 +export async function writeNotices(metafiles, destination, extra = []) { + const packages = new Map(); + const { createRequire } = await import("node:module"); + const require = createRequire(resolve("package.json")); + const extraInputs = extra.map((spec) => require.resolve(spec)); + for (const input of [...metafiles.flatMap((meta) => Object.keys(meta.inputs)), ...extraInputs]) { + if (!input.includes("node_modules/")) continue; + let directory = dirname(resolve(input)); + while (directory.includes("node_modules")) { + try { + const pkg = JSON.parse(await readFile(join(directory, "package.json"), "utf8")); + if (pkg.name && pkg.version) { + packages.set(directory, pkg); + break; + } + } catch (error) { + if (error.code !== "ENOENT") throw error; + } + directory = dirname(directory); + } + } + const notices = []; + const seen = new Set(); + for (const [directory, pkg] of [...packages].sort((a, b) => a[1].name.localeCompare(b[1].name))) { + const key = `${pkg.name}@${pkg.version}`; + if (seen.has(key)) continue; + seen.add(key); + const files = (await readdir(directory)).filter((name) => + /^(license|copying|notice)([.-]|$)/i.test(name), + ); + const texts = await Promise.all(files.map((file) => readFile(join(directory, file), "utf8"))); + if (!texts.length && !pkg.license) throw new Error(`Missing license for bundled dependency ${key}`); + if (!texts.length) texts.push(`(No license file is shipped in this package; its package.json declares the ${pkg.license} license.)`); + notices.push( + `${key} — ${typeof pkg.license === "string" ? pkg.license : JSON.stringify(pkg.license)}\n${texts.join("\n\n")}`, + ); + } + await writeFile(destination, notices.join("\n\n----------------------------------------\n\n")); +} From 66be80bf5051c268e933bb54543650333f527a08 Mon Sep 17 00:00:00 2001 From: ppppp2005-p <360128433+ppppp2005-p@users.noreply.github.com> Date: Wed, 25 Nov 2026 15:08:40 -0400 Subject: [PATCH 06/11] feat(ui-plugins): add API To SDK (api-to-sdk) --- ui-plugins/api-to-sdk/src/codegen.ts | 222 +++++++++++++++++++++++++++ ui-plugins/api-to-sdk/src/main.ts | 14 ++ ui-plugins/api-to-sdk/src/openapi.ts | 102 ++++++++++++ ui-plugins/api-to-sdk/src/server.ts | 171 +++++++++++++++++++++ ui-plugins/api-to-sdk/src/verify.ts | 117 ++++++++++++++ 5 files changed, 626 insertions(+) create mode 100644 ui-plugins/api-to-sdk/src/codegen.ts create mode 100644 ui-plugins/api-to-sdk/src/main.ts create mode 100644 ui-plugins/api-to-sdk/src/openapi.ts create mode 100644 ui-plugins/api-to-sdk/src/server.ts create mode 100644 ui-plugins/api-to-sdk/src/verify.ts diff --git a/ui-plugins/api-to-sdk/src/codegen.ts b/ui-plugins/api-to-sdk/src/codegen.ts new file mode 100644 index 00000000..89c94091 --- /dev/null +++ b/ui-plugins/api-to-sdk/src/codegen.ts @@ -0,0 +1,222 @@ +import { type Api, type Json, type Op, type Resp, pascal } from "./openapi.ts"; + +const IDENT = /^[A-Za-z_$][A-Za-z0-9_$]*$/; +const prop = (k: string) => (IDENT.test(k) ? k : JSON.stringify(k)); +const doc = (lines: (string | undefined)[], pad = "") => { const l = lines.filter(Boolean).flatMap((x) => String(x).replace(/\*\//g, "*\\/").split("\n")); return l.length ? `${pad}/**\n${l.map((x) => `${pad} * ${x}`.trimEnd()).join("\n")}\n${pad} */\n` : ""; }; +const lit = (v: Json) => (typeof v === "string" ? JSON.stringify(v) : v === null ? "null" : typeof v === "number" || typeof v === "boolean" ? String(v) : "unknown"); + +export class TypeNamer { + names = new Map(); + constructor(schemas: string[]) { + const used = new Set(["ApiError", "ClientOptions", "RequestOptions"]); + for (const s of schemas) { let n = pascal(s); if (/^\d/.test(n)) n = `T${n}`; let k = n, i = 2; while (used.has(k)) k = `${n}${i++}`; used.add(k); this.names.set(s, k); } + } + ref(ref: string) { const m = /^#\/components\/schemas\/(.+)$/.exec(ref); return m ? this.names.get(decodeURIComponent(m[1]).replace(/~1/g, "/").replace(/~0/g, "~")) : undefined; } +} + +/** OpenAPI schema → TypeScript type expression. `ns` prefixes named types (e.g. "T."). */ +export function tsType(root: Json, s: Json, namer: TypeNamer, ns = "", pad = "", depth = 0): string { + if (s === true || s === undefined || s === null || (typeof s === "object" && !Object.keys(s).length)) return "unknown"; + if (s === false) return "never"; + if (depth > 12) return "unknown"; + if (typeof s.$ref === "string") { + const n = namer.ref(s.$ref); + if (n) return ns + n; + try { let node: Json = root; for (const k of s.$ref.slice(2).split("/")) node = node[decodeURIComponent(k).replace(/~1/g, "/").replace(/~0/g, "~")]; return tsType(root, node, namer, ns, pad, depth + 1); } catch { return "unknown"; } + } + const nullable = s.nullable === true || (Array.isArray(s.type) && s.type.includes("null")); + const withNull = (t: string) => (nullable && t !== "unknown" && !/\bnull$/.test(t) ? `${t} | null` : t); + if (s.const !== undefined) return withNull(lit(s.const)); + if (Array.isArray(s.enum)) return withNull(s.enum.map(lit).join(" | ") || "never"); + const paren = (t: string) => (/[|&]/.test(t) && !/^\{[\s\S]*\}$/.test(t) ? `(${t})` : t); + if (s.oneOf || s.anyOf) { const alts = [...new Set((s.oneOf || s.anyOf).map((x: Json) => tsType(root, x, namer, ns, pad, depth + 1)))] as string[]; const base = Object.keys(s).some((k) => k === "properties") ? ` & ${objectType(root, s, namer, ns, pad, depth)}` : ""; return withNull(alts.length > 1 ? (base ? `(${alts.join(" | ")})${base}` : alts.join(" | ")) : `${alts[0]}${base}`); } + if (s.allOf) { const parts = s.allOf.map((x: Json) => paren(tsType(root, x, namer, ns, pad, depth + 1))); if (s.properties) parts.push(objectType(root, s, namer, ns, pad, depth)); return withNull(parts.join(" & ")); } + const types: string[] = (Array.isArray(s.type) ? s.type : s.type ? [s.type] : []).filter((t: string) => t !== "null"); + if (!types.length) { if (s.properties || s.additionalProperties !== undefined) types.push("object"); else if (s.items) types.push("array"); else return nullable ? "unknown" : "unknown"; } + const one = (t: string): string => { + switch (t) { + case "string": return s.format === "binary" ? "Blob" : "string"; + case "integer": case "number": return "number"; + case "boolean": return "boolean"; + case "array": { const it = tsType(root, s.items ?? {}, namer, ns, pad, depth + 1); return /[|&\s]/.test(it) && !/^\{/.test(it) ? `Array<${it}>` : `${it}[]`; } + case "object": return objectType(root, s, namer, ns, pad, depth); + default: return "unknown"; + } + }; + return withNull(types.map(one).join(" | ")); +} + +function objectType(root: Json, s: Json, namer: TypeNamer, ns: string, pad: string, depth: number): string { + const props = Object.entries(s.properties ?? {}); + const req = new Set(s.required ?? []); + const inner = pad + " "; + const lines = props.map(([k, v]) => `${doc([v?.description, v?.deprecated ? "@deprecated" : undefined, v?.format && !["binary"].includes(v.format) ? `Format: ${v.format}` : undefined], inner)}${inner}${prop(k)}${req.has(k) ? "" : "?"}: ${tsType(root, v, namer, ns, inner, depth + 1)};`); + const ap = s.additionalProperties; + if (ap === true || (ap && typeof ap === "object")) lines.push(`${inner}[key: string]: ${ap === true ? "unknown" : props.length ? "unknown" : tsType(root, ap, namer, ns, inner, depth + 1)};`); + if (!lines.length) return ap === false ? "Record" : "Record"; + return `{\n${lines.join("\n")}\n${pad}}`; +} + +const respType = (api: Api, r: Resp | undefined, namer: TypeNamer, ns: string) => { + if (!r || !r.contentType || r.status === "204") return "void"; + if (r.kind === "json") return r.schema ? tsType(api.root, r.schema, namer, ns) : "unknown"; + if (r.kind === "text") return "string"; + return "Blob"; +}; + +export interface Files { [path: string]: string } + +export function generate(api: Api, o: { className: string; packageName: string; mockPort?: number }): Files { + const namer = new TypeNamer(api.schemas); + const comps = api.root.components?.schemas ?? {}; + const types = [`// Generated by API To SDK from “${api.title}” ${api.version} (OpenAPI ${api.openapi}). Do not edit by hand; regenerate instead.\n`]; + for (const [name, s] of Object.entries(comps)) types.push(`${doc([s?.title && s.title !== name ? s.title : undefined, s?.description, s?.deprecated ? "@deprecated" : undefined])}export type ${namer.names.get(name)} = ${tsType(api.root, s, namer)};\n`); + if (!Object.keys(comps).length) types.push("export {};\n"); + + const bearer = api.schemes.some((s) => s.type === "bearer" || s.type === "oauth2" || s.type === "other"); + const apiKeys = api.schemes.filter((s) => s.type === "apiKey"); + const basic = api.schemes.some((s) => s.type === "basic"); + const opBlocks: string[] = [], argTypes: string[] = []; + for (const op of api.ops) { + const P = pascal(op.id); + const fields = op.params.map((p) => `${doc([p.description, p.deprecated ? "@deprecated" : undefined, `${p.in} parameter \`${p.name}\``], " ")} ${p.ident}${p.required ? "" : "?"}: ${tsType(api.root, p.schema, namer, "T.", " ")};`); + if (op.body) { + const bt = op.body.kind === "json" ? (op.body.schema ? tsType(api.root, op.body.schema, namer, "T.", " ") : "unknown") : op.body.kind === "multipart" ? (op.body.schema ? `${tsType(api.root, op.body.schema, namer, "T.", " ")} | FormData` : "FormData") : op.body.kind === "form" ? (op.body.schema ? `${tsType(api.root, op.body.schema, namer, "T.", " ")} | URLSearchParams` : "URLSearchParams") : op.body.kind === "text" ? "string" : "Blob | ArrayBuffer | Uint8Array"; + fields.push(`${doc([`Request body (${op.body.contentType})`], " ")} body${op.body.required ? "" : "?"}: ${bt};`); + } + const hasArgs = fields.length > 0, argsOptional = !op.params.some((p) => p.required) && !op.body?.required; + if (hasArgs) argTypes.push(`/** Arguments of {@link ${o.className}.${op.id}}. */\nexport interface ${P}Args {\n${fields.join("\n")}\n}\n`); + argTypes.push(`/** Successful response of {@link ${o.className}.${op.id}} (${op.success?.status ?? "none"}). */\nexport type ${P}Response = ${respType(api, op.success, namer, "T.")};\n`); + const errs = op.errors.filter((r) => r.kind === "json" && r.schema).map((r) => tsType(api.root, r.schema, namer, "T.")); + argTypes.push(`/** Error response bodies documented for ${op.id} (${op.errors.map((r) => r.status).join(", ") || "none"}); available as \`ApiError.body\`. */\nexport type ${P}ErrorBody = ${[...new Set(errs)].join(" | ") || "unknown"};\n`); + const q = op.params.filter((p) => p.in === "query"), hdr = op.params.filter((p) => p.in === "header"); + const pathExpr = "`" + op.path.replace(/`/g, "\\`").replace(/\$\{/g, "\\${").replace(/\{([^}]+)\}/g, (_, n) => `\${encodeURIComponent(String(args.${op.params.find((p) => p.in === "path" && p.name === n)!.ident}))}`) + "`"; + const sig = hasArgs ? `args: ${P}Args${argsOptional ? " = {}" : ""}, options: RequestOptions = {}` : "options: RequestOptions = {}"; + opBlocks.push(`${doc([op.summary, op.description && op.description !== op.summary ? op.description : undefined, `\`${op.method} ${op.path}\``, op.deprecated ? "@deprecated" : undefined, `@throws {ApiError} on a non-2xx response${op.errors.length ? ` (documented: ${op.errors.map((r) => r.status).join(", ")})` : ""}`], " ")} async ${op.id}(${sig}): Promise<${P}Response> { + return this.request<${P}Response>({ + operation: ${JSON.stringify(op.id)}, method: ${JSON.stringify(op.method)}, path: ${hasArgs ? pathExpr : JSON.stringify(op.path)},${q.length ? `\n query: { ${q.map((p) => `${JSON.stringify(p.name)}: args.${p.ident}`).join(", ")} },` : ""}${hdr.length ? `\n headers: { ${hdr.map((p) => `${JSON.stringify(p.name)}: args.${p.ident}`).join(", ")} },` : ""}${op.body ? `\n body: args.body, bodyType: ${JSON.stringify(op.body.kind)}, contentType: ${JSON.stringify(op.body.contentType)},` : ""} + security: ${JSON.stringify(op.security)}, response: ${JSON.stringify(op.success?.status === "204" || !op.success?.contentType ? "none" : op.success.kind === "json" ? "json" : op.success.kind === "text" ? "text" : "blob")}, + }, options); + }`); + } + const schemeMap = Object.fromEntries(api.schemes.map((s) => [s.name, s.type === "apiKey" ? { type: "apiKey", in: s.in, name: s.param } : { type: s.type }])); + const client = `// Generated by API To SDK from “${api.title}” ${api.version}. Do not edit by hand; regenerate instead. +import type * as T from "./types.js"; + +export interface ClientOptions { + /** Base URL of the API${api.server ? ` (default ${api.server})` : ""}. */ + baseUrl?: string; +${bearer ? ` /** Bearer / access token, or a function returning one (called per request). */\n token?: string | (() => string | undefined | Promise);\n` : ""}${apiKeys.length ? ` /** API key (${apiKeys.map((s) => `${s.in} \`${s.param}\``).join(", ")}). */\n apiKey?: string;\n` : ""}${basic ? " /** HTTP basic credentials. */\n basic?: { username: string; password: string };\n" : ""} /** Headers sent with every request. */ + headers?: Record; + /** Custom fetch (defaults to globalThis.fetch). */ + fetch?: typeof fetch; + /** Abort requests after this many milliseconds. */ + timeoutMs?: number; +} + +export interface RequestOptions { + /** Extra headers for this request. */ + headers?: Record; + signal?: AbortSignal; +} + +/** Thrown for every non-2xx response. \`body\` is the parsed JSON (or text) of the error response. */ +export class ApiError extends Error { + constructor(readonly status: number, readonly body: TBody, readonly operation: string, readonly response: Response) { + super(\`\${operation} failed with HTTP \${status}\${body && typeof body === "object" && "message" in body ? \`: \${String((body as { message: unknown }).message)}\` : ""}\`); + this.name = "ApiError"; + } +} + +interface Call { + operation: string; method: string; path: string; + query?: Record; headers?: Record; + body?: unknown; bodyType?: "json" | "multipart" | "form" | "text" | "binary"; contentType?: string; + security: string[][]; response: "json" | "text" | "blob" | "none"; +} + +const SCHEMES: Record = ${JSON.stringify(schemeMap)}; + +${doc([`Client for ${api.title} ${api.version}.`, api.description?.split("\n")[0], "", "@example", "```ts", `const api = new ${o.className}({ ${bearer ? 'token: process.env.API_TOKEN' : apiKeys.length ? "apiKey: process.env.API_KEY" : `baseUrl: "${api.server ?? "https://api.example.com"}"`} });`, api.ops[0] ? `const result = await api.${api.ops[0].id}(${api.ops[0].params.some((p) => p.required) || api.ops[0].body?.required ? "{ /* … */ }" : ""});` : "", "```"])}export class ${o.className} { + readonly baseUrl: string; + constructor(private readonly options: ClientOptions = {}) { + this.baseUrl = (options.baseUrl ?? ${JSON.stringify(api.server ?? "")}).replace(/\\/+$/, ""); + } + +${opBlocks.join("\n\n")} + + private async request(c: Call, o: RequestOptions): Promise { + const url = new URL(this.baseUrl + c.path, this.baseUrl ? undefined : "http://localhost"); + for (const [k, v] of Object.entries(c.query ?? {})) { + if (v === undefined || v === null) continue; + if (Array.isArray(v)) for (const x of v) url.searchParams.append(k, String(x)); + else url.searchParams.set(k, typeof v === "object" ? JSON.stringify(v) : String(v)); + } + const headers: Record = { Accept: c.response === "json" ? "application/json" : "*/*", ...this.options.headers }; + for (const [k, v] of Object.entries(c.headers ?? {})) if (v !== undefined && v !== null) headers[k] = String(v); + await this.authorize(c.security, headers, url); + let body: BodyInit | undefined; + if (c.body !== undefined) { + if (c.bodyType === "json") { body = JSON.stringify(c.body); headers["Content-Type"] = c.contentType ?? "application/json"; } + else if (c.bodyType === "multipart") body = c.body instanceof FormData ? c.body : toFormData(c.body as Record); + else if (c.bodyType === "form") { body = c.body instanceof URLSearchParams ? c.body : new URLSearchParams(Object.entries(c.body as Record).filter(([, v]) => v != null).map(([k, v]) => [k, String(v)])); } + else { body = c.body as BodyInit; if (c.contentType) headers["Content-Type"] = c.contentType; } + } + Object.assign(headers, o.headers); + const signals = [o.signal, this.options.timeoutMs ? AbortSignal.timeout(this.options.timeoutMs) : undefined].filter((s): s is AbortSignal => !!s); + const signal = signals.length > 1 ? AbortSignal.any(signals) : signals[0]; + const res = await (this.options.fetch ?? globalThis.fetch)(url, { method: c.method, headers, body, signal }); + if (!res.ok) { + const text = await res.text(); + let parsed: unknown = text; + try { parsed = text ? JSON.parse(text) : undefined; } catch { /* keep text */ } + throw new ApiError(res.status, parsed, c.operation, res); + } + if (c.response === "none" || res.status === 204) return undefined as R; + if (c.response === "json") { const text = await res.text(); if (!text) return undefined as R; if (!/json/i.test(res.headers.get("content-type") ?? "json")) return text as R; return JSON.parse(text) as R; } + if (c.response === "text") return (await res.text()) as R; + return (await res.blob()) as R; + } + + private async authorize(security: string[][], headers: Record, url: URL) { + for (const alternative of security) { + const parts: (() => void)[] = []; + let ok = true; + for (const name of alternative) { + const s = SCHEMES[name]; + if (!s) { ok = false; break; } +${bearer ? ` if (s.type === "bearer" || s.type === "oauth2" || s.type === "other") { + const t = typeof this.options.token === "function" ? await this.options.token() : this.options.token; + if (!t) { ok = false; break; } + parts.push(() => { headers.Authorization = \`Bearer \${t}\`; }); + } +` : ""}${apiKeys.length ? ` if (s.type === "apiKey") { + const k = this.options.apiKey; + if (!k) { ok = false; break; } + parts.push(() => { if (s.in === "query") url.searchParams.set(s.name!, k); else if (s.in === "cookie") headers.Cookie = \`\${s.name}=\${encodeURIComponent(k)}\`; else headers[s.name!] = k; }); + } +` : ""}${basic ? ` if (s.type === "basic") { + const b = this.options.basic; + if (!b) { ok = false; break; } + parts.push(() => { headers.Authorization = \`Basic \${btoa(\`\${b.username}:\${b.password}\`)}\`; }); + } +` : ""} } + if (ok) { for (const p of parts) p(); return; } + } + void headers; void url; + } +} + +function toFormData(o: Record): FormData { + const f = new FormData(); + for (const [k, v] of Object.entries(o ?? {})) { + if (v === undefined || v === null) continue; + for (const x of Array.isArray(v) ? v : [v]) f.append(k, x instanceof Blob ? x : typeof x === "object" ? JSON.stringify(x) : String(x)); + } + return f; +} + +${argTypes.join("\n")}`; + const index = `export * from "./client.js";\nexport type * from "./types.js";\n`; + return { "src/types.ts": types.join("\n"), "src/client.ts": client, "src/index.ts": index }; +} diff --git a/ui-plugins/api-to-sdk/src/main.ts b/ui-plugins/api-to-sdk/src/main.ts new file mode 100644 index 00000000..b2df0746 --- /dev/null +++ b/ui-plugins/api-to-sdk/src/main.ts @@ -0,0 +1,14 @@ +import "./kit/console.ts"; +import { dirname, resolve } from "node:path"; +import { fileURLToPath } from "node:url"; +import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"; +import { createServer } from "./server.ts"; + +const here = dirname(fileURLToPath(import.meta.url)); +const server = createServer({ + workspaceRoot: resolve(process.env.ZCODE_WORKSPACE_ROOT || process.cwd()), + assetRoot: here, + log: (line) => process.stderr.write(`[api-to-sdk] ${line}\n`), +}); +process.stdin.once("end", () => process.exit(0)); +await server.connect(new StdioServerTransport()); diff --git a/ui-plugins/api-to-sdk/src/openapi.ts b/ui-plugins/api-to-sdk/src/openapi.ts new file mode 100644 index 00000000..d093b8a2 --- /dev/null +++ b/ui-plugins/api-to-sdk/src/openapi.ts @@ -0,0 +1,102 @@ +import YAML from "yaml"; +// @ts-expect-error plain JS runtime +import { deref, mediaExample, mediaKind, synth } from "./runtime/mock.mjs"; + +export type Json = any; // eslint-disable-line @typescript-eslint/no-explicit-any +export interface Param { name: string; in: "path" | "query" | "header" | "cookie"; required: boolean; schema: Json; description?: string; example?: Json; ident: string; deprecated?: boolean } +export interface Body { required: boolean; contentType: string; kind: "json" | "multipart" | "form" | "text" | "binary"; schema?: Json; example?: Json } +export interface Resp { status: string; description?: string; contentType?: string; kind?: "json" | "text" | "binary" | "multipart" | "form"; schema?: Json; example?: Json } +export interface Op { id: string; method: string; path: string; tag?: string; summary?: string; description?: string; deprecated?: boolean; params: Param[]; body?: Body; responses: Resp[]; success?: Resp; errors: Resp[]; security: string[][]; derivedId: boolean } +export interface Scheme { name: string; type: "bearer" | "basic" | "apiKey" | "oauth2" | "other"; in?: "header" | "query" | "cookie"; param?: string } +export interface Api { root: Json; title: string; version: string; description?: string; server?: string; ops: Op[]; schemes: Scheme[]; schemas: string[]; warnings: string[]; openapi: string } + +export function parseSpec(text: string, file = "spec"): Json { + const t = text.replace(/^\uFEFF/, ""); + try { return /^\s*[{[]/.test(t) ? JSON.parse(t) : YAML.parse(t, { maxAliasCount: 1000 }); } + catch (e) { throw new Error(`${file} is not valid ${/^\s*[{[]/.test(t) ? "JSON" : "YAML"}: ${(e as Error).message.split("\n")[0]}`); } +} + +export const camel = (s: string) => { + const parts = s.replace(/([a-z0-9])([A-Z])/g, "$1 $2").split(/[^A-Za-z0-9]+/).filter(Boolean); + const c = parts.map((p, i) => (i === 0 ? p.toLowerCase() : p[0].toUpperCase() + p.slice(1).toLowerCase())).join("") || "x"; + return /^\d/.test(c) ? `_${c}` : c; +}; +/** operationId → method name: keep camelCase ids as written, normalise others. */ +export const methodName = (id: string) => (/^[a-z][A-Za-z0-9]*$/.test(id) ? id : camel(id)); +export const pascal = (s: string) => { const c = camel(s); return c[0].toUpperCase() + c.slice(1); }; +const RESERVED = new Set("break case catch class const continue debugger default delete do else enum export extends false finally for function if import in instanceof new null return super switch this throw true try typeof var void while with yield let static implements interface package private protected public await".split(" ")); +export const safeIdent = (s: string) => (RESERVED.has(s) ? `${s}_` : s); + +export function loadApi(doc: Json): Api { + if (!doc || typeof doc !== "object") throw new Error("The file does not contain an OpenAPI document."); + if (doc.swagger) throw new Error(`This is a Swagger ${doc.swagger} (OpenAPI 2) document. Convert it to OpenAPI 3 first (for example with swagger2openapi or editor.swagger.io).`); + if (!/^3\.[01]\./.test(String(doc.openapi ?? ""))) throw new Error(`Unsupported OpenAPI version “${doc.openapi ?? "(missing)"}”. Use OpenAPI 3.0 or 3.1.`); + const root = doc, warnings: string[] = []; + const d = (x: Json) => { try { return deref(root, x); } catch (e) { warnings.push((e as Error).message); return undefined; } }; + // every $ref must be local and resolvable + const walk = (n: Json, path: string) => { if (!n || typeof n !== "object") return; if (typeof n.$ref === "string") { if (!n.$ref.startsWith("#/")) warnings.push(`External $ref not supported (treated as unknown): ${n.$ref} at ${path}`); else { try { deref(root, n); } catch { warnings.push(`Unresolvable $ref ${n.$ref} at ${path}`); } } return; } for (const [k, v] of Object.entries(n)) walk(v, `${path}/${k}`); }; + walk(doc.paths, "#/paths"); + const schemes: Scheme[] = Object.entries(doc.components?.securitySchemes ?? {}).map(([name, raw]) => { + const s = d(raw) ?? {}; + if (s.type === "http" && /^bearer$/i.test(s.scheme)) return { name, type: "bearer" as const }; + if (s.type === "http" && /^basic$/i.test(s.scheme)) return { name, type: "basic" as const }; + if (s.type === "apiKey") return { name, type: "apiKey" as const, in: s.in, param: s.name }; + if (s.type === "oauth2" || s.type === "openIdConnect") return { name, type: "oauth2" as const }; + return { name, type: "other" as const }; + }); + const ops: Op[] = []; + const used = new Map(); + for (const [p, item0] of Object.entries(doc.paths ?? {})) { + const item = d(item0) ?? {}; + for (const method of ["get", "put", "post", "delete", "patch", "head", "options", "trace"]) { + const o = item[method]; + if (!o) continue; + const derived = !o.operationId; + let id = methodName(o.operationId ?? `${method} ${p.replace(/\{([^}]+)\}/g, "by $1")}`); + const n = used.get(id) ?? 0; used.set(id, n + 1); if (n) { warnings.push(`Duplicate operationId ${id}; renamed to ${id}${n + 1}`); id = `${id}${n + 1}`; } + const merged = new Map(); + for (const raw of [...(item.parameters ?? []), ...(o.parameters ?? [])]) { const prm = d(raw); if (prm?.name && prm.in) merged.set(`${prm.in}:${prm.name}`, prm); } + const idents = new Set(); + const params: Param[] = [...merged.values()].filter((x) => x.in !== "cookie" || (warnings.push(`${id}: cookie parameter ${x.name} is not supported; skipped`), false)).map((x) => { + let ident = safeIdent(camel(x.name)); while (idents.has(ident) || ident === "body") ident = `${ident}_`; idents.add(ident); + const ex = x.example !== undefined ? x.example : x.examples ? d(Object.values(x.examples)[0])?.value : undefined; + return { name: x.name, in: x.in, required: x.in === "path" ? true : !!x.required, schema: x.schema ?? (x.content ? Object.values(x.content)[0]?.schema : { type: "string" }) ?? {}, description: x.description, example: ex, ident, deprecated: x.deprecated }; + }); + for (const m of p.matchAll(/\{([^}]+)\}/g)) if (!params.find((x) => x.in === "path" && x.name === m[1])) { warnings.push(`${id}: path parameter {${m[1]}} is not declared; added as string`); params.push({ name: m[1], in: "path", required: true, schema: { type: "string" }, ident: safeIdent(camel(m[1])) }); } + let body: Body | undefined; + const rb = d(o.requestBody); + if (rb?.content) { + const entries = Object.entries(rb.content); + const pick = entries.find(([k]) => mediaKind(k) === "json") ?? entries.find(([k]) => mediaKind(k) === "multipart") ?? entries.find(([k]) => mediaKind(k) === "form") ?? entries[0]; + if (pick) body = { required: !!rb.required, contentType: pick[0], kind: mediaKind(pick[0]), schema: pick[1]?.schema, example: mediaExample(root, pick[1]) }; + } + const responses: Resp[] = Object.entries(o.responses ?? {}).map(([status, raw]) => { + const r = d(raw) ?? {}; + const entries = Object.entries(r.content ?? {}); + const pick = entries.find(([k]) => mediaKind(k) === "json") ?? entries[0]; + return { status, description: r.description, contentType: pick?.[0], kind: pick ? mediaKind(pick[0]) : undefined, schema: pick?.[1]?.schema, example: pick ? mediaExample(root, pick[1]) : undefined }; + }); + const success = responses.find((r) => /^2\d\d$/.test(r.status)) ?? responses.find((r) => /^2XX$/i.test(r.status)) ?? responses.find((r) => r.status === "default"); + const sec = (o.security ?? doc.security ?? []) as Json[]; + ops.push({ id, method: method.toUpperCase(), path: p, tag: o.tags?.[0], summary: o.summary, description: o.description, deprecated: o.deprecated, params, body, responses, success, errors: responses.filter((r) => /^[45]\d\d$/.test(r.status) || /^[45]XX$/i.test(r.status) || (r.status === "default" && r !== success)), security: sec.map((s: Json) => Object.keys(s ?? {})), derivedId: derived }); + } + } + if (!ops.length) throw new Error("The spec has no operations under paths."); + for (const op of ops) for (const alt of op.security) for (const s of alt) if (!schemes.find((x) => x.name === s)) warnings.push(`${op.id}: unknown security scheme ${s}`); + for (const s of schemes) if (s.type === "oauth2" || s.type === "other") warnings.push(`Security scheme ${s.name} (${s.type}): pass an access token with the token option; the OAuth flow itself is not generated.`); + const server = doc.servers?.[0]?.url ? String(doc.servers[0].url).replace(/\{(\w+)\}/g, (_: string, v: string) => doc.servers[0].variables?.[v]?.default ?? v) : undefined; + return { root, title: doc.info?.title ?? "API", version: String(doc.info?.version ?? "0.0.0"), description: doc.info?.description, server, ops, schemes, schemas: Object.keys(doc.components?.schemas ?? {}), warnings, openapi: String(doc.openapi) }; +} + +/** Example arguments for an operation: from parameter/body examples, else synthesised. */ +export function exampleArgs(api: Api, op: Op): Record { + const args: Record = {}; + for (const p of op.params) { + if (!p.required && p.example === undefined && p.in !== "path") continue; + let v = p.example !== undefined ? p.example : synth(api.root, p.schema, 0, p.name); + if (p.in === "path" && (v === null || v === undefined)) v = "1"; + args[p.ident] = v; + } + if (op.body) args.body = op.body.example !== undefined ? op.body.example : synth(api.root, op.body.schema ?? {}, 0); + return args; +} diff --git a/ui-plugins/api-to-sdk/src/server.ts b/ui-plugins/api-to-sdk/src/server.ts new file mode 100644 index 00000000..19244c59 --- /dev/null +++ b/ui-plugins/api-to-sdk/src/server.ts @@ -0,0 +1,171 @@ +import { readFile } from "node:fs/promises"; +import { basename, extname, join } from "node:path"; +import { z } from "zod"; +import { createKitServer } from "./kit/server-kit.ts"; +import { KitError, Workspace } from "./kit/workspace.ts"; +import { generate } from "./codegen.ts"; +import { type Api, type Op, loadApi, parseSpec, pascal } from "./openapi.ts"; +import { type Verify, compile, examplesFile, runAgainstMock } from "./verify.ts"; + +export const NAME = "api-to-sdk"; +export const VERSION = "0.1.0"; +export const PANEL_URI = `ui://${NAME}/panel.html`; +const STORE = ".api-to-sdk/sdks.json"; +const SPEC_EXT = [".yaml", ".yml", ".json"]; + +export interface ServerOptions { workspaceRoot: string; assetRoot: string; log?: (line: string) => void } +interface Saved { spec: string; out: string; packageName: string; className: string; title: string; version: string; ops: number; generatedAt: string; verify?: Verify; warnings: string[] } + +const slug = (s: string) => s.normalize("NFKD").replace(/[^\w-]+/g, "-").replace(/-{2,}/g, "-").replace(/^-+|-+$/g, "").toLowerCase().slice(0, 50) || "api"; +const opSummary = (o: Op) => ({ id: o.id, method: o.method, path: o.path, tag: o.tag, summary: o.summary, params: o.params.map((p) => `${p.in}:${p.name}${p.required ? "*" : ""}`), body: o.body ? `${o.body.contentType}${o.body.required ? "*" : ""}` : null, success: o.success?.status ?? null, errors: o.errors.map((r) => r.status), auth: o.security.map((a) => a.join("+") || "none").join(" | ") || "none", derivedId: o.derivedId }); + +export function createServer(options: ServerOptions) { + const ws = new Workspace(options.workspaceRoot); + const { server, tool } = createKitServer({ name: NAME, version: VERSION, panelUri: PANEL_URI, surface: "editor", panelHtml: () => readFile(join(options.assetRoot, "ui/panel.html"), "utf8"), log: options.log }); + const libDir = join(options.assetRoot, "types/ts-lib"); + const runtime = join(options.assetRoot, "runtime"); + const load = async (): Promise> => ((await ws.exists(STORE)) ? JSON.parse(await ws.readText(STORE)).sdks ?? {} : {}); + const save = async (all: Record) => ws.write(STORE, JSON.stringify({ version: 1, sdks: all }, null, 1) + "\n"); + + async function readApi(spec: string): Promise { + if (!SPEC_EXT.some((e) => spec.toLowerCase().endsWith(e))) throw new KitError("unsupported", `Use an OpenAPI 3 file (${SPEC_EXT.join(", ")}).`); + if (!(await ws.exists(spec))) throw new KitError("not_found", `${spec} not found.`); + try { return loadApi(parseSpec(await ws.readText(spec), spec)); } catch (e) { throw new KitError("bad_spec", (e as Error).message); } + } + const describeTest = (v: Verify) => [ + `TypeScript (strict): ${v.compiled ? "compiled with no errors" : `${v.diagnostics.length} error(s)`}${v.exampleWarnings.length ? `; ${v.exampleWarnings.length} spec example(s) don't match their schema (see examples/all-operations.ts)` : ""}.`, + ...v.diagnostics.slice(0, 15).map((d) => ` ✗ ${d.file}${d.line ? `:${d.line}` : ""} ${d.message}`), + ...v.exampleWarnings.slice(0, 10).map((d) => ` ! ${d.file}${d.line ? `:${d.line}` : ""} ${d.message.split("\n")[0]}`), + v.ops.length ? `Mock-server calls: ${v.passed}/${v.ops.length} operation(s) passed in ${(v.ms / 1000).toFixed(1)} s.` : "Mock-server calls skipped (compile failed).", + ...v.ops.filter((o) => !o.ok).map((o) => ` ✗ ${o.op} (${o.method} ${o.path}): ${o.problems.join("; ")}`), + ].join("\n"); + + async function verify(api: Api, s: Saved, files: Record): Promise { + const t0 = Date.now(); + const src = Object.fromEntries(Object.entries(files).filter(([p]) => p.startsWith("src/"))); + const { diags, dist } = compile(src, libDir, true); + const ex = diags.length ? { diags: [] } : compile({ ...src, "examples/all-operations.ts": files["examples/all-operations.ts"] }, libDir, false); + const exampleWarnings = ex.diags.filter((d) => d.file.startsWith("examples/")); + for (const [p, c] of Object.entries(dist)) await ws.write(`${s.out}/${p}`, c); + const ops = diags.length ? [] : await runAgainstMock(api, dist, s.className); + const passed = ops.filter((o) => o.ok).length; + return { compiled: !diags.length, diagnostics: diags, exampleWarnings, ops, passed, failed: ops.length - passed + (diags.length ? 1 : 0), ms: Date.now() - t0 }; + } + + tool("sdk_inspect", { + description: "Read an OpenAPI 3.0/3.1 spec (YAML or JSON) without writing anything: operations (method, path, parameters, body, responses, auth), schemas, security schemes and problems such as external or broken $refs, missing operationIds and duplicate ids.", + input: { spec: z.string().describe("Workspace path of the OpenAPI file") }, readOnly: true, openPanel: true, + }, async (i) => { + const api = await readApi(i.spec); + const all = await load(); + const saved = Object.values(all).find((x) => x.spec === i.spec) ?? null; + return { + text: [`${api.title} ${api.version} (OpenAPI ${api.openapi})${api.server ? ` — ${api.server}` : ""}: ${api.ops.length} operation(s), ${api.schemas.length} schema(s), auth: ${api.schemes.map((s) => `${s.name}=${s.type}`).join(", ") || "none"}.`, ...api.ops.map((o) => ` ${o.method.padEnd(6)} ${o.path} → ${o.id}${o.derivedId ? " (no operationId; derived)" : ""}`), api.warnings.length ? `Warnings:\n${api.warnings.map((w) => ` ! ${w}`).join("\n")}` : "No warnings."].join("\n"), + structured: { kind: "api", spec: i.spec, api: { title: api.title, version: api.version, openapi: api.openapi, server: api.server, schemes: api.schemes, schemas: api.schemas, warnings: api.warnings, ops: api.ops.map(opSummary) }, saved }, + }; + }); + + tool("sdk_generate", { + description: "Generate a typed TypeScript SDK package from an OpenAPI 3 spec: types for every schema, a fetch-based client class with one method per operation (path/query/header parameters, JSON / multipart / form bodies, bearer / API key / basic auth, timeouts, ApiError with the parsed error body), README with an operation table, an example calling every operation, and a dependency-free mock server built from the spec's examples. Then verifies it: compiles with TypeScript strict, and calls every operation against the mock (checking the request matched the spec and the response was parsed, plus one documented error status).", + input: { + spec: z.string().describe("Workspace path of the OpenAPI file"), + out: z.string().optional().describe("Output folder (default sdk/)"), + packageName: z.string().optional().describe("npm package name (default -sdk)"), + className: z.string().optional().describe("Client class name (default Client)"), + }, + openPanel: true, timeoutMs: 180_000, + }, async (i) => { + const api = await readApi(i.spec); + const all = await load(); + const prev = Object.values(all).find((x) => x.spec === i.spec && (!i.out || x.out === i.out)); + const base = slug(api.title.replace(/\b(api|openapi|rest)\b/gi, "")) || slug(basename(i.spec, extname(i.spec))); + const className = i.className ?? prev?.className ?? `${pascal(api.title.replace(/\b(api|openapi|rest)\b/gi, "")) || "Api"}Client`; + if (!/^[A-Z][A-Za-z0-9_]*$/.test(className)) throw new KitError("bad_name", `className must be a PascalCase identifier (got ${className}).`); + const packageName = i.packageName ?? prev?.packageName ?? `${base}-sdk`; + if (!/^(@[a-z0-9-~][a-z0-9-._~]*\/)?[a-z0-9-~][a-z0-9-._~]*$/.test(packageName)) throw new KitError("bad_name", `Invalid npm package name: ${packageName}`); + const out = (i.out ?? prev?.out ?? `sdk/${base}`).replace(/\\/g, "/").replace(/\/+$/, ""); + if (out === "." || out.startsWith("..") || out.startsWith("/")) throw new KitError("bad_out", "Choose an output folder inside the workspace."); + const files: Record = { ...generate(api, { className, packageName }) }; + files["examples/all-operations.ts"] = examplesFile(api, className, packageName); + files["mock/mock.mjs"] = await readFile(join(runtime, "mock.mjs"), "utf8"); + files["mock/server.mjs"] = `#!/usr/bin/env node\n// Mock of ${api.title} built from mock/openapi.json. Usage: node mock/server.mjs [port]\nimport { readFileSync } from "node:fs";\nimport { startMock } from "./mock.mjs";\nconst spec = JSON.parse(readFileSync(new URL("./openapi.json", import.meta.url), "utf8"));\nconst m = await startMock(spec, Number(process.argv[2] ?? process.env.PORT ?? 4010), process.env.HOST ?? "127.0.0.1", { log: (l) => console.log(l) });\nconsole.log(\`Mock ${api.title.replace(/[`$\\]/g, "")} on http://127.0.0.1:\${m.port} (\${m.routes.length} operations). Use "Prefer: code=404" to get a documented error.\`);\n`; + files["mock/openapi.json"] = JSON.stringify(api.root, null, 1) + "\n"; + files["package.json"] = JSON.stringify({ name: packageName, version: api.version.replace(/^v/, "").match(/^\d+\.\d+\.\d+/) ? api.version.replace(/^v/, "") : "0.1.0", description: `TypeScript client for ${api.title}`, type: "module", main: "dist/index.js", types: "dist/index.d.ts", exports: { ".": { types: "./dist/index.d.ts", import: "./dist/index.js" } }, files: ["dist", "src"], scripts: { build: "tsc -p .", mock: "node mock/server.mjs", example: "npx tsx examples/all-operations.ts" }, engines: { node: ">=20" }, devDependencies: { typescript: "^6.0.2" } }, null, 2) + "\n"; + files["tsconfig.json"] = JSON.stringify({ compilerOptions: { strict: true, target: "ES2022", module: "NodeNext", moduleResolution: "NodeNext", lib: ["ES2022", "DOM", "DOM.Iterable"], declaration: true, outDir: "dist", rootDir: "src", skipLibCheck: true, types: [] }, include: ["src"] }, null, 2) + "\n"; + files["README.md"] = readme(api, className, packageName); + for (const [p, c] of Object.entries(files)) await ws.write(`${out}/${p}`, c); + const s: Saved = { spec: i.spec, out, packageName, className, title: api.title, version: api.version, ops: api.ops.length, generatedAt: new Date().toISOString(), warnings: api.warnings }; + s.verify = await verify(api, s, files); + for (const k of Object.keys(all)) if (all[k].spec === i.spec && all[k].out !== out && prev && k === prev.out) delete all[k]; + all[out] = s; await save(all); + return { + text: [`Generated ${out}/ — ${packageName} (${className}) for ${api.title} ${api.version}: ${api.ops.length} method(s), ${api.schemas.length} type(s).`, describeTest(s.verify), api.warnings.length ? `Spec warnings:\n${api.warnings.map((w) => ` ! ${w}`).join("\n")}` : "", `Use it: import { ${className} } from "./${out}/dist/index.js" (or npm install ./${out}); mock: node ${out}/mock/server.mjs.`].filter(Boolean).join("\n"), + structured: { kind: "sdk", saved: s, files: Object.keys(files).concat(Object.keys(s.verify.ops.length ? { "dist/": 1 } : {})), preview: files["src/client.ts"].slice(0, 12000) }, + }; + }); + + tool("sdk_test", { + description: "Re-verify a generated SDK: strict TypeScript compile and calls of every operation against a mock server built from the spec (for example after editing the spec or the generated code).", + input: { out: z.string().describe("Generated SDK folder") }, readOnly: true, timeoutMs: 180_000, + }, async (i) => { + const all = await load(); + const s = all[i.out.replace(/\/+$/, "")]; + if (!s) throw new KitError("not_found", `No SDK generated at ${i.out}. Known: ${Object.keys(all).join(", ") || "none"}`); + const api = await readApi(s.spec); + const files: Record = {}; + for (const p of ["src/types.ts", "src/client.ts", "src/index.ts", "examples/all-operations.ts"]) files[p] = await ws.readText(`${s.out}/${p}`); + s.verify = await verify(api, s, files); + await save(all); + return { text: describeTest(s.verify), structured: { kind: "sdk", saved: s } }; + }); + + tool("sdk_state", { description: "Panel state.", input: {}, visibility: ["app"], readOnly: true }, async () => { + const all = Object.values(await load()).sort((a, b) => b.generatedAt.localeCompare(a.generatedAt)); + const files = (await ws.list({ exts: SPEC_EXT })).map((f) => f.path).filter((f) => !/(^|\/)(package|tsconfig|package-lock)\.json$|\/mock\/openapi\.json$|^\.api-to-sdk\//.test(f)); + return { text: "", structured: { kind: all[0] ? "sdk" : "none", saved: all[0] ?? null, files } }; + }); + return server; +} + +function readme(api: Api, cls: string, pkg: string) { + const auth = api.schemes.map((s) => s.type === "bearer" || s.type === "oauth2" || s.type === "other" ? "`token`" : s.type === "apiKey" ? "`apiKey`" : "`basic`"); + return `# ${pkg} + +TypeScript client for **${api.title}** ${api.version}, generated by API To SDK from the OpenAPI ${api.openapi} spec. No runtime dependencies (uses \`fetch\`; Node 20+, Deno, Bun, browsers). + +## Build + +\`\`\`bash +npm install && npm run build # → dist/ (already built once by the generator) +\`\`\` + +## Use + +\`\`\`ts +import { ${cls}, ApiError } from "${pkg}"; + +const api = new ${cls}({${api.server ? "" : ' baseUrl: "https://…",'}${[...new Set(auth)].map((a) => ` ${a.slice(1, -1)}: ${a === "`basic`" ? '{ username: "…", password: "…" }' : '"…"'}`).join(",")} }); +try { + ${api.ops[0] ? `const result = await api.${api.ops[0].id}(${api.ops[0].params.some((p) => p.required) || api.ops[0].body?.required ? "{ /* … */ }" : ""});` : ""} +} catch (e) { + if (e instanceof ApiError) console.error(e.status, e.body); +} +\`\`\` + +Options: \`baseUrl\`${api.server ? ` (default \`${api.server}\`)` : ""}, ${[...new Set(auth)].join(", ")}${auth.length ? ", " : ""}\`headers\`, \`fetch\`, \`timeoutMs\`. Every method also takes \`{ headers, signal }\` as its last argument. + +## Operations + +| Method | HTTP | Summary | +|---|---|---| +${api.ops.map((o) => `| \`${o.id}\` | \`${o.method} ${o.path}\` | ${(o.summary ?? "").replace(/\|/g, "\\|")} |`).join("\n")} + +## Mock server + +\`\`\`bash +npm run mock # http://127.0.0.1:4010, answers from the spec's examples and checks requests against the spec +\`\`\` + +Send \`Prefer: code=404\` to get a documented error response. \`examples/all-operations.ts\` calls every operation with the spec's example values. +`; +} diff --git a/ui-plugins/api-to-sdk/src/verify.ts b/ui-plugins/api-to-sdk/src/verify.ts new file mode 100644 index 00000000..bbf4a45a --- /dev/null +++ b/ui-plugins/api-to-sdk/src/verify.ts @@ -0,0 +1,117 @@ +import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { pathToFileURL } from "node:url"; +import ts from "typescript"; +import { type Api, type Json, exampleArgs } from "./openapi.ts"; +// @ts-expect-error plain JS runtime +import { startMock } from "./runtime/mock.mjs"; + +export interface Diag { file: string; line?: number; message: string } +export interface OpResult { op: string; method: string; path: string; ok: boolean; checks: string[]; problems: string[] } +export interface Verify { compiled: boolean; diagnostics: Diag[]; exampleWarnings: Diag[]; ops: OpResult[]; passed: number; failed: number; ms: number } + +const OPTIONS: ts.CompilerOptions = { + strict: true, target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.NodeNext, moduleResolution: ts.ModuleResolutionKind.NodeNext, + lib: ["lib.es2022.d.ts", "lib.dom.d.ts", "lib.dom.iterable.d.ts", "lib.esnext.disposable.d.ts"], types: [], declaration: true, sourceMap: false, outDir: "/pkg/dist", rootDir: "/pkg/src", + skipLibCheck: true, noUnusedLocals: false, isolatedModules: true, verbatimModuleSyntax: false, +}; + +/** Compile files (paths relative to the package) in memory. Returns emitted dist files and diagnostics for each root group. */ +export function compile(files: Record, libDir: string, emit: boolean) { + const vfs = new Map(Object.entries(files).map(([p, s]) => [`/pkg/${p}`, s])); + vfs.set("/pkg/package.json", JSON.stringify({ type: "module" })); + const read = (f: string) => vfs.get(f) ?? (f.startsWith("/lib/") ? (() => { try { return readFileSync(join(libDir, f.slice(5)), "utf8"); } catch { return undefined; } })() : undefined); + const out: Record = {}; + const host: ts.CompilerHost = { + getSourceFile: (f, v) => { const s = read(f); return s === undefined ? undefined : ts.createSourceFile(f, s, v, true); }, + getDefaultLibFileName: () => "/lib/lib.d.ts", getDefaultLibLocation: () => "/lib", + writeFile: (f, data) => { if (f.startsWith("/pkg/dist/")) out[f.slice(5)] = data; }, + getCurrentDirectory: () => "/pkg", getCanonicalFileName: (f) => f, useCaseSensitiveFileNames: () => true, getNewLine: () => "\n", + fileExists: (f) => read(f) !== undefined, readFile: read, + directoryExists: (d) => d === "/lib" || [...vfs.keys()].some((k) => k.startsWith(d.endsWith("/") ? d : `${d}/`)), getDirectories: () => [], + }; + const roots = [...vfs.keys()].filter((f) => /\.ts$/.test(f)); + const program = ts.createProgram(roots, { ...OPTIONS, rootDir: "/pkg", outDir: "/pkg/dist", noEmit: !emit }, host); + const diags = ts.getPreEmitDiagnostics(program).map((d) => ({ file: d.file ? d.file.fileName.replace(/^\/pkg\//, "") : "", line: d.file && d.start !== undefined ? d.file.getLineAndCharacterOfPosition(d.start).line + 1 : undefined, message: ts.flattenDiagnosticMessageText(d.messageText, "\n") })); + if (emit && !diags.length) program.emit(); + // dist/src/* → dist/* + const dist: Record = {}; + for (const [p, s] of Object.entries(out)) dist[p.replace(/^dist\/src\//, "dist/")] = s; + return { diags, dist }; +} + +/** TS literal for a JSON example; {__blob:true} becomes a Blob. */ +export function tsLiteral(v: Json, pad = ""): string { + if (v && typeof v === "object" && v.__blob) return 'new Blob(["example"], { type: "application/octet-stream" })'; + if (Array.isArray(v)) return v.length ? `[${v.map((x) => tsLiteral(x, pad)).join(", ")}]` : "[]"; + if (v && typeof v === "object") { const e = Object.entries(v); if (!e.length) return "{}"; const inner = pad + " "; return `{\n${e.map(([k, x]) => `${inner}${/^[A-Za-z_$][\w$]*$/.test(k) ? k : JSON.stringify(k)}: ${tsLiteral(x, inner)}`).join(",\n")},\n${pad}}`; } + return JSON.stringify(v ?? null); +} +const toRuntime = (v: Json): Json => (v && typeof v === "object" && v.__blob ? new Blob(["example"], { type: "application/octet-stream" }) : Array.isArray(v) ? v.map(toRuntime) : v && typeof v === "object" ? Object.fromEntries(Object.entries(v).map(([k, x]) => [k, toRuntime(x)])) : v); + +export function examplesFile(api: Api, className: string, pkg: string) { + const lines = [`// Calls every operation once with the example values from the spec. Run against the bundled mock:`, `// npm run mock (in another terminal) then npx tsx examples/all-operations.ts`, `import { ${className}, ApiError } from "../src/index.js";`, "", `const api = new ${className}({ baseUrl: process.env.API_URL ?? "http://127.0.0.1:4010"${api.schemes.some((s) => s.type !== "apiKey" && s.type !== "basic") ? ', token: "test-token"' : ""}${api.schemes.some((s) => s.type === "apiKey") ? ', apiKey: "test-key"' : ""}${api.schemes.some((s) => s.type === "basic") ? ', basic: { username: "test", password: "test" }' : ""} });`, "", "export async function main() {"]; + for (const op of api.ops) { + const args = exampleArgs(api, op); + const has = op.params.length || op.body; + lines.push(` // ${op.method} ${op.path}`, ` console.log(${JSON.stringify(op.id)}, await api.${op.id}(${has ? tsLiteral(args, " ") : ""}));`); + } + lines.push("}", "", "declare const process: { env: Record };", `main().catch((e) => { console.error(e instanceof ApiError ? \`\${e.message} \${JSON.stringify(e.body)}\` : e); });`, `void ${JSON.stringify(pkg)};`, ""); + return lines.join("\n"); +} + +const eq = (a: Json, b: Json) => JSON.stringify(a) === JSON.stringify(b); + +/** Load the emitted JS client and call every operation against a mock server built from the spec. */ +export async function runAgainstMock(api: Api, dist: Record, className: string): Promise { + const mock = await startMock(api.root, 0); + // fresh folder per run: ESM caches modules by URL, so a re-test must not import stale files + const dir = mkdtempSync(join(tmpdir(), "api-to-sdk-run-")); + writeFileSync(join(dir, "package.json"), '{"type":"module"}'); + for (const [p, c] of Object.entries(dist)) if (p.endsWith(".js")) writeFileSync(join(dir, p.replace(/^dist\//, "")), c); + try { + const mod = await import(pathToFileURL(join(dir, "index.js")).href); + const Client = mod[className], ApiError = mod.ApiError; + const client = new Client({ baseUrl: `http://127.0.0.1:${mock.port}${new URL(api.server ?? "http://x/", "http://x").pathname.replace(/\/$/, "")}`, token: "test-token", apiKey: "test-key", basic: { username: "u", password: "p" } }); + const results: OpResult[] = []; + for (const op of api.ops) { + const r: OpResult = { op: op.id, method: op.method, path: op.path, ok: true, checks: [], problems: [] }; + const fail = (m: string) => { r.ok = false; r.problems.push(m); }; + const args = toRuntime(exampleArgs(api, op)); + const has = op.params.length || op.body; + const before = mock.calls.length; + try { + const res = await (has ? client[op.id](args) : client[op.id]()); + const call = mock.calls[before]; + if (!call) fail("the request never reached the mock"); + else { + if (call.method !== op.method) fail(`sent ${call.method}, expected ${op.method}`); + if (call.errors.length) fail(`mock rejected the request: ${call.errors.join("; ")}`); + for (const p of op.params.filter((x) => x.in === "path")) if (String(call.pathParams[p.name]) !== String(args[p.ident])) fail(`path parameter ${p.name} = ${call.pathParams[p.name]}`); + for (const p of op.params.filter((x) => x.in === "query" && args[x.ident] !== undefined)) if (!eq(call.query[p.name], args[p.ident])) fail(`query ${p.name} = ${JSON.stringify(call.query[p.name])}, expected ${JSON.stringify(args[p.ident])}`); + for (const p of op.params.filter((x) => x.in === "header" && args[x.ident] !== undefined)) if (call.headers[p.name.toLowerCase()] !== String(args[p.ident])) fail(`header ${p.name} missing`); + if (op.body?.kind === "json" && !eq(call.body, args.body)) fail("JSON body differs from what was passed"); + const needs = op.security.length && !op.security.some((alt) => alt.length === 0); + if (needs) { const auth = call.headers.authorization || api.schemes.filter((s) => s.type === "apiKey").some((s) => s.in === "header" ? call.headers[String(s.param).toLowerCase()] : s.in === "query" ? call.query !== undefined : false); if (!auth) fail("no credentials sent"); } + if (!r.problems.length) r.checks.push(`request: ${op.method} ${call.path}${Object.keys(call.query).length ? ` ?${Object.keys(call.query).join("&")}` : ""}${op.body ? ` + ${op.body.kind} body` : ""} matched the spec`); + if (op.success?.status === "204" || !op.success?.contentType) { if (res !== undefined) fail("expected no body"); else r.checks.push("response: empty (204)"); } + else if (op.success.kind === "json" || op.success.kind === "text") { if (!eq(res, call.response)) fail(`response differs: got ${JSON.stringify(res)?.slice(0, 120)}`); else r.checks.push(`response: ${op.success.status} ${op.success.kind} parsed`); } + else r.checks.push(`response: ${op.success.status} blob`); + } + } catch (e) { fail(`threw: ${(e as Error).message}`); } + const err = op.errors.find((x) => /^[45]\d\d$/.test(x.status)); + if (err) { + try { await (has ? client[op.id](args, { headers: { Prefer: `code=${err.status}` } }) : client[op.id]({ headers: { Prefer: `code=${err.status}` } })); fail(`expected ApiError for ${err.status}`); } + catch (e) { + const x = e as { status?: number; body?: unknown }; + if (!(e instanceof ApiError) || x.status !== Number(err.status)) fail(`error ${err.status}: got ${(e as Error).message}`); + else if (err.kind === "json" && err.example !== undefined && !eq(x.body, mock.calls[mock.calls.length - 1]?.response)) fail(`error ${err.status}: body not parsed`); + else r.checks.push(`error: ${err.status} → ApiError with parsed body`); + } + } + results.push(r); + } + return results; + } finally { await mock.close(); rmSync(dir, { recursive: true, force: true }); } +} From 77535a062fba6d24e56cf109b27a355c5525298b Mon Sep 17 00:00:00 2001 From: ppppp2005-p <360128433+ppppp2005-p@users.noreply.github.com> Date: Wed, 25 Nov 2026 15:09:13 -0400 Subject: [PATCH 07/11] feat(ui-plugins): add API To SDK (api-to-sdk) --- ui-plugins/api-to-sdk/test/tools.test.ts | 134 ++++++++++++++++++ .../api-to-sdk/test/workspace-links.test.ts | 43 ++++++ 2 files changed, 177 insertions(+) create mode 100644 ui-plugins/api-to-sdk/test/tools.test.ts create mode 100644 ui-plugins/api-to-sdk/test/workspace-links.test.ts diff --git a/ui-plugins/api-to-sdk/test/tools.test.ts b/ui-plugins/api-to-sdk/test/tools.test.ts new file mode 100644 index 00000000..aaed9083 --- /dev/null +++ b/ui-plugins/api-to-sdk/test/tools.test.ts @@ -0,0 +1,134 @@ +import { execFileSync, spawn } from "node:child_process"; +import { copyFileSync, mkdirSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { Client } from "@modelcontextprotocol/sdk/client/index.js"; +import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js"; +import { beforeAll, describe, expect, it } from "vitest"; +import { TypeNamer, tsType } from "../src/codegen.ts"; +import { loadApi, parseSpec } from "../src/openapi.ts"; +import { createServer } from "../src/server.ts"; + +// 样例:虚构的 Harbor Bikes Rental API(OpenAPI 3.1,覆盖 $ref/allOf/oneOf+discriminator/const/null/multipart/text/204/安全方案)和真实的 Swagger Petstore 3.0 规范。 +const S = process.env.API_SAMPLES ?? "/workspace/zcode-new-plugins/samples/api"; +let ws: string; +let call: (name: string, args: Record) => Promise; +beforeAll(async () => { + ws = mkdtempSync(join(tmpdir(), "a2s-")); + mkdirSync(join(ws, "api")); + for (const f of ["harbor-bikes-api.yaml", "petstore3.json"]) copyFileSync(join(S, f), join(ws, "api", f)); + const server = createServer({ workspaceRoot: ws, assetRoot: join(import.meta.dirname, "../dist") }); + const [a, b] = InMemoryTransport.createLinkedPair(); + await server.connect(a); + const client = new Client({ name: "t", version: "1" }); + await client.connect(b); + call = async (name, args) => (await client.callTool({ name, arguments: args })) as any; +}); + +describe("spec model and types", () => { + it("collects operations, merged path-level params, derived ids and security", () => { + const api = loadApi(parseSpec(readFileSync(join(S, "harbor-bikes-api.yaml"), "utf8"))); + expect(api.ops).toHaveLength(12); + expect(api.server).toBe("https://api.harborbikes.example/v1"); + const op = (id: string) => api.ops.find((o) => o.id === id)!; + expect(op("getReportsMonthlyCsv")).toMatchObject({ derivedId: true, method: "GET", path: "/reports/monthly.csv" }); + expect(op("getBike").params.map((p) => `${p.in}:${p.name}`)).toEqual(["path:bikeId"]); + expect(op("listRentals").params.find((p) => p.in === "header")!.ident).toBe("xBranchId"); + expect(op("health").security).toEqual([]); + expect(op("getCustomer").security).toEqual([["apiKeyAuth"]]); + expect(op("uploadBikePhoto").body).toMatchObject({ kind: "multipart", required: true }); + expect(op("deleteBike").success!.status).toBe("204"); + expect(op("createBike").errors.map((e) => e.status)).toEqual(["400", "409"]); + }); + it("maps schemas to TypeScript", () => { + const root = parseSpec(readFileSync(join(S, "harbor-bikes-api.yaml"), "utf8")); + const n = new TypeNamer(Object.keys(root.components.schemas)); + const t = (s: unknown) => tsType(root, s, n).replace(/\s+/g, " "); + expect(t(root.components.schemas.Bike)).toMatch(/^NewBike & \{ .*id: number; inService: boolean; \}$/); + expect(t(root.components.schemas.NewRental.properties.customer)).toBe("CustomerRef | NewCustomer"); + expect(t({ type: "string", nullable: true })).toBe("string | null"); + expect(t({ type: ["integer", "null"] })).toBe("number | null"); + expect(t({ type: "object", additionalProperties: { type: "string" } })).toBe("{ [key: string]: string; }"); + expect(t({ type: "array", items: { oneOf: [{ type: "string" }, { type: "number" }] } })).toBe("Array"); + expect(t({ type: "string", format: "binary" })).toBe("Blob"); + expect(t({ properties: { "x-y": { const: 1 } }, required: ["x-y"] })).toBe('{ "x-y": 1; }'); + }); + it("rejects what it can't handle with a clear message", () => { + expect(() => loadApi({ swagger: "2.0" })).toThrow(/Convert it to OpenAPI 3/); + expect(() => loadApi({ openapi: "4.0.0", paths: {} })).toThrow(/Unsupported OpenAPI version/); + expect(() => parseSpec("a: [1,", "x.yaml")).toThrow(/not valid YAML/); + const api = loadApi({ openapi: "3.0.3", info: { title: "X", version: "1" }, paths: { "/a/{id}": { get: { responses: { 200: { description: "ok", content: { "application/json": { schema: { $ref: "other.yaml#/Thing" } } } } } } } } }); + expect(api.warnings.join("\n")).toMatch(/External \$ref not supported[\s\S]*path parameter \{id\} is not declared/); + }); +}); + +describe("tools", () => { + it("sdk_generate (Harbor Bikes): strict compile + every operation passes against the mock", async () => { + const r = await call("sdk_generate", { spec: "api/harbor-bikes-api.yaml" }); + expect(r.isError).toBeFalsy(); + const v = r.structuredContent.saved.verify; + expect(v.diagnostics).toEqual([]); + expect(v.exampleWarnings).toEqual([]); + expect(v.ops.filter((o: any) => !o.ok)).toEqual([]); + expect(v.passed).toBe(12); + const byOp = Object.fromEntries(v.ops.map((o: any) => [o.op, o.checks.join(" | ")])); + expect(byOp.listBikes).toMatch(/\?inService&tag/); + expect(byOp.createBike).toMatch(/error: 400 → ApiError/); + expect(byOp.deleteBike).toMatch(/empty \(204\)/); + expect(byOp.uploadBikePhoto).toMatch(/multipart body/); + expect(byOp.getReportsMonthlyCsv).toMatch(/200 text/); + const out = join(ws, "sdk/harbor-bikes-rental"); + expect(JSON.parse(readFileSync(join(out, "package.json"), "utf8"))).toMatchObject({ name: "harbor-bikes-rental-sdk", version: "1.4.0", types: "dist/index.d.ts" }); + expect(readFileSync(join(out, "dist/client.d.ts"), "utf8")).toContain("createRental(args: CreateRentalArgs"); + expect(readFileSync(join(out, "README.md"), "utf8")).toContain("| `returnRental` | `POST /rentals/{rentalId}/return` |"); + }); + + it("the generated package also builds with the real tsc CLI", () => { + const tsc = join(import.meta.dirname, "../node_modules/typescript/bin/tsc"); + execFileSync(process.execPath, [tsc, "-p", join(ws, "sdk/harbor-bikes-rental"), "--outDir", join(ws, "tsc-out")], { stdio: "pipe" }); + expect(readFileSync(join(ws, "tsc-out/client.js"), "utf8")).toContain("class HarborBikesRentalClient"); + }); + + it("the bundled mock runs on its own", async () => { + const p = spawn(process.execPath, [join(ws, "sdk/harbor-bikes-rental/mock/server.mjs"), "0"], { stdio: ["ignore", "pipe", "pipe"] }); + const port = await new Promise((ok, fail) => { let o = ""; p.stdout.on("data", (d) => { o += d; const m = /127\.0\.0\.1:(\d+)/.exec(o); if (m) ok(Number(m[1])); }); setTimeout(() => fail(new Error(o)), 10_000); }); + try { + const r = await fetch(`http://127.0.0.1:${port}/v1/bikes/7`); + expect((await r.json()).serial).toBe("HB-0007"); + const bad = await fetch(`http://127.0.0.1:${port}/v1/bikes`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ serial: "x" }) }); + expect(bad.status).toBe(400); + expect((await bad.json()).errors).toEqual(expect.arrayContaining(["body.model: required", "body.category: required"])); + expect((await fetch(`http://127.0.0.1:${port}/v1/bikes/7`, { headers: { Prefer: "code=404" } })).status).toBe(404); + } finally { p.kill(); } + }); + + it("sdk_test catches a broken client", async () => { + const f = join(ws, "sdk/harbor-bikes-rental/src/client.ts"); + const good = readFileSync(f, "utf8"); + writeFileSync(f, good.replace('query: { "category": args.category, "inService": args.inService, "tag": args.tag,', 'query: { "category": args.category, "inService": args.inService,')); + const r = await call("sdk_test", { out: "sdk/harbor-bikes-rental" }); + writeFileSync(f, good); + expect(r.structuredContent.saved.verify.ops.find((o: any) => o.op === "listBikes").problems.join()).toMatch(/query tag/); + writeFileSync(f, good.replace("Promise", "Promise /*x*/").replace("return this.request", "return this.request").replace("async getBike(", "async getBike(this: never, ")); + const r2 = await call("sdk_test", { out: "sdk/harbor-bikes-rental" }); + writeFileSync(f, good); + expect(r2.structuredContent.saved.verify.compiled).toBe(false); + }); + + it("real-world Petstore 3.0: all 19 operations", async () => { + const r = await call("sdk_generate", { spec: "api/petstore3.json", out: "sdk/petstore", className: "PetstoreClient", packageName: "@demo/petstore" }); + const v = r.structuredContent.saved.verify; + expect(v.compiled).toBe(true); + expect(v.ops.filter((o: any) => !o.ok)).toEqual([]); + expect(v.passed).toBe(19); + expect(r.content[0].text).toMatch(/petstore_auth \(oauth2\)/); + }); + + it("sdk_inspect lists operations without writing", async () => { + const r = await call("sdk_inspect", { spec: "api/petstore3.json" }); + expect(r.structuredContent.api.ops).toHaveLength(19); + expect(r.content[0].text).toContain("GET /pet/findByStatus → findPetsByStatus"); + writeFileSync(join(ws, "s2.json"), JSON.stringify({ swagger: "2.0" })); + expect((await call("sdk_inspect", { spec: "s2.json" })).content[0].text).toMatch(/Swagger 2.0/); + }); +}); diff --git a/ui-plugins/api-to-sdk/test/workspace-links.test.ts b/ui-plugins/api-to-sdk/test/workspace-links.test.ts new file mode 100644 index 00000000..f3dae538 --- /dev/null +++ b/ui-plugins/api-to-sdk/test/workspace-links.test.ts @@ -0,0 +1,43 @@ +import { existsSync, mkdirSync, mkdtempSync, symlinkSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { describe, expect, it } from "vitest"; +import { Workspace } from "../src/kit/workspace.ts"; + +// 回归测试:工作区里的符号链接不能把读写带到工作区之外(TEST-FINDINGS #2) +describe("workspace symlink containment", () => { + const base = mkdtempSync(join(tmpdir(), "wslinks-")); + const root = join(base, "项目 ws"), outside = join(base, "outside"); + mkdirSync(join(root, "inner"), { recursive: true }); + mkdirSync(outside, { recursive: true }); + writeFileSync(join(outside, "secret.txt"), "SECRET"); + writeFileSync(join(root, "inner", "ok.txt"), "ok"); + symlinkSync(outside, join(root, "out-link")); + symlinkSync(join(outside, "secret.txt"), join(root, "secret-link.txt")); + symlinkSync(join(outside, "new-file.txt"), join(root, "dangling.txt")); + symlinkSync(join(root, "inner"), join(root, "inner-link")); + symlinkSync(root, join(base, "root-link")); + const ws = new Workspace(root); + + it("refuses to read through a link to outside (directory and file links)", async () => { + await expect(ws.read("out-link/secret.txt")).rejects.toMatchObject({ code: "outside_workspace" }); + await expect(ws.read("secret-link.txt")).rejects.toMatchObject({ code: "outside_workspace" }); + expect(await ws.exists("out-link/secret.txt")).toBe(false); + }); + it("refuses to write through a link, including to targets that do not exist yet", async () => { + await expect(ws.write("out-link/a/b/new.txt", "x")).rejects.toMatchObject({ code: "outside_workspace" }); + await expect(ws.write("dangling.txt", "x")).rejects.toMatchObject({ code: "outside_workspace" }); + expect(existsSync(join(outside, "a"))).toBe(false); + expect(existsSync(join(outside, "new-file.txt"))).toBe(false); + }); + it("still allows normal paths, new nested files and links that stay inside", async () => { + expect(await ws.write("新 目录/子/文件.txt", "中文")).toBe("新 目录/子/文件.txt"); + expect((await ws.read("inner-link/ok.txt")).toString()).toBe("ok"); + await expect(ws.read("../outside/secret.txt")).rejects.toMatchObject({ code: "outside_workspace" }); + }); + it("works when the workspace root itself is reached through a link", async () => { + const viaLink = new Workspace(join(base, "root-link")); + expect((await viaLink.read("inner/ok.txt")).toString()).toBe("ok"); + await expect(viaLink.read("out-link/secret.txt")).rejects.toMatchObject({ code: "outside_workspace" }); + }); +}); From d84871b3fb8c1c2fb717ab79bdfbc2b437e873d9 Mon Sep 17 00:00:00 2001 From: ppppp2005-p <360128433+ppppp2005-p@users.noreply.github.com> Date: Wed, 25 Nov 2026 15:09:55 -0400 Subject: [PATCH 08/11] feat(ui-plugins): add API To SDK (api-to-sdk) --- ui-plugins/api-to-sdk/ui/env.d.ts | 4 + ui-plugins/api-to-sdk/ui/kit.css | 34 ++++++++ ui-plugins/api-to-sdk/ui/kit.ts | 133 +++++++++++++++++++++++++++++ ui-plugins/api-to-sdk/ui/main.ts | 77 +++++++++++++++++ ui-plugins/api-to-sdk/ui/panel.css | 10 +++ 5 files changed, 258 insertions(+) create mode 100644 ui-plugins/api-to-sdk/ui/env.d.ts create mode 100644 ui-plugins/api-to-sdk/ui/kit.css create mode 100644 ui-plugins/api-to-sdk/ui/kit.ts create mode 100644 ui-plugins/api-to-sdk/ui/main.ts create mode 100644 ui-plugins/api-to-sdk/ui/panel.css diff --git a/ui-plugins/api-to-sdk/ui/env.d.ts b/ui-plugins/api-to-sdk/ui/env.d.ts new file mode 100644 index 00000000..4210a464 --- /dev/null +++ b/ui-plugins/api-to-sdk/ui/env.d.ts @@ -0,0 +1,4 @@ +declare module "*.css" { + const text: string; + export default text; +} diff --git a/ui-plugins/api-to-sdk/ui/kit.css b/ui-plugins/api-to-sdk/ui/kit.css new file mode 100644 index 00000000..398bc83a --- /dev/null +++ b/ui-plugins/api-to-sdk/ui/kit.css @@ -0,0 +1,34 @@ +:root { --bg:#fff; --fg:#1d1f23; --muted:#6b7280; --line:#e5e7eb; --panel:#f7f7f8; --accent:#2563eb; --warn:#b45309; --warnbg:#fef3c7; --bad:#b91c1c; --badbg:#fee2e2; --okbg:#dcfce7; --ok:#15803d; } +[data-theme="dark"] { --bg:#18191b; --fg:#e8e8ea; --muted:#9ca3af; --line:#2e3035; --panel:#222327; --accent:#60a5fa; --warn:#fbbf24; --warnbg:#3b2f10; --bad:#f87171; --badbg:#3b1717; --okbg:#12301d; --ok:#4ade80; } +* { box-sizing: border-box; } +html, body { margin:0; background:var(--bg); color:var(--fg); font:13px/1.45 -apple-system, BlinkMacSystemFont, "Segoe UI", "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", sans-serif; } +#root { padding: 12px; } +h1 { font-size: 15px; margin: 0 0 8px; } +h2 { font-size: 13px; margin: 14px 0 6px; color: var(--muted); font-weight: 600; text-transform: none; } +button { font: inherit; border:1px solid var(--line); background:var(--panel); color:var(--fg); border-radius:6px; padding:5px 10px; cursor:pointer; } +button.primary { background:var(--accent); border-color:var(--accent); color:#fff; } +button:disabled { opacity:.5; cursor:default; } +input, select, textarea { font: inherit; color: var(--fg); background: var(--bg); border:1px solid var(--line); border-radius:5px; padding:4px 6px; } +input[type="color"] { padding: 0; width: 32px; height: 26px; } +input[type="range"] { padding: 0; } +label { display:flex; gap:6px; align-items:center; } +.row { display:flex; gap:8px; align-items:center; flex-wrap:wrap; margin: 6px 0; } +.muted { color: var(--muted); } +.card { border:1px solid var(--line); border-radius:8px; padding:10px; background:var(--panel); margin: 8px 0; } +.grid { display:grid; grid-template-columns:repeat(auto-fill, minmax(150px, 1fr)); gap:8px; } +.thumb { border:1px solid var(--line); border-radius:6px; overflow:hidden; background: var(--bg); cursor:pointer; position:relative; } +.thumb img { width:100%; display:block; aspect-ratio:1; object-fit:contain; background: repeating-conic-gradient(#ddd 0 25%, #fff 0 50%) 50% / 16px 16px; } +.thumb .cap { padding:4px 6px; font-size:12px; white-space:nowrap; overflow:hidden; text-overflow:ellipsis; } +.thumb.selected { outline: 2px solid var(--accent); } +.badge { display:inline-block; font-size:11px; padding:1px 6px; border-radius:10px; background:var(--warnbg); color:var(--warn); } +.badge.bad { background: var(--badbg); color: var(--bad); } +.badge.ok { background: var(--okbg); color: var(--ok); } +table.data { border-collapse: collapse; width: 100%; } +table.data td, table.data th { border:1px solid var(--line); padding:3px 6px; text-align:left; vertical-align:top; } +table.data th { background: var(--panel); } +.toast { position: fixed; right: 12px; bottom: 12px; padding: 8px 12px; border-radius: 6px; background: var(--okbg); color: var(--ok); z-index: 10; max-width: 80%; } +.toast.error { background: var(--badbg); color: var(--bad); } +.empty { padding: 24px; text-align:center; color: var(--muted); border: 1px dashed var(--line); border-radius: 8px; } +.busy { opacity:.6; pointer-events:none; } +.split { display:grid; grid-template-columns: minmax(0,1fr) minmax(0,1fr); gap: 10px; } +@media (max-width: 640px) { .split { grid-template-columns: 1fr; } } diff --git a/ui-plugins/api-to-sdk/ui/kit.ts b/ui-plugins/api-to-sdk/ui/kit.ts new file mode 100644 index 00000000..b0646f25 --- /dev/null +++ b/ui-plugins/api-to-sdk/ui/kit.ts @@ -0,0 +1,133 @@ +import { App } from "@modelcontextprotocol/ext-apps"; + +export class ToolError extends Error { + readonly code: string; + constructor(code: string, message: string) { + super(message); + this.code = code; + } +} + +let app: App | undefined; +let connection: Promise | undefined; +let created!: () => void; +const appCreated = new Promise((resolve) => (created = resolve)); +const resultListeners = new Set<(value: Record | undefined, tool?: string) => void>(); +const contextListeners = new Set<() => void>(); + +export function initHost(name: string, version: string) { + app = new App({ name, version }, { availableDisplayModes: ["inline", "fullscreen"] }); + app.ontoolresult = (result) => { + const content = result.structuredContent as Record | undefined; + resultListeners.forEach((listener) => listener(content)); + }; + app.onhostcontextchanged = () => contextListeners.forEach((listener) => listener()); + created(); + return ready(); +} + +export function ready(): Promise { + if (!app) return appCreated.then(() => ready()); + return (connection ??= app.connect().then(() => contextListeners.forEach((listener) => listener()))); +} + +export function onToolResult(listener: (value: Record | undefined) => void) { + resultListeners.add(listener); +} + +export function onHostContext(listener: () => void) { + contextListeners.add(listener); +} + +export function hostContext() { + return app?.getHostContext(); +} + +export function locale(): "zh" | "en" { + const fromHost = (app?.getHostContext()?.locale as string | undefined) ?? navigator.language ?? "en"; + return /^zh/i.test(fromHost) ? "zh" : "en"; +} + +export async function call>(name: string, args: Record = {}, timeout = 300_000): Promise { + await ready(); + let result; + try { + result = await app!.callServerTool({ name, arguments: args }, { timeout }); + } catch (error) { + throw new ToolError("host_error", error instanceof Error ? error.message : String(error)); + } + const content = result.structuredContent as Record | undefined; + const error = content?.error as { code?: string; message?: string } | undefined; + if (result.isError || error) { + const text = (result.content?.[0] as { text?: string } | undefined)?.text; + throw new ToolError(error?.code ?? "tool_error", error?.message ?? text ?? "The tool failed."); + } + return (content ?? {}) as T; +} + +/** 读取插件资源(二进制)。 */ +export async function readBlob(uri: string): Promise { + await ready(); + const result = await app!.readServerResource({ uri }); + const first = result.contents[0] as { blob?: string; text?: string } | undefined; + if (typeof first?.blob !== "string") throw new ToolError("host_error", first?.text?.slice(0, 300) ?? `Empty resource ${uri}`); + return base64ToBytes(first.blob); +} + +export function base64ToBytes(base64: string): Uint8Array { + const binary = atob(base64); + const bytes = new Uint8Array(binary.length); + for (let index = 0; index < binary.length; index++) bytes[index] = binary.charCodeAt(index); + return bytes; +} + +/** 由用户点击触发:把一句话发到对话里交给 Agent。 */ +export async function sendMessage(text: string) { + await ready(); + return app!.sendMessage({ role: "user", content: [{ type: "text", text }] }); +} + +export async function updateContext(text: string) { + await ready(); + return app!.updateModelContext({ content: [{ type: "text", text }] }); +} + +type Child = Node | string | number | null | undefined | false; +/** 极简 DOM 构建器。 */ +export function h( + tag: K, + props: Record = {}, + ...children: (Child | Child[])[] +): HTMLElementTagNameMap[K] { + const element = document.createElement(tag); + for (const [key, value] of Object.entries(props)) { + if (value === undefined || value === null || value === false) continue; + if (key.startsWith("on") && typeof value === "function") element.addEventListener(key.slice(2).toLowerCase(), value as EventListener); + else if (key === "class") element.className = String(value); + else if (key === "style" && typeof value === "object") Object.assign(element.style, value); + else if (key === "value" || (key in element && typeof value !== "string")) (element as any)[key] = value; + else element.setAttribute(key, value === true ? "" : String(value)); + } + for (const child of children.flat()) { + if (child === null || child === undefined || child === false) continue; + element.append(child instanceof Node ? child : String(child)); + } + return element; +} + +export function toast(message: string, kind: "ok" | "error" = "ok") { + const node = h("div", { class: `toast ${kind}`, role: "status" }, message); + document.body.append(node); + setTimeout(() => node.remove(), kind === "error" ? 6000 : 3000); +} + +/** 主题:跟随宿主的浅色 / 深色。 */ +export function applyTheme() { + const theme = (app?.getHostContext()?.theme as string | undefined) ?? "light"; + document.documentElement.dataset.theme = theme === "dark" ? "dark" : "light"; +} + +/** replaceChildren,跳过 null / false。 */ +export function put(element: Element, ...children: (Node | string | null | undefined | false)[]) { + element.replaceChildren(...(children.filter((c) => c !== null && c !== undefined && c !== false) as (Node | string)[])); +} diff --git a/ui-plugins/api-to-sdk/ui/main.ts b/ui-plugins/api-to-sdk/ui/main.ts new file mode 100644 index 00000000..f4bf7ee7 --- /dev/null +++ b/ui-plugins/api-to-sdk/ui/main.ts @@ -0,0 +1,77 @@ +import css from "./kit.css"; +import panelCss from "./panel.css"; +import { applyTheme, call, h, initHost, locale, onHostContext, onToolResult, put, toast, updateContext } from "./kit.ts"; + +const style = document.createElement("style"); +style.textContent = css + panelCss; +document.head.append(style); + +interface OpS { id: string; method: string; path: string; tag?: string; summary?: string; params: string[]; body: string | null; success: string | null; errors: string[]; auth: string; derivedId: boolean } +interface ApiS { title: string; version: string; openapi: string; server?: string; schemes: { name: string; type: string }[]; schemas: string[]; warnings: string[]; ops: OpS[] } +interface OpResult { op: string; method: string; path: string; ok: boolean; checks: string[]; problems: string[] } +interface Verify { compiled: boolean; diagnostics: { file: string; line?: number; message: string }[]; exampleWarnings: { file: string; line?: number; message: string }[]; ops: OpResult[]; passed: number; failed: number; ms: number } +interface Saved { spec: string; out: string; packageName: string; className: string; title: string; version: string; ops: number; generatedAt: string; verify?: Verify; warnings: string[] } + +const T = (cn: string, en: string) => (locale() === "zh" ? cn : en); +const root = document.getElementById("root")!; +const st: { files: string[]; spec: string; api?: ApiS; saved?: Saved | null; preview?: string; out: string; pkg: string; cls: string } = { files: [], spec: "", out: "", pkg: "", cls: "" }; + +async function busy(work: () => Promise): Promise { + root.classList.add("busy"); + try { return await work(); } catch (error) { toast(error instanceof Error ? error.message.replace(/^\[\w+\]\s*/, "") : String(error), "error"); return undefined; } finally { root.classList.remove("busy"); } +} +function setSaved(s: Saved | null | undefined) { + st.saved = s; if (s) { st.out = s.out; st.pkg = s.packageName; st.cls = s.className; st.spec = s.spec; } + if (s?.verify) void updateContext(`SDK ${s.packageName} (${s.className}) in ${s.out}/ from ${s.spec}: ${s.ops} operations; compile ${s.verify.compiled ? "ok" : "failed"}; mock calls ${s.verify.passed}/${s.verify.ops.length}.`).catch(() => undefined); +} +onToolResult((v) => { + if (v?.kind === "api") { st.api = v.api as ApiS; st.spec = v.spec as string; setSaved(v.saved as Saved | null); render(); } + if (v?.kind === "sdk") { setSaved(v.saved as Saved); if (v.preview) st.preview = v.preview as string; render(); } +}); +const inspect = async () => { if (!st.spec) { toast(T("请先选择 OpenAPI 文件", "Choose an OpenAPI file first"), "error"); return; } const r = await busy(() => call<{ api: ApiS; saved: Saved | null }>("sdk_inspect", { spec: st.spec })); if (r) { st.api = r.api; st.preview = undefined; setSaved(r.saved); render(); } }; +const gen = async () => { + const r = await busy(() => call<{ saved: Saved; preview: string }>("sdk_generate", { spec: st.spec, ...(st.out ? { out: st.out } : {}), ...(st.pkg ? { packageName: st.pkg } : {}), ...(st.cls ? { className: st.cls } : {}) }, 200_000)); + if (r) { setSaved(r.saved); st.preview = r.preview; render(); const v = r.saved.verify!; toast(v.compiled && !v.failed ? T(`已生成,${v.passed} 个接口全部调用通过`, `Generated; all ${v.passed} operations passed`) : T("已生成,但验证有失败项", "Generated, but some checks failed"), v.compiled && !v.failed ? "ok" : "error"); } +}; + +function render() { + applyTheme(); + const pick = h("div", { class: "card" }, h("div", { class: "row" }, + h("label", { class: "fld grow" }, h("span", { class: "lb" }, T("OpenAPI 3 文件(YAML / JSON)", "OpenAPI 3 file (YAML / JSON)")), + h("select", { class: "spec", onchange: (e: Event) => { st.spec = (e.target as HTMLSelectElement).value; } }, h("option", { value: "" }, T("— 选择 —", "— choose —")), ...st.files.map((f) => h("option", { value: f, selected: f === st.spec }, f)))), + h("button", { class: "inspect", onclick: () => void inspect() }, T("读取接口", "Read spec")))); + const a = st.api; + if (!a) { put(root, h("h1", {}, T("接口转 SDK", "API To SDK")), pick, h("div", { class: "empty" }, T("选择一个 OpenAPI 3.0 / 3.1 文件,生成带完整类型的 TypeScript SDK 包,并自动验证:TypeScript 严格模式编译,再用规范里的示例起一个本地模拟服务器,逐个调用每个接口。", "Choose an OpenAPI 3.0 / 3.1 file to generate a fully typed TypeScript SDK package. It is verified automatically: strict TypeScript compile, then every operation is called against a local mock server built from the spec's examples."))); return; } + const v = st.saved?.verify; + const res = new Map((v?.ops ?? []).map((o) => [o.op, o])); + const settings = h("div", { class: "card" }, h("b", {}, `${a.title} ${a.version}`), h("span", { class: "hint" }, ` · OpenAPI ${a.openapi}${a.server ? ` · ${a.server}` : ""} · ${a.ops.length} ${T("个接口", "operations")} · ${a.schemas.length} ${T("个类型", "types")} · ${T("认证", "auth")}: ${a.schemes.map((s) => `${s.name} (${s.type})`).join(", ") || T("无", "none")}`), + ...a.warnings.map((w) => h("div", { class: "warn" }, `! ${w}`)), + h("div", { class: "cols", style: "margin-top:8px" }, + h("label", { class: "fld" }, h("span", { class: "lb" }, T("输出目录", "Output folder")), h("input", { class: "out", value: st.out, placeholder: "sdk/…", oninput: (e: Event) => { st.out = (e.target as HTMLInputElement).value; } })), + h("label", { class: "fld" }, h("span", { class: "lb" }, T("npm 包名", "npm package name")), h("input", { class: "pkg", value: st.pkg, placeholder: T("自动", "auto"), oninput: (e: Event) => { st.pkg = (e.target as HTMLInputElement).value; } })), + h("label", { class: "fld" }, h("span", { class: "lb" }, T("客户端类名", "Client class")), h("input", { class: "cls", value: st.cls, placeholder: T("自动", "auto"), oninput: (e: Event) => { st.cls = (e.target as HTMLInputElement).value; } }))), + h("div", { class: "row", style: "margin-top:8px" }, h("span", { class: "grow" }), h("button", { class: "primary gen", onclick: () => void gen() }, T("生成 SDK 并验证", "Generate & verify")))); + const summary = v ? h("div", { class: v.compiled && !v.failed ? "done" : "fail" }, + v.compiled ? T(`已生成 ${st.saved!.out}/(${st.saved!.packageName},类 ${st.saved!.className})。TypeScript 严格模式编译通过;模拟服务器调用 ${v.passed}/${v.ops.length} 个接口通过(${(v.ms / 1000).toFixed(1)} 秒)。`, `Generated ${st.saved!.out}/ (${st.saved!.packageName}, class ${st.saved!.className}). Strict TypeScript compile passed; mock calls: ${v.passed}/${v.ops.length} operations passed (${(v.ms / 1000).toFixed(1)} s).`) + : T(`TypeScript 编译失败(${v.diagnostics.length} 个错误)`, `TypeScript compile failed (${v.diagnostics.length} errors)`)) : null; + const diags = v && (v.diagnostics.length || v.exampleWarnings.length) ? h("div", { class: "card" }, ...v.diagnostics.map((d) => h("div", { class: "bad" }, `✗ ${d.file}:${d.line ?? ""} ${d.message}`)), ...v.exampleWarnings.map((d) => h("div", { class: "warn" }, `! ${T("规范示例与类型不符", "spec example doesn't match its type")}: ${d.file}:${d.line ?? ""} ${d.message.split("\n")[0]}`))) : null; + const ops = h("div", { class: "card" }, h("b", {}, T("接口", "Operations")), + h("table", { class: "ops" }, h("tr", {}, h("th", {}, T("方法名", "Method")), h("th", {}, "HTTP"), h("th", {}, T("参数 / 请求体", "Params / body")), h("th", {}, T("验证", "Check"))), + ...a.ops.map((o) => { const r = res.get(o.id); return h("tr", { "data-op": o.id }, + h("td", {}, h("code", {}, o.id), o.derivedId ? h("div", { class: "hint" }, T("(没有 operationId,自动命名)", "(no operationId; derived)")) : null, o.summary ? h("div", { class: "hint" }, o.summary) : null), + h("td", {}, h("span", { class: `m ${o.method}` }, o.method), " ", h("code", {}, o.path)), + h("td", { class: "hint" }, [...o.params, ...(o.body ? [`body: ${o.body}`] : [])].join(", ") || "—", h("div", {}, `→ ${o.success ?? "—"}${o.errors.length ? ` / ${o.errors.join(", ")}` : ""} · ${T("认证", "auth")}: ${o.auth}`)), + h("td", { class: "res" }, r ? h("span", { class: r.ok ? "ok" : "bad" }, r.ok ? "✓" : "✗") : "", r ? h("div", {}, ...r.problems.map((p) => h("div", { class: "prob" }, p)), ...r.checks.map((c) => h("div", { class: "chk" }, c))) : null)); }))); + const code = st.preview ? h("div", { class: "card" }, h("b", {}, "src/client.ts"), h("pre", { class: "code" }, st.preview)) : null; + put(root, pick, settings, summary, diags, h("div", { class: "split" }, ops, code ?? h("div", {}))); +} + +onHostContext(() => render()); +render(); +void initHost("api-to-sdk", "0.1.0").then(async () => { + const s = await call<{ kind: string; saved: Saved | null; files: string[] }>("sdk_state").catch(() => undefined); + st.files = s?.files ?? []; + if (st.files.length === 1) st.spec = st.files[0]; + if (s?.saved) { setSaved(s.saved); const r = await call<{ api: ApiS }>("sdk_inspect", { spec: s.saved.spec }).catch(() => undefined); if (r) st.api = r.api; } + render(); +}); diff --git a/ui-plugins/api-to-sdk/ui/panel.css b/ui-plugins/api-to-sdk/ui/panel.css new file mode 100644 index 00000000..36496838 --- /dev/null +++ b/ui-plugins/api-to-sdk/ui/panel.css @@ -0,0 +1,10 @@ +.cols { display:grid; grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); gap:8px 14px; } +.fld { display:flex; flex-direction:column; align-items:stretch; gap:2px; } .fld .lb { font-size:12px; color: var(--muted); } .fld input, .fld select { width:100%; } +.grow { flex:1; } .hint { font-size:11px; color: var(--muted); } +.split { display:grid; grid-template-columns: minmax(440px, 1fr) minmax(420px, 1fr); gap:12px; align-items:start; } @media (max-width: 1000px) { .split { grid-template-columns: 1fr; } } +table.ops { width:100%; border-collapse:collapse; font-size:12px; margin-top:6px; } table.ops th { text-align:left; color: var(--muted); font-weight:600; padding:4px; border-bottom:1px solid var(--line); } table.ops td { padding:4px; border-bottom:1px solid var(--line); vertical-align:top; } +.m { font-family: ui-monospace, monospace; font-size:11px; font-weight:700; padding:1px 5px; border-radius:4px; background: var(--line); } .m.GET { color:#047857; } .m.POST { color:#1d4ed8; } .m.PUT, .m.PATCH { color:#b45309; } .m.DELETE { color:#b42318; } +td.res { min-width:180px; } .ok { color: var(--ok); } .bad { color: var(--bad); } .prob { color: var(--bad); font-size:11px; } .chk { color: var(--muted); font-size:11px; } +.done { background: var(--okbg); color: var(--ok); padding:8px 10px; border-radius:6px; margin:6px 0; } .fail { background:#fee4e2; color: var(--bad); padding:8px 10px; border-radius:6px; margin:6px 0; } +.warn { color: var(--warn); font-size:12px; margin:2px 0; } +pre.code { background: var(--panel); border:1px solid var(--line); border-radius:6px; padding:8px 10px; font-size:11px; max-height:520px; overflow:auto; white-space:pre; margin:6px 0 0; } From 3e92890f7c6831d956de64f77621d20edd01b749 Mon Sep 17 00:00:00 2001 From: ppppp2005-p <360128433+ppppp2005-p@users.noreply.github.com> Date: Wed, 25 Nov 2026 15:10:29 -0400 Subject: [PATCH 09/11] feat(ui-plugins): add API To SDK (api-to-sdk) --- .../api-to-sdk/skills/api-to-sdk/SKILL.md | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 external_plugins/api-to-sdk/skills/api-to-sdk/SKILL.md diff --git a/external_plugins/api-to-sdk/skills/api-to-sdk/SKILL.md b/external_plugins/api-to-sdk/skills/api-to-sdk/SKILL.md new file mode 100644 index 00000000..8d9f8930 --- /dev/null +++ b/external_plugins/api-to-sdk/skills/api-to-sdk/SKILL.md @@ -0,0 +1,13 @@ +--- +name: api-to-sdk +description: 把 OpenAPI 3 规范(YAML/JSON)生成带类型的 TypeScript SDK 包(fetch 客户端、类型、错误处理、认证、README、示例、模拟服务器),并自动验证:严格模式编译 + 对模拟服务器调用每个接口。用户提到“OpenAPI / Swagger / 接口文档生成 SDK / 生成客户端 / API client”时使用。 +--- + +# 接口转 SDK + +1. 找到规范文件(openapi.yaml / openapi.json)。如果是 Swagger 2.0,先告诉用户需要转换成 OpenAPI 3(可以用 swagger2openapi)。 +2. 先用 `sdk_inspect({spec})` 查看:接口数量、认证方式、警告(外部 $ref、缺少 operationId 等)。把重要的警告告诉用户。 +3. 用 `sdk_generate({spec, out?, packageName?, className?})` 生成 SDK。它会自动编译,并对模拟服务器调用每个接口。 +4. 报告结果:编译是否通过、通过了几个接口;有失败的,说明是哪个接口、什么问题(通常是规范自身前后矛盾,例如示例与数据结构不符)。 +5. 告诉用户怎么用:`import { } from "<包名>"`(或 `npm install ./sdk/`),`new ({ token })`;开发时可以用 `node sdk//mock/server.mjs` 启动模拟服务器。 +6. 规范或生成的代码改了以后,用 `sdk_test({out})` 重新验证。 From 35d48ab51364ae6bcfc6f0444a5136e4c7399d64 Mon Sep 17 00:00:00 2001 From: ppppp2005-p <360128433+ppppp2005-p@users.noreply.github.com> Date: Wed, 25 Nov 2026 15:11:05 -0400 Subject: [PATCH 10/11] feat(ui-plugins): add API To SDK (api-to-sdk) --- ui-plugins/api-to-sdk/src/kit/console.ts | 5 + ui-plugins/api-to-sdk/src/kit/server-kit.ts | 84 +++++++++++ ui-plugins/api-to-sdk/src/kit/workspace.ts | 151 ++++++++++++++++++++ 3 files changed, 240 insertions(+) create mode 100644 ui-plugins/api-to-sdk/src/kit/console.ts create mode 100644 ui-plugins/api-to-sdk/src/kit/server-kit.ts create mode 100644 ui-plugins/api-to-sdk/src/kit/workspace.ts diff --git a/ui-plugins/api-to-sdk/src/kit/console.ts b/ui-plugins/api-to-sdk/src/kit/console.ts new file mode 100644 index 00000000..f6817656 --- /dev/null +++ b/ui-plugins/api-to-sdk/src/kit/console.ts @@ -0,0 +1,5 @@ +// stdout 只留给 MCP 协议;依赖库的日志改写到 stderr。 +console.log = (...args: unknown[]) => process.stderr.write(`${args.map(String).join(" ")}\n`); +console.info = console.log; +console.warn = console.log; +console.debug = console.log; diff --git a/ui-plugins/api-to-sdk/src/kit/server-kit.ts b/ui-plugins/api-to-sdk/src/kit/server-kit.ts new file mode 100644 index 00000000..6bc31594 --- /dev/null +++ b/ui-plugins/api-to-sdk/src/kit/server-kit.ts @@ -0,0 +1,84 @@ +import { readFile } from "node:fs/promises"; +import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; +import type { z } from "zod"; +import { KitError } from "./workspace.ts"; + +export const HTML_MIME = "text/html;profile=mcp-app"; +type Visibility = ("model" | "app")[]; +type Content = { type: "text"; text: string } | { type: "image"; data: string; mimeType: string }; + +export interface ToolOutput { + text: string; + structured?: Record; + images?: { data: string; mimeType: string }[]; +} + +export interface KitServerOptions { + name: string; + version: string; + panelUri: string; + surface: string; + panelHtml: () => Promise; + log?: (line: string) => void; + /** 页面资源的额外 _meta,例如 { "zcode/csp": { wasmUnsafeEval: true } }。 */ + panelMeta?: Record; +} + +/** 统一的工具注册:所有工具都关联同一个侧栏面板,错误带 code 返回给 Agent 与页面。 */ +export function createKitServer(options: KitServerOptions) { + const log = options.log ?? (() => undefined); + const server = new McpServer({ name: options.name, version: options.version }, { capabilities: { logging: {} } }); + const panelMeta = { ui: { prefersBorder: false }, ...options.panelMeta }; + server.registerResource("panel", options.panelUri, { mimeType: HTML_MIME, _meta: panelMeta }, async () => ({ + contents: [{ uri: options.panelUri, mimeType: HTML_MIME, _meta: panelMeta, text: await options.panelHtml() }], + })); + + const tool = ( + name: string, + config: { + description: string; + input: Record; + visibility?: Visibility; + openPanel?: boolean; + readOnly?: boolean; + timeoutMs?: number; + }, + run: (input: any) => Promise, + ) => { + server.registerTool( + name, + { + description: config.description, + inputSchema: config.input, + annotations: { readOnlyHint: !!config.readOnly, ...(config.readOnly ? {} : { destructiveHint: false }), openWorldHint: false }, + _meta: { + ui: { resourceUri: options.panelUri, surface: options.surface, visibility: config.visibility ?? ["model", "app"] }, + ...(config.timeoutMs ? { timeoutMs: config.timeoutMs } : {}), + ...(config.openPanel ? { "openai/ui": { preferredModelDisplayMode: "fullscreen" } } : {}), + }, + }, + async (input: unknown) => { + try { + const output = await run(input); + const content: Content[] = [{ type: "text", text: output.text }]; + for (const image of output.images ?? []) content.push({ type: "image", ...image }); + return { content, ...(output.structured ? { structuredContent: output.structured } : {}) }; + } catch (error) { + const code = error instanceof KitError ? error.code : "internal_error"; + const message = error instanceof Error ? error.message : String(error); + if (!(error instanceof KitError)) log(`${name} failed: ${error instanceof Error ? error.stack : message}`); + return { + isError: true, + content: [{ type: "text" as const, text: `[${code}] ${message}` }], + structuredContent: { error: { code, message } }, + }; + } + }, + ); + }; + return { server, tool }; +} + +export async function readPanel(path: string) { + return readFile(path, "utf8"); +} diff --git a/ui-plugins/api-to-sdk/src/kit/workspace.ts b/ui-plugins/api-to-sdk/src/kit/workspace.ts new file mode 100644 index 00000000..f02c4fcb --- /dev/null +++ b/ui-plugins/api-to-sdk/src/kit/workspace.ts @@ -0,0 +1,151 @@ +import { lstatSync, readlinkSync, realpathSync } from "node:fs"; +import { mkdir, readFile, readdir, stat, writeFile } from "node:fs/promises"; +import { dirname, extname, isAbsolute, join, relative, resolve, sep } from "node:path"; + +export class KitError extends Error { + readonly code: string; + constructor(code: string, message: string) { + super(message); + this.code = code; + this.name = "KitError"; + } +} + +const SKIP = new Set(["node_modules", ".git", "dist", "build", ".next", ".cache", "__pycache__"]); + +/** 只允许读写当前工作区内的文件;所有路径都相对工作区根目录。 */ +export class Workspace { + readonly root: string; + constructor(root: string) { + this.root = resolve(root); + } + + resolve(path: string): string { + if (typeof path !== "string" || !path.trim()) throw new KitError("bad_path", "Path is empty."); + const absolute = resolve(this.root, path); + const rel = relative(this.root, absolute); + if (rel === ".." || rel.startsWith(`..${sep}`) || isAbsolute(rel)) + throw new KitError("outside_workspace", `Path is outside the workspace: ${path}`); + this.assertRealInside(absolute, path); + return absolute; + } + + private realRoot?: string; + + /** + * 符号链接不能把读写带出工作区:从目标往上找到第一个已存在的路径,取它的真实路径, + * 必须仍在工作区根目录的真实路径之下。还不存在的写入目标按其已存在的上级目录判断; + * 指向不存在位置的悬空链接一律拒绝(否则 writeFile 会顺着它在外部建文件)。 + */ + private assertRealInside(absolute: string, path: string) { + let realRoot: string; + try { + realRoot = this.realRoot ??= realpathSync(this.root); + } catch { + return; // 根目录本身不存在时,没有可逃出的链接 + } + const outside = (real: string) => { + const rel = relative(realRoot, real); + return rel === ".." || rel.startsWith(`..${sep}`) || isAbsolute(rel); + }; + let probe = absolute; + for (;;) { + let real: string | undefined; + try { + real = realpathSync(probe); + } catch { + let link = false; + try { + link = lstatSync(probe).isSymbolicLink(); + } catch {} + if (link) { + const target = resolve(dirname(probe), readlinkSync(probe)); + throw new KitError("outside_workspace", outside(target) ? `Path leaves the workspace through a link: ${path}` : `Path goes through a broken link: ${path}`); + } + } + if (real !== undefined) { + if (outside(real)) throw new KitError("outside_workspace", `Path leaves the workspace through a link: ${path}`); + return; + } + const parent = dirname(probe); + if (parent === probe) return; + probe = parent; + } + } + + rel(absolute: string): string { + return relative(this.root, absolute).split(sep).join("/") || "."; + } + + async exists(path: string): Promise { + try { + await stat(this.resolve(path)); + return true; + } catch { + return false; + } + } + + async read(path: string, maxBytes = 200 * 1024 * 1024): Promise { + const absolute = this.resolve(path); + let info; + try { + info = await stat(absolute); + } catch { + throw new KitError("not_found", `File not found: ${path}`); + } + if (!info.isFile()) throw new KitError("not_a_file", `Not a file: ${path}`); + if (info.size > maxBytes) throw new KitError("too_large", `File is larger than ${Math.round(maxBytes / 1048576)} MB: ${path}`); + return readFile(absolute); + } + + async readText(path: string): Promise { + return (await this.read(path, 20 * 1024 * 1024)).toString("utf8"); + } + + async write(path: string, data: Uint8Array | string): Promise { + const absolute = this.resolve(path); + await mkdir(dirname(absolute), { recursive: true }); + await writeFile(absolute, data); + return this.rel(absolute); + } + + /** 列出文件(默认递归、跳过依赖与构建目录),按路径排序。 */ + async list({ dir = ".", exts, recursive = true, limit = 2000 }: { dir?: string; exts?: string[]; recursive?: boolean; limit?: number } = {}) { + const wanted = exts?.map((ext) => ext.toLowerCase()); + const out: { path: string; size: number }[] = []; + const walk = async (absolute: string, depth: number) => { + if (out.length >= limit || depth > 8) return; + let entries; + try { + entries = await readdir(absolute, { withFileTypes: true }); + } catch { + return; + } + entries.sort((a, b) => a.name.localeCompare(b.name, "en", { numeric: true })); + for (const entry of entries) { + if (out.length >= limit) return; + if (entry.name.startsWith(".") && entry.name !== ".") continue; + const child = join(absolute, entry.name); + if (entry.isDirectory()) { + if (recursive && !SKIP.has(entry.name)) await walk(child, depth + 1); + } else if (entry.isFile() && (!wanted || wanted.includes(extname(entry.name).toLowerCase()))) { + out.push({ path: this.rel(child), size: (await stat(child)).size }); + } + } + }; + await walk(this.resolve(dir), 0); + return out; + } +} + +/** 把文件名中不适合的字符替换掉,保留中文。 */ +export function safeFileName(name: string, fallback = "file"): string { + const cleaned = name + .replace(/[\\/:*?"<>|]+/g, "_") + .replace(/\p{Cc}+/gu, "_") + .replace(/\s+/g, " ") + .trim() + .replace(/^\.+/, ""); + return (cleaned || fallback).slice(0, 120); +} From c5ae3403e76d9781a5bd51b169d7ef0db4ef5377 Mon Sep 17 00:00:00 2001 From: ppppp2005-p <360128433+ppppp2005-p@users.noreply.github.com> Date: Wed, 25 Nov 2026 15:11:37 -0400 Subject: [PATCH 11/11] feat(ui-plugins): add API To SDK (api-to-sdk) --- ui-plugins/api-to-sdk/src/runtime/mock.mjs | 197 +++++++++++++++++++++ 1 file changed, 197 insertions(+) create mode 100644 ui-plugins/api-to-sdk/src/runtime/mock.mjs diff --git a/ui-plugins/api-to-sdk/src/runtime/mock.mjs b/ui-plugins/api-to-sdk/src/runtime/mock.mjs new file mode 100644 index 00000000..d03f4afe --- /dev/null +++ b/ui-plugins/api-to-sdk/src/runtime/mock.mjs @@ -0,0 +1,197 @@ +// Mock server for an OpenAPI 3.x spec, generated by API To SDK (ZCode). No dependencies. +// node mock/server.mjs [port] serves the API from mock/openapi.json on http://127.0.0.1: (default 4010) +// Responses come from the spec's examples (or are synthesised from schemas). Requests are checked against the spec +// (required params, parameter types, JSON body schema) and answered with 400 when they don't match. +// Pick another documented status with the header "Prefer: code=404" (or "X-Mock-Status: 404"). +import { createServer } from "node:http"; + +export function resolveRef(root, ref) { + if (typeof ref !== "string" || !ref.startsWith("#/")) throw new Error(`Only local $refs are supported: ${ref}`); + let node = root; + for (const raw of ref.slice(2).split("/")) { const k = raw.replace(/~1/g, "/").replace(/~0/g, "~"); node = node?.[decodeURIComponent(k)]; if (node === undefined) throw new Error(`Unresolvable $ref ${ref}`); } + return node; +} +export const deref = (root, node, seen = 0) => { while (node && typeof node === "object" && typeof node.$ref === "string" && seen++ < 50) node = resolveRef(root, node.$ref); return node; }; + +const typesOf = (s) => (Array.isArray(s.type) ? s.type : s.type ? [s.type] : []).concat(s.nullable ? ["null"] : []); + +/** Deterministic example value for a schema. */ +export function synth(root, schema, depth = 0, name = "") { + let s; + try { s = deref(root, schema); } catch { return null; } + if (!s || typeof s !== "object" || depth > 8) return null; + if (s.example !== undefined) return s.example; + if (Array.isArray(s.examples) && s.examples.length) return s.examples[0]; + if (s.const !== undefined) return s.const; + if (s.default !== undefined) return s.default; + if (Array.isArray(s.enum) && s.enum.length) return s.enum[0]; + if (s.allOf) return s.allOf.reduce((acc, p) => { const v = synth(root, p, depth + 1, name); return v && typeof v === "object" && !Array.isArray(v) ? { ...acc, ...v } : acc; }, {}); + if (s.oneOf || s.anyOf) return synth(root, (s.oneOf || s.anyOf)[0], depth + 1, name); + const t = typesOf(s).filter((x) => x !== "null")[0] || (s.properties ? "object" : s.items ? "array" : undefined); + switch (t) { + case "object": { + const o = {}; + for (const [k, v] of Object.entries(s.properties || {})) { const val = synth(root, v, depth + 1, k); if (val !== undefined) o[k] = val; } + return o; + } + case "array": return s.items ? [synth(root, s.items, depth + 1, name)] : []; + case "integer": return s.minimum !== undefined ? Math.ceil(s.minimum) : 1; + case "number": return s.minimum !== undefined ? s.minimum : 1.5; + case "boolean": return true; + case "string": { + switch (s.format) { + case "date": return "2026-01-15"; + case "date-time": return "2026-01-15T09:30:00Z"; + case "email": return "user@example.com"; + case "uuid": return "00000000-0000-4000-8000-000000000001"; + case "uri": case "url": return "https://example.com/"; + case "binary": return { __blob: true }; + case "byte": return "aGVsbG8="; + default: return name ? `${name}-example`.slice(0, s.maxLength || 60) : "example"; + } + } + default: return null; + } +} + +/** Light JSON-schema check (types, required, enum, const, properties, items, oneOf/anyOf/allOf, additionalProperties, string formats). */ +export function check(root, schema, value, path = "body", errs = [], depth = 0) { + const s = deref(root, schema); + if (!s || typeof s !== "object" || depth > 20) return errs; + if (s.allOf) for (const p of s.allOf) check(root, p, value, path, errs, depth + 1); + if (s.oneOf || s.anyOf) { + const alts = s.oneOf || s.anyOf; + const ok = alts.filter((a) => !check(root, a, value, path, [], depth + 1).length).length; + if (s.oneOf ? ok !== 1 : ok < 1) errs.push(`${path}: matches ${ok} of the ${s.oneOf ? "oneOf" : "anyOf"} alternatives`); + } + if (s.const !== undefined && value !== s.const) errs.push(`${path}: must be ${JSON.stringify(s.const)}`); + if (Array.isArray(s.enum) && !s.enum.includes(value) && !(value === null && typesOf(s).includes("null"))) errs.push(`${path}: must be one of ${s.enum.map((e) => JSON.stringify(e)).join(", ")}`); + const types = typesOf(s); + if (types.length) { + const actual = value === null ? "null" : Array.isArray(value) ? "array" : typeof value === "number" ? (Number.isInteger(value) ? "integer" : "number") : typeof value; + const okType = types.includes(actual) || (actual === "integer" && types.includes("number")); + if (!okType) { errs.push(`${path}: expected ${types.join(" | ")}, got ${actual}`); return errs; } + } + if (value && typeof value === "object" && !Array.isArray(value) && (s.properties || s.required || s.additionalProperties !== undefined)) { + for (const r of s.required || []) if (value[r] === undefined) errs.push(`${path}.${r}: required`); + for (const [k, v] of Object.entries(value)) { + if (s.properties?.[k]) check(root, s.properties[k], v, `${path}.${k}`, errs, depth + 1); + else if (s.additionalProperties === false) errs.push(`${path}.${k}: unexpected property`); + else if (s.additionalProperties && typeof s.additionalProperties === "object") check(root, s.additionalProperties, v, `${path}.${k}`, errs, depth + 1); + } + } + if (Array.isArray(value) && s.items) value.forEach((v, i) => check(root, s.items, v, `${path}[${i}]`, errs, depth + 1)); + if (typeof value === "string") { + if (s.maxLength !== undefined && value.length > s.maxLength) errs.push(`${path}: longer than ${s.maxLength}`); + if (s.format === "date" && !/^\d{4}-\d{2}-\d{2}$/.test(value)) errs.push(`${path}: not a date`); + if (s.format === "date-time" && Number.isNaN(Date.parse(value))) errs.push(`${path}: not a date-time`); + if (s.format === "email" && !/^[^\s@]+@[^\s@]+$/.test(value)) errs.push(`${path}: not an email`); + if (s.pattern) { try { if (!new RegExp(s.pattern, "u").test(value)) errs.push(`${path}: does not match ${s.pattern}`); } catch {} } + } + if (typeof value === "number") { + if (s.minimum !== undefined && value < s.minimum) errs.push(`${path}: below minimum ${s.minimum}`); + if (s.maximum !== undefined && value > s.maximum) errs.push(`${path}: above maximum ${s.maximum}`); + } + return errs; +} + +const METHODS = ["get", "put", "post", "delete", "options", "head", "patch", "trace"]; +export function mediaKind(ct) { const c = String(ct || "").toLowerCase(); if (/json/.test(c)) return "json"; if (c.startsWith("multipart/")) return "multipart"; if (c === "application/x-www-form-urlencoded") return "form"; if (c.startsWith("text/")) return "text"; return "binary"; } + +/** First example of a media object (example, examples[0].value, schema example, synthesised). */ +export function mediaExample(root, media) { + if (!media) return undefined; + if (media.example !== undefined) return media.example; + if (media.examples && typeof media.examples === "object") { const first = deref(root, Object.values(media.examples)[0]); if (first && first.value !== undefined) return first.value; } + return media.schema ? synth(root, media.schema) : undefined; +} + +function coerce(root, schema, raw) { + const s = deref(root, schema) || {}; + const t = typesOf(s).filter((x) => x !== "null")[0]; + if (t === "integer") return /^-?\d+$/.test(raw) ? Number(raw) : raw; + if (t === "number") return raw !== "" && !Number.isNaN(Number(raw)) ? Number(raw) : raw; + if (t === "boolean") return raw === "true" ? true : raw === "false" ? false : raw; + return raw; +} + +export function createMock(spec, { log = () => {} } = {}) { + const root = spec; + const routes = []; + for (const [p, item0] of Object.entries(spec.paths || {})) { + const item = deref(root, item0); + const names = []; + const re = new RegExp("^" + p.replace(/[.*+?^${}()|[\]\\]/g, (c) => (c === "{" || c === "}" ? c : `\\${c}`)).replace(/\\?\{([^}]+)\\?\}/g, (_, n) => { names.push(n); return "([^/]+)"; }) + "/?$"); + for (const m of METHODS) if (item[m]) routes.push({ path: p, method: m.toUpperCase(), op: item[m], params: [...(item.parameters || []), ...(item[m].parameters || [])].map((x) => deref(root, x)), re, names, literal: p.replace(/\{[^}]+\}/g, "").length }); + } + routes.sort((a, b) => b.literal - a.literal); + const calls = []; + let basePath = ""; + try { basePath = new URL(spec.servers?.[0]?.url ?? "/", "http://mock").pathname.replace(/\/+$/, ""); } catch {} + const handler = async (req, res) => { + const url = new URL(req.url, "http://mock"); + if (basePath && (url.pathname === basePath || url.pathname.startsWith(basePath + "/"))) url.pathname = url.pathname.slice(basePath.length) || "/"; + if (req.method === "OPTIONS" && req.headers["access-control-request-method"]) { + res.writeHead(204, { "Access-Control-Allow-Origin": "*", "Access-Control-Allow-Methods": "GET,POST,PUT,PATCH,DELETE,HEAD,OPTIONS", "Access-Control-Allow-Headers": req.headers["access-control-request-headers"] || "*", "Access-Control-Max-Age": "600" }); + return res.end(); + } + const chunks = []; for await (const c of req) chunks.push(c); + const raw = Buffer.concat(chunks); + const send = (status, body, ct = "application/json") => { res.writeHead(status, { "Content-Type": ct, "Access-Control-Allow-Origin": "*" }); res.end(body === undefined ? undefined : ct.includes("json") ? JSON.stringify(body) : String(body)); }; + let route, m; + for (const r of routes) { if ((m = r.re.exec(url.pathname)) && r.method === req.method) { route = r; break; } } + if (!route) { const any = routes.some((r) => r.re.test(url.pathname)); log(`${req.method} ${url.pathname} → ${any ? 405 : 404}`); return send(any ? 405 : 404, { code: "mock_no_route", message: `${req.method} ${url.pathname} is not in the spec` }); } + const errors = []; + const pathParams = Object.fromEntries(route.names.map((n, i) => [n, decodeURIComponent(m[i + 1])])); + const query = {}; + for (const p of route.params) { + let v; + if (p.in === "path") v = pathParams[p.name]; + else if (p.in === "query") { const all = url.searchParams.getAll(p.name); const s = deref(root, p.schema) || {}; v = typesOf(s).includes("array") ? (all.length ? all : undefined) : all[0]; } + else if (p.in === "header") v = req.headers[p.name.toLowerCase()]; + else continue; + if (v === undefined) { if (p.required) errors.push(`${p.in} parameter ${p.name}: required`); continue; } + const s = deref(root, p.schema) || {}; + const val = Array.isArray(v) ? v.map((x) => coerce(root, s.items || {}, x)) : coerce(root, s, v); + check(root, s, val, `${p.in} parameter ${p.name}`, errors); + if (p.in === "query") query[p.name] = val; + } + const rb = deref(root, route.op.requestBody); + let body; + if (rb) { + const ct = String(req.headers["content-type"] || "").split(";")[0].trim(); + if (!raw.length) { if (rb.required) errors.push("request body: required"); } + else { + const media = rb.content?.[ct] || Object.entries(rb.content || {}).find(([k]) => mediaKind(k) === mediaKind(ct))?.[1]; + if (!media) errors.push(`request body: content type ${ct || "(none)"} not accepted (${Object.keys(rb.content || {}).join(", ")})`); + else if (mediaKind(ct) === "json") { try { body = JSON.parse(raw.toString("utf8")); if (media.schema) check(root, media.schema, body, "body", errors); } catch { errors.push("request body: invalid JSON"); } } + else if (mediaKind(ct) === "multipart") { body = { multipart: true, bytes: raw.length }; const s = deref(root, media.schema); for (const r of s?.required || []) if (!raw.includes(Buffer.from(`name="${r}"`))) errors.push(`body.${r}: required`); } + else body = raw.toString("utf8"); + } + } + const responses = route.op.responses || {}; + const want = String(req.headers["x-mock-status"] || (/code=(\d{3})/.exec(String(req.headers.prefer || "")) || [])[1] || ""); + let status = errors.length ? "400" : want && responses[want] ? want : Object.keys(responses).find((k) => /^2\d\d$/.test(k)) || Object.keys(responses).find((k) => /^2XX$/i.test(k)) || "default"; + const call = { method: req.method, path: url.pathname, operationId: route.op.operationId, pathParams, query, headers: req.headers, body, errors, status: Number(status) || 200 }; + calls.push(call); + if (errors.length) { log(`${req.method} ${url.pathname} → 400 ${errors.join("; ")}`); return send(400, { code: "mock_invalid_request", message: "Request does not match the OpenAPI spec", errors }); } + const resp = deref(root, responses[status]) || {}; + const code = status === "default" || /XX/i.test(status) ? (status === "default" ? 200 : Number(status[0]) * 100) : Number(status); + const entries = Object.entries(resp.content || {}); + const accept = String(req.headers.accept || ""); + const [ct, media] = (/json/.test(accept) && entries.find(([k]) => mediaKind(k) === "json")) || entries.find(([k]) => accept.includes(k)) || entries[0] || []; + if (!ct || code === 204) { call.response = undefined; log(`${req.method} ${url.pathname} → ${code}`); res.writeHead(code, { "Access-Control-Allow-Origin": "*" }); return res.end(); } + let out = mediaExample(root, media); + if (out && typeof out === "object" && out.__blob) out = "binary-example"; + call.response = out; + log(`${req.method} ${url.pathname} → ${code}`); + return send(code, out, ct); + }; + return { handler, calls, routes }; +} + +export function startMock(spec, port = 4010, host = "127.0.0.1", opts = {}) { + const mock = createMock(spec, opts); + const server = createServer((req, res) => { mock.handler(req, res).catch((e) => { res.writeHead(500); res.end(String(e?.message || e)); }); }); + return new Promise((ok) => server.listen(port, host, () => ok({ ...mock, server, port: server.address().port, close: () => new Promise((d) => { server.close(() => d()); server.closeAllConnections?.(); }) }))); +}