File size: 3,659 Bytes
a1415e8
161cb23
 
 
 
 
a1415e8
161cb23
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a1415e8
161cb23
a1415e8
 
 
 
161cb23
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a1415e8
 
 
 
 
161cb23
a1415e8
 
161cb23
 
 
 
5c265c1
161cb23
 
 
5c265c1
 
 
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
// Aggregate, code-free scoring telemetry. Every field sent here is listed in space/TELEMETRY.md.
import { byId } from "./dom.js";
import { NOTES, toHundred } from "./labels.js";
import { extensionOf } from "./languages.js";
import { apiUrl } from "./refiner.js";

export const MIN_VISIBLE_SCORED = 1000;
export const MIN_VISIBLE_TIMED = 1000;
export const MIN_BOARD_ENTRIES = 5;
const MAX_SCAN_FILES = 200;
const MAX_SCORE_MS = 60000;
const MAX_EXT_CHARS = 8;
const LOC_BUCKETS = [[50, "0-50"], [100, "50-100"], [300, "100-300"], [1000, "300-1000"]];

function baseExtension(path) {
  const ext = extensionOf(path.slice(path.lastIndexOf("/") + 1));
  return ext.length <= MAX_EXT_CHARS ? ext : "";
}

function locBucket(text) {
  const lines = text.split("\n").length;
  const bucket = LOC_BUCKETS.find(([limit]) => lines < limit);
  return bucket ? bucket[1] : "1000+";
}

async function digest16(ext, content) {
  const bytes = new TextEncoder().encode(`${ext}\0${content}`);
  const hash = new Uint8Array(await crypto.subtle.digest("SHA-256", bytes));
  return Array.from(hash.subarray(0, 8), (byte) => byte.toString(16).padStart(2, "0")).join("");
}

function squiggleCounts(squiggles) {
  const counts = {};
  for (const { kind } of squiggles) {
    if (kind in NOTES) {
      counts[kind] = (counts[kind] ?? 0) + 1;
    }
  }
  return counts;
}

function scoreMs(result) {
  return Number.isFinite(result.ms) ? Math.min(MAX_SCORE_MS, Math.round(result.ms)) : null;
}

async function scanEntry(file) {
  const ext = baseExtension(file.path);
  return {
    digest16: await digest16(ext, file.content),
    ext,
    loc_bucket: locBucket(file.content),
    score: toHundred(file.result.score),
    squiggles: squiggleCounts(file.result.squiggles),
    score_ms: scoreMs(file.result),
  };
}

export async function reportScan(sourceKind, files) {
  if (sourceKind === "examples" || files.length === 0 || !globalThis.crypto?.subtle) {
    return false;
  }
  const entries = await Promise.all(files.slice(0, MAX_SCAN_FILES).map(scanEntry));
  const request = fetch(apiUrl("telemetry/scan"), {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ source_kind: sourceKind, files: entries }),
    keepalive: true,
  });
  return request.then((response) => response.ok, () => false);
}

export function formatCount(count) {
  return count.toLocaleString("en-US");
}

export function formatMs(ms) {
  return `${formatCount(ms)} ms`;
}

const PHONE_BANNER_STATS = 2;

function bannerStat(id, value) {
  byId(id).hidden = value === null;
  if (value !== null) {
    byId(`${id}-value`).textContent = value;
  }
  return value !== null;
}

export function renderBanner(stats) {
  const scored = stats.files_scored >= MIN_VISIBLE_SCORED ? formatCount(stats.files_scored) : null;
  const flagged =
    stats.files_scored >= MIN_VISIBLE_SCORED && stats.issues_found > 0
      ? formatCount(stats.issues_found)
      : null;
  const timed = stats.score_ms_samples >= MIN_VISIBLE_TIMED ? formatMs(stats.score_ms_median) : null;
  const ids = ["banner-scored", "banner-issues", "banner-speed"];
  const shown = [scored, flagged, timed].map((value, index) => bannerStat(ids[index], value));
  const visibleIds = ids.filter((_, index) => shown[index]);
  for (const id of ids) {
    byId(id).classList.toggle("is-extra", visibleIds.indexOf(id) >= PHONE_BANNER_STATS);
  }
  byId("banner-stats").hidden = visibleIds.length === 0;
  byId("banner-board").hidden = stats.leaderboard_entries < MIN_BOARD_ENTRIES;
}

export function hideBannerStats() {
  byId("banner-stats").hidden = true;
  byId("banner-board").hidden = true;
}