@brain-toolkit/issue-forge 0.1.0 → 0.1.1

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.
@@ -1,471 +0,0 @@
1
- // src/errors/IssueForgeError.ts
2
- var IssueForgeError = class extends Error {
3
- code = "ISSUE_FORGE_FAILED";
4
- /** HTTP 状态码;网络错误等无响应时为 null */
5
- status;
6
- constructor(message, status) {
7
- super(message);
8
- this.name = "IssueForgeError";
9
- this.status = status;
10
- }
11
- };
12
-
13
- // src/github/GithubAppClient.ts
14
- import jwt from "jsonwebtoken";
15
- var GITHUB_API = "https://api.github.com";
16
- var GITHUB_API_VERSION = "2022-11-28";
17
- var DEFAULT_USER_AGENT = "brain-toolkit-issue-forge";
18
- var REQUEST_TIMEOUT_MS = 6e4;
19
- var APP_JWT_TTL_SEC = 9 * 60;
20
- var APP_JWT_CLOCK_SKEW_SEC = 60;
21
- var TOKEN_REFRESH_MARGIN_MS = 2 * 60 * 1e3;
22
- var GithubAppClient = class {
23
- cache;
24
- userAgent;
25
- constructor(options) {
26
- this.cache = options.cache;
27
- this.userAgent = options.userAgent?.trim() || DEFAULT_USER_AGENT;
28
- }
29
- async request(config, path, init) {
30
- const token = await this.getInstallationToken(config);
31
- const headers = this.headers(`Bearer ${token}`);
32
- if (init.accept) {
33
- headers.Accept = init.accept;
34
- }
35
- if (init.body !== void 0) {
36
- headers["Content-Type"] = "application/json";
37
- }
38
- const response = await this.send(`${GITHUB_API}${path}`, {
39
- method: init.method,
40
- headers,
41
- ...init.body !== void 0 ? { body: JSON.stringify(init.body) } : {}
42
- });
43
- if (response.status === 401 || response.status === 403) {
44
- await this.cache.removeItem(this.tokenCacheKey(config));
45
- }
46
- return response;
47
- }
48
- async toError(stage, response) {
49
- let detail = "";
50
- try {
51
- const json = await response.json();
52
- detail = typeof json.message === "string" ? json.message : "";
53
- } catch {
54
- detail = "";
55
- }
56
- return new IssueForgeError(
57
- `${stage}: HTTP ${String(response.status)}${detail ? ` ${detail}` : ""}`,
58
- response.status
59
- );
60
- }
61
- async getInstallationToken(config) {
62
- const cacheKey = this.tokenCacheKey(config);
63
- const cached = await this.cache.getItem(cacheKey);
64
- if (cached?.token) {
65
- return cached.token;
66
- }
67
- const response = await this.send(
68
- `${GITHUB_API}/app/installations/${encodeURIComponent(config.installationId)}/access_tokens`,
69
- {
70
- method: "POST",
71
- headers: this.headers(`Bearer ${this.signAppJwt(config)}`)
72
- }
73
- );
74
- if (!response.ok) {
75
- throw await this.toError("installation token", response);
76
- }
77
- const json = await response.json();
78
- if (typeof json.token !== "string" || !json.token) {
79
- throw new IssueForgeError(
80
- "installation token: empty token",
81
- response.status
82
- );
83
- }
84
- const expiresAtMs = typeof json.expires_at === "string" ? Date.parse(json.expires_at) : Number.NaN;
85
- const ttlMs = Number.isFinite(expiresAtMs) ? expiresAtMs - Date.now() - TOKEN_REFRESH_MARGIN_MS : 0;
86
- if (ttlMs > 0) {
87
- await this.cache.setItem(
88
- cacheKey,
89
- { token: json.token },
90
- { ttlMs }
91
- );
92
- }
93
- return json.token;
94
- }
95
- signAppJwt(config) {
96
- const nowSec = Math.floor(Date.now() / 1e3);
97
- try {
98
- return jwt.sign(
99
- {
100
- iat: nowSec - APP_JWT_CLOCK_SKEW_SEC,
101
- exp: nowSec + APP_JWT_TTL_SEC,
102
- iss: config.appId
103
- },
104
- this.normalizePrivateKey(config.privateKey),
105
- { algorithm: "RS256" }
106
- );
107
- } catch (error) {
108
- throw new IssueForgeError(
109
- `invalid GitHub App private key: ${error instanceof Error ? error.message : String(error)}`,
110
- null
111
- );
112
- }
113
- }
114
- normalizePrivateKey(raw) {
115
- return raw.replace(/\\n/g, "\n").replace(/\r\n/g, "\n").trim();
116
- }
117
- async send(url, init) {
118
- try {
119
- return await fetch(url, {
120
- ...init,
121
- signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)
122
- });
123
- } catch (error) {
124
- throw new IssueForgeError(
125
- `GitHub request failed: ${error instanceof Error ? error.message : String(error)}`,
126
- null
127
- );
128
- }
129
- }
130
- headers(authorization) {
131
- return {
132
- Accept: "application/vnd.github+json",
133
- Authorization: authorization,
134
- "User-Agent": this.userAgent,
135
- "X-GitHub-Api-Version": GITHUB_API_VERSION
136
- };
137
- }
138
- tokenCacheKey(config) {
139
- return `issue-forge:github:installation-token:${config.appId}:${config.installationId}`;
140
- }
141
- };
142
-
143
- // src/github/GithubAppRepoContentGateway.ts
144
- var ACCEPT_RAW = "application/vnd.github.raw+json";
145
- var GithubAppRepoContentGateway = class {
146
- constructor(client, config) {
147
- this.client = client;
148
- this.config = config;
149
- }
150
- /**
151
- * @override
152
- */
153
- async readTextFile(path) {
154
- const response = await this.client.request(
155
- this.config,
156
- this.contentsPath(path),
157
- { method: "GET", accept: ACCEPT_RAW }
158
- );
159
- if (response.status === 404) {
160
- return null;
161
- }
162
- if (!response.ok) {
163
- throw await this.client.toError("read file", response);
164
- }
165
- return response.text();
166
- }
167
- /**
168
- * @override
169
- */
170
- async hasFile(path, branch) {
171
- const response = await this.client.request(
172
- this.config,
173
- `${this.contentsPath(path)}?ref=${encodeURIComponent(branch)}`,
174
- { method: "GET" }
175
- );
176
- if (response.status === 404) {
177
- return false;
178
- }
179
- if (!response.ok) {
180
- throw await this.client.toError("has file", response);
181
- }
182
- return true;
183
- }
184
- /**
185
- * @override
186
- */
187
- async ensureBranch(branch, initialFile) {
188
- const found = await this.client.request(
189
- this.config,
190
- `${this.repoPath()}/git/ref/heads/${this.encodePath(branch)}`,
191
- { method: "GET" }
192
- );
193
- if (found.ok) {
194
- return;
195
- }
196
- if (found.status !== 404) {
197
- throw await this.client.toError("get branch", found);
198
- }
199
- const treeSha = await this.postForSha("create tree", "/git/trees", {
200
- tree: [
201
- {
202
- path: initialFile.path,
203
- mode: "100644",
204
- type: "blob",
205
- content: initialFile.content
206
- }
207
- ]
208
- });
209
- const commitSha = await this.postForSha("create commit", "/git/commits", {
210
- message: `chore: \u521D\u59CB\u5316 ${branch} \u5206\u652F`,
211
- tree: treeSha,
212
- parents: []
213
- });
214
- const created = await this.client.request(
215
- this.config,
216
- `${this.repoPath()}/git/refs`,
217
- {
218
- method: "POST",
219
- body: { ref: `refs/heads/${branch}`, sha: commitSha }
220
- }
221
- );
222
- if (!created.ok && created.status !== 422) {
223
- throw await this.client.toError("create branch", created);
224
- }
225
- }
226
- /**
227
- * @override
228
- */
229
- async uploadFile(input) {
230
- const response = await this.client.request(
231
- this.config,
232
- this.contentsPath(input.path),
233
- {
234
- method: "PUT",
235
- body: {
236
- message: input.message,
237
- content: input.contentBase64,
238
- branch: input.branch
239
- }
240
- }
241
- );
242
- if (response.ok) {
243
- const json = await response.json();
244
- return { url: this.requireHtmlUrl(json.content?.html_url, response) };
245
- }
246
- if (response.status === 422) {
247
- return this.readExisting(input);
248
- }
249
- throw await this.client.toError("upload file", response);
250
- }
251
- async readExisting(input) {
252
- const response = await this.client.request(
253
- this.config,
254
- `${this.contentsPath(input.path)}?ref=${encodeURIComponent(input.branch)}`,
255
- { method: "GET" }
256
- );
257
- if (!response.ok) {
258
- throw await this.client.toError("upload file", response);
259
- }
260
- const json = await response.json();
261
- return { url: this.requireHtmlUrl(json.html_url, response) };
262
- }
263
- async postForSha(stage, path, body) {
264
- const response = await this.client.request(
265
- this.config,
266
- `${this.repoPath()}${path}`,
267
- { method: "POST", body }
268
- );
269
- if (!response.ok) {
270
- throw await this.client.toError(stage, response);
271
- }
272
- const json = await response.json();
273
- if (typeof json.sha !== "string" || !json.sha) {
274
- throw new IssueForgeError(
275
- `${stage}: unexpected response`,
276
- response.status
277
- );
278
- }
279
- return json.sha;
280
- }
281
- requireHtmlUrl(value, response) {
282
- if (typeof value !== "string" || !value) {
283
- throw new IssueForgeError(
284
- "upload file: unexpected response",
285
- response.status
286
- );
287
- }
288
- return value;
289
- }
290
- contentsPath(path) {
291
- return `${this.repoPath()}/contents/${this.encodePath(path)}`;
292
- }
293
- encodePath(path) {
294
- return path.split("/").filter((segment) => segment.length > 0).map((segment) => encodeURIComponent(segment)).join("/");
295
- }
296
- repoPath() {
297
- return `/repos/${encodeURIComponent(this.config.owner)}/${encodeURIComponent(this.config.repo)}`;
298
- }
299
- };
300
-
301
- // src/github/GithubAppIssueForgeGateway.ts
302
- var COMMENTS_PAGE_SIZE = 100;
303
- var GithubAppIssueForgeGateway = class {
304
- constructor(client, config) {
305
- this.client = client;
306
- this.config = config;
307
- this.assets = new GithubAppRepoContentGateway(client, config);
308
- }
309
- assets;
310
- /**
311
- * @override
312
- */
313
- async createIssue(input) {
314
- const first = await this.postIssue(input, input.labels);
315
- if (first.ok) {
316
- return this.readCreated(first);
317
- }
318
- if (first.status === 422 && input.labels.length > 0) {
319
- const retry = await this.postIssue(input, []);
320
- if (retry.ok) {
321
- return this.readCreated(retry);
322
- }
323
- throw await this.client.toError("create issue", retry);
324
- }
325
- throw await this.client.toError("create issue", first);
326
- }
327
- /**
328
- * @override
329
- */
330
- async createComment(issue, body) {
331
- const response = await this.client.request(
332
- this.config,
333
- `${this.repoPath()}/issues/${String(issue.issueNumber)}/comments`,
334
- { method: "POST", body: { body } }
335
- );
336
- if (!response.ok) {
337
- throw await this.client.toError("create comment", response);
338
- }
339
- }
340
- /**
341
- * @override
342
- */
343
- async listComments(issue) {
344
- const comments = [];
345
- let page = 1;
346
- for (; ; ) {
347
- const response = await this.client.request(
348
- this.config,
349
- `${this.repoPath()}/issues/${String(issue.issueNumber)}/comments?per_page=${String(COMMENTS_PAGE_SIZE)}&page=${String(page)}`,
350
- { method: "GET" }
351
- );
352
- if (!response.ok) {
353
- throw await this.client.toError("list comments", response);
354
- }
355
- const json = await response.json();
356
- for (const item of json) {
357
- if (typeof item.body === "string") {
358
- comments.push({ body: item.body });
359
- }
360
- }
361
- if (json.length < COMMENTS_PAGE_SIZE) {
362
- break;
363
- }
364
- page += 1;
365
- }
366
- return comments;
367
- }
368
- /**
369
- * @override
370
- */
371
- async uploadAsset(input) {
372
- const branch = input.branch?.trim() || "feedback-assets";
373
- await this.assets.uploadFile({
374
- path: input.path,
375
- contentBase64: input.contentBase64,
376
- branch,
377
- message: input.message?.trim() || `chore(feedback): upload ${input.path}`
378
- });
379
- const encodedPath = input.path.split("/").filter((segment) => segment.length > 0).map((segment) => encodeURIComponent(segment)).join("/");
380
- return {
381
- url: `https://github.com/${encodeURIComponent(this.config.owner)}/${encodeURIComponent(this.config.repo)}/raw/${encodeURIComponent(branch)}/${encodedPath}`
382
- };
383
- }
384
- postIssue(input, labels) {
385
- return this.client.request(this.config, `${this.repoPath()}/issues`, {
386
- method: "POST",
387
- body: {
388
- title: input.title,
389
- body: input.body,
390
- ...labels.length > 0 ? { labels: [...labels] } : {}
391
- }
392
- });
393
- }
394
- async readCreated(response) {
395
- const json = await response.json();
396
- if (typeof json.number !== "number" || typeof json.html_url !== "string") {
397
- throw new IssueForgeError(
398
- "create issue: unexpected response",
399
- response.status
400
- );
401
- }
402
- return {
403
- issueNumber: json.number,
404
- issueUrl: json.html_url,
405
- ...typeof json.node_id === "string" ? { resourceKey: json.node_id } : {}
406
- };
407
- }
408
- repoPath() {
409
- return `/repos/${encodeURIComponent(this.config.owner)}/${encodeURIComponent(this.config.repo)}`;
410
- }
411
- };
412
-
413
- // src/github/GithubWebhookVerifier.ts
414
- import { createHmac, timingSafeEqual } from "crypto";
415
- var SIGNATURE_PREFIX = "sha256=";
416
- var GithubWebhookVerifier = class {
417
- constructor(secret) {
418
- this.secret = secret;
419
- }
420
- /**
421
- * @override
422
- */
423
- async verify(rawBody, signatureHeader) {
424
- if (signatureHeader == null || signatureHeader.trim() === "") {
425
- return { ok: false, reason: "signature_header_missing" };
426
- }
427
- if (!signatureHeader.startsWith(SIGNATURE_PREFIX)) {
428
- return { ok: false, reason: "signature_header_invalid" };
429
- }
430
- const secret = this.secret.trim();
431
- if (!secret) {
432
- return { ok: false, reason: "secret_not_configured" };
433
- }
434
- const expected = Buffer.from(
435
- SIGNATURE_PREFIX + createHmac("sha256", secret).update(rawBody, "utf8").digest("hex"),
436
- "utf8"
437
- );
438
- const received = Buffer.from(signatureHeader, "utf8");
439
- if (expected.length !== received.length || !timingSafeEqual(expected, received)) {
440
- return { ok: false, reason: "digest_mismatch" };
441
- }
442
- return { ok: true };
443
- }
444
- };
445
-
446
- // src/github/createGithubAppForge.ts
447
- function createGithubAppClient(options) {
448
- return new GithubAppClient(options);
449
- }
450
- function createGithubAppIssueForge(client, config) {
451
- return new GithubAppIssueForgeGateway(client, config);
452
- }
453
- function createGithubAppRepoContent(client, config) {
454
- return new GithubAppRepoContentGateway(client, config);
455
- }
456
- function createGithubWebhookVerifier(secret) {
457
- return new GithubWebhookVerifier(secret);
458
- }
459
-
460
- export {
461
- IssueForgeError,
462
- GithubAppClient,
463
- GithubAppRepoContentGateway,
464
- GithubAppIssueForgeGateway,
465
- GithubWebhookVerifier,
466
- createGithubAppClient,
467
- createGithubAppIssueForge,
468
- createGithubAppRepoContent,
469
- createGithubWebhookVerifier
470
- };
471
- //# sourceMappingURL=chunk-RQKDVDLH.js.map