master 5df91f9bfa89 cached
130 files
577.0 KB
169.1k tokens
123 symbols
2 requests
Download .txt
Showing preview only (611K chars total). Download the full file or copy to clipboard to get everything.
Repository: anuraghazra/github-readme-stats
Branch: master
Commit: 5df91f9bfa89
Files: 130
Total size: 577.0 KB

Directory structure:
gitextract_rbue6f_z/

├── .devcontainer/
│   └── devcontainer.json
├── .eslintrc.json
├── .github/
│   ├── CODEOWNERS
│   ├── FUNDING.yml
│   ├── ISSUE_TEMPLATE/
│   │   ├── bug_report.yml
│   │   ├── config.yml
│   │   └── feature_request.yml
│   ├── dependabot.yml
│   ├── labeler.yml
│   ├── stale.yml
│   └── workflows/
│       ├── codeql-analysis.yml
│       ├── deploy-prep.py
│       ├── deploy-prep.yml
│       ├── e2e-test.yml
│       ├── empty-issues-closer.yml
│       ├── generate-theme-doc.yml
│       ├── label-pr.yml
│       ├── ossf-analysis.yml
│       ├── preview-theme.yml
│       ├── prs-cache-clean.yml
│       ├── stale-theme-pr-closer.yml
│       ├── test.yml
│       ├── theme-prs-closer.yml
│       ├── top-issues-dashboard.yml
│       └── update-langs.yml
├── .gitignore
├── .husky/
│   ├── .gitignore
│   └── pre-commit
├── .nvmrc
├── .prettierignore
├── .prettierrc.json
├── .vercelignore
├── .vscode/
│   ├── extensions.json
│   └── settings.json
├── CODE_OF_CONDUCT.md
├── CONTRIBUTING.md
├── LICENSE
├── SECURITY.md
├── api/
│   ├── gist.js
│   ├── index.js
│   ├── pin.js
│   ├── status/
│   │   ├── pat-info.js
│   │   └── up.js
│   ├── top-langs.js
│   └── wakatime.js
├── codecov.yml
├── eslint.config.mjs
├── express.js
├── jest.bench.config.js
├── jest.config.js
├── jest.e2e.config.js
├── package.json
├── readme.md
├── scripts/
│   ├── close-stale-theme-prs.js
│   ├── generate-langs-json.js
│   ├── generate-theme-doc.js
│   ├── helpers.js
│   ├── preview-theme.js
│   └── push-theme-readme.sh
├── src/
│   ├── calculateRank.js
│   ├── cards/
│   │   ├── gist.js
│   │   ├── index.js
│   │   ├── repo.js
│   │   ├── stats.js
│   │   ├── top-languages.js
│   │   ├── types.d.ts
│   │   └── wakatime.js
│   ├── common/
│   │   ├── Card.js
│   │   ├── I18n.js
│   │   ├── access.js
│   │   ├── blacklist.js
│   │   ├── cache.js
│   │   ├── color.js
│   │   ├── envs.js
│   │   ├── error.js
│   │   ├── fmt.js
│   │   ├── html.js
│   │   ├── http.js
│   │   ├── icons.js
│   │   ├── index.js
│   │   ├── languageColors.json
│   │   ├── log.js
│   │   ├── ops.js
│   │   ├── render.js
│   │   └── retryer.js
│   ├── fetchers/
│   │   ├── gist.js
│   │   ├── repo.js
│   │   ├── stats.js
│   │   ├── top-languages.js
│   │   ├── types.d.ts
│   │   └── wakatime.js
│   ├── index.js
│   └── translations.js
├── tests/
│   ├── __snapshots__/
│   │   └── renderWakatimeCard.test.js.snap
│   ├── api.test.js
│   ├── bench/
│   │   ├── api.bench.js
│   │   ├── calculateRank.bench.js
│   │   ├── gist.bench.js
│   │   ├── pin.bench.js
│   │   └── utils.js
│   ├── calculateRank.test.js
│   ├── card.test.js
│   ├── color.test.js
│   ├── e2e/
│   │   └── e2e.test.js
│   ├── fetchGist.test.js
│   ├── fetchRepo.test.js
│   ├── fetchStats.test.js
│   ├── fetchTopLanguages.test.js
│   ├── fetchWakatime.test.js
│   ├── flexLayout.test.js
│   ├── fmt.test.js
│   ├── gist.test.js
│   ├── html.test.js
│   ├── i18n.test.js
│   ├── ops.test.js
│   ├── pat-info.test.js
│   ├── pin.test.js
│   ├── render.test.js
│   ├── renderGistCard.test.js
│   ├── renderRepoCard.test.js
│   ├── renderStatsCard.test.js
│   ├── renderTopLanguagesCard.test.js
│   ├── renderWakatimeCard.test.js
│   ├── retryer.test.js
│   ├── status.up.test.js
│   ├── top-langs.test.js
│   └── wakatime.test.js
├── themes/
│   ├── README.md
│   └── index.js
└── vercel.json

================================================
FILE CONTENTS
================================================

================================================
FILE: .devcontainer/devcontainer.json
================================================
{
    "name": "GitHub Readme Stats Dev",
    "image": "mcr.microsoft.com/devcontainers/base:ubuntu",
    "features": {
        "ghcr.io/devcontainers/features/node:1": { "version": "22" }
    },
    "forwardPorts": [3000],
    "portsAttributes": {
        "3000": { "label": "HTTP" }
    },
    "appPort": [],

    // Use 'postCreateCommand' to run commands after the container is created.
    "postCreateCommand": "npm install -g vercel",

    // Use 'postStartCommand' to run commands after the container is started.
    "postStartCommand": "hostname dev && npm install",

    // Configure tool-specific properties.
    "customizations": {
        "vscode": {
            "extensions": [
                "yzhang.markdown-all-in-one",
                "esbenp.prettier-vscode",
                "dbaeumer.vscode-eslint",
                "github.vscode-github-actions"
            ]
        }
    },

    "remoteUser": "root",
    "privileged": true
}


================================================
FILE: .eslintrc.json
================================================
// {
//     "env": {
//         "node": true,
//         "browser": true,
//         "es2021": true
//     },
//     "extends": [
//         // "eslint:recommended",
//         "prettier"
//     ],
//     "parserOptions": {
//         "sourceType": "module",
//         "ecmaVersion": 2022
//     },
//     "rules": {
//         // Possible Errors (overrides from recommended set)

//         // "no-extra-parens": "error",
//         "no-unexpected-multiline": "error",

//         // All JSDoc comments must be valid
        
//         "valid-jsdoc": [ "error", {
//             "requireReturn": true,
//             "requireReturnDescription": true,
//             "requireParamDescription": true,
//             "prefer": {
//                 "return": "returns"
//             }
//         }],

//         // Best Practices

//         // Allowed a getter without setter, but all setters require getters

//         "accessor-pairs": [ "error", {
//             "getWithoutSet": false,
//             "setWithoutGet": true
//         }],
//         "block-scoped-var": "warn",
//         "consistent-return": "error",
//         "curly": "error",
//         // "default-case": "warn",

//         // the dot goes with the property when doing multiline

//         // "dot-location": [ "warn", "property" ],
//         // "dot-notation": "warn",
//         // "eqeqeq": [ "error", "smart" ],
//         // "guard-for-in": "warn",
//         "no-alert": "error",
//         "no-caller": "error",
//         // "no-case-declarations": "warn",
//         // "no-div-regex": "warn",
//         // "no-else-return": "warn",
//         // "no-empty-label": "warn",
//         // "no-empty-pattern": "warn",
//         // "no-eq-null": "warn",
//         // "no-eval": "error",
//         // "no-extend-native": "error",
//         // "no-extra-bind": "warn",
//         // "no-floating-decimal": "warn",
//         // "no-implicit-coercion": [ "warn", {
//         //     "boolean": true,
//         //     "number": true,
//         //     "string": true
//         // }],
//         // "no-implied-eval": "error",
//         // "no-invalid-this": "error",
//         // "no-iterator": "error",
//         // "no-labels": "warn",
//         // "no-lone-blocks": "warn",
//         // "no-loop-func": "error",
//         // "no-magic-numbers": "warn",
//         // "no-multi-spaces": "error",
//         // "no-multi-str": "warn",
//         // "no-native-reassign": "error",
//         // "no-new-func": "error",
//         // "no-new-wrappers": "error",
//         // "no-new": "error",
//         // "no-octal-escape": "error",
//         // "no-param-reassign": "error",
//         // "no-process-env": "warn",
//         // "no-proto": "error",
//         // "no-redeclare": "error",
//         // "no-return-assign": "error",
//         // "no-script-url": "error",
//         // "no-self-compare": "error",
//         // "no-throw-literal": "error",
//         // "no-unused-expressions": "error",
//         // "no-useless-call": "error",
//         // "no-useless-concat": "error",
//         // "no-void": "warn",

//         // Produce warnings when something is commented as TODO or FIXME

//         "no-warning-comments": [ "warn", {
//             "terms": [ "TODO", "FIXME" ],
//             "location": "start"
//         }],
//         "no-with": "warn",
//         "radix": "warn",
//         // "vars-on-top": "error",

//         // Enforces the style of wrapped functions
//         // "wrap-iife": [ "error", "outside" ],
//         // "yoda": "error",

//         // Strict Mode - for ES6, never use strict.
//         // "strict": [ "error", "never" ],

//         // Variables

//         // "init-declarations": [ "error", "always" ],
//         // "no-catch-shadow": "warn",
//         "no-delete-var": "error",
//         // "no-label-var": "error",
//         // "no-shadow-restricted-names": "error",
//         // "no-shadow": "warn",

//         // We require all vars to be initialized (see init-declarations)
//         // If we NEED a var to be initialized to undefined, it needs to be explicit

//         "no-undef-init": "off",
//         "no-undef": "error",
//         "no-undefined": "off",
//         "no-unused-vars": "warn",

//         // Disallow hoisting - let & const don't allow hoisting anyhow

//         "no-use-before-define": "error",

//         // Node.js and CommonJS

//         // "callback-return": [ "warn", [ "callback", "next" ]],
//         // "global-require": "error",
//         // "handle-callback-err": "warn",
//         // "no-mixed-requires": "warn",
//         // "no-new-require": "error",

//         // Use path.concat instead

//         // "no-path-concat": "error",
//         // "no-process-exit": "error",
//         // "no-restricted-modules": "off",
//         // "no-sync": "warn",

//         // ECMAScript 6 support

//         // "arrow-body-style": [ "error", "always" ],
//         // "arrow-parens": [ "error", "always" ],
//         // "arrow-spacing": [ "error", { "before": true, "after": true }],
//         "constructor-super": "error",
//         // "generator-star-spacing": [ "error", "before" ],
//         // "no-arrow-condition": "error",
//         "no-class-assign": "error",
//         "no-const-assign": "error",
//         "no-dupe-class-members": "error",
//         "no-this-before-super": "error",
//         // "no-var": "warn",
//         "object-shorthand": [ "warn" ],
//         // "prefer-arrow-callback": "warn",
//         // "prefer-spread": "warn",
//         // "prefer-template": "warn",
//         // "require-yield": "error",

//         // Stylistic - everything here is a warning because of style.

//         // "array-bracket-spacing": [ "warn", "always" ],
//         // "block-spacing": [ "warn", "always" ],
//         // "brace-style": [ "warn", "1tbs", { "allowSingleLine": false } ],
//         // "camelcase": "warn",
//         // "comma-spacing": [ "warn", { "before": false, "after": true } ],
//         // "comma-style": [ "warn", "last" ],
//         // "computed-property-spacing": [ "warn", "never" ],
//         // "consistent-this": [ "warn", "self" ],
//         // "eol-last": "warn",
//         // "func-names": "warn",
//         // "func-style": [ "warn", "declaration" ],
//         // "id-length": [ "warn", { "min": 2, "max": 32 } ],
//         // "indent": [ "warn", 4 ],
//         // "jsx-quotes": [ "warn", "prefer-double" ],
//         // "linebreak-style": [ "warn", "unix" ],
//         // "lines-around-comment": [ "warn", { "beforeBlockComment": true } ],
//         // "max-depth": [ "warn", 8 ],
//         // "max-len": [ "warn", 132 ],
//         // "max-nested-callbacks": [ "warn", 8 ],
//         // "max-params": [ "warn", 8 ],
//         // "new-cap": "warn",
//         // "new-parens": "warn",
//         // "no-array-constructor": "warn",
//         // "no-bitwise": "off",
//         // "no-continue": "off",
//         // "no-inline-comments": "off",
//         // "no-lonely-if": "warn",
//         "no-mixed-spaces-and-tabs": "warn",
//         "no-multiple-empty-lines": "warn",
//         "no-negated-condition": "warn",
//         // "no-nested-ternary": "warn",
//         // "no-new-object": "warn",
//         // "no-plusplus": "off",
//         // "no-spaced-func": "warn",
//         // "no-ternary": "off",
//         // "no-trailing-spaces": "warn",
//         // "no-underscore-dangle": "warn",
//         "no-unneeded-ternary": "warn",
//         // "object-curly-spacing": [ "warn", "always" ],
//         // "one-var": "off",
//         // "operator-assignment": [ "warn", "never" ],
//         // "operator-linebreak": [ "warn", "after" ],
//         // "padded-blocks": [ "warn", "never" ],
//         // "quote-props": [ "warn", "consistent-as-needed" ],
//         // "quotes": [ "warn", "single" ],
//         "require-jsdoc": [ "warn", {
//             "require": {
//                 "FunctionDeclaration": true,
//                 "MethodDefinition": true,
//                 "ClassDeclaration": false
//             }
//         }],
//         // "semi-spacing": [ "warn", { "before": false, "after": true }],
//         // "semi": [ "error", "always" ],
//         // "sort-vars": "off",
//         "keyword-spacing": ["error", { "before": true, "after": true }]
//         // "space-before-blocks": [ "warn", "always" ],
//         // "space-before-function-paren": [ "warn", "never" ],
//         // "space-in-parens": [ "warn", "never" ],
//         // "space-infix-ops": [ "warn", { "int32Hint": true } ],
//         // "space-return-throw-case": "error",
//         // "space-unary-ops": "error",
//         // "spaced-comment": [ "warn", "always" ],
//         // "wrap-regex": "warn"
//     }
// }


================================================
FILE: .github/CODEOWNERS
================================================
# This file is used to define code owners for the repository.
# Code owners are automatically requested for review when someone opens a pull request that modifies code they own.

# Assign @qwerty541 as the owner for package.json and package-lock.json
package.json @qwerty541
package-lock.json @qwerty541


================================================
FILE: .github/FUNDING.yml
================================================
# These are supported funding model platforms

github: [anuraghazra] # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2]
patreon: # Replace with a single Patreon username
open_collective: # Replace with a single Open Collective username
ko_fi: # Replace with a single Ko-fi username
tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel
community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry
liberapay: # Replace with a single Liberapay username
issuehunt: # Replace with a single IssueHunt username
otechie: # Replace with a single Otechie username
custom: [
    "https://www.paypal.me/anuraghazra",
    "https://www.buymeacoffee.com/anuraghazra",
  ] # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2']


================================================
FILE: .github/ISSUE_TEMPLATE/bug_report.yml
================================================
name: Bug report
description: Create a report to help us improve.
labels:
  - "bug"
body:
  - type: markdown
    attributes:
      value: |
        :warning: PLEASE FIRST READ THE FAQ [(#1770)](https://github.com/anuraghazra/github-readme-stats/discussions/1770) AND COMMON ERROR CODES [(#1772)](https://github.com/anuraghazra/github-readme-stats/issues/1772)!!!
  - type: textarea
    attributes:
      label: Describe the bug
      description: A clear and concise description of what the bug is.
    validations:
      required: true
  - type: textarea
    attributes:
      label: Expected behavior
      description:
        A clear and concise description of what you expected to happen.
  - type: textarea
    attributes:
      label: Screenshots / Live demo link
      description: If applicable, add screenshots to help explain your problem.
      placeholder: Paste the github-readme-stats link as markdown image
  - type: textarea
    attributes:
      label: Additional context
      description: Add any other context about the problem here.
  - type: markdown
    attributes:
      value: |
        ---
        ### FAQ (Snippet)

        Below are some questions that are found in the FAQ. The full FAQ can be found in [#1770](https://github.com/anuraghazra/github-readme-stats/discussions/1770).

        #### Q: My card displays an error

        **Ans:** First, check the common error codes (i.e. https://github.com/anuraghazra/github-readme-stats/issues/1772) and existing issues before creating a new one. 

        #### Q: How to hide jupyter Notebook?

        **Ans:** `&hide=jupyter%20notebook`.

        #### Q: I could not figure out how to deploy on my own vercel instance

        **Ans:** Please check:
          - Docs: https://github.com/anuraghazra/github-readme-stats/#deploy-on-your-own-vercel-instance
          - YT tutorial by codeSTACKr: https://www.youtube.com/watch?v=n6d4KHSKqGk&feature=youtu.be&t=107

        #### Q: Language Card is incorrect

        **Ans:** Please read these issues/comments before opening any issues regarding language card stats:
          - https://github.com/anuraghazra/github-readme-stats/issues/136#issuecomment-665164174
          - https://github.com/anuraghazra/github-readme-stats/issues/136#issuecomment-665172181

        #### Q: How to count private stats?

        **Ans:** We can only count private commits & we cannot access any other private info of any users, so it's impossible. The only way is to deploy on your own instance & use your own PAT (Personal Access Token).


================================================
FILE: .github/ISSUE_TEMPLATE/config.yml
================================================
blank_issues_enabled: true
contact_links:
  - name: Question
    url: https://github.com/anuraghazra/github-readme-stats/discussions
    about: Please ask and answer questions here.
  - name: Error
    url: https://github.com/anuraghazra/github-readme-stats/issues/1772
    about:
      Before opening a bug report, please check the 'Common Error Codes' issue.
  - name: FAQ
    url: https://github.com/anuraghazra/github-readme-stats/discussions/1770
    about: Please first check the FAQ before asking a question.


================================================
FILE: .github/ISSUE_TEMPLATE/feature_request.yml
================================================
name: Feature request
description: Suggest an idea for this project.
labels:
  - "enhancement"
body:
  - type: textarea
    attributes:
      label: Is your feature request related to a problem? Please describe.
      description:
        A clear and concise description of what the problem is. Ex. I'm always
        frustrated when [...]
    validations:
      required: true
  - type: textarea
    attributes:
      label: Describe the solution you'd like
      description: A clear and concise description of what you want to happen.
  - type: textarea
    attributes:
      label: Describe alternatives you've considered
      description:
        A clear and concise description of any alternative solutions or features
        you've considered.
  - type: textarea
    attributes:
      label: Additional context
      description:
        Add any other context or screenshots about the feature request here.


================================================
FILE: .github/dependabot.yml
================================================
version: 2
updates:
  # Maintain dependencies for npm
  - package-ecosystem: npm
    directory: "/"
    schedule:
      interval: weekly
    open-pull-requests-limit: 10
    commit-message:
      prefix: "build(deps)"
      prefix-development: "build(deps-dev)"

  # Maintain dependencies for GitHub Actions
  - package-ecosystem: github-actions
    directory: "/"
    schedule:
      interval: weekly
    open-pull-requests-limit: 10
    commit-message:
      prefix: "ci(deps)"
      prefix-development: "ci(deps-dev)"

  # Maintain dependencies for Devcontainers
  - package-ecosystem: devcontainers
    directory: "/"
    schedule:
      interval: weekly
    open-pull-requests-limit: 10
    commit-message:
      prefix: "build(deps)"
      prefix-development: "build(deps-dev)"


================================================
FILE: .github/labeler.yml
================================================
themes:
  - changed-files:
      - any-glob-to-any-file:
          - themes/index.js

card-i18n:
  - changed-files:
      - any-glob-to-any-file:
          - src/translations.js
          - src/common/I18n.js

documentation:
  - changed-files:
      - any-glob-to-any-file:
          - readme.md
          - CONTRIBUTING.md
          - CODE_OF_CONDUCT.md
          - SECURITY.md

dependencies:
  - changed-files:
      - any-glob-to-any-file:
          - package.json
          - package-lock.json

lang-card:
  - changed-files:
      - any-glob-to-any-file:
          - api/top-langs.js
          - src/cards/top-languages.js
          - src/fetchers/top-languages.js
          - tests/fetchTopLanguages.test.js
          - tests/renderTopLanguagesCard.test.js
          - tests/top-langs.test.js

repo-card:
  - changed-files:
      - any-glob-to-any-file:
          - api/pin.js
          - src/cards/repo.js
          - src/fetchers/repo.js
          - tests/fetchRepo.test.js
          - tests/renderRepoCard.test.js
          - tests/pin.test.js

stats-card:
  - changed-files:
      - any-glob-to-any-file:
          - api/index.js
          - src/cards/stats.js
          - src/fetchers/stats.js
          - tests/fetchStats.test.js
          - tests/renderStatsCard.test.js
          - tests/api.test.js

wakatime-card:
  - changed-files:
      - any-glob-to-any-file:
          - api/wakatime.js
          - src/cards/wakatime.js
          - src/fetchers/wakatime.js
          - tests/fetchWakatime.test.js
          - tests/renderWakatimeCard.test.js
          - tests/wakatime.test.js

gist-card:
  - changed-files:
      - any-glob-to-any-file:
          - api/gist.js
          - src/cards/gist.js
          - src/fetchers/gist.js
          - tests/fetchGist.test.js
          - tests/renderGistCard.test.js
          - tests/gist.test.js

ranks:
  - changed-files:
      - any-glob-to-any-file:
          - src/calculateRank.js

ci:
  - changed-files:
      - any-glob-to-any-file:
          - .github/workflows/*
          - scripts/*

infrastructure:
  - changed-files:
      - any-glob-to-any-file:
          - .eslintrc.json


================================================
FILE: .github/stale.yml
================================================
# Number of days of inactivity before an issue becomes stale
daysUntilStale: 30
# Number of days of inactivity before a stale issue is closed
daysUntilClose: 7
# Issues with these labels will never be considered stale
exemptLabels:
  - feature
  - enhancement
  - help wanted
  - bug

# Label to use when marking an issue as stale
staleLabel: stale
# Comment to post when marking an issue as stale. Set to `false` to disable
markComment: >
  This issue has been automatically marked as stale because it has not had
  recent activity. It will be closed if no further activity occurs. Thank you
  for your contributions.
# Comment to post when closing a stale issue. Set to `false` to disable
closeComment: false


================================================
FILE: .github/workflows/codeql-analysis.yml
================================================
name: "Static code analysis workflow (CodeQL)"

on:
  push:
    branches:
      - master
  pull_request:
    branches:
      - master

permissions:
  actions: read
  checks: read
  contents: read
  deployments: read
  issues: read
  discussions: read
  packages: read
  pages: read
  pull-requests: read
  repository-projects: read
  security-events: write
  statuses: read

jobs:
  CodeQL-Build:
    if: github.repository == 'anuraghazra/github-readme-stats'

    # CodeQL runs on ubuntu-latest, windows-latest, and macos-latest
    runs-on: ubuntu-latest

    steps:
      - name: Checkout repository
        uses: actions/checkout@8e8c483db84b4bee98b60c0593521ed34d9990e8 # v6.0.1

      # Initializes the CodeQL tools for scanning.
      - name: Initialize CodeQL
        uses: github/codeql-action/init@46a6823b81f2d7c67ddf123851eea88365bc8a67 # v2.13.5
        with:
          languages: javascript

      - name: Perform CodeQL Analysis
        uses: github/codeql-action/analyze@46a6823b81f2d7c67ddf123851eea88365bc8a67 # v2.13.5


================================================
FILE: .github/workflows/deploy-prep.py
================================================
import os

file = open('./vercel.json', 'r')
str = file.read()
file = open('./vercel.json', 'w')

str = str.replace('"maxDuration": 10', '"maxDuration": 15')

file.write(str)
file.close()


================================================
FILE: .github/workflows/deploy-prep.yml
================================================
name: Deployment Prep
on:
  workflow_dispatch:
  push:
    branches:
      - master

jobs:
  config:
    if: github.repository == 'anuraghazra/github-readme-stats'
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@8e8c483db84b4bee98b60c0593521ed34d9990e8 # v6.0.1
      - name: Deployment Prep
        run: python ./.github/workflows/deploy-prep.py
      - uses: stefanzweifel/git-auto-commit-action@28e16e81777b558cc906c8750092100bbb34c5e3 # v7.0.0
        with:
          branch: vercel
          create_branch: true
          push_options: "--force"


================================================
FILE: .github/workflows/e2e-test.yml
================================================
name: Test Deployment
on:
  # Temporarily disabled automatic triggers; manual-only for now.
  workflow_dispatch:
  # Original trigger (restore to re-enable):
  # deployment_status:

permissions: read-all

jobs:
  e2eTests:
    # Temporarily disabled; set to the original condition to re-enable.
    # if:
    #   github.repository == 'anuraghazra/github-readme-stats' &&
    #   github.event_name == 'deployment_status' &&
    #   github.event.deployment_status.state == 'success'
    if: false
    name: Perform e2e tests
    runs-on: ubuntu-latest
    strategy:
      matrix:
        node-version: [22.x]

    steps:
      - uses: actions/checkout@8e8c483db84b4bee98b60c0593521ed34d9990e8 # v6.0.1

      - name: Setup Node
        uses: actions/setup-node@395ad3262231945c25e8478fd5baf05154b1d79f # v6.1.0
        with:
          node-version: ${{ matrix.node-version }}
          cache: npm

      - name: Install dependencies
        run: npm ci
        env:
          CI: true

      - name: Run end-to-end tests.
        run: npm run test:e2e
        # env:
        #   VERCEL_PREVIEW_URL: ${{ github.event.deployment_status.target_url }}


================================================
FILE: .github/workflows/empty-issues-closer.yml
================================================
name: Close empty issues and templates
on:
  issues:
    types:
      - reopened
      - opened
      - edited

permissions:
  actions: read
  checks: read
  contents: read
  deployments: read
  issues: write
  discussions: read
  packages: read
  pages: read
  pull-requests: read
  repository-projects: read
  security-events: read
  statuses: read

jobs:
  closeEmptyIssuesAndTemplates:
    if: github.repository == 'anuraghazra/github-readme-stats'
    name: Close empty issues
    runs-on: ubuntu-latest
    steps:
      # NOTE: Retrieve issue templates.
      - uses: actions/checkout@8e8c483db84b4bee98b60c0593521ed34d9990e8 # v6.0.1

      - name: Run empty issues closer action
        uses: rickstaa/empty-issues-closer-action@e96914613221511279ca25f50fd4acc85e331d99 # v1.1.74
        env:
          github_token: ${{ secrets.GITHUB_TOKEN }}
        with:
          close_comment:
            Closing this issue because it appears to be empty. Please update the
            issue for it to be reopened.
          open_comment:
            Reopening this issue because the author provided more information.
          check_templates: true
          template_close_comment:
            Closing this issue since the issue template was not filled in.
            Please provide us with more information to have this issue reopened.
          template_open_comment:
            Reopening this issue because the author provided more information.


================================================
FILE: .github/workflows/generate-theme-doc.yml
================================================
name: Generate Theme Readme
on:
  push:
    branches:
      - master
    paths:
      - "themes/index.js"
  workflow_dispatch:

permissions:
  actions: read
  checks: read
  contents: write
  deployments: read
  issues: read
  discussions: read
  packages: read
  pages: read
  pull-requests: read
  repository-projects: read
  security-events: read
  statuses: read

jobs:
  generateThemeDoc:
    runs-on: ubuntu-latest
    name: Generate theme doc
    strategy:
      matrix:
        node-version: [22.x]

    steps:
      - uses: actions/checkout@8e8c483db84b4bee98b60c0593521ed34d9990e8 # v6.0.1

      - name: Setup Node
        uses: actions/setup-node@395ad3262231945c25e8478fd5baf05154b1d79f # v6.1.0
        with:
          node-version: ${{ matrix.node-version }}
          cache: npm

      # Fix the unsafe repo error which was introduced by the CVE-2022-24765 git patches.
      - name: Fix unsafe repo error
        run: git config --global --add safe.directory ${{ github.workspace }}

      - name: npm install, generate readme
        run: |
          npm ci
          npm run theme-readme-gen
        env:
          CI: true

      - name: Run Script
        uses: skx/github-action-tester@e29768ff4ff67be9d1fdbccd8836ab83233bebb1 # v0.10.0
        with:
          script: ./scripts/push-theme-readme.sh
        env:
          CI: true
          PERSONAL_TOKEN: ${{ secrets.PERSONAL_TOKEN }}
          GH_REPO: ${{ secrets.GH_REPO }}


================================================
FILE: .github/workflows/label-pr.yml
================================================
name: "Pull Request Labeler"
on:
  - pull_request_target

permissions:
  actions: read
  checks: read
  contents: read
  deployments: read
  issues: read
  discussions: read
  packages: read
  pages: read
  pull-requests: write
  repository-projects: read
  security-events: read
  statuses: read

jobs:
  triage:
    if: github.repository == 'anuraghazra/github-readme-stats'
    runs-on: ubuntu-latest
    steps:
      - uses: actions/labeler@634933edcd8ababfe52f92936142cc22ac488b1b # v6.0.1
        with:
          repo-token: "${{ secrets.GITHUB_TOKEN }}"
          sync-labels: true


================================================
FILE: .github/workflows/ossf-analysis.yml
================================================
name: OSSF Scorecard analysis workflow
on:
  push:
    branches:
      - master
  pull_request:
    branches:
      - master

permissions: read-all

jobs:
  analysis:
    if: github.repository == 'anuraghazra/github-readme-stats'
    name: Scorecard analysis
    runs-on: ubuntu-latest
    permissions:
      # Needed if using Code scanning alerts
      security-events: write
      # Needed for GitHub OIDC token if publish_results is true
      id-token: write

    steps:
      - name: "Checkout code"
        uses: actions/checkout@8e8c483db84b4bee98b60c0593521ed34d9990e8 # v6.0.1
        with:
          persist-credentials: false

      - name: "Run analysis"
        uses: ossf/scorecard-action@4eaacf0543bb3f2c246792bd56e8cdeffafb205a # v2.4.3
        with:
          results_file: results.sarif
          results_format: sarif
          publish_results: true

      # Upload the results as artifacts (optional). Commenting out will disable uploads of run results in SARIF
      # format to the repository Actions tab.
      - name: "Upload artifact"
        uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6.0.0
        with:
          name: SARIF file
          path: results.sarif
          retention-days: 5

      # required for Code scanning alerts
      - name: "Upload SARIF results to code scanning"
        uses: github/codeql-action/upload-sarif@fdcae64e1484d349b3366718cdfef3d404390e85 # v2.22.1
        with:
          sarif_file: results.sarif


================================================
FILE: .github/workflows/preview-theme.yml
================================================
name: Theme preview
on:
  # Temporary disabled due to paused themes addition.
  # See: https://github.com/anuraghazra/github-readme-stats/issues/3404
  # pull_request_target:
  #   types: [opened, edited, reopened, synchronize]
  #   branches:
  #     - master
  #   paths:
  #     - "themes/index.js"
  workflow_dispatch:

permissions:
  actions: read
  checks: read
  contents: read
  deployments: read
  issues: read
  discussions: read
  packages: read
  pages: read
  pull-requests: write
  repository-projects: read
  security-events: read
  statuses: read

jobs:
  previewTheme:
    name: Install & Preview
    runs-on: ubuntu-latest
    strategy:
      matrix:
        node-version: [22.x]

    steps:
      - uses: actions/checkout@8e8c483db84b4bee98b60c0593521ed34d9990e8 # v6.0.1

      - name: Setup Node
        uses: actions/setup-node@395ad3262231945c25e8478fd5baf05154b1d79f # v6.1.0
        with:
          node-version: ${{ matrix.node-version }}
          cache: npm

      - uses: bahmutov/npm-install@3e063b974f0d209807684aa23e534b3dde517fd9 # v1.11.2
        with:
          useLockFile: false

      - run: npm run preview-theme
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}


================================================
FILE: .github/workflows/prs-cache-clean.yml
================================================
name: Cleanup closed pull requests cache
on:
  pull_request:
    types:
      - closed

permissions:
  actions: write
  checks: read
  contents: read
  deployments: read
  issues: read
  discussions: read
  packages: read
  pages: read
  pull-requests: read
  repository-projects: read
  security-events: read
  statuses: read

jobs:
  cleanup:
    runs-on: ubuntu-latest
    steps:
      - name: Cleanup
        run: |
          gh extension install actions/gh-actions-cache

          REPO=${{ github.repository }}
          BRANCH="refs/pull/${{ github.event.pull_request.number }}/merge"

          echo "Fetching list of cache key"
          cacheKeysForPR=$(gh actions-cache list -R $REPO -B $BRANCH | cut -f 1 )

          ## Setting this to not fail the workflow while deleting cache keys. 
          set +e
          echo "Deleting caches..."
          for cacheKey in $cacheKeysForPR
          do
              gh actions-cache delete $cacheKey -R $REPO -B $BRANCH --confirm
          done
          echo "Done"
        env:
          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}


================================================
FILE: .github/workflows/stale-theme-pr-closer.yml
================================================
name: Close stale theme pull requests that have the 'invalid' label.
on:
  # Temporary disabled due to paused themes addition.
  # See: https://github.com/anuraghazra/github-readme-stats/issues/3404
  # schedule:
  #   #        ┌───────────── minute (0 - 59)
  #   #        │ ┌───────────── hour (0 - 23)
  #   #        │ │  ┌───────────── day of the month (1 - 31)
  #   #        │ │  │  ┌───────────── month (1 - 12 or JAN-DEC)
  #   #        │ │  │  │ ┌───────────── day of the week (0 - 6 or SUN-SAT)
  #   #        │ │  │  │ │
  #   #        │ │  │  │ │
  #   #        │ │  │  │ │
  #   #        * *  *  * *
  #   - cron: "0 0 */7 * *"
  workflow_dispatch:

permissions:
  actions: read
  checks: read
  contents: read
  deployments: read
  issues: read
  discussions: read
  packages: read
  pages: read
  pull-requests: write
  repository-projects: read
  security-events: read
  statuses: read

jobs:
  closeOldThemePrs:
    if: github.repository == 'anuraghazra/github-readme-stats'
    name: Close stale 'invalid' theme PRs
    runs-on: ubuntu-latest
    strategy:
      matrix:
        node-version: [22.x]

    steps:
      - uses: actions/checkout@8e8c483db84b4bee98b60c0593521ed34d9990e8 # v6.0.1

      - name: Setup Node
        uses: actions/setup-node@395ad3262231945c25e8478fd5baf05154b1d79f # v6.1.0
        with:
          node-version: ${{ matrix.node-version }}
          cache: npm

      - uses: bahmutov/npm-install@3e063b974f0d209807684aa23e534b3dde517fd9 # v1.11.2
        with:
          useLockFile: false

      - run: npm run close-stale-theme-prs
        env:
          STALE_DAYS: 20
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}


================================================
FILE: .github/workflows/test.yml
================================================
name: Test
on:
  push:
    branches:
      - master
  pull_request:
    branches:
      - master

permissions: read-all

jobs:
  build:
    name: Perform tests
    runs-on: ubuntu-latest
    strategy:
      matrix:
        node-version: [22.x]

    steps:
      - uses: actions/checkout@8e8c483db84b4bee98b60c0593521ed34d9990e8 # v6.0.1

      - name: Setup Node
        uses: actions/setup-node@395ad3262231945c25e8478fd5baf05154b1d79f # v6.1.0
        with:
          node-version: ${{ matrix.node-version }}
          cache: npm

      - name: Install & Test
        run: |
          npm ci
          npm run test

      - name: Run ESLint
        run: |
          npm run lint

      - name: Run bench tests
        run: |
          npm run bench

      - name: Run Prettier
        run: |
          npm run format:check

      - name: Code Coverage
        uses: codecov/codecov-action@4fe8c5f003fae66aa5ebb77cfd3e7bfbbda0b6b0 # v3.1.5


================================================
FILE: .github/workflows/theme-prs-closer.yml
================================================
name: Theme Pull Requests Closer

on:
  - pull_request_target

permissions:
  actions: read
  checks: read
  contents: read
  deployments: read
  issues: read
  discussions: read
  packages: read
  pages: read
  pull-requests: write
  repository-projects: read
  security-events: read
  statuses: read

jobs:
  close-prs:
    if: github.repository == 'anuraghazra/github-readme-stats'
    runs-on: ubuntu-latest
    steps:
      - name: Check out the code
        uses: actions/checkout@8e8c483db84b4bee98b60c0593521ed34d9990e8 # v6.0.1

      - name: Set up Git
        run: |
          git config user.name "github-actions[bot]"
          git config user.email "github-actions[bot]@users.noreply.github.com"

      - name: Close Pull Requests
        run: |
          comment_message="We are currently pausing addition of new themes. If this theme is exclusively for your personal use, then instead of adding it to our theme collection, you can use card [customization options](https://github.com/anuraghazra/github-readme-stats?tab=readme-ov-file#customization)."

          for pr_number in $(gh pr list -l "themes" -q is:open --json number -q ".[].number"); do
            gh pr close $pr_number -c "$comment_message"
          done
        env:
          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}


================================================
FILE: .github/workflows/top-issues-dashboard.yml
================================================
name: Update top issues dashboard
on:
  schedule:
    #        ┌───────────── minute (0 - 59)
    #        │ ┌───────────── hour (0 - 23)
    #        │ │  ┌───────────── day of the month (1 - 31)
    #        │ │  │  ┌───────────── month (1 - 12 or JAN-DEC)
    #        │ │  │  │ ┌───────────── day of the week (0 - 6 or SUN-SAT)
    #        │ │  │  │ │
    #        │ │  │  │ │
    #        │ │  │  │ │
    #        * *  *  * *
    - cron: "0 0 */3 * *"
  workflow_dispatch:

permissions:
  actions: read
  checks: read
  contents: read
  deployments: read
  issues: write
  discussions: read
  packages: read
  pages: read
  pull-requests: write
  repository-projects: read
  security-events: read
  statuses: read

jobs:
  showAndLabelTopIssues:
    if: github.repository == 'anuraghazra/github-readme-stats'
    name: Update top issues Dashboard.
    runs-on: ubuntu-latest
    steps:
      - name: Run top issues action
        uses: rickstaa/top-issues-action@7e8dda5d5ae3087670f9094b9724a9a091fc3ba1 # v1.3.101
        env:
          github_token: ${{ secrets.GITHUB_TOKEN }}
        with:
          top_list_size: 10
          filter: "1772"
          label: true
          dashboard: true
          dashboard_show_total_reactions: true
          top_issues: true
          top_bugs: true
          top_features: true
          top_pull_requests: true


================================================
FILE: .github/workflows/update-langs.yml
================================================
name: Update supported languages
on:
  schedule:
    #        ┌───────────── minute (0 - 59)
    #        │ ┌───────────── hour (0 - 23)
    #        │ │  ┌───────────── day of the month (1 - 31)
    #        │ │  │   ┌───────────── month (1 - 12 or JAN-DEC)
    #        │ │  │   │ ┌───────────── day of the week (0 - 6 or SUN-SAT)
    #        │ │  │   │ │
    #        │ │  │   │ │
    #        │ │  │   │ │
    #        * *  *   * *
    - cron: "0 0 */30 * *"

permissions:
  actions: read
  checks: read
  contents: write
  deployments: read
  issues: read
  discussions: read
  packages: read
  pages: read
  pull-requests: write
  repository-projects: read
  security-events: read
  statuses: read

jobs:
  updateLanguages:
    if: github.repository == 'anuraghazra/github-readme-stats'
    name: Update supported languages
    runs-on: ubuntu-latest
    strategy:
      matrix:
        node-version: [22.x]

    steps:
      - uses: actions/checkout@8e8c483db84b4bee98b60c0593521ed34d9990e8 # v6.0.1

      - name: Setup Node
        uses: actions/setup-node@395ad3262231945c25e8478fd5baf05154b1d79f # v6.1.0
        with:
          node-version: ${{ matrix.node-version }}
          cache: npm

      - name: Install dependencies
        run: npm ci
        env:
          CI: true

      - name: Run update-languages-json.js script
        run: npm run generate-langs-json

      - name: Create Pull Request if upstream language file is changed
        uses: peter-evans/create-pull-request@98357b18bf14b5342f975ff684046ec3b2a07725 # v8.0.0
        with:
          commit-message: "refactor: update languages JSON"
          branch: "update_langs/patch"
          delete-branch: true
          title: Update languages JSON
          body:
            "The
            [update-langs](https://github.com/anuraghazra/github-readme-stats/actions/workflows/update-langs.yaml)
            action found new/updated languages in the [upstream languages JSON
            file](https://raw.githubusercontent.com/github/linguist/master/lib/linguist/languages.yml)."
          labels: "ci, lang-card"


================================================
FILE: .gitignore
================================================
.vercel
.env
node_modules
*.lock
.idea/
coverage
benchmarks
vercel_token

# IDE
.vscode/*
!.vscode/extensions.json
!.vscode/settings.json
*.code-workspace

.vercel


================================================
FILE: .husky/.gitignore
================================================
_


================================================
FILE: .husky/pre-commit
================================================
npm test
npm run lint
npx lint-staged


================================================
FILE: .nvmrc
================================================
22

================================================
FILE: .prettierignore
================================================
node_modules
*.json
*.md
coverage
.vercel


================================================
FILE: .prettierrc.json
================================================
{
  "trailingComma": "all",
  "useTabs": false,
  "endOfLine": "auto",
  "proseWrap": "always"
}

================================================
FILE: .vercelignore
================================================
.devcontainer
.github
.husky
.vscode
benchmarks
coverage
scripts
tests
.env
**/*.md
**/*.svg
.eslintrc.json
.prettierignore
.pretterrc.json
codecov.yml


================================================
FILE: .vscode/extensions.json
================================================
{
    "recommendations": [
        "yzhang.markdown-all-in-one",
        "esbenp.prettier-vscode",
        "dbaeumer.vscode-eslint",
        "ms-azuretools.vscode-containers",
        "github.vscode-github-actions"
    ]
}


================================================
FILE: .vscode/settings.json
================================================
{
    "markdown.extension.toc.levels": "1..3",
    "editor.formatOnSave": true,
    "editor.defaultFormatter": "esbenp.prettier-vscode",
    "[javascript]": {
        "editor.tabSize": 2
    }
}


================================================
FILE: CODE_OF_CONDUCT.md
================================================
# Contributor Covenant Code of Conduct

## Our Pledge

In the interest of fostering an open and welcoming environment, we as
contributors and maintainers pledge to making participation in our project and
our community a harassment-free experience for everyone, regardless of age, body
size, disability, ethnicity, sex characteristics, gender identity and expression,
level of experience, education, socio-economic status, nationality, personal
appearance, race, religion, or sexual identity and orientation.

## Our Standards

Examples of behavior that contributes to creating a positive environment
include:

* Using welcoming and inclusive language
* Being respectful of differing viewpoints and experiences
* Gracefully accepting constructive criticism
* Focusing on what is best for the community
* Showing empathy towards other community members

Examples of unacceptable behavior by participants include:

* The use of sexualized language or imagery and unwelcome sexual attention or
 advances
* Trolling, insulting/derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or electronic
 address, without explicit permission
* Other conduct which could reasonably be considered inappropriate in a
 professional setting

## Our Responsibilities

Project maintainers are responsible for clarifying the standards of acceptable
behavior and are expected to take appropriate and fair corrective action in
response to any instances of unacceptable behavior.

Project maintainers have the right and responsibility to remove, edit, or
reject comments, commits, code, wiki edits, issues, and other contributions
that are not aligned to this Code of Conduct, or to ban temporarily or
permanently any contributor for other behaviors that they deem inappropriate,
threatening, offensive, or harmful.

## Scope

This Code of Conduct applies both within project spaces and in public spaces
when an individual is representing the project or its community. Examples of
representing a project or community include using an official project e-mail
address, posting via an official social media account, or acting as an appointed
representative at an online or offline event. Representation of a project may be
further defined and clarified by project maintainers.

## Enforcement

Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported by contacting the project team at hazru.anurag@gmail.com. All
complaints will be reviewed and investigated and will result in a response that
is deemed necessary and appropriate to the circumstances. The project team is
obligated to maintain confidentiality with regard to the reporter of an incident.
Further details of specific enforcement policies may be posted separately.

Project maintainers who do not follow or enforce the Code of Conduct in good
faith may face temporary or permanent repercussions as determined by other
members of the project's leadership.

## Attribution

This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html

[homepage]: https://www.contributor-covenant.org

For answers to common questions about this code of conduct, see
https://www.contributor-covenant.org/faq


================================================
FILE: CONTRIBUTING.md
================================================
# Contributing to [github-readme-stats](https://github.com/anuraghazra/github-readme-stats)

We love your input! We want to make contributing to this project as easy and transparent as possible, whether it's:

-   Reporting [an issue](https://github.com/anuraghazra/github-readme-stats/issues/new?assignees=&labels=bug&template=bug_report.yml).
-   [Discussing](https://github.com/anuraghazra/github-readme-stats/discussions) the current state of the code.
-   Submitting [a fix](https://github.com/anuraghazra/github-readme-stats/compare).
-   Proposing [new features](https://github.com/anuraghazra/github-readme-stats/issues/new?assignees=&labels=enhancement&template=feature_request.yml).
-   Becoming a maintainer.

## All Changes Happen Through Pull Requests

Pull requests are the best way to propose changes. We actively welcome your pull requests:

1.  Fork the repo and create your branch from `master`.
2.  If you've added code that should be tested, add some tests' examples.
3.  If you've changed APIs, update the documentation.
4.  Issue that pull request!

## Under the hood of github-readme-stats

Interested in diving deeper into understanding how github-readme-stats works?

[Bohdan](https://github.com/Bogdan-Lyashenko) wrote a fantastic in-depth post about it, check it out:

**[Under the hood of github-readme-stats project](https://codecrumbs.io/library/github-readme-stats)**

## Local Development

To run & test github-readme-stats, you need to follow a few simple steps:-
_(make sure you already have a [Vercel](https://vercel.com/) account)_

1.  Install [Vercel CLI](https://vercel.com/download).
2.  Fork the repository and clone the code to your local machine.
3.  Run `npm install` in the repository root.
4.  Run the command `vercel` in the root and follow the steps there.
5.  Run the command `vercel dev` to start a development server at <http://localhost:3000>.
6.  Create a `.env` file in the root and add the following line `NODE_ENV=development`, this will disable caching for local development.
7.  The cards will then be available from this local endpoint (i.e. `http://localhost:3000/api?username=anuraghazra`).

> [!NOTE]
> You can debug the package code in [Vscode](https://code.visualstudio.com/) by using the [Node.js: Attach to process](https://code.visualstudio.com/docs/nodejs/nodejs-debugging#_setting-up-an-attach-configuration) debug option. You can also debug any tests using the [VSCode Jest extension](https://marketplace.visualstudio.com/items?itemName=Orta.vscode-jest). For more information, see https://github.com/jest-community/vscode-jest/issues/912.

## Themes Contribution

We're currently paused addition of new themes to decrease maintenance efforts. All pull requests related to new themes will be closed.

> [!NOTE]
> If you are considering contributing your theme just because you are using it personally, then instead of adding it to our theme collection, you can use card [customization options](./readme.md#customization).

## Translations Contribution

GitHub Readme Stats supports multiple languages, if we are missing your language, you can contribute it! You can check the currently supported languages [here](./readme.md#available-locales).

To contribute your language you need to edit the [src/translations.js](./src/translations.js) file and add new property to each object where the key is the language code in [ISO 639-1 standard](https://www.andiamo.co.uk/resources/iso-language-codes/) and the value is the translated string.

## Any contributions you make will be under the MIT Software License

In short, when you submit changes, your submissions are understood to be under the same [MIT License](https://choosealicense.com/licenses/mit/) that covers the project. Feel free to contact the maintainers if that's a concern.

## Report issues/bugs using GitHub's [issues](https://github.com/anuraghazra/github-readme-stats/issues)

We use GitHub issues to track public bugs. Report a bug by [opening a new issue](https://github.com/anuraghazra/github-readme-stats/issues/new/choose); it's that easy!

## Frequently Asked Questions (FAQs)

**Q:** How to hide Jupyter Notebook?

> **Ans:** &hide=jupyter%20notebook

**Q:** I could not figure out how to deploy on my own Vercel instance

> **Ans:**
>
> -   docs: <https://github.com/anuraghazra/github-readme-stats/#deploy-on-your-own-vercel-instance>
> -   YT tutorial by codeSTACKr: <https://www.youtube.com/watch?v=n6d4KHSKqGk&feature=youtu.be&t=107>

**Q:** Language Card is incorrect

> **Ans:** Please read all the related issues/comments before opening any issues regarding language card stats:
>
> -   <https://github.com/anuraghazra/github-readme-stats/issues/136#issuecomment-665164174>
>
> -   <https://github.com/anuraghazra/github-readme-stats/issues/136#issuecomment-665172181>

**Q:** How to count private stats?

> **Ans:** We can only count public commits & we cannot access any other private info of any users, so it's not possible. The only way to count your personal private stats is to deploy on your own instance & use your own PAT (Personal Access Token)

### Bug Reports

**Great Bug Reports** tend to have:

-   A quick summary and/or background
-   Steps to reproduce
    -   Be specific!
    -   Share the snapshot, if possible.
    -   GitHub Readme Stats' live link
-   What actually happens
-   What you expected would happen
-   Notes (possibly including why you think this might be happening or stuff you tried that didn't work)

People _love_ thorough bug reports. I'm not even kidding.

### Feature Request

**Great Feature Requests** tend to have:

-   A quick idea summary
-   What & why do you want to add the specific feature
-   Additional context like images, links to resources to implement the feature, etc.


================================================
FILE: LICENSE
================================================
MIT License

Copyright (c) 2020 Anurag Hazra

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.


================================================
FILE: SECURITY.md
================================================
# GitHub Readme Stats Security Policies and Procedures <!-- omit in toc -->

This document outlines security procedures and general policies for the
GitHub Readme Stats project.

- [Reporting a Vulnerability](#reporting-a-vulnerability)
- [Disclosure Policy](#disclosure-policy)

## Reporting a Vulnerability 

The GitHub Readme Stats team and community take all security vulnerabilities
seriously. Thank you for improving the security of our open source 
software. We appreciate your efforts and responsible disclosure and will
make every effort to acknowledge your contributions.

Report security vulnerabilities by emailing the GitHub Readme Stats team at:

```
hazru.anurag@gmail.com
```

The lead maintainer will acknowledge your email within 24 hours, and will
send a more detailed response within 48 hours indicating the next steps in 
handling your report. After the initial reply to your report, the security
team will endeavor to keep you informed of the progress towards a fix and
full announcement, and may ask for additional information or guidance.

Report security vulnerabilities in third-party modules to the person or 
team maintaining the module.

## Disclosure Policy

When the security team receives a security bug report, they will assign it
to a primary handler. This person will coordinate the fix and release
process, involving the following steps:

  * Confirm the problem.
  * Audit code to find any potential similar problems.
  * Prepare fixes and release them as fast as possible.


================================================
FILE: api/gist.js
================================================
// @ts-check

import { renderError } from "../src/common/render.js";
import { isLocaleAvailable } from "../src/translations.js";
import { renderGistCard } from "../src/cards/gist.js";
import { fetchGist } from "../src/fetchers/gist.js";
import {
  CACHE_TTL,
  resolveCacheSeconds,
  setCacheHeaders,
  setErrorCacheHeaders,
} from "../src/common/cache.js";
import { guardAccess } from "../src/common/access.js";
import {
  MissingParamError,
  retrieveSecondaryMessage,
} from "../src/common/error.js";
import { parseBoolean } from "../src/common/ops.js";

// @ts-ignore
export default async (req, res) => {
  const {
    id,
    title_color,
    icon_color,
    text_color,
    bg_color,
    theme,
    cache_seconds,
    locale,
    border_radius,
    border_color,
    show_owner,
    hide_border,
  } = req.query;

  res.setHeader("Content-Type", "image/svg+xml");

  const access = guardAccess({
    res,
    id,
    type: "gist",
    colors: {
      title_color,
      text_color,
      bg_color,
      border_color,
      theme,
    },
  });
  if (!access.isPassed) {
    return access.result;
  }

  if (locale && !isLocaleAvailable(locale)) {
    return res.send(
      renderError({
        message: "Something went wrong",
        secondaryMessage: "Language not found",
        renderOptions: {
          title_color,
          text_color,
          bg_color,
          border_color,
          theme,
        },
      }),
    );
  }

  try {
    const gistData = await fetchGist(id);
    const cacheSeconds = resolveCacheSeconds({
      requested: parseInt(cache_seconds, 10),
      def: CACHE_TTL.GIST_CARD.DEFAULT,
      min: CACHE_TTL.GIST_CARD.MIN,
      max: CACHE_TTL.GIST_CARD.MAX,
    });

    setCacheHeaders(res, cacheSeconds);

    return res.send(
      renderGistCard(gistData, {
        title_color,
        icon_color,
        text_color,
        bg_color,
        theme,
        border_radius,
        border_color,
        locale: locale ? locale.toLowerCase() : null,
        show_owner: parseBoolean(show_owner),
        hide_border: parseBoolean(hide_border),
      }),
    );
  } catch (err) {
    setErrorCacheHeaders(res);
    if (err instanceof Error) {
      return res.send(
        renderError({
          message: err.message,
          secondaryMessage: retrieveSecondaryMessage(err),
          renderOptions: {
            title_color,
            text_color,
            bg_color,
            border_color,
            theme,
            show_repo_link: !(err instanceof MissingParamError),
          },
        }),
      );
    }
    return res.send(
      renderError({
        message: "An unknown error occurred",
        renderOptions: {
          title_color,
          text_color,
          bg_color,
          border_color,
          theme,
        },
      }),
    );
  }
};


================================================
FILE: api/index.js
================================================
// @ts-check

import { renderStatsCard } from "../src/cards/stats.js";
import { guardAccess } from "../src/common/access.js";
import {
  CACHE_TTL,
  resolveCacheSeconds,
  setCacheHeaders,
  setErrorCacheHeaders,
} from "../src/common/cache.js";
import {
  MissingParamError,
  retrieveSecondaryMessage,
} from "../src/common/error.js";
import { parseArray, parseBoolean } from "../src/common/ops.js";
import { renderError } from "../src/common/render.js";
import { fetchStats } from "../src/fetchers/stats.js";
import { isLocaleAvailable } from "../src/translations.js";

// @ts-ignore
export default async (req, res) => {
  const {
    username,
    hide,
    hide_title,
    hide_border,
    card_width,
    hide_rank,
    show_icons,
    include_all_commits,
    commits_year,
    line_height,
    title_color,
    ring_color,
    icon_color,
    text_color,
    text_bold,
    bg_color,
    theme,
    cache_seconds,
    exclude_repo,
    custom_title,
    locale,
    disable_animations,
    border_radius,
    number_format,
    number_precision,
    border_color,
    rank_icon,
    show,
  } = req.query;
  res.setHeader("Content-Type", "image/svg+xml");

  const access = guardAccess({
    res,
    id: username,
    type: "username",
    colors: {
      title_color,
      text_color,
      bg_color,
      border_color,
      theme,
    },
  });
  if (!access.isPassed) {
    return access.result;
  }

  if (locale && !isLocaleAvailable(locale)) {
    return res.send(
      renderError({
        message: "Something went wrong",
        secondaryMessage: "Language not found",
        renderOptions: {
          title_color,
          text_color,
          bg_color,
          border_color,
          theme,
        },
      }),
    );
  }

  try {
    const showStats = parseArray(show);
    const stats = await fetchStats(
      username,
      parseBoolean(include_all_commits),
      parseArray(exclude_repo),
      showStats.includes("prs_merged") ||
        showStats.includes("prs_merged_percentage"),
      showStats.includes("discussions_started"),
      showStats.includes("discussions_answered"),
      parseInt(commits_year, 10),
    );
    const cacheSeconds = resolveCacheSeconds({
      requested: parseInt(cache_seconds, 10),
      def: CACHE_TTL.STATS_CARD.DEFAULT,
      min: CACHE_TTL.STATS_CARD.MIN,
      max: CACHE_TTL.STATS_CARD.MAX,
    });

    setCacheHeaders(res, cacheSeconds);

    return res.send(
      renderStatsCard(stats, {
        hide: parseArray(hide),
        show_icons: parseBoolean(show_icons),
        hide_title: parseBoolean(hide_title),
        hide_border: parseBoolean(hide_border),
        card_width: parseInt(card_width, 10),
        hide_rank: parseBoolean(hide_rank),
        include_all_commits: parseBoolean(include_all_commits),
        commits_year: parseInt(commits_year, 10),
        line_height,
        title_color,
        ring_color,
        icon_color,
        text_color,
        text_bold: parseBoolean(text_bold),
        bg_color,
        theme,
        custom_title,
        border_radius,
        border_color,
        number_format,
        number_precision: parseInt(number_precision, 10),
        locale: locale ? locale.toLowerCase() : null,
        disable_animations: parseBoolean(disable_animations),
        rank_icon,
        show: showStats,
      }),
    );
  } catch (err) {
    setErrorCacheHeaders(res);
    if (err instanceof Error) {
      return res.send(
        renderError({
          message: err.message,
          secondaryMessage: retrieveSecondaryMessage(err),
          renderOptions: {
            title_color,
            text_color,
            bg_color,
            border_color,
            theme,
            show_repo_link: !(err instanceof MissingParamError),
          },
        }),
      );
    }
    return res.send(
      renderError({
        message: "An unknown error occurred",
        renderOptions: {
          title_color,
          text_color,
          bg_color,
          border_color,
          theme,
        },
      }),
    );
  }
};


================================================
FILE: api/pin.js
================================================
// @ts-check

import { renderRepoCard } from "../src/cards/repo.js";
import { guardAccess } from "../src/common/access.js";
import {
  CACHE_TTL,
  resolveCacheSeconds,
  setCacheHeaders,
  setErrorCacheHeaders,
} from "../src/common/cache.js";
import {
  MissingParamError,
  retrieveSecondaryMessage,
} from "../src/common/error.js";
import { parseBoolean } from "../src/common/ops.js";
import { renderError } from "../src/common/render.js";
import { fetchRepo } from "../src/fetchers/repo.js";
import { isLocaleAvailable } from "../src/translations.js";

// @ts-ignore
export default async (req, res) => {
  const {
    username,
    repo,
    hide_border,
    title_color,
    icon_color,
    text_color,
    bg_color,
    theme,
    show_owner,
    cache_seconds,
    locale,
    border_radius,
    border_color,
    description_lines_count,
  } = req.query;

  res.setHeader("Content-Type", "image/svg+xml");

  const access = guardAccess({
    res,
    id: username,
    type: "username",
    colors: {
      title_color,
      text_color,
      bg_color,
      border_color,
      theme,
    },
  });
  if (!access.isPassed) {
    return access.result;
  }

  if (locale && !isLocaleAvailable(locale)) {
    return res.send(
      renderError({
        message: "Something went wrong",
        secondaryMessage: "Language not found",
        renderOptions: {
          title_color,
          text_color,
          bg_color,
          border_color,
          theme,
        },
      }),
    );
  }

  try {
    const repoData = await fetchRepo(username, repo);
    const cacheSeconds = resolveCacheSeconds({
      requested: parseInt(cache_seconds, 10),
      def: CACHE_TTL.PIN_CARD.DEFAULT,
      min: CACHE_TTL.PIN_CARD.MIN,
      max: CACHE_TTL.PIN_CARD.MAX,
    });

    setCacheHeaders(res, cacheSeconds);

    return res.send(
      renderRepoCard(repoData, {
        hide_border: parseBoolean(hide_border),
        title_color,
        icon_color,
        text_color,
        bg_color,
        theme,
        border_radius,
        border_color,
        show_owner: parseBoolean(show_owner),
        locale: locale ? locale.toLowerCase() : null,
        description_lines_count,
      }),
    );
  } catch (err) {
    setErrorCacheHeaders(res);
    if (err instanceof Error) {
      return res.send(
        renderError({
          message: err.message,
          secondaryMessage: retrieveSecondaryMessage(err),
          renderOptions: {
            title_color,
            text_color,
            bg_color,
            border_color,
            theme,
            show_repo_link: !(err instanceof MissingParamError),
          },
        }),
      );
    }
    return res.send(
      renderError({
        message: "An unknown error occurred",
        renderOptions: {
          title_color,
          text_color,
          bg_color,
          border_color,
          theme,
        },
      }),
    );
  }
};


================================================
FILE: api/status/pat-info.js
================================================
// @ts-check

/**
 * @file Contains a simple cloud function that can be used to check which PATs are no
 * longer working. It returns a list of valid PATs, expired PATs and PATs with errors.
 *
 * @description This function is currently rate limited to 1 request per 5 minutes.
 */

import { request } from "../../src/common/http.js";
import { logger } from "../../src/common/log.js";
import { dateDiff } from "../../src/common/ops.js";

export const RATE_LIMIT_SECONDS = 60 * 5; // 1 request per 5 minutes

/**
 * Simple uptime check fetcher for the PATs.
 *
 * @param {any} variables Fetcher variables.
 * @param {string} token GitHub token.
 * @returns {Promise<import('axios').AxiosResponse>} The response.
 */
const uptimeFetcher = (variables, token) => {
  return request(
    {
      query: `
        query {
          rateLimit {
            remaining
            resetAt
          },
        }`,
      variables,
    },
    {
      Authorization: `bearer ${token}`,
    },
  );
};

const getAllPATs = () => {
  return Object.keys(process.env).filter((key) => /PAT_\d*$/.exec(key));
};

/**
 * @typedef {(variables: any, token: string) => Promise<import('axios').AxiosResponse>} Fetcher The fetcher function.
 * @typedef {{validPATs: string[], expiredPATs: string[], exhaustedPATs: string[], suspendedPATs: string[], errorPATs: string[], details: any}} PATInfo The PAT info.
 */

/**
 * Check whether any of the PATs is expired.
 *
 * @param {Fetcher} fetcher The fetcher function.
 * @param {any} variables Fetcher variables.
 * @returns {Promise<PATInfo>} The response.
 */
const getPATInfo = async (fetcher, variables) => {
  /** @type {Record<string, any>} */
  const details = {};
  const PATs = getAllPATs();

  for (const pat of PATs) {
    try {
      const response = await fetcher(variables, process.env[pat]);
      const errors = response.data.errors;
      const hasErrors = Boolean(errors);
      const errorType = errors?.[0]?.type;
      const isRateLimited =
        (hasErrors && errorType === "RATE_LIMITED") ||
        response.data.data?.rateLimit?.remaining === 0;

      // Store PATs with errors.
      if (hasErrors && errorType !== "RATE_LIMITED") {
        details[pat] = {
          status: "error",
          error: {
            type: errors[0].type,
            message: errors[0].message,
          },
        };
        continue;
      } else if (isRateLimited) {
        const date1 = new Date();
        const date2 = new Date(response.data?.data?.rateLimit?.resetAt);
        details[pat] = {
          status: "exhausted",
          remaining: 0,
          resetIn: dateDiff(date2, date1) + " minutes",
        };
      } else {
        details[pat] = {
          status: "valid",
          remaining: response.data.data.rateLimit.remaining,
        };
      }
    } catch (err) {
      // Store the PAT if it is expired.
      const errorMessage = err.response?.data?.message?.toLowerCase();
      if (errorMessage === "bad credentials") {
        details[pat] = {
          status: "expired",
        };
      } else if (errorMessage === "sorry. your account was suspended.") {
        details[pat] = {
          status: "suspended",
        };
      } else {
        throw err;
      }
    }
  }

  const filterPATsByStatus = (status) => {
    return Object.keys(details).filter((pat) => details[pat].status === status);
  };

  const sortedDetails = Object.keys(details)
    .sort()
    .reduce((obj, key) => {
      obj[key] = details[key];
      return obj;
    }, {});

  return {
    validPATs: filterPATsByStatus("valid"),
    expiredPATs: filterPATsByStatus("expired"),
    exhaustedPATs: filterPATsByStatus("exhausted"),
    suspendedPATs: filterPATsByStatus("suspended"),
    errorPATs: filterPATsByStatus("error"),
    details: sortedDetails,
  };
};

/**
 * Cloud function that returns information about the used PATs.
 *
 * @param {any} _ The request.
 * @param {any} res The response.
 * @returns {Promise<void>} The response.
 */
export default async (_, res) => {
  res.setHeader("Content-Type", "application/json");
  try {
    // Add header to prevent abuse.
    const PATsInfo = await getPATInfo(uptimeFetcher, {});
    if (PATsInfo) {
      res.setHeader(
        "Cache-Control",
        `max-age=0, s-maxage=${RATE_LIMIT_SECONDS}`,
      );
    }
    res.send(JSON.stringify(PATsInfo, null, 2));
  } catch (err) {
    // Throw error if something went wrong.
    logger.error(err);
    res.setHeader("Cache-Control", "no-store");
    res.send("Something went wrong: " + err.message);
  }
};


================================================
FILE: api/status/up.js
================================================
// @ts-check

/**
 * @file Contains a simple cloud function that can be used to check if the PATs are still
 * functional.
 *
 * @description This function is currently rate limited to 1 request per 5 minutes.
 */

import { request } from "../../src/common/http.js";
import retryer from "../../src/common/retryer.js";
import { logger } from "../../src/common/log.js";

export const RATE_LIMIT_SECONDS = 60 * 5; // 1 request per 5 minutes

/**
 * Simple uptime check fetcher for the PATs.
 *
 * @param {any} variables Fetcher variables.
 * @param {string} token GitHub token.
 * @returns {Promise<import('axios').AxiosResponse>} The response.
 */
const uptimeFetcher = (variables, token) => {
  return request(
    {
      query: `
        query {
          rateLimit {
              remaining
          }
        }
        `,
      variables,
    },
    {
      Authorization: `bearer ${token}`,
    },
  );
};

/**
 * @typedef {{
 *  schemaVersion: number;
 *  label: string;
 *  message: "up" | "down";
 *  color: "brightgreen" | "red";
 *  isError: boolean
 * }} ShieldsResponse Shields.io response object.
 */

/**
 * Creates Json response that can be used for shields.io dynamic card generation.
 *
 * @param {boolean} up Whether the PATs are up or not.
 * @returns {ShieldsResponse}  Dynamic shields.io JSON response object.
 *
 * @see https://shields.io/endpoint.
 */
const shieldsUptimeBadge = (up) => {
  const schemaVersion = 1;
  const isError = true;
  const label = "Public Instance";
  const message = up ? "up" : "down";
  const color = up ? "brightgreen" : "red";
  return {
    schemaVersion,
    label,
    message,
    color,
    isError,
  };
};

/**
 * Cloud function that returns whether the PATs are still functional.
 *
 * @param {any} req The request.
 * @param {any} res The response.
 * @returns {Promise<void>} Nothing.
 */
export default async (req, res) => {
  let { type } = req.query;
  type = type ? type.toLowerCase() : "boolean";

  res.setHeader("Content-Type", "application/json");

  try {
    let PATsValid = true;
    try {
      await retryer(uptimeFetcher, {});
    } catch (err) {
      // Resolve eslint no-unused-vars
      err;

      PATsValid = false;
    }

    if (PATsValid) {
      res.setHeader(
        "Cache-Control",
        `max-age=0, s-maxage=${RATE_LIMIT_SECONDS}`,
      );
    } else {
      res.setHeader("Cache-Control", "no-store");
    }

    switch (type) {
      case "shields":
        res.send(shieldsUptimeBadge(PATsValid));
        break;
      case "json":
        res.send({ up: PATsValid });
        break;
      default:
        res.send(PATsValid);
        break;
    }
  } catch (err) {
    // Return fail boolean if something went wrong.
    logger.error(err);
    res.setHeader("Cache-Control", "no-store");
    res.send("Something went wrong: " + err.message);
  }
};


================================================
FILE: api/top-langs.js
================================================
// @ts-check

import { renderTopLanguages } from "../src/cards/top-languages.js";
import { guardAccess } from "../src/common/access.js";
import {
  CACHE_TTL,
  resolveCacheSeconds,
  setCacheHeaders,
  setErrorCacheHeaders,
} from "../src/common/cache.js";
import {
  MissingParamError,
  retrieveSecondaryMessage,
} from "../src/common/error.js";
import { parseArray, parseBoolean } from "../src/common/ops.js";
import { renderError } from "../src/common/render.js";
import { fetchTopLanguages } from "../src/fetchers/top-languages.js";
import { isLocaleAvailable } from "../src/translations.js";

// @ts-ignore
export default async (req, res) => {
  const {
    username,
    hide,
    hide_title,
    hide_border,
    card_width,
    title_color,
    text_color,
    bg_color,
    theme,
    cache_seconds,
    layout,
    langs_count,
    exclude_repo,
    size_weight,
    count_weight,
    custom_title,
    locale,
    border_radius,
    border_color,
    disable_animations,
    hide_progress,
    stats_format,
  } = req.query;
  res.setHeader("Content-Type", "image/svg+xml");

  const access = guardAccess({
    res,
    id: username,
    type: "username",
    colors: {
      title_color,
      text_color,
      bg_color,
      border_color,
      theme,
    },
  });
  if (!access.isPassed) {
    return access.result;
  }

  if (locale && !isLocaleAvailable(locale)) {
    return res.send(
      renderError({
        message: "Something went wrong",
        secondaryMessage: "Locale not found",
        renderOptions: {
          title_color,
          text_color,
          bg_color,
          border_color,
          theme,
        },
      }),
    );
  }

  if (
    layout !== undefined &&
    (typeof layout !== "string" ||
      !["compact", "normal", "donut", "donut-vertical", "pie"].includes(layout))
  ) {
    return res.send(
      renderError({
        message: "Something went wrong",
        secondaryMessage: "Incorrect layout input",
        renderOptions: {
          title_color,
          text_color,
          bg_color,
          border_color,
          theme,
        },
      }),
    );
  }

  if (
    stats_format !== undefined &&
    (typeof stats_format !== "string" ||
      !["bytes", "percentages"].includes(stats_format))
  ) {
    return res.send(
      renderError({
        message: "Something went wrong",
        secondaryMessage: "Incorrect stats_format input",
        renderOptions: {
          title_color,
          text_color,
          bg_color,
          border_color,
          theme,
        },
      }),
    );
  }

  try {
    const topLangs = await fetchTopLanguages(
      username,
      parseArray(exclude_repo),
      size_weight,
      count_weight,
    );
    const cacheSeconds = resolveCacheSeconds({
      requested: parseInt(cache_seconds, 10),
      def: CACHE_TTL.TOP_LANGS_CARD.DEFAULT,
      min: CACHE_TTL.TOP_LANGS_CARD.MIN,
      max: CACHE_TTL.TOP_LANGS_CARD.MAX,
    });

    setCacheHeaders(res, cacheSeconds);

    return res.send(
      renderTopLanguages(topLangs, {
        custom_title,
        hide_title: parseBoolean(hide_title),
        hide_border: parseBoolean(hide_border),
        card_width: parseInt(card_width, 10),
        hide: parseArray(hide),
        title_color,
        text_color,
        bg_color,
        theme,
        layout,
        langs_count,
        border_radius,
        border_color,
        locale: locale ? locale.toLowerCase() : null,
        disable_animations: parseBoolean(disable_animations),
        hide_progress: parseBoolean(hide_progress),
        stats_format,
      }),
    );
  } catch (err) {
    setErrorCacheHeaders(res);
    if (err instanceof Error) {
      return res.send(
        renderError({
          message: err.message,
          secondaryMessage: retrieveSecondaryMessage(err),
          renderOptions: {
            title_color,
            text_color,
            bg_color,
            border_color,
            theme,
            show_repo_link: !(err instanceof MissingParamError),
          },
        }),
      );
    }
    return res.send(
      renderError({
        message: "An unknown error occurred",
        renderOptions: {
          title_color,
          text_color,
          bg_color,
          border_color,
          theme,
        },
      }),
    );
  }
};


================================================
FILE: api/wakatime.js
================================================
// @ts-check

import { renderWakatimeCard } from "../src/cards/wakatime.js";
import { renderError } from "../src/common/render.js";
import { fetchWakatimeStats } from "../src/fetchers/wakatime.js";
import { isLocaleAvailable } from "../src/translations.js";
import {
  CACHE_TTL,
  resolveCacheSeconds,
  setCacheHeaders,
  setErrorCacheHeaders,
} from "../src/common/cache.js";
import { guardAccess } from "../src/common/access.js";
import {
  MissingParamError,
  retrieveSecondaryMessage,
} from "../src/common/error.js";
import { parseArray, parseBoolean } from "../src/common/ops.js";

// @ts-ignore
export default async (req, res) => {
  const {
    username,
    title_color,
    icon_color,
    hide_border,
    card_width,
    line_height,
    text_color,
    bg_color,
    theme,
    cache_seconds,
    hide_title,
    hide_progress,
    custom_title,
    locale,
    layout,
    langs_count,
    hide,
    api_domain,
    border_radius,
    border_color,
    display_format,
    disable_animations,
  } = req.query;

  res.setHeader("Content-Type", "image/svg+xml");

  const access = guardAccess({
    res,
    id: username,
    type: "wakatime",
    colors: {
      title_color,
      text_color,
      bg_color,
      border_color,
      theme,
    },
  });
  if (!access.isPassed) {
    return access.result;
  }

  if (locale && !isLocaleAvailable(locale)) {
    return res.send(
      renderError({
        message: "Something went wrong",
        secondaryMessage: "Language not found",
        renderOptions: {
          title_color,
          text_color,
          bg_color,
          border_color,
          theme,
        },
      }),
    );
  }

  try {
    const stats = await fetchWakatimeStats({ username, api_domain });
    const cacheSeconds = resolveCacheSeconds({
      requested: parseInt(cache_seconds, 10),
      def: CACHE_TTL.WAKATIME_CARD.DEFAULT,
      min: CACHE_TTL.WAKATIME_CARD.MIN,
      max: CACHE_TTL.WAKATIME_CARD.MAX,
    });

    setCacheHeaders(res, cacheSeconds);

    return res.send(
      renderWakatimeCard(stats, {
        custom_title,
        hide_title: parseBoolean(hide_title),
        hide_border: parseBoolean(hide_border),
        card_width: parseInt(card_width, 10),
        hide: parseArray(hide),
        line_height,
        title_color,
        icon_color,
        text_color,
        bg_color,
        theme,
        hide_progress,
        border_radius,
        border_color,
        locale: locale ? locale.toLowerCase() : null,
        layout,
        langs_count,
        display_format,
        disable_animations: parseBoolean(disable_animations),
      }),
    );
  } catch (err) {
    setErrorCacheHeaders(res);
    if (err instanceof Error) {
      return res.send(
        renderError({
          message: err.message,
          secondaryMessage: retrieveSecondaryMessage(err),
          renderOptions: {
            title_color,
            text_color,
            bg_color,
            border_color,
            theme,
            show_repo_link: !(err instanceof MissingParamError),
          },
        }),
      );
    }
    return res.send(
      renderError({
        message: "An unknown error occurred",
        renderOptions: {
          title_color,
          text_color,
          bg_color,
          border_color,
          theme,
        },
      }),
    );
  }
};


================================================
FILE: codecov.yml
================================================
codecov:
  require_ci_to_pass: yes

coverage:
  precision: 2
  round: down
  range: "70...100"

  status:
    project:
      default:
        threshold: 5
    patch: false


================================================
FILE: eslint.config.mjs
================================================
import globals from "globals";
import path from "node:path";
import { fileURLToPath } from "node:url";
import js from "@eslint/js";
import { FlatCompat } from "@eslint/eslintrc";
import jsdoc from "eslint-plugin-jsdoc";

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const compat = new FlatCompat({
  baseDirectory: __dirname,
  recommendedConfig: js.configs.recommended,
  allConfig: js.configs.all,
});

export default [
  ...compat.extends("prettier"),
  {
    languageOptions: {
      globals: {
        ...globals.node,
        ...globals.browser,
      },

      ecmaVersion: 2022,
      sourceType: "module",
    },
    plugins: {
      jsdoc,
    },
    rules: {
      "no-unexpected-multiline": "error",
      "accessor-pairs": [
        "error",
        {
          getWithoutSet: false,
          setWithoutGet: true,
        },
      ],
      "block-scoped-var": "warn",
      "consistent-return": "error",
      curly: "error",
      "no-alert": "error",
      "no-caller": "error",
      "no-warning-comments": [
        "warn",
        {
          terms: ["TODO", "FIXME"],
          location: "start",
        },
      ],
      "no-with": "warn",
      radix: "warn",
      "no-delete-var": "error",
      "no-undef-init": "off",
      "no-undef": "error",
      "no-undefined": "off",
      "no-unused-vars": "warn",
      "no-use-before-define": "error",
      "constructor-super": "error",
      "no-class-assign": "error",
      "no-const-assign": "error",
      "no-dupe-class-members": "error",
      "no-this-before-super": "error",
      "object-shorthand": ["warn"],
      "no-mixed-spaces-and-tabs": "warn",
      "no-multiple-empty-lines": "warn",
      "no-negated-condition": "warn",
      "no-unneeded-ternary": "warn",
      "keyword-spacing": [
        "error",
        {
          before: true,
          after: true,
        },
      ],
      "jsdoc/require-returns": "warn",
      "jsdoc/require-returns-description": "warn",
      "jsdoc/require-param-description": "warn",
      "jsdoc/require-jsdoc": "warn",
    },
  },
];


================================================
FILE: express.js
================================================
import "dotenv/config";
import statsCard from "./api/index.js";
import repoCard from "./api/pin.js";
import langCard from "./api/top-langs.js";
import wakatimeCard from "./api/wakatime.js";
import gistCard from "./api/gist.js";
import express from "express";

const app = express();
const router = express.Router();

router.get("/", statsCard);
router.get("/pin", repoCard);
router.get("/top-langs", langCard);
router.get("/wakatime", wakatimeCard);
router.get("/gist", gistCard);

app.use("/api", router);

const port = process.env.PORT || process.env.port || 9000;
app.listen(port, "0.0.0.0", () => {
  console.log(`Server running on port ${port}`);
});


================================================
FILE: jest.bench.config.js
================================================
export default {
  clearMocks: true,
  transform: {},
  testEnvironment: "jsdom",
  coverageProvider: "v8",
  testPathIgnorePatterns: ["<rootDir>/node_modules/", "<rootDir>/tests/e2e/"],
  modulePathIgnorePatterns: ["<rootDir>/node_modules/", "<rootDir>/tests/e2e/"],
  coveragePathIgnorePatterns: [
    "<rootDir>/node_modules/",
    "<rootDir>/tests/e2e/",
  ],
  testRegex: "(\\.bench)\\.(ts|tsx|js)$",
};


================================================
FILE: jest.config.js
================================================
export default {
  clearMocks: true,
  transform: {},
  testEnvironment: "jsdom",
  coverageProvider: "v8",
  testPathIgnorePatterns: ["<rootDir>/node_modules/", "<rootDir>/tests/e2e/"],
  modulePathIgnorePatterns: ["<rootDir>/node_modules/", "<rootDir>/tests/e2e/"],
  coveragePathIgnorePatterns: [
    "<rootDir>/node_modules/",
    "<rootDir>/tests/E2E/",
  ],
};


================================================
FILE: jest.e2e.config.js
================================================
export default {
  clearMocks: true,
  transform: {},
  testEnvironment: "node",
  coverageProvider: "v8",
  testMatch: ["<rootDir>/tests/e2e/**/*.test.js"],
};


================================================
FILE: package.json
================================================
{
  "name": "github-readme-stats",
  "version": "1.0.0",
  "description": "Dynamically generate stats for your GitHub readme",
  "keywords": [
    "github-readme-stats",
    "readme-stats",
    "cards",
    "card-generator"
  ],
  "main": "src/index.js",
  "type": "module",
  "homepage": "https://github.com/anuraghazra/github-readme-stats",
  "bugs": {
    "url": "https://github.com/anuraghazra/github-readme-stats/issues"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/anuraghazra/github-readme-stats.git"
  },
  "scripts": {
    "test": "node --experimental-vm-modules node_modules/jest/bin/jest.js --coverage",
    "test:watch": "node --experimental-vm-modules node_modules/jest/bin/jest.js --watch",
    "test:update:snapshot": "node --experimental-vm-modules node_modules/jest/bin/jest.js -u",
    "test:e2e": "node --experimental-vm-modules node_modules/jest/bin/jest.js --config jest.e2e.config.js",
    "theme-readme-gen": "node scripts/generate-theme-doc",
    "preview-theme": "node scripts/preview-theme",
    "close-stale-theme-prs": "node scripts/close-stale-theme-prs",
    "generate-langs-json": "node scripts/generate-langs-json",
    "format": "prettier --write .",
    "format:check": "prettier --check .",
    "prepare": "husky",
    "lint": "npx eslint --max-warnings 0 \"./src/**/*.js\" \"./scripts/**/*.js\" \"./tests/**/*.js\" \"./api/**/*.js\" \"./themes/**/*.js\"",
    "bench": "node --experimental-vm-modules node_modules/jest/bin/jest.js --config jest.bench.config.js"
  },
  "author": "Anurag Hazra",
  "license": "MIT",
  "devDependencies": {
    "@actions/core": "^2.0.1",
    "@actions/github": "^6.0.1",
    "@eslint/eslintrc": "^3.3.3",
    "@eslint/js": "^9.39.2",
    "@testing-library/dom": "^10.4.1",
    "@testing-library/jest-dom": "^6.9.1",
    "@uppercod/css-to-object": "^1.1.1",
    "axios-mock-adapter": "^2.1.0",
    "color-contrast-checker": "^2.1.0",
    "eslint": "^9.39.2",
    "eslint-config-prettier": "^10.1.8",
    "eslint-plugin-jsdoc": "^61.5.0",
    "express": "^5.2.1",
    "globals": "^16.5.0",
    "hjson": "^3.2.2",
    "husky": "^9.1.7",
    "jest": "^30.2.0",
    "jest-environment-jsdom": "^30.2.0",
    "js-yaml": "^4.1.1",
    "lint-staged": "^16.2.7",
    "lodash.snakecase": "^4.1.1",
    "parse-diff": "^0.11.1",
    "prettier": "^3.7.3"
  },
  "dependencies": {
    "axios": "^1.13.1",
    "dotenv": "^17.2.3",
    "emoji-name-map": "^2.0.3",
    "github-username-regex": "^1.0.0",
    "word-wrap": "^1.2.5"
  },
  "lint-staged": {
    "*.{js,css,md}": "prettier --write"
  },
  "engines": {
    "node": ">=22"
  }
}


================================================
FILE: readme.md
================================================
<div align="center">
  <img src="https://res.cloudinary.com/anuraghazra/image/upload/v1594908242/logo_ccswme.svg" width="100px" alt="GitHub Readme Stats" />
  <h1 style="font-size: 28px; margin: 10px 0;">GitHub Readme Stats</h1>
  <p>Get dynamically generated GitHub stats on your READMEs!</p>
</div>

<p align="center">
  <a href="https://github.com/anuraghazra/github-readme-stats/actions">
    <img alt="Tests Passing" src="https://github.com/anuraghazra/github-readme-stats/workflows/Test/badge.svg" />
  </a>
  <a href="https://github.com/anuraghazra/github-readme-stats/graphs/contributors">
    <img alt="GitHub Contributors" src="https://img.shields.io/github/contributors/anuraghazra/github-readme-stats" />
  </a>
  <a href="https://codecov.io/gh/anuraghazra/github-readme-stats">
    <img alt="Tests Coverage" src="https://codecov.io/gh/anuraghazra/github-readme-stats/branch/master/graph/badge.svg" />
  </a>
  <a href="https://github.com/anuraghazra/github-readme-stats/issues">
    <img alt="Issues" src="https://img.shields.io/github/issues/anuraghazra/github-readme-stats?color=0088ff" />
  </a>
  <a href="https://github.com/anuraghazra/github-readme-stats/pulls">
    <img alt="GitHub pull requests" src="https://img.shields.io/github/issues-pr/anuraghazra/github-readme-stats?color=0088ff" />
  </a>
  <a href="https://securityscorecards.dev/viewer/?uri=github.com/anuraghazra/github-readme-stats">
    <img alt="OpenSSF Scorecard" src="https://api.securityscorecards.dev/projects/github.com/anuraghazra/github-readme-stats/badge" />
  </a>
  <br />
  <br />
  <a href="https://vercel.com?utm\_source=github\_readme\_stats\_team\&utm\_campaign=oss">
    <img src="./powered-by-vercel.svg"/>
  </a>
</p>

<p align="center">
  <a href="#all-demos">View Demo</a>
  ·
  <a href="https://github.com/anuraghazra/github-readme-stats/issues/new?assignees=&labels=bug&projects=&template=bug_report.yml">Report Bug</a>
  ·
  <a href="https://github.com/anuraghazra/github-readme-stats/issues/new?assignees=&labels=enhancement&projects=&template=feature_request.yml">Request Feature</a>
  ·
  <a href="https://github.com/anuraghazra/github-readme-stats/discussions/1770">FAQ</a>
  ·
  <a href="https://github.com/anuraghazra/github-readme-stats/discussions/new?category=q-a">Ask Question</a>
</p>


<p align="center">Love the project? Please consider <a href="https://www.paypal.me/anuraghazra">donating</a> to help it improve!</p>

<details>
<summary>Table of contents (Click to show)</summary>

- [GitHub Stats Card](#github-stats-card)
    - [Hiding individual stats](#hiding-individual-stats)
    - [Showing additional individual stats](#showing-additional-individual-stats)
    - [Showing icons](#showing-icons)
    - [Showing commits count for specified year](#showing-commits-count-for-specified-year)
    - [Themes](#themes)
    - [Customization](#customization)
- [GitHub Extra Pins](#github-extra-pins)
    - [Usage](#usage)
    - [Options](#options)
    - [Demo](#demo)
- [GitHub Gist Pins](#github-gist-pins)
    - [Usage](#usage-1)
    - [Options](#options-1)
    - [Demo](#demo-1)
- [Top Languages Card](#top-languages-card)
    - [Usage](#usage-2)
    - [Options](#options-2)
    - [Language stats algorithm](#language-stats-algorithm)
    - [Exclude individual repositories](#exclude-individual-repositories)
    - [Hide individual languages](#hide-individual-languages)
    - [Show more languages](#show-more-languages)
    - [Compact Language Card Layout](#compact-language-card-layout)
    - [Donut Chart Language Card Layout](#donut-chart-language-card-layout)
    - [Donut Vertical Chart Language Card Layout](#donut-vertical-chart-language-card-layout)
    - [Pie Chart Language Card Layout](#pie-chart-language-card-layout)
    - [Hide Progress Bars](#hide-progress-bars)
    - [Change format of language's stats](#change-format-of-languages-stats)
    - [Demo](#demo-2)
- [WakaTime Stats Card](#wakatime-stats-card)
    - [Options](#options-3)
    - [Demo](#demo-3)
- [All Demos](#all-demos)
  - [Quick Tip (Align The Cards)](#quick-tip-align-the-cards)
    - [Stats and top languages cards](#stats-and-top-languages-cards)
    - [Pinning repositories](#pinning-repositories)
- [Deploy on your own](#deploy-on-your-own)
  - [GitHub Actions (Recommended)](#github-actions-recommended)
  - [Self-hosted (Vercel/Other) (Recommended)](#self-hosted-vercelother-recommended)
    - [First step: get your Personal Access Token (PAT)](#first-step-get-your-personal-access-token-pat)
    - [On Vercel](#on-vercel)
    - [:film\_projector: Check Out Step By Step Video Tutorial By @codeSTACKr](#film_projector-check-out-step-by-step-video-tutorial-by-codestackr)
    - [On other platforms](#on-other-platforms)
    - [Available environment variables](#available-environment-variables)
  - [Keep your fork up to date](#keep-your-fork-up-to-date)
- [:sparkling\_heart: Support the project](#sparkling_heart-support-the-project)
</details>

# Important Notices <!-- omit in toc -->

> [!IMPORTANT]
> The public Vercel instance at `https://github-readme-stats.vercel.app/api` is best-effort and can be unreliable due to rate limits and traffic spikes (see [#1471](https://github.com/anuraghazra/github-readme-stats/issues/1471)). We use caching to improve stability (see [common options](#common-options)), but for reliable cards we recommend [self-hosting](#deploy-on-your-own) (Vercel or other) or using the [GitHub Actions workflow](#github-actions-recommended) to generate cards in your [profile repository](https://docs.github.com/en/account-and-profile/how-tos/profile-customization/managing-your-profile-readme).

<img alt="Uptime Badge" src="https://img.shields.io/endpoint?url=https%3A%2F%2Fgithub-readme-stats-git-monitoring-github-readme-stats-team.vercel.app%2Fapi%2Fstatus%2Fup%3Ftype%3Dshields">

> [!IMPORTANT]
> We're a small team, and to prioritize, we rely on upvotes :+1:. We use the Top Issues dashboard for tracking community demand (see [#1935](https://github.com/anuraghazra/github-readme-stats/issues/1935)). Do not hesitate to upvote the issues and pull requests you are interested in. We will work on the most upvoted first.

# GitHub Stats Card

Copy and paste this into your markdown, and that's it. Simple!

Change the `?username=` value to your GitHub username.

```md
[![Anurag's GitHub stats](https://github-readme-stats.vercel.app/api?username=anuraghazra)](https://github.com/anuraghazra/github-readme-stats)
```

> [!WARNING]
> By default, the stats card only shows statistics like stars, commits, and pull requests from public repositories. To show private statistics on the stats card, you should [deploy your own instance](#deploy-on-your-own) using your own GitHub API token.

> [!NOTE]
> Available ranks are S (top 1%), A+ (12.5%), A (25%), A- (37.5%), B+ (50%), B (62.5%), B- (75%), C+ (87.5%) and C (everyone). This ranking scheme is based on the [Japanese academic grading](https://wikipedia.org/wiki/Academic_grading_in_Japan) system. The global percentile is calculated as a weighted sum of percentiles for each statistic (number of commits, pull requests, reviews, issues, stars, and followers), based on the cumulative distribution function of the [exponential](https://wikipedia.org/wiki/exponential_distribution) and the [log-normal](https://wikipedia.org/wiki/Log-normal_distribution) distributions. The implementation can be investigated at [src/calculateRank.js](https://github.com/anuraghazra/github-readme-stats/blob/master/src/calculateRank.js). The circle around the rank shows 100 minus the global percentile.

### Hiding individual stats

You can pass a query parameter `&hide=` to hide any specific stats with comma-separated values.

> Options: `&hide=stars,commits,prs,issues,contribs`

```md
![Anurag's GitHub stats](https://github-readme-stats.vercel.app/api?username=anuraghazra&hide=contribs,prs)
```

### Showing additional individual stats

You can pass a query parameter `&show=` to show any specific additional stats with comma-separated values.

> Options: `&show=reviews,discussions_started,discussions_answered,prs_merged,prs_merged_percentage`

```md
![Anurag's GitHub stats](https://github-readme-stats.vercel.app/api?username=anuraghazra&show=reviews,discussions_started,discussions_answered,prs_merged,prs_merged_percentage)
```

### Showing icons

To enable icons, you can pass `&show_icons=true` in the query param, like so:

```md
![Anurag's GitHub stats](https://github-readme-stats.vercel.app/api?username=anuraghazra&show_icons=true)
```

### Showing commits count for specified year

You can specify a year and fetch only the commits that were made in that year by passing `&commits_year=YYYY` to the parameter.

```md
![Anurag's GitHub stats](https://github-readme-stats.vercel.app/api?username=anuraghazra&commits_year=2020)
```

### Themes

With inbuilt themes, you can customize the look of the card without doing any [manual customization](#customization).

Use `&theme=THEME_NAME` parameter like so :

```md
![Anurag's GitHub stats](https://github-readme-stats.vercel.app/api?username=anuraghazra&show_icons=true&theme=radical)
```

#### All inbuilt themes

GitHub Readme Stats comes with several built-in themes (e.g. `dark`, `radical`, `merko`, `gruvbox`, `tokyonight`, `onedark`, `cobalt`, `synthwave`, `highcontrast`, `dracula`).

<img src="https://res.cloudinary.com/anuraghazra/image/upload/v1595174536/grs-themes_l4ynja.png" alt="GitHub Readme Stats Themes" width="600px"/>

You can look at a preview for [all available themes](themes/README.md) or checkout the [theme config file](themes/index.js). Please note that we paused the addition of new themes to decrease maintenance efforts; all pull requests related to new themes will be closed.

#### Responsive Card Theme

[![Anurag's GitHub stats-Dark](https://github-readme-stats.vercel.app/api?username=anuraghazra\&show_icons=true\&theme=dark#gh-dark-mode-only)](https://github.com/anuraghazra/github-readme-stats#responsive-card-theme#gh-dark-mode-only)
[![Anurag's GitHub stats-Light](https://github-readme-stats.vercel.app/api?username=anuraghazra\&show_icons=true\&theme=default#gh-light-mode-only)](https://github.com/anuraghazra/github-readme-stats#responsive-card-theme#gh-light-mode-only)

Since GitHub will re-upload the cards and serve them from their [CDN](https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/about-anonymized-urls), we can not infer the browser/GitHub theme on the server side. There are, however, four methods you can use to create dynamics themes on the client side.

##### Use the transparent theme

We have included a `transparent` theme that has a transparent background. This theme is optimized to look good on GitHub's dark and light default themes. You can enable this theme using the `&theme=transparent` parameter like so:

```md
![Anurag's GitHub stats](https://github-readme-stats.vercel.app/api?username=anuraghazra&show_icons=true&theme=transparent)
```

<details>
<summary>:eyes: Show example</summary>

![Anurag's GitHub stats](https://github-readme-stats.vercel.app/api?username=anuraghazra\&show_icons=true\&theme=transparent)

</details>

##### Add transparent alpha channel to a themes bg\_color

You can use the `bg_color` parameter to make any of [the available themes](themes/README.md) transparent. This is done by setting the `bg_color` to a color with a transparent alpha channel (i.e. `bg_color=00000000`):

```md
![Anurag's GitHub stats](https://github-readme-stats.vercel.app/api?username=anuraghazra&show_icons=true&bg_color=00000000)
```

<details>
<summary>:eyes: Show example</summary>

![Anurag's GitHub stats](https://github-readme-stats.vercel.app/api?username=anuraghazra\&show_icons=true\&bg_color=00000000)

</details>

##### Use GitHub's theme context tag

You can use [GitHub's theme context](https://github.blog/changelog/2021-11-24-specify-theme-context-for-images-in-markdown/) tags to switch the theme based on the user GitHub theme automatically. This is done by appending `#gh-dark-mode-only` or `#gh-light-mode-only` to the end of an image URL. This tag will define whether the image specified in the markdown is only shown to viewers using a light or a dark GitHub theme:

```md
[![Anurag's GitHub stats-Dark](https://github-readme-stats.vercel.app/api?username=anuraghazra&show_icons=true&theme=dark#gh-dark-mode-only)](https://github.com/anuraghazra/github-readme-stats#gh-dark-mode-only)
[![Anurag's GitHub stats-Light](https://github-readme-stats.vercel.app/api?username=anuraghazra&show_icons=true&theme=default#gh-light-mode-only)](https://github.com/anuraghazra/github-readme-stats#gh-light-mode-only)
```

<details>
<summary>:eyes: Show example</summary>

[![Anurag's GitHub stats-Dark](https://github-readme-stats.vercel.app/api?username=anuraghazra\&show_icons=true\&theme=dark#gh-dark-mode-only)](https://github.com/anuraghazra/github-readme-stats#gh-dark-mode-only)
[![Anurag's GitHub stats-Light](https://github-readme-stats.vercel.app/api?username=anuraghazra\&show_icons=true\&theme=default#gh-light-mode-only)](https://github.com/anuraghazra/github-readme-stats#gh-light-mode-only)

</details>

##### Use GitHub's new media feature

You can use [GitHub's new media feature](https://github.blog/changelog/2022-05-19-specify-theme-context-for-images-in-markdown-beta/) in HTML to specify whether to display images for light or dark themes. This is done using the HTML `<picture>` element in combination with the `prefers-color-scheme` media feature.

```html
<picture>
  <source
    srcset="https://github-readme-stats.vercel.app/api?username=anuraghazra&show_icons=true&theme=dark"
    media="(prefers-color-scheme: dark)"
  />
  <source
    srcset="https://github-readme-stats.vercel.app/api?username=anuraghazra&show_icons=true"
    media="(prefers-color-scheme: light), (prefers-color-scheme: no-preference)"
  />
  <img src="https://github-readme-stats.vercel.app/api?username=anuraghazra&show_icons=true" />
</picture>
```

<details>
<summary>:eyes: Show example</summary>

<picture>
  <source
    srcset="https://github-readme-stats.vercel.app/api?username=anuraghazra&show_icons=true&theme=dark"
    media="(prefers-color-scheme: dark)"
  />
  <source
    srcset="https://github-readme-stats.vercel.app/api?username=anuraghazra&show_icons=true"
    media="(prefers-color-scheme: light), (prefers-color-scheme: no-preference)"
  />
  <img src="https://github-readme-stats.vercel.app/api?username=anuraghazra&show_icons=true" />
</picture>

</details>

### Customization

You can customize the appearance of all your cards however you wish with URL parameters.

#### Common Options

| Name | Description | Type | Default value |
| --- | --- | --- | --- |
| `title_color` | Card's title color. | string (hex color) | `2f80ed` |
| `text_color` | Body text color. | string (hex color) | `434d58` |
| `icon_color` | Icons color if available. | string (hex color) | `4c71f2` |
| `border_color` | Card's border color. Does not apply when `hide_border` is enabled. | string (hex color) | `e4e2e2` |
| `bg_color` | Card's background color. | string (hex color or a gradient in the form of *angle,start,end*) | `fffefe` |
| `hide_border` | Hides the card's border. | boolean | `false` |
| `theme` | Name of the theme, choose from [all available themes](themes/README.md). | enum | `default` |
| `cache_seconds` | Sets the cache header manually (min: 21600, max: 86400). | integer | `21600` |
| `locale` | Sets the language in the card, you can check full list of available locales [here](#available-locales). | enum | `en` |
| `border_radius` | Corner rounding on the card. | number | `4.5` |

> [!WARNING]
> We use caching to decrease the load on our servers (see <https://github.com/anuraghazra/github-readme-stats/issues/1471#issuecomment-1271551425>). Our cards have the following default cache hours: stats card - 24 hours, top languages card - 144 hours (6 days), pin card - 240 hours (10 days), gist card - 48 hours (2 days), and wakatime card - 24 hours. If you want the data on your cards to be updated more often you can [deploy your own instance](#deploy-on-your-own) and set [environment variable](#available-environment-variables) `CACHE_SECONDS` to a value of your choosing.

##### Gradient in bg\_color

You can provide multiple comma-separated values in the bg\_color option to render a gradient with the following format:

    &bg_color=DEG,COLOR1,COLOR2,COLOR3...COLOR10

##### Available locales

Here is a list of all available locales:

<table>
<tr><td>

| Code | Locale |
| --- | --- |
| `ar` | Arabic |
| `az` | Azerbaijani |
| `bn` | Bengali |
| `bg` | Bulgarian |
| `my` | Burmese |
| `ca` | Catalan |
| `cn` | Chinese |
| `zh-tw` | Chinese (Taiwan) |
| `cs` | Czech |
| `nl` | Dutch |
| `en` | English |
| `fil` | Filipino |
| `fi` | Finnish |
| `fr` | French |
| `de` | German |
| `el` | Greek |

</td><td>

| Code | Locale |
| --- | --- |
| `he` | Hebrew |
| `hi` | Hindi |
| `hu` | Hungarian |
| `id` | Indonesian |
| `it` | Italian |
| `ja` | Japanese |
| `kr` | Korean |
| `ml` | Malayalam |
| `np` | Nepali |
| `no` | Norwegian |
| `fa` | Persian (Farsi) |
| `pl` | Polish |
| `pt-br` | Portuguese (Brazil) |
| `pt-pt` | Portuguese (Portugal) |
| `ro` | Romanian |

</td><td>

| Code | Locale |
| --- | --- |
| `ru` | Russian |
| `sa` | Sanskrit |
| `sr` | Serbian (Cyrillic) |
| `sr-latn` | Serbian (Latin) |
| `sk` | Slovak |
| `es` | Spanish |
| `sw` | Swahili |
| `se` | Swedish |
| `ta` | Tamil |
| `th` | Thai |
| `tr` | Turkish |
| `uk-ua` | Ukrainian |
| `ur` | Urdu |
| `uz` | Uzbek |
| `vi` | Vietnamese |

</td></tr>
</table>

If we don't support your language, please consider contributing! You can find more information about how to do it in our [contributing guidelines](CONTRIBUTING.md#translations-contribution).

#### Stats Card Exclusive Options

| Name | Description | Type | Default value |
| --- | --- | --- | --- |
| `hide` | Hides the [specified items](#hiding-individual-stats) from stats. | string (comma-separated values) | `null` |
| `hide_title` | Hides the title of your stats card. | boolean | `false` |
| `card_width` | Sets the card's width manually. | number | `500px  (approx.)` |
| `hide_rank` | Hides the rank and automatically resizes the card width. | boolean | `false` |
| `rank_icon` | Shows alternative rank icon (i.e. `github`, `percentile` or `default`). | enum | `default` |
| `show_icons` | Shows icons near all stats. | boolean | `false` |
| `include_all_commits` | Count total commits instead of just the current year commits. | boolean | `false` |
| `line_height` | Sets the line height between text. | integer | `25` |
| `exclude_repo` | Excludes specified repositories. | string (comma-separated values) | `null` |
| `custom_title` | Sets a custom title for the card. | string | `<username> GitHub Stats` |
| `text_bold` | Uses bold text. | boolean | `true` |
| `disable_animations` | Disables all animations in the card. | boolean | `false` |
| `ring_color` | Color of the rank circle. | string (hex color) | `2f80ed` |
| `number_format` | Switches between two available formats for displaying the card values `short` (i.e. `6.6k`) and `long` (i.e. `6626`). | enum | `short` |
| `number_precision` | Enforce the number of digits after the decimal point for `short` number format. Must be an integer between 0 and 2. Will be ignored for `long` number format. | integer (0, 1 or 2) | `null` |
| `show` | Shows [additional items](#showing-additional-individual-stats) on stats card (i.e. `reviews`, `discussions_started`, `discussions_answered`, `prs_merged` or `prs_merged_percentage`). | string (comma-separated values) | `null` |
| `commits_year` | Filters and counts only commits made in the specified year. | integer _(YYYY)_ | `<current year> (one year to date)` |

> [!WARNING]
> Custom title should be URI-escaped, as specified in [Percent Encoding](https://en.wikipedia.org/wiki/Percent-encoding) (i.e: `Anurag's GitHub Stats` should become `Anurag%27s%20GitHub%20Stats`). You can use [urlencoder.org](https://www.urlencoder.org/) to help you do this automatically.

> [!NOTE]
> When hide\_rank=`true`, the minimum card width is 270 px + the title length and padding.

***

# GitHub Extra Pins

GitHub extra pins allow you to pin more than 6 repositories in your profile using a GitHub readme profile.

Yay! You are no longer limited to 6 pinned repositories.

### Usage

Copy-paste this code into your readme and change the links.

Endpoint: `api/pin?username=anuraghazra&repo=github-readme-stats`

```md
[![Readme Card](https://github-readme-stats.vercel.app/api/pin/?username=anuraghazra&repo=github-readme-stats)](https://github.com/anuraghazra/github-readme-stats)
```

### Options

You can customize the appearance and behavior of the pinned repository card using the [common options](#common-options) and exclusive options listed in the table below.

| Name | Description | Type | Default value |
| --- | --- | --- | --- |
| `show_owner` | Shows the repo's owner name. | boolean | `false` |
| `description_lines_count` | Manually set the number of lines for the description. Specified value will be clamped between 1 and 3. If this parameter is not specified, the number of lines will be automatically adjusted according to the actual length of the description. | number | `null` |

### Demo

![Readme Card](https://github-readme-stats.vercel.app/api/pin/?username=anuraghazra\&repo=github-readme-stats)

Use `show_owner` query option to include the repo's owner username

![Readme Card](https://github-readme-stats.vercel.app/api/pin/?username=anuraghazra\&repo=github-readme-stats\&show_owner=true)

# GitHub Gist Pins

GitHub gist pins allow you to pin gists in your GitHub profile using a GitHub readme profile.

### Usage

Copy-paste this code into your readme and change the links.

Endpoint: `api/gist?id=bbfce31e0217a3689c8d961a356cb10d`

```md
[![Gist Card](https://github-readme-stats.vercel.app/api/gist?id=bbfce31e0217a3689c8d961a356cb10d)](https://gist.github.com/Yizack/bbfce31e0217a3689c8d961a356cb10d/)
```

### Options

You can customize the appearance and behavior of the gist card using the [common options](#common-options) and exclusive options listed in the table below.

| Name | Description | Type | Default value |
| --- | --- | --- | --- |
| `show_owner` | Shows the gist's owner name. | boolean | `false` |

### Demo

![Gist Card](https://github-readme-stats.vercel.app/api/gist?id=bbfce31e0217a3689c8d961a356cb10d)

Use `show_owner` query option to include the gist's owner username

![Gist Card](https://github-readme-stats.vercel.app/api/gist?id=bbfce31e0217a3689c8d961a356cb10d\&show_owner=true)

# Top Languages Card

The top languages card shows a GitHub user's most frequently used languages.

> [!WARNING]
> By default, the language card shows language results only from public repositories. To include languages used in private repositories, you should [deploy your own instance](#deploy-on-your-own) using your own GitHub API token.

> [!NOTE]
> Top Languages does not indicate the user's skill level or anything like that; it's a GitHub metric to determine which languages have the most code on GitHub. It is a new feature of github-readme-stats.

> [!WARNING]
> This card shows language usage only inside your own non-forked repositories, not depending on who the author of the commits is. It does not include your contributions into another users/organizations repositories. Currently there are no way to get this data from GitHub API. If you want this behavior to be improved you can support [this feature request](https://github.com/orgs/community/discussions/18230) created by [@rickstaa](https://github.com/rickstaa) inside GitHub Community.

> [!WARNING]
> Currently this card shows data only about first 100 repositories. This is because GitHub API limitations which cause downtimes of public instances (see [#1471](https://github.com/anuraghazra/github-readme-stats/issues/1471)). In future this behavior will be improved by releasing GitHub action or providing environment variables for user's own instances.

### Usage

Copy-paste this code into your readme and change the links.

Endpoint: `api/top-langs?username=anuraghazra`

```md
[![Top Langs](https://github-readme-stats.vercel.app/api/top-langs/?username=anuraghazra)](https://github.com/anuraghazra/github-readme-stats)
```

### Options

You can customize the appearance and behavior of the top languages card using the [common options](#common-options) and exclusive options listed in the table below.

| Name | Description | Type | Default value |
| --- | --- | --- | --- |
| `hide` | Hides the [specified languages](#hide-individual-languages) from card. | string (comma-separated values) | `null` |
| `hide_title` | Hides the title of your card. | boolean | `false` |
| `layout` | Switches between five available layouts `normal` & `compact` & `donut` & `donut-vertical` & `pie`. | enum | `normal` |
| `card_width` | Sets the card's width manually. | number | `300` |
| `langs_count` | Shows more languages on the card, between 1-20. | integer | `5` for `normal` and `donut`, `6` for other layouts |
| `exclude_repo` | Excludes specified repositories. | string (comma-separated values) | `null` |
| `custom_title` | Sets a custom title for the card. | string | `Most Used Languages` |
| `disable_animations` | Disables all animations in the card. | boolean | `false` |
| `hide_progress` | Uses the compact layout option, hides percentages, and removes the bars. | boolean | `false` |
| `size_weight` | Configures language stats algorithm (see [Language stats algorithm](#language-stats-algorithm)). | integer | `1` |
| `count_weight` | Configures language stats algorithm (see [Language stats algorithm](#language-stats-algorithm)). | integer | `0` |
| `stats_format` | Switches between two available formats for language's stats `percentages` and `bytes`. | enum | `percentages` |

> [!WARNING]
> Language names and custom title should be URI-escaped, as specified in [Percent Encoding](https://en.wikipedia.org/wiki/Percent-encoding) (i.e: `c++` should become `c%2B%2B`, `jupyter notebook` should become `jupyter%20notebook`, `Most Used Languages` should become `Most%20Used%20Languages`, etc.) You can use [urlencoder.org](https://www.urlencoder.org/) to help you do this automatically.

### Language stats algorithm

We use the following algorithm to calculate the languages percentages on the language card:

```js
ranking_index = (byte_count ^ size_weight) * (repo_count ^ count_weight)
```

By default, only the byte count is used for determining the languages percentages shown on the language card (i.e. `size_weight=1` and `count_weight=0`). You can, however, use the `&size_weight=` and `&count_weight=` options to weight the language usage calculation. The values must be positive real numbers. [More details about the algorithm can be found here](https://github.com/anuraghazra/github-readme-stats/issues/1600#issuecomment-1046056305).

*   `&size_weight=1&count_weight=0` - *(default)* Orders by byte count.
*   `&size_weight=0.5&count_weight=0.5` - *(recommended)* Uses both byte and repo count for ranking
*   `&size_weight=0&count_weight=1` - Orders by repo count

```md
![Top Langs](https://github-readme-stats.vercel.app/api/top-langs/?username=anuraghazra&size_weight=0.5&count_weight=0.5)
```

### Exclude individual repositories

You can use the `&exclude_repo=repo1,repo2` parameter to exclude individual repositories.

```md
![Top Langs](https://github-readme-stats.vercel.app/api/top-langs/?username=anuraghazra&exclude_repo=github-readme-stats,anuraghazra.github.io)
```

### Hide individual languages

You can use `&hide=language1,language2` parameter to hide individual languages.

```md
![Top Langs](https://github-readme-stats.vercel.app/api/top-langs/?username=anuraghazra&hide=javascript,html)
```

### Show more languages

You can use the `&langs_count=` option to increase or decrease the number of languages shown on the card. Valid values are integers between 1 and 20 (inclusive). By default it was set to `5` for `normal` & `donut` and `6` for other layouts.

```md
![Top Langs](https://github-readme-stats.vercel.app/api/top-langs/?username=anuraghazra&langs_count=8)
```

### Compact Language Card Layout

You can use the `&layout=compact` option to change the card design.

```md
![Top Langs](https://github-readme-stats.vercel.app/api/top-langs/?username=anuraghazra&layout=compact)
```

### Donut Chart Language Card Layout

You can use the `&layout=donut` option to change the card design.

```md
[![Top Langs](https://github-readme-stats.vercel.app/api/top-langs/?username=anuraghazra&layout=donut)](https://github.com/anuraghazra/github-readme-stats)
```

### Donut Vertical Chart Language Card Layout

You can use the `&layout=donut-vertical` option to change the card design.

```md
[![Top Langs](https://github-readme-stats.vercel.app/api/top-langs/?username=anuraghazra&layout=donut-vertical)](https://github.com/anuraghazra/github-readme-stats)
```

### Pie Chart Language Card Layout

You can use the `&layout=pie` option to change the card design.

```md
[![Top Langs](https://github-readme-stats.vercel.app/api/top-langs/?username=anuraghazra&layout=pie)](https://github.com/anuraghazra/github-readme-stats)
```

### Hide Progress Bars

You can use the `&hide_progress=true` option to hide the percentages and the progress bars (layout will be automatically set to `compact`).

```md
![Top Langs](https://github-readme-stats.vercel.app/api/top-langs/?username=anuraghazra&hide_progress=true)
```

### Change format of language's stats

You can use the `&stats_format=bytes` option to display the stats in bytes instead of percentage.

```md
![Top Langs](https://github-readme-stats.vercel.app/api/top-langs/?username=anuraghazra&stats_format=bytes)
```


### Demo

![Top Langs](https://github-readme-stats.vercel.app/api/top-langs/?username=anuraghazra)

*   Compact layout

![Top Langs](https://github-readme-stats.vercel.app/api/top-langs/?username=anuraghazra\&layout=compact)

*   Donut Chart layout

[![Top Langs](https://github-readme-stats.vercel.app/api/top-langs/?username=anuraghazra\&layout=donut)](https://github.com/anuraghazra/github-readme-stats)

*   Donut Vertical Chart layout

[![Top Langs](https://github-readme-stats.vercel.app/api/top-langs/?username=anuraghazra\&layout=donut-vertical)](https://github.com/anuraghazra/github-readme-stats)

*   Pie Chart layout

[![Top Langs](https://github-readme-stats.vercel.app/api/top-langs/?username=anuraghazra\&layout=pie)](https://github.com/anuraghazra/github-readme-stats)

*   Hidden progress bars

![Top Langs](https://github-readme-stats.vercel.app/api/top-langs/?username=anuraghazra\&hide_progress=true)


*  Display bytes instead of percentage

![Top Langs](https://github-readme-stats.vercel.app/api/top-langs/?username=anuraghazra\&stats_format=bytes)

# WakaTime Stats Card

> [!WARNING]
> Please be aware that we currently only show data from WakaTime profiles that are public. You therefore have to make sure that **BOTH** `Display code time publicly` and `Display languages, editors, os, categories publicly` are enabled.

> [!WARNING]
> In case you just created a new WakaTime account, then it might take up to 24 hours until your stats will become visible on the WakaTime stats card.

Change the `?username=` value to your [WakaTime](https://wakatime.com) username.

```md
[![Harlok's WakaTime stats](https://github-readme-stats.vercel.app/api/wakatime?username=ffflabs)](https://github.com/anuraghazra/github-readme-stats)
```

### Options

You can customize the appearance and behavior of the WakaTime stats card using the [common options](#common-options) and exclusive options listed in the table below.

| Name | Description | Type | Default value |
| --- | --- | --- | --- |
| `hide` | Hides the languages specified from the card. | string (comma-separated values) | `null` |
| `hide_title` | Hides the title of your card. | boolean | `false` |
| `card_width` | Sets the card's width manually. | number | `495` |
| `line_height` | Sets the line height between text. | integer | `25` |
| `hide_progress` | Hides the progress bar and percentage. | boolean | `false` |
| `custom_title` | Sets a custom title for the card. | string | `WakaTime Stats` |
| `layout` | Switches between two available layouts `default` & `compact`. | enum | `default` |
| `langs_count` | Limits the number of languages on the card, defaults to all reported languages. | integer | `null` |
| `api_domain` | Sets a custom API domain for the card, e.g. to use services like [Hakatime](https://github.com/mujx/hakatime) or [Wakapi](https://github.com/muety/wakapi) | string | `wakatime.com` |
| `display_format` | Sets the WakaTime stats display format. Choose `time` to display time-based stats or `percent` to show percentages. | enum | `time` |
| `disable_animations` | Disables all animations in the card. | boolean | `false` |

> [!WARNING]
> Custom title should be URI-escaped, as specified in [Percent Encoding](https://en.wikipedia.org/wiki/Percent-encoding) (i.e: `WakaTime Stats` should become `WakaTime%20Stats`). You can use [urlencoder.org](https://www.urlencoder.org/) to help you do this automatically.

### Demo

![Harlok's WakaTime stats](https://github-readme-stats.vercel.app/api/wakatime?username=ffflabs)

![Harlok's WakaTime stats](https://github-readme-stats.vercel.app/api/wakatime?username=ffflabs\&hide_progress=true)

*   Compact layout

![Harlok's WakaTime stats](https://github-readme-stats.vercel.app/api/wakatime?username=ffflabs\&layout=compact)

***

# All Demos

*   Default

![Anurag's GitHub stats](https://github-readme-stats.vercel.app/api?username=anuraghazra)

*   Hiding specific stats

![Anurag's GitHub stats](https://github-readme-stats.vercel.app/api?username=anuraghazra\&hide=contribs,issues)

*   Showing additional stats

![Anurag's GitHub stats](https://github-readme-stats.vercel.app/api?username=anuraghazra\&show_icons=true\&show=reviews,discussions_started,discussions_answered,prs_merged,prs_merged_percentage)

*   Showing icons

![Anurag's GitHub stats](https://github-readme-stats.vercel.app/api?username=anuraghazra\&hide=issues\&show_icons=true)

*   Shows GitHub logo instead rank level

![Anurag's GitHub stats](https://github-readme-stats.vercel.app/api?username=anuraghazra\&rank_icon=github)

*   Shows user rank percentile instead of rank level

![Anurag's GitHub stats](https://github-readme-stats.vercel.app/api?username=anuraghazra\&rank_icon=percentile)

*   Customize Border Color

![Anurag's GitHub stats](https://github-readme-stats.vercel.app/api?username=anuraghazra\&border_color=2e4058)

*   Include All Commits

![Anurag's GitHub stats](https://github-readme-stats.vercel.app/api?username=anuraghazra\&include_all_commits=true)

*   Themes

Choose from any of the [default themes](#themes)

![Anurag's GitHub stats](https://github-readme-stats.vercel.app/api?username=anuraghazra\&show_icons=true\&theme=radical)

*   Gradient

![Anurag's GitHub stats](https://github-readme-stats.vercel.app/api?username=anuraghazra\&bg_color=30,e96443,904e95\&title_color=fff\&text_color=fff)

*   Customizing stats card

![Anurag's GitHub stats](https://github-readme-stats.vercel.app/api/?username=anuraghazra\&show_icons=true\&title_color=fff\&icon_color=79ff97\&text_color=9f9f9f\&bg_color=151515)

*   Setting card locale

![Anurag's GitHub stats](https://github-readme-stats.vercel.app/api/?username=anuraghazra\&locale=es)

*   Customizing repo card

![Customized Card](https://github-readme-stats.vercel.app/api/pin?username=anuraghazra\&repo=github-readme-stats\&title_color=fff\&icon_color=f9f9f9\&text_color=9f9f9f\&bg_color=151515)

*   Gist card

![Gist Card](https://github-readme-stats.vercel.app/api/gist?id=bbfce31e0217a3689c8d961a356cb10d)

*   Customizing gist card

![Gist Card](https://github-readme-stats.vercel.app/api/gist?id=bbfce31e0217a3689c8d961a356cb10d&theme=calm)

*   Top languages

![Top Langs](https://github-readme-stats.vercel.app/api/top-langs/?username=anuraghazra)

*   WakaTime card

![Harlok's WakaTime stats](https://github-readme-stats.vercel.app/api/wakatime?username=ffflabs)

***

## Quick Tip (Align The Cards)

By default, GitHub does not lay out the cards side by side. To do that, you can use such approaches:

### Stats and top languages cards

```html
<a href="https://github.com/anuraghazra/github-readme-stats">
  <img height=200 align="center" src="https://github-readme-stats.vercel.app/api?username=anuraghazra" />
</a>
<a href="https://github.com/anuraghazra/convoychat">
  <img height=200 align="center" src="https://github-readme-stats.vercel.app/api/top-langs?username=anuraghazra&layout=compact&langs_count=8&card_width=320" />
</a>
```

<details>
<summary>:eyes: Show example</summary>

<a href="https://github.com/anuraghazra/github-readme-stats">
  <img height=200 align="center" src="https://github-readme-stats.vercel.app/api?username=anuraghazra" />
</a>
<a href="https://github.com/anuraghazra/convoychat">
  <img height=200 align="center" src="https://github-readme-stats.vercel.app/api/top-langs?username=anuraghazra&layout=compact&langs_count=8&card_width=320" />
</a>

</details>

### Pinning repositories

```html
<a href="https://github.com/anuraghazra/github-readme-stats">
  <img align="center" src="https://github-readme-stats.vercel.app/api/pin/?username=anuraghazra&repo=github-readme-stats" />
</a>
<a href="https://github.com/anuraghazra/convoychat">
  <img align="center" src="https://github-readme-stats.vercel.app/api/pin/?username=anuraghazra&repo=convoychat" />
</a>
```

<details>
<summary>:eyes: Show example</summary>

<a href="https://github.com/anuraghazra/github-readme-stats">
  <img align="center" src="https://github-readme-stats.vercel.app/api/pin/?username=anuraghazra&repo=github-readme-stats" />
</a>
<a href="https://github.com/anuraghazra/convoychat">
  <img align="center" src="https://github-readme-stats.vercel.app/api/pin/?username=anuraghazra&repo=convoychat" />
</a>

</details>

# Deploy on your own (recommended)

Because the public endpoint is [not reliable](#Important-Notices), we recommend self-deployment via GitHub Actions or your own hosted instance. GitHub Actions is the simplest setup with static SVGs stored in your repo but less frequent updates, while self-hosting takes more work and can serve fresher stats (with caching).

## GitHub Actions

GitHub Actions generates static SVGs and avoids per-request API calls. By default it uses `GITHUB_TOKEN` (public stats only), for private stats, set a [PAT](https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/managing-your-personal-access-tokens) as a secret and pass it to the action instead.

Create `/.github/workflows/grs.yml` in your profile repo (`USERNAME/USERNAME`):

```yaml
name: Update README cards

on:
  schedule:
    - cron: "0 3 * * *"
  workflow_dispatch:

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - name: Generate stats card
        uses: readme-tools/github-readme-stats-action@v1
        with:
          card: stats
          options: username=${{ github.repository_owner }}&show_icons=true
          path: profile/stats.svg
          token: ${{ secrets.GITHUB_TOKEN }}

      - name: Commit cards
        run: |
          git config user.name "github-actions"
          git config user.email "github-actions@users.noreply.github.com"
          git add profile/*.svg
          git commit -m "Update README cards" || exit 0
          git push
```

Then embed from your profile README:

```md
![Stats](./profile/stats.svg)
```

See more options and examples in the [GitHub Readme Stats Action README](https://github.com/readme-tools/github-readme-stats-action#readme).

## Self-hosted (Vercel/Other)

Running your own instance avoids public rate limits and gives you full control over caching, tokens, and private stats.

### First step: get your Personal Access Token (PAT)

For deploying your own instance of GitHub Readme Stats, you will need to create a GitHub Personal Access Token (PAT). Below are the steps to create one and the scopes you need to select for both classic and fine-grained tokens.

Selecting the right scopes for your token is important in case you want to display private contributions on your cards.

#### Classic token

* Go to [Account -> Settings -> Developer Settings -> Personal access tokens -> Tokens (classic)](https://github.com/settings/tokens).
* Click on `Generate new token -> Generate new token (classic)`.
* Scopes to select:
  * repo
  * read:user
* Click on `Generate token` and copy it.

#### Fine-grained token

> [!WARNING]\
> This limits the scope to issues in your repositories and includes only public commits.

* Go to [Account -> Settings -> Developer Settings -> Personal access tokens -> Fine-grained tokens](https://github.com/settings/tokens).
* Click on `Generate new token -> Generate new token`.
* Select an expiration date
* Select `All repositories`
* Scopes to select in `Repository permission`:
  * Commit statuses: read-only
  * Contents: read-only
  * Issues: read-only
  * Metadata: read-only
  * Pull requests: read-only
* Click on `Generate token` and copy it.

### On Vercel

### :film\_projector: [Check Out Step By Step Video Tutorial By @codeSTACKr](https://youtu.be/n6d4KHSKqGk?t=107)

Since the GitHub API only allows 5k requests per hour, my `https://github-readme-stats.vercel.app/api` could possibly hit the rate limiter. If you host it on your own Vercel server, then you do not have to worry about anything. Click on the deploy button to get started!

> [!NOTE]
> Since [#58](https://github.com/anuraghazra/github-readme-stats/pull/58), we should be able to handle more than 5k requests and have fewer issues with downtime :grin:.

> [!NOTE]
> If you are on the [Pro (i.e. paid)](https://vercel.com/pricing) Vercel plan, the [maxDuration](https://vercel.com/docs/concepts/projects/project-configuration#value-definition) value found in the [vercel.json](https://github.com/anuraghazra/github-readme-stats/blob/master/vercel.json) can be increased when your Vercel instance frequently times out during the card request. You are advised to keep this value lower than `30` seconds to prevent high memory usage.

[![Deploy to Vercel](https://vercel.com/button)](https://vercel.com/import/project?template=https://github.com/anuraghazra/github-readme-stats)

<details>
 <summary><b>:hammer_and_wrench: Step-by-step guide on setting up your own Vercel instance</b></summary>

1.  Go to [vercel.com](https://vercel.com/).
2.  Click on `Log in`.
    ![](https://files.catbox.moe/pcxk33.png)
3.  Sign in with GitHub by pressing `Continue with GitHub`.
    ![](https://files.catbox.moe/b9oxey.png)
4.  Sign in to GitHub and allow access to all repositories if prompted.
5.  Fork this repo.
6.  Go back to your [Vercel dashboard](https://vercel.com/dashboard).
7.  To import a project, click the `Add New...` button and select the `Project` option.
    ![](https://files.catbox.moe/3n76fh.png)
8.  Click the `Continue with GitHub` button, search for the required Git Repository and import it by clicking the `Import` button. Alternatively, you can import a Third-Party Git Repository using the `Import Third-Party Git Repository ->` link at the bottom of the page.
    ![](https://files.catbox.moe/mg5p04.png)
9.  Create a Personal Access Token (PAT) as described in the [previous section](#first-step-get-your-personal-access-token-pat).
10. Add the PAT as an environment variable named `PAT_1` (as shown).
    ![](https://files.catbox.moe/0yclio.png)
11. Click deploy, and you're good to go. See your domains to use the API!

</details>

### On other platforms

> [!WARNING]
> This way of using GRS is not officially supported and was added to cater to some particular use cases where Vercel could not be used (e.g. [#2341](https://github.com/anuraghazra/github-readme-stats/discussions/2341)). The support for this method, therefore, is limited.

<details>
<summary><b>:hammer_and_wrench: Step-by-step guide for deploying on other platforms</b></summary>

1.  Fork or clone this repo as per your needs
2.  Move `express` from the devDependencies to the dependencies section of `package.json`
    <https://github.com/anuraghazra/github-readme-stats/blob/ba7c2f8b55eac8452e479c8bd38b044d204d0424/package.json#L54-L61>
3.  Run `npm i` if needed (initial setup)
4.  Run `node express.js` to start the server, or set the entry point to `express.js` in `package.json` if you're deploying on a managed service
    <https://github.com/anuraghazra/github-readme-stats/blob/ba7c2f8b55eac8452e479c8bd38b044d204d0424/package.json#L11>
5.  You're done 🎉
    </details>

### Available environment variables

GitHub Readme Stats provides several environment variables that can be used to customize the behavior of your self-hosted instance. These include:

<table>
  <thead>
    <tr>
      <th>Name</th>
      <th>Description</th>
      <th>Supported values</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td><code>CACHE_SECONDS</code></td>
      <td>Sets the cache duration in seconds for the generated cards. This variable takes precedence over the default cache timings for the public instance. If this variable is not set, the default cache duration is 24 hours (86,400 seconds).</td>
      <td>Any positive integer or <code>0</code> to disable caching</td>
    </tr>
    <tr>
      <td><code>WHITELIST</code></td>
      <td>A comma-separated list of GitHub usernames that are allowed to access your instance. If this variable is not set, all usernames are allowed.</td>
      <td>Comma-separated GitHub usernames</td>
    </tr>
    <tr>
      <td><code>GIST_WHITELIST</code></td>
      <td>A comma-separated list of GitHub Gist IDs that are allowed to be accessed on your instance. If this variable is not set, all Gist IDs are allowed.</td>
      <td>Comma-separated GitHub Gist IDs</td>
    </tr>
    <tr>
      <td><code>EXCLUDE_REPO</code></td>
      <td>A comma-separated list of repositories that will be excluded from stats and top languages cards on your instance. This allows repository exclusion without exposing repository names in public URLs. This enhances privacy for self-hosted instances that include private repositories in stats cards.</td>
      <td>Comma-separated repository names</td>
    </tr>
    <tr>
      <td><code>FETCH_MULTI_PAGE_STARS</code></td>
      <td>Enables fetching all starred repositories for accurate star counts, especially for users with more than 100 repositories. This may increase response times and API points usage, so it is disabled on the public instance.</td>
      <td><code>true</code> or <code>false</code></td>
    </tr>
  </tbody>
</table>

See [the Vercel documentation](https://vercel.com/docs/concepts/projects/environment-variables) on adding these environment variables to your Vercel instance.

> [!WARNING]
> Please remember to redeploy your instance after making any changes to the environment variables so that the updates take effect. The changes will not be applied to the previous deployments.

## Keep your fork up to date

You can keep your fork, and thus your private Vercel instance up to date with the upstream using GitHub's [Sync Fork button](https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/working-with-forks/syncing-a-fork). You can also use the [pull](https://github.com/wei/pull) package created by [@wei](https://github.com/wei) to automate this process.

# :sparkling\_heart: Support the project

I open-source almost everything I can and try to reply to everyone needing help using these projects. Obviously,
this takes time. You can use this service for free.

However, if you are using this project and are happy with it or just want to encourage me to continue creating stuff, there are a few ways you can do it:

*   Giving proper credit when you use github-readme-stats on your readme, linking back to it. :D
*   Starring and sharing the project. :rocket:
*   [![paypal.me/anuraghazra](https://ionicabizau.github.io/badges/paypal.svg)](https://www.paypal.me/anuraghazra) - You can make a one-time donation via PayPal. I'll probably buy a ~~coffee~~ tea. :tea:

Thanks! :heart:

***

[![https://vercel.com?utm\_source=github\_readme\_stats\_team\&utm\_campaign=oss](powered-by-vercel.svg)](https://vercel.com?utm_source=github_readme_stats_team\&utm_campaign=oss)

Contributions are welcome! <3

Made with :heart: and JavaScript.


================================================
FILE: scripts/close-stale-theme-prs.js
================================================
/**
 * @file Script that can be used to close stale theme PRs that have a `invalid` label.
 */
import * as dotenv from "dotenv";
dotenv.config();

import { debug, setFailed } from "@actions/core";
import github from "@actions/github";
import { RequestError } from "@octokit/request-error";
import { getGithubToken, getRepoInfo } from "./helpers.js";

const CLOSING_COMMENT = `
	\rThis theme PR has been automatically closed due to inactivity. Please reopen it if you want to continue working on it.\
	\rThank you for your contributions.
`;
const REVIEWER = "github-actions[bot]";

/**
 * Retrieve the review user.
 * @returns {string} review user.
 */
const getReviewer = () => {
  return process.env.REVIEWER ? process.env.REVIEWER : REVIEWER;
};

/**
 * Fetch open PRs from a given repository.
 *
 * @param {module:@actions/github.Octokit} octokit The octokit client.
 * @param {string} user The user name of the repository owner.
 * @param {string} repo The name of the repository.
 * @param {string} reviewer The reviewer to filter by.
 * @returns {Promise<Object[]>} The open PRs.
 */
export const fetchOpenPRs = async (octokit, user, repo, reviewer) => {
  const openPRs = [];
  let hasNextPage = true;
  let endCursor;
  while (hasNextPage) {
    try {
      const { repository } = await octokit.graphql(
        `
            {
              repository(owner: "${user}", name: "${repo}") {
                open_prs: pullRequests(${
                  endCursor ? `after: "${endCursor}", ` : ""
                }
                  first: 100, states: OPEN, orderBy: {field: CREATED_AT, direction: DESC}) {
                  nodes {
                    number
										commits(last:1){
											nodes{
												commit{
													pushedDate
												}
											}
										}
                    labels(first: 100, orderBy:{field: CREATED_AT, direction: DESC}) {
                      nodes {
												name
                      }
                    }
                    reviews(first: 100, states: CHANGES_REQUESTED, author: "${reviewer}") {
											nodes {
                        submittedAt
											}
                    }
                  }
                  pageInfo {
                    endCursor
                    hasNextPage
                  }
                }
              }
            }
          `,
      );
      openPRs.push(...repository.open_prs.nodes);
      hasNextPage = repository.open_prs.pageInfo.hasNextPage;
      endCursor = repository.open_prs.pageInfo.endCursor;
    } catch (error) {
      if (error instanceof RequestError) {
        setFailed(`Could not retrieve top PRs using GraphQl: ${error.message}`);
      }
      throw error;
    }
  }
  return openPRs;
};

/**
 * Retrieve pull requests that have a given label.
 *
 * @param {Object[]} pulls The pull requests to check.
 * @param {string} label The label to check for.
 * @returns {Object[]} The pull requests that have the given label.
 */
export const pullsWithLabel = (pulls, label) => {
  return pulls.filter((pr) => {
    return pr.labels.nodes.some((lab) => lab.name === label);
  });
};

/**
 * Check if PR is stale. Meaning that it hasn't been updated in a given time.
 *
 * @param {Object} pullRequest request object.
 * @param {number} staleDays number of days.
 * @returns {boolean} indicating if PR is stale.
 */
const isStale = (pullRequest, staleDays) => {
  const lastCommitDate = new Date(
    pullRequest.commits.nodes[0].commit.pushedDate,
  );
  if (pullRequest.reviews.nodes[0]) {
    const lastReviewDate = new Date(
      pullRequest.reviews.nodes.sort((a, b) => (a < b ? 1 : -1))[0].submittedAt,
    );
    const lastUpdateDate =
      lastCommitDate >= lastReviewDate ? lastCommitDate : lastReviewDate;
    const now = new Date();
    return (now - lastUpdateDate) / (1000 * 60 * 60 * 24) >= staleDays;
  } else {
    return false;
  }
};

/**
 * Main function.
 *
 * @returns {Promise<void>} A promise.
 */
const run = async () => {
  try {
    // Create octokit client.
    const dryRun = process.env.DRY_RUN === "true" || false;
    const staleDays = process.env.STALE_DAYS || 20;
    debug("Creating octokit client...");
    const octokit = github.getOctokit(getGithubToken());
    const { owner, repo } = getRepoInfo(github.context);
    const reviewer = getReviewer();

    // Retrieve all theme pull requests.
    debug("Retrieving all theme pull requests...");
    const prs = await fetchOpenPRs(octokit, owner, repo, reviewer);
    const themePRs = pullsWithLabel(prs, "themes");
    const invalidThemePRs = pullsWithLabel(themePRs, "invalid");
    debug("Retrieving stale theme PRs...");
    const staleThemePRs = invalidThemePRs.filter((pr) =>
      isStale(pr, staleDays),
    );
    const staleThemePRsNumbers = staleThemePRs.map((pr) => pr.number);
    debug(`Found ${staleThemePRs.length} stale theme PRs`);

    // Loop through all stale invalid theme pull requests and close them.
    for (const prNumber of staleThemePRsNumbers) {
      debug(`Closing #${prNumber} because it is stale...`);
      if (dryRun) {
        debug("Dry run enabled, skipping...");
      } else {
        await octokit.rest.issues.createComment({
          owner,
          repo,
          issue_number: prNumber,
          body: CLOSING_COMMENT,
        });
        await octokit.rest.pulls.update({
          owner,
          repo,
          pull_number: prNumber,
          state: "closed",
        });
      }
    }
  } catch (error) {
    setFailed(error.message);
  }
};

run();


================================================
FILE: scripts/generate-langs-json.js
================================================
import axios from "axios";
import fs from "fs";
import jsYaml from "js-yaml";

const LANGS_FILEPATH = "./src/common/languageColors.json";

//Retrieve languages from github linguist repository yaml file
//@ts-ignore
axios
  .get(
    "https://raw.githubusercontent.com/github/linguist/master/lib/linguist/languages.yml",
  )
  .then((response) => {
    //and convert them to a JS Object
    const languages = jsYaml.load(response.data);

    const languageColors = {};

    //Filter only language colors from the whole file
    Object.keys(languages).forEach((lang) => {
      languageColors[lang] = languages[lang].color;
    });

    //Debug Print
    //console.dir(languageColors);
    fs.writeFileSync(
      LANGS_FILEPATH,
      JSON.stringify(languageColors, null, "    "),
    );
  });


================================================
FILE: scripts/generate-theme-doc.js
================================================
import fs from "fs";
import { themes } from "../themes/index.js";

const TARGET_FILE = "./themes/README.md";
const REPO_CARD_LINKS_FLAG = "<!-- REPO_CARD_LINKS -->";
const STAT_CARD_LINKS_FLAG = "<!-- STATS_CARD_LINKS -->";

const STAT_CARD_TABLE_FLAG = "<!-- STATS_CARD_TABLE -->";
const REPO_CARD_TABLE_FLAG = "<!-- REPO_CARD_TABLE -->";

const THEME_TEMPLATE = `## Available Themes

<!-- DO NOT EDIT THIS FILE DIRECTLY -->

With inbuilt themes, you can customize the look of the card without doing any manual customization.

Use \`?theme=THEME_NAME\` parameter like so:

\`\`\`md
![Anurag's GitHub stats](https://github-readme-stats.vercel.app/api?username=anuraghazra&theme=dark&show_icons=true)
\`\`\`

## Stats

> These themes work with all five of our cards: Stats Card, Repo Card, Gist Card, Top Languages Card, and WakaTime Card.

| | | |
| :--: | :--: | :--: |
${STAT_CARD_TABLE_FLAG}

## Repo Card

> These themes work with all five of our cards: Stats Card, Repo Card, Gist Card, Top Languages Card, and WakaTime Card.

| | | |
| :--: | :--: | :--: |
${REPO_CARD_TABLE_FLAG}

${STAT_CARD_LINKS_FLAG}

${REPO_CARD_LINKS_FLAG}
`;

const createRepoMdLink = (theme) => {
  return `\n[${theme}_repo]: https://github-readme-stats.vercel.app/api/pin/?username=anuraghazra&repo=github-readme-stats&cache_seconds=86400&theme=${theme}`;
};
const createStatMdLink = (theme) => {
  return `\n[${theme}]: https://github-readme-stats.vercel.app/api?username=anuraghazra&show_icons=true&hide=contribs,prs&cache_seconds=86400&theme=${theme}`;
};

const generateLinks = (fn) => {
  return Object.keys(themes)
    .map((name) => fn(name))
    .join("");
};

const createTableItem = ({ link, label, isRepoCard }) => {
  if (!link || !label) {
    return "";
  }
  return `\`${label}\` ![${link}][${link}${isRepoCard ? "_repo" : ""}]`;
};

const generateTable = ({ isRepoCard }) => {
  const rows = [];
  const themesFiltered = Object.keys(themes).filter(
    (name) => name !== (isRepoCard ? "default" : "default_repocard"),
  );

  for (let i = 0; i < themesFiltered.length; i += 3) {
    const one = themesFiltered[i];
    const two = themesFiltered[i + 1];
    const three = themesFiltered[i + 2];

    let tableItem1 = createTableItem({ link: one, label: one, isRepoCard });
    let tableItem2 = createTableItem({ link: two, label: two, isRepoCard });
    let tableItem3 = createTableItem({ link: three, label: three, isRepoCard });

    rows.push(`| ${tableItem1} | ${tableItem2} | ${tableItem3} |`);
  }

  return rows.join("\n");
};

const buildReadme = () => {
  return THEME_TEMPLATE.split("\n")
    .map((line) => {
      if (line.includes(REPO_CARD_LINKS_FLAG)) {
        return generateLinks(createRepoMdLink);
      }
      if (line.includes(STAT_CARD_LINKS_FLAG)) {
        return generateLinks(createStatMdLink);
      }
      if (line.includes(REPO_CARD_TABLE_FLAG)) {
        return generateTable({ isRepoCard: true });
      }
      if (line.includes(STAT_CARD_TABLE_FLAG)) {
        return generateTable({ isRepoCard: false });
      }
      return line;
    })
    .join("\n");
};

fs.writeFileSync(TARGET_FILE, buildReadme());


================================================
FILE: scripts/helpers.js
================================================
/**
 * @file Contains helper functions used in the scripts.
 */

import { getInput } from "@actions/core";

const OWNER = "anuraghazra";
const REPO = "github-readme-stats";

/**
 * Retrieve information about the repository that ran the action.
 *
 * @param {Object} ctx Action context.
 * @returns {Object} Repository information.
 */
export const getRepoInfo = (ctx) => {
  try {
    return {
      owner: ctx.repo.owner,
      repo: ctx.repo.repo,
    };
  } catch (error) {
    // Resolve eslint no-unused-vars
    error;

    return {
      owner: OWNER,
      repo: REPO,
    };
  }
};

/**
 * Retrieve github token and throw error if it is not found.
 *
 * @returns {string} GitHub token.
 */
export const getGithubToken = () => {
  const token = getInput("github_token") || process.env.GITHUB_TOKEN;
  if (!token) {
    throw Error("Could not find github token");
  }
  return token;
};


================================================
FILE: scripts/preview-theme.js
================================================
/**
 * @file This script is used to preview the theme on theme PRs.
 */
import * as dotenv from "dotenv";
dotenv.config();

import { debug, setFailed } from "@actions/core";
import github from "@actions/github";
import ColorContrastChecker from "color-contrast-checker";
import { info } from "console";
import Hjson from "hjson";
import snakeCase from "lodash.snakecase";
import parse from "parse-diff";
import { inspect } from "util";
import { isValidHexColor, isValidGradient } from "../src/common/color.js";
import { themes } from "../themes/index.js";
import { getGithubToken, getRepoInfo } from "./helpers.js";

const COMMENTER = "github-actions[bot]";

const COMMENT_TITLE = "Automated Theme Preview";
const THEME_PR_FAIL_TEXT = ":x: Theme PR does not adhere to our guidelines.";
const THEME_PR_SUCCESS_TEXT =
  ":heavy_check_mark: Theme PR does adhere to our guidelines.";
const FAIL_TEXT = `
  \rUnfortunately, your theme PR contains an error or does not adhere to our [theme guidelines](https://github.com/anuraghazra/github-readme-stats/blob/master/CONTRIBUTING.md#themes-contribution). Please fix the issues below, and we will review your\
  \r PR again. This pull request will **automatically close in 20 days** if no changes are made. After this time, you must re-open the PR for it to be reviewed.
`;
const THEME_CONTRIB_GUIDELINES = `
  \rHi, thanks for the theme contribution. Please read our theme [contribution guidelines](https://github.com/anuraghazra/github-readme-stats/blob/master/CONTRIBUTING.md#themes-contribution).

  \r> [!WARNING]\
  \r> Keep in mind that we already have a vast collection of different themes. To keep their number manageable, we began to add only themes supported by the community. Your pull request with theme addition will be merged once we get enough positive feedback from the community in the form of thumbs up :+1: emojis (see [#1935](https://github.com/anuraghazra/github-readme-stats/issues/1935#top-themes-prs)). We expect to see at least 10-15 thumbs up before making a decision to merge your pull request into the master branch. Remember that you can also support themes of other contributors that you liked to speed up their merge.

  \r> [!WARNING]\
  \r> Please do not submit a pull request with a batch of themes, since it will be hard to judge how the community will react to each of them. We will only merge one theme per pull request. If you have several themes, please submit a separate pull request for each of them. Situations when you have several versions of the same theme (e.g. light and dark) are an exception to this rule.

  \r> [!NOTE]\
  \r> Also, note that if this theme is exclusively for your personal use, then instead of adding it to our theme collection, you can use card [customization options](https://github.com/anuraghazra/github-readme-stats#customization).
`;
const COLOR_PROPS = {
  title_color: 6,
  icon_color: 6,
  text_color: 6,
  bg_color: 23,
  border_color: 6,
};
const ACCEPTED_COLOR_PROPS = Object.keys(COLOR_PROPS);
const REQUIRED_COLOR_PROPS = ACCEPTED_COLOR_PROPS.slice(0, 4);
const INVALID_REVIEW_COMMENT = (commentUrl) =>
  `Some themes are invalid. See the [Automated Theme Preview](${commentUrl}) comment above for more information.`;
var OCTOKIT;
var OWNER;
var REPO;
var PULL_REQUEST_ID;

/**
 * Incorrect JSON format error.
 * @extends Error
 * @param {string} message Error message.
 * @returns {Error} IncorrectJsonFormatError.
 */
class IncorrectJsonFormatError extends Error {
  /**
   * Constructor.
   *
   * @param {string} message Error message.
   */
  constructor(message) {
    super(message);
    this.name = "IncorrectJsonFormatError";
  }
}

/**
 * Retrieve PR number from the event payload.
 *
 * @returns {number} PR number.
 */
const getPrNumber = () => {
  if (process.env.MOCK_PR_NUMBER) {
    return process.env.MOCK_PR_NUMBER; // For testing purposes.
  }

  const pullRequest = github.context.payload.pull_request;
  if (!pullRequest) {
    throw Error("Could not get pull request number from context");
  }
  return pullRequest.number;
};

/**
 * Retrieve the commenting user.
 * @returns {string} Commenting user.
 */
const getCommenter = () => {
  return process.env.COMMENTER ? process.env.COMMENTER : COMMENTER;
};

/**
 * Returns whether the comment is a preview comment.
 *
 * @param {Object} inputs Action inputs.
 * @param {Object} comment Comment object.
 * @returns {boolean} Whether the comment is a preview comment.
 */
const isPreviewComment = (inputs, comment) => {
  return (
    (inputs.commentAuthor && comment.user
      ? comment.user.login === inputs.commentAuthor
      : true) &&
    (inputs.bodyIncludes && comment.body
      ? comment.body.includes(inputs.bodyIncludes)
      : true)
  );
};

/**
 * Find the preview theme comment.
 *
 * @param {Object} octokit Octokit instance.
 * @param {number} issueNumber Issue number.
 * @param {string} owner Owner of the repository.
 * @param {string} repo Repository name.
 * @param {string} commenter Comment author.
 * @returns {Object | undefined} The GitHub comment object.
 */
const findComment = async (octokit, issueNumber, owner, repo, commenter) => {
  const parameters = {
    owner,
    repo,
    issue_number: issueNumber,
  };
  const inputs = {
    commentAuthor: commenter,
    bodyIncludes: COMMENT_TITLE,
  };

  // Search each page for the comment
  for await (const { data: comments } of octokit.paginate.iterator(
    octokit.rest.issues.listComments,
    parameters,
  )) {
    const comment = comments.find((comment) =>
      isPreviewComment(inputs, comment),
    );
    if (comment) {
      debug(`Found theme preview comment: ${inspect(comment)}`);
      return comment;
    } else {
      debug(`No theme preview comment found.`);
    }
  }

  return undefined;
};

/**
 * Create or update the preview comment.
 *
 * @param {Object} octokit Octokit instance.
 * @param {number} issueNumber Issue number.
 * @param {Object} repo Repository name.
 * @param {Object} owner Owner of the repository.
 * @param {number} commentId Comment ID.
 * @param {string} body Comment body.
 * @returns {string} The comment URL.
 */
const upsertComment = async (
  octokit,
  issueNumber,
  repo,
  owner,
  commentId,
  body,
) => {
  let resp;
  if (commentId === undefined) {
    resp = await octokit.rest.issues.createComment({
      owner,
      repo,
      issue_number: issueNumber,
      body,
    });
  } else {
    resp = await octokit.rest.issues.updateComment({
      owner,
      repo,
      comment_id: commentId,
      body,
    });
  }
  return resp.data.html_url;
};

/**
 * Adds a review to the pull request.
 *
 * @param {Object} octokit Octokit instance.
 * @param {number} prNumber Pull request number.
 * @param {string} owner Owner of the repository.
 * @param {string} repo Repository name.
 * @param {string} reviewState The review state. Options are (APPROVE, REQUEST_CHANGES, COMMENT, PENDING).
 * @param {string} reason The reason for the review.
 * @returns {Promise<void>} Promise.
 */
const addReview = async (
  octokit,
  prNumber,
  owner,
  repo,
  reviewState,
  reason,
) => {
  await octokit.rest.pulls.createReview({
    owner,
    repo,
    pull_number: prNumber,
    event: reviewState,
    body: reason,
  });
};

/**
 * Add label to pull request.
 *
 * @param {Object} octokit Octokit instance.
 * @param {number} prNumber Pull request number.
 * @param {string} owner Repository owner.
 * @param {string} repo Repository name.
 * @param {string[]} labels Labels to add.
 * @returns {Promise<void>} Promise.
 */
const addLabel = async (octokit, prNumber, owner, repo, labels) => {
  await octokit.rest.issues.addLabels({
    owner,
    repo,
    issue_number: prNumber,
    labels,
  });
};

/**
 * Remove label from the pull request.
 *
 * @param {Object} octokit Octokit instance.
 * @param {number} prNumber Pull request number.
 * @param {string} owner Repository owner.
 * @param {string} repo Repository name.
 * @param {string} label Label to add or remove.
 * @returns {Promise<void>} Promise.
 */
const removeLabel = async (octokit, prNumber, owner, repo, label) => {
  await octokit.rest.issues.removeLabel({
    owner,
    repo,
    issue_number: prNumber,
    name: label,
  });
};

/**
 * Adds or removes a label from the pull request.
 *
 * @param {Object} octokit Octokit instance.
 * @param {number} prNumber Pull request number.
 * @param {string} owner Repository owner.
 * @param {string} repo Repository name.
 * @param {string} label Label to add or remove.
 * @param {boolean} add Whether to add or remove the label.
 * @returns {Promise<void>} Promise.
 */
const addRemoveLabel = async (octokit, prNumber, owner, repo, label, add) => {
  const res = await octokit.rest.pulls.get({
    owner,
    repo,
    pull_number: prNumber,
  });
  if (add) {
    if (!res.data.labels.find((l) => l.name === label)) {
      await addLabel(octokit, prNumber, owner, repo, [label]);
    }
  } else {
    if (res.data.labels.find((l) => l.name === label)) {
      await removeLabel(octokit, prNumber, owner, repo, label);
    }
  }
};

/**
 * Retrieve webAim contrast color check link.
 *
 * @param {string} color1 First color.
 * @param {string} color2 Second color.
 * @returns {string} WebAim contrast color check link.
 */
const getWebAimLink = (color1, color2) => {
  return `https://webaim.org/resources/contrastchecker/?fcolor=${color1}&bcolor=${color2}`;
};

/**
 * Retrieves the theme GRS url.
 *
 * @param {Object} colors The theme colors.
 * @returns {string} GRS theme url.
 */
const getGRSLink = (colors) => {
  const url = `https://github-readme-stats.vercel.app/api?username=anuraghazra`;
  const colorString = Object.keys(colors)
    .map((colorKey) => `${colorKey}=${colors[colorKey]}`)
    .join("&");

  return `${url}&${colorString}&show_icons=true`;
};

/**
 * Retrieve javascript object from json string.
 *
 * @description Wraps the Hjson parse function to fix several known json syntax errors.
 *
 * @param {string} json The json to parse.
 * @returns {Object} Object parsed from the json.
 */
const parseJSON = (json) => {
  try {
    const parsedJson = Hjson.parse(json);
    if (typeof parsedJson === "object") {
      return parsedJson;
    } else {
      throw new IncorrectJsonFormatError(
        "PR diff is not a valid theme JSON object.",
      );
    }
  } catch (error) {
    // Resolve eslint no-unused-vars
    error;

    // Remove trailing commas (if any).
    let parsedJson = json.replace(/(,\s*})/g, "}");

    // Remove JS comments (if any).
    parsedJson = parsedJson.replace(/\/\/[A-z\s]*\s/g, "");

    // Fix incorrect open bracket (if any).
    const splitJson = parsedJson
      .split(/([\s\r\s]*}[\s\r\s]*,[\s\r\s]*)(?=[\w"-]+:)/)
      .filter((x) => typeof x !== "string" || !!x.trim()); // Split json into array of strings and objects.
    if (splitJson[0].replace(/\s+/g, "") === "},") {
      splitJson[0] = "},";
      if (/\s*}\s*,?\s*$/.test(splitJson[1])) {
        splitJson.shift();
      } else {
        splitJson.push(splitJson.shift());
      }
      parsedJson = splitJson.join("");
    }

    // Try to parse the fixed json.
    try {
      return Hjson.parse(parsedJson);
    } catch (error) {
      throw new IncorrectJsonFormatError(
        `Theme JSON file could not be parsed: ${error.message}`,
      );
    }
  }
};

/**
 * Check whether the theme name is still available.
 * @param {string} name Theme name.
 * @returns {boolean} Whether the theme name is available.
 */
const themeNameAlreadyExists = (name) => {
  return themes[name] !== undefined;
};

const DRY_RUN = process.env.DRY_RUN === "true" || false;

/**
 * Main function.
 *
 * @returns {Promise<void>} Promise.
 */
export const run = async () => {
  try {
    debug("Retrieve action information from context...");
    debug(`Context: ${inspect(github.context)}`);
    let commentBody = `
      \r# ${COMMENT_TITLE}
      \r${THEME_CONTRIB_GUIDELINES}
    `;
    const ccc = new ColorContrastChecker();
    OCTOKIT = github.getOctokit(getGithubToken());
    PULL_REQUEST_ID = getPrNumber();
    const { owner, repo } = getRepoInfo(github.context);
    OWNER = owner;
    REPO = repo;
    const commenter = getCommenter();
    PULL_REQUEST_ID = getPrNumber();
    debug(`Owner: ${OWNER}`);
    debug(`Repo: ${REPO}`);
    debug(`Commenter: ${commenter}`);

    // Retrieve the PR diff and preview-theme comment.
    debug("Retrieve PR diff...");
    const res = await OCTOKIT.rest.pulls.get({
      owner: OWNER,
      repo: REPO,
      pull_number: PULL_REQUEST_ID,
      mediaType: {
        format: "diff",
      },
    });
    debug("Retrieve preview-theme comment...");
    const comment = await findComment(
      OCTOKIT,
      PULL_REQUEST_ID,
      OWNER,
      REPO,
      commenter,
    );

    // Retrieve theme changes from the PR diff.
    debug("Retrieve themes...");
    const diff = parse(res.data);

    // Retrieve all theme changes from the PR diff and convert to JSON.
    debug("Retrieve theme changes...");
    const content = diff
      .find((file) => file.to === "themes/index.js")
      .chunks.map((chunk) =>
        chunk.changes
          .filter((c) => c.type === "add")
          .map((c) => c.content.replace("+", ""))
          .join(""),
      )
      .join("");
    const themeObject = parseJSON(content);
    if (
      Object.keys(themeObject).every(
        (key) => typeof themeObject[key] !== "object",
      )
    ) {
      throw new Error("PR diff is not a valid theme JSON object.");
    }

    // Loop through themes and create theme preview body.
    debug("Create theme preview body...");
    const themeValid = Object.fromEntries(
      Object.keys(themeObject).map((name) => [name, true]),
    );
    let previewBody = "";
    for (const theme in themeObject) {
      debug(`Create theme preview for ${theme}...`);
      const themeName = theme;
      const colors = themeObject[theme];
      const warnings = [];
      const errors = [];

      // Check if the theme name is valid.
      debug("Theme preview body: Check if the theme name is valid...");
      if (themeNameAlreadyExists(themeName)) {
        warnings.push("Theme name already taken");
        themeValid[theme] = false;
      }
      if (themeName !== snakeCase(themeName)) {
        warnings.push("Theme name isn't in snake_case");
        themeValid[theme] = false;
      }

      // Check if the theme colors are valid.
      debug("Theme preview body: Check if the theme colors are valid...");
      let invalidColors = false;
      if (colors) {
        const missingKeys = REQUIRED_COLOR_PROPS.filter(
          (x) => !Object.keys(colors).includes(x),
        );
        const extraKeys = Object.keys(colors).filter(
          (x) => !ACCEPTED_COLOR_PROPS.includes(x),
        );
        if (missingKeys.length > 0 || extraKeys.length > 0) {
          for (const missingKey of missingKeys) {
            errors.push(`Theme color properties \`${missingKey}\` are missing`);
          }

          for (const extraKey of extraKeys) {
            warnings.push(
              `Theme color properties \`${extraKey}\` is not supported`,
            );
          }
          invalidColors = true;
        } else {
          for (const [colorKey, colorValue] of Object.entries(colors)) {
            if (colorValue[0] === "#") {
              errors.push(
                `Theme color property \`${colorKey}\` should not start with '#'`,
              );
              invalidColors = true;
            } else if (colorValue.length > COLOR_PROPS[colorKey]) {
              errors.push(
                `Theme color property \`${colorKey}\` can not be longer than \`${COLOR_PROPS[colorKey]}\` characters`,
              );
              invalidColors = true;
            } else if (
              !(colorKey === "bg_color" && colorValue.split(",").length > 1
                ? isValidGradient(colorValue.split(","))
                : isValidHexColor(colorValue))
            ) {
              errors.push(
                `Theme color property \`${colorKey}\` is not a valid hex color: <code>${colorValue}</code>`,
              );
              invalidColors = true;
            }
          }
        }
      } else {
        warnings.push("Theme colors are missing");
        invalidColors = true;
      }
      if (invalidColors) {
        themeValid[theme] = false;
        previewBody += `
          \r### ${
            themeName.charAt(0).toUpperCase() + themeName.slice(1)
          } theme preview
          
          \r${warnings.map((warning) => `- :warning: ${warning}.\n`).join("")}
          \r${errors.map((error) => `- :x: ${error}.\n`).join("")}

          \r>:x: Cannot create theme preview.
        `;
        continue;
      }

      // Check color contrast.
      debug("Theme preview body: Check color contrast...");
      const titleColor = colors.title_color;
      const iconColor = colors.icon_color;
      const textColor = colors.text_color;
      const bgColor = colors.bg_color;
      const borderColor = colors.border_color;
      const url = getGRSLink(colors);
      const colorPairs = {
        title_color: [titleColor, bgColor],
        icon_color: [iconColor, bgColor],
        text_color: [textColor, bgColor],
      };
      Object.keys(colorPairs).forEach((item) => {
        let color1 = colorPairs[item][0];
        let color2 = colorPairs[item][1];
        const isGradientColor = color2.split(",").length > 1;
        if (isGradientColor) {
          return;
        }
        color1 = color1.length === 4 ? color1.slice(0, 3) : color1.slice(0, 6);
        color2 = color2.length === 4 ? color2.slice(0, 3) : color2.slice(0, 6);
        if (!ccc.isLevelAA(`#${color1}`, `#${color2}`)) {
          const permalink = getWebAimLink(color1, color2);
          warnings.push(
            `\`${item}\` does not pass [AA contrast ratio](${permalink})`,
          );
          themeValid[theme] = false;
        }
      });

      // Create theme preview body.
      debug("Theme preview body: Create theme preview body...");
      previewBody += `
        \r### ${
          themeName.charAt(0).toUpperCase() + themeName.slice(1)
        } theme preview
        
        \r${warnings.map((warning) => `- :warning: ${warning}.\n`).join("")}

        \ntitle_color: <code>#${titleColor}</code> | icon_color: <code>#${iconColor}</code> | text_color: <code>#${textColor}</code> | bg_color: <code>#${bgColor}</code>${
          borderColor ? ` | border_color: <code>#${borderColor}</code>` : ""
        }

        \r[Preview Link](${url})

        \r[![](${url})](${url})
      `;
    }

    // Create comment body.
    debug("Create comment body...");
    commentBody += `
      \r${
        Object.values(themeValid).every((value) => value)
          ? THEME_PR_SUCCESS_TEXT
          : THEME_PR_FAIL_TEXT
      }
      \r## Test results
      \r${Object.entries(themeValid)
        .map(
          ([key, value]) => `- ${value ? ":heavy_check_mark:" : ":x:"} ${key}`,
        )
        .join("\r")}

      \r${
        Object.values(themeValid).every((value) => value)
          ? "**Result:** :heavy_check_mark: All themes are valid."
          : "**Result:** :x: Some themes are invalid.\n\n" + FAIL_TEXT
      }
      
      \r## Details
      \r${previewBody}
    `;

    // Create or update theme-preview comment.
    debug("Create or update theme-preview comment...");
    let comment_url;
    if (DRY_RUN) {
      info(`DRY_RUN: Comment body: ${commentBody}`);
      comment_url = "";
    } else {
      comment_url = await upsertComment(
        OCTOKIT,
        PULL_REQUEST_ID,
        REPO,
        OWNER,
        comment?.id,
        commentBody,
      );
    }

    // Change review state and add/remove `invalid` label based on theme PR validity.
    debug(
      "Change review state and add/remove `invalid` label based on whether all themes passed...",
    );
    const themesValid = Object.values(themeValid).every((value) => value);
    const reviewState = themesValid ? "APPROVE" : "REQUEST_CHANGES";
    const reviewReason = themesValid
      ? undefined
      : INVALID_REVIEW_COMMENT(comment_url);
    if (DRY_RUN) {
      info(`DRY_RUN: Review state: ${reviewState}`);
      info(`DRY_RUN: Review reason: ${reviewReason}`);
    } else {
      await addReview(
        OCTOKIT,
        PULL_REQUEST_ID,
        OWNER,
        REPO,
        reviewState,
        reviewReason,
      );
      await addRemoveLabel(
        OCTOKIT,
        PULL_REQUEST_ID,
        OWNER,
        REPO,
        "invalid",
        !themesValid,
      );
    }
  } catch (error) {
    debug("Set review state to `REQUEST_CHANGES` and add `invalid` label...");
    if (DRY_RUN) {
      info(`DRY_RUN: Review state: REQUEST_CHANGES`);
      info(`DRY_RUN: Review reason: ${error.message}`);
    } else {
      await addReview(
        OCTOKIT,
        PULL_REQUEST_ID,
        OWNER,
        REPO,
        "REQUEST_CHANGES",
        "**Something went wrong in the theme preview action:** `" +
          error.message +
          "`",
      );
      await addRemoveLabel(
        OCTOKIT,
        PULL_REQUEST_ID,
        OWNER,
        REPO,
        "invalid",
        true,
      );
    }
    setFailed(error.message);
  }
};

run();


================================================
FILE: scripts/push-theme-readme.sh
================================================
#!/bin/bash
set -x
set -e

export BRANCH_NAME=updated-theme-readme
git --version
git config --global user.email "no-reply@githubreadmestats.com"
git config --global user.name "GitHub Readme Stats Bot"
git config --global --add safe.directory ${GITHUB_WORKSPACE}
git branch -d $BRANCH_NAME || true
git checkout -b $BRANCH_NAME
git add --all
git commit --no-verify --message "docs(theme): auto update theme readme"
git remote add origin-$BRANCH_NAME https://${PERSONAL_TOKEN}@github.com/${GH_REPO}.git
git push --force --quiet --set-upstream origin-$BRANCH_NAME $BRANCH_NAME


================================================
FILE: src/calculateRank.js
================================================
/**
 * Calculates the exponential cdf.
 *
 * @param {number} x The value.
 * @returns {number} The exponential cdf.
 */
function exponential_cdf(x) {
  return 1 - 2 ** -x;
}

/**
 * Calculates the log normal cdf.
 *
 * @param {number} x The value.
 * @returns {number} The log normal cdf.
 */
function log_normal_cdf(x) {
  // approximation
  return x / (1 + x);
}

/**
 * Calculates the users rank.
 *
 * @param {object} params Parameters on which the user's rank depends.
 * @param {boolean} params.all_commits Whether `include_all_commits` was used.
 * @param {number} params.commits Number of commits.
 * @param {number} params.prs The number of pull requests.
 * @param {number} params.issues The number of issues.
 * @param {number} params.reviews The number of reviews.
 * @param {number} params.repos Total number of repos.
 * @param {number} params.stars The number of stars.
 * @param {number} params.followers The number of followers.
 * @returns {{ level: string, percentile: number }} The users rank.
 */
function calculateRank({
  all_commits,
  commits,
  prs,
  issues,
  reviews,
  // eslint-disable-next-line no-unused-vars
  repos, // unused
  stars,
  followers,
}) {
  const COMMITS_MEDIAN = all_commits ? 1000 : 250,
    COMMITS_WEIGHT = 2;
  const PRS_MEDIAN = 50,
    PRS_WEIGHT = 3;
  const ISSUES_MEDIAN = 25,
    ISSUES_WEIGHT = 1;
  const REVIEWS_MEDIAN = 2,
    REVIEWS_WEIGHT = 1;
  const STARS_MEDIAN = 50,
    STARS_WEIGHT = 4;
  const FOLLOWERS_MEDIAN = 10,
    FOLLOWERS_WEIGHT = 1;

  const TOTAL_WEIGHT =
    COMMITS_WEIGHT +
    PRS_WEIGHT +
    ISSUES_WEIGHT +
    REVIEWS_WEIGHT +
    STARS_WEIGHT +
    FOLLOWERS_WEIGHT;

  const THRESHOLDS = [1, 12.5, 25, 37.5, 50, 62.5, 75, 87.5, 100];
  const LEVELS = ["S", "A+", "A", "A-", "B+", "B", "B-", "C+", "C"];

  const rank =
    1 -
    (COMMITS_WEIGHT * exponential_cdf(commits / COMMITS_MEDIAN) +
      PRS_WEIGHT * exponential_cdf(prs / PRS_MEDIAN) +
      ISSUES_WEIGHT * exponential_cdf(issues / ISSUES_MEDIAN) +
      REVIEWS_WEIGHT * exponential_cdf(reviews / REVIEWS_MEDIAN) +
      STARS_WEIGHT * log_normal_cdf(stars / STARS_MEDIAN) +
      FOLLOWERS_WEIGHT * log_normal_cdf(followers / FOLLOWERS_MEDIAN)) /
      TOTAL_WEIGHT;

  const level = LEVELS[THRESHOLDS.findIndex((t) => rank * 100 <= t)];

  return { level, percentile: rank * 100 };
}

export { calculateRank };
export default calculateRank;


================================================
FILE: src/cards/gist.js
================================================
// @ts-check

import {
  measureText,
  flexLayout,
  iconWithLabel,
  createLanguageNode,
} from "../common/render.js";
import Card from "../common/Card.js";
import { getCardColors } from "../common/color.js";
import { kFormatter, wrapTextMultiline } from "../common/fmt.js";
import { encodeHTML } from "../common/html.js";
import { icons } from "../common/icons.js";
import { parseEmojis } from "../common/ops.js";

/** Import language colors.
 *
 * @description Here we use the workaround found in
 * https://stackoverflow.com/questions/66726365/how-should-i-import-json-in-node
 * since vercel is using v16.14.0 which does not yet support json imports without the
 * --experimental-json-modules flag.
 */
import { createRequire } from "module";
const require = createRequire(import.meta.url);
const languageColors = require("../common/languageColors.json"); // now works

const ICON_SIZE = 16;
const CARD_DEFAULT_WIDTH = 400;
const HEADER_MAX_LENGTH = 35;

/**
 * @typedef {import('./types').GistCardOptions} GistCardOptions Gist card options.
 * @typedef {import('../fetchers/types').GistData} GistData Gist data.
 */

/**
 * Render gist card.
 *
 * @param {GistData} gistData Gist data.
 * @param {Partial<GistCardOptions>} options Gist card options.
 * @returns {string} Gist card.
 */
const renderGistCard = (gistData, options = {}) => {
  const { name, nameWithOwner, description, language, starsCount, forksCount } =
    gistData;
  const {
    title_color,
    icon_color,
    text_color,
    bg_color,
    theme,
    border_radius,
    border_color,
    show_owner = false,
    hide_border = false,
  } = options;

  // returns theme based colors with proper overrides and defaults
  const { titleColor, textColor, iconColor, bgColor, borderColor } =
    getCardColors({
      title_color,
      icon_color,
      text_color,
      bg_color,
      border_color,
      theme,
    });

  const lineWidth = 59;
  const linesLimit = 10;
  const desc = parseEmojis(description || "No description provided");
  const multiLineDescription = wrapTextMultiline(desc, lineWidth, linesLimit);
  const descriptionLines = multiLineDescription.length;
  const descriptionSvg = multiLineDescription
    .map((line) => `<tspan dy="1.2em" x="25">${encodeHTML(line)}</tspan>`)
    .join("");

  const lineHeight = descriptionLines > 3 ? 12 : 10;
  const height =
    (descriptionLines > 1 ? 120 : 110) + descriptionLines * lineHeight;

  const totalStars = kFormatter(starsCount);
  const totalForks = kFormatter(forksCount);
  const svgStars = iconWithLabel(
    icons.star,
    totalStars,
    "starsCount",
    ICON_SIZE,
  );
  const svgForks = iconWithLabel(
    icons.fork,
    totalForks,
    "forksCount",
    ICON_SIZE,
  );

  const languageName = language || "Unspecified";
  // @ts-ignore
  const languageColor = languageColors[languageName] || "#858585";

  const svgLanguage = createLanguageNode(languageName, languageColor);

  const starAndForkCount = flexLayout({
    items: [svgLanguage, svgStars, svgForks],
    sizes: [
      measureText(languageName, 12),
      ICON_SIZE + measureText(`${totalStars}`, 12),
      ICON_SIZE + measureText(`${totalForks}`, 12),
    ],
    gap: 25,
  }).join("");

  const header = show_owner ? nameWithOwner : name;

  const card = new Card({
    defaultTitle:
      header.length > HEADER_MAX_LENGTH
        ? `${header.slice(0, HEADER_MAX_LENGTH)}...`
        : header,
    titlePrefixIcon: icons.gist,
    width: CARD_DEFAULT_WIDTH,
    height,
    border_radius,
    colors: {
      titleColor,
      textColor,
      iconColor,
      bgColor,
      borderColor,
    },
  });

  card.setCSS(`
    .description { font: 400 13px 'Segoe UI', Ubuntu, Sans-Serif; fill: ${textColor} }
    .gray { font: 400 12px 'Segoe UI', Ubuntu, Sans-Serif; fill: ${textColor} }
    .icon { fill: ${iconColor} }
  `);
  card.setHideBorder(hide_border);

  return card.render(`
    <text class="description" x="25" y="-5">
        ${descriptionSvg}
    </text>

    <g transform="translate(30, ${height - 75})">
        ${starAndForkCount}
    </g>
  `);
};

export { renderGistCard, HEADER_MAX_LENGTH };
export default renderGistCard;


================================================
FILE: src/cards/index.js
================================================
export { renderRepoCard } from "./repo.js";
export { renderStatsCard } from "./stats.js";
export { renderTopLanguages } from "./top-languages.js";
export { renderWakatimeCard } from "./wakatime.js";


================================================
FILE: src/cards/repo.js
================================================
// @ts-check

import { Card } from "../common/Card.js";
import { getCardColors } from "../common/color.js";
import { kFormatter, wrapTextMultiline } from "../common/fmt.js";
import { encodeHTML } from "../common/html.js";
import { I18n } from "../common/I18n.js";
import { icons } from "../common/icons.js";
import { clampValue, parseEmojis } from "../common/ops.js";
import {
  flexLayout,
  measureText,
  iconWithLabel,
  createLanguageNode,
} from "../common/render.js";
import { repoCardLocales } from "../translations.js";

const ICON_SIZE = 16;
const DESCRIPTION_LINE_WIDTH = 59;
const DESCRIPTION_MAX_LINES = 3;

/**
 * Retrieves the repository description and wraps it to fit the card width.
 *
 * @param {string} label The repository description.
 * @param {string} textColor The color of the text.
 * @returns {string} Wrapped repo description SVG object.
 */
const getBadgeSVG = (label, textColor) => `
  <g data-testid="badge" class="badge" transform="translate(320, -18)">
    <rect stroke="${textColor}" stroke-width="1" width="70" height="20" x="-12" y="-14" ry="10" rx="10"></rect>
    <text
      x="23" y="-5"
      alignment-baseline="central"
      dominant-baseline="central"
      text-anchor="middle"
      fill="${textColor}"
    >
      ${label}
    </text>
  </g>
`;

/**
 * @typedef {import("../fetchers/types").RepositoryData} RepositoryData Repository data.
 * @typedef {import("./types").RepoCardOptions} RepoCardOptions Repo card options.
 */

/**
 * Renders repository card details.
 *
 * @param {RepositoryData} repo Repository data.
 * @param {Partial<RepoCardOptions>} options Card options.
 * @returns {string} Repository card SVG object.
 */
const renderRepoCard = (repo, options = {}) => {
  const {
    name,
    nameWithOwner,
    description,
    primaryLanguage,
    isArchived,
    isTemplate,
    starCount,
    forkCount,
  } = repo;
  const {
    hide_border = false,
    title_color,
    icon_color,
    text_color,
    bg_color,
    show_owner = false,
    theme = "default_repocard",
    border_radius,
    border_color,
    locale,
    description_lines_count,
  } = options;

  const lineHeight = 10;
  const header = show_owner ? nameWithOwner : name;
  const langName = (primaryLanguage && primaryLanguage.name) || "Unspecified";
  const langColor = (primaryLanguage && primaryLanguage.color) || "#333";
  const descriptionMaxLines = description_lines_count
    ? clampValue(description_lines_count, 1, DESCRIPTION_MAX_LINES)
    : DESCRIPTION_MAX_LINES;

  const desc = parseEmojis(description || "No description provided");
  const multiLineDescription = wrapTextMultiline(
    desc,
    DESCRIPTION_LINE_WIDTH,
    descriptionMaxLines,
  );
  const descriptionLinesCount = description_lines_count
    ? clampValue(description_lines_count, 1, DESCRIPTION_MAX_LINES)
    : multiLineDescription.length;

  const descriptionSvg = multiLineDescription
    .map((line) => `<tspan dy="1.2em" x="25">${encodeHTML(line)}</tspan>`)
    .join("");

  const height =
    (descriptionLinesCount > 1 ? 120 : 110) +
    descriptionLinesCount * lineHeight;

  const i18n = new I18n({
    locale,
    translations: repoCardLocales,
  });

  // returns theme based colors with proper overrides and defaults
  const colors = getCardColors({
    title_color,
    icon_color,
    text_color,
    bg_color,
    border_color,
    theme,
  });

  const svgLanguage = primaryLanguage
    ? createLanguageNode(langName, langColor)
    : "";

  const totalStars = kFormatter(starCount);
  const totalForks = kFormatter(forkCount);
  const svgStars = iconWithLabel(
    icons.star,
    totalStars,
    "stargazers",
    ICON_SIZE,
  );
  const svgForks = iconWithLabel(
    icons.fork,
    totalForks,
    "forkcount",
    ICON_SIZE,
  );

  const starAndForkCount = flexLayout({
    items: [svgLanguage, svgStars, svgForks],
    sizes: [
      measureText(langName, 12),
      ICON_SIZE + measureText(`${totalStars}`, 12),
      ICON_SIZE + measureText(`${totalForks}`, 12),
    ],
    gap: 25,
  }).join("");

  const card = new Card({
    defaultTitle: header.length > 35 ? `${header.slice(0, 35)}...` : header,
    titlePrefixIcon: icons.contribs,
    width: 400,
    height,
    border_radius,
    colors,
  });

  card.disableAnimations();
  card.setHideBorder(hide_border);
  card.setHideTitle(false);
  card.setCSS(`
    .description { font: 400 13px 'Segoe UI', Ubuntu, Sans-Serif; fill: ${colors.textColor} }
    .gray { font: 400 12px 'Segoe UI', Ubuntu, Sans-Serif; fill: ${colors.textColor} }
    .icon { fill: ${colors.iconColor} }
    .badge { font: 600 11px 'Segoe UI', Ubuntu, Sans-Serif; }
    .badge rect { opacity: 0.2 }
  `);

  return card.render(`
    ${
      isTemplate
        ? // @ts-ignore
          getBadgeSVG(i18n.t("repocard.template"), colors.textColor)
        : isArchived
          ? // @ts-ignore
            getBadgeSVG(i18n.t("repocard.archived"), colors.textColor)
          : ""
    }

    <text class="description" x="25" y="-5">
      ${descriptionSvg}
    </text>

    <g transform="translate(30, ${height - 75})">
      ${starAndForkCount}
    </g>
  `);
};

export { renderRepoCard };
export default renderRepoCard;


================================================
FILE: src/cards/stats.js
================================================
// @ts-check

import { Card } from "../common/Card.js";
import { getCardColors } from "../common/color.js";
import { CustomError } from "../common/error.js";
import { kFormatter } from "../common/fmt.js";
import { I18n } from "../common/I18n.js";
import { icons, rankIcon } from "../common/icons.js";
import { clampValue } from "../common/ops.js";
import { flexLayout, measureText } from "../common/render.js";
import { statCardLocales, wakatimeCardLocales } from "../translations.js";

const CARD_MIN_WIDTH = 287;
const CARD_DEFAULT_WIDTH = 287;
const RANK_CARD_MIN_WIDTH = 420;
const RANK_CARD_DEFAULT_WIDTH = 450;
const RANK_ONLY_CARD_MIN_WIDTH = 290;
const RANK_ONLY_CARD_DEFAULT_WIDTH = 290;

/**
 * Long locales that need more space for text. Keep sorted alphabetically.
 *
 * @type {(keyof typeof wakatimeCardLocales["wakatimecard.title"])[]}
 */
const LONG_LOCALES = [
  "az",
  "bg",
  "cs",
  "de",
  "el",
  "es",
  "fil",
  "fi",
  "fr",
  "hu",
  "id",
  "ja",
  "ml",
  "my",
  "nl",
  "pl",
  "pt-br",
  "pt-pt",
  "ru",
  "sr",
  "sr-latn",
  "sw",
  "ta",
  "uk-ua",
  "uz",
  "zh-tw",
];

/**
 * Create a stats card text item.
 *
 * @param {object} params Object that contains the createTextNode parameters.
 * @param {string} params.icon The icon to display.
 * @param {string} params.label The label to display.
 * @param {number} params.value The value to display.
 * @param {string} params.id The id of the stat.
 * @param {string=} params.unitSymbol The unit symbol of the stat.
 * @param {number} params.index The index of the stat.
 * @param {boolean} params.showIcons Whether to show icons.
 * @param {number} params.shiftValuePos Number of pixels the value has to be shifted to the right.
 * @param {boolean} params.bold Whether to bold the label.
 * @param {string} params.numberFormat The format of numbers on card.
 * @param {number=} params.numberPrecision The precision of numbers on card.
 * @returns {string} The stats card text item SVG object.
 */
const createTextNode = ({
  icon,
  label,
  value,
  id,
  unitSymbol,
  index,
  showIcons,
  shiftValuePos,
  bold,
  numberFormat,
  numberPrecision,
}) => {
  const precision =
    typeof numberPrecision === "number" && !isNaN(numberPrecision)
      ? clampValue(numberPrecision, 0, 2)
      : undefined;
  const kValue =
    numberFormat.toLowerCase() === "long" || id === "prs_merged_percentage"
      ? value
      : kFormatter(value, precision);
  const staggerDelay = (index + 3) * 150;

  const labelOffset = showIcons ? `x="25"` : "";
  const iconSvg = showIcons
    ? `
    <svg data-testid="icon" class="icon" viewBox="0 0 16 16" version="1.1" width="16" height="16">
      ${icon}
    </svg>
  `
    : "";
  return `
    <g class="stagger" style="animation-delay: ${staggerDelay}ms" transform="translate(25, 0)">
      ${iconSvg}
      <text class="stat ${
        bold ? " bold" : "not_bold"
      }" ${labelOffset} y="12.5">${label}:</text>
      <text
        class="stat ${bold ? " bold" : "not_bold"}"
        x="${(showIcons ? 140 : 120) + shiftValuePos}"
        y="12.5"
        data-testid="${id}"
      >${kValue}${unitSymbol ? ` ${unitSymbol}` : ""}</text>
    </g>
  `;
};

/**
 * Calculates progress along the boundary of the circle, i.e. its circumference.
 *
 * @param {number} value The rank value to calculate progress for.
 * @returns {number} Progress value.
 */
const calculateCircleProgress = (value) => {
  const radius = 40;
  const c = Math.PI * (radius * 2);

  if (value < 0) {
    value = 0;
  }
  if (value > 100) {
    value = 100;
  }

  return ((100 - value) / 100) * c;
};

/**
 * Retrieves the animation to display progress along the circumference of circle
 * from the beginning to the given value in a clockwise direction.
 *
 * @param {{progress: number}} progress The progress value to animate to.
 * @returns {string} Progress animation css.
 */
const getProgressAnimation = ({ progress }) => {
  return `
    @keyframes rankAnimation {
      from {
        stroke-dashoffset: ${calculateCircleProgress(0)};
      }
      to {
        stroke-dashoffset: ${calculateCircleProgress(progress)};
      }
    }
  `;
};

/**
 * Retrieves CSS styles for a card.
 *
 * @param {Object} colors The colors to use for the card.
 * @param {string} colors.titleColor The title color.
 * @param {string} colors.textColor The text color.
 * @param {string} colors.iconColor The icon color.
 * @param {string} colors.ringColor The ring color.
 * @param {boolean} colors.show_icons Whether to show icons.
 * @param {number} colors.progress The progress value to animate to.
 * @returns {string} Card CSS styles.
 */
const getStyles = ({
  // eslint-disable-next-line no-unused-vars
  titleColor,
  textColor,
  iconColor,
  ringColor,
  show_icons,
  progress,
}) => {
  return `
    .stat {
      font: 600 14px 'Segoe UI', Ubuntu, "Helvetica Neue", Sans-Serif; fill: ${textColor};
    }
    @supports(-moz-appearance: auto) {
      /* Selector detects Firefox */
      .stat { font-size:12px; }
    }
    .stagger {
      opacity: 0;
      animation: fadeInAnimation 0.3s ease-in-out forwards;
    }
    .rank-text {
      font: 800 24px 'Segoe UI', Ubuntu, Sans-Serif; fill: ${textColor};
      animation: scaleInAnimation 0.3s ease-in-out forwards;
    }
    .rank-percentile-header {
      font-size: 14px;
    }
    .rank-percentile-text {
      font-size: 16px;
    }
    
    .not_bold { font-weight: 400 }
    .bold { font-weight: 700 }
    .icon {
      fill: ${iconColor};
      display: ${show_icons ? "block" : "none"};
    }

    .rank-circle-rim {
      stroke: ${ringColor};
      fill: none;
      stroke-width: 6;
      opacity: 0.2;
    }
    .rank-circle {
      stroke: ${ringColor};
      stroke-dasharray: 250;
      fill: none;
      stroke-width: 6;
      stroke-linecap: round;
      opacity: 0.8;
      transform-origin: -10px 8px;
      transform: rotate(-90deg);
      animation: rankAnimation 1s forwards ease-in-out;
    }
    ${process.env.NODE_ENV === "test" ? "" : getProgressAnimation({ progress })}
  `;
};

/**
 * Return the label for commits according to the selected options
 *
 * @param {boolean} include_all_commits Option to include all years
 * @param {number|undefined} commits_year Option to include only selected year
 * @param {I18n} i18n The I18n instance.
 * @returns {string} The label corresponding to the options.
 */
const getTotalCommitsYearLabel = (include_all_commits, commits_year, i18n) =>
  include_all_commits
    ? ""
    : commits_year
      ? ` (${commits_year})`
      : ` (${i18n.t("wakatimecard.lastyear")})`;

/**
 * @typedef {import('../fetchers/types').StatsData} StatsData
 * @typedef {import('./types').StatCardOptions} StatCardOptions
 */

/**
 * Renders the stats card.
 *
 * @param {StatsData} stats The stats data.
 * @param {Partial<StatCardOptions>} options The card options.
 * @returns {string} The stats card SVG object.
 */
const renderStatsCard = (stats, options = {}) => {
  const {
    name,
    totalStars,
    totalCommits,
    totalIssues,
    totalPRs,
    totalPRsMerged,
    mergedPRsPercentage,
    totalReviews,
    totalDiscussionsStarted,
    totalDiscussionsAnswered,
    contributedTo,
    rank,
  } = stats;
  const {
    hide = [],
    show_icons = false,
    hide_title = false,
    hide_border = false,
    card_width,
    hide_rank = false,
    include_all_commits = false,
    commits_year,
    line_height = 25,
    title_color,
    ring_color,
    icon_color,
    text_color,
    text_bold = true,
    bg_color,
    theme = "default",
    custom_title,
    border_radius,
    border_color,
    number_format = "short",
    number_precision,
    locale,
    disable_animations = false,
    rank_icon = "default",
    show = [],
  } = options;

  const lheight = parseInt(String(line_height), 10);

  // returns theme based colors with proper overrides and defaults
  const { titleColor, iconColor, textColor, bgColor, borderColor, ringColor } =
    getCardColors({
      title_color,
      text_color,
      icon_color,
      bg_color,
      border_color,
      ring_color,
      theme,
    });

  const apostrophe = /s$/i.test(name.trim()) ? "" : "s";
  const i18n = new I18n({
    locale,
    translations: {
      ...statCardLocales({ name, apostrophe }),
      ...wakatimeCardLocales,
    },
  });

  // Meta data for creating text nodes with createTextNode function
  const STATS = {};

  STATS.stars = {
    icon: icons.star,
    label: i18n.t("statcard.totalstars"),
    value: totalStars,
    id: "stars",
  };
  STATS.commits = {
    icon: icons.commits,
    label: `${i18n.t("statcard.commits")}${getTotalCommitsYearLabel(
      include_all_commits,
      commits_year,
      i18n,
    )}`,
    value: totalCommits,
    id: "commits",
  };
  STATS.prs = {
    icon: icons.prs,
    label: i18n.t("statcard.prs"),
    value: totalPRs,
    id: "prs",
  };

  if (show.includes("prs_merged")) {
    STATS.prs_merged = {
      icon: icons.prs_merged,
      label: i18n.t("statcard.prs-merged"),
      value: totalPRsMerged,
      id: "prs_merged",
    };
  }

  if (show.includes("prs_merged_percentage")) {
    STATS.prs_merged_percentage = {
      icon: icons.prs_merged_percentage,
      label: i18n.t("statcard.prs-merged-percentage"),
      value: mergedPRsPercentage.toFixed(
        typeof number_precision === "number" && !isNaN(number_precision)
          ? clampValue(number_precision, 0, 2)
          : 2,
      ),
      id: "prs_merged_percentage",
      unitSymbol: "%",
    };
  }

  if (show.includes("reviews")) {
    STATS.reviews = {
      icon: icons.reviews,
      label: i18n.t("statcard.reviews"),
      value: totalReviews,
      id: "reviews",
    };
  }

  STATS.issues = {
    icon: icons.issues,
    label: i18n.t("statcard.issues"),
    value: totalIssues,
    id: "issues",
  };

  if (show.includes("discussions_started")) {
    STATS.discussions_started = {
      icon: icons.discussions_started,
      label: i18n.t("statcard.discussions-started"),
      value: totalDiscussionsStarted,
      id: "discussions_started",
    };
  }
  if (show.includes("discussions_answered")) {
    STATS.discussions_answered = {
      icon: icons.discussions_answered,
      label: i18n.t("statcard.discussions-answered"),
      value: totalDiscussionsAnswered,
      id: "discussions_answered",
    };
  }

  STATS.contribs = {
    icon: icons.contribs,
    label: i18n.t("statcard.contribs"),
    value: contributedTo,
    id: "contribs",
  };

  // @ts-ignore
  const isLongLocale = locale ? LONG_LOCALES.includes(locale) : false;

  // filter out hidden stats defined by user & create the text nodes
  const statItems = Object.keys(STATS)
    .filter((key) => !hide.includes(key))
    .map((key, index) => {
      // @ts-ignore
      const stats = STATS[key];

      // create the text nodes, and pass index so that we can calculate the line spacing
      return createTextNode({
        icon: stats.icon,
        label: stats.label,
        value: stats.value,
        id: stats.id,
        unitSymbol: stats.unitSymbol,
        index,
        showIcons: show_icons,
        shiftValuePos: 79.01 + (isLongLocale ? 50 : 0),
        bold: text_bold,
        numberFormat: number_format,
        numberPrecision: number_precision,
      });
    });

  if (statItems.length === 0 && hide_rank) {
    throw new CustomError(
      "Could not render stats card.",
      "Either stats or rank are required.",
    );
  }

  // Calculate the card height depending on how many items there are
  // but if rank circle is visible clamp the minimum height to `150`
  let height = Math.max(
    45 + (statItems.length + 1) * lheight,
    hide_rank ? 0 : statItems.length ? 150 : 180,
  );

  // the lower the user's percentile the better
  const progress = 100 - rank.percentile;
  const cssStyles = getStyles({
    titleColor,
    ringColor,
    textColor,
    iconColor,
    show_icons,
    progress,
  });

  const calculateTextWidth = () => {
    return measureText(
      custom_title
        ? custom_title
        : statItems.length
          ? i18n.t("statcard.title")
          : i18n.t("statcard.ranktitle"),
    );
  };

  /*
    When hide_rank=true, the minimum card width is 270 px + the title length and padding.
    When hide_rank=false, the minimum card_width is 340 px + the icon width (if show_icons=true).
    Numbers are picked by looking at existing dimensions on production.
  */
  const iconWidth = show_icons && statItems.length ? 16 + /* padding */ 1 : 0;
  const minCardWidth =
    (hide_rank
      ? clampValue(
          50 /* padding */ + calculateTextWidth() * 2,
          CARD_MIN_WIDTH,
          Infinity,
        )
      : statItems.length
        ? RANK_CARD_MIN_WIDTH
        : RANK_ONLY_CARD_MIN_WIDTH) + iconWidth;
  const defaultCardWidth =
    (hide_rank
      ? CARD_DEFAULT_WIDTH
      : statItems.length
        ? RANK_CARD_DEFAULT_WIDTH
        : RANK_ONLY_CARD_DEFAULT_WIDTH) + iconWidth;
  let width = card_width
    ? isNaN(card_width)
      ? defaultCardWidth
      : card_width
    : defaultCardWidth;
  if (width < minCardWidth) {
    width = minCardWidth;
  }

  const card = new Card({
    customTitle: custom_title,
    defaultTitle: statItems.length
      ? i18n.t("statcard.title")
      : i18n.t("statcard.ranktitle"),
    width,
    height,
    border_radius,
    colors: {
      titleColor,
      textColor,
      iconColor,
      bgColor,
      borderColor,
    },
  });

  card.setHideBorder(hide_border);
  card.setHideTitle(hide_title);
  card.setCSS(cssStyles);

  if (disable_animations) {
    card.disableAnimations();
  }

  /**
   * Calculates the right rank circle translation values such that the rank circle
   * keeps respecting the following padding:
   *
   * width > RANK_CARD_DEFAULT_WIDTH: The default right padding of 70 px will be used.
   * width < RANK_CARD_DEFAULT_WIDTH: The left and right padding will be enlarged
   *   equally from a certain minimum at RANK_CARD_MIN_WIDTH.
   *
   * @returns {number} - Rank circle translation value.
   */
  const calculateRankXTranslation = () => {
    if (statItems.length) {
      const minXTranslation = RANK_CARD_MIN_WIDTH + iconWidth - 70;
      if (width > RANK_CARD_DEFAULT_WIDTH) {
        const xMaxExpansion = minXTranslation + (450 - minCardWidth) / 2;
        return xMaxExpansion + width - RANK_CARD_DEFAULT_WIDTH;
      } else {
        return minXTranslation + (width - minCardWidth) / 2;
      }
    } else {
      return width / 2 + 20 - 10;
    }
  };

  // Conditionally rendered elements
  const rankCircle = hide_rank
    ? ""
    : `<g data-testid="rank-circle"
          transform="translate(${calculateRankXTranslation()}, ${
            height / 2 - 50
          })">
        <circle class="rank-circle-rim" cx="-10" cy="8" r="40" />
        <circle class="rank-circle" cx="-10" cy="8" r="40" />
        <g class="rank-text">
          ${rankIcon(rank_icon, rank?.level, rank?.percentile)}
        </g>
      </g>`;

  // Accessibility Labels
  const labels = Object.keys(STATS)
    .filter((key) => !hide.includes(key))
    .map((key) => {
      // @ts-ignore
      const stats = STATS[key];
      if (key === "commits") {
        return `${i18n.t("statcard.commits")} ${getTotalCommitsYearLabel(
          include_all_commits,
          commits_year,
          i18n,
        )} : ${stats.value}`;
      }
      return `${stats.label}: ${stats.value}`;
    })
    .join(", ");

  card.setAccessibilityLabel({
    title: `${card.title}, Rank: ${rank.level}`,
    desc: labels,
  });

  return card.render(`
    ${rankCircle}
    <svg x="0" y="0">
      ${flexLayout({
        items: statItems,
        gap: lheight,
        direction: "column",
      }).join("")}
    </svg>
  `);
};

export { renderStatsCard };
export default renderStatsCard;


================================================
FILE: src/cards/top-languages.js
================================================
// @ts-check

import { Card } from "../common/Card.js";
import { getCardColors } from "../common/color.js";
import { formatBytes } from "../common/fmt.js";
import { I18n } from "../common/I18n.js";
import { chunkArray, clampValue, lowercaseTrim } from "../common/ops.js";
import {
  createProgressNode,
  flexLayout,
  measureText,
} from "../common/render.js";
import { langCardLocales } from "../translations.js";

const DEFAULT_CARD_WIDTH = 300;
const MIN_CARD_WIDTH = 280;
const DEFAULT_LANG_COLOR = "#858585";
const CARD_PADDING = 25;
const COMPACT_LAYOUT_BASE_HEIGHT = 90;
const MAXIMUM_LANGS_COUNT = 20;

const NORMAL_LAYOUT_DEFAULT_LANGS_COUNT = 5;
const COMPACT_LAYOUT_DEFAULT_LANGS_COUNT = 6;
const DONUT_LAYOUT_DEFAULT_LANGS_COUNT = 5;
const PIE_LAYOUT_DEFAULT_LANGS_COUNT = 6;
const DONUT_VERTICAL_LAYOUT_DEFAULT_LANGS_COUNT = 6;

/**
 * @typedef {import("../fetchers/types").Lang} Lang
 */

/**
 * Retrieves the programming language whose name is the longest.
 *
 * @param {Lang[]} arr Array of programming languages.
 * @returns {{ name: string, size: number, color: string }} Longest programming language object.
 */
const getLongestLang = (arr) =>
  arr.reduce(
    (savedLang, lang) =>
      lang.name.length > savedLang.name.length ? lang : savedLang,
    { name: "", size: 0, color: "" },
  );

/**
 * Convert degrees to radians.
 *
 * @param {number} angleInDegrees Angle in degrees.
 * @returns {number} Angle in radians.
 */
const degreesToRadians = (angleInDegrees) => angleInDegrees * (Math.PI / 180.0);

/**
 * Convert radians to degrees.
 *
 * @param {number} angleInRadians Angle in radians.
 * @returns {number} Angle in degrees.
 */
const radiansToDegrees = (angleInRadians) => angleInRadians / (Math.PI / 180.0);

/**
 * Convert polar coordinates to cartesian coordinates.
 *
 * @param {number} centerX Center x coordinate.
 * @param {number} centerY Center y coordinate.
 * @param {number} radius Radius of the circle.
 * @param {number} angleInDegrees Angle in degrees.
 * @returns {{x: number, y: number}} Cartesian coordinates.
 */
const polarToCartesian = (centerX, centerY, radius, angleInDegrees) => {
  const rads = degreesToRadians(angleInDegrees);
  return {
    x: centerX + radius * Math.cos(rads),
    y: centerY + radius * Math.sin(rads),
  };
};

/**
 * Convert cartesian coordinates to polar coordinates.
 *
 * @param {number} centerX Center x coordinate.
 * @param {number} centerY Center y coordinate.
 * @param {number} x Point x coordinate.
 * @param {number} y Point y coordinate.
 * @returns {{radius: number, angleInDegrees: number}} Polar coordinates.
 */
const cartesianToPolar = (centerX, centerY, x, y) => {
  const radius = Math.sqrt(Math.pow(x - centerX, 2) + Math.pow(y - centerY, 2));
  let angleInDegrees = radiansToDegrees(Math.atan2(y - c
Download .txt
gitextract_rbue6f_z/

├── .devcontainer/
│   └── devcontainer.json
├── .eslintrc.json
├── .github/
│   ├── CODEOWNERS
│   ├── FUNDING.yml
│   ├── ISSUE_TEMPLATE/
│   │   ├── bug_report.yml
│   │   ├── config.yml
│   │   └── feature_request.yml
│   ├── dependabot.yml
│   ├── labeler.yml
│   ├── stale.yml
│   └── workflows/
│       ├── codeql-analysis.yml
│       ├── deploy-prep.py
│       ├── deploy-prep.yml
│       ├── e2e-test.yml
│       ├── empty-issues-closer.yml
│       ├── generate-theme-doc.yml
│       ├── label-pr.yml
│       ├── ossf-analysis.yml
│       ├── preview-theme.yml
│       ├── prs-cache-clean.yml
│       ├── stale-theme-pr-closer.yml
│       ├── test.yml
│       ├── theme-prs-closer.yml
│       ├── top-issues-dashboard.yml
│       └── update-langs.yml
├── .gitignore
├── .husky/
│   ├── .gitignore
│   └── pre-commit
├── .nvmrc
├── .prettierignore
├── .prettierrc.json
├── .vercelignore
├── .vscode/
│   ├── extensions.json
│   └── settings.json
├── CODE_OF_CONDUCT.md
├── CONTRIBUTING.md
├── LICENSE
├── SECURITY.md
├── api/
│   ├── gist.js
│   ├── index.js
│   ├── pin.js
│   ├── status/
│   │   ├── pat-info.js
│   │   └── up.js
│   ├── top-langs.js
│   └── wakatime.js
├── codecov.yml
├── eslint.config.mjs
├── express.js
├── jest.bench.config.js
├── jest.config.js
├── jest.e2e.config.js
├── package.json
├── readme.md
├── scripts/
│   ├── close-stale-theme-prs.js
│   ├── generate-langs-json.js
│   ├── generate-theme-doc.js
│   ├── helpers.js
│   ├── preview-theme.js
│   └── push-theme-readme.sh
├── src/
│   ├── calculateRank.js
│   ├── cards/
│   │   ├── gist.js
│   │   ├── index.js
│   │   ├── repo.js
│   │   ├── stats.js
│   │   ├── top-languages.js
│   │   ├── types.d.ts
│   │   └── wakatime.js
│   ├── common/
│   │   ├── Card.js
│   │   ├── I18n.js
│   │   ├── access.js
│   │   ├── blacklist.js
│   │   ├── cache.js
│   │   ├── color.js
│   │   ├── envs.js
│   │   ├── error.js
│   │   ├── fmt.js
│   │   ├── html.js
│   │   ├── http.js
│   │   ├── icons.js
│   │   ├── index.js
│   │   ├── languageColors.json
│   │   ├── log.js
│   │   ├── ops.js
│   │   ├── render.js
│   │   └── retryer.js
│   ├── fetchers/
│   │   ├── gist.js
│   │   ├── repo.js
│   │   ├── stats.js
│   │   ├── top-languages.js
│   │   ├── types.d.ts
│   │   └── wakatime.js
│   ├── index.js
│   └── translations.js
├── tests/
│   ├── __snapshots__/
│   │   └── renderWakatimeCard.test.js.snap
│   ├── api.test.js
│   ├── bench/
│   │   ├── api.bench.js
│   │   ├── calculateRank.bench.js
│   │   ├── gist.bench.js
│   │   ├── pin.bench.js
│   │   └── utils.js
│   ├── calculateRank.test.js
│   ├── card.test.js
│   ├── color.test.js
│   ├── e2e/
│   │   └── e2e.test.js
│   ├── fetchGist.test.js
│   ├── fetchRepo.test.js
│   ├── fetchStats.test.js
│   ├── fetchTopLanguages.test.js
│   ├── fetchWakatime.test.js
│   ├── flexLayout.test.js
│   ├── fmt.test.js
│   ├── gist.test.js
│   ├── html.test.js
│   ├── i18n.test.js
│   ├── ops.test.js
│   ├── pat-info.test.js
│   ├── pin.test.js
│   ├── render.test.js
│   ├── renderGistCard.test.js
│   ├── renderRepoCard.test.js
│   ├── renderStatsCard.test.js
│   ├── renderTopLanguagesCard.test.js
│   ├── renderWakatimeCard.test.js
│   ├── retryer.test.js
│   ├── status.up.test.js
│   ├── top-langs.test.js
│   └── wakatime.test.js
├── themes/
│   ├── README.md
│   └── index.js
└── vercel.json
Download .txt
SYMBOL INDEX (123 symbols across 26 files)

FILE: api/status/pat-info.js
  constant RATE_LIMIT_SECONDS (line 14) | const RATE_LIMIT_SECONDS = 60 * 5;

FILE: api/status/up.js
  constant RATE_LIMIT_SECONDS (line 14) | const RATE_LIMIT_SECONDS = 60 * 5;

FILE: scripts/close-stale-theme-prs.js
  constant CLOSING_COMMENT (line 12) | const CLOSING_COMMENT = `
  constant REVIEWER (line 16) | const REVIEWER = "github-actions[bot]";

FILE: scripts/generate-langs-json.js
  constant LANGS_FILEPATH (line 5) | const LANGS_FILEPATH = "./src/common/languageColors.json";

FILE: scripts/generate-theme-doc.js
  constant TARGET_FILE (line 4) | const TARGET_FILE = "./themes/README.md";
  constant REPO_CARD_LINKS_FLAG (line 5) | const REPO_CARD_LINKS_FLAG = "<!-- REPO_CARD_LINKS -->";
  constant STAT_CARD_LINKS_FLAG (line 6) | const STAT_CARD_LINKS_FLAG = "<!-- STATS_CARD_LINKS -->";
  constant STAT_CARD_TABLE_FLAG (line 8) | const STAT_CARD_TABLE_FLAG = "<!-- STATS_CARD_TABLE -->";
  constant REPO_CARD_TABLE_FLAG (line 9) | const REPO_CARD_TABLE_FLAG = "<!-- REPO_CARD_TABLE -->";
  constant THEME_TEMPLATE (line 11) | const THEME_TEMPLATE = `## Available Themes

FILE: scripts/helpers.js
  constant OWNER (line 7) | const OWNER = "anuraghazra";
  constant REPO (line 8) | const REPO = "github-readme-stats";

FILE: scripts/preview-theme.js
  constant COMMENTER (line 19) | const COMMENTER = "github-actions[bot]";
  constant COMMENT_TITLE (line 21) | const COMMENT_TITLE = "Automated Theme Preview";
  constant THEME_PR_FAIL_TEXT (line 22) | const THEME_PR_FAIL_TEXT = ":x: Theme PR does not adhere to our guidelin...
  constant THEME_PR_SUCCESS_TEXT (line 23) | const THEME_PR_SUCCESS_TEXT =
  constant FAIL_TEXT (line 25) | const FAIL_TEXT = `
  constant THEME_CONTRIB_GUIDELINES (line 29) | const THEME_CONTRIB_GUIDELINES = `
  constant COLOR_PROPS (line 41) | const COLOR_PROPS = {
  constant ACCEPTED_COLOR_PROPS (line 48) | const ACCEPTED_COLOR_PROPS = Object.keys(COLOR_PROPS);
  constant REQUIRED_COLOR_PROPS (line 49) | const REQUIRED_COLOR_PROPS = ACCEPTED_COLOR_PROPS.slice(0, 4);
  class IncorrectJsonFormatError (line 63) | class IncorrectJsonFormatError extends Error {
    method constructor (line 69) | constructor(message) {
  constant DRY_RUN (line 378) | const DRY_RUN = process.env.DRY_RUN === "true" || false;

FILE: src/calculateRank.js
  function exponential_cdf (line 7) | function exponential_cdf(x) {
  function log_normal_cdf (line 17) | function log_normal_cdf(x) {
  function calculateRank (line 36) | function calculateRank({

FILE: src/cards/gist.js
  constant ICON_SIZE (line 27) | const ICON_SIZE = 16;
  constant CARD_DEFAULT_WIDTH (line 28) | const CARD_DEFAULT_WIDTH = 400;
  constant HEADER_MAX_LENGTH (line 29) | const HEADER_MAX_LENGTH = 35;

FILE: src/cards/repo.js
  constant ICON_SIZE (line 18) | const ICON_SIZE = 16;
  constant DESCRIPTION_LINE_WIDTH (line 19) | const DESCRIPTION_LINE_WIDTH = 59;
  constant DESCRIPTION_MAX_LINES (line 20) | const DESCRIPTION_MAX_LINES = 3;

FILE: src/cards/stats.js
  constant CARD_MIN_WIDTH (line 13) | const CARD_MIN_WIDTH = 287;
  constant CARD_DEFAULT_WIDTH (line 14) | const CARD_DEFAULT_WIDTH = 287;
  constant RANK_CARD_MIN_WIDTH (line 15) | const RANK_CARD_MIN_WIDTH = 420;
  constant RANK_CARD_DEFAULT_WIDTH (line 16) | const RANK_CARD_DEFAULT_WIDTH = 450;
  constant RANK_ONLY_CARD_MIN_WIDTH (line 17) | const RANK_ONLY_CARD_MIN_WIDTH = 290;
  constant RANK_ONLY_CARD_DEFAULT_WIDTH (line 18) | const RANK_ONLY_CARD_DEFAULT_WIDTH = 290;
  constant LONG_LOCALES (line 25) | const LONG_LOCALES = [

FILE: src/cards/top-languages.js
  constant DEFAULT_CARD_WIDTH (line 15) | const DEFAULT_CARD_WIDTH = 300;
  constant MIN_CARD_WIDTH (line 16) | const MIN_CARD_WIDTH = 280;
  constant DEFAULT_LANG_COLOR (line 17) | const DEFAULT_LANG_COLOR = "#858585";
  constant CARD_PADDING (line 18) | const CARD_PADDING = 25;
  constant COMPACT_LAYOUT_BASE_HEIGHT (line 19) | const COMPACT_LAYOUT_BASE_HEIGHT = 90;
  constant MAXIMUM_LANGS_COUNT (line 20) | const MAXIMUM_LANGS_COUNT = 20;
  constant NORMAL_LAYOUT_DEFAULT_LANGS_COUNT (line 22) | const NORMAL_LAYOUT_DEFAULT_LANGS_COUNT = 5;
  constant COMPACT_LAYOUT_DEFAULT_LANGS_COUNT (line 23) | const COMPACT_LAYOUT_DEFAULT_LANGS_COUNT = 6;
  constant DONUT_LAYOUT_DEFAULT_LANGS_COUNT (line 24) | const DONUT_LAYOUT_DEFAULT_LANGS_COUNT = 5;
  constant PIE_LAYOUT_DEFAULT_LANGS_COUNT (line 25) | const PIE_LAYOUT_DEFAULT_LANGS_COUNT = 6;
  constant DONUT_VERTICAL_LAYOUT_DEFAULT_LANGS_COUNT (line 26) | const DONUT_VERTICAL_LAYOUT_DEFAULT_LANGS_COUNT = 6;

FILE: src/cards/types.d.ts
  type ThemeNames (line 1) | type ThemeNames = keyof typeof import("../../themes/index.js");
  type RankIcon (line 2) | type RankIcon = "default" | "github" | "percentile";
  type CommonOptions (line 4) | type CommonOptions = {
  type StatCardOptions (line 16) | type StatCardOptions = CommonOptions & {
  type RepoCardOptions (line 35) | type RepoCardOptions = CommonOptions & {
  type TopLangOptions (line 40) | type TopLangOptions = CommonOptions & {
  type WakaTimeOptions (line 52) | type WakaTimeOptions = CommonOptions & {
  type GistCardOptions (line 65) | type GistCardOptions = CommonOptions & {

FILE: src/cards/wakatime.js
  constant DEFAULT_CARD_WIDTH (line 21) | const DEFAULT_CARD_WIDTH = 495;
  constant MIN_CARD_WIDTH (line 22) | const MIN_CARD_WIDTH = 250;
  constant COMPACT_LAYOUT_MIN_WIDTH (line 23) | const COMPACT_LAYOUT_MIN_WIDTH = 400;
  constant DEFAULT_LINE_HEIGHT (line 24) | const DEFAULT_LINE_HEIGHT = 25;
  constant PROGRESSBAR_PADDING (line 25) | const PROGRESSBAR_PADDING = 130;
  constant HIDDEN_PROGRESSBAR_PADDING (line 26) | const HIDDEN_PROGRESSBAR_PADDING = 170;
  constant COMPACT_LAYOUT_PROGRESSBAR_PADDING (line 27) | const COMPACT_LAYOUT_PROGRESSBAR_PADDING = 25;
  constant TOTAL_TEXT_WIDTH (line 28) | const TOTAL_TEXT_WIDTH = 275;

FILE: src/common/Card.js
  class Card (line 6) | class Card {
    method constructor (line 24) | constructor({
    method disableAnimations (line 61) | disableAnimations() {
    method setAccessibilityLabel (line 71) | setAccessibilityLabel({ title, desc }) {
    method setCSS (line 80) | setCSS(value) {
    method setHideBorder (line 88) | setHideBorder(value) {
    method setHideTitle (line 96) | setHideTitle(value) {
    method setTitle (line 107) | setTitle(text) {
    method renderTitle (line 114) | renderTitle() {
    method renderGradient (line 153) | renderGradient() {
    method render (line 208) | render(body) {

FILE: src/common/I18n.js
  constant FALLBACK_LOCALE (line 3) | const FALLBACK_LOCALE = "en";
  class I18n (line 8) | class I18n {
    method constructor (line 16) | constructor({ locale, translations }) {
    method t (line 27) | t(str) {

FILE: src/common/access.js
  constant NOT_WHITELISTED_USERNAME_MESSAGE (line 7) | const NOT_WHITELISTED_USERNAME_MESSAGE = "This username is not whitelist...
  constant NOT_WHITELISTED_GIST_MESSAGE (line 8) | const NOT_WHITELISTED_GIST_MESSAGE = "This gist ID is not whitelisted";
  constant BLACKLISTED_MESSAGE (line 9) | const BLACKLISTED_MESSAGE = "This username is blacklisted";

FILE: src/common/cache.js
  constant MIN (line 5) | const MIN = 60;
  constant HOUR (line 6) | const HOUR = 60 * MIN;
  constant DAY (line 7) | const DAY = 24 * HOUR;
  constant DURATIONS (line 12) | const DURATIONS = {
  constant CACHE_TTL (line 34) | const CACHE_TTL = {

FILE: src/common/error.js
  constant TRY_AGAIN_LATER (line 6) | const TRY_AGAIN_LATER = "Please try again later";
  constant SECONDARY_ERROR_MESSAGES (line 11) | const SECONDARY_ERROR_MESSAGES = {
  class CustomError (line 25) | class CustomError extends Error {
    method constructor (line 32) | constructor(message, type) {
  class MissingParamError (line 49) | class MissingParamError extends Error {
    method constructor (line 56) | constructor(missedParams, secondaryMessage) {

FILE: src/common/render.js
  constant ERROR_CARD_LENGTH (line 119) | const ERROR_CARD_LENGTH = 576.5;
  constant UPSTREAM_API_ERRORS (line 121) | const UPSTREAM_API_ERRORS = [

FILE: src/common/retryer.js
  constant RETRIES (line 12) | const RETRIES = process.env.NODE_ENV === "test" ? 7 : PATs;

FILE: src/fetchers/gist.js
  constant QUERY (line 7) | const QUERY = `

FILE: src/fetchers/stats.js
  constant GRAPHQL_REPOS_FIELD (line 17) | const GRAPHQL_REPOS_FIELD = `
  constant GRAPHQL_REPOS_QUERY (line 33) | const GRAPHQL_REPOS_QUERY = `
  constant GRAPHQL_STATS_QUERY (line 41) | const GRAPHQL_STATS_QUERY = `

FILE: src/fetchers/types.d.ts
  type GistData (line 1) | type GistData = {
  type RepositoryData (line 10) | type RepositoryData = {
  type StatsData (line 27) | type StatsData = {
  type Lang (line 42) | type Lang = {
  type TopLangData (line 48) | type TopLangData = Record<string, Lang>;
  type WakaTimeData (line 50) | type WakaTimeData = {
  type WakaTimeLang (line 114) | type WakaTimeLang = {

FILE: tests/bench/utils.js
  constant DEFAULT_RUNS (line 3) | const DEFAULT_RUNS = 1000;
  constant DEFAULT_WARMUPS (line 4) | const DEFAULT_WARMUPS = 50;

FILE: tests/e2e/e2e.test.js
  constant REPO (line 15) | const REPO = "curly-fiesta";
  constant USER (line 16) | const USER = "catelinemnemosyne";
  constant STATS_CARD_USER (line 17) | const STATS_CARD_USER = "e2eninja";
  constant GIST_ID (line 18) | const GIST_ID = "372cef55fd897b31909fdeb3a7262758";
  constant STATS_DATA (line 20) | const STATS_DATA = {
  constant LANGS_DATA (line 34) | const LANGS_DATA = {
  constant WAKATIME_DATA (line 52) | const WAKATIME_DATA = {
  constant REPOSITORY_DATA (line 69) | const REPOSITORY_DATA = {
  constant GIST_DATA (line 95) | const GIST_DATA = {
  constant CACHE_BURST_STRING (line 105) | const CACHE_BURST_STRING = `v=${new Date().getTime()}`;
Condensed preview — 130 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (631K chars).
[
  {
    "path": ".devcontainer/devcontainer.json",
    "chars": 950,
    "preview": "{\n    \"name\": \"GitHub Readme Stats Dev\",\n    \"image\": \"mcr.microsoft.com/devcontainers/base:ubuntu\",\n    \"features\": {\n "
  },
  {
    "path": ".eslintrc.json",
    "chars": 8807,
    "preview": "// {\n//     \"env\": {\n//         \"node\": true,\n//         \"browser\": true,\n//         \"es2021\": true\n//     },\n//     \"ex"
  },
  {
    "path": ".github/CODEOWNERS",
    "chars": 304,
    "preview": "# This file is used to define code owners for the repository.\n# Code owners are automatically requested for review when "
  },
  {
    "path": ".github/FUNDING.yml",
    "chars": 820,
    "preview": "# These are supported funding model platforms\n\ngithub: [anuraghazra] # Replace with up to 4 GitHub Sponsors-enabled user"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/bug_report.yml",
    "chars": 2553,
    "preview": "name: Bug report\ndescription: Create a report to help us improve.\nlabels:\n  - \"bug\"\nbody:\n  - type: markdown\n    attribu"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/config.yml",
    "chars": 516,
    "preview": "blank_issues_enabled: true\ncontact_links:\n  - name: Question\n    url: https://github.com/anuraghazra/github-readme-stats"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/feature_request.yml",
    "chars": 916,
    "preview": "name: Feature request\ndescription: Suggest an idea for this project.\nlabels:\n  - \"enhancement\"\nbody:\n  - type: textarea\n"
  },
  {
    "path": ".github/dependabot.yml",
    "chars": 784,
    "preview": "version: 2\nupdates:\n  # Maintain dependencies for npm\n  - package-ecosystem: npm\n    directory: \"/\"\n    schedule:\n      "
  },
  {
    "path": ".github/labeler.yml",
    "chars": 2144,
    "preview": "themes:\n  - changed-files:\n      - any-glob-to-any-file:\n          - themes/index.js\n\ncard-i18n:\n  - changed-files:\n    "
  },
  {
    "path": ".github/stale.yml",
    "chars": 711,
    "preview": "# Number of days of inactivity before an issue becomes stale\ndaysUntilStale: 30\n# Number of days of inactivity before a "
  },
  {
    "path": ".github/workflows/codeql-analysis.yml",
    "chars": 1038,
    "preview": "name: \"Static code analysis workflow (CodeQL)\"\n\non:\n  push:\n    branches:\n      - master\n  pull_request:\n    branches:\n "
  },
  {
    "path": ".github/workflows/deploy-prep.py",
    "chars": 188,
    "preview": "import os\n\nfile = open('./vercel.json', 'r')\nstr = file.read()\nfile = open('./vercel.json', 'w')\n\nstr = str.replace('\"ma"
  },
  {
    "path": ".github/workflows/deploy-prep.yml",
    "chars": 572,
    "preview": "name: Deployment Prep\non:\n  workflow_dispatch:\n  push:\n    branches:\n      - master\n\njobs:\n  config:\n    if: github.repo"
  },
  {
    "path": ".github/workflows/e2e-test.yml",
    "chars": 1146,
    "preview": "name: Test Deployment\non:\n  # Temporarily disabled automatic triggers; manual-only for now.\n  workflow_dispatch:\n  # Ori"
  },
  {
    "path": ".github/workflows/empty-issues-closer.yml",
    "chars": 1451,
    "preview": "name: Close empty issues and templates\non:\n  issues:\n    types:\n      - reopened\n      - opened\n      - edited\n\npermissi"
  },
  {
    "path": ".github/workflows/generate-theme-doc.yml",
    "chars": 1452,
    "preview": "name: Generate Theme Readme\non:\n  push:\n    branches:\n      - master\n    paths:\n      - \"themes/index.js\"\n  workflow_dis"
  },
  {
    "path": ".github/workflows/label-pr.yml",
    "chars": 589,
    "preview": "name: \"Pull Request Labeler\"\non:\n  - pull_request_target\n\npermissions:\n  actions: read\n  checks: read\n  contents: read\n "
  },
  {
    "path": ".github/workflows/ossf-analysis.yml",
    "chars": 1493,
    "preview": "name: OSSF Scorecard analysis workflow\non:\n  push:\n    branches:\n      - master\n  pull_request:\n    branches:\n      - ma"
  },
  {
    "path": ".github/workflows/preview-theme.yml",
    "chars": 1217,
    "preview": "name: Theme preview\non:\n  # Temporary disabled due to paused themes addition.\n  # See: https://github.com/anuraghazra/gi"
  },
  {
    "path": ".github/workflows/prs-cache-clean.yml",
    "chars": 1083,
    "preview": "name: Cleanup closed pull requests cache\non:\n  pull_request:\n    types:\n      - closed\n\npermissions:\n  actions: write\n  "
  },
  {
    "path": ".github/workflows/stale-theme-pr-closer.yml",
    "chars": 1670,
    "preview": "name: Close stale theme pull requests that have the 'invalid' label.\non:\n  # Temporary disabled due to paused themes add"
  },
  {
    "path": ".github/workflows/test.yml",
    "chars": 941,
    "preview": "name: Test\non:\n  push:\n    branches:\n      - master\n  pull_request:\n    branches:\n      - master\n\npermissions: read-all\n"
  },
  {
    "path": ".github/workflows/theme-prs-closer.yml",
    "chars": 1299,
    "preview": "name: Theme Pull Requests Closer\n\non:\n  - pull_request_target\n\npermissions:\n  actions: read\n  checks: read\n  contents: r"
  },
  {
    "path": ".github/workflows/top-issues-dashboard.yml",
    "chars": 1363,
    "preview": "name: Update top issues dashboard\non:\n  schedule:\n    #        ┌───────────── minute (0 - 59)\n    #        │ ┌──────────"
  },
  {
    "path": ".github/workflows/update-langs.yml",
    "chars": 2099,
    "preview": "name: Update supported languages\non:\n  schedule:\n    #        ┌───────────── minute (0 - 59)\n    #        │ ┌───────────"
  },
  {
    "path": ".gitignore",
    "chars": 164,
    "preview": ".vercel\n.env\nnode_modules\n*.lock\n.idea/\ncoverage\nbenchmarks\nvercel_token\n\n# IDE\n.vscode/*\n!.vscode/extensions.json\n!.vsc"
  },
  {
    "path": ".husky/.gitignore",
    "chars": 2,
    "preview": "_\n"
  },
  {
    "path": ".husky/pre-commit",
    "chars": 38,
    "preview": "npm test\nnpm run lint\nnpx lint-staged\n"
  },
  {
    "path": ".nvmrc",
    "chars": 2,
    "preview": "22"
  },
  {
    "path": ".prettierignore",
    "chars": 42,
    "preview": "node_modules\n*.json\n*.md\ncoverage\n.vercel\n"
  },
  {
    "path": ".prettierrc.json",
    "chars": 96,
    "preview": "{\n  \"trailingComma\": \"all\",\n  \"useTabs\": false,\n  \"endOfLine\": \"auto\",\n  \"proseWrap\": \"always\"\n}"
  },
  {
    "path": ".vercelignore",
    "chars": 152,
    "preview": ".devcontainer\n.github\n.husky\n.vscode\nbenchmarks\ncoverage\nscripts\ntests\n.env\n**/*.md\n**/*.svg\n.eslintrc.json\n.prettierign"
  },
  {
    "path": ".vscode/extensions.json",
    "chars": 223,
    "preview": "{\n    \"recommendations\": [\n        \"yzhang.markdown-all-in-one\",\n        \"esbenp.prettier-vscode\",\n        \"dbaeumer.vsc"
  },
  {
    "path": ".vscode/settings.json",
    "chars": 195,
    "preview": "{\n    \"markdown.extension.toc.levels\": \"1..3\",\n    \"editor.formatOnSave\": true,\n    \"editor.defaultFormatter\": \"esbenp.p"
  },
  {
    "path": "CODE_OF_CONDUCT.md",
    "chars": 3354,
    "preview": "# Contributor Covenant Code of Conduct\n\n## Our Pledge\n\nIn the interest of fostering an open and welcoming environment, w"
  },
  {
    "path": "CONTRIBUTING.md",
    "chars": 5777,
    "preview": "# Contributing to [github-readme-stats](https://github.com/anuraghazra/github-readme-stats)\n\nWe love your input! We want"
  },
  {
    "path": "LICENSE",
    "chars": 1069,
    "preview": "MIT License\n\nCopyright (c) 2020 Anurag Hazra\n\nPermission is hereby granted, free of charge, to any person obtaining a co"
  },
  {
    "path": "SECURITY.md",
    "chars": 1511,
    "preview": "# GitHub Readme Stats Security Policies and Procedures <!-- omit in toc -->\n\nThis document outlines security procedures "
  },
  {
    "path": "api/gist.js",
    "chars": 2828,
    "preview": "// @ts-check\n\nimport { renderError } from \"../src/common/render.js\";\nimport { isLocaleAvailable } from \"../src/translati"
  },
  {
    "path": "api/index.js",
    "chars": 4072,
    "preview": "// @ts-check\n\nimport { renderStatsCard } from \"../src/cards/stats.js\";\nimport { guardAccess } from \"../src/common/access"
  },
  {
    "path": "api/pin.js",
    "chars": 2929,
    "preview": "// @ts-check\n\nimport { renderRepoCard } from \"../src/cards/repo.js\";\nimport { guardAccess } from \"../src/common/access.j"
  },
  {
    "path": "api/status/pat-info.js",
    "chars": 4559,
    "preview": "// @ts-check\n\n/**\n * @file Contains a simple cloud function that can be used to check which PATs are no\n * longer workin"
  },
  {
    "path": "api/status/up.js",
    "chars": 2850,
    "preview": "// @ts-check\n\n/**\n * @file Contains a simple cloud function that can be used to check if the PATs are still\n * functiona"
  },
  {
    "path": "api/top-langs.js",
    "chars": 4331,
    "preview": "// @ts-check\n\nimport { renderTopLanguages } from \"../src/cards/top-languages.js\";\nimport { guardAccess } from \"../src/co"
  },
  {
    "path": "api/wakatime.js",
    "chars": 3358,
    "preview": "// @ts-check\n\nimport { renderWakatimeCard } from \"../src/cards/wakatime.js\";\nimport { renderError } from \"../src/common/"
  },
  {
    "path": "codecov.yml",
    "chars": 172,
    "preview": "codecov:\n  require_ci_to_pass: yes\n\ncoverage:\n  precision: 2\n  round: down\n  range: \"70...100\"\n\n  status:\n    project:\n "
  },
  {
    "path": "eslint.config.mjs",
    "chars": 2111,
    "preview": "import globals from \"globals\";\nimport path from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport js from \"@"
  },
  {
    "path": "express.js",
    "chars": 656,
    "preview": "import \"dotenv/config\";\nimport statsCard from \"./api/index.js\";\nimport repoCard from \"./api/pin.js\";\nimport langCard fro"
  },
  {
    "path": "jest.bench.config.js",
    "chars": 409,
    "preview": "export default {\n  clearMocks: true,\n  transform: {},\n  testEnvironment: \"jsdom\",\n  coverageProvider: \"v8\",\n  testPathIg"
  },
  {
    "path": "jest.config.js",
    "chars": 367,
    "preview": "export default {\n  clearMocks: true,\n  transform: {},\n  testEnvironment: \"jsdom\",\n  coverageProvider: \"v8\",\n  testPathIg"
  },
  {
    "path": "jest.e2e.config.js",
    "chars": 161,
    "preview": "export default {\n  clearMocks: true,\n  transform: {},\n  testEnvironment: \"node\",\n  coverageProvider: \"v8\",\n  testMatch: "
  },
  {
    "path": "package.json",
    "chars": 2616,
    "preview": "{\n  \"name\": \"github-readme-stats\",\n  \"version\": \"1.0.0\",\n  \"description\": \"Dynamically generate stats for your GitHub re"
  },
  {
    "path": "readme.md",
    "chars": 48632,
    "preview": "<div align=\"center\">\n  <img src=\"https://res.cloudinary.com/anuraghazra/image/upload/v1594908242/logo_ccswme.svg\" width="
  },
  {
    "path": "scripts/close-stale-theme-prs.js",
    "chars": 5527,
    "preview": "/**\n * @file Script that can be used to close stale theme PRs that have a `invalid` label.\n */\nimport * as dotenv from \""
  },
  {
    "path": "scripts/generate-langs-json.js",
    "chars": 793,
    "preview": "import axios from \"axios\";\nimport fs from \"fs\";\nimport jsYaml from \"js-yaml\";\n\nconst LANGS_FILEPATH = \"./src/common/lang"
  },
  {
    "path": "scripts/generate-theme-doc.js",
    "chars": 3141,
    "preview": "import fs from \"fs\";\nimport { themes } from \"../themes/index.js\";\n\nconst TARGET_FILE = \"./themes/README.md\";\nconst REPO_"
  },
  {
    "path": "scripts/helpers.js",
    "chars": 894,
    "preview": "/**\n * @file Contains helper functions used in the scripts.\n */\n\nimport { getInput } from \"@actions/core\";\n\nconst OWNER "
  },
  {
    "path": "scripts/preview-theme.js",
    "chars": 21286,
    "preview": "/**\n * @file This script is used to preview the theme on theme PRs.\n */\nimport * as dotenv from \"dotenv\";\ndotenv.config("
  },
  {
    "path": "scripts/push-theme-readme.sh",
    "chars": 573,
    "preview": "#!/bin/bash\nset -x\nset -e\n\nexport BRANCH_NAME=updated-theme-readme\ngit --version\ngit config --global user.email \"no-repl"
  },
  {
    "path": "src/calculateRank.js",
    "chars": 2402,
    "preview": "/**\n * Calculates the exponential cdf.\n *\n * @param {number} x The value.\n * @returns {number} The exponential cdf.\n */\n"
  },
  {
    "path": "src/cards/gist.js",
    "chars": 4167,
    "preview": "// @ts-check\n\nimport {\n  measureText,\n  flexLayout,\n  iconWithLabel,\n  createLanguageNode,\n} from \"../common/render.js\";"
  },
  {
    "path": "src/cards/index.js",
    "chars": 199,
    "preview": "export { renderRepoCard } from \"./repo.js\";\nexport { renderStatsCard } from \"./stats.js\";\nexport { renderTopLanguages } "
  },
  {
    "path": "src/cards/repo.js",
    "chars": 5192,
    "preview": "// @ts-check\n\nimport { Card } from \"../common/Card.js\";\nimport { getCardColors } from \"../common/color.js\";\nimport { kFo"
  },
  {
    "path": "src/cards/stats.js",
    "chars": 15825,
    "preview": "// @ts-check\n\nimport { Card } from \"../common/Card.js\";\nimport { getCardColors } from \"../common/color.js\";\nimport { Cus"
  },
  {
    "path": "src/cards/top-languages.js",
    "chars": 27284,
    "preview": "// @ts-check\n\nimport { Card } from \"../common/Card.js\";\nimport { getCardColors } from \"../common/color.js\";\nimport { for"
  },
  {
    "path": "src/cards/types.d.ts",
    "chars": 1616,
    "preview": "type ThemeNames = keyof typeof import(\"../../themes/index.js\");\ntype RankIcon = \"default\" | \"github\" | \"percentile\";\n\nex"
  },
  {
    "path": "src/cards/wakatime.js",
    "chars": 14201,
    "preview": "// @ts-check\n\nimport { Card } from \"../common/Card.js\";\nimport { getCardColors } from \"../common/color.js\";\nimport { I18"
  },
  {
    "path": "src/common/Card.js",
    "chars": 6570,
    "preview": "// @ts-check\n\nimport { encodeHTML } from \"./html.js\";\nimport { flexLayout } from \"./render.js\";\n\nclass Card {\n  /**\n   *"
  },
  {
    "path": "src/common/I18n.js",
    "chars": 886,
    "preview": "// @ts-check\n\nconst FALLBACK_LOCALE = \"en\";\n\n/**\n * I18n translation class.\n */\nclass I18n {\n  /**\n   * Constructor.\n   "
  },
  {
    "path": "src/common/access.js",
    "chars": 2166,
    "preview": "// @ts-check\n\nimport { renderError } from \"./render.js\";\nimport { blacklist } from \"./blacklist.js\";\nimport { whitelist,"
  },
  {
    "path": "src/common/blacklist.js",
    "chars": 159,
    "preview": "const blacklist = [\n  \"renovate-bot\",\n  \"technote-space\",\n  \"sw-yx\",\n  \"YourUsername\",\n  \"[YourUsername]\",\n];\n\nexport { "
  },
  {
    "path": "src/common/cache.js",
    "chars": 3633,
    "preview": "// @ts-check\n\nimport { clampValue } from \"./ops.js\";\n\nconst MIN = 60;\nconst HOUR = 60 * MIN;\nconst DAY = 24 * HOUR;\n\n/**"
  },
  {
    "path": "src/common/color.js",
    "chars": 3922,
    "preview": "// @ts-check\n\nimport { themes } from \"../../themes/index.js\";\n\n/**\n * Checks if a string is a valid hex color.\n *\n * @pa"
  },
  {
    "path": "src/common/envs.js",
    "chars": 374,
    "preview": "// @ts-check\n\nconst whitelist = process.env.WHITELIST\n  ? process.env.WHITELIST.split(\",\")\n  : undefined;\n\nconst gistWhi"
  },
  {
    "path": "src/common/error.js",
    "chars": 2395,
    "preview": "// @ts-check\n\n/**\n * @type {string} A general message to ask user to try again later.\n */\nconst TRY_AGAIN_LATER = \"Pleas"
  },
  {
    "path": "src/common/fmt.js",
    "chars": 2525,
    "preview": "// @ts-check\n\nimport wrap from \"word-wrap\";\nimport { encodeHTML } from \"./html.js\";\n\n/**\n * Retrieves num with suffix k("
  },
  {
    "path": "src/common/html.js",
    "chars": 389,
    "preview": "// @ts-check\n\n/**\n * Encode string as HTML.\n *\n * @see https://stackoverflow.com/a/48073476/10629172\n *\n * @param {strin"
  },
  {
    "path": "src/common/http.js",
    "chars": 464,
    "preview": "// @ts-check\n\nimport axios from \"axios\";\n\n/**\n * Send GraphQL request to GitHub API.\n *\n * @param {import('axios').Axios"
  },
  {
    "path": "src/common/icons.js",
    "chars": 7418,
    "preview": "// @ts-check\n\nconst icons = {\n  star: `<path fill-rule=\"evenodd\" d=\"M8 .25a.75.75 0 01.673.418l1.882 3.815 4.21.612a.75."
  },
  {
    "path": "src/common/index.js",
    "chars": 298,
    "preview": "// @ts-check\n\nexport { blacklist } from \"./blacklist.js\";\nexport { Card } from \"./Card.js\";\nexport { I18n } from \"./I18n"
  },
  {
    "path": "src/common/languageColors.json",
    "chars": 17260,
    "preview": "{\n    \"1C Enterprise\": \"#814CCC\",\n    \"2-Dimensional Array\": \"#38761D\",\n    \"4D\": \"#004289\",\n    \"ABAP\": \"#E8274B\",\n    "
  },
  {
    "path": "src/common/log.js",
    "chars": 292,
    "preview": "// @ts-check\n\nconst noop = () => {};\n\n/**\n * Return console instance based on the environment.\n *\n * @type {Console | {l"
  },
  {
    "path": "src/common/ops.js",
    "chars": 2831,
    "preview": "// @ts-check\n\nimport toEmoji from \"emoji-name-map\";\n\n/**\n * Returns boolean if value is either \"true\" or \"false\" else th"
  },
  {
    "path": "src/common/render.js",
    "chars": 7884,
    "preview": "// @ts-check\n\nimport { SECONDARY_ERROR_MESSAGES, TRY_AGAIN_LATER } from \"./error.js\";\nimport { getCardColors } from \"./c"
  },
  {
    "path": "src/common/retryer.js",
    "chars": 3042,
    "preview": "// @ts-check\n\nimport { CustomError } from \"./error.js\";\nimport { logger } from \"./log.js\";\n\n// Script variables.\n\n// Cou"
  },
  {
    "path": "src/fetchers/gist.js",
    "chars": 2750,
    "preview": "// @ts-check\n\nimport { retryer } from \"../common/retryer.js\";\nimport { MissingParamError } from \"../common/error.js\";\nim"
  },
  {
    "path": "src/fetchers/repo.js",
    "chars": 2755,
    "preview": "// @ts-check\n\nimport { MissingParamError } from \"../common/error.js\";\nimport { request } from \"../common/http.js\";\nimpor"
  },
  {
    "path": "src/fetchers/stats.js",
    "chars": 10024,
    "preview": "// @ts-check\n\nimport axios from \"axios\";\nimport * as dotenv from \"dotenv\";\nimport githubUsernameRegex from \"github-usern"
  },
  {
    "path": "src/fetchers/top-languages.js",
    "chars": 4582,
    "preview": "// @ts-check\n\nimport { retryer } from \"../common/retryer.js\";\nimport { logger } from \"../common/log.js\";\nimport { exclud"
  },
  {
    "path": "src/fetchers/types.d.ts",
    "chars": 2545,
    "preview": "export type GistData = {\n  name: string;\n  nameWithOwner: string;\n  description: string | null;\n  language: string | nul"
  },
  {
    "path": "src/fetchers/wakatime.js",
    "chars": 987,
    "preview": "// @ts-check\n\nimport axios from \"axios\";\nimport { CustomError, MissingParamError } from \"../common/error.js\";\n\n/**\n * Wa"
  },
  {
    "path": "src/index.js",
    "chars": 69,
    "preview": "export * from \"./common/index.js\";\nexport * from \"./cards/index.js\";\n"
  },
  {
    "path": "src/translations.js",
    "chars": 39046,
    "preview": "// @ts-check\n\nimport { encodeHTML } from \"./common/html.js\";\n\n/**\n * Retrieves stat card labels in the available locales"
  },
  {
    "path": "tests/__snapshots__/renderWakatimeCard.test.js.snap",
    "chars": 14571,
    "preview": "// Jest Snapshot v1, https://jestjs.io/docs/snapshot-testing\n\nexports[`Test Render WakaTime Card should render correctly"
  },
  {
    "path": "tests/api.test.js",
    "chars": 11030,
    "preview": "// @ts-check\n\nimport {\n  afterEach,\n  beforeEach,\n  describe,\n  expect,\n  it,\n  jest,\n} from \"@jest/globals\";\nimport axi"
  },
  {
    "path": "tests/bench/api.bench.js",
    "chars": 1920,
    "preview": "import api from \"../../api/index.js\";\nimport axios from \"axios\";\nimport MockAdapter from \"axios-mock-adapter\";\nimport { "
  },
  {
    "path": "tests/bench/calculateRank.bench.js",
    "chars": 428,
    "preview": "import { calculateRank } from \"../../src/calculateRank.js\";\nimport { it } from \"@jest/globals\";\nimport { runAndLogStats "
  },
  {
    "path": "tests/bench/gist.bench.js",
    "chars": 1337,
    "preview": "import gist from \"../../api/gist.js\";\nimport axios from \"axios\";\nimport MockAdapter from \"axios-mock-adapter\";\nimport { "
  },
  {
    "path": "tests/bench/pin.bench.js",
    "chars": 1109,
    "preview": "import pin from \"../../api/pin.js\";\nimport axios from \"axios\";\nimport MockAdapter from \"axios-mock-adapter\";\nimport { it"
  },
  {
    "path": "tests/bench/utils.js",
    "chars": 3490,
    "preview": "// @ts-check\n\nconst DEFAULT_RUNS = 1000;\nconst DEFAULT_WARMUPS = 50;\n\n/**\n * Formats a duration in nanoseconds to a comp"
  },
  {
    "path": "tests/calculateRank.test.js",
    "chars": 2494,
    "preview": "import { describe, expect, it } from \"@jest/globals\";\nimport \"@testing-library/jest-dom\";\nimport { calculateRank } from "
  },
  {
    "path": "tests/card.test.js",
    "chars": 5684,
    "preview": "import { describe, expect, it } from \"@jest/globals\";\nimport { queryByTestId } from \"@testing-library/dom\";\nimport \"@tes"
  },
  {
    "path": "tests/color.test.js",
    "chars": 1988,
    "preview": "import { getCardColors } from \"../src/common/color\";\nimport { describe, expect, it } from \"@jest/globals\";\n\ndescribe(\"Te"
  },
  {
    "path": "tests/e2e/e2e.test.js",
    "chars": 6427,
    "preview": "/**\n * @file Contains end-to-end tests for the Vercel preview instance.\n */\nimport dotenv from \"dotenv\";\ndotenv.config()"
  },
  {
    "path": "tests/fetchGist.test.js",
    "chars": 3207,
    "preview": "import { afterEach, describe, expect, it } from \"@jest/globals\";\nimport \"@testing-library/jest-dom\";\nimport axios from \""
  },
  {
    "path": "tests/fetchRepo.test.js",
    "chars": 2903,
    "preview": "import { afterEach, describe, expect, it } from \"@jest/globals\";\nimport \"@testing-library/jest-dom\";\nimport axios from \""
  },
  {
    "path": "tests/fetchStats.test.js",
    "chars": 12577,
    "preview": "import { afterEach, beforeEach, describe, expect, it } from \"@jest/globals\";\nimport \"@testing-library/jest-dom\";\nimport "
  },
  {
    "path": "tests/fetchTopLanguages.test.js",
    "chars": 4486,
    "preview": "import { afterEach, describe, expect, it } from \"@jest/globals\";\nimport \"@testing-library/jest-dom\";\nimport axios from \""
  },
  {
    "path": "tests/fetchWakatime.test.js",
    "chars": 3491,
    "preview": "import { afterEach, describe, expect, it } from \"@jest/globals\";\nimport \"@testing-library/jest-dom\";\nimport axios from \""
  },
  {
    "path": "tests/flexLayout.test.js",
    "chars": 1317,
    "preview": "import { describe, expect, it } from \"@jest/globals\";\nimport { flexLayout } from \"../src/common/render.js\";\n\ndescribe(\"f"
  },
  {
    "path": "tests/fmt.test.js",
    "chars": 3888,
    "preview": "import { describe, expect, it } from \"@jest/globals\";\nimport {\n  formatBytes,\n  kFormatter,\n  wrapTextMultiline,\n} from "
  },
  {
    "path": "tests/gist.test.js",
    "chars": 5673,
    "preview": "// @ts-check\n\nimport { afterEach, describe, expect, it, jest } from \"@jest/globals\";\nimport \"@testing-library/jest-dom\";"
  },
  {
    "path": "tests/html.test.js",
    "chars": 315,
    "preview": "import { describe, expect, it } from \"@jest/globals\";\nimport { encodeHTML } from \"../src/common/html.js\";\n\ndescribe(\"Tes"
  },
  {
    "path": "tests/i18n.test.js",
    "chars": 1117,
    "preview": "import { describe, expect, it } from \"@jest/globals\";\nimport { I18n } from \"../src/common/I18n.js\";\nimport { statCardLoc"
  },
  {
    "path": "tests/ops.test.js",
    "chars": 2927,
    "preview": "import { describe, expect, it } from \"@jest/globals\";\nimport {\n  parseBoolean,\n  parseArray,\n  clampValue,\n  lowercaseTr"
  },
  {
    "path": "tests/pat-info.test.js",
    "chars": 6155,
    "preview": "/**\n * @file Tests for the status/pat-info cloud function.\n */\n\nimport dotenv from \"dotenv\";\ndotenv.config();\n\nimport {\n"
  },
  {
    "path": "tests/pin.test.js",
    "chars": 6286,
    "preview": "// @ts-check\n\nimport { afterEach, describe, expect, it, jest } from \"@jest/globals\";\nimport \"@testing-library/jest-dom\";"
  },
  {
    "path": "tests/render.test.js",
    "chars": 900,
    "preview": "// @ts-check\n\nimport { describe, expect, it } from \"@jest/globals\";\nimport { queryByTestId } from \"@testing-library/dom\""
  },
  {
    "path": "tests/renderGistCard.test.js",
    "chars": 8493,
    "preview": "import { describe, expect, it } from \"@jest/globals\";\nimport { queryByTestId } from \"@testing-library/dom\";\nimport \"@tes"
  },
  {
    "path": "tests/renderRepoCard.test.js",
    "chars": 12648,
    "preview": "import { describe, expect, it } from \"@jest/globals\";\nimport { queryByTestId } from \"@testing-library/dom\";\nimport \"@tes"
  },
  {
    "path": "tests/renderStatsCard.test.js",
    "chars": 17206,
    "preview": "import { describe, expect, it } from \"@jest/globals\";\nimport {\n  getByTestId,\n  queryAllByTestId,\n  queryByTestId,\n} fro"
  },
  {
    "path": "tests/renderTopLanguagesCard.test.js",
    "chars": 29155,
    "preview": "import { describe, expect, it } from \"@jest/globals\";\nimport { queryAllByTestId, queryByTestId } from \"@testing-library/"
  },
  {
    "path": "tests/renderWakatimeCard.test.js",
    "chars": 2978,
    "preview": "import { describe, expect, it } from \"@jest/globals\";\nimport { queryByTestId } from \"@testing-library/dom\";\nimport \"@tes"
  },
  {
    "path": "tests/retryer.test.js",
    "chars": 2416,
    "preview": "// @ts-check\n\nimport { describe, expect, it, jest } from \"@jest/globals\";\nimport \"@testing-library/jest-dom\";\nimport { R"
  },
  {
    "path": "tests/status.up.test.js",
    "chars": 6011,
    "preview": "/**\n * @file Tests for the status/up cloud function.\n */\n\nimport { afterEach, describe, expect, it, jest } from \"@jest/g"
  },
  {
    "path": "tests/top-langs.test.js",
    "chars": 6104,
    "preview": "// @ts-check\n\nimport { afterEach, describe, expect, it, jest } from \"@jest/globals\";\nimport \"@testing-library/jest-dom\";"
  },
  {
    "path": "tests/wakatime.test.js",
    "chars": 3876,
    "preview": "import { afterEach, describe, expect, it, jest } from \"@jest/globals\";\nimport \"@testing-library/jest-dom\";\nimport axios "
  },
  {
    "path": "themes/README.md",
    "chars": 29140,
    "preview": "## Available Themes\n\n<!-- DO NOT EDIT THIS FILE DIRECTLY -->\n\nWith inbuilt themes, you can customize the look of the car"
  },
  {
    "path": "themes/index.js",
    "chars": 9722,
    "preview": "export const themes = {\n  default: {\n    title_color: \"2f80ed\",\n    icon_color: \"4c71f2\",\n    text_color: \"434d58\",\n    "
  },
  {
    "path": "vercel.json",
    "chars": 222,
    "preview": "{\n  \"functions\": {\n    \"api/*.js\": {\n      \"memory\": 128,\n      \"maxDuration\": 10\n    }\n  },\n  \"redirects\": [\n    {\n    "
  }
]

About this extraction

This page contains the full source code of the anuraghazra/github-readme-stats GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 130 files (577.0 KB), approximately 169.1k tokens, and a symbol index with 123 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!