@phren/cli 0.3.36 → 0.3.39
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/bridge/account-choice.d.ts +82 -0
- package/dist/bridge/account-choice.js +173 -0
- package/dist/bridge/account-failover.d.ts +61 -0
- package/dist/bridge/account-failover.js +189 -0
- package/dist/bridge/account-usage.d.ts +7 -2
- package/dist/bridge/account-usage.js +53 -8
- package/dist/bridge/agent-hooks.js +2 -0
- package/dist/bridge/changes.d.ts +5 -0
- package/dist/bridge/changes.js +4 -0
- package/dist/bridge/claude-accounts.d.ts +15 -4
- package/dist/bridge/claude-accounts.js +31 -16
- package/dist/bridge/claude-credits.d.ts +43 -0
- package/dist/bridge/claude-credits.js +236 -0
- package/dist/bridge/claude-question-dialog.js +6 -2
- package/dist/bridge/command.js +64 -3
- package/dist/bridge/device-enroll.d.ts +34 -0
- package/dist/bridge/device-enroll.js +57 -0
- package/dist/bridge/dispatch-command.d.ts +2 -0
- package/dist/bridge/dispatch-command.js +25 -1
- package/dist/bridge/dispatch-returns.d.ts +19 -0
- package/dist/bridge/dispatch-returns.js +93 -12
- package/dist/bridge/dispatch.d.ts +83 -3
- package/dist/bridge/dispatch.js +82 -10
- package/dist/bridge/file-range.d.ts +3 -0
- package/dist/bridge/file-range.js +5 -4
- package/dist/bridge/file-search.d.ts +37 -0
- package/dist/bridge/file-search.js +87 -0
- package/dist/bridge/file-write.d.ts +6 -0
- package/dist/bridge/file-write.js +120 -0
- package/dist/bridge/git-host-auth.d.ts +31 -0
- package/dist/bridge/git-host-auth.js +110 -0
- package/dist/bridge/git-host-gitboy.d.ts +46 -0
- package/dist/bridge/git-host-gitboy.js +296 -0
- package/dist/bridge/git-host-gitlab.d.ts +25 -0
- package/dist/bridge/git-host-gitlab.js +229 -0
- package/dist/bridge/git-host-http.d.ts +33 -0
- package/dist/bridge/git-host-http.js +70 -0
- package/dist/bridge/git-hosts.d.ts +92 -0
- package/dist/bridge/git-hosts.js +244 -0
- package/dist/bridge/git-publish.d.ts +15 -5
- package/dist/bridge/git-publish.js +69 -21
- package/dist/bridge/git-review.d.ts +23 -0
- package/dist/bridge/git-review.js +170 -0
- package/dist/bridge/git-sync.d.ts +14 -0
- package/dist/bridge/git-sync.js +143 -0
- package/dist/bridge/git.d.ts +20 -7
- package/dist/bridge/git.js +87 -68
- package/dist/bridge/gitboy-contract.d.ts +32 -0
- package/dist/bridge/gitboy-contract.js +46 -0
- package/dist/bridge/hand-off.d.ts +75 -3
- package/dist/bridge/hand-off.js +113 -27
- package/dist/bridge/health.d.ts +1 -1
- package/dist/bridge/health.js +5 -3
- package/dist/bridge/install.d.ts +14 -0
- package/dist/bridge/install.js +40 -1
- package/dist/bridge/launch-brief.d.ts +3 -0
- package/dist/bridge/launch-brief.js +16 -0
- package/dist/bridge/memory-store.d.ts +8 -0
- package/dist/bridge/memory-store.js +80 -2
- package/dist/bridge/pair.d.ts +6 -1
- package/dist/bridge/pair.js +74 -2
- package/dist/bridge/peers.js +4 -2
- package/dist/bridge/project-memory.d.ts +94 -0
- package/dist/bridge/project-memory.js +235 -0
- package/dist/bridge/push.d.ts +15 -0
- package/dist/bridge/push.js +39 -0
- package/dist/bridge/schedule-launch.js +5 -1
- package/dist/bridge/schedule-watch.d.ts +3 -0
- package/dist/bridge/schedule-watch.js +27 -1
- package/dist/bridge/scoped-gateway.d.ts +29 -0
- package/dist/bridge/scoped-gateway.js +239 -0
- package/dist/bridge/server-launch.d.ts +12 -0
- package/dist/bridge/server-launch.js +23 -12
- package/dist/bridge/server-pane-routes.js +54 -3
- package/dist/bridge/server-routes.d.ts +12 -0
- package/dist/bridge/server-routes.js +64 -5
- package/dist/bridge/server.js +50 -5
- package/dist/bridge/session-move.d.ts +288 -0
- package/dist/bridge/session-move.js +600 -0
- package/dist/bridge/subscription.d.ts +15 -0
- package/dist/bridge/subscription.js +23 -0
- package/dist/bridge/transport.js +21 -1
- package/dist/bridge/usage.d.ts +23 -4
- package/dist/bridge/usage.js +63 -11
- package/dist/bridge-hook.mjs +23280 -13252
- package/dist/cli/config.js +28 -2
- package/dist/cli-registry.js +10 -4
- package/dist/computers/command.js +3 -1
- package/dist/computers/read.d.ts +3 -0
- package/dist/computers/read.js +6 -0
- package/dist/content/summarize.d.ts +21 -0
- package/dist/content/summarize.js +56 -18
- package/dist/init/preferences.d.ts +6 -0
- package/dist/modules/registry.js +13 -13
- package/dist/project-config.d.ts +12 -0
- package/dist/project-config.js +29 -0
- package/dist/shared/retrieval.d.ts +1 -0
- package/dist/shared/retrieval.js +1 -1
- package/dist/sync/conflict-resolve.js +5 -6
- package/dist/tools/dispatch.js +20 -3
- package/dist/tools/finding.d.ts +25 -0
- package/dist/tools/finding.js +2 -1
- package/package.json +57 -1
|
@@ -0,0 +1,229 @@
|
|
|
1
|
+
import { resolveHostToken } from "./git-host-auth.js";
|
|
2
|
+
import { apiRoot, HostApiError, hostJson, safeLink } from "./git-host-http.js";
|
|
3
|
+
import { git } from "./projects.js";
|
|
4
|
+
/** GitLab, gitlab.com or self-hosted, over its REST API (v4). The token is
|
|
5
|
+
* GITLAB_TOKEN, the Hook's stored one, or glab's own sign-in, so glab itself
|
|
6
|
+
* is optional. Merge requests come back in the same shape as GitHub's pull
|
|
7
|
+
* requests; pipeline jobs are the checks, and the stage reads as the workflow. */
|
|
8
|
+
export const MERGE_TERMS = { short: "MR", long: "merge request", ref: "!" };
|
|
9
|
+
const ORDER = { failing: 0, pending: 1, passing: 2, skipped: 3, neutral: 4 };
|
|
10
|
+
/** A pipeline or job status as one state word. An allowed failure is neutral:
|
|
11
|
+
* it doesn't block the merge request. */
|
|
12
|
+
export function gitlabState(status, allowFailure = false) {
|
|
13
|
+
switch (String(status ?? "").toLowerCase()) {
|
|
14
|
+
case "success": return "passing";
|
|
15
|
+
case "failed": return allowFailure ? "neutral" : "failing";
|
|
16
|
+
case "canceled":
|
|
17
|
+
case "canceling": return allowFailure ? "neutral" : "failing";
|
|
18
|
+
case "skipped": return "skipped";
|
|
19
|
+
case "manual": return "neutral";
|
|
20
|
+
default: return "pending"; // created, waiting_for_resource, preparing, pending, running, scheduled
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
export function gitlabRollup(states) {
|
|
24
|
+
if (!states.length)
|
|
25
|
+
return null;
|
|
26
|
+
if (states.includes("failing"))
|
|
27
|
+
return "failing";
|
|
28
|
+
return states.includes("pending") ? "pending" : "passing";
|
|
29
|
+
}
|
|
30
|
+
/** What `detailed_merge_status` means, in GitHub's mergeStateStatus words
|
|
31
|
+
* (which the clients already colour) plus GitLab's own sentence. */
|
|
32
|
+
export function gitlabMergeState(detail) {
|
|
33
|
+
const value = String(detail ?? "");
|
|
34
|
+
const map = {
|
|
35
|
+
mergeable: ["CLEAN", "Ready to merge"],
|
|
36
|
+
conflict: ["DIRTY", "Has merge conflicts"],
|
|
37
|
+
need_rebase: ["BEHIND", "Needs a rebase onto the target branch"],
|
|
38
|
+
ci_must_pass: ["BLOCKED", "Waiting for the pipeline to pass"],
|
|
39
|
+
ci_still_running: ["BLOCKED", "Pipeline still running"],
|
|
40
|
+
not_approved: ["BLOCKED", "Needs approval"],
|
|
41
|
+
discussions_not_resolved: ["BLOCKED", "Has unresolved threads"],
|
|
42
|
+
draft_status: ["DRAFT", "Draft"],
|
|
43
|
+
blocked_status: ["BLOCKED", "Blocked by another merge request"],
|
|
44
|
+
requested_changes: ["BLOCKED", "Changes requested"],
|
|
45
|
+
jira_association_missing: ["BLOCKED", "Needs a Jira issue"],
|
|
46
|
+
merge_request_blocked: ["BLOCKED", "Blocked"],
|
|
47
|
+
external_status_checks: ["BLOCKED", "Waiting for external status checks"],
|
|
48
|
+
not_open: ["UNKNOWN", "Not open"],
|
|
49
|
+
checking: ["UNKNOWN", "Checking mergeability"],
|
|
50
|
+
unchecked: ["UNKNOWN", "Not checked yet"],
|
|
51
|
+
preparing: ["UNKNOWN", "Preparing"],
|
|
52
|
+
};
|
|
53
|
+
const hit = map[value];
|
|
54
|
+
return hit ? { mergeState: hit[0], mergeDetail: hit[1] } : value ? { mergeState: "UNKNOWN", mergeDetail: value.replace(/_/g, " ") } : {};
|
|
55
|
+
}
|
|
56
|
+
function upper(state) {
|
|
57
|
+
const value = String(state ?? "").toLowerCase();
|
|
58
|
+
return value === "opened" ? "OPEN" : value === "locked" ? "CLOSED" : value.toUpperCase();
|
|
59
|
+
}
|
|
60
|
+
function obj(value) {
|
|
61
|
+
return value && typeof value === "object" && !Array.isArray(value) ? value : {};
|
|
62
|
+
}
|
|
63
|
+
function projectPath(host) {
|
|
64
|
+
if (!host.webUrl || !host.domain)
|
|
65
|
+
return null;
|
|
66
|
+
const path = host.webUrl.replace(/^https?:\/\/[^/]+\//, "");
|
|
67
|
+
return path || null;
|
|
68
|
+
}
|
|
69
|
+
const SIGN_IN = (domain) => `Phren has no GitLab token for ${domain}. Connect it from the desktop's Changes pane, run phren bridge git-host set ${domain} gitlab on this computer, or sign in with glab auth login.`;
|
|
70
|
+
async function context(root, host) {
|
|
71
|
+
const path = projectPath(host);
|
|
72
|
+
if (!host.domain || !path)
|
|
73
|
+
return { available: false, reason: "unknown-host", message: "This repository has no GitLab remote.", pulls: [], current: null };
|
|
74
|
+
const token = await resolveHostToken("gitlab", host.domain);
|
|
75
|
+
if (!token)
|
|
76
|
+
return { available: false, reason: "auth", message: SIGN_IN(host.domain), pulls: [], current: null };
|
|
77
|
+
const base = await apiRoot(root, host.domain, `https://${host.domain}/api/v4`);
|
|
78
|
+
return { base, token: token.token, project: encodeURIComponent(path), domain: host.domain, account: { source: token.source, ...(token.user ? { user: token.user } : {}) } };
|
|
79
|
+
}
|
|
80
|
+
function call(ctx, path, init = {}) {
|
|
81
|
+
return hostJson(`${ctx.base}/projects/${ctx.project}${path}`, { token: ctx.token, scheme: "private-token", ...init });
|
|
82
|
+
}
|
|
83
|
+
function listed(mr) {
|
|
84
|
+
const author = obj(mr.author);
|
|
85
|
+
return { number: mr.iid, title: String(mr.title ?? ""), head: String(mr.source_branch ?? ""), base: String(mr.target_branch ?? ""),
|
|
86
|
+
author: String(author.username ?? author.name ?? ""), url: safeLink(mr.web_url) ?? "", draft: mr.draft === true || mr.work_in_progress === true,
|
|
87
|
+
state: upper(mr.state), updated: String(mr.updated_at ?? "") };
|
|
88
|
+
}
|
|
89
|
+
/** The branch's merge request with its pipeline jobs, approvals and merge state. */
|
|
90
|
+
async function currentRequest(ctx, branch) {
|
|
91
|
+
if (!branch)
|
|
92
|
+
return null;
|
|
93
|
+
const { json: found } = await call(ctx, `/merge_requests?source_branch=${encodeURIComponent(branch)}&state=all&order_by=updated_at&per_page=5`);
|
|
94
|
+
const first = (Array.isArray(found) ? found : []).map(obj).sort((a, b) => Number(upper(b.state) === "OPEN") - Number(upper(a.state) === "OPEN"))[0];
|
|
95
|
+
if (!first || typeof first.iid !== "number")
|
|
96
|
+
return null;
|
|
97
|
+
const [{ json: detail }, approvals] = await Promise.all([
|
|
98
|
+
call(ctx, `/merge_requests/${first.iid}`),
|
|
99
|
+
call(ctx, `/merge_requests/${first.iid}/approvals`).then(r => obj(r.json)).catch(() => null),
|
|
100
|
+
]);
|
|
101
|
+
const mr = obj(detail);
|
|
102
|
+
const pipeline = obj(mr.head_pipeline ?? mr.pipeline);
|
|
103
|
+
let checkRuns = [];
|
|
104
|
+
if (typeof pipeline.id === "number") {
|
|
105
|
+
const { json: jobs } = await call(ctx, `/pipelines/${pipeline.id}/jobs?per_page=100&include_retried=false`).catch(() => ({ json: [] }));
|
|
106
|
+
checkRuns = (Array.isArray(jobs) ? jobs : []).map(obj).map(job => {
|
|
107
|
+
const state = gitlabState(job.status, job.allow_failure === true);
|
|
108
|
+
const url = safeLink(job.web_url);
|
|
109
|
+
return { name: String(job.name ?? "Job").slice(0, 200), state, ...(job.stage ? { workflow: String(job.stage).slice(0, 200) } : {}), ...(url ? { url } : {}),
|
|
110
|
+
...(typeof job.duration === "number" ? { seconds: Math.round(job.duration) } : {}) };
|
|
111
|
+
}).sort((a, b) => ORDER[a.state] - ORDER[b.state]).slice(0, 100);
|
|
112
|
+
}
|
|
113
|
+
const given = Array.isArray(approvals?.approved_by) ? approvals.approved_by.length : 0;
|
|
114
|
+
const left = typeof approvals?.approvals_left === "number" ? approvals.approvals_left : undefined;
|
|
115
|
+
const required = typeof approvals?.approvals_required === "number" ? approvals.approvals_required : undefined;
|
|
116
|
+
const reviewDecision = approvals?.approved === true && (left ?? 0) === 0 && (required ?? given) > 0 ? "APPROVED"
|
|
117
|
+
: (left ?? 0) > 0 ? "REVIEW_REQUIRED" : undefined;
|
|
118
|
+
const pipelineState = typeof pipeline.status === "string" ? gitlabState(pipeline.status) : null;
|
|
119
|
+
const checks = checkRuns.length ? gitlabRollup(checkRuns.map(run => run.state)) : pipelineState === "neutral" || pipelineState === "skipped" ? "passing" : pipelineState;
|
|
120
|
+
const pipelineUrl = safeLink(pipeline.web_url);
|
|
121
|
+
return { ...listed(mr), checks, checkRuns,
|
|
122
|
+
...(reviewDecision ? { reviewDecision } : {}),
|
|
123
|
+
...gitlabMergeState(mr.detailed_merge_status ?? mr.merge_status),
|
|
124
|
+
...(typeof pipeline.id === "number" ? { pipeline: { id: pipeline.id, state: pipelineState, ...(pipelineUrl ? { url: pipelineUrl } : {}) } } : {}),
|
|
125
|
+
...(given || required !== undefined ? { approvals: { given, ...(required !== undefined ? { required } : {}) } } : {}),
|
|
126
|
+
...(typeof mr.user_notes_count === "number" ? { comments: mr.user_notes_count } : {}),
|
|
127
|
+
...(mr.has_conflicts === true ? { conflicts: true } : {}) };
|
|
128
|
+
}
|
|
129
|
+
function failed(error, domain) {
|
|
130
|
+
if (error instanceof HostApiError) {
|
|
131
|
+
const message = error.reason === "auth" ? `${error.message} ${SIGN_IN(domain)}` : error.message;
|
|
132
|
+
return { available: false, reason: error.reason, message, pulls: [], current: null };
|
|
133
|
+
}
|
|
134
|
+
return { available: false, reason: "failed", message: error instanceof Error ? error.message : String(error), pulls: [], current: null };
|
|
135
|
+
}
|
|
136
|
+
/** gh's --fill: one commit gives the title and body; several give a title from
|
|
137
|
+
* the branch and a body listing them. */
|
|
138
|
+
export async function fillFromCommits(root, baseRef, branch) {
|
|
139
|
+
const raw = await git(root, "log", "--reverse", "--format=%s%x1f%b%x1e", `${baseRef}..${branch}`).catch(() => "");
|
|
140
|
+
const commits = raw.split("\x1e").map(entry => entry.trim()).filter(Boolean).map(entry => { const [subject, body = ""] = entry.split("\x1f"); return { subject: subject.trim(), body: body.trim() }; });
|
|
141
|
+
if (commits.length === 1)
|
|
142
|
+
return { title: commits[0].subject, body: commits[0].body };
|
|
143
|
+
const words = branch.replace(/^[^/]+\//, "").replace(/[-_]+/g, " ").trim();
|
|
144
|
+
const title = words ? words[0].toUpperCase() + words.slice(1) : branch;
|
|
145
|
+
return { title, body: commits.map(commit => `- ${commit.subject}`).join("\n") };
|
|
146
|
+
}
|
|
147
|
+
export const gitlab = {
|
|
148
|
+
kind: "gitlab",
|
|
149
|
+
name: "GitLab",
|
|
150
|
+
terms: MERGE_TERMS,
|
|
151
|
+
supported: true,
|
|
152
|
+
async list(root, branch, host) {
|
|
153
|
+
const ctx = await context(root, host);
|
|
154
|
+
if (!("base" in ctx))
|
|
155
|
+
return ctx;
|
|
156
|
+
try {
|
|
157
|
+
const [{ json }, current] = await Promise.all([
|
|
158
|
+
call(ctx, "/merge_requests?state=opened&order_by=updated_at&per_page=50"),
|
|
159
|
+
currentRequest(ctx, branch),
|
|
160
|
+
]);
|
|
161
|
+
return { available: true, pulls: (Array.isArray(json) ? json : []).map(obj).map(listed), current, account: ctx.account };
|
|
162
|
+
}
|
|
163
|
+
catch (error) {
|
|
164
|
+
return failed(error, ctx.domain);
|
|
165
|
+
}
|
|
166
|
+
},
|
|
167
|
+
async open(root, branch, draft, host) {
|
|
168
|
+
const ctx = await context(root, host);
|
|
169
|
+
if (!("base" in ctx))
|
|
170
|
+
return { ok: false, reason: ctx.reason, message: ctx.message };
|
|
171
|
+
try {
|
|
172
|
+
await call(ctx, `/repository/branches/${encodeURIComponent(branch)}`).catch(error => {
|
|
173
|
+
if (error instanceof HostApiError && error.reason === "not-found")
|
|
174
|
+
throw new HostApiError("not-found", `Push ${branch} to GitLab first, then open the merge request.`, 404);
|
|
175
|
+
throw error;
|
|
176
|
+
});
|
|
177
|
+
const { json: project } = await call(ctx, "");
|
|
178
|
+
const target = String(obj(project).default_branch ?? "main");
|
|
179
|
+
const fill = await fillFromCommits(root, `${host.remote ?? "origin"}/${target}`, branch);
|
|
180
|
+
const title = draft && !/^draft:/i.test(fill.title) ? `Draft: ${fill.title}` : fill.title;
|
|
181
|
+
try {
|
|
182
|
+
const { json } = await call(ctx, "/merge_requests", { method: "POST", body: { source_branch: branch, target_branch: target, title, description: fill.body, remove_source_branch: true } });
|
|
183
|
+
return { ok: true, url: safeLink(obj(json).web_url) ?? "", number: obj(json).iid, branch, draft };
|
|
184
|
+
}
|
|
185
|
+
catch (error) {
|
|
186
|
+
if (error instanceof HostApiError && error.status === 409) {
|
|
187
|
+
const { json } = await call(ctx, `/merge_requests?source_branch=${encodeURIComponent(branch)}&state=opened&per_page=1`);
|
|
188
|
+
const existing = (Array.isArray(json) ? json : []).map(obj)[0];
|
|
189
|
+
if (existing)
|
|
190
|
+
return { ok: true, url: safeLink(existing.web_url) ?? "", number: existing.iid, branch, existing: true };
|
|
191
|
+
}
|
|
192
|
+
throw error;
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
catch (error) {
|
|
196
|
+
const result = failed(error, ctx.domain);
|
|
197
|
+
return { ok: false, reason: result.reason ?? "failed", message: result.message ?? "GitLab refused the merge request." };
|
|
198
|
+
}
|
|
199
|
+
},
|
|
200
|
+
async merge(root, request, host) {
|
|
201
|
+
const ctx = await context(root, host);
|
|
202
|
+
if (!("base" in ctx))
|
|
203
|
+
return { ok: false, reason: ctx.reason, message: ctx.message };
|
|
204
|
+
try {
|
|
205
|
+
// GitLab merges, or rebases, by the project's own merge method; squash is per request.
|
|
206
|
+
const { json } = await call(ctx, `/merge_requests/${request.number}/merge`, { method: "PUT", body: {
|
|
207
|
+
squash: request.method === "squash", ...(request.expectedHeadSha ? { sha: request.expectedHeadSha } : {}),
|
|
208
|
+
...(request.deleteBranch ? { should_remove_source_branch: true } : {})
|
|
209
|
+
} });
|
|
210
|
+
const mr = obj(json);
|
|
211
|
+
return { ok: true, number: request.number, method: request.method, state: upper(mr.state), ...(safeLink(mr.web_url) ? { url: safeLink(mr.web_url) } : {}) };
|
|
212
|
+
}
|
|
213
|
+
catch (error) {
|
|
214
|
+
if (error instanceof HostApiError && [405, 406, 409, 422].includes(error.status)) {
|
|
215
|
+
const why = error.status === 409 ? "The merge request has new commits since you looked; refresh and check them first." : error.message.replace(/^.*? answered \d+:? ?/, "") || "GitLab says it can't be merged yet.";
|
|
216
|
+
return { ok: false, reason: "blocked", message: why };
|
|
217
|
+
}
|
|
218
|
+
const result = failed(error, ctx.domain);
|
|
219
|
+
return { ok: false, reason: result.reason ?? "failed", message: result.message ?? "GitLab refused the merge." };
|
|
220
|
+
}
|
|
221
|
+
},
|
|
222
|
+
async whoami(root, host, token) {
|
|
223
|
+
if (!host.domain)
|
|
224
|
+
throw new HostApiError("failed", "This repository has no GitLab remote.");
|
|
225
|
+
const base = await apiRoot(root, host.domain, `https://${host.domain}/api/v4`);
|
|
226
|
+
const { json } = await hostJson(`${base}/user`, { token, scheme: "private-token" });
|
|
227
|
+
return { user: String(obj(json).username ?? "") };
|
|
228
|
+
},
|
|
229
|
+
};
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import type { Json } from "./protocol.js";
|
|
2
|
+
/** A small JSON client for the git hosts the Hook reads over HTTP. Every call
|
|
3
|
+
* has a deadline, never follows a redirect to another origin with the token,
|
|
4
|
+
* and turns a host's refusal into one of a few reasons clients can act on. */
|
|
5
|
+
export type HostFailure = "auth" | "not-found" | "unreachable" | "failed";
|
|
6
|
+
export declare class HostApiError extends Error {
|
|
7
|
+
reason: HostFailure;
|
|
8
|
+
status: number;
|
|
9
|
+
body: unknown;
|
|
10
|
+
/** `body` is the host's own JSON for a refusal (gitboy's `details`, say). */
|
|
11
|
+
constructor(reason: HostFailure, message: string, status?: number, body?: unknown);
|
|
12
|
+
}
|
|
13
|
+
/** The API root for a domain: `git config --global phren.<domain>.api` when
|
|
14
|
+
* set (a self-hosted server on another port or path), else the host's
|
|
15
|
+
* default. Only the user's global config counts: a repository's own config is
|
|
16
|
+
* writable by whatever runs in the checkout, and must never be able to send
|
|
17
|
+
* a stored token to another server. */
|
|
18
|
+
export declare function apiRoot(root: string, domain: string, fallback: string): Promise<string>;
|
|
19
|
+
export interface HostRequest {
|
|
20
|
+
token?: string;
|
|
21
|
+
/** How the token is sent: GitLab's PRIVATE-TOKEN header or a bearer token. */
|
|
22
|
+
scheme: "private-token" | "bearer";
|
|
23
|
+
method?: "GET" | "POST" | "PUT";
|
|
24
|
+
body?: Json;
|
|
25
|
+
timeoutMs?: number;
|
|
26
|
+
}
|
|
27
|
+
export declare function hostJson<T = unknown>(url: string, request: HostRequest): Promise<{
|
|
28
|
+
status: number;
|
|
29
|
+
json: T;
|
|
30
|
+
headers: Headers;
|
|
31
|
+
}>;
|
|
32
|
+
/** An https link, or nothing: hosts' links are shown and opened as-is. */
|
|
33
|
+
export declare function safeLink(value: unknown): string | undefined;
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import { git } from "./projects.js";
|
|
2
|
+
export class HostApiError extends Error {
|
|
3
|
+
reason;
|
|
4
|
+
status;
|
|
5
|
+
body;
|
|
6
|
+
/** `body` is the host's own JSON for a refusal (gitboy's `details`, say). */
|
|
7
|
+
constructor(reason, message, status = 0, body = null) {
|
|
8
|
+
super(message);
|
|
9
|
+
this.reason = reason;
|
|
10
|
+
this.status = status;
|
|
11
|
+
this.body = body;
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
/** The API root for a domain: `git config --global phren.<domain>.api` when
|
|
15
|
+
* set (a self-hosted server on another port or path), else the host's
|
|
16
|
+
* default. Only the user's global config counts: a repository's own config is
|
|
17
|
+
* writable by whatever runs in the checkout, and must never be able to send
|
|
18
|
+
* a stored token to another server. */
|
|
19
|
+
export async function apiRoot(root, domain, fallback) {
|
|
20
|
+
const configured = (await git(root, "config", "--global", "--get", `phren.${domain}.api`).catch(() => "")).trim();
|
|
21
|
+
return (configured || fallback).replace(/\/+$/, "");
|
|
22
|
+
}
|
|
23
|
+
export async function hostJson(url, request) {
|
|
24
|
+
const headers = { accept: "application/json", "user-agent": "phren-hook" };
|
|
25
|
+
if (request.token) {
|
|
26
|
+
if (request.scheme === "private-token")
|
|
27
|
+
headers["PRIVATE-TOKEN"] = request.token;
|
|
28
|
+
else
|
|
29
|
+
headers.authorization = `Bearer ${request.token}`;
|
|
30
|
+
}
|
|
31
|
+
if (request.body !== undefined)
|
|
32
|
+
headers["content-type"] = "application/json";
|
|
33
|
+
let response;
|
|
34
|
+
try {
|
|
35
|
+
response = await fetch(url, {
|
|
36
|
+
method: request.method ?? "GET", headers, redirect: "manual",
|
|
37
|
+
body: request.body === undefined ? undefined : JSON.stringify(request.body),
|
|
38
|
+
signal: AbortSignal.timeout(request.timeoutMs ?? 15_000),
|
|
39
|
+
});
|
|
40
|
+
}
|
|
41
|
+
catch (error) {
|
|
42
|
+
const timedOut = error instanceof Error && (error.name === "TimeoutError" || error.name === "AbortError");
|
|
43
|
+
throw new HostApiError("unreachable", timedOut ? `${new URL(url).host} did not answer within ${Math.round((request.timeoutMs ?? 15_000) / 1000)} seconds.` : `Could not reach ${new URL(url).host}.`);
|
|
44
|
+
}
|
|
45
|
+
if (response.status >= 300 && response.status < 400)
|
|
46
|
+
throw new HostApiError("failed", `${new URL(url).host} redirected the API call; set its API address with git config phren.<domain>.api <url>.`, response.status);
|
|
47
|
+
const text = await response.text();
|
|
48
|
+
let json = null;
|
|
49
|
+
try {
|
|
50
|
+
json = text ? JSON.parse(text) : null;
|
|
51
|
+
}
|
|
52
|
+
catch {
|
|
53
|
+
json = null;
|
|
54
|
+
}
|
|
55
|
+
if (response.status === 401)
|
|
56
|
+
throw new HostApiError("auth", "The host refused the token: it is missing, expired or revoked.", 401);
|
|
57
|
+
if (response.status === 403)
|
|
58
|
+
throw new HostApiError("auth", "The token cannot read this repository; it needs read access to its code, requests and pipelines.", 403);
|
|
59
|
+
if (response.status === 404)
|
|
60
|
+
throw new HostApiError("not-found", "The host has no such repository, or the token cannot see it.", 404);
|
|
61
|
+
if (response.status >= 400) {
|
|
62
|
+
const message = json && typeof json === "object" ? json.message ?? json.error : undefined;
|
|
63
|
+
throw new HostApiError("failed", `${new URL(url).host} answered ${response.status}${message ? `: ${typeof message === "string" ? message : JSON.stringify(message)}` : ""}`.slice(0, 500), response.status, json);
|
|
64
|
+
}
|
|
65
|
+
return { status: response.status, json: json, headers: response.headers };
|
|
66
|
+
}
|
|
67
|
+
/** An https link, or nothing: hosts' links are shown and opened as-is. */
|
|
68
|
+
export function safeLink(value) {
|
|
69
|
+
return typeof value === "string" && /^https?:\/\//.test(value) ? value.slice(0, 2048) : undefined;
|
|
70
|
+
}
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
import type { Json } from "./protocol.js";
|
|
2
|
+
/** Where a repository's pull or merge requests live. Phren supports three git
|
|
3
|
+
* hosts: GitHub, GitLab and gitboy (self-hosted, any domain). The host is read
|
|
4
|
+
* from the remote's URL; a self-hosted GitLab or gitboy is named by an
|
|
5
|
+
* override, per remote or per domain, in git config:
|
|
6
|
+
*
|
|
7
|
+
* git config remote.origin.phrenHost gitlab # this repository's origin
|
|
8
|
+
* git config --global phren.git.example.com.host gitboy # every repo on that domain
|
|
9
|
+
*
|
|
10
|
+
* Each host is a provider with one small interface: list the requests and
|
|
11
|
+
* the checked-out branch's own with its checks, and open one. */
|
|
12
|
+
export type HostKind = "github" | "gitlab" | "gitboy";
|
|
13
|
+
export declare const HOST_KINDS: readonly HostKind[];
|
|
14
|
+
export interface HostTerms {
|
|
15
|
+
short: string;
|
|
16
|
+
long: string;
|
|
17
|
+
ref: string;
|
|
18
|
+
}
|
|
19
|
+
export interface GitHost {
|
|
20
|
+
kind: HostKind | null;
|
|
21
|
+
/** The product name a link reads ("View on GitLab"), or "the git host". */
|
|
22
|
+
name: string;
|
|
23
|
+
/** The remote's domain and the repository's web address, when known. */
|
|
24
|
+
domain: string | null;
|
|
25
|
+
webUrl: string | null;
|
|
26
|
+
remote: string | null;
|
|
27
|
+
/** How the kind was found: from the URL, from an override, or not at all. */
|
|
28
|
+
source: "url" | "remote-override" | "domain-override" | "none";
|
|
29
|
+
terms: HostTerms;
|
|
30
|
+
/** False for a provider that is not built yet (GitLab, gitboy). */
|
|
31
|
+
supported: boolean;
|
|
32
|
+
}
|
|
33
|
+
export interface RequestList {
|
|
34
|
+
available: boolean;
|
|
35
|
+
reason?: string;
|
|
36
|
+
message?: string;
|
|
37
|
+
pulls: Json[];
|
|
38
|
+
current: Json | null;
|
|
39
|
+
/** Where the token came from and who it signs in as, when the host says. */
|
|
40
|
+
account?: {
|
|
41
|
+
source: string;
|
|
42
|
+
user?: string;
|
|
43
|
+
};
|
|
44
|
+
}
|
|
45
|
+
export interface GitHostProvider {
|
|
46
|
+
readonly kind: HostKind;
|
|
47
|
+
readonly name: string;
|
|
48
|
+
readonly terms: HostTerms;
|
|
49
|
+
readonly supported: boolean;
|
|
50
|
+
/** Open requests and the checked-out branch's own (any state) with its checks. */
|
|
51
|
+
list(root: string, branch: string, host: GitHost): Promise<RequestList>;
|
|
52
|
+
/** Open a request from `branch` into the default branch, titled from its commits. */
|
|
53
|
+
open(root: string, branch: string, draft: boolean, host: GitHost): Promise<Json>;
|
|
54
|
+
/** Merge request `number`, only while its head is still `expectedHeadSha`
|
|
55
|
+
* when one is given. The host's own refusal (checks, approvals, conflicts)
|
|
56
|
+
* comes back as `{ ok: false, reason: "blocked", message }`. */
|
|
57
|
+
merge(root: string, request: MergeRequest, host: GitHost): Promise<Json>;
|
|
58
|
+
/** Who a token signs in as, for Connect; HTTP hosts only. */
|
|
59
|
+
whoami?(root: string, host: GitHost, token: string): Promise<{
|
|
60
|
+
user: string;
|
|
61
|
+
}>;
|
|
62
|
+
}
|
|
63
|
+
export type MergeMethod = "merge" | "squash" | "rebase";
|
|
64
|
+
export interface MergeRequest {
|
|
65
|
+
number: number;
|
|
66
|
+
method: MergeMethod;
|
|
67
|
+
expectedHeadSha?: string;
|
|
68
|
+
deleteBranch?: boolean;
|
|
69
|
+
}
|
|
70
|
+
/** `git@host:owner/repo.git`, `ssh://git@host:2222/owner/repo.git`,
|
|
71
|
+
* `https://user@host/owner/repo` → the domain and the repository path. */
|
|
72
|
+
export declare function parseRemoteUrl(url: string): {
|
|
73
|
+
domain: string;
|
|
74
|
+
path: string;
|
|
75
|
+
} | null;
|
|
76
|
+
/** The kind a domain implies on its own: the public hosts by name, a
|
|
77
|
+
* self-hosted one when its first label says so (`gitlab.example.com`). */
|
|
78
|
+
export declare function kindFromDomain(domain: string): HostKind | null;
|
|
79
|
+
/** Which host a repository's remote is on, overrides first. */
|
|
80
|
+
export declare function detectHost(root: string, branch: string): Promise<GitHost>;
|
|
81
|
+
export declare function hostInfo(kind: HostKind | null, where: Pick<GitHost, "domain" | "webUrl" | "remote" | "source">): GitHost;
|
|
82
|
+
export declare function providerFor(host: GitHost): GitHostProvider | null;
|
|
83
|
+
/** Why there is no list: an unknown host says how to name it. */
|
|
84
|
+
export declare function unknownHost(host: GitHost): RequestList;
|
|
85
|
+
/** A check rollup as one word: any failure fails, anything unfinished is
|
|
86
|
+
* pending, and only finished successes (or skips) pass. No checks is null. */
|
|
87
|
+
export declare function checkRollup(items: unknown): "passing" | "failing" | "pending" | null;
|
|
88
|
+
/** Each check as clients list it: a name, the workflow that ran it, one state
|
|
89
|
+
* word and its page. Check runs and commit statuses read alike; failing
|
|
90
|
+
* first, then pending, then the rest, at most 100. */
|
|
91
|
+
export declare function checkRuns(items: unknown): Json[];
|
|
92
|
+
export declare const PROVIDERS: Record<HostKind, GitHostProvider>;
|