npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

je-sanitize

v1.0.0

Published

Production-grade code hygiene and sanitization CLI for JavaScript/TypeScript/React projects

Readme

je

JavaScript, TypeScript ve React için production-grade kod hijyen CLI aracı

Kod tabanınız her gün kirlilik biriktiriyor. je onu güvenli, anlık ve otomatik olarak temizler.

Lisans: MIT Node.js TypeScript Babel

English  ·  Türkçe


Problem

Her production kod tabanı zamanla çöp biriktirir:

console.log("debug:", userData);        // unutulmuş log
debugger;                               // kalan breakpoint
// TODO: bunu düzelt                    // 6 ay önceki eski yorum
import { helper } from "./utils";       // import edilmiş ama hiç kullanılmamış
const TEMP_FLAG = true;                 // tanımlanmış ama hiç referans verilmemiş

Bunlar bug değil — uygulamanız düzgün çalışıyor. Ama code review'ları yavaşlatıyor, git blame'i kirletiyor, bundle boyutunu şişiriyor ve yeni geliştiricilerin işi öğrenmesini zorlaştırıyor. Elle temizlemek sıkıcı. Regex ile temizlemek kırılgan.

Çözüm

je sanitize ./src

je, kodunuzu Babel kullanarak gerçek bir AST'ye parse eder — build araçlarınızın kullandığı aynı parser. TypeScript generic'lerini, JSX component'lerini, React hook'larını ve ES2024 syntax'ını doğal olarak anlar. Regex yok. String eşleştirme yok. Yanlış pozitif yok.

Öncesi

/**
 * Dashboard component
 * @author team
 */
import React, { useState, useEffect, useCallback, useMemo } from "react";
import { formatDate } from "../utils/date";
import { unusedHelper } from "../utils/helpers";

// TODO: bunu temizle
const DEBUG_MODE = true;

/* Bu geçici bir çözüm */
const TEMP_FLAG = false;

export const Dashboard = ({ userId }) => {
  const [data, setData] = useState(null);

  const unusedCallback = useCallback(() => {
    console.log("bu hiç çalışmayacak");
  }, []);

  useEffect(() => {
    console.debug("Veri çekiliyor...", userId);
    debugger;
    fetchData(userId).then(setData);
  }, [userId]);

  console.warn("Hâlâ yükleniyor...");
  return <div>{formatDate(data?.createdAt)}</div>;
};

Sonrası

import React, { useState, useEffect, useCallback } from "react";
import { formatDate } from "../utils/date";

export const Dashboard = ({ userId }) => {
  const [data, setData] = useState(null);

  const unusedCallback = useCallback(() => {
  }, []);

  useEffect(() => {
    fetchData(userId).then(setData);
  }, [userId]);

  return <div>{formatDate(data?.createdAt)}</div>;
};

14 sorun temizlendi. Kod Hijyen Puanı: 81 / 100


Kurulum

# npm
npm install -g je-sanitize

# yarn
yarn global add je-sanitize

# pnpm
pnpm add -g je-sanitize

Veya kurmadan doğrudan çalıştır:

# npm
npx je-sanitize sanitize ./src

# yarn
yarn dlx je-sanitize sanitize ./src

# pnpm
pnpm dlx je-sanitize sanitize ./src

Gereksinim: Node.js >= 18


Hızlı Başlangıç

# Tüm mevcut kuralları gör
je r

# 1. je'nin neleri sileceğini gör (güvenli — dosyalar değişmez)
je s ./src --dry

# 2. Değişikliklerin tam diff'ini gör
je s ./src --dry --diff

# 3. Sonuçlardan memnunsan uygula
je s ./src

# 4. CI'da kod hijyenini zorunlu kıl
je s ./src --ci

CLI Referansı

Komutlar

| Komut | Kısaltma | Açıklama | |-------|----------|----------| | je sanitize <yol> | je s <yol> | Kaynak dosyaları tarar ve temizler | | je rules | je r | Tüm mevcut kuralları, açıklamalarını ve puan cezalarını listeler | | je --help | je -h | Yardımı göster | | je --version | je -V | Versiyonu göster |

je sanitize <yol> [seçenekler]
je s <yol> [seçenekler]

Temel Seçenekler

| Flag | Ne yapar | Varsayılan | |------|----------|------------| | (flag yok) | Tarar ve temizlenmiş dosyaları yazar | — | | --dry | Sadece raporla, hiçbir şeye dokunma | false | | --diff | Her değişikliğin unified diff'ini göster | false | | --ci | Sorun bulunursa exit 1 döner (--dry içerir) | false | | --json | Makine tarafından okunabilir JSON rapor çıkart | false |

Davranış Seçenekleri

| Flag | Ne yapar | Varsayılan | |------|----------|------------| | --keep-console-error | console.error'u koru (genellikle kasıtlıdır) | true | | --no-keep-console-error | console.error'u da sil | — | | --keep-eslint-disable | eslint-disable yorumlarını koru | true | | --no-keep-eslint-disable | eslint-disable yorumlarını da sil | — | | --rules <liste> | Sadece belirli kuralları çalıştır (virgül ile ayrılmış) | hepsi |

Kural Kısaltmaları

Her kuralın --rules ile kullanılabilecek kısa bir takma adı vardır:

| Tam İsim | Kısaltma | |----------|----------| | remove-console | console | | remove-comments | comments | | remove-debugger | debugger | | remove-unused-imports | imports | | remove-unused-variables | variables |

Kullanım Örnekleri

# Sadece console çağrılarını ve debugger ifadelerini sil (kısa takma adlar)
je s ./src --rules console,debugger

# Aynı şey tam isimlerle
je sanitize ./src --rules remove-console,remove-debugger

# CI paneli için JSON rapor al
je s ./src --dry --json > hijyen-raporu.json

# console.error dahil her şeyi sil
je s ./src --no-keep-console-error

# Tek bir dosyayı sanitize et
je s ./src/components/Dashboard.tsx

Kurallar

remove-console

console.log(), console.warn(), console.info() ve console.debug() çağrılarını siler. console.error() genellikle kasıtlı hata yönetimi temsil ettiği için varsayılan olarak korunur.

// SİLİNİR                              // KORUNUR (varsayılan)
console.log("debug:", data);            console.error("Ölümcül:", err);
console.warn("kullanımdan kaldırıldı");
console.debug("iz:", stack);
console.info("yüklendi", count, "öğe");

remove-comments

Tek satırlı yorumları (//), blok yorumlarını (/* */) ve JSDoc bloklarını (/** */) siler. eslint-disable yorumları işlevsel direktifler olduğu için varsayılan olarak korunur.

// SİLİNİR                              // KORUNUR (varsayılan)
// TODO: sonra düzelt                   // eslint-disable-next-line
/* geçici çözüm */                      /* eslint-disable @typescript-eslint/no-explicit-any */
/** @deprecated v2'den beri */

remove-debugger

Tüm debugger ifadelerini siler. Bunlar production kodda asla bulunmamalıdır.

function processPayment(order) {
  debugger;                             // SİLİNİR
  return charge(order);
}

remove-unused-imports

Dosyada hiç referans verilmeyen import belirticilerini tespit edip siler. Tam React uyumlu:

// ÖNCESİ
import React, { useState, useEffect, useCallback, useMemo } from "react";
import { format, parse, addDays } from "date-fns";
import _ from "lodash";

// Sadece useState, useEffect ve format gerçekten kullanılıyorsa:

// SONRASI
import React, { useState, useEffect } from "react";
import { format } from "date-fns";

React uyumluluğunu ne sağlar:

  • JSX'te <Component /> kullanımı Component import'u için referans sayılır
  • <Foo.Bar /> kullanımı Foo import'u için referans sayılır
  • useState, useEffect, useCallback vb. gerçek referans olarak takip edilir
  • React, React.FC, React.createElement vb. ile kullanıldığında korunur
  • Sadece tip import'ları (import type { ... }) doğru şekilde yönetilir

remove-unused-variables

Hiç referans verilmeyen const ve let tanımlamalarını siler — ama sadece güvenli oldukları zaman. Bu kural kasıtlı olarak muhafazakâr davranır:

Silecek (saf başlangıç değerleri):

const DEBUG = true;                     // literal
const unused = [1, 2, 3];              // dizi literali
const helper = () => {};               // fonksiyon ifadesi
const tmpl = `prefix-${123}`;          // template literal

Silmeyecek (yan etki olasılığı):

const data = fetchData();              // fonksiyon çağrısı — yan etkisi olabilir
const instance = new Service();        // constructor — yan etkisi var
const el = document.getElementById();  // DOM çağrısı — yan etkisi var
var legacyFlag = true;                 // var — hoisting silmeyi riskli kılar

Silmeyecek (yapısal):

for (const item of items) { }          // döngü değişkeni — kontrol akışının parçası
const { a, b } = obj;                 // destructuring — V1'de atlanır

Desteklenen Dosya Tipleri

| Uzantı | Dil | |--------|-----| | .js | JavaScript (ES2024) | | .ts | TypeScript | | .jsx | React JSX | | .tsx | React TSX |

Otomatik yok sayılan: node_modules/, dist/, build/, .next/, coverage/, *.d.ts, *.min.js


Kod Hijyen Puanı

Her çalıştırma 0 ile 100 arasında bir Kod Hijyen Puanı hesaplar:

| Sorun Tipi | Tespit başına ceza | |------------|-------------------| | console.* çağrısı | -1 | | Yorum | -1 | | debugger ifadesi | -3 | | Kullanılmayan import | -2 | | Kullanılmayan değişken | -2 |

100 puan sıfır sorun demektir. Tipik gerçek dünya projeleri ilk çalıştırmada 60-80 puan alır.


CI Entegrasyonu

GitHub Actions

name: Kod Hijyeni
on: [push, pull_request]

jobs:
  hijyen:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: 18
      - run: npx je-sanitize sanitize ./src --ci

GitLab CI

kod-hijyeni:
  image: node:18
  script:
    - npx je-sanitize sanitize ./src --ci

Pre-commit Hook (Husky)

# .husky/pre-commit
npx je-sanitize sanitize ./src --ci

Dashboard'lar için JSON Rapor

je sanitize ./src --dry --json | jq '.score'
# Çıktı: 85

Mimari

src/
  cli/
    index.ts .................. CLI giriş noktası — Commander kurulumu
    commands/
      sanitize.ts ............. Sanitize komutu — flag ayrıştırma, orkestrasyon

  core/
    runner.ts ................. Ana döngü — dosya keşfetme, kural çalıştırma, dosya yazma
    ruleEngine.ts ............. Kural kayıt defteri — kuralları yükler, filtreler, çalıştırır
    context.ts ................ Babel parser — kaynak koddan AST'ye dönüşüm

  rules/
    removeConsole.ts .......... console.* metodları için CallExpression visitor
    removeComments.ts ......... AST comments dizisi filtreleme
    removeDebugger.ts ......... DebuggerStatement visitor
    removeUnusedImports.ts .... İki geçişli: binding toplama, sonra referans tarama
    removeUnusedVariables.ts .. Scope-tabanlı analiz + saf ifade kontrolcüsü

  reporter/
    prettyReporter.ts ......... Renkli terminal çıktısı ve puan
    jsonReporter.ts ........... Araç entegrasyonu için yapılandırılmış JSON

  utils/
    fileWalker.ts ............. fast-glob tabanlı dosya keşfetme
    diff.ts ................... Satır satır diff üreticisi
    interop.ts ................ CJS/ESM varsayılan export interop

  types.ts .................... Paylaşılan arayüzler (Rule, RemovalItem, vb.)
  index.ts .................... Public API yeniden export'ları

Tasarım İlkeleri

  1. AST-öncelikli — Her dönüşüm parse edilmiş syntax ağacı üzerinde çalışır, ham stringler üzerinde asla
  2. Kural-tabanlı — Her sorumluluk bağımsız, test edilebilir, basit arayüzlü bir kural
  3. Varsayılan olarak güvenli — Muhafazakâr silme stratejisi; şüphe durumunda kodu koru
  4. React-yerli — JSX, hook'lar ve component kalıpları birinci sınıf vatandaş
  5. Genişletilebilir — Özel kurallar tek bir arayüz ile eklenir

Özel Kural Yazma

import type { Rule, RuleContext, RuleResult } from "je-sanitize";
import traverse from "@babel/traverse";

export const removeAlerts: Rule = {
  name: "remove-alerts",
  description: "window.alert() çağrılarını siler",

  run(context: RuleContext): RuleResult {
    const removals = [];

    traverse(context.ast, {
      CallExpression(path) {
        const { callee } = path.node;
        if (
          callee.type === "MemberExpression" &&
          callee.object.type === "Identifier" &&
          callee.object.name === "window" &&
          callee.property.type === "Identifier" &&
          callee.property.name === "alert"
        ) {
          removals.push({
            rule: "remove-alerts",
            file: context.filePath,
            kind: "alert",
            lineStart: path.node.loc?.start.line ?? 0,
            snippet: "window.alert(...)",
            severity: "medium" as const,
          });
          if (path.parentPath?.isExpressionStatement()) {
            path.parentPath.remove();
          }
        }
      },
    });

    return { removals };
  },
};

Teknik Yığın

| Katman | Teknoloji | Neden | |--------|-----------|-------| | AST Parser | @babel/parser | Endüstri standardı, TS + JSX + güncel ES desteği | | AST Gezinme | @babel/traverse | Scope analizi ile visitor deseni | | Kod Üretme | @babel/generator | retainLines ile formatlama koruma | | CLI Framework | commander | Olgun, sıfır konfigürasyonlu argüman ayrıştırma | | Terminal Çıktı | chalk + ora | Renkler ve spinner'lar | | Dosya Keşfetme | fast-glob | Hızlı, gitignore kalıplarını sayar | | Dil | TypeScript (ESM) | Tip güvenliği + modern modül sistemi |


Katkı Sağla

# Klonla ve kur
git clone https://github.com/berkcangumusisik/je-sanitize.git
cd je-sanitize

# Bağımlılıkları kur (paket yöneticini seç)
npm install        # npm
yarn install       # yarn
pnpm install       # pnpm

# Derle
npm run build

# Örnekler üzerinde test et
node dist/cli/index.js sanitize examples/ --dry

# Geliştirme sırasında izleme modu
npm run dev

Yeni Kural Ekleme

  1. Rule arayüzünü implement eden src/rules/myRule.ts dosyası oluştur
  2. src/core/ruleEngine.ts dosyasına kaydet
  3. src/reporter/prettyReporter.ts dosyasına renk eşlemesi ekle
  4. Her iki reporter'a puan ağırlık değeri ekle
  5. examples/ klasörüne test örneği oluştur

Yol Haritası

  • [ ] .je.config.json konfigürasyon dosyası
  • [ ] --fix interaktif mod (neyi sileceğini seç)
  • [ ] İzleme modu (--watch)
  • [ ] VS Code eklentisi
  • [ ] Özel kural paketleri için plugin sistemi
  • [ ] remove-dead-code kuralı (erişilemeyen kod tespiti)
  • [ ] remove-empty-blocks kuralı
  • [ ] Monorepo desteği (workspaces)

Lisans

MIT — kişisel ve ticari projelerde özgürce kullanın.


Hata Bildir  ·  Özellik İste  ·  Tartışmalar