specleaf 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/cli.js ADDED
@@ -0,0 +1,223 @@
1
+ #!/usr/bin/env node
2
+ import { mkdir, readFile, realpath, rename, rm, stat, writeFile } from "node:fs/promises";
3
+ import { basename, dirname, isAbsolute, join, resolve } from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+ import $RefParser from "@apidevtools/json-schema-ref-parser";
6
+ import { randomUUID } from "node:crypto";
7
+ // src/lib/openapi.ts
8
+ var pointerEscape = (value) => value.replace(/~/g, "~0").replace(/\//g, "~1");
9
+ // build/contract.ts
10
+ var maps = /* @__PURE__ */ new Set([
11
+ "properties",
12
+ "patternProperties",
13
+ "$defs",
14
+ "definitions",
15
+ "schemas",
16
+ "examples",
17
+ "headers",
18
+ "links",
19
+ "paths",
20
+ "responses",
21
+ "callbacks",
22
+ "securitySchemes",
23
+ "requestBodies",
24
+ "parameters",
25
+ "dependentSchemas"
26
+ ]);
27
+ function literalPayload(path, value) {
28
+ const tokens = path.split("/");
29
+ const key = tokens.at(-1);
30
+ const parent = tokens.at(-2);
31
+ if (maps.has(parent)) return false;
32
+ return key.startsWith("x-") || key === "example" || key === "default" || key === "const" || key === "enum" && Array.isArray(value) || key === "examples" && Array.isArray(value) || key === "value" && tokens.at(-3) === "examples";
33
+ }
34
+ function contractEntry(root, configured = process.env.OPENAPI_ENTRY) {
35
+ const entry = configured || "examples/openapi.yaml";
36
+ if (/^[a-z][a-z\d+.-]*:/i.test(entry) && !/^[a-z]:[\\/]/i.test(entry)) throw new Error("OpenAPI 入口必须是本地 YAML / JSON 文件路径。");
37
+ return isAbsolute(entry) ? entry : resolve(root, entry);
38
+ }
39
+ function references(value, pointer = "#", result = []) {
40
+ if (!value || typeof value !== "object") return result;
41
+ if (typeof value.$ref === "string") result.push(`${pointer}/$ref → ${value.$ref}`);
42
+ for (const [key, child] of Object.entries(value)) references(child, `${pointer}/${pointerEscape(key)}`, result);
43
+ return result;
44
+ }
45
+ async function loadContract(entry) {
46
+ entry = contractEntry(process.cwd(), entry);
47
+ const parser = new $RefParser();
48
+ try {
49
+ const document = await parser.bundle(entry, {
50
+ resolve: { http: false },
51
+ parse: {
52
+ binary: false,
53
+ text: false
54
+ },
55
+ resolveExcludedPathMatcher: literalPayload,
56
+ bundle: { excludedPathMatcher: literalPayload }
57
+ });
58
+ if (!/^3\.(0|1)\.\d+$/.test(document.openapi || "")) throw new Error(`仅支持 OpenAPI 3.0 / 3.1,当前版本:${document.openapi ?? "缺失"}`);
59
+ if (!document.info?.title || !document.paths || typeof document.paths !== "object" || Array.isArray(document.paths)) throw new Error("契约必须包含 info.title 和 paths 对象。");
60
+ return {
61
+ document,
62
+ files: parser.$refs.paths(),
63
+ entry
64
+ };
65
+ } catch (cause) {
66
+ const error = cause;
67
+ const sources = parser.$refs.values();
68
+ const locations = Object.entries(sources).flatMap(([file, value]) => references(value).map((ref) => `${file} ${ref}`));
69
+ const relevant = locations.filter((location) => error.targetToken && location.includes(error.targetToken) || error.source && location.includes(error.source.split("/").at(-1)));
70
+ const context = (relevant.length ? relevant : locations).slice(0, 8);
71
+ throw new Error([
72
+ `OpenAPI 契约解析失败:${entry}`,
73
+ error.message,
74
+ error.source ? `来源文件:${error.source}` : "",
75
+ error.path?.length ? `引用位置:#/${error.path.map(pointerEscape).join("/")}` : "",
76
+ context.length ? `引用上下文:\n${context.join("\n")}` : ""
77
+ ].filter(Boolean).join("\n"), { cause });
78
+ }
79
+ }
80
+ // build/serialize.ts
81
+ function serializeContract(document) {
82
+ return JSON.stringify(document).replace(/[<>&\u2028\u2029]/g, (character) => `\\u${character.charCodeAt(0).toString(16).padStart(4, "0")}`);
83
+ }
84
+ // build/generate.ts
85
+ var projectRoot = fileURLToPath(new URL("../", import.meta.url));
86
+ function escapeHtml(value) {
87
+ return value.replace(/[&<>"']/g, (character) => ({
88
+ "&": "&amp;",
89
+ "<": "&lt;",
90
+ ">": "&gt;",
91
+ "\"": "&quot;",
92
+ "'": "&#39;"
93
+ })[character]);
94
+ }
95
+ async function renderHtml(contract) {
96
+ const assets = new URL("../lib/assets/", import.meta.url);
97
+ const [javascript, stylesheet, favicon] = await Promise.all([
98
+ "ui.js",
99
+ "ui.css",
100
+ "favicon.svg"
101
+ ].map((file) => readFile(new URL(file, assets), "utf8")));
102
+ const script = javascript.replace(/<\/script/gi, "<\\/script");
103
+ const css = stylesheet.replace(/<\/style/gi, "\\3c /style");
104
+ const title = escapeHtml(contract.document.info.title);
105
+ return `<!doctype html>
106
+ <html lang="zh-CN">
107
+ <head>
108
+ <meta charset="UTF-8">
109
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
110
+ <meta name="theme-color" content="#7357e8">
111
+ <meta http-equiv="Content-Security-Policy" content="default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; img-src data:; font-src data:; connect-src 'none'; base-uri 'none'; form-action 'none'">
112
+ <meta name="description" content="${escapeHtml(contract.document.info.description || contract.document.info.title)}">
113
+ <title>${title} · API 文档</title>
114
+ <link rel="icon" type="image/svg+xml" href="data:image/svg+xml,${encodeURIComponent(favicon)}">
115
+ <style>${css}</style>
116
+ </head>
117
+ <body><div id="root"></div><script id="specleaf-contract" type="application/json">${serializeContract(contract.document)}<\/script><script>${script}<\/script></body>
118
+ </html>\n`;
119
+ }
120
+ async function canonical(path) {
121
+ try {
122
+ return await realpath(path);
123
+ } catch (error) {
124
+ if (error.code !== "ENOENT") throw error;
125
+ const parent = dirname(path);
126
+ if (parent === path) throw error;
127
+ return join(await canonical(parent), basename(path));
128
+ }
129
+ }
130
+ async function protectSources(output, sources) {
131
+ const target = await canonical(output);
132
+ const targetStat = await stat(output).catch((error) => {
133
+ if (error.code !== "ENOENT") throw error;
134
+ });
135
+ for (const source of sources) {
136
+ const sourceStat = await stat(source);
137
+ if (target === await canonical(source) || targetStat && targetStat.dev === sourceStat.dev && targetStat.ino === sourceStat.ino) throw new Error(`禁止输出覆盖入口或引用文件:${output}\n来源文件:${source}`);
138
+ }
139
+ }
140
+ async function generate(input, destination) {
141
+ const contract = await loadContract(input);
142
+ const output = resolve(destination);
143
+ let temporary;
144
+ try {
145
+ await protectSources(output, contract.files);
146
+ const html = await renderHtml(contract);
147
+ await mkdir(dirname(output), { recursive: true });
148
+ temporary = join(dirname(output), `.${basename(output)}.${randomUUID()}.tmp`);
149
+ await writeFile(temporary, html, {
150
+ encoding: "utf8",
151
+ flag: "wx"
152
+ });
153
+ await protectSources(output, contract.files);
154
+ await rename(temporary, output);
155
+ return output;
156
+ } catch (cause) {
157
+ throw new Error(`HTML 生成或写入失败:${output}\n${cause.message}`, { cause });
158
+ } finally {
159
+ if (temporary) await rm(temporary, { force: true });
160
+ }
161
+ }
162
+ // build/cli.ts
163
+ var help = `用法:specleaf <input> [-o <output.html>]
164
+
165
+ 把本地 OpenAPI 3.0 / 3.1 YAML 或 JSON 转为单个离线 HTML。
166
+ 输入、输出路径相对调用目录解析,默认输出 ./openapi.html。
167
+
168
+ 选项:
169
+ -o, --output <文件> 指定输出文件
170
+ -h, --help 显示帮助
171
+ -v, --version 显示版本
172
+ `;
173
+ function parseArguments(args) {
174
+ let input;
175
+ let output = "openapi.html";
176
+ let positional = false;
177
+ for (let index = 0; index < args.length; index++) {
178
+ const argument = args[index];
179
+ if (!positional && (argument === "--help" || argument === "-h")) return {
180
+ output,
181
+ help: true
182
+ };
183
+ if (!positional && (argument === "--version" || argument === "-v")) return {
184
+ output,
185
+ version: true
186
+ };
187
+ if (!positional && argument === "--") {
188
+ positional = true;
189
+ continue;
190
+ }
191
+ if (!positional && (argument === "-o" || argument === "--output")) {
192
+ const value = args[++index];
193
+ if (!value || value.startsWith("-")) throw new Error(`${argument} 缺少输出文件路径。`);
194
+ output = value;
195
+ } else if (!positional && argument.startsWith("--output=")) {
196
+ output = argument.slice(9);
197
+ if (!output) throw new Error("--output 缺少输出文件路径。");
198
+ } else if (!positional && argument.startsWith("-")) throw new Error(`未知参数:${argument}`);
199
+ else if (input) throw new Error(`只能指定一个输入文件,多余输入:${argument}`);
200
+ else input = argument;
201
+ }
202
+ if (!input) throw new Error("缺少 OpenAPI 输入文件。");
203
+ return {
204
+ input,
205
+ output
206
+ };
207
+ }
208
+ try {
209
+ const args = parseArguments(process.argv.slice(2));
210
+ if (args.help) process.stdout.write(help);
211
+ else if (args.version) {
212
+ const { version } = JSON.parse(await readFile(new URL("../package.json", import.meta.url), "utf8"));
213
+ process.stdout.write(`${version}\n`);
214
+ } else {
215
+ const cwd = fileURLToPath(import.meta.url) === resolve(projectRoot, "build/cli.ts") && process.env.npm_lifecycle_event === "generate" ? process.env.INIT_CWD || process.cwd() : process.cwd();
216
+ const output = await generate(contractEntry(cwd, args.input), resolve(cwd, args.output));
217
+ process.stdout.write(`已生成离线 HTML:${output}\n`);
218
+ }
219
+ } catch (error) {
220
+ process.stderr.write(`错误:${error.message}\n运行 specleaf --help 查看用法。\n`);
221
+ process.exitCode = 1;
222
+ }
223
+ export { parseArguments };
package/package.json CHANGED
@@ -1,6 +1,60 @@
1
1
  {
2
2
  "name": "specleaf",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.0.0",
4
+ "description": "将本地 OpenAPI 3.0 / 3.1 YAML 或 JSON 转为可离线阅读的单文件 HTML 文档。",
5
+ "license": "MIT",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/SuperPx-CN/specleaf.git"
9
+ },
10
+ "homepage": "https://github.com/SuperPx-CN/specleaf#readme",
11
+ "bugs": {
12
+ "url": "https://github.com/SuperPx-CN/specleaf/issues"
13
+ },
14
+ "type": "module",
15
+ "bin": {
16
+ "specleaf": "lib/cli.js"
17
+ },
18
+ "files": [
19
+ "lib/cli.js",
20
+ "lib/assets/",
21
+ "README.md",
22
+ "LICENSE"
23
+ ],
24
+ "engines": {
25
+ "node": ">=22.19.0"
26
+ },
27
+ "scripts": {
28
+ "dev": "vite --host 127.0.0.1",
29
+ "build": "npm run typecheck && npm run build:package && node build/build.ts",
30
+ "build:package": "node build/package.ts",
31
+ "prepack": "npm run typecheck && npm run build:package",
32
+ "pregenerate": "npm run build:package",
33
+ "generate": "node build/cli.ts",
34
+ "preview": "vite preview --host 127.0.0.1",
35
+ "typecheck": "tsc --noEmit",
36
+ "pretest": "npm run build:package",
37
+ "test": "vitest run",
38
+ "test:package": "node tests/package.mjs",
39
+ "pretest:e2e": "npm run build",
40
+ "test:e2e": "playwright test"
41
+ },
42
+ "dependencies": {
43
+ "@apidevtools/json-schema-ref-parser": "^16.0.5"
44
+ },
45
+ "devDependencies": {
46
+ "@playwright/test": "^1.64.1",
47
+ "@types/node": "^24.0.0",
48
+ "@types/react": "^19.0.0",
49
+ "@types/react-dom": "^19.0.0",
50
+ "@vitejs/plugin-react": "^6.1.2",
51
+ "lucide-react": "^0.468.0",
52
+ "react": "^19.3.1",
53
+ "react-dom": "^19.3.1",
54
+ "react-markdown": "^10.1.0",
55
+ "remark-gfm": "^4.0.1",
56
+ "typescript": "~5.9.3",
57
+ "vite": "^8.3.5",
58
+ "vitest": "^5.0.5"
59
+ }
60
+ }