mcp-server-bugzilla4 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/LICENSE +21 -0
- package/README.md +161 -2
- package/package.json +35 -4
- package/src/cli-args.js +57 -0
- package/src/index.js +102 -0
- package/src/install.js +244 -0
- package/src/lib/config.js +138 -0
- package/src/lib/rpc-client.js +285 -0
- package/src/lib/search.js +143 -0
- package/src/lib/util.js +90 -0
- package/src/lib/weights.js +111 -0
- package/src/lib/xmlrpc.js +159 -0
- package/src/mcp/server.js +145 -0
- package/src/package-info.js +5 -0
- package/src/serve.js +55 -0
- package/src/tools/bugs.js +250 -0
- package/src/tools/common.js +147 -0
- package/src/tools/index.js +30 -0
- package/src/tools/meta.js +117 -0
- package/src/tools/weight.js +72 -0
- package/src/tools/write.js +159 -0
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
import { readFileSync } from 'node:fs';
|
|
2
|
+
import { parseWeights } from './weights.js';
|
|
3
|
+
|
|
4
|
+
export const DEFAULT_WEIGHTS = Object.freeze({ P0: 5, P1: 3, P2: 1, P3: 0.2 });
|
|
5
|
+
export const DEFAULT_EXCLUDE_RESOLUTIONS = Object.freeze(['INVALID', 'DUPLICATE', 'WORKSFORME']);
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Bugzilla 4.0 没有 REST 和 API Key,只能走 WebService(JSON-RPC / XML-RPC)。
|
|
9
|
+
*
|
|
10
|
+
* 协议(BUGZILLA_PROTOCOL):
|
|
11
|
+
* - jsonrpc : POST {BUGZILLA_URL}/jsonrpc.cgi(默认,需要服务器装了 JSON::RPC Perl 模块)
|
|
12
|
+
* - xmlrpc : POST {BUGZILLA_URL}/xmlrpc.cgi(4.0 默认就可用)
|
|
13
|
+
*
|
|
14
|
+
* 认证方式(BUGZILLA_AUTH_TYPE):
|
|
15
|
+
* - cookie : 调用 User.login 登录,保存返回的 Bugzilla_login / Bugzilla_logincookie Cookie(默认)
|
|
16
|
+
* - params : 每次调用在参数里带 Bugzilla_login / Bugzilla_password,不保存会话
|
|
17
|
+
* - none : 匿名访问,只能读公开 Bug
|
|
18
|
+
*/
|
|
19
|
+
export function loadConfig(env = process.env) {
|
|
20
|
+
const rawUrl = (env.BUGZILLA_URL || '').trim().replace(/\/+$/, '');
|
|
21
|
+
if (!rawUrl) throw new Error('缺少 BUGZILLA_URL,例如 https://bugzilla.example.com');
|
|
22
|
+
|
|
23
|
+
let parsed;
|
|
24
|
+
try {
|
|
25
|
+
parsed = new URL(rawUrl);
|
|
26
|
+
} catch {
|
|
27
|
+
throw new Error(`BUGZILLA_URL 不是合法的 URL:${rawUrl}`);
|
|
28
|
+
}
|
|
29
|
+
const allowInsecureHttp = parseBool(env.BUGZILLA_ALLOW_INSECURE_HTTP, false);
|
|
30
|
+
if (parsed.protocol === 'http:' && !allowInsecureHttp) {
|
|
31
|
+
throw new Error('BUGZILLA_URL 必须使用 HTTPS(密码会随登录请求发送)。仅内网可设置 BUGZILLA_ALLOW_INSECURE_HTTP=true 放开');
|
|
32
|
+
}
|
|
33
|
+
if (!['https:', 'http:'].includes(parsed.protocol)) throw new Error(`BUGZILLA_URL 协议不受支持:${parsed.protocol}`);
|
|
34
|
+
if (parsed.username || parsed.password) throw new Error('BUGZILLA_URL 中禁止携带账号密码');
|
|
35
|
+
if (/\.cgi$/i.test(parsed.pathname)) {
|
|
36
|
+
throw new Error('BUGZILLA_URL 填 Bugzilla 根地址即可(如 https://bugzilla.example.com),不要带 jsonrpc.cgi / xmlrpc.cgi');
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
const protocol = (env.BUGZILLA_PROTOCOL || 'jsonrpc').trim().toLowerCase();
|
|
40
|
+
if (!['jsonrpc', 'xmlrpc'].includes(protocol)) throw new Error(`BUGZILLA_PROTOCOL 取值非法:${protocol},可选 jsonrpc / xmlrpc`);
|
|
41
|
+
const rpcPath = `/${(env.BUGZILLA_RPC_PATH || `${protocol}.cgi`).trim().replace(/^\/+/, '')}`;
|
|
42
|
+
if (!/^\/[\w./-]+$/.test(rpcPath)) throw new Error(`BUGZILLA_RPC_PATH 非法:${rpcPath}`);
|
|
43
|
+
|
|
44
|
+
const login = (env.BUGZILLA_LOGIN || '').trim();
|
|
45
|
+
const password = readSecret(env, 'BUGZILLA_PASSWORD');
|
|
46
|
+
|
|
47
|
+
let authType = (env.BUGZILLA_AUTH_TYPE || '').trim().toLowerCase();
|
|
48
|
+
if (!authType) authType = login ? 'cookie' : 'none';
|
|
49
|
+
if (!['cookie', 'params', 'none'].includes(authType)) {
|
|
50
|
+
throw new Error(`BUGZILLA_AUTH_TYPE 取值非法:${authType},可选 cookie / params / none`);
|
|
51
|
+
}
|
|
52
|
+
if (authType !== 'none' && (!login || !password)) {
|
|
53
|
+
throw new Error(`${authType} 认证需要同时配置 BUGZILLA_LOGIN 和 BUGZILLA_PASSWORD(或 BUGZILLA_PASSWORD_FILE)`);
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
const weightField = (env.BUGZILLA_WEIGHT_FIELD || 'priority').trim();
|
|
57
|
+
if (!/^\w+$/.test(weightField)) throw new Error(`BUGZILLA_WEIGHT_FIELD 非法:${weightField}`);
|
|
58
|
+
const versionField = (env.BUGZILLA_VERSION_FIELD || 'version').trim();
|
|
59
|
+
if (!/^\w+$/.test(versionField)) throw new Error(`BUGZILLA_VERSION_FIELD 非法:${versionField}`);
|
|
60
|
+
|
|
61
|
+
return Object.freeze({
|
|
62
|
+
baseUrl: rawUrl,
|
|
63
|
+
protocol,
|
|
64
|
+
rpcPath,
|
|
65
|
+
authType,
|
|
66
|
+
login,
|
|
67
|
+
password,
|
|
68
|
+
readOnly: parseBool(env.BUGZILLA_READ_ONLY, false),
|
|
69
|
+
timeoutMs: parseIntInRange(env.BUGZILLA_TIMEOUT_MS, 60000, 1000, 600000, 'BUGZILLA_TIMEOUT_MS'),
|
|
70
|
+
concurrency: parseIntInRange(env.BUGZILLA_CONCURRENCY, 2, 1, 16, 'BUGZILLA_CONCURRENCY'),
|
|
71
|
+
maxRetries: parseIntInRange(env.BUGZILLA_MAX_RETRIES, 2, 0, 5, 'BUGZILLA_MAX_RETRIES'),
|
|
72
|
+
pageSize: parseIntInRange(env.BUGZILLA_PAGE_SIZE, 500, 0, 10000, 'BUGZILLA_PAGE_SIZE'),
|
|
73
|
+
maxResults: parseIntInRange(env.BUGZILLA_MAX_RESULTS, 10000, 1, 100000, 'BUGZILLA_MAX_RESULTS'),
|
|
74
|
+
weights: env.BUGZILLA_PRIORITY_WEIGHTS ? parseWeights(env.BUGZILLA_PRIORITY_WEIGHTS, 'BUGZILLA_PRIORITY_WEIGHTS') : { ...DEFAULT_WEIGHTS },
|
|
75
|
+
defaultWeight: parseNumber(env.BUGZILLA_DEFAULT_WEIGHT, 0, 'BUGZILLA_DEFAULT_WEIGHT'),
|
|
76
|
+
weightField,
|
|
77
|
+
versionField,
|
|
78
|
+
excludeResolutions:
|
|
79
|
+
env.BUGZILLA_EXCLUDE_RESOLUTIONS !== undefined
|
|
80
|
+
? splitList(env.BUGZILLA_EXCLUDE_RESOLUTIONS).map((s) => s.toUpperCase())
|
|
81
|
+
: [...DEFAULT_EXCLUDE_RESOLUTIONS],
|
|
82
|
+
defaultProduct: (env.BUGZILLA_DEFAULT_PRODUCT || '').trim() || undefined,
|
|
83
|
+
});
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
function readSecret(env, name) {
|
|
87
|
+
const filePath = (env[`${name}_FILE`] || '').trim();
|
|
88
|
+
if (filePath) {
|
|
89
|
+
try {
|
|
90
|
+
return readFileSync(filePath, 'utf8').trim();
|
|
91
|
+
} catch (e) {
|
|
92
|
+
throw new Error(`读取 ${name}_FILE 失败:${e.code || e.message}`);
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
return (env[name] || '').trim();
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
function parseBool(value, defaultValue) {
|
|
99
|
+
if (value === undefined || value === '') return defaultValue;
|
|
100
|
+
return ['1', 'true', 'yes', 'on'].includes(String(value).trim().toLowerCase());
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
function parseIntInRange(value, defaultValue, min, max, name) {
|
|
104
|
+
if (value === undefined || value === '') return defaultValue;
|
|
105
|
+
const n = Number.parseInt(value, 10);
|
|
106
|
+
if (!Number.isInteger(n) || n < min || n > max) throw new Error(`${name} 必须是 ${min}~${max} 之间的整数,当前值:${value}`);
|
|
107
|
+
return n;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
function parseNumber(value, defaultValue, name) {
|
|
111
|
+
if (value === undefined || value === '') return defaultValue;
|
|
112
|
+
const n = Number(value);
|
|
113
|
+
if (!Number.isFinite(n) || n < 0) throw new Error(`${name} 必须是非负数,当前值:${value}`);
|
|
114
|
+
return n;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
function splitList(value) {
|
|
118
|
+
return String(value || '')
|
|
119
|
+
.split(/[,;\n]/)
|
|
120
|
+
.map((s) => s.trim())
|
|
121
|
+
.filter(Boolean);
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/** 返回可安全打印的配置摘要(不含任何凭证) */
|
|
125
|
+
export function describeConfig(config) {
|
|
126
|
+
return {
|
|
127
|
+
baseUrl: config.baseUrl,
|
|
128
|
+
endpoint: `${config.baseUrl}${config.rpcPath}`,
|
|
129
|
+
protocol: config.protocol,
|
|
130
|
+
authType: config.authType,
|
|
131
|
+
login: config.login || undefined,
|
|
132
|
+
readOnly: config.readOnly,
|
|
133
|
+
weights: config.weights,
|
|
134
|
+
weightField: config.weightField,
|
|
135
|
+
versionField: config.versionField,
|
|
136
|
+
excludeResolutions: config.excludeResolutions,
|
|
137
|
+
};
|
|
138
|
+
}
|
|
@@ -0,0 +1,285 @@
|
|
|
1
|
+
import { RpcDateTime, XmlRpcFault, decodeResponse, encodeCall } from './xmlrpc.js';
|
|
2
|
+
|
|
3
|
+
/** 只读方法:网络错误 / 5xx 时可安全重试 */
|
|
4
|
+
const READ_METHODS = new Set([
|
|
5
|
+
'Bugzilla.version', 'Bugzilla.extensions', 'Bugzilla.time', 'Bug.get', 'Bug.search', 'Bug.history', 'Bug.comments',
|
|
6
|
+
'Bug.attachments', 'Bug.fields', 'Bug.legal_values', 'Product.get', 'Product.get_accessible_products',
|
|
7
|
+
'Product.get_selectable_products', 'Product.get_enterable_products', 'User.get',
|
|
8
|
+
]);
|
|
9
|
+
const RETRYABLE_STATUS = new Set([429, 502, 503, 504]);
|
|
10
|
+
/** 410 = 需要登录;32000 = 登录 Cookie / Token 失效 */
|
|
11
|
+
const RELOGIN_CODES = new Set([410, 32000]);
|
|
12
|
+
|
|
13
|
+
export class BugzillaError extends Error {
|
|
14
|
+
constructor(message, { status = 0, code } = {}) {
|
|
15
|
+
super(message);
|
|
16
|
+
this.name = 'BugzillaError';
|
|
17
|
+
this.status = status;
|
|
18
|
+
this.code = code;
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Bugzilla 4.0 WebService 客户端,支持 JSON-RPC(jsonrpc.cgi)与 XML-RPC(xmlrpc.cgi)。
|
|
24
|
+
* 文档:https://www.bugzilla.org/docs/4.0/en/html/api/Bugzilla/WebService.html
|
|
25
|
+
*/
|
|
26
|
+
export class BugzillaRpcClient {
|
|
27
|
+
constructor(config, fetchImpl = globalThis.fetch) {
|
|
28
|
+
if (typeof fetchImpl !== 'function') throw new Error('当前 Node 版本不支持 fetch,请升级到 Node 18.17+');
|
|
29
|
+
this.config = config;
|
|
30
|
+
this.fetch = fetchImpl;
|
|
31
|
+
this.endpoint = `${config.baseUrl}${config.rpcPath}`;
|
|
32
|
+
this.cookies = new Map();
|
|
33
|
+
this.loggedIn = false;
|
|
34
|
+
this.userId = undefined;
|
|
35
|
+
this.token = undefined;
|
|
36
|
+
this.loginPromise = null;
|
|
37
|
+
this.seq = 0;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* 调用 WebService 方法
|
|
42
|
+
* @param {string} method 如 Bug.get
|
|
43
|
+
* @param {object} params 参数(单个 hash)
|
|
44
|
+
*/
|
|
45
|
+
async call(method, params = {}, { skipAuth = false, retryAuth = true } = {}) {
|
|
46
|
+
const { authType } = this.config;
|
|
47
|
+
if (!skipAuth && authType === 'cookie' && !this.loggedIn) await this.login();
|
|
48
|
+
|
|
49
|
+
const p = stripUndefined({ ...params });
|
|
50
|
+
if (!skipAuth && authType === 'params') {
|
|
51
|
+
p.Bugzilla_login = this.config.login;
|
|
52
|
+
p.Bugzilla_password = this.config.password;
|
|
53
|
+
}
|
|
54
|
+
// 4.2.7 / 4.4.3 之后的版本会返回 token,带上可兼容新版的 CSRF 校验;4.0 没有 token 时忽略
|
|
55
|
+
if (!skipAuth && this.token) p.Bugzilla_token = this.token;
|
|
56
|
+
|
|
57
|
+
try {
|
|
58
|
+
return await this.send(method, p);
|
|
59
|
+
} catch (e) {
|
|
60
|
+
if (authType === 'cookie' && retryAuth && !skipAuth && RELOGIN_CODES.has(e.code)) {
|
|
61
|
+
this.loggedIn = false;
|
|
62
|
+
this.token = undefined;
|
|
63
|
+
this.cookies.clear();
|
|
64
|
+
await this.login();
|
|
65
|
+
return this.call(method, params, { retryAuth: false });
|
|
66
|
+
}
|
|
67
|
+
throw e;
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
async send(method, params) {
|
|
72
|
+
const isJson = this.config.protocol === 'jsonrpc';
|
|
73
|
+
const body = isJson ? JSON.stringify({ version: '1.1', method, params: [params], id: ++this.seq }) : encodeCall(method, params);
|
|
74
|
+
const canRetry = READ_METHODS.has(method);
|
|
75
|
+
let attempt = 0;
|
|
76
|
+
|
|
77
|
+
for (;;) {
|
|
78
|
+
const controller = new AbortController();
|
|
79
|
+
const timer = setTimeout(() => controller.abort(), this.config.timeoutMs);
|
|
80
|
+
let res;
|
|
81
|
+
let text;
|
|
82
|
+
try {
|
|
83
|
+
res = await this.fetch(this.endpoint, {
|
|
84
|
+
method: 'POST',
|
|
85
|
+
headers: {
|
|
86
|
+
'Content-Type': isJson ? 'application/json; charset=UTF-8' : 'text/xml; charset=UTF-8',
|
|
87
|
+
Accept: isJson ? 'application/json' : 'text/xml',
|
|
88
|
+
...(this.cookies.size ? { Cookie: [...this.cookies].map(([k, v]) => `${k}=${v}`).join('; ') } : {}),
|
|
89
|
+
},
|
|
90
|
+
body,
|
|
91
|
+
signal: controller.signal,
|
|
92
|
+
redirect: 'manual',
|
|
93
|
+
});
|
|
94
|
+
text = await res.text();
|
|
95
|
+
} catch (e) {
|
|
96
|
+
clearTimeout(timer);
|
|
97
|
+
if (canRetry && attempt < this.config.maxRetries) {
|
|
98
|
+
attempt += 1;
|
|
99
|
+
await sleep(800 * attempt);
|
|
100
|
+
continue;
|
|
101
|
+
}
|
|
102
|
+
const reason = e.name === 'AbortError' ? `请求超时(${this.config.timeoutMs}ms)` : e.message;
|
|
103
|
+
throw new BugzillaError(`访问 Bugzilla 失败:${reason}(${this.endpoint})`);
|
|
104
|
+
}
|
|
105
|
+
clearTimeout(timer);
|
|
106
|
+
this.storeCookies(res);
|
|
107
|
+
|
|
108
|
+
if (canRetry && RETRYABLE_STATUS.has(res.status) && attempt < this.config.maxRetries) {
|
|
109
|
+
attempt += 1;
|
|
110
|
+
await sleep(1000 * 2 ** (attempt - 1));
|
|
111
|
+
continue;
|
|
112
|
+
}
|
|
113
|
+
if (res.status >= 300 && res.status < 400) {
|
|
114
|
+
throw new BugzillaError(`${this.endpoint} 返回重定向(${res.status}):请确认 BUGZILLA_URL 的协议 / 域名与站点实际地址一致`, { status: res.status });
|
|
115
|
+
}
|
|
116
|
+
if (res.status === 404) {
|
|
117
|
+
throw new BugzillaError(`${this.endpoint} 不存在(404):请确认 Bugzilla 根地址,或用 BUGZILLA_RPC_PATH 指定接口路径`, { status: 404 });
|
|
118
|
+
}
|
|
119
|
+
return isJson ? this.parseJson(text, res) : this.parseXml(text, res);
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
parseJson(text, res) {
|
|
124
|
+
let data;
|
|
125
|
+
try {
|
|
126
|
+
data = JSON.parse(text);
|
|
127
|
+
} catch {
|
|
128
|
+
const hint = /<html/i.test(text)
|
|
129
|
+
? '返回的是 HTML 页面,服务器可能未安装 JSON-RPC 依赖(JSON::RPC 模块),可改用 BUGZILLA_PROTOCOL=xmlrpc'
|
|
130
|
+
: `无法解析响应:${text.slice(0, 120)}`;
|
|
131
|
+
throw new BugzillaError(`JSON-RPC 调用失败(HTTP ${res.status}):${hint}`, { status: res.status });
|
|
132
|
+
}
|
|
133
|
+
if (data?.error) throw toError(data.error.code, data.error.message, res.status);
|
|
134
|
+
return data?.result ?? null;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
parseXml(text, res) {
|
|
138
|
+
try {
|
|
139
|
+
return decodeResponse(text);
|
|
140
|
+
} catch (e) {
|
|
141
|
+
if (e instanceof XmlRpcFault) throw toError(e.code, e.message, res.status);
|
|
142
|
+
throw new BugzillaError(`XML-RPC 调用失败(HTTP ${res.status}):${e.message}`, { status: res.status });
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
storeCookies(res) {
|
|
147
|
+
const list = typeof res.headers?.getSetCookie === 'function' ? res.headers.getSetCookie() : splitSetCookie(res.headers?.get?.('set-cookie'));
|
|
148
|
+
for (const raw of list) {
|
|
149
|
+
const [pair, ...attrs] = raw.split(';');
|
|
150
|
+
const idx = pair.indexOf('=');
|
|
151
|
+
if (idx <= 0) continue;
|
|
152
|
+
const name = pair.slice(0, idx).trim();
|
|
153
|
+
const value = pair.slice(idx + 1).trim();
|
|
154
|
+
const expired = attrs.some((a) => /^\s*max-age=0/i.test(a)) || !value || value === 'X';
|
|
155
|
+
if (expired) this.cookies.delete(name);
|
|
156
|
+
else this.cookies.set(name, value);
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/** User.login:凭证在 POST 请求体中,不出现在 URL;成功后保存 Cookie(以及新版本返回的 token) */
|
|
161
|
+
async login() {
|
|
162
|
+
if (this.loginPromise) return this.loginPromise;
|
|
163
|
+
this.loginPromise = (async () => {
|
|
164
|
+
const r = await this.call('User.login', { login: this.config.login, password: this.config.password, remember: true }, { skipAuth: true });
|
|
165
|
+
this.userId = r?.id;
|
|
166
|
+
this.token = r?.token;
|
|
167
|
+
this.loggedIn = true;
|
|
168
|
+
if (!this.cookies.size && !this.token) {
|
|
169
|
+
throw new BugzillaError('登录成功但服务器未返回会话 Cookie,可能被反向代理过滤了 Set-Cookie。可改用 BUGZILLA_AUTH_TYPE=params');
|
|
170
|
+
}
|
|
171
|
+
return r;
|
|
172
|
+
})();
|
|
173
|
+
try {
|
|
174
|
+
return await this.loginPromise;
|
|
175
|
+
} finally {
|
|
176
|
+
this.loginPromise = null;
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
// ---------- 封装 ----------
|
|
181
|
+
|
|
182
|
+
version() {
|
|
183
|
+
return this.call('Bugzilla.version', {}, { skipAuth: this.config.authType === 'none' });
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
extensions() {
|
|
187
|
+
return this.call('Bugzilla.extensions');
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
async whoami() {
|
|
191
|
+
if (this.config.authType === 'cookie') {
|
|
192
|
+
if (!this.loggedIn) await this.login();
|
|
193
|
+
const r = await this.call('User.get', { ids: [this.userId] });
|
|
194
|
+
return r?.users?.[0] || { id: this.userId };
|
|
195
|
+
}
|
|
196
|
+
const r = await this.call('User.get', { names: [this.config.login] });
|
|
197
|
+
return r?.users?.[0];
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
getBugs(ids, includeFields) {
|
|
201
|
+
return this.call('Bug.get', { ids: ids.map(toIdParam), include_fields: includeFields, permissive: true });
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
searchBugs(params) {
|
|
205
|
+
return this.call('Bug.search', params);
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
history(ids) {
|
|
209
|
+
return this.call('Bug.history', { ids: ids.map(toIdParam) });
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
comments(ids, newSince) {
|
|
213
|
+
return this.call('Bug.comments', { ids: ids.map(toIdParam), new_since: newSince ? new RpcDateTime(newSince) : undefined });
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
attachments(ids) {
|
|
217
|
+
return this.call('Bug.attachments', { ids: ids.map(toIdParam), exclude_fields: ['data'] });
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
addComment(id, comment, isPrivate) {
|
|
221
|
+
return this.call('Bug.add_comment', { id: toIdParam(id), comment, is_private: isPrivate });
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
update(input) {
|
|
225
|
+
return this.call('Bug.update', input);
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
create(input) {
|
|
229
|
+
return this.call('Bug.create', input);
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
legalValues(field, productId) {
|
|
233
|
+
return this.call('Bug.legal_values', { field, product_id: productId });
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
fields(names) {
|
|
237
|
+
return this.call('Bug.fields', { names });
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
accessibleProducts() {
|
|
241
|
+
return this.call('Product.get_accessible_products');
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
getProducts(ids) {
|
|
245
|
+
return this.call('Product.get', { ids });
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
getUsers(params) {
|
|
249
|
+
return this.call('User.get', params);
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
function toError(code, message, status) {
|
|
254
|
+
const c = typeof code === 'string' && /^\d+$/.test(code) ? Number(code) : code;
|
|
255
|
+
const msg = String(message || '');
|
|
256
|
+
let text;
|
|
257
|
+
if (c === 300) text = `登录失败(300):用户名或密码错误。${msg}`;
|
|
258
|
+
else if (c === 301) text = `账号已被禁用(301):${msg}`;
|
|
259
|
+
else if (c === 410) text = `需要登录(410):请配置 BUGZILLA_LOGIN / BUGZILLA_PASSWORD。${msg}`;
|
|
260
|
+
else if (c === 101 || c === 100) text = `Bug 不存在(${c}):${msg}`;
|
|
261
|
+
else if (c === 102) text = `无权查看该 Bug(102):${msg}`;
|
|
262
|
+
else if (c === 32601 || c === -32601) text = `服务器不支持该方法(${c}),可能是 Bugzilla 版本过旧:${msg}`;
|
|
263
|
+
else text = `Bugzilla 返回错误(code ${c ?? '未知'}):${msg}`;
|
|
264
|
+
return new BugzillaError(text, { status, code: c });
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
function toIdParam(id) {
|
|
268
|
+
const s = String(id).trim();
|
|
269
|
+
return /^\d+$/.test(s) ? Number(s) : s;
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
function stripUndefined(obj) {
|
|
273
|
+
for (const k of Object.keys(obj)) if (obj[k] === undefined) delete obj[k];
|
|
274
|
+
return obj;
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
function splitSetCookie(header) {
|
|
278
|
+
if (!header) return [];
|
|
279
|
+
// 按 "逗号 + 下一个 cookie 名=" 拆分,避开 Expires 中的逗号
|
|
280
|
+
return header.split(/,(?=\s*[\w!#$%&'*+.^`|~-]+=)/);
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
function sleep(ms) {
|
|
284
|
+
return new Promise((r) => setTimeout(r, ms));
|
|
285
|
+
}
|
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
import { RpcDateTime } from './xmlrpc.js';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Bugzilla 4.0 的 Bug.search 只支持简单字段的等值 / 子串匹配和"时间 >=":
|
|
5
|
+
* 不支持 f1/o1/v1 高级条件、quicksearch、取反、时间上限和自定义字段。
|
|
6
|
+
* 因此这里把条件拆成两部分:服务端能做的放进 Bug.search 参数,其余在本地对结果过滤。
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
/** Bug.search 支持的数组字段(数组内为"任一") */
|
|
10
|
+
export const SERVER_LIST_FIELDS = [
|
|
11
|
+
'product', 'component', 'version', 'target_milestone', 'status', 'resolution', 'priority', 'severity',
|
|
12
|
+
'assigned_to', 'creator', 'qa_contact', 'op_sys', 'platform', 'alias',
|
|
13
|
+
];
|
|
14
|
+
/** Bug.search 支持的子串字段 */
|
|
15
|
+
export const SERVER_SUBSTRING_FIELDS = ['summary', 'whiteboard', 'url'];
|
|
16
|
+
|
|
17
|
+
export const DEFAULT_LIST_FIELDS = [
|
|
18
|
+
'id', 'summary', 'status', 'resolution', 'is_open', 'priority', 'severity', 'product', 'component',
|
|
19
|
+
'version', 'target_milestone', 'assigned_to', 'creator', 'creation_time', 'last_change_time', 'keywords', 'whiteboard',
|
|
20
|
+
];
|
|
21
|
+
|
|
22
|
+
const FIELD_NAME_RE = /^[A-Za-z][\w]{0,63}$/;
|
|
23
|
+
const DATE_RE = /^\d{4}-\d{2}-\d{2}(?:[ T]\d{2}:\d{2}(?::\d{2})?)?(?:Z|[+-]\d{2}:?\d{2})?$/;
|
|
24
|
+
|
|
25
|
+
export function assertFieldName(name, label = 'field') {
|
|
26
|
+
if (!FIELD_NAME_RE.test(String(name || ''))) throw new Error(`${label} 字段名非法:${name}`);
|
|
27
|
+
return name;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export function assertBugId(value) {
|
|
31
|
+
const v = String(value ?? '').trim();
|
|
32
|
+
if (!/^\d{1,9}$/.test(v) && !/^[A-Za-z][\w.-]{0,39}$/.test(v)) throw new Error(`Bug ID 非法:${v}`);
|
|
33
|
+
return v;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** 解析时间;不带时区按 UTC(与 Bugzilla WebService 的时间口径一致) */
|
|
37
|
+
export function parseDate(value, label) {
|
|
38
|
+
const v = String(value).trim();
|
|
39
|
+
if (!DATE_RE.test(v)) throw new Error(`${label} 时间格式错误:${v},应为 YYYY-MM-DD 或 YYYY-MM-DDTHH:MM:SSZ`);
|
|
40
|
+
const iso = v.length === 10 ? `${v}T00:00:00Z` : /Z$|[+-]\d{2}:?\d{2}$/.test(v) ? v.replace(' ', 'T') : `${v.replace(' ', 'T')}Z`;
|
|
41
|
+
const d = new Date(iso);
|
|
42
|
+
if (Number.isNaN(d.getTime())) throw new Error(`${label} 不是有效时间:${v}`);
|
|
43
|
+
return d;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function toList(v) {
|
|
47
|
+
if (v === undefined || v === null || v === '') return undefined;
|
|
48
|
+
return (Array.isArray(v) ? v : [v]).map((x) => String(x).trim()).filter(Boolean);
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function upperSet(list) {
|
|
52
|
+
return new Set(list.map((s) => s.toUpperCase()));
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* @returns {{ server: object, filter: (bug) => boolean, filterFields: string[], localConditions: string[] }}
|
|
57
|
+
*/
|
|
58
|
+
export function buildSearch(p = {}, { versionField = 'version' } = {}) {
|
|
59
|
+
const server = {};
|
|
60
|
+
const checks = [];
|
|
61
|
+
const filterFields = new Set();
|
|
62
|
+
const localConditions = [];
|
|
63
|
+
|
|
64
|
+
for (const field of SERVER_LIST_FIELDS) {
|
|
65
|
+
const list = toList(p[field]);
|
|
66
|
+
if (list?.length) server[field] = list;
|
|
67
|
+
}
|
|
68
|
+
for (const field of SERVER_SUBSTRING_FIELDS) {
|
|
69
|
+
if (p[field]) server[field] = String(p[field]);
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
const versions = toList(p.versions);
|
|
73
|
+
if (versions?.length) {
|
|
74
|
+
if (SERVER_LIST_FIELDS.includes(versionField)) {
|
|
75
|
+
server[versionField] = [...new Set([...(server[versionField] || []), ...versions])];
|
|
76
|
+
} else {
|
|
77
|
+
assertFieldName(versionField, 'version_field');
|
|
78
|
+
const set = new Set(versions);
|
|
79
|
+
checks.push((b) => set.has(String(b[versionField] ?? '')));
|
|
80
|
+
filterFields.add(versionField);
|
|
81
|
+
localConditions.push(`${versionField} ∈ [${versions.join(', ')}]`);
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
if (p.created_after) server.creation_time = new RpcDateTime(parseDate(p.created_after, 'created_after'));
|
|
86
|
+
if (p.changed_after) server.last_change_time = new RpcDateTime(parseDate(p.changed_after, 'changed_after'));
|
|
87
|
+
|
|
88
|
+
if (p.created_before) {
|
|
89
|
+
const t = parseDate(p.created_before, 'created_before').getTime();
|
|
90
|
+
checks.push((b) => Date.parse(b.creation_time) < t);
|
|
91
|
+
filterFields.add('creation_time');
|
|
92
|
+
localConditions.push(`creation_time < ${p.created_before}`);
|
|
93
|
+
}
|
|
94
|
+
if (p.changed_before) {
|
|
95
|
+
const t = parseDate(p.changed_before, 'changed_before').getTime();
|
|
96
|
+
checks.push((b) => Date.parse(b.last_change_time) < t);
|
|
97
|
+
filterFields.add('last_change_time');
|
|
98
|
+
localConditions.push(`last_change_time < ${p.changed_before}`);
|
|
99
|
+
}
|
|
100
|
+
if (p.status_scope === 'open' || p.status_scope === 'closed') {
|
|
101
|
+
const want = p.status_scope === 'open';
|
|
102
|
+
checks.push((b) => Boolean(b.is_open) === want);
|
|
103
|
+
filterFields.add('is_open');
|
|
104
|
+
localConditions.push(`is_open = ${want}`);
|
|
105
|
+
}
|
|
106
|
+
const excluded = toList(p.exclude_resolutions);
|
|
107
|
+
if (excluded?.length) {
|
|
108
|
+
const set = upperSet(excluded);
|
|
109
|
+
checks.push((b) => !set.has(String(b.resolution || '').toUpperCase()));
|
|
110
|
+
filterFields.add('resolution');
|
|
111
|
+
localConditions.push(`resolution ∉ [${excluded.join(', ')}]`);
|
|
112
|
+
}
|
|
113
|
+
const keywords = toList(p.keywords);
|
|
114
|
+
if (keywords?.length) {
|
|
115
|
+
const set = upperSet(keywords);
|
|
116
|
+
checks.push((b) => (b.keywords || []).some((k) => set.has(String(k).toUpperCase())));
|
|
117
|
+
filterFields.add('keywords');
|
|
118
|
+
localConditions.push(`keywords 含任一 [${keywords.join(', ')}]`);
|
|
119
|
+
}
|
|
120
|
+
for (const [field, value] of Object.entries(p.custom_fields || {})) {
|
|
121
|
+
assertFieldName(field, 'custom_fields');
|
|
122
|
+
const list = toList(value);
|
|
123
|
+
if (!list?.length) continue;
|
|
124
|
+
const set = new Set(list);
|
|
125
|
+
checks.push((b) => {
|
|
126
|
+
const v = b[field];
|
|
127
|
+
return Array.isArray(v) ? v.some((x) => set.has(String(x))) : set.has(String(v ?? ''));
|
|
128
|
+
});
|
|
129
|
+
filterFields.add(field);
|
|
130
|
+
localConditions.push(`${field} ∈ [${list.join(', ')}]`);
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
return {
|
|
134
|
+
server,
|
|
135
|
+
filter: (b) => checks.every((fn) => fn(b)),
|
|
136
|
+
filterFields: [...filterFields],
|
|
137
|
+
localConditions,
|
|
138
|
+
};
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
export function hasServerFilter(server) {
|
|
142
|
+
return Object.keys(server).length > 0;
|
|
143
|
+
}
|
package/src/lib/util.js
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
/** 限制并发地对数组执行异步映射,保持结果顺序 */
|
|
2
|
+
export async function mapLimit(items, limit, fn) {
|
|
3
|
+
const results = new Array(items.length);
|
|
4
|
+
let next = 0;
|
|
5
|
+
const workers = Array.from({ length: Math.min(limit, items.length) }, async () => {
|
|
6
|
+
while (next < items.length) {
|
|
7
|
+
const index = next;
|
|
8
|
+
next += 1;
|
|
9
|
+
results[index] = await fn(items[index], index);
|
|
10
|
+
}
|
|
11
|
+
});
|
|
12
|
+
await Promise.all(workers);
|
|
13
|
+
return results;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* 极简 JSON Schema 校验(覆盖本项目用到的子集:type / required / enum / minimum / maximum /
|
|
18
|
+
* minLength / maxLength / maxItems / items / properties / additionalProperties)。
|
|
19
|
+
* 在 MCP 入口处做参数校验,作为信任边界。
|
|
20
|
+
*/
|
|
21
|
+
export function validateArgs(schema, value, path = 'arguments') {
|
|
22
|
+
const errors = [];
|
|
23
|
+
check(schema, value, path, errors);
|
|
24
|
+
if (errors.length) throw new Error(`参数校验失败:${errors.join(';')}`);
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
function check(schema, value, path, errors) {
|
|
28
|
+
if (!schema) return;
|
|
29
|
+
if (value === undefined) return;
|
|
30
|
+
|
|
31
|
+
const types = Array.isArray(schema.type) ? schema.type : schema.type ? [schema.type] : [];
|
|
32
|
+
if (types.length && !types.some((t) => matchesType(t, value))) {
|
|
33
|
+
errors.push(`${path} 类型应为 ${types.join('|')}`);
|
|
34
|
+
return;
|
|
35
|
+
}
|
|
36
|
+
if (schema.enum && !schema.enum.includes(value)) {
|
|
37
|
+
errors.push(`${path} 取值应为 ${schema.enum.join(' / ')} 之一`);
|
|
38
|
+
}
|
|
39
|
+
if (typeof value === 'number') {
|
|
40
|
+
if (schema.minimum !== undefined && value < schema.minimum) errors.push(`${path} 不能小于 ${schema.minimum}`);
|
|
41
|
+
if (schema.maximum !== undefined && value > schema.maximum) errors.push(`${path} 不能大于 ${schema.maximum}`);
|
|
42
|
+
}
|
|
43
|
+
if (typeof value === 'string') {
|
|
44
|
+
if (schema.minLength !== undefined && value.length < schema.minLength) errors.push(`${path} 长度不能小于 ${schema.minLength}`);
|
|
45
|
+
if (schema.maxLength !== undefined && value.length > schema.maxLength) errors.push(`${path} 长度不能超过 ${schema.maxLength}`);
|
|
46
|
+
}
|
|
47
|
+
if (Array.isArray(value)) {
|
|
48
|
+
if (schema.maxItems !== undefined && value.length > schema.maxItems) errors.push(`${path} 最多 ${schema.maxItems} 项`);
|
|
49
|
+
if (schema.minItems !== undefined && value.length < schema.minItems) errors.push(`${path} 至少 ${schema.minItems} 项`);
|
|
50
|
+
value.forEach((item, i) => check(schema.items, item, `${path}[${i}]`, errors));
|
|
51
|
+
}
|
|
52
|
+
if (value && typeof value === 'object' && !Array.isArray(value)) {
|
|
53
|
+
for (const key of schema.required || []) {
|
|
54
|
+
if (value[key] === undefined || value[key] === null || value[key] === '') errors.push(`缺少必填参数 ${path}.${key}`);
|
|
55
|
+
}
|
|
56
|
+
const props = schema.properties || {};
|
|
57
|
+
for (const [key, v] of Object.entries(value)) {
|
|
58
|
+
if (props[key]) check(props[key], v, `${path}.${key}`, errors);
|
|
59
|
+
else if (schema.additionalProperties === false) errors.push(`未知参数 ${path}.${key}`);
|
|
60
|
+
else if (typeof schema.additionalProperties === 'object') check(schema.additionalProperties, v, `${path}.${key}`, errors);
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function matchesType(type, value) {
|
|
66
|
+
switch (type) {
|
|
67
|
+
case 'string':
|
|
68
|
+
return typeof value === 'string';
|
|
69
|
+
case 'integer':
|
|
70
|
+
return Number.isInteger(value);
|
|
71
|
+
case 'number':
|
|
72
|
+
return typeof value === 'number' && Number.isFinite(value);
|
|
73
|
+
case 'boolean':
|
|
74
|
+
return typeof value === 'boolean';
|
|
75
|
+
case 'array':
|
|
76
|
+
return Array.isArray(value);
|
|
77
|
+
case 'object':
|
|
78
|
+
return value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
79
|
+
case 'null':
|
|
80
|
+
return value === null;
|
|
81
|
+
default:
|
|
82
|
+
return true;
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
export function round(n, digits = 3) {
|
|
87
|
+
const f = 10 ** digits;
|
|
88
|
+
return Math.round(n * f) / f;
|
|
89
|
+
}
|
|
90
|
+
|