feat: release v0.5.0 with embedded HTTP server and resident daemon service
🚀 Release / 🚀 Build & Publish Multi-Platform Binaries (push) Has been cancelled

This commit is contained in:
gitea committed 2026-09-03 15:19:12 +08:00
1 parent 07b4e14e59
commit c1dc9f1616
17 files changed
+838 -9

No files matched your search

+29
View File
@@ -0,0 +1,29 @@
import { VERSION } from "../version.js";
export function renderDocsHtml(): string {
return `<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" />
<title>hose-use API Reference (v${VERSION})</title>
<link rel="icon" type="image/svg+xml" href="data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 100 100'><text y='.9em' font-size='90'>⚡</text></svg>" />
<style>
body {
margin: 0;
padding: 0;
background-color: #0f172a;
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
}
</style>
</head>
<body>
<script
id="api-reference"
data-url="/openapi.json"
data-configuration='{"theme":"purple","layout":"modern","showSidebar":true}'
src="https://cdn.jsdelivr.net/npm/@scalar/api-reference@1.25.101/dist/browser/standalone.js"
></script>
</body>
</html>`;
}
+180
View File
@@ -0,0 +1,180 @@
import type { IncomingMessage, ServerResponse } from "node:http";
import { URL } from "node:url";
import { runCli } from "../cli/runner.js";
import { loadCorpConfigs, loadGlobalConfig } from "../core/config/loader.js";
import { getOpenApiSchema } from "../core/embedded-openapi.js";
import { tokenizeCommand, normalizeCliArgs } from "../server.js";
import { VERSION } from "../version.js";
import { renderDocsHtml } from "./docs.js";
export async function handleHttpRequest(req: IncomingMessage, res: ServerResponse): Promise<void> {
// 1. CORS headers
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, PATCH");
res.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization, X-Hose-Corp");
if (req.method === "OPTIONS") {
res.writeHead(204);
res.end();
return;
}
const host = req.headers.host || "localhost";
const protocol = req.headers["x-forwarded-proto"] || "http";
const url = new URL(req.url || "/", `${protocol}://${host}`);
const pathname = url.pathname.replace(/\/+$/, "") || "/";
const method = (req.method || "GET").toUpperCase();
try {
// 2. Metadata & Health
if (method === "GET" && pathname === "/") {
sendJson(res, 200, {
name: "hose-use",
version: VERSION,
description: "合思/易快报企业级 CLI 工具与底层 SDK HTTP 服务",
docs: "/docs",
openapi: "/openapi.json",
rawOpenapi: "/raw-openapi.json",
health: "/health",
endpoints: {
cli: "POST /api/cli",
corps: "GET /v1/corps",
},
});
return;
}
if (method === "GET" && pathname === "/health") {
sendJson(res, 200, {
status: "ok",
name: "hose-use",
version: VERSION,
timestamp: new Date().toISOString(),
});
return;
}
if (method === "GET" && pathname === "/docs") {
sendHtml(res, 200, renderDocsHtml());
return;
}
if (method === "GET" && pathname === "/openapi.json") {
sendJson(res, 200, getOpenApiSchema("wrapped"));
return;
}
if (method === "GET" && pathname === "/raw-openapi.json") {
sendJson(res, 200, getOpenApiSchema("raw"));
return;
}
// 3. Command Execution Endpoint: POST /api/cli
if (method === "POST" && pathname === "/api/cli") {
const body = (await parseJsonBody(req)) as Record<string, unknown> | null;
const command = (typeof body?.command === "string" ? body.command : "").trim();
if (!command) {
sendError(res, 400, "Missing 'command' property in request body");
return;
}
const tokens = tokenizeCommand(command);
const cliArgs = normalizeCliArgs(tokens);
const result = await runCli(cliArgs);
let parsedData: unknown = undefined;
const trimmedStdout = result.stdout.trim();
try {
if (trimmedStdout.startsWith("{") || trimmedStdout.startsWith("[")) {
parsedData = JSON.parse(trimmedStdout);
}
} catch {
// keep string
}
sendJson(res, result.exitCode === 0 ? 200 : 400, {
success: result.exitCode === 0,
stdout: result.stdout,
stderr: result.stderr,
exitCode: result.exitCode,
...(parsedData !== undefined ? { data: parsedData } : {}),
});
return;
}
// 4. RESTful: GET /v1/corps
if (method === "GET" && pathname === "/v1/corps") {
const configs = loadCorpConfigs();
const globalConfig = loadGlobalConfig();
sendJson(res, 200, {
count: configs.length,
mode: globalConfig.stateful ? "stateful" : "stateless",
defaultCorpId: globalConfig.defaultCorpId,
corps: configs.map((c) => ({
id: c.id,
name: c.name,
source: c.source,
staffId: c.credentials.staffId,
baseUrl: c.baseUrl,
expiresAt: c.auth?.expiresAt || c.session?.expTime,
})),
});
return;
}
sendError(res, 404, `Cannot ${method} ${pathname}. Visit /docs for available endpoints.`);
} catch (err: unknown) {
const message = err instanceof Error ? err.message : String(err);
sendError(res, 500, message);
}
}
function sendJson(res: ServerResponse, status: number, data: unknown): void {
if (res.headersSent) return;
const payload = JSON.stringify(data, null, 2);
res.writeHead(status, {
"Content-Type": "application/json; charset=utf-8",
"Content-Length": Buffer.byteLength(payload, "utf-8"),
});
res.end(payload);
}
function sendHtml(res: ServerResponse, status: number, html: string): void {
if (res.headersSent) return;
res.writeHead(status, {
"Content-Type": "text/html; charset=utf-8",
"Content-Length": Buffer.byteLength(html, "utf-8"),
});
res.end(html);
}
function sendError(res: ServerResponse, status: number, message: string): void {
sendJson(res, status, { error: true, message });
}
async function parseJsonBody(req: IncomingMessage): Promise<unknown> {
return new Promise((resolve, reject) => {
let raw = "";
req.on("data", (chunk) => {
raw += chunk;
if (raw.length > 5 * 1024 * 1024) {
// 5MB max payload
reject(new Error("Request payload too large (max 5MB)"));
}
});
req.on("end", () => {
if (!raw.trim()) {
resolve(null);
return;
}
try {
resolve(JSON.parse(raw));
} catch (err) {
reject(new Error(`Invalid JSON body: ${err instanceof Error ? err.message : String(err)}`));
}
});
req.on("error", (err) => {
reject(err);
});
});
}
+96
View File
@@ -0,0 +1,96 @@
import { describe, expect, test, afterAll, beforeAll } from "bun:test";
import type { Server } from "node:http";
import { startHttpServer } from "./server.js";
import { VERSION } from "../version.js";
describe("HTTP Server - 嵌入式服务与 REST 网关", () => {
let server: Server;
const testPort = 18888;
const baseUrl = `http://127.0.0.1:${testPort}`;
beforeAll(async () => {
server = await startHttpServer({ port: testPort, host: "127.0.0.1", silent: true });
});
afterAll(async () => {
await new Promise<void>((resolve) => server.close(() => resolve()));
});
test("GET / 返回服务概览与 CORS 标头", async () => {
const res = await fetch(`${baseUrl}/`);
expect(res.status).toBe(200);
expect(res.headers.get("access-control-allow-origin")).toBe("*");
const json = (await res.json()) as any;
expect(json.name).toBe("hose-use");
expect(json.version).toBe(VERSION);
expect(json.docs).toBe("/docs");
expect(json.openapi).toBe("/openapi.json");
expect(json.health).toBe("/health");
expect(json.endpoints.cli).toBe("POST /api/cli");
});
test("GET /health 返回存活探针状态", async () => {
const res = await fetch(`${baseUrl}/health`);
expect(res.status).toBe(200);
const json = (await res.json()) as any;
expect(json.status).toBe("ok");
expect(json.name).toBe("hose-use");
expect(json.version).toBe(VERSION);
expect(json.timestamp).toBeDefined();
});
test("GET /openapi.json 返回标准包装层 OpenAPI 规范", async () => {
const res = await fetch(`${baseUrl}/openapi.json`);
expect(res.status).toBe(200);
const json = (await res.json()) as any;
expect(json.openapi).toBe("3.1.0");
expect(json.info.title).toContain("hose-use");
});
test("GET /raw-openapi.json 返回原生下游 OpenAPI 规范", async () => {
const res = await fetch(`${baseUrl}/raw-openapi.json`);
expect(res.status).toBe(200);
const json = (await res.json()) as any;
expect(json.openapi).toBe("3.1.0");
expect(json.info.title).toContain("Downstream");
});
test("GET /docs 返回 Scalar 交互式文档 HTML 页面", async () => {
const res = await fetch(`${baseUrl}/docs`);
expect(res.status).toBe(200);
expect(res.headers.get("content-type")).toContain("text/html");
const html = await res.text();
expect(html).toContain("<html");
expect(html).toContain("api-reference");
expect(html).toContain("data-url=\"/openapi.json\"");
});
test("POST /api/cli 允许同进程执行 CLI 指令", async () => {
const res = await fetch(`${baseUrl}/api/cli`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ command: "version" }),
});
expect(res.status).toBe(200);
const json = (await res.json()) as any;
expect(json.success).toBe(true);
expect(json.exitCode).toBe(0);
expect(json.stdout).toContain(`hose-use v${VERSION}`);
});
test("GET /v1/corps 返回企业列表与运行模式", async () => {
const res = await fetch(`${baseUrl}/v1/corps`);
expect(res.status).toBe(200);
const json = (await res.json()) as any;
expect(json).toHaveProperty("count");
expect(json).toHaveProperty("mode");
expect(Array.isArray(json.corps)).toBe(true);
});
test("OPTIONS /v1/corps 处理 CORS 跨域预检", async () => {
const res = await fetch(`${baseUrl}/v1/corps`, { method: "OPTIONS" });
expect(res.status).toBe(204);
expect(res.headers.get("access-control-allow-methods")).toContain("GET");
expect(res.headers.get("access-control-allow-origin")).toBe("*");
});
});
+46
View File
@@ -0,0 +1,46 @@
import { createServer, type Server } from "node:http";
import { handleHttpRequest } from "./routes.js";
import { VERSION } from "../version.js";
export type HttpServerOptions = {
port?: number;
host?: string;
silent?: boolean;
};
export const DEFAULT_HTTP_PORT = 8888;
export const DEFAULT_HTTP_HOST = "127.0.0.1";
export async function startHttpServer(options: HttpServerOptions = {}): Promise<Server> {
const port = options.port ?? (process.env.PORT ? Number.parseInt(process.env.PORT, 10) : DEFAULT_HTTP_PORT);
const host = options.host ?? (process.env.HOST ? process.env.HOST : DEFAULT_HTTP_HOST);
const server = createServer(async (req, res) => {
try {
await handleHttpRequest(req, res);
} catch (err) {
if (!res.headersSent) {
res.writeHead(500, { "Content-Type": "application/json; charset=utf-8" });
res.end(JSON.stringify({ error: true, message: err instanceof Error ? err.message : String(err) }));
}
}
});
return new Promise((resolve, reject) => {
server.on("error", (err) => {
reject(err);
});
server.listen(port, host, () => {
if (!options.silent) {
console.error(`\n⚡ hose-use HTTP Server (v${VERSION}) 已启动`);
console.error(` 主服务地址: http://${host}:${port}`);
console.error(` 交互式文档: http://${host}:${port}/docs`);
console.error(` OpenAPI规范: http://${host}:${port}/openapi.json`);
console.error(` CLI执行网关: POST http://${host}:${port}/api/cli`);
console.error(` 企业列表接口: GET http://${host}:${port}/v1/corps\n`);
}
resolve(server);
});
});
}