@socketsecurity/lib
Version:
Core utilities and infrastructure for Socket.dev security tools
179 lines (178 loc) • 5.64 kB
TypeScript
/**
* Performance metrics collected during execution.
*/
type PerformanceMetrics = {
operation: string;
duration: number;
timestamp: number;
metadata?: Record<string, unknown>;
};
/**
* Start a performance timer for an operation.
* Returns a stop function that records the duration.
*
* @param operation - Name of the operation being timed
* @param metadata - Optional metadata to attach to the metric
* @returns Stop function that completes the timing
*
* @example
* import { perfTimer } from '@socketsecurity/lib/performance'
*
* const stop = perfTimer('api-call')
* await fetchData()
* stop({ endpoint: '/npm/lodash/score' })
*/
export declare function perfTimer(operation: string, metadata?: Record<string, unknown>): (additionalMetadata?: Record<string, unknown>) => void;
/**
* Measure execution time of an async function.
*
* @param operation - Name of the operation
* @param fn - Async function to measure
* @param metadata - Optional metadata
* @returns Result of the function and duration
*
* @example
* import { measure } from '@socketsecurity/lib/performance'
*
* const { result, duration } = await measure('fetch-packages', async () => {
* return await fetchPackages()
* })
* console.log(`Fetched packages in ${duration}ms`)
*/
export declare function measure<T>(operation: string, fn: () => Promise<T>, metadata?: Record<string, unknown>): Promise<{
result: T;
duration: number;
}>;
/**
* Measure synchronous function execution time.
*
* @param operation - Name of the operation
* @param fn - Synchronous function to measure
* @param metadata - Optional metadata
* @returns Result of the function and duration
*
* @example
* import { measureSync } from '@socketsecurity/lib/performance'
*
* const { result, duration } = measureSync('parse-json', () => {
* return JSON.parse(data)
* })
*/
export declare function measureSync<T>(operation: string, fn: () => T, metadata?: Record<string, unknown>): {
result: T;
duration: number;
};
/**
* Get all collected performance metrics.
* Only available when DEBUG=perf is enabled.
*
* @returns Array of performance metrics
*
* @example
* import { getPerformanceMetrics } from '@socketsecurity/lib/performance'
*
* const metrics = getPerformanceMetrics()
* console.log(metrics)
*/
export declare function getPerformanceMetrics(): PerformanceMetrics[];
/**
* Clear all collected performance metrics.
*
* @example
* import { clearPerformanceMetrics } from '@socketsecurity/lib/performance'
*
* clearPerformanceMetrics()
*/
export declare function clearPerformanceMetrics(): void;
/**
* Get performance summary statistics.
*
* @returns Summary of metrics grouped by operation
*
* @example
* import { getPerformanceSummary } from '@socketsecurity/lib/performance'
*
* const summary = getPerformanceSummary()
* console.log(summary)
* // {
* // 'api-call': { count: 5, total: 1234, avg: 246.8, min: 100, max: 500 },
* // 'file-read': { count: 10, total: 50, avg: 5, min: 2, max: 15 }
* // }
*/
export declare function getPerformanceSummary(): Record<string, {
count: number;
total: number;
avg: number;
min: number;
max: number;
}>;
/**
* Print performance summary to console.
* Only prints when DEBUG=perf is enabled.
*
* @example
* import { printPerformanceSummary } from '@socketsecurity/lib/performance'
*
* printPerformanceSummary()
* // Performance Summary:
* // api-call: 5 calls, avg 246.8ms (min 100ms, max 500ms, total 1234ms)
* // file-read: 10 calls, avg 5ms (min 2ms, max 15ms, total 50ms)
*/
export declare function printPerformanceSummary(): void;
/**
* Mark a checkpoint in performance tracking.
* Useful for tracking progress through complex operations.
*
* @param checkpoint - Name of the checkpoint
* @param metadata - Optional metadata
*
* @example
* import { perfCheckpoint } from '@socketsecurity/lib/performance'
*
* perfCheckpoint('start-scan')
* // ... do work ...
* perfCheckpoint('fetch-packages', { count: 50 })
* // ... do work ...
* perfCheckpoint('analyze-issues', { issueCount: 10 })
* perfCheckpoint('end-scan')
*/
export declare function perfCheckpoint(checkpoint: string, metadata?: Record<string, unknown>): void;
/**
* Track memory usage at a specific point.
* Only available when DEBUG=perf is enabled.
*
* @param label - Label for this memory snapshot
* @returns Memory usage in MB
*
* @example
* import { trackMemory } from '@socketsecurity/lib/performance'
*
* const memBefore = trackMemory('before-operation')
* await heavyOperation()
* const memAfter = trackMemory('after-operation')
* console.log(`Memory increased by ${memAfter - memBefore}MB`)
*/
export declare function trackMemory(label: string): number;
/**
* Create a performance report for the current execution.
* Only available when DEBUG=perf is enabled.
*
* @returns Formatted performance report
*
* @example
* import { generatePerformanceReport } from '@socketsecurity/lib/performance'
*
* console.log(generatePerformanceReport())
* // ╔═══════════════════════════════════════════════╗
* // ║ Performance Report ║
* // ╚═══════════════════════════════════════════════╝
* //
* // api-call:
* // Calls: 5
* // Avg: 246.8ms
* // Min: 100ms
* // Max: 500ms
* // Total: 1234ms
*/
export declare function generatePerformanceReport(): string;
export {};