File size: 1,267 Bytes
161cb23
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
// Ranks the loaded GitHub repo. The server downloads and scores the repo itself;
// the page only sends the owner and name.
import { RANK_ERRORS } from "./labels.js";
import { apiUrl } from "./refiner.js";

const PERCENT_FROM = 100;

export class RankFailure extends Error {
  constructor(code, detail = {}) {
    super(code);
    this.code = code;
    this.detail = detail;
  }
}

export async function requestRank(spec) {
  const response = await fetch(apiUrl("leaderboard/rank"), {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ owner: spec.owner, repo: spec.repo }),
  });
  const body = await response.json().catch(() => ({}));
  if (!response.ok) {
    throw new RankFailure(body.code ?? "failed", body);
  }
  return body;
}

export function rankErrorText(error) {
  if (error.code === "duplicate" && error.detail.repo) {
    return `Ranked as ${error.detail.repo}`;
  }
  return RANK_ERRORS[error.code] ?? RANK_ERRORS.failed;
}

export function rankLabel({ rank, total }) {
  if (total < PERCENT_FROM) {
    return `#${rank} of ${total}`;
  }
  return `Top ${Math.max(1, Math.ceil((rank / total) * 100))}%`;
}

export function boardLink(repo) {
  return `leaderboard/#repo=${encodeURIComponent(repo)}`;
}