@jmanuelcorral/bond-app 0.1.5 → 0.2.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/README.md +280 -23
- package/app/brand/TOKENS.md +5 -5
- package/app/layouts/bond.json +10 -14
- package/app/mods/bond-agents/api.js +35 -0
- package/app/mods/bond-agents/branch.svg +1 -0
- package/app/mods/bond-agents/brand.js +53 -2
- package/app/mods/bond-agents/config.js +4 -0
- package/app/mods/bond-agents/eye-off.svg +1 -0
- package/app/mods/bond-agents/eye.svg +1 -0
- package/app/mods/bond-agents/main.js +308 -327
- package/app/mods/bond-agents/model.js +376 -5
- package/app/mods/bond-board/api.js +35 -0
- package/app/mods/bond-board/branch.svg +1 -0
- package/app/mods/bond-board/brand.js +53 -2
- package/app/mods/bond-board/config.js +4 -0
- package/app/mods/bond-board/main.js +1000 -449
- package/app/mods/bond-board/model.js +170 -28
- package/app/mods/bond-pane/close.svg +1 -0
- package/app/mods/bond-pane/hide.svg +1 -0
- package/app/mods/bond-pane/main.js +103 -0
- package/app/mods/bond-pane/mod.json +1 -0
- package/app/mods/bond-pane/model.js +18 -0
- package/app/mods/bond-pane/split-down.svg +1 -0
- package/app/mods/bond-pane/split-right.svg +1 -0
- package/app/mods/bond-pane/unzoom.svg +1 -0
- package/app/mods/bond-pane/zoom.svg +1 -0
- package/app/mods/bond-settings/api.js +35 -0
- package/app/mods/bond-settings/brand.js +53 -2
- package/app/mods/bond-settings/config.js +4 -0
- package/app/mods/bond-settings/main.js +1216 -272
- package/app/mods/bond-settings/mod.json +1 -1
- package/app/mods/bond-status/api.js +35 -0
- package/app/mods/bond-status/brand.js +53 -2
- package/app/mods/bond-status/config.js +4 -0
- package/app/mods/bond-status/main.js +37 -15
- package/app/mods/bond-status/model.js +19 -1
- package/app/mods/bond-tabs/brand.js +53 -2
- package/app/mods/bond-tabs/main.js +45 -3
- package/app/mods/bond-titlebar/brand.js +53 -2
- package/app/mods/bond-titlebar/main.js +85 -29
- package/app/mods/bond-titlebar/version.js +3 -0
- package/app/themes/bond-dark.json +5 -5
- package/app/themes/bond-light.json +5 -5
- package/package.json +1 -1
- package/runner/Dockerfile +16 -2
- package/runner/SPIKE-BOND.md +6 -2
- package/runner/entrypoint.sh +16 -0
- package/runner/setup.sh +439 -8
- package/runner/versions.env +32 -1
- package/scripts/app-install.ts +322 -27
- package/src/cli.ts +562 -21
- package/src/config.ts +15 -3
- package/src/core/agy-login.ts +683 -0
- package/src/core/delivery.ts +125 -6
- package/src/core/doctor.ts +748 -0
- package/src/core/hub-session.ts +108 -91
- package/src/core/hub.ts +40 -8
- package/src/core/orchestrator.ts +1481 -187
- package/src/core/paths.ts +107 -0
- package/src/core/permissions.ts +143 -0
- package/src/core/pr-source.ts +147 -0
- package/src/core/repo-host.ts +60 -0
- package/src/core/service-windows.ts +180 -0
- package/src/core/service.ts +861 -0
- package/src/core/setup-install.ts +1380 -0
- package/src/core/setup.ts +62 -1
- package/src/core/watchdog.ts +6 -6
- package/src/db/database.ts +54 -7
- package/src/db/settings-repo.ts +332 -7
- package/src/db/ticket-repo.ts +73 -25
- package/src/index.ts +4 -4
- package/src/runner/azure-devops-client.ts +273 -0
- package/src/runner/docker-client.ts +93 -9
- package/src/runner/github-client.ts +148 -3
- package/src/runner/hc-client.ts +33 -5
- package/src/runner/image-builder.ts +123 -5
- package/src/runner/jira-client.ts +368 -0
- package/src/runner/tool-catalog.ts +84 -0
- package/src/server/app.ts +467 -8
- package/src/types.ts +140 -2
package/src/db/ticket-repo.ts
CHANGED
|
@@ -1,9 +1,12 @@
|
|
|
1
1
|
import type { DatabaseSync } from 'node:sqlite';
|
|
2
2
|
import { randomUUID } from 'node:crypto';
|
|
3
3
|
import { REPO_NAME_RE } from '../core/hub.ts';
|
|
4
|
+
import { azureRepoUrl, parseAzureRepoUrl } from '../core/repo-host.ts';
|
|
5
|
+
import { parseSourceUrl, prTicketId } from '../core/pr-source.ts';
|
|
4
6
|
import {
|
|
5
7
|
validateGitHubUrl,
|
|
6
8
|
isValidAgent,
|
|
9
|
+
SUPPORTED_AGENTS,
|
|
7
10
|
validateBranchName,
|
|
8
11
|
validateVerifyCommands,
|
|
9
12
|
type Ticket,
|
|
@@ -42,10 +45,20 @@ export function repoKey(url: string): string {
|
|
|
42
45
|
export function issueTicketId(issueUrl?: string | null): string | null {
|
|
43
46
|
const url = String(issueUrl ?? '').trim();
|
|
44
47
|
const m = /^https:\/\/github\.com\/([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+)\/issues\/([1-9][0-9]*)(?:[#?].*)?$/.exec(url);
|
|
45
|
-
if (
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
48
|
+
if (m) {
|
|
49
|
+
const slug = (s: string) => s.replace(/[^A-Za-z0-9_.-]/g, '-').replace(/^[-.]+|[-.]+$/g, '');
|
|
50
|
+
const id = `gh-${slug(m[1])}-${slug(m[2])}-${m[3]}`.replace(/\.{2,}/g, '-');
|
|
51
|
+
return id.length <= 80 ? id : null;
|
|
52
|
+
}
|
|
53
|
+
const j = /^https:\/\/([a-zA-Z0-9_-]+)\.atlassian\.net\/browse\/([a-zA-Z0-9_-]+)(?:[#?].*)?$/.exec(url);
|
|
54
|
+
if (j) {
|
|
55
|
+
const slug = (s: string) => s.replace(/[^A-Za-z0-9_.-]/g, '-').replace(/^[-.]+|[-.]+$/g, '');
|
|
56
|
+
// The tenant is part of the id: two sites can share project keys (CORE-1 on two
|
|
57
|
+
// sites are different issues).
|
|
58
|
+
const id = `jira-${slug(j[1].toLowerCase())}-${slug(j[2].toLowerCase())}`.replace(/\.{2,}/g, '-');
|
|
59
|
+
return id.length <= 80 ? id : null;
|
|
60
|
+
}
|
|
61
|
+
return null;
|
|
49
62
|
}
|
|
50
63
|
|
|
51
64
|
/**
|
|
@@ -70,9 +83,11 @@ export function normalizeLayout(rawInput: LayoutInput): TicketLayout {
|
|
|
70
83
|
if (input.repos !== undefined && !hasRepos) throw new Error("Field 'repos' must be an array");
|
|
71
84
|
|
|
72
85
|
if (hasHub) {
|
|
73
|
-
const
|
|
74
|
-
|
|
75
|
-
|
|
86
|
+
const rawHubUrl = String(input.hub_url).trim();
|
|
87
|
+
const azure = parseAzureRepoUrl(rawHubUrl);
|
|
88
|
+
const hubUrl = azure ? azureRepoUrl(azure) : rawHubUrl;
|
|
89
|
+
if (!validateGitHubUrl(hubUrl) && !azure) {
|
|
90
|
+
throw new Error(`Invalid hub_url '${hubUrl}'. Only https://github.com/<owner>/<repo>[.git] or https://dev.azure.com/<org>/<project>/_git/<repo> URLs are allowed.`);
|
|
76
91
|
}
|
|
77
92
|
const hubBase = input.hub_base || 'main';
|
|
78
93
|
if (!validateBranchName(hubBase)) throw new Error(`Invalid hub_base '${hubBase}'`);
|
|
@@ -107,9 +122,13 @@ export function normalizeLayout(rawInput: LayoutInput): TicketLayout {
|
|
|
107
122
|
return { repo_url: repos[0].url, base_branch: repos[0].base_branch, hub_url: null, hub_base: null, repos };
|
|
108
123
|
}
|
|
109
124
|
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
125
|
+
// Plan bond-app-azure-jira P1: a single-repo ticket may live on GitHub or Azure Repos
|
|
126
|
+
// (kept in its canonical dev.azure.com form). Hubs and repo lists stay GitHub only.
|
|
127
|
+
const rawRepoUrl = String(input.repo_url).trim();
|
|
128
|
+
const azure = parseAzureRepoUrl(rawRepoUrl);
|
|
129
|
+
const repoUrl = azure ? azureRepoUrl(azure) : rawRepoUrl;
|
|
130
|
+
if (!validateGitHubUrl(repoUrl) && !azure) {
|
|
131
|
+
throw new Error(`Invalid repo_url '${repoUrl}'. Only https://github.com/<owner>/<repo>[.git] or https://dev.azure.com/<org>/<project>/_git/<repo> URLs are allowed.`);
|
|
113
132
|
}
|
|
114
133
|
const base = input.base_branch || 'main';
|
|
115
134
|
if (!validateBranchName(base)) throw new Error(`Invalid base_branch '${base}'`);
|
|
@@ -174,9 +193,20 @@ export class TicketRepository {
|
|
|
174
193
|
|
|
175
194
|
// D1: the linked issue decides the id unless one is given explicitly; the same issue
|
|
176
195
|
// cannot back two tickets.
|
|
177
|
-
|
|
196
|
+
// Plan bond-app-ticket-desde-pr (D3): a PR names the ticket the same way, and a PR
|
|
197
|
+
// backs one ticket only (the id, and the stored URL for a caller-given id).
|
|
198
|
+
const sourceUrl = input.source_pr_url ? String(input.source_pr_url).trim() : null;
|
|
199
|
+
const source = sourceUrl ? parseSourceUrl(sourceUrl) : null;
|
|
200
|
+
if (sourceUrl && !source) throw new Error(`Invalid source_pr_url '${sourceUrl}': a GitHub or Azure Repos PR or branch URL`);
|
|
201
|
+
if (source && !input.target_branch) throw new Error("A ticket from a PR or branch needs its 'target_branch'");
|
|
202
|
+
if (source?.kind === 'pr' && this.db.prepare('SELECT id FROM tickets WHERE source_pr_url = ?').get(sourceUrl)) {
|
|
203
|
+
throw new Error(`There is already a ticket for this pull request: ${sourceUrl}`);
|
|
204
|
+
}
|
|
205
|
+
const derivedId = input.id ? null : issueTicketId(input.issue_url) ?? prTicketId(source);
|
|
178
206
|
if (derivedId && this.db.prepare('SELECT 1 FROM tickets WHERE id = ?').get(derivedId)) {
|
|
179
|
-
throw new Error(
|
|
207
|
+
throw new Error(source && !issueTicketId(input.issue_url)
|
|
208
|
+
? `There is already a ticket for this pull request: ${derivedId}`
|
|
209
|
+
: `There is already a ticket for this issue: ${derivedId}`);
|
|
180
210
|
}
|
|
181
211
|
const id = input.id || derivedId || `ticket-${randomUUID().slice(0, 8)}`;
|
|
182
212
|
const now = new Date().toISOString();
|
|
@@ -192,14 +222,15 @@ export class TicketRepository {
|
|
|
192
222
|
throw new Error("Field 'budget_usd' must be a positive finite number");
|
|
193
223
|
}
|
|
194
224
|
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
225
|
+
// 0 (the default) means no timeout: the watchdog never terminates the run on time.
|
|
226
|
+
const timeoutMinutes = input.timeout_minutes !== undefined ? Number(input.timeout_minutes) : 0;
|
|
227
|
+
if (Number.isNaN(timeoutMinutes) || timeoutMinutes < 0 || !Number.isFinite(timeoutMinutes)) {
|
|
228
|
+
throw new Error("Field 'timeout_minutes' must be a finite number >= 0 (0 = no timeout)");
|
|
198
229
|
}
|
|
199
230
|
|
|
200
231
|
const agent = input.agent || 'pi';
|
|
201
232
|
if (!isValidAgent(agent)) {
|
|
202
|
-
throw new Error(`Invalid agent '${agent}'. Supported agents are:
|
|
233
|
+
throw new Error(`Invalid agent '${agent}'. Supported agents are: ${SUPPORTED_AGENTS.join(', ')}`);
|
|
203
234
|
}
|
|
204
235
|
|
|
205
236
|
const repoAgents = normalizeRepoAgents(input.repo_agents);
|
|
@@ -216,6 +247,9 @@ export class TicketRepository {
|
|
|
216
247
|
throw new Error("Field 'bondify' must be a boolean");
|
|
217
248
|
}
|
|
218
249
|
const bondify = input.bondify !== false;
|
|
250
|
+
if (input.docker !== undefined && typeof input.docker !== 'boolean') {
|
|
251
|
+
throw new Error("Field 'docker' must be a boolean");
|
|
252
|
+
}
|
|
219
253
|
if (layoutBases(layout).includes(targetBranch)) {
|
|
220
254
|
throw new Error('target_branch must differ from base_branch: a run only pushes its own branch (P4)');
|
|
221
255
|
}
|
|
@@ -226,8 +260,8 @@ export class TicketRepository {
|
|
|
226
260
|
INSERT INTO tickets (
|
|
227
261
|
id, title, description, repo_url, base_branch, target_branch,
|
|
228
262
|
budget_usd, timeout_minutes, agent, model, prompt, verify_commands,
|
|
229
|
-
hub_url, hub_base, repos, repo_agents, issue_url, story, team_engine, bondify, status, created_at, updated_at
|
|
230
|
-
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
263
|
+
hub_url, hub_base, repos, repo_agents, issue_url, story, source_pr_url, team_engine, bondify, docker, status, created_at, updated_at
|
|
264
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
231
265
|
`);
|
|
232
266
|
|
|
233
267
|
const teamEngine = input.team_engine === 'herdr' ? 'herdr' : 'hc';
|
|
@@ -250,9 +284,11 @@ export class TicketRepository {
|
|
|
250
284
|
layout.repos ? JSON.stringify(layout.repos) : null,
|
|
251
285
|
Object.keys(repoAgents).length ? JSON.stringify(repoAgents) : null,
|
|
252
286
|
input.issue_url ? String(input.issue_url).trim() : null,
|
|
253
|
-
input.story
|
|
287
|
+
input.story ?? null,
|
|
288
|
+
sourceUrl,
|
|
254
289
|
teamEngine,
|
|
255
290
|
bondify ? 1 : 0,
|
|
291
|
+
input.docker === true ? 1 : 0,
|
|
256
292
|
status,
|
|
257
293
|
now,
|
|
258
294
|
now
|
|
@@ -294,6 +330,12 @@ export class TicketRepository {
|
|
|
294
330
|
repos: existing.hub_url || existing.mode === 'single' ? null : existing.repos,
|
|
295
331
|
};
|
|
296
332
|
const layoutKeys = LAYOUT_KEYS.filter((k) => (updates as Record<string, unknown>)[k] !== undefined);
|
|
333
|
+
// Plan bond-app-ticket-desde-pr: a ticket bound to a PR or branch keeps that repo and
|
|
334
|
+
// those branches (they are the PR's); the link itself is not editable either.
|
|
335
|
+
if (existing.source_pr_url && (layoutKeys.length > 0 || (updates.target_branch !== undefined && updates.target_branch !== existing.target_branch))) {
|
|
336
|
+
throw new Error('This ticket works on an existing PR or branch: its repo and branches come from it');
|
|
337
|
+
}
|
|
338
|
+
delete (updates as Record<string, unknown>).source_pr_url;
|
|
297
339
|
if (layoutKeys.length > 0) {
|
|
298
340
|
// Review M5: a partial change keeps the rest of the same kind of layout (a new
|
|
299
341
|
// repo_url keeps its base, hub_base alone keeps the hub); another kind replaces it.
|
|
@@ -326,7 +368,7 @@ export class TicketRepository {
|
|
|
326
368
|
throw new Error("'repo_agents' is for an existing hub; in a list, give each repo its 'agent'");
|
|
327
369
|
}
|
|
328
370
|
if (updates.agent !== undefined && !isValidAgent(updates.agent)) {
|
|
329
|
-
throw new Error(`Invalid agent '${updates.agent}'. Supported agents are:
|
|
371
|
+
throw new Error(`Invalid agent '${updates.agent}'. Supported agents are: ${SUPPORTED_AGENTS.join(', ')}`);
|
|
330
372
|
}
|
|
331
373
|
if (updates.target_branch !== undefined && !validateBranchName(updates.target_branch)) {
|
|
332
374
|
throw new Error(`Invalid target_branch '${updates.target_branch}'`);
|
|
@@ -345,13 +387,16 @@ export class TicketRepository {
|
|
|
345
387
|
}
|
|
346
388
|
if (updates.timeout_minutes !== undefined) {
|
|
347
389
|
const t = Number(updates.timeout_minutes);
|
|
348
|
-
if (isNaN(t) || t
|
|
349
|
-
throw new Error("Field 'timeout_minutes' must be a
|
|
390
|
+
if (Number.isNaN(t) || t < 0 || !Number.isFinite(t)) {
|
|
391
|
+
throw new Error("Field 'timeout_minutes' must be a finite number >= 0 (0 = no timeout)");
|
|
350
392
|
}
|
|
351
393
|
}
|
|
352
394
|
if (updates.bondify !== undefined && typeof updates.bondify !== 'boolean') {
|
|
353
395
|
throw new Error("Field 'bondify' must be a boolean");
|
|
354
396
|
}
|
|
397
|
+
if (updates.docker !== undefined && typeof updates.docker !== 'boolean') {
|
|
398
|
+
throw new Error("Field 'docker' must be a boolean");
|
|
399
|
+
}
|
|
355
400
|
|
|
356
401
|
// Preserve status: status is managed via run lifecycle, not arbitrary ticket patch
|
|
357
402
|
const merged = { ...existing, ...updates, status: existing.status, updated_at: new Date().toISOString() };
|
|
@@ -361,7 +406,7 @@ export class TicketRepository {
|
|
|
361
406
|
title = ?, description = ?, repo_url = ?, base_branch = ?, target_branch = ?,
|
|
362
407
|
budget_usd = ?, timeout_minutes = ?, agent = ?, model = ?, prompt = ?,
|
|
363
408
|
verify_commands = ?, hub_url = ?, hub_base = ?, repos = ?, repo_agents = ?,
|
|
364
|
-
issue_url = ?, story = ?, team_engine = ?, bondify = ?, status = ?, updated_at = ?
|
|
409
|
+
issue_url = ?, story = ?, team_engine = ?, bondify = ?, docker = ?, status = ?, updated_at = ?
|
|
365
410
|
WHERE id = ?
|
|
366
411
|
`);
|
|
367
412
|
|
|
@@ -382,9 +427,10 @@ export class TicketRepository {
|
|
|
382
427
|
layout.repos ? JSON.stringify(layout.repos) : null,
|
|
383
428
|
Object.keys(repoAgents).length ? JSON.stringify(repoAgents) : null,
|
|
384
429
|
merged.issue_url ? String(merged.issue_url).trim() : null,
|
|
385
|
-
merged.story
|
|
430
|
+
merged.story ?? null,
|
|
386
431
|
merged.team_engine === 'herdr' ? 'herdr' : 'hc',
|
|
387
432
|
merged.bondify ? 1 : 0,
|
|
433
|
+
merged.docker ? 1 : 0,
|
|
388
434
|
merged.status,
|
|
389
435
|
merged.updated_at,
|
|
390
436
|
id
|
|
@@ -411,7 +457,8 @@ export class TicketRepository {
|
|
|
411
457
|
title: String(row.title),
|
|
412
458
|
description: row.description ? String(row.description) : undefined,
|
|
413
459
|
issue_url: row.issue_url ? String(row.issue_url) : null,
|
|
414
|
-
story: row.story ? String(row.story)
|
|
460
|
+
story: row.story === null || row.story === undefined ? null : String(row.story),
|
|
461
|
+
source_pr_url: row.source_pr_url ? String(row.source_pr_url) : null,
|
|
415
462
|
repo_url: repoUrl,
|
|
416
463
|
base_branch: baseBranch,
|
|
417
464
|
hub_url: hubUrl,
|
|
@@ -428,6 +475,7 @@ export class TicketRepository {
|
|
|
428
475
|
verify_commands: parseVerifyCommands(row.verify_commands),
|
|
429
476
|
team_engine: (row.team_engine === 'hc' ? 'hc' : 'herdr') as 'hc' | 'herdr',
|
|
430
477
|
bondify: row.bondify !== null && row.bondify !== undefined ? Number(row.bondify) !== 0 : true,
|
|
478
|
+
docker: Number(row.docker ?? 0) !== 0,
|
|
431
479
|
status: row.status as RunState,
|
|
432
480
|
created_at: String(row.created_at),
|
|
433
481
|
updated_at: String(row.updated_at),
|
package/src/index.ts
CHANGED
|
@@ -7,16 +7,16 @@ import { SettingsRepository } from './db/settings-repo.ts';
|
|
|
7
7
|
import { EventBus } from './sse/event-bus.ts';
|
|
8
8
|
import { DockerClient } from './runner/docker-client.ts';
|
|
9
9
|
import { Orchestrator } from './core/orchestrator.ts';
|
|
10
|
-
import { createServer } from './server/app.ts';
|
|
10
|
+
import { createServer, type ServerHooks } from './server/app.ts';
|
|
11
11
|
|
|
12
|
-
export async function bootstrap(configOverrides = {}) {
|
|
12
|
+
export async function bootstrap(configOverrides = {}, hooks: ServerHooks = {}) {
|
|
13
13
|
const config = loadConfig(configOverrides);
|
|
14
14
|
const db = initDatabase(config.dbPath);
|
|
15
15
|
|
|
16
16
|
const ticketRepo = new TicketRepository(db);
|
|
17
17
|
const runRepo = new RunRepository(db);
|
|
18
18
|
const eventRepo = new EventRepository(db);
|
|
19
|
-
const settingsRepo = new SettingsRepository(db);
|
|
19
|
+
const settingsRepo = new SettingsRepository(db, config.dataDir);
|
|
20
20
|
const eventBus = new EventBus(eventRepo);
|
|
21
21
|
const dockerClient = new DockerClient();
|
|
22
22
|
|
|
@@ -31,7 +31,7 @@ export async function bootstrap(configOverrides = {}) {
|
|
|
31
31
|
|
|
32
32
|
await orchestrator.start();
|
|
33
33
|
|
|
34
|
-
const server = createServer(orchestrator);
|
|
34
|
+
const server = createServer(orchestrator, hooks);
|
|
35
35
|
|
|
36
36
|
return new Promise<{ server: typeof server; orchestrator: Orchestrator; port: number }>((resolve) => {
|
|
37
37
|
server.listen(config.port, config.host, () => {
|
|
@@ -0,0 +1,273 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Plan bond-app-azure-jira P1: the Azure DevOps REST calls bond-app makes from the host
|
|
3
|
+
* with the user's PAT (Basic auth, empty user): check the credential, open the pull
|
|
4
|
+
* request of a delivered branch, and check or delete that branch when the ticket goes.
|
|
5
|
+
* Never in argv, env or logs; the push itself happens in the container (delivery.ts).
|
|
6
|
+
*/
|
|
7
|
+
import type { FetchLike, PullRequest } from './github-client.ts';
|
|
8
|
+
import { parseAzureRepoUrl, type AzureRepoRef } from '../core/repo-host.ts';
|
|
9
|
+
|
|
10
|
+
const API = 'api-version=7.1';
|
|
11
|
+
|
|
12
|
+
export class AzureDevOpsApiError extends Error {
|
|
13
|
+
status: number;
|
|
14
|
+
constructor(message: string, status: number) {
|
|
15
|
+
super(message);
|
|
16
|
+
this.name = 'AzureDevOpsApiError';
|
|
17
|
+
this.status = status;
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** https://dev.azure.com/<org> (trailing slash and the older visualstudio.com form accepted). */
|
|
22
|
+
export function normalizeAzureOrgUrl(raw: string): string | null {
|
|
23
|
+
const u = String(raw ?? '').trim().replace(/\/+$/, '');
|
|
24
|
+
const dev = /^https:\/\/dev\.azure\.com\/([A-Za-z0-9][A-Za-z0-9_.-]{0,99})$/.exec(u);
|
|
25
|
+
if (dev) return `https://dev.azure.com/${dev[1]}`;
|
|
26
|
+
const vs = /^https:\/\/([A-Za-z0-9][A-Za-z0-9_.-]{0,99})\.visualstudio\.com$/.exec(u);
|
|
27
|
+
if (vs) return `https://dev.azure.com/${vs[1]}`;
|
|
28
|
+
return null;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export class AzureDevOpsClient {
|
|
32
|
+
private fetchImpl: FetchLike;
|
|
33
|
+
|
|
34
|
+
constructor(fetchImpl: FetchLike = fetch as unknown as FetchLike) {
|
|
35
|
+
this.fetchImpl = fetchImpl;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
private async call(pat: string, method: string, url: string, body?: unknown): Promise<{ status: number; data: unknown }> {
|
|
39
|
+
const res = await this.fetchImpl(url, {
|
|
40
|
+
method,
|
|
41
|
+
headers: {
|
|
42
|
+
Accept: 'application/json',
|
|
43
|
+
Authorization: `Basic ${Buffer.from(`:${pat}`).toString('base64')}`,
|
|
44
|
+
'User-Agent': 'bond-app',
|
|
45
|
+
...(body !== undefined ? { 'Content-Type': 'application/json' } : {}),
|
|
46
|
+
},
|
|
47
|
+
body: body !== undefined ? JSON.stringify(body) : undefined,
|
|
48
|
+
});
|
|
49
|
+
const text = await res.text();
|
|
50
|
+
let data: unknown = null;
|
|
51
|
+
try {
|
|
52
|
+
data = text ? JSON.parse(text) : null;
|
|
53
|
+
} catch {
|
|
54
|
+
data = null;
|
|
55
|
+
}
|
|
56
|
+
return { status: res.status, data };
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
private repoApi(ref: AzureRepoRef, tail: string): string {
|
|
60
|
+
return `${ref.orgUrl}/${ref.project}/_apis/git/repositories/${ref.repo}${tail}`;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
private ref(repoUrl: string): AzureRepoRef {
|
|
64
|
+
const ref = parseAzureRepoUrl(repoUrl);
|
|
65
|
+
if (!ref) throw new AzureDevOpsApiError(`Not an Azure Repos URL: '${repoUrl}'`, 400);
|
|
66
|
+
return ref;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* Who the PAT belongs to in that organization (connectionData). Throws a clear error on
|
|
71
|
+
* a wrong PAT or organization: the caller shows it in Ajustes.
|
|
72
|
+
*/
|
|
73
|
+
async whoAmI(pat: string, orgUrl: string): Promise<{ name: string; email?: string; id?: string }> {
|
|
74
|
+
const res = await this.call(pat, 'GET', `${orgUrl}/_apis/connectionData?${API}-preview`);
|
|
75
|
+
const user = (res.data as { authenticatedUser?: { id?: string; providerDisplayName?: string; properties?: { Account?: { $value?: string } } } } | null)?.authenticatedUser;
|
|
76
|
+
if (res.status !== 200 || !user || !user.providerDisplayName || user.providerDisplayName === 'Anonymous') {
|
|
77
|
+
throw new AzureDevOpsApiError(
|
|
78
|
+
res.status === 401 || res.status === 203 || !user || user?.providerDisplayName === 'Anonymous'
|
|
79
|
+
? 'Azure DevOps no acepta ese PAT en esa organización'
|
|
80
|
+
: `Azure DevOps respondió ${res.status}`,
|
|
81
|
+
res.status === 200 ? 401 : res.status
|
|
82
|
+
);
|
|
83
|
+
}
|
|
84
|
+
const email = user.properties?.Account?.$value;
|
|
85
|
+
return { name: user.providerDisplayName, ...(email ? { email } : {}), ...(user.id ? { id: user.id } : {}) };
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* Open the PR `head` -> `base`, or return the active one that already exists for that
|
|
90
|
+
* branch (a delivery retried after a crash must not fail on it).
|
|
91
|
+
*/
|
|
92
|
+
async openPullRequest(pat: string, repoUrl: string, pr: { head: string; base: string; title: string; body: string }): Promise<PullRequest> {
|
|
93
|
+
const ref = this.ref(repoUrl);
|
|
94
|
+
const created = await this.call(pat, 'POST', this.repoApi(ref, `/pullrequests?${API}`), {
|
|
95
|
+
sourceRefName: `refs/heads/${pr.head}`,
|
|
96
|
+
targetRefName: `refs/heads/${pr.base}`,
|
|
97
|
+
title: pr.title,
|
|
98
|
+
// Azure caps the description at 4000 characters.
|
|
99
|
+
description: pr.body.length > 4000 ? `${pr.body.slice(0, 3990)}\n…` : pr.body,
|
|
100
|
+
});
|
|
101
|
+
const web = (id: number) => `${ref.orgUrl}/${ref.project}/_git/${ref.repo}/pullrequest/${id}`;
|
|
102
|
+
if (created.status === 201 || created.status === 200) {
|
|
103
|
+
const id = (created.data as { pullRequestId?: number }).pullRequestId!;
|
|
104
|
+
return { number: id, url: web(id), created: true };
|
|
105
|
+
}
|
|
106
|
+
if (created.status === 409) {
|
|
107
|
+
const q = `?searchCriteria.sourceRefName=${encodeURIComponent(`refs/heads/${pr.head}`)}&searchCriteria.targetRefName=${encodeURIComponent(`refs/heads/${pr.base}`)}&searchCriteria.status=active&${API}`;
|
|
108
|
+
const found = await this.call(pat, 'GET', this.repoApi(ref, `/pullrequests${q}`));
|
|
109
|
+
const first = (found.data as { value?: Array<{ pullRequestId: number }> } | null)?.value?.[0];
|
|
110
|
+
if (first) return { number: first.pullRequestId, url: web(first.pullRequestId), created: false };
|
|
111
|
+
}
|
|
112
|
+
const message = (created.data as { message?: string } | null)?.message || `HTTP ${created.status}`;
|
|
113
|
+
throw new AzureDevOpsApiError(`Azure DevOps refused the pull request: ${message}`, created.status);
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* The organization's repositories (all projects the PAT sees), for the new-ticket repo
|
|
118
|
+
* search: canonical clone URL, «org / project / repo» and the default branch.
|
|
119
|
+
*/
|
|
120
|
+
async listRepositories(pat: string, orgUrl: string): Promise<Array<{ url: string; project: string; name: string; default_branch?: string }>> {
|
|
121
|
+
const res = await this.call(pat, 'GET', `${orgUrl}/_apis/git/repositories?${API}`);
|
|
122
|
+
if (res.status !== 200) throw new AzureDevOpsApiError(`Azure DevOps repositories: HTTP ${res.status}`, res.status);
|
|
123
|
+
const rows = (res.data as { value?: Array<{ name?: string; isDisabled?: boolean; defaultBranch?: string; project?: { name?: string } }> } | null)?.value ?? [];
|
|
124
|
+
const out: Array<{ url: string; project: string; name: string; default_branch?: string }> = [];
|
|
125
|
+
for (const r of rows) {
|
|
126
|
+
if (!r?.name || !r.project?.name || r.isDisabled) continue;
|
|
127
|
+
const url = `${orgUrl}/${encodeURIComponent(r.project.name)}/_git/${encodeURIComponent(r.name)}`;
|
|
128
|
+
const branch = typeof r.defaultBranch === 'string' ? r.defaultBranch.replace(/^refs\/heads\//, '') : undefined;
|
|
129
|
+
out.push({ url, project: r.project.name, name: r.name, ...(branch ? { default_branch: branch } : {}) });
|
|
130
|
+
}
|
|
131
|
+
return out.sort((a, b) => `${a.project}/${a.name}`.localeCompare(`${b.project}/${b.name}`));
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/** The web URL of a PR (what the user copies from the browser). */
|
|
135
|
+
pullRequestWebUrl(repoUrl: string, id: number): string {
|
|
136
|
+
const ref = this.ref(repoUrl);
|
|
137
|
+
return `${ref.orgUrl}/${ref.project}/_git/${ref.repo}/pullrequest/${id}`;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/**
|
|
141
|
+
* Plan bond-app-ticket-desde-pr P1: one pull request, for a ticket that starts from it —
|
|
142
|
+
* its branches, state, whether it comes from a fork, and its title and description.
|
|
143
|
+
*/
|
|
144
|
+
async getPullRequest(pat: string, repoUrl: string, id: number): Promise<{
|
|
145
|
+
number: number; url: string; title: string; body: string; head: string; base: string;
|
|
146
|
+
state: 'open' | 'closed' | 'merged'; draft: boolean; is_fork: boolean; author?: string;
|
|
147
|
+
}> {
|
|
148
|
+
const ref = this.ref(repoUrl);
|
|
149
|
+
const res = await this.call(pat, 'GET', this.repoApi(ref, `/pullrequests/${id}?${API}`));
|
|
150
|
+
if (res.status !== 200) {
|
|
151
|
+
const msg = (res.data as { message?: string } | null)?.message || `HTTP ${res.status}`;
|
|
152
|
+
throw new AzureDevOpsApiError(`Azure DevOps pull request ${id}: ${msg}`, res.status);
|
|
153
|
+
}
|
|
154
|
+
const d = res.data as {
|
|
155
|
+
pullRequestId: number; title?: string; description?: string; status?: string; isDraft?: boolean;
|
|
156
|
+
sourceRefName?: string; targetRefName?: string; forkSource?: unknown; createdBy?: { displayName?: string };
|
|
157
|
+
};
|
|
158
|
+
const branch = (r?: string) => String(r ?? '').replace(/^refs\/heads\//, '');
|
|
159
|
+
return {
|
|
160
|
+
number: d.pullRequestId,
|
|
161
|
+
url: this.pullRequestWebUrl(repoUrl, d.pullRequestId),
|
|
162
|
+
title: d.title || '',
|
|
163
|
+
body: String(d.description ?? '').slice(0, 8000),
|
|
164
|
+
head: branch(d.sourceRefName),
|
|
165
|
+
base: branch(d.targetRefName),
|
|
166
|
+
state: d.status === 'active' ? 'open' : d.status === 'completed' ? 'merged' : 'closed',
|
|
167
|
+
draft: Boolean(d.isDraft),
|
|
168
|
+
is_fork: Boolean(d.forkSource),
|
|
169
|
+
...(d.createdBy?.displayName ? { author: d.createdBy.displayName } : {}),
|
|
170
|
+
};
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/**
|
|
174
|
+
* P1: active pull requests of one project (`project` as it appears in the URLs) or, with
|
|
175
|
+
* `repoUrl`, of one repo. Newest first, as Azure returns them.
|
|
176
|
+
*/
|
|
177
|
+
async listActivePullRequests(pat: string, orgUrl: string, scope: { project?: string; repoUrl?: string; creatorId?: string; reviewerId?: string }): Promise<Array<{
|
|
178
|
+
url: string; number: number; title: string; repo_url: string; author?: string; updated_at?: string; draft: boolean;
|
|
179
|
+
}>> {
|
|
180
|
+
const who = (scope.creatorId ? `&searchCriteria.creatorId=${encodeURIComponent(scope.creatorId)}` : '')
|
|
181
|
+
+ (scope.reviewerId ? `&searchCriteria.reviewerId=${encodeURIComponent(scope.reviewerId)}` : '');
|
|
182
|
+
const q = `?searchCriteria.status=active${who}&$top=50&${API}`;
|
|
183
|
+
const url = scope.repoUrl
|
|
184
|
+
? this.repoApi(this.ref(scope.repoUrl), `/pullrequests${q}`)
|
|
185
|
+
: `${orgUrl}/${scope.project}/_apis/git/pullrequests${q}`;
|
|
186
|
+
const res = await this.call(pat, 'GET', url);
|
|
187
|
+
if (res.status !== 200) throw new AzureDevOpsApiError(`Azure DevOps pull requests: HTTP ${res.status}`, res.status);
|
|
188
|
+
const rows = (res.data as { value?: Array<{
|
|
189
|
+
pullRequestId?: number; title?: string; isDraft?: boolean; creationDate?: string;
|
|
190
|
+
createdBy?: { displayName?: string }; repository?: { name?: string; project?: { name?: string } };
|
|
191
|
+
}> } | null)?.value ?? [];
|
|
192
|
+
const out: Array<{ url: string; number: number; title: string; repo_url: string; author?: string; updated_at?: string; draft: boolean }> = [];
|
|
193
|
+
for (const r of rows) {
|
|
194
|
+
if (!r?.pullRequestId || !r.repository?.name || !r.repository.project?.name) continue;
|
|
195
|
+
const repoUrl = `${orgUrl}/${encodeURIComponent(r.repository.project.name)}/_git/${encodeURIComponent(r.repository.name)}`;
|
|
196
|
+
out.push({
|
|
197
|
+
url: this.pullRequestWebUrl(repoUrl, r.pullRequestId),
|
|
198
|
+
number: r.pullRequestId,
|
|
199
|
+
title: r.title || '',
|
|
200
|
+
repo_url: repoUrl,
|
|
201
|
+
...(r.createdBy?.displayName ? { author: r.createdBy.displayName } : {}),
|
|
202
|
+
...(r.creationDate ? { updated_at: r.creationDate } : {}),
|
|
203
|
+
draft: Boolean(r.isDraft),
|
|
204
|
+
});
|
|
205
|
+
}
|
|
206
|
+
return out;
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
/** P1: the active PR whose source is `branch` in that repo (a branch URL that already has one). */
|
|
210
|
+
async findActivePullRequestByHead(pat: string, repoUrl: string, branch: string): Promise<number | null> {
|
|
211
|
+
const ref = this.ref(repoUrl);
|
|
212
|
+
const q = `?searchCriteria.sourceRefName=${encodeURIComponent(`refs/heads/${branch}`)}&searchCriteria.status=active&$top=5&${API}`;
|
|
213
|
+
const res = await this.call(pat, 'GET', this.repoApi(ref, `/pullrequests${q}`));
|
|
214
|
+
if (res.status !== 200) return null;
|
|
215
|
+
return (res.data as { value?: Array<{ pullRequestId?: number }> } | null)?.value?.[0]?.pullRequestId ?? null;
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
/** P1: the repo's default branch (the base of a ticket started from a bare branch). */
|
|
219
|
+
async getDefaultBranch(pat: string, repoUrl: string): Promise<string> {
|
|
220
|
+
const ref = this.ref(repoUrl);
|
|
221
|
+
const res = await this.call(pat, 'GET', this.repoApi(ref, `?${API}`));
|
|
222
|
+
if (res.status !== 200) throw new AzureDevOpsApiError(`Azure DevOps repository: HTTP ${res.status}`, res.status);
|
|
223
|
+
return String((res.data as { defaultBranch?: string } | null)?.defaultBranch ?? 'refs/heads/main').replace(/^refs\/heads\//, '');
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
/** P1: whether the repo is a bond hub (`hub.toml` at its root) at `branch`. */
|
|
227
|
+
async isHub(pat: string, repoUrl: string, branch?: string): Promise<boolean> {
|
|
228
|
+
const ref = this.ref(repoUrl);
|
|
229
|
+
const v = branch ? `&versionDescriptor.version=${encodeURIComponent(branch)}&versionDescriptor.versionType=branch` : '';
|
|
230
|
+
const res = await this.call(pat, 'GET', this.repoApi(ref, `/items?path=${encodeURIComponent('/hub.toml')}${v}&${API}`));
|
|
231
|
+
return res.status === 200;
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
/** P5: read `hub.toml` at `branch` (or default branch), or null if absent/unreadable. */
|
|
235
|
+
async getHubToml(pat: string, repoUrl: string, branch?: string): Promise<string | null> {
|
|
236
|
+
const ref = this.ref(repoUrl);
|
|
237
|
+
const v = branch ? `&versionDescriptor.version=${encodeURIComponent(branch)}&versionDescriptor.versionType=branch` : '';
|
|
238
|
+
const res = await this.call(pat, 'GET', this.repoApi(ref, `/items?path=${encodeURIComponent('/hub.toml')}&includeContent=true${v}&${API}`));
|
|
239
|
+
if (res.status !== 200 || !res.data || typeof res.data !== 'object') return null;
|
|
240
|
+
const content = (res.data as { content?: unknown }).content;
|
|
241
|
+
return typeof content === 'string' ? content : null;
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
private async branchSha(pat: string, ref: AzureRepoRef, branch: string): Promise<string | null> {
|
|
245
|
+
const res = await this.call(pat, 'GET', this.repoApi(ref, `/refs?filter=${encodeURIComponent(`heads/${branch}`)}&${API}`));
|
|
246
|
+
if (res.status !== 200) throw new AzureDevOpsApiError(`Azure DevOps refs: HTTP ${res.status}`, res.status);
|
|
247
|
+
const hit = (res.data as { value?: Array<{ name: string; objectId: string }> } | null)?.value?.find((r) => r.name === `refs/heads/${branch}`);
|
|
248
|
+
return hit ? hit.objectId : null;
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
async remoteBranchExists(pat: string, repoUrl: string, branch: string): Promise<boolean> {
|
|
252
|
+
return (await this.branchSha(pat, this.ref(repoUrl), branch)) !== null;
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
/** Whether every commit of `branch` is already in `base` (aheadCount 0). */
|
|
256
|
+
async isBranchMerged(pat: string, repoUrl: string, branch: string, base: string): Promise<boolean> {
|
|
257
|
+
const ref = this.ref(repoUrl);
|
|
258
|
+
const q = `?baseVersion=${encodeURIComponent(base)}&baseVersionType=branch&targetVersion=${encodeURIComponent(branch)}&targetVersionType=branch&$top=1&${API}`;
|
|
259
|
+
const res = await this.call(pat, 'GET', this.repoApi(ref, `/diffs/commits${q}`));
|
|
260
|
+
if (res.status !== 200) return false;
|
|
261
|
+
return (res.data as { aheadCount?: number } | null)?.aheadCount === 0;
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
async deleteRemoteBranch(pat: string, repoUrl: string, branch: string): Promise<boolean> {
|
|
265
|
+
const ref = this.ref(repoUrl);
|
|
266
|
+
const sha = await this.branchSha(pat, ref, branch);
|
|
267
|
+
if (!sha) return false;
|
|
268
|
+
const res = await this.call(pat, 'POST', this.repoApi(ref, `/refs?${API}`), [
|
|
269
|
+
{ name: `refs/heads/${branch}`, oldObjectId: sha, newObjectId: '0000000000000000000000000000000000000000' },
|
|
270
|
+
]);
|
|
271
|
+
return res.status === 200 && Boolean((res.data as { value?: Array<{ success?: boolean }> } | null)?.value?.[0]?.success);
|
|
272
|
+
}
|
|
273
|
+
}
|