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