← back to gregpriday__copytree

Function bodies 337 total

All specs Real LLM only Function bodies
PerformanceMonitor.endTimer method · javascript · L36-L81 (46 LOC)
src/utils/performance.js
  endTimer(name, metadata = {}) {
    if (!this.options.enabled) return null;

    const timer = this.timers.get(name);
    if (!timer) {
      this.logger.warn(`Timer '${name}' was not started`);
      return null;
    }

    const endTime = performance.now();
    const endMemory = process.memoryUsage();

    const duration = endTime - timer.startTime;
    const memoryDelta = {
      rss: endMemory.rss - timer.startMemory.rss,
      heapUsed: endMemory.heapUsed - timer.startMemory.heapUsed,
      heapTotal: endMemory.heapTotal - timer.startMemory.heapTotal,
    };

    const result = {
      name,
      duration: Math.round(duration * 100) / 100,
      memory: memoryDelta,
      metadata,
      timestamp: new Date().toISOString(),
    };

    // Store metric
    if (!this.metrics.has(name)) {
      this.metrics.set(name, []);
    }
    this.metrics.get(name).push(result);

    // Log if over threshold
    if (duration > this.options.logThreshold) {
      this.logger.warn('Slow operati
PerformanceMonitor.measure method · javascript · L86-L95 (10 LOC)
src/utils/performance.js
  async measure(name, fn, metadata = {}) {
    this.startTimer(name);
    try {
      const result = await fn();
      return { result, performance: this.endTimer(name, metadata) };
    } catch (error) {
      this.endTimer(name, { ...metadata, error: error.message });
      throw error;
    }
  }
PerformanceMonitor.getStats method · javascript · L108-L134 (27 LOC)
src/utils/performance.js
  getStats(name) {
    const measurements = this.metrics.get(name);
    if (!measurements || measurements.length === 0) {
      return null;
    }

    const durations = measurements.map((m) => m.duration);
    const memoryUsages = measurements.map((m) => m.memory.heapUsed);

    return {
      name,
      count: measurements.length,
      duration: {
        min: Math.min(...durations),
        max: Math.max(...durations),
        avg: durations.reduce((sum, d) => sum + d, 0) / durations.length,
        total: durations.reduce((sum, d) => sum + d, 0),
      },
      memory: {
        min: Math.min(...memoryUsages),
        max: Math.max(...memoryUsages),
        avg: memoryUsages.reduce((sum, m) => sum + m, 0) / memoryUsages.length,
        total: memoryUsages.reduce((sum, m) => sum + m, 0),
      },
      measurements: measurements.slice(-10), // Last 10 measurements
    };
  }
PerformanceMonitor.getAllStats method · javascript · L139-L145 (7 LOC)
src/utils/performance.js
  getAllStats() {
    const stats = {};
    for (const name of this.metrics.keys()) {
      stats[name] = this.getStats(name);
    }
    return stats;
  }
PerformanceMonitor.clear method · javascript · L150-L158 (9 LOC)
src/utils/performance.js
  clear(name = null) {
    if (name) {
      this.metrics.delete(name);
      this.timers.delete(name);
    } else {
      this.metrics.clear();
      this.timers.clear();
    }
  }
PerformanceMonitor.scope method · javascript · L163-L170 (8 LOC)
src/utils/performance.js
  scope(prefix) {
    return {
      startTimer: (name) => this.startTimer(`${prefix}.${name}`),
      endTimer: (name, metadata) => this.endTimer(`${prefix}.${name}`, metadata),
      measure: (name, fn, metadata) => this.measure(`${prefix}.${name}`, fn, metadata),
      measureOnly: (name, fn, metadata) => this.measureOnly(`${prefix}.${name}`, fn, metadata),
    };
  }
PerformanceMonitor.getSystemStats method · javascript · L175-L194 (20 LOC)
src/utils/performance.js
  getSystemStats() {
    const memory = process.memoryUsage();
    const cpu = process.cpuUsage();

    return {
      memory: {
        rss: memory.rss,
        heapTotal: memory.heapTotal,
        heapUsed: memory.heapUsed,
        external: memory.external,
        arrayBuffers: memory.arrayBuffers,
      },
      cpu: {
        user: cpu.user,
        system: cpu.system,
      },
      uptime: process.uptime(),
      timestamp: new Date().toISOString(),
    };
  }
Same scanner, your repo: https://repobility.com — Repobility
PerformanceMonitor.logSystemStats method · javascript · L199-L204 (6 LOC)
src/utils/performance.js
  logSystemStats(context = '') {
    if (!this.options.enabled) return;

    const stats = this.getSystemStats();
    this.logger.debug('System stats', { context, ...stats });
  }
measureMethod function · javascript · L210-L222 (13 LOC)
src/utils/performance.js
function measureMethod(target, propertyName, descriptor) {
  const originalMethod = descriptor.value;

  descriptor.value = async function (...args) {
    const monitor = new PerformanceMonitor();
    const className = this.constructor.name;
    const methodName = `${className}.${propertyName}`;

    return await monitor.measureOnly(methodName, () => originalMethod.apply(this, args));
  };

  return descriptor;
}
measureFunction function · javascript · L227-L233 (7 LOC)
src/utils/performance.js
function measureFunction(name, fn) {
  const monitor = new PerformanceMonitor();

  return async function (...args) {
    return await monitor.measureOnly(name, () => fn.apply(this, args));
  };
}
formatBytes function · javascript · L238-L246 (9 LOC)
src/utils/performance.js
function formatBytes(bytes) {
  if (bytes === 0) return '0 B';
  const k = 1024;
  const sizes = ['B', 'KB', 'MB', 'GB'];
  const i = Math.floor(Math.log(Math.abs(bytes)) / Math.log(k));
  const value = bytes / Math.pow(k, i);
  const sign = bytes < 0 ? '-' : '';
  return `${sign}${Math.round(value * 100) / 100} ${sizes[i]}`;
}
Profiler.constructor method · javascript · L18-L29 (12 LOC)
src/utils/profiler.js
  constructor(options = {}) {
    const type = (options.type || 'cpu').toLowerCase();
    if (!VALID_TYPES.includes(type)) {
      throw new Error(`Invalid profile type "${type}". Must be one of: ${VALID_TYPES.join(', ')}`);
    }

    this.type = type;
    this.profileDir = options.profileDir || '.profiles';
    this.timestamp = new Date().toISOString().replace(/[:.]/g, '-').slice(0, 19);
    this.session = options._session || new inspector.Session();
    this._started = false;
  }
Profiler.start method · javascript · L34-L54 (21 LOC)
src/utils/profiler.js
  async start() {
    this.session.connect();
    this._started = true;

    try {
      if (this.type === 'cpu' || this.type === 'all') {
        await this._post('Profiler.enable');
        await this._post('Profiler.start');
      }

      if (this.type === 'heap' || this.type === 'all') {
        await this._post('HeapProfiler.enable');
        await this._post('HeapProfiler.startSampling');
      }
    } catch (err) {
      // Rollback: disconnect and reset state so callers don't get a zombie session
      this.session.disconnect();
      this._started = false;
      throw err;
    }
  }
Profiler.stop method · javascript · L60-L87 (28 LOC)
src/utils/profiler.js
  async stop() {
    const results = {};

    try {
      await fs.ensureDir(this.profileDir);

      if (this.type === 'cpu' || this.type === 'all') {
        const { profile } = await this._post('Profiler.stop');
        const cpuPath = path.join(this.profileDir, `${this.timestamp}-cpu.cpuprofile`);
        await fs.writeJson(cpuPath, profile);
        results.cpu = cpuPath;
      }

      if (this.type === 'heap' || this.type === 'all') {
        const { profile } = await this._post('HeapProfiler.stopSampling');
        const heapPath = path.join(this.profileDir, `${this.timestamp}-heap.heapprofile`);
        await fs.writeJson(heapPath, profile);
        results.heap = heapPath;
      }
    } finally {
      if (this._started) {
        this.session.disconnect();
        this._started = false;
      }
    }

    return results;
  }
Profiler._post method · javascript · L93-L100 (8 LOC)
src/utils/profiler.js
  _post(method, params = {}) {
    return new Promise((resolve, reject) => {
      this.session.post(method, params, (err, result) => {
        if (err) reject(err);
        else resolve(result || {});
      });
    });
  }
Repobility · MCP-ready · https://repobility.com
writeProfilingReport function · javascript · L119-L153 (35 LOC)
src/utils/profiler.js
export async function writeProfilingReport({
  profileDir,
  timestamp,
  duration,
  version,
  command,
  files,
  memory,
  perStageTimings = {},
  perStageMetrics = {},
  profileFiles = {},
}) {
  await fs.ensureDir(profileDir);

  const stages = Object.entries(perStageTimings).map(([name, stageDuration]) => ({
    name,
    duration: stageDuration,
    memoryDelta: perStageMetrics[name]?.memoryUsage?.delta?.heapUsed ?? 0,
  }));

  const report = {
    timestamp: new Date().toISOString(),
    version,
    command,
    duration,
    files,
    memory,
    stages,
    profileFiles,
  };

  const reportPath = path.join(profileDir, `${timestamp}-report.json`);
  await fs.writeJson(reportPath, report, { spaces: 2 });
  return reportPath;
}
ProgressTracker.constructor method · javascript · L20-L32 (13 LOC)
src/utils/ProgressTracker.js
  constructor({ totalStages, onProgress, throttleMs = 100 } = {}) {
    this.totalStages = totalStages || 1;
    this.onProgress = onProgress || (() => {});
    this.throttleMs = throttleMs;

    this.completedStages = 0;
    this.currentStageIndex = -1;
    this.currentStageProgress = 0;
    this.lastPercent = -1;
    this.lastEmitTime = 0;
    this.started = false;
    this.finished = false;
  }
ProgressTracker.attach method · javascript · L38-L92 (55 LOC)
src/utils/ProgressTracker.js
  attach(pipeline) {
    pipeline.on('pipeline:start', () => {
      this._emitForced({ percent: 0, message: 'Starting...' });
      this.started = true;
    });

    pipeline.on('stage:start', (data) => {
      this.currentStageIndex = data.index;
      this.currentStageProgress = 0;

      const percent = this._calculatePercent();
      this._emit({ percent, message: `${this._formatStageName(data.stage)}...` });
    });

    pipeline.on('stage:progress', (data) => {
      this.currentStageProgress = data.progress || 0;

      const percent = this._calculatePercent();
      const message = data.message || `${this._formatStageName(data.stage)}...`;
      this._emit({ percent, message });
    });

    pipeline.on('file:batch', (data) => {
      const percent = this._calculatePercent();
      const message = data.lastFile
        ? `Processing ${data.lastFile}`
        : `Processed ${data.count} files`;
      this._emit({ percent, message });
    });

    pipeline.on('stage:complete', (d
ProgressTracker._formatStageName method · javascript · L111-L132 (22 LOC)
src/utils/ProgressTracker.js
  _formatStageName(stageName) {
    // Convert "FileDiscoveryStage" -> "Discovering files"
    // Convert "ProfileFilterStage" -> "Filtering by profile"
    const stageMessages = {
      FileDiscoveryStage: 'Discovering files',
      AlwaysIncludeStage: 'Including required files',
      GitFilterStage: 'Filtering by git status',
      ProfileFilterStage: 'Applying filters',
      DeduplicateFilesStage: 'Removing duplicates',
      SortFilesStage: 'Sorting files',
      FileLoadingStage: 'Loading file contents',
      TransformStage: 'Transforming files',
      CharLimitStage: 'Applying character limits',
      SecretsGuardStage: 'Scanning for secrets',
      InstructionsStage: 'Processing instructions',
      LimitStage: 'Applying limits',
      OutputFormattingStage: 'Formatting output',
      StreamingOutputStage: 'Streaming output',
    };

    return stageMessages[stageName] || stageName;
  }
ProgressTracker._emit method · javascript · L139-L157 (19 LOC)
src/utils/ProgressTracker.js
  _emit(progress) {
    // Enforce monotonic progress
    if (progress.percent <= this.lastPercent) {
      progress = { ...progress, percent: this.lastPercent };
    }

    const now = Date.now();
    if (now - this.lastEmitTime < this.throttleMs) {
      return;
    }

    this.lastPercent = progress.percent;
    this.lastEmitTime = now;
    try {
      this.onProgress(progress);
    } catch {
      // Swallow callback exceptions — progress tracking must not fail the operation
    }
  }
ProgressTracker._emitForced method · javascript · L165-L178 (14 LOC)
src/utils/ProgressTracker.js
  _emitForced(progress) {
    // Enforce monotonic progress
    if (progress.percent < this.lastPercent) {
      progress = { ...progress, percent: this.lastPercent };
    }

    this.lastPercent = progress.percent;
    this.lastEmitTime = Date.now();
    try {
      this.onProgress(progress);
    } catch {
      // Swallow callback exceptions — progress tracking must not fail the operation
    }
  }
withFsRetry function · javascript · L16-L98 (83 LOC)
src/utils/retryableFs.js
export async function withFsRetry(operation, options = {}) {
  const {
    maxAttempts = 3,
    initialDelay = 100,
    maxDelay = 2000,
    jitter = false,
    onRetry = () => {},
    signal,
  } = options;

  const createAbortError = () => {
    const abortError = new Error('Operation aborted');
    abortError.code = 'ABORT_ERR';
    return abortError;
  };

  let attempt = 0;

  while (true) {
    attempt++;

    try {
      // Check for abort signal
      if (signal?.aborted) {
        throw createAbortError();
      }

      // Execute the operation
      const result = await operation();

      // If the operation completed but the signal was aborted, treat as aborted
      if (signal?.aborted) {
        throw createAbortError();
      }

      return result;
    } catch (error) {
      const retryable = isRetryableFsError(error);

      // If not retryable or max attempts reached, throw the error
      if (!retryable || attempt >= maxAttempts) {
        throw error;
      }

   
SecretRedactor.redact method · javascript · L25-L67 (43 LOC)
src/utils/SecretRedactor.js
  static redact(content, findings, mode = 'typed') {
    if (!findings || findings.length === 0) {
      return { content, count: 0 };
    }

    // Normalize findings to unified format
    const normalized = findings.map((f) => this._normalizeFinding(f));

    // Convert content to line array for precise indexing
    const lines = content.split('\n');
    const lineOffsets = this._calculateLineOffsets(content);

    // Sort findings in reverse order (bottom to top) to maintain indices
    const sorted = [...normalized].sort((a, b) => {
      // Sort by line first, then by column
      if (b.StartLine !== a.StartLine) {
        return b.StartLine - a.StartLine;
      }
      return b.StartColumn - a.StartColumn;
    });

    let redactedContent = content;
    let redactionCount = 0;

    // Apply redactions in reverse order
    for (const finding of sorted) {
      try {
        const replacement = this.getMarker(finding, mode);
        const { startIndex, endIndex } = this._findingToI
Methodology: Repobility · https://repobility.com/research/state-of-ai-code-2026/
SecretRedactor._normalizeFinding method · javascript · L75-L91 (17 LOC)
src/utils/SecretRedactor.js
  static _normalizeFinding(finding) {
    // Check if already in Gitleaks format
    if (finding.RuleID !== undefined) {
      return finding;
    }

    // Convert SecretFinding to Gitleaks-like format
    return {
      RuleID: finding.redactionLabel || finding.type || 'UNKNOWN',
      StartLine: finding.lineStart,
      EndLine: finding.lineEnd,
      StartColumn: finding.startColumn,
      EndColumn: finding.endColumn,
      Match: finding.match,
      File: finding.file,
    };
  }
SecretRedactor.getMarker method · javascript · L100-L123 (24 LOC)
src/utils/SecretRedactor.js
  static getMarker(finding, mode) {
    const ruleId = (finding.RuleID || 'UNKNOWN').toUpperCase();

    switch (mode) {
      case 'typed':
        return `***REDACTED:${ruleId}***`;

      case 'generic':
        return '***REDACTED***';

      case 'hash': {
        // Generate short hash for debugging (never log the actual secret)
        // Use Match if available (which might be redacted by gitleaks),
        // otherwise generate a stable hash from metadata
        const hashInput =
          finding.Match || `${finding.File}:${finding.StartLine}:${finding.StartColumn}`;
        const hash = crypto.createHash('sha256').update(hashInput).digest('hex').substring(0, 8);
        return `***REDACTED:${ruleId}:${hash}***`;
      }

      default:
        return '***REDACTED***';
    }
  }
SecretRedactor._findingToIndices method · javascript · L133-L168 (36 LOC)
src/utils/SecretRedactor.js
  static _findingToIndices(finding, lines, lineOffsets) {
    const startLine = Math.max(0, (finding.StartLine ?? 1) - 1);
    const endLine = Math.max(startLine, (finding.EndLine ?? finding.StartLine ?? 1) - 1);
    const startCol = Math.max(0, (finding.StartColumn ?? 1) - 1);
    const endCol = Math.max(startCol, (finding.EndColumn ?? finding.StartColumn ?? 1) - 1);

    // Validate line indices
    if (startLine >= lines.length || endLine >= lines.length) {
      return { startIndex: -1, endIndex: -1 };
    }

    // Calculate content length
    const lastLineIndex = Math.max(lines.length - 1, 0);
    const lastLineOffset = lineOffsets[lastLineIndex] ?? 0;
    const lastLineLength = lines[lastLineIndex]?.length ?? 0;
    const contentLength = lastLineOffset + lastLineLength;

    // Calculate absolute indices
    const startIndex = lineOffsets[startLine] + startCol;

    // For end index, add 1 because column positions are inclusive (point to the last char)
    let endIndex =
      
SecretRedactor._calculateLineOffsets method · javascript · L176-L186 (11 LOC)
src/utils/SecretRedactor.js
  static _calculateLineOffsets(content) {
    const offsets = [0]; // First line starts at 0

    for (let i = 0; i < content.length; i++) {
      if (content[i] === '\n') {
        offsets.push(i + 1);
      }
    }

    return offsets;
  }
SecretRedactor.redactBatch method · javascript · L195-L204 (10 LOC)
src/utils/SecretRedactor.js
  static redactBatch(files, mode = 'typed') {
    return files.map((file) => {
      const { content, count } = this.redact(file.content, file.findings, mode);
      return {
        ...file,
        content,
        redactionCount: count,
      };
    });
  }
TaskLimiter.constructor method · javascript · L20-L32 (13 LOC)
src/utils/taskLimiter.js
  constructor() {
    /** @type {Map<string, import('p-limit').LimitFunction>} */
    this.limiters = new Map();

    /** @type {Map<string, number>} */
    this.budgets = new Map();

    /** @type {number} */
    this.totalBudget = 20; // Default global budget

    /** @type {boolean} */
    this.initialized = false;
  }
TaskLimiter.initialize method · javascript · L43-L65 (23 LOC)
src/utils/taskLimiter.js
  initialize(options = {}) {
    if (this.initialized) {
      return; // Already initialized
    }

    this.totalBudget = options.totalBudget ?? 20;

    // Set per-domain budgets (defaults ensure we don't exceed total budget)
    const defaults = {
      discovery: Math.floor(this.totalBudget * 0.4), // 40% for discovery (8 default)
      glob: Math.floor(this.totalBudget * 0.3), // 30% for glob (6 default)
      transform: Math.floor(this.totalBudget * 0.3), // 30% for transforms (6 default)
    };

    this.budgets = new Map(Object.entries({ ...defaults, ...options.budgets }));

    // Create limiters for each domain
    for (const [domain, budget] of this.budgets) {
      this.limiters.set(domain, pLimit(budget));
    }

    this.initialized = true;
  }
TaskLimiter.setBudget method · javascript · L94-L103 (10 LOC)
src/utils/taskLimiter.js
  setBudget(domain, budget) {
    if (budget < 1) {
      throw new Error(`Budget must be at least 1, got ${budget}`);
    }

    this.budgets.set(domain, budget);

    // Recreate limiter with new budget
    this.limiters.set(domain, pLimit(budget));
  }
Want fix-PRs on findings? Install Repobility's GitHub App · github.com/apps/repobility-bot
TaskLimiter.getTotalInflight method · javascript · L129-L135 (7 LOC)
src/utils/taskLimiter.js
  getTotalInflight() {
    let total = 0;
    for (const limiter of this.limiters.values()) {
      total += limiter.activeCount + limiter.pendingCount;
    }
    return total;
  }
TaskLimiter.getStats method · javascript · L141-L157 (17 LOC)
src/utils/taskLimiter.js
  getStats() {
    const stats = {};
    for (const [domain, limiter] of this.limiters) {
      stats[domain] = {
        budget: this.budgets.get(domain),
        active: limiter.activeCount,
        pending: limiter.pendingCount,
        utilization: limiter.activeCount / this.budgets.get(domain),
      };
    }
    stats.total = {
      budget: this.totalBudget,
      inflight: this.getTotalInflight(),
      utilization: this.getTotalInflight() / this.totalBudget,
    };
    return stats;
  }
TaskLimiter.waitForAll method · javascript · L183-L191 (9 LOC)
src/utils/taskLimiter.js
  async waitForAll() {
    await this._waitUntilIdle(() => {
      let inflight = 0;
      for (const limiter of this.limiters.values()) {
        inflight += limiter.activeCount + limiter.pendingCount;
      }
      return inflight;
    });
  }
TaskLimiter.reset method · javascript · L196-L201 (6 LOC)
src/utils/taskLimiter.js
  reset() {
    this.clearAll();
    this.limiters.clear();
    this.budgets.clear();
    this.initialized = false;
  }
Pipeline.send method · typescript · L861-L866 (6 LOC)
types/index.d.ts
  send<T>(passable: T): {
    through(stages: Stage[] | Array<new (options?: StageOptions) => Stage>): {
      then<TResult>(callback?: (result: T) => TResult): Promise<TResult>;
      thenReturn(): Promise<T>;
    };
  };
ConfigManager.effective method · typescript · L1172-L1179 (8 LOC)
types/index.d.ts
  effective(options?: { redact?: boolean; section?: string }): Record<
    string,
    {
      value: any;
      source: string;
      type: string;
      redacted: boolean;
    }
‹ prevpage 7 / 7