gitlytics 0.4.1__tar.gz → 0.4.4__tar.gz

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.
Files changed (53) hide show
  1. {gitlytics-0.4.1 → gitlytics-0.4.4}/PKG-INFO +1 -1
  2. {gitlytics-0.4.1 → gitlytics-0.4.4}/pyproject.toml +1 -1
  3. {gitlytics-0.4.1 → gitlytics-0.4.4}/src/gitlytics/__init__.py +1 -1
  4. {gitlytics-0.4.1 → gitlytics-0.4.4}/src/gitlytics/api.py +109 -41
  5. {gitlytics-0.4.1 → gitlytics-0.4.4}/src/gitlytics/automation.py +14 -5
  6. {gitlytics-0.4.1 → gitlytics-0.4.4}/src/gitlytics/cli.py +15 -3
  7. {gitlytics-0.4.1 → gitlytics-0.4.4}/src/gitlytics/core.py +16 -5
  8. {gitlytics-0.4.1 → gitlytics-0.4.4}/src/gitlytics/process.py +38 -10
  9. gitlytics-0.4.4/src/gitlytics/static/_headers +6 -0
  10. gitlytics-0.4.1/src/gitlytics/static/assets/CardModal-BMio-Yhe.js → gitlytics-0.4.4/src/gitlytics/static/assets/CardModal-CDZ8n_vy.js +1 -1
  11. gitlytics-0.4.1/src/gitlytics/static/assets/ExportModal-HdxhYxeV.js → gitlytics-0.4.4/src/gitlytics/static/assets/ExportModal-BBjEZhmF.js +1 -1
  12. gitlytics-0.4.1/src/gitlytics/static/assets/exports-CRz2A0EU.js → gitlytics-0.4.4/src/gitlytics/static/assets/exports-BD7YfSBX.js +3 -3
  13. gitlytics-0.4.4/src/gitlytics/static/assets/index-BRI0yQ1K.css +1 -0
  14. gitlytics-0.4.4/src/gitlytics/static/assets/index-qzHj2txI.js +123 -0
  15. gitlytics-0.4.1/src/gitlytics/static/assets/index.es-Dsx-ECMQ.js → gitlytics-0.4.4/src/gitlytics/static/assets/index.es-BvMAPrqL.js +1 -1
  16. gitlytics-0.4.1/src/gitlytics/static/assets/jspdf.es.min-BPbddhZq.js → gitlytics-0.4.4/src/gitlytics/static/assets/jspdf.es.min-BXFa7K9_.js +3 -3
  17. {gitlytics-0.4.1 → gitlytics-0.4.4}/src/gitlytics/static/index.html +4 -3
  18. gitlytics-0.4.4/src/gitlytics/static/robots.txt +4 -0
  19. {gitlytics-0.4.1 → gitlytics-0.4.4}/src/gitlytics.egg-info/PKG-INFO +1 -1
  20. {gitlytics-0.4.1 → gitlytics-0.4.4}/src/gitlytics.egg-info/SOURCES.txt +8 -7
  21. {gitlytics-0.4.1 → gitlytics-0.4.4}/tests/test_api.py +25 -0
  22. {gitlytics-0.4.1 → gitlytics-0.4.4}/tests/test_cli.py +1 -2
  23. {gitlytics-0.4.1 → gitlytics-0.4.4}/tests/test_process.py +30 -3
  24. {gitlytics-0.4.1 → gitlytics-0.4.4}/tests/test_username.py +6 -9
  25. gitlytics-0.4.1/src/gitlytics/static/assets/index-CSjcErui.js +0 -119
  26. gitlytics-0.4.1/src/gitlytics/static/assets/index-D5qdeNvu.css +0 -1
  27. gitlytics-0.4.1/src/gitlytics/static/robots.txt +0 -5
  28. {gitlytics-0.4.1 → gitlytics-0.4.4}/LICENSE +0 -0
  29. {gitlytics-0.4.1 → gitlytics-0.4.4}/README.md +0 -0
  30. {gitlytics-0.4.1 → gitlytics-0.4.4}/setup.cfg +0 -0
  31. {gitlytics-0.4.1 → gitlytics-0.4.4}/src/gitlytics/__main__.py +0 -0
  32. {gitlytics-0.4.1 → gitlytics-0.4.4}/src/gitlytics/static/_redirects +0 -0
  33. {gitlytics-0.4.1 → gitlytics-0.4.4}/src/gitlytics/static/android-chrome-192x192.png +0 -0
  34. {gitlytics-0.4.1 → gitlytics-0.4.4}/src/gitlytics/static/android-chrome-512x512.png +0 -0
  35. {gitlytics-0.4.1 → gitlytics-0.4.4}/src/gitlytics/static/apple-touch-icon.png +0 -0
  36. {gitlytics-0.4.1 → gitlytics-0.4.4}/src/gitlytics/static/assets/html2canvas-pro.esm-9xys3ejh.js +0 -0
  37. {gitlytics-0.4.1 → gitlytics-0.4.4}/src/gitlytics/static/assets/html2canvas.esm-DXEQVQnt.js +0 -0
  38. {gitlytics-0.4.1 → gitlytics-0.4.4}/src/gitlytics/static/assets/purify.es-CC4Brkr_.js +0 -0
  39. {gitlytics-0.4.1 → gitlytics-0.4.4}/src/gitlytics/static/favicon-16x16.png +0 -0
  40. {gitlytics-0.4.1 → gitlytics-0.4.4}/src/gitlytics/static/favicon-32x32.png +0 -0
  41. {gitlytics-0.4.1 → gitlytics-0.4.4}/src/gitlytics/static/favicon-48x48.png +0 -0
  42. {gitlytics-0.4.1 → gitlytics-0.4.4}/src/gitlytics/static/favicon.ico +0 -0
  43. {gitlytics-0.4.1 → gitlytics-0.4.4}/src/gitlytics/static/gitlytics-logo.png +0 -0
  44. {gitlytics-0.4.1 → gitlytics-0.4.4}/src/gitlytics/static/google-search-icon-48x48.png +0 -0
  45. {gitlytics-0.4.1 → gitlytics-0.4.4}/src/gitlytics/static/google-search-icon.png +0 -0
  46. {gitlytics-0.4.1 → gitlytics-0.4.4}/src/gitlytics/static/sitemap.xml +0 -0
  47. {gitlytics-0.4.1 → gitlytics-0.4.4}/src/gitlytics.egg-info/dependency_links.txt +0 -0
  48. {gitlytics-0.4.1 → gitlytics-0.4.4}/src/gitlytics.egg-info/entry_points.txt +0 -0
  49. {gitlytics-0.4.1 → gitlytics-0.4.4}/src/gitlytics.egg-info/requires.txt +0 -0
  50. {gitlytics-0.4.1 → gitlytics-0.4.4}/src/gitlytics.egg-info/top_level.txt +0 -0
  51. {gitlytics-0.4.1 → gitlytics-0.4.4}/tests/test_automation.py +0 -0
  52. {gitlytics-0.4.1 → gitlytics-0.4.4}/tests/test_core.py +0 -0
  53. {gitlytics-0.4.1 → gitlytics-0.4.4}/tests/test_star_history.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: gitlytics
3
- Version: 0.4.1
3
+ Version: 0.4.4
4
4
  Summary: Monitor and automate your GitHub repository traffic analytics.
5
5
  Author-email: Ameya Chopade <ameyaccod171@gmail.com>
6
6
  License: Apache-2.0
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "gitlytics"
7
- version = "0.4.1"
7
+ version = "0.4.4"
8
8
  description = "Monitor and automate your GitHub repository traffic analytics."
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.9"
@@ -9,7 +9,7 @@ from pathlib import Path
9
9
 
10
10
  # Single source of truth for the package version.
11
11
  # Mirrors the version in pyproject.toml — keep them in sync.
12
- __version__ = "0.4.1"
12
+ __version__ = "0.4.4"
13
13
 
14
14
  __all__ = [
15
15
  "fetch_traffic",
@@ -5,14 +5,16 @@ Powers the FastAPI backend — serves traffic data and the React dashboard to th
5
5
  import hashlib
6
6
  import logging
7
7
  import os
8
+ import secrets
8
9
  import shutil
10
+ import threading as _threading
9
11
  import time as _time
10
12
  import uuid
11
13
  from collections import OrderedDict
12
14
  from pathlib import Path
13
15
 
14
16
  import pandas as pd
15
- from fastapi import FastAPI, HTTPException, Body, File, Header, Response, UploadFile
17
+ from fastapi import FastAPI, HTTPException, Body, File, Header, Request, Response, UploadFile, Depends
16
18
  from fastapi.responses import FileResponse, JSONResponse
17
19
  from fastapi.middleware.cors import CORSMiddleware
18
20
  from fastapi.staticfiles import StaticFiles
@@ -22,13 +24,14 @@ from gitlytics.core import (
22
24
  get_user_profile,
23
25
  get_public_user,
24
26
  get_public_repos,
27
+ validate_github_username,
25
28
  fetch_traffic_data,
26
29
  fetch_deep_stats_for_top,
27
30
  fetch_star_history,
28
31
  GitHubRateLimitError,
29
32
  StarHistoryFetchError,
30
33
  )
31
- from gitlytics.process import process_uploaded_csv, build_react_payload
34
+ from gitlytics.process import process_uploaded_csv, build_react_payload, _to_bool
32
35
 
33
36
  logger = logging.getLogger(__name__)
34
37
 
@@ -39,9 +42,11 @@ app = FastAPI(title="GitHub Traffic API")
39
42
  _ALLOWED_ORIGINS = [
40
43
  "http://localhost",
41
44
  "http://localhost:3000",
45
+ "http://localhost:4173",
42
46
  "http://localhost:8000",
43
47
  "http://127.0.0.1",
44
48
  "http://127.0.0.1:3000",
49
+ "http://127.0.0.1:4173",
45
50
  "http://127.0.0.1:8000",
46
51
  ]
47
52
 
@@ -61,13 +66,57 @@ app.add_middleware(
61
66
  # OrderedDict + insert-order eviction gives us a bounded LRU without
62
67
  # pulling in functools.lru_cache (which can't be cleared on TTL).
63
68
  _auth_cache: "OrderedDict[str, tuple]" = OrderedDict()
64
- _AUTH_CACHE_TTL = 300 # 5 minutes
69
+ _auth_cache_lock = _threading.Lock()
70
+ _AUTH_CACHE_TTL = 300 # 5 minutes — applied only to positive (valid=True) results.
71
+ _AUTH_NEG_TTL = 10 # short TTL for negative results so a transient 5xx doesn't lock the user out.
65
72
  _AUTH_CACHE_MAX = 256 # cap entries so a long-running worker can't grow unbounded
66
73
 
67
74
  # Hard cap on CSV upload size — prevents DoS via /api/upload-csv.
68
75
  _MAX_UPLOAD_BYTES = 25 * 1024 * 1024
69
76
 
70
77
 
78
+ class _SecurityHeadersMiddleware:
79
+ def __init__(self, app):
80
+ self.app = app
81
+
82
+ async def __call__(self, scope, receive, send):
83
+ if scope["type"] != "http":
84
+ await self.app(scope, receive, send)
85
+ return
86
+
87
+ async def send_wrapper(message):
88
+ if message["type"] == "http.response.start":
89
+ headers = list(message.get("headers", []))
90
+ headers.extend([
91
+ (b"x-content-type-options", b"nosniff"),
92
+ (b"x-frame-options", b"DENY"),
93
+ (b"referrer-policy", b"strict-origin-when-cross-origin"),
94
+ ])
95
+ message = {**message, "headers": headers}
96
+ await send(message)
97
+
98
+ await self.app(scope, receive, send_wrapper)
99
+
100
+
101
+ app.add_middleware(_SecurityHeadersMiddleware)
102
+
103
+
104
+ def _require_upload_access(
105
+ request: Request,
106
+ x_upload_key: str | None = Header(default=None),
107
+ ) -> None:
108
+ client_host = (request.client.host if request.client else "").lower()
109
+ if client_host in ("127.0.0.1", "::1", "testclient", "testserver"):
110
+ return
111
+ expected = (os.environ.get("GITLYTICS_UPLOAD_KEY") or "").strip()
112
+ if not expected:
113
+ raise HTTPException(status_code=403, detail="Upload not allowed from this host.")
114
+ got = (x_upload_key or "").strip()
115
+ if got and secrets.compare_digest(got, expected):
116
+ return
117
+ raise HTTPException(status_code=403, detail="Upload not allowed from this host.")
118
+
119
+
71
120
  def _get_token(token: str = None) -> str:
72
121
  # C-2: explicit empty string must not fall through to the env token
73
122
  if token and token.strip():
@@ -77,21 +126,28 @@ def _get_token(token: str = None) -> str:
77
126
 
78
127
  def _validate_token_cached(token: str):
79
128
  # M-1: cache validation results to avoid a double HTTP round-trip on every /api/traffic call
80
- from gitlytics.core import validate_token as _validate_token
81
129
  key = hashlib.sha256(token.encode()).hexdigest()[:16]
82
130
  now = _time.time()
83
- cached = _auth_cache.get(key)
84
- if cached is not None:
85
- valid, username, expires = cached
86
- if now < expires:
87
- # Refresh insertion order so an active key isn't evicted FIFO-style.
88
- _auth_cache.move_to_end(key)
89
- return valid, username
90
- valid, username = _validate_token(token)
91
- _auth_cache[key] = (valid, username, now + _AUTH_CACHE_TTL)
92
- _auth_cache.move_to_end(key)
93
- while len(_auth_cache) > _AUTH_CACHE_MAX:
94
- _auth_cache.popitem(last=False)
131
+ # Lock guards the read-then-write so two threads can't both miss the
132
+ # cache and double-fetch the same token (FastAPI runs sync routes in
133
+ # a worker threadpool, so this race is reachable under load).
134
+ with _auth_cache_lock:
135
+ cached = _auth_cache.get(key)
136
+ if cached is not None:
137
+ valid, username, expires = cached
138
+ if now < expires:
139
+ # Refresh insertion order so an active key isn't evicted FIFO-style.
140
+ _auth_cache.move_to_end(key)
141
+ return valid, username
142
+ valid, username = validate_token(token)
143
+ # Negative results get a short TTL so a transient upstream 5xx doesn't
144
+ # lock the user out for 5 minutes; positive results cache fully.
145
+ ttl = _AUTH_CACHE_TTL if valid else _AUTH_NEG_TTL
146
+ with _auth_cache_lock:
147
+ _auth_cache[key] = (valid, username, now + ttl)
148
+ _auth_cache.move_to_end(key)
149
+ while len(_auth_cache) > _AUTH_CACHE_MAX:
150
+ _auth_cache.popitem(last=False)
95
151
  return valid, username
96
152
 
97
153
 
@@ -131,29 +187,19 @@ def auth(token: str = Body("", embed=True)):
131
187
 
132
188
  @app.post("/api/username")
133
189
  def get_username_data(username: str = Body("", embed=True)):
134
- """Fetches public profile and repos for any GitHub username — no token required."""
135
190
  if not username or not username.strip():
136
191
  raise HTTPException(status_code=400, detail="Username is required.")
137
192
  try:
138
- profile = get_public_user(username.strip())
139
- # Distinguish "user found" (login matches the request) from "GitHub failed
140
- # and we returned a stub". Returning 200 for the latter would silently mask
141
- # upstream outages.
142
- if profile.get("login") == username.strip() and profile.get("html_url"):
143
- pass
144
- elif profile.get("login") == username.strip():
145
- # Found but GitHub didn't include html_url — still treat as success.
146
- pass
147
- else:
148
- raise HTTPException(status_code=502, detail="GitHub did not return a profile.")
149
- repos = get_public_repos(username.strip())
193
+ clean = validate_github_username(username.strip())
194
+ profile = get_public_user(clean)
195
+ repos = get_public_repos(clean)
150
196
  return {"profile": profile, "repos": repos}
151
197
  except ValueError as exc:
152
198
  raise HTTPException(status_code=404, detail=str(exc))
153
- except HTTPException:
154
- raise
199
+ except RuntimeError:
200
+ raise HTTPException(status_code=502, detail="GitHub is temporarily unavailable.")
155
201
  except Exception as exc:
156
- logger.warning(f"Username fetch failed for {username}: {exc}")
202
+ logger.warning("Username fetch failed for %s: %s", username, exc)
157
203
  raise HTTPException(status_code=500, detail="Failed to fetch GitHub data.")
158
204
 
159
205
 
@@ -201,6 +247,13 @@ def get_traffic(token: str = Body("", embed=True)):
201
247
  if not df.empty:
202
248
  df = df.drop_duplicates(subset=["date", "repository"], keep="last")
203
249
 
250
+ # Normalize `is_private` to a real bool. CSV round-trip + pd.concat
251
+ # widens the dtype to object (mix of bool, "True"/"False" strings, and
252
+ # NaN); without this, downstream code calling `bool("False")` would
253
+ # label every public repo as private.
254
+ if not df.empty and "is_private" in df.columns:
255
+ df["is_private"] = df["is_private"].map(_to_bool).astype(bool)
256
+
204
257
  df = df.replace([float('inf'), float('-inf')], None).where(pd.notnull(df), None)
205
258
 
206
259
  # Build a quick view-sum map to find the top 20 repos for deep fetching.
@@ -249,12 +302,20 @@ def get_star_history_endpoint(
249
302
  # sense than 429 here so the SPA can distinguish "GitHub is throttling us"
250
303
  # from "your request was malformed".
251
304
  raise HTTPException(status_code=400, detail=str(exc))
305
+ except ValueError as exc:
306
+ # fetch_star_history raises ValueError for empty owner / repo / trailing slash;
307
+ # returning 400 is more honest than letting Starlette surface a 500.
308
+ raise HTTPException(status_code=400, detail=str(exc))
252
309
  response.headers["Cache-Control"] = "public, max-age=86400"
253
310
  return {"owner": owner, "repo": repo, "points": points}
254
311
 
255
312
 
256
313
  @app.post("/api/upload-csv")
257
- def upload_csv(file: UploadFile = File(...)):
314
+ def upload_csv(
315
+ request: Request,
316
+ file: UploadFile = File(...),
317
+ _: None = Depends(_require_upload_access),
318
+ ):
258
319
  try:
259
320
  data_dir = os.environ.get("GITLYTICS_DATA_DIR")
260
321
  if data_dir:
@@ -289,7 +350,8 @@ def upload_csv(file: UploadFile = File(...)):
289
350
  except HTTPException:
290
351
  raise
291
352
  except Exception as e:
292
- raise HTTPException(status_code=400, detail=str(e))
353
+ logger.warning("CSV upload failed: %s", e)
354
+ raise HTTPException(status_code=400, detail="Failed to process CSV upload.")
293
355
 
294
356
 
295
357
  # Static file serving
@@ -311,21 +373,27 @@ def serve_index():
311
373
  def serve_spa_fallback(full_path: str):
312
374
  """SPA catch-all — returns index.html so React Router handles navigation."""
313
375
  # Any unhandled /api/* path is a real 404, not a SPA route.
314
- if full_path.startswith("api/"):
376
+ if full_path.startswith("api/") or full_path.startswith("assets/"):
315
377
  return JSONResponse(status_code=404, content={"error": "Not found."})
316
378
 
317
- asset_file = frontend_dir / full_path
318
- if asset_file.exists() and asset_file.is_file():
379
+ # Confine the resolved path to frontend_dir — otherwise a request like
380
+ # `GET /..%2F..%2Fapp.py` would let `asset_file` escape the static
381
+ # directory and serve arbitrary files the worker can read.
382
+ frontend_root = frontend_dir.resolve()
383
+ try:
384
+ asset_file = (frontend_dir / full_path).resolve()
385
+ except (OSError, ValueError):
386
+ # `resolve()` can raise on broken symlinks or odd encodings.
387
+ return JSONResponse(status_code=404, content={"error": "Not found."})
388
+ is_inside = asset_file == frontend_root or asset_file.is_relative_to(frontend_root)
389
+ if is_inside and asset_file.is_file():
319
390
  return FileResponse(asset_file)
320
391
 
321
392
  index_file = frontend_dir / "index.html"
322
393
  if index_file.exists():
323
394
  return FileResponse(index_file)
324
395
 
325
- return JSONResponse(
326
- status_code=503,
327
- content={"error": "Dashboard assets not found in the package installation."}
328
- )
396
+ return JSONResponse(status_code=404, content={"error": "Not found."})
329
397
 
330
398
 
331
399
  assets_dir = frontend_dir / "assets"
@@ -177,11 +177,15 @@ def run_sync_cycle(token: str, repo_names=None, data_dir="./data", output_mode="
177
177
 
178
178
  final_rows.sort(key=lambda x: (str(x.get("date", "")), str(x.get("repository", ""))))
179
179
 
180
- # Write everything back to the CSV file
181
- with open(csv_path, "w", newline="", encoding="utf-8") as f:
180
+ # Atomic write: dump to a sibling .tmp file then os.replace() it into
181
+ # place. A crash mid-write leaves the original CSV intact, so a single
182
+ # interrupted sync never corrupts the user's whole traffic history.
183
+ tmp_path = csv_path + ".tmp"
184
+ with open(tmp_path, "w", newline="", encoding="utf-8") as f:
182
185
  writer = csv.DictWriter(f, fieldnames=existing_fields, extrasaction='ignore')
183
186
  writer.writeheader()
184
187
  writer.writerows(final_rows)
188
+ os.replace(tmp_path, csv_path)
185
189
 
186
190
  logger.info(f"Successfully processed traffic data. Added {new_records_added} new daily records to {csv_path}")
187
191
 
@@ -234,19 +238,24 @@ def run_sync(token: str, repo_names=None, data_dir="./data", output_mode="monthl
234
238
  # Always re-validate the token before fetching to catch expiry early
235
239
  is_valid, msg = validate_token(token)
236
240
  if not is_valid:
237
- # Distinguish between a dead token (stop forever) and a network blip (retry next cycle)
241
+ # Distinguish between a dead token (stop forever) and a network
242
+ # blip (retry next cycle). Both 401 and 403 are terminal —
243
+ # 401 means the token is gone; 403 means the token is fine but
244
+ # lacks permissions, which is also a "never coming back" state.
238
245
  msg_lower = msg.lower()
239
246
  is_auth_failure = (
240
247
  "401" in msg
248
+ or "403" in msg
241
249
  or "authentication failed" in msg_lower
242
250
  or "invalid token" in msg_lower
243
251
  or "revoked" in msg_lower
244
252
  or "bad credentials" in msg_lower
253
+ or "insufficient permissions" in msg_lower
245
254
  )
246
255
  if is_auth_failure:
247
256
  logger.critical(
248
- "FATAL: Token is expired, revoked, or invalid (401 Unauthorized). "
249
- "Terminating daemon to prevent zombie process."
257
+ "FATAL: Token is expired, revoked, or lacks permissions "
258
+ "(401/403). Terminating daemon to prevent zombie process."
250
259
  )
251
260
  sys.exit(1)
252
261
  else:
@@ -72,7 +72,12 @@ def main():
72
72
 
73
73
  # ── DASHBOARD subcommand ──────────────────────────────────────────────────
74
74
  dash_parser = subparsers.add_parser("dashboard", help="Serve the local React dashboard.")
75
- dash_parser.add_argument("--host", default="127.0.0.1", help="Host IP.")
75
+ dash_parser.add_argument("--host", default="127.0.0.1", help="Host IP (default 127.0.0.1).")
76
+ dash_parser.add_argument(
77
+ "--public-bind",
78
+ action="store_true",
79
+ help="Allow binding to 0.0.0.0 (insecure without reverse-proxy auth).",
80
+ )
76
81
  dash_parser.add_argument("--port", type=int, default=8000, help="Port to bind.")
77
82
  dash_parser.add_argument("-t", "--token", help="GitHub token for headless TV display.")
78
83
  dash_parser.add_argument("--data-dir", help="Inject historical CSV database.")
@@ -151,9 +156,16 @@ def main():
151
156
  sys.exit(2)
152
157
 
153
158
  elif args.command == "dashboard":
154
- print(f"\n[Gitlytics] Starting Gitlytics Dashboard on http://{args.host}:{args.port}\n")
159
+ host = args.host
160
+ if host == "0.0.0.0" and not args.public_bind:
161
+ print("❌ Error: Use --public-bind to listen on 0.0.0.0 (default is 127.0.0.1).")
162
+ sys.exit(2)
163
+ if args.public_bind:
164
+ host = "0.0.0.0"
165
+ print("⚠️ Warning: dashboard bound to all interfaces — use only behind a trusted network or reverse proxy.")
166
+ print(f"\n[Gitlytics] Starting Gitlytics Dashboard on http://{host}:{args.port}\n")
155
167
  serve_dashboard(
156
- host=args.host,
168
+ host=host,
157
169
  port=args.port,
158
170
  token=token,
159
171
  data_dir=args.data_dir
@@ -18,6 +18,7 @@ from datetime import datetime, timezone, timedelta
18
18
  logger = logging.getLogger(__name__)
19
19
 
20
20
  BASE = "https://api.github.com"
21
+ GITHUB_USERNAME_RE = re.compile(r"^[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,37}[a-zA-Z0-9])?$", re.IGNORECASE)
21
22
  # Single source of truth for the GitHub media-type + API version headers.
22
23
  _GITHUB_BASE_HEADERS = {
23
24
  "Accept": "application/vnd.github+json",
@@ -50,7 +51,8 @@ def validate_token(token: str) -> tuple[bool, str]:
50
51
  except requests.exceptions.ConnectionError:
51
52
  return False, "No internet connection."
52
53
  except Exception as e:
53
- return False, str(e)
54
+ logger.warning("Token validation error: %s", e)
55
+ return False, "Authentication failed."
54
56
 
55
57
  if r.status_code == 200:
56
58
  data = r.json()
@@ -82,8 +84,16 @@ def get_user_profile(token: str) -> dict:
82
84
  return {"login": "", "name": "", "avatar_url": "", "followers": 0, "following": 0}
83
85
 
84
86
 
87
+ def validate_github_username(username: str) -> str:
88
+ u = (username or "").strip()
89
+ if not u or not GITHUB_USERNAME_RE.match(u):
90
+ raise ValueError("Invalid GitHub username.")
91
+ return u
92
+
93
+
85
94
  def get_public_user(username: str) -> dict:
86
95
  """Fetches a public GitHub user profile — no PAT required."""
96
+ username = validate_github_username(username)
87
97
  try:
88
98
  r = requests.get(f"{BASE}/users/{username}", headers=_PUBLIC_HEADERS, timeout=10)
89
99
  if r.status_code == 200:
@@ -104,15 +114,15 @@ def get_public_user(username: str) -> dict:
104
114
  }
105
115
  if r.status_code == 404:
106
116
  raise ValueError(f"User '{username}' not found.")
107
- # 5xx and other unexpected codes — log a warning and return a stub so the
108
- # caller (the API endpoint) can return a 502 without leaking the failure.
109
117
  logger.warning(f"Failed to fetch user {username}: HTTP {r.status_code}")
118
+ raise RuntimeError(f"GitHub returned HTTP {r.status_code}.")
110
119
  except ValueError:
111
- # Re-raise user-not-found as-is.
120
+ raise
121
+ except RuntimeError:
112
122
  raise
113
123
  except Exception as exc:
114
124
  logger.warning(f"Could not fetch public user profile: {exc}")
115
- return {"login": username, "name": username, "avatar_url": ""}
125
+ raise RuntimeError("GitHub is unreachable.") from exc
116
126
 
117
127
 
118
128
  def _normalise_repo(repo: dict) -> dict:
@@ -174,6 +184,7 @@ def _fetch_public_repos_by_stars(username: str, per_page: int) -> list:
174
184
 
175
185
 
176
186
  def get_public_repos(username: str, max_repos: int = 50) -> list:
187
+ username = validate_github_username(username)
177
188
  """
178
189
  Fetches up to max_repos best public repos for a username using two calls:
179
190
  1. Most recently updated (catches active projects)
@@ -2,7 +2,6 @@
2
2
  gitlytics/process.py
3
3
  Handles processing Tidy DataFrames into final JSON formats for the dashboard.
4
4
  """
5
- import ast
6
5
  import json
7
6
  import logging
8
7
  from datetime import datetime, timezone
@@ -23,6 +22,31 @@ def _is_nullish(val) -> bool:
23
22
  return s in ("", "nan", "none", "null")
24
23
 
25
24
 
25
+ def _to_bool(val) -> bool:
26
+ """Parse a value as a strict boolean.
27
+
28
+ `bool("False")` returns True because every non-empty string is truthy,
29
+ which silently corrupts CSV-roundtripped `is_private` columns. This
30
+ helper accepts bool / numeric / common string spellings and returns
31
+ False for anything ambiguous.
32
+ """
33
+ if isinstance(val, bool):
34
+ return val
35
+ if val is None:
36
+ return False
37
+ if isinstance(val, (int, float)):
38
+ # Catch NaN explicitly so a missing-cell numeric doesn't propagate.
39
+ try:
40
+ if np.isnan(val):
41
+ return False
42
+ except (TypeError, ValueError):
43
+ pass
44
+ return bool(val)
45
+ if isinstance(val, str):
46
+ return val.strip().lower() in ("true", "1", "yes", "y", "t")
47
+ return False
48
+
49
+
26
50
  def build_json_payload(df: pd.DataFrame, return_format: str = "timeseries", export_public_only: bool = True) -> dict:
27
51
  """Transforms the Tidy Data DataFrame into the nested JSON structure."""
28
52
  if df.empty:
@@ -52,7 +76,7 @@ def build_json_payload(df: pd.DataFrame, return_format: str = "timeseries", expo
52
76
  r_unique_c = _safe_int(group["unique_cloners"].sum()) if "unique_cloners" in group.columns else 0
53
77
  r_stars = _safe_int(group["stars"].dropna().iloc[-1]) if "stars" in group.columns and not group["stars"].dropna().empty else 0
54
78
  r_forks = _safe_int(group["forks"].dropna().iloc[-1]) if "forks" in group.columns and not group["forks"].dropna().empty else 0
55
- r_is_private = bool(group["is_private"].dropna().iloc[-1]) if "is_private" in group.columns and not group["is_private"].dropna().empty else False
79
+ r_is_private = _to_bool(group["is_private"].dropna().iloc[-1]) if "is_private" in group.columns and not group["is_private"].dropna().empty else False
56
80
 
57
81
  top_ref = _safe_str(group["top_referrer"].dropna().iloc[-1]) if "top_referrer" in group.columns and not group["top_referrer"].dropna().empty else ""
58
82
  top_path = _safe_str(group["top_path"].dropna().iloc[-1]) if "top_path" in group.columns and not group["top_path"].dropna().empty else ""
@@ -131,23 +155,27 @@ def process_uploaded_csv(uploaded_file) -> pd.DataFrame:
131
155
 
132
156
  if "date" not in raw_df.columns:
133
157
  raise ValueError("Invalid CSV format: missing required 'date' column")
158
+
159
+ # Coerce `is_private` to a real bool. CSVs from any external tool tend
160
+ # to write True/False as strings ("True"/"False") or as 1/0, and a
161
+ # missing column concatenated later widens the dtype to object. Doing
162
+ # this here keeps every downstream consumer safe.
163
+ if "is_private" in raw_df.columns:
164
+ raw_df["is_private"] = raw_df["is_private"].map(_to_bool).astype(bool)
134
165
  return raw_df
135
166
 
136
167
 
137
168
  def _parse_raw(val) -> list:
138
- # Try JSON first, then Python literal eval, then give up
139
169
  if _is_nullish(val):
140
170
  return []
141
171
  if isinstance(val, list):
142
172
  return val
143
173
  try:
144
- return json.loads(val)
174
+ parsed = json.loads(val)
175
+ return parsed if isinstance(parsed, list) else []
145
176
  except Exception:
146
- try:
147
- return ast.literal_eval(val)
148
- except Exception:
149
- logger.warning(f"_parse_raw: could not decode value {val!r:.80}; returning []")
150
- return []
177
+ logger.warning(f"_parse_raw: could not decode value {val!r:.80}; returning []")
178
+ return []
151
179
 
152
180
 
153
181
  def _safe_int(val, fallback=0) -> int:
@@ -191,7 +219,7 @@ def build_react_payload(df: pd.DataFrame, deep_stats: dict = None) -> list:
191
219
  r_unique_c = _safe_int(group["unique_cloners"].sum()) if "unique_cloners" in group.columns else 0
192
220
  r_stars = _safe_int(group["stars"].dropna().iloc[-1]) if "stars" in group.columns and not group["stars"].dropna().empty else 0
193
221
  r_forks = _safe_int(group["forks"].dropna().iloc[-1]) if "forks" in group.columns and not group["forks"].dropna().empty else 0
194
- r_is_private = bool(group["is_private"].dropna().iloc[-1]) if "is_private" in group.columns and not group["is_private"].dropna().empty else False
222
+ r_is_private = _to_bool(group["is_private"].dropna().iloc[-1]) if "is_private" in group.columns and not group["is_private"].dropna().empty else False
195
223
 
196
224
  top_ref = _safe_str(group["top_referrer"].dropna().iloc[-1]) if "top_referrer" in group.columns and not group["top_referrer"].dropna().empty else ""
197
225
  top_ref_views = _safe_int(group["top_referrer_views"].dropna().iloc[-1]) if "top_referrer_views" in group.columns and not group["top_referrer_views"].dropna().empty else 0
@@ -0,0 +1,6 @@
1
+ /*
2
+ X-Frame-Options: DENY
3
+ X-Content-Type-Options: nosniff
4
+ Referrer-Policy: strict-origin-when-cross-origin
5
+ Permissions-Policy: camera=(), microphone=(), geolocation=()
6
+ Content-Security-Policy: default-src 'self'; script-src 'self' 'unsafe-inline' https://www.googletagmanager.com https://www.google-analytics.com https://scripts.clarity.ms https://www.clarity.ms; connect-src 'self' https://api.gitlytics.dev https://api.github.com https://www.google-analytics.com https://*.google-analytics.com https://www.googletagmanager.com https://*.clarity.ms; img-src 'self' data: https://api.gitlytics.dev https://avatars.githubusercontent.com https://github.com https://raw.githubusercontent.com https://www.google-analytics.com; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; font-src 'self' data: https://fonts.gstatic.com; frame-ancestors 'none'; base-uri 'self'; form-action 'self'
@@ -1 +1 @@
1
- import{r as j,b as k,a as D,j as e,X as E,I as $,W as v,S as w,G as y,P as G,U as I}from"./index-CSjcErui.js";import{b as O}from"./exports-CRz2A0EU.js";function U({profile:a,repos:t,onClose:c}){const[i,f]=j.useState({profile:!0,stats:!0,languages:!0,popular:!0,followers:!1}),[m,n]=j.useState(!1),{totalStars:u,totalForks:o,repoCount:g,topLangs:d,popular:p,langShares:C}=j.useMemo(()=>{const l=t.reduce((r,s)=>r+(Number(s.stars)||0),0),x=t.reduce((r,s)=>r+(Number(s.forks)||0),0),z=t.length,b=new Map;for(const r of t){const s=k(r);b.set(s,(b.get(s)||0)+1)}const F=[...b.entries()].sort((r,s)=>s[1]-r[1]).slice(0,3).map(([r])=>r),P=[...t].sort((r,s)=>(Number(s.stars)||0)-(Number(r.stars)||0))[0],N=[...b.values()].reduce((r,s)=>r+s,0),M=[...b.entries()].sort((r,s)=>s[1]-r[1]).slice(0,3).map(([r,s])=>({name:r,percentage:N>0?Math.round(s/N*100):0}));return{totalStars:l,totalForks:x,repoCount:z,topLangs:F,popular:P,langShares:M}},[t]);async function S(){n(!0);try{await O(a.username),c()}catch{}finally{n(!1)}}const L=l=>f(x=>({...x,[l]:!x[l]}));return D.createPortal(e.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-background/95 p-4 backdrop-blur-md",onClick:()=>!m&&c(),children:e.jsxs("div",{className:"glass animate-slide-up w-full max-w-4xl overflow-hidden rounded-xl border border-border",onClick:l=>l.stopPropagation(),children:[e.jsxs("div",{className:"flex items-center justify-between border-b border-border p-4",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-sm font-semibold",children:"Create Developer Card"}),e.jsx("p",{className:"mt-0.5 text-xs text-muted-foreground",children:"Shareable image for X and LinkedIn"})]}),e.jsx("button",{onClick:()=>!m&&c(),"aria-label":"Close",className:"rounded-lg p-1 text-muted-foreground transition-colors hover:bg-foreground/5 hover:text-foreground",children:e.jsx(E,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"grid gap-5 p-5 md:grid-cols-[1fr_240px]",children:[e.jsx("div",{className:"flex items-center justify-center rounded-lg border border-border/60 bg-background/30 p-4",children:e.jsx(T,{profile:a,opts:i,totalStars:u,totalForks:o,repoCount:g,topLangs:d,popular:p,langShares:C})}),e.jsxs("div",{className:"space-y-2 text-sm",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Include"}),[["profile","Profile info"],["stats","Stats"],["languages","Top languages"],["popular","Most popular repo"],["followers","Followers / following"]].map(([l,x])=>e.jsxs("label",{className:"flex cursor-pointer items-center gap-2.5 rounded-lg border border-border/60 bg-background/30 px-3 py-2 transition-colors hover:bg-foreground/5",children:[e.jsx("input",{type:"checkbox",checked:i[l],onChange:()=>L(l),className:"h-4 w-4 cursor-pointer accent-primary"}),x]},l)),e.jsxs("label",{className:"flex items-center gap-2.5 rounded-lg border border-border/60 bg-background/30 px-3 py-2 opacity-70",children:[e.jsx("input",{type:"checkbox",checked:!0,readOnly:!0,className:"h-4 w-4 accent-primary"}),"Gitlytics branding"]}),e.jsxs("button",{onClick:S,disabled:m,className:"mt-3 flex w-full items-center justify-center gap-1.5 rounded-lg bg-primary px-4 py-2.5 text-sm font-semibold text-primary-foreground transition-transform hover:scale-[1.01] disabled:opacity-50",children:[e.jsx($,{className:"h-4 w-4"}),m?"Generating…":"Download Card"]})]})]})]})}),document.body)}function T({profile:a,opts:t,totalStars:c,totalForks:i,repoCount:f,topLangs:m,popular:n,langShares:u}){return e.jsxs("div",{id:"developer-card",className:"relative w-[480px] rounded-2xl border border-border/80 p-6 shadow-2xl bg-[#141312] overflow-hidden",children:[e.jsx("div",{className:"absolute -right-20 -top-20 h-40 w-40 rounded-full bg-primary/10 pointer-events-none"}),e.jsx("div",{className:"absolute -left-20 -bottom-20 h-40 w-40 rounded-full bg-chart-2/10 pointer-events-none"}),e.jsxs("div",{className:"relative z-10 mb-5 flex items-center gap-2",children:[e.jsx("img",{src:"/gitlytics-logo.png",alt:"",className:"h-5 w-5 object-contain"}),e.jsx(v,{className:"text-xs font-bold tracking-wider uppercase opacity-90"})]}),t.profile&&e.jsxs("div",{className:"relative z-10 mb-5 flex items-center gap-4",children:[e.jsx("img",{src:a.avatar_url,alt:"",crossOrigin:"anonymous",onError:o=>{o.currentTarget.src="/gitlytics-logo.png"},className:"h-16 w-16 rounded-full border-2 border-primary/50 p-0.5 bg-surface/40 object-cover shadow-lg shadow-primary/5"}),e.jsxs("div",{className:"leading-tight",children:[e.jsx("p",{className:"text-lg font-bold tracking-tight text-foreground",children:a.name||a.username}),e.jsxs("p",{className:"text-xs font-semibold text-primary",children:["@",a.username]}),(a.bio||a.location)&&e.jsx("p",{className:"mt-1 text-xs text-muted-foreground line-clamp-2 max-w-[340px]",children:[a.bio,a.location].filter(Boolean).join(" · ")})]})]}),t.stats&&e.jsxs("div",{className:`relative z-10 mb-5 grid gap-2.5 text-xs ${t.followers?"grid-cols-4":"grid-cols-3"}`,children:[e.jsx(h,{icon:e.jsx(w,{className:"h-4 w-4"}),label:"Stars",value:c,colorClass:"text-chart-2"}),e.jsx(h,{icon:e.jsx(y,{className:"h-4 w-4"}),label:"Forks",value:i,colorClass:"text-chart-4"}),e.jsx(h,{icon:e.jsx(G,{className:"h-4 w-4"}),label:"Repos",value:f,colorClass:"text-chart-3"}),t.followers&&e.jsx(h,{icon:e.jsx(I,{className:"h-4 w-4"}),label:"Followers",value:a.followers??0,colorClass:"text-primary"})]}),t.languages&&u.length>0&&e.jsxs("div",{className:"relative z-10 mb-5",children:[e.jsx("p",{className:"mb-2 text-[10px] uppercase tracking-wider text-muted-foreground/80 font-bold",children:"Top Languages"}),e.jsx("div",{className:"mb-3 h-2 w-full rounded-full bg-foreground/5 overflow-hidden flex",children:u.map((o,g)=>{const d=["bg-primary","bg-chart-2","bg-chart-3","bg-chart-4"],p=d[g%d.length];return e.jsx("div",{style:{width:`${o.percentage}%`},className:`${p} h-full`},o.name)})}),e.jsx("div",{className:"flex flex-wrap gap-x-4 gap-y-1.5",children:u.map((o,g)=>{const d=["bg-primary","bg-chart-2","bg-chart-3","bg-chart-4"],p=d[g%d.length];return e.jsxs("div",{className:"flex items-center gap-1.5 text-xs",children:[e.jsx("span",{className:`h-2 w-2 rounded-full ${p}`}),e.jsx("span",{className:"font-semibold text-foreground",children:o.name}),e.jsxs("span",{className:"text-muted-foreground font-medium",children:[o.percentage,"%"]})]},o.name)})})]}),t.popular&&n&&e.jsxs("div",{className:"relative z-10 mb-5 rounded-xl border border-border/50 bg-foreground/[0.01] p-3.5 hover:bg-foreground/[0.02] transition-colors group",children:[e.jsx("p",{className:"mb-1.5 text-[10px] uppercase tracking-wider text-muted-foreground/80 font-bold",children:"Most Popular Project"}),e.jsx("p",{className:"truncate text-sm font-bold text-foreground group-hover:text-primary transition-colors",children:n.repository}),e.jsxs("div",{className:"mt-2 flex items-center gap-3 text-xs text-muted-foreground font-semibold",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(w,{className:"h-3.5 w-3.5 text-chart-2 fill-chart-2/10"})," ",n.stars]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(y,{className:"h-3.5 w-3.5 text-chart-4"})," ",n.forks]}),e.jsx("span",{className:"h-1.5 w-1.5 rounded-full bg-primary"}),e.jsx("span",{children:k(n)})]})]}),e.jsxs("p",{className:"relative z-10 mt-1 text-center text-[10px] tracking-wide text-muted-foreground/80",children:[e.jsx(v,{className:"font-bold inline"})," · gitlytics.dev"]})]})}function h({icon:a,label:t,value:c,colorClass:i="text-primary"}){return e.jsxs("div",{className:"flex flex-col rounded-xl border border-border/50 bg-foreground/[0.02] p-2.5 transition-all hover:bg-foreground/[0.04] relative overflow-hidden group",children:[e.jsxs("div",{className:"flex items-center justify-between text-muted-foreground",children:[e.jsx("span",{className:"text-[9px] font-bold uppercase tracking-wider text-muted-foreground/75",children:t}),e.jsx("span",{className:`transition-transform group-hover:scale-110 ${i}`,children:a})]}),e.jsx("span",{className:"text-base font-bold tracking-tight tabular-nums text-foreground mt-1.5",children:(Number(c)||0).toLocaleString()})]})}export{U as CardModal};
1
+ import{r as j,b as k,a as D,j as e,X as E,I as $,W as v,S as w,G as y,P as G,U as I}from"./index-qzHj2txI.js";import{b as O}from"./exports-BD7YfSBX.js";function U({profile:a,repos:t,onClose:c}){const[i,f]=j.useState({profile:!0,stats:!0,languages:!0,popular:!0,followers:!1}),[m,n]=j.useState(!1),{totalStars:u,totalForks:o,repoCount:g,topLangs:d,popular:p,langShares:C}=j.useMemo(()=>{const l=t.reduce((r,s)=>r+(Number(s.stars)||0),0),x=t.reduce((r,s)=>r+(Number(s.forks)||0),0),z=t.length,b=new Map;for(const r of t){const s=k(r);b.set(s,(b.get(s)||0)+1)}const F=[...b.entries()].sort((r,s)=>s[1]-r[1]).slice(0,3).map(([r])=>r),P=[...t].sort((r,s)=>(Number(s.stars)||0)-(Number(r.stars)||0))[0],N=[...b.values()].reduce((r,s)=>r+s,0),M=[...b.entries()].sort((r,s)=>s[1]-r[1]).slice(0,3).map(([r,s])=>({name:r,percentage:N>0?Math.round(s/N*100):0}));return{totalStars:l,totalForks:x,repoCount:z,topLangs:F,popular:P,langShares:M}},[t]);async function S(){n(!0);try{await O(a.username),c()}catch{}finally{n(!1)}}const L=l=>f(x=>({...x,[l]:!x[l]}));return D.createPortal(e.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-background/95 p-4 backdrop-blur-md",onClick:()=>!m&&c(),children:e.jsxs("div",{className:"glass animate-slide-up w-full max-w-4xl overflow-hidden rounded-xl border border-border",onClick:l=>l.stopPropagation(),children:[e.jsxs("div",{className:"flex items-center justify-between border-b border-border p-4",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-sm font-semibold",children:"Create Developer Card"}),e.jsx("p",{className:"mt-0.5 text-xs text-muted-foreground",children:"Shareable image for X and LinkedIn"})]}),e.jsx("button",{onClick:()=>!m&&c(),"aria-label":"Close",className:"rounded-lg p-1 text-muted-foreground transition-colors hover:bg-foreground/5 hover:text-foreground",children:e.jsx(E,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"grid gap-5 p-5 md:grid-cols-[1fr_240px]",children:[e.jsx("div",{className:"flex items-center justify-center rounded-lg border border-border/60 bg-background/30 p-4",children:e.jsx(T,{profile:a,opts:i,totalStars:u,totalForks:o,repoCount:g,topLangs:d,popular:p,langShares:C})}),e.jsxs("div",{className:"space-y-2 text-sm",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Include"}),[["profile","Profile info"],["stats","Stats"],["languages","Top languages"],["popular","Most popular repo"],["followers","Followers / following"]].map(([l,x])=>e.jsxs("label",{className:"flex cursor-pointer items-center gap-2.5 rounded-lg border border-border/60 bg-background/30 px-3 py-2 transition-colors hover:bg-foreground/5",children:[e.jsx("input",{type:"checkbox",checked:i[l],onChange:()=>L(l),className:"h-4 w-4 cursor-pointer accent-primary"}),x]},l)),e.jsxs("label",{className:"flex items-center gap-2.5 rounded-lg border border-border/60 bg-background/30 px-3 py-2 opacity-70",children:[e.jsx("input",{type:"checkbox",checked:!0,readOnly:!0,className:"h-4 w-4 accent-primary"}),"Gitlytics branding"]}),e.jsxs("button",{onClick:S,disabled:m,className:"mt-3 flex w-full items-center justify-center gap-1.5 rounded-lg bg-primary px-4 py-2.5 text-sm font-semibold text-primary-foreground transition-transform hover:scale-[1.01] disabled:opacity-50",children:[e.jsx($,{className:"h-4 w-4"}),m?"Generating…":"Download Card"]})]})]})]})}),document.body)}function T({profile:a,opts:t,totalStars:c,totalForks:i,repoCount:f,topLangs:m,popular:n,langShares:u}){return e.jsxs("div",{id:"developer-card",className:"relative w-[480px] rounded-2xl border border-border/80 p-6 shadow-2xl bg-[#141312] overflow-hidden",children:[e.jsx("div",{className:"absolute -right-20 -top-20 h-40 w-40 rounded-full bg-primary/10 pointer-events-none"}),e.jsx("div",{className:"absolute -left-20 -bottom-20 h-40 w-40 rounded-full bg-chart-2/10 pointer-events-none"}),e.jsxs("div",{className:"relative z-10 mb-5 flex items-center gap-2",children:[e.jsx("img",{src:"/gitlytics-logo.png",alt:"",className:"h-5 w-5 object-contain"}),e.jsx(v,{className:"text-xs font-bold tracking-wider uppercase opacity-90"})]}),t.profile&&e.jsxs("div",{className:"relative z-10 mb-5 flex items-center gap-4",children:[e.jsx("img",{src:a.avatar_url,alt:"",crossOrigin:"anonymous",onError:o=>{o.currentTarget.src="/gitlytics-logo.png"},className:"h-16 w-16 rounded-full border-2 border-primary/50 p-0.5 bg-surface/40 object-cover shadow-lg shadow-primary/5"}),e.jsxs("div",{className:"leading-tight",children:[e.jsx("p",{className:"text-lg font-bold tracking-tight text-foreground",children:a.name||a.username}),e.jsxs("p",{className:"text-xs font-semibold text-primary",children:["@",a.username]}),(a.bio||a.location)&&e.jsx("p",{className:"mt-1 text-xs text-muted-foreground line-clamp-2 max-w-[340px]",children:[a.bio,a.location].filter(Boolean).join(" · ")})]})]}),t.stats&&e.jsxs("div",{className:`relative z-10 mb-5 grid gap-2.5 text-xs ${t.followers?"grid-cols-4":"grid-cols-3"}`,children:[e.jsx(h,{icon:e.jsx(w,{className:"h-4 w-4"}),label:"Stars",value:c,colorClass:"text-chart-2"}),e.jsx(h,{icon:e.jsx(y,{className:"h-4 w-4"}),label:"Forks",value:i,colorClass:"text-chart-4"}),e.jsx(h,{icon:e.jsx(G,{className:"h-4 w-4"}),label:"Repos",value:f,colorClass:"text-chart-3"}),t.followers&&e.jsx(h,{icon:e.jsx(I,{className:"h-4 w-4"}),label:"Followers",value:a.followers??0,colorClass:"text-primary"})]}),t.languages&&u.length>0&&e.jsxs("div",{className:"relative z-10 mb-5",children:[e.jsx("p",{className:"mb-2 text-[10px] uppercase tracking-wider text-muted-foreground/80 font-bold",children:"Top Languages"}),e.jsx("div",{className:"mb-3 h-2 w-full rounded-full bg-foreground/5 overflow-hidden flex",children:u.map((o,g)=>{const d=["bg-primary","bg-chart-2","bg-chart-3","bg-chart-4"],p=d[g%d.length];return e.jsx("div",{style:{width:`${o.percentage}%`},className:`${p} h-full`},o.name)})}),e.jsx("div",{className:"flex flex-wrap gap-x-4 gap-y-1.5",children:u.map((o,g)=>{const d=["bg-primary","bg-chart-2","bg-chart-3","bg-chart-4"],p=d[g%d.length];return e.jsxs("div",{className:"flex items-center gap-1.5 text-xs",children:[e.jsx("span",{className:`h-2 w-2 rounded-full ${p}`}),e.jsx("span",{className:"font-semibold text-foreground",children:o.name}),e.jsxs("span",{className:"text-muted-foreground font-medium",children:[o.percentage,"%"]})]},o.name)})})]}),t.popular&&n&&e.jsxs("div",{className:"relative z-10 mb-5 rounded-xl border border-border/50 bg-foreground/[0.01] p-3.5 hover:bg-foreground/[0.02] transition-colors group",children:[e.jsx("p",{className:"mb-1.5 text-[10px] uppercase tracking-wider text-muted-foreground/80 font-bold",children:"Most Popular Project"}),e.jsx("p",{className:"truncate text-sm font-bold text-foreground group-hover:text-primary transition-colors",children:n.repository}),e.jsxs("div",{className:"mt-2 flex items-center gap-3 text-xs text-muted-foreground font-semibold",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(w,{className:"h-3.5 w-3.5 text-chart-2 fill-chart-2/10"})," ",n.stars]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(y,{className:"h-3.5 w-3.5 text-chart-4"})," ",n.forks]}),e.jsx("span",{className:"h-1.5 w-1.5 rounded-full bg-primary"}),e.jsx("span",{children:k(n)})]})]}),e.jsxs("p",{className:"relative z-10 mt-1 text-center text-[10px] tracking-wide text-muted-foreground/80",children:[e.jsx(v,{className:"font-bold inline"})," · gitlytics.dev"]})]})}function h({icon:a,label:t,value:c,colorClass:i="text-primary"}){return e.jsxs("div",{className:"flex flex-col rounded-xl border border-border/50 bg-foreground/[0.02] p-2.5 transition-all hover:bg-foreground/[0.04] relative overflow-hidden group",children:[e.jsxs("div",{className:"flex items-center justify-between text-muted-foreground",children:[e.jsx("span",{className:"text-[9px] font-bold uppercase tracking-wider text-muted-foreground/75",children:t}),e.jsx("span",{className:`transition-transform group-hover:scale-110 ${i}`,children:a})]}),e.jsx("span",{className:"text-base font-bold tracking-tight tabular-nums text-foreground mt-1.5",children:(Number(c)||0).toLocaleString()})]})}export{U as CardModal};
@@ -1 +1 @@
1
- import{r as l,a as S,j as t,X as P,C as T,I as A,F as D}from"./index-CSjcErui.js";import{r as G,a as I}from"./exports-CRz2A0EU.js";const j=[{id:"section-hero",label:"Lifetime Stats Hero Card",default:!0},{id:"section-issues-prs",label:"Issues and PRs Summary Card",default:!0},{id:"section-stat-cards",label:"6 Stat Cards",default:!0},{id:"section-top10-charts",label:"Top 10 Charts",default:!0},{id:"section-star-history",label:"Star History Chart",default:!0},{id:"section-referrer-aggregation",label:"Global Referrer Aggregation",default:!1},{id:"section-heatmap",label:"Traffic Patterns Heatmap",default:!1},{id:"section-languages",label:"Language Distribution",default:!1},{id:"section-commits",label:"Commit Activity",default:!1},{id:"section-most-cloned",label:"Most Cloned Repositories Table",default:!1},{id:"section-all-repos",label:"All Repositories Table",default:!0}];function O({onClose:u,mode:a="png",allRepos:o,defaultRepos:m,runWithRepos:y,profile:p}){const[d,x]=l.useState(!1),n=l.useMemo(()=>typeof document>"u"?j:j.filter(e=>document.getElementById(e.id)!==null),[]),[f,g]=l.useState(Object.fromEntries(n.map(e=>[e.id,e.default])));l.useEffect(()=>{g(Object.fromEntries(n.map(e=>[e.id,e.default])))},[n]);const N=m.length>0&&m.length<o.length?m:o,[s,h]=l.useState(N),w=e=>g(r=>({...r,[e]:!r[e]})),v=a==="pdf"?!0:Object.values(f).some(Boolean),i=s.length===o.length,b=l.useMemo(()=>i?"All repos":s.length===1?s[0]:`${s.length} repos`,[s,i]);function C(e){h(r=>r.includes(e)?r.filter(c=>c!==e):[...r,e])}function k(){h(i?[]:o)}async function E(){if(s.length!==0){x(!0);try{await y(i?[]:s,async()=>{if(a==="png"){const r=n.filter(c=>f[c.id]).map(c=>c.id);if(r.length===0)return;await G(r,b,p)}else await I(b,p)}),u()}catch{}finally{x(!1)}}}return S.createPortal(t.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-background/95 p-4 backdrop-blur-md",onClick:()=>!d&&u(),children:t.jsxs("div",{className:"glass animate-slide-up flex max-h-[90vh] w-full max-w-lg flex-col overflow-hidden rounded-xl border border-border",onClick:e=>e.stopPropagation(),children:[t.jsxs("div",{className:"flex shrink-0 items-center justify-between border-b border-border p-4",children:[t.jsxs("div",{children:[t.jsx("h3",{className:"text-sm font-semibold",children:a==="png"?"Export PNG":"Export PDF"}),t.jsx("p",{className:"mt-0.5 text-xs text-muted-foreground",children:a==="png"?"Choose repositories and sections to include":"Choose repositories to include in the full report"})]}),t.jsx("button",{onClick:()=>!d&&u(),"aria-label":"Close",className:"rounded-lg p-1 text-muted-foreground transition-colors hover:bg-foreground/5 hover:text-foreground",children:t.jsx(P,{className:"h-4 w-4"})})]}),t.jsxs("div",{className:"flex-1 space-y-4 overflow-y-auto p-5",children:[t.jsxs("div",{children:[t.jsxs("div",{className:"mb-1.5 flex items-center justify-between",children:[t.jsxs("p",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:["Repositories (",s.length,"/",o.length,")"]}),t.jsx("button",{onClick:k,className:"text-xs font-medium text-primary hover:underline",children:i?"Clear all":"Select all"})]}),t.jsx("div",{className:"max-h-40 space-y-1 overflow-auto rounded-lg border border-border/60 bg-background/30 p-2",children:o.map(e=>{const r=s.includes(e);return t.jsxs("button",{onClick:()=>C(e),className:"flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-xs hover:bg-foreground/5",children:[t.jsx("span",{className:`flex h-4 w-4 shrink-0 items-center justify-center rounded border ${r?"border-primary bg-primary text-primary-foreground":"border-input"}`,children:r&&t.jsx(T,{className:"h-3 w-3"})}),t.jsx("span",{className:"truncate",children:e})]},e)})})]}),a==="png"&&t.jsxs("div",{className:"space-y-1.5",children:[t.jsx("p",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Sections"}),n.length===0&&t.jsx("p",{className:"text-xs text-muted-foreground",children:"No exportable sections in the current view."}),n.map(e=>t.jsxs("label",{className:"flex cursor-pointer items-center gap-2.5 rounded-lg border border-border/60 bg-background/30 px-3 py-2 text-sm transition-colors hover:bg-foreground/5",children:[t.jsx("input",{type:"checkbox",checked:f[e.id],onChange:()=>w(e.id),className:"h-4 w-4 cursor-pointer accent-primary"}),e.label]},e.id))]}),t.jsxs("button",{onClick:E,disabled:d||!v||s.length===0,className:"flex w-full items-center justify-center gap-1.5 rounded-lg bg-primary px-4 py-2.5 text-sm font-semibold text-primary-foreground transition-transform hover:scale-[1.01] disabled:opacity-50",children:[a==="png"?t.jsx(A,{className:"h-4 w-4"}):t.jsx(D,{className:"h-4 w-4"}),d?"Generating…":a==="png"?"Export PNG":"Export PDF"]})]})]})}),document.body)}export{O as ExportModal};
1
+ import{r as l,a as S,j as t,X as P,C as T,I as A,F as D}from"./index-qzHj2txI.js";import{r as G,a as I}from"./exports-BD7YfSBX.js";const j=[{id:"section-hero",label:"Lifetime Stats Hero Card",default:!0},{id:"section-issues-prs",label:"Issues and PRs Summary Card",default:!0},{id:"section-stat-cards",label:"6 Stat Cards",default:!0},{id:"section-top10-charts",label:"Top 10 Charts",default:!0},{id:"section-star-history",label:"Star History Chart",default:!0},{id:"section-referrer-aggregation",label:"Global Referrer Aggregation",default:!1},{id:"section-heatmap",label:"Traffic Patterns Heatmap",default:!1},{id:"section-languages",label:"Language Distribution",default:!1},{id:"section-commits",label:"Commit Activity",default:!1},{id:"section-most-cloned",label:"Most Cloned Repositories Table",default:!1},{id:"section-all-repos",label:"All Repositories Table",default:!0}];function O({onClose:u,mode:a="png",allRepos:o,defaultRepos:m,runWithRepos:y,profile:p}){const[d,x]=l.useState(!1),n=l.useMemo(()=>typeof document>"u"?j:j.filter(e=>document.getElementById(e.id)!==null),[]),[f,g]=l.useState(Object.fromEntries(n.map(e=>[e.id,e.default])));l.useEffect(()=>{g(Object.fromEntries(n.map(e=>[e.id,e.default])))},[n]);const N=m.length>0&&m.length<o.length?m:o,[s,h]=l.useState(N),w=e=>g(r=>({...r,[e]:!r[e]})),v=a==="pdf"?!0:Object.values(f).some(Boolean),i=s.length===o.length,b=l.useMemo(()=>i?"All repos":s.length===1?s[0]:`${s.length} repos`,[s,i]);function C(e){h(r=>r.includes(e)?r.filter(c=>c!==e):[...r,e])}function k(){h(i?[]:o)}async function E(){if(s.length!==0){x(!0);try{await y(i?[]:s,async()=>{if(a==="png"){const r=n.filter(c=>f[c.id]).map(c=>c.id);if(r.length===0)return;await G(r,b,p)}else await I(b,p)}),u()}catch{}finally{x(!1)}}}return S.createPortal(t.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-background/95 p-4 backdrop-blur-md",onClick:()=>!d&&u(),children:t.jsxs("div",{className:"glass animate-slide-up flex max-h-[90vh] w-full max-w-lg flex-col overflow-hidden rounded-xl border border-border",onClick:e=>e.stopPropagation(),children:[t.jsxs("div",{className:"flex shrink-0 items-center justify-between border-b border-border p-4",children:[t.jsxs("div",{children:[t.jsx("h3",{className:"text-sm font-semibold",children:a==="png"?"Export PNG":"Export PDF"}),t.jsx("p",{className:"mt-0.5 text-xs text-muted-foreground",children:a==="png"?"Choose repositories and sections to include":"Choose repositories to include in the full report"})]}),t.jsx("button",{onClick:()=>!d&&u(),"aria-label":"Close",className:"rounded-lg p-1 text-muted-foreground transition-colors hover:bg-foreground/5 hover:text-foreground",children:t.jsx(P,{className:"h-4 w-4"})})]}),t.jsxs("div",{className:"flex-1 space-y-4 overflow-y-auto p-5",children:[t.jsxs("div",{children:[t.jsxs("div",{className:"mb-1.5 flex items-center justify-between",children:[t.jsxs("p",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:["Repositories (",s.length,"/",o.length,")"]}),t.jsx("button",{onClick:k,className:"text-xs font-medium text-primary hover:underline",children:i?"Clear all":"Select all"})]}),t.jsx("div",{className:"max-h-40 space-y-1 overflow-auto rounded-lg border border-border/60 bg-background/30 p-2",children:o.map(e=>{const r=s.includes(e);return t.jsxs("button",{onClick:()=>C(e),className:"flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-xs hover:bg-foreground/5",children:[t.jsx("span",{className:`flex h-4 w-4 shrink-0 items-center justify-center rounded border ${r?"border-primary bg-primary text-primary-foreground":"border-input"}`,children:r&&t.jsx(T,{className:"h-3 w-3"})}),t.jsx("span",{className:"truncate",children:e})]},e)})})]}),a==="png"&&t.jsxs("div",{className:"space-y-1.5",children:[t.jsx("p",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Sections"}),n.length===0&&t.jsx("p",{className:"text-xs text-muted-foreground",children:"No exportable sections in the current view."}),n.map(e=>t.jsxs("label",{className:"flex cursor-pointer items-center gap-2.5 rounded-lg border border-border/60 bg-background/30 px-3 py-2 text-sm transition-colors hover:bg-foreground/5",children:[t.jsx("input",{type:"checkbox",checked:f[e.id],onChange:()=>w(e.id),className:"h-4 w-4 cursor-pointer accent-primary"}),e.label]},e.id))]}),t.jsxs("button",{onClick:E,disabled:d||!v||s.length===0,className:"flex w-full items-center justify-center gap-1.5 rounded-lg bg-primary px-4 py-2.5 text-sm font-semibold text-primary-foreground transition-transform hover:scale-[1.01] disabled:opacity-50",children:[a==="png"?t.jsx(A,{className:"h-4 w-4"}):t.jsx(D,{className:"h-4 w-4"}),d?"Generating…":a==="png"?"Export PNG":"Export PDF"]})]})]})}),document.body)}export{O as ExportModal};