Skip to content

Where people and agents ship software together. The open-source git platform for the whole job: issues, agents, checks and deploys to the edge.

g1t.sh
966 linesCodeBlameRaw
1import type { ActionsApi } from "./actions";
2import type { AiApi } from "./ai";
3import type { BillingAdminApi, BillingApi } from "./billing";
4import type { DeploymentsApi } from "./deployments";
5import type { ProjectsApi } from "./projects";
6import type { EventsApi } from "./events";
7import type { IdentityAdminApi, IdentityApi } from "./identity";
8import type { IntegrationsApi } from "./integrations";
9import type { PackagesApi } from "./packages";
10import type { WebhooksApi } from "./webhooks";
11import type { ReposApi } from "./repos";
12import type { PullDetail, WorkApi } from "./work";
13import type { Result } from "./result";
14import type { RunnersAdminApi, RunnersApi } from "./runners";
15
16/** A service binding, as far as these clients need it. */
17export type ServiceBinding = {
18 fetch(input: string, init?: RequestInit): Promise<Response>;
19};
20
21/**
22 * Calls a method on a service that speaks the JSON protocol used by the
23 * Rust services: `POST /rpc/<method>` with the arguments as the body.
24 */
25async function rpc<T>(
26 service: ServiceBinding,
27 method: string,
28 args: object,
29): Promise<T> {
30 // The hostname is ignored; a service binding always reaches its service.
31 const response = await service.fetch(`https://service/rpc/${method}`, {
32 method: "POST",
33 headers: { "content-type": "application/json" },
34 body: JSON.stringify(args),
35 });
36 if (!response.ok) {
37 throw new Error(`${method} failed with status ${response.status}`);
38 }
39 return (await response.json()) as T;
40}
41
42export function identityClient(service: ServiceBinding): IdentityApi {
43 const call = <T>(method: string, args: object) => rpc<T>(service, method, args);
44 return {
45 register: (username, email, password, inviteCode, client, emailProof) =>
46 call("register", {
47 username,
48 email,
49 password,
50 invite_code: inviteCode ?? null,
51 email_proof: emailProof ?? null,
52 client: client ?? null,
53 }),
54 signIn: (username, password, client) => call("sign_in", { username, password, client: client ?? null }),
55 twoFactorSignIn: (challenge, code, client) => call("two_factor_sign_in", { challenge, code, client: client ?? null }),
56 signOut: (sessionToken) => call("sign_out", { sessionToken }),
57 resendVerification: (user) => call("resend_verification", { user }),
58 verifyEmail: (token) => call("verify_email", { token }),
59 requestPasswordReset: (email, client) => call("request_password_reset", { email, client: client ?? null }),
60 resetPassword: (token, password) =>
61 call("reset_password", { token, password }),
62 deviceStart: (clientName) => call("device_start", { clientName }),
63 deviceLookup: (userCode) => call("device_lookup", { userCode }),
64 deviceResolve: (userCode, user, approve) =>
65 call("device_resolve", { userCode, user, approve }),
66 deviceClaim: (deviceCode) => call("device_claim", { deviceCode }),
67 oauthAuthorize: (user, approval) => call("oauth_authorize", { user, ...approval }),
68 oauthExchange: (code, codeVerifier, clientId, redirectUri) =>
69 call("oauth_exchange", { code, codeVerifier, clientId, redirectUri }),
70 oauthRefresh: (refreshToken, clientId) =>
71 call("oauth_refresh", { refreshToken, clientId }),
72 listOAuthGrants: (user) => call("list_oauth_grants", { user }),
73 revokeOAuthGrant: (user, id) => call("revoke_oauth_grant", { user, id }),
74 updateOAuthGrant: (user, id, grant) =>
75 call("update_oauth_grant", { user, id, scopes: grant.scopes }),
76 createWorkspace: (user, slug, name) => call("create_workspace", { user, slug, name }),
77 getWorkspace: (slug) => call("get_workspace", { slug }),
78 workspaceResidency: (slug) => call("workspace_residency", { slug }),
79 setWorkspaceResidency: (actor, slug, residency) => call("set_workspace_residency", { actor, slug, residency }),
80 listMembers: (slug, viewer) => call("list_members", { slug, viewer }),
81 addMember: (actor, slug, username) => call("add_member", { actor, slug, username }),
82 removeMember: (actor, slug, username) =>
83 call("remove_member", { actor, slug, username, surface: "web" }),
84 updateMember: (actor, slug, username, change) =>
85 call("update_member", { actor, slug, username, role: change.role ?? null, org_roles: change.org_roles ?? null, surface: "web" }),
86 transferOwnership: (actor, slug, username) => call("transfer_ownership", { actor, slug, username, surface: "web" }),
87 leaveWorkspace: (user, slug) => call("leave_workspace", { user, slug, surface: "web" }),
88 setMemberPrivileges: (actor, slug, change) => call("set_member_privileges", { actor, slug, privileges: change, surface: "web" }),
89 setTwoFactorRequirement: (actor, slug, required) =>
90 call("set_two_factor_requirement", { actor, slug, required, surface: "web" }),
91 updateWorkspace: (actor, slug, details) =>
92 call("update_workspace", { actor, slug, ...details }),
93 renameWorkspace: (actor, slug, newSlug) => call("rename_workspace", { actor, slug, newSlug }),
94 checkWorkspaceRename: (actor, slug, newSlug) =>
95 call("check_workspace_rename", { actor, slug, newSlug }),
96 resolveSlug: (slug) => call("resolve_slug", { slug }),
97 deleteWorkspace: (actor, slug, confirm) => call("delete_workspace", { actor, slug, confirm }),
98 checkWorkspaceDeletion: (actor, slug) => call("check_workspace_deletion", { actor, slug }),
99 setWorkspaceAvatar: (actor, slug, image) => call("set_workspace_avatar", { actor, slug, image }),
100 setUserAvatar: (user, image) => call("set_user_avatar", { user, image }),
101 listWorkspaceTokens: (slug, viewer) => call("list_workspace_tokens", { slug, viewer }),
102 removeWorkspaceToken: (actor, slug, id) =>
103 call("remove_workspace_token", { actor, slug, id }),
104 createToken: (actor, input) =>
105 call("create_token", {
106 actor,
107 owner: input.owner ?? null,
108 name: input.name,
109 description: input.description ?? null,
110 ttl_seconds: input.ttlSeconds,
111 workspace: input.workspace,
112 repository_selection: input.repositorySelection,
113 repositories: input.repositories,
114 permissions: input.permissions,
115 website: input.website ?? false,
116 }),
117 updateToken: (actor, id, change, owner) =>
118 call("update_token", {
119 actor,
120 id,
121 owner: owner ?? null,
122 name: change.name ?? null,
123 description: change.description ?? null,
124 repository_selection: change.repositorySelection ?? null,
125 repositories: change.repositories ?? null,
126 permissions: change.permissions ?? null,
127 website: change.website ?? null,
128 }),
129 regenerateToken: (actor, id, ttlSeconds, owner) =>
130 call("regenerate_token", { actor, id, owner: owner ?? null, ttl_seconds: ttlSeconds ?? null }),
131 getTokenPolicy: (slug, viewer) => call("get_token_policy", { slug, viewer }),
132 setTokenPolicy: (actor, slug, change) =>
133 call("set_token_policy", {
134 actor,
135 slug,
136 allow_tokens_for_all_workspaces: change.allowTokensForAllWorkspaces ?? null,
137 allow_tokens_for_this_workspace: change.allowTokensForThisWorkspace ?? null,
138 require_approval: change.requireApproval ?? null,
139 max_lifetime_days: change.maxLifetimeDays ?? null,
140 forbid_no_expiry: change.forbidNoExpiry ?? null,
141 surface: "web",
142 }),
143 listMemberTokens: (actor, slug, filter = {}) =>
144 call("list_member_tokens", { actor, slug, status: filter.status ?? null }),
145 reviewTokenRequest: (actor, slug, id, approve, reason) =>
146 call("review_token_request", { actor, slug, id, approve, reason: reason ?? null, surface: "web" }),
147 revokeMemberToken: (actor, slug, id, reason) =>
148 call("revoke_member_token", { actor, slug, id, reason: reason ?? null, surface: "web" }),
149 userForSession: (sessionToken) => call("user_for_session", { sessionToken }),
150 listInvites: (user) => call("list_invites", { user }),
151 createInvite: (user, invite) =>
152 call("create_invite", {
153 user,
154 email: invite.email,
155 message: invite.message ?? null,
156 join: invite.join ?? null,
157 join_role: invite.join ? (invite.joinRole ?? null) : null,
158 surface: "web",
159 }),
160 revokeInvite: (user, id) => call("revoke_invite", { user, id }),
161 resendInvite: (user, id) => call("resend_invite", { user, id }),
162 checkInvite: (code, client, options = {}) =>
163 call("check_invite", {
164 code,
165 client: client ?? null,
166 viewer: options.viewer ?? null,
167 any_status: options.anyStatus ?? false,
168 email_proof: options.emailProof ?? null,
169 }),
170 acceptInvite: (user, code) => call("accept_invite", { user, code }),
171 inviteMember: (actor, slug, who) =>
172 call("invite_member", { actor, slug, email: who.email ?? "", username: who.username ?? null, role: who.role ?? null, message: who.message ?? null }),
173 listInvitations: (user) => call("list_invitations", { user }),
174 acceptInvitation: (user, id) => call("accept_invitation", { user, id, surface: "web" }),
175 declineInvitation: (user, id) => call("decline_invitation", { user, id, surface: "web" }),
176 findPeople: (query, limit) => call("find_people", { query, limit: limit ?? null }),
177 workspaceInvites: (slug, viewer) => call("workspace_invites", { slug, viewer }),
178 revokeWorkspaceInvite: (actor, slug, id) => call("revoke_workspace_invite", { actor, slug, id }),
179 resendWorkspaceInvite: (actor, slug, id) => call("resend_workspace_invite", { actor, slug, id }),
180 userForGitCredentials: (username, secret) =>
181 call("user_for_git_credentials", { username, secret }),
182 userForAccessToken: (token) => call("user_for_access_token", { token }),
183 userForSshKey: (fingerprint) => call("user_for_ssh_key", { fingerprint }),
184 userByUsername: (username) => call("user_by_username", { username }),
185 usernames: (ids) => call("usernames", { ids }),
186 usersForAudience: (ids) => call("users_for_audience", { ids }),
187 profile: (username) => call("profile", { username }),
188 updateProfile: (actor, fields) => call("update_profile", { actor, ...fields }),
189 profileWorkspaces: (username, viewer, publicIn) =>
190 call("profile_workspaces", { username, viewer, public: publicIn }),
191 dockPins: (user, workspace) => call("dock_pins", { user, workspace }),
192 setDockPins: (user, workspace, apps) => call("set_dock_pins", { user, workspace, apps }),
193 onboarding: (user, workspace) => call("onboarding", { user, workspace }),
194 setOnboarding: (user, workspace, change) => call("set_onboarding", { user, workspace, change }),
195 soundSettings: (user) => call("sound_settings", { user }),
196 setSoundSettings: (user, change) => call("set_sound_settings", { user, change }),
197 listSshKeys: (user) => call("list_ssh_keys", { user }),
198 addSshKey: (user, title, publicKey) =>
199 call("add_ssh_key", { user, title, publicKey }),
200 removeSshKey: (user, id) => call("remove_ssh_key", { user, id }),
201 listAccessTokens: (user) => call("list_access_tokens", { user }),
202 createAccessToken: (user, name, ttlSeconds, grant) =>
203 call("create_access_token", {
204 user,
205 name,
206 ttlSeconds,
207 scopes: grant?.scopes ?? null,
208 listed: grant?.listed ?? false,
209 }),
210 removeAccessToken: (user, id) => call("remove_access_token", { user, id }),
211 createRunCredential: (input) => call("create_run_credential", input),
212 bindRunCredentials: (tokenHashes, runId) => call("bind_run_credentials", { tokenHashes, runId }),
213 revokeRunCredentials: (target) => call("revoke_run_credentials", target),
214 // Who has access to a repository; see access.ts.
215 repoAccess: (owner, name, viewer) => call("repo_access", { viewer, path: { namespace: owner, name } }),
216 addCollaborator: (actor, owner, name, invitee, role) =>
217 call("add_collaborator", { actor, path: { namespace: owner, name }, invitee, role }),
218 setCollaboratorRole: (actor, owner, name, username, role) =>
219 call("set_collaborator_role", { actor, path: { namespace: owner, name }, username, role }),
220 removeCollaborator: (actor, owner, name, username) =>
221 call("remove_collaborator", { actor, path: { namespace: owner, name }, username }),
222 collaboratorPermission: (viewer, owner, name, username) =>
223 call("collaborator_permission", { viewer, path: { namespace: owner, name }, username }),
224 myRepoInvitations: (user) => call("my_repo_invitations", { user }),
225 respondRepoInvitation: (user, id, accept) => call("respond_repo_invitation", { user, id, accept }),
226 revokeRepoInvitation: (actor, owner, name, id) =>
227 call("revoke_repo_invitation", { actor, path: { namespace: owner, name }, id }),
228 setBasePermission: (actor, slug, base) => call("set_base_permission", { actor, slug, base_permission: base }),
229 outsideCollaborators: (viewer, slug) => call("outside_collaborators", { viewer, slug }),
230 // A repository's deploy keys; see deploy-keys.ts.
231 listDeployKeys: (viewer, owner, name) => call("list_deploy_keys", { viewer, path: { namespace: owner, name } }),
232 addDeployKey: (actor, owner, name, key) =>
233 call("add_deploy_key", { actor, path: { namespace: owner, name }, title: key.title, key: key.key, read_only: key.readOnly }),
234 removeDeployKey: (actor, owner, name, id) => call("remove_deploy_key", { actor, path: { namespace: owner, name }, id }),
235 // Teams; see teams.ts.
236 listTeams: (viewer, workspace, query) => call("list_teams", { viewer, workspace, query: query ?? null }),
237 getTeam: (viewer, workspace, team) => call("get_team", { viewer, workspace, team }),
238 createTeam: (actor, workspace, team) => call("create_team", { actor, workspace, ...team }),
239 setTeamCreation: (actor, slug, setting) => call("set_team_creation", { actor, slug, team_creation: setting }),
240 updateTeam: (actor, workspace, team, changes) => call("update_team", { actor, workspace, team, ...changes }),
241 deleteTeam: (actor, workspace, team) => call("delete_team", { actor, workspace, team }),
242 teamMembers: (viewer, workspace, team, includeChildTeams) =>
243 call("team_members", { viewer, workspace, team, include_child_teams: includeChildTeams ?? false }),
244 setTeamMember: (actor, workspace, team, username, role) =>
245 call("set_team_member", { actor, workspace, team, username, role }),
246 removeTeamMember: (actor, workspace, team, username) =>
247 call("remove_team_member", { actor, workspace, team, username }),
248 childTeams: (viewer, workspace, team) => call("child_teams", { viewer, workspace, team }),
249 teamRepos: (viewer, workspace, team) => call("team_repos", { viewer, workspace, team }),
250 setTeamRepo: (actor, workspace, team, owner, name, role) =>
251 call("set_team_repo", { actor, workspace, team, repo: { namespace: owner, name }, role }),
252 removeTeamRepo: (actor, workspace, team, owner, name) =>
253 call("remove_team_repo", { actor, workspace, team, repo: { namespace: owner, name } }),
254 userTeams: (viewer, workspace, username) => call("user_teams", { viewer, workspace, username }),
255 teamMemberships: (viewer, workspace) => call("team_memberships", { viewer, workspace }),
256 // People; see people.ts.
257 peopleDirectory: (viewer, workspace) => call("people_directory", { viewer, workspace }),
258 setMemberProfile: (actor, workspace, username, changes) => call("set_member_profile", { actor, workspace, username, ...changes }),
259 };
260}
261
262/**
263 * The slug a renamed workspace has now, for a `workspace.renamed` handler:
264 * asked of identity by the workspace's id, so that renames delivered twice
265 * or out of order converge. Falls back to the event's `to`.
266 */
267export async function currentWorkspaceSlug(
268 identity: ServiceBinding,
269 renamed: { workspaceId: string; to: string },
270): Promise<string> {
271 const names = await identityClient(identity).usernames([renamed.workspaceId]);
272 return names[renamed.workspaceId] ?? renamed.to;
273}
274
275/** The slugs whose rows move to `current`: the two a rename names, less `current`. */
276export function staleSlugs(renamed: { from: string; to: string }, current: string): string[] {
277 return [...new Set([renamed.from, renamed.to])].filter((slug) => slug !== current);
278}
279
280/**
281 * Where a transferred repository is now, as `namespace/name`, for a
282 * `repo.transferred` handler: asked of repos by id, so transfers delivered
283 * twice or out of order converge. Falls back to the event's destination.
284 */
285export async function currentRepoPath(
286 repos: ServiceBinding,
287 transferred: { repoId: string; name: string; to: string },
288): Promise<string> {
289 const path = await rpc<{ namespace: string; name: string } | null>(repos, "path_by_id", { id: transferred.repoId });
290 return path ? `${path.namespace}/${path.name}` : `${transferred.to}/${transferred.name}`;
291}
292
293/** The paths whose rows move to `current`: the two a transfer names, less `current`. */
294export function stalePaths(transferred: { name: string; from: string; to: string }, current: string): string[] {
295 return [...new Set([transferred.from, transferred.to].map((ns) => `${ns}/${transferred.name}`))].filter(
296 (path) => path !== current,
297 );
298}
299
300/**
301 * A repository's path change, from `repo.transferred` or `repo.renamed`,
302 * read the same way: the two paths (`namespace/name`) the event names, old
303 * then new. Null for any other event.
304 */
305export type RepoMove = { repoId: string; paths: [string, string] };
306
307export function repoMove(event: { type: string; data: unknown }): RepoMove | null {
308 const data = event.data as Record<string, string>;
309 if (event.type === "repo.transferred") {
310 return { repoId: data.repoId!, paths: [`${data.from}/${data.name}`, `${data.to}/${data.name}`] };
311 }
312 if (event.type === "repo.renamed") {
313 return { repoId: data.repoId!, paths: [`${data.namespace}/${data.from}`, `${data.namespace}/${data.to}`] };
314 }
315 return null;
316}
317
318/**
319 * Where a moved repository is now, as `namespace/name`: asked of repos by
320 * id, so moves delivered twice or out of order converge. Falls back to the
321 * event's new path.
322 */
323export async function currentMovedPath(repos: ServiceBinding, move: RepoMove): Promise<string> {
324 const path = await rpc<{ namespace: string; name: string } | null>(repos, "path_by_id", { id: move.repoId });
325 return path ? `${path.namespace}/${path.name}` : move.paths[1];
326}
327
328/** The paths whose rows move to `current`: the two a move names, less `current`. */
329export function staleMovedPaths(move: RepoMove, current: string): string[] {
330 return [...new Set(move.paths)].filter((path) => path !== current);
331}
332
333/** Staff-only identity. Only sudo binds to it; see `IdentityAdminApi`. */
334export function identityAdminClient(service: ServiceBinding): IdentityAdminApi {
335 const call = <T>(method: string, args: object) => rpc<T>(service, method, args);
336 return {
337 workspaces: (query) => call("admin_workspaces", { query: query ?? null }),
338 workspace: (slug) => call("admin_workspace", { slug }),
339 invites: (query, options = {}) => call("admin_invites", { query: query ?? null, to_g1t: options.toG1t ?? false }),
340 grantInvites: (username, amount, note, staff) => call("admin_grant_invites", { username, amount, note, staff }),
341 revokeInvite: (id, staff) => call("admin_revoke_invite", { id, staff }),
342 suspendUser: (name, suspend, reason, staff) => call("admin_suspend_user", { name, suspend, reason, staff }),
343 suspendWorkspace: (name, suspend, reason, staff) => call("admin_suspend_workspace", { name, suspend, reason, staff }),
344 blockedDomains: () => call("admin_blocked_domains", {}),
345 blockDomain: (domain, block, reason, staff) => call("admin_block_domain", { domain, block, reason, staff }),
346 deletedWorkspaces: () => call("admin_deleted_workspaces", {}),
347 restoreWorkspace: (workspaceId, staff) => call("admin_restore_workspace", { workspaceId, staff }),
348 purgeWorkspace: (workspaceId, staff, confirm) => call("admin_purge_workspace", { workspaceId, staff, confirm }),
349 aliases: () => call("admin_aliases", {}),
350 setAlias: (alias, workspace, note, staff) => call("admin_set_alias", { alias, workspace, note, staff }),
351 removeAlias: (alias, reason, staff) => call("admin_remove_alias", { alias, reason, staff }),
352 };
353}
354
355export function reposClient(service: ServiceBinding): ReposApi {
356 const call = <T>(method: string, args: object) => rpc<T>(service, method, args);
357 return {
358 get: (path, viewer) => call("get", { path, viewer }),
359 getById: (id, viewer) => call("get_by_id", { id, viewer }),
360 readable: (ids, viewer) => call("readable", { ids, viewer }),
361 publicNamespaces: (ownerId) => call("public_namespaces", { ownerId }),
362 list: (viewer, options = {}) => call("list", { viewer, ...options }),
363 create: (owner, input) => call("create", { owner, ...input }),
364 update: (actor, path, changes) => call("update", { actor, path, ...changes }),
365 transfer: (actor, path, to) => call("transfer", { actor, path, to }),
366 delete: (actor, path, confirm) => call("delete", { actor, path, confirm }),
367 deleted: (viewer, namespace) => call("deleted", { viewer, namespace }),
368 restore: (actor, path) => call("restore", { actor, path }),
369 purge: (actor, path, confirm) => call("purge", { actor, path, confirm }),
370 rename: (actor, path, name) => call("rename", { actor, path, name }),
371 archive: (actor, path, archived) => call("archive", { actor, path, archived }),
372 setVisibility: (actor, path, isPrivate, confirm) => call("set_visibility", { actor, path, isPrivate, confirm }),
373 setDefaultBranch: (actor, path, branch) => call("set_default_branch", { actor, path, branch }),
374 renameBranch: (actor, path, from, to) => call("rename_branch", { actor, path, from, to }),
375 createBranch: (actor, path, name, from = "") => call("create_branch", { actor, path, name, from }),
376 removeBranch: (actor, path, branch, head) => call("remove_branch", { actor, path, branch, head }),
377 resolveBranch: (repoId, branch) => call("resolve_branch", { repoId, branch }),
378 statusById: (id) => call("status_by_id", { id }),
379 storageOptions: () => call("storage_options", {}),
380 resolvePath: (path) => call("resolve_path", { path }),
381 tree: (path, viewer, ref, treePath) =>
382 call("tree", { path, viewer, ref, treePath }),
383 blob: (path, viewer, ref, filePath) =>
384 call("blob", { path, viewer, ref, filePath }),
385 log: (path, viewer, ref, limit) => call("log", { path, viewer, ref, limit }),
386 blame: (path, viewer, ref, filePath) => call("blame", { path, viewer, ref, filePath }),
387 forkForPull: (sourceId, pullId, actor) =>
388 call("fork_for_pull", { sourceId, pullId, actor }),
389 fork: (actor, path, input) => call("fork", { actor, path, ...input }),
390 forks: (path, viewer, limit) => call("forks", { path, viewer, limit: limit ?? null }),
391 syncFork: (actor, path, branch) => call("sync_fork", { actor, path, branch: branch ?? null }),
392 detachFork: (actor, path) => call("detach_fork", { actor, path }),
393 gitAccess: (path, viewer, service) =>
394 call("git_access", { path, viewer, service }),
395 branches: (path, viewer) => call("branches", { path, viewer }),
396 lastCommits: (path, viewer, ref, treePath) => call("last_commits", { path, viewer, ref, treePath }),
397 branchDrift: (path, viewer, base, heads) => call("branch_drift", { path, viewer, base, heads }),
398 tags: (path, viewer) => call("tags", { path, viewer }),
399 about: (path, viewer) => call("about", { path, viewer }),
400 languages: (path, viewer) => call("languages", { path, viewer }),
401 contributors: (path, viewer) => call("contributors", { path, viewer }),
402 license: (path, viewer) => call("license", { path, viewer }),
403 stars: (path, viewer) => call("stars", { path, viewer }),
404 star: (actor, path, starred) => call("star", { path, actor, starred }),
405 stargazers: (path, viewer, page) => call("stargazers", { path, viewer, page: page ?? null }),
406 starred: (username, viewer) => call("starred", { username, viewer }),
407 releases: (path, viewer) => call("releases", { path, viewer }),
408 release: (path, viewer, which) => call("release", { path, viewer, id: which.id ?? null, tag: which.tag ?? null, latest: which.latest ?? false }),
409 createRelease: (actor, path, release) => call("create_release", { path, actor, ...release }),
410 updateRelease: (actor, path, id, change) => call("update_release", { path, actor, id, ...change }),
411 deleteRelease: (actor, path, id) => call("delete_release", { path, actor, id }),
412 listFiles: (repoId, ref, limit, options) => call("list_files", { repoId, ref, skipDirs: [], limit, links: options?.links ?? false }),
413 openArchiveToken: (path, token) => call("open_archive_token", { path, token }),
414 rawBlobs: (repoId, hashes, maxBytes) => call("raw_blobs", { repoId, hashes, maxBytes }),
415 rawFile: (repoId, ref, path, maxBytes) => call("raw_file", { repoId, ref, path, maxBytes }),
416 commitFile: (repo, actor, file) => call("commit_file", { repo, actor, ...file }),
417 land: (sourceId, actor, branch) => call("land", { sourceId, actor, branch }),
418 compare: (repoId, viewer, base, head, baseBranch, paths, targetId) =>
419 call("compare", { repoId, viewer, base, head, baseBranch, paths: paths ?? null, ...(targetId ? { targetId } : {}) }),
420 claimBackups: (limit, maxRunning) => call("claim_backups", { limit, maxRunning }),
421 // The sandbox's own calls are snake_case (they come through the API).
422 failBackup: (jobId, token, error) => call("backup_fail", { job_id: jobId, token, error }),
423 };
424}
425
426/**
427 * `PullDetail`'s own fields that the work service writes in snake_case:
428 * `g1t_contracts::work::PullDetail` has no camelCase renaming, though what
429 * it holds (`Pull`, `CheckRun` and the rest) does. Each with its name here.
430 */
431const PULL_DETAIL_FIELDS = [
432 ["earlier_checks", "earlierChecks"],
433 ["required_checks", "requiredChecks"],
434 ["code_owners", "codeOwners"],
435] as const;
436
437/**
438 * A pull request's detail as the work service sent it, with its own fields
439 * in the camelCase this package uses: read at the edge, by `workClient`'s
440 * `getPull`. Either spelling is taken, so a service that already sends
441 * camelCase reads the same.
442 */
443export function pullDetailFromWire(raw: Record<string, unknown>): PullDetail {
444 const detail: Record<string, unknown> = { ...raw };
445 for (const [snake, camel] of PULL_DETAIL_FIELDS) {
446 if (snake in detail) {
447 if (!(camel in detail)) detail[camel] = detail[snake];
448 delete detail[snake];
449 }
450 }
451 return detail as PullDetail;
452}
453
454export function workClient(service: ServiceBinding): WorkApi {
455 const call = <T>(method: string, args: object) => rpc<T>(service, method, args);
456 return {
457 openIssue: (actor, repo, input) => call("open_issue", { actor, repo, ...input }),
458 listIssues: (repo, viewer, filter = {}) => call("list_issues", { repo, viewer, ...filter }),
459 getIssue: (repo, number, viewer) => call("get_issue", { repo, number, viewer }),
460 updateIssue: (actor, repo, number, input) =>
461 call("update_issue", { actor, repo, number, ...input }),
462 closeIssue: (actor, repo, number, reason) =>
463 call("close_issue", { actor, repo, number, reason }),
464 reopenIssue: (actor, repo, number) => call("reopen_issue", { actor, repo, number }),
465 listLabels: (repo, viewer) => call("list_labels", { repo, viewer }),
466 saveLabel: (actor, repo, label) => call("save_label", { actor, repo, ...label }),
467 deleteLabel: (actor, repo, name) => call("delete_label", { actor, repo, name }),
468 addDefaultLabels: (actor, repo) => call("add_default_labels", { actor, repo }),
469 setLabels: (actor, repo, number, labels, change = "set") =>
470 call("set_labels", { actor, repo, number, labels, change }),
471 listMilestones: (repo, viewer, state) => call("list_milestones", { repo, viewer, state }),
472 getMilestone: (repo, number, viewer) => call("get_milestone", { repo, number, viewer }),
473 saveMilestone: (actor, repo, milestone) => call("save_milestone", { actor, repo, ...milestone }),
474 deleteMilestone: (actor, repo, number) => call("delete_milestone", { actor, repo, number }),
475 counts: (repo, viewer) => call("counts", { repo, viewer }),
476 addComment: (actor, repo, number, comment) =>
477 call("add_comment", { actor, repo, number, ...comment }),
478 editComment: (actor, repo, commentId, body) => call("edit_comment", { actor, repo, commentId, body }),
479 deleteComment: (actor, repo, commentId) => call("delete_comment", { actor, repo, commentId }),
480 reportChecks: (runId, token, report) =>
481 call("report_checks", { runId, token, ...report }),
482 startMergecheck: (pullId) => call("start_mergecheck", { pullId }),
483 failMergecheck: (pullId, token, error) => call("report_mergecheck", { pullId, token, error }),
484 advance: (pullId) => call("advance", { pullId }),
485 managedPulls: (repoId) => call("managed_pulls", { repoId }),
486 queue: (repo, viewer) => call("queue", { repo, viewer }),
487 queueBuild: (repoId) => call("queue_build", { repoId }),
488 failQueue: (entryId, token, error) => call("report_queue", { entryId, token, error }),
489 removeFromQueue: (actor, repo, number) => call("remove_from_queue", { actor, repo, number }),
490 getSettings: (repo, viewer) => call("get_settings", { repo, viewer }),
491 // Rulesets travel in snake_case (rules.ts).
492 listRulesets: (owner, viewer, includeParents = false) =>
493 call("list_rulesets", { viewer, ...owner, include_parents: includeParents }),
494 getRuleset: (owner, id, viewer) => call("get_ruleset", { viewer, ...owner, id }),
495 saveRuleset: (actor, owner, ruleset, id) => call("save_ruleset", { actor, ...owner, id: id ?? null, ruleset }),
496 deleteRuleset: (actor, owner, id) => call("delete_ruleset", { actor, ...owner, id }),
497 effectiveRules: (repo, name, viewer, target = "branch") => call("effective_rules", { viewer, repo, name, target }),
498 ruleEvaluations: (owner, viewer, filter = {}) => call("rule_evaluations", { viewer, ...owner, ...filter }),
499 seenChecks: (repo, viewer) => call("seen_checks", { repo, viewer }),
500 commitChecks: (repo, viewer, shas) => call("commit_checks", { repo, viewer, shas }),
501 getCheckRun: (repo, id, viewer) => call("get_check_run", { repo, id, viewer }),
502 checkRunAnnotations: (repo, id, viewer) => call("check_run_annotations", { repo, id, viewer }),
503 requestCheckAction: (actor, repo, id, identifier) => call("request_check_action", { actor, repo, id, identifier }),
504 rerequestCheckRun: (actor, repo, id) => call("rerequest_check_run", { actor, repo, id }),
505 codeownersErrors: (repo, viewer, ref) => call("codeowners_errors", { repo, viewer, ref: ref ?? null }),
506 updateSettings: (actor, repo, settings) =>
507 call("update_settings", { actor, repo, settings }),
508 openPull: (actor, repo, input) => call("open_pull", { actor, repo, ...input }),
509 listPulls: (repo, viewer, state, filter = {}) => call("list_pulls", { repo, viewer, state, ...filter }),
510 deliveryInsights: (repoIds, viewer, from, until) => call("delivery_insights", { repoIds, viewer, from, until }),
511 pullsForRepos: (repoIds, viewer, limit) => call("pulls_for_repos", { repoIds, viewer, limit }),
512 // Its own fields arrive in snake_case: read into camelCase here.
513 getPull: (repo, number, viewer) =>
514 call<Result<Record<string, unknown>>>("get_pull", { repo, number, viewer }).then(
515 (found): Result<PullDetail> => (found.ok ? { ok: true, value: pullDetailFromWire(found.value) } : found),
516 ),
517 updatePull: (actor, repo, number, changes) =>
518 call("update_pull", { actor, repo, number, ...changes }),
519 catchUpPull: (actor, repo, number, options = {}) => call("catch_up_pull", { actor, repo, number, ...options }),
520 setAutoMerge: (actor, repo, number, enabled, options = {}) =>
521 call("set_auto_merge", { actor, repo, number, enabled, ...options }),
522 mergeChoices: (viewer, repo, number) => call("merge_choices", { viewer, repo, number }),
523 deleteHeadBranch: (actor, repo, number) => call("delete_head_branch", { actor, repo, number }),
524 restoreHeadBranch: (actor, repo, number) => call("restore_head_branch", { actor, repo, number }),
525 commitComments: (viewer, repo, commit, page) =>
526 call("commit_comments", { viewer, repo, commit: commit ?? null, page: page ?? null }),
527 addCommitComment: (actor, repo, commit, body, at) =>
528 call("add_commit_comment", { actor, repo, commit, body, path: at?.path ?? null, line: at?.line ?? null }),
529 editCommitComment: (actor, repo, id, body) => call("edit_commit_comment", { actor, repo, id, body }),
530 deleteCommitComment: (actor, repo, id) => call("delete_commit_comment", { actor, repo, id }),
531 readyPull: (actor, repo, number, summary) =>
532 call("ready_pull", { actor, repo, number, summary }),
533 closePull: (actor, repo, number) => call("close_pull", { actor, repo, number }),
534 reopenPull: (actor, repo, number) => call("reopen_pull", { actor, repo, number }),
535 convertPullToDraft: (actor, repo, number) => call("convert_pull_to_draft", { actor, repo, number }),
536 mergePull: (actor, repo, number, options = {}) =>
537 call("merge_pull", { actor, repo, number, ...options }),
538 listActivePulls: (viewer) => call("list_active_pulls", { viewer }),
539 byAuthor: (username, viewer, filter = {}) => call("by_author", { username, viewer, ...filter }),
540 contributions: (username, viewer) => call("contributions", { username, viewer }),
541 appendSession: (actor, repo, number, entries) =>
542 call("append_session", { actor, repo, number, entries }),
543 readSession: (repo, number, viewer, afterSeq = 0) =>
544 call("read_session", { repo, number, viewer, afterSeq }),
545 // Coordination: harness sessions, claims, an issue's whole context and
546 // decision records. Their arguments are snake_case, as the Rust service
547 // reads them; what comes back is camelCase.
548 getWork: (repo, number, viewer) => call("get_work", { repo, number, viewer }),
549 listClaims: (repo, viewer, filter = {}) =>
550 call("list_claims", { repo, viewer, state: filter.state ?? null, issue: filter.issue ?? null }),
551 listWorkSessions: (repo, viewer, filter = {}) =>
552 call("list_work_sessions", {
553 repo,
554 viewer,
555 state: filter.state ?? null,
556 issue: filter.issue ?? null,
557 pull: filter.pull ?? null,
558 path: filter.path ?? null,
559 subagents: filter.subagents ?? false,
560 }),
561 getWorkSession: (repo, id, viewer, afterSeq = 0) =>
562 call("get_work_session", { repo, id, viewer, after_seq: afterSeq }),
563 listDecisions: (repo, number, viewer) => call("list_decisions", { repo, number, viewer }),
564 };
565}
566
567export function billingClient(service: ServiceBinding): BillingApi {
568 const call = <T>(method: string, args: object) => rpc<T>(service, method, args);
569 return {
570 status: () => call("status", {}),
571 account: (workspace, viewer) => call("account", { workspace, viewer }),
572 ledger: (workspace, viewer) => call("ledger", { workspace, viewer }),
573 credits: (workspace, viewer) => call("credits", { workspace, viewer }),
574 statement: (workspace, viewer, month = null, group = "day") => call("statement", { workspace, viewer, month, group }),
575 statementEntries: (workspace, viewer, filter) =>
576 call("statement_entries", {
577 workspace,
578 viewer,
579 month: filter.month,
580 kind: filter.kind,
581 day: filter.day ?? null,
582 project: filter.project ?? null,
583 before: filter.before ?? null,
584 }),
585 usage: (workspace, viewer, since) => call("usage", { workspace, viewer, since }),
586 checkout: (actor, workspace, amountCents, returnUrl, method = "card") =>
587 call("checkout", { actor, workspace, amountCents, returnUrl, method }),
588 confirm: (workspace, viewer, session) => call("confirm", { workspace, viewer, session }),
589 trial: (workspace, exempt) => call("trial", { workspace, exempt }),
590 features: (workspace, viewer) => call("features", { workspace, viewer }),
591 subscribe: (actor, workspace, feature, returnUrl) =>
592 call("subscribe", { actor, workspace, feature, returnUrl }),
593 confirmSubscription: (workspace, viewer, session) =>
594 call("confirm_subscription", { workspace, viewer, session }),
595 cancelSubscription: (actor, workspace, feature, resume = false) =>
596 call("cancel_subscription", { actor, workspace, feature, resume }),
597 hasFeature: (workspace, feature) => call("has_feature", { workspace, feature }),
598 freeWorkspaces: (workspaces) => call("free_workspaces", { workspaces }),
599 chargeFeature: (charge) => call("charge_feature", charge),
600 billingPortal: (actor, workspace, returnUrl) => call("billing_portal", { actor, workspace, return_url: returnUrl }),
601 recordSandbox: (usage) => call("record_sandbox", usage),
602 limit: (workspace, viewer) => call("limit", { workspace, viewer }),
603 checkLimit: (workspace) => call("check_limit", { workspace }),
604 prices: () => call("prices", {}),
605 notePending: (workspace, source, costMicros, detail = null, month = null) =>
606 call("note_pending", { workspace, source, costMicros, detail, ...(month ? { month } : {}) }),
607 usageMeters: (workspace, viewer) => call("usage_meters", { workspace, viewer }),
608 setSpendLimit: (actor, workspace, spendLimitMicros, useFullLimit = false, raiseOnce = false) =>
609 call("set_spend_limit", { actor, workspace, spendLimitMicros, use_full_limit: useFullLimit, raise_once: raiseOnce }),
610 invoices: (workspace, viewer) => call("invoices", { workspace, viewer }),
611 entitlements: (workspace) => call("entitlements", { workspace }),
612 reserve: (reservation) => call("reserve", reservation),
613 settle: (reservationId, actualMicros) => call("settle", { reservationId, actualMicros }),
614 cardCheck: (actor, workspace, returnUrl) => call("card_check", { actor, workspace, returnUrl }),
615 confirmCardCheck: (workspace, viewer, session) => call("confirm_card_check", { workspace, viewer, session }),
616 requestLimit: (actor, workspace, request) => call("request_limit", { actor, workspace, ...request }),
617 limitRequests: (workspace, viewer) => call("limit_requests", { workspace, viewer }),
618 confirmSpike: (actor, workspace, keepGoing) => call("confirm_spike", { actor, workspace, keepGoing }),
619 usageReport: (workspace, viewer, range) =>
620 call("usage_report", { workspace, viewer, from: range.from, until: range.until, products: range.products ?? [], projects: range.projects ?? [] }),
621 setBudget: (actor, workspace, budget) => call("set_budget", { actor, workspace, ...budget }),
622 billingDetails: (workspace, viewer) => call("billing_details", { workspace, viewer }),
623 setBillingDetails: (actor, workspace, details) => call("set_billing_details", { actor, workspace, ...details }),
624 };
625}
626
627export function billingAdminClient(service: ServiceBinding): BillingAdminApi {
628 const call = <T>(method: string, args: object) => rpc<T>(service, method, args);
629 return {
630 accounts: (query) => call("admin_accounts", { query: query ?? null }),
631 account: (id) => call("admin_account", { id }),
632 setTerms: (id, terms, by) => call("admin_set_terms", { id, terms, by }),
633 setAllowances: (id, allowances, note, by) => call("admin_set_allowances", { id, allowances, note, by }),
634 createEnterprise: (name, workspaces, by) => call("admin_create_enterprise", { name, workspaces, by }),
635 attach: (workspace, account, by) => call("admin_attach", { workspace, account, by }),
636 credit: (workspace, amountMicros, note, by, options = { kind: "goodwill" }) =>
637 call("admin_credit", {
638 workspace,
639 amount_micros: amountMicros,
640 note,
641 by,
642 kind: options.kind,
643 expires_at: options.expiresAt ?? null,
644 refund_for: options.refundFor ?? null,
645 refund_day: options.refundDay ?? null,
646 }),
647 credits: (filter = {}) =>
648 call("admin_credits", {
649 workspace: filter.workspace ?? null,
650 kind: filter.kind ?? null,
651 month: filter.month ?? null,
652 by: filter.by ?? null,
653 }),
654 revokeCredit: (id, note, by) => call("admin_revoke_credit", { id, note, by }),
655 resetBilling: (workspace, confirm, note, by) => call("admin_reset_billing", { workspace, confirm, note, by }),
656 detachTestStripe: (a) =>
657 call("admin_detach_test_stripe", {
658 workspace: a.workspace ?? null,
659 exclude: a.exclude ?? null,
660 dry_run: a.dryRun,
661 cancel_at_stripe: a.cancelAtStripe ?? false,
662 confirm: a.confirm ?? "",
663 by: a.by,
664 }),
665 billingLink: (workspace, by) => call("admin_billing_link", { workspace, by }),
666 stripe: (fix = false, by) => call("admin_stripe", { fix, by: by ?? null }),
667 enterpriseBilling: (id, email, by) => call("admin_enterprise_billing", { id, email, by }),
668 enterpriseAddress: (id, address, taxIdType, taxId, by) => call("admin_enterprise_address", { id, address, taxIdType, taxId, by }),
669 invoiceEnterprise: (id, by) => call("admin_invoice_enterprise", { id, by }),
670 accountsFor: (workspaces) => call("admin_accounts", { query: null, workspaces }),
671 signals: () => call("admin_signals", {}),
672 overview: () => call("admin_overview", {}),
673 sales: (workspace) => call("admin_sales", { workspace }),
674 setSales: (workspace, record, by) =>
675 call("admin_set_sales", {
676 workspace,
677 stage: record.stage,
678 owner: record.owner ?? null,
679 next_step: record.nextStep ?? null,
680 next_at: record.nextAt ?? null,
681 by,
682 }),
683 addNote: (workspace, text, by) => call("admin_add_note", { workspace, text, by }),
684 workspaceInvoices: (workspace) => call("admin_workspace_invoices", { workspace }),
685 allInvoices: (filter = {}) => call("admin_invoices", { status: filter.status ?? null, month: filter.month ?? null }),
686 audit: (filter = {}) =>
687 call("admin_audit", { by: filter.by ?? null, action: filter.action ?? null, before: filter.before ?? null }),
688 limitRequests: (status = "open") => call("admin_limit_requests", { status }),
689 decideLimitRequest: (id, decision, amountMicros, note, by) =>
690 call("admin_decide_limit_request", { id, decision, amount_micros: amountMicros, note, by }),
691 overages: () => call("admin_overages", {}),
692 goodwill: (workspace, amountMicros, reason, by, day = null, requestKey = null) =>
693 call("admin_goodwill", { workspace, amount_micros: amountMicros, reason, by, day, request_key: requestKey }),
694 velocity: () => call("admin_velocity", {}),
695 recordPayment: (workspace, amountMicros, reference, note, by) =>
696 call("admin_record_payment", { workspace, amount_micros: amountMicros, reference, note, by }),
697 costs: (days) => call("admin_costs", { days: days ?? null }),
698 costAlerts: () => call("admin_cost_alerts", {}),
699 spendCaps: () => call("admin_spend_caps", {}),
700 liftBreaker: (note, by) => call("admin_lift_breaker", { note, by }),
701 platformGuard: () => call("admin_platform_guard", {}),
702 setPause: (level, paused, note, by) => call("admin_set_pause", { level, paused, note, by }),
703 decideProposal: (id, decision, note, by) => call("admin_decide_proposal", { id, decision, note, by }),
704 setCostSettings: (settings, by) => call("admin_set_cost_settings", { settings, by }),
705 setCostMapping: (mapping, by) =>
706 call("admin_set_cost_mapping", {
707 product: mapping.product,
708 meter: mapping.meter,
709 bucket: mapping.bucket ?? "",
710 price_meter: mapping.priceMeter ?? null,
711 own_meter: mapping.ownMeter ?? null,
712 scale_to_own: mapping.scaleToOwn ?? false,
713 drift_percent: mapping.driftPercent ?? null,
714 note: mapping.note ?? "",
715 remove: mapping.remove ?? false,
716 by,
717 }),
718 runCosts: (by) => call("admin_run_costs", { by }),
719 };
720}
721
722export function eventsClient(service: ServiceBinding): EventsApi {
723 const call = <T>(method: string, args: object) => rpc<T>(service, method, args);
724 return {
725 publish: (events) => call("publish", { events }),
726 list: (query) => call("list", query),
727 activityDigest: (args) => call("activity_digest", args),
728 };
729}
730
731export function integrationsClient(service: ServiceBinding): IntegrationsApi {
732 const call = <T>(method: string, args: object) => rpc<T>(service, method, args);
733 return {
734 list: (workspace, viewer) => call("list", { workspace, viewer }),
735 connect: (actor, workspace, input) => call("connect", { actor, workspace, ...input }),
736 update: (actor, workspace, id, input) => call("update", { actor, workspace, id, ...input }),
737 disconnect: (actor, workspace, id) => call("disconnect", { actor, workspace, id }),
738 test: (actor, workspace, id) => call("test", { actor, workspace, id }),
739 deliveries: (workspace, viewer, id) => call("deliveries", { workspace, viewer, id }),
740 resolve: (workspace, viewer, reference) => call("resolve", { workspace, viewer, reference }),
741 import: (actor, repo, reference) => call("import", { actor, repo, reference }),
742 links: (repo, number) => call("links", { repo, number }),
743 };
744}
745
746/**
747 * A workspace's AI providers and Ask g1t. Kept by the integrations service,
748 * so it is built on the same binding, with its own methods.
749 */
750export function aiClient(service: ServiceBinding): AiApi {
751 const call = <T>(method: string, args: object) => rpc<T>(service, method, args);
752 return {
753 list: (workspace, viewer) => call("ai_list", { workspace, viewer }),
754 add: (actor, workspace, input) => call("ai_add", { actor, workspace, ...input }),
755 update: (actor, workspace, id, input) => call("ai_update", { actor, workspace, id, ...input }),
756 remove: (actor, workspace, id) => call("ai_remove", { actor, workspace, id }),
757 test: (actor, workspace, id) => call("ai_test", { actor, workspace, id }),
758 askSettings: (workspace, viewer) => call("ask_settings", { workspace, viewer }),
759 setAskSettings: (actor, workspace, providerId, model) =>
760 call("set_ask_settings", { actor, workspace, provider_id: providerId, model }),
761 // Streamed: the response itself, not its parsed body.
762 ask: (actor, workspace, messages, page, signal) =>
763 service.fetch("https://service/rpc/ask", {
764 method: "POST",
765 headers: { "content-type": "application/json" },
766 body: JSON.stringify({ actor, workspace, messages, page }),
767 signal,
768 }),
769 };
770}
771
772export function webhooksClient(service: ServiceBinding): WebhooksApi {
773 const call = <T>(method: string, args: object) => rpc<T>(service, method, args);
774 return {
775 list: (viewer, owner) => call("list", { viewer, ...owner }),
776 create: (actor, owner, input) => call("create", { actor, ...owner, ...input }),
777 update: (actor, owner, id, input) => call("update", { actor, ...owner, id, ...input }),
778 delete: (actor, owner, id) => call("delete", { actor, ...owner, id }),
779 ping: (actor, owner, id) => call("ping", { actor, ...owner, id }),
780 deliveries: (viewer, owner, id) => call("deliveries", { viewer, ...owner, id }),
781 redeliver: (actor, owner, deliveryId) => call("redeliver", { actor, ...owner, deliveryId }),
782 };
783}
784
785export function actionsClient(service: ServiceBinding): ActionsApi {
786 const call = <T>(method: string, args: object) => rpc<T>(service, method, args);
787 return {
788 workflows: (repo, viewer) => call("workflows", { repo, viewer }),
789 runs: (repo, viewer, filter = {}) => call("runs", { repo, viewer, ...filter }),
790 run: (repo, viewer, id, attempt) => call("run", { repo, viewer, id, attempt: attempt ?? null }),
791 logs: (repo, viewer, job, after = 0) => call("logs", { repo, viewer, job, after }),
792 summaries: (repo, viewer, id, attempt) => call("summaries", { repo, viewer, id, attempt: attempt ?? null }),
793 jobLogText: (repo, viewer, job) => call("job_log_text", { repo, viewer, job }),
794 runLogs: (repo, viewer, id, attempt) => call("run_logs", { repo, viewer, id, attempt: attempt ?? null }),
795 dispatch: (actor, repo, workflow, ref, inputs) => call("dispatch", { actor, repo, workflow, ref, inputs }),
796 cancel: (actor, repo, id, force = false) => call("cancel", { actor, repo, id, force }),
797 rerun: (actor, repo, id, failedOnly = false, options = {}) =>
798 call("rerun", { actor, repo, id, failed_only: failedOnly, job: options.job ?? null, debug: options.debug ?? false }),
799 setWorkflowEnabled: (actor, repo, workflow, enabled) =>
800 call("set_workflow_enabled", { actor, repo, workflow, enabled }),
801 settings: (actor, owner, kind) => call("settings", { actor, ...owner, kind }),
802 setSetting: (actor, owner, kind, name, value, options = {}) =>
803 call("set_setting", { actor, ...owner, kind, name, value, ...options }),
804 deleteSetting: (actor, owner, kind, name, id) => call("delete_setting", { actor, ...owner, kind, name, id }),
805 approveRun: (actor, repo, id) => call("approve_run", { actor, repo, id }),
806 pendingDeployments: (repo, viewer, id) => call("pending_deployments", { repo, viewer, id }),
807 reviewDeployments: (actor, repo, id, state, environments = [], comment) =>
808 call("review_deployments", { actor, repo, id, state, environments, comment: comment ?? null }),
809 actionsSettings: (repo, viewer) => call("actions_settings", { repo, viewer }),
810 setActionsSettings: (actor, repo, change) => call("set_actions_settings", { actor, repo, ...change }),
811 workspaceActionsSettings: (workspace, viewer) => call("workspace_actions_settings", { workspace, viewer }),
812 setWorkspaceActionsSettings: (actor, workspace, change) =>
813 call("set_workspace_actions_settings", { actor, workspace, ...change }),
814 workspaceManagedWorkflows: (workspace, viewer) => call("workspace_managed_workflows", { workspace, viewer }),
815 setWorkspaceManagedWorkflow: (actor, workspace, name, change, create = false) =>
816 call("set_workspace_managed_workflow", { actor, workspace, name, create, ...change }),
817 removeWorkspaceManagedWorkflow: (actor, workspace, name) =>
818 call("remove_workspace_managed_workflow", { actor, workspace, name }),
819 environments: (repo, viewer) => call("environments", { repo, viewer }),
820 setEnvironment: (actor, repo, name, change) => call("set_environment", { actor, repo, name, ...change }),
821 deleteEnvironment: (actor, repo, name) => call("delete_environment", { actor, repo, name }),
822 artifacts: (repo, viewer, filter = {}) => call("artifacts", { repo, viewer, ...filter }),
823 artifactDownload: (repo, viewer, by) => call("artifact_download", { repo, viewer, ...by }),
824 deleteArtifact: (actor, repo, id) => call("delete_artifact", { actor, repo, id }),
825 artifactRetention: (repo, viewer, days) => call("artifact_retention", { repo, viewer, days }),
826 };
827}
828
829
830/** Staff-only self-hosted runners, on the actions service: only sudo calls it. */
831export function runnersAdminClient(service: ServiceBinding): RunnersAdminApi {
832 const call = <T>(method: string, args: object) => rpc<T>(service, method, args);
833 return {
834 list: (workspace) => call("admin_runners", { workspace }),
835 remove: (workspace, id, staff) => call("admin_remove_runners", { workspace, id, staff }),
836 };
837}
838
839/** Self-hosted runners, kept by the actions service. */
840export function runnersClient(service: ServiceBinding): RunnersApi {
841 const call = <T>(method: string, args: object) => rpc<T>(service, method, args);
842 return {
843 stuck: (viewer) => call("stuck_jobs", { viewer }),
844 activity: (actor, workspace) => call("runner_activity", { actor, workspace }),
845 list: (actor, owner) => call("runners", { actor, ...owner }),
846 createToken: (actor, owner, group) => call("create_registration_token", { actor, ...owner, group }),
847 remove: (actor, owner, id) => call("remove_runner", { actor, ...owner, id }),
848 groups: (actor, workspace) => call("runner_groups", { actor, workspace }),
849 setGroup: (actor, workspace, group) => call("set_runner_group", { actor, workspace, ...group }),
850 deleteGroup: (actor, workspace, id) => call("delete_runner_group", { actor, workspace, id }),
851 settings: (actor, owner) => call("runner_settings", { actor, ...owner }),
852 setSettings: (actor, owner, change) => call("set_runner_settings", { actor, ...owner, ...change }),
853 reportDesktop: (actor, report) => call("report_desktop", { actor, ...report }),
854 desktops: (actor, workspace) => call("desktop_runners", { actor, workspace }),
855 };
856}
857
858export function deploymentsClient(service: ServiceBinding): DeploymentsApi {
859 const call = <T>(method: string, args: object) => rpc<T>(service, method, args);
860 return {
861 settings: (project, viewer) => call("settings", { project, viewer }),
862 updateSettings: (actor, project, changes) => call("update_settings", { actor, project, changes }),
863 list: (project, viewer) => call("list", { project, viewer }),
864 get: (project, id, viewer) => call("get", { project, id, viewer }),
865 redeploy: (actor, project, branch) => call("redeploy", { actor, project, branch }),
866 takeDown: (actor, project, branch) => call("take_down", { actor, project, branch }),
867 overview: (workspace, viewer) => call("overview", { workspace, viewer }),
868 usage: (workspace, viewer) => call("usage", { workspace, viewer }),
869 domains: (project, viewer) => call("domains", { project, viewer }),
870 addDomain: (actor, project, hostname, options = {}) =>
871 call("add_domain", { actor, project, hostname, twin: !!options.twin }),
872 removeDomain: (actor, project, id) => call("remove_domain", { actor, project, id }),
873 refreshDomain: (actor, project, id) => call("refresh_domain", { actor, project, id }),
874 repoDeployments: (repo, viewer, filter = {}) => call("list_deployments", { repo, viewer, ...filter }),
875 repoDeployment: (repo, id, viewer) => call("get_deployment", { repo, id, viewer }),
876 environments: (repo, viewer) => call("list_environments", { repo, viewer }),
877 createDeployment: (actor, repo, input) => call("create_deployment", { repo, actor, ...input }),
878 createDeploymentStatus: (actor, repo, id, input) => call("create_deployment_status", { repo, actor, id, ...input }),
879 };
880}
881
882/** Packages: the registries beside the code (services/packages). */
883export function packagesClient(service: ServiceBinding): PackagesApi {
884 const call = <T>(method: string, args: object) => rpc<T>(service, method, args);
885 return {
886 list: (workspace, viewer, filter = {}) =>
887 call("list_packages", {
888 workspace,
889 viewer,
890 ecosystem: filter.ecosystem ?? null,
891 repo_id: filter.repoId ?? null,
892 query: filter.query ?? null,
893 }),
894 get: (workspace, ecosystem, name, viewer) => call("get_package", { workspace, ecosystem, name, viewer }),
895 deleteVersion: (actor, workspace, ecosystem, name, version, surface) =>
896 call("delete_version", { actor, workspace, ecosystem, name, version, surface: surface ?? null }),
897 deletePackage: (actor, workspace, ecosystem, name, surface) =>
898 call("delete_package", { actor, workspace, ecosystem, name, surface: surface ?? null }),
899 set: (actor, workspace, ecosystem, name, change, surface) =>
900 call("set_package", {
901 actor,
902 workspace,
903 ecosystem,
904 name,
905 visibility: change.visibility ?? null,
906 link: change.link ?? null,
907 unlink: change.unlink ?? false,
908 inherit_access: change.inheritAccess ?? null,
909 surface: surface ?? null,
910 }),
911 settings: (workspace, ecosystem, name, viewer) => call("package_settings", { workspace, ecosystem, name, viewer }),
912 deleted: (workspace, viewer) => call("deleted_packages", { workspace, viewer }),
913 restorePackage: (actor, workspace, ecosystem, name, surface) =>
914 call("restore_package", { actor, workspace, ecosystem, name, surface: surface ?? null }),
915 restoreVersion: (actor, workspace, ecosystem, name, version, surface) =>
916 call("restore_version", { actor, workspace, ecosystem, name, version, surface: surface ?? null }),
917 setAccess: (actor, workspace, ecosystem, name, who, role, surface) =>
918 call("set_package_access", {
919 actor,
920 workspace,
921 ecosystem,
922 name,
923 user: "user" in who ? who.user : null,
924 team: "team" in who ? who.team : null,
925 role,
926 surface: surface ?? null,
927 }),
928 removeAccess: (actor, workspace, ecosystem, name, who, surface) =>
929 call("remove_package_access", {
930 actor,
931 workspace,
932 ecosystem,
933 name,
934 user: "user" in who ? who.user : null,
935 team: "team" in who ? who.team : null,
936 surface: surface ?? null,
937 }),
938 setActionsAccess: (actor, workspace, ecosystem, name, repo, role, surface) =>
939 call("set_actions_access", { actor, workspace, ecosystem, name, repo, role, surface: surface ?? null }),
940 removeActionsAccess: (actor, workspace, ecosystem, name, repo, surface) =>
941 call("remove_actions_access", { actor, workspace, ecosystem, name, repo, surface: surface ?? null }),
942 storage: (workspace) => call("storage", { workspace }),
943 storageAll: () => call("storage_all", {}),
944 syncComposer: (repoId) => call("sync_composer", { repo_id: repoId }),
945 };
946}
947
948export function projectsClient(service: ServiceBinding): ProjectsApi {
949 const call = <T>(method: string, args: object) => rpc<T>(service, method, args);
950 return {
951 list: (workspace, viewer) => call("list", { workspace, viewer }),
952 get: (workspace, slug, viewer) => call("get", { workspace, slug, viewer }),
953 byRepo: (repoId) => call("by_repo", { repoId }),
954 create: (actor, workspace, input) => call("create", { actor, workspace, input }),
955 update: (actor, workspace, slug, changes) => call("update", { actor, workspace, slug, changes }),
956 setProductionImage: (actor, workspace, slug, change) => call("set_production_image", { actor, workspace, slug, change }),
957 externalProductions: () => call("external_productions", {}),
958 deploymentsChanged: (projectId, enabled) => call("deployments_changed", { projectId, enabled }),
959 shortcuts: (workspace, viewer) => call("shortcuts", { workspace, viewer }),
960 pin: (actor, workspace, slug, position) => call("pin", { actor, workspace, slug, position: position ?? null }),
961 unpin: (actor, workspace, slug) => call("unpin", { actor, workspace, slug }),
962 reorderPins: (actor, workspace, slugs) => call("reorder_pins", { actor, workspace, slugs }),
963 visited: (actor, projectId) => call("visited", { actor, projectId }),
964 publicLinks: (repos) => call("public_links", { repos }),
965 };
966}