@jadchene/mcp-gateway-service 0.11.2 → 0.12.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/dist/index.js CHANGED
@@ -1,4 +1,8 @@
1
1
  #!/usr/bin/env node
2
+ import { ConfigWebServer } from "./web-config/server.js";
3
+ import { parseWebArgs } from "./web-config/options.js";
4
+ import { validateGatewayConfig } from "./config.js";
5
+ import { dirname } from "node:path";
2
6
  import { existsSync } from "node:fs";
3
7
  import { resolve } from "node:path";
4
8
  import { ConfigLoader } from "./config.js";
@@ -45,6 +49,8 @@ class Application {
45
49
  * Stores the optional Streamable HTTP gateway server.
46
50
  */
47
51
  httpServer = null;
52
+ /** 独立的配置页面服务。 */
53
+ webServer;
48
54
  /**
49
55
  * Stores the file watcher used for config hot reload.
50
56
  */
@@ -62,20 +68,40 @@ class Application {
62
68
  if (!existsSync(this.configPath)) {
63
69
  throw new Error(`Config file was not found: ${this.configPath}`);
64
70
  }
65
- const startup = this.registry.initialize();
66
- this.engine.setStartupBarrier(startup);
67
- this.server.start();
68
- await startup;
69
- const serverConfig = this.cliOptions.server;
70
- this.registerSignals(Boolean(serverConfig));
71
- if (serverConfig) {
72
- this.httpServer = new StreamableHttpGatewayServer(serverConfig, this.engine, this.logger);
73
- await this.httpServer.start();
71
+ try {
72
+ const startup = this.registry.initialize();
73
+ this.engine.setStartupBarrier(startup);
74
+ this.server.start();
75
+ await startup;
76
+ const serverConfig = this.cliOptions.server;
77
+ this.registerSignals(Boolean(serverConfig));
78
+ if (serverConfig) {
79
+ this.httpServer = new StreamableHttpGatewayServer(serverConfig, this.engine, this.logger);
80
+ await this.httpServer.start();
81
+ }
82
+ this.webServer = new ConfigWebServer({
83
+ project: "gateway", configPath: this.configPath, args: process.argv.slice(2), defaultPort: 3100,
84
+ services: {
85
+ list: () => this.registry.listServiceStates(),
86
+ control: (id, action) => this.registry.controlService(id, action)
87
+ },
88
+ validate: raw => validateGatewayConfig(raw, dirname(this.configPath)), reload: () => this.registry.reloadStrict(),
89
+ startup: { mcpHttp: this.cliOptions.server ? { ...this.cliOptions.server, authToken: this.cliOptions.server.authToken ? "已配置(环境变量)" : "未配置" } : { enable: false }, source: "命令行 / 默认值" }
90
+ });
91
+ await this.webServer.startOptional();
92
+ this.watcher.start();
93
+ this.logger.info("gateway.started", {
94
+ configPath: this.configPath
95
+ });
96
+ }
97
+ catch (error) {
98
+ this.watcher.stop();
99
+ await this.webServer?.close();
100
+ await this.httpServer?.stop();
101
+ await this.server.stop();
102
+ await this.registry.dispose();
103
+ throw error;
74
104
  }
75
- this.watcher.start();
76
- this.logger.info("gateway.started", {
77
- configPath: this.configPath
78
- });
79
105
  }
80
106
  /**
81
107
  * Registers signal handlers for graceful shutdown.
@@ -88,6 +114,7 @@ class Application {
88
114
  this.shuttingDown = true;
89
115
  this.logger.info("gateway.stopping", { signal });
90
116
  this.watcher.stop();
117
+ await this.webServer?.close();
91
118
  await this.httpServer?.stop();
92
119
  await this.server.stop();
93
120
  await this.registry.dispose();
@@ -115,6 +142,7 @@ if (import.meta.main) {
115
142
  });
116
143
  }
117
144
  export function parseCliArgs(args) {
145
+ args = parseWebArgs(args).remaining;
118
146
  if (args.includes("--protocol-mode")) {
119
147
  throw new Error("--protocol-mode is no longer supported; protocol negotiation is automatic.");
120
148
  }
@@ -40,7 +40,7 @@ function createStandardTransport(command, args, cwd, env, logger, serviceId) {
40
40
  /**
41
41
  * Resolves a configured command into a directly spawnable executable on Windows.
42
42
  */
43
- export function resolveCommandSpec(command, args) {
43
+ function resolveCommandSpec(command, args) {
44
44
  if (process.platform !== "win32" || /[\\/]/.test(command) || /\.[A-Za-z0-9]+$/.test(command)) {
45
45
  return { command, args };
46
46
  }
@@ -1,4 +1,4 @@
1
- import { StreamableHTTPClientTransport } from "@modelcontextprotocol/client";
1
+ import { SdkHttpError, StreamableHTTPClientTransport } from "@modelcontextprotocol/client";
2
2
  import { SdkMcpClient } from "./sdk-client.js";
3
3
  /**
4
4
  * Connects to a downstream HTTP MCP service through the official SDK v2.
@@ -18,6 +18,35 @@ export class StreamableHttpClient extends SdkMcpClient {
18
18
  }
19
19
  }));
20
20
  }
21
+ /** 仅对已建立的旧版 HTTP 会话识别失效响应,不将认证或参数错误视为重连信号。 */
22
+ isSessionExpired(error, client) {
23
+ const transport = client?.transport;
24
+ if (!(error instanceof SdkHttpError)
25
+ || !(transport instanceof StreamableHTTPClientTransport)
26
+ || !transport.sessionId
27
+ || client?.getProtocolEra() !== "legacy") {
28
+ return false;
29
+ }
30
+ if (error.status === 404) {
31
+ return true;
32
+ }
33
+ if (error.status !== 400 || typeof error.data.text !== "string") {
34
+ return false;
35
+ }
36
+ try {
37
+ const response = JSON.parse(error.data.text);
38
+ // 微信开发者工具在旧会话不存在时返回通用 Bad Request,且响应不关联请求 ID。
39
+ return response?.error === "Invalid or missing session ID"
40
+ || (response?.jsonrpc === "2.0"
41
+ && response?.id === null
42
+ && response?.error?.code === -32000
43
+ && response?.error?.message === "Bad Request")
44
+ || response?.error?.message === "Session not found";
45
+ }
46
+ catch {
47
+ return false;
48
+ }
49
+ }
21
50
  }
22
51
  /**
23
52
  * Applies static configured headers without allowing them to replace per-request SDK headers.
@@ -19,6 +19,7 @@ export class SdkMcpClient {
19
19
  logger;
20
20
  transportFactory;
21
21
  client = null;
22
+ disposed = false;
22
23
  connecting = null;
23
24
  restartAttempts = 0;
24
25
  unavailableReason = null;
@@ -39,6 +40,10 @@ export class SdkMcpClient {
39
40
  get isUnavailable() {
40
41
  return this.unavailableReason !== null;
41
42
  }
43
+ /** 显示实际连接状态,连接关闭后立即变为 false。 */
44
+ get isConnected() { return this.client !== null; }
45
+ /** 仅由显式启动或恢复操作重新启用连接。 */
46
+ activate() { this.disposed = false; }
42
47
  /**
43
48
  * Returns the terminal unavailability reason.
44
49
  */
@@ -55,12 +60,16 @@ export class SdkMcpClient {
55
60
  * Checks whether this client can be reused after config reload.
56
61
  */
57
62
  matchesConfig(service) {
58
- return JSON.stringify(this.service) === JSON.stringify(service);
63
+ // 页面地址、名称及工具过滤由注册表处理,不应触发下游进程重启。
64
+ return JSON.stringify(this.service.transport) === JSON.stringify(service.transport)
65
+ && this.service.callTimeoutMs === service.callTimeoutMs;
59
66
  }
60
67
  /**
61
68
  * Establishes an SDK connection with the configured era negotiation policy.
62
69
  */
63
70
  async ensureConnected() {
71
+ if (this.disposed)
72
+ throw new Error(`Service '${this.key}' is stopped.`);
64
73
  if (this.client) {
65
74
  return;
66
75
  }
@@ -82,6 +91,8 @@ export class SdkMcpClient {
82
91
  * Closes the SDK client and clears lifecycle errors.
83
92
  */
84
93
  async dispose() {
94
+ this.disposed = true;
95
+ await this.connecting?.catch(() => undefined);
85
96
  this.restartAttempts = 0;
86
97
  this.unavailableReason = null;
87
98
  await this.disposeConnection();
@@ -90,8 +101,7 @@ export class SdkMcpClient {
90
101
  * Refreshes server identity and the complete tool catalog.
91
102
  */
92
103
  async getMetadata() {
93
- return this.executeWithRecovery(async () => {
94
- const client = await this.requireClient();
104
+ return this.executeWithRecovery(async (client) => {
95
105
  const tools = await this.requestToolsList(client);
96
106
  return {
97
107
  protocolVersion: client.getNegotiatedProtocolVersion() ?? null,
@@ -106,14 +116,16 @@ export class SdkMcpClient {
106
116
  * Lists the downstream tools using SDK caching and pagination behavior.
107
117
  */
108
118
  async listTools() {
109
- return this.executeWithRecovery(async () => this.requestToolsList(await this.requireClient()));
119
+ return this.executeWithRecovery((client) => this.requestToolsList(client));
110
120
  }
111
121
  /**
112
122
  * Calls a downstream tool while preserving cancellation, custom headers, and MRTR state.
113
123
  */
114
124
  async callTool(name, args, context = {}) {
125
+ let client = null;
115
126
  try {
116
- const client = await this.requireClient();
127
+ client = await this.requireClient();
128
+ const callClient = client;
117
129
  const params = {
118
130
  name,
119
131
  arguments: args,
@@ -124,7 +136,7 @@ export class SdkMcpClient {
124
136
  };
125
137
  const invoke = async (signal) => {
126
138
  const callSignal = combineWithTimeout(signal, this.service.callTimeoutMs ?? DEFAULT_CALL_TIMEOUT_MS);
127
- const result = await client.callTool(params, {
139
+ const result = await callClient.callTool(params, {
128
140
  signal: callSignal,
129
141
  allowInputRequired: true,
130
142
  toolDefinition: this.tools.get(name)
@@ -132,20 +144,28 @@ export class SdkMcpClient {
132
144
  return result;
133
145
  };
134
146
  if (client.getProtocolEra() === "legacy") {
135
- return this.formElicitationBridge.execute(name, args, context, invoke);
147
+ return await this.formElicitationBridge.execute(name, args, context, invoke);
136
148
  }
137
149
  const result = await invoke(context.signal ?? new AbortController().signal);
138
150
  return result;
139
151
  }
140
152
  catch (error) {
141
153
  const normalized = normalizeError(error);
154
+ if (this.isSessionExpired(normalized, client)) {
155
+ await this.disposeConnection(client);
156
+ throw new Error(`Downstream session expired while calling '${name}'; the gateway did not replay it. The next call will reconnect. ${normalized.message}`, { cause: normalized });
157
+ }
142
158
  if (isNonRetryable(normalized) || context.signal?.aborted) {
143
159
  throw normalized;
144
160
  }
145
- await this.disposeConnection();
161
+ await this.disposeConnection(client);
146
162
  throw new Error(`Downstream tool '${name}' failed; execution status is unknown and the gateway did not replay it. ${normalized.message}`, { cause: normalized });
147
163
  }
148
164
  }
165
+ /** 判断传输层是否明确报告当前会话已失效,默认传输不作此判断。 */
166
+ isSessionExpired(_error, _client) {
167
+ return false;
168
+ }
149
169
  /**
150
170
  * Connects one fresh SDK client and transport.
151
171
  */
@@ -185,9 +205,14 @@ export class SdkMcpClient {
185
205
  message: error.message
186
206
  });
187
207
  };
208
+ client.onclose = () => this.clearConnection(client);
188
209
  const transport = transportFactory();
189
210
  try {
190
211
  await client.connect(transport, { timeout: CONNECT_TIMEOUT_MS });
212
+ if (this.disposed) {
213
+ await client.close();
214
+ throw new Error(`Service '${this.key}' is stopped.`);
215
+ }
191
216
  this.client = client;
192
217
  this.logger.info("downstream.connected", {
193
218
  serviceId: this.key,
@@ -225,22 +250,24 @@ export class SdkMcpClient {
225
250
  return result.tools.map(normalizeToolDefinition);
226
251
  }
227
252
  /**
228
- * Retries transport failures while leaving protocol and HTTP client errors untouched.
253
+ * 重试只读元数据请求的传输或会话错误,保留其他协议及 HTTP 错误。
229
254
  */
230
255
  async executeWithRecovery(operation) {
231
256
  while (true) {
232
257
  if (this.unavailableReason) {
233
258
  throw new Error(this.unavailableReason);
234
259
  }
260
+ let client = null;
235
261
  try {
236
- return await operation();
262
+ client = await this.requireClient();
263
+ return await operation(client);
237
264
  }
238
265
  catch (error) {
239
266
  const normalized = normalizeError(error);
240
- if (isNonRetryable(normalized)) {
267
+ if (isNonRetryable(normalized) && !this.isSessionExpired(normalized, client)) {
241
268
  throw normalized;
242
269
  }
243
- await this.disposeConnection();
270
+ await this.disposeConnection(client);
244
271
  if (this.restartAttempts >= MAX_RESTART_ATTEMPTS) {
245
272
  this.unavailableReason = `Service '${this.key}' is unavailable after ${MAX_RESTART_ATTEMPTS} restart attempts. Last error: ${normalized.message}`;
246
273
  throw new Error(this.unavailableReason);
@@ -255,14 +282,26 @@ export class SdkMcpClient {
255
282
  }
256
283
  }
257
284
  /**
258
- * Closes the active SDK connection and clears derived tool views.
285
+ * 关闭失败请求所属的连接,避免旧请求误关闭已经建立的新连接。
259
286
  */
260
- async disposeConnection() {
261
- this.formElicitationBridge.reset(new Error(`Downstream service '${this.key}' connection was closed.`));
287
+ async disposeConnection(expectedClient) {
262
288
  const client = this.client;
289
+ if (expectedClient !== undefined && client !== expectedClient) {
290
+ return;
291
+ }
292
+ if (client) {
293
+ this.clearConnection(client);
294
+ await client.close().catch(() => undefined);
295
+ }
296
+ }
297
+ /** 清理当前连接的派生状态;已替换连接的关闭事件不影响新连接。 */
298
+ clearConnection(client) {
299
+ if (this.client !== client) {
300
+ return;
301
+ }
302
+ this.formElicitationBridge.reset(new Error(`Downstream service '${this.key}' connection was closed.`));
263
303
  this.client = null;
264
304
  this.tools.clear();
265
- await client?.close().catch(() => undefined);
266
305
  }
267
306
  }
268
307
  /**
@@ -36,6 +36,58 @@ export class ServiceRegistry {
36
36
  */
37
37
  reloadPromise = Promise.resolve();
38
38
  managementPromise = Promise.resolve();
39
+ /** 用户停止状态跨配置热重载保留,Gateway 重启后重新按配置加载。 */
40
+ stopped = new Set();
41
+ /** 当前执行中的生命周期动作,用于页面状态和调用拦截。 */
42
+ transitions = new Map();
43
+ /** 返回页面所需的运行信息,不包含启动参数和凭据。 */
44
+ listServiceStates() {
45
+ return this.listServices().map(snapshot => {
46
+ const id = snapshot.config.serviceId;
47
+ const client = this.clients.get(id);
48
+ return {
49
+ serviceId: id,
50
+ status: this.transitions.get(id) ?? (this.stopped.has(id) ? "stopped"
51
+ : client?.isConnected ? "running" : "failed"),
52
+ lastError: snapshot.runtime.lastError ?? (!client?.isConnected && !this.stopped.has(id) && !this.transitions.has(id) ? "下游连接已关闭" : null),
53
+ lastConnectedAt: snapshot.runtime.lastConnectedAt,
54
+ toolCount: this.listTools(id).length
55
+ };
56
+ });
57
+ }
58
+ /** 串行控制已启用服务,停止操作不修改配置文件。 */
59
+ controlService(serviceId, action) {
60
+ const operation = this.reloadPromise.catch(() => undefined).then(async () => {
61
+ const snapshot = this.requireService(serviceId);
62
+ const current = this.clients.get(serviceId);
63
+ if (action === "start" && current?.isConnected && !this.stopped.has(serviceId))
64
+ return;
65
+ this.transitions.set(serviceId, action === "stop" ? "stopping" : "starting");
66
+ try {
67
+ this.stopped.add(serviceId);
68
+ await current?.dispose();
69
+ snapshot.runtime.available = false;
70
+ snapshot.runtime.lastError = null;
71
+ if (action === "stop")
72
+ return;
73
+ this.stopped.delete(serviceId);
74
+ const next = createClient(snapshot.config, this.logger);
75
+ this.clients.set(serviceId, next);
76
+ snapshot.metadata = await next.getMetadata();
77
+ this.markServiceAvailable(serviceId, next.restartCount);
78
+ }
79
+ catch (error) {
80
+ const message = error instanceof Error ? error.message : String(error);
81
+ this.markServiceUnavailable(serviceId, message, this.clients.get(serviceId)?.restartCount ?? 0);
82
+ throw error;
83
+ }
84
+ finally {
85
+ this.transitions.delete(serviceId);
86
+ }
87
+ });
88
+ this.reloadPromise = operation.catch(() => undefined);
89
+ return operation;
90
+ }
39
91
  /**
40
92
  * Creates a registry bound to one config file path.
41
93
  */
@@ -147,6 +199,9 @@ export class ServiceRegistry {
147
199
  */
148
200
  async callTool(serviceId, toolName, args, context = {}) {
149
201
  const snapshot = this.requireService(serviceId);
202
+ if (this.stopped.has(serviceId) || this.transitions.has(serviceId)) {
203
+ throw new Error(`Service '${serviceId}' is stopped or changing state.`);
204
+ }
150
205
  if (matchesAnyToolNamePattern(toolName, snapshot.config.disabledTools)) {
151
206
  throw new Error(`Tool '${toolName}' in service '${serviceId}' is disabled by gateway configuration.`);
152
207
  }
@@ -199,6 +254,14 @@ export class ServiceRegistry {
199
254
  * Reconnects one currently configured service and refreshes its metadata snapshot.
200
255
  */
201
256
  async reconnectService(serviceId) {
257
+ // 与配置重载共用队列,防止两个替换操作同时启动同一服务。
258
+ const operation = this.reloadPromise.catch(() => undefined)
259
+ .then(() => this.reconnectServiceOnce(serviceId));
260
+ this.reloadPromise = operation.then(() => undefined, () => undefined);
261
+ return operation;
262
+ }
263
+ /** 在注册表生命周期队列中执行一次重连。 */
264
+ async reconnectServiceOnce(serviceId) {
202
265
  const snapshot = this.requireService(serviceId);
203
266
  const previousRuntime = snapshot.runtime;
204
267
  const currentClient = this.clients.get(serviceId);
@@ -206,6 +269,10 @@ export class ServiceRegistry {
206
269
  throw new Error(`Service '${serviceId}' is unavailable.`);
207
270
  }
208
271
  const nextClient = createClient(snapshot.config, this.logger);
272
+ const restartProcess = snapshot.config.transport.type === "stdio";
273
+ // stdio 子进程可能持有 Web 端口等独占资源,必须先关闭旧实例。
274
+ if (restartProcess)
275
+ await currentClient.dispose();
209
276
  try {
210
277
  const metadata = await nextClient.getMetadata();
211
278
  snapshot.metadata = metadata;
@@ -216,6 +283,7 @@ export class ServiceRegistry {
216
283
  restartAttempts: nextClient.restartCount
217
284
  };
218
285
  this.clients.set(serviceId, nextClient);
286
+ this.stopped.delete(serviceId);
219
287
  await currentClient.dispose().catch(() => undefined);
220
288
  return {
221
289
  serviceId,
@@ -227,17 +295,28 @@ export class ServiceRegistry {
227
295
  catch (error) {
228
296
  await nextClient.dispose().catch(() => undefined);
229
297
  const message = error instanceof Error ? error.message : String(error);
298
+ let restored = false;
299
+ if (restartProcess) {
300
+ try {
301
+ currentClient.activate();
302
+ snapshot.metadata = await currentClient.getMetadata();
303
+ restored = true;
304
+ }
305
+ catch {
306
+ // 原配置也无法恢复时,保留明确的不可用状态。
307
+ }
308
+ }
230
309
  snapshot.runtime = {
231
- available: previousRuntime.available,
232
- lastError: `Reconnect failed; existing connection retained: ${message}`,
233
- lastConnectedAt: previousRuntime.lastConnectedAt,
310
+ available: restartProcess ? restored : previousRuntime.available,
311
+ lastError: `Reconnect failed; ${restartProcess ? (restored ? "previous configuration restored" : "previous configuration could not be restored") : "existing connection retained"}: ${message}`,
312
+ lastConnectedAt: restored ? new Date().toISOString() : previousRuntime.lastConnectedAt,
234
313
  restartAttempts: currentClient.restartCount
235
314
  };
236
315
  return {
237
316
  serviceId,
238
317
  action: "reconnect",
239
318
  enabled: true,
240
- available: previousRuntime.available
319
+ available: snapshot.runtime.available
241
320
  };
242
321
  }
243
322
  }
@@ -285,6 +364,11 @@ export class ServiceRegistry {
285
364
  ? reusedClient
286
365
  : createClient(service, this.logger);
287
366
  nextClients.set(service.serviceId, client);
367
+ if (reusedClient && reusedClient !== client
368
+ && this.snapshots.get(service.serviceId)?.config.transport.type === "stdio") {
369
+ // 配置切换前释放旧进程的监听端口,避免新旧实例争用同一端口。
370
+ await reusedClient.dispose();
371
+ }
288
372
  let metadata = {
289
373
  protocolVersion: null,
290
374
  protocolEra: null,
@@ -296,6 +380,9 @@ export class ServiceRegistry {
296
380
  let lastError = null;
297
381
  let lastConnectedAt = null;
298
382
  try {
383
+ if (this.stopped.has(service.serviceId)) {
384
+ return { config: service, metadata, runtime: { available: false, lastError: null, lastConnectedAt: null, restartAttempts: 0 } };
385
+ }
299
386
  metadata = await client.getMetadata();
300
387
  available = true;
301
388
  lastConnectedAt = new Date().toISOString();
package/dist/version.js CHANGED
@@ -4,5 +4,4 @@ import { fileURLToPath } from "node:url";
4
4
  const __dirname = dirname(fileURLToPath(import.meta.url));
5
5
  const packageJsonPath = resolve(__dirname, "../package.json");
6
6
  const packageJson = JSON.parse(readFileSync(packageJsonPath, "utf8"));
7
- export const NAME = packageJson.name ?? "mcp-gateway-service";
8
7
  export const VERSION = packageJson.version ?? "0.0.0";
@@ -0,0 +1,71 @@
1
+ /** 检查 Web 文件配置,未设置时保持禁用。 */
2
+ export const validateWebConfig = (input) => {
3
+ if (input === undefined)
4
+ return {};
5
+ if (!input || typeof input !== "object" || Array.isArray(input))
6
+ throw new Error("web must be an object");
7
+ const value = input;
8
+ for (const key of Object.keys(value)) {
9
+ if (!["enabled", "host", "port"].includes(key))
10
+ throw new Error(`Unknown web.${key}`);
11
+ }
12
+ if (value.enabled !== undefined && typeof value.enabled !== "boolean")
13
+ throw new Error("web.enabled must be boolean");
14
+ if (value.port !== undefined &&
15
+ (!Number.isInteger(value.port) ||
16
+ Number(value.port) < 1 ||
17
+ Number(value.port) > 65535))
18
+ throw new Error("web.port must be 1–65535");
19
+ if (value.host !== undefined && value.host !== "127.0.0.1")
20
+ throw new Error("Web only supports 127.0.0.1; remote listening is disabled");
21
+ return value;
22
+ };
23
+ /** 分离 Web 参数,不改变原有 MCP 参数的含义。 */
24
+ export const parseWebArgs = (args) => {
25
+ const remaining = [];
26
+ const overrides = {};
27
+ const seen = new Set();
28
+ for (let index = 0; index < args.length; index++) {
29
+ const arg = args[index];
30
+ if (!["--web", "--no-web", "--web-host", "--web-port"].includes(arg)) {
31
+ remaining.push(arg);
32
+ continue;
33
+ }
34
+ if (seen.has(arg))
35
+ throw new Error(`Duplicate option ${arg}`);
36
+ seen.add(arg);
37
+ if (arg === "--web" || arg === "--no-web")
38
+ overrides.enabled = arg === "--web";
39
+ else {
40
+ const value = args[++index];
41
+ if (!value || value.startsWith("--"))
42
+ throw new Error(`${arg} requires a value`);
43
+ if (arg === "--web-host")
44
+ overrides.host = value;
45
+ else
46
+ overrides.port = Number(value);
47
+ }
48
+ }
49
+ if (seen.has("--web") && seen.has("--no-web"))
50
+ throw new Error("--web and --no-web cannot be combined");
51
+ validateWebConfig(overrides);
52
+ return { remaining, overrides };
53
+ };
54
+ /** 合并默认值、文件值和本次进程覆盖,并提供可展示的来源。 */
55
+ export const resolveWebOptions = (raw, args, port) => {
56
+ const file = validateWebConfig(raw);
57
+ const { overrides } = parseWebArgs(args);
58
+ const defaults = { enabled: false, host: "127.0.0.1", port };
59
+ const effective = { ...defaults, ...file, ...overrides, host: "127.0.0.1" };
60
+ const sources = Object.fromEntries(Object.keys(effective).map((key) => [
61
+ key,
62
+ key === "host"
63
+ ? "固定本机"
64
+ : Object.hasOwn(overrides, key)
65
+ ? "命令行"
66
+ : Object.hasOwn(file, key)
67
+ ? "配置文件"
68
+ : "默认值",
69
+ ]));
70
+ return { effective, sources };
71
+ };