@recoder.xyz/rithub 0.2.1 → 0.3.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.
@@ -0,0 +1,80 @@
1
+ // `rit login`'s real browser sign-in: RFC 8628-shaped device-authorization
2
+ // flow against the new server-side route this pass adds
3
+ // (apps/rithub-device-auth, proxied at https://rithub.dev/api/rit/device/*
4
+ // and https://rithub.dev/device -- see that app's README for the server
5
+ // side). Internally the server wraps Rithub's own OAuth2 "Rit CLI"
6
+ // application (confirmed registered 2026-11-18, client_id unchanged here),
7
+ // so the token this returns is a real Rithub OAuth2 access token, not a
8
+ // classic PAT -- it works identically against `/api/v1/*` either way
9
+ // (same header shape handled by fetchUser in auth.mjs: `Authorization:
10
+ // token <value>` -- Gitea accepts an OAuth2 access token there too).
11
+ import { CliError } from "./init.mjs";
12
+
13
+ const POLL_FLOOR_MS = 2000; // never hammer the server even if the returned interval is 0/missing
14
+
15
+ function sleep(ms) {
16
+ return new Promise((resolve) => setTimeout(resolve, ms));
17
+ }
18
+
19
+ async function postJson(io, apiUrl, path, json) {
20
+ const res = await io.fetchImpl(`${apiUrl}${path}`, {
21
+ method: "POST",
22
+ headers: { accept: "application/json", "content-type": "application/json", "user-agent": "rithub-cli" },
23
+ body: JSON.stringify(json ?? {}),
24
+ });
25
+ const text = await res.text();
26
+ let body = null;
27
+ try {
28
+ body = text ? JSON.parse(text) : null;
29
+ } catch {
30
+ body = null;
31
+ }
32
+ return { status: res.status, body };
33
+ }
34
+
35
+ /** Starts the device flow: prints the code + URL, best-effort opens the
36
+ * browser, then polls until the human approves (or the code expires / is
37
+ * denied). Returns the access token on success; throws CliError otherwise.
38
+ * `io.sleep` is honored if a caller (tests) supplies one, so this never
39
+ * needs a real wall-clock wait under test. */
40
+ export async function runDeviceLogin(io, apiUrl) {
41
+ const { status, body } = await postJson(io, apiUrl, "/api/rit/device/code", {});
42
+ if (status !== 200 || !body?.device_code || !body?.user_code) {
43
+ throw new CliError(
44
+ `could not start device sign-in against ${apiUrl} (HTTP ${status}): ${body?.message ?? "unknown error"}. Pass a token instead: \`rit login --token <token>\` (get one at ${apiUrl}/user/settings/applications).`,
45
+ { code: "device_flow_unavailable" }
46
+ );
47
+ }
48
+
49
+ const verificationUrl = body.verification_uri_complete ?? body.verification_uri;
50
+ io.out(`First, copy your code: ${body.user_code}`);
51
+ io.out(`Then open this URL in your browser: ${body.verification_uri}`);
52
+ io.openUrl?.(verificationUrl); // best-effort; the code + URL above are already printed either way
53
+
54
+ const intervalMs = Math.max(POLL_FLOOR_MS, (body.interval ?? 5) * 1000);
55
+ const deadline = (io.now?.() ?? Date.now()) + (body.expires_in ?? 600) * 1000;
56
+ let currentIntervalMs = intervalMs;
57
+
58
+ while ((io.now?.() ?? Date.now()) < deadline) {
59
+ await (io.sleep ?? sleep)(currentIntervalMs);
60
+ const poll = await postJson(io, apiUrl, "/api/rit/device/token", { device_code: body.device_code });
61
+ const outcome = poll.body?.error ?? (poll.status === 200 && poll.body?.access_token ? null : "unknown_error");
62
+
63
+ if (poll.status === 200 && poll.body?.access_token) {
64
+ return { token: poll.body.access_token, scope: poll.body.scope ?? null };
65
+ }
66
+ if (outcome === "authorization_pending") continue;
67
+ if (outcome === "slow_down") {
68
+ currentIntervalMs += 5000;
69
+ continue;
70
+ }
71
+ if (outcome === "expired_token") {
72
+ throw new CliError("the sign-in code expired before it was approved -- run `rit login` again.", { code: "device_flow_expired" });
73
+ }
74
+ if (outcome === "access_denied") {
75
+ throw new CliError("sign-in was denied in the browser.", { code: "device_flow_denied" });
76
+ }
77
+ throw new CliError(`device sign-in failed (HTTP ${poll.status}): ${poll.body?.message ?? outcome ?? "unknown error"}`, { code: "device_flow_error" });
78
+ }
79
+ throw new CliError("the sign-in code expired before it was approved -- run `rit login` again.", { code: "device_flow_expired" });
80
+ }
package/src/http.mjs ADDED
@@ -0,0 +1,82 @@
1
+ // Shared HTTP helpers for every gh-parity command added on top of the
2
+ // original login/clone/repo-create/push surface (src/repo.mjs, src/init.mjs
3
+ // and src/auth.mjs each keep their own small, already-tested copy of this
4
+ // rather than being refactored to import it, to avoid touching working code
5
+ // for this change -- see the CLI's README "Design notes" section).
6
+ //
7
+ // All of it talks to Rithub's own REST API at `/api/v1` with a plain
8
+ // `fetch` -- no SDK, same choice the rest of this package already made.
9
+
10
+ /** One JSON request/response round trip. Always resolves (never throws on a
11
+ * non-2xx status) so callers can turn a specific status into a clear
12
+ * CliError message instead of an unhandled rejection. */
13
+ export async function apiCall(io, apiUrl, path, init, token) {
14
+ const headers = {
15
+ accept: "application/json",
16
+ "user-agent": "rithub-cli",
17
+ ...(init?.body ? { "content-type": "application/json" } : {}),
18
+ ...(token ? { authorization: `token ${token}` } : {}),
19
+ ...(init?.headers ?? {}),
20
+ };
21
+ const res = await io.fetchImpl(`${apiUrl}${path}`, { ...init, headers });
22
+ const text = await res.text();
23
+ let body = null;
24
+ try {
25
+ body = text ? JSON.parse(text) : null;
26
+ } catch {
27
+ body = { message: text.slice(0, 300) };
28
+ }
29
+ return { status: res.status, body, raw: text };
30
+ }
31
+
32
+ /** Same request, but returns the raw response body as text with no JSON
33
+ * parsing attempt -- for endpoints that answer with a diff/patch, not JSON
34
+ * (`rit change diff`). */
35
+ export async function apiCallRaw(io, apiUrl, path, init, token) {
36
+ // Bug found + fixed 2026-12-01: `init.headers` (e.g. runApi's
37
+ // `content-type: application/json` for a PATCH/POST body) was built by
38
+ // the caller but never actually merged in here, so `rit api` with
39
+ // `--method PATCH`/`--input` sent no Content-Type at all -- confirmed
40
+ // live against rithub.dev: the server answered a 422 "Unsupported
41
+ // Content-Type" instead of applying the PATCH.
42
+ const headers = {
43
+ accept: init?.accept ?? "*/*",
44
+ "user-agent": "rithub-cli",
45
+ ...(token ? { authorization: `token ${token}` } : {}),
46
+ ...(init?.headers ?? {}),
47
+ };
48
+ const res = await io.fetchImpl(`${apiUrl}${path}`, { ...init, headers });
49
+ const text = await res.text();
50
+ return { status: res.status, text };
51
+ }
52
+
53
+ /** Uploads a local file as a release asset (`POST
54
+ * /repos/{owner}/{repo}/releases/{id}/assets`, multipart/form-data) --
55
+ * the one command here that isn't plain JSON in, JSON out. */
56
+ export async function uploadAsset(io, apiUrl, path, token, fileBuffer, fileName) {
57
+ const form = new FormData();
58
+ form.append("attachment", new Blob([fileBuffer]), fileName);
59
+ const res = await io.fetchImpl(`${apiUrl}${path}${buildQuery({ name: fileName })}`, {
60
+ method: "POST",
61
+ headers: { accept: "application/json", "user-agent": "rithub-cli", ...(token ? { authorization: `token ${token}` } : {}) },
62
+ body: form,
63
+ });
64
+ const text = await res.text();
65
+ let body = null;
66
+ try {
67
+ body = text ? JSON.parse(text) : null;
68
+ } catch {
69
+ body = { message: text.slice(0, 300) };
70
+ }
71
+ return { status: res.status, body };
72
+ }
73
+
74
+ /** `?a=b&c=d`, skipping any key whose value is `undefined`/`null`/`""` so
75
+ * optional filters don't show up as the literal string "undefined". */
76
+ export function buildQuery(params) {
77
+ const entries = Object.entries(params ?? {}).filter(([, v]) => v !== undefined && v !== null && v !== "");
78
+ if (entries.length === 0) return "";
79
+ const qs = new URLSearchParams();
80
+ for (const [k, v] of entries) qs.set(k, String(v));
81
+ return `?${qs.toString()}`;
82
+ }
package/src/issue.mjs ADDED
@@ -0,0 +1,77 @@
1
+ // `rit issue list/create/view/close/reopen/comment/edit` -- the issue half
2
+ // of the gh-parity command set, all against
3
+ // `/api/v1/repos/{owner}/{repo}/issues`.
4
+ import { CliError } from "./init.mjs";
5
+ import { resolveRepoArg, requireSession } from "./repo-arg.mjs";
6
+ import { apiCall, buildQuery } from "./http.mjs";
7
+
8
+ function issuesPath(r, suffix = "") {
9
+ return `/api/v1/repos/${encodeURIComponent(r.owner)}/${encodeURIComponent(r.repo)}/issues${suffix}`;
10
+ }
11
+
12
+ export async function runIssueList(options, io) {
13
+ const r = resolveRepoArg(io, options);
14
+ const path = issuesPath(r) + buildQuery({ state: options.state ?? "open", q: options.search, page: options.page, limit: options.limit ?? 30 });
15
+ const { status, body } = await apiCall(io, r.apiUrl, path, { method: "GET" }, r.session?.token);
16
+ if (status !== 200) throw new CliError(`could not list issues on ${r.owner}/${r.repo} (HTTP ${status}): ${body?.message ?? "unknown error"}`, { code: "network_error" });
17
+ return { owner: r.owner, repo: r.repo, issues: (body ?? []).map((i) => ({ number: i.number, title: i.title, state: i.state, html_url: i.html_url })) };
18
+ }
19
+
20
+ export async function runIssueView(options, io) {
21
+ const r = resolveRepoArg(io, options);
22
+ const { status, body } = await apiCall(io, r.apiUrl, issuesPath(r, `/${options.number}`), { method: "GET" }, r.session?.token);
23
+ if (status !== 200) throw new CliError(`issue #${options.number} not found on ${r.owner}/${r.repo} (HTTP ${status})`, { code: "not_found" });
24
+ return { owner: r.owner, repo: r.repo, number: body.number, title: body.title, state: body.state, body: body.body, html_url: body.html_url };
25
+ }
26
+
27
+ export async function runIssueCreate(options, io) {
28
+ const r = resolveRepoArg(io, options);
29
+ requireSession(r);
30
+ if (!options.title) throw new CliError("`rit issue create` needs --title <text>", { code: "invalid_argument" });
31
+ const { status, body } = await apiCall(
32
+ io,
33
+ r.apiUrl,
34
+ issuesPath(r),
35
+ { method: "POST", body: JSON.stringify({ title: options.title, body: options.body ?? "" }) },
36
+ r.session.token
37
+ );
38
+ if (status !== 201) throw new CliError(`could not create the issue (HTTP ${status}): ${body?.message ?? "unknown error"}`, { code: "create_failed" });
39
+ return { owner: r.owner, repo: r.repo, number: body.number, html_url: body.html_url };
40
+ }
41
+
42
+ async function setIssueState(options, io, state) {
43
+ const r = resolveRepoArg(io, options);
44
+ requireSession(r);
45
+ const { status, body } = await apiCall(io, r.apiUrl, issuesPath(r, `/${options.number}`), { method: "PATCH", body: JSON.stringify({ state }) }, r.session.token);
46
+ // Confirmed live 2026-12-01 against this engine build: a state-only PATCH
47
+ // on /issues/{number} answers 201, not the 200 every other issue PATCH
48
+ // (e.g. runIssueEdit below) returns -- the state change itself lands
49
+ // correctly either way (re-verified by re-fetching the issue), the status
50
+ // code was just the wrong thing to gate on.
51
+ if (status !== 200 && status !== 201) throw new CliError(`could not ${state === "closed" ? "close" : "reopen"} issue #${options.number} (HTTP ${status}): ${body?.message ?? "unknown error"}`, { code: "update_failed" });
52
+ return { owner: r.owner, repo: r.repo, number: options.number, state: body.state };
53
+ }
54
+
55
+ export const runIssueClose = (options, io) => setIssueState(options, io, "closed");
56
+ export const runIssueReopen = (options, io) => setIssueState(options, io, "open");
57
+
58
+ export async function runIssueEdit(options, io) {
59
+ const r = resolveRepoArg(io, options);
60
+ requireSession(r);
61
+ const patch = {};
62
+ if (options.title !== undefined) patch.title = options.title;
63
+ if (options.body !== undefined) patch.body = options.body;
64
+ if (Object.keys(patch).length === 0) throw new CliError("`rit issue edit` needs --title and/or --body", { code: "invalid_argument" });
65
+ const { status, body } = await apiCall(io, r.apiUrl, issuesPath(r, `/${options.number}`), { method: "PATCH", body: JSON.stringify(patch) }, r.session.token);
66
+ if (status !== 200) throw new CliError(`could not edit issue #${options.number} (HTTP ${status}): ${body?.message ?? "unknown error"}`, { code: "update_failed" });
67
+ return { owner: r.owner, repo: r.repo, number: options.number, title: body.title };
68
+ }
69
+
70
+ export async function runIssueComment(options, io) {
71
+ const r = resolveRepoArg(io, options);
72
+ requireSession(r);
73
+ if (!options.body) throw new CliError("`rit issue comment` needs --body <text>", { code: "invalid_argument" });
74
+ const { status, body } = await apiCall(io, r.apiUrl, issuesPath(r, `/${options.number}/comments`), { method: "POST", body: JSON.stringify({ body: options.body }) }, r.session.token);
75
+ if (status !== 201) throw new CliError(`could not comment on issue #${options.number} (HTTP ${status}): ${body?.message ?? "unknown error"}`, { code: "create_failed" });
76
+ return { owner: r.owner, repo: r.repo, number: options.number, id: body.id, html_url: body.html_url };
77
+ }
package/src/label.mjs ADDED
@@ -0,0 +1,31 @@
1
+ // `rit label list/create`, against `/api/v1/repos/{owner}/{repo}/labels`.
2
+ import { CliError } from "./init.mjs";
3
+ import { resolveRepoArg, requireSession } from "./repo-arg.mjs";
4
+ import { apiCall } from "./http.mjs";
5
+
6
+ function labelsPath(r) {
7
+ return `/api/v1/repos/${encodeURIComponent(r.owner)}/${encodeURIComponent(r.repo)}/labels`;
8
+ }
9
+
10
+ export async function runLabelList(options, io) {
11
+ const r = resolveRepoArg(io, options);
12
+ const { status, body } = await apiCall(io, r.apiUrl, labelsPath(r), { method: "GET" }, r.session?.token);
13
+ if (status !== 200) throw new CliError(`could not list labels on ${r.owner}/${r.repo} (HTTP ${status}): ${body?.message ?? "unknown error"}`, { code: "network_error" });
14
+ return { owner: r.owner, repo: r.repo, labels: (body ?? []).map((l) => ({ name: l.name, color: l.color, description: l.description })) };
15
+ }
16
+
17
+ export async function runLabelCreate(options, io) {
18
+ const r = resolveRepoArg(io, options);
19
+ requireSession(r);
20
+ if (!options.name) throw new CliError("`rit label create` needs a name: `rit label create <name> --color <hex>`", { code: "invalid_argument" });
21
+ if (!options.color) throw new CliError("`rit label create` needs --color <hex> (e.g. ff0000)", { code: "invalid_argument" });
22
+ const { status, body } = await apiCall(
23
+ io,
24
+ r.apiUrl,
25
+ labelsPath(r),
26
+ { method: "POST", body: JSON.stringify({ name: options.name, color: options.color.replace(/^#/, ""), description: options.description ?? "" }) },
27
+ r.session.token
28
+ );
29
+ if (status !== 201) throw new CliError(`could not create label ${options.name} (HTTP ${status}): ${body?.message ?? "unknown error"}`, { code: "create_failed" });
30
+ return { owner: r.owner, repo: r.repo, id: body.id, name: body.name, color: body.color };
31
+ }
@@ -0,0 +1,31 @@
1
+ // `rit milestone list/create`, against
2
+ // `/api/v1/repos/{owner}/{repo}/milestones`.
3
+ import { CliError } from "./init.mjs";
4
+ import { resolveRepoArg, requireSession } from "./repo-arg.mjs";
5
+ import { apiCall } from "./http.mjs";
6
+
7
+ function milestonesPath(r) {
8
+ return `/api/v1/repos/${encodeURIComponent(r.owner)}/${encodeURIComponent(r.repo)}/milestones`;
9
+ }
10
+
11
+ export async function runMilestoneList(options, io) {
12
+ const r = resolveRepoArg(io, options);
13
+ const { status, body } = await apiCall(io, r.apiUrl, milestonesPath(r), { method: "GET" }, r.session?.token);
14
+ if (status !== 200) throw new CliError(`could not list milestones on ${r.owner}/${r.repo} (HTTP ${status}): ${body?.message ?? "unknown error"}`, { code: "network_error" });
15
+ return { owner: r.owner, repo: r.repo, milestones: (body ?? []).map((m) => ({ id: m.id, title: m.title, state: m.state, due_on: m.due_on })) };
16
+ }
17
+
18
+ export async function runMilestoneCreate(options, io) {
19
+ const r = resolveRepoArg(io, options);
20
+ requireSession(r);
21
+ if (!options.title) throw new CliError("`rit milestone create` needs a title: `rit milestone create <title>`", { code: "invalid_argument" });
22
+ const { status, body } = await apiCall(
23
+ io,
24
+ r.apiUrl,
25
+ milestonesPath(r),
26
+ { method: "POST", body: JSON.stringify({ title: options.title, description: options.description ?? "", due_on: options.due }) },
27
+ r.session.token
28
+ );
29
+ if (status !== 201) throw new CliError(`could not create milestone ${options.title} (HTTP ${status}): ${body?.message ?? "unknown error"}`, { code: "create_failed" });
30
+ return { owner: r.owner, repo: r.repo, id: body.id, title: body.title };
31
+ }
@@ -0,0 +1,18 @@
1
+ // Best-effort "open this URL in the default browser" for `rit login`
2
+ // (interactive sign-in) and `rit browse`. Never throws and never blocks:
3
+ // a headless box or a sandboxed agent with no display simply won't have
4
+ // anything happen, which is fine -- the URL is always printed too.
5
+ import { spawn } from "node:child_process";
6
+
7
+ export function openUrl(url) {
8
+ try {
9
+ const [cmd, args] =
10
+ process.platform === "darwin" ? ["open", [url]] : process.platform === "win32" ? ["cmd", ["/c", "start", "", url]] : ["xdg-open", [url]];
11
+ const child = spawn(cmd, args, { stdio: "ignore", detached: true });
12
+ child.on("error", () => {}); // no browser/display available -- caller already printed the URL
13
+ child.unref();
14
+ return true;
15
+ } catch {
16
+ return false;
17
+ }
18
+ }
package/src/org.mjs ADDED
@@ -0,0 +1,34 @@
1
+ // `rit org list/view`, `rit user view`.
2
+ import { CliError } from "./init.mjs";
3
+ import { resolveSession } from "./config.mjs";
4
+ import { apiCall } from "./http.mjs";
5
+
6
+ function baseApiUrl(io, options, session) {
7
+ return session?.apiUrl ?? (options.apiUrl ?? io.env.RITHUB_API_URL ?? "https://rithub.dev").replace(/\/+$/, "");
8
+ }
9
+
10
+ export async function runOrgList(options, io) {
11
+ const session = resolveSession(io, { apiUrl: options.apiUrl });
12
+ if (!session) throw new CliError("not logged in -- run `rit login` first", { code: "not_logged_in" });
13
+ const { status, body } = await apiCall(io, session.apiUrl, "/api/v1/user/orgs", { method: "GET" }, session.token);
14
+ if (status !== 200) throw new CliError(`could not list organizations (HTTP ${status}): ${body?.message ?? "unknown error"}`, { code: "network_error" });
15
+ return { orgs: (body ?? []).map((o) => ({ name: o.username ?? o.name, html_url: o.website || `${session.apiUrl}/${o.username}` })) };
16
+ }
17
+
18
+ export async function runOrgView(options, io) {
19
+ const session = resolveSession(io, { apiUrl: options.apiUrl });
20
+ const apiUrl = baseApiUrl(io, options, session);
21
+ if (!options.name) throw new CliError("`rit org view` needs a name: `rit org view <org>`", { code: "invalid_argument" });
22
+ const { status, body } = await apiCall(io, apiUrl, `/api/v1/orgs/${encodeURIComponent(options.name)}`, { method: "GET" }, session?.token);
23
+ if (status !== 200) throw new CliError(`org ${options.name} not found (HTTP ${status})`, { code: "not_found" });
24
+ return { name: body.username ?? body.name, description: body.description, html_url: `${apiUrl}/${body.username ?? options.name}` };
25
+ }
26
+
27
+ export async function runUserView(options, io) {
28
+ const session = resolveSession(io, { apiUrl: options.apiUrl });
29
+ const apiUrl = baseApiUrl(io, options, session);
30
+ if (!options.name) throw new CliError("`rit user view` needs a username: `rit user view <username>`", { code: "invalid_argument" });
31
+ const { status, body } = await apiCall(io, apiUrl, `/api/v1/users/${encodeURIComponent(options.name)}`, { method: "GET" }, session?.token);
32
+ if (status !== 200) throw new CliError(`user ${options.name} not found (HTTP ${status})`, { code: "not_found" });
33
+ return { login: body.login, full_name: body.full_name, html_url: `${apiUrl}/${body.login}` };
34
+ }
@@ -0,0 +1,70 @@
1
+ // `rit release create/list/view/delete` (+ asset upload on create), against
2
+ // `/api/v1/repos/{owner}/{repo}/releases`. view/delete take the tag name
3
+ // directly (Rithub's own `/releases/tags/{tag}` route) so callers never have to
4
+ // resolve a numeric release id first.
5
+ import { readFileSync } from "node:fs";
6
+ import { basename } from "node:path";
7
+ import { CliError } from "./init.mjs";
8
+ import { resolveRepoArg, requireSession } from "./repo-arg.mjs";
9
+ import { apiCall, buildQuery, uploadAsset } from "./http.mjs";
10
+
11
+ function releasesPath(r, suffix = "") {
12
+ return `/api/v1/repos/${encodeURIComponent(r.owner)}/${encodeURIComponent(r.repo)}/releases${suffix}`;
13
+ }
14
+
15
+ export async function runReleaseList(options, io) {
16
+ const r = resolveRepoArg(io, options);
17
+ const { status, body } = await apiCall(io, r.apiUrl, releasesPath(r) + buildQuery({ page: options.page, limit: options.limit ?? 30 }), { method: "GET" }, r.session?.token);
18
+ if (status !== 200) throw new CliError(`could not list releases on ${r.owner}/${r.repo} (HTTP ${status}): ${body?.message ?? "unknown error"}`, { code: "network_error" });
19
+ return { owner: r.owner, repo: r.repo, releases: (body ?? []).map((rel) => ({ tag: rel.tag_name, name: rel.name, draft: rel.draft, prerelease: rel.prerelease, html_url: rel.html_url })) };
20
+ }
21
+
22
+ export async function runReleaseView(options, io) {
23
+ const r = resolveRepoArg(io, options);
24
+ const { status, body } = await apiCall(io, r.apiUrl, releasesPath(r, `/tags/${encodeURIComponent(options.tag)}`), { method: "GET" }, r.session?.token);
25
+ if (status !== 200) throw new CliError(`release ${options.tag} not found on ${r.owner}/${r.repo} (HTTP ${status})`, { code: "not_found" });
26
+ return { owner: r.owner, repo: r.repo, tag: body.tag_name, name: body.name, body: body.body, html_url: body.html_url, assets: (body.assets ?? []).map((a) => a.name) };
27
+ }
28
+
29
+ export async function runReleaseDelete(options, io) {
30
+ const r = resolveRepoArg(io, options);
31
+ requireSession(r);
32
+ const { status, body } = await apiCall(io, r.apiUrl, releasesPath(r, `/tags/${encodeURIComponent(options.tag)}`), { method: "DELETE" }, r.session.token);
33
+ if (status !== 204 && status !== 200) throw new CliError(`could not delete release ${options.tag} (HTTP ${status}): ${body?.message ?? "unknown error"}`, { code: "delete_failed" });
34
+ return { owner: r.owner, repo: r.repo, tag: options.tag, deleted: true };
35
+ }
36
+
37
+ /** `rit release create <tag> [--title <t>] [--notes <text>] [--draft]
38
+ * [--prerelease] [--asset <path>...]`: one or more `--asset` files are
39
+ * uploaded after the release itself is created, same order `gh release
40
+ * create` does it in. */
41
+ export async function runReleaseCreate(options, io) {
42
+ const r = resolveRepoArg(io, options);
43
+ requireSession(r);
44
+ if (!options.tag) throw new CliError("`rit release create` needs a tag: `rit release create <tag>`", { code: "invalid_argument" });
45
+ const { status, body } = await apiCall(
46
+ io,
47
+ r.apiUrl,
48
+ releasesPath(r),
49
+ { method: "POST", body: JSON.stringify({ tag_name: options.tag, name: options.title ?? options.tag, body: options.notes ?? "", draft: !!options.draft, prerelease: !!options.prerelease }) },
50
+ r.session.token
51
+ );
52
+ if (status !== 201) throw new CliError(`could not create release ${options.tag} (HTTP ${status}): ${body?.message ?? "unknown error"}`, { code: "create_failed" });
53
+
54
+ const assetPaths = options.assets ?? [];
55
+ const uploaded = [];
56
+ for (const assetPath of assetPaths) {
57
+ const fileName = basename(assetPath);
58
+ let fileBuffer;
59
+ try {
60
+ fileBuffer = readFileSync(assetPath);
61
+ } catch (err) {
62
+ throw new CliError(`could not read asset file ${assetPath}: ${err.message}`, { code: "invalid_argument" });
63
+ }
64
+ const uploadResult = await uploadAsset(io, r.apiUrl, releasesPath(r, `/${body.id}/assets`), r.session.token, fileBuffer, fileName);
65
+ if (uploadResult.status !== 201) throw new CliError(`release ${options.tag} was created, but uploading ${fileName} failed (HTTP ${uploadResult.status}): ${uploadResult.body?.message ?? "unknown error"}`, { code: "upload_failed" });
66
+ uploaded.push(fileName);
67
+ }
68
+
69
+ return { owner: r.owner, repo: r.repo, tag: options.tag, html_url: body.html_url, assets: uploaded };
70
+ }
@@ -0,0 +1,81 @@
1
+ // Every gh-parity command that acts on one repo (issue/change/release/
2
+ // branch/label/milestone/secret/webhook) needs an owner+repo pair. `gh`
3
+ // itself infers it from the current directory's git remote unless
4
+ // `--repo owner/name` is given; this is that same lookup for Rithub.
5
+ import { CliError } from "./init.mjs";
6
+ import { resolveSession } from "./config.mjs";
7
+
8
+ const NAME_RE = /^[A-Za-z0-9._-]{1,100}$/;
9
+
10
+ export function parseOwnerRepo(value) {
11
+ if (typeof value !== "string") return null;
12
+ const parts = value.split("/").filter(Boolean);
13
+ if (parts.length !== 2 || !NAME_RE.test(parts[0]) || !NAME_RE.test(parts[1])) return null;
14
+ return { owner: parts[0], repo: parts[1].replace(/\.git$/, "") };
15
+ }
16
+
17
+ /** Pulls `{ owner, repo }` out of a git remote URL, https or ssh, with or
18
+ * without a `.git` suffix -- `https://rithub.dev/owner/repo.git`,
19
+ * `git@rithub.dev:owner/repo.git`, or the same shapes with a token
20
+ * embedded in the https form. Returns `null` for anything else (a remote
21
+ * pointing at a different host entirely, e.g. a GitHub `origin` living
22
+ * alongside a Rithub `rithub` remote in the same checkout). */
23
+ export function parseRemoteUrl(url, apiHost) {
24
+ if (typeof url !== "string") return null;
25
+ const sshMatch = url.match(/^git@([^:]+):(.+)$/);
26
+ const path = sshMatch ? sshMatch[2] : (() => {
27
+ try {
28
+ const u = new URL(url);
29
+ return u.host === apiHost ? u.pathname.replace(/^\/+/, "") : null;
30
+ } catch {
31
+ return null;
32
+ }
33
+ })();
34
+ if (sshMatch && sshMatch[1] !== apiHost) return null;
35
+ if (!path) return null;
36
+ const parsed = parseOwnerRepo(path.replace(/\.git$/, ""));
37
+ return parsed;
38
+ }
39
+
40
+ /** `--repo owner/name` wins if given; otherwise reads `git remote -v` in
41
+ * `cwd` and uses the first remote that points at the configured Rithub
42
+ * host -- the `rithub` remote `rit push` sets up if present, else whatever
43
+ * matches first. Throws a clear, actionable error rather than letting a
44
+ * later API call fail with a confusing 404. */
45
+ export function resolveRepoArg(io, options) {
46
+ const session = resolveSession(io, { apiUrl: options.apiUrl });
47
+ const apiUrl = session?.apiUrl ?? (options.apiUrl ?? io.env.RITHUB_API_URL ?? "https://rithub.dev").replace(/\/+$/, "");
48
+ const apiHost = new URL(apiUrl).host;
49
+
50
+ if (options.repo) {
51
+ const target = parseOwnerRepo(options.repo);
52
+ if (!target) throw new CliError(`--repo "${options.repo}" doesn't look like owner/name`, { code: "invalid_argument" });
53
+ return { ...target, apiUrl, session };
54
+ }
55
+
56
+ const remotes = io.run("git", ["remote", "-v"], options.cwd ?? io.cwd);
57
+ if (remotes.ok) {
58
+ const lines = remotes.output.split("\n").filter((l) => l.includes("(fetch)"));
59
+ const candidates = lines
60
+ .map((l) => {
61
+ const [name, url] = l.split(/\s+/);
62
+ return { name, parsed: parseRemoteUrl(url, apiHost) };
63
+ })
64
+ .filter((c) => c.parsed);
65
+ const best = candidates.find((c) => c.name === "rithub") ?? candidates.find((c) => c.name === "origin") ?? candidates[0];
66
+ if (best) return { ...best.parsed, apiUrl, session };
67
+ }
68
+
69
+ throw new CliError(
70
+ `could not work out owner/repo -- pass --repo <owner/name>, or run this inside a checkout with a git remote pointing at ${apiHost}`,
71
+ { code: "no_repo" }
72
+ );
73
+ }
74
+
75
+ /** Repo-scoped commands all need a token (issues/PRs/releases are visible
76
+ * for public repos without one, but creating/editing anything needs
77
+ * write access) -- shared check so each command doesn't repeat it. */
78
+ export function requireSession(repoArg) {
79
+ if (!repoArg.session) throw new CliError("not logged in -- run `rit login` first", { code: "not_logged_in" });
80
+ return repoArg.session;
81
+ }
@@ -0,0 +1,132 @@
1
+ // `rit repo list/view/fork/delete/rename/edit/sync/import/archive` -- the
2
+ // rest of the gh-parity repo surface, alongside `rit repo create` and
3
+ // `rit clone`/`rit push` in src/repo.mjs. Kept in its own file (small
4
+ // files over one large one) since src/repo.mjs's `clone`/`create`/`push`
5
+ // already carry careful token-handling comments that don't need repeating
6
+ // nine more times.
7
+ import { CliError } from "./init.mjs";
8
+ import { parseTarget } from "./repo.mjs";
9
+ import { resolveSession } from "./config.mjs";
10
+ import { apiCall, buildQuery } from "./http.mjs";
11
+
12
+ function repoPath(owner, repo, suffix = "") {
13
+ return `/api/v1/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}${suffix}`;
14
+ }
15
+
16
+ function session(io, options, { required = false } = {}) {
17
+ const s = resolveSession(io, { apiUrl: options.apiUrl });
18
+ if (required && !s) throw new CliError("not logged in -- run `rit login` first", { code: "not_logged_in" });
19
+ return s;
20
+ }
21
+
22
+ function requireTarget(options, fallbackOwner) {
23
+ const target = parseTarget(options.name, fallbackOwner);
24
+ if (!target) throw new CliError(`"${options.name}" doesn't look like a repo -- use owner/repo${fallbackOwner ? " or a bare name" : ""}`, { code: "invalid_argument" });
25
+ return target;
26
+ }
27
+
28
+ /** `rit repo list [owner] [--json]`: your own repos with no argument, an
29
+ * owner's visible-to-you repos otherwise. */
30
+ export async function runRepoList(options, io) {
31
+ const s = session(io, options);
32
+ const apiUrl = s?.apiUrl ?? (options.apiUrl ?? io.env.RITHUB_API_URL ?? "https://rithub.dev").replace(/\/+$/, "");
33
+ const path = options.owner ? `/api/v1/users/${encodeURIComponent(options.owner)}/repos` : "/api/v1/user/repos";
34
+ if (!options.owner && !s) throw new CliError("not logged in -- run `rit login` first, or pass an owner: `rit repo list <owner>`", { code: "not_logged_in" });
35
+ const { status, body } = await apiCall(io, apiUrl, path + buildQuery({ page: options.page, limit: options.limit ?? 50 }), { method: "GET" }, s?.token);
36
+ if (status !== 200) throw new CliError(`could not list repos (HTTP ${status}): ${body?.message ?? "unknown error"}`, { code: "network_error" });
37
+ return { repos: (body ?? []).map((repo) => ({ full_name: repo.full_name, private: repo.private, fork: repo.fork, html_url: repo.html_url })) };
38
+ }
39
+
40
+ export async function runRepoView(options, io) {
41
+ const s = session(io, options);
42
+ const apiUrl = s?.apiUrl ?? (options.apiUrl ?? io.env.RITHUB_API_URL ?? "https://rithub.dev").replace(/\/+$/, "");
43
+ const target = requireTarget(options, s?.username);
44
+ const { status, body } = await apiCall(io, apiUrl, repoPath(target.owner, target.repo), { method: "GET" }, s?.token);
45
+ if (status !== 200) throw new CliError(`${target.owner}/${target.repo} was not found (HTTP ${status})`, { code: "not_found" });
46
+ return { owner: target.owner, repo: target.repo, private: body.private, description: body.description, default_branch: body.default_branch, stars: body.stars_count, html_url: body.html_url };
47
+ }
48
+
49
+ export async function runRepoFork(options, io) {
50
+ const s = session(io, options, { required: true });
51
+ const target = requireTarget(options, s.username);
52
+ const { status, body } = await apiCall(io, s.apiUrl, repoPath(target.owner, target.repo, "/forks"), { method: "POST", body: JSON.stringify({}) }, s.token);
53
+ if (status !== 202 && status !== 201) throw new CliError(`could not fork ${target.owner}/${target.repo} (HTTP ${status}): ${body?.message ?? "unknown error"}`, { code: "create_failed" });
54
+ return { owner: target.owner, repo: target.repo, forked_as: body.full_name, html_url: body.html_url };
55
+ }
56
+
57
+ /** `rit repo delete <owner/repo> --confirm`: no interactive y/N prompt on
58
+ * purpose -- an agent with no TTY must not get stuck on one, same reasoning
59
+ * as the `rit login` fix. `--confirm` is the deliberate, scriptable
60
+ * stand-in for it. */
61
+ export async function runRepoDelete(options, io) {
62
+ const s = session(io, options, { required: true });
63
+ const target = requireTarget(options, s.username);
64
+ if (!options.confirm) throw new CliError(`refusing to delete ${target.owner}/${target.repo} without --confirm`, { code: "invalid_argument" });
65
+ const { status, body } = await apiCall(io, s.apiUrl, repoPath(target.owner, target.repo), { method: "DELETE" }, s.token);
66
+ if (status !== 204 && status !== 200) throw new CliError(`could not delete ${target.owner}/${target.repo} (HTTP ${status}): ${body?.message ?? "unknown error"}`, { code: "delete_failed" });
67
+ return { owner: target.owner, repo: target.repo, deleted: true };
68
+ }
69
+
70
+ export async function runRepoRename(options, io) {
71
+ const s = session(io, options, { required: true });
72
+ const target = requireTarget(options, s.username);
73
+ if (!options.newName) throw new CliError("`rit repo rename` needs a new name: `rit repo rename <owner/repo> <new-name>`", { code: "invalid_argument" });
74
+ const { status, body } = await apiCall(io, s.apiUrl, repoPath(target.owner, target.repo), { method: "PATCH", body: JSON.stringify({ name: options.newName }) }, s.token);
75
+ if (status !== 200) throw new CliError(`could not rename ${target.owner}/${target.repo} (HTTP ${status}): ${body?.message ?? "unknown error"}`, { code: "update_failed" });
76
+ return { owner: target.owner, repo: body.name, html_url: body.html_url };
77
+ }
78
+
79
+ export async function runRepoEdit(options, io) {
80
+ const s = session(io, options, { required: true });
81
+ const target = requireTarget(options, s.username);
82
+ const patch = {};
83
+ if (options.description !== undefined) patch.description = options.description;
84
+ if (options.private) patch.private = true;
85
+ if (options.public) patch.private = false;
86
+ if (Object.keys(patch).length === 0) throw new CliError("`rit repo edit` needs --description, --private, or --public", { code: "invalid_argument" });
87
+ const { status, body } = await apiCall(io, s.apiUrl, repoPath(target.owner, target.repo), { method: "PATCH", body: JSON.stringify(patch) }, s.token);
88
+ if (status !== 200) throw new CliError(`could not edit ${target.owner}/${target.repo} (HTTP ${status}): ${body?.message ?? "unknown error"}`, { code: "update_failed" });
89
+ return { owner: target.owner, repo: target.repo, private: body.private, description: body.description };
90
+ }
91
+
92
+ export async function runRepoArchive(options, io) {
93
+ const s = session(io, options, { required: true });
94
+ const target = requireTarget(options, s.username);
95
+ const { status, body } = await apiCall(io, s.apiUrl, repoPath(target.owner, target.repo), { method: "PATCH", body: JSON.stringify({ archived: !options.unarchive }) }, s.token);
96
+ if (status !== 200) throw new CliError(`could not ${options.unarchive ? "unarchive" : "archive"} ${target.owner}/${target.repo} (HTTP ${status}): ${body?.message ?? "unknown error"}`, { code: "update_failed" });
97
+ return { owner: target.owner, repo: target.repo, archived: body.archived };
98
+ }
99
+
100
+ /** `rit repo sync <git-url> [--name <name>] [--private]`: creates a live
101
+ * pull mirror of `<git-url>` on Rithub (`POST /repos/migrate` with
102
+ * `mirror: true`) -- the repo stays in sync on its own; re-run
103
+ * `rit repo sync-now <owner/repo>` to pull immediately instead of waiting
104
+ * for the next scheduled sync. `rit repo import` is the same call with
105
+ * `mirror: false` for a one-time copy instead. */
106
+ async function migrate(options, io, { mirror }) {
107
+ const s = session(io, options, { required: true });
108
+ if (!options.url) throw new CliError(`\`rit repo ${mirror ? "sync" : "import"}\` needs a source git URL: \`rit repo ${mirror ? "sync" : "import"} <git-url>\``, { code: "invalid_argument" });
109
+ const repoName = options.name ?? options.url.replace(/\.git$/, "").split("/").pop();
110
+ const { status, body } = await apiCall(
111
+ io,
112
+ s.apiUrl,
113
+ "/api/v1/repos/migrate",
114
+ { method: "POST", body: JSON.stringify({ clone_addr: options.url, repo_name: repoName, mirror, private: !!options.private, wiki: true, issues: true, labels: true, releases: true, milestones: true, pull_requests: true }) },
115
+ s.token
116
+ );
117
+ if (status !== 201) throw new CliError(`could not ${mirror ? "mirror" : "import"} ${options.url} (HTTP ${status}): ${body?.message ?? "unknown error"}`, { code: "create_failed" });
118
+ return { owner: s.username, repo: repoName, mirror, source: options.url, html_url: body.html_url };
119
+ }
120
+ export const runRepoSync = (options, io) => migrate(options, io, { mirror: true });
121
+ export const runRepoImport = (options, io) => migrate(options, io, { mirror: false });
122
+
123
+ /** `rit repo sync-now <owner/repo>`: triggers an immediate pull on an
124
+ * existing mirror (`POST .../mirror-sync`) instead of waiting for the next
125
+ * scheduled interval. */
126
+ export async function runRepoSyncNow(options, io) {
127
+ const s = session(io, options, { required: true });
128
+ const target = requireTarget(options, s.username);
129
+ const { status, body } = await apiCall(io, s.apiUrl, repoPath(target.owner, target.repo, "/mirror-sync"), { method: "POST" }, s.token);
130
+ if (status !== 200) throw new CliError(`could not sync ${target.owner}/${target.repo} now (HTTP ${status}): ${body?.message ?? "unknown error"}`, { code: "update_failed" });
131
+ return { owner: target.owner, repo: target.repo, synced: true };
132
+ }