dev-wrapped 0.0.0-stage → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/git.js ADDED
@@ -0,0 +1,124 @@
1
+ import { spawnSync } from 'node:child_process';
2
+ import { readdirSync, statSync, existsSync } from 'node:fs';
3
+ import { join, basename, resolve } from 'node:path';
4
+
5
+ const SEP = '\x1f';
6
+ const REC = '\x1e';
7
+
8
+ function git(args, cwd) {
9
+ const res = spawnSync('git', args, { cwd, encoding: 'utf8', maxBuffer: 1024 * 1024 * 1024 });
10
+ if (res.error) throw res.error;
11
+ if (res.status !== 0) return null;
12
+ return res.stdout;
13
+ }
14
+
15
+ export function isGitRepo(dir) {
16
+ const out = git(['rev-parse', '--is-inside-work-tree'], dir);
17
+ return out !== null && out.trim() === 'true';
18
+ }
19
+
20
+ export function repoRoot(dir) {
21
+ const out = git(['rev-parse', '--show-toplevel'], dir);
22
+ return out ? out.trim() : resolve(dir);
23
+ }
24
+
25
+ export function gitConfig(key, dir) {
26
+ const out = git(['config', '--get', key], dir);
27
+ return out ? out.trim() : '';
28
+ }
29
+
30
+ /** Find git repositories under `dir` (up to `depth` levels deep). */
31
+ export function findRepos(dir, depth = 3) {
32
+ const found = [];
33
+ const skip = new Set(['node_modules', '.cache', 'vendor', 'dist', 'build', 'target', '.venv', 'venv']);
34
+ (function walk(d, level) {
35
+ if (existsSync(join(d, '.git'))) {
36
+ found.push(d);
37
+ return;
38
+ }
39
+ if (level >= depth) return;
40
+ let entries = [];
41
+ try {
42
+ entries = readdirSync(d, { withFileTypes: true });
43
+ } catch {
44
+ return;
45
+ }
46
+ for (const e of entries) {
47
+ if (!e.isDirectory() || e.name.startsWith('.') || skip.has(e.name)) continue;
48
+ walk(join(d, e.name), level + 1);
49
+ }
50
+ })(resolve(dir), 0);
51
+ return found;
52
+ }
53
+
54
+ function normalizePath(p) {
55
+ // "src/{old => new}/file.js" -> "src/new/file.js" ; "a.js => b.js" -> "b.js"
56
+ let out = p.replace(/\{([^{}]*) => ([^{}]*)\}/g, '$2');
57
+ if (out.includes(' => ')) out = out.split(' => ').pop();
58
+ return out.replace(/\/\/+/g, '/');
59
+ }
60
+
61
+ /**
62
+ * Read every non-merge commit of a repo in [since, until).
63
+ * Times are in the author's own local time (what they actually lived).
64
+ */
65
+ export function readCommits(repoDir, { since, until }) {
66
+ const args = [
67
+ 'log',
68
+ '--all',
69
+ '--no-merges',
70
+ `--since=${since}`,
71
+ `--until=${until}`,
72
+ '--date=format:%Y-%m-%d %H %M %u',
73
+ `--pretty=format:${REC}%H${SEP}%an${SEP}%ae${SEP}%ad${SEP}%s`,
74
+ '--numstat',
75
+ ];
76
+ const out = git(args, repoDir);
77
+ if (!out) return [];
78
+ const repo = basename(repoDir);
79
+ const commits = [];
80
+ const seen = new Set();
81
+ for (const chunk of out.split(REC)) {
82
+ if (!chunk.trim()) continue;
83
+ const [header, ...rest] = chunk.split('\n');
84
+ const [hash, name, email, date, subject = ''] = header.split(SEP);
85
+ if (!hash || seen.has(hash)) continue;
86
+ seen.add(hash);
87
+ const [day, hour, minute, weekday] = (date || '').split(' ');
88
+ const files = [];
89
+ let added = 0;
90
+ let removed = 0;
91
+ for (const line of rest) {
92
+ const m = line.match(/^(\d+|-)\t(\d+|-)\t(.+)$/);
93
+ if (!m) continue;
94
+ const a = m[1] === '-' ? 0 : Number(m[1]);
95
+ const r = m[2] === '-' ? 0 : Number(m[2]);
96
+ added += a;
97
+ removed += r;
98
+ files.push({ path: normalizePath(m[3]), added: a, removed: r });
99
+ }
100
+ commits.push({
101
+ repo,
102
+ hash,
103
+ name,
104
+ email: (email || '').toLowerCase(),
105
+ day,
106
+ hour: Number(hour),
107
+ minute: Number(minute),
108
+ weekday: Number(weekday), // 1 = Monday … 7 = Sunday
109
+ subject,
110
+ added,
111
+ removed,
112
+ files,
113
+ });
114
+ }
115
+ return commits;
116
+ }
117
+
118
+ export function isRepoDir(dir) {
119
+ try {
120
+ return statSync(dir).isDirectory() && isGitRepo(dir);
121
+ } catch {
122
+ return false;
123
+ }
124
+ }
package/src/github.js ADDED
@@ -0,0 +1,192 @@
1
+ import { spawnSync } from 'node:child_process';
2
+
3
+ const API = 'https://api.github.com/graphql';
4
+ const MAX_REPOS = 40; // repos whose commit history we read in detail
5
+ const MAX_PAGES = 10; // 100 commits per page -> up to 1000 commits per repo
6
+ const CONCURRENCY = 4;
7
+
8
+ export class GitHubError extends Error {}
9
+
10
+ /** Token from env, or from the GitHub CLI if the user is logged in. Never from argv (shell history). */
11
+ export function resolveToken(env = process.env) {
12
+ if (env.GITHUB_TOKEN) return env.GITHUB_TOKEN.trim();
13
+ if (env.GH_TOKEN) return env.GH_TOKEN.trim();
14
+ try {
15
+ const r = spawnSync('gh', ['auth', 'token'], { encoding: 'utf8' });
16
+ if (r.status === 0 && r.stdout.trim()) return r.stdout.trim();
17
+ } catch {
18
+ /* gh not installed */
19
+ }
20
+ return null;
21
+ }
22
+
23
+ export function makeRequest(token, fetchImpl = globalThis.fetch) {
24
+ return async function request(query, variables) {
25
+ let res;
26
+ try {
27
+ res = await fetchImpl(API, {
28
+ method: 'POST',
29
+ headers: { Authorization: `bearer ${token}`, 'Content-Type': 'application/json', 'User-Agent': 'git-wrapped' },
30
+ body: JSON.stringify({ query, variables }),
31
+ });
32
+ } catch (e) {
33
+ throw new GitHubError(`Could not reach GitHub (${e.cause?.code || e.message}).`);
34
+ }
35
+ if (res.status === 401) throw new GitHubError('GitHub rejected the token (401). Check GITHUB_TOKEN or run `gh auth login`.');
36
+ const body = await res.json().catch(() => ({}));
37
+ if (!res.ok) throw new GitHubError(`GitHub API error ${res.status}: ${body.message || 'unknown error'}`);
38
+ if (body.errors?.length) {
39
+ const msg = body.errors.map((e) => e.message).join('; ');
40
+ if (body.errors.some((e) => e.type === 'NOT_FOUND')) throw new GitHubError(msg);
41
+ if (!body.data) throw new GitHubError(msg);
42
+ }
43
+ return body.data;
44
+ };
45
+ }
46
+
47
+ const PROFILE_QUERY = `
48
+ query($login: String!, $from: DateTime!, $to: DateTime!) {
49
+ user(login: $login) {
50
+ id login name avatarUrl
51
+ contributionsCollection(from: $from, to: $to) {
52
+ totalCommitContributions
53
+ totalPullRequestContributions
54
+ totalIssueContributions
55
+ totalPullRequestReviewContributions
56
+ restrictedContributionsCount
57
+ contributionCalendar {
58
+ totalContributions
59
+ weeks { contributionDays { date contributionCount } }
60
+ }
61
+ commitContributionsByRepository(maxRepositories: 100) {
62
+ contributions { totalCount }
63
+ repository { nameWithOwner name isPrivate stargazerCount primaryLanguage { name } }
64
+ }
65
+ }
66
+ }
67
+ }`;
68
+
69
+ const HISTORY_QUERY = `
70
+ query($owner: String!, $name: String!, $author: ID!, $since: GitTimestamp!, $until: GitTimestamp!, $after: String) {
71
+ repository(owner: $owner, name: $name) {
72
+ defaultBranchRef {
73
+ target {
74
+ ... on Commit {
75
+ history(first: 100, after: $after, since: $since, until: $until, author: { id: $author }) {
76
+ pageInfo { hasNextPage endCursor }
77
+ nodes { oid authoredDate messageHeadline additions deletions parents { totalCount } }
78
+ }
79
+ }
80
+ }
81
+ }
82
+ }
83
+ }`;
84
+
85
+ /** Convert an ISO timestamp to the wall-clock time of a given time zone. */
86
+ export function localParts(iso, timeZone) {
87
+ const parts = Object.fromEntries(
88
+ new Intl.DateTimeFormat('en-US', {
89
+ timeZone,
90
+ year: 'numeric',
91
+ month: '2-digit',
92
+ day: '2-digit',
93
+ hour: '2-digit',
94
+ minute: '2-digit',
95
+ weekday: 'short',
96
+ hourCycle: 'h23',
97
+ })
98
+ .formatToParts(new Date(iso))
99
+ .map((p) => [p.type, p.value])
100
+ );
101
+ const weekday = { Mon: 1, Tue: 2, Wed: 3, Thu: 4, Fri: 5, Sat: 6, Sun: 7 }[parts.weekday];
102
+ return { day: `${parts.year}-${parts.month}-${parts.day}`, hour: Number(parts.hour) % 24, minute: Number(parts.minute), weekday };
103
+ }
104
+
105
+ async function pool(items, n, fn) {
106
+ const out = new Array(items.length);
107
+ let i = 0;
108
+ await Promise.all(
109
+ Array.from({ length: Math.min(n, items.length) }, async () => {
110
+ while (i < items.length) {
111
+ const k = i++;
112
+ out[k] = await fn(items[k], k);
113
+ }
114
+ })
115
+ );
116
+ return out;
117
+ }
118
+
119
+ /**
120
+ * Fetch a user's year from GitHub.
121
+ * Returns commits shaped like the local git reader's, plus profile-level extras.
122
+ */
123
+ export async function fetchGitHubYear(login, { year, timeZone, request, onProgress = () => {} }) {
124
+ const from = `${year}-01-01T00:00:00Z`;
125
+ const to = `${year}-12-31T23:59:59Z`;
126
+ const data = await request(PROFILE_QUERY, { login, from, to });
127
+ const user = data?.user;
128
+ if (!user) throw new GitHubError(`GitHub user "${login}" not found.`);
129
+ const cc = user.contributionsCollection;
130
+
131
+ const byRepo = [...cc.commitContributionsByRepository].sort((a, b) => b.contributions.totalCount - a.contributions.totalCount);
132
+ const repos = byRepo.slice(0, MAX_REPOS);
133
+ onProgress({ phase: 'repos', total: repos.length });
134
+
135
+ let done = 0;
136
+ const perRepo = await pool(repos, CONCURRENCY, async ({ repository: r }) => {
137
+ const [owner, name] = r.nameWithOwner.split('/');
138
+ const commits = [];
139
+ let after = null;
140
+ for (let page = 0; page < MAX_PAGES; page++) {
141
+ let d;
142
+ try {
143
+ d = await request(HISTORY_QUERY, { owner, name, author: user.id, since: from, until: to, after });
144
+ } catch (e) {
145
+ if (e instanceof GitHubError) break; // repo gone or no access: keep what we have
146
+ throw e;
147
+ }
148
+ const h = d?.repository?.defaultBranchRef?.target?.history;
149
+ if (!h) break;
150
+ for (const n of h.nodes) {
151
+ if (n.parents?.totalCount > 1) continue; // merge commit
152
+ commits.push({
153
+ repo: r.name,
154
+ hash: n.oid,
155
+ name: user.name || user.login,
156
+ email: user.login.toLowerCase(),
157
+ ...localParts(n.authoredDate, timeZone),
158
+ subject: n.messageHeadline || '',
159
+ added: n.additions || 0,
160
+ removed: n.deletions || 0,
161
+ lang: r.primaryLanguage?.name || null,
162
+ files: [],
163
+ });
164
+ }
165
+ if (!h.pageInfo.hasNextPage) break;
166
+ after = h.pageInfo.endCursor;
167
+ }
168
+ onProgress({ phase: 'repo', done: ++done, total: repos.length, repo: r.nameWithOwner });
169
+ return commits;
170
+ });
171
+
172
+ const calendar = new Map();
173
+ for (const w of cc.contributionCalendar.weeks) for (const d of w.contributionDays) if (d.date.startsWith(String(year))) calendar.set(d.date, d.contributionCount);
174
+
175
+ return {
176
+ user,
177
+ commits: perRepo.flat(),
178
+ calendar,
179
+ github: {
180
+ login: user.login,
181
+ avatarUrl: user.avatarUrl,
182
+ contributions: cc.contributionCalendar.totalContributions,
183
+ commits: cc.totalCommitContributions,
184
+ prs: cc.totalPullRequestContributions,
185
+ issues: cc.totalIssueContributions,
186
+ reviews: cc.totalPullRequestReviewContributions,
187
+ privateContributions: cc.restrictedContributionsCount,
188
+ repos: byRepo.length,
189
+ topRepos: byRepo.slice(0, 5).map((x) => ({ name: x.repository.nameWithOwner, count: x.contributions.totalCount, stars: x.repository.stargazerCount })),
190
+ },
191
+ };
192
+ }
package/src/html.js ADDED
@@ -0,0 +1,51 @@
1
+ // Builds a single self-contained HTML file: a full-screen animated story,
2
+ // ending with a downloadable 1080×1350 share card. Fonts are embedded so the
3
+ // page looks identical everywhere, even offline.
4
+ import { readFileSync } from 'node:fs';
5
+ import { ICONS, svgIcon } from './icons.js';
6
+
7
+ const here = (p) => new URL(p, import.meta.url);
8
+ const read = (p) => readFileSync(here(p));
9
+
10
+ // Make any string safe to drop inside a <script> or <style> element.
11
+ const safe = (s) => s.replace(/</g, '\\u003c').replace(/\u2028|\u2029/g, '');
12
+
13
+ export function buildHtml(stats) {
14
+ const sans = read('./fonts/Geist-Variable.woff2').toString('base64');
15
+ const mono = read('./fonts/GeistMono-Variable.woff2').toString('base64');
16
+ const css = read('./story/style.css').toString('utf8');
17
+ const app = read('./story/app.js').toString('utf8');
18
+ const data = safe(JSON.stringify(stats));
19
+ const icons = safe(JSON.stringify(ICONS));
20
+
21
+ return `<!doctype html>
22
+ <html lang="en">
23
+ <head>
24
+ <meta charset="utf-8">
25
+ <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
26
+ <meta name="theme-color" content="#000000">
27
+ <title>Git Wrapped ${stats.year}</title>
28
+ <style>
29
+ @font-face{font-family:'Geist';src:url(data:font/woff2;base64,${sans}) format('woff2');font-weight:100 900;font-display:block}
30
+ @font-face{font-family:'Geist Mono';src:url(data:font/woff2;base64,${mono}) format('woff2');font-weight:100 900;font-display:block}
31
+ ${css.replace(/<\//g, '<\\/')}
32
+ </style>
33
+ </head>
34
+ <body>
35
+ <div id="stage"><div id="story">
36
+ <div class="glow g1"></div><div class="glow g2"></div><div class="grid"></div>
37
+ <div id="bars"></div>
38
+ <div id="top"><div class="brand">${svgIcon('commit', 18)}<span>Git Wrapped · ${stats.year}</span></div><button id="sound" aria-label="Sound"></button></div>
39
+ <div class="nav l" data-d="-1"></div><div class="nav r" data-d="1"></div>
40
+ <div id="slides"></div>
41
+ <canvas id="fx"></canvas>
42
+ <div class="hint">Tap or ← → to navigate · hold to pause</div>
43
+ </div></div>
44
+ <script>
45
+ const S = ${data};
46
+ const ICONS = ${icons};
47
+ ${app.replace(/<\/script/gi, '<\\/script')}
48
+ </script>
49
+ </body>
50
+ </html>`;
51
+ }
package/src/icons.js ADDED
@@ -0,0 +1,48 @@
1
+ // Original line icons drawn for git-wrapped, in the spirit of Apple's SF Symbols
2
+ // (24×24 grid, 1.75 stroke, round caps). Pure path data, so they work both as
3
+ // inline SVG and as canvas Path2D for the share card.
4
+ const ring = (cx, cy, r) => `M${cx} ${cy - r}a${r} ${r} 0 1 1 0 ${2 * r}a${r} ${r} 0 1 1 0 ${-2 * r}z`;
5
+
6
+ export const ICONS = {
7
+ commit: `M3 12h5.5M15.5 12H21${ring(12, 12, 3.5)}`,
8
+ folder: 'M3 7.5A1.5 1.5 0 0 1 4.5 6h4.2l2 2h8.8A1.5 1.5 0 0 1 21 9.5v8a1.5 1.5 0 0 1-1.5 1.5h-15A1.5 1.5 0 0 1 3 17.5z',
9
+ calendar: 'M4.5 5.5h15A1.5 1.5 0 0 1 21 7v12a1.5 1.5 0 0 1-1.5 1.5h-15A1.5 1.5 0 0 1 3 19V7a1.5 1.5 0 0 1 1.5-1.5zM3 10h18M8 3.5v4M16 3.5v4',
10
+ weekend: 'M4.5 5.5h15A1.5 1.5 0 0 1 21 7v12a1.5 1.5 0 0 1-1.5 1.5h-15A1.5 1.5 0 0 1 3 19V7a1.5 1.5 0 0 1 1.5-1.5zM3 10h18M8 3.5v4M16 3.5v4M14 14.5h3v3h-3z',
11
+ clock: `${ring(12, 12, 9)}M12 7v5l3.5 2`,
12
+ timer: `${ring(12, 13, 8)}M12 9v4.5M10 2.5h4M18.5 6.5L20 5`,
13
+ doc: 'M6.5 3H14l5 5v11.5a1.5 1.5 0 0 1-1.5 1.5h-11A1.5 1.5 0 0 1 5 19.5v-15A1.5 1.5 0 0 1 6.5 3zM14 3v5h5M8.5 13h7M8.5 16.5h5',
14
+ book: 'M12 6.5C10 5 7 4.5 3.5 5v13c3.5-.5 6.5 0 8.5 1.5c2-1.5 5-2 8.5-1.5V5C17 4.5 14 5 12 6.5zM12 6.5v13',
15
+ moon: 'M18.5 15A7.5 7.5 0 0 1 9 5.5a7.5 7.5 0 1 0 9.5 9.5zM17.5 3v4M15.5 5h4',
16
+ flame: 'M12 21c-3.9 0-6.5-2.6-6.5-6.2c0-3.3 2.3-5.4 3.8-7.3c.4 1.6 1.2 2.7 2.2 3.2C11.6 7.6 12.8 5 15 3c.2 3 1.4 4.6 2.4 6.2c.7 1.2 1.1 2.4 1.1 3.9c0 4.4-2.6 7.9-6.5 7.9z',
17
+ bolt: 'M13 2.5L5 13.5h6l-1 8l8-11h-6z',
18
+ pr: `${ring(6, 5, 2.2)}${ring(6, 19, 2.2)}${ring(18, 19, 2.2)}M6 7.2v9.6M18 16.8V9.5A2.5 2.5 0 0 0 15.5 7H11M13.5 4.5L11 7l2.5 2.5`,
19
+ eye: `M2.5 12S6 5.5 12 5.5S21.5 12 21.5 12S18 18.5 12 18.5S2.5 12 2.5 12z${ring(12, 12, 3)}`,
20
+ issue: `${ring(12, 12, 9)}M12 7.5V13M12 16.2v.3`,
21
+ lock: 'M6.5 10.5h11A1.5 1.5 0 0 1 19 12v7a1.5 1.5 0 0 1-1.5 1.5h-11A1.5 1.5 0 0 1 5 19v-7a1.5 1.5 0 0 1 1.5-1.5zM8 10.5v-3a4 4 0 0 1 8 0v3',
22
+ people: `${ring(9, 7.5, 3.5)}M2.5 20c.5-3.5 3.2-6 6.5-6s6 2.5 6.5 6M16 4.3a3.3 3.3 0 0 1 0 6.4M18 14.4c2 .7 3.3 2.8 3.5 5.6`,
23
+ speaker: 'M4 9.5h3l5-4v13l-5-4H4zM15.5 9a4 4 0 0 1 0 6M18 6.5a7.5 7.5 0 0 1 0 11',
24
+ mute: 'M4 9.5h3l5-4v13l-5-4H4zM16 9.5l5 5M21 9.5l-5 5',
25
+ download: 'M12 3.5v12M7.5 11l4.5 4.5l4.5-4.5M4.5 17v2A1.5 1.5 0 0 0 6 20.5h12a1.5 1.5 0 0 0 1.5-1.5v-2',
26
+ share: 'M12 14V3.5M8 7.5l4-4l4 4M8.5 10.5H7A1.5 1.5 0 0 0 5.5 12v7A1.5 1.5 0 0 0 7 20.5h10a1.5 1.5 0 0 0 1.5-1.5v-7a1.5 1.5 0 0 0-1.5-1.5h-1.5',
27
+ replay: 'M4.5 12a7.5 7.5 0 1 0 2.2-5.3M4.5 4v4.5H9',
28
+ chart: 'M4 4v16h16M8.5 16v-4M12.5 16V8M16.5 16v-6',
29
+ bubble: 'M4.5 4.5h15A1.5 1.5 0 0 1 21 6v9.5a1.5 1.5 0 0 1-1.5 1.5H10l-5 4v-4h-.5A1.5 1.5 0 0 1 3 15.5V6a1.5 1.5 0 0 1 1.5-1.5z',
30
+ wrench: 'M15 4.2a4.5 4.5 0 0 0-4.6 6l-6.2 6.2a2 2 0 0 0 2.8 2.8l6.2-6.2a4.5 4.5 0 0 0 6-4.6l-2.6 2.6l-2.5-.6l-.6-2.5z',
31
+ hourglass: 'M7 3.5h10M7 20.5h10M8 3.5c0 4 8 4.5 8 8.5s-8 4.5-8 8.5M16 3.5c0 4-8 4.5-8 8.5s8 4.5 8 8.5',
32
+ warning: 'M12 4l9 15.5H3zM12 10v4.5M12 17.2v.3',
33
+ star: 'M12 3.5l2.6 5.3l5.9.9l-4.25 4.1l1 5.85L12 16.9l-5.25 2.75l1-5.85L3.5 9.7l5.9-.9z',
34
+ sunrise: 'M3 17.5h18M7 17.5a5 5 0 0 1 10 0M12 4v4M9.5 6.5L12 4l2.5 2.5M4.6 11.1l1.4 1M19.4 11.1l-1.4 1M5 21h14',
35
+ trend: 'M3 17l5.5-5.5l4 4L21 7M15.5 7H21v5.5',
36
+ trash: 'M4 6.5h16M9.5 6.5v-2h5v2M6 6.5l1 13A1.5 1.5 0 0 0 8.5 21h7a1.5 1.5 0 0 0 1.5-1.5l1-13M10 10.5V17M14 10.5V17',
37
+ cube: 'M12 2.8l8 4.6v9.2l-8 4.6l-8-4.6V7.4zM4 7.4l8 4.6l8-4.6M12 12v9.2',
38
+ scope: `${ring(12, 12, 8)}M12 1.5v5M12 17.5v5M1.5 12h5M17.5 12h5${ring(12, 12, 1)}`,
39
+ tornado: 'M3.5 5h17M5.5 9h13M8 13h9M10 17h5M11.5 21h2',
40
+ briefcase: 'M4.5 7.5h15A1.5 1.5 0 0 1 21 9v9.5a1.5 1.5 0 0 1-1.5 1.5h-15A1.5 1.5 0 0 1 3 18.5V9a1.5 1.5 0 0 1 1.5-1.5zM8.5 7.5v-2A1.5 1.5 0 0 1 10 4h4a1.5 1.5 0 0 1 1.5 1.5v2M3 13h18',
41
+ stack: 'M12 3l9 4.5l-9 4.5l-9-4.5zM3 12l9 4.5l9-4.5M3 16.5L12 21l9-4.5',
42
+ plus: 'M12 5v14M5 12h14',
43
+ minus: 'M5 12h14',
44
+ };
45
+
46
+ export function svgIcon(name, size = 18, extra = '') {
47
+ return `<svg class="ic" width="${size}" height="${size}" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" ${extra}><path d="${ICONS[name]}"/></svg>`;
48
+ }
package/src/stats.js ADDED
@@ -0,0 +1,226 @@
1
+ import { pickArchetype } from './archetypes.js';
2
+
3
+ const LANGS = {
4
+ js: 'JavaScript', mjs: 'JavaScript', cjs: 'JavaScript', jsx: 'JavaScript',
5
+ ts: 'TypeScript', tsx: 'TypeScript', mts: 'TypeScript',
6
+ py: 'Python', ipynb: 'Jupyter', rb: 'Ruby', go: 'Go', rs: 'Rust',
7
+ java: 'Java', kt: 'Kotlin', kts: 'Kotlin', scala: 'Scala', swift: 'Swift',
8
+ c: 'C', h: 'C', cpp: 'C++', cc: 'C++', cxx: 'C++', hpp: 'C++', cs: 'C#',
9
+ php: 'PHP', dart: 'Dart', lua: 'Lua', r: 'R', jl: 'Julia', ex: 'Elixir', exs: 'Elixir',
10
+ erl: 'Erlang', hs: 'Haskell', clj: 'Clojure', zig: 'Zig', nim: 'Nim', sol: 'Solidity',
11
+ vue: 'Vue', svelte: 'Svelte', astro: 'Astro', html: 'HTML', htm: 'HTML',
12
+ css: 'CSS', scss: 'SCSS', sass: 'SCSS', less: 'CSS',
13
+ sh: 'Shell', bash: 'Shell', zsh: 'Shell', fish: 'Shell', ps1: 'PowerShell',
14
+ sql: 'SQL', md: 'Markdown', mdx: 'Markdown', tex: 'LaTeX',
15
+ yml: 'YAML', yaml: 'YAML', toml: 'TOML', tf: 'Terraform', nix: 'Nix',
16
+ gd: 'GDScript', m: 'Objective-C', mm: 'Objective-C', ml: 'OCaml', fs: 'F#',
17
+ };
18
+ const IGNORED_FILES = /(^|\/)(package-lock\.json|yarn\.lock|pnpm-lock\.yaml|Cargo\.lock|poetry\.lock|composer\.lock|Gemfile\.lock|go\.sum|bun\.lockb)$/;
19
+ const IGNORED_DIRS = /(^|\/)(node_modules|dist|build|vendor|\.next|coverage)\//;
20
+
21
+ const STOPWORDS = new Set(
22
+ ('a an the and or of to in on for with from by at as is be it this that into up add added adds update updated ' +
23
+ 'updates use make made more some new remove removed change changed changes minor small ' +
24
+ 'le la les de des du un une et en pour sur avec dans au aux par ajout ajoute maj').split(' ')
25
+ );
26
+ const RAGE = /\b(wtf|damn|shit|fuck\w*|merde|putain|argh+|ugh+|please work|pls work|why+)\b/i;
27
+
28
+ const BOOKS = [
29
+ { title: 'The Little Prince', pages: 96 },
30
+ { title: 'The Great Gatsby', pages: 180 },
31
+ { title: "Harry Potter and the Philosopher's Stone", pages: 320 },
32
+ { title: 'Dune', pages: 610 },
33
+ { title: 'The Lord of the Rings', pages: 1200 },
34
+ { title: 'War and Peace', pages: 1300 },
35
+ { title: 'the entire Harry Potter series', pages: 4100 },
36
+ { title: 'the Encyclopaedia Britannica', pages: 32000 },
37
+ ];
38
+ const LINES_PER_PAGE = 50;
39
+
40
+ export const WEEKDAYS = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'];
41
+
42
+ function topN(map, n, keyName = 'name', valName = 'count') {
43
+ return [...map.entries()]
44
+ .sort((a, b) => b[1] - a[1])
45
+ .slice(0, n)
46
+ .map(([k, v]) => ({ [keyName]: k, [valName]: v }));
47
+ }
48
+
49
+ function inc(map, key, by = 1) {
50
+ map.set(key, (map.get(key) || 0) + by);
51
+ }
52
+
53
+ function dayToUTC(day) {
54
+ const [y, m, d] = day.split('-').map(Number);
55
+ return Date.UTC(y, m - 1, d);
56
+ }
57
+ const DAY = 86400000;
58
+
59
+ function minutesOfNight(c) {
60
+ // rank "how late" a commit is: 00:00-05:59 counts as the latest of the night
61
+ return (c.hour < 6 ? c.hour + 24 : c.hour) * 60 + c.minute;
62
+ }
63
+
64
+ export function bookComparison(linesAdded) {
65
+ const pages = linesAdded / LINES_PER_PAGE;
66
+ let best = null;
67
+ for (const b of BOOKS) if (pages >= b.pages) best = b;
68
+ if (!best) return { pages: Math.round(pages), times: pages / BOOKS[0].pages, title: BOOKS[0].title };
69
+ return { pages: Math.round(pages), times: pages / best.pages, title: best.title };
70
+ }
71
+
72
+ /** Estimate time spent coding: commits closer than 2h belong to the same session. */
73
+ export function estimateHours(commits) {
74
+ const times = commits
75
+ .map((c) => dayToUTC(c.day) + (c.hour * 60 + c.minute) * 60000)
76
+ .sort((a, b) => a - b);
77
+ if (!times.length) return 0;
78
+ const MAX_GAP = 2 * 3600000;
79
+ const FIRST = 0.5 * 3600000;
80
+ let total = FIRST;
81
+ for (let i = 1; i < times.length; i++) {
82
+ const gap = times[i] - times[i - 1];
83
+ total += gap < MAX_GAP ? gap : FIRST;
84
+ }
85
+ return Math.round(total / 3600000);
86
+ }
87
+
88
+ /**
89
+ * @param {Array} commits commits authored by the user
90
+ * @param {Object} opts { year, allCommits, name, repos }
91
+ */
92
+ export function computeStats(commits, { year, allCommits = commits, name = 'you', repos = [], calendar: calendarOverride = null, github = null } = {}) {
93
+ const hours = new Array(24).fill(0);
94
+ const weekdays = new Array(7).fill(0);
95
+ const days = new Map();
96
+ const files = new Map();
97
+ const langs = new Map();
98
+ const words = new Map();
99
+ const repoCount = new Map();
100
+ let added = 0;
101
+ let removed = 0;
102
+ let fixes = 0;
103
+ let rage = 0;
104
+ let wip = 0;
105
+ let weekend = 0;
106
+ let nightOwl = 0;
107
+ let earlyBird = 0;
108
+ let officeHours = 0;
109
+ let latest = null;
110
+ let longestMsg = null;
111
+ let shortestMsg = null;
112
+
113
+ for (const c of commits) {
114
+ hours[c.hour]++;
115
+ weekdays[c.weekday - 1]++;
116
+ inc(days, c.day);
117
+ inc(repoCount, c.repo);
118
+ if (c.weekday >= 6) weekend++;
119
+ if (c.hour >= 22 || c.hour < 5) nightOwl++;
120
+ if (c.hour >= 5 && c.hour < 9) earlyBird++;
121
+ if (c.weekday <= 5 && c.hour >= 9 && c.hour < 18) officeHours++;
122
+ if (/\bfix(e[sd])?\b|\bbug\b|\bhotfix\b|\bpatch\b/i.test(c.subject)) fixes++;
123
+ if (RAGE.test(c.subject)) rage++;
124
+ if (/\bwip\b/i.test(c.subject)) wip++;
125
+ if (!latest || minutesOfNight(c) > minutesOfNight(latest)) latest = c;
126
+ const msg = c.subject.trim();
127
+ if (msg) {
128
+ if (!longestMsg || msg.length > longestMsg.subject.length) longestMsg = c;
129
+ if (!shortestMsg || msg.length < shortestMsg.subject.length) shortestMsg = c;
130
+ }
131
+ for (const w of c.subject.toLowerCase().match(/[a-zà-ÿ']{3,}/g) || []) {
132
+ if (!STOPWORDS.has(w)) inc(words, w);
133
+ }
134
+ if (!c.files.length && (c.added || c.removed)) {
135
+ // remote commits (GitHub mode): no per-file detail, use totals + repo language
136
+ added += c.added;
137
+ removed += c.removed;
138
+ if (c.lang) inc(langs, c.lang, c.added + c.removed || 1);
139
+ }
140
+ for (const f of c.files) {
141
+ if (IGNORED_FILES.test(f.path) || IGNORED_DIRS.test(f.path)) continue;
142
+ added += f.added;
143
+ removed += f.removed;
144
+ inc(files, `${repos.length > 1 ? c.repo + '/' : ''}${f.path}`);
145
+ const ext = (f.path.split('/').pop().split('.').slice(1).pop() || '').toLowerCase();
146
+ const lang = LANGS[ext];
147
+ if (lang) inc(langs, lang, f.added + f.removed || 1);
148
+ }
149
+ }
150
+
151
+ // calendar + streaks
152
+ const start = Date.UTC(year, 0, 1);
153
+ const end = Date.UTC(year + 1, 0, 1);
154
+ const calendar = [];
155
+ let longest = { length: 0, from: null, to: null };
156
+ let run = 0;
157
+ let runStart = null;
158
+ for (let t = start; t < end; t += DAY) {
159
+ const day = new Date(t).toISOString().slice(0, 10);
160
+ const count = (calendarOverride || days).get(day) || 0;
161
+ calendar.push(count);
162
+ if (count > 0) {
163
+ if (run === 0) runStart = day;
164
+ run++;
165
+ if (run > longest.length) longest = { length: run, from: runStart, to: day };
166
+ } else run = 0;
167
+ }
168
+ const busiest = topN(days, 1, 'day', 'count')[0] || null;
169
+ const activeDays = calendarOverride ? calendar.filter((v) => v > 0).length : days.size;
170
+
171
+ const totalLang = [...langs.values()].reduce((a, b) => a + b, 0) || 1;
172
+ const languages = topN(langs, 6).map((l) => ({ ...l, share: l.count / totalLang }));
173
+
174
+ // teammates = other people committing in the same repos
175
+ const myEmails = new Set(commits.map((c) => c.email));
176
+ const mates = new Map();
177
+ for (const c of allCommits) {
178
+ if (myEmails.has(c.email)) continue;
179
+ if (/\[bot\]|dependabot|renovate|github-actions/i.test(c.name + c.email)) continue;
180
+ inc(mates, c.name);
181
+ }
182
+
183
+ const peakHour = hours.indexOf(Math.max(...hours));
184
+ const peakWeekday = weekdays.indexOf(Math.max(...weekdays));
185
+ const n = commits.length || 1;
186
+
187
+ const stats = {
188
+ year,
189
+ name,
190
+ commits: commits.length,
191
+ repos: github ? github.repos : repoCount.size,
192
+ topRepos: topN(repoCount, 5),
193
+ activeDays,
194
+ added,
195
+ removed,
196
+ net: added - removed,
197
+ hours,
198
+ weekdays,
199
+ calendar,
200
+ peakHour,
201
+ peakWeekday: WEEKDAYS[peakWeekday],
202
+ longestStreak: longest,
203
+ busiest,
204
+ topFiles: topN(files, 5),
205
+ languages,
206
+ words: topN(words, 12, 'word', 'count'),
207
+ fixes,
208
+ rage,
209
+ wip,
210
+ weekendShare: weekend / n,
211
+ nightShare: nightOwl / n,
212
+ earlyShare: earlyBird / n,
213
+ officeShare: officeHours / n,
214
+ fixShare: fixes / n,
215
+ avgLines: (added + removed) / n,
216
+ latest: latest && { subject: latest.subject, day: latest.day, hour: latest.hour, minute: latest.minute, repo: latest.repo },
217
+ longestMsg: longestMsg && { subject: longestMsg.subject, repo: longestMsg.repo },
218
+ shortestMsg: shortestMsg && { subject: shortestMsg.subject, repo: shortestMsg.repo },
219
+ teammates: topN(mates, 3),
220
+ hoursCoding: estimateHours(commits),
221
+ book: bookComparison(added),
222
+ github,
223
+ };
224
+ stats.archetype = pickArchetype(stats);
225
+ return stats;
226
+ }