@socketsecurity/lib 2.10.2 → 2.10.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +42 -0
- package/dist/dlx-binary.js +7 -7
- package/dist/dlx-binary.js.map +3 -3
- package/dist/dlx-package.js +7 -7
- package/dist/dlx-package.js.map +3 -3
- package/dist/dlx.js +4 -4
- package/dist/dlx.js.map +3 -3
- package/dist/download-lock.js.map +2 -2
- package/dist/env/socket-cli.d.ts +7 -0
- package/dist/env/socket-cli.js +1 -1
- package/dist/env/socket-cli.js.map +2 -2
- package/dist/external/@socketregistry/packageurl-js.js +2 -5
- package/dist/fs.d.ts +81 -26
- package/dist/fs.js +7 -7
- package/dist/fs.js.map +3 -3
- package/dist/ipc.js.map +2 -2
- package/dist/memoization.d.ts +6 -6
- package/dist/memoization.js.map +1 -1
- package/dist/performance.d.ts +10 -10
- package/dist/performance.js.map +1 -1
- package/dist/spinner.d.ts +8 -8
- package/dist/spinner.js.map +1 -1
- package/dist/suppress-warnings.d.ts +4 -4
- package/dist/suppress-warnings.js.map +1 -1
- package/dist/tables.d.ts +2 -2
- package/dist/tables.js.map +1 -1
- package/package.json +3 -3
package/dist/ipc.js.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/ipc.ts"],
|
|
4
|
-
"sourcesContent": ["/**\n * IPC (Inter-Process Communication) Module\n * ==========================================\n *\n * This module provides secure inter-process communication utilities for Socket CLI\n * and related tools. It replaces environment variable passing with more secure and\n * scalable alternatives.\n *\n * ## Key Features:\n * - File-based stub communication for initial data handoff\n * - Node.js IPC channel support for real-time bidirectional messaging\n * - Automatic cleanup of temporary files\n * - Type-safe message validation with Zod schemas\n * - Timeout handling for reliability\n *\n * ## Use Cases:\n * 1. Passing API tokens between processes without exposing them in env vars\n * 2. Transferring large configuration objects that exceed env var size limits\n * 3. Bidirectional communication between parent and child processes\n * 4. Secure handshake protocols between Socket CLI components\n *\n * ## Security Considerations:\n * - Stub files are created with restricted permissions in OS temp directory\n * - Messages include timestamps for freshness validation\n * - Automatic cleanup prevents sensitive data persistence\n * - Unique IDs prevent message replay attacks\n *\n * @module ipc\n */\n\nimport crypto from 'node:crypto'\nimport { promises as fs } from 'node:fs'\nimport path from 'node:path'\n\nimport { safeDeleteSync } from './fs'\nimport { getOsTmpDir } from './paths'\nimport { z } from './zod'\n\n// Define BufferEncoding type for TypeScript compatibility.\ntype BufferEncoding = globalThis.BufferEncoding\n\n/**\n * Zod Schemas for Runtime Validation\n * ====================================\n * These schemas provide runtime type safety for IPC messages,\n * ensuring data integrity across process boundaries.\n */\n\n/**\n * Base IPC message schema - validates the core message structure.\n * All IPC messages must conform to this schema.\n */\nconst IpcMessageSchema = z.object({\n /** Unique identifier for message tracking and response correlation. */\n id: z.string().min(1),\n /** Unix timestamp for freshness validation and replay prevention. */\n timestamp: z.number().positive(),\n /** Message type identifier for routing and handling. */\n type: z.string().min(1),\n /** Payload data - can be any JSON-serializable value. */\n data: z.unknown(),\n})\n\n/**\n * IPC handshake schema - used for initial connection establishment.\n * The handshake includes version info and authentication tokens.\n * @internal Exported for testing purposes.\n */\nexport const IpcHandshakeSchema = IpcMessageSchema.extend({\n type: z.literal('handshake'),\n data: z.object({\n /** Protocol version for compatibility checking. */\n version: z.string(),\n /** Process ID for identification. */\n pid: z.number().int().positive(),\n /** Optional API token for authentication. */\n apiToken: z.string().optional(),\n /** Application name for multi-app support. */\n appName: z.string(),\n }),\n})\n\n/**\n * IPC stub file schema - validates the structure of stub files.\n * Stub files are used for passing data between processes via filesystem.\n */\nconst IpcStubSchema = z.object({\n /** Process ID that created the stub. */\n pid: z.number().int().positive(),\n /** Creation timestamp for age validation. */\n timestamp: z.number().positive(),\n /** The actual data payload. */\n data: z.unknown(),\n})\n\n/**\n * TypeScript interfaces for IPC communication.\n * These types ensure type consistency across the IPC module.\n */\n\n/**\n * Base IPC message interface.\n * All IPC messages must conform to this structure.\n */\nexport interface IpcMessage<T = unknown> {\n /** Unique identifier for message tracking and response correlation. */\n id: string\n /** Unix timestamp for freshness validation and replay prevention. */\n timestamp: number\n /** Message type identifier for routing and handling. */\n type: string\n /** Payload data - can be any JSON-serializable value. */\n data: T\n}\n\n/**\n * IPC handshake message interface.\n * Used for initial connection establishment.\n */\nexport interface IpcHandshake\n extends IpcMessage<{\n /** Protocol version for compatibility checking. */\n version: string\n /** Process ID for identification. */\n pid: number\n /** Optional API token for authentication. */\n apiToken?: string\n /** Application name for multi-app support. */\n appName: string\n }> {\n type: 'handshake'\n}\n\n/**\n * IPC stub file interface.\n * Represents the structure of stub files used for filesystem-based IPC.\n */\nexport interface IpcStub {\n /** Process ID that created the stub. */\n pid: number\n /** Creation timestamp for age validation. */\n timestamp: number\n /** The actual data payload. */\n data: unknown\n}\n\n/**\n * Options for IPC communication\n */\nexport interface IpcOptions {\n /** Timeout in milliseconds for async operations. */\n timeout?: number\n /** Text encoding for message serialization. */\n encoding?: BufferEncoding\n}\n\n/**\n * Create a unique IPC channel identifier for message correlation.\n *\n * Generates a unique identifier that combines:\n * - A prefix for namespacing (defaults to 'socket')\n * - The current process ID for process identification\n * - A random hex string for uniqueness\n *\n * @param prefix - Optional prefix to namespace the channel ID\n * @returns A unique channel identifier string\n *\n * @example\n * ```typescript\n * const channelId = createIpcChannelId('socket-cli')\n * // Returns: 'socket-cli-12345-a1b2c3d4e5f6g7h8'\n * ```\n */\nexport function createIpcChannelId(prefix = 'socket'): string {\n return `${prefix}-${process.pid}-${crypto.randomBytes(8).toString('hex')}`\n}\n\n/**\n * Get the IPC stub path for a given application.\n *\n * This function generates a unique file path for IPC stub files that are used\n * to pass data between processes. The stub files are stored in a hidden directory\n * within the system's temporary folder.\n *\n * ## Path Structure:\n * - Base: System temp directory (e.g., /tmp on Unix, %TEMP% on Windows)\n * - Directory: `.socket-ipc/{appName}/`\n * - Filename: `stub-{pid}.json`\n *\n * ## Security Features:\n * - Files are isolated per application via appName parameter\n * - Process ID in filename prevents collisions between concurrent processes\n * - Temporary directory location ensures automatic cleanup on system restart\n *\n * @param appName - The application identifier (e.g., 'socket-cli', 'socket-dlx')\n * @returns Full path to the IPC stub file\n *\n * @example\n * ```typescript\n * const stubPath = getIpcStubPath('socket-cli')\n * // Returns: '/tmp/.socket-ipc/socket-cli/stub-12345.json' (Unix)\n * // Returns: 'C:\\\\Users\\\\Name\\\\AppData\\\\Local\\\\Temp\\\\.socket-ipc\\\\socket-cli\\\\stub-12345.json' (Windows)\n * ```\n *\n * @used Currently used by socket-cli for self-update and inter-process communication\n */\nexport function getIpcStubPath(appName: string): string {\n // Get the system's temporary directory - this is platform-specific.\n const tempDir = getOsTmpDir()\n\n // Create a hidden directory structure for Socket IPC files.\n // The dot prefix makes it hidden on Unix-like systems.\n const stubDir = path.join(tempDir, '.socket-ipc', appName)\n\n // Generate filename with process ID to ensure uniqueness.\n // The PID prevents conflicts when multiple processes run simultaneously.\n return path.join(stubDir, `stub-${process.pid}.json`)\n}\n\n/**\n * Ensure IPC directory exists for stub file creation.\n *\n * This helper function creates the directory structure needed for IPC stub files.\n * It's called before writing stub files to ensure the parent directories exist.\n *\n * @param filePath - Full path to the file that needs its directory created\n * @returns Promise that resolves when directory is created\n *\n * @internal Helper function used by writeIpcStub\n */\nasync function ensureIpcDirectory(filePath: string): Promise<void> {\n const dir = path.dirname(filePath)\n // Create directory recursively if it doesn't exist.\n await fs.mkdir(dir, { recursive: true })\n}\n\n/**\n * Write IPC data to a stub file for inter-process data transfer.\n *\n * This function creates a stub file containing data that needs to be passed\n * between processes. The stub file includes metadata like process ID and\n * timestamp for validation.\n *\n * ## File Structure:\n * ```json\n * {\n * \"pid\": 12345,\n * \"timestamp\": 1699564234567,\n * \"data\": { ... }\n * }\n * ```\n *\n * ## Use Cases:\n * - Passing API tokens to child processes\n * - Transferring configuration between Socket CLI components\n * - Sharing large data that exceeds environment variable limits\n *\n * @param appName - The application identifier\n * @param data - The data to write to the stub file\n * @returns Promise resolving to the stub file path\n *\n * @example\n * ```typescript\n * const stubPath = await writeIpcStub('socket-cli', {\n * apiToken: 'secret-token',\n * config: { ... }\n * })\n * // Pass stubPath to child process for reading\n * ```\n */\nexport async function writeIpcStub(\n appName: string,\n data: unknown,\n): Promise<string> {\n const stubPath = getIpcStubPath(appName)\n await ensureIpcDirectory(stubPath)\n\n // Create stub data with validation metadata.\n const ipcData: IpcStub = {\n data,\n pid: process.pid,\n timestamp: Date.now(),\n }\n\n // Validate data structure with Zod schema.\n const validated = IpcStubSchema.parse(ipcData)\n\n // Write with pretty printing for debugging.\n await fs.writeFile(stubPath, JSON.stringify(validated, null, 2), 'utf8')\n return stubPath\n}\n\n/**\n * Read IPC data from a stub file with automatic cleanup.\n *\n * This function reads data from an IPC stub file and validates its freshness.\n * Stale files (older than 5 minutes) are automatically cleaned up to prevent\n * accumulation of temporary files.\n *\n * ## Validation Steps:\n * 1. Read and parse JSON file\n * 2. Validate structure with Zod schema\n * 3. Check timestamp freshness\n * 4. Clean up if stale\n * 5. Return data if valid\n *\n * @param stubPath - Path to the stub file to read\n * @returns Promise resolving to the data or null if invalid/stale\n *\n * @example\n * ```typescript\n * const data = await readIpcStub('/tmp/.socket-ipc/socket-cli/stub-12345.json')\n * if (data) {\n * console.log('Received:', data)\n * }\n * ```\n *\n * @unused Reserved for future implementation\n */\nexport async function readIpcStub(stubPath: string): Promise<unknown> {\n try {\n const content = await fs.readFile(stubPath, 'utf8')\n const parsed = JSON.parse(content)\n // Validate structure with Zod schema.\n const validated = IpcStubSchema.parse(parsed)\n // Check age for freshness validation.\n const ageMs = Date.now() - validated.timestamp\n // 5 minutes.\n const maxAgeMs = 5 * 60 * 1000\n if (ageMs > maxAgeMs) {\n // Clean up stale file. IPC stubs are always in tmpdir, so use force: true.\n try {\n safeDeleteSync(stubPath, { force: true })\n } catch {\n // Ignore deletion errors\n }\n return null\n }\n return validated.data\n } catch {\n // Return null for any errors (file not found, invalid JSON, validation failure).\n return null\n }\n}\n\n/**\n * Clean up IPC stub files for an application.\n *\n * This maintenance function removes stale IPC stub files to prevent\n * accumulation in the temporary directory. It's designed to be called\n * periodically or on application startup.\n *\n * ## Cleanup Rules:\n * - Files older than 5 minutes are removed (checked via both filesystem mtime and JSON timestamp)\n * - Only stub files (stub-*.json) are processed\n * - Errors are silently ignored (best-effort cleanup)\n *\n * @param appName - The application identifier\n * @returns Promise that resolves when cleanup is complete\n *\n * @example\n * ```typescript\n * // Clean up on application startup\n * await cleanupIpcStubs('socket-cli')\n * ```\n *\n * @unused Reserved for future implementation\n */\nexport async function cleanupIpcStubs(appName: string): Promise<void> {\n const tempDir = getOsTmpDir()\n const stubDir = path.join(tempDir, '.socket-ipc', appName)\n try {\n const files = await fs.readdir(stubDir)\n const now = Date.now()\n // 5 minutes.\n const maxAgeMs = 5 * 60 * 1000\n // Process each file in parallel for efficiency.\n await Promise.all(\n files.map(async file => {\n if (file.startsWith('stub-') && file.endsWith('.json')) {\n const filePath = path.join(stubDir, file)\n try {\n // Check both filesystem mtime and JSON timestamp for more reliable detection\n const stats = await fs.stat(filePath)\n const mtimeAge = now - stats.mtimeMs\n let isStale = mtimeAge > maxAgeMs\n\n // Always check the timestamp inside the JSON file for accuracy\n // This is more reliable than filesystem mtime in some environments\n try {\n const content = await fs.readFile(filePath, 'utf8')\n const parsed = JSON.parse(content)\n const validated = IpcStubSchema.parse(parsed)\n const contentAge = now - validated.timestamp\n // File is stale if EITHER check indicates staleness\n isStale = isStale || contentAge > maxAgeMs\n } catch {\n // If we can't read/parse the file, rely on mtime check\n }\n\n if (isStale) {\n // IPC stubs are always in tmpdir, so we can use force: true to skip path checks\n safeDeleteSync(filePath, { force: true })\n }\n } catch {\n // Ignore errors for individual files.\n }\n }\n }),\n )\n } catch {\n // Directory might not exist, that's ok.\n }\n}\n\n/**\n * Send data through Node.js IPC channel.\n *\n * This function sends structured messages through the Node.js IPC channel\n * when available. The IPC channel must be established with stdio: ['pipe', 'pipe', 'pipe', 'ipc'].\n *\n * ## Requirements:\n * - Process must have been spawned with IPC channel enabled\n * - Message must be serializable to JSON\n * - Process.send() must be available\n *\n * @param process - The process object with IPC channel\n * @param message - The IPC message to send\n * @returns true if message was sent, false otherwise\n *\n * @example\n * ```typescript\n * const message = createIpcMessage('handshake', { version: '1.0.0' })\n * const sent = sendIpc(childProcess, message)\n * ```\n *\n * @unused Reserved for bidirectional communication implementation\n */\nexport function sendIpc(\n process: NodeJS.Process | unknown,\n message: IpcMessage,\n): boolean {\n if (\n process &&\n typeof process === 'object' &&\n 'send' in process &&\n typeof process.send === 'function'\n ) {\n try {\n // Validate message structure before sending.\n const validated = IpcMessageSchema.parse(message)\n return process.send(validated)\n } catch {\n return false\n }\n }\n return false\n}\n\n/**\n * Receive data through Node.js IPC channel.\n *\n * Sets up a listener for IPC messages with automatic validation and parsing.\n * Returns a cleanup function to remove the listener when no longer needed.\n *\n * ## Message Flow:\n * 1. Receive raw message from IPC channel\n * 2. Validate with parseIpcMessage\n * 3. Call handler if valid\n * 4. Ignore invalid messages\n *\n * @param handler - Function to call with valid IPC messages\n * @returns Cleanup function to remove the listener\n *\n * @example\n * ```typescript\n * const cleanup = onIpc((message) => {\n * console.log('Received:', message.type, message.data)\n * })\n * // Later...\n * cleanup() // Remove listener\n * ```\n *\n * @unused Reserved for bidirectional communication\n */\nexport function onIpc(handler: (message: IpcMessage) => void): () => void {\n const listener = (message: unknown) => {\n const parsed = parseIpcMessage(message)\n if (parsed) {\n handler(parsed)\n }\n }\n process.on('message', listener)\n // Return cleanup function for proper resource management.\n return () => {\n process.off('message', listener)\n }\n}\n\n/**\n * Create a promise that resolves when a specific IPC message is received.\n *\n * This utility function provides async/await support for IPC communication,\n * allowing you to wait for specific message types with timeout support.\n *\n * ## Features:\n * - Automatic timeout handling\n * - Type-safe message data\n * - Resource cleanup on completion\n * - Promise-based API\n *\n * @param messageType - The message type to wait for\n * @param options - Options including timeout configuration\n * @returns Promise resolving to the message data\n *\n * @example\n * ```typescript\n * try {\n * const response = await waitForIpc<ConfigData>('config-response', {\n * timeout: 5000 // 5 seconds\n * })\n * console.log('Config received:', response)\n * } catch (error) {\n * console.error('Timeout waiting for config')\n * }\n * ```\n *\n * @unused Reserved for request-response pattern implementation\n */\nexport function waitForIpc<T = unknown>(\n messageType: string,\n options: IpcOptions = {},\n): Promise<T> {\n const { timeout = 30_000 } = options\n return new Promise((resolve, reject) => {\n let cleanup: (() => void) | null = null\n let timeoutId: NodeJS.Timeout | null = null\n const handleTimeout = () => {\n if (cleanup) {\n cleanup()\n }\n reject(new Error(`IPC timeout waiting for message type: ${messageType}`))\n }\n const handleMessage = (message: IpcMessage) => {\n if (message.type === messageType) {\n if (timeoutId) {\n clearTimeout(timeoutId)\n }\n if (cleanup) {\n cleanup()\n }\n resolve(message.data as T)\n }\n }\n cleanup = onIpc(handleMessage)\n if (timeout > 0) {\n timeoutId = setTimeout(handleTimeout, timeout)\n }\n })\n}\n\n/**\n * Create an IPC message with proper structure and metadata.\n *\n * This factory function creates properly structured IPC messages with:\n * - Unique ID for tracking\n * - Timestamp for freshness\n * - Type for routing\n * - Data payload\n *\n * @param type - The message type identifier\n * @param data - The message payload\n * @returns A properly structured IPC message\n *\n * @example\n * ```typescript\n * const handshake = createIpcMessage('handshake', {\n * version: '1.0.0',\n * pid: process.pid,\n * appName: 'socket-cli'\n * })\n * ```\n *\n * @unused Reserved for future message creation needs\n */\nexport function createIpcMessage<T = unknown>(\n type: string,\n data: T,\n): IpcMessage<T> {\n return {\n id: crypto.randomBytes(16).toString('hex'),\n timestamp: Date.now(),\n type,\n data,\n }\n}\n\n/**\n * Check if process has IPC channel available.\n *\n * This utility checks whether a process object has the necessary\n * properties for IPC communication. Used to determine if IPC\n * messaging is possible before attempting to send.\n *\n * @param process - The process object to check\n * @returns true if IPC is available, false otherwise\n *\n * @example\n * ```typescript\n * if (hasIpcChannel(childProcess)) {\n * sendIpc(childProcess, message)\n * } else {\n * // Fall back to alternative communication method\n * }\n * ```\n *\n * @unused Reserved for IPC availability detection\n */\nexport function hasIpcChannel(process: unknown): boolean {\n return Boolean(\n process &&\n typeof process === 'object' &&\n 'send' in process &&\n typeof process.send === 'function' &&\n 'channel' in process &&\n process.channel !== undefined,\n )\n}\n\n/**\n * Safely parse and validate IPC messages.\n *\n * This function performs runtime validation of incoming messages\n * to ensure they conform to the IPC message structure. It uses\n * Zod schemas for robust validation.\n *\n * ## Validation Steps:\n * 1. Check if message is an object\n * 2. Validate required fields exist\n * 3. Validate field types\n * 4. Return typed message or null\n *\n * @param message - The raw message to parse\n * @returns Parsed IPC message or null if invalid\n *\n * @example\n * ```typescript\n * const parsed = parseIpcMessage(rawMessage)\n * if (parsed) {\n * handleMessage(parsed)\n * }\n * ```\n *\n * @unused Reserved for message validation needs\n */\nexport function parseIpcMessage(message: unknown): IpcMessage | null {\n try {\n // Use Zod schema for comprehensive validation.\n const validated = IpcMessageSchema.parse(message)\n return validated as IpcMessage\n } catch {\n // Return null for any validation failure.\n return null\n }\n}\n"],
|
|
5
|
-
"mappings": ";6iBAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,wBAAAE,EAAA,oBAAAC,EAAA,uBAAAC,EAAA,qBAAAC,EAAA,mBAAAC,EAAA,kBAAAC,EAAA,UAAAC,EAAA,oBAAAC,EAAA,gBAAAC,EAAA,YAAAC,EAAA,eAAAC,EAAA,iBAAAC,IAAA,eAAAC,EAAAd,GA8BA,IAAAe,EAAmB,
|
|
4
|
+
"sourcesContent": ["/**\n * IPC (Inter-Process Communication) Module\n * ==========================================\n *\n * This module provides secure inter-process communication utilities for Socket CLI\n * and related tools. It replaces environment variable passing with more secure and\n * scalable alternatives.\n *\n * ## Key Features:\n * - File-based stub communication for initial data handoff\n * - Node.js IPC channel support for real-time bidirectional messaging\n * - Automatic cleanup of temporary files\n * - Type-safe message validation with Zod schemas\n * - Timeout handling for reliability\n *\n * ## Use Cases:\n * 1. Passing API tokens between processes without exposing them in env vars\n * 2. Transferring large configuration objects that exceed env var size limits\n * 3. Bidirectional communication between parent and child processes\n * 4. Secure handshake protocols between Socket CLI components\n *\n * ## Security Considerations:\n * - Stub files are created with restricted permissions in OS temp directory\n * - Messages include timestamps for freshness validation\n * - Automatic cleanup prevents sensitive data persistence\n * - Unique IDs prevent message replay attacks\n *\n * @module ipc\n */\n\nimport crypto from 'node:crypto'\n\nimport { promises as fs } from 'node:fs'\n\nimport path from 'node:path'\n\nimport { safeDeleteSync } from './fs'\nimport { getOsTmpDir } from './paths'\nimport { z } from './zod'\n\n// Define BufferEncoding type for TypeScript compatibility.\ntype BufferEncoding = globalThis.BufferEncoding\n\n/**\n * Zod Schemas for Runtime Validation\n * ====================================\n * These schemas provide runtime type safety for IPC messages,\n * ensuring data integrity across process boundaries.\n */\n\n/**\n * Base IPC message schema - validates the core message structure.\n * All IPC messages must conform to this schema.\n */\nconst IpcMessageSchema = z.object({\n /** Unique identifier for message tracking and response correlation. */\n id: z.string().min(1),\n /** Unix timestamp for freshness validation and replay prevention. */\n timestamp: z.number().positive(),\n /** Message type identifier for routing and handling. */\n type: z.string().min(1),\n /** Payload data - can be any JSON-serializable value. */\n data: z.unknown(),\n})\n\n/**\n * IPC handshake schema - used for initial connection establishment.\n * The handshake includes version info and authentication tokens.\n * @internal Exported for testing purposes.\n */\nexport const IpcHandshakeSchema = IpcMessageSchema.extend({\n type: z.literal('handshake'),\n data: z.object({\n /** Protocol version for compatibility checking. */\n version: z.string(),\n /** Process ID for identification. */\n pid: z.number().int().positive(),\n /** Optional API token for authentication. */\n apiToken: z.string().optional(),\n /** Application name for multi-app support. */\n appName: z.string(),\n }),\n})\n\n/**\n * IPC stub file schema - validates the structure of stub files.\n * Stub files are used for passing data between processes via filesystem.\n */\nconst IpcStubSchema = z.object({\n /** Process ID that created the stub. */\n pid: z.number().int().positive(),\n /** Creation timestamp for age validation. */\n timestamp: z.number().positive(),\n /** The actual data payload. */\n data: z.unknown(),\n})\n\n/**\n * TypeScript interfaces for IPC communication.\n * These types ensure type consistency across the IPC module.\n */\n\n/**\n * Base IPC message interface.\n * All IPC messages must conform to this structure.\n */\nexport interface IpcMessage<T = unknown> {\n /** Unique identifier for message tracking and response correlation. */\n id: string\n /** Unix timestamp for freshness validation and replay prevention. */\n timestamp: number\n /** Message type identifier for routing and handling. */\n type: string\n /** Payload data - can be any JSON-serializable value. */\n data: T\n}\n\n/**\n * IPC handshake message interface.\n * Used for initial connection establishment.\n */\nexport interface IpcHandshake\n extends IpcMessage<{\n /** Protocol version for compatibility checking. */\n version: string\n /** Process ID for identification. */\n pid: number\n /** Optional API token for authentication. */\n apiToken?: string\n /** Application name for multi-app support. */\n appName: string\n }> {\n type: 'handshake'\n}\n\n/**\n * IPC stub file interface.\n * Represents the structure of stub files used for filesystem-based IPC.\n */\nexport interface IpcStub {\n /** Process ID that created the stub. */\n pid: number\n /** Creation timestamp for age validation. */\n timestamp: number\n /** The actual data payload. */\n data: unknown\n}\n\n/**\n * Options for IPC communication\n */\nexport interface IpcOptions {\n /** Timeout in milliseconds for async operations. */\n timeout?: number\n /** Text encoding for message serialization. */\n encoding?: BufferEncoding\n}\n\n/**\n * Create a unique IPC channel identifier for message correlation.\n *\n * Generates a unique identifier that combines:\n * - A prefix for namespacing (defaults to 'socket')\n * - The current process ID for process identification\n * - A random hex string for uniqueness\n *\n * @param prefix - Optional prefix to namespace the channel ID\n * @returns A unique channel identifier string\n *\n * @example\n * ```typescript\n * const channelId = createIpcChannelId('socket-cli')\n * // Returns: 'socket-cli-12345-a1b2c3d4e5f6g7h8'\n * ```\n */\nexport function createIpcChannelId(prefix = 'socket'): string {\n return `${prefix}-${process.pid}-${crypto.randomBytes(8).toString('hex')}`\n}\n\n/**\n * Get the IPC stub path for a given application.\n *\n * This function generates a unique file path for IPC stub files that are used\n * to pass data between processes. The stub files are stored in a hidden directory\n * within the system's temporary folder.\n *\n * ## Path Structure:\n * - Base: System temp directory (e.g., /tmp on Unix, %TEMP% on Windows)\n * - Directory: `.socket-ipc/{appName}/`\n * - Filename: `stub-{pid}.json`\n *\n * ## Security Features:\n * - Files are isolated per application via appName parameter\n * - Process ID in filename prevents collisions between concurrent processes\n * - Temporary directory location ensures automatic cleanup on system restart\n *\n * @param appName - The application identifier (e.g., 'socket-cli', 'socket-dlx')\n * @returns Full path to the IPC stub file\n *\n * @example\n * ```typescript\n * const stubPath = getIpcStubPath('socket-cli')\n * // Returns: '/tmp/.socket-ipc/socket-cli/stub-12345.json' (Unix)\n * // Returns: 'C:\\\\Users\\\\Name\\\\AppData\\\\Local\\\\Temp\\\\.socket-ipc\\\\socket-cli\\\\stub-12345.json' (Windows)\n * ```\n *\n * @used Currently used by socket-cli for self-update and inter-process communication\n */\nexport function getIpcStubPath(appName: string): string {\n // Get the system's temporary directory - this is platform-specific.\n const tempDir = getOsTmpDir()\n\n // Create a hidden directory structure for Socket IPC files.\n // The dot prefix makes it hidden on Unix-like systems.\n const stubDir = path.join(tempDir, '.socket-ipc', appName)\n\n // Generate filename with process ID to ensure uniqueness.\n // The PID prevents conflicts when multiple processes run simultaneously.\n return path.join(stubDir, `stub-${process.pid}.json`)\n}\n\n/**\n * Ensure IPC directory exists for stub file creation.\n *\n * This helper function creates the directory structure needed for IPC stub files.\n * It's called before writing stub files to ensure the parent directories exist.\n *\n * @param filePath - Full path to the file that needs its directory created\n * @returns Promise that resolves when directory is created\n *\n * @internal Helper function used by writeIpcStub\n */\nasync function ensureIpcDirectory(filePath: string): Promise<void> {\n const dir = path.dirname(filePath)\n // Create directory recursively if it doesn't exist.\n await fs.mkdir(dir, { recursive: true })\n}\n\n/**\n * Write IPC data to a stub file for inter-process data transfer.\n *\n * This function creates a stub file containing data that needs to be passed\n * between processes. The stub file includes metadata like process ID and\n * timestamp for validation.\n *\n * ## File Structure:\n * ```json\n * {\n * \"pid\": 12345,\n * \"timestamp\": 1699564234567,\n * \"data\": { ... }\n * }\n * ```\n *\n * ## Use Cases:\n * - Passing API tokens to child processes\n * - Transferring configuration between Socket CLI components\n * - Sharing large data that exceeds environment variable limits\n *\n * @param appName - The application identifier\n * @param data - The data to write to the stub file\n * @returns Promise resolving to the stub file path\n *\n * @example\n * ```typescript\n * const stubPath = await writeIpcStub('socket-cli', {\n * apiToken: 'secret-token',\n * config: { ... }\n * })\n * // Pass stubPath to child process for reading\n * ```\n */\nexport async function writeIpcStub(\n appName: string,\n data: unknown,\n): Promise<string> {\n const stubPath = getIpcStubPath(appName)\n await ensureIpcDirectory(stubPath)\n\n // Create stub data with validation metadata.\n const ipcData: IpcStub = {\n data,\n pid: process.pid,\n timestamp: Date.now(),\n }\n\n // Validate data structure with Zod schema.\n const validated = IpcStubSchema.parse(ipcData)\n\n // Write with pretty printing for debugging.\n await fs.writeFile(stubPath, JSON.stringify(validated, null, 2), 'utf8')\n return stubPath\n}\n\n/**\n * Read IPC data from a stub file with automatic cleanup.\n *\n * This function reads data from an IPC stub file and validates its freshness.\n * Stale files (older than 5 minutes) are automatically cleaned up to prevent\n * accumulation of temporary files.\n *\n * ## Validation Steps:\n * 1. Read and parse JSON file\n * 2. Validate structure with Zod schema\n * 3. Check timestamp freshness\n * 4. Clean up if stale\n * 5. Return data if valid\n *\n * @param stubPath - Path to the stub file to read\n * @returns Promise resolving to the data or null if invalid/stale\n *\n * @example\n * ```typescript\n * const data = await readIpcStub('/tmp/.socket-ipc/socket-cli/stub-12345.json')\n * if (data) {\n * console.log('Received:', data)\n * }\n * ```\n *\n * @unused Reserved for future implementation\n */\nexport async function readIpcStub(stubPath: string): Promise<unknown> {\n try {\n const content = await fs.readFile(stubPath, 'utf8')\n const parsed = JSON.parse(content)\n // Validate structure with Zod schema.\n const validated = IpcStubSchema.parse(parsed)\n // Check age for freshness validation.\n const ageMs = Date.now() - validated.timestamp\n // 5 minutes.\n const maxAgeMs = 5 * 60 * 1000\n if (ageMs > maxAgeMs) {\n // Clean up stale file. IPC stubs are always in tmpdir, so use force: true.\n try {\n safeDeleteSync(stubPath, { force: true })\n } catch {\n // Ignore deletion errors\n }\n return null\n }\n return validated.data\n } catch {\n // Return null for any errors (file not found, invalid JSON, validation failure).\n return null\n }\n}\n\n/**\n * Clean up IPC stub files for an application.\n *\n * This maintenance function removes stale IPC stub files to prevent\n * accumulation in the temporary directory. It's designed to be called\n * periodically or on application startup.\n *\n * ## Cleanup Rules:\n * - Files older than 5 minutes are removed (checked via both filesystem mtime and JSON timestamp)\n * - Only stub files (stub-*.json) are processed\n * - Errors are silently ignored (best-effort cleanup)\n *\n * @param appName - The application identifier\n * @returns Promise that resolves when cleanup is complete\n *\n * @example\n * ```typescript\n * // Clean up on application startup\n * await cleanupIpcStubs('socket-cli')\n * ```\n *\n * @unused Reserved for future implementation\n */\nexport async function cleanupIpcStubs(appName: string): Promise<void> {\n const tempDir = getOsTmpDir()\n const stubDir = path.join(tempDir, '.socket-ipc', appName)\n try {\n const files = await fs.readdir(stubDir)\n const now = Date.now()\n // 5 minutes.\n const maxAgeMs = 5 * 60 * 1000\n // Process each file in parallel for efficiency.\n await Promise.all(\n files.map(async file => {\n if (file.startsWith('stub-') && file.endsWith('.json')) {\n const filePath = path.join(stubDir, file)\n try {\n // Check both filesystem mtime and JSON timestamp for more reliable detection\n const stats = await fs.stat(filePath)\n const mtimeAge = now - stats.mtimeMs\n let isStale = mtimeAge > maxAgeMs\n\n // Always check the timestamp inside the JSON file for accuracy\n // This is more reliable than filesystem mtime in some environments\n try {\n const content = await fs.readFile(filePath, 'utf8')\n const parsed = JSON.parse(content)\n const validated = IpcStubSchema.parse(parsed)\n const contentAge = now - validated.timestamp\n // File is stale if EITHER check indicates staleness\n isStale = isStale || contentAge > maxAgeMs\n } catch {\n // If we can't read/parse the file, rely on mtime check\n }\n\n if (isStale) {\n // IPC stubs are always in tmpdir, so we can use force: true to skip path checks\n safeDeleteSync(filePath, { force: true })\n }\n } catch {\n // Ignore errors for individual files.\n }\n }\n }),\n )\n } catch {\n // Directory might not exist, that's ok.\n }\n}\n\n/**\n * Send data through Node.js IPC channel.\n *\n * This function sends structured messages through the Node.js IPC channel\n * when available. The IPC channel must be established with stdio: ['pipe', 'pipe', 'pipe', 'ipc'].\n *\n * ## Requirements:\n * - Process must have been spawned with IPC channel enabled\n * - Message must be serializable to JSON\n * - Process.send() must be available\n *\n * @param process - The process object with IPC channel\n * @param message - The IPC message to send\n * @returns true if message was sent, false otherwise\n *\n * @example\n * ```typescript\n * const message = createIpcMessage('handshake', { version: '1.0.0' })\n * const sent = sendIpc(childProcess, message)\n * ```\n *\n * @unused Reserved for bidirectional communication implementation\n */\nexport function sendIpc(\n process: NodeJS.Process | unknown,\n message: IpcMessage,\n): boolean {\n if (\n process &&\n typeof process === 'object' &&\n 'send' in process &&\n typeof process.send === 'function'\n ) {\n try {\n // Validate message structure before sending.\n const validated = IpcMessageSchema.parse(message)\n return process.send(validated)\n } catch {\n return false\n }\n }\n return false\n}\n\n/**\n * Receive data through Node.js IPC channel.\n *\n * Sets up a listener for IPC messages with automatic validation and parsing.\n * Returns a cleanup function to remove the listener when no longer needed.\n *\n * ## Message Flow:\n * 1. Receive raw message from IPC channel\n * 2. Validate with parseIpcMessage\n * 3. Call handler if valid\n * 4. Ignore invalid messages\n *\n * @param handler - Function to call with valid IPC messages\n * @returns Cleanup function to remove the listener\n *\n * @example\n * ```typescript\n * const cleanup = onIpc((message) => {\n * console.log('Received:', message.type, message.data)\n * })\n * // Later...\n * cleanup() // Remove listener\n * ```\n *\n * @unused Reserved for bidirectional communication\n */\nexport function onIpc(handler: (message: IpcMessage) => void): () => void {\n const listener = (message: unknown) => {\n const parsed = parseIpcMessage(message)\n if (parsed) {\n handler(parsed)\n }\n }\n process.on('message', listener)\n // Return cleanup function for proper resource management.\n return () => {\n process.off('message', listener)\n }\n}\n\n/**\n * Create a promise that resolves when a specific IPC message is received.\n *\n * This utility function provides async/await support for IPC communication,\n * allowing you to wait for specific message types with timeout support.\n *\n * ## Features:\n * - Automatic timeout handling\n * - Type-safe message data\n * - Resource cleanup on completion\n * - Promise-based API\n *\n * @param messageType - The message type to wait for\n * @param options - Options including timeout configuration\n * @returns Promise resolving to the message data\n *\n * @example\n * ```typescript\n * try {\n * const response = await waitForIpc<ConfigData>('config-response', {\n * timeout: 5000 // 5 seconds\n * })\n * console.log('Config received:', response)\n * } catch (error) {\n * console.error('Timeout waiting for config')\n * }\n * ```\n *\n * @unused Reserved for request-response pattern implementation\n */\nexport function waitForIpc<T = unknown>(\n messageType: string,\n options: IpcOptions = {},\n): Promise<T> {\n const { timeout = 30_000 } = options\n return new Promise((resolve, reject) => {\n let cleanup: (() => void) | null = null\n let timeoutId: NodeJS.Timeout | null = null\n const handleTimeout = () => {\n if (cleanup) {\n cleanup()\n }\n reject(new Error(`IPC timeout waiting for message type: ${messageType}`))\n }\n const handleMessage = (message: IpcMessage) => {\n if (message.type === messageType) {\n if (timeoutId) {\n clearTimeout(timeoutId)\n }\n if (cleanup) {\n cleanup()\n }\n resolve(message.data as T)\n }\n }\n cleanup = onIpc(handleMessage)\n if (timeout > 0) {\n timeoutId = setTimeout(handleTimeout, timeout)\n }\n })\n}\n\n/**\n * Create an IPC message with proper structure and metadata.\n *\n * This factory function creates properly structured IPC messages with:\n * - Unique ID for tracking\n * - Timestamp for freshness\n * - Type for routing\n * - Data payload\n *\n * @param type - The message type identifier\n * @param data - The message payload\n * @returns A properly structured IPC message\n *\n * @example\n * ```typescript\n * const handshake = createIpcMessage('handshake', {\n * version: '1.0.0',\n * pid: process.pid,\n * appName: 'socket-cli'\n * })\n * ```\n *\n * @unused Reserved for future message creation needs\n */\nexport function createIpcMessage<T = unknown>(\n type: string,\n data: T,\n): IpcMessage<T> {\n return {\n id: crypto.randomBytes(16).toString('hex'),\n timestamp: Date.now(),\n type,\n data,\n }\n}\n\n/**\n * Check if process has IPC channel available.\n *\n * This utility checks whether a process object has the necessary\n * properties for IPC communication. Used to determine if IPC\n * messaging is possible before attempting to send.\n *\n * @param process - The process object to check\n * @returns true if IPC is available, false otherwise\n *\n * @example\n * ```typescript\n * if (hasIpcChannel(childProcess)) {\n * sendIpc(childProcess, message)\n * } else {\n * // Fall back to alternative communication method\n * }\n * ```\n *\n * @unused Reserved for IPC availability detection\n */\nexport function hasIpcChannel(process: unknown): boolean {\n return Boolean(\n process &&\n typeof process === 'object' &&\n 'send' in process &&\n typeof process.send === 'function' &&\n 'channel' in process &&\n process.channel !== undefined,\n )\n}\n\n/**\n * Safely parse and validate IPC messages.\n *\n * This function performs runtime validation of incoming messages\n * to ensure they conform to the IPC message structure. It uses\n * Zod schemas for robust validation.\n *\n * ## Validation Steps:\n * 1. Check if message is an object\n * 2. Validate required fields exist\n * 3. Validate field types\n * 4. Return typed message or null\n *\n * @param message - The raw message to parse\n * @returns Parsed IPC message or null if invalid\n *\n * @example\n * ```typescript\n * const parsed = parseIpcMessage(rawMessage)\n * if (parsed) {\n * handleMessage(parsed)\n * }\n * ```\n *\n * @unused Reserved for message validation needs\n */\nexport function parseIpcMessage(message: unknown): IpcMessage | null {\n try {\n // Use Zod schema for comprehensive validation.\n const validated = IpcMessageSchema.parse(message)\n return validated as IpcMessage\n } catch {\n // Return null for any validation failure.\n return null\n }\n}\n"],
|
|
5
|
+
"mappings": ";6iBAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,wBAAAE,EAAA,oBAAAC,EAAA,uBAAAC,EAAA,qBAAAC,EAAA,mBAAAC,EAAA,kBAAAC,EAAA,UAAAC,EAAA,oBAAAC,EAAA,gBAAAC,EAAA,YAAAC,EAAA,eAAAC,EAAA,iBAAAC,IAAA,eAAAC,EAAAd,GA8BA,IAAAe,EAAmB,0BAEnBC,EAA+B,mBAE/BC,EAAiB,wBAEjBC,EAA+B,gBAC/BC,EAA4B,mBAC5BC,EAAkB,iBAgBlB,MAAMC,EAAmB,IAAE,OAAO,CAEhC,GAAI,IAAE,OAAO,EAAE,IAAI,CAAC,EAEpB,UAAW,IAAE,OAAO,EAAE,SAAS,EAE/B,KAAM,IAAE,OAAO,EAAE,IAAI,CAAC,EAEtB,KAAM,IAAE,QAAQ,CAClB,CAAC,EAOYnB,EAAqB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AM2B,CAAO,CAElD,MAAQ,CAEN,OAAO,IACT,CACF",
|
|
6
6
|
"names": ["ipc_exports", "__export", "IpcHandshakeSchema", "cleanupIpcStubs", "createIpcChannelId", "createIpcMessage", "getIpcStubPath", "hasIpcChannel", "onIpc", "parseIpcMessage", "readIpcStub", "sendIpc", "waitForIpc", "writeIpcStub", "__toCommonJS", "import_node_crypto", "import_node_fs", "import_node_path", "import_fs", "import_paths", "import_zod", "IpcMessageSchema", "IpcStubSchema", "prefix", "crypto", "appName", "tempDir", "stubDir", "path", "ensureIpcDirectory", "filePath", "dir", "fs", "data", "stubPath", "ipcData", "validated", "content", "parsed", "ageMs", "maxAgeMs", "files", "now", "file", "stats", "isStale", "contentAge", "process", "message", "handler", "listener", "messageType", "options", "timeout", "resolve", "reject", "cleanup", "timeoutId", "handleTimeout", "type"]
|
|
7
7
|
}
|
package/dist/memoization.d.ts
CHANGED
|
@@ -24,7 +24,7 @@ type MemoizeOptions<Args extends unknown[], _Result = unknown> = {
|
|
|
24
24
|
* @returns Memoized version of the function
|
|
25
25
|
*
|
|
26
26
|
* @example
|
|
27
|
-
* import { memoize } from '@socketsecurity/
|
|
27
|
+
* import { memoize } from '@socketsecurity/lib/memoization'
|
|
28
28
|
*
|
|
29
29
|
* const expensiveOperation = memoize((n: number) => {
|
|
30
30
|
* // Heavy computation
|
|
@@ -44,7 +44,7 @@ export declare function memoize<Args extends unknown[], Result>(fn: (...args: Ar
|
|
|
44
44
|
* @returns Memoized version of the async function
|
|
45
45
|
*
|
|
46
46
|
* @example
|
|
47
|
-
* import { memoizeAsync } from '@socketsecurity/
|
|
47
|
+
* import { memoizeAsync } from '@socketsecurity/lib/memoization'
|
|
48
48
|
*
|
|
49
49
|
* const fetchUser = memoizeAsync(async (id: string) => {
|
|
50
50
|
* const response = await fetch(`/api/users/${id}`)
|
|
@@ -65,7 +65,7 @@ export declare function memoizeAsync<Args extends unknown[], Result>(fn: (...arg
|
|
|
65
65
|
* @returns Modified descriptor with memoized method
|
|
66
66
|
*
|
|
67
67
|
* @example
|
|
68
|
-
* import { Memoize } from '@socketsecurity/
|
|
68
|
+
* import { Memoize } from '@socketsecurity/lib/memoization'
|
|
69
69
|
*
|
|
70
70
|
* class Calculator {
|
|
71
71
|
* @Memoize()
|
|
@@ -90,7 +90,7 @@ export declare function clearAllMemoizationCaches(): void;
|
|
|
90
90
|
* @returns Memoized version using WeakMap
|
|
91
91
|
*
|
|
92
92
|
* @example
|
|
93
|
-
* import { memoizeWeak } from '@socketsecurity/
|
|
93
|
+
* import { memoizeWeak } from '@socketsecurity/lib/memoization'
|
|
94
94
|
*
|
|
95
95
|
* const processConfig = memoizeWeak((config: Config) => {
|
|
96
96
|
* return expensiveTransform(config)
|
|
@@ -109,7 +109,7 @@ export declare function memoizeWeak<K extends object, Result>(fn: (key: K) => Re
|
|
|
109
109
|
* @returns Memoized version that only executes once
|
|
110
110
|
*
|
|
111
111
|
* @example
|
|
112
|
-
* import { once } from '@socketsecurity/
|
|
112
|
+
* import { once } from '@socketsecurity/lib/memoization'
|
|
113
113
|
*
|
|
114
114
|
* const initialize = once(() => {
|
|
115
115
|
* console.log('Initializing…')
|
|
@@ -130,7 +130,7 @@ export declare function once<Result>(fn: () => Result): () => Result;
|
|
|
130
130
|
* @returns Debounced memoized function
|
|
131
131
|
*
|
|
132
132
|
* @example
|
|
133
|
-
* import { memoizeDebounced } from '@socketsecurity/
|
|
133
|
+
* import { memoizeDebounced } from '@socketsecurity/lib/memoization'
|
|
134
134
|
*
|
|
135
135
|
* const search = memoizeDebounced(
|
|
136
136
|
* (query: string) => performSearch(query),
|
package/dist/memoization.js.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/memoization.ts"],
|
|
4
|
-
"sourcesContent": ["/**\n * @fileoverview Memoization utilities for caching function results.\n * Provides function result caching to optimize repeated computations and expensive operations.\n */\n\nimport { debugLog } from './debug'\n\n/**\n * Options for memoization behavior.\n */\ntype MemoizeOptions<Args extends unknown[], _Result = unknown> = {\n /** Custom cache key generator (defaults to JSON.stringify) */\n keyGen?: (...args: Args) => string\n /** Maximum cache size (LRU eviction when exceeded) */\n maxSize?: number\n /** TTL in milliseconds (cache entries expire after this time) */\n ttl?: number\n /** Cache name for debugging */\n name?: string\n /** Weak cache for object keys (enables GC) */\n weak?: boolean\n /** Custom equality check for cache hits */\n equals?: (a: Args, b: Args) => boolean\n}\n\n/**\n * Cache entry with metadata.\n */\ntype CacheEntry<T> = {\n value: T\n timestamp: number\n hits: number\n}\n\n/**\n * Memoize a function with configurable caching behavior.\n * Caches function results to avoid repeated computation.\n *\n * @param fn - Function to memoize\n * @param options - Memoization options\n * @returns Memoized version of the function\n *\n * @example\n * import { memoize } from '@socketsecurity/registry/lib/memoization'\n *\n * const expensiveOperation = memoize((n: number) => {\n * // Heavy computation\n * return Array(n).fill(0).reduce((a, _, i) => a + i, 0)\n * }, { maxSize: 100, ttl: 60000, name: 'sum' })\n *\n * expensiveOperation(1000) // Computed\n * expensiveOperation(1000) // Cached\n */\nexport function memoize<Args extends unknown[], Result>(\n fn: (...args: Args) => Result,\n options: MemoizeOptions<Args, Result> = {},\n): (...args: Args) => Result {\n const {\n keyGen = (...args) => JSON.stringify(args),\n maxSize = Number.POSITIVE_INFINITY,\n name = fn.name || 'anonymous',\n ttl = Number.POSITIVE_INFINITY,\n } = options\n\n const cache = new Map<string, CacheEntry<Result>>()\n const accessOrder: string[] = []\n\n function evictLRU(): void {\n if (cache.size >= maxSize && accessOrder.length > 0) {\n const oldest = accessOrder.shift()\n if (oldest) {\n cache.delete(oldest)\n debugLog(`[memoize:${name}] clear`, {\n key: oldest,\n reason: 'LRU',\n })\n }\n }\n }\n\n function isExpired(entry: CacheEntry<Result>): boolean {\n if (ttl === Number.POSITIVE_INFINITY) {\n return false\n }\n return Date.now() - entry.timestamp > ttl\n }\n\n return function memoized(...args: Args): Result {\n const key = keyGen(...args)\n\n // Check cache\n const cached = cache.get(key)\n if (cached && !isExpired(cached)) {\n cached.hits++\n // Move to end of access order (LRU)\n const index = accessOrder.indexOf(key)\n if (index !== -1) {\n accessOrder.splice(index, 1)\n }\n accessOrder.push(key)\n\n debugLog(`[memoize:${name}] hit`, { key, hits: cached.hits })\n return cached.value\n }\n\n // Cache miss - compute value\n debugLog(`[memoize:${name}] miss`, { key })\n const value = fn(...args)\n\n // Store in cache\n evictLRU()\n cache.set(key, {\n value,\n timestamp: Date.now(),\n hits: 0,\n })\n accessOrder.push(key)\n\n debugLog(`[memoize:${name}] set`, { key, cacheSize: cache.size })\n return value\n }\n}\n\n/**\n * Memoize an async function.\n * Similar to memoize() but handles promises properly.\n *\n * @param fn - Async function to memoize\n * @param options - Memoization options\n * @returns Memoized version of the async function\n *\n * @example\n * import { memoizeAsync } from '@socketsecurity/registry/lib/memoization'\n *\n * const fetchUser = memoizeAsync(async (id: string) => {\n * const response = await fetch(`/api/users/${id}`)\n * return response.json()\n * }, { ttl: 300000, name: 'fetchUser' })\n *\n * await fetchUser('123') // Fetches from API\n * await fetchUser('123') // Returns cached result\n */\nexport function memoizeAsync<Args extends unknown[], Result>(\n fn: (...args: Args) => Promise<Result>,\n options: MemoizeOptions<Args, Result> = {},\n): (...args: Args) => Promise<Result> {\n const {\n keyGen = (...args) => JSON.stringify(args),\n maxSize = Number.POSITIVE_INFINITY,\n name = fn.name || 'anonymous',\n ttl = Number.POSITIVE_INFINITY,\n } = options\n\n const cache = new Map<string, CacheEntry<Promise<Result>>>()\n const accessOrder: string[] = []\n\n function evictLRU(): void {\n if (cache.size >= maxSize && accessOrder.length > 0) {\n const oldest = accessOrder.shift()\n if (oldest) {\n cache.delete(oldest)\n debugLog(`[memoizeAsync:${name}] clear`, {\n key: oldest,\n reason: 'LRU',\n })\n }\n }\n }\n\n function isExpired(entry: CacheEntry<Promise<Result>>): boolean {\n if (ttl === Number.POSITIVE_INFINITY) {\n return false\n }\n return Date.now() - entry.timestamp > ttl\n }\n\n return async function memoized(...args: Args): Promise<Result> {\n const key = keyGen(...args)\n\n // Check cache\n const cached = cache.get(key)\n if (cached && !isExpired(cached)) {\n cached.hits++\n // Move to end of access order (LRU)\n const index = accessOrder.indexOf(key)\n if (index !== -1) {\n accessOrder.splice(index, 1)\n }\n accessOrder.push(key)\n\n debugLog(`[memoizeAsync:${name}] hit`, { key, hits: cached.hits })\n return await cached.value\n }\n\n // Cache miss - compute value\n debugLog(`[memoizeAsync:${name}] miss`, { key })\n const promise = fn(...args)\n\n // Store promise in cache (handles concurrent calls)\n evictLRU()\n cache.set(key, {\n value: promise,\n timestamp: Date.now(),\n hits: 0,\n })\n accessOrder.push(key)\n\n debugLog(`[memoizeAsync:${name}] set`, { key, cacheSize: cache.size })\n\n try {\n const result = await promise\n return result\n } catch (e) {\n // Remove failed promise from cache\n cache.delete(key)\n const orderIndex = accessOrder.indexOf(key)\n if (orderIndex !== -1) {\n accessOrder.splice(orderIndex, 1)\n }\n debugLog(`[memoizeAsync:${name}] clear`, { key, reason: 'error' })\n throw e\n }\n }\n}\n\n/**\n * Create a memoized version of a method.\n * Preserves 'this' context for class methods.\n *\n * @param target - Object containing the method\n * @param propertyKey - Method name\n * @param descriptor - Property descriptor\n * @returns Modified descriptor with memoized method\n *\n * @example\n * import { Memoize } from '@socketsecurity/registry/lib/memoization'\n *\n * class Calculator {\n * @Memoize()\n * fibonacci(n: number): number {\n * if (n <= 1) return n\n * return this.fibonacci(n - 1) + this.fibonacci(n - 2)\n * }\n * }\n */\nexport function Memoize(options: MemoizeOptions<unknown[], unknown> = {}) {\n return (\n _target: unknown,\n propertyKey: string,\n descriptor: PropertyDescriptor,\n ): PropertyDescriptor => {\n const originalMethod = descriptor.value as (...args: unknown[]) => unknown\n\n descriptor.value = memoize(originalMethod, {\n ...options,\n name: options.name || propertyKey,\n })\n\n return descriptor\n }\n}\n\n/**\n * Clear all memoization caches.\n * Useful for testing or when you need to force recomputation.\n */\nexport function clearAllMemoizationCaches(): void {\n // Note: This requires the memoized functions to be tracked globally.\n // For now, this is a placeholder that logs the intent.\n debugLog('[memoize:all] clear', { action: 'clear-all-caches' })\n}\n\n/**\n * Memoize with WeakMap for object keys.\n * Allows garbage collection when objects are no longer referenced.\n * Only works when first argument is an object.\n *\n * @param fn - Function to memoize\n * @returns Memoized version using WeakMap\n *\n * @example\n * import { memoizeWeak } from '@socketsecurity/registry/lib/memoization'\n *\n * const processConfig = memoizeWeak((config: Config) => {\n * return expensiveTransform(config)\n * })\n *\n * processConfig(config1) // Computed\n * processConfig(config1) // Cached\n * // When config1 is no longer referenced, cache entry is GC'd\n */\nexport function memoizeWeak<K extends object, Result>(\n fn: (key: K) => Result,\n): (key: K) => Result {\n const cache = new WeakMap<K, Result>()\n\n return function memoized(key: K): Result {\n const cached = cache.get(key)\n if (cached !== undefined) {\n debugLog(`[memoizeWeak:${fn.name}] hit`)\n return cached\n }\n\n debugLog(`[memoizeWeak:${fn.name}] miss`)\n const result = fn(key)\n cache.set(key, result)\n return result\n }\n}\n\n/**\n * Simple once() implementation - caches single result forever.\n * Useful for initialization functions that should only run once.\n *\n * @param fn - Function to run once\n * @returns Memoized version that only executes once\n *\n * @example\n * import { once } from '@socketsecurity/registry/lib/memoization'\n *\n * const initialize = once(() => {\n * console.log('Initializing\u2026')\n * return loadConfig()\n * })\n *\n * initialize() // Logs \"Initializing\u2026\" and returns config\n * initialize() // Returns cached config (no log)\n */\nexport function once<Result>(fn: () => Result): () => Result {\n let called = false\n let result: Result\n\n return function memoized(): Result {\n if (!called) {\n result = fn()\n called = true\n debugLog(`[once:${fn.name}] set`)\n } else {\n debugLog(`[once:${fn.name}] hit`)\n }\n return result\n }\n}\n\n/**\n * Create a debounced memoized function.\n * Combines memoization with debouncing for expensive operations.\n *\n * @param fn - Function to memoize and debounce\n * @param wait - Debounce wait time in milliseconds\n * @param options - Memoization options\n * @returns Debounced memoized function\n *\n * @example\n * import { memoizeDebounced } from '@socketsecurity/registry/lib/memoization'\n *\n * const search = memoizeDebounced(\n * (query: string) => performSearch(query),\n * 300,\n * { name: 'search' }\n * )\n */\nexport function memoizeDebounced<Args extends unknown[], Result>(\n fn: (...args: Args) => Result,\n wait: number,\n options: MemoizeOptions<Args, Result> = {},\n): (...args: Args) => Result {\n const memoized = memoize(fn, options)\n let timeoutId: NodeJS.Timeout | undefined\n\n return function debounced(...args: Args): Result {\n if (timeoutId) {\n clearTimeout(timeoutId)\n }\n\n timeoutId = setTimeout(() => {\n memoized(...args)\n }, wait)\n\n // For immediate return, try cached value or compute synchronously\n return memoized(...args)\n }\n}\n"],
|
|
4
|
+
"sourcesContent": ["/**\n * @fileoverview Memoization utilities for caching function results.\n * Provides function result caching to optimize repeated computations and expensive operations.\n */\n\nimport { debugLog } from './debug'\n\n/**\n * Options for memoization behavior.\n */\ntype MemoizeOptions<Args extends unknown[], _Result = unknown> = {\n /** Custom cache key generator (defaults to JSON.stringify) */\n keyGen?: (...args: Args) => string\n /** Maximum cache size (LRU eviction when exceeded) */\n maxSize?: number\n /** TTL in milliseconds (cache entries expire after this time) */\n ttl?: number\n /** Cache name for debugging */\n name?: string\n /** Weak cache for object keys (enables GC) */\n weak?: boolean\n /** Custom equality check for cache hits */\n equals?: (a: Args, b: Args) => boolean\n}\n\n/**\n * Cache entry with metadata.\n */\ntype CacheEntry<T> = {\n value: T\n timestamp: number\n hits: number\n}\n\n/**\n * Memoize a function with configurable caching behavior.\n * Caches function results to avoid repeated computation.\n *\n * @param fn - Function to memoize\n * @param options - Memoization options\n * @returns Memoized version of the function\n *\n * @example\n * import { memoize } from '@socketsecurity/lib/memoization'\n *\n * const expensiveOperation = memoize((n: number) => {\n * // Heavy computation\n * return Array(n).fill(0).reduce((a, _, i) => a + i, 0)\n * }, { maxSize: 100, ttl: 60000, name: 'sum' })\n *\n * expensiveOperation(1000) // Computed\n * expensiveOperation(1000) // Cached\n */\nexport function memoize<Args extends unknown[], Result>(\n fn: (...args: Args) => Result,\n options: MemoizeOptions<Args, Result> = {},\n): (...args: Args) => Result {\n const {\n keyGen = (...args) => JSON.stringify(args),\n maxSize = Number.POSITIVE_INFINITY,\n name = fn.name || 'anonymous',\n ttl = Number.POSITIVE_INFINITY,\n } = options\n\n const cache = new Map<string, CacheEntry<Result>>()\n const accessOrder: string[] = []\n\n function evictLRU(): void {\n if (cache.size >= maxSize && accessOrder.length > 0) {\n const oldest = accessOrder.shift()\n if (oldest) {\n cache.delete(oldest)\n debugLog(`[memoize:${name}] clear`, {\n key: oldest,\n reason: 'LRU',\n })\n }\n }\n }\n\n function isExpired(entry: CacheEntry<Result>): boolean {\n if (ttl === Number.POSITIVE_INFINITY) {\n return false\n }\n return Date.now() - entry.timestamp > ttl\n }\n\n return function memoized(...args: Args): Result {\n const key = keyGen(...args)\n\n // Check cache\n const cached = cache.get(key)\n if (cached && !isExpired(cached)) {\n cached.hits++\n // Move to end of access order (LRU)\n const index = accessOrder.indexOf(key)\n if (index !== -1) {\n accessOrder.splice(index, 1)\n }\n accessOrder.push(key)\n\n debugLog(`[memoize:${name}] hit`, { key, hits: cached.hits })\n return cached.value\n }\n\n // Cache miss - compute value\n debugLog(`[memoize:${name}] miss`, { key })\n const value = fn(...args)\n\n // Store in cache\n evictLRU()\n cache.set(key, {\n value,\n timestamp: Date.now(),\n hits: 0,\n })\n accessOrder.push(key)\n\n debugLog(`[memoize:${name}] set`, { key, cacheSize: cache.size })\n return value\n }\n}\n\n/**\n * Memoize an async function.\n * Similar to memoize() but handles promises properly.\n *\n * @param fn - Async function to memoize\n * @param options - Memoization options\n * @returns Memoized version of the async function\n *\n * @example\n * import { memoizeAsync } from '@socketsecurity/lib/memoization'\n *\n * const fetchUser = memoizeAsync(async (id: string) => {\n * const response = await fetch(`/api/users/${id}`)\n * return response.json()\n * }, { ttl: 300000, name: 'fetchUser' })\n *\n * await fetchUser('123') // Fetches from API\n * await fetchUser('123') // Returns cached result\n */\nexport function memoizeAsync<Args extends unknown[], Result>(\n fn: (...args: Args) => Promise<Result>,\n options: MemoizeOptions<Args, Result> = {},\n): (...args: Args) => Promise<Result> {\n const {\n keyGen = (...args) => JSON.stringify(args),\n maxSize = Number.POSITIVE_INFINITY,\n name = fn.name || 'anonymous',\n ttl = Number.POSITIVE_INFINITY,\n } = options\n\n const cache = new Map<string, CacheEntry<Promise<Result>>>()\n const accessOrder: string[] = []\n\n function evictLRU(): void {\n if (cache.size >= maxSize && accessOrder.length > 0) {\n const oldest = accessOrder.shift()\n if (oldest) {\n cache.delete(oldest)\n debugLog(`[memoizeAsync:${name}] clear`, {\n key: oldest,\n reason: 'LRU',\n })\n }\n }\n }\n\n function isExpired(entry: CacheEntry<Promise<Result>>): boolean {\n if (ttl === Number.POSITIVE_INFINITY) {\n return false\n }\n return Date.now() - entry.timestamp > ttl\n }\n\n return async function memoized(...args: Args): Promise<Result> {\n const key = keyGen(...args)\n\n // Check cache\n const cached = cache.get(key)\n if (cached && !isExpired(cached)) {\n cached.hits++\n // Move to end of access order (LRU)\n const index = accessOrder.indexOf(key)\n if (index !== -1) {\n accessOrder.splice(index, 1)\n }\n accessOrder.push(key)\n\n debugLog(`[memoizeAsync:${name}] hit`, { key, hits: cached.hits })\n return await cached.value\n }\n\n // Cache miss - compute value\n debugLog(`[memoizeAsync:${name}] miss`, { key })\n const promise = fn(...args)\n\n // Store promise in cache (handles concurrent calls)\n evictLRU()\n cache.set(key, {\n value: promise,\n timestamp: Date.now(),\n hits: 0,\n })\n accessOrder.push(key)\n\n debugLog(`[memoizeAsync:${name}] set`, { key, cacheSize: cache.size })\n\n try {\n const result = await promise\n return result\n } catch (e) {\n // Remove failed promise from cache\n cache.delete(key)\n const orderIndex = accessOrder.indexOf(key)\n if (orderIndex !== -1) {\n accessOrder.splice(orderIndex, 1)\n }\n debugLog(`[memoizeAsync:${name}] clear`, { key, reason: 'error' })\n throw e\n }\n }\n}\n\n/**\n * Create a memoized version of a method.\n * Preserves 'this' context for class methods.\n *\n * @param target - Object containing the method\n * @param propertyKey - Method name\n * @param descriptor - Property descriptor\n * @returns Modified descriptor with memoized method\n *\n * @example\n * import { Memoize } from '@socketsecurity/lib/memoization'\n *\n * class Calculator {\n * @Memoize()\n * fibonacci(n: number): number {\n * if (n <= 1) return n\n * return this.fibonacci(n - 1) + this.fibonacci(n - 2)\n * }\n * }\n */\nexport function Memoize(options: MemoizeOptions<unknown[], unknown> = {}) {\n return (\n _target: unknown,\n propertyKey: string,\n descriptor: PropertyDescriptor,\n ): PropertyDescriptor => {\n const originalMethod = descriptor.value as (...args: unknown[]) => unknown\n\n descriptor.value = memoize(originalMethod, {\n ...options,\n name: options.name || propertyKey,\n })\n\n return descriptor\n }\n}\n\n/**\n * Clear all memoization caches.\n * Useful for testing or when you need to force recomputation.\n */\nexport function clearAllMemoizationCaches(): void {\n // Note: This requires the memoized functions to be tracked globally.\n // For now, this is a placeholder that logs the intent.\n debugLog('[memoize:all] clear', { action: 'clear-all-caches' })\n}\n\n/**\n * Memoize with WeakMap for object keys.\n * Allows garbage collection when objects are no longer referenced.\n * Only works when first argument is an object.\n *\n * @param fn - Function to memoize\n * @returns Memoized version using WeakMap\n *\n * @example\n * import { memoizeWeak } from '@socketsecurity/lib/memoization'\n *\n * const processConfig = memoizeWeak((config: Config) => {\n * return expensiveTransform(config)\n * })\n *\n * processConfig(config1) // Computed\n * processConfig(config1) // Cached\n * // When config1 is no longer referenced, cache entry is GC'd\n */\nexport function memoizeWeak<K extends object, Result>(\n fn: (key: K) => Result,\n): (key: K) => Result {\n const cache = new WeakMap<K, Result>()\n\n return function memoized(key: K): Result {\n const cached = cache.get(key)\n if (cached !== undefined) {\n debugLog(`[memoizeWeak:${fn.name}] hit`)\n return cached\n }\n\n debugLog(`[memoizeWeak:${fn.name}] miss`)\n const result = fn(key)\n cache.set(key, result)\n return result\n }\n}\n\n/**\n * Simple once() implementation - caches single result forever.\n * Useful for initialization functions that should only run once.\n *\n * @param fn - Function to run once\n * @returns Memoized version that only executes once\n *\n * @example\n * import { once } from '@socketsecurity/lib/memoization'\n *\n * const initialize = once(() => {\n * console.log('Initializing\u2026')\n * return loadConfig()\n * })\n *\n * initialize() // Logs \"Initializing\u2026\" and returns config\n * initialize() // Returns cached config (no log)\n */\nexport function once<Result>(fn: () => Result): () => Result {\n let called = false\n let result: Result\n\n return function memoized(): Result {\n if (!called) {\n result = fn()\n called = true\n debugLog(`[once:${fn.name}] set`)\n } else {\n debugLog(`[once:${fn.name}] hit`)\n }\n return result\n }\n}\n\n/**\n * Create a debounced memoized function.\n * Combines memoization with debouncing for expensive operations.\n *\n * @param fn - Function to memoize and debounce\n * @param wait - Debounce wait time in milliseconds\n * @param options - Memoization options\n * @returns Debounced memoized function\n *\n * @example\n * import { memoizeDebounced } from '@socketsecurity/lib/memoization'\n *\n * const search = memoizeDebounced(\n * (query: string) => performSearch(query),\n * 300,\n * { name: 'search' }\n * )\n */\nexport function memoizeDebounced<Args extends unknown[], Result>(\n fn: (...args: Args) => Result,\n wait: number,\n options: MemoizeOptions<Args, Result> = {},\n): (...args: Args) => Result {\n const memoized = memoize(fn, options)\n let timeoutId: NodeJS.Timeout | undefined\n\n return function debounced(...args: Args): Result {\n if (timeoutId) {\n clearTimeout(timeoutId)\n }\n\n timeoutId = setTimeout(() => {\n memoized(...args)\n }, wait)\n\n // For immediate return, try cached value or compute synchronously\n return memoized(...args)\n }\n}\n"],
|
|
5
5
|
"mappings": ";4ZAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,aAAAE,EAAA,8BAAAC,EAAA,YAAAC,EAAA,iBAAAC,EAAA,qBAAAC,EAAA,gBAAAC,EAAA,SAAAC,IAAA,eAAAC,EAAAT,GAKA,IAAAU,EAAyB,mBAgDlB,SAASN,EACdO,EACAC,EAAwC,CAAC,EACd,CAC3B,KAAM,CACJ,OAAAC,EAAS,IAAIC,IAAS,KAAK,UAAUA,CAAI,EACzC,QAAAC,EAAU,OAAO,kBACjB,KAAAC,EAAOL,EAAG,MAAQ,YAClB,IAAAM,EAAM,OAAO,iBACf,EAAIL,EAEEM,EAAQ,IAAI,IACZC,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
|
"names": ["memoization_exports", "__export", "Memoize", "clearAllMemoizationCaches", "memoize", "memoizeAsync", "memoizeDebounced", "memoizeWeak", "once", "__toCommonJS", "import_debug", "fn", "options", "keyGen", "args", "maxSize", "name", "ttl", "cache", "accessOrder", "evictLRU", "oldest", "isExpired", "entry", "key", "cached", "index", "value", "promise", "e", "orderIndex", "_target", "propertyKey", "descriptor", "originalMethod", "result", "called", "wait", "memoized", "timeoutId"]
|
|
7
7
|
}
|
package/dist/performance.d.ts
CHANGED
|
@@ -16,7 +16,7 @@ type PerformanceMetrics = {
|
|
|
16
16
|
* @returns Stop function that completes the timing
|
|
17
17
|
*
|
|
18
18
|
* @example
|
|
19
|
-
* import { perfTimer } from '@socketsecurity/
|
|
19
|
+
* import { perfTimer } from '@socketsecurity/lib/performance'
|
|
20
20
|
*
|
|
21
21
|
* const stop = perfTimer('api-call')
|
|
22
22
|
* await fetchData()
|
|
@@ -32,7 +32,7 @@ export declare function perfTimer(operation: string, metadata?: Record<string, u
|
|
|
32
32
|
* @returns Result of the function and duration
|
|
33
33
|
*
|
|
34
34
|
* @example
|
|
35
|
-
* import { measure } from '@socketsecurity/
|
|
35
|
+
* import { measure } from '@socketsecurity/lib/performance'
|
|
36
36
|
*
|
|
37
37
|
* const { result, duration } = await measure('fetch-packages', async () => {
|
|
38
38
|
* return await fetchPackages()
|
|
@@ -52,7 +52,7 @@ export declare function measure<T>(operation: string, fn: () => Promise<T>, meta
|
|
|
52
52
|
* @returns Result of the function and duration
|
|
53
53
|
*
|
|
54
54
|
* @example
|
|
55
|
-
* import { measureSync } from '@socketsecurity/
|
|
55
|
+
* import { measureSync } from '@socketsecurity/lib/performance'
|
|
56
56
|
*
|
|
57
57
|
* const { result, duration } = measureSync('parse-json', () => {
|
|
58
58
|
* return JSON.parse(data)
|
|
@@ -69,7 +69,7 @@ export declare function measureSync<T>(operation: string, fn: () => T, metadata?
|
|
|
69
69
|
* @returns Array of performance metrics
|
|
70
70
|
*
|
|
71
71
|
* @example
|
|
72
|
-
* import { getPerformanceMetrics } from '@socketsecurity/
|
|
72
|
+
* import { getPerformanceMetrics } from '@socketsecurity/lib/performance'
|
|
73
73
|
*
|
|
74
74
|
* const metrics = getPerformanceMetrics()
|
|
75
75
|
* console.log(metrics)
|
|
@@ -79,7 +79,7 @@ export declare function getPerformanceMetrics(): PerformanceMetrics[];
|
|
|
79
79
|
* Clear all collected performance metrics.
|
|
80
80
|
*
|
|
81
81
|
* @example
|
|
82
|
-
* import { clearPerformanceMetrics } from '@socketsecurity/
|
|
82
|
+
* import { clearPerformanceMetrics } from '@socketsecurity/lib/performance'
|
|
83
83
|
*
|
|
84
84
|
* clearPerformanceMetrics()
|
|
85
85
|
*/
|
|
@@ -90,7 +90,7 @@ export declare function clearPerformanceMetrics(): void;
|
|
|
90
90
|
* @returns Summary of metrics grouped by operation
|
|
91
91
|
*
|
|
92
92
|
* @example
|
|
93
|
-
* import { getPerformanceSummary } from '@socketsecurity/
|
|
93
|
+
* import { getPerformanceSummary } from '@socketsecurity/lib/performance'
|
|
94
94
|
*
|
|
95
95
|
* const summary = getPerformanceSummary()
|
|
96
96
|
* console.log(summary)
|
|
@@ -111,7 +111,7 @@ export declare function getPerformanceSummary(): Record<string, {
|
|
|
111
111
|
* Only prints when DEBUG=perf is enabled.
|
|
112
112
|
*
|
|
113
113
|
* @example
|
|
114
|
-
* import { printPerformanceSummary } from '@socketsecurity/
|
|
114
|
+
* import { printPerformanceSummary } from '@socketsecurity/lib/performance'
|
|
115
115
|
*
|
|
116
116
|
* printPerformanceSummary()
|
|
117
117
|
* // Performance Summary:
|
|
@@ -127,7 +127,7 @@ export declare function printPerformanceSummary(): void;
|
|
|
127
127
|
* @param metadata - Optional metadata
|
|
128
128
|
*
|
|
129
129
|
* @example
|
|
130
|
-
* import { perfCheckpoint } from '@socketsecurity/
|
|
130
|
+
* import { perfCheckpoint } from '@socketsecurity/lib/performance'
|
|
131
131
|
*
|
|
132
132
|
* perfCheckpoint('start-scan')
|
|
133
133
|
* // ... do work ...
|
|
@@ -145,7 +145,7 @@ export declare function perfCheckpoint(checkpoint: string, metadata?: Record<str
|
|
|
145
145
|
* @returns Memory usage in MB
|
|
146
146
|
*
|
|
147
147
|
* @example
|
|
148
|
-
* import { trackMemory } from '@socketsecurity/
|
|
148
|
+
* import { trackMemory } from '@socketsecurity/lib/performance'
|
|
149
149
|
*
|
|
150
150
|
* const memBefore = trackMemory('before-operation')
|
|
151
151
|
* await heavyOperation()
|
|
@@ -160,7 +160,7 @@ export declare function trackMemory(label: string): number;
|
|
|
160
160
|
* @returns Formatted performance report
|
|
161
161
|
*
|
|
162
162
|
* @example
|
|
163
|
-
* import { generatePerformanceReport } from '@socketsecurity/
|
|
163
|
+
* import { generatePerformanceReport } from '@socketsecurity/lib/performance'
|
|
164
164
|
*
|
|
165
165
|
* console.log(generatePerformanceReport())
|
|
166
166
|
* // ╔═══════════════════════════════════════════════╗
|
package/dist/performance.js.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/performance.ts"],
|
|
4
|
-
"sourcesContent": ["/**\n * @fileoverview Performance monitoring utilities for profiling and optimization.\n * Provides timing, profiling, and performance metric collection for identifying bottlenecks.\n */\n\nimport { debugLog } from './debug'\n\n/**\n * Performance metrics collected during execution.\n */\ntype PerformanceMetrics = {\n operation: string\n duration: number\n timestamp: number\n metadata?: Record<string, unknown>\n}\n\n/**\n * Global metrics collection (only in debug mode).\n */\nconst performanceMetrics: PerformanceMetrics[] = []\n\n/**\n * Check if performance tracking is enabled.\n */\nfunction isPerfEnabled(): boolean {\n return process.env['DEBUG']?.includes('perf') || false\n}\n\n/**\n * Start a performance timer for an operation.\n * Returns a stop function that records the duration.\n *\n * @param operation - Name of the operation being timed\n * @param metadata - Optional metadata to attach to the metric\n * @returns Stop function that completes the timing\n *\n * @example\n * import { perfTimer } from '@socketsecurity/registry/lib/performance'\n *\n * const stop = perfTimer('api-call')\n * await fetchData()\n * stop({ endpoint: '/npm/lodash/score' })\n */\nexport function perfTimer(\n operation: string,\n metadata?: Record<string, unknown>,\n): (additionalMetadata?: Record<string, unknown>) => void {\n if (!isPerfEnabled()) {\n // No-op if perf tracking disabled\n return () => {}\n }\n\n const start = performance.now()\n debugLog(`[perf] [START] ${operation}`)\n\n return (additionalMetadata?: Record<string, unknown>) => {\n const duration = performance.now() - start\n const metric: PerformanceMetrics = {\n operation,\n // Round to 2 decimals\n duration: Math.round(duration * 100) / 100,\n timestamp: Date.now(),\n metadata: { ...metadata, ...additionalMetadata },\n }\n\n performanceMetrics.push(metric)\n debugLog(`[perf] [END] ${operation} - ${metric.duration}ms`)\n }\n}\n\n/**\n * Measure execution time of an async function.\n *\n * @param operation - Name of the operation\n * @param fn - Async function to measure\n * @param metadata - Optional metadata\n * @returns Result of the function and duration\n *\n * @example\n * import { measure } from '@socketsecurity/registry/lib/performance'\n *\n * const { result, duration } = await measure('fetch-packages', async () => {\n * return await fetchPackages()\n * })\n * console.log(`Fetched packages in ${duration}ms`)\n */\nexport async function measure<T>(\n operation: string,\n fn: () => Promise<T>,\n metadata?: Record<string, unknown>,\n): Promise<{ result: T; duration: number }> {\n const stop = perfTimer(operation, metadata)\n\n try {\n const result = await fn()\n stop({ success: true })\n\n const metric = performanceMetrics[performanceMetrics.length - 1]\n return { result, duration: metric?.duration || 0 }\n } catch (e) {\n stop({\n success: false,\n error: e instanceof Error ? e.message : 'Unknown',\n })\n throw e\n }\n}\n\n/**\n * Measure synchronous function execution time.\n *\n * @param operation - Name of the operation\n * @param fn - Synchronous function to measure\n * @param metadata - Optional metadata\n * @returns Result of the function and duration\n *\n * @example\n * import { measureSync } from '@socketsecurity/registry/lib/performance'\n *\n * const { result, duration } = measureSync('parse-json', () => {\n * return JSON.parse(data)\n * })\n */\nexport function measureSync<T>(\n operation: string,\n fn: () => T,\n metadata?: Record<string, unknown>,\n): { result: T; duration: number } {\n const stop = perfTimer(operation, metadata)\n\n try {\n const result = fn()\n stop({ success: true })\n\n const metric = performanceMetrics[performanceMetrics.length - 1]\n return { result, duration: metric?.duration || 0 }\n } catch (e) {\n stop({\n success: false,\n error: e instanceof Error ? e.message : 'Unknown',\n })\n throw e\n }\n}\n\n/**\n * Get all collected performance metrics.\n * Only available when DEBUG=perf is enabled.\n *\n * @returns Array of performance metrics\n *\n * @example\n * import { getPerformanceMetrics } from '@socketsecurity/registry/lib/performance'\n *\n * const metrics = getPerformanceMetrics()\n * console.log(metrics)\n */\nexport function getPerformanceMetrics(): PerformanceMetrics[] {\n return [...performanceMetrics]\n}\n\n/**\n * Clear all collected performance metrics.\n *\n * @example\n * import { clearPerformanceMetrics } from '@socketsecurity/registry/lib/performance'\n *\n * clearPerformanceMetrics()\n */\nexport function clearPerformanceMetrics(): void {\n performanceMetrics.length = 0\n debugLog('[perf] Cleared performance metrics')\n}\n\n/**\n * Get performance summary statistics.\n *\n * @returns Summary of metrics grouped by operation\n *\n * @example\n * import { getPerformanceSummary } from '@socketsecurity/registry/lib/performance'\n *\n * const summary = getPerformanceSummary()\n * console.log(summary)\n * // {\n * // 'api-call': { count: 5, total: 1234, avg: 246.8, min: 100, max: 500 },\n * // 'file-read': { count: 10, total: 50, avg: 5, min: 2, max: 15 }\n * // }\n */\nexport function getPerformanceSummary(): Record<\n string,\n {\n count: number\n total: number\n avg: number\n min: number\n max: number\n }\n> {\n const summary: Record<\n string,\n { count: number; total: number; min: number; max: number }\n > = Object.create(null)\n\n for (const metric of performanceMetrics) {\n const { duration, operation } = metric\n\n if (!summary[operation]) {\n summary[operation] = {\n count: 0,\n total: 0,\n min: Number.POSITIVE_INFINITY,\n max: Number.NEGATIVE_INFINITY,\n }\n }\n\n const stats = summary[operation] as {\n count: number\n total: number\n min: number\n max: number\n }\n stats.count++\n stats.total += duration\n stats.min = Math.min(stats.min, duration)\n stats.max = Math.max(stats.max, duration)\n }\n\n // Calculate averages and return with proper typing\n const result: Record<\n string,\n { count: number; total: number; avg: number; min: number; max: number }\n > = Object.create(null)\n\n for (const { 0: operation, 1: stats } of Object.entries(summary)) {\n result[operation] = {\n count: stats.count,\n total: Math.round(stats.total * 100) / 100,\n avg: Math.round((stats.total / stats.count) * 100) / 100,\n min: Math.round(stats.min * 100) / 100,\n max: Math.round(stats.max * 100) / 100,\n }\n }\n\n return result\n}\n\n/**\n * Print performance summary to console.\n * Only prints when DEBUG=perf is enabled.\n *\n * @example\n * import { printPerformanceSummary } from '@socketsecurity/registry/lib/performance'\n *\n * printPerformanceSummary()\n * // Performance Summary:\n * // api-call: 5 calls, avg 246.8ms (min 100ms, max 500ms, total 1234ms)\n * // file-read: 10 calls, avg 5ms (min 2ms, max 15ms, total 50ms)\n */\nexport function printPerformanceSummary(): void {\n if (!isPerfEnabled() || performanceMetrics.length === 0) {\n return\n }\n\n const summary = getPerformanceSummary()\n const operations = Object.keys(summary).sort()\n\n debugLog('[perf]\\n=== Performance Summary ===')\n\n for (const operation of operations) {\n const stats = summary[operation] as {\n count: number\n total: number\n avg: number\n min: number\n max: number\n }\n debugLog(\n `[perf] ${operation}: ${stats.count} calls, avg ${stats.avg}ms (min ${stats.min}ms, max ${stats.max}ms, total ${stats.total}ms)`,\n )\n }\n\n debugLog('[perf] =========================\\n')\n}\n\n/**\n * Mark a checkpoint in performance tracking.\n * Useful for tracking progress through complex operations.\n *\n * @param checkpoint - Name of the checkpoint\n * @param metadata - Optional metadata\n *\n * @example\n * import { perfCheckpoint } from '@socketsecurity/registry/lib/performance'\n *\n * perfCheckpoint('start-scan')\n * // ... do work ...\n * perfCheckpoint('fetch-packages', { count: 50 })\n * // ... do work ...\n * perfCheckpoint('analyze-issues', { issueCount: 10 })\n * perfCheckpoint('end-scan')\n */\nexport function perfCheckpoint(\n checkpoint: string,\n metadata?: Record<string, unknown>,\n): void {\n if (!isPerfEnabled()) {\n return\n }\n\n const metric: PerformanceMetrics = {\n operation: `checkpoint:${checkpoint}`,\n duration: 0,\n timestamp: Date.now(),\n ...(metadata ? { metadata } : {}),\n }\n\n performanceMetrics.push(metric)\n debugLog(`[perf] [CHECKPOINT] ${checkpoint}`)\n}\n\n/**\n * Track memory usage at a specific point.\n * Only available when DEBUG=perf is enabled.\n *\n * @param label - Label for this memory snapshot\n * @returns Memory usage in MB\n *\n * @example\n * import { trackMemory } from '@socketsecurity/registry/lib/performance'\n *\n * const memBefore = trackMemory('before-operation')\n * await heavyOperation()\n * const memAfter = trackMemory('after-operation')\n * console.log(`Memory increased by ${memAfter - memBefore}MB`)\n */\nexport function trackMemory(label: string): number {\n if (!isPerfEnabled()) {\n return 0\n }\n\n const usage = process.memoryUsage()\n const heapUsedMB = Math.round((usage.heapUsed / 1024 / 1024) * 100) / 100\n\n debugLog(`[perf] [MEMORY] ${label}: ${heapUsedMB}MB heap used`)\n\n const metric: PerformanceMetrics = {\n operation: `checkpoint:memory:${label}`,\n duration: 0,\n timestamp: Date.now(),\n metadata: {\n heapUsed: heapUsedMB,\n heapTotal: Math.round((usage.heapTotal / 1024 / 1024) * 100) / 100,\n external: Math.round((usage.external / 1024 / 1024) * 100) / 100,\n },\n }\n\n performanceMetrics.push(metric)\n\n return heapUsedMB\n}\n\n/**\n * Create a performance report for the current execution.\n * Only available when DEBUG=perf is enabled.\n *\n * @returns Formatted performance report\n *\n * @example\n * import { generatePerformanceReport } from '@socketsecurity/registry/lib/performance'\n *\n * console.log(generatePerformanceReport())\n * // \u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557\n * // \u2551 Performance Report \u2551\n * // \u255A\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255D\n * //\n * // api-call:\n * // Calls: 5\n * // Avg: 246.8ms\n * // Min: 100ms\n * // Max: 500ms\n * // Total: 1234ms\n */\nexport function generatePerformanceReport(): string {\n if (!isPerfEnabled() || performanceMetrics.length === 0) {\n return '(no performance data collected - enable with DEBUG=perf)'\n }\n\n const summary = getPerformanceSummary()\n const operations = Object.keys(summary).sort()\n\n let report = '\\n\u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557\\n'\n report += '\u2551 Performance Report \u2551\\n'\n report += '\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255D\\n\\n'\n\n for (const operation of operations) {\n const stats = summary[operation] as {\n count: number\n total: number\n avg: number\n min: number\n max: number\n }\n report += `${operation}:\\n`\n report += ` Calls: ${stats.count}\\n`\n report += ` Avg: ${stats.avg}ms\\n`\n report += ` Min: ${stats.min}ms\\n`\n report += ` Max: ${stats.max}ms\\n`\n report += ` Total: ${stats.total}ms\\n\\n`\n }\n\n const totalDuration = Object.values(summary).reduce(\n (sum, s) => sum + s.total,\n 0,\n )\n report += `Total measured time: ${Math.round(totalDuration * 100) / 100}ms\\n`\n\n return report\n}\n"],
|
|
4
|
+
"sourcesContent": ["/**\n * @fileoverview Performance monitoring utilities for profiling and optimization.\n * Provides timing, profiling, and performance metric collection for identifying bottlenecks.\n */\n\nimport { debugLog } from './debug'\n\n/**\n * Performance metrics collected during execution.\n */\ntype PerformanceMetrics = {\n operation: string\n duration: number\n timestamp: number\n metadata?: Record<string, unknown>\n}\n\n/**\n * Global metrics collection (only in debug mode).\n */\nconst performanceMetrics: PerformanceMetrics[] = []\n\n/**\n * Check if performance tracking is enabled.\n */\nfunction isPerfEnabled(): boolean {\n return process.env['DEBUG']?.includes('perf') || false\n}\n\n/**\n * Start a performance timer for an operation.\n * Returns a stop function that records the duration.\n *\n * @param operation - Name of the operation being timed\n * @param metadata - Optional metadata to attach to the metric\n * @returns Stop function that completes the timing\n *\n * @example\n * import { perfTimer } from '@socketsecurity/lib/performance'\n *\n * const stop = perfTimer('api-call')\n * await fetchData()\n * stop({ endpoint: '/npm/lodash/score' })\n */\nexport function perfTimer(\n operation: string,\n metadata?: Record<string, unknown>,\n): (additionalMetadata?: Record<string, unknown>) => void {\n if (!isPerfEnabled()) {\n // No-op if perf tracking disabled\n return () => {}\n }\n\n const start = performance.now()\n debugLog(`[perf] [START] ${operation}`)\n\n return (additionalMetadata?: Record<string, unknown>) => {\n const duration = performance.now() - start\n const metric: PerformanceMetrics = {\n operation,\n // Round to 2 decimals\n duration: Math.round(duration * 100) / 100,\n timestamp: Date.now(),\n metadata: { ...metadata, ...additionalMetadata },\n }\n\n performanceMetrics.push(metric)\n debugLog(`[perf] [END] ${operation} - ${metric.duration}ms`)\n }\n}\n\n/**\n * Measure execution time of an async function.\n *\n * @param operation - Name of the operation\n * @param fn - Async function to measure\n * @param metadata - Optional metadata\n * @returns Result of the function and duration\n *\n * @example\n * import { measure } from '@socketsecurity/lib/performance'\n *\n * const { result, duration } = await measure('fetch-packages', async () => {\n * return await fetchPackages()\n * })\n * console.log(`Fetched packages in ${duration}ms`)\n */\nexport async function measure<T>(\n operation: string,\n fn: () => Promise<T>,\n metadata?: Record<string, unknown>,\n): Promise<{ result: T; duration: number }> {\n const stop = perfTimer(operation, metadata)\n\n try {\n const result = await fn()\n stop({ success: true })\n\n const metric = performanceMetrics[performanceMetrics.length - 1]\n return { result, duration: metric?.duration || 0 }\n } catch (e) {\n stop({\n success: false,\n error: e instanceof Error ? e.message : 'Unknown',\n })\n throw e\n }\n}\n\n/**\n * Measure synchronous function execution time.\n *\n * @param operation - Name of the operation\n * @param fn - Synchronous function to measure\n * @param metadata - Optional metadata\n * @returns Result of the function and duration\n *\n * @example\n * import { measureSync } from '@socketsecurity/lib/performance'\n *\n * const { result, duration } = measureSync('parse-json', () => {\n * return JSON.parse(data)\n * })\n */\nexport function measureSync<T>(\n operation: string,\n fn: () => T,\n metadata?: Record<string, unknown>,\n): { result: T; duration: number } {\n const stop = perfTimer(operation, metadata)\n\n try {\n const result = fn()\n stop({ success: true })\n\n const metric = performanceMetrics[performanceMetrics.length - 1]\n return { result, duration: metric?.duration || 0 }\n } catch (e) {\n stop({\n success: false,\n error: e instanceof Error ? e.message : 'Unknown',\n })\n throw e\n }\n}\n\n/**\n * Get all collected performance metrics.\n * Only available when DEBUG=perf is enabled.\n *\n * @returns Array of performance metrics\n *\n * @example\n * import { getPerformanceMetrics } from '@socketsecurity/lib/performance'\n *\n * const metrics = getPerformanceMetrics()\n * console.log(metrics)\n */\nexport function getPerformanceMetrics(): PerformanceMetrics[] {\n return [...performanceMetrics]\n}\n\n/**\n * Clear all collected performance metrics.\n *\n * @example\n * import { clearPerformanceMetrics } from '@socketsecurity/lib/performance'\n *\n * clearPerformanceMetrics()\n */\nexport function clearPerformanceMetrics(): void {\n performanceMetrics.length = 0\n debugLog('[perf] Cleared performance metrics')\n}\n\n/**\n * Get performance summary statistics.\n *\n * @returns Summary of metrics grouped by operation\n *\n * @example\n * import { getPerformanceSummary } from '@socketsecurity/lib/performance'\n *\n * const summary = getPerformanceSummary()\n * console.log(summary)\n * // {\n * // 'api-call': { count: 5, total: 1234, avg: 246.8, min: 100, max: 500 },\n * // 'file-read': { count: 10, total: 50, avg: 5, min: 2, max: 15 }\n * // }\n */\nexport function getPerformanceSummary(): Record<\n string,\n {\n count: number\n total: number\n avg: number\n min: number\n max: number\n }\n> {\n const summary: Record<\n string,\n { count: number; total: number; min: number; max: number }\n > = Object.create(null)\n\n for (const metric of performanceMetrics) {\n const { duration, operation } = metric\n\n if (!summary[operation]) {\n summary[operation] = {\n count: 0,\n total: 0,\n min: Number.POSITIVE_INFINITY,\n max: Number.NEGATIVE_INFINITY,\n }\n }\n\n const stats = summary[operation] as {\n count: number\n total: number\n min: number\n max: number\n }\n stats.count++\n stats.total += duration\n stats.min = Math.min(stats.min, duration)\n stats.max = Math.max(stats.max, duration)\n }\n\n // Calculate averages and return with proper typing\n const result: Record<\n string,\n { count: number; total: number; avg: number; min: number; max: number }\n > = Object.create(null)\n\n for (const { 0: operation, 1: stats } of Object.entries(summary)) {\n result[operation] = {\n count: stats.count,\n total: Math.round(stats.total * 100) / 100,\n avg: Math.round((stats.total / stats.count) * 100) / 100,\n min: Math.round(stats.min * 100) / 100,\n max: Math.round(stats.max * 100) / 100,\n }\n }\n\n return result\n}\n\n/**\n * Print performance summary to console.\n * Only prints when DEBUG=perf is enabled.\n *\n * @example\n * import { printPerformanceSummary } from '@socketsecurity/lib/performance'\n *\n * printPerformanceSummary()\n * // Performance Summary:\n * // api-call: 5 calls, avg 246.8ms (min 100ms, max 500ms, total 1234ms)\n * // file-read: 10 calls, avg 5ms (min 2ms, max 15ms, total 50ms)\n */\nexport function printPerformanceSummary(): void {\n if (!isPerfEnabled() || performanceMetrics.length === 0) {\n return\n }\n\n const summary = getPerformanceSummary()\n const operations = Object.keys(summary).sort()\n\n debugLog('[perf]\\n=== Performance Summary ===')\n\n for (const operation of operations) {\n const stats = summary[operation] as {\n count: number\n total: number\n avg: number\n min: number\n max: number\n }\n debugLog(\n `[perf] ${operation}: ${stats.count} calls, avg ${stats.avg}ms (min ${stats.min}ms, max ${stats.max}ms, total ${stats.total}ms)`,\n )\n }\n\n debugLog('[perf] =========================\\n')\n}\n\n/**\n * Mark a checkpoint in performance tracking.\n * Useful for tracking progress through complex operations.\n *\n * @param checkpoint - Name of the checkpoint\n * @param metadata - Optional metadata\n *\n * @example\n * import { perfCheckpoint } from '@socketsecurity/lib/performance'\n *\n * perfCheckpoint('start-scan')\n * // ... do work ...\n * perfCheckpoint('fetch-packages', { count: 50 })\n * // ... do work ...\n * perfCheckpoint('analyze-issues', { issueCount: 10 })\n * perfCheckpoint('end-scan')\n */\nexport function perfCheckpoint(\n checkpoint: string,\n metadata?: Record<string, unknown>,\n): void {\n if (!isPerfEnabled()) {\n return\n }\n\n const metric: PerformanceMetrics = {\n operation: `checkpoint:${checkpoint}`,\n duration: 0,\n timestamp: Date.now(),\n ...(metadata ? { metadata } : {}),\n }\n\n performanceMetrics.push(metric)\n debugLog(`[perf] [CHECKPOINT] ${checkpoint}`)\n}\n\n/**\n * Track memory usage at a specific point.\n * Only available when DEBUG=perf is enabled.\n *\n * @param label - Label for this memory snapshot\n * @returns Memory usage in MB\n *\n * @example\n * import { trackMemory } from '@socketsecurity/lib/performance'\n *\n * const memBefore = trackMemory('before-operation')\n * await heavyOperation()\n * const memAfter = trackMemory('after-operation')\n * console.log(`Memory increased by ${memAfter - memBefore}MB`)\n */\nexport function trackMemory(label: string): number {\n if (!isPerfEnabled()) {\n return 0\n }\n\n const usage = process.memoryUsage()\n const heapUsedMB = Math.round((usage.heapUsed / 1024 / 1024) * 100) / 100\n\n debugLog(`[perf] [MEMORY] ${label}: ${heapUsedMB}MB heap used`)\n\n const metric: PerformanceMetrics = {\n operation: `checkpoint:memory:${label}`,\n duration: 0,\n timestamp: Date.now(),\n metadata: {\n heapUsed: heapUsedMB,\n heapTotal: Math.round((usage.heapTotal / 1024 / 1024) * 100) / 100,\n external: Math.round((usage.external / 1024 / 1024) * 100) / 100,\n },\n }\n\n performanceMetrics.push(metric)\n\n return heapUsedMB\n}\n\n/**\n * Create a performance report for the current execution.\n * Only available when DEBUG=perf is enabled.\n *\n * @returns Formatted performance report\n *\n * @example\n * import { generatePerformanceReport } from '@socketsecurity/lib/performance'\n *\n * console.log(generatePerformanceReport())\n * // \u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557\n * // \u2551 Performance Report \u2551\n * // \u255A\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255D\n * //\n * // api-call:\n * // Calls: 5\n * // Avg: 246.8ms\n * // Min: 100ms\n * // Max: 500ms\n * // Total: 1234ms\n */\nexport function generatePerformanceReport(): string {\n if (!isPerfEnabled() || performanceMetrics.length === 0) {\n return '(no performance data collected - enable with DEBUG=perf)'\n }\n\n const summary = getPerformanceSummary()\n const operations = Object.keys(summary).sort()\n\n let report = '\\n\u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557\\n'\n report += '\u2551 Performance Report \u2551\\n'\n report += '\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255D\\n\\n'\n\n for (const operation of operations) {\n const stats = summary[operation] as {\n count: number\n total: number\n avg: number\n min: number\n max: number\n }\n report += `${operation}:\\n`\n report += ` Calls: ${stats.count}\\n`\n report += ` Avg: ${stats.avg}ms\\n`\n report += ` Min: ${stats.min}ms\\n`\n report += ` Max: ${stats.max}ms\\n`\n report += ` Total: ${stats.total}ms\\n\\n`\n }\n\n const totalDuration = Object.values(summary).reduce(\n (sum, s) => sum + s.total,\n 0,\n )\n report += `Total measured time: ${Math.round(totalDuration * 100) / 100}ms\\n`\n\n return report\n}\n"],
|
|
5
5
|
"mappings": ";4ZAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,6BAAAE,EAAA,8BAAAC,EAAA,0BAAAC,EAAA,0BAAAC,EAAA,YAAAC,EAAA,gBAAAC,EAAA,mBAAAC,EAAA,cAAAC,EAAA,4BAAAC,EAAA,gBAAAC,IAAA,eAAAC,EAAAZ,GAKA,IAAAa,EAAyB,mBAezB,MAAMC,EAA2C,CAAC,EAKlD,SAASC,GAAyB,CAChC,OAAO,QAAQ,IAAI,OAAU,SAAS,MAAM,GAAK,EACnD,CAiBO,SAASN,EACdO,EACAC,EACwD,CACxD,GAAI,CAACF,EAAc,EAEjB,MAAO,IAAM,CAAC,EAGhB,MAAMG,EAAQ,YAAY,IAAI,EAC9B,qBAAS,kBAAkBF,CAAS,EAAE,EAE9BG,GAAiD,CACvD,MAAMC,EAAW,YAAY,IAAI,EAAIF,EAC/BG,EAA6B,CACjC,UAAAL,EAEA,SAAU,KAAK,MAAMI,EAAW,GAAG,EAAI,IACvC,UAAW,KAAK,IAAI,EACpB,SAAU,CAAE,GAAGH,EAAU,GAAGE,CAAmB,CACjD,EAEAL,EAAmB,KAAKO,CAAM,KAC9B,YAAS,gBAAgBL,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formanceMetrics", "generatePerformanceReport", "getPerformanceMetrics", "getPerformanceSummary", "measure", "measureSync", "perfCheckpoint", "perfTimer", "printPerformanceSummary", "trackMemory", "__toCommonJS", "import_debug", "performanceMetrics", "isPerfEnabled", "operation", "metadata", "start", "additionalMetadata", "duration", "metric", "fn", "stop", "result", "e", "summary", "stats", "operations", "checkpoint", "label", "usage", "heapUsedMB", "report", "totalDuration", "sum", "s"]
|
|
7
7
|
}
|
package/dist/spinner.d.ts
CHANGED
|
@@ -61,7 +61,7 @@ export type ShimmerInfo = ShimmerState & {
|
|
|
61
61
|
*
|
|
62
62
|
* @example
|
|
63
63
|
* ```ts
|
|
64
|
-
* import { Spinner } from '@socketsecurity/
|
|
64
|
+
* import { Spinner } from '@socketsecurity/lib/spinner'
|
|
65
65
|
*
|
|
66
66
|
* const spinner = Spinner({ text: 'Loading…' })
|
|
67
67
|
* spinner.start()
|
|
@@ -243,7 +243,7 @@ export declare function getCliSpinners(styleName?: string | undefined): SpinnerS
|
|
|
243
243
|
*
|
|
244
244
|
* @example
|
|
245
245
|
* ```ts
|
|
246
|
-
* import { Spinner } from '@socketsecurity/
|
|
246
|
+
* import { Spinner } from '@socketsecurity/lib/spinner'
|
|
247
247
|
*
|
|
248
248
|
* // Basic usage
|
|
249
249
|
* const spinner = Spinner({ text: 'Loading data…' })
|
|
@@ -279,7 +279,7 @@ export declare function Spinner(options?: SpinnerOptions | undefined): Spinner;
|
|
|
279
279
|
*
|
|
280
280
|
* @example
|
|
281
281
|
* ```ts
|
|
282
|
-
* import { getDefaultSpinner } from '@socketsecurity/
|
|
282
|
+
* import { getDefaultSpinner } from '@socketsecurity/lib/spinner'
|
|
283
283
|
*
|
|
284
284
|
* const spinner = getDefaultSpinner()
|
|
285
285
|
* spinner.start('Loading…')
|
|
@@ -294,11 +294,11 @@ export declare function getDefaultSpinner(): ReturnType<typeof Spinner>;
|
|
|
294
294
|
* @example
|
|
295
295
|
* ```ts
|
|
296
296
|
* // Old (deprecated):
|
|
297
|
-
* import { spinner } from '@socketsecurity/
|
|
297
|
+
* import { spinner } from '@socketsecurity/lib/spinner'
|
|
298
298
|
* spinner.start('Loading…')
|
|
299
299
|
*
|
|
300
300
|
* // New (recommended):
|
|
301
|
-
* import { getDefaultSpinner } from '@socketsecurity/
|
|
301
|
+
* import { getDefaultSpinner } from '@socketsecurity/lib/spinner'
|
|
302
302
|
* const spinner = getDefaultSpinner()
|
|
303
303
|
* spinner.start('Loading…')
|
|
304
304
|
* ```
|
|
@@ -334,7 +334,7 @@ export type WithSpinnerOptions<T> = {
|
|
|
334
334
|
*
|
|
335
335
|
* @example
|
|
336
336
|
* ```ts
|
|
337
|
-
* import { Spinner, withSpinner } from '@socketsecurity/
|
|
337
|
+
* import { Spinner, withSpinner } from '@socketsecurity/lib/spinner'
|
|
338
338
|
*
|
|
339
339
|
* const spinner = Spinner()
|
|
340
340
|
*
|
|
@@ -384,7 +384,7 @@ export type WithSpinnerRestoreOptions<T> = {
|
|
|
384
384
|
*
|
|
385
385
|
* @example
|
|
386
386
|
* ```ts
|
|
387
|
-
* import { getDefaultSpinner, withSpinnerRestore } from '@socketsecurity/
|
|
387
|
+
* import { getDefaultSpinner, withSpinnerRestore } from '@socketsecurity/lib/spinner'
|
|
388
388
|
*
|
|
389
389
|
* const spinner = getDefaultSpinner()
|
|
390
390
|
* const wasSpinning = spinner.isSpinning
|
|
@@ -432,7 +432,7 @@ export type WithSpinnerSyncOptions<T> = {
|
|
|
432
432
|
*
|
|
433
433
|
* @example
|
|
434
434
|
* ```ts
|
|
435
|
-
* import { Spinner, withSpinnerSync } from '@socketsecurity/
|
|
435
|
+
* import { Spinner, withSpinnerSync } from '@socketsecurity/lib/spinner'
|
|
436
436
|
*
|
|
437
437
|
* const spinner = Spinner()
|
|
438
438
|
*
|